// S — Inside the storyboard: how the case gets built.
// Faithful to the product flow: from the business question the agent derives
// the story SPINE (sub-questions in narrative order), verdicts what the pool
// already supports, asks the user, researches the gaps, then writes FLOWING
// headlines — each carrying how well it's backed (✓ Done / Research gap /
// Editorial review). Left: the flow. Right: the real Storyboard table view.

const { useState: seUse, useEffect: seEff } = React;
const { pitchC, pitchMono } = window;

// Flow stages (canonical order from mcp_server/tools/storyboard.py)
const FLOW = [
  { k: 'ask',    label: 'Ask',       sub: 'the business question' },
  { k: 'survey', label: 'Survey',    sub: 'decompose → story spine' },
  { k: 'approve',label: 'Approve',   sub: 'you greenlight or reshape', human: true },
  { k: 'research',label: 'Research', sub: 'close the gaps it found' },
  { k: 'write',  label: 'Headlines', sub: 'flowing, each one earned' },
];

const BQ = 'Should Habitat lead with furniture or homeware?';

// The storyboard spine: sections = sub-questions, rows = flowing headlines
const SPINE = [
  {
    band: 'Where does awareness already convert?',
    rows: [
      { n: '1', conn: null, headline: 'Homeware is where awareness already converts', badge: 'done', chart: 'bar' },
    ],
  },
  {
    band: 'How big is the gap — and is it moving?',
    rows: [
      { n: '2', conn: 'therefore', headline: 'so the conversion gap runs 2.4× against furniture', badge: 'done', chart: 'bar' },
      { n: '3', conn: 'but', headline: 'furniture momentum is quietly building', badge: 'gap', chart: 'line' },
    ],
  },
  {
    band: 'Can we win the category we’d lead with?',
    rows: [
      { n: '4', conn: 'because', headline: 'no rival has locked up homeware yet', badge: 'done', chart: 'stack' },
    ],
  },
  {
    band: 'recommendations', isRec: true,
    rows: [
      { n: 'R', conn: 'which is why', headline: 'shift the next flight behind homeware', badge: 'review', chart: 'text' },
    ],
  },
];

function SlideStoryEval() {
  // step: 1 ask · 2 survey/spine · 3 headlines drafted · 4 approve+research · 5 done
  const [step, setStep] = seUse(0);
  seEff(() => {
    const ts = [
      setTimeout(() => setStep(1), 300),
      setTimeout(() => setStep(2), 1000),
      setTimeout(() => setStep(3), 1900),
      setTimeout(() => setStep(4), 2900),
      setTimeout(() => setStep(5), 3800),
    ];
    return () => ts.forEach(clearTimeout);
  }, []);

  return (
    <div style={{
      flex: 1, minHeight: 0,
      display: 'grid',
      gridTemplateColumns: '0.62fr 1.38fr',
      gap: 26,
      marginTop: 20,
    }}>
      <FlowRail step={step} />
      <StoryboardView step={step} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// LEFT — the build flow
// ─────────────────────────────────────────────────────────────────────
function FlowRail({ step }) {
  // ribbon highlight: ask@1, survey@2, approve@3, research@4, write@5
  const reached = { ask: 1, survey: 2, approve: 3, research: 4, write: 5 };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minHeight: 0, justifyContent: 'flex-start', paddingTop: 6 }}>
      <div style={{
        fontFamily: pitchMono, fontSize: 13, fontWeight: 700,
        letterSpacing: 1.8, textTransform: 'uppercase', color: pitchC.navy, marginBottom: 4,
      }}>How it builds</div>

      {FLOW.map((f, i) => {
        const on = step >= reached[f.k];
        const active = step === reached[f.k];
        const accent = f.human ? pitchC.orange : pitchC.sea;
        return (
          <div key={f.k} style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 13 }}>
            {/* connector line */}
            {i < FLOW.length - 1 && (
              <div style={{
                position: 'absolute', left: 17, top: 36, width: 2, height: 'calc(100% - 8px)',
                background: step > reached[f.k] ? accent : pitchC.hair,
                transition: 'background 360ms ease',
              }} />
            )}
            <span style={{
              position: 'relative', zIndex: 1,
              width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: on ? accent : '#fff',
              border: `1.5px solid ${on ? accent : pitchC.hair2}`,
              color: on ? '#fff' : pitchC.muted2,
              boxShadow: active ? `0 0 0 4px ${accent}1f` : 'none',
              transition: 'all 320ms ease',
            }}>
              <FlowIcon kind={f.k} on={on} />
            </span>
            <div style={{ opacity: on ? 1 : 0.5, transition: 'opacity 300ms ease' }}>
              <div style={{ fontSize: 17.5, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.01, lineHeight: 1.1 }}>
                {f.label}
                {f.human && <span style={{
                  marginLeft: 8, fontFamily: pitchMono, fontSize: 10.5, fontWeight: 700,
                  letterSpacing: 0.6, textTransform: 'uppercase', color: pitchC.orange,
                  padding: '2px 7px', borderRadius: 5, background: '#fff1ec',
                }}>you</span>}
              </div>
              <div style={{ fontFamily: pitchMono, fontSize: 13, color: pitchC.muted2, marginTop: 2 }}>{f.sub}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function FlowIcon({ kind, on }) {
  const c = on ? '#fff' : pitchC.muted2;
  const p = { width: 17, height: 17, viewBox: '0 0 24 24', fill: 'none', stroke: c, strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'ask')     return <svg {...p}><path d="M5 5h14v10H9l-4 3z"/></svg>;
  if (kind === 'survey')  return <svg {...p}><path d="M4 6h16M4 12h10M4 18h13"/></svg>;
  if (kind === 'approve') return <svg {...p}><circle cx="12" cy="8" r="3.2"/><path d="M5 20c0-3.5 3-6 7-6 1.4 0 2.7.4 3.8 1"/><path d="M15.5 18.5l1.8 1.8 3.2-3.6"/></svg>;
  if (kind === 'research')return <svg {...p}><path d="M4 9a8 8 0 0114-3l2 2M20 5v4h-4"/><path d="M20 15a8 8 0 01-14 3l-2-2M4 19v-4h4"/></svg>;
  return <svg {...p}><path d="M7 4h10v16H7z"/><path d="M10 9h4M10 13h4"/></svg>;
}

// ─────────────────────────────────────────────────────────────────────
// RIGHT — the Storyboard table (mirrors StoryboardTable.jsx)
// ─────────────────────────────────────────────────────────────────────

const BADGE = {
  done:   { label: '✓ Done',          color: pitchC.moss,   bg: pitchC.mossBg },
  gap:    { label: 'Research gap',    color: pitchC.orange, bg: '#fff1ec' },
  review: { label: 'Editorial review',color: pitchC.sea,    bg: pitchC.seaBg },
};

function StoryboardView({ step }) {
  const showSpine = step >= 2;
  const showRows = step >= 3;
  const researching = step === 4;
  const closed = step >= 5;

  let slideNo = 0;
  const gapCount = closed ? 0 : 1;

  return (
    <div style={{
      background: '#fff', border: `1px solid ${pitchC.hair}`, borderRadius: 14,
      display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        padding: '11px 20px', borderBottom: `1px solid ${pitchC.hair}`, background: pitchC.bgSoft,
        display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
      }}>
        <span style={{ fontSize: 16.5, fontWeight: 700, color: pitchC.ink }}>Storyboard</span>
        <span style={{ fontSize: 13.5, color: pitchC.muted2 }}>Habitat — Furniture vs Homeware</span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <span style={{
            fontFamily: pitchMono, fontSize: 12, fontWeight: 600,
            padding: '4px 10px', borderRadius: 999,
            color: gapCount ? pitchC.orange : pitchC.moss,
            background: gapCount ? '#fff1ec' : pitchC.mossBg,
            border: `1px solid ${(gapCount ? pitchC.orange : pitchC.moss)}40`,
            transition: 'all 300ms ease',
          }}>{gapCount ? `${gapCount} research gap` : 'all earned'}</span>
        </span>
      </div>

      {/* business question band */}
      <div style={{
        padding: '11px 20px', borderBottom: `1px solid ${pitchC.hair}`,
        display: 'flex', alignItems: 'baseline', gap: 12, flexShrink: 0,
        opacity: step >= 1 ? 1 : 0, transition: 'opacity 360ms ease',
      }}>
        <span style={{
          fontFamily: pitchMono, fontSize: 11, fontWeight: 700, letterSpacing: 1.4,
          textTransform: 'uppercase', color: pitchC.muted2, flexShrink: 0,
        }}>Business question</span>
        <span style={{ fontSize: 17, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.01 }}>{BQ}</span>
      </div>

      {/* column headers */}
      <div style={{
        display: 'grid', gridTemplateColumns: '40px 1fr 156px 104px',
        gap: 12, padding: '7px 20px', borderBottom: `1px solid ${pitchC.hair}`,
        fontFamily: pitchMono, fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
        color: pitchC.muted2, flexShrink: 0,
      }}>
        <span>No.</span><span>Story</span><span>Evidence</span><span>Chart</span>
      </div>

      {/* spine + rows */}
      <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '6px 0' }}>
        {SPINE.map((sec, si) => (
          <React.Fragment key={si}>
            <SectionBand sec={sec} visible={showSpine} delay={si * 130} />
            {sec.rows.map((r) => {
              slideNo += 1;
              return (
                <HeadlineRow
                  key={r.n} r={r} no={slideNo}
                  visible={showRows} delay={slideNo * 110}
                  researching={researching} closed={closed}
                />
              );
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function SectionBand({ sec, visible, delay }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      margin: '6px 16px 4px', padding: '7px 14px',
      borderRadius: 9, borderLeft: `4px solid ${sec.isRec ? pitchC.sea : pitchC.moss}`,
      background: sec.isRec ? pitchC.seaBg : pitchC.mossBg,
      opacity: visible ? 1 : 0,
      transform: visible ? 'translateY(0)' : 'translateY(6px)',
      transition: `opacity 380ms ease ${delay}ms, transform 380ms ease ${delay}ms`,
    }}>
      {sec.isRec ? (
        <span style={{
          fontFamily: pitchMono, fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
          color: pitchC.sea,
        }}>recommendations</span>
      ) : (
        <span style={{ fontSize: 15.5, fontWeight: 600, color: '#16603f', letterSpacing: -0.01 }}>{sec.band}</span>
      )}
    </div>
  );
}

function HeadlineRow({ r, no, visible, delay, researching, closed }) {
  const isGap = r.badge === 'gap';
  const running = isGap && researching;
  const badgeKey = isGap && closed ? 'done' : r.badge;
  const b = BADGE[badgeKey];

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '40px 1fr 156px 104px',
      gap: 12, alignItems: 'center', padding: '9px 20px',
      opacity: visible ? 1 : 0,
      transform: visible ? 'translateY(0)' : 'translateY(8px)',
      transition: `opacity 380ms ease ${delay}ms, transform 380ms ease ${delay}ms`,
    }}>
      {/* No. */}
      <span style={{
        fontFamily: pitchMono, fontSize: 13, fontWeight: 700,
        width: 28, height: 28, borderRadius: 7,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        background: r.n === 'R' ? pitchC.seaBg : pitchC.bgSoft,
        color: r.n === 'R' ? pitchC.sea : pitchC.muted,
      }}>{r.n}</span>

      {/* Story — connective + flowing headline */}
      <span style={{ minWidth: 0, lineHeight: 1.25 }}>
        {r.conn && (
          <span style={{
            fontFamily: pitchMono, fontSize: 11, fontWeight: 700, letterSpacing: 0.5,
            textTransform: 'uppercase', color: pitchC.purple,
            padding: '2px 7px', borderRadius: 5, background: '#f3eef7', marginRight: 8,
            verticalAlign: 'middle',
          }}>{r.conn}</span>
        )}
        <span style={{ fontSize: 16.5, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.01 }}>{r.headline}</span>
      </span>

      {/* Evidence badge */}
      <span>
        {running ? (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontFamily: pitchMono, fontSize: 12.5, fontWeight: 600,
            padding: '4px 11px', borderRadius: 999,
            color: pitchC.sea, background: pitchC.seaBg, border: `1px solid ${pitchC.sea}40`,
          }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: pitchC.sea, animation: 'pulse-dot 0.9s ease-in-out infinite' }} />
            researching…
          </span>
        ) : (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 7,
            fontFamily: pitchMono, fontSize: 12.5, fontWeight: 700,
            padding: '4px 11px', borderRadius: 999,
            color: b.color, background: b.bg, border: `1px solid ${b.color}40`,
            transition: 'all 300ms ease',
          }}>{b.label}</span>
        )}
      </span>

      {/* Chart glyph */}
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: pitchC.muted }}>
        <ChartGlyph kind={r.chart} />
        <span style={{ fontFamily: pitchMono, fontSize: 12.5 }}>{r.chart === 'text' ? 'text' : r.chart}</span>
      </span>
    </div>
  );
}

function ChartGlyph({ kind }) {
  const c = pitchC.muted2;
  const p = { width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none', stroke: c, strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'bar')   return <svg {...p}><path d="M5 20V10M12 20V5M19 20v-7"/></svg>;
  if (kind === 'line')  return <svg {...p}><path d="M4 16l5-5 4 3 7-8"/></svg>;
  if (kind === 'stack') return <svg {...p}><rect x="5" y="13" width="14" height="3.4"/><rect x="5" y="8" width="9" height="3.4"/></svg>;
  return <svg {...p}><path d="M5 6h14M5 11h14M5 16h9"/></svg>;
}

window.SlideStoryEval = SlideStoryEval;
