const { useState, useEffect, useRef } = React;

// Pull tweaks components exported by tweaks-panel.jsx
const {
  useTweaks,
  TweakSection,
  TweakText,
  TweakColor,
  TweakToggle,
  TweakSelect,
} = window;

// Outer F perimeter — clockwise from START, open path (ends at right wall)
const F_PATH = "M 183,155 L 183,7 L 17,7 L 17,203 L 118,203 L 118,155 L 183,155";
const F_PATH_LEN = 724;
const STROKE_ANIMATION_MS = 5000;

const easeOutQuart = (t) => 1 - Math.pow(1 - t, 4);

// Animation phase config (fractions of total duration)
const STROKE_DRAW_END   = 0.65; // stroke finishes drawing at 65%
const STROKE_FADE_START = 0.55; // stroke begins fading at 55%
const STROKE_FADE_END   = 0.88; // stroke fully dissolved at 88%
const IMG_START         = 0.10; // image reveal begins at 10%
const WORD_TRIGGER      = 0.92; // wordmark fades in at 92%

function AnimatedMark() {
  const imgRef       = useRef(null);
  const strokeGrpRef = useRef(null);
  const baseRef      = useRef(null);
  const wakeRef      = useRef(null);
  const bodyRef      = useRef(null);
  const tipRef       = useRef(null);
  const wordRef      = useRef(null);
  const rafRef       = useRef(null);

  useEffect(() => {
    const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (prefersReduced) {
      if (imgRef.current) imgRef.current.style.clipPath = "inset(0% 0% 0% 0%)";
      if (strokeGrpRef.current) strokeGrpRef.current.style.opacity = "0";
      if (wordRef.current) {
        wordRef.current.style.opacity = "1";
        wordRef.current.style.transform = "translateY(0)";
      }
      return;
    }

    let start = null;
    const tick = (ts) => {
      if (!start) start = ts;
      const prog = Math.min((ts - start) / STROKE_ANIMATION_MS, 1);

      // Stroke draw phase
      const pStroke = easeOutQuart(Math.min(prog / STROKE_DRAW_END, 1));
      const lead = pStroke * F_PATH_LEN;

      if (baseRef.current) baseRef.current.style.strokeDashoffset = F_PATH_LEN * (1 - pStroke);
      if (tipRef.current)  tipRef.current.style.strokeDashoffset  = -(lead - 5);
      if (bodyRef.current) bodyRef.current.style.strokeDashoffset = -(lead - 22.5);
      if (wakeRef.current) wakeRef.current.style.strokeDashoffset = -(lead - 60);

      // Comet group fade
      const fadeProg = Math.max(0, Math.min(
        (prog - STROKE_FADE_START) / (STROKE_FADE_END - STROKE_FADE_START), 1
      ));
      if (strokeGrpRef.current) strokeGrpRef.current.style.opacity = 1 - fadeProg;

      // Image reveal
      const imgProg = Math.max(0, Math.min((prog - IMG_START) / (1 - IMG_START), 1));
      const pImg = 1 - Math.pow(1 - imgProg, 2.5);
      if (imgRef.current) {
        const clip = ((1 - pImg) * 100).toFixed(2);
        imgRef.current.style.clipPath = `inset(${clip}% ${clip}% 0% 0%)`;
      }

      if (prog >= WORD_TRIGGER && wordRef.current) {
        wordRef.current.style.opacity = "1";
        wordRef.current.style.transform = "translateY(0)";
      }

      if (prog < 1) rafRef.current = requestAnimationFrame(tick);
    };
    const delay = setTimeout(() => {
      rafRef.current = requestAnimationFrame(tick);
    }, 300);
    return () => {
      clearTimeout(delay);
      cancelAnimationFrame(rafRef.current);
    };
  }, []);

  const imgH = "clamp(130px, 15vw, 210px)";
  const path = F_PATH;
  const len  = F_PATH_LEN;

  return (
    <div style={{ textAlign: "center", lineHeight: 0 }}>
      <div style={{ position: "relative", display: "inline-block" }}>
        <img
          ref={imgRef}
          src="uploads/Formative_Logo.png"
          alt="Formative Labs"
          style={{
            height: imgH,
            width: "auto",
            display: "block",
            clipPath: "inset(100% 100% 0% 0%)",
          }}
        />
        <svg
          viewBox="0 0 200 220"
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            width: "100%",
            height: "100%",
            overflow: "visible",
            pointerEvents: "none",
          }}
        >
          <defs>
            <filter id="cometGlow" x="-40%" y="-40%" width="180%" height="180%">
              <feGaussianBlur stdDeviation="2.5" result="b" />
              <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
            </filter>
          </defs>
          <g ref={strokeGrpRef}>
            <path ref={baseRef} d={path} fill="none"
              stroke="rgba(0,229,195,0.15)" strokeWidth="1"
              strokeLinecap="square" strokeLinejoin="miter"
              strokeDasharray={len} strokeDashoffset={len} />
            <path ref={wakeRef} d={path} fill="none"
              stroke="rgba(0,229,195,0.2)" strokeWidth="1.5"
              strokeLinecap="round" strokeLinejoin="round"
              strokeDasharray={`50 ${len - 50}`} strokeDashoffset={len} />
            <path ref={bodyRef} d={path} fill="none"
              stroke="rgba(0,229,195,0.5)" strokeWidth="2"
              strokeLinecap="round" strokeLinejoin="round"
              strokeDasharray={`25 ${len - 25}`} strokeDashoffset={len} />
            <path ref={tipRef} d={path} fill="none"
              stroke="#00e5c3" strokeWidth="3"
              strokeLinecap="round" strokeLinejoin="round"
              strokeDasharray={`10 ${len - 10}`} strokeDashoffset={len}
              filter="url(#cometGlow)" />
          </g>
        </svg>
      </div>

      <div
        ref={wordRef}
        style={{
          opacity: 0,
          transform: "translateY(10px)",
          transition: "opacity 0.8s ease, transform 0.8s ease",
          marginTop: 20,
          lineHeight: 1,
        }}
      >
        <span
          style={{
            fontSize: "clamp(28px, 3.8vw, 50px)",
            fontWeight: 700,
            fontFamily: "'IBM Plex Sans', sans-serif",
            color: "#e8e8ef",
            letterSpacing: "-0.015em",
          }}
        >
          Formative
        </span>
        <span
          style={{
            fontSize: "clamp(28px, 3.8vw, 50px)",
            fontWeight: 300,
            fontFamily: "'IBM Plex Sans', sans-serif",
            color: "rgba(232,232,239,0.4)",
            letterSpacing: "0.05em",
            marginLeft: 10,
          }}
        >
          Labs
        </span>
      </div>
    </div>
  );
}

function GradientText({ children, style = {} }) {
  return (
    <span
      style={{
        background: "linear-gradient(135deg, #00e5c3 0%, #3b7cf4 100%)",
        WebkitBackgroundClip: "text",
        WebkitTextFillColor: "transparent",
        backgroundClip: "text",
        ...style,
      }}
    >
      {children}
    </span>
  );
}

function GridBackground({ show }) {
  if (!show) return null;
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        pointerEvents: "none",
        zIndex: 0,
        backgroundImage: `
          linear-gradient(rgba(0,229,195,0.03) 1px, transparent 1px),
          linear-gradient(90deg, rgba(0,229,195,0.03) 1px, transparent 1px)
        `,
        backgroundSize: "60px 60px",
      }}
    />
  );
}

const DEFAULT_NAV_LINKS = [
  ["Agents", "#"],
  ["Docs", "#"],
  ["Articles", "articles.html"],
  ["About", "#"],
];

function Navbar({ ctaText, links = DEFAULT_NAV_LINKS }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", fn);
    return () => window.removeEventListener("scroll", fn);
  }, []);

  return (
    <nav
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        zIndex: 100,
        padding: "0 40px",
        height: 64,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        background: scrolled ? "rgba(17,17,20,0.92)" : "transparent",
        backdropFilter: scrolled ? "blur(16px)" : "none",
        borderBottom: scrolled ? "1px solid rgba(255,255,255,0.06)" : "1px solid transparent",
        transition: "all 0.3s ease",
      }}
    >
      <a href="/" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none" }}>
        <img src="uploads/Formative_Logo.png" alt="Formative" style={{ height: 28, objectFit: "contain" }} />
        <span
          style={{
            fontSize: 16,
            fontWeight: 700,
            fontFamily: "'IBM Plex Sans', sans-serif",
            color: "#fff",
            letterSpacing: "-0.01em",
          }}
        >
          Formative
        </span>
      </a>

      <div style={{ display: "flex", alignItems: "center", gap: 32 }}>
        {links.map(([label, href]) => (
          <a
            key={label}
            href={href}
            style={{
              color: "rgba(232,232,239,0.6)",
              fontSize: 14,
              fontWeight: 500,
              textDecoration: "none",
              letterSpacing: "0.01em",
              transition: "color 0.2s",
            }}
            onMouseEnter={(e) => (e.target.style.color = "#e8e8ef")}
            onMouseLeave={(e) => (e.target.style.color = "rgba(232,232,239,0.6)")}
          >
            {label}
          </a>
        ))}
        <button
          style={{
            background: "linear-gradient(135deg, #00e5c3, #3b7cf4)",
            color: "#0a0a0c",
            border: "none",
            borderRadius: 8,
            padding: "8px 20px",
            fontSize: 13,
            fontWeight: 700,
            cursor: "pointer",
            letterSpacing: "0.02em",
            transition: "opacity 0.2s, transform 0.15s",
          }}
          onMouseEnter={(e) => {
            e.target.style.opacity = "0.85";
            e.target.style.transform = "translateY(-1px)";
          }}
          onMouseLeave={(e) => {
            e.target.style.opacity = "1";
            e.target.style.transform = "translateY(0)";
          }}
        >
          {ctaText}
        </button>
      </div>
    </nav>
  );
}

function Hero({ headline, subheadline, ctaText, fontPair }) {
  const fontMap = {
    Instrument: { family: "'Instrument Serif', serif", weight: 400, tracking: "-0.02em" },
    "Editorial New": { family: "'Playfair Display', serif", weight: 700, tracking: "-0.025em" },
    Syne: { family: "'Syne', sans-serif", weight: 800, tracking: "-0.03em" },
    "IBM Plex Sans": { family: "'IBM Plex Sans', sans-serif", weight: 700, tracking: "-0.025em" },
  };
  const font = fontMap[fontPair] || fontMap.Instrument;
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    setTimeout(() => setVisible(true), 80);
  }, []);

  return (
    <section
      style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        padding: "120px 40px 80px",
        position: "relative",
        zIndex: 1,
        textAlign: "center",
      }}
    >
      <div style={{ marginBottom: 56 }}>
        <AnimatedMark />
      </div>

      <div
        style={{
          position: "absolute",
          top: "15%",
          left: "50%",
          transform: "translateX(-50%)",
          width: 600,
          height: 400,
          background: "radial-gradient(ellipse, rgba(0,229,195,0.12) 0%, rgba(59,124,244,0.08) 40%, transparent 70%)",
          pointerEvents: "none",
          zIndex: -1,
        }}
      />

      <div
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
          border: "1px solid rgba(0,229,195,0.3)",
          borderRadius: 100,
          padding: "6px 16px",
          marginBottom: 40,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(12px)",
          transition: "all 0.6s ease",
          background: "rgba(0,229,195,0.06)",
        }}
      >
        <span
          style={{
            width: 6,
            height: 6,
            borderRadius: "50%",
            background: "#00e5c3",
            boxShadow: "0 0 8px #00e5c3",
            display: "inline-block",
            animation: "pulse 2s infinite",
          }}
        />
        <span
          style={{
            fontSize: 12,
            fontWeight: 600,
            color: "#00e5c3",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
          }}
        >
          Now in Private Beta
        </span>
      </div>

      <h1
        style={{
          fontFamily: font.family,
          fontSize: "clamp(36px, 6vw, 88px)",
          fontWeight: font.weight,
          lineHeight: 1.04,
          letterSpacing: font.tracking,
          maxWidth: 900,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(20px)",
          transition: "all 0.7s ease 0.1s",
        }}
      >
        {headline.includes("Agents") ? (
          <>
            Build the <GradientText>Agents</GradientText> That Build Everything Else.
          </>
        ) : (
          <>{headline}</>
        )}
      </h1>

      <p
        style={{
          marginTop: 28,
          fontSize: "clamp(16px, 2vw, 20px)",
          lineHeight: 1.65,
          color: "rgba(232,232,239,0.6)",
          maxWidth: 640,
          fontWeight: 400,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(20px)",
          transition: "all 0.7s ease 0.2s",
        }}
      >
        {subheadline}
      </p>

      <div
        style={{
          marginTop: 48,
          display: "flex",
          gap: 16,
          alignItems: "center",
          flexWrap: "wrap",
          justifyContent: "center",
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(20px)",
          transition: "all 0.7s ease 0.3s",
        }}
      >
        <button
          style={{
            background: "linear-gradient(135deg, #00e5c3, #3b7cf4)",
            color: "#0a0a0c",
            border: "none",
            borderRadius: 10,
            padding: "14px 32px",
            fontSize: 15,
            fontWeight: 700,
            cursor: "pointer",
            letterSpacing: "0.01em",
            transition: "all 0.2s",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = "translateY(-2px)";
            e.currentTarget.style.boxShadow = "0 12px 40px rgba(0,229,195,0.3)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = "none";
            e.currentTarget.style.boxShadow = "none";
          }}
        >
          {ctaText} →
        </button>
        <button
          style={{
            background: "transparent",
            color: "rgba(232,232,239,0.7)",
            border: "1px solid rgba(255,255,255,0.12)",
            borderRadius: 10,
            padding: "14px 32px",
            fontSize: 15,
            fontWeight: 500,
            cursor: "pointer",
            transition: "all 0.2s",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = "rgba(255,255,255,0.3)";
            e.currentTarget.style.color = "#e8e8ef";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = "rgba(255,255,255,0.12)";
            e.currentTarget.style.color = "rgba(232,232,239,0.7)";
          }}
        >
          Read the Docs
        </button>
      </div>

      <div
        style={{
          marginTop: 80,
          maxWidth: 560,
          width: "100%",
          background: "rgba(255,255,255,0.03)",
          border: "1px solid rgba(255,255,255,0.08)",
          borderRadius: 14,
          padding: "24px 28px",
          textAlign: "left",
          fontFamily: "'IBM Plex Mono', monospace",
          fontSize: 13,
          lineHeight: 1.8,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(20px)",
          transition: "all 0.8s ease 0.45s",
        }}
      >
        <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
          {["#ff5f57", "#febc2e", "#28c840"].map((c) => (
            <div key={c} style={{ width: 10, height: 10, borderRadius: "50%", background: c }} />
          ))}
        </div>
        <div>
          <span style={{ color: "#00e5c3" }}>import</span>{" "}
          <span style={{ color: "#e8e8ef" }}>{"{ FormativeAgent }"}</span>{" "}
          <span style={{ color: "#00e5c3" }}>from</span> <span style={{ color: "#a78bfa" }}>'@formative/core'</span>
        </div>
        <br />
        <div>
          <span style={{ color: "#3b7cf4" }}>const</span> <span style={{ color: "#e8e8ef" }}>agent</span>{" "}
          <span style={{ color: "#00e5c3" }}>=</span> <span style={{ color: "#3b7cf4" }}>new</span>{" "}
          <span style={{ color: "#00e5c3" }}>FormativeAgent</span>
          <span style={{ color: "#e8e8ef" }}>({"{"}</span>
        </div>
        <div style={{ paddingLeft: 20 }}>
          <span style={{ color: "#a78bfa" }}>model</span><span style={{ color: "#e8e8ef" }}>:</span>{" "}
          <span style={{ color: "#f59e0b" }}>'gpt-4o'</span><span style={{ color: "#e8e8ef" }}>,</span>
        </div>
        <div style={{ paddingLeft: 20 }}>
          <span style={{ color: "#a78bfa" }}>tools</span><span style={{ color: "#e8e8ef" }}>:</span>{" "}
          <span style={{ color: "#3b7cf4" }}>[</span><span style={{ color: "#f59e0b" }}>'search'</span>
          <span style={{ color: "#e8e8ef" }}>,</span> <span style={{ color: "#f59e0b" }}>'code'</span>
          <span style={{ color: "#e8e8ef" }}>,</span> <span style={{ color: "#f59e0b" }}>'deploy'</span>
          <span style={{ color: "#3b7cf4" }}>]</span><span style={{ color: "#e8e8ef" }}>,</span>
        </div>
        <div style={{ paddingLeft: 20 }}>
          <span style={{ color: "#a78bfa" }}>memory</span><span style={{ color: "#e8e8ef" }}>:</span>{" "}
          <span style={{ color: "#3b7cf4" }}>true</span>
        </div>
        <div><span style={{ color: "#e8e8ef" }}>{"})"}</span></div>
        <br />
        <div><span style={{ color: "#6b7280" }}>// Ship it. Agents handle the rest.</span></div>
        <div>
          <span style={{ color: "#3b7cf4" }}>await</span> <span style={{ color: "#e8e8ef" }}>agent</span>
          <span style={{ color: "#00e5c3" }}>.</span><span style={{ color: "#00e5c3" }}>run</span>
          <span style={{ color: "#e8e8ef" }}>(</span><span style={{ color: "#f59e0b" }}>'Build and deploy a REST API'</span>
          <span style={{ color: "#e8e8ef" }}>)</span>
        </div>
      </div>
    </section>
  );
}

function LogosBar() {
  const logos = ["OpenAI", "Anthropic", "LangChain", "Temporal", "Vercel", "AWS", "GitHub"];
  return (
    <section
      style={{
        padding: "32px 40px",
        borderTop: "1px solid rgba(255,255,255,0.06)",
        borderBottom: "1px solid rgba(255,255,255,0.06)",
        position: "relative",
        zIndex: 1,
      }}
    >
      <p
        style={{
          textAlign: "center",
          fontSize: 12,
          letterSpacing: "0.12em",
          textTransform: "uppercase",
          color: "rgba(232,232,239,0.25)",
          marginBottom: 24,
        }}
      >
        Integrates with the tools you already use
      </p>
      <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 48, flexWrap: "wrap" }}>
        {logos.map((name) => (
          <span
            key={name}
            style={{
              fontSize: 14,
              fontWeight: 600,
              color: "rgba(232,232,239,0.2)",
              letterSpacing: "0.04em",
              textTransform: "uppercase",
              transition: "color 0.2s",
              cursor: "default",
            }}
            onMouseEnter={(e) => (e.target.style.color = "rgba(232,232,239,0.6)")}
            onMouseLeave={(e) => (e.target.style.color = "rgba(232,232,239,0.2)")}
          >
            {name}
          </span>
        ))}
      </div>
    </section>
  );
}

function AgenticSection() {
  const steps = [
    { old: "Write code", new: "Compose agents", icon: "⌨" },
    { old: "Debug line by line", new: "Observe & orchestrate", icon: "⚡" },
    { old: "Deploy manually", new: "Ship autonomously", icon: "🚀" },
    { old: "Manage dependencies", new: "Select AI tools", icon: "🔧" },
  ];
  return (
    <section style={{ padding: "120px 40px", maxWidth: 1100, margin: "0 auto", position: "relative", zIndex: 1 }}>
      <div style={{ textAlign: "center", marginBottom: 80 }}>
        <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "#00e5c3", marginBottom: 16 }}>
          The Shift
        </p>
        <h2 style={{ fontSize: "clamp(28px, 4vw, 52px)", fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1.1 }}>
          Development has changed.
          <br />
          <GradientText>Have you?</GradientText>
        </h2>
        <p style={{ marginTop: 20, color: "rgba(232,232,239,0.55)", fontSize: 17, lineHeight: 1.7, maxWidth: 540, margin: "20px auto 0" }}>
          Agentic engineering is the discipline of building, selecting, and orchestrating AI agents as your primary development primitive.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 2 }}>
        {steps.map((step, i) => (
          <div
            key={i}
            style={{
              background: "rgba(255,255,255,0.025)",
              border: "1px solid rgba(255,255,255,0.07)",
              borderRadius: i === 0 ? "14px 0 0 14px" : i === steps.length - 1 ? "0 14px 14px 0" : "0",
              padding: "36px 28px",
              transition: "background 0.2s, border-color 0.2s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = "rgba(0,229,195,0.04)";
              e.currentTarget.style.borderColor = "rgba(0,229,195,0.2)";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = "rgba(255,255,255,0.025)";
              e.currentTarget.style.borderColor = "rgba(255,255,255,0.07)";
            }}
          >
            <div style={{ fontSize: 24, marginBottom: 20 }}>{step.icon}</div>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", color: "rgba(232,232,239,0.3)", marginBottom: 6 }}>Before</div>
            <div style={{ fontSize: 15, color: "rgba(232,232,239,0.45)", textDecoration: "line-through", marginBottom: 16 }}>{step.old}</div>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", color: "#00e5c3", marginBottom: 6 }}>Now</div>
            <div style={{ fontSize: 18, fontWeight: 600, color: "#e8e8ef" }}>{step.new}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function ProductsSection() {
  const products = [
    {
      name: "Agent Forge",
      tag: "Core Platform",
      desc: "The foundational layer for building production-grade agents. Memory, tool use, and multi-step reasoning — all configurable in code.",
      color: "#00e5c3",
    },
    {
      name: "Conductor",
      tag: "Orchestration",
      desc: "Multi-agent orchestration with DAG-based workflows. Define dependencies, handoffs, and fallback logic without managing state machines.",
      color: "#3b7cf4",
    },
    {
      name: "Signals",
      tag: "Observability",
      desc: "Full-stack observability for your agentic systems. Trace every decision, every tool call, every reasoning step in real time.",
      color: "#a78bfa",
    },
  ];

  return (
    <section style={{ padding: "80px 40px 120px", maxWidth: 1100, margin: "0 auto", position: "relative", zIndex: 1 }}>
      <div style={{ marginBottom: 64 }}>
        <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "#00e5c3", marginBottom: 16 }}>
          What We Build
        </p>
        <h2 style={{ fontSize: "clamp(28px, 4vw, 48px)", fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1.1 }}>
          A studio, not a startup.
          <br />
          <span style={{ color: "rgba(232,232,239,0.4)" }}>Every product ships as infrastructure.</span>
        </h2>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        {products.map((p, i) => (
          <div
            key={i}
            style={{
              background: "rgba(255,255,255,0.025)",
              border: "1px solid rgba(255,255,255,0.08)",
              borderRadius: 16,
              padding: "36px 32px",
              position: "relative",
              overflow: "hidden",
              transition: "transform 0.2s, box-shadow 0.2s",
              cursor: "default",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = "translateY(-4px)";
              e.currentTarget.style.boxShadow = "0 20px 60px rgba(0,0,0,0.4)";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = "none";
              e.currentTarget.style.boxShadow = "none";
            }}
          >
            <div
              style={{
                position: "absolute",
                top: 0,
                left: 0,
                right: 0,
                height: 2,
                background: `linear-gradient(90deg, ${p.color}, transparent)`,
              }}
            />
            <span
              style={{
                display: "inline-block",
                fontSize: 11,
                fontWeight: 700,
                letterSpacing: "0.1em",
                textTransform: "uppercase",
                color: p.color,
                background: `${p.color}18`,
                border: `1px solid ${p.color}40`,
                borderRadius: 6,
                padding: "3px 10px",
                marginBottom: 20,
              }}
            >
              {p.tag}
            </span>
            <h3 style={{ fontSize: 24, fontWeight: 700, marginBottom: 14, letterSpacing: "-0.02em" }}>{p.name}</h3>
            <p style={{ fontSize: 15, color: "rgba(232,232,239,0.55)", lineHeight: 1.7 }}>{p.desc}</p>
            <div style={{ marginTop: 28, fontSize: 13, fontWeight: 600, color: p.color, cursor: "pointer" }}>Learn more →</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function HowItWorksSection() {
  const steps = [
    { n: "01", title: "Define your agent", body: "Describe capabilities, tools, and context boundaries. Formative handles the plumbing." },
    { n: "02", title: "Compose workflows", body: "Chain agents together into multi-step pipelines using our declarative orchestration layer." },
    { n: "03", title: "Observe in real time", body: "Full trace visibility into every decision, handoff, and tool invocation — no black boxes." },
    { n: "04", title: "Ship to production", body: "Deploy agents as durable, stateful services with built-in retries, memory, and monitoring." },
  ];

  return (
    <section
      style={{
        padding: "80px 40px 120px",
        borderTop: "1px solid rgba(255,255,255,0.06)",
        position: "relative",
        zIndex: 1,
        background: "rgba(255,255,255,0.012)",
      }}
    >
      <div style={{ maxWidth: 1100, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 72 }}>
          <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "#00e5c3", marginBottom: 16 }}>
            How It Works
          </p>
          <h2 style={{ fontSize: "clamp(28px, 4vw, 48px)", fontWeight: 700, letterSpacing: "-0.025em" }}>From idea to agent in minutes.</h2>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 32, position: "relative" }}>
          {steps.map((s, i) => (
            <div key={i} style={{ position: "relative" }}>
              <div
                style={{
                  fontSize: "clamp(48px, 5vw, 64px)",
                  fontWeight: 700,
                  fontFamily: "'IBM Plex Mono', monospace",
                  color: "rgba(0,229,195,0.12)",
                  lineHeight: 1,
                  marginBottom: 16,
                }}
              >
                {s.n}
              </div>
              <h3 style={{ fontSize: 18, fontWeight: 600, marginBottom: 10 }}>{s.title}</h3>
              <p style={{ fontSize: 14, color: "rgba(232,232,239,0.5)", lineHeight: 1.7 }}>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}


function ArticleTag({ label, color }) {
  return (
    <span style={{
      display: "inline-block",
      fontSize: 11,
      fontWeight: 700,
      letterSpacing: "0.1em",
      textTransform: "uppercase",
      color: color,
      background: `color-mix(in srgb, ${color} 10%, transparent)`,
      border: `1px solid color-mix(in srgb, ${color} 25%, transparent)`,
      borderRadius: 6,
      padding: "3px 10px",
      fontFamily: "'IBM Plex Sans', sans-serif",
    }}>{label}</span>
  );
}

function ArticleReadLink() {
  return (
    <span style={{
      fontSize: 13,
      fontWeight: 600,
      color: "#00e5c3",
      fontFamily: "'IBM Plex Sans', sans-serif",
      cursor: "pointer",
      letterSpacing: "0.01em",
    }}
      onMouseEnter={(e) => e.currentTarget.style.opacity = "0.75"}
      onMouseLeave={(e) => e.currentTarget.style.opacity = "1"}
    >Read →</span>
  );
}

function ArticlesSection() {
  const [articles, setArticles] = React.useState([]);

  React.useEffect(() => {
    fetch("articles/manifest.json")
      .then(r => r.ok ? r.json() : [])
      .then(data => setArticles(Array.isArray(data) ? data : []))
      .catch(() => {});
  }, []);

  // Manifest is already sorted newest first
  const featured = articles[0] || null;
  const secondary = articles.slice(1, 3);

  // Don't render the section until we have at least one article
  if (!featured) return null;

  return (
    <section style={{
      padding: "120px 40px 80px",
      position: "relative",
      zIndex: 1,
      borderTop: "1px solid rgba(255,255,255,0.06)",
    }}>
      <div style={{ maxWidth: 1100, margin: "0 auto" }}>

        {/* Section header */}
        <div style={{ marginBottom: 56 }}>
          <p style={{
            fontSize: 12, fontWeight: 700, letterSpacing: "0.12em",
            textTransform: "uppercase", color: "#00e5c3",
            fontFamily: "'IBM Plex Sans', sans-serif", marginBottom: 14,
          }}>From the Lab</p>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
            <h2 style={{
              fontSize: "clamp(28px, 4vw, 44px)", fontWeight: 700,
              letterSpacing: "-0.025em", lineHeight: 1.1,
              fontFamily: "'IBM Plex Sans', sans-serif",
            }}>Writing on agentic engineering.</h2>
            <a href="articles.html" style={{
              fontSize: 13, fontWeight: 600, color: "rgba(232,232,239,0.45)",
              fontFamily: "'IBM Plex Sans', sans-serif",
              letterSpacing: "0.01em", flexShrink: 0, textDecoration: "none",
            }}
              onMouseEnter={(e) => e.currentTarget.style.color = "#e8e8ef"}
              onMouseLeave={(e) => e.currentTarget.style.color = "rgba(232,232,239,0.45)"}
            >All writing →</a>
          </div>
        </div>

        {/* Article grid: 7/12 featured + 5/12 secondary stack (only if secondary exists) */}
        <div style={{
          display: "grid",
          gridTemplateColumns: secondary.length > 0 ? "7fr 5fr" : "1fr",
          gap: 2,
        }}>

          {/* Featured article */}
          <a href={`article.html?slug=${featured.slug}`} style={{ textDecoration: "none" }}>
            <div style={{
              background: "rgba(255,255,255,0.025)",
              border: "1px solid rgba(255,255,255,0.08)",
              borderRadius: secondary.length > 0 ? "16px 0 0 16px" : "16px",
              padding: "44px 48px",
              display: "flex",
              flexDirection: "column",
              gap: 28,
              cursor: "pointer",
              height: "100%",
              transition: "border-color 0.2s, transform 0.2s, box-shadow 0.2s",
            }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = "rgba(255,255,255,0.14)";
                e.currentTarget.style.transform = "translateY(-3px)";
                e.currentTarget.style.boxShadow = "0 20px 60px rgba(0,0,0,0.4)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = "rgba(255,255,255,0.08)";
                e.currentTarget.style.transform = "none";
                e.currentTarget.style.boxShadow = "none";
              }}
            >
              <div>
                <ArticleTag label={featured.tag} color={featured.tagColor} />
              </div>
              <div>
                <h3 style={{
                  fontSize: "clamp(20px, 2.4vw, 28px)", fontWeight: 700,
                  letterSpacing: "-0.02em", lineHeight: 1.2,
                  color: "#e8e8ef", marginBottom: 16,
                  fontFamily: "'IBM Plex Sans', sans-serif",
                }}>{featured.title}</h3>
                {featured.excerpt && (
                  <p style={{
                    fontSize: 15, color: "rgba(232,232,239,0.55)",
                    lineHeight: 1.75, maxWidth: "52ch",
                    fontFamily: "'IBM Plex Sans', sans-serif",
                  }}>{featured.excerpt}</p>
                )}
              </div>

              {/* Pull quote */}
              {featured.pullQuote && (
                <blockquote style={{ margin: 0, paddingTop: 24, borderTop: "1px solid rgba(255,255,255,0.08)" }}>
                  <p style={{
                    fontSize: 17, fontWeight: 500,
                    color: "rgba(232,232,239,0.8)", lineHeight: 1.6,
                    letterSpacing: "-0.01em", fontStyle: "italic",
                    fontFamily: "'Instrument Serif', Georgia, serif",
                  }}>&ldquo;{featured.pullQuote}&rdquo;</p>
                </blockquote>
              )}

              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto" }}>
                <span style={{
                  fontSize: 12, color: "rgba(232,232,239,0.3)",
                  fontFamily: "'IBM Plex Mono', monospace", letterSpacing: "0.04em",
                }}>{featured.readTime} &nbsp;·&nbsp; {featured.date}</span>
                <ArticleReadLink />
              </div>
            </div>
          </a>

          {/* Secondary stack */}
          {secondary.length > 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {secondary.map((article, i) => (
                <a key={article.slug} href={`article.html?slug=${article.slug}`} style={{ textDecoration: "none", display: "flex", flex: 1 }}>
                  <div style={{
                    background: "rgba(255,255,255,0.02)",
                    border: "1px solid rgba(255,255,255,0.08)",
                    borderRadius: i === 0
                      ? (secondary.length === 1 ? "0 16px 16px 0" : "0 16px 0 0")
                      : "0 0 16px 0",
                    padding: "36px 36px",
                    display: "flex",
                    flexDirection: "column",
                    gap: 16,
                    flex: 1,
                    cursor: "pointer",
                    transition: "border-color 0.2s, background 0.2s",
                  }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.borderColor = "rgba(255,255,255,0.14)";
                      e.currentTarget.style.background = "rgba(255,255,255,0.035)";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.borderColor = "rgba(255,255,255,0.08)";
                      e.currentTarget.style.background = "rgba(255,255,255,0.02)";
                    }}
                  >
                    <ArticleTag label={article.tag} color={article.tagColor} />
                    <h4 style={{
                      fontSize: 17, fontWeight: 700, letterSpacing: "-0.018em",
                      lineHeight: 1.3, color: "#e8e8ef",
                      fontFamily: "'IBM Plex Sans', sans-serif",
                    }}>{article.title}</h4>
                    {article.excerpt && (
                      <p style={{
                        fontSize: 14, color: "rgba(232,232,239,0.45)",
                        lineHeight: 1.7, fontFamily: "'IBM Plex Sans', sans-serif",
                      }}>{article.excerpt}</p>
                    )}
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto" }}>
                      <span style={{
                        fontSize: 12, color: "rgba(232,232,239,0.25)",
                        fontFamily: "'IBM Plex Mono', monospace", letterSpacing: "0.04em",
                      }}>{article.readTime} &nbsp;·&nbsp; {article.date}</span>
                      <ArticleReadLink />
                    </div>
                  </div>
                </a>
              ))}
            </div>
          )}

        </div>
      </div>
    </section>
  );
}

function EnterpriseCTA() {
  return (
    <section
      style={{
        padding: "80px 40px 60px",
        position: "relative",
        zIndex: 1,
        borderTop: "1px solid rgba(255,255,255,0.06)",
      }}
    >
      <div style={{ maxWidth: 1100, margin: "0 auto", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
        <div
          style={{
            background: "linear-gradient(135deg, rgba(0,229,195,0.08), rgba(59,124,244,0.06))",
            border: "1px solid rgba(0,229,195,0.2)",
            borderRadius: 20,
            padding: "48px 40px",
          }}
        >
          <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "#00e5c3", marginBottom: 16 }}>
            For Developers
          </p>
          <h3 style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 16, lineHeight: 1.2 }}>Start building agents today.</h3>
          <p style={{ color: "rgba(232,232,239,0.55)", fontSize: 15, lineHeight: 1.7, marginBottom: 32 }}>
            Join developers rethinking what it means to ship software. Private beta is open.
          </p>
          <button
            style={{
              background: "linear-gradient(135deg, #00e5c3, #3b7cf4)",
              color: "#0a0a0c",
              border: "none",
              borderRadius: 10,
              padding: "14px 28px",
              fontSize: 14,
              fontWeight: 700,
              cursor: "pointer",
              transition: "all 0.2s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = "translateY(-2px)";
              e.currentTarget.style.boxShadow = "0 12px 40px rgba(0,229,195,0.3)";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = "none";
              e.currentTarget.style.boxShadow = "none";
            }}
          >
            Get Early Access →
          </button>
        </div>

        <div
          style={{
            background: "rgba(255,255,255,0.025)",
            border: "1px solid rgba(255,255,255,0.08)",
            borderRadius: 20,
            padding: "48px 40px",
          }}
        >
          <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(232,232,239,0.4)", marginBottom: 16 }}>
            For Enterprise
          </p>
          <h3 style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 16, lineHeight: 1.2 }}>
            Bring agentic engineering to your org.
          </h3>
          <p style={{ color: "rgba(232,232,239,0.45)", fontSize: 15, lineHeight: 1.7, marginBottom: 32 }}>
            Enterprises move slow. Formative Labs helps you move fast — with the security, compliance, and support your teams need.
          </p>
          <button
            style={{
              background: "transparent",
              color: "rgba(232,232,239,0.7)",
              border: "1px solid rgba(255,255,255,0.15)",
              borderRadius: 10,
              padding: "14px 28px",
              fontSize: 14,
              fontWeight: 600,
              cursor: "pointer",
              transition: "all 0.2s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = "rgba(255,255,255,0.35)";
              e.currentTarget.style.color = "#e8e8ef";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = "rgba(255,255,255,0.15)";
              e.currentTarget.style.color = "rgba(232,232,239,0.7)";
            }}
          >
            Talk to us →
          </button>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer
      style={{
        padding: "48px 40px",
        borderTop: "1px solid rgba(255,255,255,0.06)",
        position: "relative",
        zIndex: 1,
      }}
    >
      <div style={{ maxWidth: 1100, margin: "0 auto", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 20 }}>
        <img src="uploads/Formative-Labs-White.png" alt="Formative Labs" style={{ height: 28, opacity: 0.7 }} />
        <p style={{ fontSize: 13, color: "rgba(232,232,239,0.25)" }}>© 2026 Formative Labs · Building the agentic future.</p>
        <div style={{ display: "flex", gap: 24 }}>
          {["Twitter", "GitHub", "Discord"].map((link) => (
            <a
              key={link}
              href="#"
              style={{ fontSize: 13, color: "rgba(232,232,239,0.3)", textDecoration: "none", transition: "color 0.2s" }}
              onMouseEnter={(e) => (e.target.style.color = "#e8e8ef")}
              onMouseLeave={(e) => (e.target.style.color = "rgba(232,232,239,0.3)")}
            >
              {link}
            </a>
          ))}
        </div>
      </div>
    </footer>
  );
}

function SharedChrome({ tweaks, navLinks, children }) {
  return (
    <>
      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.5; transform: scale(0.85); }
        }
        @media (max-width: 768px) {
          nav { padding: 0 20px !important; }
          nav > div:last-child a { display: none; }
        }
      `}</style>
      <GridBackground show={tweaks.showGrid} />
      <Navbar ctaText={tweaks.ctaText} links={navLinks} />
      {children}
    </>
  );
}

function FullSiteApp({ tweaks }) {
  return (
    <SharedChrome tweaks={tweaks}>
      <Hero headline={tweaks.headline} subheadline={tweaks.subheadline} ctaText={tweaks.ctaText} fontPair={tweaks.fontPair} />
      <LogosBar />
      <AgenticSection />
      <ProductsSection />
      <HowItWorksSection />
      <ArticlesSection />
      <EnterpriseCTA />
      <Footer />
    </SharedChrome>
  );
}

function BetaV1App({ tweaks }) {
  return (
    <SharedChrome tweaks={tweaks}>
      <Hero headline={tweaks.headline} subheadline={tweaks.subheadline} ctaText={tweaks.ctaText} fontPair={tweaks.fontPair} />
      <LogosBar />
    </SharedChrome>
  );
}

function LandingApp({ tweaks }) {
  return (
    <SharedChrome tweaks={tweaks} navLinks={[["Articles", "articles.html"]]}>
      <Hero headline={tweaks.headline} subheadline={tweaks.subheadline} ctaText={tweaks.ctaText} fontPair={tweaks.fontPair} />
      <ArticlesSection />
      <Footer />
    </SharedChrome>
  );
}

function SiteShell({ mode = "full", tweakDefaults }) {
  const tweakResult = typeof useTweaks === "function" ? useTweaks(tweakDefaults) : { tweaks: tweakDefaults, TweaksPanel: () => null };
  const tweaks = tweakResult.tweaks || tweakDefaults;
  const TweaksPanel = tweakResult.TweaksPanel || (() => null);
  const AppComponent = mode === "landing" ? LandingApp : mode === "beta-v1" ? BetaV1App : FullSiteApp;

  return (
    <>
      <AppComponent tweaks={tweaks} />
      <TweaksPanel>
        <TweakSection label="Copy">
          <TweakText id="headline" label="Headline" value={tweaks.headline} />
          <TweakText id="ctaText" label="CTA Button" value={tweaks.ctaText} />
        </TweakSection>
        <TweakSection label="Visual">
          <TweakColor id="accentColor" label="Accent Color" value={tweaks.accentColor} />
          <TweakToggle id="showGrid" label="Show Grid" value={tweaks.showGrid} />
          <TweakSelect id="fontPair" label="Headline Font" value={tweaks.fontPair} options={["Instrument", "Editorial New", "Syne", "IBM Plex Sans"]} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

window.FormativeSite = {
  render: ({ rootId = "root", mode = "full", tweakDefaults }) => {
    ReactDOM.createRoot(document.getElementById(rootId)).render(
      <SiteShell mode={mode} tweakDefaults={tweakDefaults} />
    );
  },
};
