/* sections-status.jsx — Real-time claim status checks (interactive table) */

const STATUS_ROWS = [
  { payer: "Blue Cross and Blue Shield of Texas", code: "97155", units: "8.00", billed: 320.00, init: "paid",    paid: 153.36, sub: "1 line denied" },
  { payer: "Aetna Better Health Texas",           code: "97155", units: "4.00", billed: 160.00, init: "pending", paid: 76.68 },
  { payer: "Wellpoint",                           code: "97154", units: "3.00", billed: 105.00, init: "pending", paid: 52.50 },
  { payer: "Wellpoint",                           code: "97154", units: "2.00", billed: 70.00,  init: "pending", paid: 0, resolve: "denied" },
  { payer: "Aetna Better Health",                 code: "97154", units: "4.00", billed: 68.00,  init: "pending", paid: 40.80 },
  { payer: "Wellpoint",                           code: "97154", units: "4.00", billed: 140.00, init: "pending", paid: 70.00 },
  { payer: "Blue Cross and Blue Shield of Texas", code: "97154", units: "4.00", billed: 80.00,  init: "pending", paid: 48.00 },
];

const money = (n) => "$" + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");

function StatusBadge({ state }) {
  const map = {
    paid:     { cls: "paid",     label: "Paid" },
    pending:  { cls: "pending",  label: "Pending" },
    checking: { cls: "checking", label: "Checking" },
    denied:   { cls: "denied",   label: "Denied" },
  };
  const s = map[state] || map.pending;
  return (
    <span className={`stbadge stbadge-${s.cls}`}>
      {state === "checking" ? <span className="stspin"></span> : <span className="stdot"></span>}
      {s.label}
    </span>
  );
}

function StatusSection() {
  const [ref, seen] = useInView({ threshold: 0.25 });
  // each row: { state, paidShown }
  const init = () => STATUS_ROWS.map((r) => ({ state: r.init, paidShown: r.init === "paid" }));
  const [rows, setRows] = useState(init);
  const [running, setRunning] = useState(false);
  const timers = useRef([]);
  const ranOnce = useRef(false);

  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };

  const run = useCallback(() => {
    clearTimers();
    setRunning(true);
    // reset all non-initially-paid rows back to pending
    setRows(STATUS_ROWS.map((r) => ({ state: r.init === "paid" ? "paid" : "pending", paidShown: r.init === "paid" })));
    const pendingIdx = STATUS_ROWS.map((r, i) => (r.init === "paid" ? -1 : i)).filter((i) => i >= 0);
    let t = 380;
    pendingIdx.forEach((idx, k) => {
      // start checking
      timers.current.push(setTimeout(() => {
        setRows((prev) => prev.map((row, i) => (i === idx ? { ...row, state: "checking" } : row)));
      }, t));
      // resolve
      timers.current.push(setTimeout(() => {
        setRows((prev) => prev.map((row, i) => {
          if (i !== idx) return row;
          const target = STATUS_ROWS[idx].resolve || "paid";
          return { ...row, state: target, paidShown: target === "paid" };
        }));
        if (k === pendingIdx.length - 1) setRunning(false);
      }, t + 720));
      t += 540;
    });
  }, []);

  useEffect(() => {
    if (seen && !ranOnce.current) { ranOnce.current = true; const id = setTimeout(run, 500); timers.current.push(id); }
    return clearTimers;
  }, [seen, run]);

  const paidCount = rows.filter((r) => r.state === "paid").length;
  const pendingCount = rows.filter((r) => r.state === "pending" || r.state === "checking").length;
  const deniedCount = rows.filter((r) => r.state === "denied").length;

  return (
    <section className="sec-pad statuscheck" id="status" ref={ref}>
      <div className="wrap">
        <div className="sec-head sec-head-center">
          <Reveal><span className="eyebrow"><span className="dot"></span>Real-time status</span></Reveal>
          <Reveal as="h2" delay={80} className="sec-title">Know where every claim stands, automatically</Reveal>
          <Reveal as="p" delay={140} className="sec-sub">DataMed fires 276/277 status checks against each payer on a schedule, so a claim's state is never a guess. Watch a batch resolve live.</Reveal>
        </div>

        <Reveal className="st-frame" delay={120}>
          <div className="st-window">
            <div className="st-chrome">
              <div className="mini-dots"><span></span><span></span><span></span></div>
              <span className="st-title mono">claims · status monitor</span>
              <div className="st-summary">
                <span className="st-sum st-sum-paid">{paidCount} paid</span>
                <span className="st-sum st-sum-pending">{pendingCount} in flight</span>
                <span className="st-sum st-sum-denied">{deniedCount} denied</span>
                <button className="st-run" onClick={run} disabled={running}>
                  {running ? <><span className="stspin stspin-dark"></span> Checking…</> : <><I.cycle/> Run status checks</>}
                </button>
              </div>
            </div>

            <div className="st-table">
              <div className="st-row st-head">
                <span>Payer</span>
                <span>CPT</span>
                <span className="st-r">Units</span>
                <span className="st-r">Billed</span>
                <span className="st-r">Paid</span>
                <span>Status</span>
                <span className="st-r">Action</span>
              </div>
              {STATUS_ROWS.map((r, i) => {
                const st = rows[i];
                return (
                  <div key={i} className={`st-row ${st.state === "checking" ? "is-checking" : ""}`}>
                    <span className="st-payer">{r.payer}</span>
                    <span className="mono st-code">{r.code}</span>
                    <span className="st-r mono">{r.units}</span>
                    <span className="st-r mono">{money(r.billed)}</span>
                    <span className="st-r mono st-paid">{st.paidShown ? money(r.paid) : "—"}</span>
                    <span className="st-status">
                      <StatusBadge state={st.state} />
                      {r.sub && st.state === "paid" && <span className="st-sub">{r.sub}</span>}
                    </span>
                    <button className="st-r st-check" onClick={run} disabled={running}>Check status</button>
                  </div>
                );
              })}
            </div>

            <div className="st-foot">
              <span className="mini-live"><span className="live-dot"></span>Auto-checks every 6 hours · last sweep just now</span>
              
            </div>
          </div>
          <div className="dash-reflect" aria-hidden="true"></div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { StatusSection });
