// auth.jsx — v2 gate: login / join-via-invite / create-group. window.AuthGate.
(function () {
  const { useState } = React;
  const { Icon } = window;

  const field = (T) => ({
    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',
  });
  const primaryBtn = (T) => ({
    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, hasGroups, initialCode, onAuthed }) {
    const T = theme;
    const [mode, setMode] = useState(initialCode ? 'join' : (hasGroups ? 'login' : 'create'));
    const [code, setCode] = useState(initialCode || '');
    const [handle, setHandle] = useState('');
    const [name, setName] = useState('');
    const [password, setPassword] = useState('');
    const [groupName, setGroupName] = useState('');
    const [createCode, setCreateCode] = useState('');
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState('');

    const msg = (e) => ({
      invalid_invite: '招待コードが無効か、使用済みです。',
      invalid_create_code: 'グループ作成コードが無効です。',
      handle_taken: 'そのIDは使われています。別のIDを。',
      invalid_credentials: 'IDかパスワードが違います。',
      invalid_input: '入力を確認してください（パスワードは6文字以上）。',
    }[e] || ('エラー: ' + e));

    const submit = async () => {
      setErr(''); setBusy(true);
      try {
        if (mode === 'login') await window.PFApi.post('/login', { handle, password });
        else if (mode === 'join') await window.PFApi.post('/join', { code: code.trim(), handle, name, password });
        else await window.PFApi.post('/groups', {
          name: groupName, persona_name: name, exam_title: `${name}の審査`,
          handle, owner_name: name, password, create_code: createCode.trim(),
        });
        onAuthed();
      } catch (e) { setErr(msg(e.message)); setBusy(false); }
    };

    const title = mode === 'login' ? 'おかえりなさい' : mode === 'join' ? '招待で参加' : 'グループを作る';
    const lead = mode === 'login' ? 'ID とパスワードでログイン。'
      : mode === 'join' ? '招待コードと、あなたのプロフィールを入力。'
      : 'あなたが管理者になる、新しいクローズドな村をつくります。';

    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: 64, 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' }}>しんちゃんFM</h1>
          <div style={{ textAlign: 'center', color: T.sub, fontSize: 15, fontWeight: 800, marginTop: 6 }}>{title}</div>
          <p style={{ color: T.faint, fontSize: 13, lineHeight: 1.6, textAlign: 'center', margin: '4px auto 6px', maxWidth: 300 }}>{lead}</p>

          {mode === 'create' && (
            <>
              {hasGroups && <input value={createCode} onChange={(e) => setCreateCode(e.target.value)} placeholder="グループ作成コード" style={field(T)} />}
              <input value={groupName} onChange={(e) => setGroupName(e.target.value)} placeholder="グループ名（例: ◯◯組 / 音楽好きの会）" style={field(T)} />
            </>
          )}
          {mode === 'join' && <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="招待コード（例 ABCD-1234）" style={field(T)} />}
          <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={mode === 'create' ? '表示名（審査の主・例: ◯◯のパパ）' : '表示名'} style={field(T)} />}
          <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" placeholder="パスワード（6文字以上）" style={field(T)} />

          {err && <div style={{ color: '#c0392b', fontSize: 13, marginTop: 12, textAlign: 'center' }}>{err}</div>}
          <button onClick={submit} disabled={busy} style={{ ...primaryBtn(T), opacity: busy ? 0.5 : 1 }}>
            {busy ? '…' : (mode === 'login' ? 'ログイン' : mode === 'join' ? '参加する' : 'グループを作成')}
          </button>

          <div style={{ textAlign: 'center', marginTop: 18, color: T.faint, fontSize: 13.5, lineHeight: 2 }}>
            {mode !== 'login' && <div><a onClick={() => { setErr(''); setMode('login'); }} style={{ color: T.accent, cursor: 'pointer', fontWeight: 700 }}>ログイン</a></div>}
            {mode !== 'join' && <div>招待がある？ <a onClick={() => { setErr(''); setMode('join'); }} style={{ color: T.accent, cursor: 'pointer', fontWeight: 700 }}>招待で参加</a></div>}
            {mode !== 'create' && <div>新しく作る？ <a onClick={() => { setErr(''); setMode('create'); }} style={{ color: T.accent, cursor: 'pointer', fontWeight: 700 }}>グループを作成</a></div>}
          </div>
        </div>
      </div>
    );
  }

  window.AuthGate = AuthGate;
})();
