// ============================================
// PairingScreen — create or join a couple code
// ============================================

function PairingScreen({ user, store }) {
  const [tab, setTab]   = React.useState('create'); // 'create' | 'join'
  const [code, setCode] = React.useState(null);     // generated code (after create)
  const [input, setInput] = React.useState('');
  const [error, setError] = React.useState('');
  const [busy, setBusy]   = React.useState(false);
  const [copied, setCopied] = React.useState(false);

  const onCreate = async () => {
    setError(''); setBusy(true);
    try {
      const c = await store.createRoom();
      setCode(c);
    } catch (err) {
      setError(err.message || '코드 발급에 실패했어요.');
    } finally { setBusy(false); }
  };

  const onJoin = async (e) => {
    e.preventDefault();
    setError(''); setBusy(true);
    try {
      await store.joinRoom(input);
      // success → state.room appears → app routes away
    } catch (err) {
      setError(err.message || '방 입장에 실패했어요.');
    } finally { setBusy(false); }
  };

  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    } catch {}
  };

  // formatter for input — auto-uppercase + insert dash
  const onCodeInput = (raw) => {
    const x = raw.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8);
    if (x.length <= 4) setInput(x);
    else setInput(x.slice(0, 4) + '-' + x.slice(4));
  };

  return (
    <div className="pair-wrap">
      <div className="pair-card">
        <div className="pair-head">
          <div className="pair-greeting">
            <span className="pair-greet-tag">SIGNED&nbsp;IN</span>
            <span className="pair-greet-name">{user.displayName}</span>
          </div>
          <button className="pair-signout" onClick={store.signOut}>로그아웃</button>
        </div>

        <h2 className="pair-title">두 분의 전보함을 잇는 방</h2>
        <p className="pair-sub">
          한 명이 <b>코드를 발급</b>하고, 다른 한 명이 그 코드를 <b>입력</b>하면 같은 방에 들어와요.
        </p>

        <div className="pair-tabs">
          <button
            type="button"
            className={`pair-tab ${tab === 'create' ? 'active' : ''}`}
            onClick={() => { setTab('create'); setError(''); }}
          >코드 발급</button>
          <button
            type="button"
            className={`pair-tab ${tab === 'join' ? 'active' : ''}`}
            onClick={() => { setTab('join'); setError(''); setCode(null); }}
          >코드 입력</button>
        </div>

        {tab === 'create' && (
          <div className="pair-panel">
            {!code ? (
              <>
                <div className="pair-illu">
                  <div className="pair-illu-line"></div>
                  <div className="pair-illu-dot"></div>
                  <div className="pair-illu-line"></div>
                </div>
                <p className="pair-explain">
                  새 코드를 발급받아 상대에게 보내주세요.<br/>
                  상대가 입력하면 같은 전보함이 열립니다.
                </p>
                <button className="pair-primary" onClick={onCreate} disabled={busy}>
                  코드 발급하기
                </button>
              </>
            ) : (
              <>
                <div className="pair-code-label">우리의 코드</div>
                <div className="pair-code">{code}</div>
                <button className={`pair-copy ${copied ? 'copied' : ''}`} onClick={onCopy}>
                  {copied ? '복사됨 ✓' : '코드 복사'}
                </button>
                <p className="pair-waiting">
                  상대가 코드를 입력하면 자동으로 연결됩니다.<br/>
                  먼저 들어와 전보를 남겨두어도 좋아요.
                </p>
                <button className="pair-secondary" onClick={() => window.location.reload()}>
                  계속 시작하기
                </button>
              </>
            )}
          </div>
        )}

        {tab === 'join' && (
          <form className="pair-panel" onSubmit={onJoin}>
            <p className="pair-explain">
              상대가 보내준 8자리 코드를 입력해 주세요.
            </p>
            <input
              className="pair-input"
              type="text"
              value={input}
              onChange={(e) => onCodeInput(e.target.value)}
              placeholder="ABCD-2345"
              maxLength={9}
              autoCapitalize="characters"
              spellCheck={false}
            />
            {error && <div className="pair-error">{error}</div>}
            <button type="submit" className="pair-primary" disabled={busy || input.length < 9}>
              방으로 들어가기
            </button>
          </form>
        )}

        {tab === 'create' && error && <div className="pair-error">{error}</div>}
      </div>
    </div>
  );
}

window.PairingScreen = PairingScreen;
