/* global React, ReactDOM, TweaksPanel, useTweaks, TweakSection, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakText, TweakColor, TweakButton, TweakNumber */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ---------- Defaults (persisted by host via EDITMODE markers in index.html) ----------
const DEFAULTS = window.__SITE_DEFAULTS;

// ---------- Font pairings ----------
const FONT_PAIRS = {
  "grotesk-inter": {
    label: "Space Grotesk + Inter",
    display: "'Space Grotesk', system-ui, sans-serif",
    body: "'Inter', system-ui, sans-serif",
    displayWeight: 700,
    tracking: "-0.03em",
  },
  "geist-mono": {
    label: "Geist + JetBrains Mono",
    display: "'Geist', system-ui, sans-serif",
    body: "'JetBrains Mono', ui-monospace, monospace",
    displayWeight: 600,
    tracking: "-0.02em",
  },
  "serif-inter": {
    label: "Instrument Serif + Inter",
    display: "'Instrument Serif', Georgia, serif",
    body: "'Inter', system-ui, sans-serif",
    displayWeight: 400,
    tracking: "-0.01em",
  },
  "helvetica": {
    label: "Helvetica Neue",
    display: "'Helvetica Neue', Helvetica, Arial, sans-serif",
    body: "'Helvetica Neue', Helvetica, Arial, sans-serif",
    displayWeight: 800,
    tracking: "-0.04em",
  },
};

const TEXTURES = ["grid", "noise", "mesh", "dots", "none"];
const LAYOUTS = ["centered", "split", "stacked"];

// ---------- Cursor spotlight (hero only) ----------
function useMouse(ref) {
  const [pos, setPos] = useState({ x: 0.5, y: 0.5, active: false });
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      setPos({ x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height, active: true });
    };
    const onLeave = () => setPos((p) => ({ ...p, active: false }));
    el.addEventListener("mousemove", onMove);
    el.addEventListener("mouseleave", onLeave);
    return () => {
      el.removeEventListener("mousemove", onMove);
      el.removeEventListener("mouseleave", onLeave);
    };
  }, [ref]);
  return pos;
}

// ---------- Reveal on scroll ----------
function Reveal({ children, delay = 0, as: Tag = "div", className = "", style = {} }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setShown(true);
          io.disconnect();
        }
      },
      { threshold: 0.15 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        ...style,
        opacity: shown ? 1 : 0,
        transform: shown ? "translateY(0)" : "translateY(24px)",
        transition: `opacity 0.8s cubic-bezier(.2,.7,.2,1) ${delay}ms, transform 0.8s cubic-bezier(.2,.7,.2,1) ${delay}ms`,
      }}
    >
      {children}
    </Tag>
  );
}

// ---------- Magnetic button ----------
function MagneticCTA({ children, onClick, accent, fg, bg }) {
  const ref = useRef(null);
  const [t, setT] = useState({ x: 0, y: 0 });
  return (
    <button
      ref={ref}
      onClick={onClick}
      onMouseMove={(e) => {
        const r = ref.current.getBoundingClientRect();
        setT({ x: ((e.clientX - r.left - r.width / 2) / r.width) * 12, y: ((e.clientY - r.top - r.height / 2) / r.height) * 12 });
      }}
      onMouseLeave={() => setT({ x: 0, y: 0 })}
      style={{
        position: "relative",
        display: "inline-flex",
        alignItems: "center",
        gap: 12,
        padding: "18px 28px",
        background: accent,
        color: "#0a0a0a",
        border: "none",
        borderRadius: 999,
        fontSize: 16,
        fontWeight: 600,
        letterSpacing: "-0.01em",
        cursor: "pointer",
        transform: `translate(${t.x}px, ${t.y}px)`,
        transition: "transform 0.25s cubic-bezier(.2,.7,.2,1), box-shadow 0.25s",
        boxShadow: `0 0 0 0 ${accent}40, 0 8px 32px ${accent}40`,
        fontFamily: "inherit",
      }}
      onMouseEnter={(e) => (e.currentTarget.style.boxShadow = `0 0 0 8px ${accent}20, 0 16px 48px ${accent}50`)}
    >
      {children}
      <ArrowRight />
    </button>
  );
}

function ArrowRight() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  );
}

// ---------- Backgrounds ----------
function Texture({ kind, accent, mode }) {
  if (kind === "none") return null;
  const dark = mode === "dark";
  const stroke = dark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.05)";
  const dotColor = dark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)";
  if (kind === "grid")
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          backgroundImage: `linear-gradient(${stroke} 1px, transparent 1px), linear-gradient(90deg, ${stroke} 1px, transparent 1px)`,
          backgroundSize: "64px 64px",
          maskImage: "radial-gradient(ellipse at center, black 30%, transparent 80%)",
          WebkitMaskImage: "radial-gradient(ellipse at center, black 30%, transparent 80%)",
          pointerEvents: "none",
        }}
      />
    );
  if (kind === "dots")
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          backgroundImage: `radial-gradient(${dotColor} 1px, transparent 1px)`,
          backgroundSize: "24px 24px",
          maskImage: "radial-gradient(ellipse at center, black 30%, transparent 75%)",
          WebkitMaskImage: "radial-gradient(ellipse at center, black 30%, transparent 75%)",
          pointerEvents: "none",
        }}
      />
    );
  if (kind === "noise")
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          opacity: dark ? 0.5 : 0.35,
          mixBlendMode: dark ? "screen" : "multiply",
          backgroundImage:
            "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/><feColorMatrix values='0 0 0 0 1  0 0 0 0 1  0 0 0 0 1  0 0 0 0.4 0'/></filter><rect width='200' height='200' filter='url(%23n)'/></svg>\")",
          pointerEvents: "none",
        }}
      />
    );
  if (kind === "mesh")
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          background: `radial-gradient(60% 50% at 20% 30%, ${accent}30 0%, transparent 60%), radial-gradient(50% 50% at 80% 70%, ${accent}25 0%, transparent 65%), radial-gradient(40% 40% at 60% 20%, ${dark ? "rgba(120,120,255,0.18)" : "rgba(120,120,255,0.10)"} 0%, transparent 60%)`,
          filter: "blur(20px)",
          pointerEvents: "none",
        }}
      />
    );
  return null;
}

// ---------- Logo mark ----------
function LogoMark({ accent, size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="2" y="2" width="28" height="28" rx="8" fill={accent} />
      <path d="M10 22 L10 10 L16 16 L22 10 L22 22" stroke="#0a0a0a" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ---------- Nav ----------
function Nav({ brand, accent, fg, bg, onCta, ctaLabel }) {
  return (
    <nav
      style={{
        position: "sticky",
        top: 0,
        zIndex: 50,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        padding: "20px 32px",
        backdropFilter: "blur(12px)",
        WebkitBackdropFilter: "blur(12px)",
        background: bg + "cc",
        borderBottom: `1px solid ${fg}10`,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <LogoMark accent={accent} />
        <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em" }}>{brand}</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 28, fontSize: 14, color: fg + "b0" }}>
        <a href="#what" style={{ color: "inherit", textDecoration: "none" }}>What we do</a>
        <a href="#contact" style={{ color: "inherit", textDecoration: "none" }}>Contact</a>
        <button
          onClick={onCta}
          style={{
            background: accent,
            color: "#0a0a0a",
            border: "none",
            borderRadius: 999,
            padding: "10px 18px",
            fontSize: 14,
            fontWeight: 600,
            cursor: "pointer",
            fontFamily: "inherit",
          }}
        >
          {ctaLabel}
        </button>
      </div>
    </nav>
  );
}

// ---------- HERO: Centered ----------
function HeroCentered({ tw, accent, fg, bg, onCta }) {
  const ref = useRef(null);
  const mouse = useMouse(ref);
  return (
    <section
      ref={ref}
      style={{
        position: "relative",
        minHeight: "92vh",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        textAlign: "center",
        padding: "80px 32px",
        overflow: "hidden",
      }}
    >
      <Texture kind={tw.texture} accent={accent} mode={tw.mode} />
      {/* Spotlight */}
      <div
        style={{
          position: "absolute",
          inset: 0,
          background: `radial-gradient(400px 400px at ${mouse.x * 100}% ${mouse.y * 100}%, ${accent}25, transparent 70%)`,
          opacity: mouse.active ? 1 : 0,
          transition: "opacity 0.4s",
          pointerEvents: "none",
        }}
      />
      <Reveal delay={0}>
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            padding: "8px 16px",
            border: `1px solid ${fg}20`,
            borderRadius: 999,
            fontSize: 13,
            color: fg + "b0",
            marginBottom: 32,
            background: fg + "06",
          }}
        >
          <span style={{ width: 6, height: 6, borderRadius: 999, background: accent, boxShadow: `0 0 12px ${accent}` }} />
          {tw.eyebrow}
        </div>
      </Reveal>
      <Reveal delay={120}>
        <h1
          style={{
            fontFamily: "var(--font-display)",
            fontWeight: "var(--display-weight)",
            fontSize: "clamp(48px, 9vw, 128px)",
            lineHeight: 0.95,
            letterSpacing: "var(--tracking)",
            margin: 0,
            maxWidth: 1200,
            textWrap: "balance",
          }}
        >
          {tw.headline.split("◆").map((part, i) =>
            i === 0 ? (
              <span key={i}>{part}</span>
            ) : (
              <span key={i}>
                <span style={{ color: accent, fontStyle: "italic", fontWeight: 400 }}>{part.split(" ")[0]}</span>
                {part.slice(part.split(" ")[0].length)}
              </span>
            )
          )}
        </h1>
      </Reveal>
      <Reveal delay={240}>
        <p
          style={{
            fontSize: "clamp(16px, 1.3vw, 20px)",
            color: fg + "b0",
            maxWidth: 640,
            margin: "32px auto 40px",
            lineHeight: 1.5,
            textWrap: "pretty",
          }}
        >
          {tw.subhead}
        </p>
      </Reveal>
      <Reveal delay={360}>
        <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap", justifyContent: "center" }}>
          <MagneticCTA accent={accent} onClick={onCta}>
            {tw.cta}
          </MagneticCTA>
          <a
            href="#what"
            style={{
              color: fg + "c0",
              textDecoration: "none",
              fontSize: 15,
              padding: "18px 24px",
              border: `1px solid ${fg}20`,
              borderRadius: 999,
            }}
          >
            See how it works
          </a>
        </div>
      </Reveal>
      <Reveal delay={500}>
        <div
          style={{
            marginTop: 80,
            display: "flex",
            gap: 48,
            color: fg + "60",
            fontSize: 12,
            letterSpacing: "0.15em",
            textTransform: "uppercase",
            flexWrap: "wrap",
            justifyContent: "center",
          }}
        >
          <span>SOC 2 ready</span>
          <span>•</span>
          <span>EU + US data residency</span>
          <span>•</span>
          <span>Built on your stack</span>
        </div>
      </Reveal>
    </section>
  );
}

// ---------- HERO: Split ----------
function HeroSplit({ tw, accent, fg, bg, onCta }) {
  const ref = useRef(null);
  const mouse = useMouse(ref);
  return (
    <section
      ref={ref}
      style={{
        position: "relative",
        minHeight: "92vh",
        display: "grid",
        gridTemplateColumns: "1.1fr 1fr",
        gap: 0,
        padding: "80px 32px",
        overflow: "hidden",
        alignItems: "center",
      }}
    >
      <Texture kind={tw.texture} accent={accent} mode={tw.mode} />
      <div style={{ position: "relative", zIndex: 2, paddingRight: 32 }}>
        <Reveal delay={0}>
          <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: accent, marginBottom: 24 }}>
            {tw.eyebrow}
          </div>
        </Reveal>
        <Reveal delay={100}>
          <h1
            style={{
              fontFamily: "var(--font-display)",
              fontWeight: "var(--display-weight)",
              fontSize: "clamp(44px, 6.5vw, 96px)",
              lineHeight: 0.95,
              letterSpacing: "var(--tracking)",
              margin: 0,
              textWrap: "balance",
            }}
          >
            {tw.headline.split("◆").map((part, i) =>
              i === 0 ? (
                <span key={i}>{part}</span>
              ) : (
                <span key={i}>
                  <span style={{ color: accent, fontStyle: "italic", fontWeight: 400 }}>{part.split(" ")[0]}</span>
                  {part.slice(part.split(" ")[0].length)}
                </span>
              )
            )}
          </h1>
        </Reveal>
        <Reveal delay={220}>
          <p style={{ fontSize: 18, color: fg + "b0", maxWidth: 520, marginTop: 28, marginBottom: 36, lineHeight: 1.5 }}>
            {tw.subhead}
          </p>
        </Reveal>
        <Reveal delay={340}>
          <MagneticCTA accent={accent} onClick={onCta}>
            {tw.cta}
          </MagneticCTA>
        </Reveal>
      </div>
      {/* Right: animated console */}
      <Reveal delay={200}>
        <div
          style={{
            position: "relative",
            zIndex: 2,
            border: `1px solid ${fg}15`,
            borderRadius: 24,
            background: fg + "04",
            backdropFilter: "blur(8px)",
            padding: 24,
            boxShadow: `0 40px 80px -20px ${accent}15`,
            transform: `perspective(1200px) rotateY(${(mouse.x - 0.5) * -6}deg) rotateX(${(mouse.y - 0.5) * 4}deg)`,
            transition: "transform 0.2s",
          }}
        >
          <ConsoleAnim accent={accent} fg={fg} />
        </div>
      </Reveal>
    </section>
  );
}

// ---------- Animated console ----------
function ConsoleAnim({ accent, fg }) {
  const lines = [
    { t: "→ trigger", v: "new lead from website", c: accent },
    { t: "  agent", v: "enrich · score · route", c: fg + "90" },
    { t: "  decision", v: "high intent → SDR queue", c: fg + "90" },
    { t: "  draft", v: "personalized reply (3 variants)", c: fg + "90" },
    { t: "✓ done", v: "42s · $0.02 · approved", c: accent },
  ];
  const [shown, setShown] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setShown((s) => (s + 1) % (lines.length + 3)), 700);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{ fontFamily: "ui-monospace, 'JetBrains Mono', monospace", fontSize: 13, lineHeight: 1.9 }}>
      <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
        <span style={{ width: 10, height: 10, borderRadius: 999, background: fg + "20" }} />
        <span style={{ width: 10, height: 10, borderRadius: 999, background: fg + "20" }} />
        <span style={{ width: 10, height: 10, borderRadius: 999, background: fg + "20" }} />
        <span style={{ marginLeft: "auto", color: fg + "60", fontSize: 11 }}>workflow.run</span>
      </div>
      {lines.map((l, i) => (
        <div
          key={i}
          style={{
            opacity: i < shown ? 1 : 0.15,
            transform: i < shown ? "translateX(0)" : "translateX(-8px)",
            transition: "all 0.4s",
            color: l.c,
          }}
        >
          <span style={{ color: fg + "50" }}>{String(i + 1).padStart(2, "0")}  </span>
          <span style={{ fontWeight: 600 }}>{l.t}</span>
          <span style={{ color: fg + "70" }}>  {l.v}</span>
        </div>
      ))}
      <div style={{ height: 16 }} />
      <div style={{ display: "flex", gap: 8, alignItems: "center", color: fg + "60", fontSize: 12 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: accent, boxShadow: `0 0 12px ${accent}` }} />
        running · {Math.min(shown, lines.length)}/{lines.length} steps
      </div>
    </div>
  );
}

// ---------- HERO: Stacked (numbered, like reference) ----------
function HeroStacked({ tw, accent, fg, bg, onCta }) {
  return (
    <section style={{ position: "relative", minHeight: "92vh", padding: "80px 32px", overflow: "hidden" }}>
      <Texture kind={tw.texture} accent={accent} mode={tw.mode} />
      <div style={{ position: "relative", maxWidth: 1400, margin: "0 auto" }}>
        <Reveal>
          <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: accent, marginBottom: 24 }}>
            {tw.eyebrow}
          </div>
        </Reveal>
        <Reveal delay={120}>
          <h1
            style={{
              fontFamily: "var(--font-display)",
              fontWeight: "var(--display-weight)",
              fontSize: "clamp(56px, 11vw, 180px)",
              lineHeight: 0.88,
              letterSpacing: "var(--tracking)",
              margin: 0,
              textWrap: "balance",
            }}
          >
            {tw.headline.split("◆").map((part, i) =>
              i === 0 ? (
                <span key={i}>{part}</span>
              ) : (
                <span key={i}>
                  <span style={{ color: accent, fontStyle: "italic", fontWeight: 400 }}>{part.split(" ")[0]}</span>
                  {part.slice(part.split(" ")[0].length)}
                </span>
              )
            )}
          </h1>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 64, marginTop: 64, alignItems: "start" }}>
          <Reveal delay={300}>
            <p style={{ fontSize: 20, color: fg + "b0", maxWidth: 480, lineHeight: 1.5, margin: 0 }}>
              {tw.subhead}
            </p>
            <div style={{ marginTop: 36 }}>
              <MagneticCTA accent={accent} onClick={onCta}>
                {tw.cta}
              </MagneticCTA>
            </div>
          </Reveal>
          <Reveal delay={420}>
            <div style={{ minWidth: 0 }}>
              <Marquee accent={accent} fg={fg} />
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function Marquee({ accent, fg }) {
  const items = ["Customer Support", "Lead Enrichment", "RAG Search", "Ops Automation", "Sales Outreach", "Data Pipelines", "Doc Processing"];
  return (
    <div style={{ width: "100%", overflow: "hidden", maskImage: "linear-gradient(90deg, transparent, black 10%, black 90%, transparent)", WebkitMaskImage: "linear-gradient(90deg, transparent, black 10%, black 90%, transparent)" }}>
      <div
        style={{
          display: "flex",
          gap: 24,
          animation: "marquee 28s linear infinite",
          whiteSpace: "nowrap",
          width: "max-content",
        }}
      >
        {[...items, ...items].map((it, i) => (
          <span
            key={i}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 8,
              padding: "10px 18px",
              border: `1px solid ${fg}20`,
              borderRadius: 999,
              fontSize: 14,
              color: fg + "c0",
              flexShrink: 0,
            }}
          >
            <span style={{ width: 6, height: 6, borderRadius: 999, background: accent }} />
            {it}
          </span>
        ))}
      </div>
    </div>
  );
}

// ---------- What we do (numbered slabs) ----------
function WhatWeDo({ tw, accent, fg, bg }) {
  const items = tw.bullets;
  return (
    <section id="what" style={{ position: "relative", padding: "120px 32px", borderTop: `1px solid ${fg}10` }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <Reveal>
          <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: accent, marginBottom: 16 }}>
            What we do
          </div>
        </Reveal>
        <Reveal delay={100}>
          <h2
            style={{
              fontFamily: "var(--font-display)",
              fontWeight: "var(--display-weight)",
              fontSize: "clamp(40px, 5.5vw, 80px)",
              lineHeight: 1,
              letterSpacing: "var(--tracking)",
              margin: 0,
              maxWidth: 900,
              textWrap: "balance",
            }}
          >
            {tw.whatHeadline}
          </h2>
        </Reveal>
        <Reveal delay={200}>
          <p style={{ fontSize: 18, color: fg + "a0", maxWidth: 640, marginTop: 24, lineHeight: 1.5 }}>
            {tw.whatSub}
          </p>
        </Reveal>
        <div style={{ marginTop: 64, display: "flex", flexDirection: "column", gap: 0 }}>
          {items.map((it, i) => (
            <Slab key={i} idx={i} item={it} accent={accent} fg={fg} bg={bg} />
          ))}
        </div>
      </div>
    </section>
  );
}

function Slab({ idx, item, accent, fg, bg }) {
  const [hover, setHover] = useState(false);
  return (
    <Reveal delay={idx * 100}>
      <div
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          position: "relative",
          display: "grid",
          gridTemplateColumns: "120px 1fr 1fr auto",
          gap: 32,
          alignItems: "center",
          padding: "36px 0",
          borderTop: `1px solid ${fg}15`,
          cursor: "default",
          transition: "all 0.3s",
        }}
      >
        <div
          style={{
            fontFamily: "var(--font-display)",
            fontSize: 64,
            fontWeight: "var(--display-weight)",
            letterSpacing: "var(--tracking)",
            color: hover ? accent : fg + "30",
            transition: "color 0.3s",
            lineHeight: 1,
          }}
        >
          {String(idx + 1).padStart(2, "0")}
        </div>
        <div
          style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(24px, 2.5vw, 36px)",
            fontWeight: "var(--display-weight)",
            letterSpacing: "var(--tracking)",
            lineHeight: 1.05,
          }}
        >
          {item.title}
        </div>
        <div style={{ fontSize: 16, color: fg + "a0", lineHeight: 1.55, maxWidth: 480 }}>{item.body}</div>
        <div
          style={{
            width: 48,
            height: 48,
            borderRadius: 999,
            border: `1px solid ${fg}25`,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: hover ? "#0a0a0a" : fg,
            background: hover ? accent : "transparent",
            transition: "all 0.3s",
            transform: hover ? "translateX(4px)" : "translateX(0)",
          }}
        >
          <ArrowRight />
        </div>
        {/* Accent bar */}
        <div
          style={{
            position: "absolute",
            left: 0,
            top: 0,
            height: 1,
            width: hover ? "100%" : "0%",
            background: accent,
            transition: "width 0.5s cubic-bezier(.2,.7,.2,1)",
          }}
        />
      </div>
    </Reveal>
  );
}

// ---------- Contact form ----------
function Contact({ tw, accent, fg, bg }) {
  const [form, setForm] = useState({ name: "", email: "", company: "", role: "", size: "", budget: "", goal: "" });
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = (e) => {
    e.preventDefault();
    setSent(true);
  };
  const fieldStyle = {
    width: "100%",
    background: "transparent",
    border: "none",
    borderBottom: `1px solid ${fg}25`,
    padding: "16px 0",
    fontSize: 16,
    color: fg,
    fontFamily: "inherit",
    outline: "none",
    transition: "border-color 0.2s",
  };
  const labelStyle = { fontSize: 12, letterSpacing: "0.15em", textTransform: "uppercase", color: fg + "70", marginBottom: 4, display: "block" };

  return (
    <section id="contact" style={{ position: "relative", padding: "120px 32px", borderTop: `1px solid ${fg}10` }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 96, alignItems: "start" }}>
        <div>
          <Reveal>
            <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: accent, marginBottom: 16 }}>
              Contact
            </div>
          </Reveal>
          <Reveal delay={100}>
            <h2
              style={{
                fontFamily: "var(--font-display)",
                fontWeight: "var(--display-weight)",
                fontSize: "clamp(40px, 5vw, 72px)",
                lineHeight: 1,
                letterSpacing: "var(--tracking)",
                margin: 0,
                textWrap: "balance",
              }}
            >
              {tw.contactHeadline}
            </h2>
          </Reveal>
          <Reveal delay={200}>
            <p style={{ fontSize: 17, color: fg + "a0", marginTop: 24, maxWidth: 420, lineHeight: 1.5 }}>
              {tw.contactSub}
            </p>
          </Reveal>
          <Reveal delay={300}>
            <div style={{ marginTop: 48, display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, color: fg + "c0", fontSize: 15 }}>
                <Dot accent={accent} /> Reply within 1 business day
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 12, color: fg + "c0", fontSize: 15 }}>
                <Dot accent={accent} /> 30-min discovery, no pitch
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 12, color: fg + "c0", fontSize: 15 }}>
                <Dot accent={accent} /> NDA on request
              </div>
            </div>
          </Reveal>
        </div>

        <Reveal delay={150}>
          {sent ? (
            <div
              style={{
                border: `1px solid ${accent}50`,
                background: accent + "10",
                borderRadius: 24,
                padding: 48,
                textAlign: "center",
              }}
            >
              <div style={{ fontSize: 48, marginBottom: 16 }}>✓</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: "var(--display-weight)", letterSpacing: "var(--tracking)" }}>
                Got it.
              </div>
              <div style={{ color: fg + "a0", marginTop: 12 }}>We'll reply to {form.email || "you"} shortly.</div>
              <button
                onClick={() => {
                  setSent(false);
                  setForm({ name: "", email: "", company: "", role: "", size: "", budget: "", goal: "" });
                }}
                style={{
                  marginTop: 24,
                  background: "transparent",
                  border: `1px solid ${fg}30`,
                  color: fg,
                  padding: "10px 20px",
                  borderRadius: 999,
                  cursor: "pointer",
                  fontFamily: "inherit",
                }}
              >
                Send another
              </button>
            </div>
          ) : (
            <form onSubmit={submit} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
              <div>
                <label style={labelStyle}>Full name</label>
                <input required style={fieldStyle} value={form.name} onChange={set("name")} placeholder="Jane Doe" />
              </div>
              <div>
                <label style={labelStyle}>Work email</label>
                <input required type="email" style={fieldStyle} value={form.email} onChange={set("email")} placeholder="jane@company.com" />
              </div>
              <div>
                <label style={labelStyle}>Company</label>
                <input required style={fieldStyle} value={form.company} onChange={set("company")} placeholder="Acme Inc." />
              </div>
              <div>
                <label style={labelStyle}>Role</label>
                <input style={fieldStyle} value={form.role} onChange={set("role")} placeholder="Head of Ops" />
              </div>
              <div>
                <label style={labelStyle}>Team size</label>
                <select style={{ ...fieldStyle, appearance: "none" }} value={form.size} onChange={set("size")}>
                  <option value="" style={{ background: bg }}>Select…</option>
                  <option style={{ background: bg }}>1–10</option>
                  <option style={{ background: bg }}>11–50</option>
                  <option style={{ background: bg }}>51–200</option>
                  <option style={{ background: bg }}>201–1000</option>
                  <option style={{ background: bg }}>1000+</option>
                </select>
              </div>
              <div>
                <label style={labelStyle}>Budget range</label>
                <select style={{ ...fieldStyle, appearance: "none" }} value={form.budget} onChange={set("budget")}>
                  <option value="" style={{ background: bg }}>Select…</option>
                  <option style={{ background: bg }}>&lt; $10k</option>
                  <option style={{ background: bg }}>$10–25k</option>
                  <option style={{ background: bg }}>$25–75k</option>
                  <option style={{ background: bg }}>$75k+</option>
                  <option style={{ background: bg }}>Not sure yet</option>
                </select>
              </div>
              <div style={{ gridColumn: "1 / -1" }}>
                <label style={labelStyle}>What do you want to automate?</label>
                <textarea
                  required
                  style={{ ...fieldStyle, minHeight: 80, resize: "vertical" }}
                  value={form.goal}
                  onChange={set("goal")}
                  placeholder="One paragraph is fine. Be specific about the pain point."
                />
              </div>
              <div style={{ gridColumn: "1 / -1", display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8, flexWrap: "wrap", gap: 16 }}>
                <div style={{ fontSize: 12, color: fg + "70" }}>
                  By submitting, you agree to our basic terms. We don't spam.
                </div>
                <MagneticCTA accent={accent}>Send inquiry</MagneticCTA>
              </div>
            </form>
          )}
        </Reveal>
      </div>
    </section>
  );
}

function Dot({ accent }) {
  return <span style={{ width: 8, height: 8, borderRadius: 999, background: accent, boxShadow: `0 0 12px ${accent}` }} />;
}

// ---------- Footer ----------
function Footer({ brand, accent, fg }) {
  return (
    <footer style={{ padding: "48px 32px", borderTop: `1px solid ${fg}10`, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <LogoMark accent={accent} size={20} />
        <span style={{ fontSize: 14, color: fg + "80" }}>© 2026 {brand}. Built with care.</span>
      </div>
      <div style={{ fontSize: 13, color: fg + "60", fontFamily: "ui-monospace, monospace" }}>v1.0 · template</div>
    </footer>
  );
}

// ---------- Tweaks UI ----------
function TweaksUI({ tw, set }) {
  return (
    <TweaksPanel title="Template Tweaks">
      <TweakSection label="Brand">
        <TweakText label="Company name" value={tw.brand} onChange={(v) => set("brand", v)} />
        <TweakText label="Eyebrow" value={tw.eyebrow} onChange={(v) => set("eyebrow", v)} />
        <TweakText label="Headline (◆ before italic word)" value={tw.headline} onChange={(v) => set("headline", v)} />
        <TweakText label="Subhead" value={tw.subhead} onChange={(v) => set("subhead", v)} />
        <TweakText label="CTA label" value={tw.cta} onChange={(v) => set("cta", v)} />
      </TweakSection>

      <TweakSection label="Hero">
        <TweakRadio label="Layout" value={tw.layout} onChange={(v) => set("layout", v)} options={[
          { value: "centered", label: "Centered" },
          { value: "split", label: "Split" },
          { value: "stacked", label: "Stacked" },
        ]} />
      </TweakSection>

      <TweakSection label="Theme">
        <TweakRadio label="Mode" value={tw.mode} onChange={(v) => set("mode", v)} options={[
          { value: "dark", label: "Dark" },
          { value: "light", label: "Light" },
        ]} />
        <TweakColor label="Accent" value={tw.accent} onChange={(v) => set("accent", v)} />
        <TweakSelect label="Fonts" value={tw.fonts} onChange={(v) => set("fonts", v)}
          options={Object.entries(FONT_PAIRS).map(([k, v]) => ({ value: k, label: v.label }))} />
        <TweakSelect label="Texture" value={tw.texture} onChange={(v) => set("texture", v)}
          options={TEXTURES.map((t) => ({ value: t, label: t }))} />
      </TweakSection>

      <TweakSection label="What we do">
        <TweakText label="Headline" value={tw.whatHeadline} onChange={(v) => set("whatHeadline", v)} />
        <TweakText label="Subhead" value={tw.whatSub} onChange={(v) => set("whatSub", v)} />
        {tw.bullets.map((b, i) => (
          <React.Fragment key={i}>
            <TweakText label={`#${i + 1} title`} value={b.title} onChange={(v) => {
              const next = [...tw.bullets]; next[i] = { ...next[i], title: v }; set("bullets", next);
            }} />
            <TweakText label={`#${i + 1} body`} value={b.body} onChange={(v) => {
              const next = [...tw.bullets]; next[i] = { ...next[i], body: v }; set("bullets", next);
            }} />
          </React.Fragment>
        ))}
      </TweakSection>

      <TweakSection label="Contact">
        <TweakText label="Headline" value={tw.contactHeadline} onChange={(v) => set("contactHeadline", v)} />
        <TweakText label="Subhead" value={tw.contactSub} onChange={(v) => set("contactSub", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ---------- App ----------
function App() {
  const [tw, setTweak] = useTweaks(DEFAULTS);
  const set = (k, v) => setTweak({ [k]: v });

  const pair = FONT_PAIRS[tw.fonts] || FONT_PAIRS["grotesk-inter"];
  const dark = tw.mode === "dark";
  const fg = dark ? "#f5f5f4" : "#0a0a0a";
  const bg = dark ? "#0a0a0a" : "#fafaf9";

  // Apply CSS vars
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--font-display", pair.display);
    r.style.setProperty("--font-body", pair.body);
    r.style.setProperty("--display-weight", pair.displayWeight);
    r.style.setProperty("--tracking", pair.tracking);
    r.style.setProperty("--accent", tw.accent);
    r.style.setProperty("--fg", fg);
    r.style.setProperty("--bg", bg);
    document.body.style.background = bg;
    document.body.style.color = fg;
    document.body.style.fontFamily = pair.body;
  }, [tw.fonts, tw.accent, tw.mode]);

  const onCta = useCallback(() => {
    document.getElementById("contact")?.scrollIntoView?.({ behavior: "smooth" });
  }, []);

  const Hero = tw.layout === "split" ? HeroSplit : tw.layout === "stacked" ? HeroStacked : HeroCentered;

  return (
    <div style={{ background: bg, color: fg, minHeight: "100vh", fontFamily: pair.body }}>
      <Nav brand={tw.brand} accent={tw.accent} fg={fg} bg={bg} ctaLabel={tw.cta} onCta={onCta} />
      <Hero tw={tw} accent={tw.accent} fg={fg} bg={bg} onCta={onCta} />
      <WhatWeDo tw={tw} accent={tw.accent} fg={fg} bg={bg} />
      <Contact tw={tw} accent={tw.accent} fg={fg} bg={bg} />
      <Footer brand={tw.brand} accent={tw.accent} fg={fg} />
      <TweaksUI tw={tw} set={set} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
