const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

function Builder({ onBack }) {
  const [messages, setMessages] = useStateB([
    {
      role: "user",
      text: "a portfolio for a typeface designer in Lisbon, warm cream paper, italic display",
    },
    {
      role: "assistant",
      kind: "thinking",
      text: "Setting up a Next.js project with a warm, paper-like palette and an italic display face. Drafting four sections: Hero, Specimens, Custom work, About.",
    },
    {
      role: "assistant",
      kind: "files",
      files: [
        { path: "app/page.tsx", lines: 128, status: "new" },
        { path: "components/Hero.tsx", lines: 64, status: "new" },
        { path: "components/Specimen.tsx", lines: 92, status: "new" },
        { path: "styles/tokens.css", lines: 22, status: "new" },
        { path: "app/layout.tsx", lines: 18, status: "new" },
      ],
    },
    {
      role: "assistant",
      kind: "summary",
      text: "Done. The site uses Instrument Serif italic for the display, with cream paper and burnt-orange accents. Anything you want to refine?",
      suggestions: [
        "Make the hero quieter",
        "Add a contact form",
        "Try a darker palette",
        "Show 6 typefaces, not 3",
      ],
    },
  ]);
  const [draft, setDraft] = useStateB("");
  const [activeTab, setActiveTab] = useStateB("preview");
  const [activeFile, setActiveFile] = useStateB("app/page.tsx");
  const [device, setDevice] = useStateB("desktop");
  const [isStreaming, setIsStreaming] = useStateB(false);
  const scrollRef = useRefB(null);

  const send = (text) => {
    const t = (text ?? draft).trim();
    if (!t) return;
    setDraft("");
    setMessages((m) => [...m, { role: "user", text: t }]);
    setIsStreaming(true);
    setTimeout(() => {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          kind: "thinking",
          text: "On it. Adjusting the affected components and re-running the layout.",
        },
      ]);
    }, 600);
    setTimeout(() => {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          kind: "diff",
          edits: [
            { path: "components/Hero.tsx", add: 4, sub: 7 },
            { path: "styles/tokens.css", add: 2, sub: 1 },
          ],
        },
        {
          role: "assistant",
          kind: "summary",
          text: "Updated. Refresh the preview on the right — should feel calmer now.",
          suggestions: ["Make it tighter", "Try a serif headline", "Undo"],
        },
      ]);
      setIsStreaming(false);
    }, 1700);
  };

  useEffectB(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  return (
    <div style={builderStyles.shell} data-screen-label="02 Builder">
      <BuilderHeader onBack={onBack} />
      <div style={builderStyles.body}>
        <ChatPane
          messages={messages}
          draft={draft}
          setDraft={setDraft}
          send={send}
          isStreaming={isStreaming}
          scrollRef={scrollRef}
        />
        <WorkPane
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          activeFile={activeFile}
          setActiveFile={setActiveFile}
          device={device}
          setDevice={setDevice}
        />
      </div>
    </div>
  );
}

function BuilderHeader({ onBack }) {
  return (
    <header style={builderStyles.header}>
      <div style={builderStyles.headerLeft}>
        <button style={builderStyles.iconBtn} onClick={onBack} title="Back to landing">
          <span style={{ fontSize: 16 }}>◆</span>
        </button>
        <span style={builderStyles.crumb}>Personal</span>
        <span style={builderStyles.slash}>/</span>
        <span style={builderStyles.projectName}>câmara-type</span>
        <span style={builderStyles.savedPill}>
          <span style={builderStyles.savedDot} />
          saved 2s ago
        </span>
      </div>
      <div style={builderStyles.headerCenter}>
        <span style={builderStyles.branchPill}>
          <span style={builderStyles.branchIcon}>⎇</span>
          main
        </span>
        <span style={builderStyles.versionPill}>v0.4 · 12 edits</span>
      </div>
      <div style={builderStyles.headerRight}>
        <button style={builderStyles.ghostBtn}>Share</button>
        <button style={builderStyles.ghostBtn}>Export</button>
        <button style={builderStyles.publishBtn}>
          <span style={builderStyles.publishDot} />
          Publish
        </button>
      </div>
    </header>
  );
}

function ChatPane({ messages, draft, setDraft, send, isStreaming, scrollRef }) {
  return (
    <aside style={builderStyles.chatPane}>
      <div style={builderStyles.chatHeader}>
        <div style={builderStyles.chatTitle}>Conversation</div>
        <div style={builderStyles.chatMeta}>{messages.filter(m => m.role === "user").length} prompts</div>
      </div>
      <div style={builderStyles.chatScroll} ref={scrollRef}>
        {messages.map((m, i) => (
          <Message key={i} m={m} onSuggestion={(t) => send(t)} />
        ))}
        {isStreaming && <TypingDots />}
      </div>
      <ChatComposer
        draft={draft}
        setDraft={setDraft}
        onSend={() => send()}
        disabled={isStreaming}
      />
    </aside>
  );
}

function Message({ m, onSuggestion }) {
  if (m.role === "user") {
    return (
      <div style={builderStyles.msgUserWrap}>
        <div style={builderStyles.msgUser}>{m.text}</div>
      </div>
    );
  }
  if (m.kind === "thinking") {
    return (
      <div style={builderStyles.msgAssistant}>
        <div style={builderStyles.msgKicker}>
          <span style={builderStyles.thinkSpinner} />
          Thinking
        </div>
        <div style={builderStyles.msgBody}>{m.text}</div>
      </div>
    );
  }
  if (m.kind === "files") {
    return (
      <div style={builderStyles.msgAssistant}>
        <div style={builderStyles.msgKicker}>
          <span style={builderStyles.fileBadge}>WROTE {m.files.length}</span>
        </div>
        <div style={builderStyles.fileList}>
          {m.files.map((f, i) => (
            <div key={i} style={builderStyles.fileItem}>
              <span style={builderStyles.fileGlyph}>{"{ }"}</span>
              <span style={builderStyles.filePath}>{f.path}</span>
              <span style={builderStyles.fileLines}>+{f.lines}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (m.kind === "diff") {
    return (
      <div style={builderStyles.msgAssistant}>
        <div style={builderStyles.msgKicker}>
          <span style={builderStyles.editBadge}>EDITED</span>
        </div>
        <div style={builderStyles.fileList}>
          {m.edits.map((e, i) => (
            <div key={i} style={builderStyles.fileItem}>
              <span style={builderStyles.fileGlyph}>{"{ }"}</span>
              <span style={builderStyles.filePath}>{e.path}</span>
              <span style={builderStyles.diffAdd}>+{e.add}</span>
              <span style={builderStyles.diffSub}>−{e.sub}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (m.kind === "summary") {
    return (
      <div style={builderStyles.msgAssistant}>
        <div style={builderStyles.msgBody}>{m.text}</div>
        {m.suggestions && (
          <div style={builderStyles.suggestions}>
            {m.suggestions.map((s, i) => (
              <button
                key={i}
                style={builderStyles.suggestion}
                onClick={() => onSuggestion(s)}
              >
                {s}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }
  return null;
}

function TypingDots() {
  return (
    <div style={builderStyles.msgAssistant}>
      <div style={builderStyles.typing}>
        <span style={{ ...builderStyles.typingDot, animationDelay: "0s" }} />
        <span style={{ ...builderStyles.typingDot, animationDelay: "0.15s" }} />
        <span style={{ ...builderStyles.typingDot, animationDelay: "0.3s" }} />
      </div>
    </div>
  );
}

function ChatComposer({ draft, setDraft, onSend, disabled }) {
  return (
    <div style={builderStyles.composer}>
      <div style={builderStyles.composerInner}>
        <textarea
          style={builderStyles.composerInput}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              onSend();
            }
          }}
          placeholder="Refine, redirect, or ask for something new…"
          rows={2}
          disabled={disabled}
        />
        <div style={builderStyles.composerActions}>
          <div style={builderStyles.composerTools}>
            <button style={builderStyles.composerTool} title="Attach">📎</button>
            <button style={builderStyles.composerTool} title="Reference an image">🖼</button>
            <button style={builderStyles.composerTool} title="Pick a file">＠</button>
          </div>
          <button
            style={{ ...builderStyles.sendBtn, opacity: disabled ? 0.5 : 1 }}
            onClick={onSend}
            disabled={disabled}
          >
            Send <span aria-hidden="true">↵</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function WorkPane({ activeTab, setActiveTab, activeFile, setActiveFile, device, setDevice }) {
  return (
    <main style={builderStyles.workPane}>
      <div style={builderStyles.workHeader}>
        <div style={builderStyles.tabs}>
          {[
            { id: "preview", label: "Preview" },
            { id: "code", label: "Code" },
            { id: "history", label: "History" },
          ].map((t) => (
            <button
              key={t.id}
              style={{
                ...builderStyles.tab,
                ...(activeTab === t.id ? builderStyles.tabActive : {}),
              }}
              onClick={() => setActiveTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </div>
        <div style={builderStyles.urlBar}>
          <span style={builderStyles.urlDot} />
          <span style={builderStyles.urlText}>localhost:3000 · câmara-type</span>
        </div>
        <div style={builderStyles.workTools}>
          {activeTab === "preview" && (
            <div style={builderStyles.deviceGroup}>
              {[
                { id: "mobile", label: "▯" },
                { id: "tablet", label: "◧" },
                { id: "desktop", label: "▭" },
              ].map((d) => (
                <button
                  key={d.id}
                  style={{
                    ...builderStyles.deviceBtn,
                    ...(device === d.id ? builderStyles.deviceBtnActive : {}),
                  }}
                  onClick={() => setDevice(d.id)}
                  title={d.id}
                >
                  {d.label}
                </button>
              ))}
            </div>
          )}
          <button style={builderStyles.iconBtn} title="Refresh">↻</button>
          <button style={builderStyles.iconBtn} title="Open in new tab">↗</button>
        </div>
      </div>

      {activeTab === "preview" && <PreviewSurface device={device} />}
      {activeTab === "code" && (
        <CodeSurface activeFile={activeFile} setActiveFile={setActiveFile} />
      )}
      {activeTab === "history" && <HistorySurface />}
    </main>
  );
}

const DEVICE_WIDTHS = {
  desktop: "100%",
  tablet: 820,
  mobile: 390,
};

function PreviewSurface({ device }) {
  const w = DEVICE_WIDTHS[device];
  return (
    <div style={builderStyles.previewSurface}>
      <div
        style={{
          ...builderStyles.previewFrame,
          width: w,
          maxWidth: "100%",
          ...(device !== "desktop" ? { height: device === "mobile" ? 720 : 900 } : {}),
        }}
      >
        <RenderedSite device={device} />
      </div>
    </div>
  );
}

function RenderedSite({ device }) {
  const compact = device === "mobile";
  return (
    <div style={renderedStyles.site}>
      <div style={renderedStyles.nav}>
        <span style={renderedStyles.brand}>Câmara Type</span>
        {!compact && (
          <span style={renderedStyles.navLinks}>
            <span>Specimens</span>
            <span>Custom</span>
            <span>Journal</span>
            <span>Contact</span>
          </span>
        )}
      </div>
      <div style={renderedStyles.hero}>
        <div style={renderedStyles.kicker}>EST. 2021 · LISBON, PT</div>
        <div
          style={{
            ...renderedStyles.h1,
            fontSize: compact ? 56 : "clamp(64px, 9vw, 140px)",
          }}
        >
          Letterforms,<br />
          <em style={renderedStyles.h1Em}>drawn slowly.</em>
        </div>
        <div style={renderedStyles.lede}>
          A small studio drawing original typefaces and custom letter­forms for editorial,
          identity, and product work.
        </div>
      </div>
      <div style={renderedStyles.spec}>Aa Bb Cc Dd Ee Ff Gg Hh Ii</div>
      <div
        style={{
          ...renderedStyles.grid,
          gridTemplateColumns: compact ? "1fr" : "repeat(3, 1fr)",
        }}
      >
        {[
          { name: "Esfera", style: "Display Italic", year: "2024" },
          { name: "Marítimo", style: "Text Roman", year: "2023" },
          { name: "Pedra", style: "Display Roman", year: "2022" },
        ].map((t, i) => (
          <div key={i} style={renderedStyles.tile}>
            <div style={renderedStyles.tileGlyph}>Aa</div>
            <div style={renderedStyles.tileMeta}>
              <span style={renderedStyles.tileName}>{t.name}</span>
              <span style={renderedStyles.tileStyle}>{t.style} · {t.year}</span>
            </div>
          </div>
        ))}
      </div>
      <div style={renderedStyles.foot}>
        <span>Lisbon, PT</span>
        <span style={renderedStyles.footBig}>2026</span>
        <span>hello@camara.type</span>
      </div>
    </div>
  );
}

function CodeSurface({ activeFile, setActiveFile }) {
  const tree = [
    { type: "folder", name: "app", open: true, children: [
      { type: "file", name: "page.tsx" },
      { type: "file", name: "layout.tsx" },
      { type: "file", name: "globals.css" },
    ]},
    { type: "folder", name: "components", open: true, children: [
      { type: "file", name: "Hero.tsx" },
      { type: "file", name: "Specimen.tsx" },
      { type: "file", name: "Nav.tsx" },
    ]},
    { type: "folder", name: "styles", open: true, children: [
      { type: "file", name: "tokens.css" },
    ]},
    { type: "file", name: "package.json" },
    { type: "file", name: "tailwind.config.ts" },
  ];

  const codeByFile = {
    "app/page.tsx": `import { Hero } from "@/components/Hero";
import { Specimen } from "@/components/Specimen";
import { Nav } from "@/components/Nav";

export default function Home() {
  return (
    <main className="bg-paper text-ink min-h-screen">
      <Nav />
      <Hero
        kicker="EST. 2021 · LISBON, PT"
        title="Letterforms,"
        emphasis="drawn slowly."
        lede="A small studio drawing original typefaces..."
      />
      <Specimen text="Aa Bb Cc Dd Ee Ff Gg Hh Ii" />
      <section className="grid grid-cols-3 gap-4 px-12">
        {fonts.map((f) => (
          <Tile key={f.name} {...f} />
        ))}
      </section>
    </main>
  );
}`,
    "components/Hero.tsx": `export function Hero({ kicker, title, emphasis, lede }) {
  return (
    <section className="px-12 py-32">
      <p className="font-mono text-xs tracking-widest text-ink-3">
        {kicker}
      </p>
      <h1 className="font-display text-9xl leading-none -tracking-wide mt-6">
        {title}
        <em className="block italic text-accent">{emphasis}</em>
      </h1>
      <p className="mt-8 max-w-prose text-ink-2 text-pretty">
        {lede}
      </p>
    </section>
  );
}`,
    "styles/tokens.css": `:root {
  --paper: oklch(0.97 0.012 75);
  --ink: oklch(0.22 0.02 40);
  --ink-2: oklch(0.42 0.02 40);
  --ink-3: oklch(0.6 0.02 40);
  --accent: oklch(0.62 0.18 45);
  --rule: oklch(0.88 0.015 60);

  --font-display: "Instrument Serif", serif;
  --font-mono: "JetBrains Mono", ui-monospace, monospace;
}`,
  };
  const code = codeByFile[activeFile] || "// (file)";

  return (
    <div style={builderStyles.codeSurface}>
      <aside style={builderStyles.fileTree}>
        <div style={builderStyles.fileTreeHead}>FILES</div>
        {tree.map((node, i) => (
          <FileNode key={i} node={node} active={activeFile} onSelect={setActiveFile} depth={0} />
        ))}
      </aside>
      <div style={builderStyles.codeArea}>
        <div style={builderStyles.codeTabs}>
          <span style={builderStyles.codeTab}>{activeFile}</span>
        </div>
        <pre style={builderStyles.codeBlock}>
          <code>{code.split("\n").map((line, i) => (
            <div key={i} style={builderStyles.codeLine}>
              <span style={builderStyles.lineNo}>{i + 1}</span>
              <span style={builderStyles.lineText}>{line || " "}</span>
            </div>
          ))}</code>
        </pre>
      </div>
    </div>
  );
}

function FileNode({ node, active, onSelect, depth }) {
  if (node.type === "folder") {
    return (
      <div>
        <div style={{ ...builderStyles.folderRow, paddingLeft: 12 + depth * 12 }}>
          <span style={builderStyles.folderCaret}>▾</span>
          <span style={builderStyles.folderName}>{node.name}</span>
        </div>
        {node.children?.map((c, i) => (
          <FileNode
            key={i}
            node={{ ...c, name: node.name + "/" + c.name }}
            active={active}
            onSelect={onSelect}
            depth={depth + 1}
          />
        ))}
      </div>
    );
  }
  const isActive = active === node.name;
  const display = node.name.split("/").pop();
  return (
    <button
      style={{
        ...builderStyles.fileRow,
        paddingLeft: 12 + depth * 12,
        ...(isActive ? builderStyles.fileRowActive : {}),
      }}
      onClick={() => onSelect(node.name)}
    >
      <span style={builderStyles.fileGlyphSm}>{"{}"}</span>
      <span>{display}</span>
    </button>
  );
}

function HistorySurface() {
  const items = [
    { time: "now", title: "Quieter hero, smaller display type", files: 2, kind: "edit" },
    { time: "2m ago", title: "Initial draft", files: 5, kind: "build" },
  ];
  return (
    <div style={builderStyles.historySurface}>
      <div style={builderStyles.historyList}>
        {items.map((it, i) => (
          <article key={i} style={builderStyles.historyRow}>
            <div style={builderStyles.historyTime}>{it.time}</div>
            <div style={builderStyles.historyMain}>
              <div style={builderStyles.historyKind}>
                {it.kind === "build" ? "BUILD" : "EDIT"}
              </div>
              <div style={builderStyles.historyTitle}>{it.title}</div>
              <div style={builderStyles.historyFiles}>{it.files} files touched</div>
            </div>
            <button style={builderStyles.historyBtn}>Restore</button>
          </article>
        ))}
      </div>
    </div>
  );
}

const builderStyles = {
  shell: {
    height: "100vh",
    display: "flex",
    flexDirection: "column",
    background: "var(--paper-2)",
    color: "var(--ink)",
    fontFamily: "var(--font-ui)",
  },
  header: {
    display: "grid",
    gridTemplateColumns: "1fr auto 1fr",
    alignItems: "center",
    padding: "10px 16px",
    borderBottom: "1px solid var(--rule)",
    background: "var(--paper)",
    minHeight: 52,
  },
  headerLeft: { display: "flex", alignItems: "center", gap: 10, fontSize: 13 },
  iconBtn: {
    width: 32,
    height: 32,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 8,
    color: "var(--accent)",
  },
  crumb: { color: "var(--ink-2)" },
  slash: { color: "var(--ink-3)" },
  projectName: { fontFamily: "var(--font-mono)", fontSize: 13 },
  savedPill: {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "3px 8px",
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "var(--ink-3)",
    marginLeft: 8,
  },
  savedDot: {
    width: 6,
    height: 6,
    borderRadius: 999,
    background: "oklch(0.6 0.16 145)",
  },
  headerCenter: { display: "flex", alignItems: "center", gap: 8 },
  branchPill: {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "5px 10px",
    border: "1px solid var(--rule)",
    borderRadius: 6,
    fontFamily: "var(--font-mono)",
    fontSize: 12,
  },
  branchIcon: { color: "var(--accent)" },
  versionPill: {
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "var(--ink-3)",
  },
  headerRight: {
    display: "flex",
    alignItems: "center",
    gap: 6,
    justifyContent: "flex-end",
  },
  ghostBtn: {
    padding: "7px 12px",
    fontSize: 13,
    color: "var(--ink-2)",
    borderRadius: 6,
  },
  publishBtn: {
    display: "inline-flex",
    alignItems: "center",
    gap: 8,
    padding: "7px 14px",
    background: "var(--ink)",
    color: "var(--paper)",
    borderRadius: 6,
    fontSize: 13,
    fontWeight: 500,
  },
  publishDot: {
    width: 6,
    height: 6,
    borderRadius: 999,
    background: "var(--accent)",
  },

  body: {
    flex: 1,
    display: "grid",
    gridTemplateColumns: "minmax(340px, 420px) 1fr",
    minHeight: 0,
  },

  chatPane: {
    display: "flex",
    flexDirection: "column",
    background: "var(--paper)",
    borderRight: "1px solid var(--rule)",
    minHeight: 0,
  },
  chatHeader: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    padding: "14px 18px",
    borderBottom: "1px solid var(--rule)",
  },
  chatTitle: { fontSize: 13, fontWeight: 500 },
  chatMeta: { fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)" },
  chatScroll: {
    flex: 1,
    overflowY: "auto",
    padding: "20px 18px",
    display: "flex",
    flexDirection: "column",
    gap: 18,
  },
  msgUserWrap: { display: "flex", justifyContent: "flex-end" },
  msgUser: {
    background: "var(--ink)",
    color: "var(--paper)",
    padding: "10px 14px",
    borderRadius: 14,
    borderTopRightRadius: 4,
    fontSize: 14,
    lineHeight: 1.4,
    maxWidth: "85%",
    textWrap: "pretty",
  },
  msgAssistant: { display: "flex", flexDirection: "column", gap: 10, maxWidth: "100%" },
  msgKicker: {
    display: "inline-flex",
    alignItems: "center",
    gap: 8,
    fontFamily: "var(--font-mono)",
    fontSize: 10,
    color: "var(--ink-3)",
    letterSpacing: "0.1em",
  },
  thinkSpinner: {
    width: 8,
    height: 8,
    borderRadius: 999,
    background: "var(--accent)",
    boxShadow: "0 0 0 3px color-mix(in oklab, var(--accent) 25%, transparent)",
    animation: "pulse 1.4s ease-in-out infinite",
  },
  fileBadge: {
    background: "var(--accent-soft)",
    color: "var(--accent)",
    padding: "2px 6px",
    borderRadius: 3,
  },
  editBadge: {
    background: "color-mix(in oklab, oklch(0.55 0.14 145) 18%, var(--paper))",
    color: "oklch(0.45 0.16 145)",
    padding: "2px 6px",
    borderRadius: 3,
  },
  msgBody: {
    fontSize: 14,
    lineHeight: 1.5,
    color: "var(--ink)",
    textWrap: "pretty",
  },
  fileList: {
    display: "flex",
    flexDirection: "column",
    border: "1px solid var(--rule)",
    borderRadius: 8,
    overflow: "hidden",
    background: "var(--paper-2)",
  },
  fileItem: {
    display: "flex",
    alignItems: "center",
    gap: 10,
    padding: "8px 12px",
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    borderBottom: "1px solid var(--rule)",
  },
  fileGlyph: { color: "var(--accent)", fontSize: 11 },
  filePath: { flex: 1, color: "var(--ink-2)" },
  fileLines: { color: "oklch(0.5 0.16 145)", fontSize: 11 },
  diffAdd: { color: "oklch(0.5 0.16 145)", fontSize: 11 },
  diffSub: { color: "oklch(0.55 0.18 25)", fontSize: 11 },
  suggestions: { display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 },
  suggestion: {
    padding: "6px 12px",
    border: "1px solid var(--rule)",
    borderRadius: 999,
    fontSize: 12,
    color: "var(--ink-2)",
    background: "var(--paper-2)",
  },
  typing: { display: "flex", gap: 4, padding: "6px 0" },
  typingDot: {
    width: 6,
    height: 6,
    borderRadius: 999,
    background: "var(--ink-3)",
    animation: "typing 1.2s ease-in-out infinite",
    display: "inline-block",
  },

  composer: { padding: 14, borderTop: "1px solid var(--rule)" },
  composerInner: {
    background: "var(--paper-2)",
    border: "1px solid var(--rule)",
    borderRadius: 12,
    padding: 10,
  },
  composerInput: {
    width: "100%",
    border: "none",
    outline: "none",
    background: "transparent",
    fontFamily: "var(--font-ui)",
    fontSize: 14,
    color: "var(--ink)",
    resize: "none",
    padding: "4px 6px",
    lineHeight: 1.4,
  },
  composerActions: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 6,
  },
  composerTools: { display: "flex", gap: 4 },
  composerTool: {
    width: 28,
    height: 28,
    borderRadius: 6,
    fontSize: 14,
    color: "var(--ink-3)",
  },
  sendBtn: {
    padding: "6px 12px",
    background: "var(--accent)",
    color: "var(--accent-fg)",
    borderRadius: 6,
    fontSize: 13,
    fontWeight: 500,
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
  },

  workPane: {
    display: "flex",
    flexDirection: "column",
    background: "var(--paper-2)",
    minHeight: 0,
  },
  workHeader: {
    display: "flex",
    alignItems: "center",
    gap: 12,
    padding: "10px 16px",
    borderBottom: "1px solid var(--rule)",
    background: "var(--paper)",
    minHeight: 52,
  },
  tabs: { display: "flex", gap: 2 },
  tab: {
    padding: "7px 12px",
    fontSize: 13,
    color: "var(--ink-3)",
    borderRadius: 6,
  },
  tabActive: {
    background: "var(--paper-2)",
    color: "var(--ink)",
    boxShadow: "inset 0 0 0 1px var(--rule)",
  },
  urlBar: {
    flex: 1,
    display: "flex",
    alignItems: "center",
    gap: 8,
    background: "var(--paper-2)",
    border: "1px solid var(--rule)",
    borderRadius: 999,
    padding: "5px 14px",
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    color: "var(--ink-3)",
    justifyContent: "center",
    maxWidth: 380,
    margin: "0 auto",
  },
  urlDot: { width: 6, height: 6, borderRadius: 999, background: "var(--accent)" },
  urlText: {},
  workTools: { display: "flex", alignItems: "center", gap: 6 },
  deviceGroup: {
    display: "flex",
    background: "var(--paper-2)",
    border: "1px solid var(--rule)",
    borderRadius: 6,
    padding: 2,
  },
  deviceBtn: {
    padding: "4px 10px",
    fontSize: 14,
    color: "var(--ink-3)",
    borderRadius: 4,
  },
  deviceBtnActive: {
    background: "var(--paper)",
    color: "var(--ink)",
    boxShadow: "0 0 0 1px var(--rule)",
  },

  previewSurface: {
    flex: 1,
    overflow: "auto",
    display: "flex",
    justifyContent: "center",
    alignItems: "flex-start",
    padding: 32,
    background:
      "var(--paper-2) repeating-linear-gradient(45deg, transparent 0 14px, color-mix(in oklab, var(--ink) 3%, transparent) 14px 15px)",
  },
  previewFrame: {
    background: "var(--paper)",
    border: "1px solid var(--rule)",
    borderRadius: 6,
    overflow: "hidden",
    boxShadow: "0 30px 60px -30px rgba(0,0,0,0.25)",
  },

  codeSurface: {
    flex: 1,
    display: "grid",
    gridTemplateColumns: "220px 1fr",
    minHeight: 0,
  },
  fileTree: {
    background: "var(--paper)",
    borderRight: "1px solid var(--rule)",
    overflowY: "auto",
    padding: "10px 0",
  },
  fileTreeHead: {
    fontFamily: "var(--font-mono)",
    fontSize: 10,
    color: "var(--ink-3)",
    letterSpacing: "0.1em",
    padding: "0 12px 8px",
  },
  folderRow: {
    display: "flex",
    alignItems: "center",
    gap: 6,
    padding: "4px 10px",
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    color: "var(--ink-2)",
  },
  folderCaret: { color: "var(--ink-3)", fontSize: 9 },
  folderName: {},
  fileRow: {
    width: "100%",
    display: "flex",
    alignItems: "center",
    gap: 8,
    padding: "4px 10px",
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    color: "var(--ink-2)",
    background: "transparent",
    textAlign: "left",
  },
  fileRowActive: {
    background: "var(--accent-soft)",
    color: "var(--accent)",
  },
  fileGlyphSm: { fontSize: 10, opacity: 0.6 },

  codeArea: {
    display: "flex",
    flexDirection: "column",
    minHeight: 0,
    background: "var(--paper-2)",
  },
  codeTabs: {
    display: "flex",
    borderBottom: "1px solid var(--rule)",
    background: "var(--paper)",
  },
  codeTab: {
    padding: "10px 16px",
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    color: "var(--ink)",
    borderRight: "1px solid var(--rule)",
    background: "var(--paper-2)",
  },
  codeBlock: {
    margin: 0,
    padding: "16px 0",
    flex: 1,
    overflow: "auto",
    fontFamily: "var(--font-mono)",
    fontSize: 12.5,
    lineHeight: 1.7,
    color: "var(--ink)",
    background: "var(--paper-2)",
  },
  codeLine: { display: "flex" },
  lineNo: {
    width: 44,
    textAlign: "right",
    paddingRight: 16,
    color: "var(--ink-3)",
    userSelect: "none",
    flexShrink: 0,
  },
  lineText: { whiteSpace: "pre" },

  historySurface: {
    flex: 1,
    overflow: "auto",
    padding: 32,
  },
  historyList: {
    maxWidth: 720,
    margin: "0 auto",
    display: "flex",
    flexDirection: "column",
    gap: 8,
  },
  historyRow: {
    display: "grid",
    gridTemplateColumns: "100px 1fr auto",
    gap: 24,
    alignItems: "center",
    padding: "20px 24px",
    background: "var(--paper)",
    border: "1px solid var(--rule)",
    borderRadius: 12,
  },
  historyTime: {
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "var(--ink-3)",
  },
  historyMain: { display: "flex", flexDirection: "column", gap: 4 },
  historyKind: {
    fontFamily: "var(--font-mono)",
    fontSize: 10,
    letterSpacing: "0.1em",
    color: "var(--accent)",
  },
  historyTitle: { fontSize: 15, fontWeight: 500 },
  historyFiles: { fontSize: 12, color: "var(--ink-3)" },
  historyBtn: {
    padding: "7px 14px",
    border: "1px solid var(--rule)",
    borderRadius: 999,
    fontSize: 12,
  },
};

const renderedStyles = {
  site: {
    minHeight: "100%",
    background: "oklch(0.97 0.012 75)",
    color: "oklch(0.22 0.02 40)",
    fontFamily: "var(--font-ui)",
    padding: "24px clamp(24px, 5vw, 56px) 32px",
  },
  nav: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    fontFamily: "var(--font-display)",
    marginBottom: 56,
  },
  brand: { fontSize: 22, letterSpacing: "-0.01em" },
  navLinks: {
    display: "flex",
    gap: 24,
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "oklch(0.45 0.02 40)",
    letterSpacing: "0.06em",
    textTransform: "uppercase",
  },
  hero: { marginBottom: 32 },
  kicker: {
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "oklch(0.45 0.02 40)",
    letterSpacing: "0.1em",
    marginBottom: 20,
  },
  h1: {
    fontFamily: "var(--font-display)",
    fontWeight: 400,
    lineHeight: 0.95,
    letterSpacing: "-0.02em",
  },
  h1Em: { fontStyle: "italic", color: "var(--accent)" },
  lede: {
    fontSize: 16,
    lineHeight: 1.5,
    color: "oklch(0.42 0.02 40)",
    maxWidth: 460,
    marginTop: 24,
    textWrap: "pretty",
  },
  spec: {
    fontFamily: "var(--font-display)",
    fontSize: "clamp(36px, 5vw, 64px)",
    color: "oklch(0.55 0.04 40)",
    margin: "32px 0",
    letterSpacing: "0.02em",
  },
  grid: { display: "grid", gap: 12 },
  tile: {
    aspectRatio: "4 / 3",
    background: "oklch(0.93 0.03 60)",
    borderRadius: 6,
    padding: 16,
    display: "flex",
    flexDirection: "column",
    justifyContent: "space-between",
  },
  tileGlyph: {
    fontFamily: "var(--font-display)",
    fontSize: 56,
    color: "oklch(0.3 0.04 40)",
    fontStyle: "italic",
  },
  tileMeta: { display: "flex", flexDirection: "column", gap: 2 },
  tileName: { fontFamily: "var(--font-display)", fontSize: 18 },
  tileStyle: { fontFamily: "var(--font-mono)", fontSize: 10, color: "oklch(0.5 0.02 40)" },
  foot: {
    marginTop: 48,
    paddingTop: 24,
    borderTop: "1px solid oklch(0.88 0.015 60)",
    display: "grid",
    gridTemplateColumns: "1fr auto 1fr",
    alignItems: "center",
    fontFamily: "var(--font-mono)",
    fontSize: 11,
    color: "oklch(0.45 0.02 40)",
  },
  footBig: {
    fontFamily: "var(--font-display)",
    fontStyle: "italic",
    fontSize: 64,
    color: "oklch(0.22 0.02 40)",
  },
};

if (!document.getElementById("__builder_keyframes")) {
  const style = document.createElement("style");
  style.id = "__builder_keyframes";
  style.textContent = `
    @keyframes typing {
      0%, 80%, 100% { transform: translateY(0); opacity: 0.4; }
      40% { transform: translateY(-4px); opacity: 1; }
    }
  `;
  document.head.appendChild(style);
}

window.Builder = Builder;
