// Routes batch 2: /blockers, /goals, /transcripts, /tasks, /wins

const { Monogram, Sparkline, Empty, ExtArrow, RoutePage, PillBar, ReadOnlyBadge } = window.DC;

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

// ── Henry · /blockers ───────────────────────────────────────────────────────
function BlockersRoute({ blockers, setBlockers, onBack }) {
  const history = window.DC_DATA.BLOCKER_HISTORY;
  const [tab, setTab] = useState('active');
  const [filter, setFilter] = useState('all');

  const aged = blockers.filter(b => b.ageDays > 5);
  const counts = {
    me: blockers.filter(b => b.owner === 'me').length,
    team: blockers.filter(b => b.owner === 'team').length,
    client: blockers.filter(b => b.owner === 'client').length,
    external: blockers.filter(b => b.owner === 'external').length,
  };
  const visible = filter === 'all' ? blockers
    : filter === 'aged' ? aged
    : blockers.filter(b => b.owner === filter);

  return (
    <RoutePage
      eyebrow="Workflow" title="Blockers"
      lastUpdated="just now" dataSource="ClickUp · sync every 60s"
      onBack={onBack}
      rollupCards={[
        { label: 'Active total', value: blockers.length, sub: 'across 4 owner buckets' },
        { label: 'Aged > 5d',    value: aged.length, sub: 'auto-flagged', tone: aged.length ? 'red' : null },
        { label: 'On Henry',     value: counts.me, sub: 'awaiting your call', tone: counts.me ? 'amber' : null },
        { label: 'External',     value: counts.external, sub: 'vendors / 3rd party' },
      ]}
      filters={
        <div style={{ display: 'flex', border: '1px solid var(--border)' }}>
          {[{k:'active',l:`Active (${blockers.length})`},{k:'history',l:`Resolved (${history.length})`}].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>
      }
      actions={tab === 'active' && (
        <PillBar value={filter} onChange={setFilter} options={[
          { k: 'all', l: 'All', count: blockers.length },
          { k: 'aged', l: 'Aged', count: aged.length },
          { k: 'me', l: 'Me', count: counts.me },
          { k: 'team', l: 'Team', count: counts.team },
          { k: 'client', l: 'Client', count: counts.client },
          { k: 'external', l: 'External', count: counts.external },
        ]} />
      )}>
      {tab === 'active' ? (
        <div className="blockers-table-wrap" style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <table className="blockers-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--paper-100)' }}>
                {['', 'Title', 'Owner', 'Client', 'Age', ''].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(b => {
                const isAged = b.ageDays > 5;
                return (
                  <tr key={b.id} className="blockers-row" style={{ borderBottom: '1px solid var(--border-soft)', background: isAged ? 'rgba(154,42,42,.04)' : 'transparent' }}>
                    <td className="blk-cell-rail" style={{ padding: '10px 12px', width: 12, borderLeft: isAged ? '3px solid var(--status-red)' : '3px solid transparent' }}></td>
                    <td className="blk-cell-title" style={{ padding: '10px 12px', fontWeight: 500 }}>{b.title}</td>
                    <td className="blk-cell-owner" style={{ padding: '10px 12px', color: 'var(--ink-soft)' }}>
                      <span className="tag" style={{ fontSize: 9.5, marginRight: 6 }}>{b.owner}</span>
                      {b.ownerName}
                    </td>
                    <td className="blk-cell-client" style={{ padding: '10px 12px', color: 'var(--ink-soft)' }}>{b.client || '—'}</td>
                    <td className="blk-cell-age mono" style={{ padding: '10px 12px' }}>
                      <span style={{ color: isAged ? 'var(--status-red)' : 'var(--ink-soft)', fontWeight: isAged ? 700 : 400 }}>
                        {isAged && '⚑ '}{b.ageDays}d
                      </span>
                    </td>
                    <td className="blk-cell-arrow" style={{ padding: '10px 12px' }}><a href={b.clickupUrl} target="_blank" rel="noreferrer"><ExtArrow /></a></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : (
        <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)' }}>
                {['Title', 'Owner', 'Resolved', 'Days open'].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>
              {history.map(h => (
                <tr key={h.id} style={{ borderBottom: '1px solid var(--border-soft)' }}>
                  <td style={{ padding: '10px 12px' }}>{h.title}</td>
                  <td style={{ padding: '10px 12px', color: 'var(--ink-soft)' }}>
                    <span className="tag" style={{ fontSize: 9.5, marginRight: 6 }}>{h.owner}</span>{h.ownerName}
                  </td>
                  <td style={{ padding: '10px 12px', color: 'var(--ink-soft)' }} className="mono">{h.resolvedDate}</td>
                  <td style={{ padding: '10px 12px' }} className="mono">{h.daysOpen}d</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </RoutePage>
  );
}

// ── Henry · /goals ──────────────────────────────────────────────────────────
function GoalsRoute({ goals, onBack }) {
  const detail = window.DC_DATA.GOAL_DETAIL;
  const goalEntries = Object.entries(goals);
  return (
    <RoutePage
      eyebrow="Q2 plan" title="Goals"
      lastUpdated="2h ago" dataSource="GHL pipeline + ClickUp"
      onBack={onBack}
      rollupSummary={<span><strong>{goalEntries.length} goals</strong> tracked this quarter · weekly review every Friday</span>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap-grid)' }}>
        {goalEntries.map(([k, g]) => {
          const d = detail[k];
          const pct = Math.min(100, Math.round((g.current / g.target) * 100));
          const fmt = (v) => `${g.prefix || ''}${v.toLocaleString()}${g.suffix || ''}`;
          const fillColor = pct >= 90 ? 'var(--status-green)' : pct >= 60 ? 'var(--gold-deep)' : 'var(--status-amber)';
          return (
            <section key={k} style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
              <div style={{ padding: 18, borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'flex-end', gap: 18, flexWrap: 'wrap' }}>
                <div style={{ flex: 1, minWidth: 240 }}>
                  <div className="eyebrow">{g.label}</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
                    <span className="serif" style={{ fontSize: 38, lineHeight: 1, fontWeight: 400 }}>{fmt(g.current)}</span>
                    <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>/ {fmt(g.target)}</span>
                    <span style={{ fontSize: 13, color: fillColor, fontWeight: 600 }}>{pct}%</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--paper-100)', marginTop: 10, position: 'relative' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: fillColor }} />
                  </div>
                </div>
                {d && d.trajectory && (
                  <div style={{ minWidth: 200 }}>
                    <div className="eyebrow" style={{ marginBottom: 6 }}>Trajectory · last 7 weeks</div>
                    <Sparkline series={d.trajectory} width={200} height={48} color="var(--forest-700)" />
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 4 }} className="mono">
                      <span>{fmt(d.trajectory[0])}</span>
                      <span>{fmt(d.trajectory[d.trajectory.length - 1])}</span>
                    </div>
                  </div>
                )}
              </div>
              {d && d.contributing && (
                <div style={{ padding: 18 }}>
                  <div className="eyebrow" style={{ marginBottom: 8 }}>Contributing actions</div>
                  <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                    {d.contributing.map((c, i) => {
                      const color = c.status === 'won' ? 'var(--status-green)' : c.status === 'risk' ? 'var(--status-red)' : 'var(--gold-deep)';
                      return (
                        <li key={i} className="goal-action-row" style={{
                          display: 'grid', gridTemplateColumns: '90px 90px 1fr auto', gap: 12,
                          padding: '8px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)', fontSize: 13,
                        }}>
                          <span className="goal-act-date mono" style={{ color: 'var(--ink-soft)', fontSize: 11 }}>{c.date}</span>
                          <span className="goal-act-status" style={{
                            fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
                            color, alignSelf: 'center',
                          }}>● {c.status}</span>
                          <span className="goal-act-text">{c.text}</span>
                          <span className="goal-act-owner" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{c.owner}</span>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              )}
            </section>
          );
        })}
      </div>
    </RoutePage>
  );
}

// ── Henry · /transcripts ────────────────────────────────────────────────────
function TranscriptsRoute({ onBack }) {
  const archive = window.DC_DATA.TRANSCRIPT_ARCHIVE;
  const [filter, setFilter] = useState('all');
  const [theme, setTheme] = useState('all');
  const [q, setQ] = useState('');
  const themes = Array.from(new Set(archive.map(t => t.theme)));
  const counts = {
    pending: archive.filter(t => t.status === 'pending').length,
    approved: archive.filter(t => t.status === 'approved').length,
    dismissed: archive.filter(t => t.status === 'dismissed').length,
  };
  const visible = archive.filter(t => {
    if (filter !== 'all' && t.status !== filter) return false;
    if (theme !== 'all' && t.theme !== theme) return false;
    if (q && !`${t.call} ${t.client} ${t.summary}`.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });
  return (
    <RoutePage
      eyebrow="From calls" title="Transcript recommendations"
      lastUpdated="14m ago" dataSource="Cole agent · per-call"
      onBack={onBack}
      rollupCards={[
        { label: 'Awaiting review', value: counts.pending, sub: 'click into one to act', tone: counts.pending ? 'amber' : null },
        { label: 'Approved (30d)',  value: counts.approved, sub: 'shipped or in flight', tone: 'green' },
        { label: 'Dismissed (30d)', value: counts.dismissed, sub: 'with rationale logged' },
        { label: 'Themes tracked',  value: themes.length, sub: 'auto-grouped by Cole' },
      ]}
      filters={
        <PillBar value={filter} onChange={setFilter} options={[
          { k: 'all', l: 'All', count: archive.length },
          { k: 'pending', l: 'Pending', count: counts.pending },
          { k: 'approved', l: 'Approved', count: counts.approved },
          { k: 'dismissed', l: 'Dismissed', count: counts.dismissed },
        ]} />
      }
      actions={
        <React.Fragment>
          <select value={theme} onChange={e => setTheme(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="all">All themes</option>
            {themes.map(t => <option key={t} value={t}>{t}</option>)}
          </select>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search…" style={{
            padding: '6px 10px', border: '1px solid var(--border)', background: 'var(--surface)',
            fontSize: 12, fontFamily: 'inherit', minWidth: 180,
          }} />
        </React.Fragment>
      }>
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
        <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
          {visible.map((t, i) => {
            const statusColor = t.status === 'approved' ? 'var(--status-green)' : t.status === 'dismissed' ? 'var(--ink-soft)' : 'var(--gold-deep)';
            return (
              <li key={t.id} style={{ padding: '14px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 4 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <span style={{ fontSize: 13, fontWeight: 600 }}>{t.call}</span>
                    <span className="tag" style={{ fontSize: 9.5 }}>{t.theme}</span>
                  </div>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{t.date} · {t.who}</span>
                </div>
                <p style={{ margin: '4px 0 8px', fontSize: 13.5, lineHeight: 1.45 }}>{t.summary}</p>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 11 }}>
                  <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: statusColor }}>● {t.status}</span>
                  <span style={{ color: 'var(--ink-soft)' }}>·</span>
                  <span style={{ color: 'var(--ink-soft)' }}>{t.client}</span>
                </div>
              </li>
            );
          })}
          {visible.length === 0 && <li style={{ padding: 24 }}><Empty title="No matches" hint="Try clearing filters or the search." /></li>}
        </ul>
      </div>
    </RoutePage>
  );
}

// ── Vukasi · /tasks ─────────────────────────────────────────────────────────
function TasksRoute({ onBack }) {
  const tasks = window.DC_DATA.TASK_ARCHIVE;
  const [view, setViewMode] = useState('list');
  const [filter, setFilter] = useState('all');
  const counts = {
    overdue: tasks.filter(t => t.status === 'overdue').length,
    today: tasks.filter(t => t.status === 'today').length,
    this_week: tasks.filter(t => t.status === 'this_week').length,
  };
  const visible = filter === 'all' ? tasks : tasks.filter(t => t.status === filter);
  const totalH = visible.reduce((s, t) => s + t.estimateH, 0);

  const renderRow = (t, i, last) => {
    const color = t.status === 'overdue' ? 'var(--status-red)' : t.status === 'today' ? 'var(--status-amber)' : 'var(--ink-soft)';
    const pri = t.priority === 'high' ? 'var(--status-red)' : t.priority === 'med' ? 'var(--gold-deep)' : 'var(--ink-soft)';
    return (
      <a key={t.id} className="tasks-row" href={t.clickupUrl} target="_blank" rel="noreferrer" style={{
        display: 'grid', gridTemplateColumns: '110px 1fr 110px 90px 60px 24px',
        gap: 12, alignItems: 'center', padding: '10px 12px',
        borderBottom: last ? 'none' : '1px solid var(--border-soft)', color: 'inherit', fontSize: 13,
      }}>
        <span className="tasks-cell-status mono" style={{ color, fontSize: 11, textTransform: 'uppercase', fontWeight: 600 }}>{t.status.replace('_',' ')}</span>
        <span className="tasks-cell-title" style={{ fontWeight: 500 }}>{t.title}</span>
        <span className="tasks-cell-client" style={{ color: 'var(--ink-soft)', fontSize: 12 }}>{t.client}</span>
        <span className="tasks-cell-due mono" style={{ fontSize: 11, color }}>{t.dueDate}</span>
        <span className="tasks-cell-pri" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: pri }}>● {t.priority}</span>
        <span className="tasks-cell-arrow"><ExtArrow /></span>
      </a>
    );
  };

  return (
    <RoutePage
      eyebrow="ClickUp · assigned to me" title="My tasks"
      lastUpdated="3m ago" dataSource="ClickUp API"
      onBack={onBack}
      rollupCards={[
        { label: 'Overdue',   value: counts.overdue,   sub: 'fix today', tone: counts.overdue ? 'red' : null },
        { label: 'Due today', value: counts.today,     sub: 'on the runway', tone: counts.today ? 'amber' : null },
        { label: 'This week', value: counts.this_week, sub: 'next 7 days' },
        { label: 'Total est.', value: `${totalH}h`,     sub: `for ${visible.length} task${visible.length===1?'':'s'}` },
      ]}
      filters={
        <div style={{ display: 'flex', border: '1px solid var(--border)' }}>
          {[{k:'list',l:'List'},{k:'board',l:'Board'}].map(t => (
            <button key={t.k} onClick={() => setViewMode(t.k)} style={{
              padding: '7px 14px', border: 0, cursor: 'pointer',
              background: view === t.k ? 'var(--forest-700)' : 'transparent',
              color: view === t.k ? 'var(--paper-50)' : 'var(--ink-soft)',
              fontSize: 10.5, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>{t.l}</button>
          ))}
        </div>
      }
      actions={
        <PillBar value={filter} onChange={setFilter} options={[
          { k: 'all', l: 'All', count: tasks.length },
          { k: 'overdue', l: 'Overdue', count: counts.overdue },
          { k: 'today', l: 'Today', count: counts.today },
          { k: 'this_week', l: 'Week', count: counts.this_week },
        ]} />
      }>

      {view === 'list' ? (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <div className="tasks-list-head" style={{ display: 'grid', gridTemplateColumns: '110px 1fr 110px 90px 60px 24px', gap: 12, padding: '10px 12px', background: 'var(--paper-100)', fontSize: 10.5, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, borderBottom: '1px solid var(--border)' }}>
            <span>Status</span><span>Task</span><span>Client</span><span>Due</span><span>Priority</span><span></span>
          </div>
          {visible.map((t, i) => renderRow(t, i, i === visible.length - 1))}
          {visible.length === 0 && <div style={{ padding: 24 }}><Empty title="Inbox zero" /></div>}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--gap-grid)' }}>
          {[
            { k: 'overdue', l: 'Overdue', color: 'var(--status-red)' },
            { k: 'today', l: 'Due today', color: 'var(--status-amber)' },
            { k: 'this_week', l: 'This week', color: 'var(--ink-soft)' },
          ].map(col => {
            const items = tasks.filter(t => t.status === col.k);
            return (
              <div key={col.k} style={{ background: 'var(--surface)', border: '1px solid var(--border)', padding: 12 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
                  <span className="eyebrow" style={{ color: col.color }}>{col.l}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{items.length}</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {items.map(t => {
                    const pri = t.priority === 'high' ? 'var(--status-red)' : t.priority === 'med' ? 'var(--gold-deep)' : 'var(--ink-soft)';
                    return (
                      <a key={t.id} href={t.clickupUrl} target="_blank" rel="noreferrer" style={{
                        background: 'var(--surface-2)', border: '1px solid var(--border)',
                        padding: 10, fontSize: 12.5, color: 'inherit',
                        borderLeft: `3px solid ${pri}`, display: 'block',
                      }}>
                        <div style={{ fontWeight: 500, lineHeight: 1.3 }}>{t.title}</div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10.5, color: 'var(--ink-soft)' }}>
                          <span>{t.client}</span>
                          <span className="mono">{t.dueDate} · {t.estimateH}h</span>
                        </div>
                      </a>
                    );
                  })}
                  {items.length === 0 && <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', fontStyle: 'italic', padding: 8 }}>Empty.</div>}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </RoutePage>
  );
}

// ── Vukasi · /wins ──────────────────────────────────────────────────────────
function WinsRoute({ onBack, readOnly = false }) {
  const wins = window.DC_DATA.WIN_ARCHIVE;
  const patterns = window.DC_DATA.WIN_PATTERNS;
  const [tab, setTab] = useState('archive');
  const drafted = wins.filter(w => w.testimonialDrafted).length;
  const shareable = wins.filter(w => w.shareable).length;

  return (
    <RoutePage
      eyebrow="Account performance" title="Account wins"
      lastUpdated="22m ago" dataSource="ad_monitor_wins.py · weekly"
      onBack={onBack}
      rollupCards={[
        { label: 'Wins (30d)',          value: wins.length, sub: `${shareable} shareable`, tone: 'green' },
        { label: 'Testimonials drafted', value: drafted, sub: 'ready to send · Sal queue' },
        { label: 'Patterns extracted',  value: patterns.length, sub: 'reusable across portfolio' },
        { label: 'Avg lift',             value: '-29%', sub: 'CPL across CPL wins' },
      ]}
      filters={
        <React.Fragment>
          {readOnly && <ReadOnlyBadge />}
        <div style={{ display: 'flex', border: '1px solid var(--border)' }}>
          {[{k:'archive',l:'Trophy case'},{k:'patterns',l:'Patterns'}].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>
      }>
      {tab === 'archive' ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 'var(--gap-grid)' }}>
          {wins.map(w => (
            <article key={w.id} style={{
              background: 'var(--status-green-soft)', border: '1px solid transparent',
              borderTop: '3px solid var(--status-green)',
              padding: 16, display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{w.client}</span>
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{w.date}</span>
              </div>
              <div>
                <div style={{ fontSize: 10, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{w.metric}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 2 }}>
                  <span className="serif" style={{ fontSize: 32, lineHeight: 1, color: 'var(--status-green)' }}>{w.value}</span>
                  <span style={{ fontSize: 11, color: 'var(--status-green)', fontWeight: 600 }}>{w.vsTarget}</span>
                </div>
              </div>
              <div style={{ borderTop: '1px solid rgba(45,106,79,.2)', paddingTop: 8 }}>
                <div className="eyebrow" style={{ marginBottom: 4, opacity: .7 }}>What worked</div>
                <p style={{ margin: 0, fontSize: 12, lineHeight: 1.4 }}>{w.playbook}</p>
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 'auto', flexWrap: 'wrap' }}>
                {w.testimonialDrafted ? (
                  <span className="tag solid-green" style={{ fontSize: 9.5 }}>● Testimonial drafted</span>
                ) : (
                  <button className="btn-mini">Draft testimonial</button>
                )}
                {w.shareable && <button className="btn-mini">Share to Sal →</button>}
              </div>
            </article>
          ))}
        </div>
      ) : (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <p style={{ margin: 0, padding: '14px 18px', fontSize: 12.5, color: 'var(--ink-soft)', borderBottom: '1px solid var(--border-soft)', lineHeight: 1.5 }}>
            Patterns Cole extracted from the wins archive. Each one is a candidate to roll into more accounts.
          </p>
          <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
            {patterns.map((p, i) => (
              <li key={i} className="win-pattern-row" style={{
                padding: '14px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)',
                display: 'grid', gridTemplateColumns: '1fr 100px 1fr auto', gap: 16, alignItems: 'center',
              }}>
                <span className="win-pat-name" style={{ fontSize: 14, fontWeight: 500 }}>{p.pattern}</span>
                <span className="win-pat-count mono" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{p.winsCount} wins</span>
                <span className="win-pat-lift" style={{ fontSize: 12, color: 'var(--status-green)', fontWeight: 600 }}>{p.lift}</span>
                {!readOnly && <button className="btn-mini">Apply to more →</button>}
              </li>
            ))}
          </ul>
        </div>
      )}
    </RoutePage>
  );
}

// ── Vukasi · /neglected ─────────────────────────────────────────────────────
const SOURCE_META = {
  meta:    { l: 'Meta Ads', color: 'var(--gold-deep)' },
  ghl:     { l: 'GHL',      color: 'var(--forest-700)' },
  clickup: { l: 'ClickUp',  color: 'var(--ink-soft)' },
  call:    { l: 'Call',     color: 'var(--status-green)' },
  note:    { l: 'Note',     color: 'var(--status-amber)' },
};

function NeglectedRoute({ accounts, onPickClient, onBack, readOnly = false }) {
  const detail = window.DC_DATA.NEGLECTED_DETAIL;
  const rules  = window.DC_DATA.NEGLECT_RULES;
  const [tab, setTab] = useState('list');
  const [selected, setSelected] = useState({});
  const [filter, setFilter] = useState('all');
  const { push } = window.DC.useToast ? window.DC.useToast() : { push: () => {} };

  const sorted = [...accounts].sort((a, b) => b.daysNeglected - a.daysNeglected);
  const counts = {
    breach: sorted.filter(r => r.daysNeglected > 18).length,
    warn:   sorted.filter(r => r.daysNeglected > 14 && r.daysNeglected <= 18).length,
    quiet:  sorted.filter(r => r.daysNeglected <= 14).length,
  };
  const visible = filter === 'all' ? sorted
    : filter === 'breach' ? sorted.filter(r => r.daysNeglected > 18)
    : filter === 'warn'   ? sorted.filter(r => r.daysNeglected > 14 && r.daysNeglected <= 18)
    : sorted;
  const selectedCount = Object.values(selected).filter(Boolean).length;
  const toggleAll = () => {
    if (selectedCount === visible.length) setSelected({});
    else { const m = {}; visible.forEach(r => m[r.slug] = true); setSelected(m); }
  };

  return (
    <RoutePage
      eyebrow="Activity gaps" title="Neglected accounts"
      lastUpdated="11m ago" dataSource="ad_monitor_neglect.py · multi-source"
      onBack={onBack}
      rollupCards={[
        { label: 'Breach > 18d',  value: counts.breach, sub: 'auto-flagged red',   tone: counts.breach ? 'red' : null },
        { label: 'Warn 14-18d',   value: counts.warn,   sub: 'one cadence missed', tone: counts.warn ? 'amber' : null },
        { label: 'Total quiet',   value: sorted.length, sub: 'all accounts > 14d' },
        { label: 'Selected',      value: selectedCount, sub: selectedCount ? 'ready for bulk action' : 'pick rows to bulk-act' },
      ]}
      filters={
        <React.Fragment>
          {readOnly && <ReadOnlyBadge />}
        <div style={{ display: 'flex', border: '1px solid var(--border)' }}>
          {[{k:'list',l:`Register (${sorted.length})`},...(readOnly?[]:[{k:'rules',l:'Rules'}])].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 === 'list' && !readOnly && (
        <React.Fragment>
          <PillBar value={filter} onChange={setFilter} options={[
            { k: 'all', l: 'All', count: sorted.length },
            { k: 'breach', l: 'Breach', count: counts.breach },
            { k: 'warn', l: 'Warn', count: counts.warn },
          ]} />
          {selectedCount > 0 && (
            <button className="btn-mini primary" onClick={() => {
              push({ tone: 'success', initials: 'V', title: `Drafted check-in for ${selectedCount} account${selectedCount===1?'':'s'}`, body: 'Sent to Sal queue · review before sending.' });
              setSelected({});
            }}>Draft outreach ({selectedCount}) →</button>
          )}
        </React.Fragment>
      )}>

      {tab === 'list' ? (
        <div className="neglect-split" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 'var(--gap-grid)', alignItems: 'start' }}>
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
            <div className="neglect-row neglect-head" style={{ display: 'grid', gridTemplateColumns: '32px 1fr 80px 90px 24px', gap: 10, padding: '10px 12px', background: 'var(--paper-100)', borderBottom: '1px solid var(--border)', fontSize: 10.5, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, alignItems: 'center' }}>
              {!readOnly ? <input type="checkbox" checked={selectedCount === visible.length && visible.length > 0} onChange={toggleAll} /> : <span />}
              <span>Account</span><span>Days</span><span>Last</span><span></span>
            </div>
            {visible.map(r => {
              const tone = r.daysNeglected > 18 ? 'var(--status-red)' : r.daysNeglected > 14 ? 'var(--status-amber)' : 'var(--ink)';
              const bg   = r.daysNeglected > 18 ? 'rgba(154,42,42,.04)' : 'transparent';
              return (
                <div key={r.slug} className="neglect-row" style={{
                  display: 'grid', gridTemplateColumns: '32px 1fr 80px 90px 24px', gap: 10,
                  padding: '10px 12px', borderBottom: '1px solid var(--border-soft)',
                  fontSize: 13, alignItems: 'center', background: bg, cursor: 'pointer',
                  borderLeft: r.daysNeglected > 18 ? '3px solid var(--status-red)' : '3px solid transparent',
                }} onClick={() => onPickClient && onPickClient(r.slug)}>
                  {!readOnly ? <input type="checkbox" checked={!!selected[r.slug]} onClick={e => e.stopPropagation()}
                         onChange={e => setSelected(s => ({ ...s, [r.slug]: e.target.checked }))} /> : <span />}
                  <div>
                    <div style={{ fontWeight: 500 }}>{r.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{r.lastActivity}</div>
                  </div>
                  <span style={{ color: tone, fontWeight: 600 }} className="neglect-cell-days mono">{r.daysNeglected}d</span>
                  <span className="neglect-cell-date mono" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{r.lastActivityDate}</span>
                  <ExtArrow />
                </div>
              );
            })}
            {visible.length === 0 && <div style={{ padding: 24 }}><Empty title="Nothing flagged" hint="All accounts have recent activity." /></div>}
          </div>

          <aside style={{ background: 'var(--surface)', border: '1px solid var(--border)', padding: 'var(--pad-card)' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Multi-source activity feed</div>
            <p style={{ margin: '0 0 12px', fontSize: 12.5, color: 'var(--ink-soft)', lineHeight: 1.5 }}>
              Click an account on the left to see its last 90d of touches across Meta, GHL, ClickUp, and call notes.
            </p>
            {(() => {
              const first = visible[0];
              const d = first && detail[first.slug];
              if (!first || !d) return <Empty title="Pick an account" hint="Timeline appears here." />;
              return (
                <React.Fragment>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10, paddingBottom: 10, borderBottom: '1px solid var(--border-soft)' }}>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{first.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-soft)' }}>${d.mrr.toLocaleString()} MRR · {d.owner} · {d.cadence}</div>
                    </div>
                    <span className="tag" style={{ fontSize: 9.5 }}>Cadence {d.cadenceDaysExpected}d</span>
                  </div>
                  <ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 0 }}>
                    {d.timeline.map((t, i) => {
                      const s = SOURCE_META[t.source] || SOURCE_META.note;
                      return (
                        <li key={i} style={{ display: 'grid', gridTemplateColumns: '70px 60px 1fr', gap: 10, padding: '10px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)', alignItems: 'baseline' }}>
                          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{t.date}</span>
                          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: s.color }}>● {s.l}</span>
                          <span style={{ fontSize: 12.5 }}>{t.text}</span>
                        </li>
                      );
                    })}
                  </ol>
                </React.Fragment>
              );
            })()}
          </aside>
        </div>
      ) : (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>
          <p style={{ margin: 0, padding: '14px 18px', fontSize: 12.5, color: 'var(--ink-soft)', borderBottom: '1px solid var(--border-soft)', lineHeight: 1.5 }}>
            Tunable thresholds for the neglect monitor. Each one feeds the auto-flag logic on the register tab.
          </p>
          <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
            {rules.map((r, i) => (
              <li key={r.k} style={{ padding: '14px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)', display: 'grid', gridTemplateColumns: '160px 140px 1fr auto', gap: 16, alignItems: 'center' }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{r.l}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--gold-deep)' }}>{r.current}</span>
                <span style={{ fontSize: 12.5, color: 'var(--ink-soft)', lineHeight: 1.4 }}>{r.desc}</span>
                <button className="btn-mini">Edit</button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </RoutePage>
  );
}

window.DC = Object.assign(window.DC || {}, {
  BlockersRoute, GoalsRoute, TranscriptsRoute, TasksRoute, WinsRoute, NeglectedRoute,
});
