// Generic KPI strip variant for Vukasi (used on Overview + reused on routes)
// Plus the Toast system + Route shell template.

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

// ── Vukasi KPI Strip ────────────────────────────────────────────────────────
function VukasiKPIStrip({ kpis }) {
  if (!kpis) return null;
  const items = [
    { ...kpis.avgCPL,    key: 'cpl',  emphasis: true  },
    { ...kpis.cpBooked,  key: 'cpb',  emphasis: false },
    { ...kpis.hookRate,  key: 'hook', emphasis: false },
  ].filter(k => k.label);
  const trendColor = (t) => t === 'good' ? 'var(--status-green)' : t === 'warn' ? 'var(--status-amber)' : 'var(--ink-soft)';
  return (
    <section className="card card-elev" style={{ padding: 0 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {items.map((k, i) => (
          <div key={k.key} style={{
            flex: k.emphasis ? '1.4 1 280px' : '1 1 220px', minWidth: 0,
            borderRight: i < items.length - 1 ? '1px solid var(--border)' : 'none',
            padding: 'var(--pad-card)',
            background: k.emphasis ? 'rgba(248,197,48,.05)' : 'transparent',
            position: 'relative',
          }}>
            {k.emphasis && (
              <span style={{
                position: 'absolute', top: 10, right: 12,
                fontSize: 9.5, fontWeight: 600, letterSpacing: '0.08em',
                color: 'var(--gold-deep)', textTransform: 'uppercase',
              }}>Headline</span>
            )}
            <div className="eyebrow" style={{ marginBottom: 6 }}>{k.label}</div>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
              <div>
                <div className="serif" style={{ fontSize: k.emphasis ? 38 : 30, lineHeight: 1, fontWeight: 400 }}>{k.value}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 4 }}>
                  <span style={{ color: trendColor(k.trend), fontWeight: 600 }}>{k.delta}</span>
                  <span style={{ margin: '0 6px', opacity: .4 }}>·</span>
                  <span>{k.target}</span>
                </div>
              </div>
              {k.series && (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                  <Sparkline series={k.series} width={88} height={36}
                             goodIs={k.goodIs || 'up'}
                             sentiment={k.sentiment === 'down' ? 'bad' : k.sentiment === 'up' ? 'good' : undefined} />
                  <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-soft)', marginTop: 2 }}>
                    {k.prefix || ''}{k.series[0]}{k.suffix || ''} → {k.prefix || ''}{k.series[k.series.length-1]}{k.suffix || ''}
                  </span>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ── Toast system ────────────────────────────────────────────────────────────
const ToastContext = React.createContext({ push: () => {} });

function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);
  const push = useCallback((t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(prev => [...prev, { ...t, id }]);
    setTimeout(() => setToasts(prev => prev.filter(x => x.id !== id)), t.durationMs || 5500);
  }, []);
  return (
    <ToastContext.Provider value={{ push }}>
      {children}
      <div style={{
        position: 'fixed', right: 20, bottom: 20, zIndex: 200,
        display: 'flex', flexDirection: 'column', gap: 8, maxWidth: 380, pointerEvents: 'none',
      }}>
        {toasts.map(t => (
          <div key={t.id} style={{
            background: 'var(--forest-900)', color: 'var(--paper-50)',
            padding: '12px 14px', display: 'flex', gap: 10, alignItems: 'flex-start',
            boxShadow: '0 12px 30px rgba(14,42,31,.25)',
            borderLeft: `3px solid ${t.tone === 'success' ? 'var(--status-green)' : 'var(--gold)'}`,
            pointerEvents: 'auto',
            animation: 'toastIn .22s cubic-bezier(.2,.7,.2,1)',
          }}>
            <span style={{
              flex: 'none', width: 24, height: 24, borderRadius: '50%',
              background: 'var(--gold)', color: 'var(--forest-900)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700,
            }}>{t.initials || '✦'}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.3 }}>{t.title}</div>
              {t.body && <div style={{ fontSize: 11.5, opacity: .75, marginTop: 2, lineHeight: 1.4 }}>{t.body}</div>}
            </div>
          </div>
        ))}
      </div>
      <style>{`
        @keyframes toastIn {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </ToastContext.Provider>
  );
}

const useToast = () => React.useContext(ToastContext);

// ── Route page shell ────────────────────────────────────────────────────────
function RoutePage({
  eyebrow, title, lastUpdated, dataSource,
  rollupSummary,    // optional inline string
  rollupCards,      // optional [{label, value, sub, tone}]
  filters,          // optional ReactNode (rendered top-right)
  actions,          // optional ReactNode (rendered top-right after filters)
  children,
  onBack,
}) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap-grid)' }}>
      <header className="routepage-hd" style={{
        background: 'var(--surface)', border: '1px solid var(--border)',
        padding: '14px 18px', display: 'flex', alignItems: 'flex-end',
        justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {onBack && (
            <button onClick={onBack} style={{
              background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
              color: 'var(--ink-soft)', fontSize: 11, letterSpacing: '0.06em',
              textTransform: 'uppercase', fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 4, alignSelf: 'flex-start',
              marginBottom: 2,
            }}>← Overview</button>
          )}
          {eyebrow && <div className="eyebrow">{eyebrow}</div>}
          <h1 className="serif" style={{ margin: 0, fontSize: 32, fontWeight: 400, lineHeight: 1.1 }}>{title}</h1>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 4, fontSize: 11, color: 'var(--ink-soft)' }}>
            {lastUpdated && <span className="mono" style={{ textTransform: 'uppercase', letterSpacing: '0.04em' }}>Updated {lastUpdated}</span>}
            {dataSource && <React.Fragment><span style={{ opacity: .4 }}>·</span><span className="mono">{dataSource}</span></React.Fragment>}
          </div>
        </div>
        {(filters || actions) && (
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            {filters}
            {actions}
          </div>
        )}
      </header>

      {(rollupSummary || rollupCards) && (
        <section style={{
          background: 'var(--surface-2)', border: '1px solid var(--border)',
          padding: 'var(--pad-card)',
          display: 'flex', flexDirection: 'column', gap: rollupCards ? 12 : 0,
        }}>
          {rollupSummary && (
            <div className="rollup-summary" style={{ fontSize: 13, color: 'var(--ink)', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              <span className="eyebrow">Rollup</span>
              <span style={{ flex: 1 }}>{rollupSummary}</span>
            </div>
          )}
          {rollupCards && rollupCards.length > 0 && (
            <div className="rollup-grid" style={{
              display: 'grid', gridTemplateColumns: `repeat(${rollupCards.length}, minmax(140px, 1fr))`, gap: 0,
              border: '1px solid var(--border)',
            }}>
              {rollupCards.map((c, i) => (
                <div key={i} style={{
                  padding: 12, borderRight: i < rollupCards.length - 1 ? '1px solid var(--border)' : 'none',
                  background: c.tone === 'red'    ? 'rgba(154,42,42,.05)'
                            : c.tone === 'amber'  ? 'rgba(248,197,48,.06)'
                            : c.tone === 'green'  ? 'rgba(45,106,79,.05)'
                            : 'transparent',
                }}>
                  <div style={{ fontSize: 10, color: 'var(--ink-soft)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{c.label}</div>
                  <div className="serif" style={{ fontSize: 24, lineHeight: 1.05, marginTop: 4,
                    color: c.tone === 'red' ? 'var(--status-red)' : c.tone === 'amber' ? '#7a5605' : c.tone === 'green' ? 'var(--status-green)' : 'var(--ink)' }}>{c.value}</div>
                  {c.sub && <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 2 }}>{c.sub}</div>}
                </div>
              ))}
            </div>
          )}
        </section>
      )}

      <div>{children}</div>
    </div>
  );
}

// ── Phase 2 placeholder ─────────────────────────────────────────────────────
function PlaceholderRoute({ eyebrow, title, intent, willInclude, onBack }) {
  return (
    <RoutePage eyebrow={eyebrow} title={title} onBack={onBack}>
      <section style={{
        border: '1px dashed var(--border)', padding: '40px 28px',
        background: 'var(--surface)', display: 'flex', gap: 20, alignItems: 'flex-start',
      }}>
        <div style={{
          width: 56, height: 56, flex: 'none',
          border: '1.5px solid var(--ink-soft)', display: 'inline-flex',
          alignItems: 'center', justifyContent: 'center',
          fontFamily: 'JetBrains Mono, monospace', fontSize: 22, color: 'var(--ink-soft)',
          position: 'relative',
        }}>
          P2
          <span style={{ position: 'absolute', top: -3, right: -3, width: 6, height: 6, background: 'var(--gold)' }} />
        </div>
        <div style={{ flex: 1, maxWidth: 640 }}>
          <div style={{ fontSize: 11, color: 'var(--gold-deep)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>
            Coming in Phase 2
          </div>
          <h2 className="serif" style={{ margin: 0, fontSize: 24, fontWeight: 400, lineHeight: 1.1 }}>{intent}</h2>
          <p style={{ margin: '10px 0 18px', fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-soft)' }}>
            The shell is in place — header, rollup slot, and content area are all ready. The route works
            as a destination already; we just haven't filled the working surface yet. Round 4 prioritized
            building four routes deep over building all nine shallow.
          </p>
          {willInclude && (
            <div style={{ background: 'var(--paper-100)', padding: 14, fontSize: 12.5, lineHeight: 1.5 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Will include</div>
              <ul style={{ margin: 0, paddingLeft: 18, color: 'var(--ink)' }}>
                {willInclude.map((w, i) => <li key={i} style={{ marginBottom: 4 }}>{w}</li>)}
              </ul>
            </div>
          )}
        </div>
      </section>
    </RoutePage>
  );
}

// ── Filter pill bar ─────────────────────────────────────────────────────────
function PillBar({ value, onChange, options }) {
  return (
    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
      {options.map(o => (
        <button key={o.k} onClick={() => onChange(o.k)} style={{
          padding: '5px 10px', border: '1px solid var(--border)',
          background: value === o.k ? 'var(--ink)' : 'transparent',
          color: value === o.k ? 'var(--paper-50)' : 'var(--ink-soft)',
          fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, cursor: 'pointer',
        }}>
          {o.l}
          {o.count !== undefined && <span style={{ marginLeft: 6, opacity: value === o.k ? .9 : .55 }}>{o.count}</span>}
        </button>
      ))}
    </div>
  );
}

// ── Read-only badge (Henry viewing Vukasi's routes) ───────────────────────────
function ReadOnlyBadge() {
  return (
    <span title="You're viewing Vukasi's operational surface read-only." style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 10px', background: 'var(--paper-100)',
      border: '1px solid var(--border-soft)',
      fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
      textTransform: 'uppercase', color: 'var(--ink-soft)',
    }}>
      <span style={{ width: 6, height: 6, background: 'var(--gold)', display: 'inline-block' }} />
      Vukasi's view · Read-only
    </span>
  );
}

window.DC = Object.assign(window.DC || {}, {
  VukasiKPIStrip, ToastProvider, useToast, RoutePage, PlaceholderRoute, PillBar, ReadOnlyBadge,
});
