// admin.jsx — 管理者画面 (メンバー管理/追放/招待枠 + 審査問題編集). window.AdminScreen.
(function () {
  const { useState, useEffect } = React;
  const { Icon } = window;

  function AdminScreen({ app }) {
    const T = app.theme;
    const [tab, setTab] = useState('members'); // members | exam
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.bg, zIndex: 86, display: 'flex', flexDirection: 'column' }}>
        <div style={{ paddingTop: 54, paddingBottom: 10, borderBottom: `1px solid ${T.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '54px 14px 10px' }}>
          <button onClick={() => app.closeAdmin()} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, color: T.text, display: 'flex' }}><Icon.close size={24} /></button>
          <span style={{ fontWeight: 800, color: T.text }}>管理</span>
          <span style={{ width: 32 }} />
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '12px 16px 0' }}>
          {[['members', 'メンバー'], ['exam', '審査問題']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              flex: 1, padding: '9px', borderRadius: 10, border: `1px solid ${tab === k ? T.accent : T.border}`,
              background: tab === k ? T.surface2 : 'none', color: tab === k ? T.text : T.sub,
              fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
            }}>{l}</button>
          ))}
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '14px 16px 50px' }}>
          {tab === 'members' ? <Members app={app} /> : <ExamEditor app={app} />}
        </div>
      </div>
    );
  }

  function Members({ app }) {
    const T = app.theme;
    const [members, setMembers] = useState(null);
    const load = () => window.PFApi.get('/admin/members').then((r) => setMembers(r.members));
    useEffect(() => { load(); }, []);
    if (!members) return <div style={{ color: T.faint }}>読み込み中…</div>;

    const kick = async (m) => {
      if (!confirm(`${m.name} を追放しますか？（即ログイン不可）`)) return;
      await window.PFApi.post(`/admin/members/${m.id}/remove`, {});
      load();
    };
    const setQuota = async (m, delta) => {
      const v = Math.max(0, (m.invites_remaining || 0) + delta);
      await window.PFApi.post(`/admin/members/${m.id}/invites`, { invites_remaining: v });
      load();
    };

    return (
      <div>
        {members.map((m) => (
          <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 0', borderBottom: `1px solid ${T.border}` }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontWeight: 800, color: T.text }}>{m.name}</span>
                {m.role === 'admin' && <span style={{ color: T.accent }}><Icon.verified size={14} /></span>}
                {m.passed === 1 && m.role !== 'admin' && <span style={{ fontSize: 10, fontWeight: 800, color: T.accent, border: `1px solid ${T.accent}55`, borderRadius: 4, padding: '0 4px' }}>合格</span>}
                {m.status === 'removed' && <span style={{ fontSize: 10, fontWeight: 800, color: '#ff8aa0' }}>追放済</span>}
              </div>
              <div style={{ color: T.faint, fontSize: 12.5 }}>
                @{m.handle}{m.inviter_name ? ` · ${m.inviter_name}の紹介` : ''}
              </div>
              <div style={{ color: T.sub, fontSize: 12, marginTop: 3, display: 'flex', alignItems: 'center', gap: 6 }}>
                招待枠 {m.invites_remaining}
                {m.role !== 'admin' && (
                  <>
                    <button onClick={() => setQuota(m, -1)} style={quotaBtn(T)}>−</button>
                    <button onClick={() => setQuota(m, +1)} style={quotaBtn(T)}>＋</button>
                  </>
                )}
              </div>
            </div>
            {m.role !== 'admin' && m.status === 'active' && (
              <button onClick={() => kick(m)} style={{ border: `1px solid ${T.border}`, background: 'none', color: '#ff8aa0', borderRadius: 10, padding: '7px 12px', fontWeight: 800, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>追放</button>
            )}
          </div>
        ))}
      </div>
    );
  }

  function ExamEditor({ app }) {
    const T = app.theme;
    const [data, setData] = useState(null);
    const load = () => window.PFApi.get('/admin/exam').then(setData);
    useEffect(() => { load(); }, []);
    if (!data) return <div style={{ color: T.faint }}>読み込み中…</div>;

    const saveConfig = async (v) => { await window.PFApi.put('/admin/exam/config', { pass_needed: v }); load(); };
    const saveQ = async (q) => {
      await window.PFApi.put(`/admin/exam/questions/${q.id}`, q);
      load();
    };
    const addQ = async () => {
      await window.PFApi.post('/admin/exam/questions', { position: (data.questions.length + 1), question: '新しい問題', choices: ['選択肢1', '選択肢2'], answer: 0, why: '', active: true });
      load();
    };
    const delQ = async (id) => { if (confirm('この問題を削除？')) { await window.PFApi.del(`/admin/exam/questions/${id}`); load(); } };

    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <span style={{ color: T.sub, fontSize: 13.5 }}>合格に必要な正解数</span>
          <input type="number" defaultValue={data.pass_needed} min={1} max={data.questions.length}
            onBlur={(e) => saveConfig(parseInt(e.target.value, 10) || 1)}
            style={{ width: 56, padding: '6px 8px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.surface, color: T.text, fontFamily: 'inherit' }} />
          <span style={{ color: T.faint, fontSize: 12.5 }}>/ {data.questions.length}問</span>
        </div>
        {data.questions.map((q) => <QCard key={q.id} q={q} T={T} onSave={saveQ} onDel={delQ} />)}
        <button onClick={addQ} style={{ width: '100%', marginTop: 12, padding: '12px', borderRadius: 12, border: `1.5px dashed ${T.border}`, background: 'none', color: T.sub, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>＋ 問題を追加</button>
      </div>
    );
  }

  function QCard({ q, T, onSave, onDel }) {
    const [question, setQuestion] = useState(q.question);
    const [choices, setChoices] = useState(q.choices);
    const [answer, setAnswer] = useState(q.answer);
    const [why, setWhy] = useState(q.why || '');
    const inp = { width: '100%', boxSizing: 'border-box', padding: '8px 10px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.surface, color: T.text, fontFamily: 'inherit', fontSize: 13.5 };
    return (
      <div style={{ border: `1px solid ${T.border}`, borderRadius: 14, padding: 12, marginBottom: 12, background: T.surface }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
          <span style={{ color: T.faint, fontSize: 11.5, fontWeight: 800 }}>Q{q.position}</span>
          <button onClick={() => onDel(q.id)} style={{ border: 'none', background: 'none', color: '#ff8aa0', cursor: 'pointer', fontSize: 12 }}>削除</button>
        </div>
        <textarea value={question} onChange={(e) => setQuestion(e.target.value)} rows={2} style={{ ...inp, resize: 'vertical' }} />
        <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
          {choices.map((c, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <input type="radio" checked={answer === i} onChange={() => setAnswer(i)} title="正解" />
              <input value={c} onChange={(e) => { const n = [...choices]; n[i] = e.target.value; setChoices(n); }} style={{ ...inp, flex: 1 }} />
              <button onClick={() => setChoices(choices.filter((_, j) => j !== i))} style={{ border: 'none', background: 'none', color: T.faint, cursor: 'pointer' }}>×</button>
            </div>
          ))}
          <button onClick={() => setChoices([...choices, '選択肢'])} style={{ alignSelf: 'flex-start', border: 'none', background: 'none', color: T.accent, cursor: 'pointer', fontSize: 12.5, fontWeight: 700 }}>＋ 選択肢</button>
        </div>
        <input value={why} onChange={(e) => setWhy(e.target.value)} placeholder="解説（回答後に表示）" style={{ ...inp, marginTop: 8 }} />
        <button onClick={() => onSave({ ...q, question, choices, answer, why, active: true })} style={{ marginTop: 10, padding: '8px 16px', borderRadius: 10, border: 'none', background: T.accent, color: '#fff', fontWeight: 800, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>保存</button>
      </div>
    );
  }

  function quotaBtn(T) {
    return { width: 22, height: 22, borderRadius: 6, border: `1px solid ${T.border}`, background: T.surface, color: T.text, cursor: 'pointer', fontFamily: 'inherit', lineHeight: 1 };
  }

  window.AdminScreen = AdminScreen;
})();
