/* sections-top.jsx — Nav, Hero, Features, Lifecycle */

/* ───────────────────────── NAV ───────────────────────── */
function Nav({ onCta }) {
  const [solid, setSolid] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    ["Platform", "#features"],
    ["How it works", "#lifecycle"],
    ["Dashboard", "#dashboard"],
    ["Why DataMed", "#compare"],
  ];
  return (
    <header className={`nav ${solid ? "nav-solid" : ""}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="nav-brand"><Wordmark /></a>
        <nav className="nav-links">
          {links.map(([l, h]) => <a key={h} href={h}>{l}</a>)}
        </nav>
        <div className="nav-actions">
          <a href="#cta" className="nav-signin">Sign in</a>
          <button className="btn btn-primary" onClick={onCta}>Book a demo</button>
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="Menu"><I.menu/></button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile">
          {links.map(([l, h]) => <a key={h} href={h} onClick={() => setOpen(false)}>{l}</a>)}
          <a href="#cta" onClick={() => setOpen(false)} className="nav-mobile-cta">Book a demo</a>
        </div>
      )}
    </header>
  );
}

/* ───────────────────────── HERO ───────────────────────── */
function MiniDashboard() {
  const [ref, seen] = useInView({ threshold: 0.3 });
  return (
    <div className="mini-dash" ref={ref}>
      <div className="mini-top">
        <div className="mini-dots"><span></span><span></span><span></span></div>
        <span className="mini-title mono">app.datamed.health/dashboard</span>
      </div>
      <div className="mini-body">
        <div className="mini-kpis">
          {[
            { l: "Collected", v: "$128.4k", d: "+12.6%", up: true },
            { l: "Billed", v: "$184.0k", d: "30d", up: true },
            { l: "Denial rate", v: "4.1%", d: "-1.3%", up: true },
          ].map((k) => (
            <div key={k.l} className="mini-kpi">
              <span className="mk-l">{k.l}</span>
              <span className="mk-v">{k.v}</span>
              <span className={`mk-d ${k.up ? "up" : "down"}`}>{k.d}</span>
            </div>
          ))}
        </div>
        <div className="mini-chart"><AreaChart inView={seen} /></div>
        <div className="mini-foot">
          <div className="mini-legend"><span className="lg sky"></span>Billed<span className="lg teal"></span>Collected</div>
          <span className="mini-live"><span className="live-dot"></span>Live · Stedi connected</span>
        </div>
      </div>
    </div>
  );
}

const PIPE = [
  { icon: "search", label: "Eligibility" },
  { icon: "send", label: "Submit 837P" },
  { icon: "pulse", label: "Status 277" },
  { icon: "doc", label: "ERA 835" },
  { icon: "match", label: "Reconcile" },
  { icon: "wallet", label: "Paid" },
];

function PipelineStrip() {
  const [ref, seen] = useInView({ threshold: 0.3 });
  return (
    <div className={`pipe ${seen ? "in" : ""}`} ref={ref}>
      {PIPE.map((s, i) => {
        const Ico = I[s.icon];
        return (
          <React.Fragment key={s.label}>
            <div className="pipe-node" style={{ transitionDelay: `${i * 110}ms` }}>
              <div className="pipe-ic"><Ico/></div>
              <span className="pipe-lb">{s.label}</span>
            </div>
            {i < PIPE.length - 1 && <div className="pipe-link"><span></span></div>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function Hero({ variant, onCta }) {
  const centered = variant === "centered";
  return (
    <section className={`hero ${centered ? "hero-centered" : "hero-split"}`} id="top">
      <div className="hero-bg" aria-hidden="true">
        <div className="hero-orb orb-a"></div>
        <div className="hero-orb orb-b"></div>
        <div className="hero-grid"></div>
      </div>
      <div className="wrap hero-inner">
        <div className="hero-copy">
          <Reveal as="div"><span className="eyebrow"><span className="dot"></span>Built for ABA billing teams</span></Reveal>
          <Reveal as="h1" delay={80} className="hero-h1">
            The entire claims revenue cycle, <span className="grad-text">in one platform.</span>
          </Reveal>
          <Reveal as="p" delay={160} className="hero-sub">
            DataMed runs eligibility, claim submission, status checks, and ERA reconciliation end-to-end — then surfaces cash flow and denials on a live dashboard. Purpose-built for ABA clinics, not adapted from generic billing software.
          </Reveal>
          <Reveal as="div" delay={240} className="hero-cta">
            <button className="btn btn-primary btn-lg" onClick={onCta}>Book a demo <I.arrow/></button>
            <a href="#lifecycle" className="btn btn-ghost btn-lg">See how it works</a>
          </Reveal>
          <Reveal as="div" delay={320} className="hero-trust">
            {["837P · 835 · 270/271 · 276/277", "PHI encrypted at rest", "Live in production"].map((t) => (
              <span key={t} className="trust-chip"><I.check/> {t}</span>
            ))}
          </Reveal>
        </div>
        {!centered && (
          <Reveal className="hero-visual" delay={200}>
            <MiniDashboard />
          </Reveal>
        )}
      </div>
      {centered && (
        <div className="wrap hero-centered-visual">
          <Reveal delay={360}><PipelineStrip /></Reveal>
          <Reveal delay={120} className="hero-centered-dash"><MiniDashboard /></Reveal>
        </div>
      )}
    </section>
  );
}

/* ───────────────────────── FEATURES (bento) ───────────────────────── */
const FEATURES = [
  {
    key: "cycle", icon: "cycle", tone: "brand", span: "wide",
    title: "The full revenue cycle in one place",
    body: "Eligibility, claim submission, status tracking, ERA posting, and patient balances live together — no exporting between four disconnected tools. One source of truth from intake to payment.",
    chips: ["Eligibility → Claims → ERA → Payments"],
  },
  {
    key: "match", icon: "match", tone: "teal",
    title: "Automatic ERA reconciliation",
    body: "Smart matching links every 835 line to the right claim — even when payers strip member-id prefixes or split lines by date. No more manual posting.",
  },
  {
    key: "chart", icon: "chart", tone: "sky",
    title: "Real-time cash-flow analytics",
    body: "A live dashboard for collections, denials, aging, and per-payer performance — with a range slider that re-frames every chart instantly.",
  },
  {
    key: "shield", icon: "shield", tone: "indigo",
    title: "HIPAA-grade PHI security",
    body: "Member IDs, names, and DOBs are encrypted at rest with per-field keys. Full audit trail on every action.",
  },
  {
    key: "network", icon: "network", tone: "brand",
    title: "All four EDI transactions, wired",
    body: "270/271 eligibility, 837P claims, 276/277 status, and 835 remittance — connected through a single clearinghouse integration.",
  },
];

function FeatureCard({ f, i }) {
  return (
    <Reveal className={`fcard ${f.span === "wide" ? "fcard-wide" : ""}`} delay={(i % 3) * 90}>
      <IconBadge icon={f.icon} tone={f.tone} />
      <h3 className="fcard-t">{f.title}</h3>
      <p className="fcard-b">{f.body}</p>
      {f.chips && (
        <div className="fcard-chips">
          {f.chips.map((c) => <span key={c} className="fchip mono">{c}</span>)}
        </div>
      )}
      <div className="fcard-glow" aria-hidden="true"></div>
    </Reveal>
  );
}

function Features() {
  return (
    <section className="sec-pad features" id="features">
      <div className="wrap">
        <div className="sec-head">
          <Reveal><span className="eyebrow"><span className="dot"></span>What makes it different</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title">Everything billing teams stitch together — already connected</Reveal>
          <Reveal as="p" delay={140} className="sec-sub">Most clinics juggle a clearinghouse, a spreadsheet, and a dashboard that never quite agree. DataMed collapses them into one system designed around how ABA claims actually move.</Reveal>
        </div>
        <div className="bento">
          {FEATURES.map((f, i) => <FeatureCard key={f.key} f={f} i={i} />)}
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────── LIFECYCLE (animated walkthrough) ───────────────────────── */
const STAGES = [
  { icon: "search", code: "270 / 271", title: "Confirm eligibility", body: "Run a real-time eligibility check on the member and payer before a single session is billed — coverage, copay, and auth limits surface instantly.", metric: ["Coverage", "Active"], tone: "sky" },
  { icon: "send", code: "837P", title: "Submit the claim", body: "Upload a CSV and DataMed converts it to a compliant 837P professional claim, validates it, and submits to the payer through Stedi.", metric: ["Status", "Submitted"], tone: "brand" },
  { icon: "pulse", code: "276 / 277", title: "Track claim status", body: "Automated status checks poll the payer. When a 277 lags behind reality, DataMed cross-checks remittance so a paid claim is never shown as pending.", metric: ["Claim", "Accepted"], tone: "indigo" },
  { icon: "doc", code: "835", title: "Import the ERA", body: "Drop in the 835 remittance file. The parser walks every segment and emits one clean record per service line — CLP and SVC adjustments handled.", metric: ["ERA lines", "Parsed"], tone: "teal" },
  { icon: "match", code: "MATCH", title: "Reconcile automatically", body: "Three matching strategies link each remittance line to its claim — normalizing member-id quirks and dependent suffixes that break naive matching.", metric: ["Matched", "100%"], tone: "sky" },
  { icon: "wallet", code: "PAID", title: "See the money land", body: "Claim totals sum across every linked ERA line, patient responsibility is computed, and the dashboard reflects collected cash in real time.", metric: ["Collected", "+$4,210"], tone: "brand" },
];

function Lifecycle() {
  const [active, setActive] = useState(0);
  const [ref, seen] = useInView({ threshold: 0.35 });
  const [auto, setAuto] = useState(true);
  useEffect(() => {
    if (!seen || !auto) return;
    const id = setInterval(() => setActive((a) => (a + 1) % STAGES.length), 3200);
    return () => clearInterval(id);
  }, [seen, auto]);
  const stop = (i) => { setAuto(false); setActive(i); };
  const s = STAGES[active];
  const Ico = I[s.icon];
  return (
    <section className="sec-pad lifecycle" id="lifecycle" ref={ref}>
      <div className="wrap">
        <div className="sec-head sec-head-center">
          <Reveal><span className="eyebrow"><span className="dot"></span>How it works</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title">One claim, start to finish</Reveal>
          <Reveal as="p" delay={140} className="sec-sub">Follow a single claim through the lifecycle DataMed automates — from the first eligibility ping to cash in the bank.</Reveal>
        </div>

        <div className="lc">
          <div className="lc-rail">
            <div className="lc-rail-line"><div className="lc-rail-fill" style={{ height: `${(active / (STAGES.length - 1)) * 100}%` }}></div></div>
            {STAGES.map((st, i) => {
              const StIco = I[st.icon];
              return (
                <button key={i} className={`lc-step ${i === active ? "on" : ""} ${i < active ? "done" : ""}`} onClick={() => stop(i)}>
                  <span className="lc-node"><StIco/></span>
                  <span className="lc-step-tx">
                    <span className="lc-step-code mono">{st.code}</span>
                    <span className="lc-step-title">{st.title}</span>
                  </span>
                </button>
              );
            })}
          </div>

          <div className="lc-stage">
            <div className="lc-card" key={active}>
              <div className={`lc-card-ic ibadge-${s.tone}`}><Ico/></div>
              <span className="lc-card-code mono">{s.code}</span>
              <h3 className="lc-card-title">{s.title}</h3>
              <p className="lc-card-body">{s.body}</p>
              <div className="lc-card-metric">
                <span className="lcm-l">{s.metric[0]}</span>
                <span className="lcm-v">{s.metric[1]} <span className="lcm-check"><I.check/></span></span>
              </div>
              <div className="lc-progress">
                {STAGES.map((_, i) => <span key={i} className={i === active ? "on" : ""}></span>)}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Features, Lifecycle });
