← Demos
Web Pages · Templates

Spreadsheet

by Shane Hadden Aug 3, 2026 8 views 186.2 KB
Sandbox · generic-spreadsheet · no access to your account
View source — the whole page is this one file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><rect x='1' y='1' width='14' height='14' rx='2' fill='%23ffffff' stroke='%230e6a55' stroke-width='1.4'/><path d='M1 6h14M1 11h14M6 1v14M11 1v14' stroke='%23bcd9cf' stroke-width='1'/></svg>">
<title>Spreadsheet</title>
<style>
:root{
  --ink:#1b2027;
  --ink-2:#4a5560;
  --ink-3:#7b8794;
  --paper:#ffffff;
  --chrome:#f2f3f0;
  --chrome-2:#e7e9e4;
  --line:#d8dbd4;
  --grid:#e4e6e1;
  --accent:#0e6a55;
  --accent-soft:#e2f1ec;
  --accent-ring:rgba(14,106,85,.30);
  --amber:#b26a00;
  --danger:#a52626;
  --hdr:#eceee9;
  --hdr-active:#cfe4dc;
  --shadow:0 6px 24px rgba(27,32,39,.14),0 1px 2px rgba(27,32,39,.10);
  --ui:"Segoe UI",Inter,-apple-system,BlinkMacSystemFont,Roboto,Helvetica,Arial,sans-serif;
  --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace;
  --hh:24px; --rw:46px;
}
*{box-sizing:border-box}
html,body{height:100%;margin:0}
body{
  font-family:var(--ui); font-size:13px; color:var(--ink);
  background:var(--chrome); overflow:hidden;
  -webkit-font-smoothing:antialiased;
}
button,select,input{font-family:inherit;font-size:inherit;color:inherit}
#app{display:flex;flex-direction:column;height:100%}

/* ---------- top chrome ---------- */
.bar{display:flex;align-items:center;gap:2px;padding:4px 6px;background:var(--chrome);border-bottom:1px solid var(--line);flex-wrap:wrap}
.brand{display:flex;align-items:center;padding:0 12px 0 4px;margin-right:4px;
  border-right:1px solid var(--line);align-self:stretch;flex-shrink:0}
.brand-word{font-size:15px;font-weight:600;letter-spacing:-.1px;line-height:1;
  white-space:nowrap;color:var(--ink)}
.grp{display:flex;align-items:center;gap:2px;padding:0 5px;border-right:1px solid var(--chrome-2)}
.grp:last-child{border-right:0}
.tb{
  height:26px;min-width:26px;padding:0 6px;border:1px solid transparent;border-radius:4px;
  background:transparent;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:5px;
  white-space:nowrap;line-height:1;
}
.tb:hover{background:#fff;border-color:var(--line)}
.tb:active{background:var(--chrome-2)}
.tb.on{background:var(--accent-soft);border-color:#bcd9cf;color:var(--accent)}
.tb[disabled]{opacity:.35;cursor:default;background:transparent;border-color:transparent}
.tb svg{width:15px;height:15px;display:block}
.tb .lbl{font-size:12px}
.tb.tx{font-size:14px;font-weight:700}
.selwrap{position:relative;display:inline-flex;align-items:center}
.selwrap::after{content:"";position:absolute;right:6px;top:calc(50% - 2px);border:3px solid transparent;border-top-color:var(--ink-2);pointer-events:none}
.selwrap select{height:26px;border:1px solid transparent;border-radius:4px;background:transparent;padding:0 18px 0 6px;cursor:pointer;-webkit-appearance:none;appearance:none}
.selwrap select:hover{background:#fff;border-color:var(--line)}
.swatch{width:14px;height:14px;border-radius:3px;border:1px solid rgba(0,0,0,.18);display:block}
.colorbtn{flex-direction:column;gap:1px;padding:0 5px}
.colorbtn .cap{font-size:11px;font-weight:700;line-height:9px}

/* ---------- formula bar ---------- */
.fbar{display:flex;align-items:stretch;background:var(--paper);border-bottom:1px solid var(--line);height:28px}
#namebox{
  width:104px;flex:0 0 104px;border:0;border-right:1px solid var(--line);padding:0 8px;
  font-family:var(--mono);font-size:12px;background:var(--paper);outline:none;
}
#namebox:focus{box-shadow:inset 0 0 0 2px var(--accent-ring)}
.fx{width:30px;flex:0 0 30px;display:flex;align-items:center;justify-content:center;border-right:1px solid var(--line);
    font-style:italic;font-family:var(--mono);color:var(--ink-2);cursor:pointer;user-select:none}
.fx:hover{background:var(--chrome)}
#fbin{flex:1;border:0;padding:0 10px;font-family:var(--mono);font-size:12.5px;outline:none;background:var(--paper)}
#fbin:focus{box-shadow:inset 0 0 0 2px var(--accent-ring)}

/* ---------- grid ---------- */
#grid{position:relative;flex:1;overflow:hidden;background:var(--paper);user-select:none}
#corner{position:absolute;left:0;top:0;width:var(--rw);height:var(--hh);background:var(--hdr);
  border-right:1px solid var(--line);border-bottom:1px solid var(--line);z-index:6;cursor:pointer}
#corner::after{content:"";position:absolute;right:3px;bottom:3px;border:5px solid transparent;border-bottom-color:var(--ink-3);border-right-color:var(--ink-3)}
#hcols{position:absolute;left:var(--rw);top:0;right:0;height:var(--hh);overflow:hidden;background:var(--hdr);border-bottom:1px solid var(--line);z-index:5}
#hrows{position:absolute;left:0;top:var(--hh);width:var(--rw);bottom:0;overflow:hidden;background:var(--hdr);border-right:1px solid var(--line);z-index:5}
#vp{position:absolute;left:var(--rw);top:var(--hh);right:0;bottom:0;overflow:auto;outline:none}
#sizer{position:relative}
#layer{position:absolute;left:0;top:0}
.hc,.hr{position:absolute;font-size:11px;color:var(--ink-2);display:flex;align-items:center;justify-content:center;
  background:var(--hdr);overflow:hidden;letter-spacing:.02em}
.hc{border-right:1px solid var(--line);height:var(--hh);top:0}
.hr{border-bottom:1px solid var(--line);left:0;width:var(--rw);font-variant-numeric:tabular-nums}
.hc.sel,.hr.sel{background:var(--hdr-active);color:var(--accent);font-weight:600}
.hc.full,.hr.full{background:var(--accent);color:#fff}
.hgrip{position:absolute;z-index:2}
.hgrip.c{top:0;height:var(--hh);width:6px;cursor:col-resize}
.hgrip.r{left:0;width:var(--rw);height:6px;cursor:row-resize}
.cell{position:absolute;overflow:hidden;white-space:pre;padding:0 4px;line-height:1.25;
  border-right:1px solid var(--grid);border-bottom:1px solid var(--grid);background:var(--paper);
  display:flex;align-items:flex-end;font-variant-numeric:tabular-nums}
.cell.wrap{white-space:pre-wrap;word-break:break-word}
.cell.err{color:var(--danger)}
#selbox{position:absolute;border:1.5px solid var(--accent);background:rgba(14,106,85,.07);pointer-events:none;z-index:20}
#activebox{position:absolute;border:2px solid var(--accent);pointer-events:none;z-index:21;background:transparent}
#fillh{position:absolute;width:7px;height:7px;background:var(--accent);border:1px solid #fff;z-index:23;cursor:crosshair}
#vp.painting,#vp.painting .cell{cursor:url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%3E%3Cpath%20d='M19.5%203.6c.6.6.6%201.5%200%202.1l-6.4%206.4-2.1-2.1%206.4-6.4c.6-.6%201.5-.6%202.1%200z'%20fill='%234a5560'/%3E%3Cpath%20d='M9.6%2010.9l2.1%202.1-.8%201.2c-1.1%201.7-3.4%202.2-5.1%201.1%201.4-.2%201.7-1.1%201.9-2.1.2-1.2.8-1.9%201.9-2.3z'%20fill='%230e6a55'/%3E%3C/svg%3E") 4 18,copy}
#fillbox{position:absolute;border:1.5px dashed var(--ink-2);pointer-events:none;z-index:22;display:none}
#cutbox{position:absolute;border:1.5px dashed var(--accent);pointer-events:none;z-index:19;display:none}
#editor{position:absolute;z-index:30;display:none;border:2px solid var(--accent);background:#fff;
  padding:0 3px;font-family:var(--ui);resize:none;outline:none;overflow:hidden;line-height:1.25;box-shadow:var(--shadow)}

/* ---------- tabs + status ---------- */
.tabs{display:flex;align-items:center;gap:3px;padding:3px 6px;background:var(--chrome);border-top:1px solid var(--line);overflow-x:auto}
.tab{height:24px;padding:0 12px;border:1px solid transparent;border-radius:4px 4px 0 0;background:transparent;cursor:pointer;
  white-space:nowrap;display:inline-flex;align-items:center;gap:6px;font-size:12px}
.tab:hover{background:#fff}
.tab.on{background:var(--paper);border-color:var(--line);border-bottom-color:var(--paper);font-weight:600;
  box-shadow:inset 0 2px 0 var(--accent)}
.tab .dot{width:6px;height:6px;border-radius:50%;background:var(--accent);opacity:0}
.tab.on .dot{opacity:0}
.status{display:flex;align-items:center;gap:16px;padding:3px 10px;background:var(--chrome);border-top:1px solid var(--line);
  font-size:11.5px;color:var(--ink-2);min-height:24px}
.status .st{font-variant-numeric:tabular-nums}
.status .sp{flex:1}
.status b{font-weight:600;color:var(--ink)}

/* ---------- menus / dialogs ---------- */
.menu{position:fixed;z-index:200;background:var(--paper);border:1px solid var(--line);border-radius:6px;box-shadow:var(--shadow);
  padding:4px;min-width:190px;display:none}
.menu button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:16px;background:transparent;border:0;
  padding:6px 9px;border-radius:4px;cursor:pointer;text-align:left}
.menu button:hover{background:var(--accent-soft)}
.menu button kbd{font-family:var(--mono);font-size:10.5px;color:var(--ink-3)}
.menu hr{border:0;border-top:1px solid var(--chrome-2);margin:4px 2px}
.pal{display:grid;grid-template-columns:repeat(10,18px);gap:3px;padding:7px}
.pal i{width:18px;height:18px;border-radius:3px;border:1px solid rgba(0,0,0,.15);cursor:pointer;display:block}
.pal i:hover{outline:2px solid var(--accent);outline-offset:1px}
.scrim{position:fixed;inset:0;background:rgba(27,32,39,.32);z-index:300;display:none;align-items:center;justify-content:center}
.dlg{background:var(--paper);border-radius:10px;box-shadow:var(--shadow);width:min(560px,92vw);max-height:82vh;display:flex;flex-direction:column}
.dlg h2{margin:0;padding:14px 18px;font-size:14px;border-bottom:1px solid var(--chrome-2);letter-spacing:-.1px}
.dlg .body{padding:14px 18px;overflow:auto}
.dlg .foot{padding:11px 18px;border-top:1px solid var(--chrome-2);display:flex;gap:8px;justify-content:flex-end}
.field{display:flex;align-items:center;gap:10px;margin-bottom:10px}
.field label{width:96px;color:var(--ink-2);flex:0 0 96px}
.field input[type=text],.field select{flex:1;height:28px;border:1px solid var(--line);border-radius:5px;padding:0 8px;background:#fff}
.field input[type=text]:focus,.field select:focus{outline:2px solid var(--accent-ring);border-color:var(--accent)}
.btn{height:28px;padding:0 14px;border:1px solid var(--line);border-radius:5px;background:#fff;cursor:pointer}
.btn:hover{background:var(--chrome)}
.btn.pri{background:var(--accent);border-color:var(--accent);color:#fff}
.btn.pri:hover{background:#0b543f}
#fnlist{font-family:var(--mono);font-size:12px;line-height:1.9}
#fnlist b{display:inline-block;min-width:132px;color:var(--accent)}
.chartobj{position:absolute;background:#fff;border:1px solid var(--line);border-radius:6px;
  box-shadow:0 2px 10px rgba(27,32,39,.12);overflow:hidden;z-index:16}
.chartobj.sel{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-ring),0 2px 10px rgba(27,32,39,.16)}
.chartobj .chead{height:20px;display:flex;align-items:center;justify-content:flex-end;gap:2px;
  background:transparent;position:absolute;top:0;right:0;left:0;cursor:move;z-index:2}
.chartobj .cbtn{width:18px;height:18px;margin-top:1px;border:0;background:rgba(255,255,255,.7);border-radius:3px;
  cursor:pointer;color:var(--ink-2);font-size:12px;line-height:1;display:none;align-items:center;justify-content:center}
.chartobj:hover .cbtn{display:flex}
.chartobj .cbtn:hover{background:#fff;color:var(--accent)}
.chartobj svg{display:block;width:100%;height:100%}
.chartobj .cresize{position:absolute;right:0;bottom:0;width:14px;height:14px;cursor:nwse-resize;z-index:3}
.chartobj .cresize::after{content:"";position:absolute;right:2px;bottom:2px;width:7px;height:7px;
  border-right:2px solid var(--ink-3);border-bottom:2px solid var(--ink-3)}
.cell.lnk{color:var(--accent);text-decoration:underline;cursor:pointer}
.cell .noteflag{position:absolute;top:0;right:0;width:0;height:0;
  border-top:6px solid var(--danger);border-left:6px solid transparent;pointer-events:none}
#notetip{position:fixed;z-index:260;max-width:240px;background:#fffbe6;border:1px solid #e6d27a;
  color:#5b4b13;font-size:12px;line-height:1.4;padding:6px 9px;border-radius:5px;box-shadow:var(--shadow);
  display:none;white-space:pre-wrap;pointer-events:none}
#printarea{display:none}
@media print{
  body{overflow:visible!important}
  #app,.menu,.fpop,#notetip,.toast{display:none!important}
  #printarea{display:block!important;position:static!important}
  #printarea table{border-collapse:collapse;font:12px/1.35 Arial,sans-serif}
  #printarea td{border:1px solid #bbb;padding:3px 6px}
  #printarea h3{font:600 15px Arial,sans-serif;margin:0 0 8px}
}
.filter-arrow{position:absolute;z-index:14;width:15px;height:15px;border-radius:3px;
  background:var(--hdr);border:1px solid var(--line);display:flex;align-items:center;justify-content:center;
  cursor:pointer;color:var(--ink-2);box-shadow:0 1px 2px rgba(27,32,39,.12)}
.filter-arrow:hover{background:#fff;color:var(--accent)}
.filter-arrow.on{background:var(--accent);border-color:var(--accent);color:#fff}
.filter-arrow svg{width:9px;height:9px;display:block}
.fpop{position:fixed;z-index:250;background:var(--paper);border:1px solid var(--line);border-radius:8px;
  box-shadow:var(--shadow);width:250px;display:none;flex-direction:column;overflow:hidden}
.fpop .fsort{display:flex;flex-direction:column;padding:5px}
.fpop .fsort button{display:flex;align-items:center;gap:8px;background:transparent;border:0;padding:6px 8px;
  border-radius:5px;cursor:pointer;text-align:left;font-size:12.5px;color:var(--ink)}
.fpop .fsort button:hover{background:var(--accent-soft)}
.fpop hr{border:0;border-top:1px solid var(--chrome-2);margin:2px 0}
.fpop .fsearch{padding:6px 8px}
.fpop .fsearch input{width:100%;height:26px;border:1px solid var(--line);border-radius:5px;padding:0 8px;font-size:12px}
.fpop .fsearch input:focus{outline:2px solid var(--accent-ring);border-color:var(--accent)}
.fpop .flist{max-height:210px;overflow:auto;padding:2px 4px 4px;border-top:1px solid var(--chrome-2)}
.fpop .fitem{display:flex;align-items:center;gap:7px;padding:4px 6px;border-radius:4px;cursor:pointer;font-size:12.5px}
.fpop .fitem:hover{background:var(--chrome)}
.fpop .fitem input{margin:0;flex:0 0 auto}
.fpop .fitem span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fpop .fitem.all{font-weight:600;border-bottom:1px solid var(--chrome-2);border-radius:0;margin-bottom:2px}
.fpop .fitem .muted{color:var(--ink-3);font-style:italic}
.fpop .ffoot{display:flex;gap:7px;justify-content:flex-end;padding:8px;border-top:1px solid var(--chrome-2)}
.fpop .ffoot .lft{margin-right:auto}
.toast{position:fixed;left:50%;bottom:52px;transform:translateX(-50%) translateY(10px);background:var(--ink);color:#fff;
  padding:8px 16px;border-radius:6px;font-size:12px;z-index:400;opacity:0;pointer-events:none;transition:.18s}
.toast.on{opacity:1;transform:translateX(-50%)}
::-webkit-scrollbar{width:13px;height:13px}
::-webkit-scrollbar-thumb{background:#c3c8bf;border:3px solid var(--chrome);border-radius:7px}
::-webkit-scrollbar-thumb:hover{background:#a9b0a5}
::-webkit-scrollbar-track{background:var(--chrome)}
:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
</style>
</head>
<body>
<div id="app">

  <div class="bar">
    <div class="brand"><span class="brand-word">Spreadsheet</span></div>

    <div class="grp">
      <button class="tb" id="btnNew" title="New workbook"><span class="lbl">New</span></button>
      <button class="tb" id="btnOpen" title="Open .json or .csv"><span class="lbl">Open</span></button>
      <div class="selwrap"><select id="selSave" title="Save"><option value="">Save…</option><option value="json">Workbook — reopen later (.json)</option><option value="csv">This sheet — data only (.csv)</option></select></div>
      <button class="tb" id="btnPrint" title="Print this sheet (Ctrl+P)"><span class="lbl">Print</span></button>
    </div>

    <div class="grp">
      <button class="tb" id="btnUndo" title="Undo (Ctrl+Z)">&#8630;</button>
      <button class="tb" id="btnRedo" title="Redo (Ctrl+Y)">&#8631;</button>
    </div>

    <div class="grp">
      <div class="selwrap"><select id="selFont" title="Font"></select></div>
      <div class="selwrap"><select id="selSize" title="Font size"></select></div>
    </div>

    <div class="grp">
      <button class="tb tx" id="btnB" title="Bold (Ctrl+B)" style="font-weight:800">B</button>
      <button class="tb tx" id="btnI" title="Italic (Ctrl+I)" style="font-style:italic;font-weight:500">I</button>
      <button class="tb tx" id="btnU" title="Underline (Ctrl+U)" style="text-decoration:underline;font-weight:500">U</button>
      <button class="tb tx" id="btnS" title="Strikethrough" style="text-decoration:line-through;font-weight:500">S</button>
      <button class="tb colorbtn" id="btnColor" title="Text colour"><span class="cap">A</span><span class="swatch" id="swColor" style="background:#1b2027"></span></button>
      <button class="tb colorbtn" id="btnFill" title="Fill colour"><span class="cap">&#9608;</span><span class="swatch" id="swFill" style="background:#ffe680"></span></button>
      <button class="tb" id="btnBorder" title="Borders">&#9635;</button>
      <button class="tb" id="btnPaint" title="Format painter — click to copy formatting once, double-click to keep painting (Esc to stop)"><svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2.6c.5.5.5 1.2 0 1.7L8.4 8.9 7.1 7.6 11.3 2.6c.5-.5 1.2-.5 1.7 0z" fill="#4a5560"/><path d="M6.6 8.1l1.3 1.3-.5.8c-.7 1.1-2 1.6-3.2.9.9-.2 1-.9 1.1-1.6.1-.8.5-1.2 1.3-1.4z" fill="#0e6a55"/></svg></button>
    </div>

    <div class="grp">
      <button class="tb" id="btnAL" title="Align left"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2 4h12"/><path d="M2 7.5h7"/><path d="M2 11h10"/><path d="M2 14.5h5"/></svg></button>
      <button class="tb" id="btnAC" title="Align centre"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2 4h12"/><path d="M4.5 7.5h7"/><path d="M3 11h10"/><path d="M5.5 14.5h5"/></svg></button>
      <button class="tb" id="btnAR" title="Align right"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2 4h12"/><path d="M7 7.5h7"/><path d="M4 11h10"/><path d="M9 14.5h5"/></svg></button>
      <button class="tb" id="btnVT" title="Align top"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2.5 2.5h11"/><path d="M8 5.5v8"/><path d="M5.5 10.5L8 13.5l2.5-3"/></svg></button>
      <button class="tb" id="btnVM" title="Align middle"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2.5 8h11"/><path d="M8 2v3.5"/><path d="M8 10.5V14"/></svg></button>
      <button class="tb" id="btnVB" title="Align bottom"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2.5 13.5h11"/><path d="M8 2.5v8"/><path d="M5.5 7.5L8 10.5l2.5-3"/></svg></button>
      <button class="tb" id="btnWrap" title="Wrap text"><span class="lbl">Wrap</span></button>
      <button class="tb" id="btnMerge" title="Merge cells"><span class="lbl">Merge</span></button>
    </div>

    <div class="grp">
      <div class="selwrap"><select id="selFmt" title="Number format">
        <option value="general">General</option>
        <option value="number">Number</option>
        <option value="comma">Comma</option>
        <option value="currency">Currency</option>
        <option value="accounting">Accounting</option>
        <option value="percent">Percent</option>
        <option value="fraction">Fraction</option>
        <option value="sci">Scientific</option>
        <option value="date">Date</option>
        <option value="time">Time</option>
        <option value="datetime">Date &amp; time</option>
        <option value="duration">Duration</option>
        <option value="text">Text</option>
      </select></div>
      <button class="tb" id="btnDec+" title="More decimal places">.0&#8594;</button>
      <button class="tb" id="btnDec-" title="Fewer decimal places">&#8592;.0</button>
    </div>

    <div class="grp">
      <button class="tb" id="btnInsRow" title="Insert row above"><span class="lbl">+Row</span></button>
      <button class="tb" id="btnInsCol" title="Insert column left"><span class="lbl">+Col</span></button>
      <button class="tb" id="btnDelRow" title="Delete rows"><span class="lbl">&minus;Row</span></button>
      <button class="tb" id="btnDelCol" title="Delete columns"><span class="lbl">&minus;Col</span></button>
    </div>

    <div class="grp">
      <button class="tb tx" id="btnSum" title="AutoSum the numbers above or to the left" style="font-size:15px">&Sigma;</button>
      <button class="tb" id="btnFreeze" title="Freeze panes at selection"><span class="lbl">Freeze</span></button>
      <button class="tb" id="btnSortA" title="Sort selection A&rarr;Z">A&#8595;Z</button>
      <button class="tb" id="btnSortD" title="Sort selection Z&rarr;A">Z&#8595;A</button>
      <button class="tb" id="btnFilter" title="Toggle filter on the selected table"><span class="lbl">Filter</span></button>
      <button class="tb" id="btnCF" title="Conditional formatting for the selection"><span class="lbl">Rules</span></button>
      <button class="tb" id="btnChart" title="Insert a chart from the selection"><span class="lbl">Chart</span></button>
      <button class="tb" id="btnPivot" title="Create or edit a pivot table"><span class="lbl">Pivot</span></button>
      <button class="tb" id="btnFind" title="Find &amp; replace (Ctrl+F)"><span class="lbl">Find</span></button>
      <button class="tb" id="btnFns" title="Function reference"><span class="lbl">&fnof;x list</span></button>
    </div>
  </div>

  <div class="fbar">
    <input id="namebox" value="A1" spellcheck="false" aria-label="Name box">
    <div class="fx" id="fxbtn" title="Function reference">fx</div>
    <input id="fbin" spellcheck="false" autocomplete="off" aria-label="Formula bar">
  </div>

  <div id="grid">
    <div id="corner" title="Select all"></div>
    <div id="hcols"></div>
    <div id="hrows"></div>
    <div id="vp" tabindex="0">
      <div id="sizer">
        <div id="layer">
          <div id="cutbox"></div>
          <div id="selbox"></div>
          <div id="activebox"></div>
          <div id="fillbox"></div>
          <div id="fillh"></div>
          <textarea id="editor" spellcheck="false"></textarea>
        </div>
      </div>
    </div>
  </div>

  <div class="tabs" id="tabs"></div>

  <div class="status">
    <span class="st" id="stCell">A1</span>
    <span class="st" id="stAgg"></span>
    <span class="sp"></span>
    <span class="st" id="stMode"></span>
    <span class="st">Zoom</span>
    <div class="selwrap"><select id="selZoom" style="height:20px">
      <option>50%</option><option>75%</option><option>90%</option><option selected>100%</option><option>125%</option><option>150%</option><option>200%</option>
    </select></div>
  </div>
</div>

<div class="menu" id="ctx"></div>
<div class="menu" id="pal"><div class="pal" id="palGrid"></div></div>

<div class="scrim" id="scrim"><div class="dlg" id="dlg">
  <h2 id="dlgTitle">Dialog</h2>
  <div class="body" id="dlgBody"></div>
  <div class="foot" id="dlgFoot"></div>
</div></div>

<div class="toast" id="toast"></div>
<input type="file" id="fileIn" style="display:none" accept=".json,.csv,.txt,.tsv">
<script>
"use strict";
/* ============================================================
   Spreadsheet — a dependency-free spreadsheet engine
   Sections: 1 model  2 formulas  3 render  4 input  5 commands
   ============================================================ */

/* ---------- 1. MODEL ---------- */
const DEFW = 96, DEFH = 22, HH = 24, RW = 46;
const $ = id => document.getElementById(id);

function colName(c){ let s=''; c++; while(c>0){ const m=(c-1)%26; s=String.fromCharCode(65+m)+s; c=(c-m-1)/26; } return s; }
function colIndex(s){ let n=0; for(const ch of s.toUpperCase()) n=n*26+(ch.charCodeAt(0)-64); return n-1; }
function a1(r,c){ return colName(c)+(r+1); }
function esc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function clamp(v,a,b){ return v<a?a:v>b?b:v; }
function key(r,c){ return r+':'+c; }

function newSheet(name){
  return { name, cells:Object.create(null), colW:{}, rowH:{}, hiddenC:{}, hiddenR:{}, fhR:{},
           nRows:200, nCols:40, fzR:0, fzC:0, merges:[], filter:null, cf:[], charts:[], pivot:null };
}
let DOC = { sheets:[newSheet('Sheet1')], active:0, name:'Untitled workbook' };
const cur = () => DOC.sheets[DOC.active];
const cellAt = (S,r,c) => S.cells[key(r,c)];
function ensure(S,r,c){ const k=key(r,c); let x=S.cells[k]; if(!x){ x={v:'',s:null}; S.cells[k]=x; } return x; }

/* selection: r1/c1 anchor, r2/c2 focus (may be inverted) */
let sel = {r1:0,c1:0,r2:0,c2:0};
const selBox = () => ({ r1:Math.min(sel.r1,sel.r2), r2:Math.max(sel.r1,sel.r2),
                        c1:Math.min(sel.c1,sel.c2), c2:Math.max(sel.c1,sel.c2) });
let zoom = 1, editing = false, dirty = false;

/* ---------- geometry ---------- */
let colX=[0], rowY=[0];
const cwRaw = c => cur().hiddenC[c] ? 0 : (cur().colW[c]||DEFW);
const rhRaw = r => (cur().hiddenR[r]||cur().fhR[r]) ? 0 : (cur().rowH[r]||DEFH);
const cw = c => Math.round(cwRaw(c)*zoom);
const rh = r => Math.round(rhRaw(r)*zoom);
function geom(){
  const S=cur();
  colX=new Array(S.nCols+1); colX[0]=0;
  for(let c=0;c<S.nCols;c++) colX[c+1]=colX[c]+cw(c);
  rowY=new Array(S.nRows+1); rowY[0]=0;
  for(let r=0;r<S.nRows;r++) rowY[r+1]=rowY[r]+rh(r);
}
function idxAt(arr,pos,n){
  let lo=0,hi=n-1,best=0;
  while(lo<=hi){ const m=(lo+hi)>>1; if(arr[m]<=pos){best=m;lo=m+1;} else hi=m-1; }
  return best;
}

/* ---------- merges ---------- */
function mergeOf(S,r,c){
  for(const m of S.merges) if(r>=m.r1&&r<=m.r2&&c>=m.c1&&c<=m.c2) return m;
  return null;
}
function isCovered(S,r,c){ const m=mergeOf(S,r,c); return m && !(m.r1===r&&m.c1===c); }

/* ---------- date serials (Excel-compatible, 1900 system) ---------- */
const EPOCH = Date.UTC(1899,11,30);
const DAY = 86400000;
function serialToDate(n){ return new Date(EPOCH + Math.round(n*DAY)); }
function dateToSerial(d){
  return (Date.UTC(d.getFullYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds())-EPOCH)/DAY;
}
const MON=['January','February','March','April','May','June','July','August','September','October','November','December'];
const DOW=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

/* ---------- error values ---------- */
class Err{ constructor(e){ this.e=e; } toString(){ return this.e; } }
const ERR = {
  DIV:()=>new Err('#DIV/0!'), VAL:()=>new Err('#VALUE!'), REF:()=>new Err('#REF!'),
  NAME:()=>new Err('#NAME?'), NUM:()=>new Err('#NUM!'), NA:()=>new Err('#N/A'), CYC:()=>new Err('#CYCLE!')
};
const isErr = v => v instanceof Err;
/* ---------- 2. FORMULA ENGINE ---------- */

const RE_REF = /^(\$?)([A-Za-z]{1,3})(\$?)([0-9]{1,7})(?![A-Za-z0-9_.])/;
const RE_SHEET = /^((?:'(?:[^']|'')*')|(?:[A-Za-z_][A-Za-z0-9_.]*))!/;
const RE_IDENT = /^[A-Za-z_][A-Za-z0-9_.]*/;
const OPS3 = ['<=','>=','<>'];

function tokenize(s){
  const T=[]; let i=0;
  while(i<s.length){
    const st=i, ch=s[i];
    if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){ i++; T.push({t:'ws',src:s.slice(st,i)}); continue; }
    if(/[0-9]/.test(ch) || (ch==='.'&&/[0-9]/.test(s[i+1]||''))){
      let j=i; while(j<s.length&&/[0-9.]/.test(s[j])) j++;
      if(s[j]==='e'||s[j]==='E'){ let k=j+1; if(s[k]==='+'||s[k]==='-')k++; if(/[0-9]/.test(s[k]||'')){ j=k; while(j<s.length&&/[0-9]/.test(s[j]))j++; } }
      i=j; T.push({t:'num',v:parseFloat(s.slice(st,i)),src:s.slice(st,i)}); continue;
    }
    if(ch==='"'){
      let j=i+1,v='';
      while(j<s.length){ if(s[j]==='"'){ if(s[j+1]==='"'){v+='"';j+=2;} else {j++;break;} } else v+=s[j++]; }
      i=j; T.push({t:'str',v,src:s.slice(st,i)}); continue;
    }
    const rest = s.slice(i);
    const ms = RE_SHEET.exec(rest);
    if(ms){
      const after = RE_REF.exec(rest.slice(ms[0].length));
      if(after){
        let nm=ms[1];
        if(nm[0]==="'") nm=nm.slice(1,-1).replace(/''/g,"'");
        i += ms[0].length + after[0].length;
        T.push({t:'ref',sheet:nm,ca:after[1]==='$',c:colIndex(after[2]),ra:after[3]==='$',r:parseInt(after[4],10)-1,src:s.slice(st,i)});
        continue;
      }
    }
    const mr = RE_REF.exec(rest);
    if(mr){
      i += mr[0].length;
      T.push({t:'ref',sheet:null,ca:mr[1]==='$',c:colIndex(mr[2]),ra:mr[3]==='$',r:parseInt(mr[4],10)-1,src:s.slice(st,i)});
      continue;
    }
    const mi = RE_IDENT.exec(rest);
    if(mi){ i+=mi[0].length; T.push({t:'name',v:mi[0].toUpperCase(),src:mi[0]}); continue; }
    const three = s.substr(i,2);
    if(OPS3.includes(three)){ i+=2; T.push({t:'op',v:three,src:three}); continue; }
    if('+-*/^&%=<>'.includes(ch)){ i++; T.push({t:'op',v:ch,src:ch}); continue; }
    if(ch==='('){ i++; T.push({t:'(',src:ch}); continue; }
    if(ch===')'){ i++; T.push({t:')',src:ch}); continue; }
    if(ch===','||ch===';'){ i++; T.push({t:',',src:ch}); continue; }
    if(ch===':'){ i++; T.push({t:':',src:ch}); continue; }
    if(ch==='#'){ // error literal such as #REF!
      const me=/^#[A-Z0-9\/]+!?/.exec(rest); if(me){ i+=me[0].length; T.push({t:'err',v:me[0],src:me[0]}); continue; }
    }
    i++; T.push({t:'bad',src:ch});
  }
  return T;
}

const astCache = new Map();
function getAst(src){
  let a = astCache.get(src);
  if(a===undefined){ try{ a = parse(src); }catch(e){ a = {k:'err',v:'#NAME?'}; } astCache.set(src,a); if(astCache.size>4000) astCache.clear(); }
  return a;
}

function parse(src){
  const A = tokenize(src).filter(t=>t.t!=='ws');
  let p=0;
  const peek=()=>A[p], take=()=>A[p++];
  const isOp=v=>{ const t=A[p]; return t&&t.t==='op'&&(Array.isArray(v)?v.includes(t.v):t.v===v); };

  function expr(){ return cmp(); }
  function cmp(){ let l=cat(); while(isOp(['=','<>','<','>','<=','>='])){ const o=take().v; l={k:'bin',o,l,r:cat()}; } return l; }
  function cat(){ let l=add(); while(isOp('&')){ take(); l={k:'bin',o:'&',l,r:add()}; } return l; }
  function add(){ let l=mul(); while(isOp(['+','-'])){ const o=take().v; l={k:'bin',o,l,r:mul()}; } return l; }
  function mul(){ let l=pow(); while(isOp(['*','/'])){ const o=take().v; l={k:'bin',o,l,r:pow()}; } return l; }
  function pow(){ const b=un(); if(isOp('^')){ take(); return {k:'bin',o:'^',l:b,r:pow()}; } return b; }
  function un(){ if(isOp(['-','+'])){ const o=take().v; return {k:'un',o,a:un()}; } return pct(); }
  function pct(){ let a=prim(); while(isOp('%')){ take(); a={k:'pct',a}; } return a; }

  function prim(){
    const t=take();
    if(!t) throw new Err('#NAME?');
    if(t.t==='num') return {k:'num',v:t.v};
    if(t.t==='str') return {k:'str',v:t.v};
    if(t.t==='err') return {k:'err',v:t.v};
    if(t.t==='('){ const e=expr(); if(!peek()||peek().t!==')') throw new Err('#NAME?'); take(); return e; }
    if(t.t==='ref'){
      if(peek()&&peek().t===':'&&A[p+1]&&A[p+1].t==='ref'){ take(); const b=take(); return {k:'rng',a:t,b}; }
      return {k:'ref',t};
    }
    if(t.t==='name'){
      if(t.v==='TRUE') return {k:'bool',v:true};
      if(t.v==='FALSE') return {k:'bool',v:false};
      if(peek()&&peek().t==='('){
        take(); const args=[];
        if(peek()&&peek().t===')'){ take(); return {k:'fn',n:t.v,args}; }
        for(;;){
          if(peek()&&(peek().t===','||peek().t===')')) args.push({k:'blank'});
          else args.push(expr());
          const nx=take();
          if(!nx) throw new Err('#NAME?');
          if(nx.t===')') break;
          if(nx.t!==',') throw new Err('#NAME?');
        }
        return {k:'fn',n:t.v,args};
      }
      return {k:'name',v:t.v};
    }
    throw new Err('#NAME?');
  }
  const e = expr();
  return e;
}

/* ---------- value helpers ---------- */
function sheetIndexByName(nm){
  const n=String(nm).toLowerCase();
  for(let i=0;i<DOC.sheets.length;i++) if(DOC.sheets[i].name.toLowerCase()===n) return i;
  return -1;
}
function literal(cell){
  const raw = cell.v;
  if(raw===null||raw===undefined) return null;
  if(cell.s && cell.s.fmt && cell.s.fmt.t==='text') return String(raw);
  const t=String(raw).trim();
  if(t==='') return null;
  const up=t.toUpperCase();
  if(up==='TRUE') return true;
  if(up==='FALSE') return false;
  if(/^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t)) return parseFloat(t);
  if(/^#(DIV\/0|VALUE|REF|NAME|NUM|N\/A|CYCLE)[!?]?$/.test(up)) return new Err(up.endsWith('!')||up.endsWith('?')?up:up+'!');
  return String(raw);
}

const memo = new Map();
const stack = new Set();
function recalc(){ memo.clear(); }

function getVal(si,r,c){
  if(si<0||si>=DOC.sheets.length) return ERR.REF();
  const S=DOC.sheets[si];
  if(r<0||c<0||r>=1048576||c>=16384) return ERR.REF();
  const k=si+'|'+r+'|'+c;
  if(memo.has(k)) return memo.get(k);
  const cell=S.cells[key(r,c)];
  if(!cell || cell.v==='' || cell.v==null) return null;
  let out;
  const raw=String(cell.v);
  if(raw[0]==='='){
    if(stack.has(k)) return ERR.CYC();
    stack.add(k);
    try{ out = s1(evalNode(getAst(raw.slice(1)),{si,r,c})); }
    catch(e){ out = isErr(e)?e:ERR.VAL(); }
    finally{ stack.delete(k); }
    if(out===undefined) out=null;
  } else out = literal(cell);
  memo.set(k,out);
  return out;
}

const s1 = a => (a&&a.rng)? getVal(a.rng.si,a.rng.r1,a.rng.c1) : a;
function toNum(v){
  v=s1(v);
  if(v===null||v===undefined) return 0;
  if(isErr(v)) throw v;
  if(typeof v==='number') return v;
  if(typeof v==='boolean') return v?1:0;
  const t=String(v).trim();
  if(t==='') return 0;
  if(/^-?[\d,]*\.?\d+([eE][+-]?\d+)?%?$/.test(t)){
    const n=parseFloat(t.replace(/,/g,''));
    return t.endsWith('%')? n/100 : n;
  }
  const d=parseDateString(t);
  if(d!==null) return d;
  throw ERR.VAL();
}
function toStr(v){
  v=s1(v);
  if(v===null||v===undefined) return '';
  if(isErr(v)) throw v;
  if(typeof v==='boolean') return v?'TRUE':'FALSE';
  if(typeof v==='number') return genNum(v);
  return String(v);
}
function toBool(v){
  v=s1(v);
  if(v===null||v===undefined) return false;
  if(isErr(v)) throw v;
  if(typeof v==='boolean') return v;
  if(typeof v==='number') return v!==0;
  const t=String(v).trim().toUpperCase();
  if(t==='TRUE') return true;
  if(t==='FALSE'||t==='') return false;
  throw ERR.VAL();
}

function evalNode(n,ctx){
  switch(n.k){
    case 'num': return n.v;
    case 'str': return n.v;
    case 'bool': return n.v;
    case 'blank': return null;
    case 'err': return new Err(n.v);
    case 'name': throw ERR.NAME();
    case 'ref': {
      const si = n.t.sheet? sheetIndexByName(n.t.sheet) : ctx.si;
      if(si<0) throw ERR.REF();
      return getVal(si,n.t.r,n.t.c);
    }
    case 'rng': {
      const si = (n.a.sheet||n.b.sheet)? sheetIndexByName(n.a.sheet||n.b.sheet) : ctx.si;
      if(si<0) throw ERR.REF();
      return {rng:{si,r1:Math.min(n.a.r,n.b.r),r2:Math.max(n.a.r,n.b.r),c1:Math.min(n.a.c,n.b.c),c2:Math.max(n.a.c,n.b.c)}};
    }
    case 'pct': return toNum(evalNode(n.a,ctx))/100;
    case 'un': { const v=toNum(evalNode(n.a,ctx)); return n.o==='-'? -v : v; }
    case 'bin': {
      const o=n.o;
      if(o==='&') return toStr(evalNode(n.l,ctx))+toStr(evalNode(n.r,ctx));
      if('=<>'.includes(o[0])||o==='<>'||o==='<='||o==='>='){
        let a=s1(evalNode(n.l,ctx)), b=s1(evalNode(n.r,ctx));
        if(isErr(a)) throw a; if(isErr(b)) throw b;
        return compare(a,b,o);
      }
      const a=toNum(evalNode(n.l,ctx)), b=toNum(evalNode(n.r,ctx));
      switch(o){
        case '+':return a+b; case '-':return a-b; case '*':return a*b;
        case '/': if(b===0) throw ERR.DIV(); return a/b;
        case '^': { const v=Math.pow(a,b); if(!isFinite(v)) throw ERR.NUM(); return v; }
      }
      throw ERR.VAL();
    }
    case 'fn': {
      const d=FN[n.n];
      if(!d) throw ERR.NAME();
      if(d.lazy) return d.f(n.args,ctx,x=>evalNode(x,ctx));
      let args=n.args.map(x=>evalNode(x,ctx));
      if(!d.r) args=args.map(s1);
      for(const a of args) if(isErr(a) && !d.keepErr) throw a;
      return d.f(args,ctx);
    }
  }
  throw ERR.VAL();
}

function rank(v){ if(v===null) return 0; if(typeof v==='number') return 1; if(typeof v==='string') return 2; return 3; }
function compare(a,b,o){
  if(a===null&&typeof b==='number') a=0;
  if(b===null&&typeof a==='number') b=0;
  if(a===null&&typeof b==='string') a='';
  if(b===null&&typeof a==='string') b='';
  if(a===null&&b===null){ a=0;b=0; }
  let cmpv;
  if(typeof a==='string'&&typeof b==='string') cmpv = a.toUpperCase()<b.toUpperCase()?-1:(a.toUpperCase()>b.toUpperCase()?1:0);
  else if(rank(a)!==rank(b)) cmpv = rank(a)<rank(b)?-1:1;
  else cmpv = a<b?-1:(a>b?1:0);
  switch(o){ case '=':return cmpv===0; case '<>':return cmpv!==0; case '<':return cmpv<0;
             case '>':return cmpv>0; case '<=':return cmpv<=0; case '>=':return cmpv>=0; }
  return false;
}
/* ---------- 2b. FUNCTION LIBRARY ---------- */
function iterRange(rg,cb){
  for(let r=rg.r1;r<=rg.r2;r++) for(let c=rg.c1;c<=rg.c2;c++) cb(getVal(rg.si,r,c),r,c);
}
function flatVals(args){
  const o=[];
  for(const a of args){ if(a&&a.rng) iterRange(a.rng,v=>o.push(v)); else o.push(a); }
  return o;
}
function numsOf(args){
  const o=[];
  for(const a of args){
    if(a&&a.rng) iterRange(a.rng,v=>{ if(isErr(v)) throw v; if(typeof v==='number') o.push(v); });
    else { const v=a; if(v===null||v===undefined) continue; if(isErr(v)) throw v;
           if(typeof v==='boolean') o.push(v?1:0); else o.push(toNum(v)); }
  }
  return o;
}
const sum = a => a.reduce((x,y)=>x+y,0);
const avg = a => { if(!a.length) throw ERR.DIV(); return sum(a)/a.length; };
function variance(a,pop){ if(a.length<(pop?1:2)) throw ERR.DIV();
  const m=sum(a)/a.length; return sum(a.map(x=>(x-m)*(x-m)))/(a.length-(pop?0:1)); }
function rangeOf(a){ if(!a||!a.rng) throw ERR.REF(); return a.rng; }
function colOf(rg,i){ const o=[]; for(let r=rg.r1;r<=rg.r2;r++) o.push(getVal(rg.si,r,rg.c1+i)); return o; }

function makeCrit(cr){
  if(isErr(cr)) throw cr;
  let op='=', val=cr;
  if(typeof cr==='string'){
    const m=/^(<=|>=|<>|=|<|>)?([\s\S]*)$/.exec(cr.trim());
    op=m[1]||'='; val=m[2];
    if(val!=='' && /^-?[\d.]+%?$/.test(val.trim())) val = val.trim().endsWith('%')? parseFloat(val)/100 : parseFloat(val);
    else { const d=parseDateString(val); if(d!==null) val=d; }
  }
  const wild = typeof val==='string' && /[*?]/.test(val);
  let rx=null;
  if(wild) rx=new RegExp('^'+val.replace(/[.+^${}()|[\]\\]/g,'\\$&').replace(/\*/g,'[\\s\\S]*').replace(/\?/g,'[\\s\\S]')+'$','i');
  return v=>{
    if(rx&&(op==='='||op==='<>')){ const hit=rx.test(v==null?'':String(v)); return op==='='?hit:!hit; }
    let a=v,b=val;
    if(a===null) a = (typeof b==='number')?null:'';
    if(typeof a==='string'&&typeof b==='string'){ a=a.toUpperCase(); b=b.toUpperCase(); }
    if(op==='=')  return a===b;
    if(op==='<>') return a!==b;
    if(typeof a!==typeof b) return false;
    if(op==='>')  return a>b;
    if(op==='<')  return a<b;
    if(op==='>=') return a>=b;
    if(op==='<=') return a<=b;
    return false;
  };
}
function ifsCollect(args,start){
  const pairs=[];
  for(let i=start;i+1<args.length;i+=2) pairs.push([rangeOf(args[i]),makeCrit(args[i+1])]);
  return pairs;
}
function ifsMatchIdx(pairs,cb){
  const [rg0]=pairs[0];
  const nr=rg0.r2-rg0.r1+1, nc=rg0.c2-rg0.c1+1;
  for(let i=0;i<nr;i++) for(let j=0;j<nc;j++){
    let ok=true;
    for(const [rg,f] of pairs){ if(!f(getVal(rg.si,rg.r1+i,rg.c1+j))){ ok=false; break; } }
    if(ok) cb(i,j);
  }
}

const FN = {};
const def=(n,o)=>{ FN[n]=o; };
const N1=f=>({f:a=>f(toNum(a[0]))});
const N2=f=>({f:a=>f(toNum(a[0]),toNum(a[1]))});

/* --- math --- */
def('SUM',{r:1,f:a=>sum(numsOf(a))});
def('PRODUCT',{r:1,f:a=>{const n=numsOf(a);return n.length?n.reduce((x,y)=>x*y,1):0;}});
def('SUMSQ',{r:1,f:a=>sum(numsOf(a).map(x=>x*x))});
def('SUMPRODUCT',{r:1,f:a=>{
  const cols=a.map(x=>x&&x.rng?flatVals([x]):[s1(x)]);
  const n=cols[0].length; let t=0;
  for(let i=0;i<n;i++){ let p=1; for(const col of cols){ const v=col[i%col.length]; if(isErr(v)) throw v;
    p *= (typeof v==='number')?v:(typeof v==='boolean'?(v?1:0):(v===null?0:(isNaN(parseFloat(v))?0:parseFloat(v)))); } t+=p; }
  return t;}});
def('ABS',N1(Math.abs)); def('SIGN',N1(Math.sign)); def('SQRT',N1(x=>{if(x<0)throw ERR.NUM();return Math.sqrt(x);}));
def('POWER',N2((a,b)=>{const v=Math.pow(a,b); if(!isFinite(v))throw ERR.NUM(); return v;}));
def('EXP',N1(Math.exp));
def('LN',N1(x=>{if(x<=0)throw ERR.NUM();return Math.log(x);}));
def('LOG10',N1(x=>{if(x<=0)throw ERR.NUM();return Math.log10(x);}));
def('LOG',{f:a=>{const x=toNum(a[0]),b=a.length>1?toNum(a[1]):10; if(x<=0||b<=0)throw ERR.NUM(); return Math.log(x)/Math.log(b);}});
def('MOD',N2((a,b)=>{if(b===0)throw ERR.DIV();return a-b*Math.floor(a/b);}));
def('QUOTIENT',N2((a,b)=>{if(b===0)throw ERR.DIV();return Math.trunc(a/b);}));
def('INT',N1(Math.floor));
def('TRUNC',{f:a=>{const d=a.length>1?toNum(a[1]):0,p=Math.pow(10,d);return Math.trunc(toNum(a[0])*p)/p;}});
def('ROUND',{f:a=>{const d=a.length>1?toNum(a[1]):0,p=Math.pow(10,d),x=toNum(a[0]);
  return Math.sign(x)*Math.round(Math.abs(x)*p+1e-9)/p;}});
def('ROUNDUP',{f:a=>{const d=a.length>1?toNum(a[1]):0,p=Math.pow(10,d),x=toNum(a[0]);return Math.sign(x)*Math.ceil(Math.abs(x)*p-1e-9)/p;}});
def('ROUNDDOWN',{f:a=>{const d=a.length>1?toNum(a[1]):0,p=Math.pow(10,d),x=toNum(a[0]);return Math.sign(x)*Math.floor(Math.abs(x)*p+1e-9)/p;}});
def('MROUND',N2((x,m)=>{if(m===0)return 0;return Math.round(x/m)*m;}));
def('CEILING',{f:a=>{const x=toNum(a[0]),m=a.length>1?toNum(a[1]):1;if(m===0)return 0;return Math.ceil(x/m)*m;}});
def('FLOOR',{f:a=>{const x=toNum(a[0]),m=a.length>1?toNum(a[1]):1;if(m===0)throw ERR.DIV();return Math.floor(x/m)*m;}});
def('EVEN',N1(x=>{const s=x<0?-1:1;return s*Math.ceil(Math.abs(x)/2)*2;}));
def('ODD',N1(x=>{const s=x<0?-1:1,v=Math.ceil((Math.abs(x)-1)/2)*2+1;return s*v;}));
def('GCD',{r:1,f:a=>{const g=(x,y)=>y?g(y,x%y):x;return numsOf(a).map(Math.abs).reduce((x,y)=>g(x,y),0);}});
def('LCM',{r:1,f:a=>{const g=(x,y)=>y?g(y,x%y):x;return numsOf(a).map(Math.abs).reduce((x,y)=>x*y/g(x,y),1);}});
def('FACT',N1(x=>{x=Math.floor(x);if(x<0)throw ERR.NUM();let v=1;for(let i=2;i<=x;i++)v*=i;return v;}));
function nCr(n,k){ let v=1; for(let i=1;i<=k;i++) v=v*(n-k+i)/i; return Math.round(v); }
def('COMBIN',N2((n,k)=>nCr(Math.floor(n),Math.floor(k))));
def('PERMUT',N2((n,k)=>{let v=1;for(let i=0;i<k;i++)v*=(n-i);return v;}));
def('PI',{f:()=>Math.PI});
def('RAND',{f:()=>Math.random()});
def('RANDBETWEEN',N2((a,b)=>Math.floor(Math.random()*(b-a+1))+a));
def('DEGREES',N1(x=>x*180/Math.PI)); def('RADIANS',N1(x=>x*Math.PI/180));
['SIN','COS','TAN','ASIN','ACOS','ATAN','SINH','COSH','TANH'].forEach(k=>def(k,N1(x=>{const v=Math[k.toLowerCase()](x);if(isNaN(v))throw ERR.NUM();return v;})));
def('ATAN2',N2((x,y)=>Math.atan2(y,x)));

/* --- statistics --- */
def('AVERAGE',{r:1,f:a=>avg(numsOf(a))});
def('AVERAGEA',{r:1,f:a=>{const v=flatVals(a).filter(x=>x!==null);if(!v.length)throw ERR.DIV();
  return sum(v.map(x=>typeof x==='number'?x:(x===true?1:0)))/v.length;}});
def('COUNT',{r:1,f:a=>flatVals(a).filter(v=>typeof v==='number').length});
def('COUNTA',{r:1,f:a=>flatVals(a).filter(v=>v!==null&&v!=='').length});
def('COUNTBLANK',{r:1,f:a=>flatVals(a).filter(v=>v===null||v==='').length});
def('MIN',{r:1,f:a=>{const n=numsOf(a);return n.length?Math.min(...n):0;}});
def('MAX',{r:1,f:a=>{const n=numsOf(a);return n.length?Math.max(...n):0;}});
def('MEDIAN',{r:1,f:a=>{const n=numsOf(a).sort((x,y)=>x-y);if(!n.length)throw ERR.NUM();
  const m=n.length>>1;return n.length%2?n[m]:(n[m-1]+n[m])/2;}});
def('MODE',{r:1,f:a=>{const n=numsOf(a),m=new Map();let best=null,bc=1;
  for(const x of n){const c=(m.get(x)||0)+1;m.set(x,c);if(c>bc){bc=c;best=x;}}
  if(best===null)throw ERR.NA();return best;}});
def('STDEV',{r:1,f:a=>Math.sqrt(variance(numsOf(a),false))});
def('STDEVP',{r:1,f:a=>Math.sqrt(variance(numsOf(a),true))});
def('VAR',{r:1,f:a=>variance(numsOf(a),false)});
def('VARP',{r:1,f:a=>variance(numsOf(a),true)});
def('LARGE',{r:1,f:a=>{const n=numsOf([a[0]]).sort((x,y)=>y-x),k=toNum(a[1]);if(k<1||k>n.length)throw ERR.NUM();return n[k-1];}});
def('SMALL',{r:1,f:a=>{const n=numsOf([a[0]]).sort((x,y)=>x-y),k=toNum(a[1]);if(k<1||k>n.length)throw ERR.NUM();return n[k-1];}});
def('RANK',{r:1,f:a=>{const x=toNum(s1(a[0])),n=numsOf([a[1]]),asc=a.length>2&&toNum(a[2])!==0;
  n.sort((p,q)=>asc?p-q:q-p);const i=n.indexOf(x);if(i<0)throw ERR.NA();return i+1;}});
def('PERCENTILE',{r:1,f:a=>{const n=numsOf([a[0]]).sort((x,y)=>x-y),k=toNum(a[1]);
  if(!n.length||k<0||k>1)throw ERR.NUM();const pos=(n.length-1)*k,lo=Math.floor(pos);
  return n[lo]+(pos-lo)*((n[lo+1]===undefined?n[lo]:n[lo+1])-n[lo]);}});
def('QUARTILE',{r:1,f:a=>FN.PERCENTILE.f([a[0],toNum(a[1])/4])});
def('CORREL',{r:1,f:a=>{const x=numsOf([a[0]]),y=numsOf([a[1]]);const n=Math.min(x.length,y.length);
  const mx=sum(x)/n,my=sum(y)/n;let sxy=0,sx=0,sy=0;
  for(let i=0;i<n;i++){sxy+=(x[i]-mx)*(y[i]-my);sx+=(x[i]-mx)**2;sy+=(y[i]-my)**2;}
  if(!sx||!sy)throw ERR.DIV();return sxy/Math.sqrt(sx*sy);}});
def('SLOPE',{r:1,f:a=>{const y=numsOf([a[0]]),x=numsOf([a[1]]),n=Math.min(x.length,y.length);
  const mx=sum(x)/n,my=sum(y)/n;let sxy=0,sx=0;
  for(let i=0;i<n;i++){sxy+=(x[i]-mx)*(y[i]-my);sx+=(x[i]-mx)**2;}
  if(!sx)throw ERR.DIV();return sxy/sx;}});
def('INTERCEPT',{r:1,f:a=>{const y=numsOf([a[0]]),x=numsOf([a[1]]),n=Math.min(x.length,y.length);
  return sum(y)/n - FN.SLOPE.f(a)*(sum(x)/n);}});
def('COUNTIF',{r:1,f:a=>{const rg=rangeOf(a[0]),f=makeCrit(s1(a[1]));let n=0;iterRange(rg,v=>{if(f(v))n++;});return n;}});
def('SUMIF',{r:1,f:a=>{const rg=rangeOf(a[0]),f=makeCrit(s1(a[1])),tg=a[2]?rangeOf(a[2]):rg;let t=0;
  iterRange(rg,(v,r,c)=>{ if(f(v)){ const w=getVal(tg.si,tg.r1+(r-rg.r1),tg.c1+(c-rg.c1)); if(typeof w==='number')t+=w; } });return t;}});
def('AVERAGEIF',{r:1,f:a=>{const rg=rangeOf(a[0]),f=makeCrit(s1(a[1])),tg=a[2]?rangeOf(a[2]):rg;let t=0,n=0;
  iterRange(rg,(v,r,c)=>{ if(f(v)){ const w=getVal(tg.si,tg.r1+(r-rg.r1),tg.c1+(c-rg.c1)); if(typeof w==='number'){t+=w;n++;} } });
  if(!n)throw ERR.DIV();return t/n;}});
def('COUNTIFS',{r:1,f:a=>{const p=ifsCollect(a,0);let n=0;ifsMatchIdx(p,()=>n++);return n;}});
def('SUMIFS',{r:1,f:a=>{const tg=rangeOf(a[0]),p=ifsCollect(a,1);let t=0;
  ifsMatchIdx(p,(i,j)=>{const v=getVal(tg.si,tg.r1+i,tg.c1+j);if(typeof v==='number')t+=v;});return t;}});
def('AVERAGEIFS',{r:1,f:a=>{const tg=rangeOf(a[0]),p=ifsCollect(a,1);let t=0,n=0;
  ifsMatchIdx(p,(i,j)=>{const v=getVal(tg.si,tg.r1+i,tg.c1+j);if(typeof v==='number'){t+=v;n++;}});
  if(!n)throw ERR.DIV();return t/n;}});
def('MAXIFS',{r:1,f:a=>{const tg=rangeOf(a[0]),p=ifsCollect(a,1);let b=null;
  ifsMatchIdx(p,(i,j)=>{const v=getVal(tg.si,tg.r1+i,tg.c1+j);if(typeof v==='number'&&(b===null||v>b))b=v;});return b===null?0:b;}});
def('MINIFS',{r:1,f:a=>{const tg=rangeOf(a[0]),p=ifsCollect(a,1);let b=null;
  ifsMatchIdx(p,(i,j)=>{const v=getVal(tg.si,tg.r1+i,tg.c1+j);if(typeof v==='number'&&(b===null||v<b))b=v;});return b===null?0:b;}});

/* --- logic --- */
def('IF',{lazy:1,f:(n,ctx,ev)=>{ const t=toBool(ev(n[0])); if(t) return n.length>1?s1(ev(n[1])):true;
  return n.length>2?s1(ev(n[2])):false; }});
def('IFS',{lazy:1,f:(n,ctx,ev)=>{ for(let i=0;i+1<n.length;i+=2) if(toBool(ev(n[i]))) return s1(ev(n[i+1])); throw ERR.NA(); }});
def('SWITCH',{lazy:1,f:(n,ctx,ev)=>{ const x=s1(ev(n[0]));
  for(let i=1;i+1<n.length;i+=2) if(compare(x,s1(ev(n[i])),'=')) return s1(ev(n[i+1]));
  return (n.length%2===0)? s1(ev(n[n.length-1])) : (()=>{throw ERR.NA();})(); }});
def('IFERROR',{lazy:1,f:(n,ctx,ev)=>{ try{ const v=s1(ev(n[0])); return isErr(v)? s1(ev(n[1])) : v; }
  catch(e){ if(isErr(e)) return s1(ev(n[1])); throw e; } }});
def('IFNA',{lazy:1,f:(n,ctx,ev)=>{ try{ const v=s1(ev(n[0])); return (isErr(v)&&v.e==='#N/A')? s1(ev(n[1])) : v; }
  catch(e){ if(isErr(e)&&e.e==='#N/A') return s1(ev(n[1])); throw e; } }});
def('AND',{r:1,f:a=>{ const v=flatVals(a).filter(x=>x!==null); if(!v.length)throw ERR.VAL();
  return v.every(x=>{ if(isErr(x))throw x; return toBool(x); }); }});
def('OR',{r:1,f:a=>{ const v=flatVals(a).filter(x=>x!==null); if(!v.length)throw ERR.VAL();
  return v.some(x=>{ if(isErr(x))throw x; return toBool(x); }); }});
def('XOR',{r:1,f:a=>flatVals(a).filter(x=>x!==null&&toBool(x)).length%2===1});
def('NOT',{f:a=>!toBool(a[0])});
def('TRUE',{f:()=>true}); def('FALSE',{f:()=>false});

/* --- info --- */
def('ISBLANK',{r:1,keepErr:1,f:a=>{const v=s1(a[0]);return v===null||v==='';}});
def('ISNUMBER',{r:1,keepErr:1,f:a=>typeof s1(a[0])==='number'});
def('ISTEXT',{r:1,keepErr:1,f:a=>typeof s1(a[0])==='string'});
def('ISNONTEXT',{r:1,keepErr:1,f:a=>typeof s1(a[0])!=='string'});
def('ISLOGICAL',{r:1,keepErr:1,f:a=>typeof s1(a[0])==='boolean'});
def('ISERROR',{r:1,keepErr:1,lazy:1,f:(n,ctx,ev)=>{try{return isErr(s1(ev(n[0])));}catch(e){return isErr(e);}}});
def('ISERR',{lazy:1,f:(n,ctx,ev)=>{try{const v=s1(ev(n[0]));return isErr(v)&&v.e!=='#N/A';}catch(e){return isErr(e)&&e.e!=='#N/A';}}});
def('ISNA',{lazy:1,f:(n,ctx,ev)=>{try{const v=s1(ev(n[0]));return isErr(v)&&v.e==='#N/A';}catch(e){return isErr(e)&&e.e==='#N/A';}}});
def('ISEVEN',{f:a=>Math.floor(toNum(a[0]))%2===0});
def('ISODD',{f:a=>Math.abs(Math.floor(toNum(a[0]))%2)===1});
def('NA',{f:()=>{throw ERR.NA();}});
def('N',{r:1,f:a=>{const v=s1(a[0]);if(typeof v==='number')return v;if(v===true)return 1;if(isErr(v))throw v;return 0;}});
def('T',{r:1,f:a=>{const v=s1(a[0]);return typeof v==='string'?v:'';}});
def('TYPE',{r:1,keepErr:1,f:a=>{const v=s1(a[0]);if(typeof v==='number'||v===null)return 1;
  if(typeof v==='string')return 2;if(typeof v==='boolean')return 4;return 16;}});

/* --- text --- */
def('CONCAT',{r:1,f:a=>flatVals(a).map(v=>v===null?'':toStr(v)).join('')});
def('CONCATENATE',{r:1,f:a=>flatVals(a).map(v=>v===null?'':toStr(v)).join('')});
def('TEXTJOIN',{r:1,f:a=>{const d=toStr(s1(a[0])),skip=toBool(s1(a[1]));
  return flatVals(a.slice(2)).filter(v=>!(skip&&(v===null||v==='')) ).map(v=>v===null?'':toStr(v)).join(d);}});
def('LEFT',{f:a=>toStr(a[0]).slice(0,a.length>1?Math.max(0,toNum(a[1])):1)});
def('RIGHT',{f:a=>{const s=toStr(a[0]),n=a.length>1?Math.max(0,toNum(a[1])):1;return n?s.slice(-n):'';}});
def('MID',{f:a=>{const s=toStr(a[0]),st=toNum(a[1]),n=toNum(a[2]);if(st<1||n<0)throw ERR.VAL();return s.substr(st-1,n);}});
def('LEN',{f:a=>toStr(a[0]).length});
def('LOWER',{f:a=>toStr(a[0]).toLowerCase()});
def('UPPER',{f:a=>toStr(a[0]).toUpperCase()});
def('PROPER',{f:a=>toStr(a[0]).replace(/\w\S*/g,w=>w[0].toUpperCase()+w.slice(1).toLowerCase())});
def('TRIM',{f:a=>toStr(a[0]).replace(/\s+/g,' ').trim()});
def('CLEAN',{f:a=>toStr(a[0]).replace(/[\x00-\x1f]/g,'')});
def('SUBSTITUTE',{f:a=>{const s=toStr(a[0]),o=toStr(a[1]),n=toStr(a[2]);
  if(a.length<4) return o===''?s:s.split(o).join(n);
  let k=toNum(a[3]),i=-1;
  while(k-->0){ i=s.indexOf(o,i+1); if(i<0) return s; }
  return s.slice(0,i)+n+s.slice(i+o.length);}});
def('REPLACE',{f:a=>{const s=toStr(a[0]),st=toNum(a[1]),n=toNum(a[2]),t=toStr(a[3]);
  return s.slice(0,st-1)+t+s.slice(st-1+n);}});
def('FIND',{f:a=>{const i=toStr(a[1]).indexOf(toStr(a[0]),a.length>2?toNum(a[2])-1:0);if(i<0)throw ERR.VAL();return i+1;}});
def('SEARCH',{f:a=>{const i=toStr(a[1]).toUpperCase().indexOf(toStr(a[0]).toUpperCase(),a.length>2?toNum(a[2])-1:0);
  if(i<0)throw ERR.VAL();return i+1;}});
def('REPT',{f:a=>{const n=toNum(a[1]);if(n<0)throw ERR.VAL();return toStr(a[0]).repeat(Math.min(n,10000));}});
def('EXACT',{f:a=>toStr(a[0])===toStr(a[1])});
def('CHAR',{f:a=>String.fromCharCode(toNum(a[0]))});
def('CODE',{f:a=>{const s=toStr(a[0]);if(!s)throw ERR.VAL();return s.charCodeAt(0);}});
def('VALUE',{f:a=>toNum(a[0])});
def('NUMBERVALUE',{f:a=>toNum(a[0])});
def('TEXT',{f:a=>textFormat(s1(a[0]),toStr(a[1]))});
def('DOLLAR',{f:a=>textFormat(toNum(a[0]),'$#,##0.'+'0'.repeat(a.length>1?toNum(a[1]):2))});
def('FIXED',{f:a=>{const d=a.length>1?toNum(a[1]):2,noc=a.length>2&&toBool(a[2]);
  return textFormat(toNum(a[0]),(noc?'0':'#,##0')+(d>0?'.'+'0'.repeat(d):''));}});
def('UNICHAR',{f:a=>String.fromCodePoint(toNum(a[0]))});
def('UNICODE',{f:a=>toStr(a[0]).codePointAt(0)});

/* --- lookup --- */
def('ROW',{r:1,f:(a,ctx)=>a.length&&a[0]&&a[0].rng?a[0].rng.r1+1:(a.length&&a[0]===null?ctx.r+1:ctx.r+1)});
def('COLUMN',{r:1,f:(a,ctx)=>a.length&&a[0]&&a[0].rng?a[0].rng.c1+1:ctx.c+1});
def('ROWS',{r:1,f:a=>{const g=rangeOf(a[0]);return g.r2-g.r1+1;}});
def('COLUMNS',{r:1,f:a=>{const g=rangeOf(a[0]);return g.c2-g.c1+1;}});
def('CHOOSE',{lazy:1,f:(n,ctx,ev)=>{const i=toNum(ev(n[0]));if(i<1||i>=n.length)throw ERR.VAL();return s1(ev(n[i]));}});
def('VLOOKUP',{r:1,f:a=>{
  const x=s1(a[0]),g=rangeOf(a[1]),ci=toNum(a[2]),approx=a.length<4?true:toBool(a[3]);
  if(ci<1||g.c1+ci-1>g.c2)throw ERR.REF();
  let best=null;
  for(let r=g.r1;r<=g.r2;r++){
    const v=getVal(g.si,r,g.c1);
    if(approx){ if(compare(v,x,'<=')) best=r; else break; }
    else if(compare(v,x,'=')) return getVal(g.si,r,g.c1+ci-1);
  }
  if(best===null)throw ERR.NA();
  return getVal(g.si,best,g.c1+ci-1);}});
def('HLOOKUP',{r:1,f:a=>{
  const x=s1(a[0]),g=rangeOf(a[1]),ri=toNum(a[2]),approx=a.length<4?true:toBool(a[3]);
  let best=null;
  for(let c=g.c1;c<=g.c2;c++){
    const v=getVal(g.si,g.r1,c);
    if(approx){ if(compare(v,x,'<=')) best=c; else break; }
    else if(compare(v,x,'=')) return getVal(g.si,g.r1+ri-1,c);
  }
  if(best===null)throw ERR.NA();
  return getVal(g.si,g.r1+ri-1,best);}});
def('MATCH',{r:1,f:a=>{
  const x=s1(a[0]),g=rangeOf(a[1]),ty=a.length>2?toNum(a[2]):1;
  const vert=(g.c2===g.c1);
  const n=vert?g.r2-g.r1+1:g.c2-g.c1+1;
  const at=i=>vert?getVal(g.si,g.r1+i,g.c1):getVal(g.si,g.r1,g.c1+i);
  let best=-1;
  for(let i=0;i<n;i++){ const v=at(i);
    if(ty===0){ if(typeof x==='string'&&/[*?]/.test(x)){ if(makeCrit(x)(v)) return i+1; } else if(compare(v,x,'=')) return i+1; }
    else if(ty===1){ if(compare(v,x,'<=')) best=i; else break; }
    else { if(compare(v,x,'>=')) best=i; else break; }
  }
  if(best<0)throw ERR.NA(); return best+1;}});
def('INDEX',{r:1,f:a=>{
  const g=rangeOf(a[0]); let ri=a.length>1?toNum(a[1]):0, ci=a.length>2?toNum(a[2]):0;
  const nr=g.r2-g.r1+1, nc=g.c2-g.c1+1;
  if(nr===1&&a.length===2){ ci=ri; ri=1; }
  if(nc===1&&a.length===2) ci=1;
  if(ri<0||ci<0||ri>nr||ci>nc)throw ERR.REF();
  return getVal(g.si,g.r1+Math.max(ri-1,0),g.c1+Math.max(ci-1,0));}});
def('XLOOKUP',{r:1,f:a=>{
  const x=s1(a[0]),lk=rangeOf(a[1]),rt=rangeOf(a[2]);
  const vert=(lk.c2===lk.c1), n=vert?lk.r2-lk.r1+1:lk.c2-lk.c1+1;
  for(let i=0;i<n;i++){
    const v=vert?getVal(lk.si,lk.r1+i,lk.c1):getVal(lk.si,lk.r1,lk.c1+i);
    if(compare(v,x,'=')) return vert?getVal(rt.si,rt.r1+i,rt.c1):getVal(rt.si,rt.r1,rt.c1+i);
  }
  if(a.length>3) return s1(a[3]);
  throw ERR.NA();}});
def('OFFSET',{r:1,f:a=>{
  const g=rangeOf(a[0]),dr=toNum(a[1]),dc=toNum(a[2]);
  const h=a.length>3?toNum(a[3]):(g.r2-g.r1+1), w=a.length>4?toNum(a[4]):(g.c2-g.c1+1);
  const r1=g.r1+dr,c1=g.c1+dc;
  if(r1<0||c1<0)throw ERR.REF();
  return {rng:{si:g.si,r1,c1,r2:r1+h-1,c2:c1+w-1}};}});
def('INDIRECT',{f:(a,ctx)=>{
  const s=toStr(a[0]); const ast=getAst(s);
  if(ast.k!=='ref'&&ast.k!=='rng')throw ERR.REF();
  return evalNode(ast,ctx);}});
def('TRANSPOSE',{r:1,f:a=>s1(a[0])});

/* --- date & time --- */
def('TODAY',{f:()=>{const d=new Date();return Math.floor(dateToSerial(new Date(d.getFullYear(),d.getMonth(),d.getDate())));}});
def('NOW',{f:()=>dateToSerial(new Date())});
def('DATE',{f:a=>{const y=toNum(a[0]),m=toNum(a[1]),d=toNum(a[2]);
  return dateToSerial(new Date(y<1900?1900+y:y,m-1,d));}});
def('TIME',{f:a=>(toNum(a[0])*3600+toNum(a[1])*60+toNum(a[2]))/86400});
def('DATEVALUE',{f:a=>{const v=parseDateString(toStr(a[0]));if(v===null)throw ERR.VAL();return Math.floor(v);}});
def('TIMEVALUE',{f:a=>{const v=parseDateString(toStr(a[0]));if(v===null)throw ERR.VAL();return v-Math.floor(v);}});
const dpart=f=>({f:a=>f(serialToDate(toNum(a[0])))});
def('YEAR',dpart(d=>d.getUTCFullYear()));
def('MONTH',dpart(d=>d.getUTCMonth()+1));
def('DAY',dpart(d=>d.getUTCDate()));
def('HOUR',dpart(d=>d.getUTCHours()));
def('MINUTE',dpart(d=>d.getUTCMinutes()));
def('SECOND',dpart(d=>d.getUTCSeconds()));
def('WEEKDAY',{f:a=>{const w=serialToDate(toNum(a[0])).getUTCDay(),t=a.length>1?toNum(a[1]):1;
  if(t===1)return w+1; if(t===2)return w===0?7:w; if(t===3)return w===0?6:w-1; return w+1;}});
def('WEEKNUM',{f:a=>{const d=serialToDate(toNum(a[0]));const s=Date.UTC(d.getUTCFullYear(),0,1);
  return Math.floor((d.getTime()-s)/DAY/7)+1;}});
def('DAYS',{f:a=>Math.floor(toNum(a[0]))-Math.floor(toNum(a[1]))});
def('DAYS360',{f:a=>{const A=serialToDate(toNum(a[0])),B=serialToDate(toNum(a[1]));
  const d1=Math.min(A.getUTCDate(),30),d2=Math.min(B.getUTCDate(),30);
  return (B.getUTCFullYear()-A.getUTCFullYear())*360+(B.getUTCMonth()-A.getUTCMonth())*30+(d2-d1);}});
def('EDATE',{f:a=>{const d=serialToDate(toNum(a[0])),m=toNum(a[1]);
  const nd=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+m,d.getUTCDate()));
  return Math.round((nd.getTime()-EPOCH)/DAY);}});
def('EOMONTH',{f:a=>{const d=serialToDate(toNum(a[0])),m=toNum(a[1]);
  const nd=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+m+1,0));
  return Math.round((nd.getTime()-EPOCH)/DAY);}});
def('DATEDIF',{f:a=>{const A=serialToDate(toNum(a[0])),B=serialToDate(toNum(a[1])),u=toStr(a[2]).toUpperCase();
  let y=B.getUTCFullYear()-A.getUTCFullYear(), m=B.getUTCMonth()-A.getUTCMonth(), d=B.getUTCDate()-A.getUTCDate();
  if(d<0){m--;d+=new Date(Date.UTC(B.getUTCFullYear(),B.getUTCMonth(),0)).getUTCDate();}
  if(m<0){y--;m+=12;}
  if(u==='Y')return y; if(u==='M')return y*12+m; if(u==='D')return Math.floor(toNum(a[1]))-Math.floor(toNum(a[0]));
  if(u==='MD')return d; if(u==='YM')return m; throw ERR.NUM();}});
def('NETWORKDAYS',{r:1,f:a=>{let s=Math.floor(toNum(s1(a[0]))),e=Math.floor(toNum(s1(a[1])));
  const hol=new Set(a[2]?flatVals([a[2]]).filter(v=>typeof v==='number').map(Math.floor):[]);
  let sign=1; if(s>e){const t=s;s=e;e=t;sign=-1;}
  let n=0; for(let i=s;i<=e;i++){const w=serialToDate(i).getUTCDay(); if(w!==0&&w!==6&&!hol.has(i))n++;}
  return n*sign;}});
def('WORKDAY',{r:1,f:a=>{let s=Math.floor(toNum(s1(a[0])));let n=toNum(s1(a[1]));
  const hol=new Set(a[2]?flatVals([a[2]]).filter(v=>typeof v==='number').map(Math.floor):[]);
  const step=n<0?-1:1; n=Math.abs(n);
  while(n>0){ s+=step; const w=serialToDate(s).getUTCDay(); if(w!==0&&w!==6&&!hol.has(s))n--; }
  return s;}});

/* --- financial --- */
function pmtCalc(r,n,pv,fv,ty){
  fv=fv||0; ty=ty||0;
  if(r===0) return -(pv+fv)/n;
  const p=Math.pow(1+r,n);
  return -(pv*p+fv)/((1+r*ty)*(p-1)/r);
}
def('PMT',{f:a=>pmtCalc(toNum(a[0]),toNum(a[1]),toNum(a[2]),a.length>3?toNum(a[3]):0,a.length>4?toNum(a[4]):0)});
def('FV',{f:a=>{const r=toNum(a[0]),n=toNum(a[1]),p=toNum(a[2]),pv=a.length>3?toNum(a[3]):0,ty=a.length>4?toNum(a[4]):0;
  if(r===0) return -(pv+p*n);
  const q=Math.pow(1+r,n); return -(pv*q + p*(1+r*ty)*(q-1)/r);}});
def('PV',{f:a=>{const r=toNum(a[0]),n=toNum(a[1]),p=toNum(a[2]),fv=a.length>3?toNum(a[3]):0,ty=a.length>4?toNum(a[4]):0;
  if(r===0) return -(fv+p*n);
  const q=Math.pow(1+r,n); return -(fv + p*(1+r*ty)*(q-1)/r)/q;}});
def('NPER',{f:a=>{const r=toNum(a[0]),p=toNum(a[1]),pv=toNum(a[2]),fv=a.length>3?toNum(a[3]):0,ty=a.length>4?toNum(a[4]):0;
  if(r===0) return -(pv+fv)/p;
  const z=p*(1+r*ty)/r; return Math.log((-fv+z)/(pv+z))/Math.log(1+r);}});
def('RATE',{f:a=>{const n=toNum(a[0]),p=toNum(a[1]),pv=toNum(a[2]),fv=a.length>3?toNum(a[3]):0,ty=a.length>4?toNum(a[4]):0;
  let r=a.length>5?toNum(a[5]):0.1;
  for(let i=0;i<80;i++){
    const q=Math.pow(1+r,n);
    const f=pv*q + p*(1+r*ty)*(q-1)/r + fv;
    const dq=n*Math.pow(1+r,n-1);
    const df=pv*dq + p*(1+r*ty)*(dq*r-(q-1))/(r*r) + p*ty*(q-1)/r;
    const nr=r-f/df;
    if(!isFinite(nr))break;
    if(Math.abs(nr-r)<1e-10){r=nr;break;}
    r=nr;
  }
  return r;}});
def('NPV',{r:1,f:a=>{const r=toNum(s1(a[0])),v=numsOf(a.slice(1));
  return v.reduce((t,x,i)=>t+x/Math.pow(1+r,i+1),0);}});
def('IRR',{r:1,f:a=>{const v=numsOf([a[0]]);let r=a.length>1?toNum(s1(a[1])):0.1;
  for(let i=0;i<100;i++){
    let f=0,df=0;
    v.forEach((x,k)=>{f+=x/Math.pow(1+r,k); df+=-k*x/Math.pow(1+r,k+1);});
    if(!df)break; const nr=r-f/df;
    if(!isFinite(nr))break;
    if(Math.abs(nr-r)<1e-10){r=nr;break;} r=nr;
  }
  return r;}});
def('SLN',{f:a=>(toNum(a[0])-toNum(a[1]))/toNum(a[2])});
def('IPMT',{f:a=>{const r=toNum(a[0]),per=toNum(a[1]),n=toNum(a[2]),pv=toNum(a[3]),fv=a.length>4?toNum(a[4]):0;
  const pmt=pmtCalc(r,n,pv,fv,0);
  let bal=pv;
  for(let i=1;i<per;i++){ bal=bal*(1+r)+pmt; }
  return -bal*r;}});
def('PPMT',{f:a=>{const pmt=pmtCalc(toNum(a[0]),toNum(a[2]),toNum(a[3]),a.length>4?toNum(a[4]):0,0);
  return pmt-FN.IPMT.f(a);}});
/* ---------- 2c. NUMBER / DATE FORMATTING ---------- */
function genNum(n){
  if(!isFinite(n)) return n>0?'∞':'-∞';
  if(Number.isInteger(n) && Math.abs(n)<1e15) return String(n);
  const a=Math.abs(n);
  if(a>=1e11 || (a<1e-4 && a>0)) return n.toExponential(5).toUpperCase().replace('E','E');
  return String(parseFloat(n.toPrecision(11)));
}
function parseDateString(t){
  t=String(t).trim();
  if(!t) return null;
  let m;
  if(m=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(t))
    return dateToSerial(new Date(+m[1],+m[2]-1,+m[3],+(m[4]||0),+(m[5]||0),+(m[6]||0)));
  if(m=/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?\s*(am|pm)?)?$/i.exec(t)){
    let y=+m[3]; if(y<100) y+= y<30?2000:1900;
    let h=+(m[4]||0); if(m[7]) h = (h%12) + (/p/i.test(m[7])?12:0);
    return dateToSerial(new Date(y,+m[1]-1,+m[2],h,+(m[5]||0),+(m[6]||0)));
  }
  if(m=/^(\d{1,2})[- ]([A-Za-z]{3,})[- ](\d{2,4})$/.exec(t)){
    const mi=MON.findIndex(x=>x.toLowerCase().startsWith(m[2].toLowerCase().slice(0,3)));
    if(mi>=0){ let y=+m[3]; if(y<100) y+= y<30?2000:1900; return dateToSerial(new Date(y,mi,+m[1])); }
  }
  if(m=/^([A-Za-z]{3,})\.? (\d{1,2}),? (\d{4})$/.exec(t)){
    const mi=MON.findIndex(x=>x.toLowerCase().startsWith(m[1].toLowerCase().slice(0,3)));
    if(mi>=0) return dateToSerial(new Date(+m[3],mi,+m[2]));
  }
  if(m=/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(am|pm)?$/i.exec(t)){
    let h=+m[1]; if(m[4]) h=(h%12)+(/p/i.test(m[4])?12:0);
    return (h*3600+ (+m[2])*60 + (+(m[3]||0)))/86400;
  }
  return null;
}
function fmtDate(n,pat){
  const d=serialToDate(n);
  const Y=d.getUTCFullYear(),M=d.getUTCMonth(),D=d.getUTCDate();
  const h=d.getUTCHours(),mi=d.getUTCMinutes(),se=d.getUTCSeconds();
  const p2=v=>String(v).padStart(2,'0');
  const h12=/am\/pm|a\/p/i.test(pat);
  let out='',i=0,afterHour=false;
  while(i<pat.length){
    const rest=pat.slice(i); let m;
    if(m=/^\[h+\]/i.exec(rest)){ out+=Math.floor(n*24); i+=m[0].length; afterHour=true; continue; }
    if(m=/^\[m+\]/i.exec(rest)){ out+=Math.floor(n*1440); i+=m[0].length; continue; }
    if(m=/^\[s+\]/i.exec(rest)){ out+=Math.floor(n*86400); i+=m[0].length; continue; }
    if(m=/^(am\/pm|a\/p)/i.exec(rest)){ out+=(h<12?'AM':'PM'); i+=m[0].length; continue; }
    if(m=/^y{3,4}/i.exec(rest)){ out+=Y; i+=m[0].length; continue; }
    if(m=/^y{1,2}/i.exec(rest)){ out+=p2(Y%100); i+=m[0].length; continue; }
    if(m=/^d{4,}/i.exec(rest)){ out+=DOW[d.getUTCDay()]; i+=m[0].length; continue; }
    if(m=/^d{3}/i.exec(rest)){ out+=DOW[d.getUTCDay()].slice(0,3); i+=3; continue; }
    if(m=/^d{2}/i.exec(rest)){ out+=p2(D); i+=2; continue; }
    if(m=/^d/i.exec(rest)){ out+=D; i++; continue; }
    if(m=/^h{1,2}/i.exec(rest)){ const hh=h12?(h%12||12):h; out+=(m[0].length>1?p2(hh):hh); i+=m[0].length; afterHour=true; continue; }
    if(m=/^s{1,2}/i.exec(rest)){ out+=(m[0].length>1?p2(se):se); i+=m[0].length; afterHour=false; continue; }
    if(m=/^m{4,}/i.exec(rest)){ out+=MON[M]; i+=m[0].length; afterHour=false; continue; }
    if(m=/^m{3}/i.exec(rest)){ out+=MON[M].slice(0,3); i+=3; afterHour=false; continue; }
    if(m=/^m{1,2}/i.exec(rest)){
      const nextIsSec=/^[^a-z0-9]{0,2}s/i.test(rest.slice(m[0].length));
      if(afterHour||nextIsSec) out+=(m[0].length>1?p2(mi):mi);
      else out+=(m[0].length>1?p2(M+1):(M+1));
      i+=m[0].length; afterHour=false; continue;
    }
    if(rest[0]==='"'){ const j=rest.indexOf('"',1); out+=rest.slice(1,j<0?rest.length:j); i+=(j<0?rest.length:j+1); continue; }
    if(rest[0]==='\\'){ out+=(rest[1]||''); i+=2; continue; }
    out+=rest[0]; i++;
  }
  return out;
}
function textFormat(v,pat){
  if(pat==='@') return v===null?'':String(v);
  if(typeof v!=='number'){
    if(typeof v==='boolean') return v?'TRUE':'FALSE';
    if(v===null) v=0; else { const n=parseDateString(String(v)); if(n===null) return String(v); v=n; }
  }
  if(!/[#0]/.test(pat) && /[ymdhs]/i.test(pat)) return fmtDate(v,pat);
  const m=/[#0][#0,]*(\.[#0]+)?/.exec(pat);
  if(!m) return genNum(v);
  const core=m[0], pre=pat.slice(0,m.index), suf=pat.slice(m.index+core.length);
  const pct=/%/.test(pre+suf);
  let x=pct? v*100 : v;
  const dec=core.includes('.')? core.split('.')[1].length : 0;
  const comma=core.includes(',');
  let s=Math.abs(x).toFixed(dec);
  if(comma){ const p=s.split('.'); p[0]=p[0].replace(/\B(?=(\d{3})+(?!\d))/g,','); s=p.join('.'); }
  const intPad=core.split('.')[0].replace(/,/g,'');
  const zeros=(intPad.match(/0/g)||[]).length;
  if(zeros>1){ const p=s.split('.'); while(p[0].replace(/,/g,'').length<zeros) p[0]='0'+p[0]; s=p.join('.'); }
  return (x<0?'-':'')+pre+s+suf;
}
function toFraction(x,maxDen){
  const sign=x<0?-1:1; x=Math.abs(x);
  const whole=Math.floor(x); let fr=x-whole;
  if(fr<1e-9) return (sign<0?'-':'')+whole;
  let bn=1,bd=1,best=1e9;
  for(let d=1;d<=maxDen;d++){ const n=Math.round(fr*d); const e=Math.abs(fr-n/d);
    if(e<best-1e-12){ best=e; bn=n; bd=d; if(e<1e-9) break; } }
  if(bn===0) return (sign<0?'-':'')+whole;
  return (sign<0?'-':'')+(whole?whole+' ':'')+bn+'/'+bd;
}
const CURSYM={USD:'$',EUR:'€',GBP:'£',JPY:'¥',INR:'₹',CAD:'CA$',AUD:'A$',CHF:'CHF ',BRL:'R$',NGN:'₦'};
function grp(s){ const p=s.split('.'); p[0]=p[0].replace(/\B(?=(\d{3})+(?!\d))/g,','); return p.join('.'); }

function displayText(v,fmt){
  if(v===null||v===undefined) return '';
  if(isErr(v)) return v.e;
  if(typeof v==='boolean') return v?'TRUE':'FALSE';
  const t=fmt?fmt.t:'general';
  if(typeof v==='string') return v;
  const d=(fmt&&fmt.d!=null)?fmt.d:2;
  const sym=(fmt&&fmt.cur)?(CURSYM[fmt.cur]||fmt.cur):'$';
  const neg=v<0, a=Math.abs(v);
  switch(t){
    case 'number':  return (neg?'-':'')+a.toFixed(d);
    case 'comma':   return (neg?'-':'')+grp(a.toFixed(d));
    case 'currency':return (neg?'-':'')+sym+grp(a.toFixed(d));
    case 'accounting': return neg? '('+sym+grp(a.toFixed(d))+')' : sym+grp(a.toFixed(d));
    case 'percent': return (neg?'-':'')+(a*100).toFixed(d)+'%';
    case 'fraction':return toFraction(v,(fmt&&fmt.den)||16);
    case 'sci':     return v.toExponential(d).toUpperCase();
    case 'date':    return fmtDate(v,(fmt&&fmt.pat)||'yyyy-mm-dd');
    case 'time':    return fmtDate(v,(fmt&&fmt.pat)||'h:mm:ss AM/PM');
    case 'datetime':return fmtDate(v,(fmt&&fmt.pat)||'yyyy-mm-dd hh:mm');
    case 'duration':return fmtDate(v,(fmt&&fmt.pat)||'[h]:mm:ss');
    case 'custom':  return textFormat(v,(fmt&&fmt.pat)||'General');
    case 'text':    return genNum(v);
    default:        return genNum(v);
  }
}

/* ---------- 3. RENDER ---------- */
const vp=$('vp'), layer=$('layer'), sizer=$('sizer'), hcols=$('hcols'), hrows=$('hrows'),
      selbox=$('selbox'), activebox=$('activebox'), fillh=$('fillh'), fillbox=$('fillbox'),
      cutbox=$('cutbox'), editor=$('editor'), grid=$('grid');
let cellsHost=document.createElement('div');
cellsHost.id='cellsHost';
cellsHost.style.cssText='position:absolute;left:0;top:0';
layer.insertBefore(cellsHost, layer.firstChild);
const filterHost=document.createElement('div');
filterHost.id='filterHost';
filterHost.style.cssText='position:absolute;left:0;top:0;pointer-events:none';
layer.appendChild(filterHost);
const chartHost=document.createElement('div');
chartHost.id='chartHost';
chartHost.style.cssText='position:absolute;left:0;top:0';
layer.appendChild(chartHost);
let selectedChart=null, chartRenderGen=-1, chartRenderSheet=-1;
chartHost.addEventListener('mousedown',e=>{
  const el=e.target.closest('.chartobj'); if(!el) return;
  const ch=cur().charts.find(c=>c.id==el.dataset.id); if(!ch) return;
  e.stopPropagation();
  const btn=e.target.closest('[data-act]');
  if(btn){ e.preventDefault();
    if(btn.dataset.act==='del'){ snap(); cur().charts=cur().charts.filter(c=>c.id!==ch.id); selectedChart=null; invalidateCharts(); after(); }
    else if(btn.dataset.act==='edit'){ openChartDialog(ch); }
    return; }
  selectedChart=ch.id;
  if(e.target.closest('.cresize')){ drag={mode:'chartsize',ch,x0:e.clientX,y0:e.clientY,w0:ch.w,h0:ch.h}; }
  else { drag={mode:'chartmove',ch,x0:e.clientX,y0:e.clientY,cx:ch.x,cy:ch.y}; }
  e.preventDefault();
  [...chartHost.children].forEach(x=>x.classList.toggle('sel',x.dataset.id==ch.id));
});
filterHost.addEventListener('mousedown',e=>{
  const a=e.target.closest('.filter-arrow'); if(!a) return;
  e.preventDefault(); e.stopPropagation();
  const r=a.getBoundingClientRect();
  openFilterMenu(+a.dataset.col, r.left, r.bottom+4);
});
const notetip=document.createElement('div'); notetip.id='notetip'; document.body.appendChild(notetip);
cellsHost.addEventListener('mousedown',e=>{
  const cell=e.target.closest('.cell.lnk'); if(!cell) return;
  if(e.ctrlKey||e.metaKey){ const u=cell.dataset.link; if(u){ window.open(normLink(u),'_blank','noopener'); e.preventDefault(); e.stopPropagation(); } }
},true);
cellsHost.addEventListener('mouseover',e=>{
  const cell=e.target.closest('.cell'); if(!cell||!cell.dataset.rc) { notetip.style.display='none'; return; }
  const [r,c]=cell.dataset.rc.split(',').map(Number);
  const x=cur().cells[key(r,c)];
  if(x&&x.note){ notetip.textContent=x.note; notetip.style.display='block';
    const R=cell.getBoundingClientRect(); notetip.style.left=Math.min(R.right+6,innerWidth-250)+'px'; notetip.style.top=(R.top)+'px'; }
  else notetip.style.display='none';
});
cellsHost.addEventListener('mouseleave',()=>{ notetip.style.display='none'; });
function normLink(u){ return /^[a-z][a-z0-9+.-]*:|^\/|^#/i.test(u)? u : 'https://'+u; }
const pointbox=document.createElement('div');
pointbox.id='pointbox';
pointbox.style.cssText='position:absolute;display:none;pointer-events:none;z-index:24';
layer.appendChild(pointbox);

const tx=c=>(c<cur().fzC? vp.scrollLeft:0)+colX[c];
const ty=r=>(r<cur().fzR? vp.scrollTop:0)+rowY[r];

function styleOf(S,r,c){ const x=S.cells[key(r,c)]; return x&&x.s?x.s:null; }

/* ---------- conditional formatting ---------- */
function hex2rgb(h){ h=h.replace('#',''); if(h.length===3) h=h.split('').map(x=>x+x).join('');
  return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]; }
function rgb2hex(r){ return '#'+r.map(x=>Math.round(clamp(x,0,255)).toString(16).padStart(2,'0')).join(''); }
function mix(a,b,t){ const x=hex2rgb(a),y=hex2rgb(b); return rgb2hex([x[0]+(y[0]-x[0])*t,x[1]+(y[1]-x[1])*t,x[2]+(y[2]-x[2])*t]); }
function inRuleRange(rule,r,c){ return r>=rule.r1&&r<=rule.r2&&c>=rule.c1&&c<=rule.c2; }
let cfCache={gen:-1,sheet:-1,ctx:[]};
function buildCFContexts(S){
  if(cfCache.gen===dataGen && cfCache.sheet===DOC.active) return cfCache.ctx;
  const ctx=(S.cf||[]).map(rule=>{
    const o={rule};
    const nums=[]; const vals=[]; const countMap=new Map();
    for(let r=rule.r1;r<=rule.r2;r++) for(let c=rule.c1;c<=rule.c2;c++){
      const v=getVal(DOC.active,r,c);
      if(v===null||v===''||isErr(v)) continue;
      vals.push(v);
      if(typeof v==='number') nums.push(v);
      const kk=(typeof v==='number')?('n'+v):('s'+String(v).toLowerCase());
      countMap.set(kk,(countMap.get(kk)||0)+1);
    }
    if(nums.length){ o.min=Math.min(...nums); o.max=Math.max(...nums); }
    if(rule.type==='top'){ const srt=nums.slice().sort((a,b)=>rule.mode==='bottom'?a-b:b-a);
      let n=rule.pct? Math.max(1,Math.ceil(nums.length*rule.n/100)) : rule.n;
      n=clamp(n,1,srt.length); o.threshold = srt.length? srt[n-1] : null; }
    o.countMap=countMap;
    return o;
  });
  cfCache={gen:dataGen,sheet:DOC.active,ctx};
  return ctx;
}
/* returns {bg?,color?,bold?,bar?{color,pct,neg}} or null */
function cfOverlay(S,r,c,v){
  const ctx=buildCFContexts(S);
  let out=null;
  for(const o of ctx){
    const rule=o.rule;
    if(!inRuleRange(rule,r,c)) continue;
    const blank=(v===null||v===''||isErr(v));
    if(rule.type==='cell'){
      if(blank) continue;
      if(cfMatchCell(rule,v)) out=Object.assign(out||{}, cfFillOut(rule));
    } else if(rule.type==='top'){
      if(typeof v!=='number'||o.threshold===null) continue;
      const hit = rule.mode==='bottom'? v<=o.threshold : v>=o.threshold;
      if(hit) out=Object.assign(out||{}, cfFillOut(rule));
    } else if(rule.type==='dup'){
      if(blank) continue;
      const kk=(typeof v==='number')?('n'+v):('s'+String(v).toLowerCase());
      const cnt=o.countMap.get(kk)||0;
      const hit = rule.mode==='unique'? cnt<=1 : cnt>1;
      if(hit) out=Object.assign(out||{}, cfFillOut(rule));
    } else if(rule.type==='scale2'||rule.type==='scale3'){
      if(typeof v!=='number'||o.min===undefined||o.max===o.min) { if(typeof v==='number'&&o.max===o.min){ out=Object.assign(out||{},{bg:rule.type==='scale3'?rule.midColor:rule.maxColor}); } continue; }
      const t=(v-o.min)/(o.max-o.min);
      let col;
      if(rule.type==='scale2') col=mix(rule.minColor,rule.maxColor,t);
      else col = t<=0.5 ? mix(rule.minColor,rule.midColor,t/0.5) : mix(rule.midColor,rule.maxColor,(t-0.5)/0.5);
      out=Object.assign(out||{},{bg:col});
    } else if(rule.type==='databar'){
      if(typeof v!=='number'||o.max===undefined) continue;
      const lo=Math.min(0,o.min), hi=Math.max(0,o.max), span=hi-lo||1;
      const pct=clamp((v-lo)/span,0,1)*100;
      out=Object.assign(out||{},{bar:{color:rule.color,pct,grad:!!rule.grad}});
    }
  }
  return out;
}
function cfMatchCell(rule,v){
  const op=rule.op;
  if(op==='contains'||op==='notcontains'||op==='begins'||op==='ends'){
    const sv=String(v).toLowerCase(), q=String(rule.v1||'').toLowerCase();
    if(op==='contains') return sv.indexOf(q)>=0;
    if(op==='notcontains') return sv.indexOf(q)<0;
    if(op==='begins') return sv.startsWith(q);
    if(op==='ends') return sv.endsWith(q);
  }
  const a=v, b=parseCFNum(rule.v1);
  if(op==='eq') return compare(a,b,'=');
  if(op==='ne') return compare(a,b,'<>');
  if(typeof a!=='number') { const bn=parseCFNum(rule.v1);
    if(op==='between'){ return compare(a,bn,'>=')&&compare(a,parseCFNum(rule.v2),'<='); }
    return false; }
  if(op==='gt') return a>b; if(op==='lt') return a<b;
  if(op==='ge') return a>=b; if(op==='le') return a<=b;
  if(op==='between'){ const c=parseCFNum(rule.v2); return a>=Math.min(b,c)&&a<=Math.max(b,c); }
  return false;
}
function parseCFNum(x){ if(x==null) return 0; const n=parseFloat(String(x).replace(/,/g,'')); return isNaN(n)?String(x):n; }
function cfFillOut(rule){ const o={}; if(rule.fill) o.bg=rule.fill; if(rule.color) o.color=rule.color; if(rule.bold) o.bold=true; return o; }

function cellStyleCss(s,v){
  let t='';
  if(s){
    if(s.b) t+='font-weight:700;';
    if(s.i) t+='font-style:italic;';
    let td=(s.u?'underline ':'')+(s.st?'line-through':'');
    if(td.trim()) t+='text-decoration:'+td.trim()+';';
    if(s.ff) t+='font-family:'+s.ff+';';
    if(s.fs) t+='font-size:'+Math.round(s.fs*zoom)+'px;';
    if(s.color) t+='color:'+s.color+';';
    if(s.bg) t+='background:'+s.bg+';';
    if(s.bl) t+='border-left:1px solid '+s.bl+';';
    if(s.bt) t+='border-top:1px solid '+s.bt+';';
    if(s.br) t+='border-right:1px solid '+s.br+';';
    if(s.bb) t+='border-bottom:1px solid '+s.bb+';';
  }
  const ha=(s&&s.ha)||(typeof v==='number'?'right':(typeof v==='boolean'||isErr(v))?'center':'left');
  t+='justify-content:'+(ha==='right'?'flex-end':ha==='center'?'center':'flex-start')+';';
  const va=(s&&s.va)||'bottom';
  t+='align-items:'+(va==='top'?'flex-start':va==='middle'?'center':'flex-end')+';';
  return t;
}

let renderQueued=false;
function draw(){ if(renderQueued) return; renderQueued=true; requestAnimationFrame(()=>{ renderQueued=false; render(); }); }

function visibleRange(){
  const S=cur();
  const sl=vp.scrollLeft, st=vp.scrollTop, vw=vp.clientWidth, vh=vp.clientHeight;
  const fzW=colX[S.fzC]||0, fzH=rowY[S.fzR]||0;
  let c0=idxAt(colX,sl+fzW,S.nCols), c1=Math.min(idxAt(colX,sl+vw,S.nCols)+1,S.nCols-1);
  let r0=idxAt(rowY,st+fzH,S.nRows), r1=Math.min(idxAt(rowY,st+vh,S.nRows)+1,S.nRows-1);
  const cols=[],rows=[];
  for(let c=0;c<S.fzC;c++) cols.push(c);
  for(let c=Math.max(c0,S.fzC);c<=c1;c++) cols.push(c);
  for(let r=0;r<S.fzR;r++) rows.push(r);
  for(let r=Math.max(r0,S.fzR);r<=r1;r++) rows.push(r);
  return {rows,cols,r0,r1,c0,c1};
}

function render(){
  const S=cur();
  geom();
  sizer.style.width=(colX[S.nCols]+40)+'px';
  sizer.style.height=(rowY[S.nRows]+40)+'px';
  layer.style.fontSize=Math.round(13*zoom)+'px';
  const {rows,cols}=visibleRange();
  const sb=selBox();
  let html='';
  const drawn=new Set();
  const cell=(r,c)=>{
    const m=mergeOf(S,r,c);
    let R=r,C=c,W,H;
    if(m){ if(drawn.has(m.r1+':'+m.c1)) return; R=m.r1; C=m.c1; drawn.add(R+':'+C);
      W=colX[Math.min(m.c2+1,S.nCols)]-colX[m.c1]; H=rowY[Math.min(m.r2+1,S.nRows)]-rowY[m.r1]; }
    else { W=cw(c); H=rh(r); if(W===0||H===0) return; }
    const v=getVal(DOC.active,R,C);
    const s=styleOf(S,R,C);
    const txt=displayText(v,s&&s.fmt);
    const z=(R<S.fzR?1:0)+(C<S.fzC?1:0);
    const cx=S.cells[key(R,C)];
    const lnk=cx&&cx.link, note=cx&&cx.note;
    const cf=(S.cf&&S.cf.length)? cfOverlay(S,R,C,v):null;
    let extra='';
    if(cf){
      if(cf.bar){ const p=cf.bar.pct.toFixed(1); const col=cf.bar.color;
        const fillc=cf.bar.grad? 'linear-gradient(90deg,'+col+'cc,'+col+'66)' : col;
        extra += 'background:linear-gradient(90deg,'+ (cf.bar.grad?col:'') +' 0,'+col+' '+p+'%,transparent '+p+'%);';
      } else if(cf.bg){ extra+='background:'+cf.bg+';'; }
      if(cf.color) extra+='color:'+cf.color+';';
      if(cf.bold) extra+='font-weight:700;';
    }
    html+='<div class="cell'+(s&&s.wrap?' wrap':'')+(isErr(v)?' err':'')+(lnk?' lnk':'')+'"'
        + (lnk?' data-link="'+esc(lnk)+'"':'') + ' data-rc="'+R+','+C+'"'
        + ' style="left:'+tx(C)+'px;top:'+ty(R)+'px;width:'+W+'px;height:'+H+'px;'
        + (z?'z-index:'+(2+z)+';':'') + cellStyleCss(s,v) + extra + '">'+esc(txt)
        + (note?'<span class="noteflag"></span>':'') + '</div>';
  };
  for(const r of rows) for(const c of cols) cell(r,c);
  for(const m of S.merges){ if(!drawn.has(m.r1+':'+m.c1) && m.r2>=rows[0] && m.r1<=rows[rows.length-1]) cell(m.r1,m.c1); }
  cellsHost.innerHTML=html;

  /* headers */
  let ch='';
  for(const c of cols){
    const w=cw(c); if(!w) continue;
    const x=(c<S.fzC?0:-vp.scrollLeft)+colX[c];
    const on=c>=sb.c1&&c<=sb.c2;
    const full=on && sb.r1===0 && sb.r2>=S.nRows-1;
    ch+='<div class="hc'+(full?' full':on?' sel':'')+'" style="left:'+x+'px;width:'+w+'px'+(c<S.fzC?';z-index:2':'')+'">'+colName(c)+'</div>';
    ch+='<div class="hgrip c" data-c="'+c+'" style="left:'+(x+w-3)+'px"></div>';
  }
  hcols.innerHTML=ch;
  let rhh='';
  for(const r of rows){
    const h=rh(r); if(!h) continue;
    const y=(r<S.fzR?0:-vp.scrollTop)+rowY[r];
    const on=r>=sb.r1&&r<=sb.r2;
    const full=on && sb.c1===0 && sb.c2>=S.nCols-1;
    rhh+='<div class="hr'+(full?' full':on?' sel':'')+'" style="top:'+y+'px;height:'+h+'px'+(r<S.fzR?';z-index:2':'')+'">'+(r+1)+'</div>';
    rhh+='<div class="hgrip r" data-r="'+r+'" style="top:'+(y+h-3)+'px"></div>';
  }
  hrows.innerHTML=rhh;

  drawFilterArrows();
  drawCharts();
  drawOverlays();
  updateStatus();
}
function drawCharts(){
  const S=cur(), list=S.charts||[];
  const rebuild = (chartRenderGen!==dataGen || chartRenderSheet!==DOC.active);
  if(rebuild){
    chartHost.innerHTML='';
    list.forEach(ch=>{
      const el=document.createElement('div');
      el.className='chartobj'+(selectedChart===ch.id?' sel':'');
      el.dataset.id=ch.id;
      el.innerHTML='<div class="chead"><button class="cbtn" data-act="edit" title="Edit">✎</button>'
        +'<button class="cbtn" data-act="del" title="Delete">✕</button></div>'
        + svgChart(ch) + '<div class="cresize"></div>';
      chartHost.appendChild(el);
    });
    chartRenderGen=dataGen; chartRenderSheet=DOC.active;
  }
  // (re)position every render (cheap) so charts track zoom/scroll-content coords
  [...chartHost.children].forEach(el=>{
    const ch=list.find(c=>c.id==el.dataset.id); if(!ch){ el.remove(); return; }
    el.style.left=Math.round(ch.x*zoom)+'px'; el.style.top=Math.round(ch.y*zoom)+'px';
    el.style.width=Math.round(ch.w*zoom)+'px'; el.style.height=Math.round(ch.h*zoom)+'px';
    el.classList.toggle('sel',selectedChart===ch.id);
  });
}
function invalidateCharts(){ chartRenderGen=-1; }
function filterDisp(S,r,c){
  const x=S.cells[key(r,c)];
  if(!x||x.v===''||x.v==null) return '';
  return String(displayText(getVal(DOC.active,r,c), x.s&&x.s.fmt));
}
function drawFilterArrows(){
  const S=cur(), F=S.filter;
  if(!F){ filterHost.innerHTML=''; return; }
  const hr=F.hdr;
  if(rh(hr)===0){ filterHost.innerHTML=''; return; }
  let html='';
  for(let c=F.c1;c<=F.c2;c++){
    if(cw(c)===0) continue;
    const x=tx(c)+cw(c)-17, y=ty(hr)+3;
    const active=!!(F.crit && F.crit[c]);
    html+='<div class="filter-arrow'+(active?' on':'')+'" data-col="'+c+'" style="pointer-events:auto;left:'+x+'px;top:'+y+'px">'
      + (active
         ? '<svg viewBox="0 0 12 12" fill="currentColor"><path d="M1 2h10L7 7v4L5 10V7z"/></svg>'
         : '<svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M3 4.5l3 3 3-3"/></svg>')
      + '</div>';
  }
  filterHost.innerHTML=html;
}

function rectOf(r1,c1,r2,c2){
  const S=cur();
  r2=Math.min(r2,S.nRows-1); c2=Math.min(c2,S.nCols-1);
  const x=tx(c1), y=ty(r1);
  return {x,y,w:colX[c2+1]-colX[c1],h:rowY[r2+1]-rowY[r1]};
}
function drawOverlays(){
  const S=cur(); const sb=selBox();
  let er=sb.r1,ec=sb.c1,er2=sb.r2,ec2=sb.c2;
  const m0=mergeOf(S,sel.r1,sel.c1);
  const R=rectOf(er,ec,er2,ec2);
  selbox.style.cssText='position:absolute;left:'+R.x+'px;top:'+R.y+'px;width:'+R.w+'px;height:'+R.h+'px;'
    +(sb.r1===sb.r2&&sb.c1===sb.c2?'display:none':'');
  let ar=sel.r1,ac=sel.c1;
  const am=mergeOf(S,ar,ac);
  const A=am?rectOf(am.r1,am.c1,am.r2,am.c2):rectOf(ar,ac,ar,ac);
  activebox.style.cssText='position:absolute;left:'+A.x+'px;top:'+A.y+'px;width:'+A.w+'px;height:'+A.h+'px';
  fillh.style.cssText='position:absolute;left:'+(R.x+R.w-4)+'px;top:'+(R.y+R.h-4)+'px';
  if(clip && clip.marching){
    const K=rectOf(clip.r1,clip.c1,clip.r2,clip.c2);
    cutbox.style.cssText='position:absolute;display:block;left:'+K.x+'px;top:'+K.y+'px;width:'+K.w+'px;height:'+K.h+'px';
  } else cutbox.style.display='none';
}

function updateStatus(){
  const sb=selBox(), S=cur();
  $('stCell').textContent = (sb.r1===sb.r2&&sb.c1===sb.c2)? a1(sb.r1,sb.c1)
    : a1(sb.r1,sb.c1)+':'+a1(sb.r2,sb.c2)+'  ('+(sb.r2-sb.r1+1)+'R × '+(sb.c2-sb.c1+1)+'C)';
  if(!editing) $('namebox').value = (sb.r1===sb.r2&&sb.c1===sb.c2)? a1(sb.r1,sb.c1) : a1(sb.r1,sb.c1)+':'+a1(sb.r2,sb.c2);
  const nums=[]; let count=0;
  const lim=Math.min((sb.r2-sb.r1+1)*(sb.c2-sb.c1+1), 200000);
  let seen=0;
  for(let r=sb.r1;r<=sb.r2&&seen<lim;r++) for(let c=sb.c1;c<=sb.c2&&seen<lim;c++){
    seen++;
    const v=getVal(DOC.active,r,c);
    if(v===null||v==='') continue;
    count++;
    if(typeof v==='number') nums.push(v);
  }
  let s='';
  if(nums.length){
    const t=sum(nums);
    s='Sum <b>'+genNum(t)+'</b>   Average <b>'+genNum(t/nums.length)+'</b>   Min <b>'+genNum(Math.min(...nums))+'</b>   Max <b>'+genNum(Math.max(...nums))+'</b>   ';
  }
  if(count) s+='Count <b>'+count+'</b>';
  $('stAgg').innerHTML=s;
  const cellObj=S.cells[key(sel.r1,sel.c1)];
  if(!editing) $('fbin').value = cellObj? String(cellObj.v) : '';
  syncToolbar();
}
/* ---------- 4. STATE CHANGES & HISTORY ---------- */
let undoStack=[], redoStack=[], clip=null, painter=null;

/* ---------- charts ---------- */
const CHART_COLORS=['#2b7a63','#c9591b','#2c6ea8','#8a5a9e','#b28900','#4a8a2f','#c04663','#3aa0a0','#7a6cc4','#9c7b3a'];
let chartSeq=1;
function chartData(rng){
  const {r1,c1,r2,c2}=rng;
  const grid=[];
  for(let r=r1;r<=r2;r++){ const row=[]; for(let c=c1;c<=c2;c++) row.push(getVal(DOC.active,r,c)); grid.push(row); }
  const nR=grid.length, nC=grid[0].length;
  const isTxt=v=>typeof v==='string'&&v!=='', isNum=v=>typeof v==='number';
  const mostlyText=arr=>{ let t=0,n=0; arr.forEach(v=>{ if(isTxt(v))t++; else if(isNum(v))n++; }); return t>n; };
  const corner=grid[0][0];
  const col0=grid.slice(1).map(r=>r[0]);          // first column below row 0
  const row0=grid[0].slice(1);                     // first row right of col 0
  const rowHeader = nC>1 && mostlyText(col0);       // first column = category labels
  let colHeader = nR>1 && ( mostlyText(row0) || ((isTxt(corner)||corner===null) && rowHeader) );
  // plain two-column list (labels + one numeric column, no real header): keep the first row as data
  const _c0 = rowHeader?1:0;
  if(colHeader && (nC-_c0)===1 && isNum(grid[0][_c0])) colHeader=false;
  const cats=[], series=[];
  const c0 = rowHeader?1:0, r0 = colHeader?1:0;
  const sc = nC-c0;
  for(let j=0;j<sc;j++){
    const name = colHeader? String(grid[0][c0+j]??('Series '+(j+1))) : ('Series '+(j+1));
    series.push({name, values:[]});
  }
  for(let i=r0;i<nR;i++){
    cats.push(rowHeader? String(grid[i][0]??'') : String(i-r0+1));
    for(let j=0;j<sc;j++){ const v=grid[i][c0+j]; series[j].values.push(typeof v==='number'?v:(v===true?1:(v===false?0:null))); }
  }
  return {cats,series};
}
function niceTicks(min,max,n){
  if(min===max){ if(min===0) return {lo:0,hi:1,step:0.25}; min=Math.min(0,min); max=Math.max(0,max*1.2||1); }
  const span=max-min, raw=span/n, mag=Math.pow(10,Math.floor(Math.log10(raw)));
  const norm=raw/mag, step=(norm<1.5?1:norm<3?2:norm<7?5:10)*mag;
  const lo=Math.floor(min/step)*step, hi=Math.ceil(max/step)*step;
  return {lo,hi,step};
}
function fmtTick(v){ if(Math.abs(v)>=1e6) return (v/1e6)+'M'; if(Math.abs(v)>=1e3) return (v/1e3)+'k';
  return (Math.round(v*100)/100).toString(); }
function svgChart(ch){
  const d=chartData(ch.range);
  const W=ch.w, H=ch.h, pad={l:44,r:12,t:ch.title?30:12,b:38};
  const legendH = (d.series.length>1 || ch.type==='pie')? 20:0;
  const plotW=W-pad.l-pad.r, plotH=H-pad.t-pad.b-legendH;
  let g='';
  const esc2=s=>String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  if(ch.title) g+='<text x="'+(W/2)+'" y="18" text-anchor="middle" font-size="13" font-weight="600" fill="#1b2027">'+esc2(ch.title)+'</text>';

  if(ch.type==='pie'){
    const ser=d.series[0]||{values:[]};
    const vals=ser.values.map(v=>Math.max(0,v||0));
    const tot=vals.reduce((a,b)=>a+b,0)||1;
    const cx=pad.l+plotW/2, cy=pad.t+plotH/2, rad=Math.min(plotW,plotH)/2-4;
    let ang=-Math.PI/2;
    vals.forEach((v,i)=>{ const a2=ang+v/tot*Math.PI*2;
      const x1=cx+rad*Math.cos(ang), y1=cy+rad*Math.sin(ang), x2=cx+rad*Math.cos(a2), y2=cy+rad*Math.sin(a2);
      const large=(a2-ang)>Math.PI?1:0;
      g+='<path d="M'+cx+' '+cy+' L'+x1.toFixed(1)+' '+y1.toFixed(1)+' A'+rad+' '+rad+' 0 '+large+' 1 '+x2.toFixed(1)+' '+y2.toFixed(1)+' Z" fill="'+CHART_COLORS[i%CHART_COLORS.length]+'" stroke="#fff" stroke-width="1"/>';
      ang=a2; });
    d.cats.forEach((c,i)=>{ const y=pad.t+plotH+8+i*0; });
    // legend = categories
    let lx=pad.l, ly=H-legendH+4;
    d.cats.forEach((c,i)=>{ if(lx>W-60){return;} g+='<rect x="'+lx+'" y="'+ly+'" width="10" height="10" fill="'+CHART_COLORS[i%CHART_COLORS.length]+'"/>'
      +'<text x="'+(lx+14)+'" y="'+(ly+9)+'" font-size="10" fill="#4a5560">'+esc2(c)+'</text>'; lx+=Math.max(50, esc2(c).length*6+24); });
    return '<svg viewBox="0 0 '+W+' '+H+'" xmlns="http://www.w3.org/2000/svg">'+g+'</svg>';
  }

  if(ch.type==='scatter'){
    const xs=d.series[0]?d.series[0].values:[], ys=d.series[1]?d.series[1].values:d.series[0].values;
    const xt=niceTicks(Math.min(...xs.filter(isFinite),0),Math.max(...xs.filter(isFinite),1),5);
    const yt=niceTicks(Math.min(...ys.filter(isFinite),0),Math.max(...ys.filter(isFinite),1),5);
    const X=v=>pad.l+(v-xt.lo)/(xt.hi-xt.lo)*plotW, Y=v=>pad.t+plotH-(v-yt.lo)/(yt.hi-yt.lo)*plotH;
    for(let t=yt.lo;t<=yt.hi+1e-9;t+=yt.step){ const y=Y(t); g+='<line x1="'+pad.l+'" y1="'+y+'" x2="'+(pad.l+plotW)+'" y2="'+y+'" stroke="#e4e6e1"/>'
      +'<text x="'+(pad.l-6)+'" y="'+(y+3)+'" text-anchor="end" font-size="10" fill="#7b8794">'+fmtTick(t)+'</text>'; }
    for(let t=xt.lo;t<=xt.hi+1e-9;t+=xt.step){ const x=X(t); g+='<text x="'+x+'" y="'+(pad.t+plotH+14)+'" text-anchor="middle" font-size="10" fill="#7b8794">'+fmtTick(t)+'</text>'; }
    xs.forEach((xv,i)=>{ const yv=ys[i]; if(!isFinite(xv)||!isFinite(yv))return; g+='<circle cx="'+X(xv).toFixed(1)+'" cy="'+Y(yv).toFixed(1)+'" r="3.5" fill="'+CHART_COLORS[0]+'" opacity="0.85"/>'; });
    return '<svg viewBox="0 0 '+W+' '+H+'" xmlns="http://www.w3.org/2000/svg">'+g+'</svg>';
  }

  // column / bar / line / area
  const allV=[]; d.series.forEach(s=>s.values.forEach(v=>{ if(typeof v==='number') allV.push(v); }));
  const dmin=Math.min(0,...allV), dmax=Math.max(0,...(allV.length?allV:[1]));
  const horiz = ch.type==='bar';
  const t=niceTicks(dmin,dmax,5);
  const n=d.cats.length, ns=d.series.length;
  if(!horiz){
    const X=v=>pad.l+(v)/(n)*plotW, Y=v=>pad.t+plotH-(v-t.lo)/(t.hi-t.lo)*plotH;
    for(let tk=t.lo;tk<=t.hi+1e-9;tk+=t.step){ const y=Y(tk); g+='<line x1="'+pad.l+'" y1="'+y.toFixed(1)+'" x2="'+(pad.l+plotW)+'" y2="'+y.toFixed(1)+'" stroke="#e4e6e1"/>'
      +'<text x="'+(pad.l-6)+'" y="'+(y+3).toFixed(1)+'" text-anchor="end" font-size="10" fill="#7b8794">'+fmtTick(tk)+'</text>'; }
    const bw=plotW/n, gap=bw*0.18, innerW=(bw-2*gap), sw=innerW/ns;
    d.cats.forEach((c,i)=>{ const cxx=pad.l+bw*i+bw/2;
      g+='<text x="'+cxx.toFixed(1)+'" y="'+(pad.t+plotH+14)+'" text-anchor="middle" font-size="10" fill="#4a5560">'+esc2(c.length>10?c.slice(0,9)+'…':c)+'</text>'; });
    if(ch.type==='line'||ch.type==='area'){
      d.series.forEach((s,si)=>{ const col=CHART_COLORS[si%CHART_COLORS.length];
        let pts=s.values.map((v,i)=> (typeof v==='number')? ((pad.l+bw*i+bw/2).toFixed(1)+','+Y(v).toFixed(1)):null).filter(Boolean);
        if(ch.type==='area'&&pts.length){ const y0=Y(t.lo<0?0:t.lo);
          g+='<polygon points="'+(pad.l+bw*0+bw/2).toFixed(1)+','+y0.toFixed(1)+' '+pts.join(' ')+' '+(pad.l+bw*(s.values.length-1)+bw/2).toFixed(1)+','+y0.toFixed(1)+'" fill="'+col+'" opacity="0.18"/>'; }
        g+='<polyline points="'+pts.join(' ')+'" fill="none" stroke="'+col+'" stroke-width="2" stroke-linejoin="round"/>';
        s.values.forEach((v,i)=>{ if(typeof v==='number') g+='<circle cx="'+(pad.l+bw*i+bw/2).toFixed(1)+'" cy="'+Y(v).toFixed(1)+'" r="2.5" fill="'+col+'"/>'; });
      });
    } else {
      d.series.forEach((s,si)=>{ const col=CHART_COLORS[si%CHART_COLORS.length];
        s.values.forEach((v,i)=>{ if(typeof v!=='number')return; const x=pad.l+bw*i+gap+sw*si; const y=Y(Math.max(v,t.lo<0?0:t.lo)); const yb=Y(0<t.lo?t.lo:0);
          const top=Math.min(y,yb), hh=Math.abs(y-yb);
          g+='<rect x="'+x.toFixed(1)+'" y="'+top.toFixed(1)+'" width="'+Math.max(1,sw-1).toFixed(1)+'" height="'+hh.toFixed(1)+'" fill="'+col+'"/>'; });
      });
    }
    const axisY=Y(0<t.lo?t.lo:0);
    g+='<line x1="'+pad.l+'" y1="'+axisY.toFixed(1)+'" x2="'+(pad.l+plotW)+'" y2="'+axisY.toFixed(1)+'" stroke="#b0b7bd"/>';
  } else {
    const Y=v=>pad.t+plotH*(v)/n, X=v=>pad.l+(v-t.lo)/(t.hi-t.lo)*plotW;
    for(let tk=t.lo;tk<=t.hi+1e-9;tk+=t.step){ const x=X(tk); g+='<line x1="'+x.toFixed(1)+'" y1="'+pad.t+'" x2="'+x.toFixed(1)+'" y2="'+(pad.t+plotH)+'" stroke="#e4e6e1"/>'
      +'<text x="'+x.toFixed(1)+'" y="'+(pad.t+plotH+14)+'" text-anchor="middle" font-size="10" fill="#7b8794">'+fmtTick(tk)+'</text>'; }
    const bh=plotH/n, gap=bh*0.18, innerH=(bh-2*gap), sh=innerH/ns;
    d.cats.forEach((c,i)=>{ const cyy=pad.t+bh*i+bh/2;
      g+='<text x="'+(pad.l-6)+'" y="'+(cyy+3).toFixed(1)+'" text-anchor="end" font-size="10" fill="#4a5560">'+esc2(c.length>8?c.slice(0,7)+'…':c)+'</text>'; });
    d.series.forEach((s,si)=>{ const col=CHART_COLORS[si%CHART_COLORS.length];
      s.values.forEach((v,i)=>{ if(typeof v!=='number')return; const y=pad.t+bh*i+gap+sh*si; const x0=X(0<t.lo?t.lo:0), x1=X(v);
        g+='<rect x="'+Math.min(x0,x1).toFixed(1)+'" y="'+y.toFixed(1)+'" width="'+Math.abs(x1-x0).toFixed(1)+'" height="'+Math.max(1,sh-1).toFixed(1)+'" fill="'+col+'"/>'; }); });
    g+='<line x1="'+X(0<t.lo?t.lo:0).toFixed(1)+'" y1="'+pad.t+'" x2="'+X(0<t.lo?t.lo:0).toFixed(1)+'" y2="'+(pad.t+plotH)+'" stroke="#b0b7bd"/>';
  }
  if(legendH){ let lx=pad.l, ly=H-legendH+4;
    d.series.forEach((s,si)=>{ g+='<rect x="'+lx+'" y="'+ly+'" width="10" height="10" fill="'+CHART_COLORS[si%CHART_COLORS.length]+'"/>'
      +'<text x="'+(lx+14)+'" y="'+(ly+9)+'" font-size="10" fill="#4a5560">'+esc2(s.name)+'</text>'; lx+=Math.max(56,esc2(s.name).length*6+26); }); }
  return '<svg viewBox="0 0 '+W+' '+H+'" xmlns="http://www.w3.org/2000/svg">'+g+'</svg>';
}

/* ---------- pivot tables ---------- */
const PIVOT_AGGS={
  sum:{label:'Sum', f:vs=>{ const n=vs.filter(v=>typeof v==='number'); return n.reduce((a,b)=>a+b,0); }, fmt:{t:'comma',d:0}},
  count:{label:'Count', f:vs=>vs.filter(v=>v!==null&&v!==''&&!isErr(v)).length, fmt:{t:'number',d:0}},
  countnum:{label:'Count numbers', f:vs=>vs.filter(v=>typeof v==='number').length, fmt:{t:'number',d:0}},
  avg:{label:'Average', f:vs=>{ const n=vs.filter(v=>typeof v==='number'); return n.length? n.reduce((a,b)=>a+b,0)/n.length : null; }, fmt:{t:'number',d:2}},
  min:{label:'Min', f:vs=>{ const n=vs.filter(v=>typeof v==='number'); return n.length?Math.min(...n):null; }, fmt:{t:'comma',d:0}},
  max:{label:'Max', f:vs=>{ const n=vs.filter(v=>typeof v==='number'); return n.length?Math.max(...n):null; }, fmt:{t:'comma',d:0}}
};
function pivotKeyStr(v){ if(v===null||v==='') return '\u0000(blank)'; return (typeof v==='number')?('n'+v):('s'+String(v)); }
function pivotDisp(v){ return (v===null||v==='')?'(blank)':v; }
function pivotSortKeys(keys){
  return keys.sort((a,b)=>{
    const A=a.v,B=b.v;
    if(A===null&&B===null) return 0; if(A===null) return 1; if(B===null) return -1;
    if(typeof A==='number'&&typeof B==='number') return A-B;
    return String(A).localeCompare(String(B),undefined,{numeric:true,sensitivity:'base'});
  });
}
function computePivot(def){
  const si=sheetIndexByName(def.srcName);
  if(si<0) return {error:'Source sheet "'+def.srcName+'" not found'};
  const {r1,c1,r2,c2}=def;
  const header=c=>{ const v=getVal(si,r1,c); return (v===null||v==='')? colName(c) : String(v); };
  const rowF=def.rowFields||[], colF=(def.colField!=null?def.colField:null), valF=def.valFields||[];
  if(!valF.length) return {error:'Add at least one value field'};
  // gather records
  const recs=[];
  for(let r=r1+1;r<=r2;r++){
    let blank=true; const rowVals={};
    for(let c=c1;c<=c2;c++){ const v=getVal(si,r,c); rowVals[c]=v; if(v!==null&&v!=='') blank=false; }
    if(!blank) recs.push(rowVals);
  }
  // distinct row keys (tuples) and col keys
  const rowMap=new Map();
  recs.forEach((rec,idx)=>{
    const parts=rowF.map(c=>rec[c]); const ks=parts.map(pivotKeyStr).join('\u0001');
    if(!rowMap.has(ks)) rowMap.set(ks,{parts,key:ks,idx:[]});
    rowMap.get(ks).idx.push(idx);
  });
  let rowKeys=[...rowMap.values()];
  if(rowF.length){ // sort by each level
    rowKeys.sort((a,b)=>{ for(let i=0;i<rowF.length;i++){ const A=a.parts[i],B=b.parts[i];
      let d; if(A===null&&B===null)d=0; else if(A===null)d=1; else if(B===null)d=-1;
      else if(typeof A==='number'&&typeof B==='number')d=A-B; else d=String(A).localeCompare(String(B),undefined,{numeric:true,sensitivity:'base'});
      if(d)return d; } return 0; });
  } else rowKeys=[{parts:[],key:'',idx:recs.map((_,i)=>i)}];
  let colKeys=[];
  if(colF!=null){ const cm=new Map();
    recs.forEach((rec,idx)=>{ const v=rec[colF]; const ks=pivotKeyStr(v);
      if(!cm.has(ks)) cm.set(ks,{v,key:ks,idx:[]}); cm.get(ks).idx.push(idx); });
    colKeys=pivotSortKeys([...cm.values()]);
  }
  // aggregation helper over a set of record indices
  const aggAt=(idxArr, valField)=>{ const vs=idxArr.map(i=>recs[i][valField.c]); return PIVOT_AGGS[valField.agg].f(vs); };
  const inter=(a,b)=>{ const sb=new Set(b); return a.filter(x=>sb.has(x)); };

  // ---- build output matrix of {v,s} ----
  const HDR={b:true,bg:'#e2f1ec',color:'#0e6a55'};
  const HDRR={b:true,bg:'#eef4f2'};
  const GT={b:true,bt:'#5b6470'};
  const nRowF=Math.max(rowF.length,1), nVal=valF.length;
  const hasCol=colF!=null;
  const twoRow = hasCol && nVal>1;
  const out=[]; const put=(r,c,v,st)=>{ (out[r]=out[r]||[])[c]={v:(v==null?'':v),s:st||null}; };

  // corner text
  const cornerTxt = (nVal===1)? (PIVOT_AGGS[valF[0].agg].label+' of '+header(valF[0].c)) : 'Values';

  // column layout
  const groups = hasCol ? colKeys.concat([{grand:true}]) : [{single:true}];
  const dataStartCol=nRowF;
  const headRows = twoRow?2:1;

  // headers
  if(twoRow){
    // row A: group labels; row B: value names
    put(0,0,cornerTxt,HDR);
    for(let i=1;i<nRowF;i++) put(0,i,'',HDR);
    rowF.forEach((c,i)=>put(1,i,header(c),HDR));
    let cc=dataStartCol;
    groups.forEach(g=>{ const lbl=g.grand?'Grand Total':String(pivotDisp(g.v));
      put(0,cc,lbl,HDR); for(let k=1;k<nVal;k++) put(0,cc+k,'',HDR);
      valF.forEach((vf,k)=>put(1,cc+k,PIVOT_AGGS[vf.agg].label+' of '+header(vf.c),HDR)); cc+=nVal; });
  } else {
    // single header row
    if(rowF.length) rowF.forEach((c,i)=>put(0,i,header(c),HDR)); else put(0,0,'',HDR);
    let cc=dataStartCol;
    if(hasCol){ // one col per colKey (nVal===1) + grand total
      colKeys.forEach(g=>{ put(0,cc,String(pivotDisp(g.v)),HDR); cc++; });
      put(0,cc,'Grand Total',HDR);
    } else { valF.forEach(vf=>{ put(0,cc,PIVOT_AGGS[vf.agg].label+' of '+header(vf.c),HDR); cc++; }); }
  }

  // data rows
  let rr=headRows;
  rowKeys.forEach(rk=>{
    // row labels
    rowF.forEach((c,i)=>{ put(rr,i, (rk.parts[i]===null||rk.parts[i]==='')?'(blank)':rk.parts[i], HDRR); });
    if(!rowF.length) put(rr,0,'Total',HDRR);
    let cc=dataStartCol;
    if(hasCol){
      colKeys.forEach(g=>{ const idx=inter(rk.idx,g.idx);
        valF.slice(0,nVal).forEach((vf,k)=>{ const val=aggAt(idx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt}); });
        cc+=nVal; });
      // grand total column (all colKeys for this rowKey = rk.idx)
      valF.forEach((vf,k)=>{ const val=aggAt(rk.idx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt,b:true}); });
    } else {
      valF.forEach((vf,k)=>{ const val=aggAt(rk.idx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt}); });
    }
    rr++;
  });

  // grand total row
  const allIdx=recs.map((_,i)=>i);
  rowF.forEach((c,i)=>put(rr,i, i===0?'Grand Total':'', GT));
  if(!rowF.length) put(rr,0,'Grand Total',GT);
  let cc=dataStartCol;
  if(hasCol){
    colKeys.forEach(g=>{ valF.slice(0,nVal).forEach((vf,k)=>{ const val=aggAt(g.idx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt,b:true,bt:'#5b6470'}); }); cc+=nVal; });
    valF.forEach((vf,k)=>{ const val=aggAt(allIdx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt,b:true,bt:'#5b6470'}); });
  } else {
    valF.forEach((vf,k)=>{ const val=aggAt(allIdx,vf); put(rr,cc+k,val,{fmt:PIVOT_AGGS[vf.agg].fmt,b:true,bt:'#5b6470'}); });
  }

  const nCols = dataStartCol + (hasCol? (colKeys.length*nVal + (twoRow?nVal:1)) : nVal);
  return {matrix:out, rows:rr+1, cols:nCols, colWidths:{0:120}};
}
function refreshPivot(S){
  if(!S.pivot) return;
  const res=computePivot(S.pivot);
  S.cells=Object.create(null);              // pivot sheet is dedicated to its output
  if(res.error){ ensure(S,0,0).v=res.error; ensure(S,0,0).s={color:'#a52626',b:true}; S.pivot.extent={r:1,c:1}; return; }
  const m=res.matrix;
  for(let r=0;r<m.length;r++){ const row=m[r]||[]; for(let c=0;c<row.length;c++){ const cell=row[c]; if(!cell) continue;
    const x=ensure(S,r,c); x.v=(cell.v==null?'':String(cell.v)); x.s=cell.s||null; } }
  S.nRows=Math.max(S.nRows, res.rows+5); S.nCols=Math.max(S.nCols, res.cols+3);
  S.colW[0]=Math.max(S.colW[0]||0,130);
  S.pivot.extent={r:res.rows,c:res.cols};
}

function serialize(){
  return JSON.stringify({v:1,name:DOC.name,active:DOC.active,sel:sel,
    sheets:DOC.sheets.map(S=>({name:S.name,cells:S.cells,colW:S.colW,rowH:S.rowH,hiddenC:S.hiddenC,hiddenR:S.hiddenR,
      fhR:S.fhR,nRows:S.nRows,nCols:S.nCols,fzR:S.fzR,fzC:S.fzC,merges:S.merges,filter:S.filter,cf:S.cf||[],charts:S.charts||[],pivot:S.pivot||null}))});
}
function deserialize(txt){
  const o=JSON.parse(txt);
  DOC={name:o.name||'Untitled workbook',active:o.active||0,
    sheets:(o.sheets||[]).map(s=>Object.assign(newSheet(s.name||'Sheet'),s,{cells:Object.assign(Object.create(null),s.cells||{})}))};
  if(!DOC.sheets.length) DOC.sheets=[newSheet('Sheet1')];
  DOC.active=clamp(DOC.active,0,DOC.sheets.length-1);
  DOC.sheets.forEach(S=>{ if(!S.fhR) S.fhR={}; if(S.filter===undefined) S.filter=null; if(!S.cf) S.cf=[]; if(!S.charts) S.charts=[]; if(S.pivot===undefined) S.pivot=null; });
  if(o.sel) sel=o.sel;
  astCache.clear();
  const _a=DOC.active; DOC.sheets.forEach((_,i)=>{ DOC.active=i; applyFilters(); }); DOC.active=_a;
}
function snap(){ undoStack.push(serialize()); if(undoStack.length>100) undoStack.shift(); redoStack.length=0; dirty=true; }
function undo(){ if(!undoStack.length){toast('Nothing to undo');return;} redoStack.push(serialize()); deserialize(undoStack.pop()); after(); }
function redo(){ if(!redoStack.length){toast('Nothing to redo');return;} undoStack.push(serialize()); deserialize(redoStack.pop()); after(); }
let dataGen=0;
function after(){ dataGen++; recalc(); buildTabs(); render(); if(typeof onWorkbookChange==='function') onWorkbookChange(); }

function setFmt(cell,f){ cell.s=cell.s||{}; cell.s.fmt=f; }
function setCellInput(S,r,c,text){
  const cell=ensure(S,r,c);
  text=(text==null)?'':String(text);
  if(text===''){ cell.v=''; return; }
  if(text[0]==='='){ cell.v=text; return; }
  const cf=cell.s&&cell.s.fmt?cell.s.fmt.t:'general';
  if(cf==='text'){ cell.v=text; return; }
  const t=text.trim(); let m;
  if(/^-?[\d,]*\.?\d+([eE][+-]?\d+)?$/.test(t)&&/\d/.test(t)){
    cell.v=String(parseFloat(t.replace(/,/g,'')));
    if(t.indexOf(',')>=0&&cf==='general') setFmt(cell,{t:'comma',d:(t.split('.')[1]||'').length});
    return;
  }
  if(m=/^(-?)([\d,]*\.?\d+)\s*%$/.exec(t)){
    cell.v=String(parseFloat((m[1]+m[2]).replace(/,/g,''))/100);
    if(cf==='general') setFmt(cell,{t:'percent',d:(m[2].split('.')[1]||'').length});
    return;
  }
  if(m=/^(-?)\s*([$£€¥₹])\s*([\d,]*\.?\d+)$/.exec(t)){
    cell.v=String((m[1]==='-'?-1:1)*parseFloat(m[3].replace(/,/g,'')));
    if(cf==='general'){ const sym=m[2]; const code=Object.keys(CURSYM).find(k=>CURSYM[k]===sym)||'USD';
      setFmt(cell,{t:'currency',d:(m[3].split('.')[1]||'').length||2,cur:code}); }
    return;
  }
  const d=parseDateString(t);
  if(d!==null&&!/^\d+$/.test(t)){
    cell.v=String(d);
    if(cf==='general'){
      if(d<1) setFmt(cell,{t:'time'});
      else if(Math.floor(d)!==d) setFmt(cell,{t:'datetime'});
      else setFmt(cell,{t:'date',pat:/^\d{4}-/.test(t)?'yyyy-mm-dd':'m/d/yyyy'});
    }
    return;
  }
  cell.v=text;
}
function growTo(r,c){
  const S=cur();
  if(r>=S.nRows) S.nRows=Math.min(r+50,1048576);
  if(c>=S.nCols) S.nCols=Math.min(c+10,16384);
}

/* ---------- selection helpers ---------- */
function setSel(r1,c1,r2,c2){
  const S=cur();
  r1=clamp(r1,0,S.nRows-1); c1=clamp(c1,0,S.nCols-1);
  r2=clamp(r2==null?r1:r2,0,S.nRows-1); c2=clamp(c2==null?c1:c2,0,S.nCols-1);
  sel={r1,c1,r2,c2};
}
function moveTo(r,c,extend){
  const S=cur();
  growTo(r,c);
  if(extend){ sel.r2=clamp(r,0,S.nRows-1); sel.c2=clamp(c,0,S.nCols-1); }
  else setSel(r,c);
  scrollIntoView(extend?sel.r2:sel.r1, extend?sel.c2:sel.c1);
  render();
}
function scrollIntoView(r,c){
  const S=cur(); geom();
  const fzW=colX[S.fzC]||0, fzH=rowY[S.fzR]||0;
  const x1=colX[c], x2=colX[c+1], y1=rowY[r], y2=rowY[r+1];
  if(c>=S.fzC){
    if(x1 < vp.scrollLeft+fzW) vp.scrollLeft = x1-fzW;
    else if(x2 > vp.scrollLeft+vp.clientWidth) vp.scrollLeft = x2-vp.clientWidth;
  }
  if(r>=S.fzR){
    if(y1 < vp.scrollTop+fzH) vp.scrollTop = y1-fzH;
    else if(y2 > vp.scrollTop+vp.clientHeight) vp.scrollTop = y2-vp.clientHeight;
  }
}
function nextNonBlank(r,c,dr,dc){
  const S=cur();
  const has=(rr,cc)=>{ const x=S.cells[key(rr,cc)]; return x && x.v!=='' && x.v!=null; };
  let rr=r+dr, cc=c+dc;
  if(!has(rr,cc)){
    while(rr>=0&&cc>=0&&rr<S.nRows&&cc<S.nCols&&!has(rr,cc)){ rr+=dr; cc+=dc; }
    if(rr<0||cc<0||rr>=S.nRows||cc>=S.nCols){ rr-=dr; cc-=dc; }
  } else {
    while(rr+dr>=0&&cc+dc>=0&&rr+dr<S.nRows&&cc+dc<S.nCols&&has(rr+dr,cc+dc)){ rr+=dr; cc+=dc; }
  }
  return [clamp(rr,0,S.nRows-1),clamp(cc,0,S.nCols-1)];
}

/* ---------- editing ---------- */
function startEdit(initial){
  const S=cur(), r=sel.r1, c=sel.c1;
  const m=mergeOf(S,r,c);
  const R=m?rectOf(m.r1,m.c1,m.r2,m.c2):rectOf(r,c,r,c);
  const cell=S.cells[key(r,c)];
  editing=true; endPoint();
  editor.value = initial!=null? initial : (cell? String(cell.v):'');
  const s=cell&&cell.s;
  editor.style.display='block';
  editor.style.left=R.x+'px'; editor.style.top=R.y+'px';
  editor.style.minWidth=Math.max(R.w,60)+'px'; editor.style.width=Math.max(R.w,60)+'px';
  editor.style.height=Math.max(R.h,20)+'px';
  editor.style.fontSize=((s&&s.fs?s.fs:13)*zoom)+'px';
  editor.style.fontWeight=(s&&s.b)?'700':'400';
  editor.style.fontStyle=(s&&s.i)?'italic':'normal';
  editor.style.fontFamily=(s&&s.ff)||'var(--ui)';
  editor.style.textAlign=(s&&s.ha)||'left';
  $('stMode').textContent = initial!=null?'Enter':'Edit';
  editor.focus();
  if(initial==null) editor.select();
  else { editor.selectionStart=editor.selectionEnd=editor.value.length; }
  autoSizeEditor();
}
function autoSizeEditor(){
  editor.style.height='auto';
  editor.style.height=Math.max(editor.scrollHeight, rh(sel.r1))+'px';
}
function commitEdit(dr,dc){
  if(!editing) return;
  if(editor.style.display==='none'){ editing=false; $('stMode').textContent=''; return; }
  const S=cur(), r=sel.r1, c=sel.c1;
  const before=S.cells[key(r,c)];
  const val=editor.value;
  if(!before || String(before.v)!==val){ snap(); setCellInput(S,r,c,val); }
  endPoint(); editing=false; editor.style.display='none'; $('stMode').textContent='';
  vp.focus();
  recalc();
  if(dr||dc) moveTo(r+(dr||0),c+(dc||0),false); else render();
  if(typeof onWorkbookChange==='function') onWorkbookChange();
}
function cancelEdit(){ endPoint(); editing=false; editor.style.display='none'; $('stMode').textContent=''; vp.focus(); render(); }

/* ---------- formula "point" mode: click/drag a cell to insert its reference ---------- */
let pointRef=null, pointAnchor=null;
function pointField(){
  const ae=document.activeElement;
  if(ae===editor && editing && editor.style.display!=='none' && editor.value[0]==='=') return editor;
  if(ae===$('fbin') && $('fbin').value[0]==='=') return $('fbin');
  return null;
}
function pointCaretOK(field){
  if(!field || field.value[0]!=='=') return false;
  if(pointRef) return true;                       /* replace the ref we just pointed at */
  const p=field.selectionStart;
  if(p<=0) return false;
  return /[=+\-*/^&(,<>%: \t\n]/.test(field.value[p-1]);
}
function refFor(r1,c1,r2,c2){
  const a=colName(c1)+(r1+1);
  return (r1===r2&&c1===c2)? a : a+':'+colName(c2)+(r2+1);
}
function applyPoint(field,ar,ac,fr,fc){
  const r1=Math.min(ar,fr),r2=Math.max(ar,fr),c1=Math.min(ac,fc),c2=Math.max(ac,fc);
  const refStr=refFor(r1,c1,r2,c2);
  let start,end;
  if(pointRef){ start=pointRef.start; end=pointRef.end; }
  else { start=field.selectionStart; end=field.selectionEnd; }
  field.value=field.value.slice(0,start)+refStr+field.value.slice(end);
  pointRef={start,end:start+refStr.length};
  if(document.activeElement!==field) field.focus();
  try{ field.selectionStart=field.selectionEnd=pointRef.end; }catch(_){}
  if(field===editor){ autoSizeEditor(); $('fbin').value=field.value; }
  const R=rectOf(r1,c1,r2,c2);
  pointbox.style.cssText='position:absolute;display:block;left:'+R.x+'px;top:'+R.y+'px;width:'+R.w
    +'px;height:'+R.h+'px;border:1.5px dashed var(--accent);background:rgba(14,106,85,.10);pointer-events:none;z-index:24';
  $('stMode').textContent='Point';
}
function endPoint(){ pointRef=null; pointAnchor=null; if(pointbox) pointbox.style.display='none'; }

/* ---------- hit testing ---------- */
function hitCell(clientX,clientY){
  const S=cur(), R=vp.getBoundingClientRect();
  const px=clientX-R.left, py=clientY-R.top;
  const fzW=colX[S.fzC]||0, fzH=rowY[S.fzR]||0;
  const c=idxAt(colX, px<fzW?px:px+vp.scrollLeft, S.nCols);
  const r=idxAt(rowY, py<fzH?py:py+vp.scrollTop, S.nRows);
  return [clamp(r,0,S.nRows-1),clamp(c,0,S.nCols-1)];
}
function hitColHeader(clientX){
  const S=cur(), R=hcols.getBoundingClientRect();
  const px=clientX-R.left, fzW=colX[S.fzC]||0;
  return clamp(idxAt(colX, px<fzW?px:px+vp.scrollLeft, S.nCols),0,S.nCols-1);
}
function hitRowHeader(clientY){
  const S=cur(), R=hrows.getBoundingClientRect();
  const py=clientY-R.top, fzH=rowY[S.fzR]||0;
  return clamp(idxAt(rowY, py<fzH?py:py+vp.scrollTop, S.nRows),0,S.nRows-1);
}

/* ---------- mouse on grid ---------- */
let drag=null;
vp.addEventListener('mousedown',e=>{
  if(e.button===2) return;
  if(e.target===editor) return;
  if(e.target===fillh){
    drag={mode:'fill',base:selBox()};
    e.preventDefault(); return;
  }
  const _pf=pointField();
  if(pointCaretOK(_pf)){
    const [pr,pc]=hitCell(e.clientX,e.clientY);
    pointAnchor=[pr,pc];
    applyPoint(_pf,pr,pc,pr,pc);
    drag={mode:'point',field:_pf};
    e.preventDefault();               /* keep focus in the formula field */
    return;
  }
  if(painter){
    if(editing) commitEdit(0,0);
    const [r,c]=hitCell(e.clientX,e.clientY);
    drag={mode:'paint',anchor:[r,c],target:{r1:r,r2:r,c1:c,c2:c}};
    const R=rectOf(r,c,r,c);
    fillbox.style.cssText='position:absolute;display:block;left:'+R.x+'px;top:'+R.y+'px;width:'+R.w+'px;height:'+R.h+'px';
    e.preventDefault(); return;
  }
  if(editing) commitEdit(0,0);
  if(selectedChart){ selectedChart=null; [...chartHost.children].forEach(x=>x.classList.remove('sel')); }
  const [r,c]=hitCell(e.clientX,e.clientY);
  const S=cur();
  if(e.shiftKey){ sel.r2=r; sel.c2=c; }
  else { const m=mergeOf(S,r,c); if(m) setSel(m.r1,m.c1,m.r2,m.c2); else setSel(r,c); }
  drag={mode:'sel'};
  render(); vp.focus(); e.preventDefault();
});
vp.addEventListener('dblclick',e=>{ const [r,c]=hitCell(e.clientX,e.clientY); setSel(r,c); startEdit(); });
window.addEventListener('mousemove',e=>{
  if(!drag) return;
  if(drag.mode==='sel'){
    const [r,c]=hitCell(e.clientX,e.clientY);
    if(r!==sel.r2||c!==sel.c2){ sel.r2=r; sel.c2=c; render(); }
  } else if(drag.mode==='fill'){
    const [r,c]=hitCell(e.clientX,e.clientY);
    const b=drag.base;
    let t;
    if(r>b.r2) t={r1:b.r2+1,r2:r,c1:b.c1,c2:b.c2,dir:'d'};
    else if(r<b.r1) t={r1:r,r2:b.r1-1,c1:b.c1,c2:b.c2,dir:'u'};
    else if(c>b.c2) t={r1:b.r1,r2:b.r2,c1:b.c2+1,c2:c,dir:'r'};
    else if(c<b.c1) t={r1:b.r1,r2:b.r2,c1:c,c2:b.c1-1,dir:'l'};
    drag.target=t;
    if(t){ const R=rectOf(t.r1,t.c1,t.r2,t.c2);
      fillbox.style.cssText='position:absolute;display:block;left:'+R.x+'px;top:'+R.y+'px;width:'+R.w+'px;height:'+R.h+'px';
    } else fillbox.style.display='none';
  } else if(drag.mode==='paint'){
    const [r,c]=hitCell(e.clientX,e.clientY), a=drag.anchor;
    const t={r1:Math.min(a[0],r),r2:Math.max(a[0],r),c1:Math.min(a[1],c),c2:Math.max(a[1],c)};
    drag.target=t;
    const R=rectOf(t.r1,t.c1,t.r2,t.c2);
    fillbox.style.cssText='position:absolute;display:block;left:'+R.x+'px;top:'+R.y+'px;width:'+R.w+'px;height:'+R.h+'px';
  } else if(drag.mode==='chartmove'){
    const ch=drag.ch;
    ch.x=Math.max(0,drag.cx+(e.clientX-drag.x0)/zoom);
    ch.y=Math.max(0,drag.cy+(e.clientY-drag.y0)/zoom);
    const el=[...chartHost.children].find(x=>x.dataset.id==ch.id);
    if(el){ el.style.left=Math.round(ch.x*zoom)+'px'; el.style.top=Math.round(ch.y*zoom)+'px'; }
  } else if(drag.mode==='chartsize'){
    const ch=drag.ch;
    ch.w=Math.max(160,drag.w0+(e.clientX-drag.x0)/zoom);
    ch.h=Math.max(120,drag.h0+(e.clientY-drag.y0)/zoom);
    const el=[...chartHost.children].find(x=>x.dataset.id==ch.id);
    if(el){ el.style.width=Math.round(ch.w*zoom)+'px'; el.style.height=Math.round(ch.h*zoom)+'px'; }
  } else if(drag.mode==='point'){
    const [r,c]=hitCell(e.clientX,e.clientY);
    applyPoint(drag.field,pointAnchor[0],pointAnchor[1],r,c);
  } else if(drag.mode==='colsize'){
    const w=Math.max(4,drag.w0+(e.clientX-drag.x0)/zoom);
    cur().colW[drag.c]=Math.round(w); render();
  } else if(drag.mode==='rowsize'){
    const h=Math.max(4,drag.h0+(e.clientY-drag.y0)/zoom);
    cur().rowH[drag.r]=Math.round(h); render();
  } else if(drag.mode==='colsel'){
    const c=hitColHeader(e.clientX); sel.c2=c; sel.r2=cur().nRows-1; render();
  } else if(drag.mode==='rowsel'){
    const r=hitRowHeader(e.clientY); sel.r2=r; sel.c2=cur().nCols-1; render();
  }
});
window.addEventListener('mouseup',()=>{
  if(drag&&drag.mode==='paint'){ const t=drag.target; drag=null; fillbox.style.display='none'; paintTo(t); return; }
  if(drag&&drag.mode==='point'){ const f=drag.field; drag=null;
    if(f&&document.activeElement!==f){ f.focus(); if(pointRef) try{ f.selectionStart=f.selectionEnd=pointRef.end; }catch(_){} }
    return; }
  if(drag&&(drag.mode==='chartmove'||drag.mode==='chartsize')){
    dirty=true; if(drag.mode==='chartsize') invalidateCharts();
    const wasResize=drag.mode==='chartsize'; drag=null; if(wasResize) render(); return; }
  if(drag&&drag.mode==='fill'&&drag.target){ doFill(drag.base,drag.target); }
  if(drag&&(drag.mode==='colsize'||drag.mode==='rowsize')){ dirty=true; }
  fillbox.style.display='none';
  drag=null;
});

/* header interactions */
hcols.addEventListener('mousedown',e=>{
  const g=e.target.closest('.hgrip');
  if(g){ const c=+g.dataset.c; drag={mode:'colsize',c,x0:e.clientX,w0:cwRaw(c)}; e.preventDefault(); return; }
  const c=hitColHeader(e.clientX);
  if(e.shiftKey) sel.c2=c; else { sel.c1=c; sel.c2=c; }
  sel.r1=0; sel.r2=cur().nRows-1;
  drag={mode:'colsel'}; render(); vp.focus(); e.preventDefault();
});
hcols.addEventListener('dblclick',e=>{ const g=e.target.closest('.hgrip'); if(g){ snap(); autofitCol(+g.dataset.c); after(); } });
hrows.addEventListener('mousedown',e=>{
  const g=e.target.closest('.hgrip');
  if(g){ const r=+g.dataset.r; drag={mode:'rowsize',r,y0:e.clientY,h0:rhRaw(r)}; e.preventDefault(); return; }
  const r=hitRowHeader(e.clientY);
  if(e.shiftKey) sel.r2=r; else { sel.r1=r; sel.r2=r; }
  sel.c1=0; sel.c2=cur().nCols-1;
  drag={mode:'rowsel'}; render(); vp.focus(); e.preventDefault();
});
hrows.addEventListener('dblclick',e=>{ const g=e.target.closest('.hgrip'); if(g){ snap(); cur().rowH[+g.dataset.r]=DEFH; after(); } });
$('corner').addEventListener('click',()=>{ const S=cur(); setSel(0,0,S.nRows-1,S.nCols-1); render(); });

function autofitCol(c){
  const S=cur(); let w=30;
  const probe=document.createElement('span');
  probe.style.cssText='position:absolute;visibility:hidden;white-space:pre;font-family:var(--ui);font-size:13px';
  document.body.appendChild(probe);
  for(let r=0;r<Math.min(S.nRows,600);r++){
    const cell=S.cells[key(r,c)]; if(!cell||cell.v==='') continue;
    const s=cell.s;
    probe.style.fontWeight=(s&&s.b)?'700':'400';
    probe.style.fontSize=((s&&s.fs)||13)+'px';
    probe.textContent=displayText(getVal(DOC.active,r,c),s&&s.fmt);
    w=Math.max(w,probe.offsetWidth+12);
  }
  probe.remove();
  S.colW[c]=Math.min(Math.ceil(w),480);
}

/* scroll */
vp.addEventListener('scroll',()=>{
  const S=cur();
  if(vp.scrollTop+vp.clientHeight > rowY[S.nRows]-200 && S.nRows<1048576){ S.nRows=Math.min(S.nRows+80,1048576); }
  if(vp.scrollLeft+vp.clientWidth > colX[S.nCols]-160 && S.nCols<16384){ S.nCols=Math.min(S.nCols+12,16384); }
  draw();
});
window.addEventListener('resize',draw);

/* ---------- keyboard ---------- */
editor.addEventListener('input',autoSizeEditor);
editor.addEventListener('keydown',e=>{
  if(pointRef && e.key.length===1 && !e.ctrlKey && !e.metaKey){ endPoint(); $('stMode').textContent='Enter'; }
  if(e.key==='Enter'&&!e.altKey&&!e.shiftKey){ e.preventDefault(); commitEdit(1,0); }
  else if(e.key==='Enter'&&e.altKey){ const p=editor.selectionStart;
    editor.value=editor.value.slice(0,p)+'\n'+editor.value.slice(editor.selectionEnd);
    editor.selectionStart=editor.selectionEnd=p+1; autoSizeEditor(); e.preventDefault(); }
  else if(e.key==='Escape'){ e.preventDefault(); cancelEdit(); }
  else if(e.key==='Tab'){ e.preventDefault(); commitEdit(0,e.shiftKey?-1:1); }
  e.stopPropagation();
});
$('fbin').addEventListener('focus',()=>{ if(!editing){ editing=true; $('stMode').textContent='Edit'; } });
$('fbin').addEventListener('blur',()=>{ if(editor.style.display==='none'){ editing=false; $('stMode').textContent=''; } });
$('fbin').addEventListener('keydown',e=>{
  if(pointRef && e.key.length===1 && !e.ctrlKey && !e.metaKey){ endPoint(); }
  if(e.key==='Enter'){ e.preventDefault(); const S=cur(); snap(); setCellInput(S,sel.r1,sel.c1,$('fbin').value);
    editing=false; recalc(); moveTo(sel.r1+1,sel.c1,false); vp.focus(); if(typeof onWorkbookChange==='function') onWorkbookChange(); }
  else if(e.key==='Escape'){ editing=false; render(); vp.focus(); }
  e.stopPropagation();
});
$('namebox').addEventListener('keydown',e=>{
  if(e.key==='Enter'){
    const t=$('namebox').value.trim().toUpperCase();
    const m=/^([A-Z]{1,3})([0-9]{1,7})(?::([A-Z]{1,3})([0-9]{1,7}))?$/.exec(t);
    if(m){ const r1=+m[2]-1,c1=colIndex(m[1]);
      growTo(m[4]?+m[4]-1:r1, m[3]?colIndex(m[3]):c1);
      setSel(r1,c1,m[4]?+m[4]-1:r1,m[3]?colIndex(m[3]):c1);
      scrollIntoView(r1,c1); render(); }
    vp.focus();
  }
  e.stopPropagation();
});

document.addEventListener('keydown',e=>{
  if(editing) return;
  const tag=(e.target.tagName||'').toLowerCase();
  if(tag==='input'||tag==='textarea'||tag==='select') return;
  const S=cur(), ctrl=e.ctrlKey||e.metaKey;
  const k=e.key;
  if(ctrl){
    const lk=k.toLowerCase();
    if(lk==='z'){ e.preventDefault(); undo(); return; }
    if(lk==='y'||(lk==='z'&&e.shiftKey)){ e.preventDefault(); redo(); return; }
    if(lk==='b'){ e.preventDefault(); toggleStyle('b'); return; }
    if(lk==='i'){ e.preventDefault(); toggleStyle('i'); return; }
    if(lk==='u'){ e.preventDefault(); toggleStyle('u'); return; }
    if(lk==='a'){ e.preventDefault(); setSel(0,0,S.nRows-1,S.nCols-1); render(); return; }
    if(lk==='f'){ e.preventDefault(); openFind(); return; }
    if(lk==='s'){ e.preventDefault(); saveAs('json'); return; }
    if(lk==='d'){ e.preventDefault(); fillDR('down'); return; }
    if(lk==='r'){ e.preventDefault(); fillDR('right'); return; }
    if(lk==='p'){ e.preventDefault(); printSheet(); return; }
    if(lk==='k'&&!e.shiftKey){ e.preventDefault(); editLink(); return; }
    if(k===';'||k===':'){ e.preventDefault(); insertNow(e.shiftKey); return; }
    if(lk==='v'&&e.shiftKey){ e.preventDefault(); openPasteSpecial(); return; }
    if(lk==='c'||lk==='x'||lk==='v') return; /* handled by copy/cut/paste events */
    if(k==='ArrowUp'||k==='ArrowDown'||k==='ArrowLeft'||k==='ArrowRight'){
      e.preventDefault();
      const d={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]}[k];
      const [r,c]=nextNonBlank(e.shiftKey?sel.r2:sel.r1,e.shiftKey?sel.c2:sel.c1,d[0],d[1]);
      moveTo(r,c,e.shiftKey); return;
    }
    if(k==='Home'){ e.preventDefault(); moveTo(0,0,e.shiftKey); return; }
    return;
  }
  switch(k){
    case 'ArrowUp':    e.preventDefault(); moveTo((e.shiftKey?sel.r2:sel.r1)-1,(e.shiftKey?sel.c2:sel.c1),e.shiftKey); break;
    case 'ArrowDown':  e.preventDefault(); moveTo((e.shiftKey?sel.r2:sel.r1)+1,(e.shiftKey?sel.c2:sel.c1),e.shiftKey); break;
    case 'ArrowLeft':  e.preventDefault(); moveTo((e.shiftKey?sel.r2:sel.r1),(e.shiftKey?sel.c2:sel.c1)-1,e.shiftKey); break;
    case 'ArrowRight': e.preventDefault(); moveTo((e.shiftKey?sel.r2:sel.r1),(e.shiftKey?sel.c2:sel.c1)+1,e.shiftKey); break;
    case 'Tab':        e.preventDefault(); moveTo(sel.r1,sel.c1+(e.shiftKey?-1:1),false); break;
    case 'Enter':      e.preventDefault(); moveTo(sel.r1+(e.shiftKey?-1:1),sel.c1,false); break;
    case 'Home':       e.preventDefault(); moveTo(sel.r1,0,e.shiftKey); break;
    case 'End':        e.preventDefault(); { const [r,c]=nextNonBlank(sel.r1,0,0,1); moveTo(sel.r1,c,e.shiftKey); } break;
    case 'PageDown':   e.preventDefault(); moveTo(sel.r1+20,sel.c1,e.shiftKey); break;
    case 'PageUp':     e.preventDefault(); moveTo(sel.r1-20,sel.c1,e.shiftKey); break;
    case 'F2':         e.preventDefault(); startEdit(); break;
    case 'Delete': case 'Backspace': e.preventDefault();
      if(selectedChart){ snap(); cur().charts=cur().charts.filter(c=>c.id!==selectedChart); selectedChart=null; invalidateCharts(); after(); }
      else clearContents(); break;
    case 'Escape':     if(painter) setPainter(null); clip=null; render(); break;
    default:
      if(k.length===1&&!e.altKey){ e.preventDefault(); startEdit(k); }
  }
});
/* ---------- 5. COMMANDS ---------- */
const round12=x=>Math.round(x*1e10)/1e10;
function refStr(sheet,c,r,ca,ra){
  let p='';
  if(sheet) p=(/^[A-Za-z_][A-Za-z0-9_.]*$/.test(sheet)? sheet : "'"+sheet.replace(/'/g,"''")+"'")+'!';
  return p+(ca?'$':'')+colName(c)+(ra?'$':'')+(r+1);
}
function shiftFormula(src,dr,dc){
  return tokenize(src).map(t=>{
    if(t.t!=='ref') return t.src;
    const r=t.ra?t.r:t.r+dr, c=t.ca?t.c:t.c+dc;
    if(r<0||c<0) return '#REF!';
    return refStr(t.sheet,c,r,t.ca,t.ra);
  }).join('');
}
function eachSel(fn){
  const sb=selBox(), S=cur();
  for(let r=sb.r1;r<=sb.r2;r++) for(let c=sb.c1;c<=sb.c2;c++) fn(ensure(S,r,c),r,c);
}
function clearContents(){ snap(); const S=cur(); const sb=selBox();
  for(let r=sb.r1;r<=sb.r2;r++) for(let c=sb.c1;c<=sb.c2;c++) delete S.cells[key(r,c)];
  after(); }
function clearFormats(){ snap(); eachSel(x=>{x.s=null;}); after(); }

/* --- hyperlinks --- */
function editLink(){
  const S=cur(), x=S.cells[key(sel.r1,sel.c1)];
  const curUrl=(x&&x.link)||'', curText=x?String(x.v):'';
  openDialog('Link',
    '<div class="field"><label for="lkText">Text</label><input type="text" id="lkText" value="'+esc(curText)+'"></div>'+
    '<div class="field"><label for="lkUrl">Address</label><input type="text" id="lkUrl" placeholder="https://example.com" value="'+esc(curUrl)+'"></div>'+
    '<p style="margin:6px 0 0;color:var(--ink-3);font-size:11.5px">Ctrl-click a linked cell to open it.</p>',
    [ (curUrl?['Remove link',()=>{ snap(); const c=ensure(S,sel.r1,sel.c1); delete c.link; after(); closeDialog(); }]:['Cancel',closeDialog]),
      ['Apply',()=>{ const u=$('lkUrl').value.trim(), t=$('lkText').value;
        snap(); const c=ensure(S,sel.r1,sel.c1);
        if(!u){ delete c.link; } else { c.link=u; if(t!=='') setCellInput(S,sel.r1,sel.c1,t); }
        after(); closeDialog(); },'pri'] ]);
  setTimeout(()=>{ const n=$('lkUrl'); if(n) n.focus(); },30);
}
/* --- notes --- */
function editNote(){
  const S=cur(), x=S.cells[key(sel.r1,sel.c1)];
  openDialog('Note on '+a1(sel.r1,sel.c1),
    '<textarea id="ntBody" style="width:100%;height:110px;border:1px solid var(--line);border-radius:6px;padding:8px;'
    +'font-family:var(--ui);font-size:13px;resize:vertical;outline:none">'+esc((x&&x.note)||'')+'</textarea>',
    [ ((x&&x.note)?['Delete note',()=>{ snap(); const c=ensure(S,sel.r1,sel.c1); delete c.note; if(c.v===''&&!c.s&&!c.link) delete S.cells[key(sel.r1,sel.c1)]; after(); closeDialog(); }]:['Cancel',closeDialog]),
      ['Save',()=>{ const t=$('ntBody').value; snap(); const c=ensure(S,sel.r1,sel.c1);
        if(t.trim()==='') delete c.note; else c.note=t; after(); closeDialog(); },'pri'] ]);
  setTimeout(()=>{ const n=$('ntBody'); if(n){ n.focus(); n.selectionStart=n.value.length; } },30);
}

/* --- fill down / right (Ctrl+D / Ctrl+R): replicate the edge, shifting formulas --- */
function fillDR(dir){
  const sb=selBox(), S=cur();
  if(dir==='down' && sb.r2===sb.r1) return;
  if(dir==='right' && sb.c2===sb.c1) return;
  snap();
  if(dir==='down'){
    for(let c=sb.c1;c<=sb.c2;c++){ const src=S.cells[key(sb.r1,c)];
      for(let r=sb.r1+1;r<=sb.r2;r++){ const t=key(r,c);
        if(!src){ delete S.cells[t]; continue; }
        const cell=ensure(S,r,c); cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null;
        if(src.link)cell.link=src.link; else delete cell.link; delete cell.note;
        cell.v = (typeof src.v==='string'&&src.v[0]==='=')? '='+shiftFormula(src.v.slice(1),r-sb.r1,0) : src.v;
      } }
  } else {
    for(let r=sb.r1;r<=sb.r2;r++){ const src=S.cells[key(r,sb.c1)];
      for(let c=sb.c1+1;c<=sb.c2;c++){ const t=key(r,c);
        if(!src){ delete S.cells[t]; continue; }
        const cell=ensure(S,r,c); cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null;
        if(src.link)cell.link=src.link; else delete cell.link; delete cell.note;
        cell.v = (typeof src.v==='string'&&src.v[0]==='=')? '='+shiftFormula(src.v.slice(1),0,c-sb.c1) : src.v;
      } }
  }
  after();
}
/* --- insert today's date / current time into the active cell --- */
function insertNow(withTime){
  const S=cur(); snap();
  const d=new Date();
  if(withTime){ const t=(d.getHours()*3600+d.getMinutes()*60+d.getSeconds())/86400;
    const cell=ensure(S,sel.r1,sel.c1); cell.v=String(t); setFmt(cell,{t:'time',pat:'h:mm:ss AM/PM'}); }
  else { const serial=Math.floor(dateToSerial(new Date(d.getFullYear(),d.getMonth(),d.getDate())));
    const cell=ensure(S,sel.r1,sel.c1); cell.v=String(serial); setFmt(cell,{t:'date',pat:'yyyy-mm-dd'}); }
  after();
}
/* --- print the current sheet's used range as a clean table --- */
function printSheet(){
  const S=cur();
  let host=$('printarea'); if(!host){ host=document.createElement('div'); host.id='printarea'; document.body.appendChild(host); }
  host.innerHTML='<h3>'+esc(S.name)+'</h3>'+sheetHTML(S,DOC.active);
  const done=()=>{ host.innerHTML=''; window.removeEventListener('afterprint',done); };
  window.addEventListener('afterprint',done);
  window.print();
}

/* --- fill --- */
function buildSeries(cells,n,fwd){
  const L=cells.length;
  const raw=cells.map(c=>c?String(c.v):'');
  const hasF=raw.some(t=>t[0]==='=');
  const numRe=/^-?\d*\.?\d+([eE][+-]?\d+)?$/;
  const out=[];
  if(!hasF && L>=2 && raw.every(t=>numRe.test(t.trim())&&t.trim()!=='')){
    const v=raw.map(parseFloat), step=(v[L-1]-v[0])/(L-1);
    for(let k=0;k<n;k++){ const pos=fwd?(L+k):(-1-k); out.push({v:String(round12(v[0]+step*pos))}); }
    return out;
  }
  const pat=/^(.*?)(\d+)(\D*)$/;
  if(!hasF && raw.every(t=>pat.test(t))){
    const parts=raw.map(t=>pat.exec(t));
    if(parts.every(p=>p[1]===parts[0][1]&&p[3]===parts[0][3])){
      const nums=parts.map(p=>parseInt(p[2],10));
      const step=L>=2?(nums[L-1]-nums[0])/(L-1):1;
      for(let k=0;k<n;k++){ const pos=fwd?(L+k):(-1-k);
        out.push({v:parts[0][1]+Math.round(nums[0]+step*pos)+parts[0][3]}); }
      return out;
    }
  }
  const lists=[DOW,DOW.map(d=>d.slice(0,3)),MON,MON.map(m=>m.slice(0,3))];
  for(const list of lists){
    const idx=raw.map(t=>list.findIndex(x=>x.toLowerCase()===t.trim().toLowerCase()));
    if(idx.length&&idx.every(i=>i>=0)){
      const step=L>=2?(idx[1]-idx[0]||1):1;
      for(let k=0;k<n;k++){ const pos=fwd?(L+k):(-1-k);
        out.push({v:list[(((idx[0]+step*pos)%list.length)+list.length*100)%list.length]}); }
      return out;
    }
  }
  for(let k=0;k<n;k++){
    const si=fwd?(k%L):(L-1-(k%L));
    if(raw[si][0]==='=') out.push({si,formulaFrom:true}); else out.push({v:raw[si]});
  }
  return out;
}
function doFill(base,t){
  snap();
  const S=cur();
  const vert=(t.dir==='d'||t.dir==='u');
  const fwd=(t.dir==='d'||t.dir==='r');
  const count=vert?(t.r2-t.r1+1):(t.c2-t.c1+1);
  const lanes=vert?(base.c2-base.c1+1):(base.r2-base.r1+1);
  const srcLen=vert?(base.r2-base.r1+1):(base.c2-base.c1+1);
  for(let L=0;L<lanes;L++){
    const src=[];
    for(let i=0;i<srcLen;i++){
      const r=vert?base.r1+i:base.r1+L, c=vert?base.c1+L:base.c1+i;
      src.push({r,c,cell:S.cells[key(r,c)]});
    }
    const seq=buildSeries(src.map(x=>x.cell),count,fwd);
    for(let k=0;k<count;k++){
      const tr=vert?(fwd?t.r1+k:t.r2-k):(base.r1+L);
      const tc=vert?(base.c1+L):(fwd?t.c1+k:t.c2-k);
      const item=seq[k];
      const sidx=fwd?(k%srcLen):(srcLen-1-(k%srcLen));
      const s0=src[sidx].cell;
      const cell=ensure(S,tr,tc);
      cell.s=(s0&&s0.s)?JSON.parse(JSON.stringify(s0.s)):null;
      if(item.formulaFrom){ const fr=src[item.si];
        cell.v='='+shiftFormula(String(fr.cell.v).slice(1),tr-fr.r,tc-fr.c); }
      else cell.v=item.v;
    }
  }
  setSel(Math.min(base.r1,t.r1),Math.min(base.c1,t.c1),Math.max(base.r2,t.r2),Math.max(base.c2,t.c2));
  after();
}

/* --- clipboard --- */
function copySel(cut){
  const sb=selBox(), S=cur(), cells=[], lines=[];
  for(let r=sb.r1;r<=sb.r2;r++){
    const row=[],ln=[];
    for(let c=sb.c1;c<=sb.c2;c++){
      const x=S.cells[key(r,c)];
      const cv=getVal(DOC.active,r,c);
      row.push(x?{v:x.v,s:x.s?JSON.parse(JSON.stringify(x.s)):null,
                  cv:(isErr(cv)?{e:cv.e}:cv),link:x.link||null,note:x.note||null}:null);
      ln.push(String(displayText(cv,x&&x.s&&x.s.fmt)).replace(/[\t\n]/g,' '));
    }
    cells.push(row); lines.push(ln.join('\t'));
  }
  clip={cells,r1:sb.r1,c1:sb.c1,r2:sb.r2,c2:sb.c2,cut:!!cut,marching:true,tsv:lines.join('\n')};
  render();
  return clip.tsv;
}
function pasteInternal(){
  if(!clip) return;
  snap();
  const S=cur(), sb=selBox();
  const h=clip.cells.length, w=clip.cells[0].length;
  const repR=Math.max(1,Math.floor((sb.r2-sb.r1+1)/h)), repC=Math.max(1,Math.floor((sb.c2-sb.c1+1)/w));
  for(let br=0;br<repR;br++) for(let bc=0;bc<repC;bc++)
  for(let i=0;i<h;i++) for(let j=0;j<w;j++){
    const tr=sb.r1+br*h+i, tc=sb.c1+bc*w+j;
    growTo(tr,tc);
    const src=clip.cells[i][j];
    if(!src){ delete S.cells[key(tr,tc)]; continue; }
    const cell=ensure(S,tr,tc);
    cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null;
    if(src.link) cell.link=src.link; else delete cell.link;
    if(src.note) cell.note=src.note; else delete cell.note;
    if(typeof src.v==='string'&&src.v[0]==='='&&!clip.cut)
      cell.v='='+shiftFormula(src.v.slice(1),tr-(clip.r1+i),tc-(clip.c1+j));
    else cell.v=src.v;
  }
  if(clip.cut){
    for(let r=clip.r1;r<=clip.r2;r++) for(let c=clip.c1;c<=clip.c2;c++) delete S.cells[key(r,c)];
    clip=null;
  } else clip.marching=false;
  setSel(sb.r1,sb.c1,sb.r1+h*repR-1,sb.c1+w*repC-1);
  after();
}
function cvLiteral(cv){
  if(cv===null||cv===undefined) return '';
  if(cv&&cv.e) return cv.e;                 /* error text */
  if(typeof cv==='boolean') return cv?'TRUE':'FALSE';
  if(typeof cv==='number') return String(cv);
  return String(cv);
}
/* mode: 'all' | 'values' | 'valuesFmt' | 'formulas' | 'formats' | 'transpose' */
function pasteSpecial(mode){
  if(!clip){ toast('Nothing copied yet'); return; }
  if(clip.cut && mode!=='all'){ pasteInternal(); return; }   /* cut always moves whole cells */
  snap();
  const S=cur(), sb=selBox();
  let h=clip.cells.length, w=clip.cells[0].length;
  const get=(i,j)=> mode==='transpose' ? clip.cells[j][i] : clip.cells[i][j];
  if(mode==='transpose'){ const t=h; h=w; w=t; }
  for(let i=0;i<h;i++) for(let j=0;j<w;j++){
    const tr=sb.r1+i, tc=sb.c1+j; growTo(tr,tc);
    const src=get(i,j);
    if(!src){
      if(mode==='formats'){ const c=S.cells[key(tr,tc)]; if(c) c.s=null; }
      else if(mode==='all'||mode==='transpose'||mode==='valuesFmt') delete S.cells[key(tr,tc)];
      continue;
    }
    const cell=ensure(S,tr,tc);
    const oi = mode==='transpose'? j : i, oj = mode==='transpose'? i : j;   /* source coords */
    const isF = typeof src.v==='string' && src.v[0]==='=';
    if(mode==='formats'){ cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null; continue; }
    if(mode==='values'){ cell.v=cvLiteral(src.cv); continue; }
    if(mode==='valuesFmt'){ cell.v=cvLiteral(src.cv); cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null; continue; }
    if(mode==='formulas'){
      cell.v = isF ? '='+shiftFormula(src.v.slice(1),tr-(clip.r1+oi),tc-(clip.c1+oj)) : src.v;
      continue;
    }
    /* 'all' and 'transpose' -> full cell (transpose bakes formulas to values, refs can't be re-mapped safely) */
    cell.s=src.s?JSON.parse(JSON.stringify(src.s)):null;
    if(src.link) cell.link=src.link; else delete cell.link;
    if(src.note) cell.note=src.note; else delete cell.note;
    if(mode==='transpose') cell.v = isF ? cvLiteral(src.cv) : src.v;
    else cell.v = isF ? '='+shiftFormula(src.v.slice(1),tr-(clip.r1+oi),tc-(clip.c1+oj)) : src.v;
  }
  clip.marching=false;
  setSel(sb.r1,sb.c1,sb.r1+h-1,sb.c1+w-1);
  after();
}
function splitDelimited(txt){
  const hasTab=txt.indexOf('\t')>=0;
  if(hasTab) return txt.replace(/\r/g,'').split('\n').map(l=>l.split('\t'));
  return parseCSV(txt);
}
function parseCSV(txt){
  const rows=[]; let row=[],f='',q=false;
  txt=txt.replace(/\r\n/g,'\n').replace(/\r/g,'\n');
  for(let i=0;i<txt.length;i++){
    const ch=txt[i];
    if(q){ if(ch==='"'){ if(txt[i+1]==='"'){f+='"';i++;} else q=false; } else f+=ch; }
    else if(ch==='"') q=true;
    else if(ch===','){ row.push(f); f=''; }
    else if(ch==='\n'){ row.push(f); rows.push(row); row=[]; f=''; }
    else f+=ch;
  }
  if(f!==''||row.length){ row.push(f); rows.push(row); }
  return rows;
}
function pasteText(txt){
  if(!txt) return;
  snap();
  const S=cur(), rows=splitDelimited(txt);
  rows.forEach((line,i)=>line.forEach((v,j)=>{
    const r=sel.r1+i, c=sel.c1+j; growTo(r,c); setCellInput(S,r,c,v);
  }));
  setSel(sel.r1,sel.c1,sel.r1+rows.length-1,sel.c1+Math.max(...rows.map(r=>r.length))-1);
  after();
}
document.addEventListener('copy',e=>{ if(editing)return; e.clipboardData.setData('text/plain',copySel(false)); e.preventDefault(); });
document.addEventListener('cut', e=>{ if(editing)return; e.clipboardData.setData('text/plain',copySel(true));  e.preventDefault(); });
document.addEventListener('paste',e=>{
  if(editing) return;
  const txt=(e.clipboardData||window.clipboardData).getData('text/plain');
  e.preventDefault();
  if(clip&&txt===clip.tsv) pasteInternal(); else pasteText(txt);
});

/* --- styling --- */
function toggleStyle(k){
  snap();
  const sb=selBox(), S=cur();
  let allOn=true;
  for(let r=sb.r1;r<=sb.r2&&allOn;r++) for(let c=sb.c1;c<=sb.c2;c++){
    const x=S.cells[key(r,c)]; if(!(x&&x.s&&x.s[k])){ allOn=false; break; }
  }
  eachSel(x=>{ x.s=x.s||{}; if(allOn) delete x.s[k]; else x.s[k]=true; });
  after();
}
function setStyle(props){ snap(); eachSel(x=>{ x.s=x.s||{}; Object.assign(x.s,props); }); after(); }

/* --- format painter --- */
function setPainter(p){
  painter=p;
  $('btnPaint').classList.toggle('on',!!p);
  vp.classList.toggle('painting',!!p);
  $('stMode').textContent = p ? (p.locked?'Painter · locked (Esc to stop)':'Painter') : '';
}
function capturePainter(locked){
  const sb=selBox(), S=cur();
  const h=sb.r2-sb.r1+1, w=sb.c2-sb.c1+1, styles=[];
  for(let r=sb.r1;r<=sb.r2;r++){ const row=[];
    for(let c=sb.c1;c<=sb.c2;c++){ const x=S.cells[key(r,c)];
      row.push(x&&x.s? JSON.parse(JSON.stringify(x.s)) : null); }
    styles.push(row); }
  setPainter({styles,h,w,locked:!!locked});
}
function paintTo(tb){
  if(!painter) return;
  snap();
  const S=cur();
  for(let r=tb.r1;r<=tb.r2;r++) for(let c=tb.c1;c<=tb.c2;c++){
    const src=painter.styles[(r-tb.r1)%painter.h][(c-tb.c1)%painter.w];
    ensure(S,r,c).s = src? JSON.parse(JSON.stringify(src)) : null;
  }
  const locked=painter.locked;
  after();
  if(!locked) setPainter(null);
}
function setNumFmt(t){
  snap();
  eachSel(x=>{
    x.s=x.s||{};
    const old=x.s.fmt||{};
    if(t==='general') delete x.s.fmt;
    else if(t==='date') x.s.fmt={t:'date',pat:old.pat||'yyyy-mm-dd'};
    else if(t==='time') x.s.fmt={t:'time',pat:'h:mm:ss AM/PM'};
    else if(t==='datetime') x.s.fmt={t:'datetime',pat:'yyyy-mm-dd hh:mm'};
    else if(t==='duration') x.s.fmt={t:'duration',pat:'[h]:mm:ss'};
    else if(t==='currency'||t==='accounting') x.s.fmt={t,d:old.d!=null?old.d:2,cur:old.cur||'USD'};
    else if(t==='percent') x.s.fmt={t,d:old.d!=null?old.d:1};
    else if(t==='fraction') x.s.fmt={t,den:16};
    else if(t==='text') x.s.fmt={t:'text'};
    else x.s.fmt={t,d:old.d!=null?old.d:2};
  });
  after();
}
function bumpDec(n){
  snap();
  eachSel(x=>{
    x.s=x.s||{};
    const f=x.s.fmt||{t:'number',d:2};
    if(['number','comma','currency','accounting','percent','sci'].indexOf(f.t)<0){ x.s.fmt={t:'number',d:clamp(2+n,0,10)}; return; }
    f.d=clamp((f.d==null?2:f.d)+n,0,10); x.s.fmt=f;
  });
  after();
}
function applyBorder(kind,color){
  snap();
  const sb=selBox(), S=cur();
  color=color||'#5b6470';
  for(let r=sb.r1;r<=sb.r2;r++) for(let c=sb.c1;c<=sb.c2;c++){
    const x=ensure(S,r,c); x.s=x.s||{};
    if(kind==='none'){ delete x.s.bt; delete x.s.bb; delete x.s.bl; delete x.s.br; continue; }
    if(kind==='all'){ x.s.bt=x.s.bb=x.s.bl=x.s.br=color; continue; }
    if(kind==='outer'){
      if(r===sb.r1)x.s.bt=color; if(r===sb.r2)x.s.bb=color;
      if(c===sb.c1)x.s.bl=color; if(c===sb.c2)x.s.br=color; continue;
    }
    if(kind==='top'&&r===sb.r1) x.s.bt=color;
    if(kind==='bottom'&&r===sb.r2) x.s.bb=color;
    if(kind==='left'&&c===sb.c1) x.s.bl=color;
    if(kind==='right'&&c===sb.c2) x.s.br=color;
  }
  after();
}
function mergeToggle(){
  snap();
  const S=cur(), sb=selBox();
  const idx=S.merges.findIndex(m=>m.r1===sb.r1&&m.c1===sb.c1&&m.r2===sb.r2&&m.c2===sb.c2);
  if(idx>=0) S.merges.splice(idx,1);
  else {
    S.merges=S.merges.filter(m=>!(m.r1<=sb.r2&&m.r2>=sb.r1&&m.c1<=sb.c2&&m.c2>=sb.c1));
    if(sb.r1!==sb.r2||sb.c1!==sb.c2) S.merges.push({r1:sb.r1,c1:sb.c1,r2:sb.r2,c2:sb.c2});
  }
  after();
}

/* --- rows & columns --- */
function rewriteRefs(kind,tgtSi,at,n){
  DOC.sheets.forEach((S,si)=>{
    for(const k in S.cells){
      const cell=S.cells[k];
      if(typeof cell.v==='string'&&cell.v[0]==='='){
        cell.v='='+tokenize(cell.v.slice(1)).map(t=>{
          if(t.t!=='ref') return t.src;
          const rsi=t.sheet?sheetIndexByName(t.sheet):si;
          if(rsi!==tgtSi) return t.src;
          let r=t.r,c=t.c;
          if(kind==='row'){
            if(n>0){ if(r>=at) r+=n; }
            else { if(r>=at&&r<at-n) return '#REF!'; if(r>=at-n) r+=n; }
          } else {
            if(n>0){ if(c>=at) c+=n; }
            else { if(c>=at&&c<at-n) return '#REF!'; if(c>=at-n) c+=n; }
          }
          return refStr(t.sheet,c,r,t.ca,t.ra);
        }).join('');
      }
    }
  });
  astCache.clear();
}
function insertRows(at,n){
  snap();
  const S=cur();
  if(S.filter){ S.filter=null; S.fhR={}; }
  const nc={};
  for(const k in S.cells){ const [r,c]=k.split(':').map(Number); nc[key(r>=at?r+n:r,c)]=S.cells[k]; }
  S.cells=Object.assign(Object.create(null),nc);
  const nh={}; for(const k in S.rowH){ const r=+k; nh[r>=at?r+n:r]=S.rowH[k]; } S.rowH=nh;
  S.merges=S.merges.map(m=>({r1:m.r1>=at?m.r1+n:m.r1,r2:m.r2>=at?m.r2+n:m.r2,c1:m.c1,c2:m.c2}));
  S.nRows+=n;
  rewriteRefs('row',DOC.active,at,n); after();
}
function deleteRows(at,n){
  snap();
  const S=cur();
  if(S.filter){ S.filter=null; S.fhR={}; }
  const nc={};
  for(const k in S.cells){ const [r,c]=k.split(':').map(Number);
    if(r>=at&&r<at+n) continue; nc[key(r>=at+n?r-n:r,c)]=S.cells[k]; }
  S.cells=Object.assign(Object.create(null),nc);
  const nh={}; for(const k in S.rowH){ const r=+k; if(r>=at&&r<at+n) continue; nh[r>=at+n?r-n:r]=S.rowH[k]; } S.rowH=nh;
  S.merges=S.merges.filter(m=>!(m.r1>=at&&m.r2<at+n)).map(m=>({r1:m.r1>=at+n?m.r1-n:m.r1,r2:m.r2>=at+n?m.r2-n:m.r2,c1:m.c1,c2:m.c2}));
  S.nRows=Math.max(1,S.nRows-n);
  rewriteRefs('row',DOC.active,at,-n); after();
}
function insertCols(at,n){
  snap();
  const S=cur();
  if(S.filter){ S.filter=null; S.fhR={}; }
  const nc={};
  for(const k in S.cells){ const [r,c]=k.split(':').map(Number); nc[key(r,c>=at?c+n:c)]=S.cells[k]; }
  S.cells=Object.assign(Object.create(null),nc);
  const nw={}; for(const k in S.colW){ const c=+k; nw[c>=at?c+n:c]=S.colW[k]; } S.colW=nw;
  S.merges=S.merges.map(m=>({c1:m.c1>=at?m.c1+n:m.c1,c2:m.c2>=at?m.c2+n:m.c2,r1:m.r1,r2:m.r2}));
  S.nCols+=n;
  rewriteRefs('col',DOC.active,at,n); after();
}
function deleteCols(at,n){
  snap();
  const S=cur();
  if(S.filter){ S.filter=null; S.fhR={}; }
  const nc={};
  for(const k in S.cells){ const [r,c]=k.split(':').map(Number);
    if(c>=at&&c<at+n) continue; nc[key(r,c>=at+n?c-n:c)]=S.cells[k]; }
  S.cells=Object.assign(Object.create(null),nc);
  const nw={}; for(const k in S.colW){ const c=+k; if(c>=at&&c<at+n) continue; nw[c>=at+n?c-n:c]=S.colW[k]; } S.colW=nw;
  S.merges=S.merges.filter(m=>!(m.c1>=at&&m.c2<at+n)).map(m=>({c1:m.c1>=at+n?m.c1-n:m.c1,c2:m.c2>=at+n?m.c2-n:m.c2,r1:m.r1,r2:m.r2}));
  S.nCols=Math.max(1,S.nCols-n);
  rewriteRefs('col',DOC.active,at,-n); after();
}
function hideRows(hide){ snap(); const sb=selBox(),S=cur();
  for(let r=sb.r1;r<=sb.r2;r++){ if(hide) S.hiddenR[r]=1; else delete S.hiddenR[r]; } after(); }
function hideCols(hide){ snap(); const sb=selBox(),S=cur();
  for(let c=sb.c1;c<=sb.c2;c++){ if(hide) S.hiddenC[c]=1; else delete S.hiddenC[c]; } after(); }

/* --- sort --- */
function sortSel(desc,byCol){
  snap();
  const S=cur(); let sb=selBox();
  if(sb.r1===sb.r2&&sb.c1===sb.c2){
    let r1=sb.r1,r2=sb.r1,c1=sb.c1,c2=sb.c1;
    while(r1>0&&S.cells[key(r1-1,c1)]&&S.cells[key(r1-1,c1)].v!=='') r1--;
    while(S.cells[key(r2+1,c1)]&&S.cells[key(r2+1,c1)].v!=='') r2++;
    while(c1>0&&S.cells[key(r1,c1-1)]&&S.cells[key(r1,c1-1)].v!=='') c1--;
    while(S.cells[key(r1,c2+1)]&&S.cells[key(r1,c2+1)].v!=='') c2++;
    sb={r1,r2,c1,c2};
  }
  const kc=(byCol==null?sb.c1:byCol);
  const rows=[];
  for(let r=sb.r1;r<=sb.r2;r++){
    const row=[];
    for(let c=sb.c1;c<=sb.c2;c++){ const x=S.cells[key(r,c)]; row.push(x?{v:x.v,s:x.s}:null); }
    rows.push({row,k:getVal(DOC.active,r,kc)});
  }
  rows.sort((a,b)=>{
    const x=a.k,y=b.k;
    if(x===null&&y===null) return 0;
    if(x===null) return 1;
    if(y===null) return -1;
    return (compare(x,y,'<')?-1:compare(x,y,'>')?1:0)*(desc?-1:1);
  });
  rows.forEach((o,i)=>{
    for(let j=0;j<o.row.length;j++){
      const k=key(sb.r1+i,sb.c1+j);
      if(o.row[j]===null) delete S.cells[k];
      else S.cells[k]={v:o.row[j].v,s:o.row[j].s};
    }
  });
  after();
}

/* --- filter (AutoFilter) --- */
function detectTable(){
  const S=cur(); let sb=selBox();
  if(sb.r1===sb.r2&&sb.c1===sb.c2){
    const nb=(r,c)=>{ const x=S.cells[key(r,c)]; return x && x.v!=='' && x.v!=null; };
    if(!nb(sb.r1,sb.c1)) return null;
    let r1=sb.r1,r2=sb.r1,c1=sb.c1,c2=sb.c1;
    while(r1>0&&nb(r1-1,c1)) r1--;
    while(nb(r2+1,c1)) r2++;
    while(c1>0&&nb(r1,c1-1)) c1--;
    while(nb(r1,c2+1)) c2++;
    return {r1,r2,c1,c2};
  }
  return sb;
}
function applyFilters(){
  const S=cur(), F=S.filter;
  S.fhR={};
  if(!F || !F.crit) return;
  for(let r=F.hdr+1;r<=F.r2;r++){
    let show=true;
    for(const ck in F.crit){
      const allow=F.crit[ck]; if(!allow) continue;
      const set=(allow instanceof Set)?allow:new Set(allow);
      if(!set.has(filterDisp(S,r,+ck))){ show=false; break; }
    }
    if(!show) S.fhR[r]=1;
  }
}
function toggleFilter(){
  const S=cur();
  if(S.filter){ snap(); S.filter=null; S.fhR={}; after(); toast('Filter removed'); return; }
  const t=detectTable();
  if(!t || t.r2<=t.r1){ toast('Select a table (a header row plus data) to filter'); return; }
  snap();
  S.filter={hdr:t.r1,r1:t.r1,r2:t.r2,c1:t.c1,c2:t.c2,crit:null};
  applyFilters(); after();
  toast('Filter on '+a1(t.r1,t.c1)+':'+a1(t.r2,t.c2)+' — click a ▾ to filter a column');
}
function clearAllFilters(reveal){
  const S=cur(); if(!S.filter) return;
  if(S.filter.crit){ S.filter.crit=null; }
  if(reveal) S.fhR={};
}
function sortTableBy(col,desc){
  const S=cur(), F=S.filter; if(!F) return;
  snap();
  const rows=[];
  for(let r=F.hdr+1;r<=F.r2;r++){
    const row=[]; for(let c=F.c1;c<=F.c2;c++){ const x=S.cells[key(r,c)]; row.push(x?{v:x.v,s:x.s}:null); }
    rows.push({row,k:getVal(DOC.active,r,col)});
  }
  rows.sort((a,b)=>{ const x=a.k,y=b.k;
    if(x===null&&y===null)return 0; if(x===null)return 1; if(y===null)return -1;
    return (compare(x,y,'<')?-1:compare(x,y,'>')?1:0)*(desc?-1:1); });
  rows.forEach((o,i)=>{ for(let j=0;j<o.row.length;j++){ const k=key(F.hdr+1+i,F.c1+j);
    if(o.row[j]===null) delete S.cells[k]; else S.cells[k]={v:o.row[j].v,s:o.row[j].s}; } });
  applyFilters(); after();
}
function columnValues(col){
  const S=cur(), F=S.filter;
  const seen=new Map(); let blanks=false;
  for(let r=F.hdr+1;r<=F.r2;r++){
    const d=filterDisp(S,r,col);
    if(d==='') blanks=true; else if(!seen.has(d)) seen.set(d, getVal(DOC.active,r,col));
  }
  const arr=[...seen.keys()].sort((a,b)=>{
    const x=seen.get(a),y=seen.get(b);
    if(typeof x==='number'&&typeof y==='number') return x-y;
    return a.localeCompare(b,undefined,{numeric:true,sensitivity:'base'});
  });
  return {values:arr, blanks};
}

/* filter popover */
let fpop=null;
function closeFilterPop(){ if(fpop){ fpop.remove(); fpop=null; document.removeEventListener('mousedown',fpopOutside,true); } }
function fpopOutside(e){ if(fpop && !fpop.contains(e.target) && !e.target.closest('.filter-arrow')) closeFilterPop(); }
function openFilterMenu(col, ax, ay){
  closeFilterPop();
  const S=cur(), F=S.filter;
  const {values,blanks}=columnValues(col);
  const BLANK='\u0000blank';
  const existing = F.crit && F.crit[col] ? new Set(F.crit[col]) : null;   // null => all checked
  const isChecked = v => existing? existing.has(v) : true;

  fpop=document.createElement('div'); fpop.className='fpop';
  const rowsHtml = values.map((v,i)=>
    '<label class="fitem"><input type="checkbox" data-v="'+i+'"'+(isChecked(v)?' checked':'')+'><span>'+esc(v)+'</span></label>').join('');
  const blankHtml = blanks
    ? '<label class="fitem"><input type="checkbox" data-blank="1"'+(isChecked('')?' checked':'')+'><span class="muted">(Blanks)</span></label>' : '';
  fpop.innerHTML =
    '<div class="fsort">'
    + '<button data-act="asc"><svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M4 12V4M4 4L2 6M4 4l2 2M8 5h6M8 8h4M8 11h2"/></svg>Sort A → Z</button>'
    + '<button data-act="desc"><svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M4 4v8M4 12l-2-2M4 12l2-2M8 11h6M8 8h4M8 5h2"/></svg>Sort Z → A</button>'
    + '</div><hr>'
    + '<div class="fsearch"><input type="text" placeholder="Search values…" spellcheck="false"></div>'
    + '<div class="flist">'
    + '<label class="fitem all"><input type="checkbox" data-all="1"><span>(Select all)</span></label>'
    + rowsHtml + blankHtml
    + '</div>'
    + '<div class="ffoot"><button class="btn lft" data-act="clear">Clear</button>'
    + '<button class="btn" data-act="cancel">Cancel</button>'
    + '<button class="btn pri" data-act="ok">Apply</button></div>';
  document.body.appendChild(fpop);
  fpop.style.display='flex';
  const w=fpop.offsetWidth,h=fpop.offsetHeight;
  fpop.style.left=Math.min(ax,innerWidth-w-8)+'px';
  fpop.style.top=Math.min(ay,innerHeight-h-8)+'px';

  const boxes=()=>[...fpop.querySelectorAll('.flist input[type=checkbox]:not([data-all])')];
  const allBox=fpop.querySelector('input[data-all]');
  const syncAll=()=>{ const b=boxes().filter(x=>x.parentElement.style.display!=='none');
    const on=b.filter(x=>x.checked).length; allBox.indeterminate = on>0 && on<b.length; allBox.checked = on===b.length && b.length>0; };
  syncAll();
  allBox.addEventListener('change',()=>{ boxes().forEach(x=>{ if(x.parentElement.style.display!=='none') x.checked=allBox.checked; }); allBox.indeterminate=false; });
  fpop.querySelector('.flist').addEventListener('change',e=>{ if(e.target!==allBox) syncAll(); });
  const search=fpop.querySelector('.fsearch input');
  search.addEventListener('input',()=>{ const q=search.value.toLowerCase();
    fpop.querySelectorAll('.flist .fitem:not(.all)').forEach(it=>{
      const t=it.querySelector('span').textContent.toLowerCase();
      it.style.display = t.indexOf(q)>=0 ? 'flex':'none'; }); syncAll(); });
  setTimeout(()=>search.focus(),20);

  fpop.addEventListener('click',e=>{
    const b=e.target.closest('[data-act]'); if(!b) return;
    const act=b.dataset.act;
    if(act==='asc'){ closeFilterPop(); sortTableBy(col,false); return; }
    if(act==='desc'){ closeFilterPop(); sortTableBy(col,true); return; }
    if(act==='cancel'){ closeFilterPop(); return; }
    if(act==='clear'){ snap(); if(F.crit){ delete F.crit[col]; if(!Object.keys(F.crit).length) F.crit=null; } applyFilters(); after(); closeFilterPop(); return; }
    if(act==='ok'){
      const chosen=[]; let anyOff=false;
      boxes().forEach(x=>{ const v = x.dataset.blank ? '' : values[+x.dataset.v];
        if(x.checked) chosen.push(v); else anyOff=true; });
      snap();
      F.crit = F.crit || {};
      if(!anyOff){ delete F.crit[col]; }          /* all checked = no filter on this column */
      else { if(!chosen.length){ toast('Select at least one value'); return; } F.crit[col]=chosen; }
      if(F.crit && !Object.keys(F.crit).length) F.crit=null;
      applyFilters(); after(); closeFilterPop();
    }
  });
  document.addEventListener('mousedown',fpopOutside,true);
}

/* --- freeze --- */
function freezeHere(){
  snap();
  const S=cur(), sb=selBox();
  if(S.fzR===sb.r1&&S.fzC===sb.c1&&(sb.r1||sb.c1)){ S.fzR=0; S.fzC=0; }
  else { S.fzR=sb.r1; S.fzC=sb.c1; }
  after();
  toast(cur().fzR||cur().fzC ? 'Panes frozen at '+a1(cur().fzR,cur().fzC) : 'Panes unfrozen');
}

/* --- sheets --- */
function buildTabs(){
  const el=$('tabs'); el.innerHTML='';
  DOC.sheets.forEach((S,i)=>{
    const b=document.createElement('button');
    b.className='tab'+(i===DOC.active?' on':'');
    b.textContent=S.name;
    b.onclick=()=>{ if(typeof closeFilterPop==='function') closeFilterPop(); if(editing) commitEdit(0,0); DOC.active=i;
      if(DOC.sheets[i].pivot){ recalc(); refreshPivot(DOC.sheets[i]); }
      sel={r1:0,c1:0,r2:0,c2:0}; vp.scrollTop=vp.scrollLeft=0; render(); buildTabs(); };
    b.ondblclick=()=>renameSheet(i);
    b.oncontextmenu=ev=>{ ev.preventDefault(); sheetMenu(ev,i); };
    el.appendChild(b);
  });
  const add=document.createElement('button');
  add.className='tab'; add.textContent='+'; add.title='Add sheet';
  add.onclick=()=>{ snap(); let n=1; while(DOC.sheets.some(s=>s.name==='Sheet'+n)) n++;
    DOC.sheets.push(newSheet('Sheet'+n)); DOC.active=DOC.sheets.length-1; sel={r1:0,c1:0,r2:0,c2:0}; after(); };
  el.appendChild(add);
}
function renameSheet(i){
  openDialog('Rename sheet',
    '<div class="field"><label for="dlgName">Name</label><input type="text" id="dlgName" value="'+esc(DOC.sheets[i].name)+'"></div>',
    [['Cancel',closeDialog],['Rename',()=>{
      const v=$('dlgName').value.trim();
      if(!v) return;
      if(DOC.sheets.some((s,j)=>j!==i&&s.name.toLowerCase()===v.toLowerCase())){ toast('That name is taken'); return; }
      snap();
      const old=DOC.sheets[i].name;
      DOC.sheets[i].name=v;
      DOC.sheets.forEach((S,si)=>{ for(const k in S.cells){ const cell=S.cells[k];
        if(typeof cell.v==='string'&&cell.v[0]==='=')
          cell.v='='+tokenize(cell.v.slice(1)).map(t=>(t.t==='ref'&&t.sheet&&t.sheet.toLowerCase()===old.toLowerCase())
            ?refStr(v,t.c,t.r,t.ca,t.ra):t.src).join(''); } });
      astCache.clear(); closeDialog(); after();
    },'pri']]);
  setTimeout(()=>{ const n=$('dlgName'); n.focus(); n.select(); },30);
}
function sheetMenu(ev,i){
  showMenu(ev.clientX,ev.clientY,[
    ['Rename',()=>renameSheet(i)],
    ['Duplicate',()=>{ snap(); const c=JSON.parse(JSON.stringify(DOC.sheets[i]));
      let n=2; while(DOC.sheets.some(s=>s.name===c.name+' ('+n+')')) n++;
      c.name=c.name+' ('+n+')'; c.cells=Object.assign(Object.create(null),c.cells);
      DOC.sheets.splice(i+1,0,c); DOC.active=i+1; after(); }],
    ['Move left',()=>{ if(i===0)return; snap(); const s=DOC.sheets.splice(i,1)[0]; DOC.sheets.splice(i-1,0,s); DOC.active=i-1; after(); }],
    ['Move right',()=>{ if(i===DOC.sheets.length-1)return; snap(); const s=DOC.sheets.splice(i,1)[0]; DOC.sheets.splice(i+1,0,s); DOC.active=i+1; after(); }],
    null,
    ['Delete sheet',()=>{ if(DOC.sheets.length===1){ toast('A workbook needs at least one sheet'); return; }
      snap(); DOC.sheets.splice(i,1); DOC.active=clamp(DOC.active,0,DOC.sheets.length-1); after(); }]
  ]);
}
/* ---------- 6. UI: menus, dialogs, toolbar ---------- */
let toastT=null;
function toast(msg){
  const t=$('toast'); t.textContent=msg; t.classList.add('on');
  clearTimeout(toastT); toastT=setTimeout(()=>t.classList.remove('on'),2200);
}
const ctxEl=$('ctx'), palEl=$('pal');
function showMenu(x,y,items){
  ctxEl.innerHTML='';
  items.forEach(it=>{
    if(!it){ ctxEl.appendChild(document.createElement('hr')); return; }
    const b=document.createElement('button');
    b.innerHTML='<span>'+esc(it[0])+'</span>'+(it[2]?'<kbd>'+esc(it[2])+'</kbd>':'');
    b.onclick=()=>{ hideMenus(); it[1](); };
    ctxEl.appendChild(b);
  });
  ctxEl.style.display='block';
  const w=ctxEl.offsetWidth,h=ctxEl.offsetHeight;
  ctxEl.style.left=Math.min(x,innerWidth-w-8)+'px';
  ctxEl.style.top=Math.min(y,innerHeight-h-8)+'px';
}
function hideMenus(){ ctxEl.style.display='none'; palEl.style.display='none'; }
document.addEventListener('mousedown',e=>{ if(!e.target.closest('.menu')) hideMenus(); },true);

const PALETTE=['#000000','#1b2027','#4a5560','#7b8794','#b0b7bd','#ffffff','#a52626','#c9591b','#b26a00','#6d7d17',
'#0e6a55','#0f6a7a','#1e5aa8','#4b3fa0','#7a2f7a','#f7d4d4','#fbe3d0','#fdf0c8','#e6f0cd','#d5eee6',
'#d3ecf2','#d8e4f7','#e2ddf5','#f3daf1','#eceee9','#ff6b6b','#ff9f43','#ffd166','#a3d977','#4ecdc4',
'#45b7d1','#5f8fe8','#9b8ce8','#d98cd0','#c3c8bf'];
function showPalette(x,y,cb,withAuto){
  palEl.innerHTML='<div class="pal" id="palGrid"></div>';
  const g=palEl.firstChild;
  if(withAuto){
    const a=document.createElement('i');
    a.style.cssText='background:linear-gradient(135deg,#fff 45%,#a52626 45%,#a52626 55%,#fff 55%)';
    a.title='No fill / automatic'; a.onclick=()=>{ hideMenus(); cb(null); };
    g.appendChild(a);
  }
  PALETTE.forEach(col=>{
    const i=document.createElement('i'); i.style.background=col; i.title=col;
    i.onclick=()=>{ hideMenus(); cb(col); };
    g.appendChild(i);
  });
  palEl.style.display='block';
  palEl.style.left=Math.min(x,innerWidth-palEl.offsetWidth-8)+'px';
  palEl.style.top=Math.min(y,innerHeight-palEl.offsetHeight-8)+'px';
}
function openDialog(title,bodyHtml,buttons){
  $('dlgTitle').textContent=title;
  $('dlgBody').innerHTML=bodyHtml;
  const f=$('dlgFoot'); f.innerHTML='';
  buttons.forEach(([label,fn,cls])=>{
    const b=document.createElement('button'); b.className='btn'+(cls?' '+cls:''); b.textContent=label; b.onclick=fn;
    f.appendChild(b);
  });
  $('scrim').style.display='flex';
}
function closeDialog(){ $('scrim').style.display='none'; vp.focus(); }
$('scrim').addEventListener('mousedown',e=>{ if(e.target===$('scrim')) closeDialog(); });

/* --- context menu on grid --- */
grid.addEventListener('contextmenu',e=>{
  e.preventDefault();
  if(e.target.closest('#hcols')){
    const c=hitColHeader(e.clientX);
    if(c<selBox().c1||c>selBox().c2){ sel={r1:0,c1:c,r2:cur().nRows-1,c2:c}; render(); }
  } else if(e.target.closest('#hrows')){
    const r=hitRowHeader(e.clientY);
    if(r<selBox().r1||r>selBox().r2){ sel={r1:r,c1:0,r2:r,c2:cur().nCols-1}; render(); }
  } else if(e.target.closest('#vp')){
    const [r,c]=hitCell(e.clientX,e.clientY);
    const sb=selBox();
    if(r<sb.r1||r>sb.r2||c<sb.c1||c>sb.c2){ setSel(r,c); render(); }
  }
  const sb=selBox();
  const hasLink=!!(cur().cells[key(sel.r1,sel.c1)]||{}).link;
  const hasNote=!!(cur().cells[key(sel.r1,sel.c1)]||{}).note;
  showMenu(e.clientX,e.clientY,[
    ['Cut',()=>{ document.execCommand('cut'); },'Ctrl+X'],
    ['Copy',()=>{ document.execCommand('copy'); },'Ctrl+C'],
    ['Paste',()=>{ if(clip) pasteInternal(); else toast('Press Ctrl+V to paste from the system clipboard'); },'Ctrl+V'],
    ['Paste special…',()=>openPasteSpecial(),'Ctrl+Shift+V'],
    null,
    ['Fill down',()=>fillDR('down'),'Ctrl+D'],
    ['Fill right',()=>fillDR('right'),'Ctrl+R'],
    null,
    ['Insert '+(sb.r2-sb.r1+1)+' row(s) above',()=>insertRows(sb.r1,sb.r2-sb.r1+1)],
    ['Insert '+(sb.c2-sb.c1+1)+' column(s) left',()=>insertCols(sb.c1,sb.c2-sb.c1+1)],
    ['Delete row(s)',()=>deleteRows(sb.r1,sb.r2-sb.r1+1)],
    ['Delete column(s)',()=>deleteCols(sb.c1,sb.c2-sb.c1+1)],
    null,
    ['Hide rows',()=>hideRows(true)],
    ['Unhide rows',()=>hideRows(false)],
    ['Hide columns',()=>hideCols(true)],
    ['Unhide columns',()=>hideCols(false)],
    null,
    ['Clear contents',clearContents,'Delete'],
    ['Clear formatting',clearFormats],
    ['Merge / unmerge',mergeToggle],
    null,
    [hasLink?'Edit link…':'Insert link…',()=>editLink(),'Ctrl+K'],
    [hasNote?'Edit note…':'Insert note…',()=>editNote()],
    null,
    ['Sort A → Z',()=>sortSel(false)],
    ['Sort Z → A',()=>sortSel(true)],
    null,
    ['Print sheet…',()=>printSheet(),'Ctrl+P']
  ]);
});

function openPasteSpecial(){
  if(!clip){ toast('Nothing copied yet'); return; }
  const row=(act,label,desc)=>'<button class="btn" data-act="'+act+'" style="display:flex;flex-direction:column;align-items:flex-start;gap:2px;height:auto;padding:8px 12px;text-align:left;width:100%">'
    +'<b style="font-weight:600">'+label+'</b><span style="color:var(--ink-3);font-size:11.5px">'+desc+'</span></button>';
  openDialog('Paste special',
    '<div id="psList" style="display:flex;flex-direction:column;gap:6px">'
    + row('all','Everything','Values, formulas, and formatting')
    + row('values','Values only','Formula results as static values, no formatting')
    + row('valuesFmt','Values &amp; formatting','Results plus the source formatting')
    + row('formulas','Formulas only','Keeps formulas, drops formatting')
    + row('formats','Formatting only','Just the look — colours, borders, number format')
    + row('transpose','Transpose','Flip rows and columns (formulas become values)')
    + '</div>',
    [['Cancel',closeDialog]]);
  $('psList').addEventListener('click',e=>{ const b=e.target.closest('[data-act]'); if(!b) return;
    closeDialog(); pasteSpecial(b.dataset.act); });
}

function ruleSummary(rl){
  const rng=a1(rl.r1,rl.c1)+':'+a1(rl.r2,rl.c2);
  if(rl.type==='cell'){ const names={gt:'>',lt:'<',ge:'≥',le:'≤',eq:'=',ne:'≠',between:'between',contains:'contains',notcontains:'not contains',begins:'begins with',ends:'ends with'};
    return 'Cell '+ (names[rl.op]||rl.op) +' '+ (rl.v1!=null?rl.v1:'') + (rl.op==='between'?(' and '+rl.v2):'') + ' → '+rng; }
  if(rl.type==='top') return (rl.mode==='bottom'?'Bottom ':'Top ')+rl.n+(rl.pct?'%':'')+' → '+rng;
  if(rl.type==='dup') return (rl.mode==='unique'?'Unique':'Duplicate')+' values → '+rng;
  if(rl.type==='scale2') return '2-colour scale → '+rng;
  if(rl.type==='scale3') return '3-colour scale → '+rng;
  if(rl.type==='databar') return 'Data bars → '+rng;
  return rng;
}
function pivotFieldList(def){
  const si=sheetIndexByName(def.srcName); if(si<0) return [];
  const out=[];
  for(let c=def.c1;c<=def.c2;c++){ const v=getVal(si,def.r1,c); out.push({c, name:(v===null||v==='')?colName(c):String(v)}); }
  return out;
}
function openPivot(){
  const S=cur();
  // editing an existing pivot?
  const existing = S.pivot ? S.pivot : null;
  let def;
  if(existing){ def=JSON.parse(JSON.stringify(existing)); }
  else {
    const t=detectTable();
    if(!t || t.r2<=t.r1){ toast('Select a table with a header row, then create a pivot'); return; }
    def={srcName:cur().name, r1:t.r1,c1:t.c1,r2:t.r2,c2:t.c2, rowFields:[], colField:null, valFields:[]};
  }
  const roleOf=(c)=>{
    if(def.rowFields.includes(c)) return 'row';
    if(def.colField===c) return 'col';
    const vf=def.valFields.find(v=>v.c===c); if(vf) return 'val:'+vf.agg;
    return '';
  };
  const build=()=>{
    const fields=pivotFieldList(def);
    const opt=(cur,val,label)=>'<option value="'+val+'"'+(cur===val?' selected':'')+'>'+label+'</option>';
    const rowsHtml=fields.map(f=>{
      const role=roleOf(f.c);
      return '<div style="display:flex;align-items:center;gap:8px;margin-bottom:5px">'
        +'<span style="flex:1;font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">'+esc(f.name)+'</span>'
        +'<select data-c="'+f.c+'" style="height:26px;border:1px solid var(--line);border-radius:5px;padding:0 6px">'
          +opt(role,'','—')
          +opt(role,'row','Row')
          +opt(role,'col','Column')
          +opt(role,'val:sum','Value: Sum')
          +opt(role,'val:count','Value: Count')
          +opt(role,'val:countnum','Value: Count numbers')
          +opt(role,'val:avg','Value: Average')
          +opt(role,'val:min','Value: Min')
          +opt(role,'val:max','Value: Max')
        +'</select></div>';
    }).join('');
    return '<div class="field"><label>Source</label><input type="text" id="pvRange" value="'
        + a1(def.r1,def.c1)+':'+a1(def.r2,def.c2)+'" style="flex:0 0 150px"><span style="color:var(--ink-3);font-size:11.5px;margin-left:8px">on '+esc(def.srcName)+'</span></div>'
      +'<p style="margin:8px 0 6px;color:var(--ink-2)">Assign each field a role. Row order sets the nesting; multiple values are allowed. A single Column field builds the cross-tab.</p>'
      +'<div style="max-height:230px;overflow:auto;padding-right:4px">'+rowsHtml+'</div>';
  };
  const readForm=()=>{
    def.rowFields=[]; def.colField=null; def.valFields=[];
    [...document.querySelectorAll('#dlgBody select[data-c]')].forEach(sel=>{
      const c=+sel.dataset.c, v=sel.value;
      if(v==='row') def.rowFields.push(c);
      else if(v==='col'){ if(def.colField==null) def.colField=c; }
      else if(v.startsWith('val:')) def.valFields.push({c, agg:v.slice(4)});
    });
    const m=/^([A-Za-z]{1,3})(\d+):([A-Za-z]{1,3})(\d+)$/.exec($('pvRange').value.trim().toUpperCase());
    if(m){ def.r1=Math.min(+m[2],+m[4])-1; def.r2=Math.max(+m[2],+m[4])-1;
           def.c1=Math.min(colIndex(m[1]),colIndex(m[3])); def.c2=Math.max(colIndex(m[1]),colIndex(m[3])); }
  };
  const apply=()=>{
    readForm();
    if(!def.valFields.length){ toast('Add at least one Value field'); return; }
    if([...document.querySelectorAll('#dlgBody select[data-c]')].filter(s=>s.value==='col').length>1)
      toast('Only the first Column field is used');
    snap();
    if(existing){ cur().pivot=def; refreshPivot(cur()); }
    else {
      const ps=Object.assign(newSheet(uniquePivotName()),{pivot:def});
      DOC.sheets.push(ps); DOC.active=DOC.sheets.length-1; refreshPivot(cur());
    }
    closeDialog(); after(); vp.scrollTop=vp.scrollLeft=0; sel={r1:0,c1:0,r2:0,c2:0}; render();
    toast('Pivot table ready');
  };
  openDialog(existing?'Edit pivot table':'Create pivot table', build(),
    existing
     ? [['Delete pivot',()=>{ snap(); cur().pivot=null; closeDialog(); after(); toast('Pivot removed — the sheet keeps its cells'); }],
        ['Refresh',()=>{ readForm(); if(def.valFields.length){ snap(); cur().pivot=def; refreshPivot(cur()); after(); } }],
        ['Apply',apply,'pri']]
     : [['Cancel',closeDialog],['Create',apply,'pri']]);
}
function uniquePivotName(){ let n=1; while(DOC.sheets.some(s=>s.name==='Pivot '+n)) n++; return 'Pivot '+n; }

function openChartDialog(existing){
  const S=cur(), sb=selBox();
  const rng = existing? existing.range : {r1:sb.r1,c1:sb.c1,r2:sb.r2,c2:sb.c2};
  const rngStr = a1(rng.r1,rng.c1)+':'+a1(rng.r2,rng.c2);
  const ty = existing? existing.type : 'column';
  const title = existing? (existing.title||'') : '';
  const opt=(v,l)=>'<option value="'+v+'"'+(ty===v?' selected':'')+'>'+l+'</option>';
  openDialog(existing?'Edit chart':'Insert chart',
    '<div class="field"><label>Type</label><select id="chType">'
      +opt('column','Column')+opt('bar','Bar (horizontal)')+opt('line','Line')+opt('area','Area')+opt('pie','Pie')+opt('scatter','Scatter (X,Y)')
    +'</select></div>'
    +'<div class="field"><label>Data range</label><input type="text" id="chRange" value="'+rngStr+'"></div>'
    +'<div class="field"><label>Title</label><input type="text" id="chTitle" value="'+esc(title)+'" placeholder="(optional)"></div>'
    +'<p style="margin:6px 0 0;color:var(--ink-3);font-size:11.5px">First row and first column are used as series names and category labels when they look like text.</p>',
    [['Cancel',closeDialog],[existing?'Update':'Insert',()=>{
      const t=$('chType').value, tt=$('chTitle').value.trim();
      const m=/^([A-Za-z]{1,3})(\d+):([A-Za-z]{1,3})(\d+)$/.exec($('chRange').value.trim().toUpperCase());
      if(!m){ toast('Enter a range like A1:C10'); return; }
      const r={r1:Math.min(+m[2],+m[4])-1,r2:Math.max(+m[2],+m[4])-1,c1:Math.min(colIndex(m[1]),colIndex(m[3])),c2:Math.max(colIndex(m[1]),colIndex(m[3]))};
      snap();
      if(existing){ existing.type=t; existing.range=r; existing.title=tt; }
      else {
        const S=cur();
        const anchorX = colX[Math.min(r.c2+1,S.nCols)]!=null? colX[Math.min(r.c2+1,S.nCols)]+16 : 60;
        const ch={id:chartSeq++ +'_'+Date.now(), type:t, range:r, title:tt,
          x:anchorX, y:(rowY[r.r1]||0), w:420, h:280};
        S.charts.push(ch); selectedChart=ch.id;
      }
      invalidateCharts(); after(); closeDialog();
    },'pri']]);
  setTimeout(()=>{ const n=$('chRange'); if(n) n.focus(); },30);
}
function insertChart(){
  const sb=selBox();
  if(sb.r1===sb.r2&&sb.c1===sb.c2){ toast('Select the data range first, then insert a chart'); return; }
  openChartDialog(null);
}

function openCF(){
  const S=cur(), sb=selBox();
  const list=()=> (S.cf||[]).map((rl,i)=>
    '<div class="cfrow" style="display:flex;align-items:center;gap:8px;padding:6px 8px;border:1px solid var(--line);border-radius:6px;margin-bottom:6px">'
    +'<span style="flex:1;font-size:12.5px">'+esc(ruleSummary(rl))+'</span>'
    +'<button class="btn" data-del="'+i+'" style="height:24px;padding:0 8px">Remove</button></div>').join('')
    || '<p style="color:var(--ink-3);margin:0 0 8px">No rules yet on this sheet.</p>';
  const body =
    '<div style="max-height:190px;overflow:auto;margin-bottom:10px" id="cfList">'+list()+'</div>'
    +'<hr style="border:0;border-top:1px solid var(--chrome-2);margin:8px 0">'
    +'<p style="margin:0 0 8px;color:var(--ink-2)">New rule for <b>'+a1(sb.r1,sb.c1)+':'+a1(sb.r2,sb.c2)+'</b></p>'
    +'<div class="field"><label>Type</label><select id="cfType">'
      +'<option value="gt">Cell value greater than</option>'
      +'<option value="lt">Cell value less than</option>'
      +'<option value="between">Cell value between</option>'
      +'<option value="eq">Cell value equal to</option>'
      +'<option value="ne">Cell value not equal to</option>'
      +'<option value="ge">Cell value ≥</option>'
      +'<option value="le">Cell value ≤</option>'
      +'<option value="contains">Text contains</option>'
      +'<option value="notcontains">Text does not contain</option>'
      +'<option value="begins">Text begins with</option>'
      +'<option value="ends">Text ends with</option>'
      +'<option value="top">Top N</option>'
      +'<option value="bottom">Bottom N</option>'
      +'<option value="toppct">Top N%</option>'
      +'<option value="dup">Duplicate values</option>'
      +'<option value="unique">Unique values</option>'
      +'<option value="scale2">2-colour scale</option>'
      +'<option value="scale3">3-colour scale</option>'
      +'<option value="databar">Data bars</option>'
    +'</select></div>'
    +'<div class="field" id="cfV1row"><label id="cfV1lab">Value</label><input type="text" id="cfV1"></div>'
    +'<div class="field" id="cfV2row" style="display:none"><label>And</label><input type="text" id="cfV2"></div>'
    +'<div class="field" id="cfStyleRow"><label>Format</label><select id="cfPreset"><option value="#ffc7ce|#9c0006">Red fill / red text</option><option value="#ffeb9c|#9c6500">Yellow fill / brown text</option><option value="#c6efce|#006100">Green fill / green text</option><option value="#ffcccc|#a52626">Red border-ish (light)</option><option value="#e2e8f0|#1b2027">Grey fill</option><option value="custom">Custom…</option></select></div>'
    +'<div class="field" id="cfCustomRow" style="display:none"><label>Fill / text</label>'
      +'<input type="color" id="cfFill" value="#ffeb9c" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<input type="color" id="cfColor" value="#9c6500" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<label style="width:auto;margin-left:8px;flex:0 0 auto"><input type="checkbox" id="cfBold"> Bold</label></div>'
    +'<div class="field" id="cfScaleRow" style="display:none"><label>Colours</label>'
      +'<input type="color" id="cfMin" value="#f8696b" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<input type="color" id="cfMid" value="#ffeb84" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<input type="color" id="cfMax" value="#63be7b" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<span id="cfMidTag" style="color:var(--ink-3);font-size:11px;margin-left:6px">min · mid · max</span></div>'
    +'<div class="field" id="cfBarRow" style="display:none"><label>Bar colour</label>'
      +'<input type="color" id="cfBar" value="#5b9bd5" style="width:38px;height:28px;padding:0;border:1px solid var(--line);border-radius:5px">'
      +'<label style="width:auto;margin-left:8px;flex:0 0 auto"><input type="checkbox" id="cfGrad" checked> Gradient</label></div>';
  openDialog('Conditional formatting', body,
    [['Close',closeDialog],['Add rule',()=>cfAdd(sb),'pri']]);

  const typeEl=$('cfType');
  const upd=()=>{
    const ty=typeEl.value;
    const isText=['contains','notcontains','begins','ends'].includes(ty);
    const isCmp=['gt','lt','ge','le','eq','ne','between'].includes(ty);
    const isN=['top','bottom','toppct'].includes(ty);
    const isScale=['scale2','scale3'].includes(ty);
    const isBar=ty==='databar';
    const isDU=['dup','unique'].includes(ty);
    $('cfV1row').style.display=(isCmp||isText||isN)?'flex':'none';
    $('cfV2row').style.display=(ty==='between')?'flex':'none';
    $('cfV1lab').textContent=isN?'How many':(isText?'Text':'Value');
    $('cfStyleRow').style.display=(isCmp||isText||isN||isDU)?'flex':'none';
    $('cfScaleRow').style.display=isScale?'flex':'none';
    $('cfMid').style.display=(ty==='scale3')?'':'none';
    $('cfBarRow').style.display=isBar?'flex':'none';
    $('cfCustomRow').style.display=($('cfPreset').value==='custom' && (isCmp||isText||isN||isDU))?'flex':'none';
    if(isN&&!$('cfV1').value) $('cfV1').value='10';
  };
  typeEl.addEventListener('change',upd);
  $('cfPreset').addEventListener('change',upd);
  upd();
  $('cfList').addEventListener('click',e=>{ const b=e.target.closest('[data-del]'); if(!b) return;
    snap(); S.cf.splice(+b.dataset.del,1); cfCache.gen=-1; after(); openCF(); });
}
function cfAdd(sb){
  const S=cur(), ty=$('cfType').value;
  const base={r1:sb.r1,c1:sb.c1,r2:sb.r2,c2:sb.c2};
  let rule;
  const preset=$('cfPreset').value;
  let fill,color,bold=false;
  if(preset==='custom'){ fill=$('cfFill').value; color=$('cfColor').value; bold=$('cfBold').checked; }
  else { const parts=preset.split('|'); fill=parts[0]; color=parts[1]; }
  const styleBits={fill,color,bold};
  if(['gt','lt','ge','le','eq','ne','between'].includes(ty)){
    rule=Object.assign(base,{type:'cell',op:ty,v1:$('cfV1').value,v2:$('cfV2').value},styleBits);
  } else if(['contains','notcontains','begins','ends'].includes(ty)){
    rule=Object.assign(base,{type:'cell',op:ty,v1:$('cfV1').value},styleBits);
  } else if(ty==='top'||ty==='bottom'||ty==='toppct'){
    rule=Object.assign(base,{type:'top',mode:(ty==='bottom'?'bottom':'top'),n:Math.max(1,parseInt($('cfV1').value,10)||10),pct:ty==='toppct'},styleBits);
  } else if(ty==='dup'||ty==='unique'){
    rule=Object.assign(base,{type:'dup',mode:ty},styleBits);
  } else if(ty==='scale2'){
    rule=Object.assign(base,{type:'scale2',minColor:$('cfMin').value,maxColor:$('cfMax').value});
  } else if(ty==='scale3'){
    rule=Object.assign(base,{type:'scale3',minColor:$('cfMin').value,midColor:$('cfMid').value,maxColor:$('cfMax').value});
  } else if(ty==='databar'){
    rule=Object.assign(base,{type:'databar',color:$('cfBar').value,grad:$('cfGrad').checked});
  }
  snap(); S.cf.push(rule); cfCache.gen=-1; after(); openCF();
  toast('Rule added');
}

/* --- find & replace --- */
function openFind(){
  openDialog('Find and replace',
    '<div class="field"><label for="fFind">Find</label><input type="text" id="fFind"></div>'+
    '<div class="field"><label for="fRepl">Replace with</label><input type="text" id="fRepl"></div>'+
    '<div class="field"><label for="fScope">Look in</label><select id="fScope">'+
      '<option value="values">Displayed values</option><option value="raw">Formulas &amp; raw text</option></select></div>'+
    '<div class="field"><label for="fWhere">Search</label><select id="fWhere">'+
      '<option value="sheet">This sheet</option><option value="book">All sheets</option></select></div>'+
    '<div class="field"><label for="fCase">Match case</label><input type="checkbox" id="fCase" style="flex:0 0 auto"></div>'+
    '<div id="fStat" style="color:var(--ink-3);min-height:16px"></div>',
    [['Close',closeDialog],['Find next',()=>findNext(1),''],['Replace all',replaceAll,'pri']]);
  setTimeout(()=>{ const n=$('fFind'); if(n){ n.focus(); n.onkeydown=e=>{ if(e.key==='Enter') findNext(1); }; } },30);
}
function cellText(si,r,c,scope){
  const S=DOC.sheets[si], x=S.cells[key(r,c)];
  if(!x) return '';
  if(scope==='raw') return String(x.v);
  return String(displayText(getVal(si,r,c),x.s&&x.s.fmt));
}
function findNext(dir){
  const q=$('fFind').value; if(!q) return;
  const cs=$('fCase').checked, scope=$('fScope').value, all=$('fWhere').value==='book';
  const needle=cs?q:q.toLowerCase();
  const sheets=all?DOC.sheets.map((_,i)=>i):[DOC.active];
  let start=sheets.indexOf(DOC.active); if(start<0) start=0;
  for(let sIdx=0;sIdx<sheets.length;sIdx++){
    const si=sheets[(start+sIdx)%sheets.length];
    const S=DOC.sheets[si];
    let r0=0,c0=0;
    if(si===DOC.active&&sIdx===0){ r0=sel.r1; c0=sel.c1+1; }
    for(let r=r0;r<S.nRows;r++){
      for(let c=(r===r0?c0:0);c<S.nCols;c++){
        let t=cellText(si,r,c,scope); if(!cs) t=t.toLowerCase();
        if(t&&t.indexOf(needle)>=0){
          DOC.active=si; buildTabs(); setSel(r,c); scrollIntoView(r,c); render();
          $('fStat').textContent='Found in '+S.name+'!'+a1(r,c);
          return true;
        }
      }
    }
  }
  $('fStat').textContent='No more matches';
  return false;
}
function replaceAll(){
  const q=$('fFind').value; if(!q) return;
  const rep=$('fRepl').value, cs=$('fCase').checked, all=$('fWhere').value==='book';
  snap();
  const rx=new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),cs?'g':'gi');
  let n=0;
  (all?DOC.sheets:[cur()]).forEach(S=>{
    for(const k in S.cells){
      const cell=S.cells[k];
      const t=String(cell.v);
      if(rx.test(t)){ rx.lastIndex=0; const nt=t.replace(rx,rep); if(nt!==t){ n++;
        const [r,c]=k.split(':').map(Number); setCellInput(S,r,c,nt); } }
      rx.lastIndex=0;
    }
  });
  after();
  $('fStat').textContent=n?('Replaced '+n+' cell'+(n===1?'':'s')):'Nothing to replace';
}

/* --- function reference --- */
function openFns(){
  const names=Object.keys(FN).sort();
  const html='<p style="margin:0 0 12px;color:var(--ink-3)">'+names.length+
    ' functions. Type <code>=</code> in a cell to start a formula. Ranges (A1:B9), absolute refs ($A$1) and cross-sheet refs (Sheet2!A1) all work.</p>'+
    '<div id="fnlist">'+names.map(n=>'<b>'+n+'</b>').join('')+'</div>';
  openDialog('Function reference',html,[['Close',closeDialog,'pri']]);
}

/* --- import / export --- */
function download(name,text,mime){
  const b=new Blob([text],{type:mime||'text/plain;charset=utf-8'});
  const u=URL.createObjectURL(b), a=document.createElement('a');
  a.href=u; a.download=name; a.rel='noopener';
  a.style.display='none';
  document.body.appendChild(a);          // Firefox/Safari ignore clicks on detached anchors
  a.click();
  setTimeout(()=>{ document.body.removeChild(a); URL.revokeObjectURL(u); },3000);
}
function usedRange(S){
  let r2=-1,c2=-1;
  for(const k in S.cells){ const cell=S.cells[k]; if(cell.v===''||cell.v==null) continue;
    const [r,c]=k.split(':').map(Number); if(r>r2)r2=r; if(c>c2)c2=c; }
  return {r2,c2};
}
function sheetCSV(S,si){
  const {r2,c2}=usedRange(S);
  const out=[];
  for(let r=0;r<=r2;r++){
    const row=[];
    for(let c=0;c<=c2;c++){
      const x=S.cells[key(r,c)];
      let t=x?String(displayText(getVal(si,r,c),x.s&&x.s.fmt)):'';
      if(/[",\n]/.test(t)) t='"'+t.replace(/"/g,'""')+'"';
      row.push(t);
    }
    out.push(row.join(','));
  }
  return out.join('\n');
}
function sheetHTML(S,si){
  const {r2,c2}=usedRange(S);
  let h='<table style="border-collapse:collapse;font-family:sans-serif;font-size:13px">';
  for(let r=0;r<=r2;r++){
    h+='<tr>';
    for(let c=0;c<=c2;c++){
      const x=S.cells[key(r,c)], s=x&&x.s;
      const v=getVal(si,r,c);
      let st='border:1px solid #ccc;padding:3px 6px;';
      if(s){ if(s.b)st+='font-weight:700;'; if(s.i)st+='font-style:italic;';
        if(s.color)st+='color:'+s.color+';'; if(s.bg)st+='background:'+s.bg+';';
        if(s.ha)st+='text-align:'+s.ha+';'; }
      else if(typeof v==='number') st+='text-align:right;';
      h+='<td style="'+st+'">'+esc(displayText(v,s&&s.fmt))+'</td>';
    }
    h+='</tr>';
  }
  return h+'</table>';
}
function saveAs(kind){
  const S=cur();
  if(kind==='json'){ download((DOC.name||'workbook')+'.json',serialize(),'application/json'); dirty=false; }
  else if(kind==='csv') download(S.name+'.csv',sheetCSV(S,DOC.active),'text/csv;charset=utf-8');
}
$('fileIn').addEventListener('change',e=>{
  const f=e.target.files[0]; if(!f) return;
  const rd=new FileReader();
  rd.onload=()=>{
    const txt=String(rd.result);
    snap();
    if(/\.json$/i.test(f.name)){
      try{ deserialize(txt); DOC.name=f.name.replace(/\.json$/i,''); }
      catch(err){ toast('That file is not a valid workbook'); return; }
    } else {
      const rows=parseCSV(txt);
      const S=newSheet(f.name.replace(/\.[^.]+$/,'').slice(0,28));
      rows.forEach((line,r)=>line.forEach((v,c)=>{ if(v!=='') setCellInput(S,r,c,v); }));
      S.nRows=Math.max(200,rows.length+40);
      S.nCols=Math.max(26,Math.max(...rows.map(r=>r.length))+4);
      DOC.sheets.push(S); DOC.active=DOC.sheets.length-1;
    }
    sel={r1:0,c1:0,r2:0,c2:0};
    after(); toast('Opened '+f.name);
  };
  rd.readAsText(f);
  e.target.value='';
});

/* --- toolbar wiring --- */
const FONTS=['Default','Arial','Georgia','Courier New','Times New Roman','Verdana','Tahoma','Trebuchet MS','Garamond','Impact'];
const SIZES=[8,9,10,11,12,13,14,16,18,20,24,28,32,40,48];
FONTS.forEach(f=>{ const o=document.createElement('option'); o.value=(f==='Default'?'':f); o.textContent=f; $('selFont').appendChild(o); });
SIZES.forEach(s=>{ const o=document.createElement('option'); o.value=s; o.textContent=s; $('selSize').appendChild(o); });

function syncToolbar(){
  const S=cur(), x=S.cells[key(sel.r1,sel.c1)], s=(x&&x.s)||{};
  [['btnB','b'],['btnI','i'],['btnU','u'],['btnS','st']].forEach(([id,k])=>$(id).classList.toggle('on',!!s[k]));
  $('btnWrap').classList.toggle('on',!!s.wrap);
  $('btnAL').classList.toggle('on',s.ha==='left');
  $('btnAC').classList.toggle('on',s.ha==='center');
  $('btnAR').classList.toggle('on',s.ha==='right');
  $('btnVT').classList.toggle('on',s.va==='top');
  $('btnVM').classList.toggle('on',s.va==='middle');
  $('btnVB').classList.toggle('on',s.va==='bottom'||!s.va);
  $('selFont').value=s.ff||'';
  $('selSize').value=s.fs||13;
  $('selFmt').value=(s.fmt&&s.fmt.t)||'general';
  $('btnMerge').classList.toggle('on',!!mergeOf(S,sel.r1,sel.c1));
  $('btnFreeze').classList.toggle('on',!!(S.fzR||S.fzC));
  $('btnPaint').classList.toggle('on',!!painter);
  $('btnFilter').classList.toggle('on',!!cur().filter);
  $('btnUndo').disabled=!undoStack.length;
  $('btnRedo').disabled=!redoStack.length;
}
let lastColor='#a52626', lastFill='#ffe680';
$('btnB').onclick=()=>toggleStyle('b');
$('btnI').onclick=()=>toggleStyle('i');
$('btnU').onclick=()=>toggleStyle('u');
$('btnS').onclick=()=>toggleStyle('st');
$('btnWrap').onclick=()=>{ const S=cur(),x=S.cells[key(sel.r1,sel.c1)]; setStyle({wrap:!(x&&x.s&&x.s.wrap)}); };
$('btnAL').onclick=()=>setStyle({ha:'left'});
$('btnAC').onclick=()=>setStyle({ha:'center'});
$('btnAR').onclick=()=>setStyle({ha:'right'});
$('btnVT').onclick=()=>setStyle({va:'top'});
$('btnVM').onclick=()=>setStyle({va:'middle'});
$('btnVB').onclick=()=>setStyle({va:'bottom'});
$('btnMerge').onclick=mergeToggle;
$('btnPaint').onclick=()=>{ if(painter) setPainter(null); else capturePainter(false); };
$('btnPaint').ondblclick=()=>{ capturePainter(true); };
$('btnColor').onclick=e=>{ const r=e.currentTarget.getBoundingClientRect();
  showPalette(r.left,r.bottom+4,col=>{ lastColor=col||'#1b2027'; $('swColor').style.background=lastColor;
    setStyle({color:col||undefined}); },true); };
$('btnFill').onclick=e=>{ const r=e.currentTarget.getBoundingClientRect();
  showPalette(r.left,r.bottom+4,col=>{ lastFill=col||'#ffffff'; $('swFill').style.background=lastFill;
    setStyle({bg:col||undefined}); },true); };
$('btnBorder').onclick=e=>{
  const r=e.currentTarget.getBoundingClientRect();
  showMenu(r.left,r.bottom+4,[
    ['All borders',()=>applyBorder('all')],
    ['Outside border',()=>applyBorder('outer')],
    ['Top border',()=>applyBorder('top')],
    ['Bottom border',()=>applyBorder('bottom')],
    ['Left border',()=>applyBorder('left')],
    ['Right border',()=>applyBorder('right')],
    null,
    ['Thick outside (accent)',()=>applyBorder('outer','#0e6a55')],
    ['No border',()=>applyBorder('none')]
  ]);
};
$('selFont').onchange=e=>setStyle({ff:e.target.value||undefined});
$('selSize').onchange=e=>setStyle({fs:+e.target.value});
$('selFmt').onchange=e=>setNumFmt(e.target.value);
$('btnDec+').onclick=()=>bumpDec(1);
$('btnDec-').onclick=()=>bumpDec(-1);
$('btnInsRow').onclick=()=>{ const sb=selBox(); insertRows(sb.r1,sb.r2-sb.r1+1); };
$('btnInsCol').onclick=()=>{ const sb=selBox(); insertCols(sb.c1,sb.c2-sb.c1+1); };
$('btnDelRow').onclick=()=>{ const sb=selBox(); deleteRows(sb.r1,sb.r2-sb.r1+1); };
$('btnDelCol').onclick=()=>{ const sb=selBox(); deleteCols(sb.c1,sb.c2-sb.c1+1); };
function autoSum(){
  const S=cur(), sb=selBox(), r=sb.r1, c=sb.c1;
  let r0=r-1; while(r0>=0&&typeof getVal(DOC.active,r0,c)==='number') r0--;
  if(r0<r-1){ snap(); setCellInput(S,r,c,'=SUM('+a1(r0+1,c)+':'+a1(r-1,c)+')'); after(); return; }
  let c0=c-1; while(c0>=0&&typeof getVal(DOC.active,r,c0)==='number') c0--;
  if(c0<c-1){ snap(); setCellInput(S,r,c,'=SUM('+a1(r,c0+1)+':'+a1(r,c-1)+')'); after(); return; }
  toast('No numbers above or to the left to add up');
}
$('btnSum').onclick=autoSum;
$('btnFreeze').onclick=freezeHere;
$('btnSortA').onclick=()=>sortSel(false);
$('btnSortD').onclick=()=>sortSel(true);
$('btnFilter').onclick=toggleFilter;
$('btnCF').onclick=openCF;
$('btnChart').onclick=insertChart;
$('btnPivot').onclick=openPivot;
$('btnFind').onclick=openFind;
$('btnFns').onclick=openFns;
$('fxbtn').onclick=openFns;
$('btnUndo').onclick=undo;
$('btnRedo').onclick=redo;
$('btnOpen').onclick=()=>$('fileIn').click();
$('selSave').onchange=e=>{ const v=e.target.value; e.target.value=''; if(v) saveAs(v); };
$('btnPrint').onclick=printSheet;
$('btnNew').onclick=()=>{
  openDialog('New workbook','<p style="margin:0">This replaces everything currently open. Unsaved changes are lost.</p>',
    [['Cancel',closeDialog],['Create new workbook',()=>{ snap(); DOC={sheets:[newSheet('Sheet1')],active:0,name:'Untitled workbook'};
      sel={r1:0,c1:0,r2:0,c2:0}; closeDialog(); after(); },'pri']]);
};
$('selZoom').onchange=e=>{ zoom=parseInt(e.target.value,10)/100; render(); };

window.addEventListener('beforeunload',e=>{ if(dirty){ e.preventDefault(); e.returnValue=''; } });

/* ---------- public API (for the surrounding PHP page) ---------- */
window.Sheet={
  get doc(){ return DOC; },
  toJSON:()=>serialize(),
  load:txt=>{ deserialize(typeof txt==='string'?txt:JSON.stringify(txt)); after(); },
  toCSV:(i)=>sheetCSV(DOC.sheets[i==null?DOC.active:i],i==null?DOC.active:i),
  toHTML:(i)=>sheetHTML(DOC.sheets[i==null?DOC.active:i],i==null?DOC.active:i),
  value:(ref,sheet)=>{ const m=/^([A-Za-z]{1,3})(\d+)$/.exec(ref); if(!m) return null;
    const si=sheet==null?DOC.active:(typeof sheet==='number'?sheet:sheetIndexByName(sheet));
    return getVal(si,+m[2]-1,colIndex(m[1])); },
  set:(ref,val,sheet)=>{ const m=/^([A-Za-z]{1,3})(\d+)$/.exec(ref); if(!m) return;
    const si=sheet==null?DOC.active:(typeof sheet==='number'?sheet:sheetIndexByName(sheet));
    setCellInput(DOC.sheets[si],+m[2]-1,colIndex(m[1]),val); after(); },
  isDirty:()=>dirty,
  markSaved:()=>{ dirty=false; },
  refresh:after
};
var onWorkbookChange=null;
window.Sheet.onChange=fn=>{ onWorkbookChange=fn; };
window.Spreadsheet=window.Sheet; window.Gridwork=window.Sheet; /* aliases */

/* ---------- boot ---------- */
/* start blank: a single empty sheet, comfortable default widths */
(function(){ const S=cur(); for(let c=0;c<6;c++) S.colW[c]=96; })();
buildTabs();
recalc();
render();
vp.focus();
dirty=false;
</script>
</body>
</html>

Reaches out to

Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.

  • www.w3.org
  • example.com

Licence

Published on Globefin under the MIT License. You may copy, change, and reuse this page, including commercially — just keep the notice below with it.

Copyright © 2026 Shane Hadden. Licensed under the MIT License. Published on Globefin.

Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →

Sandbox

Scripts run, but the demo has its own throwaway origin. It can't read your session or cookies, can't reach the page around it, and can't navigate your tab. Don't enter real passwords or personal data into any demo.