// Admin Settings — KPI Targets + Team + Exemptions CRUD
// Uses SALES_DB helpers (upsertKpiTarget, deleteKpiTarget, upsertTeamRoster, etc.)

function AdminSettings({ onClose, lang, perms }) {
  const [tab, setTab] = React.useState('kpi');

  const L = lang === 'en'
    ? { title:'Admin Settings', close:'Close', tabKpi:'KPI Targets', tabTeam:'Team', tabExempt:'Exemptions', readOnly:'Read-only (admins only)' }
    : { title:'관리자 설정', close:'닫기', tabKpi:'KPI 목표', tabTeam:'팀', tabExempt:'예외 항목', readOnly:'읽기 전용 (관리자만 수정 가능)' };

  return (
    <div style={{
      position:'fixed', inset:0, zIndex:200,
      background:'rgba(0,0,0,0.5)', backdropFilter:'blur(4px)',
      display:'flex', alignItems:'center', justifyContent:'center', padding:20,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width:'100%', maxWidth:1000, maxHeight:'90vh', overflow:'auto',
        background:'var(--bg-solid)', border:'1px solid var(--border)',
        borderRadius:16, boxShadow:'var(--shadow-3)', display:'flex', flexDirection:'column',
      }}>
        <header style={{
          padding:'16px 20px', borderBottom:'1px solid var(--divider)',
          display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0,
        }}>
          <h2 style={{ fontSize:17, fontWeight:700, margin:0 }}>{L.title}</h2>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:18, cursor:'pointer', color:'var(--fg-muted)' }}>✕</button>
        </header>

        <nav style={{ padding:'0 20px', borderBottom:'1px solid var(--divider)', display:'flex', gap:4, flexShrink:0 }}>
          {[['kpi', L.tabKpi], ['team', L.tabTeam], ['exemptions', L.tabExempt]].map(([k,l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              padding:'10px 14px', fontSize:13, fontWeight:500,
              background:'transparent', color: tab===k ? 'var(--accent)':'var(--fg-2)',
              border:'none', borderBottom: tab===k ? '2px solid var(--accent)':'2px solid transparent',
              cursor:'pointer', marginBottom:-1,
            }}>{l}</button>
          ))}
        </nav>

        <div style={{ padding:20, flex:1, overflowY:'auto' }}>
          {!perms?.isAdmin && (
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginBottom:12, fontStyle:'italic' }}>{L.readOnly}</div>
          )}
          {tab === 'kpi'        && <KpiTargetsTab lang={lang} perms={perms}/>}
          {tab === 'team'       && <TeamTab lang={lang} perms={perms}/>}
          {tab === 'exemptions' && <ExemptionsTab lang={lang} perms={perms}/>}
        </div>
      </div>
    </div>
  );
}

// ============================================================
// KPI Targets CRUD
// ============================================================
function KpiTargetsTab({ lang, perms }) {
  const [rows, setRows]       = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr]         = React.useState(null);
  const [year, setYear]       = React.useState(2026);
  const [editRow, setEditRow] = React.useState(null);  // null = new row form hidden
  const [saving, setSaving]   = React.useState(false);

  const isAdmin = perms?.isAdmin;
  const t = lang === 'en'
    ? { add:'Add target', edit:'Edit', del:'Delete', save:'Save', cancel:'Cancel', confirmDel:'Delete this target?' }
    : { add:'목표 추가', edit:'수정', del:'삭제', save:'저장', cancel:'취소', confirmDel:'이 목표를 삭제할까요?' };

  const SEGMENTS = ['Total','US','ROW','ROW_GER','ROW_AUS','ROW_CHN','ROW_existing','KR','US+ROW'];
  const METRICS  = ['revenue','b2c_share','bumper_share'];

  async function load() {
    setLoading(true); setErr(null);
    try {
      const data = await SALES_DB.fetchKpiTargets(year);
      setRows(data.sort((a,b) => (a.segment+a.metric).localeCompare(b.segment+b.metric)));
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }

  React.useEffect(() => { load(); }, [year]);

  async function handleSave(form) {
    setSaving(true);
    try {
      await SALES_DB.upsertKpiTarget({
        year:         parseInt(form.year, 10),
        segment:      form.segment,
        metric:       form.metric,
        target_value: parseFloat(form.target_value),
        unit:         form.unit || (form.metric === 'revenue' ? 'KRW' : 'percent'),
        notes:        form.notes || null,
        growth_rate:  form.growth_rate ? parseFloat(form.growth_rate) : null,
        updated_by:   'admin',
      });
      setEditRow(null);
      await load();
    } catch (e) { alert('Error: ' + e.message); }
    finally { setSaving(false); }
  }

  async function handleDelete(r) {
    if (!confirm(t.confirmDel)) return;
    try { await SALES_DB.deleteKpiTarget(r.year, r.segment, r.metric); await load(); }
    catch (e) { alert('Error: ' + e.message); }
  }

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
        <h3 style={{ fontSize:14, fontWeight:600, margin:0 }}>{lang === 'en' ? 'KPI Targets' : 'KPI 목표'}</h3>
        <select value={year} onChange={e => setYear(+e.target.value)} style={adminSelectStyle}>
          {[2026,2025,2024].map(y => <option key={y} value={y}>{y}</option>)}
        </select>
        {isAdmin && (
          <button onClick={() => setEditRow({ year, segment:'Total', metric:'revenue', target_value:'', unit:'KRW', notes:'' })}
            style={adminBtnPrimary}>{t.add}</button>
        )}
      </div>

      {loading && <div style={adminMuted}>{lang === 'en' ? 'Loading…' : '불러오는 중…'}</div>}
      {err    && <div style={{ color:'#FF453A', fontSize:12 }}>Error: {err}</div>}

      {editRow && (
        <KpiForm row={editRow} segments={SEGMENTS} metrics={METRICS} saving={saving}
          onSave={handleSave} onCancel={() => setEditRow(null)} lang={lang} t={t}/>
      )}

      {!loading && (
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
          <thead>
            <tr style={{ borderBottom:'2px solid var(--border)' }}>
              {['Year','Segment','Metric','Target Value','Unit','Notes',''].map(h => (
                <th key={h} style={{ padding:'7px 10px', textAlign: h ? 'left':'right', color:'var(--fg-muted)', fontWeight:600, fontSize:10.5, textTransform:'uppercase' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={`${r.year}-${r.segment}-${r.metric}`} style={{ borderBottom:'1px solid var(--divider)' }}>
                <td style={adminTd}>{r.year}</td>
                <td style={{ ...adminTd, fontWeight:600 }}>{r.segment}</td>
                <td style={adminTd}>{r.metric}</td>
                <td style={{ ...adminTd, fontFamily:'var(--font-mono)', textAlign:'right' }}>
                  {r.metric === 'revenue'
                    ? '₩' + (r.target_value/1e8).toFixed(1) + '억'
                    : r.target_value + '%'}
                </td>
                <td style={{ ...adminTd, color:'var(--fg-muted)' }}>{r.unit}</td>
                <td style={{ ...adminTd, color:'var(--fg-muted)', maxWidth:200, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{r.notes || '—'}</td>
                <td style={{ padding:'6px 8px', textAlign:'right', whiteSpace:'nowrap' }}>
                  {isAdmin && (
                    <>
                      <button onClick={() => setEditRow({ ...r, target_value: String(r.target_value), growth_rate: r.growth_rate ? String(r.growth_rate) : '' })}
                        style={adminBtnSm}>{t.edit}</button>
                      <button onClick={() => handleDelete(r)} style={{ ...adminBtnSm, color:'#FF453A', borderColor:'rgba(255,69,58,.3)', marginLeft:4 }}>
                        {t.del}
                      </button>
                    </>
                  )}
                </td>
              </tr>
            ))}
            {rows.length === 0 && !loading && (
              <tr><td colSpan={7} style={{ padding:20, textAlign:'center', color:'var(--fg-muted)', fontSize:12 }}>
                {lang === 'en' ? 'No targets yet. Run 0003_kpi_seed.sql first.' : '목표 없음. 0003_kpi_seed.sql 먼저 실행하세요.'}
              </td></tr>
            )}
          </tbody>
        </table>
      )}
    </div>
  );
}

function KpiForm({ row, segments, metrics, saving, onSave, onCancel, lang, t }) {
  const [form, setForm] = React.useState(row);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  return (
    <div style={{ background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:10, padding:14, marginBottom:14 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:10, marginBottom:10 }}>
        <Field label="Year">
          <input type="number" value={form.year} onChange={e => set('year', e.target.value)} style={adminInputStyle}/>
        </Field>
        <Field label="Segment">
          <select value={form.segment} onChange={e => set('segment', e.target.value)} style={adminInputStyle}>
            {segments.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </Field>
        <Field label="Metric">
          <select value={form.metric} onChange={e => set('metric', e.target.value)} style={adminInputStyle}>
            {metrics.map(m => <option key={m} value={m}>{m}</option>)}
          </select>
        </Field>
        <Field label="Target Value">
          <input type="number" value={form.target_value} onChange={e => set('target_value', e.target.value)} style={adminInputStyle} placeholder="0"/>
        </Field>
        <Field label="Unit">
          <select value={form.unit} onChange={e => set('unit', e.target.value)} style={adminInputStyle}>
            <option value="KRW">KRW</option>
            <option value="percent">percent</option>
          </select>
        </Field>
        <Field label="Growth Rate %">
          <input type="number" value={form.growth_rate || ''} onChange={e => set('growth_rate', e.target.value)} style={adminInputStyle} placeholder="optional"/>
        </Field>
      </div>
      <Field label="Notes">
        <input type="text" value={form.notes || ''} onChange={e => set('notes', e.target.value)} style={{ ...adminInputStyle, width:'100%' }} placeholder="optional"/>
      </Field>
      <div style={{ display:'flex', gap:8, marginTop:12 }}>
        <button onClick={() => onSave(form)} disabled={saving} style={adminBtnPrimary}>{saving ? '…' : t.save}</button>
        <button onClick={onCancel} style={adminBtnSm}>{t.cancel}</button>
      </div>
    </div>
  );
}

// ============================================================
// Team CRUD
// ============================================================
function TeamTab({ lang, perms }) {
  const [rows, setRows]       = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr]         = React.useState(null);
  const [editRow, setEditRow] = React.useState(null);
  const [saving, setSaving]   = React.useState(false);
  const isAdmin = perms?.isAdmin;
  const t = lang === 'en'
    ? { invite:'Invite member', save:'Save', cancel:'Cancel', del:'Remove', confirmDel:'Remove this member?' }
    : { invite:'멤버 초대', save:'저장', cancel:'취소', del:'제거', confirmDel:'이 멤버를 제거할까요?' };

  const ROLES = ['admin','strategy','team_member','viewer'];

  async function load() {
    setLoading(true); setErr(null);
    try { setRows(await SALES_DB.fetchTeamRoster()); }
    catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { load(); }, []);

  async function handleSave(form) {
    if (!form.email?.trim() || !form.full_name?.trim()) { alert('Email and name required.'); return; }
    setSaving(true);
    try {
      await SALES_DB.upsertTeamRoster({
        email:        form.email.trim().toLowerCase(),
        full_name:    form.full_name.trim(),
        english_name: form.english_name?.trim() || null,
        title:        form.title?.trim() || null,
        role:         form.role || 'viewer',
        team:         form.team?.trim() || null,
        notes:        form.notes?.trim() || null,
        invited_by:   'admin',
      });
      setEditRow(null);
      await load();
    } catch (e) { alert('Error: ' + e.message); }
    finally { setSaving(false); }
  }

  async function handleDelete(email) {
    if (!confirm(t.confirmDel)) return;
    try { await SALES_DB.deleteTeamRoster(email); await load(); }
    catch (e) { alert('Error: ' + e.message); }
  }

  const ROLE_COLOR = { admin:'#007AFF', strategy:'#AF52DE', team_member:'#34C759', viewer:'#8E8E93' };

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
        <h3 style={{ fontSize:14, fontWeight:600, margin:0 }}>{lang === 'en' ? 'Team Roster' : '팀원 명단'}</h3>
        <span style={{ fontSize:11, color:'var(--fg-muted)' }}>sales.team_roster</span>
        {isAdmin && (
          <button onClick={() => setEditRow({ email:'', full_name:'', english_name:'', title:'', role:'viewer', team:'', notes:'' })}
            style={adminBtnPrimary}>{t.invite}</button>
        )}
      </div>

      {loading && <div style={adminMuted}>{lang === 'en' ? 'Loading…' : '불러오는 중…'}</div>}
      {err    && <div style={{ color:'#FF453A', fontSize:12 }}>Error: {err}</div>}

      {editRow && (
        <TeamForm row={editRow} roles={ROLES} saving={saving} onSave={handleSave} onCancel={() => setEditRow(null)} t={t}/>
      )}

      {!loading && (
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
          <thead>
            <tr style={{ borderBottom:'2px solid var(--border)' }}>
              {['Email','Name','Title','Role','Team',''].map(h => (
                <th key={h} style={{ padding:'7px 10px', textAlign:'left', color:'var(--fg-muted)', fontWeight:600, fontSize:10.5, textTransform:'uppercase' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.email} style={{ borderBottom:'1px solid var(--divider)' }}>
                <td style={adminTd}>{r.email}</td>
                <td style={{ ...adminTd, fontWeight:600 }}>{r.full_name}{r.english_name ? ` (${r.english_name})` : ''}</td>
                <td style={{ ...adminTd, color:'var(--fg-muted)' }}>{r.title || '—'}</td>
                <td style={adminTd}>
                  <span style={{ padding:'2px 7px', borderRadius:99, fontSize:10.5, fontWeight:600,
                    background: (ROLE_COLOR[r.role] || '#999') + '22', color: ROLE_COLOR[r.role] || '#999' }}>
                    {r.role}
                  </span>
                </td>
                <td style={{ ...adminTd, color:'var(--fg-muted)' }}>{r.team || '—'}</td>
                <td style={{ padding:'6px 8px', textAlign:'right', whiteSpace:'nowrap' }}>
                  {isAdmin && (
                    <>
                      <button onClick={() => setEditRow({ ...r, english_name: r.english_name||'', title: r.title||'', team: r.team||'', notes: r.notes||'' })}
                        style={adminBtnSm}>{lang === 'en' ? 'Edit' : '수정'}</button>
                      <button onClick={() => handleDelete(r.email)}
                        style={{ ...adminBtnSm, color:'#FF453A', borderColor:'rgba(255,69,58,.3)', marginLeft:4 }}>
                        {t.del}
                      </button>
                    </>
                  )}
                </td>
              </tr>
            ))}
            {rows.length === 0 && !loading && (
              <tr><td colSpan={6} style={{ padding:20, textAlign:'center', color:'var(--fg-muted)', fontSize:12 }}>
                {lang === 'en' ? 'No team members.' : '팀원 없음.'}
              </td></tr>
            )}
          </tbody>
        </table>
      )}
    </div>
  );
}

function TeamForm({ row, roles, saving, onSave, onCancel, t }) {
  const [form, setForm] = React.useState(row);
  const set = (k,v) => setForm(f => ({...f,[k]:v}));
  return (
    <div style={{ background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:10, padding:14, marginBottom:14 }}>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:10 }}>
        <Field label="Email *">
          <input type="email" value={form.email} onChange={e => set('email',e.target.value)} style={adminInputStyle} placeholder="user@example.com"/>
        </Field>
        <Field label="Full Name *">
          <input type="text" value={form.full_name} onChange={e => set('full_name',e.target.value)} style={adminInputStyle}/>
        </Field>
        <Field label="English Name">
          <input type="text" value={form.english_name||''} onChange={e => set('english_name',e.target.value)} style={adminInputStyle}/>
        </Field>
        <Field label="Title">
          <input type="text" value={form.title||''} onChange={e => set('title',e.target.value)} style={adminInputStyle}/>
        </Field>
        <Field label="Role">
          <select value={form.role} onChange={e => set('role',e.target.value)} style={adminInputStyle}>
            {roles.map(r => <option key={r} value={r}>{r}</option>)}
          </select>
        </Field>
        <Field label="Team">
          <input type="text" value={form.team||''} onChange={e => set('team',e.target.value)} style={adminInputStyle} placeholder="sales / exec / finance…"/>
        </Field>
      </div>
      <div style={{ display:'flex', gap:8, marginTop:8 }}>
        <button onClick={() => onSave(form)} disabled={saving} style={adminBtnPrimary}>{saving ? '…' : t.save}</button>
        <button onClick={onCancel} style={adminBtnSm}>{t.cancel}</button>
      </div>
    </div>
  );
}

// ============================================================
// Exemptions (read-only)
// ============================================================
function ExemptionsTab({ lang, perms }) {
  const [rows, setRows]       = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr]         = React.useState(null);

  React.useEffect(() => {
    (async () => {
      try { setRows(await SALES_DB.fetchExemptions()); }
      catch (e) { setErr(e.message); }
      finally { setLoading(false); }
    })();
  }, []);

  return (
    <div>
      <h3 style={{ fontSize:14, fontWeight:600, marginTop:0, marginBottom:6 }}>
        {lang === 'en' ? 'Exempted Invoices' : '예외 처리 Invoice'}
      </h3>
      <div style={{ fontSize:11, color:'var(--fg-muted)', marginBottom:12 }}>
        {lang === 'en'
          ? 'Invoices excluded from aggregation. Synced from Google Sheets "이상행_예외" tab.'
          : '집계에서 제외된 Invoice 목록. Google Sheets 이상행_예외 탭에서 싱크됩니다.'}
      </div>

      {loading && <div style={adminMuted}>{lang === 'en' ? 'Loading…' : '불러오는 중…'}</div>}
      {err    && <div style={{ color:'#FF453A', fontSize:12 }}>Error: {err}</div>}

      {!loading && (
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
          <thead>
            <tr style={{ borderBottom:'2px solid var(--border)' }}>
              {['Invoice No.', 'Issue Types', 'Notes', 'Created At'].map(h => (
                <th key={h} style={{ padding:'7px 10px', textAlign:'left', color:'var(--fg-muted)', fontWeight:600, fontSize:10.5, textTransform:'uppercase' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.invoice_no} style={{ borderBottom:'1px solid var(--divider)' }}>
                <td style={{ ...adminTd, fontFamily:'var(--font-mono)' }}>{r.invoice_no}</td>
                <td style={adminTd}>{r.issue_types || '—'}</td>
                <td style={{ ...adminTd, color:'var(--fg-muted)' }}>{r.notes || '—'}</td>
                <td style={{ ...adminTd, color:'var(--fg-muted)' }}>{r.created_at?.slice(0,10) || '—'}</td>
              </tr>
            ))}
            {rows.length === 0 && !loading && (
              <tr><td colSpan={4} style={{ padding:20, textAlign:'center', color:'var(--fg-muted)', fontSize:12 }}>
                {lang === 'en' ? 'No exemptions.' : '예외 항목 없음.'}
              </td></tr>
            )}
          </tbody>
        </table>
      )}
    </div>
  );
}

// ============================================================
// Shared atoms
// ============================================================
function Field({ label, children }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
      <label style={{ fontSize:10.5, fontWeight:600, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:.04 }}>{label}</label>
      {children}
    </div>
  );
}

const adminTd         = { padding:'7px 10px', verticalAlign:'middle' };
const adminMuted      = { color:'var(--fg-muted)', fontSize:12 };
const adminSelectStyle = { padding:'5px 8px', fontSize:12, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:7, color:'var(--fg)' };
const adminInputStyle  = { padding:'6px 9px', fontSize:12, background:'var(--bg-solid)', border:'1px solid var(--border)', borderRadius:7, color:'var(--fg)', width:'100%', boxSizing:'border-box' };
const adminBtnPrimary  = { padding:'7px 14px', fontSize:12, fontWeight:600, background:'var(--accent)', color:'#fff', border:'none', borderRadius:7, cursor:'pointer' };
const adminBtnSm       = { padding:'5px 10px', fontSize:11.5, fontWeight:500, background:'var(--surface-2)', color:'var(--fg-2)', border:'1px solid var(--border)', borderRadius:6, cursor:'pointer' };

window.AdminSettings = AdminSettings;
