// Slide — The storyboard. Findings become a story.
// The piece between research and the deck: an analyst doesn't hand you
// charts, they build a case. The agent crystallizes a thesis, orders the
// evidence into a narrative, decides what leads vs what's appendix, and
// ties every section back to the research package that proves it.
//
// Left  — "Composing the story": the editorial reasoning, three decisions
//          that mirror how a senior analyst structures an argument.
// Right — the storyboard itself assembling: thesis bar, section cards
//          dropping in narrative order with their source-package dots, then
//          one section demoted to the appendix to hit the slide target.

const { useState: sbUse, useEffect: sbEff, useRef: sbRef } = React;
const { pitchC, pitchMono } = window;

// ──── Source-package palette (echoes the research packages from slide 3) ──
const PK = {
  assoc:  pitchC.sea,
  future: pitchC.moss,
  share:  pitchC.amber,
  spend:  pitchC.purple,
  percep: pitchC.orange,
};

const THESIS =
  "Habitat should double down on homeware — it's the one category where awareness already converts, and the one no rival has locked up.";

// Type → left-edge accent (matches the product's section coloring)
const TYPE_COLOR = {
  'EXECUTIVE SUMMARY': pitchC.orange,
  'FINDINGS':          pitchC.moss,
  'ANALYSIS':          pitchC.sea,
  'RECOMMENDATION':    pitchC.purple,
};

const SECTIONS = [
  {
    n: '01', type: 'EXECUTIVE SUMMARY',
    title: 'Homeware is the growth lever',
    abstract: 'Awareness converts at 22% in homeware vs 9% in furniture. Lead with the category we already win.',
    slides: 2, pkgs: [PK.future, PK.percep],
  },
  {
    n: '02', type: 'FINDINGS',
    title: 'The conversion gap is the signal',
    abstract: 'Homeware future-consideration runs 2.4× furniture — the strongest, most actionable move in the data.',
    slides: 2, pkgs: [PK.future, PK.assoc, PK.percep],
  },
  {
    n: '03', type: 'ANALYSIS',
    title: 'A concentrated category we can win',
    abstract: 'IKEA (20%) and Dunelm (14%) lead, but Habitat\'s 4.2% homeware share is rising where it counts.',
    slides: 2, pkgs: [PK.share, PK.assoc],
  },
  {
    n: '04', type: 'RECOMMENDATION',
    title: 'Shift the next flight to homeware',
    abstract: 'Move 60% of Q1 spend behind homeware consideration; hold furniture as a long-horizon equity play.',
    slides: 2, pkgs: [PK.spend, PK.percep],
  },
  {
    n: '05', type: 'ANALYSIS',
    title: 'Full category-association detail',
    abstract: 'Association across bedding, lighting and decorative — useful reference, tangential to the homeware call.',
    slides: 2, pkgs: [PK.assoc], demote: true,
  },
];

const MAIN = SECTIONS.filter(s => !s.demote);
const APPENDIX = SECTIONS.filter(s => s.demote);

// Narrative beats that fill as the main sections land
const ARC = ['Set the stakes', 'Quantify', 'Diagnose', 'Recommend'];

function SlideStoryboard() {
  // stage: 0 init · 1 thesis · 2 sections drop · 3 trim to appendix · 4 done
  const [stage, setStage] = sbUse(0);
  sbEff(() => {
    const ts = [
      setTimeout(() => setStage(1),  350),
      setTimeout(() => setStage(2), 1250),
      setTimeout(() => setStage(3), 4300),
      setTimeout(() => setStage(4), 5400),
    ];
    return () => ts.forEach(clearTimeout);
  }, []);

  return (
    <div style={{
      flex: 1, minHeight: 0,
      display: 'grid',
      gridTemplateColumns: '0.82fr 1.18fr',
      gap: 24,
      marginTop: 22,
    }}>
      <StoryLogic stage={stage} />
      <StoryboardPanel stage={stage} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// LEFT — Composing the story (the analyst's editorial reasoning)
// ─────────────────────────────────────────────────────────────────────

function StoryLogic({ stage }) {
  const building = stage >= 1 && stage < 4;
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 14, minHeight: 0,
    }}>
      {/* Header card — thinking like an analyst */}
      <div style={{
        position: 'relative',
        padding: '16px 20px 16px 58px',
        background: '#fff7f3',
        border: '1px solid #ffd9c9',
        borderRadius: 12,
        flexShrink: 0,
      }}>
        <div style={{
          position: 'absolute', left: 16, top: 16,
          width: 30, height: 30, borderRadius: '50%',
          background: pitchC.orange, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="#fff" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 2C5.8 2 4 3.6 4 5.7c0 .6.2 1.2.5 1.7C3.6 7.8 3 8.6 3 9.6c0 1.3 1 2.4 2.3 2.4M8 2c2.2 0 4 1.6 4 3.7 0 .6-.2 1.2-.5 1.7.9.4 1.5 1.2 1.5 2.2 0 1.3-1 2.4-2.3 2.4M5.3 12c0 1.1.9 2 2 2h1.4c1.1 0 2-.9 2-2"/>
            <path d="M8 4v8"/>
          </svg>
        </div>
        <div style={{
          fontFamily: pitchMono, fontSize: 12, fontWeight: 700,
          letterSpacing: 1.8, textTransform: 'uppercase', color: pitchC.orange,
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4,
        }}>
          <span>Composing the story</span>
          {building && (
            <span style={{ display: 'inline-flex', gap: 3 }}>
              {[0, 1, 2].map(i => (
                <span key={i} style={{
                  width: 4, height: 4, borderRadius: '50%', background: pitchC.orange, opacity: 0.5,
                  animation: `pulse-dot 1s ${i * 0.18}s ease-in-out infinite`,
                }} />
              ))}
            </span>
          )}
        </div>
        <div style={{ fontSize: 17, lineHeight: 1.35, color: pitchC.ink, fontWeight: 500 }}>
          Research is verified. Now the agent writes the <em style={{ color: pitchC.purple, fontStyle: 'italic' }}>thesis first</em>, then earns each section against the package that proves it.
        </div>
      </div>

      {/* The three editorial decisions */}
      <Decision
        idx="1" label="Thesis first"
        active={stage === 1} done={stage >= 2}
        q="What's the one thing they have to walk away believing?"
        answer="Crystallize 7 research packages into a single, defensible spine." />

      <Decision
        idx="2" label="Sequence the argument"
        active={stage === 2} done={stage >= 3}
        q="What order makes the case land?"
        answer={<ArcRow stage={stage} />} isArc />

      <Decision
        idx="3" label="Earn the slide"
        active={stage === 3} done={stage >= 4}
        q="Main narrative, or appendix?"
        answer="Demote what's tangential to the decision. Trim to a 10-slide deck." />

      {/* Footer status */}
      <div style={{
        marginTop: 'auto', flexShrink: 0,
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '12px 16px',
        background: '#fff',
        border: `1px solid ${stage >= 4 ? pitchC.moss + '55' : pitchC.hair}`,
        borderRadius: 12,
        transition: 'border-color 300ms ease',
      }}>
        <span style={{
          width: 9, height: 9, borderRadius: '50%',
          background: stage >= 4 ? pitchC.moss : pitchC.orange,
          animation: stage < 4 ? 'pulse-dot 1.1s ease-in-out infinite' : 'none',
        }} />
        <span style={{ fontFamily: pitchMono, fontSize: 13.5, color: pitchC.muted }}>
          {stage >= 4 ? 'story ready · thesis-led · 4 sections + appendix' : 'structuring the narrative…'}
        </span>
      </div>
    </div>
  );
}

function Decision({ idx, label, q, answer, active, done, isArc }) {
  const accent = done ? pitchC.moss : active ? pitchC.navy : pitchC.muted2;
  const lit = active || done;
  return (
    <div style={{
      padding: '13px 16px 14px',
      background: '#fff',
      border: `1px solid ${active ? pitchC.navy : pitchC.hair}`,
      borderRadius: 12,
      boxShadow: active ? `0 0 0 3px ${pitchC.navy}12` : 'none',
      opacity: lit ? 1 : 0.55,
      transition: 'opacity 300ms ease, border-color 300ms ease, box-shadow 300ms ease',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 7 }}>
        <span style={{
          width: 22, height: 22, borderRadius: 6, flexShrink: 0,
          background: done ? pitchC.moss : active ? pitchC.navy : '#eceef2',
          color: lit ? '#fff' : pitchC.muted2,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: pitchMono, fontSize: 12, fontWeight: 700,
        }}>
          {done
            ? <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="#fff" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8.5l3 3 7-7"/></svg>
            : idx}
        </span>
        <span style={{
          fontFamily: pitchMono, fontSize: 12, fontWeight: 700,
          letterSpacing: 1.4, textTransform: 'uppercase', color: accent,
        }}>{label}</span>
      </div>
      <div style={{ fontSize: 16.5, lineHeight: 1.28, color: pitchC.ink, fontWeight: 500, fontStyle: 'italic', marginBottom: isArc ? 10 : 5 }}>
        “{q}”
      </div>
      {isArc ? answer : (
        <div style={{ fontSize: 14, lineHeight: 1.35, color: pitchC.muted }}>{answer}</div>
      )}
    </div>
  );
}

function ArcRow({ stage }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      {ARC.map((beat, i) => (
        <React.Fragment key={beat}>
          <span style={{
            flex: 1,
            padding: '6px 4px',
            textAlign: 'center',
            background: stage >= 2 ? pitchC.navy : pitchC.bgSoft,
            color: stage >= 2 ? '#fff' : pitchC.muted2,
            border: `1px solid ${stage >= 2 ? pitchC.navy : pitchC.hair}`,
            borderRadius: 7,
            fontFamily: pitchMono, fontSize: 11.5, fontWeight: 700,
            letterSpacing: 0.2, textTransform: 'uppercase',
            transition: 'all 360ms ease',
            transitionDelay: `${i * 120}ms`,
            whiteSpace: 'nowrap',
          }}>{beat}</span>
          {i < ARC.length - 1 && (
            <span style={{ color: pitchC.muted2, fontSize: 12, flexShrink: 0 }}>›</span>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// RIGHT — the storyboard assembling
// ─────────────────────────────────────────────────────────────────────

function StoryboardPanel({ stage }) {
  const showAppendix = stage >= 3;
  return (
    <div style={{
      background: '#fff',
      border: `1px solid ${pitchC.hair}`,
      borderRadius: 14,
      display: 'flex', flexDirection: 'column',
      minHeight: 0, overflow: 'hidden',
      boxShadow: '0 2px 0 rgba(0,0,0,0.02)',
    }}>
      {/* Header strip */}
      <div style={{
        padding: '12px 22px',
        borderBottom: `1px solid ${pitchC.hair}`,
        background: pitchC.bgSoft,
        display: 'flex', alignItems: 'center', gap: 12,
        flexShrink: 0,
      }}>
        <span style={{ fontSize: 17, fontWeight: 700, color: pitchC.ink, letterSpacing: -0.005 }}>Storyboard</span>
        <span style={{ fontSize: 14, color: pitchC.muted2 }}>Habitat — Furniture vs Homeware</span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <Tag>{MAIN.length} sections</Tag>
          <Tag accent={stage >= 4 ? pitchC.moss : undefined}>{stage >= 4 ? '10 slides' : 'drafting…'}</Tag>
        </span>
      </div>

      <div style={{
        flex: 1, minHeight: 0, overflow: 'auto',
        padding: '14px 22px 14px',
        display: 'flex', flexDirection: 'column', gap: 9,
      }}>
        {/* Thesis */}
        <div style={{
          position: 'relative',
          padding: '12px 18px 12px 20px',
          background: 'linear-gradient(135deg, rgba(255,102,58,0.06) 0%, rgba(0,0,153,0.06) 100%)',
          border: '1px solid rgba(0,0,153,0.12)',
          borderRadius: 12,
          opacity: stage >= 1 ? 1 : 0,
          transform: stage >= 1 ? 'translateY(0)' : 'translateY(8px)',
          transition: 'opacity 420ms ease, transform 420ms ease',
          flexShrink: 0,
        }}>
          <div style={{
            position: 'absolute', left: 0, top: 10, bottom: 10, width: 4,
            borderRadius: 4,
            background: 'linear-gradient(180deg, #ff663a 0%, #7f3399 50%, #000099 100%)',
          }} />
          <div style={{
            fontFamily: pitchMono, fontSize: 11, fontWeight: 700,
            letterSpacing: 1.8, textTransform: 'uppercase', color: pitchC.navy, marginBottom: 5,
          }}>Thesis</div>
          <div style={{ fontSize: 18, lineHeight: 1.24, color: pitchC.ink, fontWeight: 500, letterSpacing: -0.01 }}>
            {THESIS}
          </div>
        </div>

        {/* Main sections */}
        {MAIN.map((s, i) => (
          <SectionCard key={s.n} s={s} visible={stage >= 2} delay={i * 220} />
        ))}

        {/* Appendix divider + demoted section */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          margin: '4px 0 2px',
          opacity: showAppendix ? 1 : 0,
          transition: 'opacity 360ms ease',
        }}>
          <div style={{ height: 1, flex: 1, background: pitchC.hair }} />
          <span style={{
            fontFamily: pitchMono, fontSize: 11, fontWeight: 700,
            letterSpacing: 1.6, textTransform: 'uppercase', color: pitchC.muted2,
            whiteSpace: 'nowrap',
          }}>Appendix · moved to hit 10 slides</span>
          <div style={{ height: 1, flex: 1, background: pitchC.hair }} />
        </div>
        {APPENDIX.map((s) => (
          <SectionCard key={s.n} s={s} visible={showAppendix} delay={120} appendix />
        ))}
      </div>
    </div>
  );
}

function Tag({ children, accent }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 10px', borderRadius: 999,
      background: accent ? `${accent}16` : '#fff',
      border: `1px solid ${accent ? `${accent}55` : pitchC.hair}`,
      color: accent || pitchC.muted,
      fontFamily: pitchMono, fontSize: 12, fontWeight: 600,
      letterSpacing: 0.3, whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function SectionCard({ s, visible, delay = 0, appendix }) {
  const edge = appendix ? pitchC.muted2 : (TYPE_COLOR[s.type] || pitchC.navy);
  return (
    <div style={{
      position: 'relative',
      display: 'grid', gridTemplateColumns: '40px 1fr',
      gap: 14,
      padding: '11px 16px 11px 18px',
      background: '#fff',
      border: `1px solid ${pitchC.hair}`,
      borderRadius: 12,
      flexShrink: 0,
      opacity: visible ? (appendix ? 0.72 : 1) : 0,
      transform: visible ? 'translateY(0)' : 'translateY(10px)',
      transition: `opacity 420ms cubic-bezier(.2,.7,.2,1) ${delay}ms, transform 420ms cubic-bezier(.2,.7,.2,1) ${delay}ms`,
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', left: 0, top: 10, bottom: 10, width: 4,
        borderRadius: 4, background: edge,
      }} />
      {/* Number */}
      <div style={{
        width: 40, height: 40, borderRadius: '50%',
        border: `1.5px solid ${pitchC.hair2}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: pitchMono, fontSize: 15, fontWeight: 700, color: pitchC.muted,
        alignSelf: 'flex-start',
      }}>{s.n}</div>

      {/* Content */}
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 5, flexWrap: 'wrap' }}>
          <span style={{
            fontSize: 18.5, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.01, lineHeight: 1.1,
          }}>{s.title}</span>
          <span style={{
            fontFamily: pitchMono, fontSize: 10.5, fontWeight: 700,
            letterSpacing: 1.2, textTransform: 'uppercase', color: edge,
            padding: '2px 8px', borderRadius: 5, background: `${edge}14`,
            whiteSpace: 'nowrap',
          }}>{s.type}</span>
          {appendix && (
            <span style={{
              fontFamily: pitchMono, fontSize: 10.5, fontWeight: 700,
              letterSpacing: 1.2, textTransform: 'uppercase', color: pitchC.muted,
              padding: '2px 8px', borderRadius: 5,
              border: `1px solid ${pitchC.hair2}`,
            }}>In appendix</span>
          )}
        </div>
        <div style={{ fontSize: 14, lineHeight: 1.35, color: pitchC.muted, marginBottom: 7 }}>
          {s.abstract}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <span style={{ fontFamily: pitchMono, fontSize: 12.5, color: pitchC.muted2 }}>
            {s.slides} slides · drawn from
          </span>
          <span style={{ display: 'flex', gap: 5 }}>
            {s.pkgs.map((c, i) => (
              <span key={i} title="research package" style={{
                width: 13, height: 13, borderRadius: 3.5, background: c,
                boxShadow: `0 0 0 1px ${c}33`,
              }} />
            ))}
          </span>
          <span style={{ fontFamily: pitchMono, fontSize: 12.5, color: pitchC.muted2 }}>
            {s.pkgs.length} {s.pkgs.length === 1 ? 'package' : 'packages'}
          </span>
        </div>
      </div>
    </div>
  );
}

window.SlideStoryboard = SlideStoryboard;
