// Slide 1 — Real chat-panel cascade.
// Matches the actual product UI: chat panel on the left (header bar,
// user bubble, tool-call stack, agent answer), Research Overview-style
// sidebar on the right that updates as the pipeline runs.

const { useState: s1use, useEffect: s1eff, useRef: s1ref } = React;
const {
  ToolCallCard, Typewriter, CitationChip, ChatBubble, AppChatPanel,
  pitchC, pitchMono, Reveal,
} = window;

// Each step's "View" pill becomes available once it's `done`.
// `phase` labels the analyst loop; `model` shows which Claude model the
// orchestrator routes that step to.
const SCRIPT = [
  { id: 'orch',    phase: 'Orient',      name: 'Orient · scope the question',  sub: 'route → research · time → P11-13 Q4 25/26', model: 'sonnet-4-6', start:  300, dur:  900 },
  { id: 'plan',    phase: 'Plan',        name: 'Plan the investigation',       sub: '4 angles · 7 hypotheses',                   model: 'sonnet-4-6', start: 1500, dur: 1100 },
  { id: 'run',     phase: 'Investigate', name: 'Investigate · run research',   sub: '7 queries via MCP → DuckDB · 148.1s',       model: 'haiku-4-5',  start: 3000, dur: 2400 },
  { id: 'gate',    phase: 'Assess',      name: 'Assess the evidence',          sub: 'Enough evidence? Go deeper, or synthesize.',                     start: 5600, dur:  900 },
  { id: 'consol',  phase: 'Assess',      name: 'Consolidate blocks',           sub: '2 hero charts assembled',                                        start: 6700, dur:  900 },
  { id: 'answer',  phase: 'Synthesize',  name: 'Synthesize the answer',        sub: '5 claims · 5 citations · 0 hallucinated',   model: 'opus-4-8',   start: 7800, dur: 1400 },
];

const TOTAL_MS = 9400;

const QUESTION = "Are we known more for furniture or homeware? Where should we focus to build presence?";

const ANSWER_TEXT = [
  { kind: 'text', value: 'Habitat is modestly better known for homeware than furniture, and the gap is wider — and more actionable — on consideration and perception. On category association, 60% of consumers link Habitat to homeware vs 53% to furniture' },
  { kind: 'cite', n: 1 },
  { kind: 'text', value: '. But the bigger signal is conversion: homeware future consideration sits at 22% against just 9% for furniture' },
  { kind: 'cite', n: 2 },
  { kind: 'text', value: '. Habitat captures 4.2% of last-homeware-purchases vs 3.9% in furniture' },
  { kind: 'cite', n: 3 },
  { kind: 'text', value: ' — in a much more concentrated category where IKEA (20%) and Dunelm (14%) dominate. Recommendation: double down on homeware to compound existing traction.' },
];

function Slide1Cascade() {
  const [t, setT] = s1use(0);
  const [questionDone, setQuestionDone] = s1use(false);
  const [phase, setPhase] = s1use('intro');
  const startedAt = s1ref(null);
  const rafRef = s1ref(null);

  s1eff(() => {
    if (!questionDone) return;
    setPhase('running');
    startedAt.current = performance.now();
    const tick = (now) => {
      const elapsed = now - startedAt.current;
      setT(elapsed);
      if (elapsed >= TOTAL_MS) { setPhase('answer'); return; }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [questionDone]);

  function stateAt(step) {
    if (t < step.start) return 'queued';
    if (t < step.start + step.dur) return 'running';
    return 'done';
  }
  const visible = (step) => t >= step.start - 250;
  const showAnswer = phase === 'answer' || phase === 'done';

  // Sidebar values update as tool calls complete
  const research =
    stateAt(SCRIPT[2]) === 'done' ? '7 packages' :
    stateAt(SCRIPT[2]) === 'running' ? 'Running…' :
    stateAt(SCRIPT[1]) === 'done' ? '7 planned' :
    'Pending';
  const storyboard =
    stateAt(SCRIPT[3]) === 'done' ? '4 sections' :
    stateAt(SCRIPT[3]) === 'running' ? 'Building…' :
    'Pending';
  const deck =
    showAnswer ? 'Ready' :
    stateAt(SCRIPT[4]) === 'running' ? 'Synthesizing…' :
    '—';

  return (
    <div style={{
      flex: 1, minHeight: 0,
      display: 'grid',
      gridTemplateColumns: '1.45fr 1fr',
      gap: 24,
      marginTop: 22,
    }}>

      <AppChatPanel title="Habitat — Furniture vs Homeware" dataset="Habitat">
        <ChatBubble side="user">
          <Typewriter
            text={QUESTION}
            speed={16}
            startDelay={150}
            onDone={() => setQuestionDone(true)}
          />
        </ChatBubble>

        {/* Tool call stack — always visible, scrollable when the answer arrives
            so the full trail stays reachable below the streamed answer */}
        <div style={{
          display: 'flex', flexDirection: 'column', gap: 10,
          flex: showAnswer ? '0 1 auto' : 1,
          maxHeight: showAnswer ? 290 : 'none',
          minHeight: 0,
          overflowY: 'auto',
          paddingRight: 6,
          marginRight: -6,
        }}>
          {SCRIPT.map((step) => {
            if (!visible(step)) return null;
            const st = stateAt(step);
            if (step.id === 'gate') {
              return (
                <div key={step.id}>
                  <AnalystThought state={st} />
                </div>
              );
            }
            return (
              <div key={step.id}>
                <ToolCallCard
                  name={step.name}
                  sub={st === 'queued' ? null : step.sub}
                  state={st}
                  viewLabel="View"
                  model={st === 'queued' ? null : step.model}
                />
              </div>
            );
          })}
        </div>

        {showAnswer && (
          <div style={{
            paddingTop: 4,
            color: pitchC.ink,
            flex: 1,
            minHeight: 0,
            overflow: 'hidden',
          }}>
            <AnswerStream parts={ANSWER_TEXT} />
          </div>
        )}
      </AppChatPanel>

      {/* Right sidebar — research overview */}
      <OverviewSidebar
        research={research}
        dataset="Habitat"
        storyboard={storyboard}
        deck={deck}
        elapsed={t}
        questionDone={questionDone}
        answerDone={showAnswer}
      />

    </div>
  );
}

function OverviewSidebar({ research, dataset, storyboard, deck, elapsed, questionDone, answerDone }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 14,
      minHeight: 0,
    }}>
      <div style={{
        fontSize: 18, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.005,
        marginBottom: -4,
      }}>Research Overview</div>

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
      }}>
        <OverviewCard label="RESEARCH"   value={research}   accent="dynamic" state={research} />
        <OverviewCard label="DATASET"    value={dataset}    accent="static" />
        <OverviewCard label="STORYBOARD" value={storyboard} accent="dynamic" state={storyboard} />
        <OverviewCard label="DECK"       value={deck}       accent="dynamic" state={deck} />
      </div>

      {/* Live metrics */}
      <div style={{
        background: '#fff',
        border: `1px solid ${pitchC.hair}`,
        borderRadius: 12,
        padding: '14px 18px',
        flex: 1, minHeight: 0,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          fontSize: 13, fontWeight: 600, letterSpacing: 1.6,
          textTransform: 'uppercase', color: pitchC.muted2,
          fontFamily: pitchMono, marginBottom: 12,
        }}>Pipeline</div>

        <Metric k="status"        v={!questionDone ? 'idle' : answerDone ? 'completed' : 'running'} accent={!questionDone ? pitchC.muted2 : answerDone ? pitchC.moss : pitchC.sea} />
        <Metric k="elapsed"       v={questionDone ? `${(elapsed / 1000).toFixed(1)}s` : '—'} />
        <Metric k="queries"       v={answerDone ? '7' : (elapsed > 3000 ? `${Math.min(7, Math.floor((elapsed - 3000) / 350))}` : '0')} />
        <Metric k="citations"     v={answerDone ? '5' : '—'} />
        <Metric k="models"        v="opus · sonnet · haiku" accent={pitchC.purple} />
        <Metric k="hallucinated"  v={answerDone ? '0' : '—'} accent={answerDone ? pitchC.moss : undefined} />

        <div style={{
          marginTop: 'auto',
          paddingTop: 14,
          borderTop: `1px solid ${pitchC.hair}`,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <span style={{
            width: 9, height: 9, borderRadius: '50%',
            background: answerDone ? pitchC.moss : pitchC.sea,
            animation: !answerDone && questionDone ? 'pulse-dot 1.1s ease-in-out infinite' : 'none',
          }} />
          <span style={{
            fontSize: 14, color: pitchC.muted, fontFamily: pitchMono,
          }}>
            {answerDone ? 'every claim traces to evidence' : questionDone ? 'orchestrating tool calls…' : 'awaiting question'}
          </span>
        </div>
      </div>
    </div>
  );
}

function OverviewCard({ label, value, accent, state }) {
  const pending = state === 'Pending' || value === '—';
  return (
    <div style={{
      background: '#fff',
      border: `1px solid ${pitchC.hair}`,
      borderRadius: 12,
      padding: '14px 16px',
    }}>
      <div style={{
        fontSize: 12, fontWeight: 600, letterSpacing: 1.6,
        textTransform: 'uppercase', color: pitchC.muted2,
        fontFamily: pitchMono,
      }}>{label}</div>
      <div style={{
        fontSize: 22, fontWeight: 600, marginTop: 6,
        color: pending ? pitchC.muted2 : pitchC.ink,
        letterSpacing: -0.01,
        fontFamily: 'Hanken Grotesk, sans-serif',
      }}>{value}</div>
    </div>
  );
}

function Metric({ k, v, accent }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '120px 1fr',
      fontFamily: pitchMono,
      fontSize: 14,
      padding: '5px 0',
    }}>
      <span style={{ color: pitchC.muted2 }}>{k}</span>
      <span style={{ color: accent || pitchC.ink, textAlign: 'right', fontWeight: 600 }}>{v}</span>
    </div>
  );
}

// Stream the answer text token-by-token with citations becoming chips.
// ─────────────────────────────────────────────────────────────────────
// AnalystThought — the "thinking like an analyst" card. Renders for the
// Quality gate step. Three questions cycle through while running; when
// done, shows the verdict (continue / synthesize) with quiet authority.
// ─────────────────────────────────────────────────────────────────────

const ANALYST_QUESTIONS = [
  'Do we have enough evidence to answer?',
  'Are there gaps a stakeholder would push back on?',
  'Is the methodology airtight?',
];

function AnalystThought({ state }) {
  const [qIdx, setQIdx] = s1use(0);
  const running = state === 'running';
  const done = state === 'done';

  // Cycle the questions while running
  s1eff(() => {
    if (!running) return;
    const t = setInterval(() => {
      setQIdx((i) => (i + 1) % ANALYST_QUESTIONS.length);
    }, 700);
    return () => clearInterval(t);
  }, [running]);

  const accent = done ? pitchC.moss : pitchC.orange;
  const accentBg = done ? '#f3fbf7' : '#fff7f3';
  const accentBd = done ? `${pitchC.moss}33` : '#ffd9c9';

  return (
    <div style={{
      position: 'relative',
      padding: '14px 18px 14px 56px',
      background: accentBg,
      border: `1px solid ${accentBd}`,
      borderRadius: 12,
      overflow: 'hidden',
    }}>
      {/* Brain / thought icon */}
      <div style={{
        position: 'absolute',
        left: 14, top: 14,
        width: 28, height: 28, borderRadius: '50%',
        background: accent,
        color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <svg width="15" height="15" 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: 11.5, fontWeight: 700,
        letterSpacing: 1.6, textTransform: 'uppercase',
        color: accent,
        marginBottom: 4,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span>Thinking like an analyst</span>
        {running && (
          <span style={{ display: 'inline-flex', gap: 3 }}>
            {[0, 1, 2].map(i => (
              <span key={i} style={{
                width: 4, height: 4, borderRadius: '50%',
                background: accent,
                opacity: 0.5,
                animation: `pulse-dot 1s ${i * 0.18}s ease-in-out infinite`,
              }} />
            ))}
          </span>
        )}
      </div>

      <div style={{
        fontSize: 17,
        lineHeight: 1.3,
        color: pitchC.ink,
        fontWeight: 500,
        letterSpacing: -0.005,
        fontStyle: 'italic',
        minHeight: 22,
      }}>
        {running && (
          <span key={qIdx} style={{
            display: 'inline-block',
            animation: 'fade-up 280ms ease',
          }}>
            "{ANALYST_QUESTIONS[qIdx]}"
          </span>
        )}
        {done && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontStyle: 'normal', color: pitchC.ink, fontWeight: 500,
          }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 18, height: 18, borderRadius: '50%',
              background: pitchC.moss, color: '#fff',
            }}>
              <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8.5l3 3 7-7"/></svg>
            </span>
            <span>Coverage sufficient — synthesize.</span>
          </span>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Stream the answer text in word-chunks, with citations becoming clickable as
// they appear. Just visual flair — no real interaction needed in this slide.
// ─────────────────────────────────────────────────────────────────────

function AnswerStream({ parts }) {
  const tokens = [];
  parts.forEach((p) => {
    if (p.kind === 'text') {
      const words = p.value.split(/(\s+)/);
      for (let j = 0; j < words.length; j += 4) {
        tokens.push({ kind: 'text', value: words.slice(j, j + 4).join('') });
      }
    } else {
      tokens.push(p);
    }
  });
  const [n, setN] = s1use(0);
  s1eff(() => {
    if (n >= tokens.length) return;
    const t = setTimeout(() => setN(n + 1), 32);
    return () => clearTimeout(t);
  }, [n, tokens.length]);

  return (
    <div style={{
      fontSize: 19, lineHeight: 1.5, color: pitchC.ink,
    }}>
      {tokens.slice(0, n).map((tk, i) => {
        if (tk.kind === 'text') return <span key={i}>{tk.value}</span>;
        return <CitationChip key={i} n={tk.n} active={false} onClick={() => {}} />;
      })}
      {n < tokens.length && (
        <span style={{
          display: 'inline-block',
          width: 2, height: '0.95em',
          background: pitchC.ink,
          marginLeft: 2,
          transform: 'translateY(2px)',
          animation: 'blink-caret 1s steps(1) infinite',
        }} />
      )}
    </div>
  );
}

window.Slide1Cascade = Slide1Cascade;
