// auth.jsx — first-run setup / login / invite-join gate. window.AuthGate.
(function () {
  const { useState, useEffect } = React;
  const { Icon } = window;

  function field(T) {
    return {
      width: '100%', boxSizing: 'border-box', marginTop: 10, padding: '13px 14px',
      borderRadius: 12, border: `1px solid ${T.border}`, background: T.surface,
      color: T.text, fontSize: 15, fontFamily: 'inherit', outline: 'none',
    };
  }
  function primaryBtn(T) {
    return {
      width: '100%', marginTop: 18, padding: '15px', borderRadius: 14, border: 'none',
      background: T.accent, color: '#fff', fontWeight: 800, fontSize: 16, cursor: 'pointer',
      fontFamily: 'inherit', boxShadow: `0 6px 18px ${T.accent}55`,
    };
  }

  function AuthGate({ theme, needsSetup, initialCode, onAuthed }) {
    const T = theme;
    // mode: 'setup' | 'login' | 'join'
    const [mode, setMode] = useState(needsSetup ? 'setup' : (initialCode ? 'join' : 'login'));
    const [handle, setHandle] = useState('');
    const [name, setName] = useState('');
    const [password, setPassword] = useState('');
    const [code, setCode] = useState(initialCode || '');
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState('');

    const errMsg = (e) => ({
      invalid_invite: '招待コードが無効か、使用済みです。',
      handle_taken: 'そのIDは使われています。別のIDを。',
      invalid_credentials: 'IDかパスワードが違います。',
      invalid_input: '入力を確認してください（パスワードは6文字以上）。',
      already_initialized: 'すでに初期化済みです。ログインしてください。',
      no_invites_left: '招待枠がありません。',
    }[e] || ('エラー: ' + e));

    const submit = async () => {
      setErr(''); setBusy(true);
      try {
        let r;
        if (mode === 'setup') r = await window.PFApi.post('/setup', { handle, name, password });
        else if (mode === 'login') r = await window.PFApi.post('/login', { handle, password });
        else r = await window.PFApi.post('/join', { code: code.trim(), handle, name, password });
        onAuthed(r.user);
      } catch (e) {
        setErr(errMsg(e.message));
        setBusy(false);
      }
    };

    const title = mode === 'setup' ? '管理者をつくる' : mode === 'login' ? 'おかえりなさい' : '招待で参加';
    const lead = mode === 'setup'
      ? 'ぱぱFMの最初の管理者（あなた）を登録します。'
      : mode === 'login' ? 'ID とパスワードでログイン。'
      : '招待コードと、あなたのプロフィールを入力。';

    return (
      <div style={{ position: 'absolute', inset: 0, zIndex: 95, background: T.bg, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 28px', overflow: 'auto' }}>
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 300, background: `radial-gradient(90% 100% at 50% 0%, ${T.accent}33, transparent 70%)`, pointerEvents: 'none' }} />
        <div style={{ position: 'relative', paddingTop: 70, paddingBottom: 40 }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: T.accent, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', boxShadow: `0 10px 26px ${T.accent}66` }}>
            {Icon ? <Icon.music size={30} /> : '♪'}
          </div>
          <h1 style={{ fontFamily: T.display, fontSize: 30, fontWeight: 900, color: T.text, textAlign: 'center', margin: '18px 0 4px' }}>{title}</h1>
          <p style={{ color: T.sub, fontSize: 14, lineHeight: 1.6, textAlign: 'center', margin: '0 auto 8px', maxWidth: 300 }}>{lead}</p>

          {mode === 'join' && (
            <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="招待コード（例 ABCD-1234）" style={field(T)} />
          )}
          {mode !== 'setup' && mode === 'login' ? null : null}
          <input value={handle} onChange={(e) => setHandle(e.target.value.replace(/\s/g, ''))} placeholder="ID（半角・ログインに使用）" autoCapitalize="none" style={field(T)} />
          {mode !== 'login' && (
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="表示名（例 そうきくんのパパ）" style={field(T)} />
          )}
          <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" placeholder="パスワード（6文字以上）" style={field(T)} />

          {err && <div style={{ color: '#ff8aa0', fontSize: 13, marginTop: 12, textAlign: 'center' }}>{err}</div>}

          <button onClick={submit} disabled={busy} style={{ ...primaryBtn(T), opacity: busy ? 0.5 : 1 }}>
            {busy ? '…' : (mode === 'setup' ? '管理者を登録' : mode === 'login' ? 'ログイン' : '参加する')}
          </button>

          {!needsSetup && (
            <div style={{ textAlign: 'center', marginTop: 18, color: T.faint, fontSize: 13.5 }}>
              {mode === 'login' ? (
                <span>招待がある？ <a onClick={() => { setErr(''); setMode('join'); }} style={{ color: T.accent, cursor: 'pointer', fontWeight: 700 }}>招待で参加</a></span>
              ) : (
                <span>登録ずみ？ <a onClick={() => { setErr(''); setMode('login'); }} style={{ color: T.accent, cursor: 'pointer', fontWeight: 700 }}>ログイン</a></span>
              )}
            </div>
          )}
          <p style={{ color: T.faint, fontSize: 11.5, marginTop: 22, lineHeight: 1.6, textAlign: 'center' }}>
            招待制・クローズド。知らない人は入れません。
          </p>
        </div>
      </div>
    );
  }

  window.AuthGate = AuthGate;
})();
