/* Headroom Compression — public marketing page for the sellable context-
   compression feature.

   Ported from packages/web-portal/src/pages/features/HeadroomCompression.tsx
   (portal route /features/headroom) as part of the portal-5-page redesign —
   public marketing pages don't belong behind/inside the authenticated
   web-portal bundle, they belong on the marketing site. Layout follows
   page-features-cave-recorder.jsx: section components composed into one Page
   function, using Header / Footer / StampBadge / Underline / Ico from
   shared.jsx + page-home.jsx. Static site, no build step — same as every
   other page here.

   Configuration itself is admin-side (RuntimeConfig: headroom.config +
   headroom.company.<id>) — CTAs point at the portal login / usage dashboard
   on app.mammoth-dev.com rather than an in-app <Link>, since this page is
   served from a separate static origin and can't use react-router.
*/

const HR = {
  brandName: () => (typeof window !== 'undefined' && window.MAMMOTH_BRAND_NAME) || 'Mammoth-dev',
  appUrl: (path) => `https://app.mammoth-dev.com${path}`,
};

function HeadroomHero() {
  const name = HR.brandName();
  return (
    <section className="m-section" style={{paddingTop:56, paddingBottom:40}}>
      <div className="m-container" style={{textAlign:'center', maxWidth:880}}>
        <StampBadge color="var(--teal)">New · Sellable feature</StampBadge>
        <h1 style={{marginTop:20, marginBottom:20, textWrap:'balance'}}>
          Cut LLM token costs <Underline color="var(--teal)">40–90%</Underline> — same answers
        </h1>
        <p className="lead" style={{margin:'0 auto 20px', maxWidth:700}}>
          Headroom compresses the noisy parts of every prompt — tool outputs,
          logs, RAG chunks — <em>before</em> they reach the model. It runs inside
          the {name} proxy, so there's nothing to install. You keep the
          quality; you split the savings.
        </p>
        <div className="m-row" style={{justifyContent:'center', gap:12}}>
          <a href={HR.appUrl('/login')} className="m-btn m-btn-russet m-btn-lg">
            Enable for my account {Ico.arrow(16,'currentColor')}
          </a>
          <a href="#how-it-works" className="m-btn m-btn-ghost m-btn-lg">
            See how it works
          </a>
        </div>
        <p style={{fontSize:13, color:'var(--charcoal-soft)', marginTop:16}}>
          Benchmarked ~0 quality change. Off by default — flip it on per account.
        </p>
      </div>
    </section>
  );
}

function HeadroomFlowDiagram() {
  return (
    <div className="m-card" style={{marginTop:32, padding:20, overflowX:'auto'}}>
      <svg
        viewBox="0 0 880 160"
        style={{width:'100%', maxWidth:880, height:'auto', display:'block'}}
        role="img"
        aria-label="Headroom compression flow diagram"
      >
        <HeadroomFlowBox x={10} y={50} w={150} h={60} title="Client LLM call" sub="messages array" fill="#e8f0ff" />
        <HeadroomFlowArrow from={[160, 80]} to={[200, 80]} />
        <HeadroomFlowBox x={200} y={50} w={160} h={60} title="Compression layer" sub="per-company gate" fill="#e0f2ec" />
        <HeadroomFlowArrow from={[360, 80]} to={[400, 80]} />
        <HeadroomFlowBox x={400} y={50} w={150} h={60} title="Headroom sidecar" sub="Kompress model" fill="#dff3e6" />
        <HeadroomFlowArrow from={[550, 80]} to={[590, 80]} />
        <HeadroomFlowBox x={590} y={50} w={140} h={60} title="Vendor API" sub="fewer input tok" fill="#fff7e0" />
        <HeadroomFlowArrow from={[730, 80]} to={[770, 80]} />
        <HeadroomFlowBox x={770} y={50} w={100} h={60} title="Billing" sub="split savings" fill="#fef2f7" />
      </svg>
    </div>
  );
}

function HeadroomHowItWorks() {
  const steps = [
    { n:'1', title:'Your call hits the proxy', body:'Any anthropic / openai / gemini / grok / perplexity chat call routed through the platform is intercepted before it leaves for the vendor.' },
    { n:'2', title:'Headroom compresses', body:'The local Kompress model squeezes repetitive tool outputs, logs and RAG chunks. Short prose is left alone — it self-calibrates by payload.' },
    { n:'3', title:'Vendor sees fewer tokens', body:'The compressed prompt goes upstream. The model answers from the same information at a fraction of the input tokens. Tens of ms added, fully cached-warm.' },
    { n:'4', title:'Savings get split', body:'A configurable split passes part of the savings to you as a lower bill and keeps part as platform margin. Every call is itemized for audit.' },
  ];
  return (
    <section id="how-it-works" className="m-section m-section-alt">
      <div className="m-container">
        <div style={{textAlign:'center', marginBottom:24}}>
          <StampBadge color="var(--teal)">How it works</StampBadge>
          <h2 style={{marginTop:16, marginBottom:8}}>A compression step sits on the LLM proxy path.</h2>
          <p className="lead" style={{maxWidth:640, margin:'0 auto'}}>
            Every chat/completion call through the platform passes through it — no SDK, no code change.
          </p>
        </div>

        <HeadroomFlowDiagram />

        <div className="m-grid m-grid-2" style={{gap:20, marginTop:40}}>
          {steps.map((s, i) => (
            <div key={i} className="m-card" style={{display:'flex', gap:16, alignItems:'flex-start'}}>
              <div style={{width:28, height:28, borderRadius:14, background:'var(--teal)', color:'var(--cream)', fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, flexShrink:0}}>
                {s.n}
              </div>
              <div>
                <div style={{fontWeight:700, fontSize:16, marginBottom:6}}>{s.title}</div>
                <p style={{margin:0, fontSize:14, color:'var(--charcoal-soft)'}}>{s.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HeadroomSavingsSplit() {
  const splits = [
    { label:'Split 0%', billed:'Billed 1,000 tok', who:'All savings → platform margin. Invisible to the client.', featured:false },
    { label:'Split 50%', billed:'Billed 800 tok', who:'Savings shared evenly. Client bill drops, margin grows.', featured:true },
    { label:'Split 100%', billed:'Billed 600 tok', who:'All savings → client. Sell it as a pure cost-cut feature.', featured:false },
  ];
  return (
    <section className="m-section">
      <div className="m-container">
        <div style={{textAlign:'center', marginBottom:36}}>
          <StampBadge color="var(--teal)">You choose the split</StampBadge>
          <h2 style={{marginTop:16, marginBottom:8}}>One dial controls who captures the savings.</h2>
          <p className="lead" style={{maxWidth:640, margin:'0 auto'}}>
            Example: a call whose input compresses from 1,000 → 600 tokens.
          </p>
        </div>
        <div className="m-grid m-grid-3" style={{gap:20}}>
          {splits.map((s, i) => (
            <div
              key={i}
              className="m-card"
              style={{border: s.featured ? '2px solid var(--teal)' : undefined, boxShadow: s.featured ? '0 8px 24px rgba(0,102,102,0.12)' : undefined}}
            >
              <div style={{fontSize:13, color:'var(--teal)', fontWeight:700, letterSpacing:'0.05em', textTransform:'uppercase'}}>{s.label}</div>
              <div style={{fontSize:26, fontWeight:800, margin:'8px 0 10px'}}>{s.billed}</div>
              <div style={{fontSize:14, color:'var(--charcoal-soft)', lineHeight:1.5}}>{s.who}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HeadroomCTAFooter() {
  return (
    <section className="m-section" style={{background:'var(--charcoal)', color:'var(--cream)'}}>
      <div className="m-container" style={{textAlign:'center', maxWidth:720}}>
        <StampBadge color="var(--teal)">Stop paying for tokens the model doesn't need</StampBadge>
        <h2 style={{marginTop:16, color:'var(--cream)'}}>Turn Headroom on and watch the input-token line drop.</h2>
        <p style={{color:'rgba(255,253,249,0.85)', fontSize:18, marginBottom:28}}>
          No SDK, no migration, reversible instantly.
        </p>
        <a href={HR.appUrl('/login')} className="m-btn m-btn-gold m-btn-lg">
          Enable Headroom {Ico.arrow(16,'currentColor')}
        </a>
      </div>
    </section>
  );
}

function FeaturesHeadroomCompressionPage() {
  return (
    <div className="m-root">
      <Header current="" />
      <HeadroomHero />
      <HeadroomHowItWorks />
      <HeadroomSavingsSplit />
      <HeadroomCTAFooter />
      <Footer />
    </div>
  );
}

// ─── Small shared SVG helpers (mirrors page-features-cave-recorder.jsx style
// of keeping the page fully self-contained) ─────────────────────────────────

function HeadroomFlowBox({ x, y, w, h, title, sub, fill }) {
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={6} fill={fill} stroke="#bbb" strokeWidth={1} />
      <text x={x + w / 2} y={y + 25} textAnchor="middle" fontSize={13} fontWeight={700} fill="#222">{title}</text>
      <text x={x + w / 2} y={y + 44} textAnchor="middle" fontSize={11} fill="#555">{sub}</text>
    </g>
  );
}

function HeadroomFlowArrow({ from, to }) {
  const [x1, y1] = from;
  const [x2, y2] = to;
  const angle = Math.atan2(y2 - y1, x2 - x1);
  const a = 6;
  const ax = x2 - a * Math.cos(angle - Math.PI / 6);
  const ay = y2 - a * Math.sin(angle - Math.PI / 6);
  const bx = x2 - a * Math.cos(angle + Math.PI / 6);
  const by = y2 - a * Math.sin(angle + Math.PI / 6);
  return (
    <g stroke="#888" strokeWidth={1.5} fill="none">
      <line x1={x1} y1={y1} x2={x2} y2={y2} />
      <line x1={x2} y1={y2} x2={ax} y2={ay} />
      <line x1={x2} y1={y2} x2={bx} y2={by} />
    </g>
  );
}

Object.assign(window, { FeaturesHeadroomCompressionPage });
