/* ═══════════════════════════════════════════════════════════
   OpAgent | Anywhere — Eligibility Desk
   A DrChrono-faithful SKIN of Craig's eligibility workflow, branded
   OpAgent. Mirrors three DrChrono surfaces verbatim in layout:
     1) Billing → Live Claims Feed  (the ELIG REQUIRED worklist)
     2) Patient chart → Demographics → Insurances  (where the note lands)
     3) NGSConnex / Wellpoint Federal → Eligibility  (the determination read)
   Wired to the SAME live endpoints as the Eligibility tab:
     GET  /api/eligibility/worklist        (Adapters.eligibilityWorklist)
     POST /api/eligibility/run/:id         (Adapters.eligibilityRun — startOnly + poll status)
     GET  /api/eligibility/run/:id/status  (Adapters.eligibilityRunStatus)
     POST /api/eligibility/writeback/:id   (Adapters.eligibilityWriteback)
     GET  /api/eligibility/portal/status   (Adapters.eligibilityPortalStatus)
     POST /api/eligibility/portal/login    (Adapters.eligibilityPortalLogin)
   Fail-closed PENDING CRAIG. Benchmark mode leaves billing status untouched.
   ═══════════════════════════════════════════════════════════ */
(function(){
  const { useEffect, useState } = React;

  // Stable config from Build Spec v4 §10 (SPNY / Practice Group 312514).
  const PRACTICE_GROUP_ID = "312514";
  const NGS_PROVIDER = { name:"SPINE AND PAIN CONSULTANT PL", ptan:"A100001454", npi:"1477792232" };
  const PLAN_TYPE_LABEL = "MB - Medicare Part B (Professional)";

  // ── palette (OpAgent tokens; DrChrono/Wellpoint structure) ──
  const INK = "var(--ink)", INK_SOFT = "var(--ink-soft)", INK_FAINT = "var(--ink-faint)";
  const FOREST = "var(--forest)", FOREST_LIGHT = "var(--forest-light)", FOREST_PALE = "var(--forest-pale)";
  const SLATE = "var(--slate)", SLATE_PALE = "var(--slate-pale)", GILT = "var(--gilt)";
  const AVAILITY = "var(--availity)";
  const LINE = "var(--canvas-dark)", PURE = "var(--pure)", CANVAS_MID = "var(--canvas-mid)";
  const FM = "var(--fm)", FB = "var(--fb)";

  function initialsOf(name){
    const p = String(name||"").trim().split(/\s+/);
    return ((p[0]||"?")[0] + (p.length>1 ? p[p.length-1][0] : "")).toUpperCase();
  }

  /** Portal theme for desk branding — Availity (orange) vs NGSConnex (blue). */
  function deskPortal(row){
    const payer = String((row && row.payer) || "");
    const keyFromServer = row && row.portalKey;
    const isAvaility = keyFromServer === "availity"
      || (!keyFromServer && row && row.liveCapable && payer && !/\bmedicare\b|\bngs\b/i.test(payer));
    if(isAvaility){
      return {
        key:"availity",
        name:"Availity",
        short:"Availity",
        headerBg:AVAILITY,
        bodyBg:"#3A220F",
        footBg:"#2A180A",
        muted:"#F0C9A8",
        soft:"#D4A07A",
        idleCopy:"Run eligibility to read the Availity coverage & benefits.",
      };
    }
    return {
      key:"ngsconnex",
      name:"NGSConnex",
      short:"NGS",
      headerBg:SLATE,
      bodyBg:"#0F2740",
      footBg:"#0B1E33",
      muted:"#BFD6EA",
      soft:"#8FB0CC",
      idleCopy:"Run eligibility to read the NGSConnex determination tabs.",
    };
  }

  // Parse the Medicare chart-note OpAgent generated into the five NGSConnex
  // determination fields, so the portal panel shows authoritative per-tab values
  // (Craig reads exactly these tabs). Robust to PENDING CRAIG placeholders.
  function parseDeterminations(note){
    const out = { partA:null, partB:null, deductible:null, ma:null, msp:null, crossover:null, qmb:null };
    if(!note) return out;
    const g = (re) => { const m = note.match(re); return m ? (m[1]||"").trim() : null; };
    const eff = note.match(/PART A\s*\(([^)]*)\)\s*--\s*PART B\s*\(([^)]*)\)/i);
    if(eff){ out.partA = eff[1].trim(); out.partB = eff[2].trim(); }
    out.deductible = g(/PART B REMAINING DEDUCTIBLE:\s*([^\n]+)/i);
    if(/NO MEDICARE ADVANTAGE PLAN/i.test(note)) out.ma = "None — straight Medicare";
    else out.ma = g(/MEDICARE ADVANTAGE:\s*([^\n]+)/i);
    if(/MEDICARE (IS )?SECONDARY/i.test(note)) out.msp = g(/MEDICARE (?:IS )?SECONDARY[^\n]*/i) || "Present";
    else out.msp = "Medicare primary";
    if(/NO (CROSSOVER|.*CROSSOVER INFO)/i.test(note)) out.crossover = "None on file";
    else out.crossover = g(/CROSSOVER:\s*([^\n]+)/i);
    if(/NO QUALIFIED MEDICARE BENEFICIARY/i.test(note)) out.qmb = "Not a QMB";
    else out.qmb = g(/QMB:\s*([^\n]+)/i);
    return out;
  }

  // Parse Availity commercial preview note into Craig's capture lines.
  // Prefer structured availityCommercial from the API when present.
  function parseAvailityCommercial(note, structured){
    const out = { planType:null, planProduct:null, planProductSource:null, specialistCopay:null, oop:null, pcp:null };
    if(structured && typeof structured === "object"){
      if(structured.insuranceType) out.planType = String(structured.insuranceType).trim();
      if(structured.planProduct) out.planProduct = String(structured.planProduct).trim();
      if(structured.planProductSource) out.planProductSource = String(structured.planProductSource).trim();
      if(structured.specialistCopay) out.specialistCopay = String(structured.specialistCopay).trim();
      if(structured.oop) out.oop = String(structured.oop).trim();
      if(structured.pcp) out.pcp = String(structured.pcp).trim();
    }
    if(!note) return out;
    const g = (re) => { const m = note.match(re); return m ? (m[1]||"").trim() : null; };
    if(!out.planType) out.planType = g(/INSURANCE TYPE:\s*([^\n]+)/i);
    if(!out.planProduct){
      const planLine = g(/PLAN:\s*([^\n]+)/i);
      if(planLine){
        const fromM = planLine.match(/^(.*?)\s*\(from\s+(.+?)\)\s*$/i);
        if(fromM){
          out.planProduct = fromM[1].trim();
          const src = fromM[2].trim()
            .replace(/^Availity\s+/i, "")
            .replace(/\s+/g, " ");
          out.planProductSource = src || null;
        } else {
          out.planProduct = planLine;
        }
      }
    }
    if(!out.specialistCopay) out.specialistCopay = g(/SPECIALIST COPAY[^:]*:\s*([^\n]+)/i);
    if(!out.oop) out.oop = g(/OUT-OF-POCKET:\s*([^\n]+)/i);
    if(!out.pcp) out.pcp = g(/PCP:\s*([^\n]+)/i);
    return out;
  }

  function planProductDisplay(av){
    if(!av || !av.planProduct) return null;
    const src = av.planProductSource ? String(av.planProductSource).trim() : "";
    return src ? `${av.planProduct} · from ${src}` : av.planProduct;
  }

  // Real Craig dry-run note — never treat empty / "run eligibility…" placeholders as PROPOSED.
  function meaningfulEligNote(note){
    const n = String(note || "").trim();
    if(n.length < 40) return false;
    if(/run eligibility to generate|dry-run preview|not read yet/i.test(n)) return false;
    // Commercial Craig fields OR straight-Medicare template (no INSURANCE TYPE labels).
    if(/INSURANCE TYPE\s*:|\bPLAN\s*:|SPECIALIST COPAY|OUT-OF-POCKET\s*:|\bPCP\s*:|\bPAYER\s*:/i.test(n)) return true;
    if(/TRADITIONAL\s*MEDICARE|PART\s*A\s*EFFECTIVE|PART\s*B\s*EFFECTIVE|PART\s*B\s*REMAINING\s*DEDUCTIBLE|\bQMB\s*(STATUS|EFFECTIVE)|\bCROSSOVER\s*:/i.test(n)) return true;
    if(/^DATE:\s*\d{1,2}\/\d{1,2}\/\d{4}/im.test(n) && /OpAgent\s*\|/i.test(n) && /MEDICARE|INSURANCE TYPE|SPECIALIST COPAY|OUT-OF-POCKET|\bPCP\s*:|\bPAYER\s*:/i.test(n)) return true;
    return false;
  }

  // Disposition tag per row — Craig's "did it get done" signal.
  // Prefer sticky server disposition (survives refresh) over in-memory wb/run.
  // 3-tier colors: green = clean proposed, gilt amber = proposed+Craig gaps, red = total no-go.
  function rowTag({ row, run, wb }){
    if(wb && wb.status==="done" && wb.result && wb.result.armed){
      const allOk = (wb.result.steps||[]).every(s=>["written","verified","noop","skipped"].includes(s.status));
      return allOk ? { label:"DONE", tone:"ok" } : { label:"PARTIAL", tone:"warn" };
    }
    if(row && row.deskDisposition==="done") return { label:"DONE", tone:"ok" };
    if(row && row.deskDisposition==="partial") return { label:"PARTIAL", tone:"warn" };
    if(row && row.deskDisposition==="pending_craig") return { label:"DONE · PENDING CRAIG", tone:"warn" };
    // PROPOSED READY only with a real persisted Craig note — never empty deskDisposition.
    if(row && row.deskDisposition==="proposed" && meaningfulEligNote(row.deskChartNote)) {
      const pending = Array.isArray(row.deskPendingCraig) && row.deskPendingCraig.length;
      // Partial: real note + Craig gaps → calm gilt amber (not red).
      if(pending || row.deskTerminalStatus==="PENDING CRAIG") return { label:"PROPOSED · PENDING CRAIG", tone:"warn" };
      return { label:"PROPOSED READY", tone:"ok" };
    }
    if(run && run.status==="running"){
      const p = deskPortal(row);
      return { label:`READING ${p.name.toUpperCase()}…`, tone:"neutral" };
    }
    // Lock / auth / Connect-needed blips must never sticky-paint ERROR over a
    // real proposed note — operator action, not a failed determination.
    if(run && run.status==="error"){
      const msg = String(run.message || "");
      if(/eligibility_run_in_progress|in progress|sign_in_required|Sign in required|Connect NGS|Connect Availity|click Connect|MFA required/i.test(msg)) {
        /* fall through to deskDisposition / TO DO */
      } else {
        return { label:"ERROR", tone:"deny" };
      }
    }
    if(run && run.status==="done" && run.result){
      const r = run.result;
      const note = r.chartNote || r.note || "";
      const hasNote = meaningfulEligNote(note);
      const hasPending = !!(r.pendingCraig && r.pendingCraig.length) || r.terminalStatus==="PENDING CRAIG";
      // Yellow: usable proposed note with Craig gaps.
      if(hasPending && hasNote) return { label:"PROPOSED · PENDING CRAIG", tone:"warn" };
      // Red: total no-go — failed read / no usable determination.
      if(hasPending) return { label:"PENDING CRAIG", tone:"deny" };
      // Green: clean ready.
      if(hasNote) return { label:"PROPOSED READY", tone:"ok" };
      return { label:"TO DO", tone:"neutral" };
    }
    if(row.status==="needs-human-review") return { label:"PENDING CRAIG", tone:"deny" };
    return { label:"TO DO", tone:"neutral" };
  }

  /**
   * Remaining = still to-do for a dry-run sweep.
   * Include: TO DO, ERROR, PENDING CRAIG, PROPOSED · PENDING CRAIG.
   * Skip: DONE / PARTIAL / DONE · PENDING CRAIG (written-back), green PROPOSED READY,
   * in-flight READING…, and needs-human-review rows (same exclusion as Re-run all).
   */
  function isRemainingWork({ row, run, wb }){
    if(!row || !row.patientRef) return false;
    if(row.status==="needs-human-review") return false;
    // Skip DOB-missing portal rows. liveCapable alone is too narrow — portalKey
    // defaults to ngsconnex for many payers, and the live DOB gate used to fire
    // for those too (mass false ERROR on Run remaining).
    const pk = (row.portalKey || deskPortal(row).key || "");
    const needsDob = !!(row.liveCapable || pk === "ngsconnex" || pk === "availity");
    if(needsDob && !String(row.dob || "").trim()) return false;
    const label = rowTag({ row, run, wb }).label || "";
    return label==="TO DO"
      || label==="ERROR"
      || label==="PENDING CRAIG"
      || label==="PROPOSED · PENDING CRAIG";
  }

  function identityLine(row){
    if(!row || !row.liveCapable) return null;
    if(row.memberId || row.dob){
      return (row.memberId ? "MBI "+row.memberId : "MBI —")+(row.dob ? " · DOB "+row.dob : " · DOB missing");
    }
    return "MBI — · DOB missing — chart enrich pending";
  }

  function Tag({ tone, children, small }){
    const t = tone==="ok" || tone==="deny" || tone==="warn" ? tone : "neutral";
    return <span className={"desk-pill "+t+(small?" small":"")}>{children}</span>;
  }

  // ─────────────────────────────────────────────────────────
  //  EHR chrome — OpAgent-branded top bar + DrChrono-style subnav
  // ─────────────────────────────────────────────────────────
  function EhrChrome({ portal, availity, ehrSession, onReconnectEhr, signer, context, onConnectPortal, onManualPortal, onPortalStatus, onConnectAvaility }){
    const [code, setCode] = useState("");
    const [busy, setBusy] = useState(false);
    const [manualBusy, setManualBusy] = useState(false);
    const [ehrBusy, setEhrBusy] = useState(false);
    const [avBusy, setAvBusy] = useState(false);
    const [msg, setMsg] = useState("");
    const connected = !!(portal && portal.connected);
    const reconnecting = !!(portal && portal.reconnecting);
    // MFA is daily — only prompt when the server says the MFA wall is up.
    const needsMfa = !!(portal && portal.needsMfa);
    const pTone = connected ? "ok" : (reconnecting || manualBusy ? "warn" : (needsMfa ? "deny" : "warn"));
    const sessionOnDisk = !!(portal && portal.sessionExists);
    const pLabel = !portal ? "Checking NGSConnex…"
      : connected ? "NGSConnex connected · valid today"
      : manualBusy ? "Manual NGS login open…"
      : reconnecting ? "Waking today's NGS session…"
      : needsMfa ? "NGSConnex — paste today's same MFA code"
      : sessionOnDisk ? "NGS tab cold — Reconnect (password wake; MFA only if challenged)"
      : "NGSConnex not connected today";
    const avConnected = !!(availity && availity.connected);
    const avConnecting = !!(availity && (availity.connecting || /connecting/i.test(String(availity.reason || ""))));
    const avCreds = !(availity && availity.credsConfigured === false);
    const avTotp = !(availity && availity.totpConfigured === false);
    const avTone = avConnected ? "ok" : (avBusy || avConnecting ? "warn" : "warn");
    const avLabel = !availity ? "Checking Availity…"
      : avConnected ? "Availity connected"
      : (avBusy || avConnecting) ? "Connecting Availity…"
      : !avCreds ? "Availity — creds missing"
      : !avTotp ? "Availity — TOTP missing"
      : "Availity not connected";
    // Optional batch gate: both portals warm before Run remaining / Re-run all.
    const portalsReady = connected && avConnected;
    const portalsTone = portalsReady ? "ok" : ((reconnecting || avBusy || avConnecting || needsMfa) ? "warn" : "deny");
    const portalsLabel = portalsReady
      ? "Portals ready · NGS + Availity"
      : needsMfa ? "Portals cold · Connect NGS (MFA)"
      : (avBusy || avConnecting) ? "Portals warming…"
      : !connected && !avConnected ? "Portals cold · Connect NGS + Availity"
      : !connected ? "Portals cold · Connect NGS"
      : "Portals cold · Connect Availity";
    // One truth: never show a sticky local toast that contradicts polled status
    // (e.g. "Availity connected." next to AVAILITY NOT CONNECTED after a cold wake).
    useEffect(()=>{
      if(!msg) return;
      if(/Availity connected/i.test(msg) && !avConnected && !avBusy && !avConnecting){
        setMsg((availity && availity.reason) || "");
      } else if(/Availity not connected|Availity login failed|availity_login/i.test(msg) && avConnected && !avBusy){
        setMsg("Availity connected.");
      } else if(/Connected for today/i.test(msg) && !connected && !busy && !manualBusy && !reconnecting){
        setMsg((portal && portal.reason) || "");
      }
    }, [avConnected, avBusy, avConnecting, connected, busy, manualBusy, reconnecting, availity, portal, msg]);
    // Separate from NGS — dry-run can succeed while DrChrono cookies are stale.
    const ehrHealthy = !!(ehrSession && ehrSession.healthy);
    const ehrRelogin = !!(ehrSession && ehrSession.relogin && ehrSession.relogin.running);
    const ehrTone = ehrHealthy ? "ok" : (ehrRelogin || ehrBusy ? "warn" : "deny");
    const ehrLabel = !ehrSession ? "Checking Dr. Chrono…"
      : ehrHealthy ? "Dr. Chrono connected"
      : ehrRelogin || ehrBusy ? "Dr. Chrono reconnecting…"
      : "Dr. Chrono session stale — writeback blocked";
    async function reconnectEhr(){
      if(!onReconnectEhr) return;
      setEhrBusy(true); setMsg("Reconnecting Dr. Chrono…");
      try {
        await onReconnectEhr();
        setMsg("Dr. Chrono reconnect started.");
      } catch(e){ setMsg((e && e.message) || "Dr. Chrono reconnect failed"); }
      finally { setEhrBusy(false); }
    }
    async function connect(){
      const typed = code.trim();
      setBusy(true); setMsg(typed ? "Submitting today's MFA…" : "Reconnecting NGS (password wake)…");
      try {
        const r = await onConnectPortal(code);
        if(r && r.connected){ setCode(""); setMsg("Connected for today."); }
        else if(r && r.needsMfa) setMsg((r.reason) || "Paste today's same MFA code (does not send a new email).");
        else setMsg((r && (r.reason || r.error)) || "Not connected.");
      } catch(e){ setMsg((e && e.message) || "Login failed"); }
      finally { setBusy(false); }
    }
    async function connectAvaility(){
      if(!onConnectAvaility) return;
      setAvBusy(true); setMsg("Connecting Availity (password + TOTP)…");
      try {
        const r = await onConnectAvaility();
        if(r && r.connected) setMsg("Availity connected.");
        else setMsg((r && (r.reason || r.error)) || "Availity not connected.");
      } catch(e){ setMsg((e && e.message) || "Availity login failed"); }
      finally { setAvBusy(false); }
    }
    async function manualLogin(){
      if(!onManualPortal) return;
      setManualBusy(true);
      setMsg("Opening NGS login window…");
      try {
        const r = await onManualPortal();
        if(r && r.loginWindowUrl){
          // Always open a fresh window name so a dead post-deploy tab isn't reused.
          const w = window.open(r.loginWindowUrl, "ngs-login-" + Date.now(), "width=1200,height=800,menubar=no,toolbar=no,location=yes,status=no");
          if(!w){
            setMsg("Popup blocked — allow popups for inside.theopagent.ai, then click Manual NGS login again.");
            setManualBusy(false);
            return;
          }
          setMsg("In the window: click Enter → finish MFA until Eligibility Lookup. Close the old black tab if you still have one.");
        } else if(r && r.mode === "supervised"){
          setMsg("NGS login window opened — click Enter, finish MFA until Eligibility Lookup appears.");
        } else {
          setMsg((r && (r.reason || r.error)) || "Could not open manual login.");
          setManualBusy(false);
          return;
        }
        // Poll until connected or failed — does not block the worklist.
        const deadline = Date.now() + 8 * 60_000;
        while(Date.now() < deadline){
          await new Promise(res=>setTimeout(res, 2000));
          const st = onPortalStatus ? await onPortalStatus() : null;
          const man = window.Adapters.eligibilityPortalManualLoginStatus
            ? await window.Adapters.eligibilityPortalManualLoginStatus()
            : null;
          if(st && st.connected){
            setMsg("Connected for today.");
            break;
          }
          if(man && man.result === "success"){
            const again = onPortalStatus ? await onPortalStatus() : null;
            if(again && again.connected) setMsg("Connected for today.");
            else setMsg("Manual login saved — refreshing status…");
            if(onPortalStatus) await onPortalStatus();
            break;
          }
          if(man && man.result === "failed"){
            setMsg((man.error) || "Manual login failed — try again.");
            break;
          }
          if(man && !man.running && man.result !== "pending") break;
        }
      } catch(e){ setMsg((e && e.message) || "Manual login failed"); }
      finally { setManualBusy(false); if(onPortalStatus) onPortalStatus(); }
    }
    return (
      <div style={{ border:"1px solid "+LINE, borderRadius:12, overflow:"hidden", boxShadow:"var(--shadow-sm)", background:PURE }}>
        {/* top bar — forest (OpAgent) where DrChrono is charcoal */}
        <div style={{ display:"flex", alignItems:"center", gap:14, padding:"10px 16px", background:FOREST, color:"#EAF3EC" }}>
          <div style={{ display:"flex", alignItems:"center", gap:9 }}>
            <Reticle size={22}/>
            <span style={{ fontFamily:"var(--fd)", fontSize:16, fontWeight:600, letterSpacing:".01em" }}>OpAgent</span>
            <span style={{ width:1, height:16, background:"rgba(255,255,255,.28)" }}></span>
            <span style={{ fontFamily:FM, fontSize:11, letterSpacing:".16em", textTransform:"uppercase", color:"#B9D6C4" }}>Eligibility Desk</span>
          </div>
          <span style={{ fontFamily:FM, fontSize:10, letterSpacing:".06em", color:"#9CC0AA", border:"1px solid rgba(255,255,255,.22)", borderRadius:20, padding:"3px 9px" }}>
            EHR VIEW · mirrors Dr. Chrono
          </span>
          <span style={{ flex:1 }}></span>
          <span style={{ fontFamily:FM, fontSize:11, color:"#B9D6C4" }}>Practice Group {PRACTICE_GROUP_ID}</span>
          <span style={{ width:1, height:16, background:"rgba(255,255,255,.28)" }}></span>
          <span style={{ display:"inline-flex", alignItems:"center", gap:8, fontSize:12, color:"#EAF3EC" }}>
            <span style={{ display:"inline-flex", width:22, height:22, borderRadius:"50%", background:GILT, color:FOREST, fontFamily:FM, fontSize:10, fontWeight:700, alignItems:"center", justifyContent:"center" }}>{initialsOf(signer)}</span>
            {signer}
          </span>
        </div>
        {/* subnav — DrChrono module tabs, Billing active */}
        <div style={{ display:"flex", alignItems:"center", gap:2, padding:"0 12px", background:"#12261B", color:"#8FB39D", borderTop:"1px solid rgba(255,255,255,.06)" }}>
          {["Schedule","Patients","Reports","Billing","Account","Marketplace"].map(x=>(
            <span key={x} style={{ padding:"8px 12px", fontSize:12.5, color: x==="Billing" ? "#fff" : "#8FB39D", borderBottom: x==="Billing" ? "2px solid "+GILT : "2px solid transparent" }}>{x}</span>
          ))}
          <span style={{ flex:1 }}></span>
          <span style={{ display:"inline-flex", alignItems:"center", gap:8, padding:"6px 10px", flexWrap:"wrap", justifyContent:"flex-end" }}>
            <Tag tone={ehrTone} small>{ehrLabel}</Tag>
            {!ehrHealthy && !ehrRelogin && (
              <button className={"pill-btn "+(ehrBusy?"loading":"")} disabled={ehrBusy} onClick={reconnectEhr}
                style={{ fontSize:11, padding:"4px 10px" }}
                title="Dr. Chrono is required for writeback. Dry-run can still use NGS + cached identity when this is stale.">
                {ehrBusy && <span className="wf-mini-spinner" aria-hidden="true"></span>}{ehrBusy?"Reconnecting…":"Reconnect Dr. Chrono"}
              </button>
            )}
            <Tag tone={pTone} small>{pLabel}</Tag>
            {/* Not connected: Reconnect = password wake. After challenge (or anytime),
                paste today's same daily MFA — never auto-Send / inbox guess. */}
            {!connected && !reconnecting && portal && portal.credsConfigured!==false && (
              <>
                <input value={code} onChange={e=>setCode(e.target.value)} onKeyDown={e=>{ if(e.key==="Enter"&&!busy) connect(); }}
                  inputMode="numeric" autoComplete="one-time-code" placeholder="Today's same MFA code"
                  style={{ fontFamily:FM, fontSize:11, border:"1px solid rgba(255,255,255,.25)", borderRadius:6, padding:"4px 7px", background:"rgba(255,255,255,.06)", color:"#fff", width:160 }}/>
                <button className={"pill-btn "+(busy?"loading":"")} disabled={busy||manualBusy} onClick={connect} style={{ fontSize:11, padding:"4px 10px" }}
                  title={code.trim()
                    ? "Enter today's same daily MFA (valid until 11:59 PM EST). Does not send a new email."
                    : "Submit stored password. If NGS challenges, paste today's same MFA code next."}>
                  {busy && <span className="wf-mini-spinner" aria-hidden="true"></span>}
                  {busy ? "Connecting…" : (code.trim() ? "Submit MFA" : "Reconnect")}
                </button>
              </>
            )}
            {/* ALWAYS available (even if the badge shows connected) so a stale/false
                green state can never lock the operator out of re-authenticating. */}
            {portal && portal.credsConfigured!==false && (
              <button className={"pill-btn "+(manualBusy?"loading":"")} disabled={manualBusy} onClick={manualLogin}
                style={{ fontSize:11, padding:"4px 10px", borderColor:"rgba(240,192,112,.55)", color:"#F0C070" }}
                title="Open NGS in a login window, finish MFA yourself. Use this any time to (re)establish a verified session.">
                {manualBusy && <span className="wf-mini-spinner" aria-hidden="true"></span>}{manualBusy?"Manual login…":(connected?"Re-verify NGS":"Manual NGS login")}
              </button>
            )}
            <Tag tone={avTone} small>{avLabel}</Tag>
            {avCreds && onConnectAvaility && (
              <button className={"pill-btn "+((avBusy||avConnecting)?"loading":"")} disabled={avBusy || avConnecting || avConnected} onClick={connectAvaility}
                style={{ fontSize:11, padding:"4px 10px" }}
                title={avConnected ? "Already connected — dry-run uses this session" : (avConnecting ? "Availity login in progress…" : "Headless Availity login using stored password + TOTP seed (no phone).")}>
                {(avBusy||avConnecting) && <span className="wf-mini-spinner" aria-hidden="true"></span>}
                {(avBusy||avConnecting) ? "Connecting…" : (avConnected ? "Availity connected" : "Connect Availity")}
              </button>
            )}
            <span title="Warm both portals before batch dry-runs for predictable one-shot reads">
              <Tag tone={portalsTone} small>{portalsLabel}</Tag>
            </span>
            {!!msg && <span style={{ fontFamily:FM, fontSize:10, color: (connected||avConnected)?"#8FE0AE":"#F0C070", maxWidth:420 }} title={msg}>{msg}</span>}
          </span>
        </div>
        {context && (
          <div style={{ padding:"6px 16px", background:CANVAS_MID, borderTop:"1px solid "+LINE, fontFamily:FM, fontSize:11, color:INK_SOFT }}>{context}</div>
        )}
      </div>
    );
  }

  // ─────────────────────────────────────────────────────────
  //  Live Claims Feed skin — the ELIG REQUIRED worklist
  // ─────────────────────────────────────────────────────────
  const FEED_LEFTNAV = ["Billing Summary","Live Claims Feed","Patient Payments","Day Sheet","Transactions","Remittance Reports","Aging AR Analysis","Patient Statements","Patient Balance Ledger","Fee Schedule","Billing Log","Enrollment"];

  function BucketFilterBar({ buckets, statuses, benchmark }){
    const defs = (statuses && statuses.length) ? statuses.map(s=>s.label) : Object.keys(buckets||{});
    return (
      <div style={{ display:"flex", gap:8, flexWrap:"wrap", alignItems:"center", padding:"10px 12px", background:CANVAS_MID, borderBottom:"1px solid "+LINE }}>
        <span style={{ fontFamily:FM, fontSize:10, letterSpacing:".08em", textTransform:"uppercase", color:INK_FAINT }}>Billing status:</span>
        {defs.map(label=>{
          const n = (buckets && buckets[label]) || 0;
          const inScope = !benchmark || !benchmark.bucketCodes || !benchmark.bucketCodes.length || (statuses||[]).some(s=>s.label===label && (benchmark.bucketCodes||[]).includes(s.code));
          return (
            <span key={label} style={{ fontFamily:FM, fontSize:11, color: inScope?FOREST:INK_FAINT, background:PURE, border:"1px solid "+(inScope?FOREST_LIGHT:LINE), borderRadius:20, padding:"3px 10px", opacity: inScope?1:.6 }}>
              {label} · <b>{n}</b>
            </span>
          );
        })}
        <span style={{ flex:1 }}></span>
        <span style={{ fontFamily:FM, fontSize:10, letterSpacing:".06em", color:INK_FAINT, border:"1px solid "+LINE, borderRadius:20, padding:"3px 10px", background:PURE }}>
          DOS: {benchmark && benchmark.minDos ? "≥ "+benchmark.minDos : "beginning of time"}
        </span>
      </div>
    );
  }

  function ClaimsFeed({ data, loading, runs, wb, sweep, busyRun, onOpen, onRerun, onRefresh, onSweep, onSweepRemaining, coverageAll, onToggleCoverage }){
    const queue = Array.isArray(data.queue) ? data.queue : [];
    const readyCount = queue.filter(r=>r.status!=="needs-human-review").length;
    const writtenCount = queue.filter(r=>{
      const t = rowTag({ row:r, run:runs[r.id], wb:wb[r.id] });
      return /DONE|PROPOSED/i.test(t.label);
    }).length;
    const remainingCount = queue.filter(r=>isRemainingWork({ row:r, run:runs[r.id], wb:wb[r.id] })).length;
    const missingDobCount = typeof data.missingDob === "number"
      ? data.missingDob
      : queue.filter(r=>r.liveCapable && r.patientRef && !r.dob).length;
    const enriching = !!(data && data.identityEnriching);
    const sweepRunning = !!(sweep && sweep.running);
    const sweepMode = sweep && sweep.mode;
    const cols = ["", "Claim ID","Patient","Date of Service","Payer","Bucket","Billing Status","OpAgent"];
    return (
      <div style={{ display:"flex", border:"1px solid "+LINE, borderRadius:12, overflow:"hidden", background:PURE, boxShadow:"var(--shadow-sm)" }}>
        {/* left billing nav (cosmetic, matches DrChrono) */}
        <div style={{ width:186, flexShrink:0, background:CANVAS_MID, borderRight:"1px solid "+LINE, padding:"8px 0" }}>
          {FEED_LEFTNAV.map(x=>(
            <div key={x} style={{ padding:"7px 14px", fontSize:12, color: x==="Live Claims Feed" ? "#fff" : INK_SOFT, background: x==="Live Claims Feed" ? FOREST_LIGHT : "transparent", fontWeight: x==="Live Claims Feed"?600:400 }}>{x}</div>
          ))}
        </div>
        {/* main feed */}
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:"flex", alignItems:"center", gap:10, padding:"12px 14px", borderBottom:"1px solid "+LINE, flexWrap:"wrap" }}>
            <div style={{ fontFamily:"var(--fd)", fontSize:17, color:INK }}>Live Claims Feed</div>
            <Tag tone="ok" small>{readyCount} to work</Tag>
            {remainingCount>0 && <Tag tone="neutral" small>{remainingCount} remaining</Tag>}
            {missingDobCount>0 && <Tag tone="deny" small>{missingDobCount} missing DOB</Tag>}
            {enriching && <Tag tone="warn" small>Enriching chart DOB/MBI…</Tag>}
            <span style={{ flex:1 }}></span>
            <button className="pill-btn" onClick={onRefresh} disabled={loading} style={{ fontSize:12 }} title="Re-scrape the ELIG REQUIRED bucket (slow)">
              {loading ? "Refreshing…" : "Refresh bucket"}
            </button>
            <button className={"pill-btn "+(sweepRunning&&sweepMode==="remaining"?"loading":"")} onClick={onSweepRemaining}
              disabled={sweepRunning||!!busyRun||!remainingCount} style={{ fontSize:12 }}
              title="Dry-run only rows still to-do (TO DO, ERROR, PENDING CRAIG, PROPOSED · PENDING CRAIG). Skips DONE / written-back and green PROPOSED READY.">
              {sweepRunning&&sweepMode==="remaining" && <span className="wf-mini-spinner" aria-hidden="true"></span>}
              {sweepRunning&&sweepMode==="remaining"
                ? `Running remaining… ${sweep.done}/${sweep.total}`
                : `Run remaining ${remainingCount} (dry)`}
            </button>
            <button className={"pill-btn "+(sweepRunning&&sweepMode==="all"?"loading":"")} onClick={onSweep}
              disabled={sweepRunning||!!busyRun||!readyCount} style={{ fontSize:12 }}
              title="Dry-run every row in this feed (including DONE) — re-reads NGS, no DrChrono writes.">
              {sweepRunning&&sweepMode==="all" && <span className="wf-mini-spinner" aria-hidden="true"></span>}
              {sweepRunning&&sweepMode==="all"
                ? `Running… ${sweep.done}/${sweep.total}`
                : (writtenCount ? `Re-run all ${readyCount} (dry)` : "Run the queue (dry)")}
            </button>
          </div>

          <BucketFilterBar buckets={data.buckets} statuses={data.statuses} benchmark={data.benchmark}/>

          {data.benchmark && data.benchmark.mode==="scoped" && (
            <div style={{ padding:"8px 14px", background:"rgba(180,120,20,.08)", borderBottom:"1px solid rgba(180,120,20,.30)", fontFamily:FB, fontSize:12, color:"#7a5210" }}>
              <b>Benchmark mode</b> · Dry-run saves the proposed note <b>in OpAgent</b> (reopen patient to see it). Dr. Chrono Primary Insurance Notes stay empty until <b>Save Demographics</b> (writes armed). Billing status is never flipped. Scope: {(data.benchmark.bucketCodes||[]).join(", ")} · DOS ≥ {data.benchmark.minDos}.
            </div>
          )}

          {data.coverage && (
            <div style={{ display:"flex", gap:10, flexWrap:"wrap", alignItems:"center", padding:"8px 14px", borderBottom:"1px solid "+LINE }}>
              <Tag tone="ok" small>{data.coverage.live} live-determinable (Medicare + Availity: BCBS/Aetna/Humana/Cigna)</Tag>
              {data.coverage.hidden>0 && <Tag tone="warn" small>{data.coverage.hidden} hidden — no live portal yet</Tag>}
              {data.meta && (
                <Tag tone="neutral" small>
                  {data.meta.eligibilityRows||0} scraped → {data.meta.inScope||0} in benchmark → {data.meta.shown||0} shown
                </Tag>
              )}
              <label style={{ display:"inline-flex", gap:6, alignItems:"center", fontFamily:FM, fontSize:11, color:INK_FAINT, cursor:"pointer" }}>
                <input type="checkbox" checked={coverageAll} onChange={e=>onToggleCoverage(e.target.checked)}/> Show all payers (incl. WC/no-fault)
              </label>
            </div>
          )}

          {/* claims table */}
          <div style={{ overflowX:"auto" }}>
            <table style={{ width:"100%", borderCollapse:"collapse", fontFamily:FB, fontSize:12.5 }}>
              <thead>
                <tr style={{ background:FOREST_PALE, color:"var(--forest-mid)", textAlign:"left" }}>
                  {cols.map((c,i)=>(<th key={i} style={{ padding:"7px 10px", fontFamily:FM, fontSize:10, letterSpacing:".05em", textTransform:"uppercase", fontWeight:700, borderBottom:"1px solid "+FOREST_LIGHT, whiteSpace:"nowrap" }}>{c}</th>))}
                </tr>
              </thead>
              <tbody>
                {!queue.length && (
                  <tr><td colSpan={cols.length} style={{ padding:"22px 14px", color:INK_FAINT, fontStyle:"italic" }}>
                    {(loading || data.pending) ? "Scraping Live Claims Feed (ELIG REQUIRED)… usually ~30–60s on a cold cache." : "No pending-eligibility claims in scope. Craig's queue is clear."}
                  </td></tr>
                )}
                {queue.map(row=>{
                  const tag = rowTag({ row, run:runs[row.id], wb:wb[row.id] });
                  const run = runs[row.id];
                  const running = run && run.status==="running";
                  const canRerun = /DONE|PROPOSED|PENDING CRAIG/i.test(tag.label);
                  const idLine = identityLine(row);
                  const dobMissing = !!(row.liveCapable && !row.dob);
                  const deskLabel = dobMissing ? "DOB MISSING" : tag.label;
                  const deskTone = dobMissing ? "deny" : tag.tone;
                  return (
                    <tr key={row.id} onClick={()=>onOpen(row)} style={{ cursor:"pointer", borderBottom:"1px solid "+CANVAS_MID }}
                      onMouseEnter={e=>e.currentTarget.style.background=FOREST_PALE} onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                      <td style={{ padding:"8px 10px", color:INK_FAINT }}>▸</td>
                      <td style={{ padding:"8px 10px", fontFamily:FM, color:SLATE, fontWeight:600, whiteSpace:"nowrap" }}>{row.claimId||"—"}</td>
                      <td style={{ padding:"8px 10px", fontWeight:600, color:INK, whiteSpace:"nowrap" }}>
                        <div>{row.patientName||"Unknown"}</div>
                        {idLine ? (
                          <div style={{ fontFamily:FM, fontSize:10.5, fontWeight:500, color: dobMissing ? "#9b2c2c" : INK_FAINT, marginTop:2 }}>
                            {idLine}
                          </div>
                        ) : null}
                      </td>
                      <td style={{ padding:"8px 10px", color:INK_SOFT, whiteSpace:"nowrap" }}>{row.dos||"—"}</td>
                      <td style={{ padding:"8px 10px", color:INK_SOFT }}>{row.payer||"—"}</td>
                      <td style={{ padding:"8px 10px", color:INK_FAINT, fontFamily:FM, fontSize:11 }}>{row.bucket||"—"}</td>
                      <td style={{ padding:"8px 10px", color:INK_SOFT, whiteSpace:"nowrap" }}>{row.bucket||"ELIG REQUIRED"}</td>
                      <td style={{ padding:"8px 10px" }} onClick={e=>e.stopPropagation()}>
                        <div style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap" }}>
                          <Tag tone={deskTone} small>{deskLabel}</Tag>
                          {canRerun && !running && (
                            <button
                              className="pill-btn"
                              disabled={!!busyRun || (sweep&&sweep.running) || !row.patientRef || dobMissing}
                              onClick={(e)=>{ e.stopPropagation(); onOpen(row); onRerun(row); }}
                              style={{ fontSize:10.5, padding:"2px 8px" }}
                              title={dobMissing
                                ? "DOB missing — wait for chart enrich or Refresh bucket before NGS/Availity"
                                : `Re-read ${deskPortal(row).name} and rebuild the proposed note (no write until you Save)`}>
                              Re-run
                            </button>
                          )}
                          {running && <span className="wf-mini-spinner" aria-hidden="true"></span>}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div style={{ padding:"8px 14px", fontFamily:FM, fontSize:10.5, color:INK_FAINT, borderTop:"1px solid "+LINE }}>
            Practice Group ID: {PRACTICE_GROUP_ID}
            {data.cached && <span> · cached{data.stale?" (stale)":""}{data.generatedAt?" "+new Date(data.generatedAt).toLocaleTimeString():""}</span>}
            {enriching && <span> · enriching DOB/MBI from DrChrono charts…</span>}
            {missingDobCount>0 && !enriching && <span style={{ color:"#9b2c2c" }}> · {missingDobCount} row(s) still missing DOB — Refresh bucket or wait for repair</span>}
            {" · "}Click a claim to open the chart. <b>Run remaining</b> skips DONE / PROPOSED READY and DOB-missing rows; per-row <b>Re-run</b> refreshes from the portal before rewriting.
          </div>
        </div>
      </div>
    );
  }

  // ─────────────────────────────────────────────────────────
  //  Patient chart skin — Demographics/Insurances + NGS panel
  // ─────────────────────────────────────────────────────────
  const CHART_LEFTNAV = ["Patient Summary","Demographics","Appointments","Clinical Dashboard","Documents","Eligibility","Tasks","Problem List","Medication List"];
  const INS_TABS = ["Demographics","Insurances","Authorizations","Patient Flags","Payments"];
  const INS_SUBTABS = ["Primary Ins","Secondary Ins","Tertiary Ins","Auto Accident","Worker's Comp","Durable Med Eqpt"];

  function Field({ label, value, mono, area, highlight, editable, onChange, placeholder }){
    return (
      <div style={{ display:"grid", gridTemplateColumns:"150px 1fr", gap:10, alignItems: area?"start":"center", marginBottom:8 }}>
        <label style={{ fontSize:11.5, color:INK_SOFT, textAlign:"right", paddingTop: area?6:0 }}>{label}</label>
        {area && editable ? (
          <textarea
            value={value||""}
            onChange={(e)=>onChange && onChange(e.target.value)}
            placeholder={placeholder||""}
            rows={10}
            style={{ whiteSpace:"pre-wrap", fontFamily:FM, fontSize:11.5, color:INK, margin:0, minHeight:140, width:"100%", boxSizing:"border-box", resize:"vertical", border:"1px solid "+(highlight?FOREST_LIGHT:LINE), borderRadius:6, padding:"8px 10px", background:highlight?FOREST_PALE:PURE, lineHeight:1.45 }}
          />
        ) : area ? (
          <pre style={{ whiteSpace:"pre-wrap", fontFamily:FM, fontSize:11.5, color:INK, margin:0, minHeight:64, border:"1px solid "+(highlight?FOREST_LIGHT:LINE), borderRadius:6, padding:"8px 10px", background:highlight?FOREST_PALE:PURE }}>{value||""}</pre>
        ) : (
          <div style={{ fontFamily: mono?FM:FB, fontSize:12.5, color:INK, border:"1px solid "+(highlight?FOREST_LIGHT:LINE), borderRadius:6, padding:"7px 10px", background:highlight?FOREST_PALE:CANVAS_MID }}>{value||"—"}</div>
        )}
      </div>
    );
  }

  function DeterminationRow({ label, value, active, labelColor }){
    const has = value!=null && value!=="" && !/PENDING CRAIG/i.test(String(value));
    const pending = /PENDING CRAIG/i.test(String(value||""));
    return (
      <div style={{ display:"flex", alignItems:"baseline", gap:8, padding:"7px 12px", borderBottom:"1px solid rgba(255,255,255,.10)" }}>
        <span style={{ width:15, color: has?"#8FE0AE":(pending?"#F0C070":"rgba(255,255,255,.30)"), fontSize:12 }}>{has?"✓":(pending?"!":"·")}</span>
        <span style={{ width:150, flexShrink:0, fontSize:11.5, color:labelColor||"#C8DCEC" }}>{label}</span>
        <span style={{ flex:1, fontFamily:FM, fontSize:11.5, color: pending?"#F0C070":"#fff", wordBreak:"break-word" }}>{active ? (value||"—") : "—"}</span>
      </div>
    );
  }

  function PortalEligPanel({ row, run }){
    const portal = deskPortal(row);
    const availity = portal.key === "availity";
    const r = run && run.status==="done" ? run.result : null;
    const active = !!r;
    const note = r && (r.chartNote || r.note);
    const det = availity ? null : parseDeterminations(note);
    const av = availity ? parseAvailityCommercial(note, r && r.availityCommercial) : null;
    const memberId = (r && r.cleaning && r.cleaning.memberId && r.cleaning.memberId.value) || row.memberId || "—";
    const stage2 = r && (r.stages||[]).find(s=>/portal/i.test(s.key)||s.stage===2);
    const labelTint = availity ? "#F5D4B8" : "#C8DCEC";
    return (
      <div style={{ border:"1px solid "+LINE, borderRadius:12, overflow:"hidden", boxShadow:"var(--shadow-sm)", background:portal.bodyBg }}>
        <div style={{ padding:"10px 14px", background:portal.headerBg, color:"#fff", display:"flex", alignItems:"center", gap:10 }}>
          <span style={{ fontFamily:"var(--fd)", fontSize:14, fontWeight:600 }}>{portal.name}</span>
          <span style={{ width:1, height:14, background:"rgba(255,255,255,.3)" }}></span>
          <span style={{ fontFamily:FM, fontSize:11, letterSpacing:".14em", color:portal.muted }}>ELIGIBILITY</span>
          <span style={{ flex:1 }}></span>
          <span style={{ fontFamily:FM, fontSize:10, color:portal.muted }}>{active ? (r.synthetic ? "STUB READ" : "LIVE READ") : "not read yet"}</span>
        </div>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:0, borderBottom:"1px solid rgba(255,255,255,.12)" }}>
          <div style={{ padding:"9px 14px", borderRight:"1px solid rgba(255,255,255,.12)" }}>
            <div style={{ fontSize:10, color:portal.soft, textTransform:"uppercase", letterSpacing:".06em" }}>Provider</div>
            <div style={{ fontSize:12.5, color:"#fff", fontWeight:600 }}>{NGS_PROVIDER.name}</div>
            <div style={{ fontFamily:FM, fontSize:10.5, color:portal.muted }}>PTAN {NGS_PROVIDER.ptan} · NPI {NGS_PROVIDER.npi}</div>
          </div>
          <div style={{ padding:"9px 14px" }}>
            <div style={{ fontSize:10, color:portal.soft, textTransform:"uppercase", letterSpacing:".06em" }}>{availity ? "Member" : "Beneficiary"}</div>
            <div style={{ fontSize:12.5, color:"#fff", fontWeight:600 }}>{row.patientName||"—"}</div>
            <div style={{ fontFamily:FM, fontSize:10.5, color:portal.muted }}>
              {availity ? `Ins ID ${memberId}` : `Medicare # ${memberId}`}
            </div>
          </div>
        </div>
        <div>
          {availity ? (
            <>
              <DeterminationRow label="Insurance Type" active={active} value={av.planType} labelColor={labelTint}/>
              <DeterminationRow label="Plan / Product" active={active} value={planProductDisplay(av)} labelColor={labelTint}/>
              <DeterminationRow label="Specialist Copay" active={active} value={av.specialistCopay} labelColor={labelTint}/>
              <DeterminationRow label="Out-of-Pocket" active={active} value={av.oop} labelColor={labelTint}/>
              <DeterminationRow label="PCP" active={active} value={av.pcp} labelColor={labelTint}/>
              <DeterminationRow label="Payer" active={active} value={active ? (row.payer || "—") : null} labelColor={labelTint}/>
            </>
          ) : (
            <>
              <DeterminationRow label="Beneficiary Eligibility" active={active} value={active ? (det.partA||det.partB ? `Part A ${det.partA||"—"} · Part B ${det.partB||"—"}` : "Active Medicare") : null}/>
              <DeterminationRow label="Part B Deductibles" active={active} value={det.deductible}/>
              <DeterminationRow label="Medicare Advantage" active={active} value={det.ma}/>
              <DeterminationRow label="Medicare Secondary Payer" active={active} value={det.msp}/>
              <DeterminationRow label="Crossover" active={active} value={det.crossover}/>
              <DeterminationRow label="Qualified Medicare Beneficiary" active={active} value={det.qmb}/>
            </>
          )}
        </div>
        <div style={{ padding:"8px 14px", background:portal.footBg, fontFamily:FM, fontSize:10.5, color:portal.soft }}>
          {active ? (stage2 ? stage2.summary : "Determination read complete.") : portal.idleCopy}
        </div>
      </div>
    );
  }

  function WritebackStrip({ run, wb, onWriteback, busyWb, overridePendingCraig, onOverrideChange, noteDirty }){
    const r = run && run.status==="done" ? run.result : null;
    if(!r) return null;
    const pending = !!(r.pendingCraig && r.pendingCraig.length) || r.terminalStatus==="PENDING CRAIG";
    const armed = r.writeback && r.writeback.armed;
    const running = wb && wb.status==="running";
    const canWrite = !pending || !!overridePendingCraig;
    const btnLabel = running
      ? "Saving…"
      : (!armed
        ? "Preview writeback (no DrChrono write)"
        : (pending && overridePendingCraig ? "Override & write anyway" : "Save Demographics (write)"));
    const btnTitle = !armed
      ? "Writes disarmed — dry-run already saved the preview in OpAgent; this only re-previews (0 DrChrono writes)"
      : pending && !overridePendingCraig
        ? "PENDING CRAIG blocks writeback until you confirm the override below"
        : pending && overridePendingCraig
          ? "Writes the note and plan type as shown (including your edits). PENDING CRAIG fields may remain in the note unless you edited them. Billing status is not flipped when benchmark mode forbids it."
          : "Writes the proposed note into Dr. Chrono Primary Insurance Notes (billing status suppressed in benchmark mode)";
    return (
      <div style={{ marginTop:10, padding:"10px 12px", border:"1px solid "+LINE, borderRadius:10, background:CANVAS_MID }}>
        {pending && (
          <label style={{ display:"flex", gap:10, alignItems:"flex-start", marginBottom:10, padding:"10px 12px", borderRadius:8, background:"var(--deny-pale)", border:"2px solid var(--deny)", cursor:"pointer" }}>
            <input type="checkbox" checked={!!overridePendingCraig} onChange={(e)=>onOverrideChange && onOverrideChange(e.target.checked)} style={{ marginTop:3, width:16, height:16, flexShrink:0 }}/>
            <span style={{ fontFamily:FB, fontSize:12.5, color:"var(--deny)", lineHeight:1.4 }}>
              <b>Override & write anyway</b> — I reviewed this note. Write the note and plan-type fields as shown
              {noteDirty ? " (including my edits)" : ""} to Dr. Chrono Primary Insurance Notes.
              PENDING CRAIG placeholders stay in the note unless I edited them.
            </span>
          </label>
        )}
        <div style={{ display:"flex", alignItems:"center", gap:10, flexWrap:"wrap" }}>
          <b style={{ fontFamily:FB, fontSize:12.5, color:INK }}>Save to chart — Steps 10–12</b>
          {armed ? <Tag tone="ok" small>WRITES ARMED</Tag> : <Tag tone="warn" small>DISARMED PREVIEW</Tag>}
          {pending && !overridePendingCraig ? <Tag tone="deny" small>PENDING CRAIG — will not write</Tag> : null}
          {pending && overridePendingCraig ? <Tag tone="warn" small>PENDING CRAIG — override armed</Tag> : null}
          <span style={{ flex:1 }}></span>
          <button className={"pill-btn "+(running?"loading":"")} disabled={busyWb||running||!canWrite} onClick={onWriteback} style={{ fontSize:12 }}
            title={btnTitle}>
            {running && <span className="wf-mini-spinner" aria-hidden="true"></span>}
            {btnLabel}
          </button>
        </div>
        <div style={{ marginTop:8, display:"grid", gap:5 }}>
          {(r.writeback && r.writeback.steps||[]).map(st=>(
            <div key={st.key} style={{ fontFamily:FM, fontSize:11.5, color:INK }}>
              <span style={{ color: st.recommended ? "var(--forest-mid)" : "var(--warn)", fontWeight:700 }}>{st.recommended?"READY":"HOLD"}</span>
              {" · "}{st.order}. {st.title} — {st.action}
            </div>
          ))}
        </div>
        {wb && wb.status==="done" && wb.result && (
          <div style={{ marginTop:8, display:"grid", gap:4, borderTop:"1px dashed "+LINE, paddingTop:8 }}>
            <div style={{ fontFamily:FM, fontSize:11.5, color:INK }}>{wb.result.armed?"ARMED":"DISARMED preview"} — {wb.result.message}</div>
            {(wb.result.steps||[]).slice().sort((a,b)=>a.order-b.order).map(s=>(
              <div key={s.key} style={{ fontFamily:FM, fontSize:11, color:INK }}>
                <span style={{ fontWeight:700, color: ["written","verified","noop","skipped"].includes(s.status)?"var(--forest-mid)":"var(--deny)" }}>{(s.status||"").toUpperCase()}</span>
                {" · "}{s.order}. {s.key} — {s.message}
              </div>
            ))}
          </div>
        )}
        {wb && wb.status==="error" && <div style={{ marginTop:6, fontFamily:FM, fontSize:11.5, color:"var(--deny)" }}>{wb.message}</div>}
      </div>
    );
  }

  function PatientChart({ row, run, wb, busyRun, busyWb, onRun, onWriteback, onBack }){
    const r = run && run.status==="done" ? run.result : null;
    const running = run && run.status==="running";
    const portal = deskPortal(row);
    const mbi = (r && r.cleaning && r.cleaning.memberId && r.cleaning.memberId.value) || row.memberId || "—";
    const pipelineNote = r ? String(r.chartNote || r.note || "") : "";
    const [noteDraft, setNoteDraft] = useState("");
    const [noteSourceKey, setNoteSourceKey] = useState("");
    const [overridePendingCraig, setOverridePendingCraig] = useState(false);
    const sourceKey = r ? (row.id + "|" + String(r.ranAt || row.deskWrittenAt || "") + "|" + String(run && run.fromDesk ? "desk" : "live")) : "";
    useEffect(()=>{
      if(sourceKey === noteSourceKey) return;
      setNoteSourceKey(sourceKey);
      setNoteDraft(pipelineNote);
      setOverridePendingCraig(false);
    }, [sourceKey, noteSourceKey, pipelineNote]);
    const note = noteSourceKey === sourceKey ? noteDraft : pipelineNote;
    const noteDirty = !!(pipelineNote && noteDraft && noteDraft !== pipelineNote);
    const avNote = r && portal.key === "availity"
      ? parseAvailityCommercial(note, r.availityCommercial)
      : null;
    const planType = r
      ? (portal.key === "availity" ? (avNote.planType || "—") : PLAN_TYPE_LABEL)
      : "—";
    const planTypeForWrite = r
      ? (portal.key === "availity"
        ? (avNote.planType && !/PENDING CRAIG/i.test(String(avNote.planType)) ? avNote.planType : undefined)
        : "Medicare Part B based")
      : undefined;
    const tag = rowTag({ row, run, wb });
    const idLabel = portal.key === "availity" ? "Ins ID" : "Medicare #";
    return (
      <div style={{ border:"1px solid "+LINE, borderRadius:12, overflow:"hidden", background:PURE, boxShadow:"var(--shadow-sm)" }}>
        {/* patient header bar */}
        <div style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 16px", background:CANVAS_MID, borderBottom:"1px solid "+LINE }}>
          <button className="pill-btn" onClick={onBack} style={{ fontSize:12 }}>← Live Claims Feed</button>
          <span style={{ display:"inline-flex", width:30, height:30, borderRadius:"50%", background:FOREST, color:"#fff", fontFamily:FM, fontSize:12, fontWeight:700, alignItems:"center", justifyContent:"center" }}>{initialsOf(row.patientName)}</span>
          <div>
            <div style={{ fontFamily:"var(--fd)", fontSize:16, color:INK }}>{row.patientName||"Unknown patient"}</div>
            <div style={{ fontFamily:FM, fontSize:10.5, color:INK_FAINT }}>Chart {row.patientRef||"—"} · Claim #{row.claimId||"—"} · {idLabel} {mbi}</div>
          </div>
          <span style={{ flex:1 }}></span>
          <Tag tone={tag.tone}>{tag.label}</Tag>
          {row.patientUrl && <a className="pill-btn" href={row.patientUrl} target="_blank" rel="noreferrer" style={{ fontSize:12 }}>Open in Dr. Chrono</a>}
        </div>

        {/* provider/appt strip */}
        <div style={{ display:"flex", gap:26, padding:"8px 16px", borderBottom:"1px solid "+LINE, fontSize:12, color:INK_SOFT }}>
          <span><b style={{ color:INK }}>Payer</b> · {row.payer||"—"}</span>
          <span><b style={{ color:INK }}>DOS</b> · {row.dos||"—"}</span>
          <span><b style={{ color:INK }}>Bucket</b> · {row.bucket||"—"}</span>
          <span style={{ flex:1 }}></span>
          <button className={"pill-btn "+(running?"loading":"")} disabled={busyRun||running||!row.patientRef} onClick={()=>onRun(row)} style={{ fontSize:12.5 }}
            title={r ? `Re-read ${portal.name} and rebuild the proposed note (does not write until you Save Demographics)` : `Read ${portal.name} and propose the insurance note`}>
            {running && <span className="wf-mini-spinner" aria-hidden="true"></span>}
            {running
              ? `Reading ${portal.name}…`
              : (r
                ? (run && run.fromDesk ? `Re-run from ${portal.short} (refresh note)` : "Re-run eligibility")
                : `Run eligibility (${portal.name} read)`)}
          </button>
        </div>

        <div style={{ display:"flex" }}>
          {/* chart left nav (cosmetic) */}
          <div style={{ width:170, flexShrink:0, background:CANVAS_MID, borderRight:"1px solid "+LINE, padding:"8px 0" }}>
            {CHART_LEFTNAV.map(x=>(
              <div key={x} style={{ padding:"7px 14px", fontSize:12, color: x==="Demographics"?"#fff":INK_SOFT, background: x==="Demographics"?FOREST_LIGHT:"transparent", fontWeight: x==="Demographics"?600:400 }}>{x}</div>
            ))}
          </div>

          {/* main: two columns — Insurances form + NGS panel */}
          <div style={{ flex:1, minWidth:0, padding:"12px 16px" }}>
            {r && r.pendingCraig && r.pendingCraig.length>0 && (
              <div style={{ marginBottom:10, padding:"9px 12px", borderRadius:8, background:"var(--deny-pale)", border:"1px solid var(--deny)", fontFamily:FB, fontSize:12, color:"var(--deny)" }}>
                <div>
                  <b>PENDING CRAIG</b> — {r.pendingCraig.map((x)=>{
                    let s=String(x||"").replace(/\s+/g," ").trim();
                    // Never show Availity DOM inventories / field dumps on the desk.
                    s=s.replace(/\s*\|\s*fields:\s*.+$/i,"").replace(/\b(?:INPUT|BUTTON|SELECT|TEXTAREA)\[[^\]]{0,200}\]/gi,"").replace(/\borgAfter="[^"]*"\s*/gi,"").replace(/\s+/g," ").trim();
                    if(/patient\s*last\s*name/i.test(s)&&/enter a name|invalid|error/i.test(s)) s="Availity rejected inquiry: Patient Last Name invalid";
                    else if(/patient\s*first\s*name/i.test(s)&&/enter a name|invalid|error/i.test(s)) s="Availity rejected inquiry: Patient First Name invalid";
                    else if(/results not recognized/i.test(s)&&/alerts=/i.test(s)) s="Availity rejected inquiry: form validation failed";
                    if(s.length>160) s=s.slice(0,157)+"…";
                    return s;
                  }).filter(Boolean).join("; ") || "needs human review"}.
                  {row.deskDisposition==="pending_craig" || (wb && wb.fromDesk)
                    ? " Note is already on the chart for Craig to review."
                    : " Review/edit the note below, then check Override & write anyway to save to Dr. Chrono."}
                </div>
                {!(row.deskDisposition==="pending_craig" || (wb && wb.fromDesk)) && (
                  <label style={{ display:"flex", gap:10, alignItems:"flex-start", marginTop:10, padding:"9px 10px", borderRadius:8, background:"#fff", border:"2px solid var(--deny)", cursor:"pointer", color:"var(--deny)" }}>
                    <input type="checkbox" checked={!!overridePendingCraig} onChange={(e)=>setOverridePendingCraig(e.target.checked)} style={{ marginTop:2, width:16, height:16, flexShrink:0 }}/>
                    <span style={{ fontFamily:FB, fontSize:12.5, lineHeight:1.4 }}>
                      <b>Override & write anyway</b> — I reviewed this note and want Save Demographics enabled.
                    </span>
                  </label>
                )}
              </div>
            )}
            {run && run.fromDesk && (row.deskDisposition==="proposed" || run.deskPreview) && (
              <div style={{ marginBottom:10, padding:"9px 12px", borderRadius:8, background:"rgba(180,140,40,.10)", border:"1px solid rgba(180,140,40,.45)", fontFamily:FB, fontSize:12, color:"#7a5a10" }}>
                <b>Dry-run preview</b> — saved in OpAgent{row.deskWrittenAt ? (" · "+new Date(row.deskWrittenAt).toLocaleString()) : ""}. Not written to Dr. Chrono until you click Save Demographics (writes armed).
              </div>
            )}
            {run && run.fromDesk && row.deskWrittenAt && row.deskDisposition!=="proposed" && !run.deskPreview && (
              <div style={{ marginBottom:10, padding:"9px 12px", borderRadius:8, background:FOREST_PALE, border:"1px solid "+FOREST_LIGHT, fontFamily:FB, fontSize:12, color:"var(--forest-mid)" }}>
                <b>Last writeback</b> — {new Date(row.deskWrittenAt).toLocaleString()}. Showing the note OpAgent saved to primary insurance (re-run to refresh from {portal.name}).
              </div>
            )}
            {r && r.softCheckFyi && r.softCheckFyi.length>0 && !(r.pendingCraig && r.pendingCraig.length) && (
              <div style={{ marginBottom:10, padding:"9px 12px", borderRadius:8, background:"rgba(180,140,40,.10)", border:"1px solid rgba(180,140,40,.45)", fontFamily:FB, fontSize:12, color:"#7a5a10" }}>
                <b>271 FYI</b> — {r.softCheckFyi.join("; ")}. Portal determination resolved; soft check does not block proposal.
              </div>
            )}

            {/* Insurances tab strip */}
            <div style={{ display:"flex", gap:2, borderBottom:"1px solid "+LINE, marginBottom:4 }}>
              {INS_TABS.map(t=>(
                <span key={t} style={{ padding:"7px 12px", fontSize:12.5, color: t==="Insurances"?INK:INK_SOFT, borderBottom: t==="Insurances"?"2px solid "+FOREST_LIGHT:"2px solid transparent", fontWeight: t==="Insurances"?600:400 }}>{t}</span>
              ))}
            </div>
            <div style={{ display:"flex", gap:4, marginBottom:12 }}>
              {INS_SUBTABS.map(t=>(
                <span key={t} style={{ fontFamily:FM, fontSize:10.5, padding:"3px 9px", borderRadius:20, color: t==="Primary Ins"?"#fff":INK_SOFT, background: t==="Primary Ins"?(portal.key==="availity"?AVAILITY:SLATE):PURE, border:"1px solid "+(t==="Primary Ins"?(portal.key==="availity"?AVAILITY:SLATE):LINE) }}>{t}</span>
              ))}
            </div>

            <div style={{ display:"grid", gridTemplateColumns:"minmax(0,1fr) minmax(320px,420px)", gap:18 }}>
              {/* Demographics → Insurances form */}
              <div>
                <div style={{ fontFamily:"var(--fd)", fontSize:14, color:INK, marginBottom:10 }}>Default Primary Insurance</div>
                <Field label="Insurance Company" value={row.payer}/>
                <Field label="Carrier Payer ID" value={row.payerId} mono/>
                <Field label="Insurance ID Number" value={mbi} mono/>
                <Field label="Insurance plan type" value={planType} highlight={!!r}/>
                <Field
                  label="Primary Insurance Notes"
                  value={r ? note : (running ? `Reading ${portal.name}…` : "(run eligibility to generate a dry-run preview — Save Demographics writes to Dr. Chrono)")}
                  area
                  highlight={!!note}
                  editable={!!r && !!pipelineNote}
                  onChange={setNoteDraft}
                  placeholder="Edit the proposed note before writing to Dr. Chrono…"
                />
                {r && !!pipelineNote && (
                  <div style={{ margin:"-2px 0 10px 160px", fontFamily:FM, fontSize:10.5, color:INK_FAINT }}>
                    Editable — your edits are what get written on Save Demographics{noteDirty ? " · edited" : ""}.
                  </div>
                )}
                <WritebackStrip
                  run={run}
                  wb={wb}
                  busyWb={busyWb}
                  overridePendingCraig={overridePendingCraig}
                  onOverrideChange={setOverridePendingCraig}
                  noteDirty={noteDirty}
                  onWriteback={()=>onWriteback(row, {
                    overridePendingCraig: !!overridePendingCraig,
                    chartNoteOverride: note,
                    planTypeLabel: planTypeForWrite,
                  })}
                />
              </div>

              {/* Portal determination panel (NGSConnex blue / Availity orange) */}
              <div>
                <PortalEligPanel row={row} run={run}/>
                {r && (
                  <details style={{ marginTop:10 }}>
                    <summary style={{ fontFamily:FM, fontSize:11, color:INK_SOFT, cursor:"pointer" }}>Full signed audit note (preview)</summary>
                    <pre style={{ whiteSpace:"pre-wrap", fontFamily:FM, fontSize:11, color:INK, margin:"6px 0 0", border:"1px solid "+LINE, borderRadius:8, padding:"8px 10px", background:CANVAS_MID }}>{r.note}</pre>
                  </details>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─────────────────────────────────────────────────────────
  //  Module root
  // ─────────────────────────────────────────────────────────
  window.EligDeskModule = function EligDeskModule(){
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [err, setErr] = useState("");
    const [portal, setPortal] = useState(null);
    const [availity, setAvaility] = useState(null);
    const [ehrSession, setEhrSession] = useState(null);
    const [selectedId, setSelectedId] = useState("");
    const [runs, setRuns] = useState({});
    const [busyRun, setBusyRun] = useState("");
    const [wb, setWb] = useState({});
    const [busyWb, setBusyWb] = useState("");
    const [sweep, setSweep] = useState(null);
    const [coverageAll, setCoverageAll] = useState(false);

    // Rebuild in-memory run/wb from sticky server desk state so opening a
    // patient after refresh still shows the last dry-run preview (or write).
    function hydrateFromDesk(queue){
      if(!Array.isArray(queue) || !queue.length) return;
      setRuns(prev=>{
        const next = Object.assign({}, prev);
        for(const row of queue){
          if(!row || !row.id || !row.deskChartNote) continue;
          // Never hydrate empty/placeholder notes as a finished dry-run (fake PROPOSED READY).
          if(row.deskDisposition==="proposed" && !meaningfulEligNote(row.deskChartNote)) continue;
          const cur = next[row.id];
          // Don't clobber a fresher live run in this tab session.
          if(cur && cur.status==="done" && cur.result && !cur.fromDesk) continue;
          if(cur && cur.status==="running") continue;
          const written = row.deskDisposition==="done" || row.deskDisposition==="partial" || row.deskDisposition==="pending_craig";
          next[row.id] = {
            status:"done",
            fromDesk:true,
            deskPreview: !written,
            result:{
              chartNote: row.deskChartNote,
              note: row.deskChartNote,
              terminalStatus: row.deskTerminalStatus || (row.deskDisposition==="pending_craig" ? "PENDING CRAIG" : "blank"),
              pendingCraig: row.deskPendingCraig || [],
              softCheckFyi: row.deskSoftCheckFyi || [],
              cleaning:{ memberId:{ value: row.memberId||"" } },
              writeback:{
                // Proposed dry-runs still need Save Demographics when server writes are armed.
                armed: (row.deskDisposition === "proposed" && meaningfulEligNote(row.deskChartNote)) || !!written,
                // Restored proposed runs have no stored write steps (they were never
                // written) — synthesize the Steps 10–12 preview so the box below Save
                // still shows exactly what a Save Demographics will write (2026-08-18).
                steps:((row.deskWriteSteps && row.deskWriteSteps.length) ? row.deskWriteSteps : [
                  { key:"insurance_note", order:10, status:"preview", recommended:true,
                    message:"Will paste the note shown above ("+String(row.deskChartNote||"").length+" chars) into Primary Insurance Notes — any prior note is preserved below a dated divider." },
                  { key:"billing_status", order:11, status:"skipped", recommended:false,
                    message:"Benchmark mode: billing status is never flipped — the human rep reviews." },
                  { key:"plan_type", order:12, status:"preview", recommended:true,
                    message:"Will set the insurance plan type shown above (when the insurer offers it)." },
                ]).map(s=>({
                  key:s.key, order:s.order, status:s.status, message:s.message,
                  recommended: (s.recommended != null) ? s.recommended : ["written","verified","noop"].includes(s.status),
                  title: s.key==="insurance_note"?"Update demographics insurance note"
                    : s.key==="plan_type"?"Set plan type"
                    : s.key==="billing_status"?"Advance billing status"
                    : s.key,
                  action: s.message || s.status,
                })),
              },
              stages:[],
            },
          };
        }
        return next;
      });
      setWb(prev=>{
        const next = Object.assign({}, prev);
        for(const row of queue){
          // Only hydrate writeback outcomes for real DrChrono saves — never
          // pretend a dry-run preview was written to the chart.
          const written = row && (row.deskDisposition==="done" || row.deskDisposition==="partial" || row.deskDisposition==="pending_craig");
          if(!written || !row.deskWriteSteps || !row.deskWriteSteps.length) continue;
          const cur = next[row.id];
          if(cur && cur.status==="done" && cur.result && !cur.fromDesk) continue;
          if(cur && cur.status==="running") continue;
          next[row.id] = {
            status:"done",
            fromDesk:true,
            result:{
              ok:true,
              armed:true,
              message: row.deskWrittenAt
                ? ("Last writeback "+new Date(row.deskWrittenAt).toLocaleString()+" — note verified in Dr. Chrono.")
                : "Last writeback on file — note verified in Dr. Chrono.",
              steps: (row.deskWriteSteps||[]).map(s=>({
                key:s.key, order:s.order||0, status:s.status, message:s.message||s.status,
              })),
            },
          };
        }
        return next;
      });
    }

    async function loadWorklist(refresh, allOverride){
      setLoading(true); setErr("");
      try {
        const all = (allOverride===undefined ? coverageAll : allOverride);
        // Retry once on a soft miss (timeout/null). Do NOT force refresh=1 on retry —
        // that piles a second full scrape on top of the first and makes timeouts worse.
        let j = await window.Adapters.eligibilityWorklist(refresh, all);
        if(!j) j = await window.Adapters.eligibilityWorklist(false, all);
        const hasQueue = !!(j && Array.isArray(j.queue) && j.queue.length);
        // A queue (even with a soft error string) is success — never blank the desk.
        if(j && (hasQueue || !j.error || j.pending || j.stale)){ setErr(""); setData(j); if(hasQueue) hydrateFromDesk(j.queue); }
        else { setErr((j&&j.error)||"Worklist unavailable. Connect Dr. Chrono and retry."); if(j) setData(j); }
        // Keep polling while scrape is pending OR identity enrich/repair is still
        // stamping DOB/MBI — stopping at first queue publish left newly added
        // patients blank under the name forever.
        const stillEnriching = (payload) => !!(
          payload
          && (payload.pending
            || payload.identityEnriching
            || (typeof payload.missingDob === "number" && payload.missingDob > 0 && payload.stale))
        );
        if(j && (stillEnriching(j) || (refresh && !hasQueue && !j.error))){
          for(let i=0;i<90;i++){
            await new Promise(r=>setTimeout(r, 2000));
            const again = await window.Adapters.eligibilityWorklist(false, all);
            if(!again) continue;
            if(again.pending){ setData(again); continue; }
            const q = !!(again.queue && again.queue.length);
            if(q || !again.error){
              setErr("");
              setData(again);
              if(q) hydrateFromDesk(again.queue);
              // Bucket landed but DOB/MBI enrich still running — keep polling.
              if(stillEnriching(again)) continue;
              break;
            }
            setErr(again.error||"Worklist unavailable. Connect Dr. Chrono and retry.");
            setData(again);
            break;
          }
        }
      } catch(_e){ setErr("Worklist unavailable. Connect Dr. Chrono and retry."); }
      finally { setLoading(false); }
    }
    async function connectPortal(code){
      try {
        const typed = (code || "").trim();
        // Empty Reconnect → credentialWake (password). Typed code → enter once.
        const r = await window.Adapters.eligibilityPortalLogin(typed, { credentialWake: !typed });
        setPortal(Object.assign({}, r, { reconnecting:false, needsMfa: !!(r && r.needsMfa) }));
        return r;
      } catch(e){
        const fail = { connected:false, sessionExists:false, needsMfa:true, reconnecting:false, reason:(e&&e.message)||"Login failed" };
        setPortal(fail);
        return fail;
      }
    }
    // On tab open: status → probe-only wake if profile on disk (no password / MFA).
    // User Reconnect does credentialWake. MFA field only for human paste of today's code.
    async function refreshPortalStatus(){
      try {
        const st = await window.Adapters.eligibilityPortalStatus();
        setPortal(Object.assign({}, st||{}, { reconnecting:false, needsMfa: !!(st && st.needsMfa) }));
        return st;
      } catch(_e){
        return null;
      }
    }
    async function ensurePortal(){
      try {
        // Status + probe-only. Do NOT auto password-wake NGS on desk open —
        // that burns the daily MFA cap and contends with DrChrono worklist /
        // Availity cold-warm after ECS deploys. Operator clicks Reconnect when
        // Medicare work is needed (Availity commercial can proceed without NGS).
        let st = await window.Adapters.eligibilityPortalStatus();
        if(st && st.sessionExists && !st.connected && !st.needsMfa){
          setPortal(Object.assign({}, st, { reconnecting:true, needsMfa:false }));
          const woken = await window.Adapters.eligibilityPortalLogin("", { credentialWake: false });
          st = woken || st;
        }
        setPortal(Object.assign({}, st||{}, {
          reconnecting:false,
          needsMfa: !!(st && st.needsMfa),
        }));
      } catch(_e){
        setPortal({ connected:false, sessionExists:false, needsMfa:false, reconnecting:false, reason:"status unavailable" });
      }
    }
    async function startManualPortal(){
      return window.Adapters.eligibilityPortalManualLogin();
    }
    async function refreshAvailityStatus(){
      try {
        const st = await window.Adapters.eligibilityAvailityStatus();
        setAvaility(st || { connected:false });
        return st;
      } catch(_e){ return null; }
    }
    // Status-only on desk open. Do NOT auto credential-wake Availity here —
    // that contended with the DrChrono worklist scrape and blanked the feed.
    // Operator clicks Connect Availity (TOTP is automatic from Secrets Manager).
    async function ensureAvaility(){
      try {
        const st = await window.Adapters.eligibilityAvailityStatus();
        setAvaility(st || { connected:false });
      } catch(_e){
        setAvaility({ connected:false, reason:"status unavailable" });
      }
    }
    async function connectAvaility(){
      try {
        // Fire-and-poll — server returns immediately; CloudFront would 504 a long wait.
        let r = await window.Adapters.eligibilityAvailityLogin({ credentialWake: true });
        setAvaility(r || { connected:false });
        if(r && r.connected) return r;
        const deadline = Date.now() + 150_000;
        while(Date.now() < deadline){
          await new Promise(res=>setTimeout(res, 2500));
          const st = await window.Adapters.eligibilityAvailityStatus();
          if(!st) continue;
          setAvaility(st);
          if(st.connected) return st;
          // Final failure (login finished, not mid-connect).
          if(st.reason && !/connecting/i.test(st.reason) && !/click Connect/i.test(st.reason)){
            await new Promise(res=>setTimeout(res, 2000));
            const again = await window.Adapters.eligibilityAvailityStatus();
            if(again) setAvaility(again);
            if(again && again.connected) return again;
            if(again && again.reason && /connecting/i.test(again.reason)) continue;
            return again || st;
          }
        }
        return r || { connected:false, reason:"Availity login timed out" };
      } catch(e){
        const fail = { connected:false, reason:(e&&e.message)||"Availity login failed" };
        setAvaility(fail);
        return fail;
      }
    }
    async function refreshEhrSession(){
      try {
        const r = await fetch("/api/inside/session");
        const st = await r.json().catch(()=>({}));
        setEhrSession(st || { healthy:false });
        return st;
      } catch(_e){ setEhrSession({ healthy:false }); return null; }
    }
    async function reconnectEhr(){
      await window.Adapters.startRelogin();
      const deadline = Date.now() + 90_000;
      while(Date.now() < deadline){
        await new Promise(r=>setTimeout(r, 2000));
        const st = await refreshEhrSession();
        if(st && st.healthy) return st;
        if(st && st.relogin && (st.relogin.result === "failed" || st.relogin.result === "timeout")) break;
      }
      return refreshEhrSession();
    }
    useEffect(()=>{
      loadWorklist(false);
      ensurePortal();
      ensureAvaility();
      refreshEhrSession();
      // Re-probe portal status on an interval so the badge can NEVER go stale
      // (e.g. after a redeploy or a silent NGS session drop). The backend
      // short-circuits this probe while a manual login is running, so it's safe.
      // Status-only (no credential wake) — avoids burning NGS MFA on every poll.
      const iv = setInterval(()=>{ refreshPortalStatus(); refreshAvailityStatus(); refreshEhrSession(); }, 20000);
      return ()=>clearInterval(iv);
      /* eslint-disable-next-line */
    },[]);

    function stampProposedOnQueue(rowId, result){
      const note = String((result && (result.chartNote || result.note)) || "").trim();
      // Never mint a green PROPOSED READY from empty / placeholder notes.
      if(!meaningfulEligNote(note)) return;
      setData(prev=>{
        if(!prev || !Array.isArray(prev.queue)) return prev;
        return Object.assign({}, prev, {
          queue: prev.queue.map(r=>{
            if(r.id!==rowId) return r;
            return Object.assign({}, r, {
              deskDisposition: "proposed",
              deskWrittenAt: new Date().toISOString(),
              deskChartNote: note,
              deskNoteHead: note.slice(0, 220).replace(/\s+/g, " ").trim(),
              deskTerminalStatus: result.terminalStatus,
              deskPendingCraig: result.pendingCraig || [],
              deskSoftCheckFyi: result.softCheckFyi || [],
              deskWriteSteps: [],
            });
          }),
        });
      });
    }
    async function onRun(row){
      // One NGS tab for the whole service — never start a second dry-run while
      // another is in flight (queue sweep or chart re-run). Overlap was flipping
      // PENDING/PROPOSED on the same patients.
      if (busyRun || (sweep && sweep.running)) {
        setErr("Another eligibility run is in progress — wait for it to finish (shared portal session).");
        return { status:"error", message:"eligibility_run_in_progress" };
      }
      if (row && row.liveCapable && !row.dob) {
        const msg = "DOB missing — wait for chart enrich or Refresh bucket before NGS/Availity lookup.";
        setErr(msg);
        const outcome = { status:"error", message: msg };
        setRuns(m=>Object.assign({}, m, { [row.id]: outcome }));
        return outcome;
      }
      setBusyRun(row.id);
      setRuns(m=>Object.assign({}, m, { [row.id]: { status:"running" } }));
      let outcome = { status:"error" };
      try {
        const r = await window.Adapters.eligibilityRun(row.id, { patientRef:row.patientRef, appointmentId:row.claimId, payer:row.payer, patientName:row.patientName, memberId:row.memberId, dob:row.dob, pcp:row.pcp });
        const errMsg = (r && r.error) || "";
        if (r && /Connect NGS|Connect Availity|click Connect|MFA required/i.test(errMsg)) {
          setErr(errMsg);
          outcome = { status:"error", message: errMsg };
        } else {
          outcome = (!r || r.error) ? { status:"error", message: errMsg || "Pipeline failed" } : { status:"done", result:r.result };
        }
        if(outcome.status==="done" && outcome.result) {
          stampProposedOnQueue(row.id, outcome.result);
          // Pull EFS deskDisposition so table/header stay PROPOSED after back-nav / refresh.
          // Soft refresh (no scrape) — stampWorklistDeskState merges sticky notes.
          try { await loadWorklist(false); } catch(_e) { /* keep local stamp */ }
        }
      } catch(e){ outcome = { status:"error", message:(e&&e.message)||"Pipeline failed" }; }
      finally { setRuns(m=>Object.assign({}, m, { [row.id]: outcome })); setBusyRun(""); }
      return outcome;
    }
    async function onWriteback(row, opts){
      if (busyRun || busyWb || (sweep && sweep.running)) {
        setWb(m=>Object.assign({}, m, { [row.id]: { status:"error", message:"Wait for the current eligibility run to finish before writing." } }));
        return;
      }
      const overridePendingCraig = !!(opts && opts.overridePendingCraig);
      const chartNoteOverride = opts && typeof opts.chartNoteOverride === "string" ? opts.chartNoteOverride.trim() : "";
      const planTypeLabel = opts && typeof opts.planTypeLabel === "string" ? opts.planTypeLabel.trim() : "";
      setBusyWb(row.id);
      setWb(m=>Object.assign({}, m, { [row.id]: { status:"running" } }));
      try {
        const payload = {
          patientRef:row.patientRef,
          appointmentId:row.claimId,
          payer:row.payer,
          patientName:row.patientName,
          memberId:row.memberId,
          dob:row.dob,
          pcp:row.pcp,
        };
        if (overridePendingCraig) payload.overridePendingCraig = true;
        if (chartNoteOverride) payload.chartNoteOverride = chartNoteOverride;
        if (planTypeLabel && !/PENDING CRAIG/i.test(planTypeLabel) && planTypeLabel !== "—") payload.planTypeLabel = planTypeLabel;
        const r = await window.Adapters.eligibilityWriteback(row.id, payload);
        if(!r || r.error) setWb(m=>Object.assign({}, m, { [row.id]: { status:"error", message:(r&&(r.error||r.reason||r.writeback&&r.writeback.blocked))||"Writeback failed" } }));
        else if(r.writeback && r.writeback.ok === false && r.writeback.blocked) setWb(m=>Object.assign({}, m, { [row.id]: { status:"error", message:r.writeback.blocked } }));
        else setWb(m=>Object.assign({}, m, { [row.id]: { status:"done", result:r.writeback } }));
      } catch(e){ setWb(m=>Object.assign({}, m, { [row.id]: { status:"error", message:(e&&e.message)||"Writeback failed" } })); }
      finally { setBusyWb(""); }
    }
    async function runQueue(opts){
      if (busyRun || (sweep && sweep.running)) return;
      const remainingOnly = !!(opts && opts.remainingOnly);
      const mode = remainingOnly ? "remaining" : "all";
      const rows = (data && data.queue ? data.queue : []).filter(r=>{
        if(!r.patientRef || r.status==="needs-human-review") return false;
        if(remainingOnly) return isRemainingWork({ row:r, run:runs[r.id], wb:wb[r.id] });
        return true;
      });
      if(!rows.length) return;
      setErr("");
      setSweep({ total:rows.length, done:0, running:true, mode });
      let aborted = null;
      for(let i=0;i<rows.length;i++){
        // Bypass the busyRun guard for sequential queue steps (we hold sweep.running).
        // Shared portal lock + server 409 still serialize one-at-a-time.
        const row = rows[i];
        const prior = runs[row.id];
        setBusyRun(row.id);
        setRuns(m=>Object.assign({}, m, { [row.id]: { status:"running" } }));
        let outcome = { status:"error" };
        try {
          // Skip DOB-missing portal rows without painting ERROR (filter should already exclude).
          const pk = row.portalKey || deskPortal(row).key || "";
          const needsDob = !!(row.liveCapable || pk === "ngsconnex" || pk === "availity");
          if (needsDob && !String(row.dob || "").trim()) {
            outcome = prior && prior.status !== "running" ? prior : null;
          } else {
            const r = await window.Adapters.eligibilityRun(row.id, {
              patientRef:row.patientRef,
              appointmentId:row.claimId,
              payer:row.payer,
              patientName:row.patientName,
              memberId:row.memberId,
              dob:row.dob,
              pcp:row.pcp,
            });
            const errMsg = r && (r.error || r.message) || "";
            // Systemic / lock / Connect-needed errors must NOT mass-paint every remaining row ERROR.
            if (r && (r.error === "sign_in_required" || r.unauthenticated)) {
              aborted = "Sign in required — re-open Eligibility Desk and sign in, then Run remaining again.";
              outcome = prior && prior.status !== "running" ? prior : null;
            } else if (r && (r.error === "eligibility_run_in_progress" || /in progress/i.test(String(errMsg)))) {
              aborted = "Another eligibility run is still holding the shared portal session — wait for it to finish, then Run remaining again.";
              outcome = prior && prior.status !== "running" ? prior : null;
            } else if (r && /Connect NGS|Connect Availity|click Connect|MFA required/i.test(String(errMsg))) {
              aborted = String(errMsg);
              outcome = prior && prior.status !== "running" ? prior : null;
            } else if (!r || r.error) {
              outcome = { status:"error", message: errMsg || "Pipeline failed" };
            } else {
              outcome = { status:"done", result:r.result };
              if (outcome.result) stampProposedOnQueue(row.id, outcome.result);
            }
          }
        } catch(e){
          outcome = { status:"error", message:(e&&e.message)||"Pipeline failed" };
        } finally {
          if (outcome) setRuns(m=>Object.assign({}, m, { [row.id]: outcome }));
          else setRuns(m=>{
            const next = Object.assign({}, m);
            if (prior) next[row.id] = prior;
            else delete next[row.id];
            return next;
          });
          setBusyRun("");
        }
        setSweep({ total:rows.length, done:i+1, running:i+1<rows.length && !aborted, mode });
        if (aborted) break;
      }
      if (aborted) setErr(aborted);
      setSweep(s=>s?Object.assign({}, s, { running:false }):s);
    }

    // Never block the whole tab on the slow claims-feed scrape — show the EHR
    // chrome immediately; the table shows its own loading state.
    const d = data || { queue:[], buckets:{}, statuses:[], benchmark:null, coverage:null, pending: loading };
    const signer = (window.DEMO && window.DEMO.practice && window.DEMO.practice.signer) || "Craig Epstein";
    const selected = d.queue.find(r=>r.id===selectedId) || null;

    return (
      <div className="module">
        <div className="idr-wrap" style={{ display:"grid", gap:14 }}>
          {!!err && <div className="datamode-banner" style={{ background:"rgba(154,42,42,.08)", border:"1px solid rgba(154,42,42,.28)", color:"#7a1e1e" }}>{err}</div>}

          <EhrChrome portal={portal} availity={availity} ehrSession={ehrSession} onReconnectEhr={reconnectEhr} signer={signer}
            onConnectPortal={connectPortal}
            onManualPortal={startManualPortal}
            onPortalStatus={refreshPortalStatus}
            onConnectAvaility={connectAvaility}
            context={selected ? `Patient chart · ${selected.patientName||""} · Claim #${selected.claimId||"—"}` : "Billing · Live Claims Feed · ELIG REQUIRED statuses · back to the beginning of time"}/>

          {selected ? (
            <PatientChart row={selected} run={runs[selected.id]} wb={wb[selected.id]}
              busyRun={busyRun===selected.id} busyWb={busyWb===selected.id}
              onRun={onRun} onWriteback={onWriteback} onBack={()=>setSelectedId("")}/>
          ) : (
            <ClaimsFeed data={d} loading={loading} runs={runs} wb={wb} sweep={sweep} busyRun={busyRun}
              onOpen={(row)=>setSelectedId(row.id)} onRerun={onRun}
              onRefresh={()=>loadWorklist(true)}
              onSweep={()=>runQueue({ remainingOnly:false })}
              onSweepRemaining={()=>runQueue({ remainingOnly:true })}
              coverageAll={coverageAll} onToggleCoverage={(v)=>{ setCoverageAll(v); loadWorklist(false, v); }}/>
          )}
        </div>
      </div>
    );
  };
})();
