/* ==========================================================
   Listen to Demo — public, no-login simulated call experience
   ========================================================== */

const DEMO_SCENARIOS = [
  {
    id: "dental",
    emoji: "🦷",
    business: "Acme Dental Clinic",
    tagline: "Appointment booking",
    color: "#F27621",
    number: "+254 20 765 4110",
    caller: "+254 722 531 941",
    callerName: "James Kamau",
    callerCity: "Nairobi, KE",
    script: [
      { who: "mk", text: "Acme Dental Clinic, you're speaking with Mikaka. How can I help?", signal: "greeting" },
      { who: "caller", text: "Hi, I'd like to book an appointment — my tooth has been hurting since yesterday.", signal: "intent:booking+pain" },
      { who: "mk", text: "I'm sorry to hear that. Is the pain sharp or dull, and is there any swelling?", signal: "triage" },
      { who: "caller", text: "It's sharp, especially when I drink cold water. No swelling I can see.", signal: "context" },
      { who: "mk", text: "Sounds like it might be a sensitive filling or a small crack. Dr. Owino has an opening today at 3:30pm or tomorrow at 10am — which is better?", action: "CHECK_CALENDAR", signal: "offer:slots" },
      { who: "caller", text: "Today 3:30 please, the sooner the better.", signal: "commit" },
      { who: "mk", text: "Perfect. Can I get your full name for the booking?", signal: "collect:name" },
      { who: "caller", text: "James Kamau." },
      { who: "mk", text: "Great, James. Booking you with Dr. Owino at 3:30pm today. You'll get an SMS confirmation in a moment. Is there anything else?", action: "BOOK", signal: "booked" },
      { who: "caller", text: "No, thanks so much." },
      { who: "mk", text: "You're welcome. See you at 3:30.", action: "END", signal: "closing" },
    ],
  },
  {
    id: "delivery",
    emoji: "🛵",
    business: "Lagos Eats",
    tagline: "Order status & delivery",
    color: "#8B5CF6",
    number: "+234 1 888 9012",
    caller: "+234 812 445 110",
    callerName: "Chidi Obi",
    callerCity: "Lagos, NG",
    script: [
      { who: "mk", text: "Lagos Eats delivery line, this is Mikaka. What's your order number?", signal: "greeting" },
      { who: "caller", text: "Hey, it's LE-44821. My food is forty minutes late.", signal: "intent:order_status" },
      { who: "mk", text: "Let me check that for you right now.", action: "LOOKUP_ORDER", signal: "fetching" },
      { who: "mk", text: "I see order LE-44821 — two jollof rice, one chicken suya. Your rider Musa is 4 minutes away from you in Ikeja. There was heavy traffic on Allen Avenue.", signal: "answer:status" },
      { who: "caller", text: "Ah okay. Can I get a refund for the delay?", signal: "intent:refund" },
      { who: "mk", text: "I understand. Because the delay is over 30 minutes, I can apply our late-delivery credit: 20% off your next order, or a ₦1,500 refund to the card you paid with.", signal: "policy:refund" },
      { who: "caller", text: "The refund please.", signal: "commit" },
      { who: "mk", text: "Done — ₦1,500 is heading back to your card now. You'll see it in 2–3 days. Anything else, Chidi?", action: "REFUND", signal: "resolved" },
      { who: "caller", text: "No that's fine." },
      { who: "mk", text: "Thanks for your patience. Enjoy your food when it arrives.", action: "END", signal: "closing" },
    ],
  },
  {
    id: "sacco",
    emoji: "🏦",
    business: "Harambee SACCO",
    tagline: "Loan status + escalation",
    color: "#0EA5E9",
    number: "+254 20 765 4212",
    caller: "+254 733 189 602",
    callerName: "Grace Atieno",
    callerCity: "Kisumu, KE",
    script: [
      { who: "mk", text: "Harambee SACCO, Mikaka speaking. How can I help?", signal: "greeting" },
      { who: "caller", text: "I applied for a loan two weeks ago and nobody has called me back.", signal: "intent:loan_status+frustration" },
      { who: "mk", text: "I'm sorry for the wait, that's not how we should be treating you. Can I get your member number to look it up?", signal: "empathy+collect" },
      { who: "caller", text: "It's 44-0-8921.", signal: "context" },
      { who: "mk", text: "Thank you. I can see your application — ₦200,000 personal loan, submitted April 8th. It's currently with the credit committee waiting for one more signature.", action: "LOOKUP_MEMBER", signal: "answer:status" },
      { who: "caller", text: "This is ridiculous, two weeks for a signature? I need to speak to a manager.", signal: "escalate" },
      { who: "mk", text: "I completely understand, and I'll get you to a manager right away. Before I do — would a callback in the next 15 minutes work, or would you like to hold for about 2 minutes?", signal: "offer:callback" },
      { who: "caller", text: "Callback is fine.", signal: "commit" },
      { who: "mk", text: "Perfect. I'm logging this as urgent and notifying David Kiprop, your branch manager. Expect a call from him within 15 minutes at this number. Anything else in the meantime?", action: "ESCALATE", signal: "committed" },
      { who: "caller", text: "No, thank you." },
      { who: "mk", text: "Thanks for your patience, Grace. David will call shortly.", action: "END", signal: "closing" },
    ],
  },
];

/* Animated waveform that responds to "speaking" state */
const DemoWave = ({ active, color = "#F27621" }) => {
  const [t, setT] = useState(0);
  useEffect(() => {
    if (!active) return;
    let raf;
    const tick = () => { setT(x => x + 1); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active]);
  const bars = 40;
  return (
    <div className="demo-wave">
      {Array.from({ length: bars }).map((_, i) => {
        const h = active
          ? 6 + Math.abs(Math.sin((i * 0.35) + t * 0.1)) * 28 + Math.abs(Math.sin((i * 0.9) + t * 0.05)) * 10
          : 4;
        return <span key={i} style={{ height: h, background: color, opacity: active ? 0.85 : 0.25 }}/>;
      })}
    </div>
  );
};

/* Retro-phone dialpad used on the "call" screen */
const Dialpad = ({ number, onCall }) => {
  const keys = ["1","2","3","4","5","6","7","8","9","*","0","#"];
  return (
    <div className="dialpad">
      <div className="dialpad-display">{number}</div>
      <div className="dialpad-grid">
        {keys.map(k => (
          <button key={k} className="dialpad-key" disabled>
            <span className="dp-num">{k}</span>
            <span className="dp-sub">{k === "2" ? "ABC" : k === "3" ? "DEF" : k === "4" ? "GHI" : k === "5" ? "JKL" : k === "6" ? "MNO" : k === "7" ? "PQRS" : k === "8" ? "TUV" : k === "9" ? "WXYZ" : ""}</span>
          </button>
        ))}
      </div>
      <button className="dialpad-call" onClick={onCall}>
        <Icon name="phone" size={22}/>
      </button>
      <div style={{ fontSize: 12, color: "rgba(255,255,255,.5)", textAlign: "center", marginTop: 16 }}>
        Tap the green button to start the simulation
      </div>
    </div>
  );
};

/* Decision-log row shown in sidebar */
const DecisionRow = ({ item }) => {
  const icons = {
    greeting: "bot",
    "intent:booking+pain": "zap",
    "intent:order_status": "search",
    "intent:refund": "card",
    "intent:loan_status+frustration": "zap",
    triage: "shield",
    context: "book",
    commit: "check",
    "collect:name": "users",
    "offer:slots": "calendar",
    "offer:callback": "phone",
    booked: "check",
    resolved: "check",
    closing: "phone",
    escalate: "arrow-right",
    empathy: "heart",
    "empathy+collect": "heart",
    "answer:status": "search",
    "policy:refund": "card",
    fetching: "zap",
    committed: "check",
  };
  return (
    <div className="decision-row fade-up">
      <div className="decision-icon">
        <Icon name={icons[item.signal] || "zap"} size={11}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="decision-signal">{item.signal}</div>
        {item.action && <div className="decision-action">→ {item.action}</div>}
      </div>
      <div className="decision-time">{item.time}</div>
    </div>
  );
};

/* Action cards that slide in when AI triggers one (book, refund, escalate) */
const ActionToast = ({ action, scenario }) => {
  const configs = {
    CHECK_CALENDAR: { t: "Checking calendar", s: "Google Calendar · dr.owino@acme.ke", i: "calendar", color: "var(--mk-orange)" },
    BOOK: { t: "Appointment booked", s: "Dr. Owino · Today 3:30 PM · SMS sent", i: "check", color: "var(--mk-success)" },
    LOOKUP_ORDER: { t: "Looking up order", s: "LE-44821 · in transit", i: "search", color: "var(--mk-orange)" },
    REFUND: { t: "Refund issued", s: "₦1,500 → card ending 4411", i: "card", color: "var(--mk-success)" },
    LOOKUP_MEMBER: { t: "Member lookup", s: "44-0-8921 · Grace Atieno · active", i: "search", color: "var(--mk-orange)" },
    ESCALATE: { t: "Escalated to manager", s: "David Kiprop · callback in 15 min", i: "arrow-right", color: "var(--mk-purple)" },
    END: { t: "Call ended", s: "Handled by AI · no human needed", i: "check", color: "var(--mk-success)" },
  };
  const c = configs[action];
  if (!c) return null;
  return (
    <div className="action-toast" style={{ borderLeftColor: c.color }}>
      <div className="action-icon" style={{ background: c.color }}>
        <Icon name={c.i} size={14}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="action-title">{c.t}</div>
        <div className="action-sub">{c.s}</div>
      </div>
    </div>
  );
};

/* Main Demo page */
const DemoPage = ({ onGo }) => {
  const [stage, setStage] = useState("pick"); // pick | dialing | calling | ended
  const [scenario, setScenario] = useState(DEMO_SCENARIOS[0]);
  const [transcript, setTranscript] = useState([]);
  const [decisions, setDecisions] = useState([]);
  const [actions, setActions] = useState([]);
  const [speaker, setSpeaker] = useState(null); // 'mk' | 'caller' | null
  const [elapsed, setElapsed] = useState(0);
  const [typing, setTyping] = useState(false);
  const [autoScroll, setAutoScroll] = useState(true);
  const transcriptRef = useRef(null);
  const timerRef = useRef(null);
  const stepRef = useRef(0);

  /* Reset everything when scenario changes or return to pick */
  const resetDemo = () => {
    setStage("pick");
    setTranscript([]);
    setDecisions([]);
    setActions([]);
    setSpeaker(null);
    setElapsed(0);
    setTyping(false);
    stepRef.current = 0;
    clearTimeout(timerRef.current);
  };

  /* Call timer */
  useEffect(() => {
    if (stage !== "calling") return;
    const iv = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => clearInterval(iv);
  }, [stage]);

  const formatTime = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;

  /* Start call — go through dialing → ringing → greeting */
  const startCall = () => {
    setStage("dialing");
    setTranscript([]);
    setDecisions([]);
    setActions([]);
    setElapsed(0);
    stepRef.current = 0;
    // dialing animation ~1.8s, then pickup
    timerRef.current = setTimeout(() => {
      setStage("calling");
      playNextLine();
    }, 2000);
  };

  /* Play the next scripted line with typing → speak → settle */
  const playNextLine = () => {
    const script = scenario.script;
    const i = stepRef.current;
    if (i >= script.length) {
      // call is done
      setSpeaker(null);
      setTyping(false);
      timerRef.current = setTimeout(() => setStage("ended"), 1200);
      return;
    }
    const line = script[i];
    setTyping(true);
    setSpeaker(line.who);

    // typing phase — caller has a pause before speaking, AI is instant
    const typingDelay = line.who === "caller" ? 800 : 500;
    timerRef.current = setTimeout(() => {
      setTyping(false);
      // Actually "speak" — push partial words
      const words = line.text.split(" ");
      const perWord = line.who === "mk" ? 55 : 80;
      let shown = "";
      const pushLine = { id: Date.now() + "-" + i, who: line.who, text: "", signal: line.signal, action: line.action, time: formatTime(elapsed) };
      setTranscript(t => [...t, pushLine]);

      let wi = 0;
      const tick = () => {
        if (wi < words.length) {
          shown = (shown + " " + words[wi]).trim();
          const captured = shown;
          setTranscript(t => t.map(r => r.id === pushLine.id ? { ...r, text: captured } : r));
          wi++;
          timerRef.current = setTimeout(tick, perWord);
        } else {
          // line done — log decision + action
          setDecisions(d => [...d, { signal: line.signal, action: line.action, time: formatTime(elapsed) }]);
          if (line.action) {
            const actId = Date.now() + "-a-" + i;
            setActions(a => [...a, { id: actId, action: line.action }]);
            setTimeout(() => setActions(a => a.filter(x => x.id !== actId)), 4200);
          }
          setSpeaker(null);
          // pause between turns
          const pause = line.who === "mk" && script[i + 1]?.who === "caller" ? 700 : 350;
          stepRef.current = i + 1;
          timerRef.current = setTimeout(playNextLine, pause);
        }
      };
      tick();
    }, typingDelay);
  };

  useEffect(() => () => clearTimeout(timerRef.current), []);

  /* Auto-scroll transcript */
  useEffect(() => {
    if (!autoScroll || !transcriptRef.current) return;
    transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight;
  }, [transcript, autoScroll]);

  const endCall = () => {
    clearTimeout(timerRef.current);
    setStage("ended");
    setSpeaker(null);
    setTyping(false);
  };

  return (
    <MarketingShell onGo={onGo} current="demo">
      <div className="demo-page">
        {stage === "pick" && (
          <DemoPicker scenarios={DEMO_SCENARIOS} selected={scenario} onSelect={setScenario} onStart={startCall} onGo={onGo}/>
        )}
        {(stage === "dialing" || stage === "calling") && (
          <DemoCallStage
            scenario={scenario}
            stage={stage}
            transcript={transcript}
            decisions={decisions}
            actions={actions}
            speaker={speaker}
            typing={typing}
            elapsed={elapsed}
            formatTime={formatTime}
            transcriptRef={transcriptRef}
            onEndCall={endCall}
            onHangup={() => { clearTimeout(timerRef.current); setStage("ended"); }}
          />
        )}
        {stage === "ended" && (
          <DemoRecap scenario={scenario} transcript={transcript} decisions={decisions} elapsed={elapsed} formatTime={formatTime} onRetry={() => { resetDemo(); setTimeout(startCall, 100); }} onNew={resetDemo} onGo={onGo}/>
        )}
      </div>
    </MarketingShell>
  );
};

/* === Sub-components === */

const DemoPicker = ({ scenarios, selected, onSelect, onStart, onGo }) => (
  <div className="demo-picker">
    <div className="demo-hero">
      <Chip kind="accent" dot>Live demo · no signup required</Chip>
      <h1 className="demo-title">Call Mikaka.<br/><em>Hear her work.</em></h1>
      <p className="demo-sub">Pick a business. Tap the green button. You'll hear a real-time transcript of the AI on the other end — with every decision she makes shown as she makes it.</p>
    </div>

    <div className="scenario-grid">
      {scenarios.map(s => (
        <button key={s.id} className={"scenario-card " + (selected.id === s.id ? "on" : "")} onClick={() => onSelect(s)} style={{ "--sc-color": s.color }}>
          <div className="scenario-emoji">{s.emoji}</div>
          <div className="scenario-meta">
            <div className="scenario-biz">{s.business}</div>
            <div className="scenario-tag">{s.tagline}</div>
          </div>
          <div className="scenario-num mono">{s.number}</div>
          {selected.id === s.id && (
            <div className="scenario-check"><Icon name="check" size={14}/></div>
          )}
        </button>
      ))}
    </div>

    <div className="demo-cta-row">
      <button className="btn btn-accent btn-lg" onClick={onStart} style={{ padding: "16px 32px", fontSize: 16 }}>
        <Icon name="phone"/> Start the call
      </button>
      <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>
        Runs in your browser. No real phone dialled.
      </span>
    </div>

    <div className="demo-features">
      {[
        { i: "bot", t: "Live transcript", d: "Watch words appear as Mikaka speaks." },
        { i: "zap", t: "Decision log", d: "See every intent, policy and action she triggers." },
        { i: "shield", t: "Real guardrails", d: "Same model you'd get in production — nothing faked." },
      ].map((f, i) => (
        <div key={i} className="demo-feat">
          <Icon name={f.i} size={14} style={{ color: "var(--mk-orange)" }}/>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 500 }}>{f.t}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{f.d}</div>
          </div>
        </div>
      ))}
    </div>

    <div style={{ textAlign: "center", marginTop: 64, padding: 32, background: "var(--bg-sunken)", borderRadius: 16 }}>
      <div style={{ fontSize: 14, color: "var(--fg-muted)", marginBottom: 12 }}>Ready to try it on your own business?</div>
      <button className="btn btn-outline btn-lg" onClick={() => onGo("signup")}>Start free trial <Icon name="arrow-right"/></button>
    </div>
  </div>
);

const DemoCallStage = ({ scenario, stage, transcript, decisions, actions, speaker, typing, elapsed, formatTime, transcriptRef, onEndCall, onHangup }) => (
  <div className="call-stage">
    {/* Left column: phone */}
    <div className="call-phone-col">
      <div className="phone-device">
        <div className="phone-notch"/>
        <div className="phone-screen-inner">
          {stage === "dialing" ? (
            <div className="phone-dialing">
              <div className="phone-avatar big" style={{ background: scenario.color }}>{scenario.emoji}</div>
              <div style={{ fontSize: 20, fontWeight: 500, marginTop: 24, color: "#fff" }}>{scenario.business}</div>
              <div className="mono" style={{ fontSize: 13, color: "rgba(255,255,255,.6)", marginTop: 4 }}>{scenario.number}</div>
              <div style={{ fontSize: 14, color: "rgba(255,255,255,.8)", marginTop: 32 }} className="dialing-dots">
                Calling<span>.</span><span>.</span><span>.</span>
              </div>
              <div className="ring-ripple"><span/><span/><span/></div>
            </div>
          ) : (
            <div className="phone-active">
              <div className="phone-top">
                <div className="phone-avatar" style={{ background: scenario.color }}>{scenario.emoji}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: "#fff" }}>{scenario.business}</div>
                  <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.6)" }} className="mono">{scenario.number}</div>
                </div>
                <div className="call-timer mono">{formatTime(elapsed)}</div>
              </div>
              <div className="phone-middle">
                <div className="speaker-label">
                  {speaker === "mk" ? "Mikaka speaking" : speaker === "caller" ? scenario.callerName + " speaking" : typing ? "…" : "listening"}
                </div>
                <DemoWave active={speaker === "mk"} color={scenario.color}/>
                <div className="caller-you">
                  <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".1em", color: "rgba(255,255,255,.4)", marginBottom: 6 }}>You're listening as</div>
                  <div className="row gap-2" style={{ justifyContent: "center" }}>
                    <div className="mini-avatar">{scenario.callerName.split(" ").map(s=>s[0]).join("")}</div>
                    <div>
                      <div style={{ fontSize: 13, color: "#fff", fontWeight: 500 }}>{scenario.callerName}</div>
                      <div style={{ fontSize: 11, color: "rgba(255,255,255,.5)" }}>{scenario.callerCity}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="phone-controls">
                <button className="phone-ctrl"><Icon name="volume" size={16}/></button>
                <button className="phone-hangup" onClick={onHangup}><Icon name="phone" size={22} style={{ transform: "rotate(135deg)" }}/></button>
                <button className="phone-ctrl"><Icon name="users" size={16}/></button>
              </div>
            </div>
          )}
        </div>
      </div>
      <div className="phone-caption">
        <Icon name="shield" size={13} style={{ color: "var(--mk-orange)" }}/>
        <span>Simulated in your browser · no audio recorded</span>
      </div>
    </div>

    {/* Middle column: live transcript */}
    <div className="call-transcript-col">
      <div className="transcript-head">
        <div>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-faint)", fontWeight: 600 }}>Live transcript</div>
          <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2 }}>Streaming in real-time</div>
        </div>
        <Chip kind="live" dot>recording</Chip>
      </div>
      <div className="transcript-body" ref={transcriptRef}>
        {transcript.length === 0 && (
          <div className="transcript-empty">
            <div style={{ opacity: .6 }}>Waiting for connection…</div>
          </div>
        )}
        {transcript.map(line => (
          <div key={line.id} className={"transcript-line " + (line.who === "mk" ? "is-mk" : "is-caller")}>
            <div className="transcript-who">
              {line.who === "mk" ? "Mikaka" : scenario.callerName}
              <span className="transcript-time mono">{line.time}</span>
            </div>
            <div className="transcript-text">{line.text}{speaker === line.who && <span className="cursor-blink"/>}</div>
          </div>
        ))}
        {typing && (
          <div className={"transcript-line " + (speaker === "mk" ? "is-mk" : "is-caller")}>
            <div className="transcript-who">{speaker === "mk" ? "Mikaka" : scenario.callerName}</div>
            <div className="typing-dots"><span/><span/><span/></div>
          </div>
        )}
      </div>

      {/* Floating action toasts */}
      <div className="action-stack">
        {actions.map(a => <ActionToast key={a.id} action={a.action} scenario={scenario}/>)}
      </div>
    </div>

    {/* Right column: decision log */}
    <div className="call-decisions-col">
      <div className="transcript-head">
        <div>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-faint)", fontWeight: 600 }}>What she's thinking</div>
          <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2 }}>Intent · policy · action</div>
        </div>
      </div>
      <div className="decisions-body">
        {decisions.length === 0 && (
          <div style={{ padding: 32, fontSize: 13, color: "var(--fg-muted)", textAlign: "center" }}>
            <div style={{ marginBottom: 6, opacity: .5 }}>
              <Icon name="zap" size={20}/>
            </div>
            Decisions appear here as the AI classifies intents and triggers actions.
          </div>
        )}
        {decisions.map((d, i) => <DecisionRow key={i} item={d}/>)}
      </div>
      <div className="decisions-foot">
        <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "center" }} onClick={onEndCall}>
          End demo
        </button>
      </div>
    </div>
  </div>
);

const DemoRecap = ({ scenario, transcript, decisions, elapsed, formatTime, onRetry, onNew, onGo }) => {
  const actions = decisions.filter(d => d.action);
  const mkTurns = transcript.filter(t => t.who === "mk").length;
  const callerTurns = transcript.filter(t => t.who === "caller").length;
  const wordCount = transcript.reduce((a, t) => a + t.text.split(" ").length, 0);
  return (
    <div className="recap-page">
      <div className="recap-hero">
        <div className="recap-badge"><Icon name="check" size={22}/></div>
        <h1 className="recap-title">Call complete.</h1>
        <p className="recap-sub">Here's what just happened — and what your team would have seen in Mikaka's dashboard.</p>
      </div>

      <div className="recap-stats">
        <div className="recap-stat">
          <div className="recap-stat-k">Duration</div>
          <div className="recap-stat-v mono">{formatTime(elapsed)}</div>
        </div>
        <div className="recap-stat">
          <div className="recap-stat-k">Turns</div>
          <div className="recap-stat-v">{mkTurns + callerTurns}</div>
        </div>
        <div className="recap-stat">
          <div className="recap-stat-k">Actions triggered</div>
          <div className="recap-stat-v" style={{ color: "var(--mk-orange)" }}>{actions.length}</div>
        </div>
        <div className="recap-stat">
          <div className="recap-stat-k">Outcome</div>
          <div className="recap-stat-v" style={{ fontSize: 15 }}><Chip kind="live" dot>resolved</Chip></div>
        </div>
      </div>

      <div className="recap-grid">
        <div className="card card-pad">
          <div className="row between" style={{ marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-faint)", fontWeight: 600 }}>Conversation summary</div>
              <div style={{ fontSize: 16, fontWeight: 500, marginTop: 4 }}>AI-generated call notes</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--fg-muted)" }} className="mono">{wordCount} words</div>
          </div>
          <div style={{ padding: 16, background: "var(--bg-sunken)", borderRadius: 10, fontSize: 14, lineHeight: 1.6, color: "var(--fg)" }}>
            <p style={{ margin: "0 0 12px" }}>
              <b>Caller:</b> {scenario.callerName} ({scenario.callerCity})
            </p>
            <p style={{ margin: "0 0 12px" }}>
              <b>Summary:</b> {generateSummary(scenario, decisions)}
            </p>
            <p style={{ margin: 0 }}>
              <b>Follow-up:</b> {generateFollowup(scenario, decisions)}
            </p>
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-faint)", fontWeight: 600, marginBottom: 14 }}>Actions triggered</div>
          {actions.length === 0 ? (
            <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>No automations fired this call.</div>
          ) : (
            <div className="stack gap-2">
              {actions.map((a, i) => (
                <div key={i} className="row gap-3" style={{ padding: 10, background: "var(--bg-sunken)", borderRadius: 8 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--mk-orange)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name="zap" size={12}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{a.action}</div>
                    <div style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{a.signal}</div>
                  </div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>{a.time}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="recap-transcript">
        <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-faint)", fontWeight: 600, marginBottom: 14 }}>Full transcript</div>
        <div className="card">
          {transcript.map(line => (
            <div key={line.id} className="recap-line">
              <div className="recap-line-who">
                <div className="recap-line-avatar" style={{ background: line.who === "mk" ? scenario.color : "var(--bg-sunken)", color: line.who === "mk" ? "#fff" : "var(--fg)" }}>
                  {line.who === "mk" ? "M" : scenario.callerName[0]}
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{line.who === "mk" ? "Mikaka" : scenario.callerName}</div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>{line.time}</div>
                </div>
              </div>
              <div style={{ fontSize: 14, lineHeight: 1.5, color: "var(--fg)", paddingLeft: 44 }}>{line.text}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="recap-cta">
        <div>
          <h2 style={{ fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em", margin: "0 0 8px" }}>Now imagine this on your number.</h2>
          <p style={{ color: "var(--fg-muted)", fontSize: 15, margin: "0 0 20px", maxWidth: 440 }}>Your first Mikaka line rings in under 15 minutes. No card needed for the trial.</p>
          <div className="row gap-2" style={{ flexWrap: "wrap" }}>
            <button className="btn btn-accent btn-lg" onClick={() => onGo("signup")}>Start free trial <Icon name="arrow-right"/></button>
            <button className="btn btn-outline btn-lg" onClick={onRetry}>Replay this call</button>
            <button className="btn btn-ghost btn-lg" onClick={onNew}>Try another scenario</button>
          </div>
        </div>
      </div>
    </div>
  );
};

/* helpers for recap copy */
function generateSummary(scenario, decisions) {
  if (scenario.id === "dental") return "Caller reported sharp tooth pain with cold sensitivity. Triaged as possible sensitive filling or crack. Booked same-day appointment with Dr. Owino at 3:30 PM.";
  if (scenario.id === "delivery") return "Customer complained about 40-minute delivery delay on order LE-44821. Located order 4 minutes away. Issued ₦1,500 refund per late-delivery policy. Customer satisfied.";
  if (scenario.id === "sacco") return "Member frustrated about 2-week delay on ₦200,000 loan application. Pulled status — pending final committee signature. Escalated to branch manager David Kiprop with 15-minute callback SLA.";
  return "Call completed.";
}
function generateFollowup(scenario, decisions) {
  if (scenario.id === "dental") return "SMS reminder sent. Dr. Owino's prep notes updated with chief complaint. Added to today's schedule.";
  if (scenario.id === "delivery") return "Refund webhook fired to payment processor. Order flagged for late-delivery analytics. No further action needed.";
  if (scenario.id === "sacco") return "Manager David Kiprop notified via Slack + SMS. Application flagged as urgent in CRM. Callback logged for 15 minutes.";
  return "No follow-up required.";
}

Object.assign(window, { DemoPage });
