// Demo controller: timeline, auto-play, scrubber, scene mounting

const { motion: mc, AnimatePresence: APc } = window;

const SCENE_DEFS = [
  { id: 1, dur: 4.0, name: "Hero", Comp: () => window.Scene1Hero },
  { id: 2, dur: 8.0, name: "Onboarding", Comp: () => window.Scene2Onboarding },
  { id: 3, dur: 6.0, name: "Plan", Comp: () => window.Scene3Plan },
  { id: 4, dur: 6.0, name: "Browse", Comp: () => window.Scene4Browse },
  { id: 5, dur: 7.0, name: "Detail", Comp: () => window.Scene5Detail },
  { id: 6, dur: 6.0, name: "Cart", Comp: () => window.Scene6Cart },
  { id: 7, dur: 7.0, name: "Forwarder", Comp: () => window.Scene7Forwarder },
  { id: 8, dur: 5.0, name: "3PL", Comp: () => window.Scene8ThreePL },
  { id: 9, dur: 6.0, name: "Tracking", Comp: () => window.Scene9Tracking },
];

const TOTAL_DUR = SCENE_DEFS.reduce((s, sc) => s + sc.dur, 0);

function getSceneAtTime(t) {
  let acc = 0;
  for (let i = 0; i < SCENE_DEFS.length; i++) {
    const s = SCENE_DEFS[i];
    if (t < acc + s.dur) {
      return { idx: i, def: s, sceneTime: t - acc, progress: (t - acc) / s.dur };
    }
    acc += s.dur;
  }
  const last = SCENE_DEFS[SCENE_DEFS.length - 1];
  return { idx: SCENE_DEFS.length - 1, def: last, sceneTime: last.dur, progress: 1 };
}

function DemoController() {
  const embed = new URLSearchParams(window.location.search).get("embed") === "1";
  const [t, setT] = React.useState(0);
  const [playing, setPlaying] = React.useState(!embed);
  const lastTickRef = React.useRef(performance.now());
  const rafRef = React.useRef(0);

  const { w: vw } = window.useWindowSize();
  const showPanels = vw >= 1200;
  const isMobile = vw < 600;

  React.useEffect(() => {
    function loop(now) {
      if (playing) {
        const dt = (now - lastTickRef.current) / 1000;
        setT(prev => {
          let next = prev + dt;
          if (next >= TOTAL_DUR) next = 0;
          return next;
        });
      }
      lastTickRef.current = now;
      rafRef.current = requestAnimationFrame(loop);
    }
    lastTickRef.current = performance.now();
    rafRef.current = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  React.useEffect(() => {
    if (embed) return;
    const saved = parseFloat(localStorage.getItem("soko-demo-t") || "0");
    if (!isNaN(saved) && saved > 0 && saved < TOTAL_DUR) setT(saved);
  }, []);
  React.useEffect(() => {
    if (embed) return;
    localStorage.setItem("soko-demo-t", String(t));
  }, [t]);

  React.useEffect(() => {
    if (!embed) return;
    const handler = (e) => {
      if (e.data?.type === "soko:active") setPlaying(e.data.active);
    };
    window.addEventListener("message", handler);
    return () => window.removeEventListener("message", handler);
  }, []);

  const { idx, def, progress } = getSceneAtTime(t);
  const SceneComp = def.Comp();
  const beat = window.SOKO_DATA.beats[idx];

  if (embed) {
    return (
      <div style={{ position: "fixed", inset: 0, background: "#0c0a09", overflow: "hidden", fontFamily: "'Inter', -apple-system, sans-serif" }}>
        <APc mode="wait">
          <mc.div key={idx}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.3 }}
            style={{ position: "absolute", inset: 0 }}>
            <SceneComp progress={progress} />
          </mc.div>
        </APc>
      </div>
    );
  }

  return (
    <div style={{
      width: "100%", minHeight: "100vh",
      background: "#0c0a09",
      color: "#fafaf9",
      display: "flex", flexDirection: "column",
      fontFamily: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif",
    }}>
      {window.TopBarApp ? <window.TopBarApp active="demo" /> : <TopBar />}

      <div style={{
        flex: 1, display: "flex", alignItems: "center", justifyContent: "center",
        gap: showPanels ? 60 : 0,
        padding: showPanels ? "32px 40px" : isMobile ? "12px 16px" : "24px",
        flexWrap: "nowrap",
        overflow: "hidden",
      }}>
        {showPanels && (
          <div style={{ width: 280, flexShrink: 0 }}>
            <div style={{
              fontSize: 10, fontFamily: "ui-monospace, Menlo, monospace",
              color: "rgba(250,250,249,0.4)", letterSpacing: 1, marginBottom: 8,
            }}>SCENE {beat.i} · {beat.label}</div>
            <div style={{
              fontSize: 22, lineHeight: 1.25,
              fontFamily: "'Inter', -apple-system, sans-serif",
              color: "#fafaf9", marginBottom: 16,
            }}>
              {beat.text}
            </div>
            <div style={{
              padding: "10px 12px", borderRadius: 8,
              background: "rgba(250,250,249,0.04)",
              border: "1px solid rgba(250,250,249,0.08)",
              fontSize: 11, color: "rgba(250,250,249,0.6)", lineHeight: 1.5,
            }}>
              <div style={{ fontSize: 9, color: "rgba(250,250,249,0.4)", fontFamily: "ui-monospace, monospace", letterSpacing: 0.8, marginBottom: 4 }}>WHAT YOU'RE SEEING</div>
              {sceneNarration[idx]}
            </div>
          </div>
        )}

        <div style={{ position: "relative" }}>
          <window.PhoneFrame statusTime="9:41" chromeH={160}>
            <APc mode="wait">
              <mc.div key={idx}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.3 }}
                style={{ position: "absolute", inset: 0 }}>
                <SceneComp progress={progress} />
              </mc.div>
            </APc>
          </window.PhoneFrame>
        </div>

        {showPanels && (
          <div style={{ width: 200, flexShrink: 0 }}>
            <div style={{
              fontSize: 10, fontFamily: "ui-monospace, Menlo, monospace",
              color: "rgba(250,250,249,0.4)", letterSpacing: 1, marginBottom: 12,
            }}>USER JOURNEY</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {SCENE_DEFS.map((s, i) => {
                const active = i === idx;
                return (
                  <button key={s.id}
                    onClick={() => {
                      let acc = 0;
                      for (let k = 0; k < i; k++) acc += SCENE_DEFS[k].dur;
                      setT(acc);
                    }}
                    style={{
                      display: "flex", alignItems: "center", gap: 10,
                      padding: "8px 10px", border: "none", background: active ? "rgba(250,250,249,0.08)" : "transparent",
                      borderRadius: 6, cursor: "pointer",
                      color: active ? "#fafaf9" : "rgba(250,250,249,0.5)",
                      textAlign: "left", fontFamily: "inherit",
                    }}>
                    <span style={{
                      width: 18, fontSize: 9, fontFamily: "ui-monospace, monospace",
                      color: active ? "oklch(0.78 0.10 50)" : "rgba(250,250,249,0.3)",
                      letterSpacing: 0.5,
                    }}>0{s.id}</span>
                    <span style={{ fontSize: 12 }}>{s.name}</span>
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>

      <Scrubber t={t} setT={setT} playing={playing} setPlaying={setPlaying} idx={idx} compact={isMobile} />
    </div>
  );
}

const sceneNarration = [
  "AI agent introduces itself. Onboarding feels like chat, not a form.",
  "Three questions in 90 seconds replace a two-week supplier hunt.",
  "Plan generated: suppliers, freight, fulfillment, projected margin.",
  "1688 catalog, translated and price-tiered in USD.",
  "Sizes flip cm to inch live. Variants surfaced as a real grid.",
  "MOQ optimizer nudges to the next price tier — buyer saves $52 at signup.",
  "Forwarder picked using sentiment scraped from LATAM Telegram + forums.",
  "Local Mexican 3PL, NOM-compliant, matched to Maria's city.",
  "Order tracked end-to-end. Reorder loop triggered by margin data.",
];

function TopBar() {
  return (
    <div style={{
      padding: "20px 32px",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      borderBottom: "1px solid rgba(250,250,249,0.06)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <window.SokoWordmark size={26} color="#fafaf9" />
        <span style={{ fontSize: 10, fontFamily: "ui-monospace, monospace", color: "rgba(250,250,249,0.4)", padding: "3px 8px", border: "1px solid rgba(250,250,249,0.15)", borderRadius: 4, letterSpacing: 0.5 }}>
          INVESTOR DEMO · v0.9
        </span>
      </div>
      <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
        <a href="#" onClick={(e) => { e.preventDefault(); window.__sokoSetView("demo"); }} style={navLinkStyle(true)}>Demo</a>
        <a href="#" onClick={(e) => { e.preventDefault(); window.__sokoSetView("app"); }} style={navLinkStyle(false)}>Full app</a>
        <a href="#" onClick={(e) => { e.preventDefault(); window.__sokoSetView("closing"); }} style={navLinkStyle(false)}>Business</a>
      </div>
    </div>
  );
}

function navLinkStyle(active) {
  return {
    fontSize: 12, color: active ? "#fafaf9" : "rgba(250,250,249,0.5)",
    textDecoration: "none", fontFamily: "ui-monospace, monospace",
    letterSpacing: 0.5, padding: "6px 10px", borderRadius: 4,
    background: active ? "rgba(250,250,249,0.08)" : "transparent",
  };
}

function Scrubber({ t, setT, playing, setPlaying, idx, compact }) {
  const pct = (t / TOTAL_DUR) * 100;
  const onScrub = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    setT(ratio * TOTAL_DUR);
  };

  let acc = 0;
  const segments = SCENE_DEFS.map(s => {
    const start = (acc / TOTAL_DUR) * 100;
    acc += s.dur;
    return { start, end: (acc / TOTAL_DUR) * 100, name: s.name };
  });

  const pad = compact ? "12px 16px 16px" : "16px 40px 24px";

  return (
    <div style={{
      padding: pad,
      borderTop: "1px solid rgba(250,250,249,0.06)",
      background: "rgba(0,0,0,0.4)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: compact ? 10 : 16 }}>
        <button onClick={() => setPlaying(p => !p)} style={{
          width: 36, height: 36, borderRadius: 18,
          border: "1px solid rgba(250,250,249,0.2)",
          background: "rgba(250,250,249,0.06)",
          color: "#fafaf9", display: "flex", alignItems: "center", justifyContent: "center",
          cursor: "pointer", flexShrink: 0,
        }}>
          {playing ? (
            <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><rect x="2" y="1" width="3" height="10" rx="0.5" /><rect x="7" y="1" width="3" height="10" rx="0.5" /></svg>
          ) : (
            <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><path d="M2 1L11 6L2 11Z" /></svg>
          )}
        </button>

        <div style={{ flex: 1, position: "relative" }}>
          <div onClick={onScrub} style={{
            height: 28, position: "relative", cursor: "pointer",
            display: "flex", alignItems: "center",
          }}>
            <div style={{
              position: "absolute", left: 0, right: 0, height: 4, top: 12,
              background: "rgba(250,250,249,0.1)", borderRadius: 2, overflow: "hidden",
            }}>
              <div style={{
                position: "absolute", left: 0, top: 0, bottom: 0,
                width: `${pct}%`,
                background: "oklch(0.55 0.16 40)",
                transition: "width 60ms linear",
              }} />
            </div>
            {segments.map((seg, i) => (
              <div key={i} style={{
                position: "absolute", top: 8, height: 12, width: 1,
                left: `${seg.end}%`,
                background: "rgba(250,250,249,0.2)",
              }} />
            ))}
            <div style={{
              position: "absolute", top: 6, left: `${pct}%`,
              transform: "translateX(-50%)",
              width: 16, height: 16, borderRadius: 8,
              background: "#fafaf9", border: "2px solid oklch(0.55 0.16 40)",
              transition: "left 60ms linear",
            }} />
          </div>
          {!compact && (
            <div style={{
              display: "flex", justifyContent: "space-between", marginTop: 4,
              fontSize: 9, fontFamily: "ui-monospace, monospace", color: "rgba(250,250,249,0.4)",
            }}>
              {segments.map((seg, i) => (
                <span key={i} style={{
                  width: `${seg.end - seg.start}%`, textAlign: "center",
                  color: i === idx ? "oklch(0.85 0.10 50)" : "rgba(250,250,249,0.4)",
                  letterSpacing: 0.3,
                }}>{seg.name.toLowerCase()}</span>
              ))}
            </div>
          )}
        </div>

        {!compact && (
          <div style={{
            fontFamily: "ui-monospace, monospace", fontSize: 11,
            color: "rgba(250,250,249,0.6)",
            minWidth: 80, textAlign: "right",
            fontVariantNumeric: "tabular-nums",
          }}>
            {t.toFixed(1)}s / {TOTAL_DUR.toFixed(1)}s
          </div>
        )}
      </div>
    </div>
  );
}

window.DemoController = DemoController;
window.SCENE_DEFS = SCENE_DEFS;
