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

/* ───────────────────────── NAV ───────────────────────── */
function Nav({ onCta, route }) {
  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 navLinks = [
    ["Home", "#top", "home"],
    ["Services", "#solutions", "services"],
    ["How it works", "#lifecycle", "how-it-works"],
    ["Denial Management", "#denial-hero", "denial-management"],
    ["Custom reporting", "#dashboard", "custom-reporting"],
    ["Why DataMed", "#compare", "why-datamed"],
  ];
  return (
    <header className={`nav ${solid ? "nav-solid" : ""}`}>
      <div className="nav-topbar">
        <div className="wrap nav-topbar-inner">
          <a href="tel:+14698781620" className="nav-phone">
            <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5.5 4h3l1.7 4.2-2 1.6a13 13 0 0 0 5.9 5.9l1.6-2L20 15.4v3.1A1.7 1.7 0 0 1 18.2 20 15.4 15.4 0 0 1 4 5.8 1.7 1.7 0 0 1 5.5 4z" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round"/></svg>
            (469) 878-1620
          </a>
        </div>
      </div>
      <div className="wrap nav-inner">
        <a href="#top" className="nav-brand"><Wordmark /></a>
        <nav className="nav-links">
          {navLinks.map(([l, h, r]) => <a key={h} href={h} className={route === r ? "active" : ""}>{l}</a>)}
        </nav>
        <div className="nav-actions">
          <button className="btn btn-primary" onClick={onCta}>Schedule a Consultation</button>
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label={open ? "Close menu" : "Menu"} aria-expanded={open}>{open ? <I.x/> : <I.menu/>}</button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile">
          {navLinks.map(([l, h, r]) => <a key={h} href={h} className={route === r ? "active" : ""} onClick={() => setOpen(false)}>{l}</a>)}
          <a href="#cta" onClick={() => setOpen(false)} className="nav-mobile-cta">Schedule a Consultation</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: "1.6%", d: "-0.03%", 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</span>
        </div>
      </div>
    </div>
  );
}

const PIPE = [
  { icon: "search", label: "Eligibility" },
  { icon: "send", label: "DataMed files 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 providers</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 handles eligibility, claim submission, status checks, and ERA reconciliation end-to-end, then surfaces your cash flow and denials on a live dashboard. Built for ABA billing, not a one-size-fits-all billing tool.
          </Reveal>
          <Reveal as="div" delay={240} className="hero-cta">
            <a href="#/services" className="btn btn-primary btn-lg">See our services<I.arrow/></a>
            <button className="btn btn-ghost btn-lg" onClick={onCta}>Schedule a Consultation</button>
          </Reveal>
          <Reveal as="div" delay={320} className="hero-trust">
          </Reveal>
        </div>
        {!centered && (
          <Reveal className="hero-visual" delay={200}>
            <MiniDashboard />
            <MetricsGrid />
          </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>
  );
}

/* ───────────────────────── METRICS BAND ───────────────────────── */
const METRICS = [
  { value: "~14d", label: "Average days in A/R", emph: true },
  { value: "<2%", label: "Claim denial rate" },
  { value: "98%", label: "Collections rate on eligible charges" },
  { value: "<24 hours", label: "Response time to your questions" },
];

function MetricsGrid() {
  return (
    <div className="metrics-grid">
      {METRICS.map((m, i) => (
        <Reveal key={m.label} className={`metric-card ${m.emph ? "metric-emph" : ""}`} delay={i * 90}>
          <span className="metric-value">{m.value}</span>
          <span className="metric-label">{m.label}</span>
        </Reveal>
      ))}
    </div>
  );
}

/* ───────────────────────── OUR SOLUTIONS ───────────────────────── */
const PILLARS = [
  {
    num: "01",
    title: "Streamline operations",
    sub: "Billing, claims, and RCM workflows that run themselves, with one source of truth from intake to payment.",
    cards: [
      {
        key: "cycle", icon: "cycle", tone: "brand",
        title: "The full revenue cycle in one place",
        body: "Eligibility, claim submission, status tracking, ERA posting, and patient balances live together, with no exporting between four disconnected tools.",
        chips: ["Eligibility → Claims → ERA → Payments"],
      },
      {
        key: "send", icon: "send", tone: "sky",
        title: "Claims filed for you",
        body: "Each session becomes a compliant 837P claim, validated and filed directly with the payer. No data entry, straight from your existing exports.",
      },
      {
        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.",
      },
    ],
  },
  {
    num: "02",
    title: "Support your staff",
    sub: "Less admin burden on your team, and an ABA billing team behind them when questions come up.",
    cards: [
      {
        key: "pulse", icon: "pulse", tone: "indigo",
        title: "No more chasing payers",
        body: "Automated status checks poll the payer, and remittance cross-checks make sure a paid claim is never shown as pending, without your staff following up.",
      },
      {
        key: "chart", icon: "chart", tone: "sky",
        title: "Answers in minutes, not month-end",
        body: "Your real denial rate, aging, and per-payer performance on a live dashboard, with no spreadsheet stitching required.",
      },
      {
        key: "people", icon: "check", tone: "brand",
        title: "Backed by an ABA billing team",
        body: "DataMed is built and supported by people from inside the ABA world. When something looks off, you talk to someone who understands your billing.",
      },
    ],
  },
  {
    num: "03",
    title: "Deliver better care",
    sub: "Faster, cleaner reimbursements mean more resources, and more staff hours, going to the people you serve.",
    cards: [
      {
        key: "wallet", icon: "wallet", tone: "brand",
        title: "Cash lands sooner",
        body: "Collected cash reflects on the dashboard in real time, and faster reimbursement keeps resources flowing toward patient programs instead of paperwork.",
      },
      {
        key: "search", icon: "search", tone: "teal",
        title: "Coverage confirmed before care",
        body: "Real-time eligibility checks surface coverage, copay, and auth limits before a session is billed, so there are fewer billing surprises for families.",
      },
      {
        key: "time", icon: "cycle", tone: "indigo",
        title: "More time for clinical work",
        body: "With submission, tracking, and reconciliation automated, your clinical and admin staff spend their hours on clients, not claims.",
      },
    ],
  },
];

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>
  );
}

const PLATFORM_NOTE = {
  key: "shield", icon: "shield", tone: "indigo", span: "wide",
  title: "The platform behind it",
  body: "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, with member IDs, names, and DOBs encrypted at rest with per-field keys and a full audit trail on every action.",
  chips: ["837P", "835", "270/271", "276/277", "HIPAA"],
};

const SERVICE_TILES = [
  { icon: "\u{1F50D}", title: "Full Claim Visibility", body: "One dashboard shows exactly where every claim stands, so nothing slips through the cracks.", href: "#/custom-reporting" },
  { icon: "\u26A1", title: "Real-Time Status Checks", body: "Check claim status on demand, with no more waiting on hold with payers.", href: "#status" },
  { icon: "\u2705", title: "Eligibility Verification", body: "Confirm a child\u2019s coverage before the appointment and avoid costly surprises.", href: "#/how-it-works" },
  { icon: "\u{1F916}", title: "AI Denial Resolution", body: "When a claim is denied, our AI pinpoints the reason and recommends (or automates) the fix so denials get recovered, not written off.", href: "#/how-it-works" },
  { icon: "\u{1F4E7}", title: "Email Status Updates", body: "Your team is notified automatically as claims move through each stage, with no manual checking.", href: "#/custom-reporting" },
  { icon: "\u{1F6E0}\uFE0F", title: "Fully Customizable", body: "Configured around your workflows, payers, and reporting needs, not a rigid one-size-fits-all system.", href: "#/custom-reporting" },
];

function Solutions({ onCta }) {
  return (
    <React.Fragment>
    <section className="svc-hero">
      <div className="wrap">
        <Reveal><span className="eyebrow"><span className="dot"></span>ABA Billing</span></Reveal>
        <Reveal as="h1" delay={80} className="svc-hero-h1">ABA billing built around how <em>your specialty</em> actually works.</Reveal>
        <Reveal as="p" delay={140} className="svc-hero-sub">Everything your ABA practice needs to streamline operations, support staff, and deliver better care.</Reveal>
      </div>
    </section>
    <section className="svc-grid-sec">
      <div className="wrap">
        <div className="svc-grid">
          {SERVICE_TILES.map((c, i) => (
            <Reveal key={c.title} className="svc-tile" delay={(i % 3) * 90}>
              <span className="svc-tile-ic" aria-hidden="true">{c.icon}</span>
              <h3 className="svc-tile-t">{c.title}</h3>
              <p className="svc-tile-b">{c.body}</p>
              <a className="svc-tile-link" href={c.href}>Learn more {"\u2192"}</a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
    <section className="sec-pad features" id="solutions">
      <div className="wrap">
        {PILLARS.map((p) => (
          <div key={p.num} className="sol-pillar">
            <Reveal as="h3" className="sol-pillar-t"><span className="sol-pillar-num mono">{p.num}</span>{p.title}</Reveal>
            <Reveal as="p" delay={80} className="sol-pillar-sub">{p.sub}</Reveal>
            <div className="bento">
              {p.cards.map((f, i) => <FeatureCard key={f.key} f={f} i={i} />)}
            </div>
          </div>
        ))}
        <div className="sol-pillar">
          <div className="bento">
            <FeatureCard f={PLATFORM_NOTE} i={0} />
          </div>
        </div>
      </div>
    </section>
    </React.Fragment>
  );
}

/* ───────────────────────── 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: "DataMed files the claim", body: "DataMed turns each session into a compliant 837P professional claim, validates it, and files it directly with the payer. Your team never has to submit a thing.", metric: ["Filed by", "DataMed"], 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: "DataMed ingests the 835 remittance automatically, walking every segment to emit one clean record per service line, with 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, MetricsGrid, Solutions, Lifecycle });
