/* global React, I, useState, useEffect, useMemo, CheckBox, FilterPills, Modal */

// ============================================================================
// CLAIMS
// ============================================================================
const CLAIMS = [
  { id: "C-1841", patient: "Katie Filby", insurance: "Delta Dental of California", dos: "Apr 28, 2026", primary: true, billed: 348.00, status: "draft", attach: false, prov: "TDR" },
  { id: "C-1840", patient: "Chase Rowley", insurance: "Aetna Open Access", dos: "Apr 22, 2026", primary: true, billed: 480.00, status: "draft", attach: true, prov: "MR" },
  { id: "C-1839", patient: "Ross Geller", insurance: "Delta Dental PPO", dos: "Apr 27, 2026", primary: true, billed: 188.00, status: "draft", attach: false, prov: "JP" },
  { id: "C-1838", patient: "Phoebe Buffay", insurance: "United Concordia", dos: "Apr 26, 2026", primary: true, billed: 88.00, status: "draft", attach: false, prov: "EL" },
  { id: "C-1837", patient: "Chandler Bing", insurance: "MetLife PPO", dos: "Apr 24, 2026", primary: false, billed: 750.00, status: "blocked", attach: true, blockReason: "A clipping of the primary claim's EOB is required.", prov: "TDR" },
  { id: "C-1836", patient: "Tom Haverford", insurance: "Self-pay", dos: "Apr 23, 2026", primary: true, billed: 1200.00, status: "draft", attach: false, prov: "RG" },
  { id: "C-1835", patient: "Joey Tribbiani", insurance: "Cigna Dental Care", dos: "Apr 22, 2026", primary: true, billed: 2150.00, status: "draft", attach: true, prov: "MR" },
  { id: "C-1834", patient: "Rachel Green", insurance: "Guardian", dos: "Apr 21, 2026", primary: true, billed: 165.00, status: "draft", attach: false, prov: "JP" },
  { id: "C-1833", patient: "Ben Wyatt", insurance: "Anthem BCBS", dos: "Apr 20, 2026", primary: true, billed: 245.00, status: "draft", attach: false, prov: "RG" },
  { id: "C-1832", patient: "Andy Dwyer", insurance: "Anthem BCBS", dos: "Apr 20, 2026", primary: true, billed: 132.00, status: "draft", attach: false, prov: "TDR" },
  { id: "C-1831", patient: "Leslie Knope", insurance: "Humana Dental", dos: "Apr 18, 2026", primary: true, billed: 320.00, status: "draft", attach: false, prov: "SK" },
  { id: "C-1830", patient: "April Ludgate", insurance: "MetLife PPO", dos: "Apr 18, 2026", primary: true, billed: 105.00, status: "draft", attach: false, prov: "EL" },
  { id: "C-1829", patient: "Monica Geller", insurance: "Self-pay", dos: "Apr 17, 2026", primary: true, billed: 0, status: "draft", attach: false, prov: "SK" },
  { id: "C-1828", patient: "Bobby Newport", insurance: "Cigna Dental Care", dos: "Apr 17, 2026", primary: true, billed: 265.00, status: "draft", attach: false, prov: "MR" },
];

const SENT_CLAIMS = [
  { id: "C-1820", patient: "Jandy Olivey", insurance: "Delta Dental of California", dos: "Apr 14, 2026", billed: 480.00, paid: 380.00, status: "underpaid", sentDate: "Apr 15", paidDate: "Apr 22" },
  { id: "C-1819", patient: "Marcus Hill", insurance: "Delta Dental of California", dos: "Apr 14, 2026", billed: 348.00, paid: 348.00, status: "paid", sentDate: "Apr 15", paidDate: "Apr 22" },
  { id: "C-1818", patient: "Hannah Sloane", insurance: "Delta Dental of California", dos: "Apr 12, 2026", billed: 165.00, paid: 165.00, status: "paid", sentDate: "Apr 13", paidDate: "Apr 22" },
  { id: "C-1817", patient: "Donna Meagle", insurance: "Delta Dental of California", dos: "Apr 11, 2026", billed: 740.00, paid: 590.00, status: "underpaid", sentDate: "Apr 12", paidDate: "Apr 22" },
  { id: "C-1816", patient: "Jerry Gergich", insurance: "Delta Dental of California", dos: "Apr 10, 2026", billed: 245.00, paid: 245.00, status: "paid", sentDate: "Apr 11", paidDate: "Apr 22" },
  { id: "C-1815", patient: "Tommy Park", insurance: "Delta Dental of California", dos: "Apr 8, 2026", billed: 880.00, paid: 0, status: "denied", sentDate: "Apr 9", paidDate: "—" },
  { id: "C-1814", patient: "Mark Brendanawicz", insurance: "Delta Dental of California", dos: "Apr 8, 2026", billed: 132.00, paid: 132.00, status: "paid", sentDate: "Apr 9", paidDate: "Apr 22" },
];

function Claims({ onOpenEOB }) {
  const [tab, setTab] = useState("drafts");
  const [selected, setSelected] = useState(new Set());
  const [carrierFilter, setCarrierFilter] = useState("all");

  const rows = tab === "drafts" ? CLAIMS : SENT_CLAIMS;
  const filtered = tab === "sent" && carrierFilter !== "all"
    ? rows.filter(r => r.insurance.startsWith(carrierFilter))
    : rows;

  const toggleAll = () => {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map(r => r.id)));
  };
  const toggle = (id) => {
    const n = new Set(selected);
    if (n.has(id)) n.delete(id); else n.add(id);
    setSelected(n);
  };

  const selectedSum = filtered.filter(r => selected.has(r.id)).reduce((acc, r) => acc + (tab === "drafts" ? r.billed : r.paid || 0), 0);
  const submitCount = selected.size > 0 ? selected.size : filtered.filter(r => r.status === "draft").length;

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600 }}>Claims</div>
            <div className="tiny muted">via Dental Exchange · unlimited submissions + attachments</div>
          </div>
          <div className="spacer" />
          <div className="row" style={{ gap: 14 }}>
            <Stat label="Drafts" v="14" color="amber" />
            <Stat label="In flight" v="38" color="blue" />
            <Stat label="Paid (30d)" v="$24.8k" color="sage" />
            <Stat label="Denials" v="2" color="rose" />
            <Stat label="Avg days to pay" v="11.2" />
          </div>
        </div>

        <div style={{ display: "flex", alignItems: "center", marginTop: 10 }}>
          <div className="tabs" style={{ borderBottom: "none" }}>
            <div className={"tab " + (tab === "drafts" ? "active" : "")} onClick={() => setTab("drafts")}>Drafts <span className="count">{CLAIMS.length}</span></div>
            <div className={"tab " + (tab === "sent" ? "active" : "")} onClick={() => setTab("sent")}>Sent <span className="count">{SENT_CLAIMS.length}</span></div>
            <div className="tab">Pending payment <span className="count">38</span></div>
            <div className="tab">Denials <span className="count">2</span></div>
            <div className="tab">Pre-auth <span className="count">7</span></div>
          </div>
          <div className="spacer" />
          {tab === "sent" && (
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <span className="tiny muted">Filter:</span>
              <select className="select" style={{ width: 240, padding: "4px 8px" }} value={carrierFilter} onChange={e => setCarrierFilter(e.target.value)}>
                <option value="all">All carriers</option>
                <option value="Delta Dental">Delta Dental of California</option>
                <option value="MetLife">MetLife PPO</option>
                <option value="Aetna">Aetna Open Access</option>
              </select>
              <button className="btn sm"><I.Filter size={11} /> More</button>
            </div>
          )}
          {tab === "drafts" && (
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn sm"><I.Filter size={11} /> Filter</button>
              <button className="btn sm primary">
                <I.Send size={11} />
                {selected.size > 0 ? `Submit ${selected.size} selected` : `Bulk submit · ${CLAIMS.filter(c => c.status === "draft").length}`}
              </button>
            </div>
          )}
          {tab === "sent" && selected.size > 0 && (
            <button className="btn sm primary" onClick={onOpenEOB} style={{ marginLeft: 8 }}>
              <I.Layers size={11} /> Process EOB · {selected.size} claims · ${selectedSum.toFixed(2)}
            </button>
          )}
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="table" style={{ minWidth: 1100 }}>
          <thead>
            <tr>
              <th style={{ width: 36 }}>
                <CheckBox checked={selected.size === filtered.length && filtered.length > 0} indeterminate={selected.size > 0 && selected.size < filtered.length} onChange={toggleAll} />
              </th>
              <th style={{ width: 80 }}>Claim #</th>
              <th>Patient</th>
              <th>Carrier</th>
              <th style={{ width: 90 }}>DOS</th>
              <th style={{ width: 60 }}>Prov</th>
              <th style={{ width: 100, textAlign: "right" }}>Billed</th>
              {tab === "sent" && <th style={{ width: 100, textAlign: "right" }}>Paid</th>}
              <th style={{ width: 60 }}>Attach</th>
              <th style={{ width: 140 }}>Status</th>
              <th style={{ width: 40 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => (
              <ClaimRow key={r.id} r={r} tab={tab} selected={selected.has(r.id)} onToggle={() => toggle(r.id)} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ClaimRow({ r, tab, selected, onToggle }) {
  return (
    <tr className={selected ? "selected" : ""}>
      <td><CheckBox checked={selected} onChange={onToggle} /></td>
      <td><span className="mono tabular" style={{ fontSize: 11.5, fontWeight: 600 }}>{r.id}</span></td>
      <td><div className="medium" style={{ fontSize: 13 }}>{r.patient}</div></td>
      <td>
        <div style={{ fontSize: 12.5 }}>{r.insurance}</div>
        {r.primary !== undefined && <span className="chip outline sm" style={{ marginTop: 2 }}>{r.primary ? "Primary" : "Secondary"}</span>}
      </td>
      <td className="tabular tiny muted">{r.dos}</td>
      <td><span className="chip outline sm">{r.prov}</span></td>
      <td className="tabular medium" style={{ textAlign: "right" }}>${r.billed.toFixed(2)}</td>
      {tab === "sent" && (
        <td className="tabular medium" style={{ textAlign: "right", color: r.status === "denied" ? "var(--rose-700)" : r.status === "underpaid" ? "var(--amber-700)" : "var(--sage-700)" }}>
          ${r.paid?.toFixed(2)}
        </td>
      )}
      <td>
        {r.attach ? <I.PaperClip size={13} style={{ color: r.status === "blocked" ? "var(--rose-700)" : "var(--fg-secondary)" }} /> : <span className="muted tiny">—</span>}
      </td>
      <td>
        {r.status === "draft" && <span className="chip outline sm">Draft</span>}
        {r.status === "blocked" && (
          <div>
            <span className="chip rose sm"><I.AlertCircle size={10} /> Blocked</span>
            <div className="tiny rose" style={{ marginTop: 3, color: "var(--rose-700)", fontSize: 10.5 }}>{r.blockReason}</div>
          </div>
        )}
        {r.status === "paid" && <span className="chip sage sm"><I.Check size={10} /> Paid</span>}
        {r.status === "underpaid" && <span className="chip amber sm"><I.AlertTriangle size={10} /> Underpaid</span>}
        {r.status === "denied" && <span className="chip rose sm"><I.X size={10} /> Denied</span>}
      </td>
      <td><button className="btn icon ghost sm"><I.MoreHorizontal size={12} /></button></td>
    </tr>
  );
}

function Stat({ label, v, color }) {
  return (
    <div>
      <div className="tiny muted">{label}</div>
      <div className="tabular medium" style={{ fontSize: 14, color: color ? `var(--${color}-700)` : "var(--fg-primary)", fontWeight: 600 }}>{v}</div>
    </div>
  );
}

// ============================================================================
// EOB WIZARD (4 steps)
// ============================================================================
function EOBWizard({ open, onClose }) {
  const [step, setStep] = useState(1);
  const [payment, setPayment] = useState("2,460.00");
  const [check, setCheck] = useState("48217-DD");
  const [expanded, setExpanded] = useState(null);
  const [claims, setClaims] = useState([
    { id: "C-1820", patient: "Jandy Olivey", billed: 480.00, allocated: 380.00, codes: [
      { code: "D1110", desc: "Adult prophy", billed: 110, ins: 110, pat: 0 },
      { code: "D0274", desc: "4 bitewings", billed: 80, ins: 80, pat: 0 },
      { code: "D0150", desc: "Comprehensive exam", billed: 120, ins: 120, pat: 0 },
      { code: "D2391", desc: "Composite 1S #14", billed: 170, ins: 70, pat: 100 },
    ], status: "underpaid", tags: [] },
    { id: "C-1819", patient: "Marcus Hill", billed: 348.00, allocated: 348.00, codes: [
      { code: "D1110", desc: "Adult prophy", billed: 110, ins: 110, pat: 0 },
      { code: "D0150", desc: "Comp exam", billed: 120, ins: 120, pat: 0 },
      { code: "D0210", desc: "FMX", billed: 118, ins: 118, pat: 0 },
    ], status: "paid", tags: [] },
    { id: "C-1818", patient: "Hannah Sloane", billed: 165.00, allocated: 165.00, codes: [
      { code: "D1110", desc: "Adult prophy", billed: 110, ins: 110, pat: 0 },
      { code: "D0274", desc: "4 bitewings", billed: 55, ins: 55, pat: 0 },
    ], status: "paid", tags: [] },
    { id: "C-1817", patient: "Donna Meagle", billed: 740.00, allocated: 590.00, codes: [
      { code: "D2740", desc: "Crown #14", billed: 650, ins: 500, pat: 150 },
      { code: "D2950", desc: "Core build-up #14", billed: 90, ins: 90, pat: 0 },
    ], status: "underpaid", tags: [] },
    { id: "C-1816", patient: "Jerry Gergich", billed: 245.00, allocated: 245.00, codes: [
      { code: "D2391", desc: "Composite 1S #19", billed: 215, ins: 215, pat: 0 },
      { code: "D0140", desc: "Limited exam", billed: 30, ins: 30, pat: 0 },
    ], status: "paid", tags: [] },
    { id: "C-1814", patient: "Mark Brendanawicz", billed: 132.00, allocated: 132.00, codes: [
      { code: "D1110", desc: "Adult prophy", billed: 110, ins: 110, pat: 0 },
      { code: "D0120", desc: "Periodic exam", billed: 22, ins: 22, pat: 0 },
    ], status: "paid", tags: [] },
  ]);

  if (!open) return null;

  const totalAllocated = claims.reduce((acc, c) => acc + c.allocated, 0);
  const enteredPayment = parseFloat(payment.replace(",", ""));
  const diff = totalAllocated - enteredPayment;

  const Wizard = (
    <div style={{ display: "flex", alignItems: "center", padding: "10px 20px", gap: 8, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-subtle)" }}>
      {["Payment", "Distribute", "Review", "Finalize"].map((label, i) => {
        const n = i + 1;
        const active = step === n;
        const done = step > n;
        return (
          <React.Fragment key={n}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{
                width: 22, height: 22, borderRadius: "50%",
                background: done ? "var(--sage-500)" : active ? "var(--sage-500)" : "var(--bg-sunken)",
                color: done || active ? "white" : "var(--fg-tertiary)",
                display: "grid", placeItems: "center",
                fontSize: 11, fontWeight: 600,
              }}>
                {done ? <I.Check size={12} sw={3} /> : n}
              </div>
              <span style={{ fontSize: 12.5, fontWeight: active ? 600 : 500, color: active || done ? "var(--fg-primary)" : "var(--fg-tertiary)" }}>{label}</span>
            </div>
            {i < 3 && <div style={{ flex: 1, height: 1, background: done ? "var(--sage-500)" : "var(--border-hairline)", maxWidth: 80 }} />}
          </React.Fragment>
        );
      })}
    </div>
  );

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ width: 960, height: "85vh" }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h2>Process EOB · Delta Dental of California</h2>
          <span className="chip outline">{claims.length} claims</span>
          <div className="spacer" />
          <button className="btn icon ghost" onClick={onClose}><I.X size={14} /></button>
        </div>

        {Wizard}

        <div style={{ flex: 1, overflow: "auto", padding: 20 }}>
          {step === 1 && (
            <div style={{ maxWidth: 540, margin: "0 auto" }}>
              <div style={{ marginBottom: 18 }}>
                <h3 style={{ margin: "0 0 4px", fontSize: 16, fontWeight: 600 }}>Enter the insurance payment</h3>
                <p className="muted" style={{ fontSize: 12.5, margin: 0 }}>A single check from Delta covers multiple patients. Enter the total received from the carrier, then upload the EOB document.</p>
              </div>
              <div className="field" style={{ marginBottom: 14 }}>
                <label className="label">Total payment received</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 12, top: 9, color: "var(--fg-tertiary)" }}>$</span>
                  <input className="input tabular" style={{ paddingLeft: 24, fontSize: 18, fontWeight: 600 }} value={payment} onChange={e => setPayment(e.target.value)} />
                </div>
              </div>
              <div className="field" style={{ marginBottom: 14 }}>
                <label className="label">Check / EFT reference</label>
                <input className="input" value={check} onChange={e => setCheck(e.target.value)} />
              </div>
              <div className="field" style={{ marginBottom: 14 }}>
                <label className="label">Payment date</label>
                <input className="input" defaultValue="May 22, 2026" />
              </div>
              <div className="field">
                <label className="label">EOB document</label>
                <div style={{ padding: 24, border: "2px dashed var(--border-strong)", borderRadius: 10, textAlign: "center", background: "var(--bg-subtle)" }}>
                  <I.Upload size={20} style={{ color: "var(--fg-tertiary)" }} />
                  <div style={{ marginTop: 6, fontSize: 13, fontWeight: 500 }}>Drag and drop EOB here</div>
                  <div className="tiny muted">PDF or image · max 10 MB · saved to each associated claim</div>
                  <button className="btn sm" style={{ marginTop: 10 }}>Browse files</button>
                </div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
                <div>
                  <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Distribute ${payment} across claims</h3>
                  <div className="tiny muted">Click any claim to expand and adjust at the procedure level.</div>
                </div>
                <div className="spacer" />
                <button className="btn sm">Auto-distribute</button>
              </div>

              {/* Progress bar */}
              <div style={{
                padding: 12,
                background: Math.abs(diff) < 0.01 ? "var(--sage-50)" : "var(--amber-50)",
                border: "1px solid " + (Math.abs(diff) < 0.01 ? "var(--sage-200)" : "var(--amber-200)"),
                borderRadius: 8, marginBottom: 14,
                display: "flex", alignItems: "center", gap: 12,
              }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                    <span className="tabular" style={{ fontSize: 18, fontWeight: 600 }}>${totalAllocated.toFixed(2)}</span>
                    <span className="muted">/ ${enteredPayment.toFixed(2)}</span>
                  </div>
                  <div style={{ height: 6, background: "var(--bg-surface)", borderRadius: 3, marginTop: 4, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${Math.min(totalAllocated / enteredPayment * 100, 100)}%`, background: Math.abs(diff) < 0.01 ? "var(--sage-500)" : "var(--amber-500)" }} />
                  </div>
                </div>
                {Math.abs(diff) > 0.01 ? (
                  <div style={{ textAlign: "right" }}>
                    <div className="tiny" style={{ color: "var(--amber-700)" }}>{diff > 0 ? "Over by" : "Short by"}</div>
                    <div className="tabular medium" style={{ fontSize: 16, color: "var(--amber-700)" }}>${Math.abs(diff).toFixed(2)}</div>
                  </div>
                ) : (
                  <span className="chip sage"><I.Check size={11} /> Balanced</span>
                )}
              </div>

              <div className="card">
                <table className="table" style={{ fontSize: 12 }}>
                  <thead>
                    <tr>
                      <th style={{ width: 20 }}></th>
                      <th style={{ width: 80 }}>Claim #</th>
                      <th>Patient</th>
                      <th style={{ width: 100, textAlign: "right" }}>Billed</th>
                      <th style={{ width: 130, textAlign: "right" }}>Allocated</th>
                      <th style={{ width: 100 }}>Variance</th>
                    </tr>
                  </thead>
                  <tbody>
                    {claims.map(c => {
                      const variance = c.billed - c.allocated;
                      return (
                        <React.Fragment key={c.id}>
                          <tr onClick={() => setExpanded(expanded === c.id ? null : c.id)} style={{ cursor: "pointer" }}>
                            <td><I.ChevronRight size={11} style={{ color: "var(--fg-tertiary)", transform: expanded === c.id ? "rotate(90deg)" : "none", transition: "transform 120ms" }} /></td>
                            <td><span className="mono tabular tiny medium">{c.id}</span></td>
                            <td className="medium">{c.patient}</td>
                            <td className="tabular" style={{ textAlign: "right" }}>${c.billed.toFixed(2)}</td>
                            <td style={{ textAlign: "right" }}>
                              <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                                <span className="muted">$</span>
                                <input
                                  className="input tabular"
                                  style={{ width: 90, padding: "3px 6px", textAlign: "right", fontSize: 12 }}
                                  value={c.allocated.toFixed(2)}
                                  onChange={(e) => {
                                    const n = claims.map(x => x.id === c.id ? { ...x, allocated: parseFloat(e.target.value) || 0 } : x);
                                    setClaims(n);
                                  }}
                                  onClick={e => e.stopPropagation()}
                                />
                              </div>
                            </td>
                            <td>
                              {Math.abs(variance) < 0.01 ? <span className="chip sage sm">Paid full</span>
                                : variance > 0 ? <span className="chip amber sm">−${variance.toFixed(2)}</span>
                                : <span className="chip blue sm">+${Math.abs(variance).toFixed(2)}</span>}
                            </td>
                          </tr>
                          {expanded === c.id && (
                            <tr><td colSpan={6} style={{ padding: 0, background: "var(--bg-subtle)" }}>
                              <table style={{ width: "100%", fontSize: 11.5 }}>
                                <thead>
                                  <tr>
                                    <th style={{ padding: "6px 12px 6px 36px", textAlign: "left", color: "var(--fg-tertiary)", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Code</th>
                                    <th style={{ padding: "6px 12px", textAlign: "left", color: "var(--fg-tertiary)", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Procedure</th>
                                    <th style={{ padding: "6px 12px", textAlign: "right", color: "var(--fg-tertiary)", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Billed</th>
                                    <th style={{ padding: "6px 12px", textAlign: "right", color: "var(--fg-tertiary)", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Ins. paid</th>
                                    <th style={{ padding: "6px 12px", textAlign: "right", color: "var(--fg-tertiary)", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Pat. resp.</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {c.codes.map((p, j) => (
                                    <tr key={j}>
                                      <td style={{ padding: "5px 12px 5px 36px" }} className="mono medium" style={{ color: "var(--sage-700)" }}>{p.code}</td>
                                      <td style={{ padding: "5px 12px" }}>{p.desc}</td>
                                      <td style={{ padding: "5px 12px", textAlign: "right" }} className="tabular">${p.billed}</td>
                                      <td style={{ padding: "5px 12px", textAlign: "right" }} className="tabular medium" style={{ color: "var(--sage-700)" }}>${p.ins}</td>
                                      <td style={{ padding: "5px 12px", textAlign: "right" }} className="tabular medium">${p.pat}</td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </td></tr>
                          )}
                        </React.Fragment>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
                <div>
                  <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Review payment accuracy</h3>
                  <div className="tiny muted">Tag, comment on, and flag any claim before posting to the ledger.</div>
                </div>
                <div className="spacer" />
                <div className="row" style={{ gap: 12 }}>
                  <Stat label="Paid" v={claims.filter(c => c.status === "paid").length} color="sage" />
                  <Stat label="Underpaid" v={claims.filter(c => c.status === "underpaid").length} color="amber" />
                  <Stat label="Denied" v="0" color="rose" />
                </div>
              </div>

              <div className="card">
                <table className="table">
                  <thead>
                    <tr>
                      <th style={{ width: 80 }}>Claim #</th>
                      <th>Patient</th>
                      <th style={{ width: 100, textAlign: "right" }}>Billed</th>
                      <th style={{ width: 100, textAlign: "right" }}>Paid</th>
                      <th style={{ width: 130 }}>Outcome</th>
                      <th>Tags</th>
                      <th style={{ width: 36 }}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {claims.map(c => (
                      <tr key={c.id} style={{ background: c.status === "underpaid" ? "oklch(99% 0.01 80)" : "transparent" }}>
                        <td><span className="mono tabular tiny medium">{c.id}</span></td>
                        <td className="medium">{c.patient}</td>
                        <td className="tabular" style={{ textAlign: "right" }}>${c.billed.toFixed(2)}</td>
                        <td className="tabular medium" style={{ textAlign: "right", color: c.status === "underpaid" ? "var(--amber-700)" : "var(--sage-700)" }}>${c.allocated.toFixed(2)}</td>
                        <td>
                          {c.status === "paid" && <span className="chip sage sm"><I.Check size={10} /> Paid in full</span>}
                          {c.status === "underpaid" && <span className="chip amber sm"><I.AlertTriangle size={10} /> Underpaid −${(c.billed - c.allocated).toFixed(2)}</span>}
                        </td>
                        <td>
                          <div style={{ display: "flex", gap: 4 }}>
                            {c.status === "underpaid" && <span className="chip amber sm">Appeal</span>}
                            {c.status === "underpaid" && <span className="chip outline sm">Balance Due</span>}
                            <button className="btn icon ghost sm" style={{ width: 18, height: 18 }}><I.Plus size={10} /></button>
                          </div>
                        </td>
                        <td><button className="btn icon ghost sm"><I.MessageSquare size={11} /></button></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div style={{ marginTop: 14, padding: 12, background: "var(--amber-50)", border: "1px solid var(--amber-200)", borderRadius: 8, display: "flex", alignItems: "center", gap: 8 }}>
                <I.AlertTriangle size={14} style={{ color: "var(--amber-700)" }} />
                <div style={{ fontSize: 12, color: "var(--amber-700)", flex: 1 }}>
                  <strong>Jandy Olivey's claim is underpaid by $100.</strong> Reconcile this discrepancy by moving the shortfall to a procedure or flagging for appeal.
                </div>
                <button className="btn sm">Resolve</button>
              </div>
            </div>
          )}

          {step === 4 && (
            <div style={{ maxWidth: 540, margin: "0 auto", textAlign: "center", paddingTop: 30 }}>
              <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--sage-100)", color: "var(--sage-700)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
                <I.Check size={32} sw={2.5} />
              </div>
              <h3 style={{ margin: "0 0 6px", fontSize: 18, fontWeight: 600 }}>Ready to post</h3>
              <p className="muted" style={{ fontSize: 13, margin: "0 auto 20px", maxWidth: 380 }}>
                Once confirmed, this insurance payment will automatically post to each patient's ledger.
              </p>
              <div style={{ background: "var(--bg-subtle)", borderRadius: 10, padding: 16, textAlign: "left", marginBottom: 14 }}>
                <SumRow label="Total payment" v={`$${payment}`} big />
                <SumRow label="Check / EFT" v={check} />
                <SumRow label="Payment date" v="May 22, 2026" />
                <SumRow label="Claims paid" v={`${claims.length}`} />
                <SumRow label="Claims to ledger" v={claims.length - 1 + " full · 1 partial"} />
              </div>
              <div className="field" style={{ textAlign: "left" }}>
                <label className="label">Final notes (optional)</label>
                <textarea className="textarea" rows={3} placeholder="Any notes for this batch posting…" />
              </div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Save & exit</button>
          <div className="spacer" />
          {step > 1 && <button className="btn" onClick={() => setStep(step - 1)}><I.ChevronLeft size={12} /> Back</button>}
          {step < 4 ? (
            <button className="btn primary" onClick={() => setStep(step + 1)}>
              Next: {["", "Distribute", "Review", "Finalize"][step]} <I.ChevronRight size={12} />
            </button>
          ) : (
            <button className="btn primary" onClick={onClose}>
              <I.Check size={12} /> Confirm & post ${payment}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function SumRow({ label, v, big }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid var(--border-hairline)" }}>
      <span className="muted" style={{ fontSize: 12 }}>{label}</span>
      <span className={"tabular " + (big ? "medium" : "")} style={{ fontSize: big ? 16 : 13, fontWeight: big ? 600 : 500 }}>{v}</span>
    </div>
  );
}

// ============================================================================
// BILLING
// ============================================================================
function Billing() {
  const [view, setView] = useState("ledger");
  const [expandedAppt, setExpandedAppt] = useState(2);
  const [paymentPlanOpen, setPaymentPlanOpen] = useState(false);

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {/* Header */}
      <div style={{ padding: "12px 18px", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-hairline)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div className="avatar lg av-4">JT</div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600 }}>Joey Tribbiani · Billing</div>
            <div className="tiny muted">53 y/o · Cigna · Pt #5571 · Guarantor: self</div>
          </div>
          <div className="spacer" />
          <span className="chip mint">Payment plan active</span>
          <button className="btn sm"><I.MessageSquare size={12} /></button>
          <button className="btn sm primary"><I.CreditCard size={12} /> Take payment</button>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10, marginTop: 14 }}>
          <BalanceCard label="Patient balance" v="$250.00" sub="14 days old" color="amber" />
          <BalanceCard label="Insurance pending" v="$925.00" sub="2 claims in flight" color="blue" />
          <BalanceCard label="Family balance" v="$250.00" sub="No other members owe" />
          <BalanceCard label="Digital wallet" v="$140.00" sub="Insurance overpayment Apr" color="sage" />
          <BalanceCard label="Active plan" v="$291.69 / $300" sub="6 of 7 payments made" color="mint" />
        </div>
      </div>

      <div style={{ padding: "8px 18px", borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-subtle)" }}>
        <div className="tabs" style={{ borderBottom: "none" }}>
          <div className={"tab " + (view === "ledger" ? "active" : "")} onClick={() => setView("ledger")}>Ledger</div>
          <div className={"tab " + (view === "plans" ? "active" : "")} onClick={() => setView("plans")}>Payment plans</div>
          <div className={"tab " + (view === "wallet" ? "active" : "")} onClick={() => setView("wallet")}>Digital wallet</div>
          <div className="tab">Statements</div>
          <div className="tab">Payments</div>
          <div className="tab">Adjustments</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 18 }}>
        {view === "ledger" && (
          <div className="card">
            <div className="card-head">
              <h3>Ledger · appointment by appointment</h3>
              <div className="spacer" />
              <span className="tiny muted">Showing 6 of 14 visits</span>
              <button className="btn ghost sm">All visits →</button>
            </div>
            <div className="card-body tight">
              {[
                { date: "Apr 22, 2026", title: "Implant #19 + Bone Graft", prov: "Dr. Reilly", charges: 2150, ins: 1075, paid: 1075, bal: 0, codes: [
                  { code: "D6010", desc: "Implant body endosteal", fee: 1850, ins: 925, pat: 925 },
                  { code: "D7953", desc: "Bone graft alveolus", fee: 300, ins: 150, pat: 150 },
                ]},
                { date: "Mar 11, 2026", title: "Crown Seat #14", prov: "Dr. Reilly", charges: 1450, ins: 725, paid: 1075, bal: 0, codes: [
                  { code: "D2740", desc: "Crown porcelain/ceramic", fee: 1450, ins: 725, pat: 725 },
                ]},
                { date: "Feb 18, 2026", title: "Crown Prep #14", prov: "Dr. Reilly", charges: 295, ins: 0, paid: 295, bal: 0, codes: [
                  { code: "D2950", desc: "Core build-up", fee: 295, ins: 0, pat: 295 },
                ]},
                { date: "Oct 14, 2025", title: "Adult Prophy + 4BW", prov: "Hyg. Park", charges: 188, ins: 188, paid: 0, bal: 0, codes: [
                  { code: "D1110", desc: "Adult prophy", fee: 110, ins: 110, pat: 0 },
                  { code: "D0274", desc: "4 bitewings", fee: 78, ins: 78, pat: 0 },
                ]},
                { date: "Mar 18, 2025", title: "Periodic exam", prov: "Dr. Reilly", charges: 65, ins: 65, paid: 0, bal: 0, codes: [{ code: "D0120", desc: "Periodic exam", fee: 65, ins: 65, pat: 0 }] },
              ].map((row, i) => (
                <div key={i}>
                  <div onClick={() => setExpandedAppt(expandedAppt === i ? null : i)} style={{
                    padding: "12px 14px",
                    borderBottom: "1px solid var(--border-hairline)",
                    display: "flex", alignItems: "center", gap: 12, cursor: "pointer",
                    background: expandedAppt === i ? "var(--bg-subtle)" : "transparent",
                  }}>
                    <I.ChevronRight size={12} style={{ color: "var(--fg-tertiary)", transform: expandedAppt === i ? "rotate(90deg)" : "none", transition: "transform 120ms" }} />
                    <div className="tabular medium" style={{ width: 110, fontSize: 12.5 }}>{row.date}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 550 }}>{row.title}</div>
                      <div className="tiny muted">{row.prov}</div>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 100px)", gap: 8, textAlign: "right" }}>
                      <BalCol l="Charges" v={`$${row.charges.toFixed(2)}`} />
                      <BalCol l="Insurance" v={`$${row.ins.toFixed(2)}`} c="sage" />
                      <BalCol l="Payments" v={`$${row.paid.toFixed(2)}`} c="sage" />
                      <BalCol l="Balance" v={`$${row.bal.toFixed(2)}`} c={row.bal > 0 ? "rose" : ""} bold />
                    </div>
                  </div>
                  {expandedAppt === i && (
                    <div style={{ background: "var(--bg-subtle)", padding: "8px 16px 12px 50px", borderBottom: "1px solid var(--border-hairline)" }}>
                      <table style={{ width: "100%", fontSize: 11.5 }}>
                        <thead>
                          <tr style={{ color: "var(--fg-tertiary)" }}>
                            <th style={{ textAlign: "left", padding: "4px 8px", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Code</th>
                            <th style={{ textAlign: "left", padding: "4px 8px", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Procedure</th>
                            <th style={{ textAlign: "right", padding: "4px 8px", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Fee</th>
                            <th style={{ textAlign: "right", padding: "4px 8px", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Ins. est.</th>
                            <th style={{ textAlign: "right", padding: "4px 8px", fontWeight: 500, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>Pat. resp.</th>
                          </tr>
                        </thead>
                        <tbody>
                          {row.codes.map((c, j) => (
                            <tr key={j}>
                              <td style={{ padding: "4px 8px" }} className="mono medium" style={{ color: "var(--sage-700)" }}>{c.code}</td>
                              <td style={{ padding: "4px 8px" }}>{c.desc}</td>
                              <td style={{ padding: "4px 8px", textAlign: "right" }} className="tabular">${c.fee}</td>
                              <td style={{ padding: "4px 8px", textAlign: "right" }} className="tabular" style={{ color: "var(--sage-700)" }}>${c.ins}</td>
                              <td style={{ padding: "4px 8px", textAlign: "right" }} className="tabular medium">${c.pat}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {view === "plans" && (
          <PaymentPlans onCreate={() => setPaymentPlanOpen(true)} />
        )}

        {view === "wallet" && (
          <div className="card" style={{ maxWidth: 720 }}>
            <div className="card-head">
              <h3>Digital wallet · $140.00 stored</h3>
              <div className="spacer" />
              <button className="btn sm">Send refund check</button>
              <button className="btn primary sm" style={{ marginLeft: 6 }}>Apply to balance</button>
            </div>
            <div className="card-body">
              <p className="muted small" style={{ marginTop: 0 }}>Insurance overpayments and patient credits are stored here instead of being refunded by check.</p>
              <table className="table">
                <thead><tr><th>Date</th><th>Source</th><th style={{ textAlign: "right" }}>Amount</th><th>Notes</th></tr></thead>
                <tbody>
                  <tr><td className="tabular tiny">Apr 22, 2026</td><td>Cigna overpayment</td><td className="tabular medium" style={{ textAlign: "right", color: "var(--sage-700)" }}>+$140.00</td><td className="tiny muted">Claim C-1825</td></tr>
                  <tr><td className="tabular tiny">Feb 11, 2026</td><td>Applied to balance</td><td className="tabular medium" style={{ textAlign: "right", color: "var(--rose-700)" }}>−$60.00</td><td className="tiny muted">Appt 2/18 prep</td></tr>
                  <tr><td className="tabular tiny">Jan 20, 2026</td><td>Cigna overpayment</td><td className="tabular medium" style={{ textAlign: "right", color: "var(--sage-700)" }}>+$60.00</td><td className="tiny muted">Claim C-1798</td></tr>
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      <PaymentPlanModal open={paymentPlanOpen} onClose={() => setPaymentPlanOpen(false)} />
    </div>
  );
}

function BalanceCard({ label, v, sub, color }) {
  const c = color === "rose" ? "var(--rose-700)" : color === "amber" ? "var(--amber-700)" : color === "sage" ? "var(--sage-700)" : color === "blue" ? "var(--blue-700)" : color === "mint" ? "oklch(38% 0.06 175)" : "var(--fg-primary)";
  const bg = color === "rose" ? "var(--rose-50)" : color === "amber" ? "var(--amber-50)" : color === "sage" ? "var(--sage-50)" : color === "blue" ? "var(--blue-50)" : color === "mint" ? "var(--mint-100)" : "var(--bg-subtle)";
  return (
    <div style={{ background: bg, borderRadius: 8, padding: 12 }}>
      <div className="tiny" style={{ color: c, opacity: 0.8, fontWeight: 500 }}>{label}</div>
      <div className="tabular" style={{ fontSize: 17, fontWeight: 600, color: c, letterSpacing: "-0.015em", marginTop: 2 }}>{v}</div>
      <div className="tiny" style={{ color: c, opacity: 0.7, marginTop: 2 }}>{sub}</div>
    </div>
  );
}
function BalCol({ l, v, c, bold }) {
  return (
    <div>
      <div className="tiny muted">{l}</div>
      <div className={"tabular" + (bold ? " medium" : "")} style={{ fontSize: bold ? 14 : 13, color: c ? `var(--${c}-700)` : "var(--fg-primary)", fontWeight: bold ? 600 : 500 }}>{v}</div>
    </div>
  );
}

function PaymentPlans({ onCreate }) {
  return (
    <div className="card" style={{ maxWidth: 760 }}>
      <div className="card-head">
        <h3>Payment plans</h3>
        <div className="spacer" />
        <button className="btn primary sm" onClick={onCreate}><I.Plus size={11} /> New plan</button>
      </div>
      <div className="card-body">
        <div style={{ padding: 14, background: "linear-gradient(135deg, var(--mint-100), var(--bg-surface))", borderRadius: 10, border: "1px solid oklch(82% 0.04 175)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
            <span className="chip" style={{ background: "white", color: "oklch(38% 0.06 175)", fontWeight: 600 }}>Active</span>
            <div style={{ fontSize: 14, fontWeight: 600 }}>"joey plan 3" · $300 total</div>
            <div className="spacer" />
            <button className="btn icon ghost sm"><I.MoreHorizontal size={13} /></button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 12 }}>
            <div><div className="tiny muted">Down payment</div><div className="tabular medium">$50.00</div></div>
            <div><div className="tiny muted">Installments</div><div className="tabular medium">6 × $41.67</div></div>
            <div><div className="tiny muted">Frequency</div><div className="medium">Weekly · Fri</div></div>
            <div><div className="tiny muted">Card on file</div><div className="medium">Visa ••4421</div></div>
          </div>
          <div style={{ display: "flex", gap: 4, marginBottom: 6 }}>
            {Array.from({length: 7}).map((_, i) => (
              <div key={i} style={{ flex: 1, height: 6, borderRadius: 3, background: i < 6 ? "var(--sage-500)" : "var(--bg-sunken)" }} />
            ))}
          </div>
          <div className="tiny muted">6 of 7 paid · Next charge May 29 · $41.67</div>
        </div>

        <div className="divider" />

        <div className="tiny muted heavy" style={{ textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 8 }}>Completed plans</div>
        <div style={{ padding: 12, background: "var(--bg-subtle)", borderRadius: 8, display: "flex", alignItems: "center", gap: 10 }}>
          <span className="chip sage sm"><I.Check size={10} /> Completed Feb 4</span>
          <div style={{ fontSize: 13 }}>"joey plan 2" · $620 total · 6 monthly payments</div>
        </div>
      </div>
    </div>
  );
}

function PaymentPlanModal({ open, onClose }) {
  const [total, setTotal] = useState("300");
  const [down, setDown] = useState("50");
  const [count, setCount] = useState(6);
  const [freq, setFreq] = useState("weekly");
  const installment = ((parseFloat(total) || 0) - (parseFloat(down) || 0)) / count;

  if (!open) return null;
  return (
    <Modal open={open} onClose={onClose} title="New payment plan" width={560}
      foot={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={onClose}><I.Check size={12} /> Create plan & charge $50 down</button>
      </>}
    >
      <div className="field" style={{ marginBottom: 12 }}>
        <label className="label">Plan name</label>
        <input className="input" defaultValue="joey plan 3" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 12 }}>
        <div className="field">
          <label className="label">Total amount</label>
          <input className="input tabular" value={total} onChange={e => setTotal(e.target.value)} />
        </div>
        <div className="field">
          <label className="label">Down payment</label>
          <input className="input tabular" value={down} onChange={e => setDown(e.target.value)} />
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 12 }}>
        <div className="field">
          <label className="label">Number of payments</label>
          <input className="input tabular" type="number" value={count} onChange={e => setCount(parseInt(e.target.value) || 1)} />
        </div>
        <div className="field">
          <label className="label">Frequency</label>
          <select className="select" value={freq} onChange={e => setFreq(e.target.value)}>
            <option value="weekly">Weekly · every Friday</option>
            <option value="biweekly">Bi-weekly</option>
            <option value="monthly">Monthly</option>
          </select>
        </div>
      </div>
      <div className="field" style={{ marginBottom: 14 }}>
        <label className="label">Card on file</label>
        <div className="input" style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <I.CreditCard size={14} />
          <span>Visa ending in 4421 · Joey Tribbiani</span>
          <span className="chip outline sm" style={{ marginLeft: "auto" }}>Default</span>
        </div>
      </div>
      <div style={{ padding: 14, background: "var(--sage-50)", border: "1px solid var(--sage-200)", borderRadius: 10 }}>
        <div className="tiny" style={{ color: "var(--sage-700)", fontWeight: 500, marginBottom: 6 }}>SCHEDULE</div>
        <div className="tabular" style={{ fontSize: 14, fontWeight: 600, color: "var(--sage-700)" }}>
          ${down} today, then {count} × ${installment.toFixed(2)} {freq}
        </div>
        <div className="tiny" style={{ color: "var(--sage-700)", marginTop: 4 }}>
          Card on file is charged automatically — no staff action after setup.
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { Claims, EOBWizard, Billing });
