// Vukasi's widgets: At-Risk Accounts, Neglected Accounts, My Tasks,
// Creative Log Gaps, Account Wins, plus the Next-Steps modal body.

const { Monogram, WidgetCard, Sparkline, Empty, ExtArrow } = window.DC;

// ── At-Risk Accounts ────────────────────────────────────────────────────────
function AtRiskAccounts({ accounts, onOpenSteps }) {
  if (!accounts || accounts.length === 0) {
    return (
      <WidgetCard eyebrow="Attention required" title="At-risk accounts">
        <Empty icon="✓" title="No accounts at risk" hint="All ad accounts trending on or above target." />
      </WidgetCard>
    );
  }
  const trendIsBad = (s) => s[s.length-1] > s[0]; // CPL going up = bad. We assume series is the "bad" metric
  return (
    <WidgetCard eyebrow="Attention required" title="At-risk accounts"
      action={<span className="tag solid-red">{accounts.length} flagged</span>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 10 }}>
        {accounts.map(a => {
          const bad = trendIsBad(a.metricSeries);
          return (
            <article key={a.slug} style={{
              background: 'var(--surface-2)', border: '1px solid var(--border)',
              borderTop: '3px solid var(--status-red)',
              padding: 14, display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{a.name}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 2, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                    {a.metricName}
                  </div>
                </div>
                <span className="pip red" />
              </div>
              <p style={{ margin: 0, fontSize: 13, lineHeight: 1.45, color: 'var(--ink)' }}>{a.issue}</p>
              <div style={{ background: 'var(--paper-100)', padding: '6px 8px' }}>
                <Sparkline series={a.metricSeries} width={240} height={42}
                           color={bad ? 'var(--status-red)' : 'var(--status-green)'} />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--ink-soft)', marginTop: 4 }}>
                  <span className="mono">{a.metricSeries[0]} → {a.metricSeries[a.metricSeries.length-1]}</span>
                  <span className="mono">lo {Math.min(...a.metricSeries)} · hi {Math.max(...a.metricSeries)}</span>
                </div>
              </div>
              <button className="btn-gold" onClick={() => onOpenSteps(a)}>
                Next steps →
              </button>
            </article>
          );
        })}
      </div>
    </WidgetCard>
  );
}

// ── Next Steps Modal ────────────────────────────────────────────────────────
function NextStepsModal({ account, onClose }) {
  const [checked, setChecked] = useState({});
  if (!account) return null;
  const toggle = (id) => setChecked(c => ({ ...c, [id]: !c[id] }));
  return (
    <React.Fragment>
      <header style={{ padding: '18px 20px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div className="eyebrow">Recommended actions</div>
          <h2 className="serif" style={{ margin: 0, fontSize: 24, lineHeight: 1.05, fontWeight: 400 }}>{account.name}</h2>
        </div>
        <button onClick={onClose} aria-label="Close" style={{
          background: 'transparent', border: 0, fontSize: 22, cursor: 'pointer', color: 'var(--ink-soft)', padding: '0 4px',
        }}>×</button>
      </header>
      <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 22 }}>
        {/* The recs */}
        <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {account.nextSteps.map(s => (
            <li key={s.id} style={{
              display: 'flex', alignItems: 'flex-start', gap: 12, padding: 12,
              border: '1px solid var(--border)',
              background: checked[s.id] ? 'var(--status-green-soft)' : 'var(--surface)',
              transition: 'background .15s',
            }}>
              <button onClick={() => toggle(s.id)}
                      aria-label={checked[s.id] ? 'Uncheck' : 'Check'}
                      style={{
                        width: 22, height: 22, flex: 'none',
                        border: '1.5px solid currentColor', background: checked[s.id] ? 'var(--forest-700)' : 'transparent',
                        color: checked[s.id] ? 'var(--paper-50)' : 'var(--ink-soft)',
                        cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        marginTop: 1,
                      }}>
                {checked[s.id] && (
                  <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 6L5 9L10 3" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                )}
              </button>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 4 }}>
                  Action 0{s.priority}
                </div>
                <div style={{ fontSize: 13.5, lineHeight: 1.4, textDecoration: checked[s.id] ? 'line-through' : 'none' }}>{s.text}</div>
              </div>
            </li>
          ))}
        </ol>

        {/* Evidence */}
        <section>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Why · the data</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(110px, 1fr))', gap: 6, marginBottom: 12 }}>
            {account.evidence.metrics.map(m => (
              <div key={m.k} style={{ background: 'var(--paper-100)', padding: 8 }}>
                <div style={{ fontSize: 10, color: 'var(--ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{m.k}</div>
                <div className="serif" style={{ fontSize: 18, lineHeight: 1.05, marginTop: 2 }}>{m.v}</div>
                <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 2 }}>{m.delta}</div>
              </div>
            ))}
          </div>

          {account.evidence.recentCreatives && account.evidence.recentCreatives.length > 0 && (
            <div style={{ marginBottom: 12 }}>
              <div className="eyebrow" style={{ marginBottom: 6, opacity: .75 }}>Recent creatives</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {account.evidence.recentCreatives.map((c, i) => (
                  <li key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)', fontSize: 12.5 }}>
                    <span>{c.name} <span className="tag" style={{ marginLeft: 6, padding: '1px 6px', fontSize: 9.5 }}>{c.type}</span></span>
                    <span className="mono" style={{ color: c.age > 14 ? 'var(--status-amber)' : 'var(--ink-soft)' }}>{c.age}d old</span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {account.evidence.recentClickup && account.evidence.recentClickup.length > 0 && (
            <div>
              <div className="eyebrow" style={{ marginBottom: 6, opacity: .75 }}>ClickUp activity</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {account.evidence.recentClickup.map((a, i) => (
                  <li key={i} style={{ display: 'grid', gridTemplateColumns: '60px 1fr', gap: 10, padding: '6px 0', borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)', fontSize: 12.5 }}>
                    <span className="mono" style={{ color: 'var(--ink-soft)' }}>{a.date}</span>
                    <span>{a.text}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </section>
      </div>
    </React.Fragment>
  );
}

// ── Neglected Accounts ──────────────────────────────────────────────────────
function NeglectedAccounts({ rows, onPickClient }) {
  const [sortKey, setSortKey] = useState('daysNeglected');
  const [sortDir, setSortDir] = useState('desc');
  const sorted = useMemo(() => {
    const a = [...rows];
    a.sort((x, y) => {
      const xv = x[sortKey], yv = y[sortKey];
      if (xv === yv) return 0;
      const cmp = xv < yv ? -1 : 1;
      return sortDir === 'asc' ? cmp : -cmp;
    });
    return a;
  }, [rows, sortKey, sortDir]);
  const hdr = (k, l) => (
    <th className="sortable"
        onClick={() => {
          if (sortKey === k) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
          else { setSortKey(k); setSortDir('desc'); }
        }}
        style={{ textAlign: 'left', padding: '8px 10px', fontWeight: 600, fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-soft)', borderBottom: '1px solid var(--border)' }}>
      {l}{sortKey === k ? <span style={{ marginLeft: 4 }}>{sortDir === 'asc' ? '↑' : '↓'}</span> : null}
    </th>
  );
  if (rows.length === 0) {
    return <WidgetCard eyebrow="ad_monitor_neglect.py" title="Neglected accounts">
      <Empty icon="·" title="No neglected accounts" hint="Every account has had activity in the last 14 days." />
    </WidgetCard>;
  }
  return (
    <WidgetCard eyebrow="ad_monitor_neglect.py" title="Neglected accounts"
      action={<span className="tag">{rows.length} accounts &gt; 14d quiet</span>}>
      <div style={{ overflowX: 'auto' }}>
        <table className="mobile-stack" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>
              {hdr('name', 'Account')}
              {hdr('daysNeglected', 'Days neglected')}
              {hdr('lastActivity', 'Last activity')}
              {hdr('lastActivityDate', 'On')}
              <th></th>
            </tr>
          </thead>
          <tbody>
            {sorted.map(r => (
              <tr key={r.slug} onClick={() => onPickClient(r.slug)}
                  style={{ cursor: 'pointer', borderBottom: '1px solid var(--border-soft)' }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--paper-100)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                <td data-mobile="primary" style={{ padding: '10px' }}>{r.name}</td>
                <td data-label="Days neglected" style={{ padding: '10px', color: r.daysNeglected > 18 ? 'var(--status-red)' : r.daysNeglected > 14 ? 'var(--status-amber)' : 'var(--ink)', fontWeight: 600 }}>{r.daysNeglected}d</td>
                <td data-label="Last activity" style={{ padding: '10px', color: 'var(--ink-soft)' }}>{r.lastActivity}</td>
                <td data-label="On" style={{ padding: '10px', color: 'var(--ink-soft)' }} className="mono">{r.lastActivityDate}</td>
                <td data-mobile="trail" style={{ padding: '10px', color: 'var(--ink-soft)' }}><ExtArrow /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </WidgetCard>
  );
}

// ── My Tasks ────────────────────────────────────────────────────────────────
function MyTasks({ tasks }) {
  const sections = [
    { 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)' },
  ];
  return (
    <WidgetCard eyebrow="ClickUp · assigned to me" title="My tasks">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {sections.map(s => {
          const items = tasks.filter(t => t.status === s.k);
          if (items.length === 0) return null;
          return (
            <div key={s.k}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.color, display: 'inline-block' }} />
                <span className="eyebrow" style={{ color: s.color }}>{s.l}</span>
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>{items.length}</span>
              </div>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                {items.map((t, i) => (
                  <li key={t.id}>
                    <a href={t.clickupUrl} target="_blank" rel="noreferrer"
                       style={{
                         display: 'grid', gridTemplateColumns: '1fr auto auto',
                         alignItems: 'center', gap: 12,
                         padding: '8px 0',
                         borderTop: i === 0 ? 'none' : '1px solid var(--border-soft)',
                         color: 'inherit',
                       }}>
                      <span style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
                        <span style={{ fontSize: 13, lineHeight: 1.3 }}>{t.title}</span>
                        {t.client && <span style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 2 }}>{t.client}</span>}
                      </span>
                      <span className="mono" style={{ fontSize: 11, color: s.color }}>{t.dueDate}</span>
                      <ExtArrow />
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          );
        })}
        {tasks.length === 0 && <Empty icon="✓" title="No tasks assigned" hint="ClickUp queue is clear." />}
      </div>
    </WidgetCard>
  );
}

// ── Creative Log Gaps (sortable table) ──────────────────────────────────────
function CreativeLogGaps({ rows }) {
  const [sortKey, setSortKey] = useState('daysSinceLastCreative');
  const [sortDir, setSortDir] = useState('desc');
  const sorted = useMemo(() => {
    const a = [...rows];
    a.sort((x, y) => {
      const xv = x[sortKey], yv = y[sortKey];
      if (xv === yv) return 0;
      const cmp = xv < yv ? -1 : 1;
      return sortDir === 'asc' ? cmp : -cmp;
    });
    return a;
  }, [rows, sortKey, sortDir]);
  const hdr = (k, l) => (
    <th className="sortable"
        onClick={() => { if (sortKey === k) setSortDir(d => d === 'asc' ? 'desc' : 'asc'); else { setSortKey(k); setSortDir('desc'); } }}
        style={{ textAlign: 'left', padding: '8px 10px', fontWeight: 600, fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-soft)', borderBottom: '1px solid var(--border)' }}>
      {l}{sortKey === k ? <span style={{ marginLeft: 4 }}>{sortDir === 'asc' ? '↑' : '↓'}</span> : null}
    </th>
  );
  return (
    <WidgetCard eyebrow="Creative refresh cadence" title="Creative log gaps">
      <div style={{ overflowX: 'auto' }}>
        <table className="mobile-stack" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>
              {hdr('name', 'Account')}
              {hdr('daysSinceLastCreative', 'Days since')}
              {hdr('lastCreativeType', 'Last type')}
            </tr>
          </thead>
          <tbody>
            {sorted.map(r => (
              <tr key={r.slug} style={{
                borderBottom: '1px solid var(--border-soft)',
                background: r.daysSinceLastCreative > 14 ? 'var(--status-amber-soft)' : 'transparent',
              }}>
                <td data-mobile="primary" style={{ padding: '10px' }}>{r.name}</td>
                <td data-label="Days since" style={{ padding: '10px', fontWeight: 600,
                  color: r.daysSinceLastCreative > 14 ? '#7a5605' : 'var(--ink)' }}>{r.daysSinceLastCreative}d</td>
                <td data-label="Last type" style={{ padding: '10px', color: 'var(--ink-soft)' }}>{r.lastCreativeType}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {rows.length === 0 && <Empty icon="✓" title="All accounts refreshed recently" />}
    </WidgetCard>
  );
}

// ── Account Wins ────────────────────────────────────────────────────────────
function AccountWins({ wins }) {
  if (!wins || wins.length === 0) {
    return <WidgetCard eyebrow="ad_monitor_wins.py" title="Account wins">
      <Empty icon="·" title="No standout wins this week" hint="Most accounts within target band." />
    </WidgetCard>;
  }
  return (
    <WidgetCard eyebrow="ad_monitor_wins.py" title="Account wins"
      action={<span className="tag solid-green">{wins.length} above target</span>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 8 }}>
        {wins.map(w => (
          <div key={w.slug} style={{
            background: 'var(--status-green-soft)',
            border: '1px solid transparent', padding: 12,
          }}>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>{w.name}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
              <span className="serif" style={{ fontSize: 26, lineHeight: 1, color: 'var(--status-green)' }}>{w.value}</span>
              <span style={{ fontSize: 10.5, color: 'var(--status-green)', fontWeight: 600 }}>{w.vsTarget}</span>
            </div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 2, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{w.metric}</div>
          </div>
        ))}
      </div>
    </WidgetCard>
  );
}

window.DC = Object.assign(window.DC || {}, {
  AtRiskAccounts, NextStepsModal, NeglectedAccounts, MyTasks, CreativeLogGaps, AccountWins,
});
