// Demo scenes 1-5 — English, USD only, no Chinese characters
const { motion: m1, AnimatePresence: AP1 } = window;

const D = () => window.SOKO_DATA;
const supplierById = (id) => D().suppliers.find(s => s.id === id);
const productById = (id) => D().products.find(p => p.id === id);
const fwdById = (id) => D().forwarders.find(f => f.id === id);
const plById = (id) => D().threePls.find(p => p.id === id);

// ====== SCENE 1: Hero ======
function Scene1Hero({ progress }) {
  const tagline = "Smart sourcing from China for sellers on Mercado Libre, Magalu and Falabella.";
  const showTag = progress > 0.15;
  const showCta = progress > 0.55;
  const typed = window.useTypewriter(tagline, 55, showTag);

  return (
    <div style={{
      position: "absolute", inset: 0, padding: "32px 28px",
      display: "flex", flexDirection: "column",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ fontSize: 11, fontFamily: "ui-monospace, monospace", color: "#a8a29e", letterSpacing: 1 }}>v0.9 BETA</span>
        <window.LangToggle value="EN" />
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", gap: 24 }}>
        <window.FadeUp delay={0.05}>
          <window.SokoWordmark size={56} />
        </window.FadeUp>

        <div style={{
          fontSize: 18, lineHeight: 1.35, color: "#1c1917",
          fontFamily: "'Inter', -apple-system, sans-serif",
          fontWeight: 500,
          minHeight: 90,
        }}>
          {typed}
          {showTag && typed.length < tagline.length && (
            <span style={{ display: "inline-block", width: 2, height: 18, background: "oklch(0.55 0.16 40)", marginLeft: 2, verticalAlign: "middle" }} />
          )}
        </div>

        {showCta && (
          <m1.button
            initial={{ opacity: 0, scale: 0.96 }}
            animate={{ opacity: 1, scale: [0.96, 1.04, 1] }}
            transition={{ duration: 0.6 }}
            style={{
              padding: "14px 28px", border: "none",
              background: "oklch(0.55 0.16 40)", color: "#fafaf9",
              borderRadius: 10, fontSize: 14, fontWeight: 600,
              fontFamily: "inherit", letterSpacing: 0.2,
              cursor: "pointer",
              boxShadow: "0 8px 24px -8px oklch(0.55 0.16 40 / 0.4)",
            }}
          >
            Get started →
          </m1.button>
        )}
      </div>

      <div style={{
        fontSize: 10, fontFamily: "ui-monospace, monospace",
        color: "#a8a29e", letterSpacing: 0.8, lineHeight: 1.6,
      }}>
        Powered by AI · Vetted logistics · 4 LATAM markets<br />
        MX · BR · CL · CO
      </div>
    </div>
  );
}

// ====== SCENE 2: Onboarding interview ======
function Scene2Onboarding({ progress }) {
  const turns = D().interview;
  const visibleTurns = Math.floor(progress * (turns.length + 1));

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column" }}>
      <div style={{
        padding: "12px 20px 10px", display: "flex", alignItems: "center", gap: 10,
        borderBottom: "1px solid #f5f5f4",
      }}>
        <window.SokoMark size={28} pulsing />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: "#1c1917" }}>soko</div>
          <div style={{ fontSize: 10, color: "#78716c", fontFamily: "ui-monospace, monospace" }}>your sourcing agent</div>
        </div>
        <window.LangToggle value="EN" />
      </div>

      <div style={{ flex: 1, padding: "16px 20px", display: "flex", flexDirection: "column", gap: 10, overflow: "hidden" }}>
        {turns.slice(0, visibleTurns).map((turn, i) => (
          <ChatBubble key={i} turn={turn} />
        ))}
      </div>
    </div>
  );
}

function ChatBubble({ turn }) {
  const isAgent = turn.speaker === "agent";
  const typed = window.useTypewriter(isAgent && !turn.thinking ? turn.text : "", 35, isAgent && !turn.thinking);
  const text = isAgent && !turn.thinking ? typed : turn.text;

  return (
    <m1.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      style={{
        display: "flex", justifyContent: isAgent ? "flex-start" : "flex-end",
      }}
    >
      <div style={{
        maxWidth: "78%",
        padding: "10px 14px",
        borderRadius: isAgent ? "4px 14px 14px 14px" : "14px 4px 14px 14px",
        background: isAgent ? "#f5f5f4" : "oklch(0.55 0.16 40)",
        color: isAgent ? "#1c1917" : "#fafaf9",
        fontSize: 14, lineHeight: 1.4,
      }}>
        {turn.thinking ? (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span style={{ color: "#57534e" }}>{turn.text}</span>
            <window.ThreeDots />
          </span>
        ) : text}
      </div>
    </m1.div>
  );
}

// ====== SCENE 3: Plan generated ======
function Scene3Plan({ progress }) {
  const plan = D().plan;
  const supplierObjs = plan.suppliers.map(supplierById);
  const fwd = fwdById(plan.forwarderId);
  const pl = plById(plan.threePlId);

  const stage = Math.floor(progress * 6);

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", padding: "14px 18px 0" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <window.SokoMark size={20} />
          <span style={{ fontSize: 11, color: "#78716c", fontFamily: "ui-monospace, monospace" }}>plan generated in 4.2s</span>
        </div>
        <window.LangToggle value="EN" />
      </div>

      <div style={{
        fontSize: 22, fontFamily: "'Inter', -apple-system, sans-serif",
        color: "#1c1917", marginBottom: 14, fontWeight: 600,
        letterSpacing: -0.3,
      }}>
        Your sourcing plan
      </div>

      <div style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column", gap: 10 }}>
        {stage >= 1 && (
          <PlanSection label="PLATFORMS">
            <div style={{ display: "flex", gap: 8 }}>
              {plan.platforms.map(p => (
                <div key={p.name} style={{
                  flex: 1, padding: "10px 12px",
                  background: p.role === "primary" ? "oklch(0.96 0.04 50)" : "#fafaf9",
                  border: `1px solid ${p.role === "primary" ? "oklch(0.85 0.06 50)" : "#e7e5e4"}`,
                  borderRadius: 8,
                }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "#1c1917" }}>{p.name}</div>
                  <div style={{ fontSize: 10, color: "#78716c", fontFamily: "ui-monospace, monospace", marginTop: 2 }}>{p.role.toUpperCase()} · {p.note}</div>
                </div>
              ))}
            </div>
          </PlanSection>
        )}

        {stage >= 2 && (
          <PlanSection label="RECOMMENDED SUPPLIERS">
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {supplierObjs.map(s => (
                <div key={s.id} style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "8px 10px", border: "1px solid #f5f5f4", borderRadius: 6,
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 4,
                    background: "linear-gradient(135deg, oklch(0.78 0.04 50), oklch(0.55 0.04 30))",
                    flexShrink: 0,
                  }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#1c1917", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                    <div style={{ fontSize: 9, color: "#78716c", fontFamily: "ui-monospace, monospace" }}>{s.province} · {s.years}y · {s.response}% resp</div>
                  </div>
                  <window.TrustPassBadge kind={s.badge.includes("Audit") ? "Audit" : "TrustPass"} />
                </div>
              ))}
            </div>
          </PlanSection>
        )}

        {stage >= 3 && (
          <PlanSection label="FORWARDER">
            <div style={{
              padding: "10px 12px", background: "#fafaf9",
              border: "1px solid #e7e5e4", borderRadius: 8,
              display: "flex", alignItems: "center", gap: 10,
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 4,
                background: "oklch(0.92 0.02 220)",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="oklch(0.42 0.08 220)" strokeWidth="1.8">
                  <path d="M2 16h20M2 16l3-9h14l3 9M6 16v3M18 16v3" strokeLinecap="round" />
                </svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: "#1c1917" }}>{fwd.name}</div>
                <div style={{ fontSize: 10, color: "#78716c", fontFamily: "ui-monospace, monospace" }}>{fwd.city} · Sea freight · 28–35 days</div>
              </div>
            </div>
          </PlanSection>
        )}

        {stage >= 4 && (
          <PlanSection label="3PL IN MEXICO">
            <div style={{
              padding: "10px 12px", background: "#fafaf9",
              border: "1px solid #e7e5e4", borderRadius: 8,
            }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "#1c1917" }}>{pl.name}</div>
              <div style={{ fontSize: 10, color: "#78716c", fontFamily: "ui-monospace, monospace", marginTop: 2 }}>
                {pl.city} · NOM ✓ · Repack ✓ · Photography ✓
              </div>
            </div>
          </PlanSection>
        )}

        {stage >= 5 && (
          <m1.div
            initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
            style={{
              marginTop: "auto", marginBottom: 12,
              padding: "12px 14px",
              background: "linear-gradient(180deg, oklch(0.97 0.03 50), oklch(0.94 0.04 50))",
              border: "1px solid oklch(0.88 0.06 50)",
              borderRadius: 10,
              display: "flex", justifyContent: "space-between",
              fontFamily: "ui-monospace, monospace",
            }}
          >
            <Stat n="$5,910" l="total cost" />
            <Stat n="38%" l="margin" />
            <Stat n="45d" l="to first sale" />
          </m1.div>
        )}
      </div>
    </div>
  );
}

function PlanSection({ label, children }) {
  return (
    <m1.div
      initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35 }}
    >
      <div style={{ fontSize: 9, color: "#a8a29e", fontFamily: "ui-monospace, monospace", letterSpacing: 1, marginBottom: 5 }}>{label}</div>
      {children}
    </m1.div>
  );
}

function Stat({ n, l }) {
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: "oklch(0.42 0.16 40)" }}>{n}</div>
      <div style={{ fontSize: 8, color: "#78716c", letterSpacing: 0.5, marginTop: 1 }}>{l}</div>
    </div>
  );
}

// ====== SCENE 4: Browse 1688 ======
function Scene4Browse({ progress }) {
  const items = D().products.slice(0, 6);
  const scrollY = Math.max(0, (progress - 0.15) * 60);
  const zoomIn = progress > 0.85;

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column" }}>
      <div style={{ padding: "12px 18px 8px", borderBottom: "1px solid #f5f5f4" }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "8px 12px", background: "#f5f5f4", borderRadius: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#78716c" strokeWidth="2">
            <circle cx="11" cy="11" r="7" /><path d="M21 21l-4-4" strokeLinecap="round" />
          </svg>
          <input value="women's activewear" readOnly style={{
            flex: 1, border: "none", background: "transparent", fontSize: 13, color: "#1c1917", outline: "none",
            fontFamily: "inherit",
          }} />
          <window.CurrencyToggle value="USD" />
        </div>
        <div style={{
          marginTop: 8, fontSize: 10, color: "#78716c",
          fontFamily: "ui-monospace, monospace", display: "flex", alignItems: "center", gap: 6,
        }}>
          <svg width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="oklch(0.55 0.16 40)" strokeWidth="1.5">
            <circle cx="6" cy="6" r="5" /><path d="M6 3v3l2 2" strokeLinecap="round" />
          </svg>
          1688 catalog · auto-translated to EN
        </div>
      </div>

      <div style={{ flex: 1, overflow: "hidden", padding: "12px 14px", position: "relative" }}>
        <m1.div
          animate={{ y: -scrollY, scale: zoomIn ? 1.08 : 1 }}
          transition={{ duration: zoomIn ? 0.6 : 0.1, ease: "easeOut" }}
          style={{
            display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10,
            transformOrigin: "top left",
          }}
        >
          {items.map((p, i) => (
            <m1.div key={p.id}
              initial={{ opacity: 0, y: 6 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.06 }}
              style={{
                background: "#fff", border: "1px solid #f5f5f4", borderRadius: 10,
                overflow: "hidden",
              }}>
              <window.ProductPlaceholder product={p} height={100} />
              <div style={{ padding: 8 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: "#1c1917", lineHeight: 1.3, minHeight: 28, overflow: "hidden" }}>
                  {p.en}
                </div>
                <div style={{
                  marginTop: 6, display: "flex", justifyContent: "space-between", alignItems: "center",
                  fontFamily: "ui-monospace, monospace",
                }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: "oklch(0.42 0.16 40)" }}>
                    ${p.tiers[0].usd.toFixed(2)}–${p.tiers[p.tiers.length - 1].usd.toFixed(2)}
                  </span>
                  <span style={{ fontSize: 8, color: "#78716c" }}>MOQ {p.moq}</span>
                </div>
                <div style={{ marginTop: 6, fontSize: 9, color: "#78716c", display: "flex", alignItems: "center", gap: 4 }}>
                  <svg width="9" height="9" viewBox="0 0 12 12" fill="oklch(0.42 0.08 180)">
                    <circle cx="6" cy="6" r="5" />
                    <path d="M3.5 6L5 7.5L8 4.5" stroke="#fafaf9" strokeWidth="1.4" fill="none" strokeLinecap="round" />
                  </svg>
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{supplierById(p.supplierId).name.split(" ").slice(0, 2).join(" ")}</span>
                </div>
              </div>
            </m1.div>
          ))}
        </m1.div>
      </div>
    </div>
  );
}

// ====== SCENE 5: Product detail ======
function Scene5Detail({ progress }) {
  const p = productById("p-01");
  const sup = supplierById(p.supplierId);
  const showInch = progress > 0.55;

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column" }}>
      <window.ProductPlaceholder product={p} height={140} />
      <div style={{ padding: "12px 18px 10px" }}>
        <window.BilingualTitle en={p.en} size={15} />
      </div>

      <div style={{ display: "flex", gap: 16, padding: "0 18px", borderBottom: "1px solid #f5f5f4" }}>
        {["Overview", "Sizes", "Variants", "Supplier"].map((t, i) => (
          <div key={t} style={{
            fontSize: 12, padding: "8px 0",
            color: i === 1 ? "#1c1917" : "#a8a29e",
            fontWeight: i === 1 ? 600 : 400,
            borderBottom: i === 1 ? "2px solid oklch(0.55 0.16 40)" : "2px solid transparent",
            marginBottom: -1,
          }}>{t}</div>
        ))}
      </div>

      <div style={{ flex: 1, padding: "12px 18px", overflow: "hidden" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
          <span style={{ fontSize: 10, fontFamily: "ui-monospace, monospace", color: "#78716c", letterSpacing: 0.5 }}>SIZE CHART</span>
          <m1.div animate={{ scale: showInch ? [1, 1.05, 1] : 1 }} transition={{ duration: 0.3 }}>
            <window.UnitToggle value={showInch ? "inch" : "cm"} />
          </m1.div>
        </div>

        <table style={{ width: "100%", fontSize: 11, borderCollapse: "collapse", fontFamily: "ui-monospace, monospace" }}>
          <thead>
            <tr style={{ color: "#a8a29e", fontWeight: 400 }}>
              <th style={{ textAlign: "left", padding: "6px 0", fontWeight: 400 }}>Size</th>
              <th style={{ textAlign: "right", padding: "6px 0", fontWeight: 400 }}>Chest</th>
              <th style={{ textAlign: "right", padding: "6px 0", fontWeight: 400 }}>Length</th>
              <th style={{ textAlign: "right", padding: "6px 0", fontWeight: 400 }}>Shoulder</th>
              <th style={{ textAlign: "right", padding: "6px 0", fontWeight: 400 }}>Hip</th>
            </tr>
          </thead>
          <tbody>
            {p.measurements.map((m, idx) => (
              <m1.tr key={m.size}
                initial={{ opacity: 0, x: -4 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.1 + idx * 0.08 }}
                style={{ borderTop: "1px solid #f5f5f4", color: "#1c1917" }}
              >
                <td style={{ padding: "7px 0", fontWeight: 600 }}>{m.size}</td>
                <td style={{ padding: "7px 0", textAlign: "right" }}>{showInch ? (m.chest / 2.54).toFixed(1) : m.chest}</td>
                <td style={{ padding: "7px 0", textAlign: "right" }}>{showInch ? (m.length / 2.54).toFixed(1) : m.length}</td>
                <td style={{ padding: "7px 0", textAlign: "right" }}>{showInch ? (m.shoulder / 2.54).toFixed(1) : m.shoulder}</td>
                <td style={{ padding: "7px 0", textAlign: "right" }}>{showInch ? (m.hip / 2.54).toFixed(1) : m.hip}</td>
              </m1.tr>
            ))}
          </tbody>
        </table>

        <div style={{ marginTop: 14 }}>
          <div style={{ fontSize: 10, fontFamily: "ui-monospace, monospace", color: "#78716c", letterSpacing: 0.5, marginBottom: 6 }}>VARIANTS · 16 SKU</div>
          <div style={{ display: "grid", gridTemplateColumns: "70px repeat(4, 1fr)", gap: 4, fontSize: 10 }}>
            <div></div>
            {p.sizes.map(s => <div key={s} style={{ textAlign: "center", color: "#78716c", fontFamily: "ui-monospace, monospace" }}>{s}</div>)}
            {p.colors.map((c, ci) => (
              <React.Fragment key={c.en}>
                <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 10, color: "#1c1917" }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: c.swatch, border: "1px solid #e7e5e4" }} />
                  {c.en}
                </div>
                {p.sizes.map((s, si) => (
                  <m1.div key={s}
                    animate={ci === 1 && si === 2 ? { boxShadow: ["0 0 0 0 oklch(0.55 0.16 40 / 0)", "0 0 0 3px oklch(0.55 0.16 40 / 0.3)", "0 0 0 0 oklch(0.55 0.16 40 / 0)"] } : {}}
                    transition={{ duration: 1.6, repeat: Infinity }}
                    style={{
                      height: 22, borderRadius: 4,
                      border: "1px solid #e7e5e4",
                      background: ci === 1 && si === 2 ? "oklch(0.96 0.04 50)" : "#fafaf9",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 9, color: "#78716c", fontFamily: "ui-monospace, monospace",
                    }}
                  >
                    {Math.floor(Math.random() * 9 + 1) * 100}
                  </m1.div>
                ))}
              </React.Fragment>
            ))}
          </div>
        </div>

        <m1.div
          initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.6 }}
          style={{
            marginTop: 14, padding: "10px 12px",
            background: "#fafaf9", border: "1px solid #f5f5f4", borderRadius: 8,
          }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: "#1c1917" }}>{sup.name}</div>
          <div style={{ fontSize: 9, color: "#78716c", marginTop: 2, fontFamily: "ui-monospace, monospace", display: "flex", flexWrap: "wrap", gap: 6 }}>
            <span>{sup.province}</span><span>·</span>
            <span>{sup.years} years</span><span>·</span>
            <span>{sup.response}% resp</span><span>·</span>
            <span>${sup.volumeUsd}M / yr</span>
          </div>
          <div style={{ marginTop: 6 }}>
            <window.TrustPassBadge kind="Audit" />
          </div>
        </m1.div>
      </div>
    </div>
  );
}

Object.assign(window, { Scene1Hero, Scene2Onboarding, Scene3Plan, Scene4Browse, Scene5Detail });
