/* ============================================================
   Scenario — "AI thinking out loud"
   Three preset drives. Click Run.
   Stage 1 (SENSE):  contextual signals stream in
   Stage 2 (REASON): LLM reasoning streams token-by-token
   Stage 3 (ASSEMBLE): atomic components fly from the library
                       onto the cabin screen, leaving faint
                       connector lines back to the signals
                       that motivated each one.
   The interesting thing: same machinery, very different UIs
   across the three presets — proves it's combinatorial reasoning,
   not flag-flipping.
   ============================================================ */

/* ---------- Preset drives ---------- */
const SCENARIOS = [
  {
    id: "sara",
    name: "Sara",
    sub: "Night · storm · low fuel · nervous",
    signals: [
      { id: "time", icon: "Moon", label: "20:34, low ambient light" },
      { id: "weather", icon: "Cloud", label: "Heavy rain, trend ↑ next 15min" },
      { id: "fuel", icon: "Fuel", label: "Fuel 12% · 47 km range" },
      { id: "hrv", icon: "Heart", label: "HRV elevated · last 8 min" },
      { id: "drive", icon: "Alert", label: "Irregular braking pattern" },
    ],
    reasoning: [
      "Low light + precipitation → visibility-critical.",
      "Range < distance to next station off-route → range anxiety.",
      "HRV + braking pattern → driver under stress.",
      "Inference: surface fuel proactively, suppress non-critical, calm the field.",
    ],
    /* Each placement: which atomic component, where it goes,
       and which signals motivated it. */
    placements: [
      {
        comp: "header",
        region: "top",
        from: ["time", "weather"],
        note: "Status strip · context summary",
      },
      {
        comp: "navMap",
        region: "left",
        from: ["drive"],
        note: "Navigation · primary task",
      },
      {
        comp: "fuelPOI",
        region: "left",
        from: ["fuel"],
        note: "Stations on route · proactive",
      },
      {
        comp: "alert",
        region: "right",
        from: ["weather"],
        note: "Weather alert · high contrast",
      },
      {
        comp: "fuelMini",
        region: "right",
        from: ["fuel"],
        note: "Fuel widget · prominent",
      },
      {
        comp: "calm",
        region: "right",
        from: ["hrv"],
        note: "Reduced motion · suppressed widgets",
      },
    ],
    summary: "Critical first. Music, calls, and recommendations suppressed.",
  },
  {
    id: "marc",
    name: "Marc",
    sub: "Morning · clear · airport · running late",
    signals: [
      { id: "time", icon: "Sun", label: "07:42, bright daylight" },
      { id: "weather", icon: "Cloud", label: "Clear skies, 12°C" },
      { id: "calendar", icon: "Phone", label: "Flight in 92 min · ZRH" },
      { id: "traffic", icon: "Alert", label: "A1 northbound: heavy traffic" },
      { id: "fuel", icon: "Fuel", label: "Fuel 68% · 290 km range" },
    ],
    reasoning: [
      "Calendar destination matches active route → goal-aware.",
      "Traffic on primary route → ETA risk.",
      "Fuel comfortable → no stop needed.",
      "Inference: surface ETA prominently, suggest reroute, suppress comfort widgets.",
    ],
    placements: [
      {
        comp: "header",
        region: "top",
        from: ["time", "calendar"],
        note: "Status strip · flight countdown",
      },
      {
        comp: "navMap",
        region: "left",
        from: ["calendar"],
        note: "Navigation · airport-aware",
      },
      {
        comp: "reroute",
        region: "left",
        from: ["traffic"],
        note: "Reroute suggestion · saves 11 min",
      },
      {
        comp: "etaBig",
        region: "right",
        from: ["calendar", "traffic"],
        note: "ETA card · prominent",
      },
      {
        comp: "weather",
        region: "right",
        from: ["weather"],
        note: "Weather widget · compact",
      },
      {
        comp: "music",
        region: "right",
        from: [],
        note: "Music · low priority but kept",
      },
    ],
    summary: "Goal-aware. ETA dominates, comfort widgets compressed.",
  },
  {
    id: "lena",
    name: "Lena",
    sub: "Evening · clear · home · relaxed",
    signals: [
      { id: "time", icon: "Moon", label: "19:08, dusk light" },
      { id: "weather", icon: "Cloud", label: "Clear · mild evening" },
      { id: "route", icon: "Nav", label: "Familiar route home · 18 min" },
      { id: "hrv", icon: "Heart", label: "HRV calm · steady" },
      { id: "media", icon: "Music", label: "Podcast paused · 24:18" },
    ],
    reasoning: [
      "Familiar route + calm driver → low cognitive demand.",
      "No safety-critical signals.",
      "Media context present → resume affordance valuable.",
      "Inference: minimal nav, foreground media, allow ambient detail.",
    ],
    placements: [
      {
        comp: "header",
        region: "top",
        from: ["time"],
        note: "Status strip · ambient",
      },
      {
        comp: "navMini",
        region: "left",
        from: ["route"],
        note: "Compact nav · familiar route",
      },
      {
        comp: "scenic",
        region: "left",
        from: ["weather"],
        note: "Ambient · sunset palette",
      },
      {
        comp: "podcast",
        region: "right",
        from: ["media"],
        note: "Resume podcast · prominent",
      },
      {
        comp: "smartHome",
        region: "right",
        from: ["route"],
        note: "Home arrival · suggested actions",
      },
      {
        comp: "weather",
        region: "right",
        from: ["weather"],
        note: "Weather widget · ambient",
      },
    ],
    summary: "Calm route. Media foregrounded, smart-home pre-warmed.",
  },
]

function Scenario() {
  const [pick, setPick] = useState(0)
  const [stage, setStage] = useState(0) // 0 idle, 1 sense, 2 reason, 3 assemble, 4 done
  const [signalIdx, setSignalIdx] = useState(0)
  const [reasonChars, setReasonChars] = useState(0)
  const [placedCount, setPlacedCount] = useState(0)
  const [hovered, setHovered] = useState(null)
  const tRef = useRef([])

  const scenario = SCENARIOS[pick]

  // Cleanup helper
  const clearAll = () => {
    tRef.current.forEach((t) => clearTimeout(t))
    tRef.current = []
  }

  // Reset whenever scenario changes
  useEffect(() => {
    clearAll()
    setStage(0)
    setSignalIdx(0)
    setReasonChars(0)
    setPlacedCount(0)
    return clearAll
  }, [pick])

  const reasoningText = scenario.reasoning.join("\n")

  const run = () => {
    clearAll()
    setStage(1)
    setSignalIdx(0)
    setReasonChars(0)
    setPlacedCount(0)

    // Stage 1 — signals stream in (each ~140ms apart)
    scenario.signals.forEach((_, i) => {
      tRef.current.push(setTimeout(() => setSignalIdx(i + 1), (i + 1) * 160))
    })
    const senseEnd = scenario.signals.length * 160 + 200

    // Stage 2 — reasoning streams in (typewriter, ~14ms per char)
    tRef.current.push(setTimeout(() => setStage(2), senseEnd))
    const charSpeed = 14
    const totalChars = reasoningText.length
    for (let c = 1; c <= totalChars; c++) {
      tRef.current.push(
        setTimeout(() => setReasonChars(c), senseEnd + c * charSpeed),
      )
    }
    const reasonEnd = senseEnd + totalChars * charSpeed + 300

    // Stage 3 — components fly in
    tRef.current.push(setTimeout(() => setStage(3), reasonEnd))
    scenario.placements.forEach((_, i) => {
      tRef.current.push(
        setTimeout(() => setPlacedCount(i + 1), reasonEnd + (i + 1) * 280),
      )
    })
    const assembleEnd = reasonEnd + scenario.placements.length * 280 + 400
    tRef.current.push(setTimeout(() => setStage(4), assembleEnd))
  }

  const reasoningShown = reasoningText.slice(0, reasonChars)

  return (
    <section
      id="scenario"
      style={{
        background: "var(--page-card)",
        borderTop: "1px solid var(--page-line)",
        borderBottom: "1px solid var(--page-line)",
      }}
    >
      <div className="wrap">
        <SectionHead
          num="02 — Example Scenarios"
          eyebrow="Same machinery, three drives"
          title="Watch the AI sense, reason, and assemble the UI."
        >
          <p className="lede">
            Pick a driver. Hit <em>Run</em>. The car streams its sensor signals
            into the model, the model thinks out loud, and the cabin screen
            assembles itself from atomic components, each pulled from a
            validated library and placed in response to specific signals.
          </p>
          <p className="muted" style={{ marginTop: 12, fontSize: 14 }}>
            The same machinery handles all three. The combinations of signals
            produce genuinely different UIs. That's the point.
          </p>
        </SectionHead>

        {/* Driver picker + run */}
        <div className="sc-pick">
          <div className="sc-pick-row">
            {SCENARIOS.map((s, i) => (
              <button
                key={s.id}
                onClick={() => setPick(i)}
                className={"sc-tab " + (pick === i ? "on" : "")}
                aria-pressed={pick === i}
              >
                <span className="sc-tab-name">{s.name}</span>
                <span className="sc-tab-sub">{s.sub}</span>
              </button>
            ))}
          </div>
          <button
            className="sc-run"
            onClick={run}
            disabled={stage > 0 && stage < 4}
          >
            <span
              className="sc-run-dot"
              data-running={stage > 0 && stage < 4}
            />
            {stage === 0 && "Run scenario"}
            {stage === 1 && "Sensing…"}
            {stage === 2 && "Reasoning…"}
            {stage === 3 && "Assembling…"}
            {stage === 4 && "Run again"}
          </button>
        </div>

        {/* The stage */}
        <div className="sc-stage">
          {/* Left rail — Sense */}
          <div className="sc-pane">
            <PaneHeader
              n="01"
              k="SENSE"
              hint="Contextual signals"
              active={stage === 1}
              done={stage > 1}
            />
            <div className="sc-signals">
              {scenario.signals.map((s, i) => {
                const visible = signalIdx > i || stage > 1
                const Ico = Icon[s.icon] || Icon.Alert
                const isLinked = hovered && hovered.signals.includes(s.id)
                return (
                  <div
                    key={s.id}
                    className={
                      "sc-signal " +
                      (visible ? "in " : "") +
                      (isLinked ? "linked" : "")
                    }
                    data-signal={s.id}
                  >
                    <span className="sc-signal-ico">
                      <Ico />
                    </span>
                    <span className="sc-signal-label">{s.label}</span>
                    <span className="sc-signal-tag">{s.id}</span>
                  </div>
                )
              })}
            </div>

            {/* Reasoning, in same pane */}
            <PaneHeader
              n="02"
              k="REASON"
              hint="LLM thinking"
              active={stage === 2}
              done={stage > 2}
            />
            <div className="sc-reasoning" data-active={stage >= 2}>
              {stage < 2 ? (
                <span className="sc-reason-placeholder">Awaiting signals…</span>
              ) : (
                <pre className="sc-reason-pre">
                  {reasoningShown}
                  {stage === 2 && <span className="sc-caret" />}
                </pre>
              )}
              {stage >= 3 && (
                <div className="sc-conclusion">
                  <span className="mono sc-conclusion-tag">→ DECISION</span>
                  <span>{scenario.summary}</span>
                </div>
              )}
            </div>
          </div>

          {/* Right — Assemble */}
          <div className="sc-pane sc-pane-right">
            <PaneHeader
              n="03"
              k="ASSEMBLE"
              hint="Atomic library → cabin UI"
              active={stage === 3}
              done={stage === 4}
            />

            <div className="sc-assemble">
              {/* Component library shelf */}
              <div className="sc-shelf">
                {scenario.placements.map((p, i) => {
                  const placed = placedCount > i
                  const isHovered = hovered && hovered.idx === i
                  return (
                    <button
                      key={i}
                      className={
                        "sc-chip " +
                        (placed ? "flown " : "") +
                        (isHovered ? "hl" : "")
                      }
                      onMouseEnter={() =>
                        placed && setHovered({ idx: i, signals: p.from })
                      }
                      onMouseLeave={() => setHovered(null)}
                      onFocus={() =>
                        placed && setHovered({ idx: i, signals: p.from })
                      }
                      onBlur={() => setHovered(null)}
                      style={{ animationDelay: `${i * 60}ms` }}
                    >
                      <span className="sc-chip-glyph">
                        <CompGlyph kind={p.comp} />
                      </span>
                      <span className="sc-chip-name">{compName(p.comp)}</span>
                    </button>
                  )
                })}
              </div>

              {/* Cabin screen */}
              <div className="sc-screen">
                <div className="sc-screen-bezel">
                  <div className="sc-screen-bezel-dots">
                    {[0, 1, 2].map((i) => (
                      <span key={i} />
                    ))}
                  </div>
                  <div className="mono sc-screen-tag">
                    {stage < 3
                      ? "STANDBY"
                      : stage === 3
                      ? "ASSEMBLING"
                      : "GENERATED · " + scenario.id.toUpperCase()}
                  </div>
                </div>
                <div className="sc-screen-grid">
                  {/* Region labels (visible until assembled) */}
                  {stage < 4 && (
                    <>
                      <span
                        className="sc-region-tag"
                        style={{ gridColumn: "1 / span 2", gridRow: "1" }}
                      >
                        STATUS
                      </span>
                      <span
                        className="sc-region-tag"
                        style={{ gridColumn: "1", gridRow: "2 / span 4" }}
                      >
                        NAVIGATION
                      </span>
                      <span
                        className="sc-region-tag"
                        style={{ gridColumn: "2", gridRow: "2 / span 4" }}
                      >
                        CONTEXT
                      </span>
                    </>
                  )}
                  {scenario.placements.map((p, i) => {
                    if (placedCount <= i) return null
                    const isHovered = hovered && hovered.idx === i
                    return (
                      <PlacedComponent
                        key={p.comp + i}
                        kind={p.comp}
                        scenario={scenario.id}
                        note={p.note}
                        highlighted={isHovered}
                        onHover={(h) =>
                          setHovered(h ? { idx: i, signals: p.from } : null)
                        }
                      />
                    )
                  })}
                </div>
                {stage === 4 && (
                  <div className="sc-screen-foot mono">
                    {scenario.placements.length} components · assembled in real
                    time
                  </div>
                )}
              </div>
            </div>

            <div className="sc-hint mono" data-show={stage === 4}>
              Hover a component to see which signals motivated it.
            </div>
          </div>
        </div>
      </div>

      <style>{`
        /* Picker */
        .sc-pick {
          display: flex; gap: 16px; align-items: stretch;
          margin-bottom: 24px;
          flex-wrap: wrap;
        }
        .sc-pick-row {
          display: flex; gap: 6px; flex: 1; min-width: 280px;
          background: var(--page-bg);
          border: 1px solid var(--page-line);
          border-radius: 12px;
          padding: 4px;
        }
        .sc-tab {
          flex: 1; min-width: 0;
          padding: 10px 14px;
          border: none; border-radius: 8px;
          background: transparent; color: var(--page-fg);
          text-align: left; cursor: pointer;
          display: flex; flex-direction: column; gap: 2px;
          transition: background 200ms;
          font-family: var(--font-sans);
        }
        .sc-tab:hover { background: rgba(0,0,0,0.04); }
        .sc-tab.on { background: var(--page-fg); color: #F4EFDF; }
        .sc-tab-name { font-size: 14px; font-weight: 600; }
        .sc-tab-sub  { font-size: 11px; opacity: 0.7; font-family: var(--font-mono); letter-spacing: 0.04em; }

        .sc-run {
          padding: 12px 22px; border-radius: 12px;
          background: var(--page-accent); color: #fff;
          border: 1px solid var(--page-accent);
          font-family: var(--font-sans); font-size: 14px; font-weight: 600;
          cursor: pointer;
          display: inline-flex; align-items: center; gap: 10px;
          transition: opacity 200ms, transform 150ms;
        }
        .sc-run:hover:not(:disabled) { transform: translateY(-1px); }
        .sc-run:disabled { opacity: 0.7; cursor: not-allowed; }
        .sc-run-dot {
          width: 8px; height: 8px; border-radius: 999px; background: #fff;
        }
        .sc-run-dot[data-running="true"] { animation: scPulse 900ms ease-in-out infinite; }
        @keyframes scPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(0.7); } }

        /* Stage */
        .sc-stage {
          display: grid;
          grid-template-columns: minmax(280px, 360px) 1fr;
          gap: 24px;
          align-items: start;
        }
        .sc-pane {
          background: var(--page-bg);
          border: 1px solid var(--page-line);
          border-radius: 16px;
          padding: 20px;
        }
        .sc-pane-right { background: var(--page-fg); color: #F4EFDF; border-color: var(--page-fg); }

        /* Pane headers */
        .sc-pane-h {
          display: flex; align-items: baseline; gap: 10px;
          padding-bottom: 10px; margin-bottom: 14px;
          border-bottom: 1px solid var(--page-line);
        }
        .sc-pane-right .sc-pane-h { border-bottom-color: rgba(244,239,223,0.15); }
        .sc-pane-h-num {
          font-family: var(--font-mono); font-size: 11px;
          color: var(--page-muted); letter-spacing: 0.08em;
        }
        .sc-pane-right .sc-pane-h-num { color: rgba(244,239,223,0.45); }
        .sc-pane-h-k {
          font-family: var(--font-mono); font-size: 12px;
          letter-spacing: 0.1em;
        }
        .sc-pane-h-k[data-active="true"] { color: var(--page-accent); }
        .sc-pane-h-hint {
          margin-left: auto;
          font-family: var(--font-mono); font-size: 10px;
          color: var(--page-muted); letter-spacing: 0.06em;
          text-transform: uppercase;
        }
        .sc-pane-right .sc-pane-h-hint { color: rgba(244,239,223,0.45); }

        /* Signals */
        .sc-signals { display: flex; flex-direction: column; gap: 6px; margin-bottom: 18px; }
        .sc-signal {
          display: grid; grid-template-columns: 24px 1fr auto;
          align-items: center; gap: 10px;
          padding: 8px 10px;
          background: var(--page-card);
          border: 1px solid var(--page-line);
          border-radius: 8px;
          font-size: 12px;
          opacity: 0; transform: translateX(-8px);
          transition: opacity 220ms, transform 260ms, border-color 200ms, box-shadow 200ms;
        }
        .sc-signal.in { opacity: 1; transform: translateX(0); }
        .sc-signal.linked {
          border-color: var(--page-accent);
          box-shadow: 0 0 0 1px var(--page-accent), 0 8px 20px rgba(224,123,44,0.18);
        }
        .sc-signal-ico {
          width: 24px; height: 24px; border-radius: 6px;
          display: inline-flex; align-items: center; justify-content: center;
          background: var(--page-bg);
          color: var(--page-fg);
        }
        .sc-signal-ico svg { width: 14px; height: 14px; }
        .sc-signal-label { line-height: 1.3; }
        .sc-signal-tag {
          font-family: var(--font-mono); font-size: 10px;
          color: var(--page-muted); letter-spacing: 0.04em;
        }

        /* Reasoning */
        .sc-reasoning {
          background: var(--page-fg); color: #F4EFDF;
          border-radius: 10px; padding: 14px 14px;
          min-height: 110px;
          font-family: var(--font-mono); font-size: 12px; line-height: 1.55;
        }
        .sc-reason-placeholder { color: rgba(244,239,223,0.4); }
        .sc-reason-pre {
          margin: 0; white-space: pre-wrap; font: inherit;
          background: transparent;
          color: #F4EFDF;
        }
        .sc-caret {
          display: inline-block; width: 7px; height: 13px;
          background: var(--page-accent);
          margin-left: 2px; vertical-align: -2px;
          animation: scCaret 700ms steps(2) infinite;
        }
        @keyframes scCaret { 50% { opacity: 0; } }

        .sc-conclusion {
          margin-top: 12px; padding-top: 10px;
          border-top: 1px dashed rgba(244,239,223,0.2);
          display: flex; gap: 8px; align-items: flex-start;
          font-family: var(--font-sans); font-size: 12.5px;
        }
        .sc-conclusion-tag { color: var(--page-accent); flex-shrink: 0; }

        /* Assemble */
        .sc-assemble {
          display: flex; flex-direction: column; gap: 14px;
        }
        .sc-shelf {
          display: flex; flex-wrap: wrap; gap: 6px;
          padding: 10px;
          background: rgba(244,239,223,0.04);
          border: 1px solid rgba(244,239,223,0.12);
          border-radius: 10px;
        }
        .sc-chip {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 10px 6px 6px;
          background: rgba(244,239,223,0.08);
          border: 1px solid rgba(244,239,223,0.2);
          border-radius: 8px;
          color: #F4EFDF;
          font-family: var(--font-sans); font-size: 11px;
          cursor: default;
          transition: opacity 350ms, transform 350ms, background 200ms, border-color 200ms;
        }
        .sc-chip.flown { opacity: 0.35; }
        .sc-chip.flown.hl, .sc-chip:hover.flown {
          opacity: 1; border-color: var(--page-accent); background: rgba(224,123,44,0.18);
        }
        .sc-chip-glyph {
          width: 22px; height: 22px; border-radius: 4px;
          background: rgba(244,239,223,0.12);
          display: inline-flex; align-items: center; justify-content: center;
          color: #F4EFDF;
        }
        .sc-chip-glyph svg { width: 14px; height: 14px; }
        .sc-chip-name { font-weight: 500; letter-spacing: 0.01em; }

        /* Screen */
        .sc-screen {
          background: #0E1116;
          border-radius: 14px; padding: 12px;
          border: 1px solid rgba(244,239,223,0.1);
        }
        .sc-screen-bezel {
          display: flex; justify-content: space-between; align-items: center;
          padding: 0 4px 8px;
        }
        .sc-screen-bezel-dots { display: flex; gap: 6px; }
        .sc-screen-bezel-dots span {
          width: 6px; height: 6px; border-radius: 999px;
          background: rgba(244,239,223,0.25);
        }
        .sc-screen-tag {
          font-size: 10px; letter-spacing: 0.1em;
          color: rgba(244,239,223,0.5);
        }
        .sc-screen-grid {
          display: grid;
          grid-template-columns: 1.4fr 1fr;
          grid-template-rows: auto repeat(4, auto);
          gap: 8px;
          background: rgba(244,239,223,0.02);
          border-radius: 10px;
          padding: 10px;
          min-height: 360px;
          position: relative;
        }
        .sc-region-tag {
          align-self: start; justify-self: start;
          font-family: var(--font-mono); font-size: 9px;
          letter-spacing: 0.1em;
          color: rgba(244,239,223,0.25);
          padding: 4px 6px;
        }
        .sc-screen-foot {
          padding-top: 10px;
          font-size: 10px;
          letter-spacing: 0.08em;
          color: rgba(244,239,223,0.4);
          text-align: right;
        }

        /* Placed components */
        .sc-place {
          padding: 10px;
          background: rgba(244,239,223,0.06);
          border: 1px solid rgba(244,239,223,0.12);
          border-radius: 10px;
          color: #F4EFDF;
          font-size: 12px;
          animation: scFly 540ms cubic-bezier(.2,0,0,1) both;
          transition: outline 180ms, box-shadow 180ms, border-color 180ms;
        }
        .sc-place.hl {
          border-color: var(--page-accent);
          box-shadow: 0 0 0 1px var(--page-accent), 0 12px 28px rgba(224,123,44,0.2);
        }
        @keyframes scFly {
          from { opacity: 0; transform: translate(-12px, -8px) scale(0.92); }
          to   { opacity: 1; transform: translate(0, 0)        scale(1); }
        }

        .sc-hint {
          margin-top: 14px;
          font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase;
          color: rgba(244,239,223,0.45);
          opacity: 0; transition: opacity 300ms;
        }
        .sc-hint[data-show="true"] { opacity: 1; }

        @media (max-width: 980px) {
          .sc-stage { grid-template-columns: 1fr; }
        }
        @media (max-width: 720px) {
          .sc-pick { flex-direction: column; }
          .sc-run { width: 100%; justify-content: center; }
        }
      `}</style>
    </section>
  )
}

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

function PaneHeader({ n, k, hint, active, done }) {
  return (
    <div className="sc-pane-h">
      <span className="sc-pane-h-num">{n}</span>
      <span className="sc-pane-h-k" data-active={active}>
        {k}
        {done ? " ✓" : ""}
      </span>
      <span className="sc-pane-h-hint">{hint}</span>
    </div>
  )
}

function compName(kind) {
  return (
    {
      header: "App panel",
      navMap: "Navigation",
      navMini: "Nav · compact",
      fuelPOI: "Fuel POIs",
      fuelMini: "Fuel widget",
      alert: "Weather alert",
      calm: "Calm mode",
      reroute: "Reroute card",
      etaBig: "ETA card",
      weather: "Weather widget",
      music: "Now playing",
      podcast: "Resume podcast",
      smartHome: "Home arrival",
      scenic: "Scenic ambient",
    }[kind] || kind
  )
}

function CompGlyph({ kind }) {
  const stroke = "currentColor"
  const opts = {
    width: 14,
    height: 14,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke,
    strokeWidth: 2,
    strokeLinecap: "round",
    strokeLinejoin: "round",
  }
  if (kind === "header")
    return (
      <svg {...opts}>
        <rect x="3" y="6" width="18" height="4" rx="1" />
      </svg>
    )
  if (kind === "navMap" || kind === "navMini")
    return (
      <svg {...opts}>
        <polygon points="3 11 22 2 13 21 11 13 3 11" />
      </svg>
    )
  if (kind === "fuelPOI")
    return (
      <svg {...opts}>
        <circle cx="12" cy="11" r="3" />
        <path d="M12 2 L12 8" />
        <path d="M5 20 h14" />
      </svg>
    )
  if (kind === "fuelMini")
    return (
      <svg {...opts}>
        <path d="M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18" />
        <line x1="3" y1="22" x2="15" y2="22" />
      </svg>
    )
  if (kind === "alert")
    return (
      <svg {...opts}>
        <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
        <line x1="12" y1="9" x2="12" y2="13" />
        <line x1="12" y1="17" x2="12.01" y2="17" />
      </svg>
    )
  if (kind === "calm")
    return (
      <svg {...opts}>
        <circle cx="12" cy="12" r="9" />
        <line x1="8" y1="12" x2="16" y2="12" />
      </svg>
    )
  if (kind === "reroute")
    return (
      <svg {...opts}>
        <path d="M4 12 C 8 4, 16 4, 20 12" />
        <polyline points="16 8 20 12 16 16" />
      </svg>
    )
  if (kind === "etaBig")
    return (
      <svg {...opts}>
        <circle cx="12" cy="12" r="9" />
        <polyline points="12 7 12 12 15 14" />
      </svg>
    )
  if (kind === "weather")
    return (
      <svg {...opts}>
        <path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z" />
      </svg>
    )
  if (kind === "music")
    return (
      <svg {...opts}>
        <path d="M9 18V5l12-2v13" />
        <circle cx="6" cy="18" r="3" />
        <circle cx="18" cy="16" r="3" />
      </svg>
    )
  if (kind === "podcast")
    return (
      <svg {...opts}>
        <circle cx="12" cy="11" r="3" />
        <path d="M5 11 a7 7 0 0 1 14 0" />
        <path d="M9 18 l3 -4 l3 4" />
      </svg>
    )
  if (kind === "smartHome")
    return (
      <svg {...opts}>
        <path d="M3 12 L12 3 L21 12 V21 H3z" />
        <path d="M9 21 V14 h6 v7" />
      </svg>
    )
  if (kind === "scenic")
    return (
      <svg {...opts}>
        <path d="M3 18 L9 10 L13 14 L17 8 L21 14" />
        <circle cx="17" cy="6" r="2" />
      </svg>
    )
  return (
    <svg {...opts}>
      <rect x="4" y="4" width="16" height="16" rx="2" />
    </svg>
  )
}

/* Placed component renderer — full visual once "flown in" */
function PlacedComponent({ kind, scenario, note, highlighted, onHover }) {
  const className = "sc-place " + (highlighted ? "hl" : "")
  const hover = {
    onMouseEnter: () => onHover(true),
    onMouseLeave: () => onHover(false),
  }
  const titleLabel = compName(kind)

  if (kind === "header")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "1 / span 2",
          gridRow: "1",
          padding: "8px 12px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <span
          className="mono"
          style={{ fontSize: 10, color: "rgba(244,239,223,0.7)" }}
        >
          {scenario === "sara" && "20:34 · STORM · LOW FUEL"}
          {scenario === "marc" && "07:42 · ZRH IN 92 MIN"}
          {scenario === "lena" && "19:08 · HOMEWARD · MILD"}
        </span>
        <span
          className="mono"
          style={{ fontSize: 10, color: "var(--page-accent)" }}
        >
          ● VOICE READY
        </span>
      </div>
    )

  if (kind === "navMap")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "1",
          gridRow: scenario === "marc" ? "2 / span 3" : "2 / span 3",
          display: "flex",
          flexDirection: "column",
          gap: 8,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <CompGlyph kind="navMap" />
          <span style={{ fontWeight: 600 }}>{titleLabel}</span>
        </div>
        <div
          style={{
            flex: 1,
            minHeight: 150,
            borderRadius: 8,
            position: "relative",
            background:
              "radial-gradient(circle at 30% 60%, rgba(255,138,61,0.18), transparent 50%), repeating-linear-gradient(45deg, rgba(244,239,223,0.04) 0 12px, transparent 12px 24px)",
          }}
        >
          <svg
            viewBox="0 0 200 120"
            preserveAspectRatio="none"
            style={{
              position: "absolute",
              inset: 0,
              width: "100%",
              height: "100%",
            }}
          >
            <path
              d="M 10 100 C 60 80, 80 40, 130 50 S 180 30, 195 20"
              stroke="var(--page-accent)"
              strokeWidth="3"
              fill="none"
              strokeLinecap="round"
            />
            <circle cx="10" cy="100" r="4" fill="var(--page-accent)" />
            <circle cx="195" cy="20" r="4" fill="#F4EFDF" />
          </svg>
        </div>
        <div style={{ fontSize: 11 }}>In 800 m, turn right · Königstraße</div>
      </div>
    )

  if (kind === "navMini")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "1",
          gridRow: "2 / span 2",
          display: "flex",
          flexDirection: "column",
          gap: 6,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <CompGlyph kind="navMap" />
          <span style={{ fontWeight: 600 }}>Home · 18 min</span>
        </div>
        <div
          style={{
            minHeight: 90,
            borderRadius: 8,
            background:
              "linear-gradient(135deg, rgba(255,138,61,0.18), rgba(244,239,223,0.04))",
            position: "relative",
          }}
        >
          <svg
            viewBox="0 0 200 80"
            preserveAspectRatio="none"
            style={{
              position: "absolute",
              inset: 0,
              width: "100%",
              height: "100%",
            }}
          >
            <path
              d="M 10 70 Q 100 10, 195 30"
              stroke="var(--page-accent)"
              strokeWidth="2.5"
              fill="none"
              strokeLinecap="round"
            />
          </svg>
        </div>
      </div>
    )

  if (kind === "fuelPOI")
    return (
      <div
        className={className}
        {...hover}
        style={{ gridColumn: "1", gridRow: "5" }}
      >
        <div
          className="mono"
          style={{ fontSize: 10, color: "var(--page-accent)", marginBottom: 6 }}
        >
          3 STATIONS ON ROUTE
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          {[
            ["Aral · 4.2 km", "1.79 €"],
            ["Shell · 9.8 km", "1.81 €"],
            ["BP · 22 km", "1.74 €"],
          ].map(([n, p]) => (
            <div
              key={n}
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontSize: 11,
                padding: "3px 0",
                borderTop: "1px dashed rgba(244,239,223,0.12)",
              }}
            >
              <span>{n}</span>
              <span style={{ color: "var(--page-accent)" }}>{p}</span>
            </div>
          ))}
        </div>
      </div>
    )

  if (kind === "fuelMini")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "2",
          gridRow: "3",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <CompGlyph kind="fuelMini" />
          <div>
            <div style={{ fontSize: 11, fontWeight: 600 }}>Fuel</div>
            <div style={{ fontSize: 10, opacity: 0.7 }}>47 km</div>
          </div>
        </div>
        <div
          style={{
            width: 40,
            height: 4,
            borderRadius: 2,
            background: "rgba(244,239,223,0.15)",
            overflow: "hidden",
          }}
        >
          <div
            style={{
              width: "12%",
              height: "100%",
              background: "var(--page-accent)",
            }}
          />
        </div>
      </div>
    )

  if (kind === "alert")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "2",
          gridRow: "2",
          borderColor: "var(--page-accent)",
          background: "rgba(224,123,44,0.14)",
          color: "var(--page-accent)",
          display: "flex",
          gap: 8,
          alignItems: "flex-start",
        }}
      >
        <CompGlyph kind="alert" />
        <div style={{ fontSize: 11, lineHeight: 1.4 }}>
          <strong>Heavy rain ahead</strong>
          <br />
          <span style={{ opacity: 0.85 }}>Reduced visibility</span>
        </div>
      </div>
    )

  if (kind === "calm")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "2",
          gridRow: "4 / span 2",
          borderStyle: "dashed",
          color: "rgba(244,239,223,0.6)",
          textAlign: "center",
        }}
      >
        <CompGlyph kind="calm" />
        <div
          className="mono"
          style={{ marginTop: 6, fontSize: 10, letterSpacing: "0.06em" }}
        >
          CALM MODE
        </div>
        <div style={{ fontSize: 11, marginTop: 4 }}>
          Music, calls, recommendations
          <br />
          suppressed
        </div>
      </div>
    )

  if (kind === "reroute")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "1",
          gridRow: "5",
          borderColor: "var(--page-accent)",
          background: "rgba(224,123,44,0.14)",
          color: "var(--page-accent)",
          display: "flex",
          gap: 8,
          alignItems: "center",
          marginTop: 0,
        }}
      >
        <CompGlyph kind="reroute" />
        <div style={{ fontSize: 11, lineHeight: 1.3 }}>
          <strong>Reroute via A4</strong> · saves 11 min
        </div>
      </div>
    )

  if (kind === "etaBig")
    return (
      <div
        className={className}
        {...hover}
        style={{ gridColumn: "2", gridRow: "2 / span 2" }}
      >
        <div
          className="mono"
          style={{
            fontSize: 10,
            color: "rgba(244,239,223,0.6)",
            marginBottom: 6,
          }}
        >
          ETA · ZURICH AIRPORT
        </div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
          <span
            style={{
              fontFamily: "var(--font-display)",
              fontStyle: "italic",
              fontSize: 38,
              lineHeight: 1,
              letterSpacing: "-0.02em",
            }}
          >
            09:02
          </span>
          <span style={{ fontSize: 11, color: "var(--page-accent)" }}>
            +8 min
          </span>
        </div>
        <div style={{ fontSize: 10, opacity: 0.7, marginTop: 4 }}>
          Flight 14:14 · gate B27
        </div>
      </div>
    )

  if (kind === "weather")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "2",
          gridRow: scenario === "lena" ? "5" : "4",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <CompGlyph kind={scenario === "marc" ? "scenic" : "weather"} />
          <div>
            <div style={{ fontSize: 11, fontWeight: 600 }}>
              {scenario === "marc" ? "Clear, 12°" : "Mild evening"}
            </div>
            <div style={{ fontSize: 10, opacity: 0.7 }}>
              {scenario === "marc" ? "ZRH bright" : "Sunset 19:42"}
            </div>
          </div>
        </div>
      </div>
    )

  if (kind === "music")
    return (
      <div
        className={className}
        {...hover}
        style={{ gridColumn: "2", gridRow: "5", opacity: 0.7 }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            marginBottom: 4,
          }}
        >
          <CompGlyph kind="music" />
          <span style={{ fontSize: 11, fontWeight: 600 }}>Now Playing</span>
        </div>
        <div style={{ fontSize: 11, opacity: 0.7 }}>Morning Mix · Spotify</div>
      </div>
    )

  if (kind === "podcast")
    return (
      <div
        className={className}
        {...hover}
        style={{ gridColumn: "2", gridRow: "2 / span 2" }}
      >
        <div
          className="mono"
          style={{ fontSize: 10, color: "var(--page-accent)", marginBottom: 6 }}
        >
          RESUME
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.3 }}>
          The Daily — Episode 1812
        </div>
        <div style={{ fontSize: 10, opacity: 0.7, marginTop: 4 }}>
          24:18 / 31:02
        </div>
        <div
          style={{
            height: 3,
            background: "rgba(244,239,223,0.15)",
            borderRadius: 2,
            marginTop: 8,
          }}
        >
          <div
            style={{
              width: "78%",
              height: "100%",
              background: "var(--page-accent)",
              borderRadius: 2,
            }}
          />
        </div>
      </div>
    )

  if (kind === "smartHome")
    return (
      <div
        className={className}
        {...hover}
        style={{ gridColumn: "2", gridRow: "4" }}
      >
        <div
          className="mono"
          style={{
            fontSize: 10,
            color: "rgba(244,239,223,0.6)",
            marginBottom: 6,
          }}
        >
          ON ARRIVAL
        </div>
        <div style={{ fontSize: 11, lineHeight: 1.4 }}>
          Lights on · Heat to 21°
          <br />
          Garage opens at 200 m
        </div>
      </div>
    )

  if (kind === "scenic")
    return (
      <div
        className={className}
        {...hover}
        style={{
          gridColumn: "1",
          gridRow: "5",
          padding: 0,
          overflow: "hidden",
          minHeight: 80,
          background:
            "linear-gradient(180deg, #2A1F3A 0%, #6B4A4A 50%, #C77B4D 100%)",
          border: "1px solid rgba(244,239,223,0.12)",
        }}
      >
        <div style={{ padding: 10, color: "#F4EFDF" }}>
          <div
            className="mono"
            style={{ fontSize: 9, letterSpacing: "0.1em", opacity: 0.7 }}
          >
            AMBIENT
          </div>
          <div style={{ fontSize: 11, marginTop: 2 }}>Sunset palette</div>
        </div>
      </div>
    )

  return null
}

window.Scenario = Scenario
