// Billing Tab — financial control center for project billing
// Sections: summary KPIs, model indicator, Schedule of Values workspace,
// readiness panel, change-order impact, invoice history, AI assist, filters.

const BILLING_PERIODS = [
  "Apr 1 – Apr 30, 2026 (Current)",
  "Mar 1 – Mar 31, 2026",
  "Feb 1 – Feb 28, 2026",
  "Jan 1 – Jan 31, 2026",
  "Dec 1 – Dec 31, 2025",
];

const BILLING_MODELS = ["Progress Billing", "Milestone Billing", "Time & Materials", "Fixed Fee", "Hybrid"];

// Schedule of Values rows. Loosely tracks the SCOPES, but billing-flavored.
// previouslyBilled + currentDraft = total billed-this-cycle once invoiced.
const SOV_INITIAL = [
  { id: "01.100", scope: "Site Prep & Earthwork", desc: "Clearing, grading, erosion control",
    contract: 492_000, pct: 100, prevBilled: 492_000, current: 0, retainage: 0.05, ready: true },
  { id: "02.100", scope: "Pile Driving & Foundation", desc: "Driven piles + pull-out testing",
    contract: 1_268_000, pct: 100, prevBilled: 1_204_600, current: 63_400, retainage: 0.05, ready: true },
  { id: "03.100", scope: "Racking — Uprights & Torque Tubes", desc: "Field-installed racking system",
    contract: 1_840_000, pct: 78, prevBilled: 1_104_000, current: 331_200, retainage: 0.05, ready: true },
  { id: "04.100", scope: "Module Installation", desc: "PV module mounting + wire mgmt",
    contract: 980_000, pct: 42, prevBilled: 245_000, current: 166_600, retainage: 0.05, ready: true },
  { id: "05.100", scope: "DC Electrical & Combiners", desc: "Source-circuit harnesses + combiners",
    contract: 620_000, pct: 28, prevBilled: 124_000, current: 49_600, retainage: 0.05, ready: false, blockReason: "Awaiting megger test results — uploaded but unsigned" },
  { id: "06.100", scope: "AC Electrical & Inverters", desc: "Inverter pads, AC collection, MV",
    contract: 540_000, pct: 12, prevBilled: 0, current: 64_800, retainage: 0.05, ready: true },
  { id: "07.100", scope: "Commissioning & Startup", desc: "PCS, SCADA, owner training",
    contract: 280_000, pct: 0, prevBilled: 0, current: 0, retainage: 0.05, ready: false, blockReason: "Phase not started" },
  // CO additions
  { id: "CO-013", scope: "CO-013 — Predrill 480 piles (refusal)", desc: "Approved field-condition CO", isCO: true,
    contract: 92_800, pct: 100, prevBilled: 46_400, current: 46_400, retainage: 0.05, ready: true },
  { id: "CO-009", scope: "CO-009 — SWPPP extension", desc: "Approved code/permit CO", isCO: true,
    contract: 12_400, pct: 100, prevBilled: 12_400, current: 0, retainage: 0.05, ready: true },
];

const INVOICES = [
  { num: "INV-2026-008", date: "04/30/2026", period: "Apr 1 – Apr 30", amount: 0, status: "Draft", cos: ["CO-013"], note: "Draft — current cycle" },
  { num: "INV-2026-007", date: "03/31/2026", period: "Mar 1 – Mar 31", amount: 542_800, status: "Sent", cos: ["CO-013"], note: "Submitted to Solis Energy" },
  { num: "INV-2026-006", date: "02/28/2026", period: "Feb 1 – Feb 28", amount: 612_400, status: "Paid", cos: [], note: "Paid 03/18/2026" },
  { num: "INV-2026-005", date: "01/31/2026", period: "Jan 1 – Jan 31", amount: 488_200, status: "Paid", cos: ["CO-009"], note: "Paid 02/12/2026" },
  { num: "INV-2026-004", date: "12/31/2025", period: "Dec 1 – Dec 31", amount: 720_600, status: "Paid", cos: [], note: "Paid 01/14/2026" },
  { num: "INV-2026-003", date: "11/30/2025", period: "Nov 1 – Nov 30", amount: 360_000, status: "Paid", cos: [], note: "Paid 12/16/2025" },
];

const INVOICE_TONES = {
  Draft: { tone: "neutral", icon: "pen", label: "Draft" },
  Sent: { tone: "info", icon: "send", label: "Sent" },
  "Pending Approval": { tone: "warning", icon: "clock", label: "Pending" },
  Paid: { tone: "success", icon: "check", label: "Paid" },
  Overdue: { tone: "danger", icon: "alertCircle", label: "Overdue" },
};

const PENDING_COS = [
  { id: "CO-014", title: "Add 240 modules — east tracker row extension", value: 184_500, status: "Pending Approval" },
  { id: "CO-011", title: "Schedule acceleration — second torque-tube crew", value: 68_400, status: "Internal Review" },
  { id: "CO-012", title: "Substitute galvanized racking", value: 0, status: "Sent" },
];

// =============================================================================
// MAIN
// =============================================================================
const BillingTab = ({ p }) => {
  const [sov, setSov] = React.useState(SOV_INITIAL);
  const [period, setPeriod] = React.useState(BILLING_PERIODS[0]);
  const [scopeFilter, setScopeFilter] = React.useState("All");
  const [billableOnly, setBillableOnly] = React.useState(false);
  const [invoiceState, setInvoiceState] = React.useState("draft"); // empty | draft | ready | complete

  // Totals
  const totalContract = sov.reduce((s, r) => s + r.contract, 0);
  const earnedRevenue = sov.reduce((s, r) => s + r.contract * (r.pct / 100), 0);
  const billedToDate = sov.reduce((s, r) => s + r.prevBilled, 0);
  const currentDraft = sov.reduce((s, r) => s + r.current, 0);
  const retainageHeld = sov.reduce((s, r) => s + (r.prevBilled + r.current) * r.retainage, 0);
  const remaining = totalContract - billedToDate - currentDraft;
  const approvedCOs = sov.filter(r => r.isCO).reduce((s, r) => s + r.contract, 0);
  const pendingCOValue = PENDING_COS.reduce((s, c) => s + c.value, 0);

  const filtered = sov.filter(r => {
    if (scopeFilter !== "All" && r.scope !== scopeFilter) return false;
    if (billableOnly && r.current === 0) return false;
    return true;
  });

  const updatePct = (id, newPct) => {
    setSov(prev => prev.map(r => {
      if (r.id !== id) return r;
      const earned = r.contract * (newPct / 100);
      const newCurrent = Math.max(0, earned - r.prevBilled);
      return { ...r, pct: newPct, current: newCurrent };
    }));
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <BillingSummary
        contract={totalContract}
        billed={billedToDate}
        remaining={remaining}
        current={currentDraft}
        retainage={retainageHeld}
        approvedCOs={approvedCOs}
        pendingCOs={pendingCOValue}
      />

      <BillingModelBar model="Hybrid" breakdown={["Progress Billing", "Time & Materials"]} period={period} onPeriod={setPeriod} />

      {/* AI suggestion hero — replaces side panel */}
      <BillingAISuggestion
        currentDraft={currentDraft}
        earned={earnedRevenue}
        billed={billedToDate}
      />

      <FiltersBar
        period={period} onPeriod={setPeriod}
        scopeFilter={scopeFilter} onScope={setScopeFilter}
        scopes={["All", ...sov.map(r => r.scope)]}
        billableOnly={billableOnly} onBillableOnly={setBillableOnly}
        state={invoiceState} onState={setInvoiceState}
      />

      {invoiceState === "empty" ? (
        <EmptyBillingState />
      ) : invoiceState === "complete" ? (
        <CompleteBillingState contract={totalContract} billed={billedToDate} />
      ) : (
        <>
          <BillingWorkspace
            rows={filtered}
            onPctChange={updatePct}
            currentDraft={currentDraft}
            earnedRevenue={earnedRevenue}
            billedToDate={billedToDate}
          />

          <BillingActionsBar
            currentDraft={currentDraft}
            ready={invoiceState === "ready"}
          />

          <BillingReadinessPanel rows={sov} />
        </>
      )}

      <ChangeOrderImpact approvedCOs={approvedCOs} pendingCOs={PENDING_COS} />

      <InvoiceHistoryTable invoices={INVOICES} />
    </div>
  );
};

// =============================================================================
// AI SUGGESTION HERO
// =============================================================================
const BillingAISuggestion = ({ currentDraft, earned, billed }) => (
  <div style={{
    background: "linear-gradient(180deg, rgb(243,242,255) 0%, rgb(248,248,251) 100%)",
    border: "1px solid rgb(220,217,255)", borderRadius: 12, padding: "16px 20px",
    display: "flex", alignItems: "center", gap: 16
  }}>
    <div style={{ width: 36, height: 36, borderRadius: 10, background: "#fff", border: "1px solid rgb(220,217,255)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Icon name="sparkles" size={18} color="rgb(83,74,255)" />
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: "rgb(83,74,255)", textTransform: "uppercase", letterSpacing: ".05em" }}>Billing Assist</span>
        <span style={{ width: 3, height: 3, borderRadius: "50%", background: "rgb(163,172,186)" }} />
        <span style={{ fontSize: 11, color: "rgb(106,115,131)" }}>Updated 4m ago</span>
      </div>
      <div style={{ fontSize: 15, fontWeight: 600, color: "rgb(26,27,37)", letterSpacing: "-.01em", lineHeight: 1.4 }}>
        <span style={{ fontVariantNumeric: "tabular-nums" }}>{fmtMoneyFull(currentDraft)}</span> is ready to be invoiced based on current progress.
      </div>
      <div style={{ fontSize: 12, color: "rgb(65,69,82)", lineHeight: 1.5, marginTop: 2 }}>
        Earned through Apr 30 is <span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>{fmtMoneyFull(earned)}</span>; with <span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>{fmtMoneyFull(billed)}</span> previously billed, the suggested current draw matches scope progress within ±2%.
      </div>
    </div>
    <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
      <Button size="sm" kind="ghost">Review breakdown</Button>
      <Button size="sm" kind="primary" icon="sparkles">Generate Billing Draft</Button>
    </div>
  </div>
);

// =============================================================================
// READINESS PANEL — sticky right rail, lives inline with SoV
// =============================================================================
const BillingReadinessPanel = ({ rows }) => {
  const checks = [
    { id: "progress", label: "Progress updated through Apr 30", state: "ok", detail: "All scopes refreshed today" },
    { id: "cos", label: "Approved change orders applied", state: "ok", detail: "CO-013, CO-009 included" },
    { id: "docs", label: "Required documents uploaded", state: "warn", detail: "Megger test report uploaded but unsigned", action: "Request signature" },
    { id: "compliance", label: "Compliance & lien waivers", state: "ok", detail: "All lower-tier waivers current" },
    { id: "retainage", label: "Retainage schedule applied", state: "ok", detail: "5% across all scopes" },
    { id: "submittal", label: "Owner AIA G702/G703 packet", state: "ok", detail: "Format verified" },
  ];
  const okCount = checks.filter(c => c.state === "ok").length;
  const warnCount = checks.filter(c => c.state !== "ok").length;
  const overallTone = warnCount === 0 ? "success" : "warning";

  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(280px, 1fr) minmax(280px, 1fr)", gap: 16, alignItems: "flex-start" }}>
      {/* Readiness checklist */}
      <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
        <div style={{ padding: "14px 16px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Icon name="check" size={14} color={TONES[overallTone].fg} />
            <span style={{ fontSize: 13, fontWeight: 600, color: "rgb(26,27,37)" }}>Billing Readiness</span>
          </div>
          <Chip tone={overallTone}>{okCount}/{checks.length}</Chip>
        </div>
        <div style={{ padding: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 16px" }}>
          {checks.map(c => <ReadinessCheck key={c.id} {...c} />)}
        </div>
      </div>

      {/* Inline alerts */}
      <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
        <div style={{ padding: "14px 16px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name="sparkles" size={13} color="rgb(83,74,255)" />
          <span style={{ fontSize: 13, fontWeight: 600, color: "rgb(26,27,37)" }}>AI Alerts</span>
          <Chip tone="warning" style={{ marginLeft: "auto" }}>3 to review</Chip>
        </div>
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 8 }}>
          <AlertCard
            tone="warning"
            icon="alertCircle"
            title="Under-billed scope"
            body="DC Electrical & Combiners is at 28% complete but only 20% billed. Consider catching up this cycle."
            cta="Review scope"
          />
          <AlertCard
            tone="danger"
            icon="alert"
            title="Missing data — DC Electrical"
            body="Megger test report is uploaded but unsigned. Required for $49.6K in current draft to invoice."
            cta="Request signature"
          />
          <AlertCard
            tone="info"
            icon="info"
            title="Over-billing risk"
            body="Pile Driving has been 100% billed previously. Current draft adds $63.4K — verify retainage release."
            cta="Verify"
          />
        </div>
      </div>
    </div>
  );
};

// =============================================================================
// SUMMARY
// =============================================================================
const BillingSummary = ({ contract, billed, remaining, current, retainage, approvedCOs, pendingCOs }) => {
  const billedPct = (billed / contract) * 100;
  const draftPct = (current / contract) * 100;
  return (
    <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Billing Summary</div>
          <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.015em", display: "flex", alignItems: "baseline", gap: 8, fontVariantNumeric: "tabular-nums" }}>
            {fmtMoneyFull(billed)} <span style={{ fontSize: 13, fontWeight: 400, color: "rgb(106,115,131)" }}>billed of {fmtMoneyFull(contract)} ({billedPct.toFixed(1)}%)</span>
          </div>
        </div>
        <Chip tone="info" dot>{fmtMoneyFull(current)} in current draft</Chip>
      </div>

      {/* Stacked progress bar: Billed (purple) | Draft (purple-50) | Remaining (gray) */}
      <div style={{ padding: "0 20px 16px 20px", paddingTop: 8 }}>
        <div style={{ position: "relative", height: 12, background: "rgb(241,242,244)", borderRadius: 9999, overflow: "hidden", display: "flex" }}>
          <div style={{ width: `${billedPct}%`, background: "rgb(83,74,255)" }} />
          <div style={{ width: `${draftPct}%`, background: "rgb(167,160,255)", borderLeft: "1px dashed #fff" }} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11, color: "rgb(106,115,131)", fontVariantNumeric: "tabular-nums" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: "rgb(83,74,255)" }} /> Billed {fmtMoney(billed)}
          </span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: "rgb(167,160,255)" }} /> Draft {fmtMoney(current)}
          </span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: "rgb(213,219,225)" }} /> Remaining {fmtMoney(remaining)}
          </span>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", borderTop: "1px solid rgb(239,240,242)" }}>
        <SummaryStat label="Contract Value" value={fmtMoney(contract)} sub="incl. approved COs" />
        <SummaryStat label="Billed to Date" value={fmtMoney(billed)} sub={`${billedPct.toFixed(0)}% of contract`} tone="info" />
        <SummaryStat label="Current Draft" value={fmtMoney(current)} sub="this period" tone="purple" />
        <SummaryStat label="Remaining" value={fmtMoney(remaining)} sub="to be billed" />
        <SummaryStat label="Retainage Held" value={fmtMoney(retainage)} sub="5% — Solis" />
        <SummaryStat label="Approved COs" value={fmtMoney(approvedCOs)} sub="in contract" tone="success" />
        <SummaryStat label="Pending COs" value={fmtMoney(pendingCOs)} sub="excluded" tone="warning" last />
      </div>
    </div>
  );
};

const SummaryStat = ({ label, value, sub, tone, last }) => {
  const fg = tone ? TONES[tone].fg : "rgb(26,27,37)";
  return (
    <div style={{ padding: "14px 16px", borderRight: last ? "none" : "1px solid rgb(239,240,242)" }}>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontWeight: 500, marginBottom: 6, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.015em", color: fg, fontVariantNumeric: "tabular-nums", lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 4 }}>{sub}</div>
    </div>
  );
};

// =============================================================================
// MODEL INDICATOR
// =============================================================================
const BillingModelBar = ({ model, breakdown, period, onPeriod }) => (
  <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, padding: "12px 16px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
      <div style={{ width: 32, height: 32, borderRadius: 8, background: "rgb(232,233,246)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon name="receipt" size={16} color="rgb(83,74,255)" />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, whiteSpace: "nowrap" }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "rgb(26,27,37)" }}>Billing Model</span>
          <Chip tone="info" dot>{model}</Chip>
        </div>
        <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {model === "Hybrid" ? `${breakdown.join(" + ")}` : "AIA G702/G703 Schedule of Values format"}
        </div>
      </div>
    </div>
    <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
      <span style={{ fontSize: 12, color: "rgb(106,115,131)" }}>Cycle:</span>
      <span style={{ fontSize: 13, color: "rgb(26,27,37)", fontWeight: 500 }}>Monthly</span>
      <span style={{ width: 1, height: 16, background: "rgb(231,233,236)" }} />
      <span style={{ fontSize: 12, color: "rgb(106,115,131)" }}>Customer:</span>
      <span style={{ fontSize: 13, color: "rgb(26,27,37)", fontWeight: 500 }}>Solis Energy</span>
      <span style={{ width: 1, height: 16, background: "rgb(231,233,236)" }} />
      <span style={{ fontSize: 12, color: "rgb(106,115,131)" }}>Net 30</span>
    </div>
  </div>
);

// =============================================================================
// FILTERS
// =============================================================================
const FiltersBar = ({ period, onPeriod, scopeFilter, onScope, scopes, billableOnly, onBillableOnly, state, onState }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
    <SelectField icon="calendar" value={period} options={BILLING_PERIODS} onChange={onPeriod} width={240} />
    <SelectField icon="layers" value={scopeFilter} options={scopes} onChange={onScope} width={200} />
    <ToggleChip active={billableOnly} onClick={() => onBillableOnly(!billableOnly)}>
      <Icon name="filter" size={12} />
      Billable items only
    </ToggleChip>
    <div style={{ flex: 1 }} />
    {/* State demo (designer convenience) */}
    <div style={{ display: "inline-flex", background: "rgb(248,248,251)", border: "1px solid rgb(231,233,236)", borderRadius: 9999, padding: 2 }}>
      {[
        { id: "draft", label: "Draft" },
        { id: "ready", label: "Ready" },
        { id: "empty", label: "Empty" },
        { id: "complete", label: "Complete" },
      ].map(o => (
        <button key={o.id} onClick={() => onState(o.id)} style={{
          padding: "4px 10px", border: 0, borderRadius: 9999, fontSize: 11, fontWeight: 500, fontFamily: "inherit",
          background: state === o.id ? "#fff" : "transparent",
          color: state === o.id ? "rgb(83,74,255)" : "rgb(106,115,131)",
          boxShadow: state === o.id ? "0 1px 2px rgba(42,43,57,.08)" : "none", cursor: "pointer"
        }}>{o.label}</button>
      ))}
    </div>
  </div>
);

const SelectField = ({ icon, value, options, onChange, width = 200 }) => (
  <div style={{ position: "relative", width }}>
    {icon && <Icon name={icon} size={13} color="rgb(106,115,131)" style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }} />}
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      width: "100%", boxSizing: "border-box", height: 30, paddingLeft: icon ? 30 : 12, paddingRight: 28,
      borderRadius: 9999, border: "1px solid rgb(213,219,225)", background: "#fff",
      fontSize: 13, fontFamily: "inherit", color: "rgb(26,27,37)", appearance: "none", cursor: "pointer", outline: "none"
    }}>
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
    <Icon name="expandDown" size={12} color="rgb(106,115,131)" style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }} />
  </div>
);

const ToggleChip = ({ active, onClick, children }) => (
  <button onClick={onClick} style={{
    height: 30, padding: "0 12px", borderRadius: 9999,
    border: `1px solid ${active ? "rgb(83,74,255)" : "rgb(213,219,225)"}`,
    background: active ? "rgb(232,233,246)" : "#fff",
    color: active ? "rgb(83,74,255)" : "rgb(65,69,82)",
    fontSize: 12, fontWeight: 500, fontFamily: "inherit", cursor: "pointer",
    display: "inline-flex", alignItems: "center", gap: 6
  }}>{children}</button>
);

// =============================================================================
// SCHEDULE OF VALUES
// =============================================================================
const BillingWorkspace = ({ rows, onPctChange, currentDraft, earnedRevenue, billedToDate }) => {
  const cols = "minmax(240px, 1.4fr) minmax(160px, 1fr) 110px 110px 130px 130px 130px 130px";
  return (
    <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
      <div style={{ padding: "14px 20px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "rgb(26,27,37)" }}>Schedule of Values</div>
          <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2 }}>AIA G703 — edit % complete to recalculate current billing</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Button size="sm" kind="secondary" icon="refresh">Refresh from Progress</Button>
          <Button size="sm" kind="secondary" icon="columns">Columns</Button>
          <Button size="sm" kind="secondary" icon="download">Export</Button>
        </div>
      </div>

      <div style={{ overflowX: "auto" }}>
        <div style={{ minWidth: 1100 }}>
          {/* Header */}
          <div style={{
            display: "grid", gridTemplateColumns: cols, gap: 0,
            background: "rgb(248,248,251)", borderBottom: "1px solid rgb(239,240,242)",
            fontSize: 11, fontWeight: 600, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em"
          }}>
            <SovHead>Scope / Line Item</SovHead>
            <SovHead>Description</SovHead>
            <SovHead align="right">Contract</SovHead>
            <SovHead align="right">% Complete</SovHead>
            <SovHead align="right">Earned</SovHead>
            <SovHead align="right">Previously Billed</SovHead>
            <SovHead align="right">Current Billing</SovHead>
            <SovHead align="right">Remaining</SovHead>
          </div>

          {/* Rows */}
          <div>
            {rows.map((r, i) => (
              <SovRow key={r.id} row={r} cols={cols} last={i === rows.length - 1} onPctChange={onPctChange} />
            ))}
          </div>

          {/* Footer totals */}
          <div style={{
            display: "grid", gridTemplateColumns: cols, gap: 0,
            background: "rgb(248,248,251)", borderTop: "1px solid rgb(231,233,236)",
            fontSize: 13, fontWeight: 600, color: "rgb(26,27,37)", fontVariantNumeric: "tabular-nums"
          }}>
            <div style={{ padding: "12px 14px", gridColumn: "span 2" }}>Totals</div>
            <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(rows.reduce((s, r) => s + r.contract, 0))}</div>
            <div style={{ padding: "12px 14px", textAlign: "right", color: "rgb(106,115,131)" }}>—</div>
            <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(rows.reduce((s, r) => s + r.contract * r.pct / 100, 0))}</div>
            <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(rows.reduce((s, r) => s + r.prevBilled, 0))}</div>
            <div style={{ padding: "12px 14px", textAlign: "right", color: "rgb(83,74,255)" }}>{fmtMoneyFull(rows.reduce((s, r) => s + r.current, 0))}</div>
            <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(rows.reduce((s, r) => s + r.contract - r.prevBilled - r.current, 0))}</div>
          </div>
        </div>
      </div>
    </div>
  );
};

const SovHead = ({ children, align = "left" }) => (
  <div style={{ padding: "10px 14px", textAlign: align }}>{children}</div>
);

const SovRow = ({ row, cols, last, onPctChange }) => {
  const earned = row.contract * (row.pct / 100);
  const remaining = row.contract - row.prevBilled - row.current;
  const overBilled = (row.prevBilled + row.current) > earned + 1;
  const underBilled = earned - (row.prevBilled + row.current) > row.contract * 0.05;

  return (
    <div style={{
      display: "grid", gridTemplateColumns: cols,
      borderBottom: last ? "none" : "1px solid rgb(239,240,242)",
      fontSize: 13, color: "rgb(26,27,37)", fontVariantNumeric: "tabular-nums", alignItems: "center"
    }}
      onMouseEnter={e => e.currentTarget.style.background = "rgb(252,252,254)"}
      onMouseLeave={e => e.currentTarget.style.background = "transparent"}
    >
      {/* Scope */}
      <div style={{ padding: "12px 14px", display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
        {row.isCO && <Chip tone="purple" style={{ fontSize: 10, padding: "1px 6px" }}>CO</Chip>}
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 500, color: "rgb(26,27,37)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {row.scope}
          </div>
          <div style={{ fontSize: 11, color: "rgb(106,115,131)", fontVariantNumeric: "tabular-nums" }}>{row.id}</div>
        </div>
        {!row.ready && (
          <span title={row.blockReason} style={{ display: "inline-flex" }}>
            <Icon name="alertCircle" size={14} color="rgb(178,121,26)" />
          </span>
        )}
      </div>

      <div style={{ padding: "12px 14px", color: "rgb(65,69,82)", fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        {row.desc}
      </div>

      <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(row.contract)}</div>

      {/* Editable % */}
      <div style={{ padding: "12px 14px", textAlign: "right" }}>
        <PctEditor value={row.pct} onChange={v => onPctChange(row.id, v)} />
      </div>

      <div style={{ padding: "12px 14px", textAlign: "right" }}>{fmtMoneyFull(earned)}</div>
      <div style={{ padding: "12px 14px", textAlign: "right", color: "rgb(106,115,131)" }}>{fmtMoneyFull(row.prevBilled)}</div>

      {/* Current billing — highlight when nonzero */}
      <div style={{ padding: "12px 14px", textAlign: "right" }}>
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 4,
          padding: row.current > 0 ? "2px 8px" : 0, borderRadius: 6,
          background: row.current > 0 ? "rgb(232,233,246)" : "transparent",
          color: row.current > 0 ? "rgb(83,74,255)" : "rgb(163,172,186)",
          fontWeight: row.current > 0 ? 600 : 400
        }}>
          {row.current > 0 ? fmtMoneyFull(row.current) : "—"}
        </span>
        {(overBilled || underBilled) && row.current > 0 && (
          <div style={{ fontSize: 10, marginTop: 2, color: overBilled ? "rgb(192,47,50)" : "rgb(178,121,26)" }}>
            {overBilled ? "Over earned" : "Under earned"}
          </div>
        )}
      </div>

      <div style={{ padding: "12px 14px", textAlign: "right", color: remaining === 0 ? "rgb(34,134,58)" : "rgb(65,69,82)" }}>
        {remaining === 0 ? "—" : fmtMoneyFull(remaining)}
      </div>
    </div>
  );
};

const PctEditor = ({ value, onChange }) => {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(String(value));
  React.useEffect(() => setDraft(String(value)), [value]);
  const commit = () => {
    const n = Math.max(0, Math.min(100, parseFloat(draft) || 0));
    onChange(n);
    setEditing(false);
  };
  return editing ? (
    <input
      autoFocus
      value={draft}
      onChange={e => setDraft(e.target.value)}
      onBlur={commit}
      onKeyDown={e => { if (e.key === "Enter") commit(); if (e.key === "Escape") { setDraft(String(value)); setEditing(false); } }}
      style={{
        width: 64, height: 26, padding: "0 8px", borderRadius: 6,
        border: "1px solid rgb(83,74,255)", fontSize: 13, fontFamily: "inherit",
        textAlign: "right", outline: "none", background: "#fff", boxShadow: "0 0 0 3px rgba(83,74,255,.12)"
      }}
    />
  ) : (
    <button onClick={() => setEditing(true)} style={{
      display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 8px", borderRadius: 6,
      border: "1px solid transparent", background: "transparent", fontSize: 13, fontFamily: "inherit", fontVariantNumeric: "tabular-nums",
      color: "rgb(26,27,37)", fontWeight: 500, cursor: "pointer"
    }}
      onMouseEnter={e => { e.currentTarget.style.background = "rgb(248,248,251)"; e.currentTarget.style.borderColor = "rgb(231,233,236)"; }}
      onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.borderColor = "transparent"; }}
    >
      {value}%
      <Icon name="pen" size={10} color="rgb(163,172,186)" />
    </button>
  );
};

// =============================================================================
// ACTIONS
// =============================================================================
const BillingActionsBar = ({ currentDraft, ready }) => (
  <div style={{
    background: ready ? "rgb(244,251,246)" : "#fff",
    border: `1px solid ${ready ? "rgb(195,228,205)" : "rgb(231,233,236)"}`,
    borderRadius: 12, padding: "14px 18px",
    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap"
  }}>
    <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0, flex: "1 1 320px" }}>
      <div style={{
        width: 36, height: 36, borderRadius: "50%",
        background: ready ? "rgb(218,240,224)" : "rgb(241,242,244)",
        display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0
      }}>
        <Icon name={ready ? "check" : "receipt"} size={18} color={ready ? "rgb(34,134,58)" : "rgb(106,115,131)"} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: "rgb(26,27,37)" }}>
          {ready ? "Ready to invoice" : "Draft in progress"}
        </div>
        <div style={{ fontSize: 12, color: "rgb(106,115,131)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>
          {ready
            ? `${fmtMoneyFull(currentDraft)} will be invoiced for the current period`
            : `${fmtMoneyFull(currentDraft)} drafted — resolve readiness checks before generating invoice`}
        </div>
      </div>
    </div>
    <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
      <Button size="sm" kind="ghost" icon="refresh">Refresh from Progress</Button>
      <Button size="sm" kind="secondary" icon="link">Apply Approved COs</Button>
      <Button size="sm" kind="secondary" icon="eye">Preview Invoice</Button>
      <Button size="sm" kind="secondary" icon="archive">Save Draft</Button>
      <Button size="sm" kind="primary" icon="send">Generate Invoice</Button>
    </div>
  </div>
);

// =============================================================================
// CHANGE ORDER IMPACT
// =============================================================================
const ChangeOrderImpact = ({ approvedCOs, pendingCOs }) => (
  <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
    <div style={{ padding: "14px 20px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: "rgb(26,27,37)" }}>Change Order Impact</span>
        <Chip tone="success">{fmtMoney(approvedCOs)} approved</Chip>
        <Chip tone="warning">{fmtMoney(pendingCOs.reduce((s,c) => s + c.value, 0))} pending</Chip>
      </div>
      <Button size="sm" kind="ghost" iconRight="chevronRight">Open Change Orders</Button>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}>
      {/* Approved */}
      <div style={{ padding: 18, borderRight: "1px solid rgb(239,240,242)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "rgb(34,134,58)", marginBottom: 10, textTransform: "uppercase", letterSpacing: ".05em" }}>
          <Icon name="check" size={12} color="rgb(34,134,58)" />
          Included in billing (Approved)
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <COImpactRow id="CO-013" title="Predrill 480 piles — refusal zone" value={92_800} status="Applied" />
          <COImpactRow id="CO-009" title="SWPPP extension — 60 days" value={12_400} status="Applied" />
        </div>
      </div>
      {/* Pending */}
      <div style={{ padding: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "rgb(178,121,26)", marginBottom: 10, textTransform: "uppercase", letterSpacing: ".05em" }}>
          <Icon name="clock" size={12} color="rgb(178,121,26)" />
          Excluded — awaiting approval
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {pendingCOs.map(co => (
            <COImpactRow key={co.id} id={co.id} title={co.title} value={co.value} status={co.status} pending />
          ))}
        </div>
      </div>
    </div>
  </div>
);

const COImpactRow = ({ id, title, value, status, pending }) => (
  <div style={{
    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
    padding: "10px 12px", borderRadius: 8,
    background: pending ? "rgb(255,250,242)" : "rgb(244,251,246)",
    border: `1px solid ${pending ? "rgb(245,231,207)" : "rgb(220,237,225)"}`
  }}>
    <div style={{ minWidth: 0, display: "flex", alignItems: "center", gap: 10 }}>
      <Chip tone={pending ? "warning" : "success"} style={{ fontSize: 11 }}>{id}</Chip>
      <span style={{ fontSize: 13, color: "rgb(26,27,37)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</span>
    </div>
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: "rgb(26,27,37)", fontVariantNumeric: "tabular-nums" }}>
        {value > 0 ? fmtMoneyFull(value) : "Cost-only"}
      </span>
      {pending ? (
        <Button size="xs" kind="secondary">Apply when approved</Button>
      ) : (
        <span style={{ fontSize: 11, color: "rgb(34,134,58)", fontWeight: 500 }}>{status}</span>
      )}
    </div>
  </div>
);

// =============================================================================
// INVOICE HISTORY
// =============================================================================
const InvoiceHistoryTable = ({ invoices }) => {
  const cols = "140px 110px 200px 130px 120px 140px 1fr 100px";
  return (
    <div style={{ background: "#fff", border: "1px solid rgb(231,233,236)", borderRadius: 12, overflow: "hidden" }}>
      <div style={{ padding: "14px 20px", borderBottom: "1px solid rgb(239,240,242)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: "rgb(26,27,37)" }}>Invoice History</span>
          <Chip tone="neutral">{invoices.length}</Chip>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Button size="sm" kind="ghost" icon="download">Export</Button>
          <Button size="sm" kind="secondary" icon="filter">Filter</Button>
        </div>
      </div>

      <div style={{
        display: "grid", gridTemplateColumns: cols,
        background: "rgb(248,248,251)", borderBottom: "1px solid rgb(239,240,242)",
        fontSize: 11, fontWeight: 600, color: "rgb(106,115,131)", textTransform: "uppercase", letterSpacing: ".04em"
      }}>
        <div style={{ padding: "10px 14px" }}>Invoice #</div>
        <div style={{ padding: "10px 14px" }}>Date</div>
        <div style={{ padding: "10px 14px" }}>Period</div>
        <div style={{ padding: "10px 14px", textAlign: "right" }}>Amount</div>
        <div style={{ padding: "10px 14px" }}>Status</div>
        <div style={{ padding: "10px 14px" }}>Related COs</div>
        <div style={{ padding: "10px 14px" }}>Note</div>
        <div style={{ padding: "10px 14px", textAlign: "right" }}>Actions</div>
      </div>

      {invoices.map((inv, i) => {
        const t = INVOICE_TONES[inv.status];
        return (
          <div key={inv.num} style={{
            display: "grid", gridTemplateColumns: cols,
            borderBottom: i === invoices.length - 1 ? "none" : "1px solid rgb(239,240,242)",
            fontSize: 13, color: "rgb(26,27,37)", fontVariantNumeric: "tabular-nums", alignItems: "center"
          }}
            onMouseEnter={e => e.currentTarget.style.background = "rgb(252,252,254)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}
          >
            <div style={{ padding: "12px 14px", fontWeight: 500 }}>{inv.num}</div>
            <div style={{ padding: "12px 14px", color: "rgb(65,69,82)" }}>{inv.date}</div>
            <div style={{ padding: "12px 14px", color: "rgb(65,69,82)" }}>{inv.period}</div>
            <div style={{ padding: "12px 14px", textAlign: "right", fontWeight: 600 }}>
              {inv.amount === 0 ? <span style={{ color: "rgb(163,172,186)", fontWeight: 400 }}>—</span> : fmtMoneyFull(inv.amount)}
            </div>
            <div style={{ padding: "12px 14px" }}>
              <Chip tone={t.tone} dot>{t.label}</Chip>
            </div>
            <div style={{ padding: "12px 14px", display: "flex", gap: 4, flexWrap: "wrap" }}>
              {inv.cos.length === 0
                ? <span style={{ color: "rgb(163,172,186)" }}>—</span>
                : inv.cos.map(co => <Chip key={co} tone="purple" style={{ fontSize: 11 }}>{co}</Chip>)}
            </div>
            <div style={{ padding: "12px 14px", color: "rgb(106,115,131)", fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              {inv.note}
            </div>
            <div style={{ padding: "12px 14px", textAlign: "right", display: "flex", justifyContent: "flex-end", gap: 4 }}>
              <IconBtn icon="eye" size={26} />
              <IconBtn icon="download" size={26} />
              <IconBtn icon="more" size={26} />
            </div>
          </div>
        );
      })}
    </div>
  );
};

// =============================================================================
// READINESS CHECK + ALERT CARD + QUICK ACTION (used by BillingReadinessPanel)
// =============================================================================
const ReadinessCheck = ({ label, state, detail, action }) => {
  const tone = state === "ok" ? "success" : state === "warn" ? "warning" : "danger";
  const icon = state === "ok" ? "check" : state === "warn" ? "alertCircle" : "alert";
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
      <div style={{
        width: 20, height: 20, borderRadius: "50%", flexShrink: 0,
        background: TONES[tone].bg, color: TONES[tone].fg,
        display: "inline-flex", alignItems: "center", justifyContent: "center", marginTop: 1
      }}>
        <Icon name={icon} size={11} color={TONES[tone].fg} />
      </div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13, color: "rgb(26,27,37)", fontWeight: 500, lineHeight: 1.35 }}>{label}</div>
        <div style={{ fontSize: 11, color: "rgb(106,115,131)", marginTop: 2, lineHeight: 1.4 }}>{detail}</div>
        {action && (
          <button style={{ background: "transparent", border: 0, padding: 0, fontSize: 11, color: "rgb(83,74,255)", fontWeight: 500, fontFamily: "inherit", cursor: "pointer", marginTop: 4 }}>
            {action} →
          </button>
        )}
      </div>
    </div>
  );
};

const AlertCard = ({ tone, icon, title, body, cta }) => (
  <div style={{
    background: tone === "info" ? "rgb(248,248,251)" : TONES[tone].bg,
    border: `1px solid ${tone === "info" ? "rgb(231,233,236)" : "transparent"}`,
    borderRadius: 8, padding: 10
  }}>
    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
      <Icon name={icon} size={12} color={TONES[tone].fg} />
      <span style={{ fontSize: 12, fontWeight: 600, color: tone === "info" ? "rgb(26,27,37)" : TONES[tone].fg }}>{title}</span>
    </div>
    <div style={{ fontSize: 11, color: "rgb(65,69,82)", lineHeight: 1.45, marginBottom: 6 }}>{body}</div>
    {cta && (
      <button style={{
        background: "transparent", border: 0, padding: 0, fontSize: 11, fontWeight: 500,
        color: TONES[tone].fg, fontFamily: "inherit", cursor: "pointer"
      }}>
        {cta} →
      </button>
    )}
  </div>
);

const QuickAction = ({ icon, label }) => (
  <button style={{
    display: "flex", alignItems: "center", gap: 8, width: "100%",
    padding: "8px 10px", borderRadius: 8, border: "1px solid rgb(239,240,242)",
    background: "#fff", fontFamily: "inherit", fontSize: 12, color: "rgb(26,27,37)",
    fontWeight: 500, cursor: "pointer", textAlign: "left"
  }}
    onMouseEnter={e => { e.currentTarget.style.background = "rgb(248,248,251)"; e.currentTarget.style.borderColor = "rgb(231,233,236)"; }}
    onMouseLeave={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.style.borderColor = "rgb(239,240,242)"; }}
  >
    <Icon name={icon} size={13} color="rgb(83,74,255)" />
    {label}
    <span style={{ flex: 1 }} />
    <Icon name="chevronRight" size={12} color="rgb(163,172,186)" />
  </button>
);

// =============================================================================
// EMPTY / COMPLETE STATES
// =============================================================================
const EmptyBillingState = () => (
  <div style={{
    background: "#fff", border: "1px dashed rgb(213,219,225)", borderRadius: 12,
    padding: "60px 24px", textAlign: "center"
  }}>
    <div style={{ width: 56, height: 56, borderRadius: 14, background: "rgb(248,248,251)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
      <Icon name="receipt" size={26} color="rgb(106,115,131)" />
    </div>
    <div style={{ fontSize: 16, fontWeight: 600, color: "rgb(26,27,37)", marginBottom: 6 }}>No billing activity yet</div>
    <div style={{ fontSize: 13, color: "rgb(106,115,131)", maxWidth: 420, margin: "0 auto 18px" }}>
      Once progress is logged on the first scope, your Schedule of Values will populate here. You can also start a manual draft.
    </div>
    <div style={{ display: "inline-flex", gap: 8 }}>
      <Button kind="primary" size="md" icon="plus">Start Billing Draft</Button>
      <Button kind="secondary" size="md" icon="refresh">Sync from Progress</Button>
    </div>
  </div>
);

const CompleteBillingState = ({ contract, billed }) => (
  <div style={{
    background: "linear-gradient(180deg, rgb(244,251,246) 0%, #fff 100%)",
    border: "1px solid rgb(220,237,225)", borderRadius: 12,
    padding: "32px 28px", display: "flex", alignItems: "center", gap: 24
  }}>
    <div style={{ width: 56, height: 56, borderRadius: 14, background: "rgb(218,240,224)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
      <Icon name="check" size={28} color="rgb(34,134,58)" />
    </div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 16, fontWeight: 600, color: "rgb(26,27,37)" }}>Project fully billed</div>
      <div style={{ fontSize: 13, color: "rgb(65,69,82)", marginTop: 4 }}>
        {fmtMoneyFull(billed)} of {fmtMoneyFull(contract)} contract value invoiced. Final retainage release pending closeout.
      </div>
    </div>
    <Button kind="secondary" icon="receipt">View Final Invoice</Button>
    <Button kind="primary" icon="archive">Initiate Closeout</Button>
  </div>
);

window.BillingTab = BillingTab;
