// Homepage-only sections: Hero, Pillars, HowItWorks, Stats, CodeStrip
const { useState, useEffect, useMemo } = React;

const HERO_VARIANTS = {
  economics: {
    eyebrow: 'The AI inference economics control plane',
    h1: <>Inference is<br/>infrastructure.<br/><em>Treat it like a P&amp;L.</em></>,
    sub: 'Bloom sits between your app and every model. Per-customer cost attribution, smart routing, guardrails, and closed-loop evals — governed at the inference layer.',
  },
  slo: {
    eyebrow: 'The AI inference control plane',
    h1: <>Route inference.<br/>Hit your SLO.<br/><em>Pay for what runs.</em></>,
    sub: 'One endpoint. Every provider. Bloom routes across regions, enforces SLOs, batches and caches — and gives you one bill, one dashboard, and one set of metrics.',
  },
  cfo: {
    eyebrow: 'AI economics, governed',
    h1: <>The CFO sees one line.<br/>The CTO sees a thousand traces.<br/><em>Bloom shows the P&amp;L.</em></>,
    sub: 'Per-customer, per-agent, per-team economics for every dollar of inference you spend. Visibility first. Routing savings second. Guardrails always.',
  },
  half: {
    eyebrow: 'Half a sprint to deploy',
    h1: <>One URL change.<br/>1,000+ models.<br/><em>20–60% less cost.</em></>,
    sub: 'Point your existing client at the gateway. Keep your provider contracts. Bloom never sits on the bill — we sit between every prompt and every model.',
  },
};

const Hero = ({ headline = 'economics', illustration = 'route' }) => {
  const v = HERO_VARIANTS[headline] || HERO_VARIANTS.economics;
  const VIZ_MAP = {
    route: window.RouteDiagram,
    topology: window.TopologyViz,
    latency: window.LatencyViz,
    stack: window.StackViz,
    dashboard: window.DashboardViz,
    flow: window.FlowViz,
  };
  const Viz = VIZ_MAP[illustration] || window.RouteDiagram;
  return (
    <div className="hero">
      <div className="bg-grid-dec" />
      <div className="container inner">
        <div>
          <div className="eyebrow">{v.eyebrow}</div>
          <h1 style={{ marginTop: 18 }}>{v.h1}</h1>
          <p className="sub">{v.sub}</p>
          <div className="cta-row">
            <a href="pilot.html" className="btn btn-primary btn-lg">Apply to pilot →</a>
            <a href="product.html" className="btn btn-secondary btn-lg">See the product</a>
          </div>
          <div className="proof">
            <span>BACKED BY LG NOVA</span>
            <span className="sep">·</span>
            <span>SOC 2 TYPE II</span>
            <span className="sep">·</span>
            <span>1,000+ MODELS</span>
            <span className="sep">·</span>
            <span>VPC OR SAAS</span>
          </div>
        </div>
        <div><Viz /></div>
      </div>
    </div>
  );
};

/* ───────────── Stats strip ───────────── */
const StatsStrip = () => {
  return (
    <div className="container">
      <div className="stats">
        <div className="stat">
          <div className="k">Time to deploy</div>
          <div className="v">~½<small>sprint</small></div>
          <div className="note">One URL change. Keep your provider contracts.</div>
        </div>
        <div className="stat">
          <div className="k">Gateway overhead · target</div>
          <div className="v">&lt; 100<small>ms</small></div>
          <div className="note">Added p99 between your client and the model.</div>
        </div>
        <div className="stat">
          <div className="k">Modeled cost reduction</div>
          <div className="v">20–60<small>%</small></div>
          <div className="note">Routing, caching, and prompt optimization, combined.</div>
        </div>
        <div className="stat">
          <div className="k">Models supported</div>
          <div className="v tabular">1,000+</div>
          <div className="note">OpenAI · Anthropic · Gemini · OSS · your own vLLM.</div>
        </div>
      </div>
    </div>
  );
};

/* ───────────── Four pillars (tabbed) ───────────── */
const PILLARS = [
  {
    num: '01', verb: 'observe', title: 'Visibility',
    h: 'Per-customer gross margin intelligence.',
    lede: '',
    bullets: [
      'Per-customer LLM cost attribution · x-customer-id',
      'Per-session and per-agent cost rollups',
      'Gross margin dashboard: revenue vs. LLM cost',
      'Spend spike and margin degradation alerts',
    ],
  },
  {
    num: '02', verb: 'route', title: 'Smart routing',
    h: 'Optimal model. Optimal provider. Every request.',
    lede: 'Bloom dynamically routes each request balancing cost, quality, and latency. 20–60% reduction in inference costs. Near-zero added latency. No ongoing engineering overhead.',
    bullets: [
      'Rules-based routing by cost, latency SLA, or task',
      'Semantic caching: reuse responses for equivalent prompts',
      'Prompt optimization: trim redundant tokens before dispatch',
      'Failover across OpenAI · Anthropic · Gemini · 1,000+',
    ],
  },
  {
    num: '03', verb: 'enforce', title: 'Guardrails',
    h: 'Policy at the inference layer. Not the app layer.',
    lede: 'Bloom enforces input/output policies at the gateway, before prompts reach models and before responses reach users. App-layer guardrails are inconsistent. At the inference layer, they are universal.',
    bullets: [
      'Token budget and quota enforcement, per team or customer',
      'PII detection and redaction in prompts (pre-send)',
      'Toxicity and content policy filters on responses',
      'Audit logging for compliance and incident review',
    ],
  },
  {
    num: '04', verb: 'score', title: 'Closed-loop evals',
    h: 'Quality intelligence that feeds routing.',
    lede: 'Bloom continuously scores model output quality and feeds that signal back into routing. The data flywheel: more traffic → better evals → smarter routing → lower cost and higher quality.',
    bullets: [
      'Automated scoring: relevance, coherence, instruction-following',
      'A/B model evaluation across providers on live traffic',
      'Regression detection: alert when quality degrades',
      'Routing feedback loop: scores inform future decisions',
    ],
  },
];

const PillarPanelViz = ({ which }) => {
  const reqId = useTicker(412, () => Math.floor(Math.random() * 9) + 1, 1300, n => n.toLocaleString());
  if (which === 0) {
    // Visibility: full DashboardViz with by-customer / by-agent toggle (compact in pillar panel)
    return <window.DashboardViz compact />;
  }
  if (which === 1) {
    // Routing: mini route diagram
    return (
      <div style={{ background: 'var(--paper)', border: '1px solid var(--border-1)', borderRadius: 6, padding: 12 }}>
        <window.RouteDiagram />
      </div>
    );
  }
  if (which === 2) {
    // Guardrails: policy checklist
    const policies = [
      { k: 'Token budget · acme · weekly', v: '$840 / $1,000', state: 'ok' },
      { k: 'PII redaction · all prompts',   v: '↓ 7 fields',     state: 'ok' },
      { k: 'Toxicity filter · output',      v: 'on · 0 blocked', state: 'ok' },
      { k: 'Topic blocklist · finance-bot', v: '12 terms',       state: 'ok' },
      { k: 'Quota · stark · monthly',       v: '92% of cap',     state: 'warn' },
    ];
    return (
      <div style={{ background: 'var(--paper)', border: '1px solid var(--border-1)', borderRadius: 6 }}>
        {policies.map((p, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderTop: i ? '1px solid var(--border-1)' : 0, fontSize: 13 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: p.state === 'ok' ? 'var(--ok)' : 'var(--warn)' }} />
              {p.k}
            </span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>{p.v}</span>
          </div>
        ))}
      </div>
    );
  }
  // Evals
  const models = [
    { m: 'gpt-4o',         s: 0.94 },
    { m: 'claude-sonnet-4', s: 0.96 },
    { m: 'llama-3-70b',    s: 0.88 },
    { m: 'gemini-1.5-pro', s: 0.91 },
  ];
  return (
    <div style={{ background: 'var(--paper)', border: '1px solid var(--border-1)', borderRadius: 6, padding: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 12 }}>
        <span>Model quality · 7 days</span><span>support-bot</span>
      </div>
      {models.map((m, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 60px', gap: 12, alignItems: 'center', padding: '6px 0', fontSize: 13 }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{m.m}</span>
          <span style={{ height: 6, background: 'var(--paper-3)', borderRadius: 2, position: 'relative', overflow: 'hidden' }}>
            <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: (m.s * 100) + '%', background: m.s > 0.92 ? 'var(--ok)' : m.s > 0.89 ? 'var(--signal)' : 'var(--warn)' }}/>
          </span>
          <span className="tabular" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, textAlign: 'right' }}>{m.s.toFixed(2)}</span>
        </div>
      ))}
    </div>
  );
};

const Pillars = () => {
  const [active, setActive] = useState(0);
  const p = PILLARS[active];
  return (
    <div className="section" id="pillars">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow center">What it does</div>
          <h2>Four pillars.<br/>One control plane.</h2>
          <p className="sub">Visibility first. Then routing. Then guardrails. Quality stays in the loop. Each pillar feeds the next — the longer Bloom runs, the more it learns.</p>
        </div>
        <div className="pillars">
          <div className="pillar-tabs" role="tablist">
            {PILLARS.map((pp, i) => (
              <button key={pp.num} className={'pillar-tab ' + (i === active ? 'active' : '')} onClick={() => setActive(i)}>
                <span className="num">{pp.num}</span>
                <span className="grow">
                  <div className="title">{pp.title}</div>
                  <div className="verb">{pp.verb}</div>
                </span>
                <span className="arrow">→</span>
              </button>
            ))}
          </div>
          <div className="pillar-panel" key={active}>
            <div className="head">
              <h3>{p.h}</h3>
              <span className="verb">{p.num} · {p.verb}</span>
            </div>
            {p.lede && <p className="lede">{p.lede}</p>}
            <ul>{p.bullets.map(b => <li key={b}>{b}</li>)}</ul>
            <div className="panel-viz"><PillarPanelViz which={active}/></div>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ───────────── How it works ───────────── */
const HowItWorks = () => (
  <div className="section" id="how">
    <div className="container">
      <div className="section-head">
        <div className="eyebrow center">How it works</div>
        <h2>A lightweight gateway.<br/>One HTTP header.</h2>
        <p className="sub">Half a sprint to deploy. Sits in your VPC or our SaaS. You keep your provider relationships — Bloom never sits on the bill.</p>
      </div>
      <div className="how">
        <div className="step">
          <div className="num">01 · INTEGRATE</div>
          <div className="h">One URL change.</div>
          <div className="p">Point your existing client at the gateway. No rewrites. OpenAI-compatible, drop-in for LangChain, LlamaIndex, and your homemade Python.</div>
          <div className="code"><span className="c"># swap base_url</span>{`\n`}base_url=<span className="k">"api.bloom.dev/v1"</span></div>
        </div>
        <div className="step">
          <div className="num">02 · DEPLOY</div>
          <div className="h">Your VPC, or Bloom SaaS.</div>
          <div className="p">Run the gateway in your own cloud, or use our hosted control plane. Either way, &lt; 100ms p99 added overhead. SOC 2 Type II from day one.</div>
          <div className="code"><span className="c"># or terraform apply</span>{`\n`}helm install bloom .</div>
        </div>
        <div className="step">
          <div className="num">03 · OWN</div>
          <div className="h">Keep your contracts.</div>
          <div className="p">Your provider relationships and rate cards stay yours. Bloom never sits on the bill. Switch to or away from us in an afternoon.</div>
          <div className="code"><span className="c"># your keys, your invoices</span>{`\n`}provider <span className="k">openai</span>{` { … }`}</div>
        </div>
      </div>
    </div>
  </div>
);

/* ───────────── Code strip ───────────── */
const SAMPLES = {
  python: (
    <pre><span className="c"># Bloom inference · Python</span>{`
`}<span className="k">from</span> openai <span className="k">import</span> OpenAI{`

`}client = OpenAI({`
  `}base_url=<span className="s">"https://api.bloom.dev/v1"</span>,{`
  `}api_key=<span className="s">"sk_live_…"</span>,{`
  `}default_headers={`{`}<span className="s">"x-customer-id"</span>: <span className="s">"acme_42"</span>{`}`}{`
)

`}resp = client.chat.completions.create({`
  `}model=<span className="s">"auto"</span>,  <span className="c"># bloom routes</span>{`
  `}messages=[{`{`}<span className="s">"role"</span>: <span className="s">"user"</span>, <span className="s">"content"</span>: <span className="s">"hi"</span>{`}`}],{`
  `}metadata={`{`}<span className="s">"team"</span>: <span className="s">"support"</span>{`}`}{`
)`}</pre>
  ),
  node: (
    <pre><span className="c">// Bloom inference · Node</span>{`
`}<span className="k">import</span> OpenAI <span className="k">from</span> <span className="s">"openai"</span>;{`

`}<span className="k">const</span> client = <span className="k">new</span> OpenAI({`{`}{`
  `}baseURL: <span className="s">"https://api.bloom.dev/v1"</span>,{`
  `}apiKey: process.env.BLOOM_KEY,{`
  `}defaultHeaders: {`{`} <span className="s">"x-customer-id"</span>: <span className="s">"acme_42"</span> {`}`}{`
{`}{`});

`}<span className="k">const</span> r = <span className="k">await</span> client.chat.completions.create({`{`}{`
  `}model: <span className="s">"auto"</span>,{`
  `}messages: [{`{`} role: <span className="s">"user"</span>, content: <span className="s">"hi"</span> {`}`}]{`
{`}{`});`}</pre>
  ),
  curl: (
    <pre><span className="c"># Bloom inference · curl</span>{`
`}curl https://api.bloom.dev/v1/chat/completions \\{`
  `}-H <span className="s">"authorization: Bearer $BLOOM_KEY"</span> \\{`
  `}-H <span className="s">"x-customer-id: acme_42"</span> \\{`
  `}-H <span className="s">"x-team-id: support"</span> \\{`
  `}-d <span className="s">'{`{`}"model":"auto","messages":[…]{`}`}'</span></pre>
  ),
};

const CodeStrip = () => {
  const [tab, setTab] = useState('python');
  return (
    <div className="code-strip">
      <div className="container inner">
        <div>
          <div className="eyebrow">Drop-in</div>
          <h2>Three lines.<br/>Same SDK.</h2>
          <p>Change your base URL. Add one header. Keep your code. Bloom is OpenAI-compatible, so anything that talks to OpenAI talks to Bloom.</p>
        </div>
        <div>
          <div className="code-tabs">
            {['python', 'node'].map(t => (
              <button key={t} className={'code-tab ' + (tab === t ? 'active' : '')} onClick={() => setTab(t)}>{t}</button>
            ))}
          </div>
          {SAMPLES[tab]}
        </div>
      </div>
    </div>
  );
};

/* ───────────── Backed by + value-over-time ───────────── */
const ValueOverTime = () => (
  <div className="section">
    <div className="container">
      <div className="section-head left">
        <div className="eyebrow">The value to you</div>
        <h2>Day 1 to month 3.<br/>Then compounding.</h2>
        <p className="sub">Each phase unlocks the next. Most customers recover the platform fee inside 60 days.</p>
      </div>
      <div className="phases">
        <div className="phase">
          <div className="lab">DAY 1</div>
          <div className="h">Cost attribution</div>
          <div className="p">Finance can finally allocate AI spend. Every dollar tagged to a customer, feature, and team.</div>
          <div className="out">▸ COST BY CUSTOMER · AGENT · TEAM</div>
        </div>
        <div className="phase">
          <div className="lab">WEEK 2</div>
          <div className="h">Routing savings</div>
          <div className="p">Prompt optimization, semantic caching, and multi-model routing kick in.</div>
          <div className="out">▸ 20–60% INFERENCE COST CUT</div>
        </div>
        <div className="phase">
          <div className="lab">MONTH 3</div>
          <div className="h">Governed economics</div>
          <div className="p">Budgets, alerts, and guardrails enforced at the gateway. Surprise bills become impossible.</div>
          <div className="out">▸ POLICY IN PRODUCTION</div>
        </div>
        <div className="phase">
          <div className="lab">ONGOING</div>
          <div className="h">Compounding intelligence</div>
          <div className="p">Closed-loop evals feed routing. Quality goes up. Cost goes down. The system improves with every request.</div>
          <div className="out">▸ FLYWHEEL ENGAGED</div>
        </div>
      </div>
    </div>
  </div>
);

const PilotCTA = () => (
  <div className="section" id="pilot-cta">
    <div className="container">
      <div className="cta-strip">
        <div>
          <div className="eyebrow">Design partner program · Q2 2026</div>
          <h3>90 days. Four phases. One workload.</h3>
          <p>The cohort is small and intentional. A handful of customers shaping what the first commercial release looks like, before pricing and roadmap harden.</p>
        </div>
        <div className="right">
          <a href="pilot.html" className="btn btn-primary btn-lg">Apply to pilot →</a>
          <span className="meta">4 of 6 spots remaining · closes this quarter</span>
        </div>
      </div>
    </div>
  </div>
);

window.HomeHero = Hero;
window.HomeStats = StatsStrip;
window.HomePillars = Pillars;
window.HomeHow = HowItWorks;
window.HomeCode = CodeStrip;
window.HomeValue = ValueOverTime;
window.HomePilotCTA = PilotCTA;
