/* eslint-disable */
const { useState, useMemo, useEffect, useRef } = React;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

// Where the "Book a discovery call" button sends people.
// Update this to your real Calendly / GHL booking link.
const BOOKING_URL = 'https://app.gohighlevel.com/v2/preview/FALjYTuKhXi4NaB4WPyx?notrack=true';

// Optional: send leads to a webhook (Zapier, GHL inbound webhook, Make, etc.)
// Leave as empty string to disable.
const LEAD_WEBHOOK_URL = '';

const TIERS = {
  recover: {
    id: 'recover',
    name: 'Recover',
    eyebrow: 'For the lost-lead audit',
    headline: 'Turn dead leads into booked jobs.',
    description:
      'A 2–3 week, multi-channel revival that finds the money you already paid for. Qualifying automation routes hot replies instantly while stop-on-booking logic prevents waste and lifts ROI fast.',
    bullets: [
      'Multi-channel dead-lead revival (SMS + email + voicemail)',
      'Instant routing of hot replies to your team',
      'Stop-on-booking logic — no wasted outreach',
      'Reports on revived revenue you can take to the bank',
    ],
    closeLiftBand: [1.0, 1.3],
    responseImpact: 'recovered',
    metric: 'Revived revenue',
  },
  booking: {
    id: 'booking',
    name: 'Booking',
    eyebrow: 'The system most clients start with',
    headline: 'First response in under 60 seconds. Always.',
    description:
      'Cut first response to under 60 seconds across web, text, and missed calls, then let the AI assistant qualify, schedule, and remind so more leads show up. Expect more conversations, more booked appointments, and fewer no-shows from the same lead flow.',
    bullets: [
      '<60-second response across web, text, and missed calls',
      'AI assistant qualifies, schedules, and reminds',
      'Fewer no-shows from automated confirmations',
      'More booked jobs from the leads you already get',
    ],
    closeLiftBand: [1.4, 2.0],
    responseImpact: 'speed',
    metric: 'Net new revenue',
    recommended: true,
  },
  scaling: {
    id: 'scaling',
    name: 'Scaling',
    eyebrow: 'For operators ready to compound',
    headline: 'A system that grows without breaking your team.',
    description:
      'Wire your operation end-to-end with AI assistants, capacity-aware routing, and integrations that remove manual work and protect margins as volume grows. You get predictable bookings, clearer attribution (CAC/LTV), and a system that scales without burning the team.',
    bullets: [
      'End-to-end AI assistants across every touchpoint',
      'Capacity-aware routing keeps techs full, not slammed',
      'CAC/LTV attribution so you know which $ to spend',
      'A backbone that scales bookings 2–3× without new hires',
    ],
    closeLiftBand: [1.6, 2.2],
    responseImpact: 'compound',
    metric: 'Net new revenue + margin',
  },
};

const INDUSTRIES = [
  { id: 'plumbing',   label: 'Plumbing',   avgJob: 650,  closeRate: 0.32, deadLeadPct: 0.55 },
  { id: 'hvac',       label: 'HVAC',       avgJob: 750,  closeRate: 0.30, deadLeadPct: 0.58 },
  { id: 'roofing',    label: 'Roofing',    avgJob: 9500, closeRate: 0.22, deadLeadPct: 0.65 },
  { id: 'electrical', label: 'Electrical', avgJob: 700,  closeRate: 0.30, deadLeadPct: 0.55 },
  { id: 'other',      label: 'Other',      avgJob: 800,  closeRate: 0.28, deadLeadPct: 0.60 },
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const fmtUSD = (n, opts = {}) =>
  (n || 0).toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
    ...opts,
  });
const fmtPct = (n, digits = 0) => `${(n * 100).toFixed(digits)}%`;
const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));

function useCountUp(target, duration = 1000) {
  const [val, setVal] = useState(0);
  const startRef = useRef(null);
  useEffect(() => {
    startRef.current = null;
    let raf;
    const step = (ts) => {
      if (startRef.current === null) startRef.current = ts;
      const p = Math.min(1, (ts - startRef.current) / duration);
      const ease = 1 - Math.pow(1 - p, 3);
      setVal(target * ease);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return val;
}

// ---------------------------------------------------------------------------
// Main App
// ---------------------------------------------------------------------------
function App() {
  const [step, setStep] = useState(1);

  const [tierId, setTierId] = useState('booking');
  const [industryId, setIndustryId] = useState('plumbing');
  const [monthlyLeads, setMonthlyLeads] = useState(120);
  const [avgJob, setAvgJob] = useState(650);
  const [closeRate, setCloseRate] = useState(0.32);
  const [responseMin, setResponseMin] = useState(45);

  const [email, setEmail] = useState('');
  const [mobile, setMobile] = useState('');
  const [company, setCompany] = useState('');

  useEffect(() => {
    const ind = INDUSTRIES.find((i) => i.id === industryId);
    if (ind && industryId !== 'other') {
      setAvgJob(ind.avgJob);
      setCloseRate(ind.closeRate);
    }
  }, [industryId]);

  const tier = TIERS[tierId];
  const industry = INDUSTRIES.find((i) => i.id === industryId);

  // ---------- ROI calculation ----------
  const roi = useMemo(() => {
    const leads = Math.max(10, monthlyLeads);
    const job = Math.max(350, avgJob);
    const cr = clamp(closeRate, 0.01, 0.95);
    const rt = clamp(responseMin, 1, 240);

    const baselineMonthlyRev = leads * cr * job;
    const baselineAnnualRev = baselineMonthlyRev * 12;

    let liftMultiplier;
    let extraLeadsFromRevival = 0;

    if (tier.responseImpact === 'speed') {
      const responseFactor = clamp((rt - 5) / 55, 0, 1);
      liftMultiplier = tier.closeLiftBand[0] + (tier.closeLiftBand[1] - tier.closeLiftBand[0]) * responseFactor;
    } else if (tier.responseImpact === 'recovered') {
      const deadPool = leads * 6 * industry.deadLeadPct;
      const revivalRate = 0.06;
      extraLeadsFromRevival = (deadPool * revivalRate) / 12;
      liftMultiplier = 1.0;
    } else {
      const responseFactor = clamp((rt - 5) / 55, 0, 1);
      liftMultiplier = tier.closeLiftBand[0] + (tier.closeLiftBand[1] - tier.closeLiftBand[0]) * responseFactor;
      const recoveryRate = 0.08;
      extraLeadsFromRevival = leads * recoveryRate;
    }

    const newCloseRate = Math.min(0.95, cr * liftMultiplier);
    const newMonthlyJobs = leads * newCloseRate + extraLeadsFromRevival * cr;
    const newMonthlyRev = newMonthlyJobs * job;

    const monthlyLift = newMonthlyRev - baselineMonthlyRev;
    const annualLift = monthlyLift * 12;

    const baselineJobs = leads * cr;
    const additionalJobsPerMonth = newMonthlyJobs - baselineJobs;
    const additionalJobsPerYear = additionalJobsPerMonth * 12;

    return {
      baselineMonthlyRev,
      baselineAnnualRev,
      newMonthlyRev,
      newAnnualRev: newMonthlyRev * 12,
      monthlyLift,
      annualLift,
      liftMultiplier,
      newCloseRate,
      baselineCloseRate: cr,
      additionalJobsPerMonth,
      additionalJobsPerYear,
      extraLeadsFromRevival,
      currentResponseMin: rt,
    };
  }, [tier, industry, monthlyLeads, avgJob, closeRate, responseMin]);

  // Send lead to webhook (fire-and-forget on results screen)
  useEffect(() => {
    if (step === 4 && LEAD_WEBHOOK_URL && email) {
      const payload = {
        email, mobile, company,
        tier: tier.name,
        industry: industry.label,
        monthly_leads: monthlyLeads,
        avg_job: avgJob,
        close_rate: closeRate,
        response_minutes: responseMin,
        projected_monthly_lift: Math.round(roi.monthlyLift),
        projected_annual_lift: Math.round(roi.annualLift),
        additional_jobs_per_year: Math.round(roi.additionalJobsPerYear),
        source: 'roi_calculator',
        timestamp: new Date().toISOString(),
      };
      fetch(LEAD_WEBHOOK_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      }).catch(() => {});
    }
  }, [step]);

  const next = () => setStep((s) => Math.min(4, s + 1));
  const back = () => setStep((s) => Math.max(1, s - 1));

  const profileValid = monthlyLeads >= 10 && avgJob >= 350 && closeRate > 0;
  const gateValid =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) &&
    mobile.replace(/\D/g, '').length >= 10;

  return (
    <div className="min-h-screen bg-white">
      <Header />

      <main className="max-w-5xl mx-auto px-5 lg:px-8 pb-24 pt-8">
        <StepIndicator step={step} />

        <div key={step} className="step-enter">
          {step === 1 && <StepTier tierId={tierId} setTierId={setTierId} onNext={next} />}
          {step === 2 && (
            <StepProfile
              industryId={industryId}
              setIndustryId={setIndustryId}
              monthlyLeads={monthlyLeads}
              setMonthlyLeads={setMonthlyLeads}
              avgJob={avgJob}
              setAvgJob={setAvgJob}
              closeRate={closeRate}
              setCloseRate={setCloseRate}
              responseMin={responseMin}
              setResponseMin={setResponseMin}
              onNext={next}
              onBack={back}
              valid={profileValid}
            />
          )}
          {step === 3 && (
            <StepGate
              email={email}
              setEmail={setEmail}
              mobile={mobile}
              setMobile={setMobile}
              company={company}
              setCompany={setCompany}
              valid={gateValid}
              onNext={next}
              onBack={back}
            />
          )}
          {step === 4 && (
            <StepResults
              tier={tier}
              industry={industry}
              roi={roi}
              monthlyLeads={monthlyLeads}
              avgJob={avgJob}
              onBack={() => setStep(2)}
              onReset={() => {
                setStep(1);
                setEmail('');
                setMobile('');
                setCompany('');
              }}
            />
          )}
        </div>

        <Footer />
      </main>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Header
// ---------------------------------------------------------------------------

function Header() {
  return (
    <header className="border-b border-surface-line bg-white/95 backdrop-blur sticky top-0 z-20">
      <div className="max-w-5xl mx-auto px-5 lg:px-8 py-4 flex items-center justify-between">
        <a href={BOOKING_URL.replace(/\/v2\/preview\/[^?]+.*/, '')} className="flex items-center gap-3 group">
          <img
            src="./logo.png"
            alt="Acquisition Systems"
            className="h-9 sm:h-10 w-auto"
          />
        </a>
        <a
          href={BOOKING_URL}
          className="text-xs sm:text-sm text-navy-900 hover:text-brand-500 font-bold tracking-wide transition-colors"
        >
          BOOK A DEMO →
        </a>
      </div>
    </header>
  );
}

function StepIndicator({ step }) {
  const labels = ['Choose system', 'Your numbers', 'Where to send it', 'Your estimate'];
  return (
    <div className="mb-10">
      <div className="flex items-center justify-between gap-2">
        {labels.map((l, i) => {
          const n = i + 1;
          const done = step > n;
          const active = step === n;
          return (
            <div key={n} className="flex-1 flex items-center gap-2 min-w-0">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-extrabold shrink-0 transition-all ${
                  done
                    ? 'bg-ok-500 text-white'
                    : active
                    ? 'bg-navy-900 text-white ring-4 ring-navy-900/10'
                    : 'bg-surface-soft text-ink-400 border-2 border-surface-line'
                }`}
              >
                {done ? '✓' : n}
              </div>
              <div
                className={`text-xs font-bold hidden sm:block truncate tracking-wide ${
                  active ? 'text-navy-900' : done ? 'text-ink-500' : 'text-ink-400'
                }`}
              >
                {l}
              </div>
              {i < labels.length - 1 && (
                <div className={`flex-1 h-0.5 ${done ? 'bg-ok-500' : 'bg-surface-line'}`}></div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 1 — Tier selection
// ---------------------------------------------------------------------------

function StepTier({ tierId, setTierId, onNext }) {
  return (
    <section>
      <div className="text-center mb-10 max-w-3xl mx-auto">
        <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-surface-soft border border-surface-line text-navy-900 text-[11px] uppercase tracking-[0.2em] font-bold mb-6">
          <span className="w-1.5 h-1.5 bg-brand-500 rounded-full"></span>
          60-Second Estimate
        </div>
        <h1 className="text-4xl sm:text-5xl lg:text-6xl font-black tracking-tight leading-[1.05] mb-5 text-navy-900">
          How much revenue is leaking past your front door?
        </h1>
        <p className="text-lg text-ink-500 leading-relaxed max-w-xl mx-auto">
          Pick the system that fits where you are right now. We'll show you the math.
        </p>
      </div>

      <div className="grid md:grid-cols-3 gap-5 mb-10">
        {Object.values(TIERS).map((t) => (
          <TierCard key={t.id} tier={t} active={tierId === t.id} onClick={() => setTierId(t.id)} />
        ))}
      </div>

      <div className="flex justify-center">
        <button
          onClick={onNext}
          className="btn-primary px-10 py-4 rounded-full font-extrabold text-sm tracking-wide uppercase"
        >
          Continue with {TIERS[tierId].name} →
        </button>
      </div>
    </section>
  );
}

function TierCard({ tier, active, onClick }) {
  return (
    <button
      onClick={onClick}
      className={`text-left rounded-2xl border-2 p-6 transition-all relative ${
        active
          ? 'border-navy-900 bg-navy-900 text-white shadow-2xl scale-[1.02]'
          : 'border-surface-line bg-white hover:border-brand-500 hover:shadow-lg'
      }`}
    >
      {tier.recommended && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full text-[10px] uppercase tracking-widest font-extrabold bg-brand-500 text-white shadow-md">
          Most Popular
        </div>
      )}
      <div className={`text-[10px] uppercase tracking-[0.2em] font-bold mb-2 ${active ? 'text-brand-300' : 'text-ink-500'}`}>
        {tier.eyebrow}
      </div>
      <div className={`text-2xl font-black tracking-tight mb-2 ${active ? 'text-white' : 'text-navy-900'}`}>
        {tier.name}
      </div>
      <div className={`text-sm font-bold mb-4 leading-snug ${active ? 'text-brand-400' : 'text-brand-500'}`}>
        {tier.headline}
      </div>
      <div className={`text-xs leading-relaxed mb-4 ${active ? 'text-surface-line' : 'text-ink-700'}`}>
        {tier.description}
      </div>
      <ul className="space-y-2">
        {tier.bullets.map((b, i) => (
          <li key={i} className={`text-xs flex items-start gap-2 leading-snug ${active ? 'text-surface-line' : 'text-ink-700'}`}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" className="mt-0.5 shrink-0">
              <circle cx="7" cy="7" r="7" fill={active ? '#188bf6' : '#188bf6'} />
              <path d="M4 7L6 9L10 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <span>{b}</span>
          </li>
        ))}
      </ul>
    </button>
  );
}

// ---------------------------------------------------------------------------
// Step 2 — Profile inputs
// ---------------------------------------------------------------------------

function StepProfile({
  industryId, setIndustryId,
  monthlyLeads, setMonthlyLeads,
  avgJob, setAvgJob,
  closeRate, setCloseRate,
  responseMin, setResponseMin,
  onNext, onBack, valid,
}) {
  return (
    <section className="max-w-2xl mx-auto">
      <div className="text-center mb-8">
        <h2 className="text-3xl sm:text-4xl font-black tracking-tight leading-tight mb-3 text-navy-900">
          Tell us about your business.
        </h2>
        <p className="text-base text-ink-500">
          Five quick numbers. No fluff.
        </p>
      </div>

      <div className="bg-white rounded-2xl border-2 border-surface-line p-6 sm:p-8 space-y-6 shadow-sm">
        <Field label="What industry are you in?">
          <div className="grid grid-cols-2 sm:grid-cols-5 gap-2">
            {INDUSTRIES.map((ind) => (
              <button
                key={ind.id}
                onClick={() => setIndustryId(ind.id)}
                className={`px-3 py-2.5 text-xs sm:text-sm rounded-lg border-2 font-bold uppercase tracking-wide transition-all ${
                  industryId === ind.id
                    ? 'border-navy-900 bg-navy-900 text-white'
                    : 'border-surface-line bg-white text-ink-700 hover:border-brand-500 hover:text-brand-500'
                }`}
              >
                {ind.label}
              </button>
            ))}
          </div>
        </Field>

        <div className="grid sm:grid-cols-2 gap-5">
          <NumberField
            label="Monthly leads (all channels)"
            value={monthlyLeads}
            onChange={setMonthlyLeads}
            min={10}
            step={5}
            hint="Minimum 10. Calls, forms, chats — everything."
          />
          <NumberField
            label="Avg job / customer value"
            value={avgJob}
            onChange={setAvgJob}
            min={350}
            step={25}
            prefix="$"
            hint="Minimum $350. Your average ticket."
          />
        </div>

        <RangeField
          label="Current close rate"
          value={closeRate}
          onChange={setCloseRate}
          min={0.05}
          max={0.8}
          step={0.01}
          format={(v) => fmtPct(v)}
          hint="What % of leads turn into paying jobs today?"
        />

        <RangeField
          label="Current lead response time"
          value={responseMin}
          onChange={setResponseMin}
          min={1}
          max={240}
          step={1}
          format={(v) => `${v} min`}
          hint="How long until a lead hears back from you on average?"
        />
      </div>

      <div className="flex items-center justify-between mt-6">
        <button
          onClick={onBack}
          className="text-sm text-ink-500 hover:text-navy-900 font-bold uppercase tracking-wide"
        >
          ← Back
        </button>
        <button
          onClick={onNext}
          disabled={!valid}
          className={`px-10 py-4 rounded-full font-extrabold text-sm tracking-wide uppercase transition-all ${
            valid ? 'btn-primary' : 'bg-surface-soft text-ink-400 cursor-not-allowed'
          }`}
        >
          See My Results →
        </button>
      </div>
    </section>
  );
}

// ---------------------------------------------------------------------------
// Step 3 — Gate form
// ---------------------------------------------------------------------------

function StepGate({ email, setEmail, mobile, setMobile, company, setCompany, valid, onNext, onBack }) {
  const submit = (e) => {
    e?.preventDefault();
    if (valid) onNext();
  };
  return (
    <section className="max-w-xl mx-auto">
      <div className="text-center mb-6">
        <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-ok-500 text-white text-[11px] uppercase tracking-[0.2em] font-bold mb-5">
          Almost There
        </div>
        <h2 className="text-3xl sm:text-4xl font-black tracking-tight leading-tight mb-3 text-navy-900">
          Where should we send your estimate?
        </h2>
        <p className="text-base text-ink-500">
          You'll get your full results on the next screen — plus a copy of the assumptions used so you can audit the math yourself.
        </p>
      </div>

      <form onSubmit={submit} className="bg-white rounded-2xl border-2 border-surface-line p-6 sm:p-8 space-y-5 shadow-sm">
        <TextField
          label="Work email"
          type="email"
          value={email}
          onChange={setEmail}
          placeholder="you@company.com"
          required
        />
        <TextField
          label="Mobile number"
          type="tel"
          value={mobile}
          onChange={setMobile}
          placeholder="(555) 123-4567"
          required
        />
        <TextField
          label="Company name"
          type="text"
          value={company}
          onChange={setCompany}
          placeholder="Optional"
        />

        <div className="text-xs text-ink-500 leading-relaxed bg-surface-soft rounded-lg p-3.5 border border-surface-line">
          <strong className="text-navy-900">We'll text you the estimate within 60 seconds</strong> — yes, from the same system we'd build for you. No spam, no list-sharing, unsubscribe anytime.
        </div>

        <div className="flex items-center justify-between pt-2">
          <button
            type="button"
            onClick={onBack}
            className="text-sm text-ink-500 hover:text-navy-900 font-bold uppercase tracking-wide"
          >
            ← Back
          </button>
          <button
            type="submit"
            disabled={!valid}
            className={`px-10 py-4 rounded-full font-extrabold text-sm tracking-wide uppercase transition-all ${
              valid ? 'btn-accent' : 'bg-surface-soft text-ink-400 cursor-not-allowed'
            }`}
          >
            See My Results →
          </button>
        </div>
      </form>
    </section>
  );
}

// ---------------------------------------------------------------------------
// Step 4 — Results
// ---------------------------------------------------------------------------

function StepResults({ tier, industry, roi, monthlyLeads, avgJob, onBack, onReset }) {
  const monthlyLiftAnim = useCountUp(roi.monthlyLift, 1200);
  const annualLiftAnim = useCountUp(roi.annualLift, 1500);
  const jobsAnim = useCountUp(roi.additionalJobsPerMonth, 1000);

  return (
    <section>
      <div className="text-center mb-8">
        <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-brand-500 text-white text-[11px] uppercase tracking-[0.2em] font-bold mb-5">
          Your Estimate · {tier.name} System
        </div>
        <h2 className="text-2xl sm:text-3xl font-black tracking-tight leading-tight mb-2 max-w-2xl mx-auto text-navy-900">
          Based on your numbers, here's the revenue {industry.label.toLowerCase()} businesses like yours typically unlock.
        </h2>
      </div>

      {/* Hero metric */}
      <div className="bg-navy-900 text-white rounded-2xl p-8 sm:p-12 mb-6 text-center relative overflow-hidden shadow-2xl">
        <div className="grid-paper absolute inset-0 opacity-30"></div>
        <div className="absolute top-0 right-0 w-80 h-80 bg-brand-500/20 rounded-full blur-3xl -translate-y-20 translate-x-20"></div>
        <div className="relative">
          <div className="text-[11px] uppercase tracking-[0.25em] text-brand-300 font-bold mb-3">
            Projected Annual Revenue Lift
          </div>
          <div className="text-6xl sm:text-7xl lg:text-8xl font-black num text-white leading-none mb-3 tracking-tight">
            {fmtUSD(annualLiftAnim)}
          </div>
          <div className="text-base text-surface-line">
            <span className="font-bold text-white">{fmtUSD(monthlyLiftAnim)}</span> extra per month
            <span className="mx-2 text-brand-400">·</span>
            <span className="font-bold text-white">{jobsAnim.toFixed(1)}</span> more booked jobs/mo
          </div>
        </div>
      </div>

      {/* Breakdown grid */}
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        <MetricCard
          label="Where you are today"
          value={fmtUSD(roi.baselineAnnualRev)}
          sub={`${fmtUSD(roi.baselineMonthlyRev)}/mo from ${monthlyLeads} leads`}
        />
        <MetricCard
          label="With the system"
          value={fmtUSD(roi.newAnnualRev)}
          sub={`${fmtUSD(roi.newMonthlyRev)}/mo from the same leads`}
          accent
        />
        <MetricCard
          label="Additional jobs per year"
          value={`+${Math.round(roi.additionalJobsPerYear)}`}
          sub={`Avg job: ${fmtUSD(avgJob)}`}
        />
      </div>

      {/* Detail breakdown */}
      <div className="bg-white border-2 border-surface-line rounded-2xl p-6 sm:p-8 mb-6">
        <div className="text-[10px] uppercase tracking-[0.2em] text-ink-500 font-bold mb-2">
          How we got here
        </div>
        <div className="text-xl font-black tracking-tight mb-6 text-navy-900">The math behind your estimate</div>

        <div className="space-y-5">
          <BreakdownRow
            before={`${fmtPct(roi.baselineCloseRate)}`}
            beforeLabel="Today's close rate"
            arrow={`× ${roi.liftMultiplier.toFixed(2)}`}
            after={`${fmtPct(roi.newCloseRate)}`}
            afterLabel="With AI-assisted qualifying"
          />
          {tier.responseImpact !== 'recovered' && (
            <BreakdownRow
              before={`${roi.currentResponseMin} min`}
              beforeLabel="Today's response time"
              arrow="→"
              after="<60 sec"
              afterLabel={`${tier.name} system response`}
            />
          )}
          {roi.extraLeadsFromRevival > 0 && (
            <BreakdownRow
              before={`${monthlyLeads}`}
              beforeLabel="Leads/mo today"
              arrow="+"
              after={`${roi.extraLeadsFromRevival.toFixed(1)}`}
              afterLabel={tier.responseImpact === 'recovered' ? 'Revived dead leads/mo' : 'Recaptured missed leads/mo'}
            />
          )}
        </div>

        <div className="mt-6 pt-5 border-t border-surface-line text-xs text-ink-500 leading-relaxed">
          <strong className="text-navy-900">Assumptions used:</strong> The lift multiplier comes from speed-to-lead industry research ({tier.name === 'Recover' ? 'dead-lead revival typically converts 5–8% of stale pools' : 'sub-60-second response lifts contact rates ~8× per the InsideSales 5.7M-lead study'}). We use a realistic-but-optimistic band for the {tier.name} system based on outcomes from operators in your industry. Your real result will vary based on lead quality, offer, and follow-through.
        </div>
      </div>

      {/* CTA */}
      <div className="bg-gradient-to-br from-navy-900 to-navy-700 rounded-2xl p-8 sm:p-12 text-center relative overflow-hidden">
        <div className="absolute top-0 left-0 w-96 h-96 bg-brand-500/30 rounded-full blur-3xl -translate-x-32 -translate-y-32"></div>
        <div className="relative text-white">
          <div className="text-[11px] uppercase tracking-[0.25em] font-bold mb-3 text-brand-300">
            Next Step
          </div>
          <h3 className="text-3xl sm:text-4xl font-black tracking-tight leading-tight mb-3 max-w-xl mx-auto">
            Want to see exactly how we'd unlock this for your business?
          </h3>
          <p className="text-base mb-7 max-w-lg mx-auto text-surface-line">
            Book a 20-minute discovery call. We'll walk through your current setup and show you the build map — no pitch, no pressure.
          </p>
          <a
            href={BOOKING_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-block px-10 py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-full font-extrabold text-sm tracking-wide uppercase shadow-2xl hover:shadow-brand-500/50 transition-all hover:-translate-y-0.5"
          >
            Book a Discovery Call →
          </a>
          <div className="text-xs mt-4 text-surface-line">
            Spots fill 2–3 weeks out · We only take on what we can deliver
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between mt-6 text-sm">
        <button onClick={onBack} className="text-ink-500 hover:text-navy-900 font-bold uppercase tracking-wide">
          ← Adjust My Numbers
        </button>
        <button onClick={onReset} className="text-ink-500 hover:text-navy-900 font-bold uppercase tracking-wide">
          Start Over
        </button>
      </div>
    </section>
  );
}

function MetricCard({ label, value, sub, accent }) {
  return (
    <div className={`rounded-2xl p-5 border-2 ${
      accent ? 'bg-brand-500 text-white border-brand-500 shadow-lg' : 'bg-white border-surface-line'
    }`}>
      <div className={`text-[10px] uppercase tracking-[0.2em] font-bold mb-2 ${
        accent ? 'text-white/80' : 'text-ink-500'
      }`}>
        {label}
      </div>
      <div className={`text-2xl sm:text-3xl font-black num leading-none mb-1.5 tracking-tight ${
        accent ? 'text-white' : 'text-navy-900'
      }`}>
        {value}
      </div>
      <div className={`text-xs ${accent ? 'text-white/85' : 'text-ink-500'}`}>{sub}</div>
    </div>
  );
}

function BreakdownRow({ before, beforeLabel, arrow, after, afterLabel }) {
  return (
    <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 sm:gap-6">
      <div className="text-right">
        <div className="text-xl sm:text-2xl font-black num text-navy-900 tracking-tight">{before}</div>
        <div className="text-[11px] text-ink-500 mt-0.5">{beforeLabel}</div>
      </div>
      <div className="text-brand-500 font-extrabold text-sm sm:text-base whitespace-nowrap">{arrow}</div>
      <div>
        <div className="text-xl sm:text-2xl font-black num text-brand-500 tracking-tight">{after}</div>
        <div className="text-[11px] text-ink-500 mt-0.5">{afterLabel}</div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Form primitives
// ---------------------------------------------------------------------------

function Field({ label, children, hint }) {
  return (
    <label className="block">
      <div className="text-xs uppercase tracking-[0.15em] text-navy-900 font-bold mb-2">{label}</div>
      {children}
      {hint && <div className="text-[11px] text-ink-500 mt-1.5">{hint}</div>}
    </label>
  );
}

function NumberField({ label, value, onChange, min, max, step = 1, prefix, hint }) {
  return (
    <Field label={label} hint={hint}>
      <div className="relative">
        {prefix && (
          <div className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-500 font-bold text-sm pointer-events-none">
            {prefix}
          </div>
        )}
        <input
          type="number"
          value={value}
          min={min}
          max={max}
          step={step}
          onChange={(e) => {
            const v = e.target.value === '' ? min : parseFloat(e.target.value);
            onChange(isNaN(v) ? min : Math.max(min, v));
          }}
          className={`w-full bg-white border-2 border-surface-line rounded-lg ${prefix ? 'pl-7' : 'pl-3'} pr-3 py-3 text-base num font-bold text-navy-900 focus:outline-none focus:border-brand-500 transition-colors`}
        />
      </div>
    </Field>
  );
}

function TextField({ label, type = 'text', value, onChange, placeholder, required }) {
  return (
    <Field label={label}>
      <input
        type={type}
        value={value}
        required={required}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        className="w-full bg-white border-2 border-surface-line rounded-lg px-4 py-3 text-base text-navy-900 focus:outline-none focus:border-brand-500 transition-colors"
      />
    </Field>
  );
}

function RangeField({ label, value, onChange, min, max, step, format, hint }) {
  return (
    <Field
      label={
        <span className="flex items-baseline justify-between gap-3">
          <span>{label}</span>
          <span className="font-black text-brand-500 num text-base tracking-tight">{format(value)}</span>
        </span>
      }
      hint={hint}
    >
      <input
        type="range"
        value={value}
        min={min}
        max={max}
        step={step}
        onChange={(e) => onChange(parseFloat(e.target.value))}
        className="w-full mt-2"
      />
    </Field>
  );
}

// ---------------------------------------------------------------------------
// Footer
// ---------------------------------------------------------------------------

function Footer() {
  return (
    <footer className="mt-16 pt-8 border-t border-surface-line text-center text-xs text-ink-400">
      <p>
        © Acquisition Systems · This estimate is based on industry benchmarks and your inputs.
        Real outcomes depend on lead quality, offer fit, and execution.
      </p>
    </footer>
  );
}

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