/* Finance — invoice-approval.xlsx
 * 5-sheet workbook with cross-sheet formulas.
 * Click any cell to see its formula in the formula bar.
 * Click any sheet tab to switch.
 */

const xlTheme = {
  bg:    "#1a1816",
  chrome:"#211e1b",
  border:"#2a2825",
  ink:   "#f0ece4",
  ink2:  "#a8a49b",
  ink3:  "#6b6862",
  ink4:  "#4a4842",
  amber: "#d99350",
  // sheet
  sheetBg: "#ffffff",
  sheetGrid: "#dadcd8",
  sheetGridStrong: "#b8bab5",
  sheetHeader: "#f2f1ec",
  sheetSelected: "#cce4cf", // Excel-green
  sheetSelectedBorder: "#137333",
  cellInk: "#1a1a18",
  cellInk2: "#5a594e",
  cellInk3: "#9c988e",
  formulaBlue: "#1a73b8",
  varianceRed: "#c0392b",
  variancePill: "#fdeed3",
  okPill: "#e3edd9",
};

// ─── Data ─────────────────────────────────────────────────────────────────
// Invoices sheet — 12 rows (1–12 shown, conceptually 800)
const INV_ROWS = [
  ["INV-104377", "Hwang Foods Ltd",          "2026-05-04", 18420.50, "PO-7733"],
  ["INV-104378", "Ortega Maintenance",        "2026-05-06",  2940.00, "PO-7735"],
  ["INV-104379", "Maritime Brokers GmbH",     "2026-05-08", 34200.00, "PO-7736"],
  ["INV-104380", "Halcyon Print Services",    "2026-05-09",   486.00, "PO-7738"],
  ["INV-104381", "Norlex Industrial",          "2026-05-10",  8412.40, "PO-7740"],
  ["INV-104382", "Brevard Logistics SARL",    "2026-05-11", 12480.00, "PO-7741"],
  ["INV-104383", "Aurum Office Supplies",      "2026-05-11",   312.80, "PO-7742"],
  ["INV-104384", "Verdani Cleaning",            "2026-05-12",  1820.00, "PO-7743"],
  ["INV-104385", "Tilbury Freight",             "2026-05-12",  4980.00, "PO-7745"],
  ["INV-104386", "Northbridge Insurance",       "2026-05-13",  9200.00, "PO-7748"],
  ["INV-104387", "Brevard Logistics SARL",    "2026-05-14",  3940.00, "PO-7752"],
  ["INV-104388", "Atlas Steel Works",            "2026-05-14", 27410.00, "PO-7754"],
];
const INV_HEADERS = ["Invoice", "Supplier", "Date", "Amount (€)", "PO"];

// POs sheet
const PO_ROWS = [
  ["PO-7733", "Hwang Foods Ltd",          18420.50, "approved"],
  ["PO-7735", "Ortega Maintenance",        2740.00, "approved"],
  ["PO-7736", "Maritime Brokers GmbH",    34200.00, "approved"],
  ["PO-7738", "Halcyon Print Services",     486.00, "approved"],
  ["PO-7740", "Norlex Industrial",         8200.00, "approved"],
  ["PO-7741", "Brevard Logistics SARL",   12480.00, "approved"],
  ["PO-7742", "Aurum Office Supplies",       312.80, "approved"],
  ["PO-7743", "Verdani Cleaning",            1820.00, "approved"],
  ["PO-7745", "Tilbury Freight",              4800.00, "approved"],
  ["PO-7748", "Northbridge Insurance",      9200.00, "approved"],
  ["PO-7752", "Brevard Logistics SARL",      3940.00, "approved"],
  ["PO-7754", "Atlas Steel Works",          26000.00, "approved"],
];
const PO_HEADERS = ["PO", "Supplier", "Total (€)", "Status"];

// Variances sheet — fully formula-driven
const VARI_ROWS = INV_ROWS.map((r, i) => {
  const po = PO_ROWS.find(p => p[0] === r[4]);
  const variance = r[3] - po[2];
  return { inv: r[0], invAmt: r[3], poId: r[4], poAmt: po[2], variance };
});
const VARI_HEADERS = ["Invoice", "Inv €", "PO", "PO €", "Variance €", "Result"];

// Approvals sheet — routes by approver
const APPROVERS = [
  ["operations", "P. Khoury",      "ops@",     50000],
  ["facilities", "S. Petersen",     "fac@",     10000],
  ["logistics",  "J. Marini",       "log@",    100000],
  ["finance",    "A. Soumare",      "fin@",   1000000],
];

function routeFor(supplier, variance) {
  if (variance === 0) return "auto";
  if (supplier.includes("Logistics") || supplier.includes("Freight") || supplier.includes("Maritime")) return "logistics";
  if (supplier.includes("Maintenance") || supplier.includes("Cleaning")) return "facilities";
  if (supplier.includes("Industrial") || supplier.includes("Steel")) return "operations";
  return "finance";
}

const APPR_ROWS = VARI_ROWS.map((v, i) => {
  const r = INV_ROWS[i];
  const dept = routeFor(r[1], v.variance);
  const status = v.variance === 0 ? "auto-approved" : "review";
  const approver = dept === "auto" ? "—" : (APPROVERS.find(a => a[0] === dept)?.[1] || "—");
  return [r[0], r[1], v.variance, status, dept, approver];
});
const APPR_HEADERS = ["Invoice", "Supplier", "Variance €", "Status", "Routed to", "Approver"];

// Summary sheet — cells with formulas (key: "A1" style)
const SUMMARY_CELLS = {
  // title row
  A1: { v: "Invoice Approval — May 2026", b: true, size: 16, ink: xlTheme.cellInk, span: 4 },
  A3: { v: "Workbook:" },                B3: { v: "invoice-approval.xlsx", ink: xlTheme.formulaBlue },
  A4: { v: "Generated:" },               B4: { v: "18 May 2026, 09:42" },
  A5: { v: "Auditor:" },                 B5: { v: "ForgeAI · sig 0xa17e…" },

  // headline metrics
  A7: { v: "HEADLINE METRICS", b: true, ink: xlTheme.ink3, size: 11 },
  A8:  { v: "Invoices this period" },          B8:  { v: 800,         f: "=COUNTA(Invoices!A2:A801)" },
  A9:  { v: "Total invoiced (€)" },             B9:  { v: 1847290.40,  f: "=SUM(Invoices!D2:D801)", money: true },
  A10: { v: "Matched to PO (auto-approved)" }, B10: { v: 753,         f: "=COUNTIF(Approvals!D2:D801,\"auto-approved\")", ink: "#137333", b: true },
  A11: { v: "Flagged for review" },             B11: { v:  47,         f: "=COUNTIF(Approvals!D2:D801,\"review\")",         ink: xlTheme.amber,  b: true },
  A12: { v: "Total variance value (€)" },        B12: { v: 12840.20,    f: "=SUMIF(Variances!E2:E801,\">0\")", money: true },
  A13: { v: "Average variance · flagged (€)" },   B13: { v: 273.20,      f: "=AVERAGEIFS(Variances!E2:E801,Variances!E2:E801,\">0\")", money: true },

  // by approver
  A15: { v: "ROUTED BY APPROVER", b: true, ink: xlTheme.ink3, size: 11 },
  A16: { v: "Operations · P. Khoury" },      B16: { v:  14, f: "=COUNTIF(Approvals!E2:E801,\"operations\")" },  C16: { v: 4120.20,  f: "=SUMIF(Approvals!E2:E801,\"operations\",Approvals!C2:C801)", money: true },
  A17: { v: "Facilities · S. Petersen" },      B17: { v:   9, f: "=COUNTIF(Approvals!E2:E801,\"facilities\")" }, C17: { v:  840.00,  f: "=SUMIF(Approvals!E2:E801,\"facilities\",Approvals!C2:C801)", money: true },
  A18: { v: "Logistics · J. Marini" },           B18: { v:  18, f: "=COUNTIF(Approvals!E2:E801,\"logistics\")" },  C18: { v: 6210.00,  f: "=SUMIF(Approvals!E2:E801,\"logistics\",Approvals!C2:C801)", money: true },
  A19: { v: "Finance · A. Soumare" },             B19: { v:   6, f: "=COUNTIF(Approvals!E2:E801,\"finance\")" },    C19: { v: 1670.00,  f: "=SUMIF(Approvals!E2:E801,\"finance\",Approvals!C2:C801)", money: true },
  A20: { v: "Total" },                              B20: { v:  47, f: "=B16+B17+B18+B19", b: true },                C20: { v: 12840.20, f: "=C16+C17+C18+C19", money: true, b: true },

  // health check
  A22: { v: "HEALTH CHECK", b: true, ink: xlTheme.ink3, size: 11 },
  A23: { v: "Match rate" },              B23: { v: "94.1%", f: "=TEXT(B10/B8,\"0.0%\")" },
  A24: { v: "Largest single variance" }, B24: { v: 1410.00, f: "=MAX(Variances!E2:E801)", money: true },
  A25: { v: "Suppliers w/ variance"},     B25: { v: 12,      f: "=SUMPRODUCT((COUNTIFS(Approvals!B2:B801,Approvals!B2:B801,Approvals!D2:D801,\"review\")>0)/COUNTIF(Approvals!B2:B801,Approvals!B2:B801))" },
  A26: { v: "Saved vs manual review" },   B26: { v: "≈ 96 hrs", f: "=(B8*22-B11*8)/60 & \" hrs\"" },
};

// Sheets ordering
const XL_SHEETS = ["Invoices", "POs", "Variances", "Approvals", "Summary"];

// ─── Formula generators (for non-summary sheets) ───────────────────────────
function variancesFormula(col, row /* 2-based excel row */) {
  // row is 2..13
  const i = row - 2;
  if (col === "A") return `=Invoices!A${row}`;
  if (col === "B") return `=Invoices!D${row}`;
  if (col === "C") return `=Invoices!E${row}`;
  if (col === "D") return `=VLOOKUP(C${row}, POs!A:C, 3, FALSE)`;
  if (col === "E") return `=B${row}-D${row}`;
  if (col === "F") return `=IF(E${row}=0, "auto-approved", "review")`;
  return null;
}

function approvalsFormula(col, row) {
  if (col === "A") return `=Invoices!A${row}`;
  if (col === "B") return `=Invoices!B${row}`;
  if (col === "C") return `=Variances!E${row}`;
  if (col === "D") return `=Variances!F${row}`;
  if (col === "E") return `=IF(C${row}=0,"auto",IF(ISNUMBER(SEARCH("Logist",B${row})),"logistics",IF(ISNUMBER(SEARCH("Maint",B${row})),"facilities","operations")))`;
  if (col === "F") return `=VLOOKUP(E${row}, RoutingTable!A:B, 2, FALSE)`;
  return null;
}

// ─── Helpers ──────────────────────────────────────────────────────────────
function colLetter(i) { return String.fromCharCode(65 + i); }

function fmtMoney(n) {
  return n.toLocaleString("en", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// ─── Render a sheet ───────────────────────────────────────────────────────
function SheetGrid({ sheetName, headers, rows, formulaFor, selected, onPick, colWidths }) {
  const widths = colWidths || headers.map(h => 130);

  return (
    <table style={{
      borderCollapse: "separate",
      borderSpacing: 0,
      width: "100%",
      fontSize: 12,
      fontFamily: '"Inter", system-ui, sans-serif',
      color: xlTheme.cellInk,
      tableLayout: "fixed",
    }}>
      <colgroup>
        <col style={{ width: 36 }} />
        {widths.map((w, i) => <col key={i} style={{ width: w }} />)}
      </colgroup>
      <thead>
        {/* Column letters */}
        <tr>
          <th style={{
            background: xlTheme.sheetHeader,
            borderRight: "1px solid " + xlTheme.sheetGrid,
            borderBottom: "1px solid " + xlTheme.sheetGrid,
            height: 22,
          }} />
          {headers.map((h, i) => (
            <th key={i} style={{
              background: xlTheme.sheetHeader,
              borderRight: "1px solid " + xlTheme.sheetGrid,
              borderBottom: "1px solid " + xlTheme.sheetGrid,
              padding: "2px 0",
              textAlign: "center",
              fontSize: 11,
              color: xlTheme.cellInk2,
              fontWeight: 500,
              height: 22,
            }}>{colLetter(i)}</th>
          ))}
        </tr>
        {/* Column titles row 1 */}
        <tr>
          <td style={{
            background: xlTheme.sheetHeader,
            borderRight: "1px solid " + xlTheme.sheetGrid,
            borderBottom: "1px solid " + xlTheme.sheetGridStrong,
            padding: "5px 4px",
            textAlign: "right",
            fontSize: 11,
            color: xlTheme.cellInk2,
            fontWeight: 500,
          }}>1</td>
          {headers.map((h, i) => {
            const isSel = selected.row === 1 && selected.col === i;
            return (
              <td key={i}
                onClick={() => onPick({ row: 1, col: i, formula: null, value: h })}
                style={{
                  background: xlTheme.sheetHeader,
                  borderRight: "1px solid " + xlTheme.sheetGrid,
                  borderBottom: "1px solid " + xlTheme.sheetGridStrong,
                  padding: "5px 8px",
                  fontWeight: 600,
                  outline: isSel ? "2px solid " + xlTheme.sheetSelectedBorder : "none",
                  outlineOffset: "-2px",
                  cursor: "cell",
                }}>{h}</td>
            );
          })}
        </tr>
      </thead>
      <tbody>
        {rows.map((row, r) => {
          const excelRow = r + 2;
          return (
            <tr key={r}>
              <td style={{
                background: xlTheme.sheetHeader,
                borderRight: "1px solid " + xlTheme.sheetGrid,
                borderBottom: "1px solid " + xlTheme.sheetGrid,
                padding: "5px 4px",
                textAlign: "right",
                fontSize: 11,
                color: xlTheme.cellInk2,
                fontWeight: 500,
              }}>{excelRow}</td>
              {row.map((cell, c) => {
                const isSel = selected.row === excelRow && selected.col === c;
                const f = formulaFor ? formulaFor(colLetter(c), excelRow) : null;
                const display = typeof cell === "object" ? cell : { v: cell };
                let cellValue = display.v;
                let cellInk = display.ink || xlTheme.cellInk;
                let bg = "white";
                let align = display.align || (typeof cellValue === "number" ? "right" : "left");
                if (display.money) cellValue = fmtMoney(cellValue);
                if (display.pill) {
                  bg = display.pillBg;
                }
                if (isSel) bg = xlTheme.sheetSelected;
                return (
                  <td key={c}
                    onClick={() => onPick({ row: excelRow, col: c, formula: f, value: cellValue })}
                    style={{
                      borderRight: "1px solid " + xlTheme.sheetGrid,
                      borderBottom: "1px solid " + xlTheme.sheetGrid,
                      padding: "5px 8px",
                      background: bg,
                      color: cellInk,
                      fontWeight: display.b ? 600 : 400,
                      textAlign: align,
                      fontVariantNumeric: "tabular-nums",
                      outline: isSel ? "2px solid " + xlTheme.sheetSelectedBorder : "none",
                      outlineOffset: "-2px",
                      cursor: "cell",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      fontSize: display.size || 12,
                    }}>
                    {display.pill ? (
                      <span style={{
                        fontSize: 10.5,
                        padding: "1px 6px",
                        background: display.pillBg,
                        color: display.ink,
                        borderRadius: 3,
                        fontWeight: 600,
                        letterSpacing: "0.04em",
                      }}>{display.v}</span>
                    ) : cellValue}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// Variances sheet rows — formatted
function buildVarianceRows() {
  return VARI_ROWS.map((v, i) => [
    v.inv,
    { v: v.invAmt, money: true },
    v.poId,
    { v: v.poAmt, money: true },
    { v: v.variance, money: true, ink: v.variance > 0 ? xlTheme.varianceRed : xlTheme.cellInk2, b: v.variance > 0 },
    v.variance === 0
      ? { v: "auto-approved", pill: true, pillBg: xlTheme.okPill,        ink: "#3a5a43" }
      : { v: "review",         pill: true, pillBg: xlTheme.variancePill,  ink: "#7d5512" },
  ]);
}

function buildApprovalRows() {
  return APPR_ROWS.map(r => [
    r[0],
    r[1],
    { v: r[2], money: true, ink: r[2] > 0 ? xlTheme.varianceRed : xlTheme.cellInk2, b: r[2] > 0 },
    r[3] === "auto-approved"
      ? { v: "auto-approved", pill: true, pillBg: xlTheme.okPill,       ink: "#3a5a43" }
      : { v: "review",         pill: true, pillBg: xlTheme.variancePill, ink: "#7d5512" },
    r[4],
    r[5],
  ]);
}

function SummarySheet({ selected, onPick }) {
  // Build a 26-row layout addressed by A..E columns
  const rowCount = 27;
  const cols = ["A", "B", "C", "D", "E"];
  return (
    <table style={{
      borderCollapse: "separate",
      borderSpacing: 0,
      width: "100%",
      fontSize: 12,
      fontFamily: '"Inter", system-ui, sans-serif',
      color: xlTheme.cellInk,
      tableLayout: "fixed",
    }}>
      <colgroup>
        <col style={{ width: 36 }} />
        <col style={{ width: 260 }} />
        <col style={{ width: 140 }} />
        <col style={{ width: 140 }} />
        <col style={{ width: 140 }} />
        <col style={{ width: 140 }} />
      </colgroup>
      <thead>
        <tr>
          <th style={{ background: xlTheme.sheetHeader, borderRight: "1px solid " + xlTheme.sheetGrid, borderBottom: "1px solid " + xlTheme.sheetGrid, height: 22 }} />
          {cols.map(c => (
            <th key={c} style={{
              background: xlTheme.sheetHeader,
              borderRight: "1px solid " + xlTheme.sheetGrid,
              borderBottom: "1px solid " + xlTheme.sheetGrid,
              padding: "2px 0",
              textAlign: "center", fontSize: 11,
              color: xlTheme.cellInk2, fontWeight: 500, height: 22,
            }}>{c}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {Array.from({ length: rowCount }, (_, r) => {
          const excelRow = r + 1;
          return (
            <tr key={r}>
              <td style={{
                background: xlTheme.sheetHeader,
                borderRight: "1px solid " + xlTheme.sheetGrid,
                borderBottom: "1px solid " + xlTheme.sheetGrid,
                padding: "5px 4px",
                textAlign: "right", fontSize: 11,
                color: xlTheme.cellInk2, fontWeight: 500,
              }}>{excelRow}</td>
              {cols.map((c, ci) => {
                const key = c + excelRow;
                const cell = SUMMARY_CELLS[key];
                const isSel = selected.row === excelRow && selected.col === ci;
                const f = cell?.f || null;
                let v = cell?.v;
                if (cell?.money && typeof v === "number") v = fmtMoney(v);
                // Handle span (title row)
                if (cell?.span) {
                  return (
                    <td key={c} colSpan={cell.span}
                      onClick={() => onPick({ row: excelRow, col: ci, formula: f, value: cell.v })}
                      style={{
                        borderRight: "1px solid " + xlTheme.sheetGrid,
                        borderBottom: "1px solid " + xlTheme.sheetGrid,
                        padding: "8px 12px",
                        background: isSel ? xlTheme.sheetSelected : "white",
                        color: cell.ink || xlTheme.cellInk,
                        fontWeight: cell.b ? 700 : 400,
                        fontSize: cell.size || 12,
                        outline: isSel ? "2px solid " + xlTheme.sheetSelectedBorder : "none",
                        outlineOffset: "-2px",
                        cursor: "cell",
                      }}>{cell.v}</td>
                  );
                }
                // Skip rendering columns covered by previous span
                const prevSpan = cols.slice(0, ci).find(pc => {
                  const cc = SUMMARY_CELLS[pc + excelRow];
                  return cc && cc.span && cols.indexOf(pc) + cc.span > ci;
                });
                if (prevSpan) return null;
                return (
                  <td key={c}
                    onClick={() => onPick({ row: excelRow, col: ci, formula: f, value: cell?.v })}
                    style={{
                      borderRight: "1px solid " + xlTheme.sheetGrid,
                      borderBottom: "1px solid " + xlTheme.sheetGrid,
                      padding: "5px 8px",
                      background: isSel ? xlTheme.sheetSelected : "white",
                      color: cell?.ink || xlTheme.cellInk,
                      fontWeight: cell?.b ? 600 : 400,
                      textAlign: cell?.money || typeof cell?.v === "number" ? "right" : "left",
                      fontVariantNumeric: "tabular-nums",
                      outline: isSel ? "2px solid " + xlTheme.sheetSelectedBorder : "none",
                      outlineOffset: "-2px",
                      cursor: "cell",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      fontSize: cell?.size || 12,
                    }}>{v ?? ""}</td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// ─── Main component ───────────────────────────────────────────────────────
function WorkbookPreview() {
  const [sheet, setSheet] = React.useState("Summary");
  const [selected, setSelected] = React.useState({ sheet: "Summary", row: 10, col: 1, formula: "=COUNTIF(Approvals!D2:D801,\"auto-approved\")", value: 753 });

  const pick = (newSel) => {
    setSelected({ ...newSel, sheet });
  };

  // When switching sheets, reset selection to a meaningful default
  const switchSheet = (name) => {
    setSheet(name);
    const defaults = {
      Invoices:  { row: 2, col: 3, formula: null, value: INV_ROWS[0][3] },
      POs:       { row: 2, col: 2, formula: null, value: PO_ROWS[0][2] },
      Variances: { row: 2, col: 4, formula: "=B2-D2", value: 0 },
      Approvals: { row: 2, col: 3, formula: "=Variances!F2", value: "auto-approved" },
      Summary:   { row: 10, col: 1, formula: "=COUNTIF(Approvals!D2:D801,\"auto-approved\")", value: 753 },
    };
    setSelected({ sheet: name, ...defaults[name] });
  };

  const selRef = colLetter(selected.col) + selected.row;
  const formulaShown = selected.formula || (selected.value != null ? String(selected.value) : "");

  // Build display rows for each sheet
  const invDisplay = INV_ROWS.map(r => [r[0], r[1], r[2], { v: r[3], money: true }, r[4]]);
  const poDisplay = PO_ROWS.map(r => [r[0], r[1], { v: r[2], money: true }, r[3]]);
  const varDisplay = buildVarianceRows();
  const apprDisplay = buildApprovalRows();

  return (
    <div style={{
      background: xlTheme.bg,
      color: xlTheme.ink,
      borderRadius: 14,
      padding: "0",
      boxShadow: "0 30px 60px -25px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.05)",
      maxWidth: 860,
      fontFamily: '"Inter", system-ui, sans-serif',
      overflow: "hidden",
    }}>
      {/* Window chrome */}
      <div style={{
        padding: "14px 20px",
        background: xlTheme.chrome,
        borderBottom: "1px solid " + xlTheme.border,
        display: "flex", alignItems: "center", gap: 14,
      }}>
        <div style={{
          width: 26, height: 26, background: "#137333",
          color: "white", borderRadius: 4,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontWeight: 700, fontSize: 13,
        }}>X</div>
        <div>
          <div style={{ fontSize: 13, color: xlTheme.ink, fontWeight: 500 }}>
            invoice-approval.xlsx
            <span style={{ marginLeft: 10, fontSize: 11, color: xlTheme.ink3, fontWeight: 400 }}>· auto-saved</span>
          </div>
          <div style={{ fontSize: 11, color: xlTheme.ink3, marginTop: 1 }}>5 sheets · 1,847 formulas · 800 rows · generated by ForgeAI</div>
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 11, color: xlTheme.ink3 }}>shared with: A. Soumare (CFO), 4 approvers</div>
      </div>

      {/* Formula bar */}
      <div style={{
        display: "flex", alignItems: "stretch",
        background: "#fafaf7",
        borderBottom: "1px solid " + xlTheme.sheetGrid,
        fontFamily: '"Inter", system-ui, sans-serif',
      }}>
        <div style={{
          width: 60,
          background: xlTheme.sheetHeader,
          borderRight: "1px solid " + xlTheme.sheetGrid,
          fontSize: 11.5,
          color: xlTheme.cellInk2,
          padding: "6px 10px",
          fontWeight: 600,
          letterSpacing: "0.02em",
        }}>{selRef}</div>
        <div style={{
          width: 36,
          background: xlTheme.sheetHeader,
          borderRight: "1px solid " + xlTheme.sheetGrid,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 12, color: xlTheme.formulaBlue,
          fontStyle: "italic",
          fontFamily: '"JetBrains Mono", monospace',
        }}>fx</div>
        <div style={{
          flex: 1,
          padding: "6px 12px",
          fontSize: 12.5,
          color: selected.formula ? xlTheme.formulaBlue : xlTheme.cellInk,
          fontFamily: selected.formula ? '"JetBrains Mono", monospace' : '"Inter", sans-serif',
          background: "white",
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}>{formulaShown}</div>
      </div>

      {/* Sheet body */}
      <div style={{
        background: "white",
        maxHeight: 380,
        overflow: "auto",
      }}>
        {sheet === "Invoices" && (
          <SheetGrid
            sheetName="Invoices"
            headers={INV_HEADERS}
            rows={invDisplay}
            formulaFor={null}
            selected={selected}
            onPick={pick}
            colWidths={[120, 220, 100, 110, 100]}
          />
        )}
        {sheet === "POs" && (
          <SheetGrid
            sheetName="POs"
            headers={PO_HEADERS}
            rows={poDisplay}
            formulaFor={null}
            selected={selected}
            onPick={pick}
            colWidths={[100, 240, 130, 120]}
          />
        )}
        {sheet === "Variances" && (
          <SheetGrid
            sheetName="Variances"
            headers={VARI_HEADERS}
            rows={varDisplay}
            formulaFor={variancesFormula}
            selected={selected}
            onPick={pick}
            colWidths={[120, 100, 100, 100, 110, 130]}
          />
        )}
        {sheet === "Approvals" && (
          <SheetGrid
            sheetName="Approvals"
            headers={APPR_HEADERS}
            rows={apprDisplay}
            formulaFor={approvalsFormula}
            selected={selected}
            onPick={pick}
            colWidths={[120, 200, 110, 130, 110, 140]}
          />
        )}
        {sheet === "Summary" && <SummarySheet selected={selected} onPick={pick} />}
      </div>

      {/* Sheet tabs */}
      <div style={{
        display: "flex",
        background: xlTheme.chrome,
        borderTop: "1px solid " + xlTheme.border,
        padding: "6px 12px",
        gap: 0,
        alignItems: "center",
      }}>
        {XL_SHEETS.map(s => {
          const active = s === sheet;
          return (
            <button key={s} onClick={() => switchSheet(s)} style={{
              padding: "6px 14px",
              fontSize: 11.5,
              color: active ? xlTheme.ink : xlTheme.ink3,
              background: active ? "#2e2b27" : "transparent",
              borderTop: active ? "2px solid " + xlTheme.amber : "2px solid transparent",
              borderRadius: 0,
              cursor: "pointer",
              fontWeight: active ? 600 : 400,
              letterSpacing: "0.02em",
            }}>{s}</button>
          );
        })}
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 10.5, color: xlTheme.ink3 }}>cell {selRef} · click any cell for its formula</div>
      </div>
    </div>
  );
}

window.WorkbookPreview = WorkbookPreview;
