// Henry's full routes: /ai-agents, /client-health
// Vukasi's full routes: /at-risk-accounts, /creative-log
// touch

const { Monogram, WidgetCard, Sparkline, Empty, ExtArrow, RoutePage, PillBar, PlaceholderRoute, useToast, ClientHealth, ClientDrawerBody, AtRiskAccounts, NextStepsModal, ReadOnlyBadge } = window.DC;

const fmtAgo = (iso) => {
  const m = Math.round((new Date('2026-04-29T09:00:00Z') - new Date(iso)) / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.round(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.round(h/24)}d ago`;
};

// ── Henry · /ai-agents ──────────────────────────────────────────────────────
function AgentsRoute({ onBack }) {
  const toast = useToast();
  const agents = window.DC_DATA.AGENT_DETAIL;
  const [openAgent, setOpenAgent] = useState('cole');
  const [activityFeed, setActivityFeed] = useState({ sal: [], cole: [], david: [] });
  const [inputModal, setInputModal] = useState(null); // { agent, trigger }

  const fireTrigger = (agent, trigger) => {
    const eta = 4 + Math.floor(Math.random() * 8);
    toast.push({
      title: `${agent.name.split(' ')[0]} is on it.`,
      body: `${trigger.label} — ETA ${eta} min`,
      initials: agent.initials, tone: 'success',
    });
    setActivityFeed(prev => ({
      ...prev,
      [agent.id]: [{
        id: Math.random().toString(36).slice(2),
        when: new Date().toISOString(),
        title: trigger.label,
        status: 'running',
        eta,
      }, ...prev[agent.id]],
    }));
    setInputModal(null);
  };

  const handleClick = (agent, trigger) => {
    if (trigger.kind === 'input') setInputModal({ agent, trigger });
    else fireTrigger(agent, trigger);
  };

  const totalRunning = Object.values(activityFeed).flat().length;
  const totalShipped = Object.values(agents).reduce((s, a) => s + a.outputs.filter(o => o.status === 'shipped').length, 0);
  const totalReview  = Object.values(agents).reduce((s, a) => s + a.outputs.filter(o => o.status === 'review').length, 0);

  return (
    <React.Fragment>
      <RoutePage
        eyebrow="Agent control center"
        title="AI agents"
        lastUpdated="6m ago"
        dataSource="agents.config.yml · last edit 2026-04-22"
        onBack={onBack}
        rollupCards={[
          { label: 'Running now',   value: totalRunning,  sub: totalRunning ? 'mocked from this session' : 'idle' },
          { label: 'Shipped (7d)',  value: totalShipped,  sub: 'across all 3 agents', tone: 'green' },
          { label: 'Awaiting Henry',value: totalReview,   sub: 'click expand to review', tone: 'amber' },
          { label: 'Failed runs',   value: '2',           sub: 'last 7 days', tone: 'red' },
        ]}
        actions={
          <button className="btn-mini" onClick={() => setOpenAgent(null)}>Collapse all</button>
        }>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap-grid)' }}>
          {Object.values(agents).map(a => (
            <AgentPanel key={a.id} agent={a}
                        expanded={openAgent === a.id}
                        onToggle={() => setOpenAgent(openAgent === a.id ? null : a.id)}
                        onTrigger={handleClick}
                        liveActivity={activityFeed[a.id] || []} />
          ))}
        </div>
      </RoutePage>

      <Modal open={!!inputModal} onClose={() => setInputModal(null)}>
        {inputModal && (
          <TriggerInputForm agent={inputModal.agent} trigger={inputModal.trigger}
                            onSubmit={() => fireTrigger(inputModal.agent, inputModal.trigger)}
                            onClose={() => setInputModal(null)} />
        )}
      </Modal>
    </React.Fragment>
  );
}

function AgentPanel({ agent, expanded, onToggle, onTrigger, liveActivity }) {
  const tone = agent.id === 'sal' ? 'forest' : agent.id === 'cole' ? 'gold' : 'forest';
  const okRuns = agent.runHistory.filter(r => r.status === 'ok').length;
  const failRuns = agent.runHistory.filter(r => r.status === 'fail').length;

  return (
    <section className="agent-panel" style={{
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderLeft: '3px solid var(--forest-700)',
    }}>
      {/* Header */}
      <button className="agent-panel-hd" onClick={onToggle} style={{
        width: '100%', textAlign: 'left', cursor: 'pointer',
        background: 'transparent', border: 0, padding: '14px 18px',
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <Monogram initials={agent.initials} tone={tone} size={44} />
        <div className="agent-panel-name" style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
            <span className="serif" style={{ fontSize: 22, lineHeight: 1.05 }}>{agent.name}</span>
            <span className="tag" style={{ fontSize: 9.5 }}>{agent.role}</span>
            <span className="tag" style={{ fontSize: 9.5 }}>{agent.scope.replace('-',' ')}</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 2 }}>{agent.description}</div>
        </div>
        <div className="agent-panel-meta" style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
          <span style={{ fontSize: 10.5, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{agent.cadence.split(' · ')[0]}</span>
          <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{okRuns} ok · {failRuns} fail (7d)</span>
        </div>
        <span className="agent-panel-chev" style={{ marginLeft: 12, fontSize: 18, color: 'var(--ink-soft)', transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform .15s' }}>›</span>
      </button>

      {expanded && (
        <div className="agent-panel-body" style={{ borderTop: '1px solid var(--border)', display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 0 }}>
          {/* Left col: triggers */}
          <div className="agent-panel-triggers" style={{ padding: 18, borderRight: '1px solid var(--border)' }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Trigger a task</div>
            <div className="agent-trigger-grid" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {agent.triggers.map(t => (
                <TriggerCard key={t.id} trigger={t} agent={agent}
                             onClick={() => onTrigger(agent, t)} />
              ))}
            </div>
            <div className="agent-trigger-legend" style={{ marginTop: 16, fontSize: 11, color: 'var(--ink-soft)', display: 'flex', gap: 12 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span className="mono" style={{ fontSize: 11 }}>▶</span> fire-and-forget
              </span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span className="mono" style={{ fontSize: 11 }}>→</span> needs input
              </span>
            </div>
          </div>

          {/* Right col: outputs + run history */}
          <div className="agent-panel-outputs" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 18 }}>
            <section>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Last 10 outputs</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {liveActivity.map(o => (
                  <li key={o.id} className="agent-output-row" style={{
                    display: 'grid', gridTemplateColumns: '70px 1fr auto', gap: 10,
                    padding: '7px 0', fontSize: 12.5,
                    background: 'rgba(248,197,48,.10)', borderTop: '1px solid var(--border-soft)',
                    paddingLeft: 8, paddingRight: 8,
                  }}>
                    <span className="mono" style={{ color: 'var(--gold-deep)', fontSize: 10.5 }}>{fmtAgo(o.when)}</span>
                    <span>{o.title}</span>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: 'var(--gold-deep)', fontWeight: 600 }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--gold-deep)', animation: 'pulse 1.5s ease-in-out infinite' }} />
                      RUNNING · ETA {o.eta}m
                    </span>
                  </li>
                ))}
                {agent.outputs.slice(0, 10).map((o, i) => {
                  const statusColor = o.status === 'shipped' ? 'var(--status-green)' : o.status === 'review' ? 'var(--status-amber)' : 'var(--ink-soft)';
                  return (
                    <li key={o.id}>
                      <a className="agent-output-row" href={o.url} target="_blank" rel="noreferrer" style={{
                        display: 'grid', gridTemplateColumns: '70px 1fr auto', gap: 10,
                        padding: '7px 0', fontSize: 12.5, color: 'inherit',
                        borderTop: i === 0 && liveActivity.length === 0 ? 'none' : '1px solid var(--border-soft)',
                      }}>
                        <span className="mono" style={{ color: 'var(--ink-soft)', fontSize: 10.5 }}>{fmtAgo(o.when)}</span>
                        <span>{o.title}</span>
                        <span style={{ fontSize: 10, color: statusColor, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
                          {o.status === 'shipped' ? '● shipped' : o.status === 'review' ? '○ review' : '× dropped'}
                        </span>
                      </a>
                    </li>
                  );
                })}
              </ul>
            </section>

            <section>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Run history · last 7d</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {agent.runHistory.map((r, i) => (
                  <li key={i} className="agent-runhist-row" style={{
                    display: 'grid', gridTemplateColumns: '120px 60px 1fr auto', gap: 10,
                    padding: '5px 0', fontSize: 11.5,
                    borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)',
                    color: 'var(--ink-soft)',
                  }}>
                    <span className="mono">{new Date(r.when).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}</span>
                    <span className="mono">{r.durationS}s</span>
                    <span style={{ color: r.status === 'fail' ? 'var(--status-red)' : 'var(--ink)' }}>
                      {r.status === 'ok' ? `${r.outputs} outputs` : `failed: ${r.err}`}
                    </span>
                    <span style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: r.status === 'ok' ? 'var(--status-green)' : 'var(--status-red)',
                      alignSelf: 'center',
                    }} />
                  </li>
                ))}
              </ul>
            </section>
          </div>
        </div>
      )}

      <style>{`
        @keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: .35 } }
      `}</style>
    </section>
  );
}

function TriggerCard({ trigger, agent, onClick }) {
  const isInput = trigger.kind === 'input';
  return (
    <button onClick={onClick} style={{
      cursor: 'pointer', textAlign: 'left',
      background: 'linear-gradient(135deg, rgba(248,197,48,.06) 0%, transparent 60%), var(--surface-2)',
      border: '1px solid var(--border)',
      padding: '12px 14px', display: 'flex', alignItems: 'flex-start', gap: 12,
      position: 'relative', overflow: 'hidden',
      transition: 'border-color .15s, background .15s, transform .08s',
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--gold-deep)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}
    onMouseDown={(e) => { e.currentTarget.style.transform = 'translateY(1px)'; }}
    onMouseUp={(e) => { e.currentTarget.style.transform = 'translateY(0)'; }}>

      <span style={{
        flex: 'none', width: 36, height: 36,
        background: isInput ? 'transparent' : 'var(--gold)',
        color: isInput ? 'var(--forest-900)' : 'var(--forest-900)',
        border: isInput ? '1.5px solid var(--forest-900)' : 'none',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14, fontWeight: 700,
      }}>{isInput ? '→' : '▶'}</span>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{trigger.label}</span>
          {isInput && <span style={{ fontSize: 9.5, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>· input needed</span>}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 3, lineHeight: 1.4 }}>{trigger.desc}</div>
      </div>

      <span className="mono" style={{
        position: 'absolute', top: 8, right: 10,
        fontSize: 9, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase',
      }}>{agent.initials}</span>
    </button>
  );
}

function TriggerInputForm({ agent, trigger, onSubmit, onClose }) {
  const [client, setClient] = useState('');
  const [notes, setNotes] = useState('');
  return (
    <React.Fragment>
      <header style={{ padding: '18px 20px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div className="eyebrow">{agent.name} · trigger</div>
          <h2 className="serif" style={{ margin: 0, fontSize: 22, fontWeight: 400 }}>{trigger.label}</h2>
        </div>
        <button onClick={onClose} style={{ background: 'transparent', border: 0, fontSize: 22, cursor: 'pointer', color: 'var(--ink-soft)' }}>×</button>
      </header>
      <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5 }}>{trigger.desc}</p>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span className="eyebrow">Client / prospect</span>
          <select value={client} onChange={e => setClient(e.target.value)} style={{
            padding: '10px 12px', border: '1px solid var(--border)', background: 'var(--surface-2)', fontSize: 13,
          }}>
            <option value="">Pick one…</option>
            {window.DC_DATA.CLIENTS.slice(0, 12).map(c => <option key={c.slug} value={c.slug}>{c.name}</option>)}
          </select>
        </label>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span className="eyebrow">Notes <span style={{ opacity: .55, textTransform: 'none', letterSpacing: 0 }}>· optional</span></span>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} style={{
            padding: '10px 12px', border: '1px solid var(--border)', background: 'var(--surface-2)',
            fontSize: 13, fontFamily: 'inherit', resize: 'vertical',
          }} placeholder={`E.g. "Tone: more direct, less hype" or "Lean into estimator angle"`} />
        </label>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 6 }}>
          <button className="btn-mini" onClick={onClose}>Cancel</button>
          <button className="btn-gold" onClick={onSubmit} disabled={!client} style={{ opacity: client ? 1 : .55 }}>
            Run {agent.name.split(' ')[0]} →
          </button>
        </div>
      </div>
    </React.Fragment>
  );
}

// ── Henry · /client-health ──────────────────────────────────────────────────
function ClientHealthRoute({ clients, onPickClient, onBack }) {
  const [filter, setFilter] = useState('all');
  const [sortKey, setSortKey] = useState('status');

  const sortClients = (arr) => {
    const order = { red: 0, yellow: 1, green: 2 };
    const cpb = (c) => 42 + ((c.slug.charCodeAt(0) + c.slug.length) % 60);
    if (sortKey === 'status') return [...arr].sort((a, b) => order[a.status] - order[b.status]);
    if (sortKey === 'cpb')    return [...arr].sort((a, b) => cpb(b) - cpb(a));
    if (sortKey === 'days')   return [...arr].sort((a, b) => b.daysSinceLastBooking - a.daysSinceLastBooking);
    if (sortKey === 'name')   return [...arr].sort((a, b) => a.name.localeCompare(b.name));
    return arr;
  };

  const counts = {
    red:    clients.filter(c => c.status === 'red').length,
    yellow: clients.filter(c => c.status === 'yellow').length,
    green:  clients.filter(c => c.status === 'green').length,
  };
  const visible = sortClients(filter === 'all' ? clients : clients.filter(c => c.status === filter));

  return (
    <RoutePage
      eyebrow="Portfolio"
      title="Client health"
      lastUpdated="4m ago"
      dataSource="Meta + GHL + ClickUp · joined hourly"
      onBack={onBack}
      rollupSummary={
        <span>
          <strong style={{ color: 'var(--status-red)' }}>{counts.red} RED</strong>
          <span style={{ margin: '0 8px', opacity: .4 }}>·</span>
          <strong style={{ color: '#7a5605' }}>{counts.yellow} YELLOW</strong>
          <span style={{ margin: '0 8px', opacity: .4 }}>·</span>
          <strong style={{ color: 'var(--status-green)' }}>{counts.green} GREEN</strong>
          <span style={{ margin: '0 8px', opacity: .4 }}>·</span>
          <span>3 neglected · 2 missing photos · {clients.length} active total</span>
        </span>
      }
      rollupCards={[
        { label: 'Need a Henry call', value: counts.red, sub: 'CPL or bookings critical', tone: 'red' },
        { label: 'Watch through Fri', value: counts.yellow, sub: 'Vukasi is on it', tone: 'amber' },
        { label: 'Holding the line',  value: counts.green, sub: 'Above target', tone: 'green' },
        { label: 'Avg CPB (portfolio)', value: '$58', sub: 'target $50', tone: 'amber' },
      ]}
      filters={
        <PillBar value={filter} onChange={setFilter} options={[
          { k: 'all', l: 'All', count: clients.length },
          { k: 'red', l: 'Red', count: counts.red },
          { k: 'yellow', l: 'Yellow', count: counts.yellow },
          { k: 'green', l: 'Green', count: counts.green },
        ]} />
      }
      actions={
        <select value={sortKey} onChange={(e) => setSortKey(e.target.value)} style={{
          padding: '5px 10px', border: '1px solid var(--border)', background: 'var(--surface)',
          fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-soft)',
        }}>
          <option value="status">Sort: by status</option>
          <option value="cpb">Sort: by CPB</option>
          <option value="days">Sort: days since booked</option>
          <option value="name">Sort: alphabetical</option>
        </select>
      }>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10,
      }}>
        {visible.map(c => {
          const cpb = 42 + ((c.slug.charCodeAt(0) + c.slug.length) % 60);
          return (
            <button key={c.slug} onClick={() => onPickClient(c.slug)}
                    style={{
                      textAlign: 'left', cursor: 'pointer',
                      background: 'var(--surface-2)', border: '1px solid var(--border)',
                      padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 6,
                      borderTop: `3px solid ${c.status === 'red' ? 'var(--status-red)' : c.status === 'yellow' ? 'var(--status-amber)' : 'var(--status-green)'}`,
                    }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <Monogram initials={c.initials} tone={c.tone} size={28} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{c.name}</div>
                </div>
                <span className={`pip ${c.status === 'red' ? 'red' : c.status === 'yellow' ? 'yellow' : 'green'}`} />
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink)', lineHeight: 1.3 }}>{c.drivingMetric}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 'auto', paddingTop: 4, borderTop: '1px dashed var(--border-soft)', fontSize: 10.5, color: 'var(--ink-soft)' }}>
                <span>CPB <span className="mono" style={{ color: 'var(--ink)' }}>${cpb}</span></span>
                <span>{c.daysSinceLastBooking}d since booked</span>
              </div>
            </button>
          );
        })}
      </div>
    </RoutePage>
  );
}

// ── Vukasi · /at-risk-accounts ──────────────────────────────────────────────
function AtRiskRoute({ accounts, onOpenSteps, onBack, readOnly = false }) {
  const register = window.DC_DATA.RISK_REGISTER;
  const resolved = window.DC_DATA.RISK_RESOLVED;
  const thresholds = window.DC_DATA.RISK_THRESHOLDS;
  const [tab, setTab] = useState('register');
  const [filter, setFilter] = useState('all');

  const counts = {
    flagged:  register.filter(r => r.status === 'flagged').length,
    watching: register.filter(r => r.status === 'watching').length,
    healthy:  register.filter(r => r.status === 'healthy').length,
  };
  const visible = filter === 'all' ? register : register.filter(r => r.status === filter);

  return (
    <RoutePage
      eyebrow="Risk register"
      title="At-risk accounts"
      lastUpdated="7m ago"
      dataSource="ad_monitor_risk.py · runs every 30 min"
      onBack={onBack}
      rollupSummary={
        <span>
          <strong style={{ color: 'var(--status-red)' }}>{counts.flagged} flagged</strong>
          <span style={{ margin: '0 8px', opacity: .4 }}>·</span>
          <strong style={{ color: '#7a5605' }}>{counts.watching} on watch</strong>
          <span style={{ margin: '0 8px', opacity: .4 }}>·</span>
          <span>{counts.healthy} healthy · {resolved.length} resolved this month</span>
        </span>
      }
      rollupCards={[
        { label: 'Flagged',     value: counts.flagged,  sub: 'Action needed today', tone: 'red' },
        { label: 'Watching',    value: counts.watching, sub: 'Health 31-69', tone: 'amber' },
        { label: 'Avg time-to-resolve', value: '6.3d', sub: 'last 30 days' },
        { label: 'Avg account health', value: 53, sub: 'portfolio · target >60' },
      ]}
      filters={
        <React.Fragment>
          {readOnly && <ReadOnlyBadge />}
        <div style={{ display: 'flex', border: '1px solid var(--border)' }}>
          {[
            { k: 'register', l: 'Register' },
            { k: 'resolved', l: `Resolved (${resolved.length})` },
            ...(readOnly ? [] : [{ k: 'thresholds', l: 'Thresholds' }]),
          ].map(t => (
            <button key={t.k} onClick={() => setTab(t.k)} style={{
              padding: '7px 14px', border: 0, cursor: 'pointer',
              background: tab === t.k ? 'var(--forest-700)' : 'transparent',
              color: tab === t.k ? 'var(--paper-50)' : 'var(--ink-soft)',
              fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>{t.l}</button>
          ))}
        </div>
        </React.Fragment>
      }
      actions={tab === 'register' && (
        <PillBar value={filter} onChange={setFilter} options={[
          { k: 'all', l: 'All', count: register.length },
          { k: 'flagged', l: 'Flagged', count: counts.flagged },
          { k: 'watching', l: 'Watching', count: counts.watching },
          { k: 'healthy', l: 'Healthy', count: counts.healthy },
        ]} />
      )}>

      {tab === 'register' && (
        <div className="risk-register-wrap" style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <table className="risk-register-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--paper-100)' }}>
                {['Health', 'Account', 'Status', 'Trigger', 'Since', 'CPL', 'Spend pace', ''].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 12px', fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-soft)', borderBottom: '1px solid var(--border)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map(r => {
                const flagged = r.status === 'flagged';
                const watching = r.status === 'watching';
                const acct = accounts.find(a => a.slug === r.slug);
                return (
                  <tr key={r.slug} style={{
                    borderBottom: '1px solid var(--border-soft)',
                    background: flagged ? 'rgba(154,42,42,.04)' : 'transparent',
                  }}>
                    <td style={{ padding: '10px 12px', width: 70 }}>
                      <span className="serif" style={{
                        fontSize: 20, fontWeight: 400,
                        color: flagged ? 'var(--status-red)' : watching ? '#7a5605' : 'var(--status-green)',
                      }}>{r.score}</span>
                    </td>
                    <td style={{ padding: '10px 12px', fontWeight: 600 }}>{r.name}</td>
                    <td style={{ padding: '10px 12px' }}>
                      <span className={`tag ${flagged ? 'solid-red' : watching ? 'solid-amber' : 'solid-green'}`} style={{ fontSize: 9.5 }}>
                        {r.status}
                      </span>
                    </td>
                    <td style={{ padding: '10px 12px', color: 'var(--ink)' }}>{r.trigger}</td>
                    <td style={{ padding: '10px 12px', color: 'var(--ink-soft)' }} className="mono">{r.sinceDays > 0 ? `${r.sinceDays}d` : '—'}</td>
                    <td style={{ padding: '10px 12px', color: 'var(--ink-soft)' }} className="mono">{r.cpl ? `$${r.cpl}` : '—'}</td>
                    <td style={{ padding: '10px 12px' }} className="mono">
                      <span style={{ color: r.spendPace < 80 ? 'var(--status-amber)' : r.spendPace > 110 ? 'var(--status-amber)' : 'var(--ink-soft)' }}>
                        {r.spendPace}%
                      </span>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      {acct && !readOnly && <button className="btn-mini primary" onClick={() => onOpenSteps(acct)}>Next steps →</button>}
                      {acct && readOnly && <span style={{ fontSize: 11, color: 'var(--ink-soft)' }}>Vukasi's queue</span>}
                      {!acct && r.status !== 'healthy' && <span style={{ fontSize: 11, color: 'var(--ink-soft)' }}>No actions yet</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'resolved' && (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--paper-100)' }}>
                {['Account', 'Resolved', 'Days at risk', 'What revived it'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 12px', fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-soft)', borderBottom: '1px solid var(--border)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {resolved.map(r => (
                <tr key={r.slug} style={{ borderBottom: '1px solid var(--border-soft)' }}>
                  <td style={{ padding: '10px 12px', fontWeight: 600 }}>{r.name}</td>
                  <td style={{ padding: '10px 12px', color: 'var(--ink-soft)' }} className="mono">{r.resolvedDate}</td>
                  <td style={{ padding: '10px 12px', color: 'var(--ink)' }} className="mono">{r.daysAtRisk}d</td>
                  <td style={{ padding: '10px 12px', color: 'var(--ink)' }}>{r.action}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'thresholds' && (
        <section style={{ background: 'var(--surface)', border: '1px solid var(--border)', padding: 18 }}>
          <p style={{ margin: '0 0 16px', fontSize: 13, color: 'var(--ink-soft)', maxWidth: 640, lineHeight: 1.5 }}>
            Risk scores roll up these four signals. Adjust to make the register more or less sensitive — changes apply on the next 30-min run.
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
            {Object.entries(thresholds).map(([k, t]) => (
              <div key={k} style={{ border: '1px solid var(--border)', padding: 14, background: 'var(--surface-2)' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>{t.label}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                  <span className="serif" style={{ fontSize: 32, lineHeight: 1, color: 'var(--forest-700)' }}>{t.value}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{t.unit}</span>
                </div>
                <p style={{ margin: 0, fontSize: 12, color: 'var(--ink-soft)', lineHeight: 1.4 }}>{t.desc}</p>
                <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                  <button className="btn-mini">Edit</button>
                  <button className="btn-mini">Reset</button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </RoutePage>
  );
}

// ── Vukasi · /creative-log ──────────────────────────────────────────────────
function CreativeLogRoute({ onBack, readOnly = false }) {
  const archive = window.DC_DATA.CREATIVE_ARCHIVE;
  const refreshPlan = window.DC_DATA.CREATIVE_REFRESH_PLAN;
  const [activeAccount, setActiveAccount] = useState(Object.keys(archive)[0]);
  const [bulkMode, setBulkMode] = useState(false);
  const [bulkSelection, setBulkSelection] = useState({});

  const accounts = Object.keys(archive).map(slug => ({
    slug, count: archive[slug].length,
    name: window.DC_DATA.CLIENTS.find(c => c.slug === slug)?.name || slug,
    initials: window.DC_DATA.CLIENTS.find(c => c.slug === slug)?.initials || slug.slice(0,2).toUpperCase(),
    tone: window.DC_DATA.CLIENTS.find(c => c.slug === slug)?.tone || 'forest',
  }));

  const overdueCount = refreshPlan.filter(p => p.urgency === 'overdue').length;
  const totalVariants = Object.values(archive).flat().length;

  const variants = archive[activeAccount] || [];
  const accountInfo = accounts.find(a => a.slug === activeAccount);

  const toggleBulk = (slug) => setBulkSelection(prev => ({ ...prev, [slug]: !prev[slug] }));
  const selectedCount = Object.values(bulkSelection).filter(Boolean).length;

  return (
    <RoutePage
      eyebrow="Per-account archive · refresh planning"
      title="Creative log"
      lastUpdated="9m ago"
      dataSource="Meta Ads Library + manual log"
      onBack={onBack}
      rollupSummary={
        <span>
          <strong>{totalVariants} variants</strong> across {accounts.length} accounts ·{' '}
          <strong style={{ color: 'var(--status-amber)' }}>{overdueCount} accounts</strong> overdue for refresh
        </span>
      }
      rollupCards={[
        { label: 'Overdue refresh', value: overdueCount, sub: '5 accounts > target cadence', tone: 'red' },
        { label: 'Due this week',   value: refreshPlan.filter(p => p.urgency === 'soon').length, sub: 'plan now', tone: 'amber' },
        { label: 'Variants live',   value: Object.values(archive).flat().filter(v => v.status === 'live').length, sub: 'currently in rotation' },
        { label: 'Avg hook rate',   value: '7.4%', sub: 'across live variants' },
      ]}
      actions={
        <React.Fragment>
          {readOnly && <ReadOnlyBadge />}
          {!readOnly && (
            <React.Fragment>
          <button className="btn-mini" onClick={() => { setBulkMode(!bulkMode); setBulkSelection({}); }}>
            {bulkMode ? 'Cancel bulk' : 'Bulk refresh'}
          </button>
          {bulkMode && selectedCount > 0 && (
            <button className="btn-gold">
              Generate {selectedCount} brief{selectedCount === 1 ? '' : 's'} →
            </button>
          )}
            </React.Fragment>
          )}
        </React.Fragment>
      }>

      <div className="creative-log-split" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 'var(--gap-grid)' }}>
        {/* Phone-only account dropdown */}
        <div className="creative-log-mobile-picker" style={{ display: 'none' }}>
          <label style={{ display: 'block', fontSize: 10, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 6 }}>Account</label>
          <select value={activeAccount} onChange={(e) => setActiveAccount(e.target.value)}
                  style={{
                    width: '100%', padding: '10px 12px',
                    fontSize: 14, fontFamily: 'inherit',
                    background: 'var(--surface)', color: 'var(--ink)',
                    border: '1px solid var(--border)', borderRadius: 0,
                    appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
                    backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none' stroke='%236b7068' stroke-width='1.5'><path d='M3 5l3 3 3-3'/></svg>\")",
                    backgroundRepeat: 'no-repeat',
                    backgroundPosition: 'right 12px center',
                    paddingRight: 36,
                  }}>
            {accounts.map(a => (
              <option key={a.slug} value={a.slug}>{a.name} · {a.count} variants</option>
            ))}
          </select>
        </div>

        {/* Account picker (desktop) */}
        <aside className="creative-log-aside" style={{ background: 'var(--surface)', border: '1px solid var(--border)', display: 'flex', flexDirection: 'column' }}>
          <div className="eyebrow" style={{ padding: '12px 14px 8px', borderBottom: '1px solid var(--border-soft)' }}>Accounts</div>
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {accounts.map(a => {
              const planned = refreshPlan.find(p => p.slug === a.slug);
              const overdue = planned && planned.urgency === 'overdue';
              return (
                <button key={a.slug} onClick={() => setActiveAccount(a.slug)}
                        style={{
                          width: '100%', textAlign: 'left', cursor: 'pointer',
                          padding: '10px 14px', border: 0,
                          borderLeft: activeAccount === a.slug ? '3px solid var(--gold)' : '3px solid transparent',
                          background: activeAccount === a.slug ? 'var(--paper-100)' : 'transparent',
                          display: 'flex', alignItems: 'center', gap: 10,
                          borderBottom: '1px solid var(--border-soft)',
                        }}>
                  {bulkMode && !readOnly && (
                    <input type="checkbox" checked={!!bulkSelection[a.slug]} onChange={(e) => { e.stopPropagation(); toggleBulk(a.slug); }} onClick={(e) => e.stopPropagation()} />
                  )}
                  <Monogram initials={a.initials} tone={a.tone} size={26} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.2 }}>{a.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{a.count} variants</div>
                  </div>
                  {overdue && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--status-red)', flex: 'none' }} />}
                </button>
              );
            })}
          </div>
        </aside>

        {/* Variant grid */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {accountInfo && (
            <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
              <Monogram initials={accountInfo.initials} tone={accountInfo.tone} size={36} />
              <div style={{ flex: 1 }}>
                <div className="serif" style={{ fontSize: 22, lineHeight: 1.05 }}>{accountInfo.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 2 }}>
                  {variants.length} variants archived · {variants.filter(v => v.status === 'live').length} live · next refresh due in{' '}
                  {(refreshPlan.find(p => p.slug === activeAccount)?.dueIn ?? '—') + 'd'}
                </div>
              </div>
              {!readOnly && <button className="btn-gold">New variant brief →</button>}
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 10 }}>
            {variants.map(v => <VariantCard key={v.id} variant={v} />)}
          </div>
        </div>
      </div>
    </RoutePage>
  );
}

function VariantCard({ variant }) {
  const v = variant;
  const formatColors = {
    video:    ['#1B4332', '#2D6A4F'],
    image:    ['#7A5605', '#D6A317'],
    carousel: ['#0E2A1F', '#40916C'],
  };
  const [c1, c2] = formatColors[v.format] || formatColors.image;
  const statusColor = v.status === 'live' ? 'var(--status-green)' : v.status === 'paused' ? 'var(--status-red)' : 'var(--ink-soft)';
  const statusBg    = v.status === 'live' ? 'var(--status-green-soft)' : v.status === 'paused' ? 'var(--status-red-soft)' : 'var(--paper-100)';

  return (
    <article style={{
      background: 'var(--surface-2)', border: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Thumbnail tile */}
      <div style={{
        height: 120, background: `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)`,
        display: 'flex', alignItems: 'flex-end', padding: 12, position: 'relative',
        color: 'var(--paper-50)',
      }}>
        <span style={{
          position: 'absolute', top: 10, right: 10,
          fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase',
          background: 'rgba(255,255,255,.18)', color: 'var(--paper-50)',
          padding: '3px 7px', fontWeight: 700, backdropFilter: 'blur(4px)',
        }}>{v.format}</span>
        <span style={{
          position: 'absolute', top: 10, left: 10,
          width: 28, height: 28, border: '1.5px solid rgba(255,255,255,.5)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12,
        }}>
          {v.format === 'video' ? '▶' : v.format === 'carousel' ? '▦' : '◰'}
        </span>
        <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.3, textShadow: '0 1px 2px rgba(0,0,0,.25)' }}>
          {v.name}
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{v.shipped} · {v.age}d ago</span>
          <span style={{
            fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
            color: statusColor, background: statusBg, padding: '2px 7px',
          }}>{v.status}</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--border-soft)' }}>
          {[
            { l: 'Hook', v: `${v.hookRate.toFixed(1)}%`, good: v.hookRate >= 7 },
            { l: 'CPL',  v: v.cpl ? `$${v.cpl}` : '—',    good: v.cpl != null && v.cpl <= 50 },
            { l: 'CTR',  v: `${v.ctr.toFixed(1)}%`,        good: v.ctr >= 2.0 },
          ].map((m, i) => (
            <div key={i} style={{ padding: '6px 8px', borderRight: i < 2 ? '1px solid var(--border-soft)' : 'none' }}>
              <div style={{ fontSize: 9, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{m.l}</div>
              <div className="mono" style={{ fontSize: 12, fontWeight: 600, color: m.good ? 'var(--status-green)' : 'var(--ink)' }}>{m.v}</div>
            </div>
          ))}
        </div>
      </div>
    </article>
  );
}

// Use the existing Modal from window.DC, keep handle local
const { Modal } = window.DC;

window.DC = Object.assign(window.DC || {}, {
  AgentsRoute, ClientHealthRoute, AtRiskRoute, CreativeLogRoute,
});
