/* ============================================================
   Benehab RPM — landing page (Direction B) · patch v2
   Uses Calculator/CONFIG/compute/netPill from calc.jsx.
   Real facts only — no invented proofs, metrics, or logos.
   ============================================================ */
const { useState, useRef, useEffect } = React;

/* ---------- icons (simple line) ---------- */
const I = {
  tick: "M4 10.5l3.5 3.5L16 5.5",
  setup: "M3 8l7-4 7 4v7l-7 4-7-4V8z M3 8l7 4 7-4 M10 12v7",
  engage: "M4 5h12a1 1 0 011 1v7a1 1 0 01-1 1H8l-4 3V6a1 1 0 011-1z M7.5 9.5h5 M7.5 11.5h3",
  bill: "M6 3h8a1 1 0 011 1v13l-2.5-1.5L10 17l-2.5-1.5L5 17V4a1 1 0 011-1z M8 7h4 M8 10h4",
  shield: "M10 3l6 2v4c0 4-2.7 6.7-6 8-3.3-1.3-6-4-6-8V5l6-2z M7.5 9.8l1.8 1.8L13 8",
  eye: "M2 10s3-5 8-5 8 5 8 5-3 5-8 5-8-5-8-5z M10 12.2a2.2 2.2 0 100-4.4 2.2 2.2 0 000 4.4",
  fee: "M10 3v14 M13.5 6.2C12.8 5.2 11.6 4.7 10 4.7c-2 0-3.3 1-3.3 2.5 0 3.6 7 1.8 7 5.4 0 1.6-1.4 2.7-3.7 2.7-1.8 0-3.1-.6-3.8-1.7",
  doc: "M6 3h5l4 4v10a1 1 0 01-1 1H6a1 1 0 01-1-1V4a1 1 0 011-1z M11 3v4h4 M7.5 11h5 M7.5 13.5h5",
  lock: "M6 9V6.6a4 4 0 018 0V9 M4.7 9h10.6v7.5H4.7z M10 12v2",
  device: "M3.5 5h13v8h-13z M7 16h6 M10 13v3",
  live: "M10 8.4a1.6 1.6 0 100 3.2 1.6 1.6 0 000-3.2 M6.2 6.2a5.4 5.4 0 000 7.6 M13.8 6.2a5.4 5.4 0 010 7.6",
  chev: "M5 8l5 5 5-5",
  cal: "M4 5h12a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V6a1 1 0 011-1z M3 8.5h14 M7 3.5v3 M13 3.5v3",
  phone: "M5 3.5h3l1.4 3.8-1.9 1.4a9 9 0 003.8 3.8l1.4-1.9 3.8 1.4v3A1.5 1.5 0 0118.4 18C9.4 17.6 2.4 10.6 2 1.6",
};
const Ico = ({ d, cls }) => (
  <svg className={cls || "icon"} viewBox="0 0 20 20" aria-hidden="true"><path d={d} /></svg>
);
const Tick = ({ cls }) => (
  <svg className={cls || "tick"} viewBox="0 0 20 20" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d={I.tick} /></svg>
);

/* ---------- announcement ribbon ---------- */
function Announce() {
  return (
    <div className="announce">
      <span className="dot"></span>
      Now live — early-access practices are onboarding now. Founding practices get hands-on onboarding.
    </div>
  );
}

/* ---------- header ---------- */
function Header({ onLead }) {
  return (
    <header className="site-header">
      <div className="wrap">
        <a href="#top" className="brand"><span className="mark"></span><span>Benehab RPM</span></a>
        <div className="header-right">
          <span className="cobrand">Remote Patient Monitoring, fully managed</span>
          <a href="#contact" className="btn btn-primary btn-sm" onClick={() => onLead("demo")}>Request a demo</a>
        </div>
      </div>
    </header>
  );
}

/* ---------- trust chips ---------- */
const CHIPS = [
  { ico: I.doc, t: "Built on established Medicare RPM codes" },
  { ico: I.device, t: "FDA-cleared Tenovi devices" },
  { ico: I.lock, t: "HIPAA-compliant — BAA provided" },
];
function Chips() {
  return (
    <div className="chips">
      {CHIPS.map((c, i) => (
        <span className="chip" key={i}><Ico d={c.ico} cls="chip-ico" />{c.t}</span>
      ))}
    </div>
  );
}

/* ---------- hero ---------- */
function Hero({ patients, ccmPct, setPatients, setCcm, onLead, onEstimate }) {
  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="hero-text">
          <span className="eyebrow">Fully managed Remote Patient Monitoring</span>
          <h1>A new <span className="uline">recurring revenue stream</span> from the patients you already care for</h1>
          <p className="sub">We set up and run remote monitoring for your chronic-care patients — FDA-cleared devices,
            patient engagement, and billing support. We run it; your team does one short monthly review per patient and
            keeps the Medicare collections.</p>
          <div className="cta-row">
            <a href="#contact" className="btn btn-primary" onClick={() => onLead("demo")}>Request a demo</a>
            <a href="#how" className="btn btn-ghost">See how it works</a>
          </div>
          <Chips />
        </div>
        <div className="hero-calc" id="estimate">
          <span className="kicker">Estimate your monthly revenue</span>
          <div className="card-calc">
            <Calculator
              variant="B"
              simple={true}
              hideCcm={true}
              patients={patients} ccmPct={ccmPct}
              onPatients={setPatients} onCcm={setCcm}
              ctaLead="Want a month-by-month projection for your practice?"
              ctaLabel="Get your detailed estimate (PDF)"
              onCta={onEstimate}
            />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- how it works ---------- */
const STEPS = [
  { n: "Step 1", ico: I.setup, h: "We set it up",
    p: "We enroll your eligible chronic-care patients and ship FDA-cleared, cellular-connected devices (blood-pressure cuff, scale) straight to their homes — no smartphone, no app, no Wi-Fi." },
  { n: "Step 2", ico: I.engage, h: "We keep patients engaged",
    p: "A voice assistant checks in with patients between visits to keep readings flowing and adherence high — the repetitive outreach that usually eats your staff's time." },
  { n: "Step 3", ico: I.bill, h: "You bill and earn",
    p: "Your practice bills Medicare under standard remote-monitoring codes, keeps the reimbursement, and pays one simple per-patient service fee." },
];
function HowItWorks() {
  return (
    <section className="band-section" id="how">
      <div className="wrap">
        <div className="sec-head reveal">
          <span className="eyebrow">How it works</span>
          <h2>Three steps — most of the work is ours</h2>
        </div>
        <div className="steps">
          {STEPS.map((s, i) => (
            <div className="step reveal" key={i} style={{ transitionDelay: (i * 80) + "ms" }}>
              <span className="num">{s.n}</span>
              <div className="ico-wrap"><Ico d={s.ico} /></div>
              <h3>{s.h}</h3>
              <p>{s.p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- voice assistant demo ---------- */
const WAVE = [5,9,14,8,18,12,22,16,26,20,30,24,18,28,14,22,10,17,24,30,20,12,26,16,9,15,21,28,18,11,24,30,22,14,8,17,12,20,9,14,7,11,6,10];
function fmtTime(s) { const m = Math.floor(s / 60); const ss = Math.floor(s % 60); return m + ":" + String(ss).padStart(2, "0"); }
function VoiceAgent({ onLead }) {
  const DUR = 30;
  const [playing, setPlaying] = useState(false);
  const [t, setT] = useState(0);
  const audioRef = useRef(null);
  useEffect(() => {
    if (!playing) return;
    if (CONFIG.SAMPLE_AUDIO && audioRef.current) { audioRef.current.play().catch(() => {}); }
    const start = performance.now() - t * 1000;
    const id = setInterval(() => {
      const el = (performance.now() - start) / 1000;
      if (el >= DUR) { setT(DUR); setPlaying(false); clearInterval(id); }
      else setT(el);
    }, 100);
    return () => clearInterval(id);
  }, [playing]);
  const toggle = () => {
    if (t >= DUR) setT(0);
    if (playing && CONFIG.SAMPLE_AUDIO && audioRef.current) audioRef.current.pause();
    setPlaying((p) => !p);
  };
  const prog = t / DUR;
  return (
    <section className="band-section voice" id="voice">
      <div className="wrap voice-grid">
        <div className="reveal">
          <span className="eyebrow" style={{ display: "block", marginBottom: 16 }}>The voice assistant</span>
          <h2>Meet the voice assistant that does the chasing</h2>
          <p className="voice-body">Between visits, our voice assistant calls your patients in a calm, natural
            voice — reminding them to take readings, answering simple questions, and flagging concerns to your
            team, always within your care plan. It does the repetitive outreach that usually burns staff hours.
            It prepares the monthly check-in; your clinician completes it.</p>
          <button type="button" className="btn btn-primary voice-cta" onClick={toggle}>
            <span className={"play-ico" + (playing ? " is-playing" : "")} aria-hidden="true"></span>
            {playing ? "Pause sample" : (t > 0 && t < DUR ? "Resume sample" : "Hear a sample call")}
          </button>
        </div>
        <div className="reveal" style={{ transitionDelay: "90ms" }}>
          <div className="call-card">
            <div className="call-top">
              <div className="call-avatar"><Ico d={I.phone} /></div>
              <div className="call-meta">
                <div className="call-name">Benehab voice assistant</div>
                <div className="call-sub">Monthly check-in · sample call</div>
              </div>
              <span className={"call-live" + (playing ? " on" : "")}>{playing ? "On call" : "Sample"}</span>
            </div>
            <div className={"waveform" + (playing ? " playing" : "")} aria-hidden="true">
              {WAVE.map((h, i) => {
                const active = i / WAVE.length <= prog;
                return <span key={i} className={"wbar" + (active ? " active" : "")} style={{ height: h + "px", animationDelay: (i * 40) + "ms" }}></span>;
              })}
            </div>
            <div className="call-foot">
              <span>{fmtTime(t)}</span>
              <span className="call-note">Representative sample</span>
              <span>{fmtTime(DUR)}</span>
            </div>
            <audio ref={audioRef} src={CONFIG.SAMPLE_AUDIO || undefined} preload="none"></audio>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- footprint ---------- */
function Footprint() {
  const you = [
    "One short clinical review per enrolled patient each month — a few minutes by your own clinician, fully prepared by us",
    "Bill Medicare and keep the collections",
  ];
  const us = [
    "Patient enrollment & onboarding support",
    "Device logistics, shipping & setup",
    "Day-to-day patient engagement (voice assistant)",
    "Monitoring & documentation workflow",
    "Billing setup & automation with your biller",
  ];
  return (
    <section className="band-section alt" id="footprint">
      <div className="wrap">
        <div className="sec-head reveal">
          <span className="eyebrow">A light footprint</span>
          <h2>A light footprint for your team</h2>
          <p>You keep clinical oversight and the collections. We carry the operations.</p>
        </div>
        <div className="footprint">
          <div className="fp-card you reveal">
            <span className="fp-label">What your practice does</span>
            <h3>Two small things</h3>
            <div className="fp-list">
              {you.map((t, i) => (<div className="row" key={i}><Tick />{t}</div>))}
              <div className="row final"><Tick />That's it.</div>
            </div>
          </div>
          <div className="fp-card us reveal" style={{ transitionDelay: "90ms" }}>
            <span className="fp-label">What we handle</span>
            <h3>Everything else</h3>
            <div className="fp-list">
              {us.map((t, i) => (<div className="row" key={i}><Tick />{t}</div>))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- billing setup (small block — we organize the billing) ---------- */
function BillingSetup() {
  const rows = [
    "We map the right codes for your panel (RPM, and CCM where eligible) and set up the claim workflow together with your biller",
    "Audit-ready documentation is generated automatically for every billable patient-month",
    "You bill under your own NPI and keep 100% of the collections — we never touch them",
  ];
  return (
    <section className="amplify billing" id="billing">
      <div className="wrap amplify-in reveal">
        <span className="eyebrow">Billing support</span>
        <h2>Billing, set up with your team</h2>
        <p>RPM billing is codes, day-thresholds, and documentation. We set it up once with your biller —
          so claims go out clean from month one, without your team learning a new specialty.</p>
        <div className="billing-rows">
          {rows.map((t, i) => (<div className="row" key={i}><Tick />{t}</div>))}
        </div>
      </div>
    </section>
  );
}

/* ---------- patient value ---------- */
function PatientValue() {
  return (
    <section className="band-section" id="patients">
      <div className="wrap patient">
        <div className="reveal">
          <span className="eyebrow" style={{ display: "block", marginBottom: 16 }}>Why it works for your patients</span>
          <h2 style={{ fontSize: "clamp(28px,3.4vw,40px)", lineHeight: 1.07, marginBottom: 18 }}>Better care between visits</h2>
          <p className="body">Your chronic-care patients stay monitored and engaged year-round, not just at
            appointments. Consistent readings help catch issues earlier, improve adherence, and keep your
            patients connected to your practice between visits.</p>
        </div>
        <div className="img-col reveal" style={{ transitionDelay: "90ms" }}>
          <div className="ph"><img src="assets/patient-home.png" alt="An older patient at home checking her connected health device" /></div>
        </div>
      </div>
    </section>
  );
}

/* ---------- compliance ---------- */
const ASSURE = [
  { ico: I.doc, h: "Established CMS codes", p: "Your practice bills under long-standing Medicare RPM (and optional CCM) codes." },
  { ico: I.fee, h: "Fair-market-value fee", p: "A flat service fee for technology and support — never tied to your reimbursement." },
  { ico: I.lock, h: "HIPAA-compliant — BAA provided", p: "We operate under a Business Associate Agreement, with HIPAA-compliant handling of all patient data and call recordings." },
  { ico: I.device, h: "FDA-cleared devices (Tenovi)", p: "Patients use FDA-cleared, cellular-connected devices validated for clinical use." /* TODO: confirm cleared vs registered per device */ },
];
function Compliance({ onLead }) {
  return (
    <section className="band-section alt" id="compliance">
      <div className="wrap">
        <div className="sec-head center reveal">
          <span className="eyebrow">Compliance &amp; peace of mind</span>
          <h2>Built to be compliant — and easy to defend</h2>
        </div>
        <div className="assure">
          {ASSURE.map((a, i) => (
            <div className="assure-card reveal" key={i} style={{ transitionDelay: (i % 3 * 70) + "ms" }}>
              <div className="ico-wrap"><Ico d={a.ico} /></div>
              <div><h3>{a.h}</h3><p>{a.p}</p></div>
            </div>
          ))}
        </div>
        <div className="compliance-statement reveal">
          <Ico d={I.shield} cls="cs-ico" />
          <p>Built on established Medicare RPM/CCM codes, with a flat fair-market-value service fee
            (not tied to reimbursement), HIPAA-compliant handling, and a signed BAA.</p>
        </div>
      </div>
    </section>
  );
}

/* ---------- mid-page CTA ---------- */
function MidCTA({ onLead, text }) {
  return (
    <section className="midcta">
      <div className="wrap midcta-in reveal">
        <p>{text}</p>
        <a href="#contact" className="btn btn-primary" onClick={() => onLead("demo")}>Request a demo</a>
      </div>
    </section>
  );
}

/* ---------- amplify (switcher) — single declaration, no detail ---------- */
function Amplify({ onLead }) {
  return (
    <section className="amplify" id="amplify">
      <div className="wrap amplify-in reveal">
        <span className="eyebrow">Already running RPM?</span>
        <h2>We can make it pay more</h2>
        <p>Benehab layers on top of your existing setup — we lift patient adherence and streamline the
          workflow, so more of your patients bill each month. No rip-and-replace.</p>
        <a href="#contact" className="amplify-cta" onClick={() => onLead("demo")}>
          See what we'd add<span aria-hidden="true"> → Request a demo</span>
        </a>
      </div>
    </section>
  );
}

/* ---------- FAQ ---------- */
const FAQS = [
  { q: "Is this compliant?", a: "Yes. Your practice bills Medicare under established RPM (and optional CCM) codes and retains full clinical oversight. The service fee is a flat, fair-market-value charge for technology and support — not tied to your reimbursement. We operate under a Business Associate Agreement and will share documentation your billing and compliance teams can review." },
  { q: "Will it burden my staff?", a: "We handle enrollment, devices, day-to-day patient outreach, and the monitoring and documentation workflow. Your team keeps one short clinical review per enrolled patient each month — usually a few minutes, and we prepare everything for it. Because this monthly clinician touch is a required part of the billing, it stays with your practice; we handle essentially everything around it." },
  { q: "What about patient copays?", a: "RPM may carry a small monthly patient cost-share, like other Medicare services. Here's what your front desk actually does: we provide the consent and cost-share script, your team explains it at enrollment, and we handle disenrollments — so there are no surprises for your patients and no guesswork for your staff." },
  { q: "Are the devices reliable?", a: "Patients receive FDA-cleared, cellular-connected devices (by Tenovi) that transmit readings automatically through a cellular hub — no smartphone, no app, no Wi-Fi, no patient setup." },
  { q: "How soon do we see revenue?", a: "Most practices begin enrolling within weeks. Billing starts the month devices are set up and monitoring thresholds are met, and revenue ramps as your enrolled panel grows." },
];
function FaqItem({ q, a, open, onClick }) {
  const ref = useRef(null);
  const [h, setH] = useState(0);
  useEffect(() => { setH(open && ref.current ? ref.current.scrollHeight : 0); }, [open]);
  return (
    <div className={"faq-item" + (open ? " open" : "")}>
      <button className="faq-q" aria-expanded={open} onClick={onClick}>
        {q}<svg className="chev" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d={I.chev} /></svg>
      </button>
      <div className="faq-a" style={{ height: h }}><div className="inner" ref={ref}>{a}</div></div>
    </div>
  );
}
function Faq() {
  const [open, setOpen] = useState(0);
  return (
    <section className="band-section" id="faq">
      <div className="wrap">
        <div className="sec-head center reveal"><span className="eyebrow">FAQ</span><h2>Questions practices ask us</h2></div>
        <div className="faq reveal">
          {FAQS.map((f, i) => (
            <FaqItem key={i} q={f.q} a={f.a} open={open === i} onClick={() => setOpen(open === i ? -1 : i)} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Demo form (primary path) + calendar placeholder ---------- */
function DemoForm() {
  const [f, setF] = useState({ name: "", practice: "", role: "", email: "", phone: "", panel: "", notes: "" });
  const [consent, setConsent] = useState(false);
  const [status, setStatus] = useState("idle");
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    try {
      // TODO: wire backend (Phase 2b) — notify sales email + Airtable
      await fetch(CONFIG.LEAD_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...f, consent, source: "demo" }),
      });
    } catch (err) { /* stubbed endpoint in prototype — ignore */ }
    setStatus("done");
  };
  return (
    <section className="cta-band" id="contact">
      <div className="wrap cta-grid">
        <div className="reveal">
          <span className="eyebrow">Request a demo</span>
          <h2>See Benehab RPM for your practice</h2>
          <p className="lede">A 20-minute walkthrough — your numbers, the workflow, and how billing works.
            No obligation.</p>
          <div className="reassure">
            <span className="item"><Tick />Your estimated numbers, walked through live</span>
            <span className="item"><Tick />The workflow and how billing works</span>
            <span className="item"><Tick />You keep clinical oversight and collections</span>
          </div>
        </div>

        {status === "done" ? (
          <div className="lead-card lead-done reveal">
            <div className="done-mark"><Tick cls="done-tick" /></div>
            <h3>Thanks — pick a time below, or we'll reach out within one business day.</h3>
            {/* TODO: embed Cal.com/Calendly (Phase 2b) */}
            <div className="cal-embed">
              <Ico d={I.cal} cls="cal-ico" />
              <span className="cal-label">Calendar booking embeds here</span>
              <span className="cal-sub">Cal.com / Calendly · placeholder</span>
            </div>
          </div>
        ) : (
          <form className="lead-card reveal" onSubmit={submit}
                action={"mailto:" + CONFIG.BRAND.email} method="post" encType="text/plain"
                style={{ transitionDelay: "80ms" }}>
            <h3>Book your walkthrough</h3>
            <p className="sub">Tell us a little about your practice and we'll tailor the demo.</p>
            <input type="hidden" name="source" value="demo" />
            <div className="field-row">
              <div className="field">
                <label htmlFor="df-name">Full name</label>
                <input id="df-name" name="name" required value={f.name} onChange={set("name")} placeholder="Dr. Jane Smith" />
              </div>
              <div className="field">
                <label htmlFor="df-role">Your role</label>
                <input id="df-role" name="role" value={f.role} onChange={set("role")} placeholder="Physician / Office manager" />
              </div>
            </div>
            <div className="field">
              <label htmlFor="df-practice">Practice name</label>
              <input id="df-practice" name="practice" required value={f.practice} onChange={set("practice")} placeholder="Riverside Internal Medicine" />
            </div>
            <div className="field-row">
              <div className="field">
                <label htmlFor="df-email">Work email</label>
                <input id="df-email" name="email" type="email" required value={f.email} onChange={set("email")} placeholder="jane@practice.com" />
              </div>
              <div className="field">
                <label htmlFor="df-phone">Phone <span className="opt">(optional)</span></label>
                <input id="df-phone" name="phone" type="tel" value={f.phone} onChange={set("phone")} placeholder="(555) 012-3456" />
              </div>
            </div>
            <div className="field">
              <label htmlFor="df-panel">Approx. patient panel</label>
              <input id="df-panel" name="panel" inputMode="numeric" value={f.panel} onChange={set("panel")} placeholder="2,000" />
            </div>
            <div className="field">
              <label htmlFor="df-notes">Anything specific you'd like to cover? <span className="opt">(optional)</span></label>
              <input id="df-notes" name="notes" value={f.notes} onChange={set("notes")} placeholder="Billing setup, compliance, devices…" />
            </div>
            <label className="consent">
              <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} required />
              <span>I agree to be contacted about Benehab RPM.</span>
            </label>
            <button type="submit" className="btn btn-primary" disabled={status === "sending"}>
              {status === "sending" ? "Sending…" : "Request a demo"}
            </button>
            <p className="form-note">No obligation. We'll never share your details.</p>
          </form>
        )}
      </div>
    </section>
  );
}

/* ---------- footer ---------- */
const DISCLAIMER_FOOT =
  "The figures shown on this page are illustrative estimates, not a guarantee of payment. They are shown at full " +
  "enrollment assuming strong monthly utilization; not every enrolled patient bills every month, and typical results " +
  "are lower. Actual Medicare reimbursement depends on your MAC locality, each patient's eligibility, and correct " +
  "billing — for which your practice is responsible. The service fee is a flat charge for technology and support at " +
  "fair market value and is not contingent on the volume or value of any reimbursement. This page is informational " +
  "and is not legal, billing, or clinical advice.";
function Footer() {
  const b = CONFIG.BRAND;
  return (
    <footer className="site-footer">
      <div className="wrap">
        <div className="top">
          <div>
            <div className="brand"><span className="mark"></span><span>Benehab RPM</span></div>
            <div className="f-cobrand">A <b>Benehab</b> product · benehab.com</div>
          </div>
          <div className="f-contact">
            <a href="#contact">Request a demo</a><br />
            <a href={"mailto:" + b.email}>{b.email}</a>
            {b.phone ? <span><br /><a href={"tel:" + b.phone.replace(/[^\d+]/g, "")}>{b.phone}</a></span> : null}
          </div>
        </div>
        <p className="disclaimer">{DISCLAIMER_FOOT}</p>
        <p className="copyright">© 2026 {b.legal}. Remote Patient Monitoring, fully managed. All rights reserved.</p>
      </div>
    </footer>
  );
}

/* ---------- floating mobile CTA ---------- */
function FloatingCTA({ onLead }) {
  return (
    <a href="#contact" className="floating-cta" onClick={() => onLead("demo")}>Request a demo</a>
  );
}

/* ---------- reveal-on-scroll ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) { els.forEach((e) => e.classList.add("in")); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => { if (en.isIntersecting) { en.target.classList.add("in"); io.unobserve(en.target); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    els.forEach((e) => io.observe(e));
    return () => io.disconnect();
  }, []);
}

/* ---------- estimate modal (3 fields -> opens the personal P&L report) ---------- */
function EstimateModal({ open, patients, onClose }) {
  const [practice, setPractice] = useState("");
  const [chronic, setChronic] = useState("");
  const [newpm, setNewpm] = useState("");
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const [emailed, setEmailed] = useState(false);
  useEffect(() => {
    if (open) { setChronic(String(patients)); setSent(false); setEmailed(false); }
  }, [open]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);
  if (!open) return null;
  const submit = (e) => {
    e.preventDefault();
    const c = Math.max(10, Number(chronic) || 0);
    const n = Math.max(1, Number(newpm) || 0);
    const url = "report.html?chronic=" + c + "&newpm=" + n +
      (practice.trim() ? "&practice=" + encodeURIComponent(practice.trim()) : "");
    // open synchronously (popup-blocker safe), then capture the lead + email the link in the background
    window.open(url, "_blank", "noopener");
    setSent(true);
    fetch("/api/lead", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, practice: practice.trim(), chronic: c, newpm: n }),
    }).then((r) => r.json()).then((d) => { if (d && d.emailed) setEmailed(true); }).catch(() => {});
  };
  return (
    <div className="modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-card" role="dialog" aria-modal="true" aria-label="Get your detailed estimate">
        <button type="button" className="modal-x" aria-label="Close" onClick={onClose}>×</button>
        {sent ? (
          <div className="modal-done">
            <h3>Your estimate is ready</h3>
            <p>It opened in a new tab — use “Print / Save as PDF” there to keep a copy for your team.{emailed ? " We've also emailed you the link." : ""}</p>
            <a className="btn btn-primary" href="#contact" onClick={onClose}>Request a demo</a>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h3>Get your detailed estimate (PDF)</h3>
            <p className="modal-sub">A month-by-month P&amp;L projection for your practice. A few quick fields:</p>
            <div className="field">
              <label htmlFor="em-practice">Practice name</label>
              <input id="em-practice" required value={practice}
                     onChange={(e) => setPractice(e.target.value)} placeholder="Riverside Internal Medicine" />
            </div>
            <div className="field">
              <label htmlFor="em-chronic">Patients with chronic conditions</label>
              <input id="em-chronic" inputMode="numeric" required value={chronic}
                     onChange={(e) => setChronic(e.target.value)} placeholder="e.g. 540" />
            </div>
            <div className="field">
              <label htmlFor="em-newpm">New patients joining per month</label>
              <input id="em-newpm" inputMode="numeric" required value={newpm}
                     onChange={(e) => setNewpm(e.target.value)} placeholder="e.g. 25" />
            </div>
            <div className="field">
              <label htmlFor="em-email">Work email</label>
              <input id="em-email" type="email" required value={email}
                     onChange={(e) => setEmail(e.target.value)} placeholder="jane@practice.com" />
            </div>
            <button type="submit" className="btn btn-primary modal-go">Get my PDF<span aria-hidden="true"> →</span></button>
            <p className="form-note">By submitting, you agree to be contacted about Benehab RPM. No spam.</p>
          </form>
        )}
      </div>
    </div>
  );
}

function App() {
  useReveal();
  const [patients, setPatients] = useState(CONFIG.DEFAULT_PATIENTS);
  const [ccmPct, setCcmPct] = useState(CONFIG.DEFAULT_CCM_PCT);
  const [estOpen, setEstOpen] = useState(false);
  const onLead = () => {}; // demo is the single conversion path now
  return (
    <div className="site">
      <Announce />
      <Header onLead={onLead} />
      <Hero patients={patients} ccmPct={ccmPct} setPatients={setPatients} setCcm={setCcmPct} onLead={onLead}
            onEstimate={() => setEstOpen(true)} />
      <HowItWorks />
      <VoiceAgent onLead={onLead} />
      <Footprint />
      <BillingSetup />
      <PatientValue />
      <Compliance onLead={onLead} />
      <MidCTA onLead={onLead} text="Ready to see your numbers?" />
      <Amplify onLead={onLead} />
      <Faq />
      <DemoForm />
      <Footer />
      <FloatingCTA onLead={onLead} />
      <EstimateModal open={estOpen} patients={patients} onClose={() => setEstOpen(false)} />
    </div>
  );
}

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