/* global React */
// V2 — single continuous canvas. Seed plant-drag, industry pick (species
// transforms), platform pick (pot), bloom opens to working app UI, seed
// packet email capture.

// --- HubSpot lead capture ---
// Portal ID (aka Hub ID) for noodleseed.com account
const HUBSPOT_PORTAL_ID = "244706579";
// PASTE the Form ID (UUID) from the form created in HubSpot → Marketing → Forms.
// See HUBSPOT_SETUP.md for the exact field setup.
const HUBSPOT_FORM_ID  = "203a8855-f716-418c-900e-867d1d901c15";
const LEAD_SOURCE_TAG  = "Startup Grind 2026";

function submitToHubSpot({ email }) {
  if (!HUBSPOT_FORM_ID || HUBSPOT_FORM_ID === "REPLACE_WITH_FORM_ID") {
    console.warn("[HubSpot] Form ID not set — skipping submission.");
    return;
  }
  const url = `https://api.hsforms.com/submissions/v3/integration/submit/${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_ID}`;
  const hutkMatch = document.cookie.match(/hubspotutk=([^;]+)/);
  const context = {
    pageUri: window.location.href,
    pageName: "Plant a Seed — Startup Grind 2026 booth"
  };
  if (hutkMatch) context.hutk = hutkMatch[1];
  fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      fields: [{ objectTypeId: "0-1", name: "email", value: email }],
      context
    })
  }).then(r => r.json()).then(body => {
    console.log("[HubSpot] submitted:", email, body.inlineMessage !== undefined ? "ok" : body);
  }).catch(err => console.error("[HubSpot] failed:", err));
}

const INDUSTRIES_V2 = ["Coffee shop", "Bakery", "Yoga studio", "Creator", "Online store", "Real estate", "Consultant", "Restaurant", "Other"];

const PLATFORMS_V2 = [
  { id: "chatgpt", name: "ChatGPT", logo: "assets/chatgpt.svg", pot: "#10a37f" },
  { id: "claude",  name: "Claude",  logo: "assets/claude.svg",  pot: "#d97757" },
  { id: "gemini",  name: "Gemini",  logo: "assets/gemini.svg",  pot: "#4285f4" }
];

// Brand marks rendered on a cream disc so full-color logos (Claude, Gemini) pop
// against the colored pot. ChatGPT uses the existing SVG.
const PLATFORM_ASSET = {
  chatgpt: "assets/chatgpt.svg",
  claude:  "assets/claude.png",
  gemini:  "assets/gemini.png"
};
function PlatformMark({ id, size = 56, disc = true }) {
  const src = PLATFORM_ASSET[id];
  if (!src) return null;
  if (!disc) {
    return <img src={src} alt="" style={{ width: size, height: size, display: "block",
      objectFit: "contain" }}/>;
  }
  // Claude's PNG has a baked-in cream square bg — fill the disc edge-to-edge
  // and clip via overflow:hidden so that bg seamlessly becomes the disc.
  // Gemini + ChatGPT are transparent, so inset with padding for breathing room.
  const fill = id === "claude";
  const pad = fill ? 0 : Math.round(size * 0.16);
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: "#f5ebd6",
      border: `2px solid ${LINE}`,
      display: "flex", alignItems: "center", justifyContent: "center",
      boxShadow: "inset 0 2px 4px rgba(0,0,0,0.08)",
      overflow: "hidden"
    }}>
      <img src={src} alt="" style={{
        width: size - pad * 2, height: size - pad * 2, display: "block",
        objectFit: fill ? "cover" : "contain"
      }}/>
    </div>
  );
}

// --------- helpers ----------
function lerp(a, b, t) { return a + (b - a) * t; }

// --------- Seed ----------
function DraggableSeed({ onPlanted }) {
  const [dragging, setDragging] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const startRef = useRef({ x: 0, y: 0 });
  const seedRef = useRef(null);

  useEffect(() => {
    if (!dragging) return;
    const onMove = (e) => {
      const pt = e.touches ? e.touches[0] : e;
      setPos({ x: pt.clientX - startRef.current.x, y: pt.clientY - startRef.current.y });
    };
    const onUp = (e) => {
      setDragging(false);
      const r = seedRef.current?.getBoundingClientRect();
      const soilEl = document.getElementById("v2-soil");
      const soil = soilEl?.getBoundingClientRect();
      if (r && soil && r.bottom > soil.top + 20 && r.left < soil.right && r.right > soil.left) {
        SFX.pop();
        onPlanted();
      } else {
        SFX.soft();
        setPos({ x: 0, y: 0 });
      }
    };
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", onUp);
    window.addEventListener("touchmove", onMove, { passive: false });
    window.addEventListener("touchend", onUp);
    return () => {
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onUp);
    };
  }, [dragging, onPlanted]);

  const onDown = (e) => {
    const pt = e.touches ? e.touches[0] : e;
    startRef.current = { x: pt.clientX, y: pt.clientY };
    setDragging(true);
    SFX.tap();
  };

  return (
    <div
      ref={seedRef}
      onPointerDown={onDown}
      onTouchStart={onDown}
      style={{
        position: "absolute",
        left: "50%", top: "52%",
        transform: `translate(-50%, -50%) translate(${pos.x}px, ${pos.y}px) scale(${dragging ? 1.08 : 1})`,
        cursor: dragging ? "grabbing" : "grab",
        transition: dragging ? "none" : "transform .4s var(--ease-spring)",
        filter: dragging ? "drop-shadow(0 20px 24px rgba(12,10,9,0.25))" : "drop-shadow(0 8px 12px rgba(12,10,9,0.15))",
        zIndex: 40,
        touchAction: "none"
      }}
    >
      <svg width="90" height="120" viewBox="0 0 90 120" fill="none">
        <ellipse cx="45" cy="58" rx="26" ry="34" fill="#6b3b1f"/>
        <ellipse cx="45" cy="58" rx="26" ry="34" fill="none" stroke="#2d1a0c" strokeWidth="1.4"/>
        <path d="M45 30 C 40 45 40 72 45 88 M45 30 C 50 45 50 72 45 88" stroke="#3d1f0f" strokeWidth="1" fill="none" opacity="0.5"/>
        <ellipse cx="38" cy="48" rx="6" ry="10" fill="#8a4e2a" opacity="0.5"/>
      </svg>
    </div>
  );
}

// --------- Seed Packet (industry picker) ----------
function SeedPacket({ industry, onPick, selected }) {
  const sp = SPECIES[industry];
  if (!sp) return null;
  const { C } = sp;
  return (
    <button onPointerDown={() => { SFX.pop(); onPick(industry); }}
      style={{
        width: 112, height: 168, border: "none", background: "transparent",
        cursor: "pointer", padding: 0, position: "relative",
        transform: selected ? "translateY(-20px) scale(1.05)" : "translateY(0) scale(1)",
        transition: "transform .4s var(--ease-spring)",
        filter: selected ? "drop-shadow(0 16px 20px rgba(12,10,9,0.2))" : "drop-shadow(0 6px 8px rgba(12,10,9,0.12))"
      }}>
      {/* Envelope background */}
      <div style={{
        position: "absolute", inset: 0,
        background: "#f5ebd6",
        border: `1.4px solid ${LINE}`,
        borderRadius: 3,
        boxShadow: "inset 0 0 0 3px #f5ebd6, inset 0 0 0 4px rgba(61,42,24,0.15)"
      }}/>
      {/* torn flap edge */}
      <svg width="112" height="12" viewBox="0 0 112 12" style={{ position: "absolute", top: 4, left: 0, display: "block" }}>
        <path d="M4 4 L 20 10 L 36 2 L 52 10 L 68 2 L 84 10 L 100 2 L 108 4" stroke={LINE} strokeWidth="1.2" fill="none" strokeLinecap="round"/>
      </svg>
      {/* plant preview — small, centered upper region */}
      <div style={{ position: "absolute", top: 14, left: 0, right: 0, height: 100,
        display: "flex", alignItems: "center", justifyContent: "center" }}>
        <svg width="68" height="96" viewBox="0 0 200 280" preserveAspectRatio="xMidYMax meet">
          <C grow={1} bloom={0.5}/>
        </svg>
      </div>
      {/* separator */}
      <div style={{ position: "absolute", left: 10, right: 10, top: 118,
        borderTop: `1px dashed ${LINE}` }}/>
      {/* label band */}
      <div style={{ position: "absolute", bottom: 12, left: 4, right: 4, textAlign: "center",
        fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 14, color: "#3d2a18",
        lineHeight: 1.1, pointerEvents: "none" }}>
        {industry}
        <div style={{ fontFamily: "var(--font-sans)", fontStyle: "normal",
          fontSize: 8, letterSpacing: "0.12em", textTransform: "uppercase",
          color: "#6b4a2a", marginTop: 4 }}>
          {sp.label}
        </div>
      </div>
    </button>
  );
}

// --------- Pot (platform picker) ----------
function Pot({ platform, onPick, selected }) {
  const potW = Math.min(160, Math.floor((window.innerWidth - 80) / 3));
  const potH = Math.round(potW * 0.875);
  const markSize = Math.round(potW * 0.35);
  return (
    <button onPointerDown={() => { SFX.pop(); onPick(platform); }}
      style={{ width: potW, height: potW + 40, border: "none", background: "transparent",
        cursor: "pointer", padding: 0,
        transform: selected ? "translateY(-16px) scale(1.08)" : "translateY(0) scale(1)",
        transition: "transform .4s var(--ease-spring)",
        filter: selected ? "drop-shadow(0 20px 20px rgba(12,10,9,0.22))" : "drop-shadow(0 6px 8px rgba(12,10,9,0.12))" }}>
      <div style={{ position: "relative", width: potW, height: potH }}>
        <svg width={potW} height={potH} viewBox="0 0 160 140" style={{ position: "absolute", inset: 0 }}>
          <path d="M10 30 L 150 30 L 142 44 L 18 44 Z" fill={platform.pot} stroke={LINE} strokeWidth="1.6"/>
          <path d="M18 44 L 142 44 L 128 132 L 32 132 Z" fill={platform.pot} stroke={LINE} strokeWidth="1.6"/>
          <path d="M28 50 L 26 126" stroke="rgba(255,255,255,0.35)" strokeWidth="4" fill="none" strokeLinecap="round"/>
          <path d="M18 44 L 142 44" stroke="rgba(0,0,0,0.18)" strokeWidth="2"/>
        </svg>
        <div style={{ position: "absolute", left: 0, right: 0, top: Math.round(potH * 0.4),
          display: "flex", justifyContent: "center", pointerEvents: "none" }}>
          <PlatformMark id={platform.id} size={markSize}/>
        </div>
      </div>
      <div style={{ marginTop: 4, fontSize: "clamp(12px, 2vw, 16px)", letterSpacing: "0.02em",
        color: platform.pot, fontWeight: 600, fontFamily: "var(--font-sans)" }}>
        {platform.name}
      </div>
    </button>
  );
}

// --------- SeedPacketEmail (final capture) ----------
function SeedPacketEmail({ industry, onSubmit }) {
  const [email, setEmail] = useState("");
  const [sealed, setSealed] = useState(false);
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const sp = SPECIES[industry];
  const { C } = sp || SPECIES["Coffee shop"];

  const seal = () => {
    if (!valid) return;
    SFX.chime();
    setSealed(true);
    setTimeout(() => onSubmit(email), 900);
  };

  return (
    <div style={{ width: "min(320px, 100%)", margin: "0 auto", position: "relative",
      animation: "bloom .6s var(--ease-spring) both" }}>
      <div style={{
        position: "relative",
        background: "#f5ebd6",
        border: `1.5px solid ${LINE}`,
        borderRadius: 6,
        padding: "20px 22px 70px",
        boxShadow: "0 20px 40px -12px rgba(12,10,9,0.25)",
        transform: sealed ? "rotate(-1.5deg)" : "rotate(0)",
        transition: "transform .6s var(--ease-spring)"
      }}>
        {/* torn edge */}
        <svg width="100%" height="10" viewBox="0 0 280 10" style={{ position: "absolute", top: -1, left: 0, right: 0, display: "block" }}>
          <path d="M0 0 L 20 6 L 40 2 L 60 6 L 80 2 L 100 6 L 120 2 L 140 6 L 160 2 L 180 6 L 200 2 L 220 6 L 240 2 L 260 6 L 280 0" fill="#f5ebd6" stroke={LINE} strokeWidth="1.5"/>
        </svg>

        <div style={{ textAlign: "center", marginBottom: 8 }}>
          <div style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 20, color: "#3d2a18" }}>
            Noodle Seed Co.
          </div>
          <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "#6b4a2a", marginTop: 2 }}>
            {SPECIES[industry]?.label || "Seeds"} · est. 2026
          </div>
        </div>

        {/* mini plant illustration on packet */}
        <div style={{ display: "flex", justifyContent: "center", margin: "4px 0 10px" }}>
          <svg width="90" height="120" viewBox="0 0 200 280">
            <C grow={1} bloom={1}/>
          </svg>
        </div>

        {/* ship to */}
        <div style={{ borderTop: `1px dashed ${LINE}`, paddingTop: 10, marginTop: 4 }}>
          <div style={{ fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "#6b4a2a", marginBottom: 4 }}>
            Ship to
          </div>
          <input
            type="email"
            inputMode="email"
            placeholder="you@yourbusiness.com"
            value={email}
            onChange={e => setEmail(e.target.value)}
            disabled={sealed}
            style={{
              width: "100%", background: "transparent", border: "none", outline: "none",
              fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 18,
              color: "#2d1a0c", padding: "4px 0",
              borderBottom: `1px solid ${LINE}`
            }}
          />
        </div>

        {/* wax seal */}
        <div onPointerDown={seal}
          style={{
            position: "absolute", bottom: -18, right: 20, width: 60, height: 60, borderRadius: "50%",
            background: valid ? "radial-gradient(circle at 35% 35%, #4ade80, #16a34a)" : "#c9b89c",
            border: `2px solid ${LINE}`, cursor: valid ? "pointer" : "default",
            display: "flex", alignItems: "center", justifyContent: "center",
            transform: sealed ? "scale(1.15)" : "scale(1)",
            transition: "all .4s var(--ease-spring)",
            boxShadow: valid ? "0 4px 8px rgba(22,163,74,0.4)" : "none",
            animation: valid && !sealed ? "softPulse 2s ease-in-out infinite" : "none"
          }}>
          <svg width="30" height="30" viewBox="0 0 40 40" fill="none">
            <NoodleSeedMark size={24}/>
          </svg>
          <div style={{ position: "absolute", inset: 6, borderRadius: "50%",
            border: "1px dashed rgba(255,255,255,0.4)", pointerEvents: "none" }}/>
        </div>

        {!valid && !sealed && (
          <div style={{ position: "absolute", bottom: -30, left: 0, right: 0,
            textAlign: "center", fontSize: 11, color: "var(--fg-3)", letterSpacing: "0.04em" }}>
            Enter your email → tap the wax seal
          </div>
        )}
      </div>
    </div>
  );
}

// --------- Celebrate (final) ----------
function V2Celebrate({ session, tweaks, onReset }) {
  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", padding: "48px 24px 0",
      animation: "fadeIn .6s var(--ease-apple) both" }}>
      <div style={{ flex: 1, display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "center", gap: 0 }}>
        <div style={{ marginBottom: 18 }}>
          <Badge tone="outline">Planted</Badge>
        </div>
        <h1 style={{ fontSize: "clamp(40px, 6vw, 72px)", margin: 0, textAlign: "center",
          fontWeight: 400, letterSpacing: "-0.02em", lineHeight: 1.05, textWrap: "balance" }}>
          Your <span className="serif-accent">{SPECIES[session.industry]?.label?.toLowerCase() || "seedling"}</span><br/>
          is growing.
        </h1>
        <p className="lead" style={{ marginTop: 18, textAlign: "center", fontSize: 17 }}>
          A sprout arrives at <strong style={{ color: "var(--fg-1)", fontFamily: "var(--font-mono)", fontSize: 15 }}>{session.email}</strong><br/>
          when your {session.industry?.toLowerCase()} app is ready.
        </p>
      </div>
      <div style={{ padding: "24px 0 40%", flexShrink: 0 }}>
        <PillButton variant="primary" size="lg" onClick={onReset}>Plant another →</PillButton>
      </div>
    </div>
  );
}

// --------- The Stage ----------
function V2Stage({ tweaks }) {
  const [phase, setPhase] = useState("seed");        // seed, species, platform, bloom, email, done
  const [session, setSession] = useState({});
  const [grow, setGrow] = useState(0);               // 0..1
  const [bloom, setBloom] = useState(0);             // 0..1

  const reset = () => {
    SFX.tap();
    setSession({});
    setGrow(0); setBloom(0);
    setPhase("seed");
  };

  // plant → sprout
  const onPlant = () => {
    setPhase("species");
    // stem begins to draw
    let t = 0;
    const i = setInterval(() => {
      t += 0.04;
      setGrow(g => Math.min(0.35, g + 0.04));
      if (t >= 0.35) clearInterval(i);
    }, 40);
    SFX.grow();
  };

  // industry chosen → plant finishes growing
  const onPickIndustry = (industry) => {
    setSession(s => ({ ...s, industry }));
    setPhase("platform");
    SFX.grow();
    const start = performance.now();
    const dur = 1400;
    const from = grow;
    const anim = (now) => {
      const t = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - t, 3);
      setGrow(from + (1 - from) * eased);
      if (t < 1) requestAnimationFrame(anim);
    };
    requestAnimationFrame(anim);
  };

  // platform chosen → bloom
  const onPickPlatform = (platform) => {
    setSession(s => ({ ...s, platform }));
    setPhase("bloom");
    SFX.bloom();
    const start = performance.now();
    const dur = 1100;
    const anim = (now) => {
      const t = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - t, 2);
      setBloom(eased);
      if (t < 1) requestAnimationFrame(anim);
      else setTimeout(() => setPhase("email"), 700);
    };
    requestAnimationFrame(anim);
  };

  const onEmail = (email) => {
    setSession(s => ({ ...s, email }));
    setPhase("done");
    submitToHubSpot({ email });
  };

  // Auto-advance: after email phase → celebrate
  // Reset idle after done
  useEffect(() => {
    if (phase !== "done") return;
    const t = setTimeout(() => reset(), 14000);
    return () => clearTimeout(t);
  }, [phase]);

  const species = session.industry ? SPECIES[session.industry] : null;
  const SpeciesComp = species?.C || GenericSprout;

  // positions (percent of stage)
  const potCx = "50%";
  const potCy = "65%";

  // Sky gradient shifts by phase
  const skyColor = phase === "bloom" || phase === "email" || phase === "done"
    ? "linear-gradient(180deg, #fef6ec 0%, #fdf3e5 55%, #f5ebd6 100%)"
    : "linear-gradient(180deg, #fafaf9 0%, #f5f1e8 60%, #e8dcc0 100%)";

  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden",
      background: skyColor, transition: "background 1.2s ease" }}>

      {/* Sun */}
      <div style={{ position: "absolute", top: "8%", right: "10%",
        width: 80, height: 80, borderRadius: "50%",
        background: "radial-gradient(circle, rgba(244,193,74,0.4), transparent 65%)",
        animation: "softPulse 4s ease-in-out infinite", pointerEvents: "none" }}/>

      {/* Soil / ground */}
      <div id="v2-soil" style={{
        position: "absolute", bottom: 0, left: 0, right: 0, height: "32%",
        background: "linear-gradient(180deg, #8a6a3f 0%, #5d4528 60%, #3d2a18 100%)",
        zIndex: 1
      }}>
        {/* ground texture dots */}
        <svg width="100%" height="100%" style={{ position: "absolute", inset: 0, opacity: 0.4 }}>
          {Array.from({ length: 40 }).map((_, i) => (
            <circle key={i} cx={`${(i * 37) % 100}%`} cy={`${10 + (i * 13) % 80}%`} r="1.5" fill="#2d1a0c"/>
          ))}
        </svg>
      </div>

      {/* Grass blades tapered */}
      <svg style={{ position: "absolute", bottom: "31.5%", left: 0, right: 0, width: "100%", height: 20, zIndex: 2 }}
        viewBox="0 0 100 20" preserveAspectRatio="none">
        <path d="M0 20 L 3 12 L 6 20 L 10 10 L 14 20 L 18 14 L 22 20 L 26 8 L 30 20 L 34 13 L 38 20 L 42 9 L 46 20 L 50 12 L 54 20 L 58 10 L 62 20 L 66 14 L 70 20 L 74 8 L 78 20 L 82 12 L 86 20 L 90 10 L 94 20 L 98 14 L 100 20 Z"
          fill="#7a9c6b"/>
      </svg>

      {/* Phase: SEED — hero text + draggable seed */}
      {phase === "seed" && (
        <>
          {/* Background garden: preview of botanicals growing from the soil */}
          <div style={{ position: "absolute", inset: 0, zIndex: 3, pointerEvents: "none" }}>
            {[
              { C: SPECIES["Coffee shop"].C,  left: "4%",  scale: 0.45, delay: 0 },
              { C: SPECIES["Bakery"].C,       left: "14%", scale: 0.32, delay: 200 },
              { C: SPECIES["Yoga studio"].C,  left: "22%", scale: 0.36, delay: 400 },
              { C: SPECIES["Consultant"].C,   left: "78%", scale: 0.36, delay: 300 },
              { C: SPECIES["Creator"].C,      left: "86%", scale: 0.45, delay: 500 },
              { C: SPECIES["Online store"].C, left: "97%", scale: 0.32, delay: 100 }
            ].map((p, i) => (
              <div key={i} style={{
                position: "absolute", left: p.left, bottom: "31%",
                width: 200, height: 280,
                transform: `translateX(-50%) scale(${p.scale})`,
                transformOrigin: "bottom center",
                opacity: 0.45,
                animation: `fadeSlide .9s var(--ease-apple) ${p.delay}ms both`
              }}>
                <svg width="200" height="280" viewBox="0 0 200 280" style={{ overflow: "visible" }}
                  preserveAspectRatio="xMidYMax meet">
                  <p.C grow={1} bloom={1}/>
                </svg>
              </div>
            ))}
          </div>

          <div style={{ position: "absolute", top: "10%", left: 0, right: 0,
            textAlign: "center", padding: "0 24px", zIndex: 10 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
              color: "var(--fg-3)", marginBottom: 10 }}>
              Noodle Seed · a tiny ritual
            </div>
            <h1 style={{ fontSize: "clamp(34px, 5.5vw, 64px)", margin: 0,
              fontWeight: 400, letterSpacing: "-0.025em", lineHeight: 1.02 }}>
              Plant a <span className="serif-accent">seed</span>,
              grow an <span className="serif-accent">app</span>.
            </h1>
            <p className="lead" style={{ marginTop: 12, fontSize: 15, maxWidth: 520,
              margin: "12px auto 0", lineHeight: 1.45 }}>
              Tell us your business. We'll sprout a working app inside ChatGPT, Claude,
              or Gemini — so your customers book, order, and buy without leaving the chat.
            </p>
          </div>
          <DraggableSeed onPlanted={onPlant}/>
          {/* Hint arrow */}
          <div style={{ position: "absolute", left: "50%", top: "63%", transform: "translateX(-50%)",
            fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-3)",
            animation: "fadeIn 1s ease 1.2s both", pointerEvents: "none", zIndex: 10 }}>
            ↓ drag the seed into the soil ↓
          </div>
        </>
      )}

      {/* Phase: plant grows out of soil */}
      {(phase === "species" || phase === "platform") && (
        <div style={{
          position: "absolute",
          left: "50%",
          bottom: phase === "platform" ? "28%" : "32%",
          transform: "translateX(-50%)",
          zIndex: 5,
          transition: "all .6s var(--ease-apple)",
          pointerEvents: "none"
        }}>
          <div style={{ position: "relative", width: 240, height: 280 }}>
            <svg width="240" height="280" viewBox="0 0 200 280"
              style={{ position: "absolute", inset: 0, margin: "auto", overflow: "visible" }}>
              <SpeciesComp grow={grow} bloom={bloom}/>
            </svg>
          </div>
        </div>
      )}

      {/* Phase: species picker */}
      {phase === "species" && (
        <>
          <div style={{ position: "absolute", top: "6%", left: 0, right: 0, textAlign: "center",
            animation: "fadeSlide .5s var(--ease-apple) both" }}>
            <h2 style={{ fontSize: "clamp(26px, 4vw, 42px)", margin: 0, fontWeight: 400,
              letterSpacing: "-0.02em", lineHeight: 1.1 }}>
              Pick your <span className="serif-accent">species</span>.
            </h2>
            <p className="caption" style={{ marginTop: 6 }}>
              Which seed did you bring?
            </p>
          </div>

          <div style={{
            position: "absolute", left: "50%", transform: "translateX(-50%)",
            top: "22%", bottom: "34%",
            width: "min(720px, calc(100vw - 32px))",
            display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap",
            alignContent: "flex-start",
            padding: "0 4px 12px", zIndex: 30,
            overflowY: "auto", WebkitOverflowScrolling: "touch",
          }}>
            {INDUSTRIES_V2.slice(0, 8).map(ind => (
              <SeedPacket key={ind} industry={ind} onPick={onPickIndustry}/>
            ))}
          </div>
        </>
      )}

      {/* Phase: platform picker */}
      {phase === "platform" && (
        <>
          <div style={{ position: "absolute", top: "6%", left: 0, right: 0, textAlign: "center",
            animation: "fadeSlide .5s var(--ease-apple) both" }}>
            <h2 style={{ fontSize: "clamp(26px, 4vw, 42px)", margin: 0, fontWeight: 400,
              letterSpacing: "-0.02em", lineHeight: 1.1 }}>
              Where should it <span className="serif-accent">live</span>?
            </h2>
            <p className="caption" style={{ marginTop: 6 }}>
              Pick a pot. Your app grows inside.
            </p>
          </div>

          <div style={{
            position: "absolute", left: 0, right: 0, bottom: "14%",
            display: "flex", gap: "clamp(8px, 3vw, 30px)", justifyContent: "center",
            padding: "0 12px", zIndex: 30
          }}>
            {PLATFORMS_V2.map(p => (
              <Pot key={p.id} platform={p} onPick={onPickPlatform}/>
            ))}
          </div>
        </>
      )}

      {/* Phase: bloom — flower opens revealing widget, w/ plant + pot as frame */}
      {(phase === "bloom" || phase === "email") && (
        <>
          {/* Small plant + pot icon in upper area */}
          <div style={{
            position: "absolute", left: "50%",
            top: phase === "email" ? "1%" : "10%",
            transform: `translateX(-50%) scale(${phase === "email" ? 0.32 : 0.85})`,
            transformOrigin: "center top",
            zIndex: 5, pointerEvents: "none",
            transition: "all .6s var(--ease-apple)",
            opacity: phase === "email" ? 0.5 : 1
          }}>
            <div style={{ position: "relative", width: 180, height: 220 }}>
              <svg width="180" height="220" viewBox="0 0 200 280"
                style={{ position: "absolute", inset: 0, overflow: "visible" }}>
                <SpeciesComp grow={grow} bloom={bloom}/>
              </svg>
            </div>
            {session.platform && (
              <div style={{ marginTop: -6, display: "flex", justifyContent: "center",
                animation: "bloom .5s var(--ease-spring) both", position: "relative" }}>
                <svg width="110" height="66" viewBox="0 0 120 80">
                  <path d="M12 8 L 108 8 L 102 18 L 18 18 Z" fill={session.platform.pot} stroke={LINE} strokeWidth="1.4"/>
                  <path d="M18 18 L 102 18 L 92 74 L 28 74 Z" fill={session.platform.pot} stroke={LINE} strokeWidth="1.4"/>
                </svg>
                <div style={{ position: "absolute", top: 22, left: 0, right: 0,
                  display: "flex", justifyContent: "center", pointerEvents: "none" }}>
                  <PlatformMark id={session.platform.id} size={34} disc={true}/>
                </div>
              </div>
            )}
          </div>

          {/* Chat widget — in email phase: far smaller + top-anchored */}
          <div style={{
            position: "absolute", left: "50%",
            top: phase === "email" ? "12%" : "38%",
            transform: `translateX(-50%) scale(${phase === "email" ? 0.55 : 1})`,
            transformOrigin: "center top",
            width: "min(340px, 88vw)",
            zIndex: 40,
            opacity: bloom,
            transition: "all .6s var(--ease-apple)"
          }}>
          {/* ChatGPT/etc chat bubble wrapping the widget */}
          <div style={{
            borderRadius: 20, border: "1px solid var(--border)",
            background: "var(--surface-card)",
            boxShadow: "0 20px 40px -12px rgba(12,10,9,0.2)",
            overflow: "hidden",
            animation: "bloom .7s var(--ease-spring) both"
          }}>
            <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--border)",
              background: "var(--bg-subtle)", display: "flex", alignItems: "center", gap: 8 }}>
              <PlatformMark id={session.platform?.id} size={16} disc={false}/>
              <span style={{ fontSize: 11, fontWeight: 500 }}>{session.platform?.name}</span>
              <span style={{ fontSize: 9, color: "var(--fg-3)", marginLeft: "auto",
                letterSpacing: "0.06em", textTransform: "uppercase",
                whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 140 }}>
                · {session.industry?.toLowerCase()}
              </span>
            </div>
            <div style={{ padding: "12px 14px" }}>
              {/* user question */}
              <div style={{ alignSelf: "flex-end", marginLeft: "auto", maxWidth: "85%",
                padding: "8px 12px", borderRadius: "14px 14px 4px 14px",
                background: "var(--stone-950)", color: "#fff", fontSize: 12, lineHeight: 1.4,
                marginBottom: 10, width: "fit-content", marginLeft: "auto" }}>
                {species?.q || "..."}
              </div>
              {/* AI response = app */}
              <div style={{ display: "flex", gap: 6, alignItems: "flex-start" }}>
                <div style={{ width: 22, height: 22, borderRadius: "50%",
                  background: "var(--bg-subtle)", border: "1px solid var(--border)",
                  display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 2 }}>
                  <Halo size={14}/>
                </div>
                <div style={{ flex: 1, padding: "10px 12px", borderRadius: "14px 14px 14px 4px",
                  background: "var(--bg-subtle)", border: "1px solid var(--border)" }}>
                  {species?.widget === "booking" && <MiniBooking industry={session.industry}/>}
                  {species?.widget === "order"   && <MiniOrder industry={session.industry}/>}
                  {species?.widget === "product" && <MiniProduct industry={session.industry}/>}
                </div>
              </div>
            </div>
          </div>
          <p className="caption" style={{ textAlign: "center", marginTop: 10, fontSize: 11 }}>
            Your live app · inside {session.platform?.name}
          </p>
        </div>
        </>
      )}

      {/* Phase: email capture — seed packet anchored bottom */}
      {phase === "email" && (
        <div style={{
          position: "absolute", left: 0, right: 0, bottom: "2%",
          display: "flex", justifyContent: "center",
          padding: "0 16px", zIndex: 50,
          animation: "fadeSlide .6s var(--ease-apple) both .3s"
        }}>
          <SeedPacketEmail industry={session.industry} onSubmit={onEmail}/>
        </div>
      )}

      {/* Phase: done */}
      {phase === "done" && <V2Celebrate session={session} tweaks={tweaks} onReset={reset}/>}

      {/* Reset button (corner, except during seed) */}
      {phase !== "seed" && phase !== "done" && (
        <button onClick={reset}
          style={{ position: "absolute", top: 22, right: 28, zIndex: 100,
            fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase",
            padding: "6px 12px", borderRadius: 9999, border: "1px solid var(--border)",
            background: "rgba(255,255,255,0.7)", backdropFilter: "blur(8px)",
            color: "var(--fg-2)", cursor: "pointer", fontWeight: 500 }}>
          Start over ↻
        </button>
      )}
    </div>
  );
}

Object.assign(window, { V2Stage });
