/* Admin views — Overview, Matches, Create, Settle, Draw. */

/* ============================================================
   OVERVIEW
   ============================================================ */
function StatCard({ label, value, accent = 'orange', delta }) {
  const colors = {
    orange: 'var(--orange)',
    ink:    'var(--ink)',
    green:  'var(--success)',
    grey:   'var(--grey-400)',
  };
  return (
    <div style={{
      background: '#fff', border: '1.5px solid var(--grey-200)',
      padding: '18px 20px', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, bottom: 0, width: 4, background: colors[accent],
      }} />
      <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--grey-500)', fontWeight: 700 }}>
        {label}
      </div>
      <div className="font-display" style={{ fontSize: 32, lineHeight: 1, marginTop: 8, letterSpacing: '-0.02em', color: accent === 'green' ? colors.green : 'var(--ink)' }}>
        {value}
      </div>
      {delta && (
        <div style={{ marginTop: 6, fontSize: 12, color: 'var(--success)', fontWeight: 600 }}>
          {delta}
        </div>
      )}
    </div>
  );
}

function AdminOverview({ ctx }) {
  const t = DASHBOARD.totals;
  const open = ctx.matchesState.filter(m => m.status === 'OPEN');
  const closed = ctx.matchesState.filter(m => m.status === 'CLOSED');
  const settled = ctx.matchesState.filter(m => m.status === 'SETTLED');

  return (
    <AdminSection
      title="Campaign command centre"
      sub="Live numbers across the four outlets. Use the side nav to manage matches, content, and data."
      right={
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <AdminBtn kind="outline" icon="calendar" onClick={() => ctx.goTab('create')}>New match</AdminBtn>
          <AdminBtn kind="primary" icon="trophy" onClick={() => ctx.goTab('draw')}>Run lucky draw</AdminBtn>
        </div>
      }
    >
      {/* Top stats */}
      <div className="admin-stats" style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22,
      }}>
        <StatCard label="Total predictions" value={<AnimatedCounter value={t.totalPredictions} />} accent="orange" delta="+ 632 today" />
        <StatCard label="Open right now" value={String(open.length).padStart(2,'0')} accent="green" />
        <StatCard label="Awaiting result" value={String(closed.length).padStart(2,'0')} accent="ink" />
        <StatCard label="Settled" value={String(settled.length).padStart(2,'0')} accent="grey" />
      </div>

      {/* Two-column: activity + quick controls */}
      <div className="admin-2col" style={{
        display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 18,
      }}>
        {/* Activity feed */}
        <Panel
          title="Recent activity"
          action={<span style={{ fontSize: 11, color: 'var(--grey-500)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Last 24h</span>}
          padding={0}
        >
          <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
            {ADMIN_ACTIVITY.map((a, i) => (
              <li key={i} style={{
                display: 'flex', alignItems: 'flex-start', gap: 14,
                padding: '14px 18px',
                borderBottom: i < ADMIN_ACTIVITY.length - 1 ? '1px solid var(--grey-100)' : 'none',
              }}>
                <div style={{
                  width: 32, height: 32, flexShrink: 0,
                  background: a.kind === 'predict' ? 'var(--orange-50)' :
                              a.kind === 'settle'  ? 'var(--grey-100)' :
                              a.kind === 'draw'    ? 'var(--orange)' :
                                                     'var(--grey-100)',
                  color:      a.kind === 'predict' ? 'var(--orange-dark)' :
                              a.kind === 'draw'    ? '#fff' : 'var(--ink)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon
                    name={a.kind === 'predict' ? 'check' : a.kind === 'settle' ? 'flag' : a.kind === 'draw' ? 'trophy' : 'bolt'}
                    size={15}
                  />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: 'var(--ink)' }}>{a.text}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--grey-500)', marginTop: 2, display: 'flex', gap: 10 }}>
                    <span>{timeAgo(a.t)}</span>
                    {a.outlet && <span>· {a.outlet}</span>}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </Panel>

        {/* Quick panels */}
        <div style={{ display: 'grid', gap: 18 }}>
          <Panel title="Next match" padding={18}>
            {(() => {
              const next = [...ctx.matchesState]
                .filter(m => m.status !== 'SETTLED' && m.status !== 'CLOSED')
                .sort((a, b) => a.kickoffMs - b.kickoffMs)[0];
              if (!next) return <div style={{ color: 'var(--grey-500)' }}>No upcoming matches.</div>;
              return (
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Flag code={next.teamA.flag} w={26} h={18} />
                      <div className="font-display" style={{ fontSize: 14 }}>{next.teamA.name}</div>
                    </div>
                    <span className="font-mono" style={{ fontSize: 11, color: 'var(--grey-500)' }}>vs</span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div className="font-display" style={{ fontSize: 14 }}>{next.teamB.name}</div>
                      <Flag code={next.teamB.flag} w={26} h={18} />
                    </div>
                  </div>
                  <div style={{ marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--grey-500)', fontWeight: 700 }}>
                      Kicks off in
                    </div>
                    <Countdown to={next.kickoffMs} tone="ink" />
                  </div>
                </div>
              );
            })()}
          </Panel>

          <Panel title="Outlets · today" padding={18}>
            <div style={{ display: 'grid', gap: 10 }}>
              {DASHBOARD.byOutlet.map((o, i) => {
                const max = Math.max(...DASHBOARD.byOutlet.map(x => x.count));
                return (
                  <div key={o.outlet}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 4 }}>
                      <span style={{ fontWeight: 600 }}>{o.outlet}</span>
                      <span className="font-mono">{o.count.toLocaleString()}</span>
                    </div>
                    <div style={{ height: 8, background: 'var(--grey-100)' }}>
                      <div className="stripes-bg" style={{ width: `${(o.count / max) * 100}%`, height: '100%' }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </Panel>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .admin-stats { grid-template-columns: 1fr 1fr !important; }
          .admin-2col  { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </AdminSection>
  );
}

/* ============================================================
   MATCHES LIST
   ============================================================ */
function AdminMatches({ ctx }) {
  const [q, setQ] = useState('');
  const [filter, setFilter] = useState('ALL');

  const filtered = ctx.matchesState.filter(m => {
    if (filter !== 'ALL' && m.status !== filter) return false;
    if (q) {
      const Q = q.toLowerCase();
      return (m.teamA.name + ' ' + m.teamB.name + ' ' + m.stage + ' ' + m.venue).toLowerCase().includes(Q);
    }
    return true;
  });

  const filters = ['ALL', 'OPEN', 'SCHEDULED', 'CLOSED', 'SETTLED'];
  const counts = filters.reduce((acc, f) => {
    acc[f] = f === 'ALL' ? ctx.matchesState.length : ctx.matchesState.filter(m => m.status === f).length;
    return acc;
  }, {});

  function fakeCsv(label) {
    ctx.setToast({ message: `CSV "${label}" queued for download.`, tone: 'info' });
  }
  function deleteMatch(id) {
    ctx.setMatchesState(s => s.filter(m => m.id !== id));
    ctx.setToast({ message: 'Match removed.', tone: 'success' });
  }

  return (
    <AdminSection
      title="All matches"
      sub="Schedule, settle, run draws, or export per-match prediction CSVs."
      right={
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <AdminBtn kind="outline" icon="receipt" onClick={() => fakeCsv('all_predictions.csv')}>Export all predictions</AdminBtn>
          <AdminBtn kind="primary" icon="calendar" onClick={() => ctx.goTab('create')}>Schedule new</AdminBtn>
        </div>
      }
    >
      <Panel padding={0}>
        {/* Filter bar */}
        <div style={{
          padding: '14px 18px',
          display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center',
          borderBottom: '1px solid var(--grey-200)',
        }}>
          <div style={{ position: 'relative', flex: '1 1 240px', maxWidth: 320 }}>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search by team, stage, venue…"
              style={{ ...inputStyle, paddingLeft: 36 }} />
            <svg style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)' }}
              width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--grey-400)" strokeWidth="2" strokeLinecap="round">
              <circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/>
            </svg>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {filters.map(f => {
              const active = filter === f;
              return (
                <button key={f} onClick={() => setFilter(f)} style={{
                  background: active ? 'var(--ink)' : 'transparent',
                  color: active ? '#fff' : 'var(--grey-700)',
                  border: `1.5px solid ${active ? 'var(--ink)' : 'var(--grey-300)'}`,
                  padding: '7px 12px',
                  fontSize: 11.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700,
                  cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  {f}
                  <span style={{
                    background: active ? 'var(--orange)' : 'var(--grey-100)',
                    color: active ? '#fff' : 'var(--grey-600)',
                    padding: '1px 6px', fontSize: 10, borderRadius: 999,
                  }}>{counts[f]}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Table */}
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 880 }}>
            <thead>
              <tr style={{ background: 'var(--grey-50)' }}>
                <Th>Match</Th>
                <Th>Stage</Th>
                <Th>Kickoff</Th>
                <Th>Status</Th>
                <Th align="right">Predictions</Th>
                <Th align="right">Actions</Th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(m => {
                const predCount = SAMPLE_PREDICTIONS.filter(p => p.matchId === m.id).length;
                return (
                  <tr key={m.id} style={{ borderTop: '1px solid var(--grey-100)' }}>
                    <Td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Flag code={m.teamA.flag} w={24} h={16} />
                        <span style={{ fontWeight: 700, fontSize: 13.5 }}>{m.teamA.name}</span>
                        <span style={{ color: 'var(--grey-400)', fontSize: 11 }}>vs</span>
                        <span style={{ fontWeight: 700, fontSize: 13.5 }}>{m.teamB.name}</span>
                        <Flag code={m.teamB.flag} w={24} h={16} />
                      </div>
                      <div style={{ fontSize: 11.5, color: 'var(--grey-500)', marginTop: 4 }}>{m.venue}</div>
                    </Td>
                    <Td><span style={{ fontSize: 12.5 }}>{m.stage}</span></Td>
                    <Td>
                      <div style={{ fontSize: 12.5 }}>{formatKickoff(m.kickoffAt)}</div>
                      {(m.status === 'OPEN' || m.status === 'SCHEDULED') && (
                        <div style={{ marginTop: 4 }}>
                          <Countdown to={m.kickoffMs} tone="light" size="sm" prefix={m.status === 'OPEN' ? 'CLOSE' : 'KICK'} />
                        </div>
                      )}
                    </Td>
                    <Td><StatusBadge status={m.status} size="sm" /></Td>
                    <Td align="right">
                      <span className="font-display" style={{ fontSize: 18 }}>{predCount.toLocaleString()}</span>
                    </Td>
                    <Td align="right">
                      <div style={{ display: 'inline-flex', gap: 6 }}>
                        <IconBtn title="Download CSV" onClick={() => fakeCsv(`match_${m.id}_predictions.csv`)} icon="receipt" />
                        {m.status === 'CLOSED' && (
                          <IconBtn title="Settle" onClick={() => ctx.goTab('settle')} icon="check" tone="orange" />
                        )}
                        {m.status === 'SETTLED' && (
                          <IconBtn title="Run draw" onClick={() => ctx.goTab('draw')} icon="trophy" tone="orange" />
                        )}
                        <IconBtn title="Delete" onClick={() => deleteMatch(m.id)} icon="bolt" tone="danger" />
                      </div>
                    </Td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan="6" style={{ padding: 32, textAlign: 'center', color: 'var(--grey-500)' }}>No matches match those filters.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Panel>
    </AdminSection>
  );
}

function Th({ children, align = 'left' }) {
  return (
    <th style={{
      padding: '12px 14px', textAlign: align,
      fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
      color: 'var(--grey-600)', fontWeight: 700,
    }}>{children}</th>
  );
}
function Td({ children, align = 'left' }) {
  return <td style={{ padding: '14px', textAlign: align, verticalAlign: 'middle' }}>{children}</td>;
}
function IconBtn({ icon, title, onClick, tone = 'default' }) {
  const palette = {
    default: { bg: '#fff',          fg: 'var(--grey-700)', bd: 'var(--grey-300)' },
    orange:  { bg: 'var(--orange-50)', fg: 'var(--orange-dark)', bd: 'var(--orange)' },
    danger:  { bg: '#fff',          fg: '#b91c1c',         bd: '#fecaca' },
  }[tone];
  return (
    <button onClick={onClick} title={title} style={{
      background: palette.bg, color: palette.fg, border: `1.5px solid ${palette.bd}`,
      padding: 7, cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <Icon name={icon} size={15} />
    </button>
  );
}

/* ============================================================
   CREATE MATCH
   ============================================================ */
function AdminCreate({ ctx }) {
  const teamKeys = Object.keys(TEAMS);
  const [teamA, setTeamA] = useState('');
  const [teamB, setTeamB] = useState('');
  const [kickoff, setKickoff] = useState('');
  const [stage, setStage] = useState('Group Stage');
  const [venue, setVenue] = useState('');

  const ok = teamA && teamB && teamA !== teamB && kickoff;

  function submit() {
    if (!ok) return;
    const ko = new Date(kickoff);
    const newMatch = {
      id: Math.max(...ctx.matchesState.map(m => m.id)) + 1,
      teamA: TEAMS[teamA], teamB: TEAMS[teamB],
      teamAKey: teamA, teamBKey: teamB,
      kickoffAt: ko, kickoffMs: ko.getTime(),
      stage, venue: venue || '—',
      status: ko.getTime() - Date.now() > HOURS(24) ? 'SCHEDULED' : 'OPEN',
      settled: null,
    };
    ctx.setMatchesState(s => [...s, newMatch]);
    ctx.setToast({ message: `Match created: ${newMatch.teamA.name} vs ${newMatch.teamB.name}`, tone: 'success' });
    setTeamA(''); setTeamB(''); setKickoff(''); setStage('Group Stage'); setVenue('');
  }

  return (
    <AdminSection
      title="Schedule a new match"
      sub="Pick the two teams, set the kickoff, and choose the stage. Predictions auto-open 24h before kickoff."
    >
      <div className="admin-2col" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 18 }}>
        <Panel title="Match details">
          <div style={{ display: 'grid', gap: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <FormSelect label="Team A" value={teamA} onChange={setTeamA} options={teamKeys.map(k => ({ value: k, label: TEAMS[k].name }))} placeholder="Select team A" />
              <FormSelect label="Team B" value={teamB} onChange={setTeamB} options={teamKeys.filter(k => k !== teamA).map(k => ({ value: k, label: TEAMS[k].name }))} placeholder="Select team B" />
            </div>
            <div>
              <FormLabel>Kickoff (your local time)</FormLabel>
              <input type="datetime-local" value={kickoff} onChange={(e) => setKickoff(e.target.value)} style={inputStyle} />
            </div>
            <FormSelect label="Stage" value={stage} onChange={setStage} options={STAGES.map(s => ({ value: s, label: s }))} />
            <div>
              <FormLabel>Venue <span style={{ color: 'var(--grey-400)', fontWeight: 400 }}>(optional)</span></FormLabel>
              <input value={venue} onChange={(e) => setVenue(e.target.value)} placeholder="e.g. MetLife Stadium, New Jersey" style={inputStyle} />
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              <AdminBtn kind="primary" icon="check" onClick={submit} disabled={!ok}>Create match</AdminBtn>
              <AdminBtn kind="ghost" onClick={() => { setTeamA(''); setTeamB(''); setKickoff(''); setVenue(''); }}>Reset</AdminBtn>
            </div>
          </div>
        </Panel>

        <Panel title="Preview" action={<span style={{ fontSize: 11, color: 'var(--grey-500)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>How it'll look</span>}>
          {(teamA && teamB) ? (
            <div style={{
              border: '2px solid var(--grey-200)', padding: 18, background: 'var(--grey-50)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                <StatusBadge status="SCHEDULED" size="sm" />
                <span className="font-mono" style={{ fontSize: 11, color: 'var(--grey-500)' }}>{stage}</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 14 }}>
                <div style={{ textAlign: 'center' }}>
                  <Flag code={TEAMS[teamA].flag} w={48} h={32} />
                  <div className="font-display" style={{ fontSize: 14, marginTop: 6 }}>{TEAMS[teamA].name}</div>
                </div>
                <VSHex size={32} />
                <div style={{ textAlign: 'center' }}>
                  <Flag code={TEAMS[teamB].flag} w={48} h={32} />
                  <div className="font-display" style={{ fontSize: 14, marginTop: 6 }}>{TEAMS[teamB].name}</div>
                </div>
              </div>
              <div style={{ marginTop: 14, fontSize: 12, color: 'var(--grey-600)' }}>
                {kickoff ? formatKickoff(new Date(kickoff)) : 'Set a kickoff time…'}
                {venue && <> · {venue}</>}
              </div>
            </div>
          ) : (
            <div style={{ color: 'var(--grey-500)', fontSize: 13.5, padding: 20, textAlign: 'center' }}>
              Pick two teams to see the preview.
            </div>
          )}
        </Panel>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .admin-2col { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </AdminSection>
  );
}

function FormLabel({ children }) {
  return <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>{children}</div>;
}
function FormSelect({ label, value, onChange, options, placeholder }) {
  return (
    <div>
      <FormLabel>{label}</FormLabel>
      <select value={value} onChange={(e) => onChange(e.target.value)} style={inputStyle}>
        {placeholder && <option value="">— {placeholder} —</option>}
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </div>
  );
}

/* ============================================================
   SETTLE
   ============================================================ */
function AdminSettle({ ctx }) {
  const candidates = ctx.matchesState.filter(m => m.status === 'CLOSED' || m.status === 'OPEN');
  const [mid, setMid] = useState('');
  const [result, setResult] = useState(null); // 'A' | 'DRAW' | 'B'
  const [scoreA, setScoreA] = useState('');
  const [scoreB, setScoreB] = useState('');
  const match = candidates.find(m => m.id === Number(mid));

  function settle() {
    if (!match || !result) return;
    const winner = result === 'A' ? match.teamA.name : result === 'B' ? match.teamB.name : 'Draw';
    ctx.setMatchesState(s => s.map(m => m.id === match.id ? {
      ...m, status: 'SETTLED',
      settled: {
        winner: result === 'A' ? match.teamAKey : result === 'B' ? match.teamBKey : null,
        scoreA: Number(scoreA) || 0, scoreB: Number(scoreB) || 0,
        draw: result === 'DRAW',
      }
    } : m));
    ctx.setToast({ message: `Settled: ${match.teamA.name} ${scoreA || 0}–${scoreB || 0} ${match.teamB.name} · ${winner}`, tone: 'success' });
    setMid(''); setResult(null); setScoreA(''); setScoreB('');
  }

  return (
    <AdminSection
      title="Settle a match"
      sub="Enter the result for a closed match. Predictions are auto-flagged correct/incorrect and unlock the lucky-draw."
    >
      <Panel>
        {candidates.length === 0 ? (
          <div style={{ color: 'var(--grey-500)', padding: 20, textAlign: 'center' }}>
            No matches awaiting a result.
          </div>
        ) : (
          <>
            <div style={{ maxWidth: 480 }}>
              <FormSelect label="Pick a match" value={mid} onChange={setMid} placeholder="Select"
                options={candidates.map(m => ({
                  value: String(m.id),
                  label: `${m.teamA.name} vs ${m.teamB.name} · ${m.stage} · ${m.status}`,
                }))}
              />
            </div>

            {match && (
              <div style={{ marginTop: 22 }}>
                <FormLabel>Final result</FormLabel>
                <div className="settle-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                  <SettleBtn selected={result === 'A'} onClick={() => setResult('A')} kind="team" flag={match.teamA.flag} label={`${match.teamA.name} wins`} />
                  <SettleBtn selected={result === 'DRAW'} onClick={() => setResult('DRAW')} kind="draw" label="Draw" />
                  <SettleBtn selected={result === 'B'} onClick={() => setResult('B')} kind="team" flag={match.teamB.flag} label={`${match.teamB.name} wins`} />
                </div>

                <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, maxWidth: 360 }}>
                  <div>
                    <FormLabel>{match.teamA.name} score</FormLabel>
                    <input type="number" min="0" value={scoreA} onChange={(e) => setScoreA(e.target.value)} className="font-mono" style={inputStyle} />
                  </div>
                  <div>
                    <FormLabel>{match.teamB.name} score</FormLabel>
                    <input type="number" min="0" value={scoreB} onChange={(e) => setScoreB(e.target.value)} className="font-mono" style={inputStyle} />
                  </div>
                </div>

                <div style={{ marginTop: 24, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  <AdminBtn kind="primary" icon="check" disabled={!result} onClick={settle}>Mark match settled</AdminBtn>
                  <AdminBtn kind="ghost" onClick={() => { setMid(''); setResult(null); }}>Cancel</AdminBtn>
                </div>

                <div style={{
                  marginTop: 18, padding: '12px 14px', background: 'var(--orange-50)', border: '1.5px solid var(--orange-100)',
                  fontSize: 12.5, color: 'var(--ink)',
                }}>
                  ⚠ This action is irreversible. It will flag <strong>{SAMPLE_PREDICTIONS.filter(p => p.matchId === match.id).length}</strong> predictions
                  as correct / incorrect and unlock the lucky draw.
                </div>
              </div>
            )}
          </>
        )}
      </Panel>

      <style>{`
        @media (max-width: 700px) {
          .settle-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </AdminSection>
  );
}

function SettleBtn({ selected, onClick, kind, flag, label }) {
  return (
    <button onClick={onClick} style={{
      background: selected ? 'var(--orange-50)' : '#fff',
      border: selected ? '2px solid var(--orange)' : '1px solid var(--grey-200)',
      borderRadius: 10,
      boxShadow: selected ? '0 4px 16px rgba(241,86,35,0.22)' : '0 2px 8px rgba(17,6,24,0.05)',
      padding: '18px 14px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
      cursor: 'pointer',
    }}>
      {kind === 'draw' ? (
        <div style={{ width: 56, height: 40, background: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="scale" size={22} color="var(--orange)" />
        </div>
      ) : (
        <Flag code={flag} w={56} h={38} />
      )}
      <span className="font-display" style={{ fontSize: 13.5, textAlign: 'center' }}>{label}</span>
    </button>
  );
}

/* ============================================================
   DRAW
   ============================================================ */
function AdminDraw({ ctx }) {
  const settled = ctx.matchesState.filter(m => m.status === 'SETTLED');
  const [mid, setMid] = useState('');
  const [n, setN] = useState(5);
  const [rolling, setRolling] = useState(false);
  const [winners, setWinners] = useState(null);
  const match = settled.find(m => m.id === Number(mid));

  function rollDraw() {
    if (!match) return;
    setRolling(true);
    setWinners(null);
    setTimeout(() => {
      const pool = SAMPLE_PREDICTIONS.filter(p => p.matchId === match.id && p.isCorrect);
      const shuffled = [...pool].sort(() => Math.random() - 0.5);
      setWinners({ pool: pool.length, picks: shuffled.slice(0, Math.min(n, pool.length)) });
      setRolling(false);
      ctx.setToast({ message: `${Math.min(n, pool.length)} winners drawn from ${pool.length} correct predictions.`, tone: 'success' });
    }, 1100);
  }

  return (
    <AdminSection
      title="Run the lucky draw"
      sub="Random winners from the pool of correct predictions. Uses cryptographic randomness in production."
    >
      <Panel>
        {settled.length === 0 ? (
          <div style={{ color: 'var(--grey-500)', padding: 20, textAlign: 'center' }}>
            No settled matches yet. Settle one first.
          </div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, maxWidth: 700 }} className="draw-grid">
              <FormSelect label="Settled match" value={mid} onChange={setMid} placeholder="Select"
                options={settled.map(m => ({ value: String(m.id), label: `${m.teamA.name} vs ${m.teamB.name} · ${m.stage}` }))} />
              <div>
                <FormLabel>Number of winners</FormLabel>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <input type="range" min="1" max="50" value={n} onChange={(e) => setN(Number(e.target.value))} style={{ flex: 1 }} />
                  <input type="number" min="1" max="50" value={n} onChange={(e) => setN(Math.max(1, Math.min(50, Number(e.target.value) || 1)))}
                    className="font-mono" style={{ ...inputStyle, width: 70, padding: '8px 10px', textAlign: 'center' }} />
                </div>
              </div>
            </div>

            <div style={{ marginTop: 22 }}>
              <AdminBtn kind="primary" icon="trophy" disabled={!match || rolling} onClick={rollDraw}>
                {rolling ? 'Rolling…' : '🎲 Run lucky draw'}
              </AdminBtn>
            </div>

            {/* Results */}
            {winners && (
              <div style={{ marginTop: 24 }}>
                <div style={{
                  background: 'var(--ink)', color: '#fff',
                  padding: '16px 18px',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12,
                }}>
                  <div>
                    <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--orange)', fontWeight: 700 }}>
                      Lucky draw winners
                    </div>
                    <div className="font-display" style={{ fontSize: 22, marginTop: 4 }}>
                      {winners.picks.length} from a pool of {winners.pool}
                    </div>
                  </div>
                  <AdminBtn kind="ink" icon="receipt" onClick={() => ctx.setToast({ message: 'Winners CSV queued.', tone: 'info' })}>Export winners CSV</AdminBtn>
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 640 }}>
                    <thead>
                      <tr style={{ background: 'var(--grey-50)' }}>
                        <Th>#</Th><Th>Name</Th><Th>Mobile</Th><Th>Outlet</Th><Th>Bill</Th><Th>Pick</Th>
                      </tr>
                    </thead>
                    <tbody>
                      {winners.picks.map((w, i) => (
                        <tr key={w.id} style={{ borderTop: '1px solid var(--grey-100)' }}>
                          <Td><span className="font-display" style={{ fontSize: 16, color: 'var(--orange)' }}>{String(i + 1).padStart(2,'0')}</span></Td>
                          <Td><strong>{w.customerName}</strong></Td>
                          <Td><span className="font-mono">{w.customerPhone}</span></Td>
                          <Td>{w.outlet}</Td>
                          <Td><span className="font-mono">{w.billNumber}</span></Td>
                          <Td>{w.pick}</Td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </>
        )}
      </Panel>
      <style>{`
        @media (max-width: 700px) {
          .draw-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </AdminSection>
  );
}

Object.assign(window, {
  AdminOverview, AdminMatches, AdminCreate, AdminSettle, AdminDraw,
  Th, Td, IconBtn, FormLabel, FormSelect, StatCard,
});
