/* global React */
const { useState: useDState, useEffect: useDEffect, useRef: useDRef } = React;

// Scripted timeline for the product demo. Each entry: { at: ms, do: () => state }
const DEMO_PROMPT = "A subscription for single-origin matcha from Uji. Earthy, ceremonial brand. Two tiers — monthly tin and quarterly gift box.";

const AI_REPLY_LINES = [
  "Got it — building a ceremonial-grade matcha subscription from the ground up.",
  "I'll set up storefront, two products, brand kit, checkout with subscriptions, and shipping rules.",
];

const BUILD_LINES = [
  { t: 700, lbl: "domain",      val: "ujimatcha.shop", status: "ok" },
  { t: 1500, lbl: "brand kit",  val: "warm-paper · ink · matcha-green", status: "ok" },
  { t: 2400, lbl: "logo",       val: "wordmark — instrument serif italic", status: "ok" },
  { t: 3300, lbl: "products",   val: "2 SKUs · Tin (30g) · Gift box", status: "ok" },
  { t: 4200, lbl: "checkout",   val: "Stripe · subscriptions · tax", status: "ok" },
  { t: 5200, lbl: "shipping",   val: "USPS + DHL · zones 1–4", status: "ok" },
  { t: 6200, lbl: "campaign",   val: "launch email · 1,420 subs imported", status: "ok" },
  { t: 7100, lbl: "deploy",     val: "production · cdn warm · SSL", status: "ok" },
];

function useTypewriter(text, speed = 18, start = true, delay = 0) {
  const [out, setOut] = useDState("");
  const [done, setDone] = useDState(false);
  useDEffect(() => {
    setOut(""); setDone(false);
    if (!start) return;
    let i = 0;
    const startT = setTimeout(() => {
      const tick = () => {
        i += 1;
        setOut(text.slice(0, i));
        if (i < text.length) setTimeout(tick, speed);
        else setDone(true);
      };
      tick();
    }, delay);
    return () => clearTimeout(startT);
  }, [text, start, delay, speed]);
  return [out, done];
}

function ProductDemo() {
  // Phase 0: idle/prompt typing
  // Phase 1: AI replies streaming
  // Phase 2: Build log animates
  // Phase 3: Storefront fades in
  // Phase 4: hold
  const [tick, setTick] = useDState(0); // 0..N, drives the whole sequence
  const [loopKey, setLoopKey] = useDState(0);
  const containerRef = useDRef(null);

  // restart loop
  useDEffect(() => {
    let mounted = true;
    const total = 13000;
    const start = Date.now();
    const tickFn = () => {
      if (!mounted) return;
      const dt = Date.now() - start;
      setTick(dt);
      if (dt > total) {
        setTimeout(() => { if (mounted) setLoopKey((k) => k + 1); }, 600);
        return;
      }
      requestAnimationFrame(tickFn);
    };
    requestAnimationFrame(tickFn);
    return () => { mounted = false; };
  }, [loopKey]);

  // Prompt typewriter — start at 200ms, finish ~2300ms
  const promptTyped = (() => {
    const start = 200;
    const speed = 22; // ms/char
    if (tick < start) return "";
    const chars = Math.min(DEMO_PROMPT.length, Math.floor((tick - start) / speed));
    return DEMO_PROMPT.slice(0, chars);
  })();
  const promptDone = promptTyped.length >= DEMO_PROMPT.length;
  const promptSubmittedAt = 200 + DEMO_PROMPT.length * 22 + 250;

  // AI reply 1
  const aiStartAt = promptSubmittedAt + 600;
  const aiSpeed = 14;
  const aiLines = AI_REPLY_LINES.map((line, li) => {
    const baseStart = aiStartAt + AI_REPLY_LINES.slice(0, li).reduce((s, l) => s + l.length * aiSpeed + 400, 0);
    if (tick < baseStart) return { text: "", done: false, started: false };
    const n = Math.min(line.length, Math.floor((tick - baseStart) / aiSpeed));
    return { text: line.slice(0, n), done: n >= line.length, started: true };
  });
  const aiFullyDone = aiLines.every((l) => l.done);
  const buildStartAt = aiStartAt + AI_REPLY_LINES.reduce((s, l) => s + l.length * aiSpeed + 400, 0) + 200;

  // Build log entries appear at buildStartAt + line.t
  const builds = BUILD_LINES.map((b) => ({
    ...b,
    visible: tick >= buildStartAt + b.t,
    completed: tick >= buildStartAt + b.t + 350,
  }));
  const allBuilt = builds[builds.length - 1].completed;
  const deployAt = buildStartAt + BUILD_LINES[BUILD_LINES.length - 1].t + 350;

  // Storefront wireframe appears as soon as 'brand kit' is set, full storefront after deploy
  const wireAt = buildStartAt + BUILD_LINES[1].t + 200;
  const showWire = tick >= wireAt && tick < deployAt;
  const showFinal = tick >= deployAt;

  return (
    <section className="section demo-shell" id="product">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow"><span className="num">01 ——</span> The build</span>
          <h2>One sentence in.<br/><span className="accent">A live business</span> out.</h2>
          <p className="lede">No templates. No drag-and-drop. Dispatch reasons about your category, designs the brand,
          writes the copy, models the products, configures payments, and ships a production storefront — usually before your coffee gets cold. You approve what matters; it builds the rest.</p>
        </div>

        <div className="demo-window" ref={containerRef}>
          <div className="demo-bar">
            <div className="demo-dots"><span /><span /><span /></div>
            <div className="demo-url">
              <span className="pad">project &nbsp;/&nbsp; uji-matcha</span>
            </div>
            <div style={{display: "flex", gap: 6, color: "var(--ink-3)", fontSize: 10.5, fontFamily: "Geist Mono, monospace"}}>
              <span style={{padding: "4px 10px", border: "1px solid rgba(255,255,255,0.4)", background: "rgba(255,255,255,0.2)", borderRadius: 999, backdropFilter: "blur(10px)"}}>live</span>
            </div>
          </div>

          <div className="demo-body">
            {/* CHAT PANE */}
            <div className="demo-chat">
              <div style={{fontFamily: "Geist Mono, monospace", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.14em", color: "var(--ink-4)"}}>Conversation</div>

              {/* User message */}
              <div className="msg user">
                <div className="who">You</div>
                <div className="bubble">
                  {promptTyped}
                  {!promptDone && <span className="caret" style={{background: "var(--paper)"}} />}
                </div>
              </div>

              {/* AI reply */}
              {tick >= aiStartAt && (
                <div className="msg ai">
                  <div className="who" style={{display: "inline-flex", alignItems: "center", gap: 6}}>
                    <Sparkle size={10} /> Dispatch
                  </div>
                  <div className="bubble">
                    {aiLines.map((l, i) => (
                      <div key={i} style={{marginBottom: 6}}>
                        {l.text}
                        {l.started && !l.done && <span className="caret" />}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Build log */}
              {tick >= buildStartAt && (
                <div className="log">
                  {builds.map((b, i) => (
                    b.visible && (
                      <div className="ln" key={i}>
                        <span className={b.completed ? "tick" : "pend"}>{b.completed ? "✓" : "○"}</span>
                        <span className="lbl">{b.lbl}</span>
                        <span className="val">{b.val}</span>
                      </div>
                    )
                  ))}
                </div>
              )}

              {/* Thinking dots between phases */}
              {(!promptDone || (promptDone && !aiLines[0].started) || (aiFullyDone && tick < buildStartAt + BUILD_LINES[0].t)) && (
                <div className="thinking" style={{marginTop: 4}}>
                  <span className="dot"></span><span className="dot"></span><span className="dot"></span>
                  <span style={{marginLeft: 8, fontFamily: "Geist Mono, monospace", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase"}}>Thinking</span>
                </div>
              )}

              {allBuilt && (
                <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 4}}>
                  <div style={{fontSize: 12, color: "var(--ink-3)"}}>Total build · <span style={{color: "var(--ink)"}}>1m 47s</span></div>
                  <a href="#" className="btn btn-outline" style={{height: 32, fontSize: 12, padding: "0 12px"}}>Open store <ArrowRight size={12}/></a>
                </div>
              )}
            </div>

            {/* STAGE PANE */}
            <div className="demo-stage">
              {/* Empty state */}
              {!showWire && !showFinal && (
                <div className="stage-empty" style={{position: "absolute", inset: 24}}>
                  <div className="ring" />
                  <div>Awaiting prompt</div>
                </div>
              )}

              {/* Wireframe state */}
              {showWire && <Wireframe />}

              {/* Final storefront */}
              <div className={"sf-frame" + (showFinal ? " show" : "")} style={{display: showFinal ? "flex" : "none"}}>
                <Storefront />
              </div>
            </div>
          </div>
        </div>

        <div className="generated-grid">
          {[
            { t: "Brand identity",   s: "Logo, type, palette, voice",          k: "brand" },
            { t: "Product catalog",  s: "Names, copy, photography, pricing",   k: "catalog" },
            { t: "Storefront",       s: "Pages, navigation, layouts, mobile",  k: "storefront" },
            { t: "Operations",       s: "Payments, tax, shipping, support",    k: "checkout" },
          ].map((c) => (
            <div className="gen-card" key={c.t}>
              <div className="gen-card-top">
                <span className="gen-tag"><span className="gen-tag-dot" />Generated</span>
                <span className="gen-icon"><Glyph kind={c.k} size={20} /></span>
              </div>
              <div className="gen-card-body">
                <div className="gen-title">{c.t}</div>
                <div className="gen-sub">{c.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Wireframe() {
  return (
    <div style={{position: "absolute", inset: 24, display: "flex", flexDirection: "column", gap: 14}}>
      <div style={{display: "flex", justifyContent: "space-between", paddingBottom: 14, borderBottom: "1px dashed var(--hairline-strong)"}}>
        <div style={{width: 90, height: 12, background: "var(--hairline)", borderRadius: 2}} />
        <div style={{display: "flex", gap: 10}}>
          <div style={{width: 38, height: 8, background: "var(--hairline)", borderRadius: 2}} />
          <div style={{width: 38, height: 8, background: "var(--hairline)", borderRadius: 2}} />
          <div style={{width: 38, height: 8, background: "var(--hairline)", borderRadius: 2}} />
        </div>
      </div>
      <div style={{display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 20, alignItems: "stretch"}}>
        <div style={{display: "flex", flexDirection: "column", gap: 10, justifyContent: "center"}}>
          <div style={{width: "85%", height: 26, background: "var(--hairline)", borderRadius: 4}} />
          <div style={{width: "70%", height: 26, background: "var(--hairline)", borderRadius: 4}} />
          <div style={{width: "60%", height: 10, background: "var(--hairline)", borderRadius: 2, marginTop: 6}} />
          <div style={{width: "50%", height: 10, background: "var(--hairline)", borderRadius: 2}} />
          <div style={{width: 100, height: 26, background: "var(--ink-4)", borderRadius: 999, marginTop: 8, opacity: 0.4}} />
        </div>
        <div style={{background: "var(--hairline)", borderRadius: 8, minHeight: 160}} />
      </div>
      <div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginTop: 8}}>
        {[0,1,2].map(i => (
          <div key={i} style={{border: "1px dashed var(--hairline-strong)", borderRadius: 8, padding: 8, display: "flex", flexDirection: "column", gap: 6}}>
            <div style={{aspectRatio: 1, background: "var(--hairline)", borderRadius: 4}} />
            <div style={{width: "60%", height: 8, background: "var(--hairline)", borderRadius: 2}} />
            <div style={{width: "40%", height: 6, background: "var(--hairline)", borderRadius: 2}} />
          </div>
        ))}
      </div>
      <div style={{position: "absolute", top: 0, right: 0, fontFamily: "Geist Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-4)"}}>
        Layout · drafting
      </div>
    </div>
  );
}

function Storefront() {
  return (
    <>
      <div className="sf-nav sf-nav-hi">
        <div className="sf-logo sf-logo-hi">
          <span className="sf-mark">辰</span>
          <span>Hoshino Matcha</span>
        </div>
        <div className="links sf-links-hi">
          <span>Shop</span>
          <span>Subscription</span>
          <span>Story</span>
          <span>Journal</span>
          <span className="sf-cart">Cart · 0</span>
        </div>
      </div>
      <div className="sf-hero sf-hero-hi">
        <div className="sf-hero-copy">
          <div className="sf-eyebrow-hi">— Spring harvest · Uji, Kyoto</div>
          <div className="sf-h1 sf-h1-hi">
            Stone-milled<br/>
            ceremonial matcha,<br/>
            <span className="sf-h1-italic">delivered fresh.</span>
          </div>
          <div className="sf-sub sf-sub-hi">From a family farm tended for four generations. Sealed in nitrogen tins the morning it ships, so it tastes the way it would in Kyoto.</div>
          <div className="sf-row">
            <button className="sf-cta sf-cta-hi">Start your subscription <ArrowRight size={11}/></button>
            <span className="sf-pill sf-pill-hi">Free shipping · US / EU / JP</span>
          </div>
          <div className="sf-trust">
            <span>★ 4.9 · 1,420 subscribers</span>
            <span className="sf-trust-dot" />
            <span>As featured in Kinfolk</span>
          </div>
        </div>
        <div className="sf-img sf-img-hi">
          <div className="sf-tin">
            <div className="sf-tin-label">
              <div className="sf-tin-kanji">星野</div>
              <div className="sf-tin-mark">HOSHINO · MATCHA</div>
              <div className="sf-tin-rule" />
              <div className="sf-tin-grade">CEREMONIAL · 30G</div>
            </div>
          </div>
          <div className="sf-leaves" />
          <span className="tag sf-tag-hi">Spring 2026 harvest</span>
        </div>
      </div>
      <div className="sf-grid sf-grid-hi">
        <div className="sf-prod sf-prod-hi">
          <div className="ph sf-ph-1">
            <span className="sf-badge">Most popular</span>
            <div className="sf-prod-mark">月</div>
          </div>
          <div className="meta sf-meta-hi">
            <span className="name">Monthly Tin · 30g</span>
            <span className="sf-prod-desc">Ceremonial grade, ships first of the month.</span>
            <span className="price sf-price-hi">$32<span className="sf-per">/mo</span></span>
          </div>
        </div>
        <div className="sf-prod sf-prod-hi">
          <div className="ph sf-ph-2">
            <span className="sf-badge sf-badge-gift">Gift</span>
            <div className="sf-prod-mark">季</div>
          </div>
          <div className="meta sf-meta-hi">
            <span className="name">Quarterly Box · 120g</span>
            <span className="sf-prod-desc">Tin, chawan, chasen, and a hand-written note.</span>
            <span className="price sf-price-hi">$96<span className="sf-per">/qtr</span></span>
          </div>
        </div>
        <div className="sf-prod sf-prod-hi">
          <div className="ph sf-ph-3">
            <span className="sf-badge sf-badge-new">New</span>
            <div className="sf-prod-mark">初</div>
          </div>
          <div className="meta sf-meta-hi">
            <span className="name">Starter Kit</span>
            <span className="sf-prod-desc">Everything for your first bowl, no subscription.</span>
            <span className="price sf-price-hi">$54<span className="sf-per">once</span></span>
          </div>
        </div>
      </div>
    </>
  );
}

window.ProductDemo = ProductDemo;
