/* sections-bottom.jsx — Dashboard preview, Comparison, Security, CTA, Footer */

/* ───────────────────────── DASHBOARD PREVIEW ───────────────────────── */
function KpiTile({ label, value, delta, up, spark, color, inView, delay }) {
  return (
    <Reveal className="kpi" delay={delay}>
      <div className="kpi-head">
        <span className="kpi-l">{label}</span>
        <span className={`kpi-d ${up ? "up" : "down"}`}>{up ? "▲" : "▼"} {delta}</span>
      </div>
      <div className="kpi-v">{value}</div>
      <Spark data={spark} color={color} inView={inView} />
    </Reveal>
  );
}

function DashboardPreview() {
  const [ref, seen] = useInView({ threshold: 0.25 });
  const [range, setRange] = useState("90d");
  const ranges = ["7d", "30d", "90d", "365d"];
  return (
    <section className="sec-pad dashboard" id="dashboard">
      <div className="wrap">
        <div className="sec-head sec-head-center">
          <Reveal><span className="eyebrow"><span className="dot"></span>The dashboard</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title">Your whole clinic's cash flow, at a glance</Reveal>
          <Reveal as="p" delay={140} className="sec-sub">Collections, denials, aging, and per-payer performance — recomputed the moment you move the time window. This is the screen your billing team actually lives in.</Reveal>
        </div>

        <Reveal className="dash-frame" delay={120}>
          <div ref={ref} className="dash-window">
            <div className="dash-chrome">
              <div className="mini-dots"><span></span><span></span><span></span></div>
              <span className="dash-url mono">app.datamed.health</span>
              <div className="dash-range">
                {ranges.map((r) => (
                  <button key={r} className={`rg ${range === r ? "on" : ""}`} onClick={() => setRange(r)}>{r}</button>
                ))}
              </div>
            </div>

            <div className="dash-grid">
              <div className="dash-kpis">
                <KpiTile label="Collected (net)" value="$128,440" delta="12.6%" up spark={[20,28,24,33,30,42,38,52,49,61]} color="#16CFBD" inView={seen} delay={0}/>
                <KpiTile label="Billed" value="$184,020" delta="8.2%" up spark={[30,34,31,40,44,50,47,58,63,70]} color="#2FB1F0" inView={seen} delay={80}/>
                <KpiTile label="Denial rate" value="4.1%" delta="1.3%" up spark={[9,8,8.5,7,7.2,6,5.4,5,4.6,4.1]} color="#0EA371" inView={seen} delay={160}/>
                <KpiTile label="Avg days to pay" value="18.4" delta="3.1d" up spark={[28,27,26,24,23,22,21,20,19,18.4]} color="#5C6CF2" inView={seen} delay={240}/>
              </div>

              <div className="dash-main">
                <div className="dpanel dpanel-area">
                  <div className="dpanel-head">
                    <span className="dpanel-t">Billed vs. collected</span>
                    <span className="dpanel-legend"><span className="lg sky"></span>Billed<span className="lg teal"></span>Collected</span>
                  </div>
                  <div className="dpanel-chart"><AreaChart inView={seen} /></div>
                </div>
                <div className="dpanel dpanel-donut">
                  <div className="dpanel-head"><span className="dpanel-t">Status mix</span></div>
                  <Donut inView={seen} />
                </div>
              </div>

              <div className="dpanel dpanel-bars">
                <div className="dpanel-head"><span className="dpanel-t">Top payers by volume</span><span className="dpanel-sub mono">last {range}</span></div>
                <Bars inView={seen} />
              </div>
            </div>
          </div>
          <div className="dash-reflect" aria-hidden="true"></div>
        </Reveal>
      </div>
    </section>
  );
}

/* ───────────────────────── COMPARISON ───────────────────────── */
const CMP_ROWS = [
  ["Eligibility, claims, ERA & payments in one system", "full", "none", "none"],
  ["Automatic ERA → claim reconciliation", "full", "partial", "none"],
  ["Handles payer member-id quirks & split lines", "full", "none", "none"],
  ["Real-time cash-flow & denial analytics", "full", "partial", "none"],
  ["Purpose-built for ABA workflows", "full", "none", "partial"],
  ["Per-field PHI encryption + audit trail", "full", "partial", "none"],
  ["No per-claim clearinghouse markup", "full", "none", "full"],
];
const CMP_COLS = ["DataMed", "Generic billing tool", "Spreadsheets + clearinghouse"];

function Cell({ kind }) {
  if (kind === "full") return <span className="cmp-cell full"><I.check/></span>;
  if (kind === "partial") return <span className="cmp-cell partial">Partial</span>;
  return <span className="cmp-cell none"><I.x/></span>;
}

function Comparison() {
  const [hl, setHl] = useState(0);
  return (
    <section className="sec-pad compare" id="compare">
      <div className="wrap">
        <div className="sec-head sec-head-center">
          <Reveal><span className="eyebrow"><span className="dot"></span>Why DataMed</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title">What you give up everywhere else</Reveal>
          <Reveal as="p" delay={140} className="sec-sub">Generic billing tools weren't built for ABA, and spreadsheets can't reconcile a split-line ERA. Here's how the approaches compare.</Reveal>
        </div>

        <Reveal className="cmp-wrap" delay={120}>
          <table className="cmp-table">
            <thead>
              <tr>
                <th className="cmp-feat"></th>
                {CMP_COLS.map((c, i) => (
                  <th key={c} className={`cmp-col ${i === 0 ? "cmp-us" : ""} ${hl === i ? "hl" : ""}`}
                      onMouseEnter={() => setHl(i)}>
                    {i === 0 && <span className="cmp-badge"><LogoMark size={20}/></span>}
                    <span>{c}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {CMP_ROWS.map((row, ri) => (
                <tr key={ri}>
                  <td className="cmp-feat">{row[0]}</td>
                  {[1, 2, 3].map((ci) => (
                    <td key={ci} className={`${ci - 1 === 0 ? "cmp-us" : ""} ${hl === ci - 1 ? "hl" : ""}`}
                        onMouseEnter={() => setHl(ci - 1)}>
                      <Cell kind={row[ci]} />
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </Reveal>
      </div>
    </section>
  );
}

/* ───────────────────────── SECURITY ───────────────────────── */
function Security() {
  const items = [
    { icon: "lock", t: "Encrypted at rest", b: "Member IDs, names, DOBs and addresses sealed with per-field Fernet keys." },
    { icon: "shield", t: "Audited end-to-end", b: "Every submit, void, rebill and payment writes an immutable audit record." },
    { icon: "doc", t: "BAA in place", b: "Healthcare-grade email and clearinghouse integrations under signed BAAs." },
  ];
  return (
    <section className="sec-pad security">
      <div className="wrap sec-inner">
        <div className="sec-copy">
          <Reveal><span className="eyebrow eyebrow-light"><span className="dot"></span>Security & compliance</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title sec-title-light">PHI handled the way regulators expect</Reveal>
          <Reveal as="p" delay={140} className="sec-sub sec-sub-light">DataMed runs in production against real protected health information — so security isn't a feature page, it's the foundation.</Reveal>
        </div>
        <div className="sec-cards">
          {items.map((it, i) => {
            const Ico = I[it.icon];
            return (
              <Reveal key={it.t} className="sec-card" delay={i * 100}>
                <div className="sec-card-ic"><Ico/></div>
                <div>
                  <h4 className="sec-card-t">{it.t}</h4>
                  <p className="sec-card-b">{it.b}</p>
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────── CTA / CONTACT ───────────────────────── */
const DEMO_NOTIFY_EMAIL = "hanad@datamed-solutions.live";
const DEMO_NOTIFY_ENDPOINT = `https://formsubmit.co/ajax/${encodeURIComponent(DEMO_NOTIFY_EMAIL)}`;

function CTA() {
  const [form, setForm] = useState({ name: "", clinic: "", email: "" });
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [err, setErr] = useState({});
  const [submitErr, setSubmitErr] = useState("");
  const upd = (k) => (e) => { setForm((f) => ({ ...f, [k]: e.target.value })); setErr((x) => ({ ...x, [k]: false })); };
  const submit = async (e) => {
    e.preventDefault();
    const next = {};
    if (!form.name.trim()) next.name = true;
    if (!form.clinic.trim()) next.clinic = true;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) next.email = true;
    setErr(next);
    if (Object.keys(next).length > 0) return;

    setSubmitting(true);
    setSubmitErr("");
    try {
      const res = await fetch(DEMO_NOTIFY_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          name: form.name,
          clinic: form.clinic,
          email: form.email,
          _subject: `New demo request — ${form.clinic} (${form.name})`,
          _template: "table",
          _captcha: "false",
          _replyto: form.email,
        }),
      });
      const data = await res.json().catch(() => ({}));
      const msg = (data && data.message) || "";
      // FormSubmit returns success:"false" with an activation notice on the very
      // first submission to a new address. Treat that as a soft success — the
      // submission is captured once the owner clicks the activation link.
      if (/activat/i.test(msg)) {
        setSent(true);
        return;
      }
      if (!res.ok || (data && data.success === "false")) {
        throw new Error(msg || `Request failed (${res.status})`);
      }
      setSent(true);
    } catch (ex) {
      setSubmitErr("We couldn't send that just now. Please try again or email us directly at " + DEMO_NOTIFY_EMAIL + ".");
    } finally {
      setSubmitting(false);
    }
  };
  return (
    <section className="sec-pad cta" id="cta">
      <div className="wrap">
        <Reveal className="cta-card">
          <div className="cta-bg" aria-hidden="true"><div className="cta-orb"></div><div className="cta-orb cta-orb-2"></div></div>
          <div className="cta-grid">
            <div className="cta-copy">
              <span className="eyebrow eyebrow-light"><span className="dot"></span>Get started</span>
              <h2 className="cta-title">See DataMed run on your own claims</h2>
              <p className="cta-sub">Book a 30-minute walkthrough. We'll load a sample of your billing export and show the full cycle — eligibility to reconciled payment — live.</p>
              <ul className="cta-list">
                {["No rip-and-replace — import your existing CSV exports", "See your real denial rate and aging in minutes", "Built and supported by an ABA billing team"].map((t) => (
                  <li key={t}><span className="cta-tick"><I.check/></span>{t}</li>
                ))}
              </ul>
            </div>
            <div className="cta-form-wrap">
              {!sent ? (
                <form className="cta-form" onSubmit={submit} noValidate>
                  <h3 className="cta-form-t">Request a demo</h3>
                  <label className={`field ${err.name ? "bad" : ""}`}>
                    <span>Your name</span>
                    <input value={form.name} onChange={upd("name")} placeholder="Jordan Ellis" />
                  </label>
                  <label className={`field ${err.clinic ? "bad" : ""}`}>
                    <span>Clinic / organization</span>
                    <input value={form.clinic} onChange={upd("clinic")} placeholder="Riverside ABA Therapy" />
                  </label>
                  <label className={`field ${err.email ? "bad" : ""}`}>
                    <span>Work email</span>
                    <input value={form.email} onChange={upd("email")} placeholder="you@clinic.com" />
                    {err.email && <em className="field-err">Enter a valid email address</em>}
                  </label>
                  <button type="submit" className="btn btn-primary btn-lg cta-submit" disabled={submitting}>
                    {submitting ? "Sending…" : <>Book my demo <I.arrow/></>}
                  </button>
                  {submitErr && <p className="cta-fine" style={{ color: "var(--danger)" }}>{submitErr}</p>}
                  <p className="cta-fine">We'll never share your information. PHI never required to start.</p>
                </form>
              ) : (
                <div className="cta-done">
                  <div className="cta-done-ic"><I.check/></div>
                  <h3>You're on the list, {form.name.split(" ")[0]}.</h3>
                  <p>We'll reach out to <strong>{form.email}</strong> within one business day to schedule your walkthrough.</p>
                  <button className="btn btn-ghost" onClick={() => { setSent(false); setForm({ name: "", clinic: "", email: "" }); }}>Submit another</button>
                </div>
              )}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ───────────────────────── FOOTER ───────────────────────── */
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap footer-inner">
        <div className="footer-brand">
          <Wordmark />
          <p className="footer-tag">ABA claims automation, end to end.</p>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <span className="footer-h">Platform</span>
            <a href="#features">Features</a>
            <a href="#lifecycle">How it works</a>
            <a href="#dashboard">Dashboard</a>
            <a href="#compare">Why DataMed</a>
          </div>
          <div className="footer-col">
            <span className="footer-h">Transactions</span>
            <a href="#lifecycle">270 / 271 Eligibility</a>
            <a href="#lifecycle">837P Claims</a>
            <a href="#lifecycle">276 / 277 Status</a>
            <a href="#lifecycle">835 Remittance</a>
          </div>
          <div className="footer-col">
            <span className="footer-h">Company</span>
            <a href="#cta">Book a demo</a>
            <a href="#cta">Contact</a>
            <a href="#top">Security</a>
          </div>
        </div>
      </div>
      <div className="wrap footer-base">
        <span>© 2026 DataMed</span>
        <span className="mono">Live in production · Stedi connected</span>
      </div>
    </footer>
  );
}

Object.assign(window, { DashboardPreview, Comparison, Security, CTA, Footer });
