// Shared trade landing page template — designed for paid traffic.
// Expects window.TRADE_DATA to be set in the host page before this script loads.

const { C, F, Nav, Footer, SectionTitle, Stamp, Btn, Eyebrow, JumpNav, StickyBottomCTA } = window;
const T = window.TRADE_DATA;

const TRADE_JUMP_LINKS = [
  { label: 'Pipeline',  href: '#pipeline' },
  { label: 'Simulator', href: '#simulator' },
  { label: 'Proof',     href: '#proof' },
  { label: 'Stack',     href: '#features' },
  { label: 'FAQ',       href: '#faq' },
];

function Hero() {
  return (
    <section id="overview" className="hero-viewport" style={{ position: 'relative', borderBottom: `2px solid ${C.ink}`, background: C.ink }}>
      <img src={`/img/${T.heroImg}`} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(95deg, rgba(22,22,26,0.92) 0%, rgba(22,22,26,0.55) 60%, rgba(22,22,26,0.15) 100%)' }} />
      <div style={{ position: 'relative', padding: '40px 40px 80px', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', height: '100%' }}>
        <div style={{ minWidth: 0, maxWidth: 900 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 28, flexWrap: 'wrap' }}>
            <Stamp color={C.hi}>// TRADE: {T.code}</Stamp>
            <Stamp color={C.hi}>{T.cycle} CYCLE</Stamp>
            <Stamp color={C.hi}>{T.ticket} AVG</Stamp>
            <Stamp color={C.hi}>1 PER METRO</Stamp>
            <Stamp color={C.hi}>★ {T.trust.rating} · {T.trust.operators} OPERATORS</Stamp>
          </div>
          <h1 style={{
            fontFamily: F.display, fontSize: 'clamp(56px, 6.5vw, 100px)', lineHeight: 0.84, color: C.bg,
            letterSpacing: '-0.025em', textTransform: 'uppercase', margin: 0, textWrap: 'balance',
            whiteSpace: 'pre-line', overflowWrap: 'break-word', hyphens: 'auto',
          }}>
            {T.hero.title}
          </h1>
          <p style={{ fontFamily: F.sans, fontSize: 19, lineHeight: 1.5, color: C.faint, maxWidth: 620, marginTop: 32 }}>
            {T.hero.sub}
          </p>
          <div style={{ display: 'flex', gap: 16, marginTop: 36, flexWrap: 'wrap' }}>
            <Btn primary href="/book-scoping-call">GET STARTED ▸</Btn>
            <Btn dark href="#simulator">CALCULATE PROFIT ▸</Btn>
          </div>
        </div>
      </div>
    </section>
  );
}

function TrustBar() {
  return (
    <section style={{ background: C.ink, color: C.panel, padding: '28px 40px', borderBottom: `4px solid ${C.hi}` }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 32, fontFamily: F.mono, fontSize: 12, letterSpacing: 1.2, fontWeight: 600 }}>
        <span style={{ color: C.hi }}>★★★★★ 4.9 AVG CLIENT RATING</span>
        <span>1 OPERATOR PER METRO · {T.code}</span>
        <span>14 METROS LIVE · 10 TRADES</span>
        <span>99.98% UPTIME · 24/7 OPS</span>
      </div>
    </section>
  );
}

function Physics() {
  return (
    <section id="physics" style={{ padding: '100px 40px' }}>
      <SectionTitle eyebrow="Pipeline physics">How {T.name.toLowerCase()} actually behaves.</SectionTitle>
      <p style={{ fontFamily: F.sans, fontSize: 17, lineHeight: 1.55, color: C.muted, maxWidth: 720, margin: '0 0 48px' }}>
        Every trade has its own pipeline economics. Here's what we tune for in {T.name.toLowerCase()} specifically.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', border: `2px solid ${C.ink}`, background: C.bg }}>
        {T.physics.map((p, i) => (
          <div key={p.t} style={{ padding: 32, borderRight: i < T.physics.length - 1 ? `1px solid ${C.rule}` : 'none' }}>
            <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.6, color: C.hiDark, fontWeight: 700, marginBottom: 12 }}>{p.t}</div>
            <div style={{ fontFamily: F.display, fontSize: 56, color: C.ink, letterSpacing: -1.4, lineHeight: 0.88, marginBottom: 12 }}>{p.v}</div>
            <div style={{ fontFamily: F.sans, fontSize: 13, lineHeight: 1.5, color: C.muted }}>{p.d}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function Problem() {
  return (
    <section id="problem" style={{ padding: '100px 40px', background: C.ink, color: C.panel }}>
      <SectionTitle eyebrow="The problem" dark>End the feast<br />or famine stress.</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
        {T.problems.map((p, i) => (
          <div key={i} style={{ padding: 32, background: 'rgba(255,255,255,0.03)', border: `1px solid rgba(255,255,255,0.1)` }}>
            <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.6, color: C.hi, fontWeight: 700, marginBottom: 16 }}>F-{String(i+1).padStart(3,'0')} · {p.code}</div>
            <h3 style={{ fontFamily: F.display, fontSize: 30, letterSpacing: -0.6, textTransform: 'uppercase', color: C.bg, margin: '0 0 16px', lineHeight: 1 }}>{p.t}</h3>
            <p style={{ fontFamily: F.sans, fontSize: 14, lineHeight: 1.55, color: C.faint, margin: 0 }}>{p.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function PipelineFlow() {
  return (
    <section id="pipeline" style={{ background: C.ink, color: C.panel, padding: '88px 40px', position: 'relative', borderTop: `2px solid rgba(255,255,255,0.08)` }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px),
                          linear-gradient(90deg, rgba(255,255,255,0.05) 1px, transparent 1px)`,
        backgroundSize: '40px 40px',
      }} />
      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.4fr)', gap: 56, alignItems: 'start' }}>
        <div style={{ minWidth: 0 }}>
          <Stamp color={C.hi}>DRAWING DTG-{T.code}</Stamp>
          <h2 style={{ fontFamily: F.display, fontSize: 'clamp(48px, 5.5vw, 88px)', lineHeight: 0.88, letterSpacing: '-0.025em', color: C.panel, margin: '20px 0 16px', textTransform: 'uppercase' }}>
            The {T.name.toLowerCase()}<br /><span style={{ color: C.hi }}>pipeline.</span>
          </h2>
          <div style={{ fontFamily: F.mono, fontSize: 11, color: C.faint, letterSpacing: 0.4, marginBottom: 24 }}>
            HOW A STRANGER BECOMES A PAID {T.name.toUpperCase()} INSTALL ↓
          </div>
          <p style={{ fontFamily: F.sans, fontSize: 16, lineHeight: 1.55, color: 'rgba(242,239,233,0.78)', maxWidth: 360, margin: '0 0 36px' }}>
            Six steps. Each one measurable. Each one tunable. Built for how {T.name.toLowerCase()} sales actually close.
          </p>
          <Btn primary href="/book-scoping-call">GET STARTED ▸</Btn>
        </div>
        <div style={{ minWidth: 0 }}>
          {T.pipeline.map((step, i, arr) => (
            <div key={step.code} style={{
              display: 'grid', gridTemplateColumns: '40px 1fr auto',
              gap: 16, alignItems: 'center', padding: '16px 0',
              borderBottom: i < arr.length - 1 ? `1px dashed rgba(255,255,255,0.18)` : 'none',
            }}>
              <div style={{
                width: 36, height: 36, border: `1.5px solid ${C.hi}`, color: C.hi,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: F.display, fontSize: 18, letterSpacing: -0.4,
              }}>{step.code}</div>
              <div>
                <div style={{ fontFamily: F.display, fontSize: 18, color: C.panel, letterSpacing: -0.2, textTransform: 'uppercase' }}>{step.label}</div>
                <div style={{ fontFamily: F.mono, fontSize: 11, color: C.faint, letterSpacing: 0.4, marginTop: 2 }}>{step.sub}</div>
              </div>
              <div style={{ fontFamily: F.mono, fontSize: 12, color: C.hi, letterSpacing: 1.2, fontWeight: 700, whiteSpace: 'nowrap' }}>{step.metric}</div>
            </div>
          ))}
          <div style={{
            marginTop: 20, padding: '16px 18px',
            border: `2px solid ${C.hi}`, color: C.hi,
            fontFamily: F.mono, fontSize: 12, letterSpacing: 1.4, fontWeight: 700,
            display: 'flex', justifyContent: 'space-between',
          }}>
            <span>● NET RESULT</span>
            <span>~{T.sim.installs} INSTALLS / MONTH</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function Stack() {
  return (
    <>
    <section id="features" style={{ padding: '100px 40px', background: C.panel }}>
      <SectionTitle eyebrow="The system">What we install for {T.name.toLowerCase()}.</SectionTitle>
      <p style={{ fontFamily: F.sans, fontSize: 17, lineHeight: 1.55, color: C.muted, maxWidth: 720, margin: '0 0 48px' }}>
        Same 9-system spine. Trade-specific tuning on top. Here's the high-level for {T.code} — and the full inventory underneath.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 56 }}>
        {T.playbook.map((p, i) => (
          <div key={p.t} style={{ padding: 32, border: `2px solid ${C.ink}`, background: C.bg, position: 'relative' }}>
            <div style={{ position: 'absolute', top: 0, left: 0, padding: '4px 12px', background: C.ink, color: C.hi, fontFamily: F.mono, fontSize: 10, fontWeight: 700, letterSpacing: 1.4 }}>STEP 0{i+1}</div>
            <div style={{ fontFamily: F.display, fontSize: 84, color: C.hi, letterSpacing: -2, lineHeight: 0.85, marginTop: 16, marginBottom: 20 }}>0{i+1}</div>
            <h3 style={{ fontFamily: F.display, fontSize: 26, letterSpacing: -0.4, textTransform: 'uppercase', margin: '0 0 12px', lineHeight: 1 }}>{p.t}</h3>
            <p style={{ fontFamily: F.sans, fontSize: 14, lineHeight: 1.55, color: C.muted, margin: 0 }}>{p.d}</p>
            <div style={{ marginTop: 20, paddingTop: 16, borderTop: `1px solid ${C.rule}`, fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, color: C.hiDark, fontWeight: 700 }}>
              {p.tag}
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 24, marginBottom: 24, paddingBottom: 16, borderBottom: `2px solid ${C.ink}`, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap', gap: 12 }}>
        <h3 style={{ fontFamily: F.display, fontSize: 28, letterSpacing: -0.4, textTransform: 'uppercase', margin: 0, color: C.ink }}>Full inventory</h3>
        <span style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, color: C.hiDark, fontWeight: 700 }}>{T.features.length} COMPONENTS · {T.code}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', border: `2px solid ${C.ink}`, background: C.bg }}>
        {T.features.map((f, i) => {
          const total = T.features.length;
          const isLastRow = i >= total - (total % 2 === 0 ? 2 : 1);
          const isRightCol = i % 2 === 1;
          return (
            <div key={f.t} style={{
              padding: '24px 28px',
              display: 'grid', gridTemplateColumns: '60px 1fr',
              alignItems: 'start', gap: 16,
              borderBottom: isLastRow ? 'none' : `1px solid ${C.rule}`,
              borderRight: isRightCol ? 'none' : `1px solid ${C.rule}`,
            }}>
              <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, fontWeight: 700, color: C.hiDark, paddingTop: 6 }}>{String(i+1).padStart(2,'0')}</div>
              <div>
                <div style={{ fontFamily: F.display, fontSize: 18, letterSpacing: -0.2, textTransform: 'uppercase', color: C.ink, marginBottom: 6 }}>{f.t}</div>
                <div style={{ fontFamily: F.sans, fontSize: 13, lineHeight: 1.5, color: C.muted }}>{f.d}</div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
    </>
  );
}

function FieldBand() {
  if (!T.img2) return null;
  return (
    <section style={{ position: 'relative', height: 480, overflow: 'hidden', borderTop: `2px solid ${C.ink}`, borderBottom: `2px solid ${C.ink}` }}>
      <img src={`/img/${T.img2}`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(90deg, rgba(22,22,26,0.82) 0%, rgba(22,22,26,0.45) 55%, rgba(22,22,26,0.1) 100%)' }} />
      <div style={{ position: 'absolute', inset: 0, padding: '48px 60px', display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 600 }}>
        <Stamp color={C.hi}>// FIELD: {T.code}</Stamp>
        <h2 style={{ fontFamily: F.display, fontSize: 'clamp(40px, 5vw, 72px)', lineHeight: 0.9, letterSpacing: '-0.025em', color: C.panel, margin: '20px 0 20px', textTransform: 'uppercase' }}>
          {T.name} operators.<br /><span style={{ color: C.hi }}>Full calendar.</span>
        </h2>
        <p style={{ fontFamily: F.sans, fontSize: 17, color: 'rgba(242,239,233,0.82)', lineHeight: 1.5, margin: '0 0 28px', maxWidth: 420 }}>
          The same system running in {T.metroAvail}+ metros. Get booked weeks in advance — full calendar, not a feast-or-famine month.
        </p>
        <div>
          <Btn primary href="/book-scoping-call">GET STARTED ▸</Btn>
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 20, right: 32, fontFamily: F.mono, fontSize: 10, color: 'rgba(242,239,233,0.5)', letterSpacing: 1.4 }}>// FIELD CAPTURE · {T.code}</div>
    </section>
  );
}

function FitFilter() {
  const [revenue, setRevenue] = React.useState(null);
  const [spend,   setSpend]   = React.useState(null);
  const [crew,    setCrew]    = React.useState(null);

  const Q = [
    {
      key: 'revenue',
      label: 'Annual revenue right now',
      value: revenue, set: setRevenue,
      options: [
        { v: 'starter',  l: '< $250K',     score: 0 },
        { v: 'growing',  l: '$250K–$1M',  score: 1 },
        { v: 'scaling',  l: '$1M–$5M',     score: 2 },
        { v: 'large',    l: '$5M+',        score: 2 },
      ],
    },
    {
      key: 'spend',
      label: 'Current monthly ad spend',
      value: spend, set: setSpend,
      options: [
        { v: 'none',  l: '$0 — none',     score: 0 },
        { v: 'low',   l: '< $2K / mo',    score: 0 },
        { v: 'mid',   l: '$2K–$5K / mo',  score: 1 },
        { v: 'high',  l: '$5K+ / mo',     score: 2 },
      ],
    },
    {
      key: 'crew',
      label: 'Crew size',
      value: crew, set: setCrew,
      options: [
        { v: 'solo',    l: 'Just me',           score: 0 },
        { v: 'small',   l: '1–3 people',        score: 0 },
        { v: 'mid',     l: '4–8 people',        score: 1 },
        { v: 'large',   l: '9+ people',         score: 2 },
      ],
    },
  ];

  const allAnswered = revenue && spend && crew;
  let recommended = null;
  if (allAnswered) {
    const scores = {
      revenue: Q[0].options.find(o => o.v === revenue).score,
      spend:   Q[1].options.find(o => o.v === spend).score,
      crew:    Q[2].options.find(o => o.v === crew).score,
    };
    const total = scores.revenue + scores.spend + scores.crew;
    recommended = total <= 1 ? { label: 'LAUNCH', fee: '$1,500/mo', sub: "You're early. Launch is built for solo + small operators getting the phone ringing for the first time." }
                : total <= 3 ? { label: 'GROW',   fee: '$2,500/mo', sub: 'Grow fits operators with reviews + an inconsistent pipeline. Most common path for trades on this list.' }
                              : { label: 'SCALE',  fee: '$3,500/mo', sub: 'Scale matches established operators ready to dominate the metro for their trade.' };
  }

  return (
    <section style={{ padding: '88px 40px', background: C.panel, borderTop: `2px solid ${C.ink}`, borderBottom: `2px solid ${C.ink}` }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        <SectionTitle eyebrow="Is this for me?">3 questions, 30 seconds.</SectionTitle>
        <Stamp color={C.hiDark}>// FIT.CHECK · {T.code}</Stamp>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 16 }}>
        {Q.map(q => (
          <div key={q.key} style={{ padding: 24, border: `2px solid ${C.ink}`, background: C.bg }}>
            <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, fontWeight: 700, color: C.hiDark, marginBottom: 14 }}>{q.label.toUpperCase()}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {q.options.map(o => (
                <button key={o.v} onClick={() => q.set(o.v)} style={{
                  textAlign: 'left',
                  padding: '14px 16px',
                  minHeight: 44,
                  fontFamily: F.mono, fontSize: 13, letterSpacing: 0.4, fontWeight: 600,
                  background: q.value === o.v ? C.hi : 'transparent',
                  color: q.value === o.v ? C.ink : C.ink,
                  border: `1.5px solid ${q.value === o.v ? C.ink : C.rule}`,
                  cursor: 'pointer',
                }}>
                  {q.value === o.v ? '● ' : '○ '}{o.l}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{
        marginTop: 24, padding: '20px 24px',
        background: allAnswered ? C.ink : C.bg,
        color: allAnswered ? C.panel : C.muted,
        border: `2px solid ${C.ink}`,
        display: 'grid', gridTemplateColumns: allAnswered ? 'auto 1fr auto' : '1fr', gap: 20, alignItems: 'center',
      }}>
        {!allAnswered && (
          <div style={{ fontFamily: F.mono, fontSize: 12, letterSpacing: 1.2, fontWeight: 700 }}>
            ANSWER ALL 3 → SEE WHICH PLAN FITS YOU
          </div>
        )}
        {allAnswered && (
          <>
            <div>
              <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: C.faint, fontWeight: 700, marginBottom: 6 }}>RECOMMENDED PLAN</div>
              <div style={{ fontFamily: F.display, fontSize: 36, color: C.hi, letterSpacing: -0.8, lineHeight: 1 }}>{recommended.label}</div>
              <div style={{ fontFamily: F.mono, fontSize: 11, color: C.faint, letterSpacing: 1.2, marginTop: 4 }}>{recommended.fee}</div>
            </div>
            <div style={{ fontFamily: F.sans, fontSize: 14, lineHeight: 1.5, color: 'rgba(242,239,233,0.85)' }}>
              {recommended.sub}
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <Btn primary href="/book-scoping-call">GET STARTED ▸</Btn>
              <Btn dark href="#simulator">CALCULATE PROFIT ▸</Btn>
            </div>
          </>
        )}
      </div>
    </section>
  );
}

const SIM_FORMSPREE_ID = 'YOUR_SIM_FORM_ID'; // swap in from formspree.io

const SIM_PLANS = [
  { id: 'LAUNCH', label: 'Launch', fee: 1500, desc: 'Core stack · 1 channel (Google or Meta)' },
  { id: 'GROW',   label: 'Grow',   fee: 2500, desc: 'Full stack · Google + Meta · AI receptionist · social media' },
  { id: 'SCALE',  label: 'Scale',  fee: 3500, desc: 'Full stack + growth ops · video content · all channels' },
];
const PLAN_MIN_SPEND = [1500, 3000, 3000];
const PLAN_ADJUSTMENTS = [
  { answerAdd: 0,  closeAdd: 0,  cplMult: 1.00, tags: [] },
  { answerAdd: 15, closeAdd: 5,  cplMult: 1.00, tags: ['AI receptionist → +15% answer rate', 'Social media → +5% close rate'] },
  { answerAdd: 15, closeAdd: 5,  cplMult: 0.80, tags: ['AI receptionist + social → higher rates', 'Video content → −20% CPL'] },
];

function TradeSimulator() {
  const sim = T.sim;
  const defaultPlan = sim.deal < 7000 ? 0 : sim.deal < 18000 ? 1 : 2;

  const mkInputs = (planI, prev) => {
    const adj = PLAN_ADJUSTMENTS[planI];
    const base = prev || { adSpend: sim.adSpend, cpl: sim.cpl, answerRate: sim.answerRate, book: 45, close: sim.closeRate, deal: sim.deal, margin: sim.margin, commRate: sim.commRate || 0 };
    return { ...base, adSpend: Math.max(base.adSpend, PLAN_MIN_SPEND[planI]), cpl: Math.round(sim.cpl * adj.cplMult), answerRate: Math.min(95, sim.answerRate + adj.answerAdd), close: Math.min(80, sim.closeRate + adj.closeAdd) };
  };

  const [planIdx,   setPlanIdx]   = React.useState(defaultPlan);
  const [inputs,    setInputs]    = React.useState(() => mkInputs(defaultPlan, null));
  const [stress,    setStress]    = React.useState(false);
  const [commBasis, setCommBasis] = React.useState('revenue');
  const [leadEmail, setLeadEmail] = React.useState('');
  const [leadPhone, setLeadPhone] = React.useState('');
  const [leadSent,  setLeadSent]  = React.useState(false);
  const [leadErr,   setLeadErr]   = React.useState(false);

  const plan      = SIM_PLANS[planIdx];
  const planFee   = plan.fee;
  const planAdj   = PLAN_ADJUSTMENTS[planIdx];
  const adWarn    = inputs.adSpend < PLAN_MIN_SPEND[planIdx];
  const sf        = stress ? 0.7 : 1;

  const leads       = Math.floor(inputs.adSpend / inputs.cpl);
  const answered    = Math.floor(leads * (inputs.answerRate / 100) * sf);
  const booked      = Math.floor(answered * (inputs.book / 100));
  const closed      = Math.floor(booked * (inputs.close / 100) * sf);
  const sales       = closed * inputs.deal;
  const grossProfit = sales * (inputs.margin / 100);
  const commission  = commBasis === 'profit'
    ? grossProfit * (inputs.commRate / 100)
    : sales * (inputs.commRate / 100);
  const netProfit   = grossProfit - inputs.adSpend - planFee - commission;
  const totalIn     = inputs.adSpend + planFee;
  const roi         = totalIn > 0 ? ((netProfit / totalIn) * 100).toFixed(0) : '0';

  const setField  = (k, v) => setInputs(p => ({ ...p, [k]: v }));
  const handlePlan = (i) => { setPlanIdx(i); setInputs(p => mkInputs(i, p)); };

  const handleLeadSubmit = async (e) => {
    e.preventDefault(); setLeadErr(false);
    try {
      const res = await fetch(`https://formspree.io/f/${SIM_FORMSPREE_ID}`, {
        method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          email: leadEmail, phone: leadPhone || 'not provided', trade: T.name, plan: plan.label,
          adSpend: `$${inputs.adSpend.toLocaleString()}/mo`, cpl: `$${inputs.cpl}`,
          answerRate: `${inputs.answerRate}%`, bookingRate: `${inputs.book}%`, closeRate: `${inputs.close}%`,
          dealValue: `$${inputs.deal.toLocaleString()}`, margin: `${inputs.margin}%`,
          commRate: `${inputs.commRate}% on ${commBasis}`,
          commission: `$${Math.round(commission).toLocaleString()}`,
          stress: stress ? 'ON (×0.7)' : 'OFF', leads, answered, booked, closed,
          revenue: `$${sales.toLocaleString()}`,
          netProfit: `${netProfit >= 0 ? '+' : ''}$${Math.abs(Math.round(netProfit)).toLocaleString()}/mo`, roi: `${roi}%`,
        }),
      });
      if (!res.ok) throw new Error();
      setLeadSent(true);
    } catch { setLeadErr(true); }
  };

  const Slider = ({ label, value, onChange, min, max, step, prefix = '', suffix = '', stressed }) => (
    <div style={{ marginBottom: 16, ...(stressed ? { borderLeft: '3px solid rgba(250,98,21,0.7)', paddingLeft: 10, background: 'rgba(250,98,21,0.05)', marginLeft: -13 } : {}) }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
        <span style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, color: stressed ? C.hi : C.muted, textTransform: 'uppercase', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
          {label}
          {stressed && <span style={{ background: C.hi, color: C.ink, fontSize: 8, letterSpacing: 1, fontWeight: 700, padding: '2px 5px', lineHeight: 1.4 }}>⚡ ×0.7</span>}
        </span>
        <span style={{ color: C.ink, fontFamily: F.display, fontSize: 18, letterSpacing: -0.3 }}>{prefix}{value.toLocaleString()}{suffix}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(+e.target.value)} className="sim-slider" aria-label={label} />
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 3, fontFamily: F.mono, fontSize: 9, letterSpacing: 0.8, color: C.faint }}>
        <span>{prefix}{min.toLocaleString()}{suffix}</span><span>{prefix}{max.toLocaleString()}{suffix}</span>
      </div>
    </div>
  );

  const funnelStages = [
    { label: 'LEADS', val: leads }, { label: 'ANSWERED', val: answered },
    { label: 'BOOKED', val: booked }, { label: 'CLOSED', val: closed, accent: true },
  ];
  const fTop = funnelStages[0].val || 1;
  const fPct = v => Math.max(30, Math.round((v / fTop) * 100));
  const fConv = (val, max) => max > 0 ? Math.round((val / max) * 100) : 0;

  return (
    <section id="simulator" style={{ padding: '100px 40px', background: C.panel, borderBottom: `2px solid ${C.ink}` }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40, flexWrap: 'wrap', gap: 24 }}>
        <SectionTitle eyebrow={`${T.name} revenue model`}>Run your numbers.<br />See the return.</SectionTitle>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, color: C.muted, marginBottom: 4 }}>DEFAULTS: {T.name.toUpperCase()} MARKET AVERAGES</div>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, color: C.hiDark, fontWeight: 700 }}>${sim.cpl} CPL · ${sim.deal.toLocaleString()} DEAL · {sim.closeRate}% CLOSE</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', border: `2px solid ${C.ink}` }}>
        {/* Inputs */}
        <div style={{ padding: 32, background: C.bg, borderRight: `2px solid ${C.ink}` }}>
          <div style={{ marginBottom: 20 }}>
            <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: C.muted, fontWeight: 700, marginBottom: 8, textTransform: 'uppercase' }}>// Plan</div>
            <div style={{ display: 'flex', border: `1px solid ${C.ink}` }}>
              {SIM_PLANS.map((p, i) => (
                <button key={p.id} onClick={() => handlePlan(i)} style={{
                  flex: 1, padding: '8px 6px', textAlign: 'center',
                  background: i === planIdx ? C.ink : 'transparent', color: i === planIdx ? C.hi : C.ink,
                  border: 'none', borderRight: i < SIM_PLANS.length - 1 ? `1px solid ${C.ink}` : 'none',
                  cursor: 'pointer', fontFamily: F.mono, fontSize: 9, letterSpacing: 1.2, fontWeight: 700,
                }}>
                  <div>{p.label.toUpperCase()}</div>
                  <div style={{ fontSize: 11, marginTop: 1, fontFamily: F.display, letterSpacing: -0.2 }}>${p.fee.toLocaleString()}/mo</div>
                </button>
              ))}
            </div>
            <div style={{ fontFamily: F.mono, fontSize: 9, color: C.muted, marginTop: 6, letterSpacing: 0.8, lineHeight: 1.5 }}>{plan.desc}</div>
          </div>
          <div style={{ marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Stamp color={C.ink}>INPUT PARAMETERS</Stamp>
            <button onClick={() => setStress(s => !s)} style={{
              background: stress ? C.ink : 'transparent', color: stress ? C.hi : C.muted,
              border: `1px solid ${stress ? C.hi : C.rule}`,
              fontFamily: F.mono, fontSize: 9, letterSpacing: 1.2, fontWeight: 700, padding: '5px 10px', cursor: 'pointer',
            }}>STRESS {stress ? 'ON ×0.7' : 'OFF'}</button>
          </div>
          <Slider label="Monthly ad spend" value={inputs.adSpend} onChange={v => setField('adSpend', v)} min={PLAN_MIN_SPEND[planIdx]} max={20000} step={250} prefix="$" />
          {adWarn && (
            <div style={{ marginTop: -10, marginBottom: 14, padding: '6px 10px', background: '#FFF3CD', border: '1px solid #FFC107', fontFamily: F.mono, fontSize: 9, letterSpacing: 1.1, color: '#7A5600', display: 'flex', gap: 6, alignItems: 'center' }}>
              ⚠ {planIdx === 0 ? 'Min $1,500/platform recommended' : `${plan.label} requires $1,500 × 2 platforms = $${PLAN_MIN_SPEND[planIdx].toLocaleString()} min`}
            </div>
          )}
          <Slider label="Cost per lead"  value={inputs.cpl}       onChange={v => setField('cpl', v)}       min={5}   max={150}    step={1}   prefix="$" />
          <Slider label="Answer rate"    value={inputs.answerRate} onChange={v => setField('answerRate', v)} min={20}  max={95}     step={1}   suffix="%" stressed={stress} />
          <Slider label="Booking rate"   value={inputs.book}       onChange={v => setField('book', v)}       min={5}   max={80}     step={1}   suffix="%" />
          <Slider label="Close rate"     value={inputs.close}      onChange={v => setField('close', v)}      min={5}   max={80}     step={1}   suffix="%" stressed={stress} />
          <Slider label="Avg deal value" value={inputs.deal}       onChange={v => setField('deal', v)}       min={500} max={120000} step={500} prefix="$" />
          <Slider label="Profit margin"  value={inputs.margin}     onChange={v => setField('margin', v)}     min={10}  max={70}     step={1}   suffix="%" />
          <Slider label="Commission rate" value={inputs.commRate}   onChange={v => setField('commRate', v)}   min={0}   max={20}     step={1}   suffix="%" />
          <div style={{ marginTop: -8, marginBottom: 16, display: 'flex', border: `1px solid ${C.rule}` }}>
            {[['revenue', 'On Revenue'], ['profit', 'On Profit']].map(([val, lbl]) => (
              <button key={val} onClick={() => setCommBasis(val)} style={{
                flex: 1, padding: '7px 8px',
                background: commBasis === val ? C.ink : 'transparent',
                color: commBasis === val ? C.hi : C.muted,
                border: 'none', borderRight: val === 'revenue' ? `1px solid ${C.rule}` : 'none',
                cursor: 'pointer', fontFamily: F.mono, fontSize: 9, letterSpacing: 1.2, fontWeight: 700, textTransform: 'uppercase',
              }}>{lbl}</button>
            ))}
          </div>
          <div style={{ marginTop: 8, padding: '10px 12px', border: `1px dashed ${C.rule}`, fontFamily: F.mono, fontSize: 9, color: C.muted, lineHeight: 1.6, letterSpacing: 0.8 }}>
            <div style={{ color: C.ink, fontWeight: 700, marginBottom: 3 }}>// MODEL ASSUMPTIONS</div>
            Plan fee (${planFee.toLocaleString()}/mo) deducted as fixed cost. Plan selection updates CPL, answer rate, and close rate. Commission applied to {commBasis === 'profit' ? 'gross profit' : 'revenue'}. Stress applies ×0.7 to answer + close rates.
          </div>
        </div>

        {/* Output */}
        <div style={{ padding: 32, background: C.ink, color: C.panel, position: 'relative' }}>
          <div style={{ marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
            <Stamp color={C.hi}>● {T.name.toUpperCase()} OUTPUT</Stamp>
            <Stamp color={C.hi}>{plan.label.toUpperCase()} PLAN · ${planFee.toLocaleString()}/MO</Stamp>
          </div>

          {/* Big 3 numbers */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.7fr 1fr', gap: 16, marginBottom: 16 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: 'rgba(242,239,233,0.45)', marginBottom: 4, fontWeight: 700 }}>NET PROFIT / MO</div>
              <div style={{ fontFamily: F.display, fontSize: 'clamp(20px, 3vw, 44px)', color: netProfit >= 0 ? C.hi : '#ff4d4d', letterSpacing: '-0.035em', lineHeight: 0.9, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {netProfit >= 0 ? '' : '−'}${Math.abs(Math.round(netProfit)).toLocaleString()}
              </div>
              <div style={{ fontFamily: F.mono, fontSize: 9, color: 'rgba(242,239,233,0.45)', marginTop: 5, letterSpacing: 0.8 }}>
                ${Math.abs(Math.round(netProfit / 30.4)).toLocaleString()} / day
              </div>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: 'rgba(242,239,233,0.45)', marginBottom: 4, fontWeight: 700 }}>ROI</div>
              <div style={{ fontFamily: F.display, fontSize: 'clamp(20px, 3vw, 44px)', color: C.panel, letterSpacing: '-0.035em', lineHeight: 0.9, whiteSpace: 'nowrap' }}>{roi}%</div>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: 'rgba(242,239,233,0.45)', marginBottom: 4, fontWeight: 700 }}>TOTAL SALES</div>
              <div style={{ fontFamily: F.display, fontSize: 'clamp(20px, 3vw, 44px)', color: C.panel, letterSpacing: '-0.035em', lineHeight: 0.9, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>${sales.toLocaleString()}</div>
            </div>
          </div>

          {/* Verdict */}
          <div style={{ padding: '10px 14px', background: netProfit > 0 ? C.hi : '#3a1a1a', color: netProfit > 0 ? C.ink : '#ff7a6a', fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, fontWeight: 700, display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 12 }}>
            <span>● {netProfit > 0 ? 'MODEL VIABLE' : 'MODEL UNDER WATER'}</span>
            <span>{netProfit > 0 ? 'POSITIVE UNIT ECONOMICS' : 'TIGHTEN INPUTS'}</span>
          </div>

          {/* Plan tags */}
          {planAdj.tags.length > 0 && (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
              {planAdj.tags.map((tag, i) => (
                <span key={i} style={{ fontFamily: F.mono, fontSize: 8, letterSpacing: 1.1, color: C.hi, background: 'rgba(250,98,21,0.12)', padding: '3px 7px', border: '1px solid rgba(250,98,21,0.3)', whiteSpace: 'nowrap' }}>▲ {tag}</span>
              ))}
            </div>
          )}

          {/* Funnel */}
          <div style={{ border: '1px solid rgba(255,255,255,0.12)', marginBottom: 12 }}>
            <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(242,239,233,0.35)', padding: '7px 14px', borderBottom: '1px solid rgba(255,255,255,0.08)', fontWeight: 700 }}>// CONVERSION FUNNEL</div>
            <div style={{ padding: '14px 14px 12px' }}>
              {funnelStages.map((s, i) => {
                const c = i > 0 ? fConv(s.val, funnelStages[i - 1].val) : null;
                return (
                  <div key={s.label}>
                    {i > 0 && (
                      <div style={{ textAlign: 'center', fontFamily: F.mono, fontSize: 8, letterSpacing: 1.2, color: c >= 50 ? C.hi : c >= 25 ? 'rgba(250,98,21,0.75)' : '#ff6b6b', padding: '4px 0', fontWeight: 700 }}>↓ {c}% CONVERSION</div>
                    )}
                    <div style={{ width: `${fPct(s.val)}%`, margin: '0 auto', background: s.accent ? C.hi : 'rgba(255,255,255,0.09)', padding: '8px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, transition: 'width 220ms' }}>
                      <span style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.3, color: s.accent ? C.ink : 'rgba(242,239,233,0.55)', fontWeight: 700, whiteSpace: 'nowrap' }}>{s.label}</span>
                      <span style={{ fontFamily: F.display, fontSize: 18, letterSpacing: -0.3, lineHeight: 1, color: s.accent ? C.ink : C.panel, whiteSpace: 'nowrap' }}>{s.val.toLocaleString()}</span>
                    </div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderTop: '1px solid rgba(255,255,255,0.12)' }}>
              {[['SALES', `$${sales.toLocaleString()}`, C.hi], ['COMMISS.', `$${Math.round(commission).toLocaleString()}`, C.panel], ['NET', `${netProfit >= 0 ? '+' : '−'}$${Math.abs(Math.round(netProfit)).toLocaleString()}`, netProfit >= 0 ? C.hi : '#ff4d4d']].map(([l, v, color], i) => (
                <div key={l} style={{ padding: '10px 12px', borderRight: i < 2 ? '1px solid rgba(255,255,255,0.12)' : 'none' }}>
                  <div style={{ fontFamily: F.mono, fontSize: 8, letterSpacing: 1.2, color: 'rgba(242,239,233,0.4)', fontWeight: 700, marginBottom: 3 }}>{l}</div>
                  <div style={{ fontFamily: F.display, fontSize: 17, letterSpacing: -0.3, color: color, lineHeight: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Cost breakdown */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', border: '1px solid rgba(255,255,255,0.1)', marginBottom: 12 }}>
            {[['AD SPEND', `$${inputs.adSpend.toLocaleString()}`], ['PLAN FEE', `$${planFee.toLocaleString()}`], ['GROSS PROFIT', `$${Math.round(grossProfit).toLocaleString()}`]].map(([l, v], i) => (
              <div key={l} style={{ padding: '12px 14px', borderRight: i < 2 ? '1px solid rgba(255,255,255,0.1)' : 'none' }}>
                <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(242,239,233,0.4)', marginBottom: 4 }}>{l}</div>
                <div style={{ fontFamily: F.display, fontSize: 18, color: C.panel, letterSpacing: -0.3 }}>{v}</div>
              </div>
            ))}
          </div>

          {/* Unit economics */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', border: '1px solid rgba(255,255,255,0.1)', marginBottom: 12 }}>
            {[
              ['REV/LEAD',   `$${leads > 0 ? Math.round(sales / leads).toLocaleString() : '0'}`],
              ['COST/CLOSE', `$${closed > 0 ? Math.round(totalIn / closed).toLocaleString() : '—'}`],
              ['ROAS',       `${inputs.adSpend > 0 ? (sales / inputs.adSpend).toFixed(1) : '—'}×`],
              ['BREAK-EVEN', `${inputs.deal > 0 ? Math.ceil(totalIn / (inputs.deal * inputs.margin / 100)) : '—'} DEALS`],
            ].map(([l, v], i) => (
              <div key={l} style={{ padding: '10px 10px', borderRight: i < 3 ? '1px solid rgba(255,255,255,0.1)' : 'none' }}>
                <div style={{ fontFamily: F.mono, fontSize: 8, letterSpacing: 1.2, color: 'rgba(242,239,233,0.35)', marginBottom: 4, fontWeight: 700 }}>{l}</div>
                <div style={{ fontFamily: F.display, fontSize: 15, color: C.hi, letterSpacing: -0.2, lineHeight: 1.1, wordBreak: 'break-all' }}>{v}</div>
              </div>
            ))}
          </div>

          {/* 12-month projection */}
          <div style={{ border: '1px solid rgba(255,255,255,0.12)', marginBottom: 12 }}>
            <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(242,239,233,0.35)', padding: '7px 14px', borderBottom: '1px solid rgba(255,255,255,0.08)', fontWeight: 700 }}>// 12-MONTH PROJECTION</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)' }}>
              {[['ANN. REVENUE', `$${(sales * 12).toLocaleString()}`], ['ANN. PROFIT', `${netProfit >= 0 ? '+' : '−'}$${Math.abs(Math.round(netProfit * 12)).toLocaleString()}`], ['TOTAL SPEND', `$${(totalIn * 12).toLocaleString()}`]].map(([l, v], i) => (
                <div key={l} style={{ padding: '12px 14px', borderRight: i < 2 ? '1px solid rgba(255,255,255,0.1)' : 'none' }}>
                  <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: 1.4, color: 'rgba(242,239,233,0.4)', marginBottom: 4 }}>{l}</div>
                  <div style={{ fontFamily: F.display, fontSize: 18, color: C.panel, letterSpacing: -0.3 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* CTAs */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 10 }}>
            <a href="/book-scoping-call" style={{ display: 'block', padding: '12px 14px', background: C.hi, color: C.ink, fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, fontWeight: 700, textAlign: 'center', textDecoration: 'none', textTransform: 'uppercase' }}>GET STARTED ▸</a>
            <a href="/book-scoping-call" style={{ display: 'block', padding: '12px 14px', background: 'transparent', color: C.panel, border: '1px solid rgba(255,255,255,0.25)', fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, fontWeight: 700, textAlign: 'center', textDecoration: 'none', textTransform: 'uppercase' }}>BOOK A CALL ▸</a>
          </div>

          {leadSent ? (
            <div style={{ padding: '10px 14px', background: 'rgba(250,98,21,0.15)', border: '1px solid rgba(250,98,21,0.35)', fontFamily: F.mono, fontSize: 10, color: C.hi, letterSpacing: 1.2 }}>
              ✓ MODEL SENT · Team follows up within 24h
            </div>
          ) : (
            <form onSubmit={handleLeadSubmit} style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'stretch' }}>
              <div style={{ fontFamily: F.mono, fontSize: 9, color: C.hi, letterSpacing: 1.4, fontWeight: 700, alignSelf: 'center', flexShrink: 0 }}>// EMAIL MY MODEL</div>
              <input type="email" value={leadEmail} onChange={e => setLeadEmail(e.target.value)} placeholder="your@email.com" required
                style={{ flex: '1 1 150px', padding: '8px 10px', fontFamily: F.mono, fontSize: 10, background: 'rgba(255,255,255,0.09)', border: `1px solid ${leadErr ? '#ff4d4d' : 'rgba(255,255,255,0.2)'}`, color: C.panel, outline: 'none', minWidth: 0 }} />
              <input type="tel" value={leadPhone} onChange={e => setLeadPhone(e.target.value)} placeholder="Phone (optional)"
                style={{ flex: '1 1 130px', padding: '8px 10px', fontFamily: F.mono, fontSize: 10, background: 'rgba(255,255,255,0.09)', border: '1px solid rgba(255,255,255,0.2)', color: C.panel, outline: 'none', minWidth: 0 }} />
              <button type="submit" style={{ padding: '8px 12px', background: C.hi, color: C.ink, fontFamily: F.mono, fontSize: 9, fontWeight: 700, border: 'none', cursor: 'pointer', letterSpacing: 1.2, whiteSpace: 'nowrap' }}>SEND ▸</button>
            </form>
          )}
        </div>
      </div>

      <div style={{ marginTop: 12, fontFamily: F.mono, fontSize: 10, color: C.faint, letterSpacing: 0.8 }}>
        Defaults pre-set for {T.name.toLowerCase()} market averages. {plan.label} plan fee (${plan.fee.toLocaleString()}/mo) deducted from profit. Stress applies ×0.7 to answer + close rates.
      </div>
    </section>
  );
}

function Receipts() {
  return (
    <section id="proof" style={{ padding: '100px 40px' }}>
      <SectionTitle eyebrow="Field receipts">{T.name} clients · operators in the field.</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {T.receipts.map((r) => (
          <div key={r.code} style={{ padding: 36, border: `2px solid ${C.ink}`, background: C.bg }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
              <Stamp color={C.hiDark}>{r.code}</Stamp>
              <Stamp color={C.ink}>{r.metro}</Stamp>
            </div>
            <p style={{ fontFamily: F.display, fontSize: 28, lineHeight: 1.1, letterSpacing: -0.5, textTransform: 'uppercase', margin: '0 0 28px' }}>"{r.q}"</p>
            <div style={{ paddingTop: 20, borderTop: `1px solid ${C.rule}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontFamily: F.mono, fontSize: 11, color: C.muted, letterSpacing: 0.6, fontWeight: 600 }}>{r.who}</div>
              <div style={{ fontFamily: F.display, fontSize: 32, color: C.hi, letterSpacing: -0.6 }}>{r.metric}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function AIReceptionistDemo() {
  // Only relevant for trades where 24/7 answer is core to the offer.
  const VOICE_TRADES = ['HVAC', 'RF', 'EPX'];
  if (!VOICE_TRADES.includes(T.code)) return null;
  return (
    <section style={{ padding: '88px 40px', background: C.ink, color: C.panel, borderTop: `2px solid ${C.ink}`, borderBottom: `2px solid ${C.ink}` }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr)', gap: 40, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{
          width: 168, height: 168, flexShrink: 0,
          border: `2px solid ${C.hi}`, background: 'rgba(250,98,21,0.08)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
        }}>
          <span style={{
            width: 0, height: 0,
            borderLeft: `40px solid ${C.hi}`,
            borderTop: '28px solid transparent', borderBottom: '28px solid transparent',
            marginLeft: 8,
          }} />
          <span style={{ position: 'absolute', top: 12, left: 12, fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: C.hi, fontWeight: 700 }}>// AUDIO</span>
          <span style={{ position: 'absolute', bottom: 12, right: 12, fontFamily: F.mono, fontSize: 9, letterSpacing: 1.6, color: C.faint, fontWeight: 700 }}>~30s</span>
        </div>
        <div>
          <Stamp color={C.hi}>// AI RECEPTIONIST · KACHING CRM</Stamp>
          <h3 style={{ fontFamily: F.display, fontSize: 'clamp(28px, 3.5vw, 44px)', lineHeight: 1.05, letterSpacing: -0.6, color: C.panel, margin: '16px 0 14px', textTransform: 'uppercase' }}>
            Hear how it answers a 2am call.
          </h3>
          <p style={{ fontFamily: F.sans, fontSize: 16, lineHeight: 1.55, color: 'rgba(242,239,233,0.78)', margin: '0 0 24px', maxWidth: 620 }}>
            Your AI receptionist runs on Kaching CRM — emergency intake, scheduling, dispatch handoff. Qualifies intent, logs the transcript, drops the appointment on your calendar. We play a real recorded call on the scoping call before you sign anything.
          </p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Btn primary href="/book-scoping-call">Hear the demo →</Btn>
            <Btn dark href="#features">See where it fits</Btn>
          </div>
        </div>
      </div>
    </section>
  );
}

function MidCTA() {
  return (
    <section style={{ background: C.hi, padding: '60px 40px', borderTop: `2px solid ${C.ink}`, borderBottom: `2px solid ${C.ink}` }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.6, fontWeight: 700, color: C.ink, marginBottom: 12 }}>// {T.code} · TERRITORY</div>
          <h3 style={{ fontFamily: F.display, fontSize: 56, lineHeight: 0.92, letterSpacing: -1.4, textTransform: 'uppercase', color: C.ink, margin: 0, maxWidth: 800 }}>
            One {T.singular.toLowerCase()} per metro.<br />Once it's locked, it's gone.
          </h3>
        </div>
        <Btn dark href="/book-scoping-call">GET STARTED ▸</Btn>
      </div>
    </section>
  );
}

const UNIVERSAL_FAQS = [
  {
    q: 'I already have a website. Do I have to throw it out?',
    a: "No. We rebuild the conversion-critical pages (hero, gallery, pricing, contact) on our spine and keep your domain. Useful parts of your existing site (blog, portfolio, gallery) get migrated. Your historical SEO compounds. You own the new code from day one.",
  },
  {
    q: 'What about my existing crew and sales process?',
    a: "We don't replace them — we feed them. Kaching CRM's AI receptionist and follow-up sequences hand qualified appointments to your existing closer or technician. If you don't have a closer yet, we help you script a 15-minute consult flow.",
  },
  {
    q: 'Do I lose my Google reviews or reputation?',
    a: "Never. We work with your existing Google Business Profile and feed it more reviews — most operators run 5× their baseline review velocity within 90 days. Your historical reputation is the foundation we build on.",
  },
  {
    q: 'What about my brand and logo? Do I have to rebrand?',
    a: "No. Bring your logo, colors, voice, and brand standards — we engineer them into the system. We're sales infrastructure, not a creative agency. If you want a brand refresh, that's a separate conversation we can refer out.",
  },
  {
    q: 'What if my metro is too small to support the spend?',
    a: "That comes up on the scoping call. If your TAM doesn't support a $1.5K+/mo ad spend, we tell you on minute 4 of the call. We don't sell into markets where the math doesn't work — better to lose the deal than lose your investment.",
  },
];

function FAQ() {
  const [open, setOpen] = React.useState(0);
  const tradeFaqs = T.faqs || [];
  const allFaqs = [
    ...tradeFaqs.map(f => ({ ...f, group: 'trade' })),
    ...UNIVERSAL_FAQS.map(f => ({ ...f, group: 'owner' })),
  ];
  return (
    <section id="faq" style={{ padding: '100px 40px', background: C.panel }}>
      <SectionTitle eyebrow="Common objections">Answers before you ask.</SectionTitle>
      <div style={{ border: `2px solid ${C.ink}`, background: C.bg }}>
        {allFaqs.map((f, i) => {
          const prev = allFaqs[i - 1];
          const groupChanged = !prev || prev.group !== f.group;
          return (
            <React.Fragment key={i}>
              {groupChanged && (
                <div style={{
                  padding: '14px 28px',
                  background: f.group === 'owner' ? C.ink : C.panel,
                  color: f.group === 'owner' ? C.hi : C.hiDark,
                  fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, fontWeight: 700,
                  borderBottom: `1px solid ${C.rule}`,
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                }}>
                  <span>{f.group === 'trade' ? `// ${T.code} · TRADE-SPECIFIC` : '// OWNER OBJECTIONS'}</span>
                  <span style={{ opacity: 0.5 }}>{f.group === 'trade' ? `${tradeFaqs.length} Q` : `${UNIVERSAL_FAQS.length} Q`}</span>
                </div>
              )}
              <div style={{ borderBottom: i < allFaqs.length - 1 ? `1px solid ${C.rule}` : 'none' }}>
                <button onClick={() => setOpen(open === i ? -1 : i)} style={{
                  width: '100%', padding: '24px 28px', textAlign: 'left',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  background: 'none', border: 'none', cursor: 'pointer',
                  fontFamily: F.display, fontSize: 22, letterSpacing: -0.3, textTransform: 'uppercase', color: C.ink,
                }}>
                  <span>{f.q}</span>
                  <span style={{ fontFamily: F.mono, fontSize: 22, color: C.hi, fontWeight: 700, marginLeft: 16 }}>{open === i ? '−' : '+'}</span>
                </button>
                {open === i && (
                  <div style={{ padding: '0 28px 28px', fontFamily: F.sans, fontSize: 15, lineHeight: 1.6, color: C.muted, maxWidth: 800 }}>
                    {f.a}
                  </div>
                )}
              </div>
            </React.Fragment>
          );
        })}
      </div>
    </section>
  );
}

function RelatedBlog() {
  if (!T.relatedBlog || !T.relatedBlog.length) return null;
  return (
    <section style={{ padding: '60px 40px', background: C.panel, borderTop: `1px solid ${C.rule}` }}>
      <div style={{ maxWidth: 960, margin: '0 auto' }}>
        <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, color: C.hi, fontWeight: 700, marginBottom: 20 }}>// FROM THE BLOG</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {T.relatedBlog.map(post => (
            <a key={post.url} href={post.url} style={{ textDecoration: 'none', display: 'block', background: C.bg, border: `1px solid ${C.rule}`, padding: '24px 20px', transition: 'border-color 0.15s' }}>
              <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, color: C.muted, fontWeight: 700, marginBottom: 10, textTransform: 'uppercase' }}>{post.label}</div>
              <div style={{ fontFamily: F.display, fontSize: 18, color: C.ink, textTransform: 'uppercase', lineHeight: 1.1, letterSpacing: '-0.01em', marginBottom: 10 }}>{post.title}</div>
              <div style={{ fontFamily: F.sans, fontSize: 13, color: C.hi, fontWeight: 600 }}>Read →</div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function AfterSign() {
  const steps = [
    { d: 'DAY 0',    t: 'Contract',      body: `Signed in 20 min. Stripe + DocuSign. Your ${T.name.toLowerCase()} territory is locked.` },
    { d: 'DAY 1–7',  t: 'Build',         body: 'Kaching CRM, ad creatives, AI receptionist, landing pages — tuned for ' + T.code + '. Ads go live by day 3.' },
    { d: 'DAY 8',    t: 'Leads flowing', body: 'Real bookings appear in your inbox + calendar. We monitor every lead for the first 30 days.' },
    { d: 'WEEK 4',   t: 'Review + tune', body: 'Reinforcement call. Audience expansion. CPL reduction. Close-rate playbooks.' },
  ];
  return (
    <section style={{ padding: '88px 40px', background: C.bg, borderTop: `2px solid ${C.ink}` }}>
      <SectionTitle eyebrow="After you sign">No black box.<br />Here's what happens next.</SectionTitle>
      <p style={{ fontFamily: F.sans, fontSize: 16, lineHeight: 1.5, color: C.muted, margin: '0 0 40px', maxWidth: 680 }}>
        Same flow for every {T.name.toLowerCase()} operator. Predictable from contract to first booked install.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        {steps.map((s, i) => (
          <div key={s.d} style={{
            position: 'relative', padding: 24,
            background: C.panel, border: `2px solid ${C.ink}`,
          }}>
            <div style={{
              position: 'absolute', top: -12, left: 16, padding: '4px 10px',
              background: C.hi, color: C.ink,
              fontFamily: F.mono, fontSize: 10, letterSpacing: 1.4, fontWeight: 700,
            }}>{s.d}</div>
            <div style={{
              fontFamily: F.display, fontSize: 56, color: C.hi,
              letterSpacing: -1.2, lineHeight: 0.85, marginTop: 12, marginBottom: 14,
            }}>0{i + 1}</div>
            <h3 style={{
              fontFamily: F.display, fontSize: 20, letterSpacing: -0.3,
              textTransform: 'uppercase', margin: '0 0 8px', lineHeight: 1, color: C.ink,
            }}>{s.t}</h3>
            <p style={{ fontFamily: F.sans, fontSize: 13, lineHeight: 1.5, color: C.muted, margin: 0 }}>{s.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function FinalCTA() {
  return (
    <section style={{ background: C.ink, color: C.panel, padding: '120px 40px', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 6, background: `repeating-linear-gradient(45deg, ${C.hi} 0, ${C.hi} 12px, ${C.ink} 12px, ${C.ink} 24px)` }} />
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(280px, 1fr)', gap: 64 }}>
        <div>
          <Eyebrow color={C.hi}>{T.code} · LOCK IN</Eyebrow>
          <h2 style={{ fontFamily: F.display, fontSize: 'clamp(56px, 6.5vw, 96px)', lineHeight: 0.88, letterSpacing: '-0.025em', textTransform: 'uppercase', color: C.bg, margin: '20px 0 24px', textWrap: 'balance' }}>
            {T.finalCta.title}
          </h2>
          <p style={{ fontFamily: F.sans, fontSize: 18, lineHeight: 1.55, color: C.faint, maxWidth: 600, marginBottom: 36 }}>
            {T.finalCta.sub}
          </p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Btn primary href="/book-scoping-call">GET STARTED ▸</Btn>
            <Btn href="#simulator" style={{ background: 'transparent', color: C.bg, border: `2px solid ${C.bg}` }}>CALCULATE PROFIT ▸</Btn>
          </div>
        </div>
        <div style={{ background: 'rgba(255,255,255,0.04)', border: `1px solid rgba(255,255,255,0.12)`, padding: 32 }}>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1.4, color: C.hi, fontWeight: 700, marginBottom: 20 }}>// WHAT HAPPENS NEXT</div>
          {[
            ['01', 'Check availability', 'See if your city + trade is open. 30 seconds.'],
            ['02', 'Scoping call', '20-min scoping call. We confirm fit and lock the seat.'],
            ['03', '3-week install', 'Ads live day 3 · Wk 1 foundation · Wk 2+ optimize.'],
            ['04', 'Locked + running', 'Your metro is yours. Permanent.'],
          ].map(([n, t, d]) => (
            <div key={n} style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 16, marginBottom: 20 }}>
              <div style={{ fontFamily: F.display, fontSize: 28, color: C.hi, letterSpacing: -0.6, lineHeight: 1 }}>{n}</div>
              <div>
                <div style={{ fontFamily: F.display, fontSize: 16, textTransform: 'uppercase', letterSpacing: -0.2, color: C.bg, marginBottom: 4 }}>{t}</div>
                <div style={{ fontFamily: F.sans, fontSize: 13, lineHeight: 1.5, color: C.faint }}>{d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function App() {
  return (
    <div data-screen-label={T.label}>
      <Nav current="/trades" />
      <main>
        <Hero />
        <JumpNav links={TRADE_JUMP_LINKS} />
        <TrustBar />
        <Physics />
        <Problem />
        <PipelineFlow />
        <FieldBand />
        <FitFilter />
        <TradeSimulator />
        <Receipts />
        <AIReceptionistDemo />
        <MidCTA />
        <Stack />
        <FAQ />
        <RelatedBlog />
        <AfterSign />
        <FinalCTA />
      </main>
      <Footer />
      <StickyBottomCTA tradeName={T.name} />
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
