/* "Build a site" — a fully interactive, simulated Horizons flow, end to end:
   chat + live preview  →  "ready to build in code?"  →  grant source access
   →  Horizons builds the code  →  connect a Hostinger domain  →  live countdown.
   All inside Horizons / Hostinger (no external tools). */

const HZDS = window.HostingerHPanelDesignSystem_3ef285;
const { Button: HzBtn, Card: HzCard, SpotlightPanel: HzSpot, Badge: HzBadge, Icon: HzIcon, Input: HzInput } = HZDS;
const BakerySiteCmp = window.BakerySite;

/* ───────────────── small shared chrome ───────────────── */
function HzMark({ size = 26, label, labelColor = "#fff" }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
      <span style={{ width: size, height: size, borderRadius: size * 0.32, background: "linear-gradient(135deg, var(--violet-400), var(--violet-600))", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", boxShadow: "0 4px 12px rgba(103,61,230,.4)" }}>
        <HzIcon name="sparkles" size={size * 0.56} color="#fff" />
      </span>
      {label && <span style={{ fontWeight: "var(--fw-semibold)", fontSize: 15, color: labelColor, letterSpacing: "-0.01em" }}>{label}</span>}
    </span>
  );
}

function HzBrowserChrome({ url, children, live, scrollable }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", borderRadius: "var(--radius-md)", overflow: "hidden", border: "1px solid var(--border-hairline)", background: "var(--neutral-0)", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", background: "var(--neutral-50)", borderBottom: "1px solid var(--border-hairline)" }}>
        <span style={{ display: "flex", gap: 6 }}>
          {["#E2484D", "#E29400", "#18A971"].map((c) => (<span key={c} style={{ width: 9, height: 9, borderRadius: "50%", background: c }} />))}
        </span>
        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 7, height: 26, padding: "0 12px", borderRadius: "var(--radius-pill)", background: "var(--neutral-0)", border: "1px solid var(--border-hairline)", fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)", overflow: "hidden", whiteSpace: "nowrap" }}>
          {live ? <HzIcon name="shield" size={12} color="var(--success)" /> : <HzIcon name="globe" size={12} color="var(--text-subtle)" />}
          {url}
        </div>
        {live && <HzBadge tone="success" dot>Live</HzBadge>}
      </div>
      <div style={{ flex: 1, minHeight: 0, overflowY: scrollable ? "auto" : "hidden", background: "var(--neutral-0)" }}>{children}</div>
    </div>
  );
}

/* ───────────────── chat panel ───────────────── */
const SEED_MSGS = [
  { who: "ai", text: "Hi — I'm Horizons. Tell me what you'd like to build and I'll design it for you, live." },
  { who: "me", text: "A warm, modern site for my bakery, Sweet Crumb. I want a hero, our signature bakes, the story, and a way to order ahead." },
  { who: "ai", text: "Love it. I've designed a homepage for Sweet Crumb — warm terracotta and cream colours, an elegant heading, your three signature bakes, a short story, and an order section. It's on the right. Want to change anything?" },
];
const AI_REPLIES = [
  "Done — I refreshed the preview on the right with that change.",
  "Updated the layout. Take a look at the preview.",
  "Nice idea. I adjusted the design — check the right side.",
];

function ChatPanel({ onRegenerate }) {
  const [msgs, setMsgs] = React.useState(SEED_MSGS);
  const [draft, setDraft] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);
  const replyIx = React.useRef(0);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, thinking]);

  function send() {
    const t = draft.trim();
    if (!t || thinking) return;
    setMsgs((m) => [...m, { who: "me", text: t }]);
    setDraft("");
    setThinking(true);
    onRegenerate && onRegenerate();
    setTimeout(() => {
      setThinking(false);
      setMsgs((m) => [...m, { who: "ai", text: AI_REPLIES[replyIx.current++ % AI_REPLIES.length] }]);
    }, 1300);
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "var(--neutral-0)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
      <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderBottom: "1px solid var(--border-hairline)" }}>
        <HzMark size={24} label="Horizons" labelColor="var(--text-strong)" />
        <HzBadge tone="brand" style={{ marginLeft: "auto" }}>Designing</HzBadge>
      </div>

      <div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
        {msgs.map((m, i) => (
          m.who === "ai" ? (
            <div key={i} style={{ display: "flex", gap: 9, maxWidth: "94%" }}>
              <span style={{ flex: "none", marginTop: 1 }}><HzMark size={22} /></span>
              <div style={{ background: "var(--neutral-50)", border: "1px solid var(--border-hairline)", borderRadius: "4px 14px 14px 14px", padding: "11px 13px", fontSize: "var(--fs-sm)", color: "var(--text-body)", lineHeight: "var(--lh-normal)" }}>{m.text}</div>
            </div>
          ) : (
            <div key={i} style={{ alignSelf: "flex-end", maxWidth: "90%", background: "var(--neutral-950)", color: "#fff", borderRadius: "14px 14px 4px 14px", padding: "11px 14px", fontSize: "var(--fs-sm)", lineHeight: "var(--lh-normal)" }}>{m.text}</div>
          )
        ))}
        {thinking && (
          <div style={{ display: "flex", gap: 9 }}>
            <span style={{ flex: "none", marginTop: 1 }}><HzMark size={22} /></span>
            <div style={{ background: "var(--neutral-50)", border: "1px solid var(--border-hairline)", borderRadius: "4px 14px 14px 14px", padding: "13px 15px", display: "flex", gap: 5 }}>
              {[0, 1, 2].map((d) => (<span key={d} style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--text-subtle)", animation: `hzblink 1s ${d * 0.18}s infinite` }} />))}
            </div>
          </div>
        )}
      </div>

      <div style={{ flex: "none", padding: 12, borderTop: "1px solid var(--border-hairline)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 6px 6px 14px", border: "1px solid var(--border-default)", borderRadius: "var(--radius-pill)", background: "var(--neutral-0)" }}>
          <input
            value={draft} onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") send(); }}
            placeholder="Ask Horizons to change anything…"
            style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "var(--fs-sm)", color: "var(--text-body)" }}
          />
          <button onClick={send} aria-label="Send" style={{ flex: "none", width: 34, height: 34, borderRadius: "50%", border: "none", background: "var(--neutral-950)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
            <HzIcon name="arrow-right" size={16} />
          </button>
        </div>
      </div>
    </div>
  );
}

/* ───────────────── overlay shell ───────────────── */
function HzOverlay({ children, onClose, max = 520 }) {
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "rgba(14,14,17,.46)", backdropFilter: "blur(3px)", animation: "hzfade .16s ease" }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: max, background: "var(--neutral-0)", borderRadius: "var(--radius-lg)", boxShadow: "0 24px 70px rgba(14,14,17,.34)", overflow: "hidden", animation: "hzpop .18s ease" }}>
        {children}
      </div>
    </div>
  );
}

/* ───────────────── ready-to-build modal ───────────────── */
function ReadyModal({ onYes, onClose }) {
  return (
    <HzOverlay onClose={onClose} max={480}>
      <div style={{ padding: "30px 30px 26px" }}>
        <HzMark size={34} />
        <h3 style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-semibold)", marginTop: 18 }}>Happy with your design?</h3>
        <p style={{ fontSize: "var(--fs-body)", color: "var(--text-muted)", lineHeight: "var(--lh-relaxed)", marginTop: 8 }}>
          When you're ready, Horizons turns this design into a real website and puts it online for you. No tech skills needed — we handle the rest.
        </p>
        <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
          <HzBtn variant="primary" iconLeft="check" onClick={onYes}>Yes, build my website</HzBtn>
          <HzBtn variant="secondary" onClick={onClose}>Keep editing</HzBtn>
        </div>
      </div>
    </HzOverlay>
  );
}

/* ───────────────── connect-source modal ───────────────── */
function HostingerTile({ size = 26 }) {
  return <img src="assets/hostinger-logo-mark-violet.png" alt="" style={{ width: size, height: size }} />;
}
function GitHubTile({ size = 26 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="#1B1B1F"><path d="M12 1.5a10.5 10.5 0 0 0-3.32 20.46c.53.1.72-.23.72-.5v-1.9c-2.93.64-3.55-1.25-3.55-1.25-.48-1.22-1.17-1.55-1.17-1.55-.96-.65.07-.64.07-.64 1.06.08 1.62 1.09 1.62 1.09.94 1.62 2.47 1.15 3.07.88.1-.68.37-1.15.67-1.41-2.34-.27-4.8-1.17-4.8-5.2 0-1.15.41-2.09 1.08-2.82-.11-.27-.47-1.34.1-2.79 0 0 .88-.28 2.88 1.08a9.9 9.9 0 0 1 5.24 0c2-1.36 2.88-1.08 2.88-1.08.57 1.45.21 2.52.1 2.79.68.73 1.08 1.67 1.08 2.82 0 4.04-2.46 4.93-4.81 5.19.38.33.71.97.71 1.96v2.9c0 .28.19.61.73.5A10.5 10.5 0 0 0 12 1.5Z" /></svg>
  );
}
function FolderTile({ size = 26 }) {
  return <HzIcon name="folder" size={size} color="var(--text-strong)" />;
}

const SOURCES = [
  { id: "hostinger", title: "Keep it on Hostinger", body: "The simplest choice — we host and look after everything for you.", Tile: HostingerTile, recommended: true },
  { id: "local", title: "Download to my computer", body: "Save a copy of your website's files to your computer.", Tile: FolderTile },
  { id: "github", title: "Save to GitHub", body: "For developers — keep a copy of the code on GitHub.", Tile: GitHubTile },
];

function ConnectModal({ onBuild, onClose }) {
  const [sel, setSel] = React.useState("hostinger");
  const [connecting, setConnecting] = React.useState(false);

  function grant() {
    setConnecting(true);
    setTimeout(() => onBuild(SOURCES.find((s) => s.id === sel)), 1100);
  }

  return (
    <HzOverlay onClose={connecting ? undefined : onClose} max={560}>
      <div style={{ padding: "28px 28px 24px" }}>
        <h3 style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-semibold)" }}>Where should we keep your website?</h3>
        <p style={{ fontSize: "var(--fs-sm)", color: "var(--text-muted)", marginTop: 6 }}>Choose where your website should live. Not sure? Keep it on Hostinger — it's the easiest.</p>

        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 20 }}>
          {SOURCES.map((s) => {
            const active = sel === s.id;
            return (
              <button key={s.id} type="button" onClick={() => !connecting && setSel(s.id)} style={{
                display: "flex", alignItems: "center", gap: 14, textAlign: "left", cursor: connecting ? "default" : "pointer",
                padding: "14px 16px", borderRadius: "var(--radius-md)", background: active ? "var(--brand-soft-bg)" : "var(--neutral-0)",
                border: active ? "1.5px solid var(--brand)" : "1.5px solid var(--border-default)", transition: "all var(--dur-fast)",
              }}>
                <span style={{ flex: "none", width: 46, height: 46, borderRadius: "var(--radius-md)", background: "var(--neutral-0)", border: "1px solid var(--border-hairline)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <s.Tile size={24} />
                </span>
                <span style={{ flex: 1 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: "var(--fs-body)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>
                    {s.title}{s.recommended && <HzBadge tone="brand">Recommended</HzBadge>}
                  </span>
                  <span style={{ display: "block", fontSize: "var(--fs-xs)", color: "var(--text-muted)", marginTop: 2 }}>{s.body}</span>
                </span>
                <span style={{ flex: "none", width: 20, height: 20, borderRadius: "50%", border: active ? "6px solid var(--brand)" : "2px solid var(--border-default)", transition: "all var(--dur-fast)" }} />
              </button>
            );
          })}
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 24 }}>
          <HzBtn variant="primary" iconLeft={connecting ? undefined : "check"} onClick={connecting ? undefined : grant} disabled={connecting}>
            {connecting ? "Setting up…" : "Save here & continue"}
          </HzBtn>
          {!connecting && <HzBtn variant="ghost" onClick={onClose}>Back</HzBtn>}
        </div>
      </div>
    </HzOverlay>
  );
}

/* ───────────────── preview popup ───────────────── */
function PreviewModal({ onBuild, onClose }) {
  return (
    <HzOverlay onClose={onClose} max={1000}>
      <div style={{ display: "flex", flexDirection: "column", height: "86vh", maxHeight: 760 }}>
        {/* guidance banner */}
        <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 16, padding: "16px 20px", background: "var(--brand-soft-bg)", borderBottom: "1px solid var(--border-hairline)" }}>
          <span style={{ flex: "none", width: 38, height: 38, borderRadius: "50%", background: "var(--neutral-0)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--brand)" }}><HzIcon name="window" size={19} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>This is a preview of your website</div>
            <div style={{ fontSize: "var(--fs-xs)", color: "var(--text-muted)", marginTop: 2 }}>Happy with it? Click <strong>Build my website</strong> to put it online — or keep editing to change anything.</div>
          </div>
          <div style={{ flex: "none", display: "flex", gap: 10 }}>
            <HzBtn variant="secondary" onClick={onClose}>Keep editing</HzBtn>
            <HzBtn variant="primary" iconRight="arrow-right" onClick={onBuild}>Build my website</HzBtn>
          </div>
        </div>
        {/* the site */}
        <div style={{ flex: 1, minHeight: 0, padding: 16, background: "var(--neutral-50)" }}>
          <HzBrowserChrome url="sweetcrumb.horizons.app" scrollable><BakerySiteCmp /></HzBrowserChrome>
        </div>
      </div>
    </HzOverlay>
  );
}

/* ───────────────── building stage ───────────────── */
const BUILD_STEPS = [
  "Looking at your design",
  "Building your website",
  "Putting your pages together",
  "Getting your photos ready",
  "Putting it online",
];
const BUILD_FILES = ["your homepage", "the menu section", "your story", "your photos", "the order button", "the final touches"];

function BuildingStage({ source, onDone }) {
  const [pct, setPct] = React.useState(0);
  const [files, setFiles] = React.useState([]);

  React.useEffect(() => {
    const t = setInterval(() => setPct((p) => Math.min(100, p + 2)), 90);
    return () => clearInterval(t);
  }, []);
  React.useEffect(() => {
    const shown = Math.floor((pct / 100) * BUILD_FILES.length);
    setFiles(BUILD_FILES.slice(0, shown));
    if (pct >= 100) { const t = setTimeout(onDone, 850); return () => clearTimeout(t); }
  }, [pct]);

  const activeStep = Math.min(BUILD_STEPS.length - 1, Math.floor((pct / 100) * BUILD_STEPS.length));

  return (
    <HzOverlay max={620}>
      <div style={{ padding: 28 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <HzMark size={30} />
          <div>
            <div style={{ fontSize: "var(--fs-h4)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>Building your website</div>
            <div style={{ fontSize: "var(--fs-xs)", color: "var(--text-muted)", display: "flex", alignItems: "center", gap: 6 }}>
              <source.Tile size={13} /> {source.title}
            </div>
          </div>
          <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: "var(--fw-medium)", color: "var(--text-strong)" }}>{pct}%</span>
        </div>

        {/* progress bar */}
        <div style={{ height: 8, borderRadius: 999, background: "var(--neutral-100)", marginTop: 20, overflow: "hidden" }}>
          <div style={{ height: "100%", width: pct + "%", borderRadius: 999, background: "linear-gradient(90deg, var(--violet-400), var(--violet-600))", transition: "width .12s linear" }} />
        </div>

        {/* steps */}
        <div style={{ display: "flex", flexDirection: "column", gap: 11, marginTop: 22 }}>
          {BUILD_STEPS.map((s, i) => {
            const done = i < activeStep || pct >= 100;
            const now = i === activeStep && pct < 100;
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, fontSize: "var(--fs-sm)", color: done || now ? "var(--text-body)" : "var(--text-subtle)" }}>
                <span style={{ flex: "none", width: 20, height: 20, borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center", background: done ? "var(--success)" : (now ? "var(--brand-soft-bg)" : "var(--neutral-100)"), color: "#fff", border: now ? "1px solid var(--brand)" : "none" }}>
                  {done ? <HzIcon name="check" size={12} /> : now ? <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--brand)", animation: "hzpulse 1s infinite" }} /> : null}
                </span>
                {s}
              </div>
            );
          })}
        </div>

        {/* file log */}
        <div style={{ marginTop: 20, borderRadius: "var(--radius-md)", background: "var(--neutral-950)", padding: "14px 16px", fontFamily: "var(--font-mono)", fontSize: 12, minHeight: 96 }}>
          {files.map((f, i) => (
            <div key={i} style={{ color: "var(--success)", display: "flex", gap: 8 }}><span>✓</span><span style={{ color: "rgba(255,255,255,.78)" }}>Added {f}</span></div>
          ))}
          {pct < 100 && <div style={{ color: "rgba(255,255,255,.4)" }}>Working on it…</div>}
        </div>
      </div>
    </HzOverlay>
  );
}

/* ───────────────── domain stage ───────────────── */
const OWNED = [
  { name: "sweetcrumb.com", note: "You own this · not used yet", pick: true },
  { name: "adalovelace.dev", note: "Already used by another site" },
  { name: "ada.shop", note: "You own this · not used yet" },
];
const AVAILABLE = [
  { name: "sweetcrumb.bakery", price: "$24.99/yr" },
  { name: "sweetcrumb.shop", price: "$2.99/yr" },
  { name: "getsweetcrumb.com", price: "$9.99/yr" },
];

function DomainStage({ onConnect }) {
  const [mode, setMode] = React.useState("have"); // have | need
  const [ownedPick, setOwnedPick] = React.useState("sweetcrumb.com");
  const [needPick, setNeedPick] = React.useState("sweetcrumb.bakery");

  const chosen = mode === "have" ? ownedPick : needPick;

  return (
    <HzOverlay max={560}>
      <div style={{ padding: "28px 28px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 4 }}>
          <span style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--success-soft-bg, #E6F6EE)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><HzIcon name="check" size={16} /></span>
          <span style={{ fontSize: "var(--fs-xs)", fontWeight: "var(--fw-semibold)", color: "var(--success)" }}>Your website is built and ready</span>
        </div>
        <h3 style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-semibold)" }}>Give your website an address</h3>
        <p style={{ fontSize: "var(--fs-sm)", color: "var(--text-muted)", marginTop: 6 }}>Your address is what people type to visit you, like sweetcrumb.com. Do you already have one, or need a new one?</p>

        {/* segmented */}
        <div style={{ display: "flex", gap: 8, marginTop: 18, padding: 4, background: "var(--neutral-50)", borderRadius: "var(--radius-pill)" }}>
          {[["have", "I have one"], ["need", "I need a new one"]].map(([v, l]) => (
            <button key={v} onClick={() => setMode(v)} style={{
              flex: 1, height: 38, border: "none", borderRadius: "var(--radius-pill)", cursor: "pointer",
              background: mode === v ? "var(--neutral-0)" : "transparent", boxShadow: mode === v ? "var(--shadow-sm)" : "none",
              fontFamily: "var(--font-sans)", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: mode === v ? "var(--text-strong)" : "var(--text-muted)",
            }}>{l}</button>
          ))}
        </div>

        {/* list */}
        <div style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: 18 }}>
          {mode === "have" ? OWNED.map((d) => {
            const active = ownedPick === d.name;
            return (
              <button key={d.name} onClick={() => setOwnedPick(d.name)} style={rowStyle(active)}>
                <HzIcon name="globe" size={18} color={active ? "var(--brand)" : "var(--text-subtle)"} />
                <span style={{ flex: 1, textAlign: "left" }}>
                  <span style={{ display: "block", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{d.name}</span>
                  <span style={{ display: "block", fontSize: "var(--fs-2xs)", color: "var(--text-muted)" }}>{d.note}</span>
                </span>
                <span style={radioDot(active)} />
              </button>
            );
          }) : (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "0 2px 4px", fontSize: "var(--fs-2xs)", color: "var(--text-subtle)", textTransform: "uppercase", letterSpacing: "var(--ls-label)", fontWeight: "var(--fw-semibold)" }}>Addresses you can get for "sweetcrumb"</div>
              {AVAILABLE.map((d) => {
                const active = needPick === d.name;
                return (
                  <button key={d.name} onClick={() => setNeedPick(d.name)} style={rowStyle(active)}>
                    <HzIcon name="globe" size={18} color={active ? "var(--brand)" : "var(--text-subtle)"} />
                    <span style={{ flex: 1, textAlign: "left", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)" }}>{d.name}</span>
                    <span style={{ fontSize: "var(--fs-xs)", color: "var(--text-muted)" }}>{d.price}</span>
                    <span style={radioDot(active)} />
                  </button>
                );
              })}
            </>
          )}
        </div>

        <div style={{ marginTop: 22 }}>
          <HzBtn variant="primary" fullWidth iconRight="arrow-right" onClick={() => onConnect(chosen, mode)}>
            {mode === "have" ? `Use ${chosen}` : `Get ${chosen}`}
          </HzBtn>
        </div>
      </div>
    </HzOverlay>
  );
}
function rowStyle(active) {
  return {
    display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", cursor: "pointer",
    borderRadius: "var(--radius-md)", background: active ? "var(--brand-soft-bg)" : "var(--neutral-0)",
    border: active ? "1.5px solid var(--brand)" : "1.5px solid var(--border-default)", transition: "all var(--dur-fast)",
  };
}
function radioDot(active) {
  return { flex: "none", width: 18, height: 18, borderRadius: "50%", border: active ? "5px solid var(--brand)" : "2px solid var(--border-default)", transition: "all var(--dur-fast)" };
}

/* ───────────────── live countdown stage ───────────────── */
function LiveStage({ domain, onReset }) {
  const TOTAL = 90;
  const [left, setLeft] = React.useState(TOTAL);
  const live = left <= 0;

  React.useEffect(() => {
    if (live) return;
    const t = setInterval(() => setLeft((s) => Math.max(0, s - 1)), 1000);
    return () => clearInterval(t);
  }, [live]);

  const mm = String(Math.floor(left / 60)).padStart(1, "0");
  const ss = String(left % 60).padStart(2, "0");
  const frac = (TOTAL - left) / TOTAL;
  const R = 54, C = 2 * Math.PI * R;

  return (
    <HzOverlay max={480}>
      <div style={{ padding: "34px 30px 30px", textAlign: "center" }}>
        {!live ? (
          <>
            <div style={{ position: "relative", width: 140, height: 140, margin: "0 auto" }}>
              <svg width="140" height="140" viewBox="0 0 140 140" style={{ transform: "rotate(-90deg)" }}>
                <circle cx="70" cy="70" r={R} fill="none" stroke="var(--neutral-100)" strokeWidth="9" />
                <circle cx="70" cy="70" r={R} fill="none" stroke="var(--brand)" strokeWidth="9" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - frac)} style={{ transition: "stroke-dashoffset 1s linear" }} />
              </svg>
              <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 30, fontWeight: "var(--fw-medium)", color: "var(--text-strong)", lineHeight: 1 }}>{mm}:{ss}</span>
                <span style={{ fontSize: "var(--fs-2xs)", color: "var(--text-subtle)", marginTop: 4, textTransform: "uppercase", letterSpacing: "var(--ls-label)" }}>Publishing</span>
              </div>
            </div>
            <h3 style={{ fontSize: "var(--fs-h3)", fontWeight: "var(--fw-semibold)", marginTop: 22 }}>We're putting your website online</h3>
            <p style={{ fontSize: "var(--fs-body)", color: "var(--text-muted)", lineHeight: "var(--lh-relaxed)", marginTop: 8 }}>
              Sweet Crumb will be ready in a moment. Pop back soon and see it live at:
            </p>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginTop: 14, padding: "9px 16px", borderRadius: "var(--radius-pill)", background: "var(--neutral-50)", border: "1px solid var(--border-hairline)", fontFamily: "var(--font-mono)", fontSize: "var(--fs-sm)", color: "var(--text-link)" }}>
              <HzIcon name="globe" size={15} /> {domain}
            </div>
            <p style={{ fontSize: "var(--fs-xs)", color: "var(--text-subtle)", marginTop: 18 }}>You can close this window — we'll email you the moment it's ready.</p>
          </>
        ) : (
          <>
            <span style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--success-soft-bg, #E6F6EE)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto" }}><HzIcon name="check-circle" size={38} /></span>
            <h3 style={{ fontSize: "var(--fs-h2)", fontWeight: "var(--fw-semibold)", marginTop: 18 }}>Your website is live!</h3>
            <p style={{ fontSize: "var(--fs-body)", color: "var(--text-muted)", marginTop: 8 }}>Sweet Crumb is now online for everyone to see, safe and secure.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
              <a href={"https://" + domain} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
                <HzBtn variant="primary" fullWidth iconRight="external">Visit {domain}</HzBtn>
              </a>
              <HzBtn variant="ghost" fullWidth iconLeft="refresh" onClick={onReset}>Build another website</HzBtn>
            </div>
          </>
        )}
      </div>
    </HzOverlay>
  );
}

/* ════════════════════ ORCHESTRATOR ════════════════════ */
function BuildScreen() {
  const [phase, setPhase] = React.useState("builder"); // builder | building | domain | live
  const [modal, setModal] = React.useState(null);        // null | ready | connect
  const [source, setSource] = React.useState(null);
  const [domain, setDomain] = React.useState("sweetcrumb.com");
  const [regen, setRegen] = React.useState(false);
  const regenTimer = React.useRef(null);

  function pingPreview() {
    setRegen(true);
    clearTimeout(regenTimer.current);
    regenTimer.current = setTimeout(() => setRegen(false), 1400);
  }
  function reset() {
    setPhase("builder"); setModal(null); setSource(null);
  }

  return (
    <div style={{ flex: 1, minWidth: 0, minHeight: 0, display: "flex", flexDirection: "column", padding: "22px 26px" }}>
      {/* builder top bar */}
      <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
        <h1 style={{ fontSize: "var(--fs-h2)", fontWeight: "var(--fw-bold)" }}>Sweet Crumb</h1>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--fs-xs)", color: "var(--text-subtle)" }}><HzIcon name="check" size={13} color="var(--success)" /> Saved automatically</span>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
          <HzBtn variant="secondary" iconLeft="external" onClick={() => setModal("preview")}>Preview</HzBtn>
          <HzBtn variant="primary" iconRight="arrow-right" onClick={() => setModal("ready")}>Build my website</HzBtn>
        </div>
      </div>

      {/* builder body: chat + preview */}
      <div style={{ flex: 1, minHeight: 0, display: "grid", gridTemplateColumns: "380px 1fr", gridTemplateRows: "minmax(0, 1fr)", gap: 16 }}>
        <ChatPanel onRegenerate={pingPreview} />
        <div style={{ position: "relative", minWidth: 0, minHeight: 0, height: "100%" }}>
          <HzBrowserChrome url="sweetcrumb.horizons.app" scrollable>
            <BakerySiteCmp />
          </HzBrowserChrome>
          {regen && (
            <div style={{ position: "absolute", inset: 0, borderRadius: "var(--radius-md)", background: "rgba(255,255,255,.55)", backdropFilter: "blur(1.5px)", display: "flex", alignItems: "center", justifyContent: "center", gap: 10, zIndex: 5 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "10px 18px", borderRadius: "var(--radius-pill)", background: "var(--neutral-950)", color: "#fff", fontSize: "var(--fs-sm)", fontWeight: "var(--fw-medium)" }}>
                <span style={{ width: 14, height: 14, border: "2px solid rgba(255,255,255,.35)", borderTopColor: "#fff", borderRadius: "50%", animation: "hzspin .7s linear infinite" }} /> Updating design…
              </span>
            </div>
          )}
        </div>
      </div>

      {/* overlays */}
      {modal === "preview" && <PreviewModal onClose={() => setModal(null)} onBuild={() => setModal("ready")} />}
      {modal === "ready" && <ReadyModal onClose={() => setModal(null)} onYes={() => setModal("connect")} />}
      {modal === "connect" && <ConnectModal onClose={() => setModal("ready")} onBuild={(src) => { setSource(src); setModal(null); setPhase("building"); }} />}
      {phase === "building" && source && <BuildingStage source={source} onDone={() => setPhase("domain")} />}
      {phase === "domain" && <DomainStage onConnect={(d) => { setDomain(d); setPhase("live"); }} />}
      {phase === "live" && <LiveStage domain={domain} onReset={reset} />}
    </div>
  );
}

window.BuildScreen = BuildScreen;
