/* global React, C, Screen, Header, Avatar, Pill, Toggle, CTA, Chevron, Refresh, Check, Lock, Plus, Close, Search */
// screens-admin.jsx — Commissioner Admin · god mode dashboard.

function AdminScreen() {
  const [maintenanceMode, setMaintenanceMode] = React.useState(false);
  const [clubhouseOpen, setClubhouseOpen] = React.useState(true);
  const [lateSwap, setLateSwap] = React.useState(false);

  // Live data
  const [members, setMembers] = React.useState([]);
  const [tournaments, setTournaments] = React.useState([]);
  const [tournament, setTournament] = React.useState(null);
  const [field, setField] = React.useState([]);
  const [audit, setAudit] = React.useState([]);
  const [dispatches, setDispatches] = React.useState([]);

  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) return;
    let cancelled = false;
    (async () => {
      try {
        const [ms, ts, t, al, cl] = await Promise.all([
          api.loadAllMembers(),
          api.loadAllTournaments(2026),
          api.currentTournament?.(),
          api.loadAuditLog(20),
          api.loadLatestCaddieList(10),
        ]);
        if (cancelled) return;
        setMembers(ms || []);
        setTournaments(ts || []);
        setTournament(t || null);
        setAudit(al || []);
        setDispatches(cl || []);
        if (t) {
          const f = await api.loadField(t.id);
          if (!cancelled) setField(f || []);
        }
      } catch (e) { console.warn('admin load failed', e); }
    })();
    return () => { cancelled = true; };
  }, []);

  // Derived stats
  const activeCount    = members.filter((m) => m.status === 'active' && !m.is_suspended).length;
  const invitedCount   = members.filter((m) => m.status === 'pending').length;
  const suspendedCount = members.filter((m) => m.is_suspended).length;
  const deputies       = members.filter((m) => m.role === 'deputy');
  const fieldCount     = field.length;
  const salaryRange    = field.length ? `$${Math.min(...field.map((f) => f.salary))} — $${Math.max(...field.map((f) => f.salary))}` : '—';

  const caddieCommand = `cd server && node cli/caddie.js --tournament=${tournament?.major || 'open'} --tone=snarky`;
  const refreshCaddie = () => {
    if (tournament?.major) localStorage.removeItem(`caddie-article-v3:${tournament.major}`);
    window.dispatchEvent(new CustomEvent('caddie:regen'));
    window.STORE && window.STORE.toast && window.STORE.toast('Refreshing dispatch');
  };
  const copyCliCommand = () => {
    if (navigator.clipboard) navigator.clipboard.writeText(caddieCommand).catch(() => {});
    window.STORE && window.STORE.toast && window.STORE.toast('Command copied');
  };
  const ago = (ts) => {
    if (!ts) return '';
    const ms = Date.now() - new Date(ts).getTime();
    const m = Math.floor(ms / 60000);
    if (m < 1)  return 'now';
    if (m < 60) return `${m}m`;
    const h = Math.floor(m / 60);
    if (h < 24) return `${h}h`;
    const d = Math.floor(h / 24);
    return `${d}d`;
  };

  return (
    <Screen label="10 Admin" bottomNav="stats">
      <Header title="Commissioner" subtitle="God mode · 2026 season" onBack />

      {/* Identity / context */}
      <AdminHero />

      {/* Quick actions */}
      <SectionLabel right="Most-used">Quick actions</SectionLabel>
      <div style={{ margin: '0 16px 24px', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
        <QuickBtn glyph={<Bolt size={18} />}           label="Force-lock lineups"   sub="Current major" warn />
        <QuickBtn glyph={<UnlockGlyph size={18} />}    label="Re-open for member"   sub="Pick a member" />
        <QuickBtn glyph={<Megaphone size={18} />}      label="Broadcast push"        sub={`All ${members.length} ${members.length === 1 ? 'member' : 'members'}`} />
        <QuickBtn glyph={<Pencil size={18} />}         label="Adjust a score"        sub="Manual override" />
      </div>

      {/* Jump nav — pill row of section anchors */}
      <JumpNav items={[
        'Members', 'Lineups', 'Rules', 'Schedule', 'Tournament', 'Field',
        'Caddie', 'Clubhouse', 'Comms', 'Money', 'Awards', 'Audit',
        'Integrations', 'Data', 'Branding', 'Danger',
      ]} />

      {/* Members */}
      <AdminCard
        title="Members & access" sub={`${activeCount} active · ${invitedCount} invited · ${suspendedCount} suspended`}
        rightStat={String(members.length)}
        rows={[
          { l: 'Active',     v: String(activeCount) },
          { l: 'Pending invite', v: String(invitedCount), accent: invitedCount > 0 ? 'amber' : undefined },
          { l: 'Suspended',  v: String(suspendedCount), accent: suspendedCount > 0 ? 'red' : undefined },
          { l: 'Deputies',   v: deputies.length ? `${deputies.length} (${deputies.map((d) => d.handle || d.display_name).join(', ')})` : 'None' },
          { l: 'Commissioner', v: members.find((m) => m.role === 'commissioner')?.handle || members.find((m) => m.role === 'commissioner')?.display_name || '—' },
        ]}
        cta="Manage members"
      />

      {/* Lineups */}
      <AdminCard
        title="Lineups · current major"
        sub={tournament ? `For ${tournament.name}` : 'No active tournament'}
        rows={[
          { l: 'Tournament', v: tournament?.name || '—' },
          { l: 'Lock time',  v: tournament?.lineup_locks_at ? new Date(tournament.lineup_locks_at).toLocaleString('en-US') : '—' },
          { l: 'Status',     v: tournament?.status ? tournament.status[0].toUpperCase() + tournament.status.slice(1) : '—', accent: tournament?.status === 'live' ? 'emerald' : undefined },
        ]}
        cta="Open lineup overrides"
      />

      {/* Pool rules */}
      <AdminCard
        title="Pool rules" sub="Buy-in, cap, scoring, lock times"
        rows={[
          { l: 'Buy-in',       v: '$200.00' },
          { l: 'Salary cap',   v: '$200' },
          { l: 'Roster size',  v: '6 golfers' },
          { l: 'Lock time',    v: 'Thu 7:00a ET' },
          { l: 'Late swap',    v: lateSwap ? 'Allowed (R3 only)' : 'Disabled' },
          { l: 'Scoring profile', v: 'Standard · birdie +1, eagle +3' },
        ]}
        cta="Edit rules"
      >
        <InlineToggleRow label="Allow R3 late-swap (24-hr window)" on={lateSwap} onChange={setLateSwap}
          sub="Members can replace one golfer after R2 cut. Resets on each major." />
      </AdminCard>

      {/* Schedule */}
      <SectionLabel>2026 Schedule</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12 }}>
        {tournaments.length === 0 ? (
          <div style={{ padding: '16px 20px', color: C.text2, font: '400 13px/18px Inter' }}>No tournaments seeded yet.</div>
        ) : tournaments.map((t, i) => {
          const startsAt = t.starts_at ? new Date(t.starts_at) : null;
          const range = startsAt
            ? startsAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
            : '';
          return (
            <ScheduleRow
              key={t.id}
              major={t.name}
              venue={t.venue}
              state={t.status === 'final' ? 'done' : t.status === 'live' ? 'live' : 'upcoming'}
              who={t.status === 'live' ? 'In progress' : t.status === 'final' ? 'Final' : `Starts ${range}`}
              last={i === tournaments.length - 1}
            />
          );
        })}
      </div>

      {/* Current tournament overrides */}
      <SectionLabel>{tournament ? `Current major · ${tournament.name}` : 'Current major'}</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12 }}>
        <ManageRow label="Field"           value={fieldCount ? `${fieldCount} golfers` : 'Not priced yet'} />
        <ManageRow label="Salary range"    value={salaryRange} />
        <ManageRow label="Status"          value={tournament?.status || '—'} accent={tournament?.status === 'live' ? 'emerald' : undefined} />
        <ManageRow label="Disqualifications" value={field.filter((f) => f.is_active === false).length || 'None'} last />
      </div>

      {/* Field & salaries editor */}
      <AdminCard
        title="Field & salaries"
        sub="Pulled from Yahoo by the live-scoring worker."
        rows={[
          { l: 'Field size',         v: fieldCount ? `${fieldCount} golfers` : 'Not priced' },
          { l: 'Salary range',       v: salaryRange },
          { l: 'Active',             v: String(field.filter((f) => f.is_active !== false).length) },
          { l: 'Source',             v: 'Yahoo DFS' },
        ]}
        cta="Open field editor"
      />

      {/* Score & rules engine */}
      <AdminCard
        title="Scoring · live overrides"
        sub="Manually edit any score, apply event multipliers, recalc all."
        rows={[
          { l: 'Manual overrides',    v: '3 this round · last 11m ago' },
          { l: 'Event multiplier',    v: '1.0× (no boost)' },
          { l: 'Bonus / penalty pts', v: '+12 / -0 total' },
          { l: 'Last full recalc',    v: '38m ago · auto' },
        ]}
        cta="Open scoring console"
      />

      {/* Caddie — generation lives in a CLI; this card just explains how */}
      <SectionLabel right="CLI · runs 4×/year">The Caddie</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12 }}>
        <div style={{ padding: '14px 16px', borderBottom: `1px solid ${C.hairline}` }}>
          <div style={{ font: '500 13px/18px Inter', color: C.text }}>
            Dispatches are generated out-of-band by a CLI script that calls
            Claude Code in headless mode. No API key, no servers — run it from
            your laptop after each major.
          </div>
          <div style={{
            marginTop: 10, padding: '10px 12px', borderRadius: 8,
            background: C.surface2,
            font: '500 12px/18px ui-monospace, SFMono-Regular, Menlo, monospace',
            color: C.text, whiteSpace: 'pre-wrap', overflowX: 'auto',
          }}>
            {caddieCommand}
          </div>
          <div style={{
            marginTop: 8, display: 'flex', gap: 8,
          }}>
            <button onClick={copyCliCommand} style={{
              height: 36, padding: '0 12px', borderRadius: 8,
              background: C.surface2, color: C.text, border: `1px solid ${C.hairline}`,
              font: '600 12px/1 Inter', cursor: 'pointer',
            }}>Copy command</button>
            <button onClick={refreshCaddie} style={{
              height: 36, padding: '0 12px', borderRadius: 8,
              background: C.emerald, color: '#0a0a0a', border: 'none',
              font: '600 12px/1 Inter', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Refresh size={12} />
              <span>Refresh dispatch</span>
            </button>
          </div>
          <div style={{ font: '400 12px/16px Inter', color: C.text3, marginTop: 10 }}>
            Tone: <span style={{ color: C.text2 }}>--tone=dry | snarky | roast | wholesome</span>.
            Length: <span style={{ color: C.text2 }}>--length=tweet | standard | longform</span>.
            Add <span style={{ color: C.text2 }}>--dry-run</span> to preview without publishing.
          </div>
        </div>

        {/* Recent dispatches — pulled live from caddie_articles. */}
        <div style={{ borderTop: `1px solid ${C.hairline}` }}>
          <div style={{
            padding: '12px 16px 8px',
            font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11, color: C.text3,
          }}>Recent dispatches</div>
          {dispatches.length === 0 ? (
            <div style={{ padding: '14px 16px', color: C.text3, font: '400 13px/18px Inter' }}>
              None yet. Run the CLI command after each major.
            </div>
          ) : dispatches.map((d, i) => (
            <DispatchRow
              key={d.id || i}
              title={d.headline}
              when={d.created_at ? new Date(d.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : ''}
              tone={d.tone ? d.tone[0].toUpperCase() + d.tone.slice(1) : ''}
              reactions=""
              last={i === dispatches.length - 1}
            />
          ))}
        </div>
      </div>

      {/* Clubhouse */}
      <AdminCard
        title="Clubhouse" sub="Per-pool message board"
        rows={[
          { l: 'Status',          v: clubhouseOpen ? 'Open' : 'Locked', accent: clubhouseOpen ? 'emerald' : 'amber' },
        ]}
        cta="Open moderation"
      >
        <InlineToggleRow label="Clubhouse open" on={clubhouseOpen} onChange={setClubhouseOpen}
          sub="When off, members see a read-only archive." />
      </AdminCard>

      {/* Buy-ins (currently just lists members — buy-in tracking not in schema yet) */}
      <SectionLabel right={`${members.length} members`}>Members · 2026 season</SectionLabel>
      <div style={{ margin: '0 16px 16px', background: C.surface, borderRadius: 12 }}>
        {members.length === 0 ? (
          <div style={{ padding: '16px 20px', color: C.text2, font: '400 13px/18px Inter' }}>
            No members yet. Insert them via SQL Editor or invite them.
          </div>
        ) : members.map((m, i) => (
          <BuyInRow
            key={m.id || i}
            name={m.display_name || m.handle || '—'}
            tone={m.avatar_tone || 1}
            paid={m.status === 'active'}
            champion={!!m.champion}
            last={i === members.length - 1}
          />
        ))}
      </div>

      {/* Audit log */}
      <SectionLabel right={audit.length ? `Last ${audit.length}` : ''}>Audit log</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12 }}>
        {audit.length === 0 ? (
          <div style={{ padding: '16px 20px', color: C.text2, font: '400 13px/18px Inter' }}>
            No admin actions recorded yet.
          </div>
        ) : audit.map((row, i) => (
          <AuditRow
            key={row.id || i}
            who={row.actor?.handle || row.actor?.display_name || 'system'}
            what={row.action.replace(/_/g, ' ')}
            when={ago(row.created_at)}
            last={i === audit.length - 1}
          />
        ))}
      </div>

      {/* Integrations */}
      <AdminCard
        title="Integrations"
        sub="Slack, Discord, webhooks, outbound API"
        rows={[
          { l: 'Slack webhook',     v: '#fantasy-talk', accent: 'emerald' },
          { l: 'Discord webhook',   v: 'Not connected' },
          { l: 'Outbound API key',  v: 'sk_•••••••42a8' },
          { l: 'Inbound webhooks',  v: '2 active (Tour API, Stripe)' },
          { l: 'Calendar feed',     v: 'iCal · live' },
        ]}
        cta="Manage integrations"
      />

      {/* Data tools */}
      <AdminCard
        title="Data tools"
        sub="Export. Import. Backup. GDPR / right-to-delete."
        rows={[
          { l: 'Last backup',         v: '12h ago · auto' },
          { l: 'Export formats',      v: 'CSV · JSON · PDF' },
          { l: 'Bulk import',         v: 'Members · field · salaries' },
          { l: 'Deletion requests',   v: '0 pending' },
          { l: 'Retention policy',    v: 'Forever for season data' },
        ]}
        cta="Open data tools"
      />

      {/* Branding */}
      <AdminCard
        title="Branding"
        sub="Pool name, tagline, logo, default palette"
        rows={[
          { l: 'Pool name',           v: "CamBam · Majors '26" },
          { l: 'Tagline',             v: 'Augusta at dusk' },
          { l: 'Logo',                v: 'CB monogram · emerald' },
          { l: 'Default palette',     v: 'Augusta at dusk' },
          { l: 'Custom domain',       v: 'cambam.fans/majors' },
        ]}
        cta="Edit branding"
      />

      {/* Site / system */}
      <AdminCard
        title="System" sub="Maintenance, exports, integrations"
        rows={[
          { l: 'Pool URL',     v: 'cambam.fans/majors' },
          { l: 'Magic-link domain', v: 'cambam.fans' },
          { l: 'Live results provider', v: 'PGA Tour API · healthy' },
          { l: 'Notifications',v: 'OneSignal · 47 / 47 subscribed' },
        ]}
        cta="System settings"
      >
        <InlineToggleRow label="Maintenance mode" on={maintenanceMode} onChange={setMaintenanceMode}
          sub="Members see a friendly down-screen. Magic-links still work for admins." />
      </AdminCard>

      {/* Danger zone */}
      <SectionLabel right="Cannot be undone">Danger zone</SectionLabel>
      <div style={{
        margin: '0 16px 32px', padding: 14,
        background: 'rgba(239,68,68,0.04)',
        border: `1px solid rgba(239,68,68,0.18)`,
        borderRadius: 12,
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        <DangerRow label="Transfer commissioner role"  sub="Hand the keys to someone else. Irreversible without their consent." />
        <DangerRow label="Add or revoke a deputy"      sub="Grant another member admin access. Can be undone." />
        <DangerRow label="Force log-out all members"   sub="Invalidates every active session. Magic-links still work." />
        <DangerRow label="Rotate magic-link signing key" sub="Every existing magic-link in inboxes goes invalid." />
        <DangerRow label="Reset all member lineups"    sub="For the current major only. Use to recover from a bug." />
        <DangerRow label="Recalculate all scores"      sub="From scratch using current rules. Takes ~30 seconds." />
        <DangerRow label="Archive '26 season"          sub="Locks the data, starts a fresh one. You'll get a new pool ID." />
        <DangerRow label="Delete a member account"     sub="GDPR / right-to-delete. Removes all their data. Buy-in stays in pot." />
        <DangerRow label="Delete this pool"            sub="48-hour soft-delete. Members are notified by email." nuke />
      </div>
    </Screen>
  );
}

// ─── Building blocks ────────────────────────────────────────────────

function JumpNav({ items }) {
  return (
    <div style={{
      margin: '0 0 16px',
      padding: '0 16px',
      overflow: 'auto',
      WebkitOverflowScrolling: 'touch',
    }}>
      <div style={{
        display: 'flex', gap: 6, paddingBottom: 4,
      }}>
        {items.map(p => (
          <button key={p} style={{
            flexShrink: 0, padding: '6px 12px', borderRadius: 999,
            background: C.surface2, border: `1px solid ${C.hairline}`,
            color: C.text2, font: '500 12px/16px Inter', whiteSpace: 'nowrap',
            cursor: 'pointer',
          }}>{p}</button>
        ))}
      </div>
    </div>
  );
}

function AdminHero() {
  const me = window.useStore((s) => s.me) || {};
  const isCommissioner = me.role === 'commissioner' || me.role === 'deputy';
  const joinedAt = me.joinedAt || me.joined_at ? new Date(me.joinedAt || me.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '';
  return (
    <>
      <div style={{
        margin: '4px 16px 16px', padding: '14px',
        background: 'rgba(31, 138, 91, 0.06)',
        border: `1px solid rgba(31, 138, 91, 0.22)`,
        borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <Avatar name={me.displayName || me.handle || 'You'} size={40} tone={me.tone || 6} champion={!!me.champion} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '600 15px/20px Inter', color: C.text }}>
            {isCommissioner ? `Signed in as ${me.role === 'deputy' ? 'deputy' : 'commissioner'}` : 'Member view (read-only)'}
          </div>
          <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 2 }}>
            {[me.handle, joinedAt && `Since ${joinedAt}`].filter(Boolean).join(' · ') || me.email || ''}
          </div>
        </div>
        <Pill kind={isCommissioner ? 'paid' : 'neutral'}>{isCommissioner ? 'Admin' : 'Read'}</Pill>
      </div>
      {!isCommissioner && (
        <div style={{
          margin: '0 16px 16px', padding: '12px 14px',
          background: C.surface, borderRadius: 12,
          font: '400 13px/18px Inter', color: C.text2,
        }}>
          The admin view is visible to everyone but only commissioners can change settings. Most stats below are illustrative until live data accumulates.
        </div>
      )}
    </>
  );
}

function SectionLabel({ children, right }) {
  return (
    <div style={{
      padding: '0 16px 12px',
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
    }}>
      <span style={{
        font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        color: C.text3,
      }}>{children}</span>
      {right && <span style={{
        font: '400 11px/16px Inter', color: C.text3,
      }}>{right}</span>}
    </div>
  );
}

function AdminCard({ title, sub, rows, cta, rightStat, children }) {
  return (
    <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12, overflow: 'hidden' }}>
      <div style={{ padding: '14px 16px', borderBottom: rows && rows.length ? `1px solid ${C.hairline}` : 'none' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ font: '600 15px/20px Inter', color: C.text, flex: 1 }}>{title}</span>
          {rightStat && <span className="tnum" style={{ font: '700 18px/22px Inter', color: C.text }}>{rightStat}</span>}
        </div>
        {sub && <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 2 }}>{sub}</div>}
      </div>

      {rows && rows.map((r, i) => (
        <div key={i} style={{
          padding: '12px 16px', display: 'flex', justifyContent: 'space-between', gap: 10,
          borderBottom: (i < rows.length - 1 || cta || children) ? `1px solid ${C.hairline}` : 'none',
          font: '500 13px/18px Inter',
        }}>
          <span style={{ color: C.text2 }}>{r.l}</span>
          <span className="tnum" style={{
            color: r.accent === 'emerald' ? C.emerald
                 : r.accent === 'amber'   ? C.amber
                 : r.accent === 'red'     ? C.red : C.text,
            textAlign: 'right',
          }}>{r.v}</span>
        </div>
      ))}

      {children}

      {cta && (
        <button style={{
          width: '100%', padding: '14px 16px', background: 'transparent',
          border: 'none', borderTop: `1px solid ${C.hairline}`,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span style={{ color: C.emerald, font: '600 14px/18px Inter' }}>{cta}</span>
          <Chevron dir="right" size={14} />
        </button>
      )}
    </div>
  );
}

function QuickBtn({ glyph, label, sub, warn }) {
  return (
    <button style={{
      padding: '14px', background: C.surface, border: `1px solid ${C.hairline}`,
      borderRadius: 12, cursor: 'pointer', textAlign: 'left',
      display: 'flex', flexDirection: 'column', gap: 8, minHeight: 84,
      color: C.text,
    }}>
      <span style={{ color: warn ? C.amber : C.emerald }}>{glyph}</span>
      <span style={{ font: '600 13px/16px Inter', color: warn ? C.amber : C.text }}>{label}</span>
      <span style={{ font: '400 11px/14px Inter', color: C.text3, marginTop: 'auto' }}>{sub}</span>
    </button>
  );
}

// Inline glyphs for QuickBtn (not exposed elsewhere)
function UnlockGlyph({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="10" rx="2"/>
      <path d="M7 11V7a5 5 0 019.6-2"/>
    </svg>
  );
}
function Megaphone({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 11v2a2 2 0 002 2h2l8 4V5L7 9H5a2 2 0 00-2 2z"/>
      <path d="M18 8a4 4 0 010 8"/>
    </svg>
  );
}
function Pencil({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 20h9"/>
      <path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/>
    </svg>
  );
}

function InlineToggleRow({ label, sub, on, onChange }) {
  return (
    <div style={{
      padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderTop: `1px solid ${C.hairline}`,
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ font: '500 14px/20px Inter', color: C.text }}>{label}</div>
        {sub && <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{sub}</div>}
      </div>
      <Toggle on={on} onChange={onChange} />
    </div>
  );
}

function ScheduleRow({ major, venue, state, who, last }) {
  const live = state === 'live';
  const done = state === 'done';
  return (
    <div style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 999,
        background: done ? C.emeraldMute : live ? 'rgba(31, 138, 91, 0.18)' : C.surface2,
        color: done || live ? C.emerald : C.text3,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {done && <Check size={12} />}
        {live && <span className="live-pulse" style={{ width: 6, height: 6, borderRadius: 999, background: C.emerald }} />}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 14px/18px Inter', color: C.text }}>{major}</div>
        <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{venue} · {who}</div>
      </div>
      <Chevron dir="right" size={14} />
    </div>
  );
}

function ManageRow({ label, value, accent, last }) {
  return (
    <div style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <span style={{ font: '500 13px/18px Inter', color: C.text2 }}>{label}</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span className="tnum" style={{
          font: '500 13px/18px Inter',
          color: accent === 'emerald' ? C.emerald : C.text,
        }}>{value}</span>
        <Chevron dir="right" size={12} />
      </span>
    </div>
  );
}

function DispatchRow({ title, when, tone, reactions, last }) {
  return (
    <div style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '500 14px/20px Inter', color: C.text,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
        <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 2 }}>
          {when} · {tone} · {reactions}
        </div>
      </div>
      <Chevron dir="right" size={14} />
    </div>
  );
}

function BuyInRow({ name, tone, paid, champion, last }) {
  return (
    <div style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10,
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <Avatar name={name} size={32} tone={tone} champion={champion} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 14px/18px Inter', color: C.text }}>{name}</div>
        <div className="tnum" style={{ font: '500 12px/16px Inter', color: C.text2 }}>$200.00</div>
      </div>
      {paid ? (
        <Pill kind="paid">Paid</Pill>
      ) : (
        <button style={{
          height: 28, padding: '0 10px', borderRadius: 999,
          background: 'rgba(245,158,11,0.10)', border: `1px solid rgba(245,158,11,0.30)`,
          color: C.amber, cursor: 'pointer',
          font: '600 11px/1 Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        }}>Nudge</button>
      )}
    </div>
  );
}

function AuditRow({ who, what, when, last }) {
  return (
    <div style={{
      padding: '12px 16px',
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
      font: '400 13px/18px Inter', color: C.text2,
      display: 'flex', justifyContent: 'space-between', gap: 12,
    }}>
      <div style={{ flex: 1 }}>
        <span style={{ color: C.text, fontWeight: 600 }}>{who}</span> {what}
      </div>
      <span style={{ color: C.text3, font: '400 12px/18px Inter' }}>{when}</span>
    </div>
  );
}

function DangerRow({ label, sub, nuke }) {
  return (
    <div style={{
      padding: '12px 14px', borderRadius: 8,
      background: nuke ? 'rgba(239,68,68,0.08)' : 'transparent',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 14px/18px Inter', color: nuke ? C.red : C.text }}>{label}</div>
        <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{sub}</div>
      </div>
      <button style={{
        height: 32, padding: '0 12px', borderRadius: 6,
        background: 'transparent', border: `1px solid rgba(239,68,68,0.4)`,
        color: C.red, font: '600 12px/1 Inter', cursor: 'pointer',
      }}>{nuke ? 'Delete' : 'Action'}</button>
    </div>
  );
}

const ghostBtn = () => ({
  flex: 1, height: 44, borderRadius: 8, background: C.surface,
  border: `1px solid ${C.hairline}`, color: C.text,
  font: '600 14px/1 Inter', cursor: 'pointer',
});
const primaryBtn = () => ({
  flex: 1, height: 44, borderRadius: 8, background: C.emerald,
  border: 'none', color: '#0a0a0a',
  font: '600 14px/1 Inter', cursor: 'pointer',
});

Object.assign(window, { AdminScreen });
