<template>
  <div
    class="eg-shell"
    :class="['eg-size-' + internalSize, 'eg-theme-' + internalTheme, { 'eg-shell-fullscreen': isFullscreen, 'eg-locked': internalLocked }]"
    :style="shellStyle"
  >
    <!-- Toolbar -->
    <div v-if="_toolbarVisible" class="eg-toolbar">
      <div class="eg-toolbar-group">
        <button
          v-if="toolbarHas('undoRedo')"
          type="button"
          class="eg-toolbar-btn"
          :disabled="internalLocked || !canUndo || toolbarDisabled('undoRedo')"
          :title="t.undo"
          @click="undo"
        ><span class="eg-toolbar-icon eg-icon-undo"></span></button>
        <button
          v-if="toolbarHas('undoRedo')"
          type="button"
          class="eg-toolbar-btn"
          :disabled="internalLocked || !canRedo || toolbarDisabled('undoRedo')"
          :title="t.redo"
          @click="redo"
        ><span class="eg-toolbar-icon eg-icon-redo"></span></button>
      </div>

      <div class="eg-toolbar-group">
        <button
          v-if="toolbarHas('export')"
          type="button"
          class="eg-toolbar-btn"
          :disabled="toolbarDisabled('export')"
          :title="t.export"
          @click="toolbarExportClick"
        ><span class="eg-toolbar-icon eg-icon-export"></span></button>
        <button
          v-if="toolbarHas('import')"
          type="button"
          class="eg-toolbar-btn"
          :disabled="internalLocked || toolbarDisabled('import')"
          :title="t.import"
          @click="toolbarImportClick"
        ><span class="eg-toolbar-icon eg-icon-import"></span></button>
        <input
          v-if="toolbarHas('import')"
          ref="toolbarImportInput"
          type="file"
          accept=".xlsx,.xls,.csv"
          style="display: none"
          @change="onToolbarImportFile"
        >
        <button
          v-if="toolbarHas('print')"
          type="button"
          class="eg-toolbar-btn"
          :disabled="toolbarDisabled('print')"
          :title="t.print"
          @click="printGrid"
        ><span class="eg-toolbar-icon eg-icon-print"></span></button>
        <button
          v-if="localSyncKey && toolbarHas('localSync')"
          type="button"
          class="eg-toolbar-btn eg-toolbar-btn-badged"
          :disabled="toolbarDisabled('localSync')"
          :title="localSyncAvailable ? t.localSyncAvailable : t.localSync"
          @click="openLocalSyncModal"
        ><span class="eg-toolbar-icon eg-icon-local-sync"></span
        ><span v-if="localSyncAvailable" class="eg-toolbar-badge" aria-hidden="true"></span></button>
      </div>

      <slot name="toolbar-extra" :locked="internalLocked" :fullscreen="isFullscreen"></slot>

      <div v-if="toolbarButtons.length" class="eg-toolbar-group">
        <button
          v-for="btn in toolbarButtons"
          :key="btn.key"
          type="button"
          class="eg-toolbar-btn"
          :title="btn.title"
          @click="onToolbarButtonClick(btn, $event)"
        ><span class="eg-toolbar-icon" :style="btn.icon ? { maskImage: 'url(' + btn.icon + ')', webkitMaskImage: 'url(' + btn.icon + ')' } : null">{{ btn.icon ? '' : (btn.label || '') }}</span></button>
      </div>

      <div class="eg-toolbar-spacer"></div>

      <div v-if="toolbarHas('theme')" class="eg-toolbar-group">
        <select
          class="eg-toolbar-select"
          :value="internalTheme"
          :disabled="toolbarDisabled('theme')"
          :title="t.theme"
          @change="setTheme($event.target.value)"
        >
          <option value="excel">Excel</option>
          <option value="material">Material</option>
          <option value="antd">Ant Design</option>
          <option value="fluent">Fluent</option>
          <option value="carbon">Carbon</option>
        </select>
      </div>

      <div v-if="toolbarHas('size')" class="eg-toolbar-segmented" role="radiogroup" :aria-label="t.size">
        <button
          v-for="key in sizeOptions"
          :key="key"
          type="button"
          role="radio"
          class="eg-toolbar-btn eg-toolbar-segment"
          :class="['eg-toolbar-segment-' + key, { 'eg-toolbar-btn-active': internalSize === key }]"
          :aria-checked="internalSize === key"
          :disabled="toolbarDisabled('size')"
          :title="sizeTitle(key)"
          @click="setSize(key)"
        ><span class="eg-toolbar-icon" :class="'eg-icon-size-' + key"></span></button>
      </div>

      <div class="eg-toolbar-group">
        <button
          v-if="toolbarHas('lock')"
          type="button"
          class="eg-toolbar-btn"
          :class="{ 'eg-toolbar-btn-active': internalLocked }"
          :disabled="toolbarDisabled('lock')"
          :title="internalLocked ? t.unlock : t.lock"
          @click="toggleLock"
        ><span class="eg-toolbar-icon" :class="internalLocked ? 'eg-icon-lock' : 'eg-icon-unlock'"></span></button>
        <button
          v-if="toolbarHas('fullscreen')"
          type="button"
          class="eg-toolbar-btn"
          :class="{ 'eg-toolbar-btn-active': isFullscreen }"
          :disabled="toolbarDisabled('fullscreen')"
          :title="isFullscreen ? t.exitFullscreen : t.fullscreen"
          @click="toggleFullscreen"
        ><span class="eg-toolbar-icon" :class="isFullscreen ? 'eg-icon-compress' : 'eg-icon-expand'"></span></button>
      </div>
    </div>

  <div
    class="eg-wrapper"
    :class="'eg-size-' + internalSize"
    :style="wrapperStyle"
    tabindex="0"
    @keydown="onKeyDown"
    @keypress="onKeyPress"
    ref="wrapper"
  >
    <!-- Context menu -->
    <div
      v-if="contextMenu.visible"
      key="eg-context-menu"
      ref="contextMenuEl"
      class="eg-context-menu"
      :style="{ top: contextMenu.y + 'px', left: (contextMenuPositioned ? contextMenu.x : -9999) + 'px', visibility: contextMenuPositioned ? 'visible' : 'hidden' }"
      @click.stop
    >
      <div class="eg-context-item" @click="ctxCopy">{{ t.copy }}</div>
      <div class="eg-context-item" @click="ctxCut">{{ t.cut }}</div>
      <div class="eg-context-item" @click="ctxPaste">{{ t.paste }}</div>
      <div class="eg-context-separator"></div>
      <div class="eg-context-item eg-context-submenu-parent">
        {{ t.pasteSpecial }}
        <div class="eg-context-submenu">
          <div class="eg-context-item" @click="ctxPasteSpecial('all')">{{ t.pasteAll }}</div>
          <div class="eg-context-item" @click="ctxPasteSpecial('values')">{{ t.pasteValues }}</div>
          <div class="eg-context-item" @click="ctxPasteSpecial('formats')">{{ t.pasteFormats }}</div>
          <div class="eg-context-item" @click="ctxPasteSpecial('all', true)">{{ t.transpose }}</div>
        </div>
      </div>
      <div class="eg-context-separator"></div>
      <div class="eg-context-item" @click="ctxMerge">{{ t.mergeCells }}</div>
      <div class="eg-context-item" @click="ctxUnmerge">{{ t.unmergeCells }}</div>
      <div class="eg-context-separator"></div>
      <div v-if="contextMenu.row >= 0" class="eg-context-item" @click="ctxHideRow">{{ t.hideRows }}</div>
      <div v-if="contextMenu.col >= 0" class="eg-context-item" @click="ctxHideColumn">{{ t.hideColumns }}</div>
      <div class="eg-context-item" @click="ctxUnhideRows">{{ t.unhideRows }}</div>
      <div class="eg-context-item" @click="ctxUnhideColumns">{{ t.unhideColumns }}</div>
      <template v-if="contextMenu.row < 0 && contextMenu.col >= 0">
        <div class="eg-context-separator"></div>
        <div class="eg-context-item" @click="ctxPinLeft">{{ t.pinLeft }}</div>
        <div class="eg-context-item" @click="ctxPinRight">{{ t.pinRight }}</div>
        <div class="eg-context-item" v-if="isColPinned(contextMenu.col)" @click="ctxUnpin">{{ t.unpin }}</div>
      </template>
      <template v-if="devMode && (contextMenu.col >= 0 || contextMenu.row >= 0)">
        <div class="eg-context-separator"></div>
        <div class="eg-context-item" v-if="contextMenu.col >= 0" @click="ctxShowColumnInfo">{{ t.columnInfo }}</div>
        <div class="eg-context-item" v-if="contextMenu.row >= 0" @click="ctxShowRowInfo">{{ t.rowInfo }}</div>
      </template>
    </div>

    <!-- Sort popup menu (header sort icon) -->
    <div
      v-if="sortMenu.visible"
      key="eg-sort-menu"
      ref="sortMenuEl"
      class="eg-context-menu eg-sort-menu"
      :style="{ top: sortMenu.y + 'px', left: (sortMenuPositioned ? sortMenu.x : -9999) + 'px', visibility: sortMenuPositioned ? 'visible' : 'hidden' }"
      @click.stop
    >
      <div class="eg-context-item" :class="{ 'eg-context-item-active': isSortMenuOptionActive('asc') }" @click="sortMenuPickAsc">{{ t.sortMenuAsc }}</div>
      <div class="eg-context-item" :class="{ 'eg-context-item-active': isSortMenuOptionActive('desc') }" @click="sortMenuPickDesc">{{ t.sortMenuDesc }}</div>
      <div class="eg-context-separator"></div>
      <div class="eg-context-item" @click="sortMenuPickClear">{{ t.sortMenuClear }}</div>
    </div>

    <!-- devMode: column/row info modal -->
    <div v-if="infoModal" key="eg-info-modal-backdrop" class="eg-info-modal-backdrop" @click="closeInfoModal">
      <div class="eg-info-modal" @click.stop>
        <div class="eg-info-modal-header">
          <span class="eg-info-modal-title">{{ infoModal.title }}</span>
          <button type="button" class="eg-info-modal-close" @click="closeInfoModal">×</button>
        </div>
        <pre class="eg-info-modal-body">{{ infoModal.json }}</pre>
      </div>
    </div>

    <!-- Scroll container -->
    <div class="eg-container" :class="{ 'eg-col-dragging': colDrag.active }" ref="container" @scroll="onScroll" @click="hideFloatingMenus">

      <!-- ===== HEADER AREA ===== -->
      <div class="eg-header-area" :style="headerAreaStyle">

        <!-- Corner cell -->
        <div
          class="eg-corner"
          :style="cornerStyle"
          @click="selectAll"
        ></div>

        <!-- Row group outline gutter (left) -->
        <div v-if="rowGroups.length" class="eg-row-outline-gutter" :style="rowOutlineGutterStyle"></div>

        <!-- Frozen columns header -->
        <div v-if="getFrozenWidth() > 0" class="eg-frozen-col-header" :class="{ 'eg-shadow-edge': hasHiddenScrollLeft() }" :style="frozenColHeaderStyle">
          <div :style="{ position: 'relative', height: (headerRowHeight * headerDepth + _filterRowH) + 'px' }">
            <template v-for="(row, rowIdx) in headerRows">
              <template v-for="cell in row">
                <template v-if="isCellVisible(cell, rowIdx, true)">
                  <div
                    :key="'fh-' + rowIdx + '-' + (cell.column.key || cell.column.title)"
                    class="eg-header-cell"
                    :class="{ 'eg-header-group': cell.isGroup, 'eg-header-cell--drag-source': colDrag.active && cell._firstLeafFlatIndex >= colDrag.sourceFirstLeaf && cell._firstLeafFlatIndex < colDrag.sourceFirstLeaf + colDrag.sourceLeafCount }"
                    :data-fi="!cell.isGroup ? cell.column._flatIndex : undefined"
                    :data-start="cell.isGroup ? cell._firstLeafFlatIndex : undefined"
                    :data-end="cell.isGroup ? cell._firstLeafFlatIndex + cell.colspan - 1 : undefined"
                    :style="getHeaderCellStyle(cell, rowIdx, true)"
                    @mousedown="onColHeaderMouseDown($event, cell)"
                    @dblclick="onColHeaderDblClick($event, cell)"
                    @contextmenu.prevent="onColHeaderContextMenu($event, cell)"
                  >
                    <slot v-if="!cell.isGroup" :name="'header-' + cell.column.key" :column="cell.column">
                      {{ cell.column.title }}
                    </slot>
                    <span v-else>{{ cell.column.title }}</span>
                    <span
                      v-if="!cell.isGroup && isColSortable(cell.column)"
                      class="eg-sort-icon"
                      :class="sortIconClass(cell.column)"
                      :title="sortIconTitle()"
                      @mousedown.stop
                      @click.stop="openSortMenu($event, cell.column)"
                    ></span>
                    <div
                      v-if="!cell.isGroup"
                      class="eg-col-resize-handle"
                      @mousedown.stop="startColResize($event, cell.column._flatIndex)"
                    ></div>
                  </div>
                </template>
              </template>
            </template>
            <template v-if="filterRow">
              <template v-for="(col, ci) in leafCols">
                <template v-if="isColumnPinnedLeft(ci) && !isColHidden(ci)">
                  <div
                    :key="'ffilter-' + ci"
                    class="eg-filter-cell"
                    :class="{ 'eg-filter-cell-empty': filterControlType(col) === 'none' }"
                    :style="getFilterCellStyle(ci)"
                    @mousedown.stop
                  >
                    <input
                      v-if="filterControlType(col) === 'text'"
                      type="text"
                      class="eg-filter-input"
                      :value="internalFilters[col.key] || ''"
                      :placeholder="t.filterPlaceholder"
                      @input="setFilter(col.key, $event.target.value)"
                      @keydown.stop
                      @click.stop
                    />
                    <select
                      v-else-if="filterControlType(col) === 'select'"
                      class="eg-filter-select"
                      :value="internalFilters[col.key] || ''"
                      @change="setFilter(col.key, $event.target.value)"
                      @click.stop
                    >
                      <option value="">{{ t.filterAll }}</option>
                      <option v-for="opt in filterOptionsFor(col)" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                    </select>
                    <select
                      v-else-if="filterControlType(col) === 'checkbox'"
                      class="eg-filter-select"
                      :value="internalFilters[col.key] || ''"
                      @change="setFilter(col.key, $event.target.value)"
                      @click.stop
                    >
                      <option value="">{{ t.filterAll }}</option>
                      <option value="true">{{ t.filterChecked }}</option>
                      <option value="false">{{ t.filterUnchecked }}</option>
                    </select>
                  </div>
                </template>
              </template>
            </template>
          </div>
        </div>

        <!-- Scrollable columns header -->
        <div class="eg-scroll-col-header" ref="scrollColHeader" :style="scrollColHeaderStyle">
          <!-- Inner width = scrollable columns only: this strip renders no pinned cells
               (they live in the sibling zones), and scrollableContentWidth keeps its max
               scrollLeft identical to the body's (see scrollColHeaderStyle). -->
          <div class="eg-scroll-col-header-inner" :style="{ width: scrollableContentWidth + 'px', height: (headerRowHeight * headerDepth + _filterRowH) + 'px', position: 'relative' }">
            <template v-for="(row, rowIdx) in headerRows">
              <template v-for="cell in row">
                <template v-if="isCellVisible(cell, rowIdx, false)">
                  <div
                    :key="'sh-' + rowIdx + '-' + (cell.column.key || cell.column.title)"
                    class="eg-header-cell"
                    :class="{ 'eg-header-group': cell.isGroup, 'eg-header-cell--drag-source': colDrag.active && cell._firstLeafFlatIndex >= colDrag.sourceFirstLeaf && cell._firstLeafFlatIndex < colDrag.sourceFirstLeaf + colDrag.sourceLeafCount }"
                    :data-fi="!cell.isGroup ? cell.column._flatIndex : undefined"
                    :data-start="cell.isGroup ? cell._firstLeafFlatIndex : undefined"
                    :data-end="cell.isGroup ? cell._firstLeafFlatIndex + cell.colspan - 1 : undefined"
                    :style="getHeaderCellStyle(cell, rowIdx, false)"
                    @mousedown="onColHeaderMouseDown($event, cell)"
                    @dblclick="onColHeaderDblClick($event, cell)"
                    @contextmenu.prevent="onColHeaderContextMenu($event, cell)"
                  >
                    <slot v-if="!cell.isGroup" :name="'header-' + cell.column.key" :column="cell.column">
                      {{ cell.column.title }}
                    </slot>
                    <span v-else>{{ cell.column.title }}</span>
                    <span
                      v-if="!cell.isGroup && isColSortable(cell.column)"
                      class="eg-sort-icon"
                      :class="sortIconClass(cell.column)"
                      :title="sortIconTitle()"
                      @mousedown.stop
                      @click.stop="openSortMenu($event, cell.column)"
                    ></span>
                    <div
                      v-if="!cell.isGroup"
                      class="eg-col-resize-handle"
                      @mousedown.stop="startColResize($event, cell.column._flatIndex)"
                    ></div>
                  </div>
                </template>
              </template>
            </template>
            <template v-if="filterRow">
              <template v-for="(col, ci) in leafCols">
                <template v-if="isColumnScrollable(ci) && !isColHidden(ci)">
                  <div
                    :key="'sfilter-' + ci"
                    class="eg-filter-cell"
                    :class="{ 'eg-filter-cell-empty': filterControlType(col) === 'none' }"
                    :style="getFilterCellStyle(ci)"
                    @mousedown.stop
                  >
                    <input
                      v-if="filterControlType(col) === 'text'"
                      type="text"
                      class="eg-filter-input"
                      :value="internalFilters[col.key] || ''"
                      :placeholder="t.filterPlaceholder"
                      @input="setFilter(col.key, $event.target.value)"
                      @keydown.stop
                      @click.stop
                    />
                    <select
                      v-else-if="filterControlType(col) === 'select'"
                      class="eg-filter-select"
                      :value="internalFilters[col.key] || ''"
                      @change="setFilter(col.key, $event.target.value)"
                      @click.stop
                    >
                      <option value="">{{ t.filterAll }}</option>
                      <option v-for="opt in filterOptionsFor(col)" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                    </select>
                    <select
                      v-else-if="filterControlType(col) === 'checkbox'"
                      class="eg-filter-select"
                      :value="internalFilters[col.key] || ''"
                      @change="setFilter(col.key, $event.target.value)"
                      @click.stop
                    >
                      <option value="">{{ t.filterAll }}</option>
                      <option value="true">{{ t.filterChecked }}</option>
                      <option value="false">{{ t.filterUnchecked }}</option>
                    </select>
                  </div>
                </template>
              </template>
            </template>
          </div>
        </div>

        <!-- Pinned Right columns header -->
        <div v-if="hasPinnedRight" class="eg-pinned-right-header" :class="{ 'eg-shadow-edge': hasHiddenScrollRight() }" :style="pinnedRightHeaderStyle">
          <div :style="{ position: 'relative', height: (headerRowHeight * headerDepth + _filterRowH) + 'px' }">
            <template v-for="(row, rowIdx) in headerRows">
              <template v-for="cell in row">
                <template v-if="isCellInZone(cell, rowIdx, 'right')">
                  <div
                    :key="'prh-' + rowIdx + '-' + (cell.column.key || cell.column.title)"
                    class="eg-header-cell"
                    :class="{ 'eg-header-group': cell.isGroup, 'eg-header-cell--drag-source': colDrag.active && cell._firstLeafFlatIndex >= colDrag.sourceFirstLeaf && cell._firstLeafFlatIndex < colDrag.sourceFirstLeaf + colDrag.sourceLeafCount }"
                    :data-fi="!cell.isGroup ? cell.column._flatIndex : undefined"
                    :data-start="cell.isGroup ? cell._firstLeafFlatIndex : undefined"
                    :data-end="cell.isGroup ? cell._firstLeafFlatIndex + cell.colspan - 1 : undefined"
                    :style="getHeaderCellStyleForZone(cell, rowIdx, 'right')"
                    @mousedown="onColHeaderMouseDown($event, cell)"
                    @dblclick="onColHeaderDblClick($event, cell)"
                    @contextmenu.prevent="onColHeaderContextMenu($event, cell)"
                  >
                    <slot v-if="!cell.isGroup" :name="'header-' + cell.column.key" :column="cell.column">
                      {{ cell.column.title }}
                    </slot>
                    <span v-else>{{ cell.column.title }}</span>
                    <span
                      v-if="!cell.isGroup && isColSortable(cell.column)"
                      class="eg-sort-icon"
                      :class="sortIconClass(cell.column)"
                      :title="sortIconTitle()"
                      @mousedown.stop
                      @click.stop="openSortMenu($event, cell.column)"
                    ></span>
                    <div
                      v-if="!cell.isGroup"
                      class="eg-col-resize-handle"
                      @mousedown.stop="startColResize($event, cell.column._flatIndex)"
                    ></div>
                  </div>
                </template>
              </template>
            </template>
            <template v-if="filterRow">
              <div
                v-for="col in pinnedRightCols"
                :key="'prfilter-' + col._flatIndex"
                class="eg-filter-cell"
                :class="{ 'eg-filter-cell-empty': filterControlType(col) === 'none' }"
                :style="getFilterCellStyle(col._flatIndex)"
                @mousedown.stop
              >
                <input
                  v-if="filterControlType(col) === 'text'"
                  type="text"
                  class="eg-filter-input"
                  :value="internalFilters[col.key] || ''"
                  :placeholder="t.filterPlaceholder"
                  @input="setFilter(col.key, $event.target.value)"
                  @keydown.stop
                  @click.stop
                />
                <select
                  v-else-if="filterControlType(col) === 'select'"
                  class="eg-filter-select"
                  :value="internalFilters[col.key] || ''"
                  @change="setFilter(col.key, $event.target.value)"
                  @click.stop
                >
                  <option value="">{{ t.filterAll }}</option>
                  <option v-for="opt in filterOptionsFor(col)" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                </select>
                <select
                  v-else-if="filterControlType(col) === 'checkbox'"
                  class="eg-filter-select"
                  :value="internalFilters[col.key] || ''"
                  @change="setFilter(col.key, $event.target.value)"
                  @click.stop
                >
                  <option value="">{{ t.filterAll }}</option>
                  <option value="true">{{ t.filterChecked }}</option>
                  <option value="false">{{ t.filterUnchecked }}</option>
                </select>
              </div>
            </template>
          </div>
        </div>
      </div>

      <!-- ===== BODY AREA ===== -->
      <div class="eg-body-area" :style="bodyAreaStyle">

        <!-- Row number header column -->
        <div class="eg-row-header-col" :style="rowHeaderColStyle">
          <!-- Scrollable row headers -->
          <div class="eg-scroll-row-headers" :style="scrollRowHeadersStyle" ref="scrollRowHeaders">
            <div :style="{ height: totalVirtualHeight + 'px', position: 'relative' }">
              <div :style="{ transform: 'translateY(' + virtualOffsetTop + 'px)', willChange: 'transform', contain: 'layout style' }">
                <template v-for="ri in visibleRowRange">
                  <div
                    v-if="!isRowHidden(ri)"
                    :key="'srh-' + ri"
                    class="eg-row-header-cell"
                    :style="getRowHeaderStyle(ri)"
                    @mousedown="onRowHeaderMouseDown($event, ri)"
                    @contextmenu.prevent="onRowContextMenu($event, ri)"
                  >
                    {{ ri + 1 }}
                    <div class="eg-row-resize-handle" @mousedown.stop="startRowResize($event, ri)"></div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>

        <!-- Row group outline gutter (left side of rows) -->
        <div v-if="rowGroups.length" class="eg-row-outline-col" :style="rowOutlineColStyle">
          <template v-for="group in rowGroups">
            <div
              :key="'rg-' + group.startIndex + '-' + group.endIndex"
              class="eg-group-btn"
              :class="{ collapsed: isGroupCollapsed(group) }"
              :style="getRowGroupBtnStyle(group)"
              @click="toggleGroup(group)"
            >{{ isGroupCollapsed(group) ? '+' : '−' }}</div>
          </template>
        </div>

        <!-- Main scroll body -->
        <div class="eg-scroll-body" ref="scrollBody" :style="scrollBodyStyle" @scroll="onBodyScroll">
          <!-- display:flex puts the two sticky pinned zones side by side at y=0 (as
               blocks they'd stack vertically, pushing pinned-right below the rows), and
               lets margin-left:auto give pinned-right its natural place at the inner's
               RIGHT edge — sticky right:0 only ever pulls an element back toward its
               natural position, so from x=0 (block flow) it would never stick at all.
               .eg-main-cells is position:absolute and doesn't participate. -->
          <div class="eg-scroll-body-inner" :style="{ width: scrollContentWidth + 'px', height: totalVirtualHeight + 'px', position: 'relative', display: 'flex' }">

            <!-- Pinned left column body -->
            <div v-if="getFrozenWidth() > 0" class="eg-frozen-col-body" :class="{ 'eg-shadow-edge': hasHiddenScrollLeft() }" :style="frozenColBodyStyle">
              <div :style="{ height: totalVirtualHeight + 'px', position: 'relative' }">
                <div :style="{ transform: 'translateY(' + virtualOffsetTop + 'px)', willChange: 'transform', contain: 'layout style' }">
                  <template v-for="ri in visibleRowRange">
                      <div v-if="!isRowHidden(ri)" :key="'fc-row-' + ri" class="eg-row" :class="{ 'eg-row--even': ri % 2 === 0 }" :style="getRowStyle(ri)">
                        <template v-for="(col, ci) in leafCols">
                          <template v-if="isColumnPinnedLeft(ci) && !isColHidden(ci)">
                            <div
                              :key="'fc-cell-' + ri + '-' + ci"
                              class="eg-cell"
                              :data-fi="ci"
                              :class="getCellClasses(ri, ci)"
                              :style="[getCellStyle(ri, ci), getRowCustomStyle(ri)]"
                              @mousedown="onCellMouseDown($event, ri, ci)"
                              @mouseover="onCellMouseOver($event, ri, ci)"
                              @mouseup="onCellMouseUp"
                              @dblclick="onCellDblClick(ri, ci)"
                              @contextmenu.prevent="onCellContextMenu($event, ri, ci)"
                            >
                              <div v-if="isMergedAway(ri, ci)" style="display:none"></div>
                              <template v-else-if="isEditing(ri, ci)">
                                <slot v-if="hasCellSlot(col)" :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :isEditing="true" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                                <slot v-else-if="hasLegacyEditSlot(col)" :name="'edit-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                                <input v-else ref="editInput" class="eg-cell-input" v-model="editValue" @input="onEditInput" @blur="commitEdit" @keydown.stop="onEditKeyDown" />
                              </template>
                              <template v-else-if="col.type === 'checkbox'">
                                <eg-checkbox
                                  :value="isCheckboxChecked(ri, ci)"
                                  :disabled="!isCellEditable(ri, ci)"
                                  @change="(v) => setCheckboxValue(ri, ci, v)"
                                />
                              </template>
                              <template v-else-if="col.type === 'action'">
                                <span class="eg-cell-action-wrap" @[actionHandlerEvent(col)]="triggerCellAction(ri, ci, $event)">
                                  <slot :name="'action-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" />
                                </span>
                              </template>
                              <template v-else>
                                <slot :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :isEditing="false" :done="null" :cancel="null">
                                  <slot v-if="hasPrefixSlot(col)" :name="'prefix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" /><template v-if="hasSuffixSlot(col) && isSelectLikeCol(col)"><span class="eg-cell-select-trigger-wrap"><span class="eg-cell-value">{{ getCellDisplayValue(ci, getCellValue(ri, ci), ri) }}</span><span class="eg-cell-select-caret-inline">▾</span></span></template><template v-else><span class="eg-cell-value">{{ getCellDisplayValue(ci, getCellValue(ri, ci), ri) }}</span></template><span v-if="hasSuffixSlot(col)" class="eg-cell-suffix-wrap"><slot :name="'suffix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" /></span>
                                </slot>
                              </template>
                            </div>
                          </template>
                        </template>
                      </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- Main data cells -->
            <div class="eg-main-cells" :style="mainCellsStyle">
              <div :style="{ height: totalVirtualHeight + 'px', position: 'relative', width: scrollableContentWidth + 'px' }">
                <div :style="{ transform: 'translateY(' + virtualOffsetTop + 'px)', willChange: 'transform', contain: 'layout style' }">
                  <template v-for="ri in visibleRowRange">
                      <div
                        v-if="!isRowHidden(ri)"
                        :key="'row-' + ri"
                        class="eg-row"
                        :class="{ 'eg-row--even': ri % 2 === 0 }"
                        :style="getRowStyle(ri)"
                        :data-row="ri"
                      >
                        <template v-for="(col, ci) in leafCols">
                          <template v-if="isColumnScrollable(ci) && !isColHidden(ci)">
                            <div
                              :key="'cell-' + ri + '-' + ci"
                              class="eg-cell"
                              :data-fi="ci"
                              :class="getCellClasses(ri, ci)"
                              :style="[getCellStyle(ri, ci), getRowCustomStyle(ri)]"
                              @mousedown="onCellMouseDown($event, ri, ci)"
                              @mouseover="onCellMouseOver($event, ri, ci)"
                              @mouseup="onCellMouseUp"
                              @dblclick="onCellDblClick(ri, ci)"
                              @contextmenu.prevent="onCellContextMenu($event, ri, ci)"
                            >
                              <div v-if="isMergedAway(ri, ci)" style="display:none"></div>
                              <template v-else-if="isEditing(ri, ci)">
                                <slot v-if="hasCellSlot(col)" :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :isEditing="true" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                                <slot v-else-if="hasLegacyEditSlot(col)" :name="'edit-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                                <input
                                  v-else
                                  ref="editInput"
                                  class="eg-cell-input"
                                  v-model="editValue"
                                  @input="onEditInput"
                                  @blur="commitEdit"
                                  @keydown.stop="onEditKeyDown"
                                />
                              </template>
                              <template v-else-if="col.type === 'checkbox'">
                                <eg-checkbox
                                  :value="isCheckboxChecked(ri, ci)"
                                  :disabled="!isCellEditable(ri, ci)"
                                  @change="(v) => setCheckboxValue(ri, ci, v)"
                                />
                              </template>
                              <template v-else-if="col.type === 'action'">
                                <span class="eg-cell-action-wrap" @[actionHandlerEvent(col)]="triggerCellAction(ri, ci, $event)">
                                  <slot :name="'action-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" />
                                </span>
                              </template>
                              <template v-else>
                                <slot :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" :isEditing="false" :done="null" :cancel="null">
                                  <slot v-if="hasPrefixSlot(col)" :name="'prefix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" /><template v-if="hasSuffixSlot(col) && isSelectLikeCol(col)"><span class="eg-cell-select-trigger-wrap"><span class="eg-cell-value">{{ getCellDisplayValue(ci, getCellValue(ri, ci), ri) }}</span><span class="eg-cell-select-caret-inline">▾</span></span></template><template v-else><span class="eg-cell-value">{{ getCellDisplayValue(ci, getCellValue(ri, ci), ri) }}</span></template><span v-if="hasSuffixSlot(col)" class="eg-cell-suffix-wrap"><slot :name="'suffix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, ci)" /></span>
                                </slot>
                              </template>
                            </div>
                          </template>
                        </template>
                      </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- Pinned Right column body -->
            <div v-if="hasPinnedRight" class="eg-pinned-right-body" :class="{ 'eg-shadow-edge': hasHiddenScrollRight() }" :style="pinnedRightBodyStyle">
              <div :style="{ height: totalVirtualHeight + 'px', position: 'relative' }">
                <div :style="{ transform: 'translateY(' + virtualOffsetTop + 'px)', willChange: 'transform', contain: 'layout style' }">
                  <template v-for="ri in visibleRowRange">
                      <div v-if="!isRowHidden(ri)" :key="'pr-row-' + ri" class="eg-row" :class="{ 'eg-row--even': ri % 2 === 0 }" :style="getRowStyle(ri)">
                        <template v-for="col in pinnedRightCols">
                          <div
                            :key="'pr-cell-' + ri + '-' + col._flatIndex"
                            class="eg-cell"
                            :data-fi="col._flatIndex"
                            :class="getCellClasses(ri, col._flatIndex)"
                            :style="[getCellStyle(ri, col._flatIndex), getRowCustomStyle(ri)]"
                            @mousedown="onCellMouseDown($event, ri, col._flatIndex)"
                            @mouseover="onCellMouseOver($event, ri, col._flatIndex)"
                            @mouseup="onCellMouseUp"
                            @dblclick="onCellDblClick(ri, col._flatIndex)"
                            @contextmenu.prevent="onCellContextMenu($event, ri, col._flatIndex)"
                          >
                            <div v-if="isMergedAway(ri, col._flatIndex)" style="display:none"></div>
                            <template v-else-if="isEditing(ri, col._flatIndex)">
                              <slot v-if="hasCellSlot(col)" :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" :isEditing="true" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                              <slot v-else-if="hasLegacyEditSlot(col)" :name="'edit-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" :done="(v) => commitEditSlot(v)" :cancel="cancelEdit" />
                              <input v-else ref="editInput" class="eg-cell-input" v-model="editValue" @input="onEditInput" @blur="commitEdit" @keydown.stop="onEditKeyDown" />
                            </template>
                            <template v-else-if="col.type === 'checkbox'">
                              <eg-checkbox
                                :value="isCheckboxChecked(ri, col._flatIndex)"
                                :disabled="!isCellEditable(ri, col._flatIndex)"
                                @change="(v) => setCheckboxValue(ri, col._flatIndex, v)"
                              />
                            </template>
                            <template v-else-if="col.type === 'action'">
                              <span class="eg-cell-action-wrap" @[actionHandlerEvent(col)]="triggerCellAction(ri, col._flatIndex, $event)">
                                <slot :name="'action-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" />
                              </span>
                            </template>
                            <template v-else>
                              <slot :name="'cell-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" :isEditing="false" :done="null" :cancel="null">
                                <slot v-if="hasPrefixSlot(col)" :name="'prefix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" /><template v-if="hasSuffixSlot(col) && isSelectLikeCol(col)"><span class="eg-cell-select-trigger-wrap"><span class="eg-cell-value">{{ getCellDisplayValue(col._flatIndex, getCellValue(ri, col._flatIndex), ri) }}</span><span class="eg-cell-select-caret-inline">▾</span></span></template><template v-else><span class="eg-cell-value">{{ getCellDisplayValue(col._flatIndex, getCellValue(ri, col._flatIndex), ri) }}</span></template><span v-if="hasSuffixSlot(col)" class="eg-cell-suffix-wrap"><slot :name="'suffix-' + col.key" :row="_dataRaw[ri]" :rowIndex="ri" :column="col" :value="getCellValue(ri, col._flatIndex)" /></span>
                              </slot>
                            </template>
                          </div>
                        </template>
                      </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- Fill handle (shown on primary range) -->
            <div
              v-if="fillHandleVisible"
              class="eg-fill-handle"
              :style="fillHandleStyle"
              @mousedown.stop="startFillDrag"
            ></div>

            <!-- Drag move ghost border -->
            <div
              v-if="dragMove.active"
              class="eg-drag-ghost"
              :style="dragGhostStyle"
            ></div>
          </div>
        </div>

        <!-- Column group outline row (top, above body) -->
        <div v-if="colGroups.length" class="eg-col-outline-row" :style="colOutlineRowStyle">
          <template v-for="group in colGroups">
            <div
              :key="'cg-' + group.startIndex + '-' + group.endIndex"
              class="eg-group-btn"
              :class="{ collapsed: isGroupCollapsed(group) }"
              :style="getColGroupBtnStyle(group)"
              @click="toggleGroup(group)"
            >{{ isGroupCollapsed(group) ? '+' : '−' }}</div>
          </template>
        </div>

      </div><!-- end body-area -->

      <!-- ===== FOOTER AREA (column totals) ===== -->
      <div v-if="hasFooter" class="eg-footer-area" :style="footerAreaStyle">

        <!-- "Jami" label cell (mirrors corner cell) -->
        <div class="eg-footer-label" :style="footerLabelStyle">{{ t.total }}</div>

        <!-- Frozen columns footer -->
        <div v-if="getFrozenWidth() > 0" class="eg-frozen-col-footer" :class="{ 'eg-shadow-edge': hasHiddenScrollLeft() }" :style="frozenColFooterStyle">
          <div :style="{ position: 'relative', height: footerRowHeight + 'px' }">
            <template v-for="(col, ci) in leafCols">
              <template v-if="isColumnPinnedLeft(ci) && !isColHidden(ci)">
                <div :key="'ff-' + ci" class="eg-footer-cell" :class="getFooterCellClass(ci)" :style="getFooterCellStyle(ci)">
                  {{ getColumnTotalDisplay(ci) }}
                </div>
              </template>
            </template>
          </div>
        </div>

        <!-- Scrollable footer (horizontally synced with body via scrollFooter ref) -->
        <div class="eg-scroll-col-footer" ref="scrollFooter" :style="scrollColHeaderStyle">
          <div class="eg-scroll-col-footer-inner" :style="{ width: scrollableContentWidth + 'px', height: footerRowHeight + 'px', position: 'relative' }">
            <template v-for="(col, ci) in leafCols">
              <template v-if="isColumnScrollable(ci) && !isColHidden(ci)">
                <div :key="'sf-' + ci" class="eg-footer-cell" :class="getFooterCellClass(ci)" :style="getFooterCellStyle(ci)">
                  {{ getColumnTotalDisplay(ci) }}
                </div>
              </template>
            </template>
          </div>
        </div>

        <!-- Pinned Right columns footer -->
        <div v-if="hasPinnedRight" class="eg-pinned-right-footer" :class="{ 'eg-shadow-edge': hasHiddenScrollRight() }" :style="pinnedRightFooterStyle">
          <div :style="{ position: 'relative', height: footerRowHeight + 'px' }">
            <div
              v-for="col in pinnedRightCols"
              :key="'prf-' + col._flatIndex"
              class="eg-footer-cell"
              :class="getFooterCellClass(col._flatIndex)"
              :style="getFooterCellStyle(col._flatIndex)"
            >{{ getColumnTotalDisplay(col._flatIndex) }}</div>
          </div>
        </div>
      </div><!-- end footer-area -->

      <!-- Resize indicator line -->
      <div v-if="resizing.active" class="eg-resize-line" :style="resizeLineStyle"></div>

      <!-- Loading overlay (host-driven, e.g. during an async data fetch) -->
      <div v-if="loading" class="eg-loading-overlay">
        <template v-if="columns && columns.length">
          <div class="eg-skeleton">
            <div class="eg-skeleton-row eg-skeleton-row-header" :style="{ height: headerRowHeight + 'px' }">
              <div
                v-for="col in leafCols"
                :key="'sk-h-' + col._flatIndex"
                class="eg-skeleton-block"
                :style="{ width: getColW(col._flatIndex) + 'px' }"
              ></div>
            </div>
            <div
              v-for="r in 20"
              :key="'sk-r-' + r"
              class="eg-skeleton-row"
              :style="{ height: _rowH + 'px' }"
            >
              <div
                v-for="col in leafCols"
                :key="'sk-c-' + col._flatIndex"
                class="eg-skeleton-block"
                :style="{ width: getColW(col._flatIndex) + 'px' }"
              ></div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="eg-loading-spinner"></div>
        </template>
      </div>
    </div><!-- end container -->

    <!-- Import progress overlay -->
    <div v-if="importState.active" class="eg-import-overlay">
      <div class="eg-import-dialog">
        <div class="eg-import-title">Fayl import qilinmoqda</div>
        <div class="eg-import-bar-wrap">
          <div class="eg-import-bar" :style="{ width: importState.percent + '%' }"></div>
        </div>
        <div class="eg-import-msg">{{ importState.message }}</div>
        <div class="eg-import-pct">{{ importState.percent }}%</div>
      </div>
    </div>

    <!-- Export progress overlay -->
    <div v-if="exportState.active" class="eg-import-overlay">
      <div class="eg-import-dialog">
        <div class="eg-import-title">Fayl export qilinmoqda...</div>
        <div class="eg-export-spinner"></div>
      </div>
    </div>

    <!-- Local sync modal (localSyncKey feature) -->
    <eg-local-sync-modal
      v-if="localSyncKey"
      :visible="localSyncModal.visible"
      :grid-options="_selfComponentDef"
      :columns="_localSyncPreviewColumns"
      :versions="localSyncModal.versions"
      :selected-id="localSyncModal.selectedId"
      :selected-version="localSyncModal.selectedVersion"
      :locale="locale"
      :theme="internalTheme"
      @close="closeLocalSyncModal"
      @select="_selectLocalSyncModalVersion"
      @save="_onLocalSyncModalSave"
      @restore="restoreLocalVersion"
      @clear="_onLocalSyncModalDelete"
    />

    <!-- Lock/unlock state feedback — brief centered icon flash -->
    <div v-if="lockFlashVisible" class="eg-lock-flash" aria-hidden="true">
      <span
        ref="lockFlashIconEl"
        class="eg-lock-flash-icon"
        :class="lockFlashLocked ? 'eg-icon-lock' : 'eg-icon-unlock'"
      ></span>
    </div>

    <!-- Select dropdown overlay (flat select) -->
    <eg-select
      v-if="selectDropdown && !selectDropdown.tree"
      ref="selectDropdownComp"
      :value="selectDropdown.currentValue"
      :options="selectDropdown.rawOptions"
      :value-key="selectDropdown.keys.valueKey"
      :label-key="selectDropdown.keys.labelKey"
      :enable-search="selectDropdown.enableSearch"
      :trigger-rect="selectDropdown.rect"
      :dropdown-only="true"
      :size="internalSize"
      :locale="locale"
      :clearable="selectDropdown.clearable"
      @select="onComponentSelect"
      @close="closeSelectDropdown"
    />
    <!-- Tree select dropdown overlay -->
    <eg-tree-select
      v-if="selectDropdown && selectDropdown.tree"
      ref="selectDropdownComp"
      :value="selectDropdown.currentValue"
      :options="selectDropdown.rawOptions"
      :value-key="selectDropdown.keys.valueKey"
      :label-key="selectDropdown.keys.labelKey"
      :children-key="selectDropdown.keys.childrenKey"
      :enable-search="selectDropdown.enableSearch"
      :trigger-rect="selectDropdown.rect"
      :dropdown-only="true"
      :size="internalSize"
      :locale="locale"
      :clearable="selectDropdown.clearable"
      @select="onComponentSelect"
      @close="closeSelectDropdown"
    />

    <!-- Date picker overlay -->
    <eg-date-picker
      v-if="datePickerOverlay"
      ref="datePickerComp"
      :value="datePickerOverlay.value"
      :format="datePickerOverlay.format"
      :locale="locale"
      :trigger-rect="datePickerOverlay.rect"
      @pick="onDatePick"
      @typing="onDateTyping"
      @close="closeDatePicker"
    />

    <!-- Validation error tooltip (cellValidator) -->
    <div
      v-if="invalidCell && invalidCell.rect"
      class="eg-validation-tooltip"
      :style="invalidTooltipStyle"
    >{{ invalidCell.message }}</div>

    <!-- Column drag ghost — a header-shaped copy of the grabbed column that follows
         the cursor with the original grab point preserved (position updated via
         direct DOM in handleColDragMove) -->
    <div
      v-if="colDrag.active"
      ref="colDragGhost"
      class="eg-col-drag-ghost"
      :style="{
        left: (colDrag.startX - colDrag.grabOffsetX) + 'px',
        top: (colDrag.startY - 14) + 'px',
        width: colDrag.ghostWidth + 'px',
        height: _headerRowH + 'px'
      }"
    >{{ colDrag.ghostLabel }}</div>

  </div>
  </div>
</template>

<script>
import {
  normalizeRange, isCellInRange, isCellInAnyRange,
  buildRange, singleCellRange, getPrimaryRange
} from '../utils/selection.js'
import { flattenColumns, buildHeaderRows, columnTreeDepth, moveColumnNodeInTree } from '../utils/headerTree.js'
import { calcVisibleRows, buildCumulativeHeights, findVisibleRange, getRowTop, getRowHeight } from '../utils/virtualScroll.js'
import { generateFillValues } from '../utils/fillHandle.js'
import {
  matrixToTSV, tsvToMatrix, extractMatrix, transposeMatrix, applyMatrix, tileMatrix
} from '../utils/clipboard.js'
import {
  mergeHasConflict, findMergeAtCell, isMergeAnchor, addMerge,
  removeMergeAt, resolveMergeAnchor
} from '../utils/merge.js'
import {
  addGroup, removeGroup, toggleGroupCollapse, isGroupCollapsed as _isGroupCollapsed,
  getCollapsedRowIndices, getCollapsedColIndices
} from '../utils/outline.js'
import { exportToExcel as _exportToExcel } from '../utils/excelExport.js'
import { buildPrintTableHtml } from '../utils/printTable.js'
import { importFromFile as _importFromFile } from '../utils/excelImport.js'
import { createExcelImportWorker, createExcelExportWorker } from '../utils/workerFactory'
import { getMessages } from '../utils/i18n.js'
import EgCheckbox from './EgCheckbox.vue'
import anime from 'animejs'
import EgSelect from './EgSelect.vue'
import EgTreeSelect from './EgTreeSelect.vue'
import EgDatePicker from './EgDatePicker.vue'
import EgLocalSyncModal from './EgLocalSyncModal.vue'
import { parseDateValue, formatDate, DEFAULT_DATE_FORMAT } from '../utils/dateUtils.js'
import { formatNumber as _formatNumber } from '../utils/numberFormat.js'
import { Mask, MaskInput } from '../utils/mask.js'
import { listVersions, getVersion, deleteVersion, saveOrTouchVersion, putBuffer, getBuffer, clearBuffer } from '../utils/idbStore.js'
import { hashRows, hashRowsAsync } from '../utils/dataHash.js'

const SIZE_CONFIG = {
  small:  { row: 22, header: 24, footer: 24, filter: 26 },
  middle: { row: 28, header: 28, footer: 28, filter: 32 },
  large:  { row: 36, header: 36, footer: 36, filter: 40 }
}
const ROW_HEADER_WIDTH = 50
const DEFAULT_COL_WIDTH = 100
const OUTLINE_GUTTER = 20
const FIT_COLUMNS_MIN_WIDTH = 40
const ROW_LIST_EDGE_PAD = 8 // birinchi/oxirgi qator bilan tepa/pastki border orasidagi bo'sh joy (px)
const FILL_DRAG_EDGE_ZONE = 24 // px from .eg-scroll-body's edge that triggers continuous auto-scroll while fill-dragging
const FILL_DRAG_MAX_SPEED = 18 // px/frame, at the very edge (scales down to 0 at the zone's outer boundary)

// Classifies a col.width spec so resolveColWidth() knows how to turn it into a
// concrete px number. Plain numbers/px strings resolve instantly with no DOM
// work; '%' resolves via arithmetic against the grid's own measured viewport
// width; any other CSS length (em, rem, vw, calc(), ...) needs a DOM probe.
function parseColWidthSpec(spec) {
  if (typeof spec === 'number' && !isNaN(spec)) return { type: 'px', value: spec }
  if (typeof spec === 'string') {
    const trimmed = spec.trim()
    if (/^\d+(\.\d+)?$/.test(trimmed)) return { type: 'px', value: parseFloat(trimmed) }
    if (/^\d+(\.\d+)?px$/.test(trimmed)) return { type: 'px', value: parseFloat(trimmed) }
    if (/^\d+(\.\d+)?%$/.test(trimmed)) return { type: 'percent', value: parseFloat(trimmed) }
    if (trimmed) return { type: 'css', value: trimmed }
  }
  return { type: 'px', value: DEFAULT_COL_WIDTH }
}
// Default toolbar tool list when `toolbar` is `true` or an object without
// its own `list` — every tool group. Like `size`, the theme picker mirrors
// its own `internalTheme` state and works standalone; `:theme.sync` is only
// needed if the host wants to read the current theme back, not a prerequisite
// for the picker to function.
const DEFAULT_TOOLBAR_LIST = ['undoRedo', 'export', 'import', 'print', 'localSync', 'size', 'lock', 'fullscreen', 'theme']
// Column drag live-preview transition (AG Grid-like feel). Native CSS transitions
// retarget smoothly from whatever intermediate position an element is currently
// at when the drop slot changes mid-flight — no JS animation library races.
const COL_DRAG_TRANSITION = 'transform 200ms cubic-bezier(0.2, 0, 0, 1)'
const THEME_LIST = ['excel', 'material', 'antd', 'fluent', 'carbon']

// Kept as a named const (rather than an inline `export default {}`) so the
// local-sync preview modal can receive the plain component definition
// itself as a prop — see `_selfComponentDef` below. Importing ExcelGrid.vue
// from EgLocalSyncModal.vue to nest a grid inside it would be a circular
// import (ExcelGrid.vue -> EgLocalSyncModal.vue -> ExcelGrid.vue); passing
// this reference down avoids that entirely, and avoids passing `this.$options`
// (an instance's merged/runtime-contaminated options, not a clean definition).
const ExcelGridComponent = {
  name: 'ExcelGrid',

  components: { EgCheckbox, EgSelect, EgTreeSelect, EgDatePicker, EgLocalSyncModal },

  // v-model → :data + @input
  model: { prop: 'data', event: 'input' },

  props: {
    /** Array of row objects keyed by columns[].key */
    data: { type: Array, default: () => [] },

    /**
     * Column definitions (may be nested via children[]).
     *
     * `width` accepts anything the CSS `width` property accepts, not just a
     * raw px number:
     * - `Number` (e.g. `150`) or `'150px'` — fixed pixel width (fast path, no
     *   DOM measurement).
     * - `'20%'` — relative to the grid's own rendered viewport width. Stays
     *   responsive: recalculated whenever the grid's container is resized,
     *   exactly like a real CSS percentage — until the column is manually
     *   drag-resized (or auto-fit), at which point it becomes a fixed px
     *   override and stops rescaling.
     * - Any other CSS length (`'10em'`, `'5rem'`, `'20vw'`, `calc(...)`, ...)
     *   — resolved once via a hidden probe element measured against the
     *   grid's own font-size/layout. `'auto'`/`'fit-content'` have no
     *   intrinsic width this way and fall back to the 100px default; use the
     *   `autoWidth` prop or double-click auto-fit for real content-fit sizing.
     *
     * `mask` — input mask for the plain-text editable input (engine adapted
     * from the `maska` library, vendored in `src/utils/mask.js`), applied
     * while typing and to every other value-entry path (paste, fill handle,
     * custom edit slots). Ignored by `select`/`treeSelect`/`date`/`checkbox`/
     * `action` columns, which use their own pickers. The masked/formatted
     * text is what gets written to `data` — display, storage, and export
     * all see the same string.
     * - `String` — e.g. `'(##) ###-##-##'` (`#` digit, `@` letter, `*`
     *   alphanumeric by default). Use non-digit separators (spaces, dashes,
     *   parens, letters) between token runs — a literal made of digits
     *   (e.g. `'998##'`) can misalign against a raw/pasted value whose own
     *   digits happen to coincide with the literal's; type the value through
     *   the live cell editor or keep the fixed prefix outside the mask
     *   (as static UI, e.g. a `#prefix-{key}` slot) if that's a concern.
     * - `Array<String>` — dynamic mask, picked by input length, e.g.
     *   `['#-#', '##-##']`.
     * - `Object` — full maska options passthrough (`{ mask, tokens, eager,
     *   reversed, ... }`) for custom tokens or advanced behavior.
     *
     * @example
     * columns: [
     *   { key: 'id', title: '#', width: 60 },
     *   { key: 'name', title: 'Name', width: '30%' },
     *   { key: 'note', title: 'Note', width: '12em' },
     *   { key: 'phone', title: 'Phone', mask: '(##) ###-##-##' }
     * ]
     */
    columns: { type: Array, default: () => [] },

    /** Indices of hidden leaf columns */
    hiddenColumns: { type: Array, default: () => [] },

    /** Indices of hidden rows */
    hiddenRows: { type: Array, default: () => [] },

    /**
     * Dynamic row visibility: (row, rowIndex) => boolean. Return false to
     * hide that row — same visual effect as `hiddenRows`/collapsed groups
     * (row is not rendered, but stays in `data`; nothing is deleted). Feeds
     * the same unification point as every other row-hiding mechanism, so it
     * automatically applies to virtual scroll, keyboard navigation, and
     * Excel export with no extra wiring.
     *
     * @example
     * // Hide inactive rows
     * <excel-grid :row-visible="(row) => row.status !== 'inactive'" />
     * @example
     * // Hide every other row (by position, not by content)
     * <excel-grid :row-visible="(row, rowIndex) => rowIndex % 2 === 0" />
     */
    rowVisible: { type: Function, default: null },

    /** Initial merge descriptors [{ startRow, startCol, endRow, endCol }] */
    merges: { type: Array, default: () => [] },

    /** Collapsed group descriptors [{ type, startIndex, endIndex }] */
    collapsedGroups: { type: Array, default: () => [] },

    /**
     * Height of the grid container in px.
     *
     * Omit it (or pass `null`) for auto-height: the grid sizes itself to fit
     * the header + filter row + all rows + footer for the current `data`
     * length, capped at 70% of the viewport height (`window.innerHeight`) —
     * beyond that it stops growing and scrolls internally, same as a fixed
     * `height` would. Recomputes reactively as `data` grows/shrinks and on
     * window resize. Does not apply in fullscreen mode (already sized to the
     * viewport there) and does not include the toolbar's own height.
     *
     * Pass an explicit `Number` to opt back into the old fixed-height behavior.
     */
    height: { type: Number, default: null },

    /**
     * Width of the grid container (px or a CSS length string).
     * Only applies while `widthMode` is `'full'` — in `'auto'` mode the grid
     * sizes itself to its columns and this prop is ignored.
     */
    width: { type: [Number, String], default: '100%' },

    /**
     * How the grid decides its overall width.
     *
     * - `'full'` (default) — the grid takes the `width` prop's value
     *   (default `100%` of the host container), regardless of how little
     *   space its columns actually need. Current/legacy behavior.
     * - `'auto'` — the grid hugs its content (max-content): its width is
     *   the row-number gutter + the sum of all visible column widths
     *   (live: reacts to column resize, hide/show, and `col.visible`),
     *   plus the vertical scrollbar's width when rows overflow the height.
     *   Capped at `max-width: 100%` — when the columns are wider than the
     *   host, the grid stops at the host's edge and scrolls horizontally
     *   inside, exactly like `'full'`. The `width` prop is ignored.
     *
     * Fullscreen mode always fills the viewport, whatever this is set to.
     *
     * @example
     * <excel-grid v-model="rows" :columns="columns" width-mode="auto" />
     */
    widthMode: {
      type: String,
      default: 'full',
      validator: (v) => ['full', 'auto'].includes(v)
    },

    /**
     * Called before drag-drop: (sourceRange, targetRange) => bool
     * Return false to cancel the drop.
     */
    beforeDrop: { type: Function, default: null },

    /**
     * UI locale for the context menu.
     * Supported: 'en' | 'ru' | 'uz' | 'uz-Cyrl'
     */
    locale: { type: String, default: 'en' },

    /**
     * Pinned columns map: { [colKey]: 'left' | 'right' }
     * Pinned-left columns render as a fixed zone on the left.
     * Pinned-right columns render as a fixed zone on the right.
     * Emit 'update:pinnedColumns' to support .sync modifier.
     */
    pinnedColumns: { type: Object, default: () => ({}) },

    /**
     * Dynamic cell editability: (row, rowIndex, col, colIndex) => boolean
     * Overrides column-level editable when provided.
     * row = plain data object, col = column definition.
     */
    cellEditable: { type: Function, default: null },

    /**
     * Cell value validation: (value, row, rowIndex, col, colIndex) => boolean
     * Return false to reject the write — the cell keeps its old value and
     * an error tooltip is shown anchored to that cell.
     */
    cellValidator: { type: Function, default: null },

    /**
     * Error tooltip text for a rejected value.
     * Function: (value, row, rowIndex, col, colIndex) => string
     * String: same message for every rejected cell.
     * Default: locale's "invalidValue" message.
     */
    cellValidationMessage: { type: [Function, String], default: null },

    /**
     * Bulk-write strictness (paste / fill handle / Delete).
     * false (default): invalid cells in the affected range are skipped,
     *   the rest of the operation still applies.
     * true: if ANY cell in the affected range fails validation, the whole
     *   bulk operation is rejected — nothing is written.
     */
    strictBulkValidation: { type: Boolean, default: false },

    /**
     * Paste auto-grows rows: false (default) — pasting a clipboard matrix
     * taller than the remaining rows below the paste target clips to the
     * existing rows, same as before. true — missing rows are appended to
     * `data` to fit the full pasted range (Excel/Sheets-style). New rows'
     * columns not covered by the pasted matrix get a type-aware blank value
     * (`type: 'checkbox'` → false, everything else → ''). Columns are never
     * auto-created — pasting more columns than exist still clips.
     * @type {Boolean}
     * @default false
     * @example
     * <excel-grid :columns="columns" v-model="data" paste-grows-rows />
     */
    pasteGrowsRows: { type: Boolean, default: false },

    /**
     * Extra fields merged into rows auto-created by pasteGrowsRows, beyond
     * the type-aware column blanks. Rows only ever get values for `columns`
     * keys — anything else your app tracks per row (an id, a visibility
     * flag `rowVisible` depends on, a nested list, etc.) is NOT set unless
     * provided here, since the grid has no way to know about it.
     * Object: same fields merged into every new row.
     * Function(newRowIndex) => Object: computed per new row (e.g. a fresh
     *   uuid per row). `newRowIndex` is the row's index in the resulting
     *   `data` array.
     * Applied before the pasted values are written, so pasted cells always
     * win over any column-key present here.
     * For a single aggregate action after ALL rows from one paste have been
     * created and written to v-model, listen for the `rows-added` event
     * instead of doing it here (this runs once per row, before the commit).
     * @type {Object|Function}
     * @default null
     * @example
     * <excel-grid :columns="columns" v-model="data" paste-grows-rows
     *   :paste-row-defaults="() => ({ uuid: uuidv4(), state: 1 })" />
     */
    pasteRowDefaults: { type: [Object, Function], default: null },

    /** Visual size of the grid. Affects row/header height and font sizes. */
    size: { type: String, default: 'middle' },

    /** Auto-fit all column widths to content (same as double-clicking each resize handle). Re-applies on data/columns change. */
    autoWidth: { type: Boolean, default: false },

    /**
     * Forces every visible leaf column to fit within a single viewport —
     * no horizontal scroll. Column widths are still resolved (`col.width`,
     * `%`/`px`/other CSS lengths, `DEFAULT_COL_WIDTH` when omitted) but only
     * as RELATIVE WEIGHTS: all resolved widths are scaled by one shared
     * factor so their sum exactly fills the available width, keeping each
     * column's proportion to the others. Each column still gets at least
     * `40px` — if there are enough columns that even that minimum doesn't
     * fit, horizontal scroll returns for that (rare) case rather than
     * shrinking columns illegibly thin.
     *
     * Highest-priority width control: overrides `col.width` as an absolute
     * value and `autoWidth`. Manual column resize (drag handle) and
     * double-click auto-fit ARE both allowed — either one turns that column
     * into a fixed px width, excluded from the fit; the rest keep scaling
     * proportionally to fill what's left, which can reintroduce horizontal
     * scroll if the fixed column(s) alone exceed the viewport. Pinned
     * columns count toward the fit too — the goal is the whole row fitting,
     * regardless of pin state.
     * @type {Boolean}
     * @default false
     * @example
     * <excel-grid :columns="columns" v-model="data" fit-columns />
     */
    fitColumns: { type: Boolean, default: false },

    /**
     * Allow columns to be reordered by dragging their headers.
     * On drop, emits 'update:columns' (compatible with .sync) and 'column-reorder'.
     */
    columnDraggable: { type: Boolean, default: true },

    /**
     * Controls the built-in toolbar above the grid — visibility as a whole,
     * and (optionally) which individual tool groups appear. Controlled
     * entirely by the parent — no in-component toggle for the bar itself.
     *
     * @type {Boolean|{visible?: Boolean, list?: Array<('undoRedo'|'export'|'import'|'print'|'size'|'lock'|'fullscreen'|'theme')>, disabled?: Array<('undoRedo'|'export'|'import'|'print'|'size'|'lock'|'fullscreen'|'theme')>}}
     * @default false
     *
     * Two forms:
     * - `Boolean` — `false` (default) hides the toolbar entirely; `true`
     *   shows it with the default tool list — every group, including
     *   `'theme'` (it mirrors its own internal state like `size` does;
     *   `:theme.sync` is optional, only needed if the parent wants to read
     *   the current theme back).
     * - `Object { visible, list, disabled }` — fine-grained control:
     *   - `visible` {Boolean} — defaults to `true` when an object is given
     *     (passing an object is itself an opt-in to show the toolbar);
     *     set explicitly to `false` to hide it while still describing a
     *     `list` you intend to reuse later.
     *   - `list` {Array<String>} — which tool groups render, using the
     *     identifiers above. Unknown/misspelled strings are silently
     *     ignored. Omitting `list` falls back to the same default set as
     *     the `true` shorthand. **Order in `list` does not change the
     *     toolbar's layout** — groups always render in a fixed position
     *     (undo/redo → export/import/print → #toolbar-extra slot → toolbarButtons
     *     → spacer → theme → size → lock/fullscreen); `list` is purely an
     *     inclusion filter.
     *   - `disabled` {Array<String>} — which tool groups render grayed out
     *     and unclickable while staying **visible** (same identifiers as
     *     `list`) — distinct from `list`, which removes a tool entirely.
     *     Scoped to the toolbar button itself: it doesn't block the
     *     underlying keyboard shortcut (only `'undoRedo'` has one —
     *     Ctrl+Z/Ctrl+Y) or a ref method call (`undo()`, `exportToExcel()`,
     *     etc.), matching how `list` also only hides the button, not the
     *     shortcut/method. Omitting `disabled` disables nothing (default).
     *
     * `toolbarButtons` and the `#toolbar-extra` slot are independent of
     * this prop — they render whenever content is provided, regardless of
     * `list`/`disabled`.
     *
     * @example
     * // Whole default set
     * <excel-grid toolbar />
     * @example
     * // Only undo/redo and fullscreen
     * <excel-grid :toolbar="{ list: ['undoRedo', 'fullscreen'] }" />
     * @example
     * // Toggle visibility from a data property while keeping a fixed list
     * <excel-grid :toolbar="{ visible: showToolbar, list: ['export', 'import'] }" />
     * @example
     * // Visible but grayed out — e.g. import disabled while a prior import is processing
     * <excel-grid :toolbar="{ disabled: ['import', 'size'] }" />
     * @example
     * // Read the current theme back (optional — the picker works without it too)
     * <excel-grid toolbar :theme.sync="myTheme" />
     */
    toolbar: { type: [Boolean, Object], default: false },

    /** Extra custom toolbar buttons: [{ key, icon, title, onClick(event, gridApi) }] */
    toolbarButtons: { type: Array, default: () => [] },

    /**
     * Print (`printGrid()`/toolbar "Print" tugmasi) chiqishida jadval tepasida,
     * markazda ko'rinadigan sarlavha. `null` (standart) — sarlavha umuman
     * render qilinmaydi.
     * @property {String} title - sarlavha matni (bo'sh/undefined bo'lsa render qilinmaydi)
     * @property {Object} [style] - Vue :style uslubidagi obyekt (camelCase),
     *   standart markazlashtirilgan/qalin uslub USTIGA qo'shiladi
     * @property {String} [class] - qo'shimcha CSS klass nomi(lari)
     * @example
     * <excel-grid :print-title="{ title: 'Talabalar ro\'yxati', style: { color: '#1a73e8' } }" />
     */
    printTitle: { type: Object, default: null },

    /**
     * Locks the entire grid: blocks all edits (typing, paste, fill, delete,
     * checkbox, select/treeSelect) and structural changes (resize, column
     * reorder, merge/unmerge, undo/redo). Independent from cellEditable/
     * col.editable, which remain per-cell rules. Emit 'update:locked' to
     * support the .sync modifier.
     */
    locked: { type: Boolean, default: false },

    /**
     * Host-driven loading state (e.g. while an async data fetch is in
     * flight). When `true`, only the grid body (`.eg-container`) is
     * covered — the toolbar stays visible and interactive. If `columns`
     * is non-empty, a shimmering skeleton matching each column's width is
     * shown; otherwise a plain centered spinner is shown. Purely visual —
     * doesn't block edits/interaction the way `locked` does (combine both
     * if that's also needed).
     * @type {Boolean}
     * @default false
     * @example
     * <excel-grid :columns="columns" v-model="data" :loading="isFetching" />
     */
    loading: { type: Boolean, default: false },

    /**
     * Data-driven per-row styling: `(row, rowIndex) => styleObject`. The
     * returned style object is applied to every cell in that row (across
     * the frozen/scrollable/pinned-right zones alike), giving the row a
     * continuous horizontal background/style without any host-side CSS.
     * Selection/active/fill-preview/readonly cell highlighting keeps
     * winning visually — those already use `!important`, which always
     * beats a plain (non-`!important`) inline style. Doesn't affect the
     * row-number header column (mirrors Excel: conditional formatting
     * colors data cells, not the row gutter). Return `null`/`undefined`
     * for rows that shouldn't get a custom style.
     * @type {Function}
     * @default null
     * @example
     * <excel-grid :columns="columns" v-model="data" :row-style="(row) => row.status === 'error' ? { background: '#fde2e2' } : null" />
     */
    rowStyle: { type: Function, default: null },

    /** Show "Column info" / "Row info" items in the context menu (dev/debug aid). */
    devMode: { type: Boolean, default: false },

    /**
     * Visual theme of the grid.
     * Built-in: 'excel' | 'material' | 'antd' | 'fluent' | 'carbon'
     * Default is the classic Excel 365 look. Use 'material' for Material Design 3.
     * Mirrors the `size` prop's convention: an internal `internalTheme` state
     * mirrors this prop and is what the toolbar's theme picker actually reads
     * from/writes to (via `setTheme()`), so the picker works standalone even
     * without `:theme.sync` — `.sync` is only needed to reflect the current
     * theme back into the host's own state.
     */
    theme: { type: String, default: 'excel' },

    /**
     * Shows a filter row directly beneath the column headers (inside the
     * sticky header area). Each leaf column gets a filter control matched to
     * its `type`:
     *  - default (no type / 'date' / 'progress'): text search input,
     *    matched case-insensitively against the column's *displayed* value
     *    (so 'date' matches the formatted string, not the raw stored value).
     *  - 'select' / 'treeSelect' *with a static `col.options` array*: a
     *    native <select> populated from those options (tree options are
     *    flattened, indented by depth), matched by exact raw value.
     *  - 'select' / 'treeSelect' with function-based `col.options` (options
     *    computed per-row): falls back to the text control, since a single
     *    fixed option list can't be resolved outside a specific row.
     *  - 'checkbox': a tri-state <select> — All / Checked / Unchecked.
     *  - 'action': no filter control (not a data-bound column).
     *
     * Rows that don't match every active filter are hidden using the same
     * mechanism as `hiddenRows` — virtual scroll, keyboard navigation, and
     * `exportToExcel()` all skip them automatically, with no separate
     * filtering code path to keep in sync.
     *
     * Set `col.filterable: false` to omit the filter control for one column
     * (its filter cell renders empty). Set
     * `col.filterFn(cellValue, filterValue, row, rowIndex, column)` to
     * override the default match logic for that column entirely.
     *
     * @type {Boolean}
     * @default false
     * @example
     * <excel-grid :columns="columns" v-model="data" filter-row />
     */
    filterRow: { type: Boolean, default: false },

    /**
     * Current filter values, keyed by column `key`. Optional — the filter
     * row works standalone via internal state (`internalFilters`) even
     * without `.sync`, mirroring the `size`/`theme` prop convention. Bind
     * `:filters.sync` only if the host needs to read or restore the current
     * filter state.
     * @type {Object}
     * @default {}
     * @example
     * <excel-grid :columns="columns" v-model="data" filter-row :filters.sync="myFilters" />
     */
    filters: { type: Object, default: () => ({}) },

    /**
     * Shows a sort icon (kebab/"more actions" glyph) in every leaf column
     * header. Clicking it opens a popup menu — A → Z / Z → A / Clear sort —
     * matched to Excel's own column-header dropdown. Picking a different
     * column's option replaces the active sort — single-column sort only.
     *
     * Sorting **physically reorders** the `data` array (like a real
     * spreadsheet sort) and emits it through the normal v-model/`input`
     * event — it is recorded in the undo/redo history exactly like any
     * other data edit, so `undo()` restores the pre-sort row order.
     * "Clear sort" (or `clearSort()`) both clears the indicator **and**
     * restores the row order from immediately before the first sort of
     * this session — switching columns or direction in between doesn't
     * move that reference point. If rows were added/removed since sorting
     * (row count no longer matches), the restore is skipped and only the
     * indicator clears, to avoid silently dropping/duplicating rows.
     *
     * Comparison is matched to the column's `type`: plain/`'progress'`
     * columns compare the raw value (numeric-aware); `'date'` compares the
     * parsed date chronologically, not the formatted string; `'select'` /
     * `'treeSelect'` compare the displayed option label; `'checkbox'`
     * compares the boolean state. Empty/`null` values always sort last,
     * regardless of direction. `'action'` columns are never sortable.
     *
     * Set `col.sortable: false` to omit the icon for one column. Set
     * `col.sortFn(rowA, rowB, column) => number` to fully override the
     * comparison for that column.
     *
     * Blocked (no-op) while the grid is `locked`, or while any merged
     * cells or row outline groups exist — both are anchored to row
     * *position*, which a reorder would silently invalidate.
     *
     * @type {Boolean}
     * @default false
     * @example
     * <excel-grid :columns="columns" v-model="data" sortable />
     */
    sortable: { type: Boolean, default: false },

    /**
     * Current sort state — `{ key, direction }` (`direction` is `'asc'` or
     * `'desc'`) or `null` when unsorted. Optional — sorting works standalone
     * via internal state (`internalSort`) even without `.sync`, mirroring
     * the `size`/`theme`/`filters` prop convention. Bind `:sort.sync` only
     * if the host needs to read or restore the current sort state.
     * @type {Object}
     * @default null
     * @example
     * <excel-grid :columns="columns" v-model="data" sortable :sort.sync="mySort" />
     */
    sort: { type: Object, default: null },

    /**
     * Unique key that opts the grid into local version history: when the page
     * is being left (tab hidden/closed, or this component unmounted — NOT on
     * every edit), the current `v-model` is content-hashed (via a Web Worker
     * when available, so the main thread stays responsive right as the page
     * may be unloading) and saved to the browser's IndexedDB as a **version**,
     * keyed by this string. If the hash matches an already-saved version for
     * this key, that version's timestamp is refreshed instead of creating a
     * duplicate — only genuinely different content produces a new version.
     * Also adds a toolbar button ('localSync' — see the `toolbar` prop's
     * `list`/`disabled`) that opens a modal listing saved versions, each with
     * a read-only preview and **Restore** / **Delete** actions, plus a
     * **Save** button for an explicit checkpoint.
     *
     * Two different grid instances must use different keys — the same key
     * means "the same version history" (concurrent tabs interleave). Omit
     * this prop entirely to opt out completely: no IndexedDB access happens
     * at all, and the toolbar button never renders.
     *
     * See also `localSyncMaxVersions`, the ref-callable methods
     * `listLocalVersions()`, `getLocalVersion(id)`, `restoreLocalVersion(id)`,
     * `deleteLocalVersion(id)`, `saveLocalVersionNow()`,
     * `openLocalSyncModal()`/`closeLocalSyncModal()`, and the
     * `local-sync-save`/`local-sync-restore`/`local-sync-clear`/`local-sync-error`/`local-sync-available`
     * events — [details](/local-sync).
     * @type {String}
     * @default null
     * @example
     * <excel-grid :columns="columns" v-model="data" local-sync-key="invoice-42" toolbar />
     */
    localSyncKey: { type: String, default: null },

    /**
     * Optional tenant/organization identifier for multi-tenant hosts (SaaS
     * apps where the same browser/device is used across different
     * organizations). When set, it's combined with `localSyncKey`
     * internally (`${tenant}::${localSyncKey}`) so each tenant gets a fully
     * isolated IndexedDB version history — switching tenants on the same
     * device never shows another tenant's saved drafts. Omit it (default)
     * for single-tenant hosts; behavior is then identical to before this
     * prop existed.
     *
     * Has no effect without `localSyncKey` — it only changes how that key
     * is namespaced internally, it doesn't opt into the feature by itself.
     * Reactive: changing `tenant` (e.g. after an async "current
     * organization" load) reloads that tenant's own version list/buffer,
     * the same way a `localSyncKey` that starts empty and becomes truthy
     * later does. Avoid `::` inside `tenant`/`localSyncKey` values
     * themselves — it's the internal separator between the two.
     * @type {String}
     * @default null
     * @example
     * <excel-grid :columns="columns" v-model="data" local-sync-key="invoice-42" :tenant="currentOrgId" toolbar />
     */
    tenant: { type: String, default: null },

    /**
     * Maximum number of local versions kept per `localSyncKey` (per
     * `tenant`, when set). Once a new version pushes the count past this,
     * the oldest version(s) (by `createdAt`) are deleted automatically
     * (FIFO). Has no effect without `localSyncKey`.
     * @type {Number}
     * @default 10
     * @example
     * <excel-grid :columns="columns" v-model="data" local-sync-key="invoice-42" :local-sync-max-versions="20" />
     */
    localSyncMaxVersions: { type: Number, default: 10 }
  },

  data() {
    return {
      // Selection
      activeCell: { row: 0, col: 0 },
      selectionRanges: [], // [{ startRow, startCol, endRow, endCol }]
      isMouseDown: false,
      mouseDownRange: null,
      isCtrlDrag: false,

      // Edit
      editingCell: null, // { row, col }
      editValue: '',
      editOriginalValue: '',

      // Scroll
      scrollTop: 0,
      scrollLeft: 0,
      headerViewportWidth: null,
      // The grid's DOM parent's width — the reference for relative (%, css)
      // column widths, in BOTH widthMode values (see _relativeWidthContainer).
      // In 'auto' mode the shell's width is DERIVED from column widths, so
      // resolving a relative column width against the shell's own measured
      // viewport (headerViewportWidth) is circular (each resolve nudges the
      // shell size, which nudges the next resolve...). 'full' mode isn't
      // circular that way, but headerViewportWidth (scrollBody.clientWidth)
      // turned out to have its OWN instability source: a vertical scrollbar
      // toggling on/off flips it by the scrollbar's width even though the
      // shell's own outer size never changes — confirmed via a real host
      // report (repeated brief re-render bursts hurting CLS) that 'auto'
      // mode didn't reproduce. The parent's width doesn't depend on the
      // grid's own rendered size OR its internal scrollbar state, so using
      // it everywhere sidesteps both instability sources uniformly.
      hostContainerWidth: null,
      // Real vertical-scrollbar width measured off the scroll body (0 for
      // macOS overlay scrollbars) — widthMode:'auto' adds it to the natural
      // width so the scrollbar never eats into the last column.
      vScrollbarW: 0,
      // .eg-shell's horizontal border total (border-box). Measured at mount —
      // themes can restyle it — so widthMode:'auto' accounts for it instead
      // of shaving those pixels off the last column.
      shellBorderW: 2,

      // Auto-height (height prop omitted) — 70vh cap, kept in sync on resize
      windowInnerH: typeof window !== 'undefined' ? window.innerHeight : 800,

      // Virtual scroll
      virtualStartIndex: 0,
      virtualEndIndex: 0,
      virtualOffsetTop: 0,
      totalVirtualHeight: 0,

      // Column widths (flat index → px)
      colWidths: {},

      // Flat index → raw CSS width spec, for columns whose width is a relative
      // unit ('20%', '10em', ...) and therefore needs re-resolving whenever the
      // grid's viewport width changes. Cleared for a column once it's manually
      // resized/auto-fit — see startColResize/autoFitColumn/_applyAutoWidth.
      relativeColSpecs: {},

      // col.key → true, for columns manually resized while fitColumns is on.
      // Such a column becomes a fixed px width (excluded from the proportional
      // fit); the rest keep scaling among themselves to fill what's left — see
      // _applyFitColumns(). Keyed by col.key (not flat index) so it survives
      // column reorders, same convention as relativeColSpecs preservation.
      fitColumnsOverrides: {},

      // Row heights (row index → px)
      rowHeights: {},

      // Import/export progress
      importState: { active: false, percent: 0, message: '' },
      exportState: { active: false },

      // localSyncKey feature — modal state: the version list (metadata only)
      // plus which one is selected/previewed. `selectedVersion` holds that
      // version's full { id, data, createdAt, updatedAt } for the nested-grid
      // preview (see EgLocalSyncModal.vue).
      localSyncModal: { visible: false, versions: [], selectedId: null, selectedVersion: null },
      // True when one or more versions already existed at mount and the user
      // hasn't opened the modal yet — drives the toolbar button's "unseen
      // local versions" dot. See _loadLocalVersionsOnMount() for the full lifecycle.
      localSyncAvailable: false,

      resizing: {
        active: false,
        type: null, // 'col' | 'row'
        index: -1,
        startX: 0,
        startY: 0,
        startSize: 0,
        currentPos: 0
      },

      // Fill handle
      fillDrag: {
        active: false,
        sourceRange: null,
        currentRow: -1,
        currentCol: -1
      },

      // Drag-move
      dragMove: {
        active: false,
        sourceRange: null,
        startX: 0,
        startY: 0,
        targetRow: -1,
        targetCol: -1,
        copyMode: false
      },

      // Clipboard (internal)
      clipboardMatrix: null,
      clipboardRange: null,
      clipboardMode: null, // 'copy' | 'cut'

      // Context menu
      contextMenu: { visible: false, x: 0, y: 0, row: -1, col: -1 },
      // false while the menu's real size hasn't been measured yet — kept hidden
      // (not painted) so the flip-to-fit repositioning in _positionContextMenu()
      // doesn't cause a visible jump.
      contextMenuPositioned: false,

      // Sort popup menu (header sort icon click) — { visible, x, y, key }
      sortMenu: { visible: false, x: 0, y: 0, key: null },
      sortMenuPositioned: false,

      // devMode — column/row config info modal ({ title, json } | null)
      infoModal: null,

      // Select dropdown
      selectDropdown: null, // { row, col, options, currentValue, rect }

      // Date picker overlay
      datePickerOverlay: null, // { row, col, format, value, rect }

      // Cell value validation (cellValidator)
      invalidCell: null, // { row, col, message, rect }

      // Merges (controlled via prop + update:merges)
      internalMerges: [],

      // Toolbar (controlled via prop + update:locked / update:size / update:theme)
      internalLocked: false,
      internalSize: 'middle',
      internalTheme: 'excel',
      // Pinned columns — merges col.pin (columns config default) with pinnedColumns prop.
      // context-menu pin/unpin updates this directly so .sync is not required.
      internalPinnedColumns: {},
      // Brief centered icon feedback whenever the lock state actually changes
      // (toolbar click, toggleLock(), or a host-driven :locked.sync change).
      lockFlashVisible: false,
      lockFlashLocked: false,
      isFullscreen: false,
      // Bumped whenever _history/_historyIndex change so canUndo/canRedo stay reactive.
      historyVersion: 0,

      // Groups
      internalGroups: [], // [{ type, startIndex, endIndex }]
      internalCollapsedGroups: [],

      // Header
      headerDepth: 1,
      headerRows: [],

      // Leaf columns cache
      leafCols: [],

      // Footer column totals (flat col index → number | null)
      columnTotals: {},

      // Filter row (controlled via prop + update:filters)
      internalFilters: {},
      // Row indices currently hidden by an active filter — merged into
      // hiddenRowSet, so virtual scroll/export/navigation need no separate path.
      filteredRowIndices: [],

      // Sort (controlled via prop + update:sort) — { key, direction } | null
      internalSort: null,

      // Column drag-and-drop state
      colDrag: {
        pending: false,       // mousedown received, waiting for movement threshold
        active: false,        // drag in progress
        sourceFirstLeaf: -1,  // first leaf flat-index of the dragged node
        sourceLeafCount: 1,   // number of leaves in the dragged node (1=leaf, N=group)
        dropIndex: -1,        // insert-before flat index (0..N)
        startX: 0,
        startY: 0,
        ghostLabel: '',
        ghostWidth: 0,        // ghost mirrors the grabbed header's real width (capped)
        grabOffsetX: 0        // cursor offset inside the grabbed header — keeps the grab point under the cursor
      },
    }
  },

  computed: {
    t() { return getMessages(this.locale) },

    // localSyncKey feature — the actual IndexedDB storage key. idbStore.js
    // itself knows nothing about "tenants"; this is the one place that
    // namespaces localSyncKey by tenant when one is given, so every
    // storage-layer call site below just uses this instead of
    // this.localSyncKey directly. null whenever localSyncKey itself is
    // unset — tenant alone doesn't opt into the feature.
    effectiveSyncKey() {
      if (!this.localSyncKey) return null
      return this.tenant ? `${this.tenant}::${this.localSyncKey}` : this.localSyncKey
    },

    pinnedLeftSet() {
      const s = new Set()
      this.leafCols.forEach(col => { if (this.internalPinnedColumns[col.key] === 'left') s.add(col._flatIndex) })
      return s
    },

    pinnedRightSet() {
      const s = new Set()
      this.leafCols.forEach(col => { if (this.internalPinnedColumns[col.key] === 'right') s.add(col._flatIndex) })
      return s
    },

    pinnedLeftCols() { return this.leafCols.filter(col => this.pinnedLeftSet.has(col._flatIndex) && !this.isColHidden(col._flatIndex)) },
    pinnedRightCols() { return this.leafCols.filter(col => this.pinnedRightSet.has(col._flatIndex) && !this.isColHidden(col._flatIndex)) },

    hasPinnedLeft() { return this.pinnedLeftSet.size > 0 },
    hasPinnedRight() { return this.pinnedRightSet.size > 0 },

    hasFooter() { return this.leafCols.some(col => this.isColumnTotalVisible(col)) },

    pinnedLeftWidth() {
      let w = 0
      for (const col of this.pinnedLeftCols) {
        if (!this.isColHidden(col._flatIndex)) w += this.getColW(col._flatIndex)
      }
      return w
    },

    pinnedRightWidth() {
      let w = 0
      for (const col of this.pinnedRightCols) {
        if (!this.isColHidden(col._flatIndex)) w += this.getColW(col._flatIndex)
      }
      return w
    },

    totalRows() { return this.data.length },

    // See the `toolbar` prop's JSDoc for the full Boolean|Object contract.
    _toolbarVisible() {
      if (typeof this.toolbar === 'boolean') return this.toolbar
      return !!this.toolbar && this.toolbar.visible !== false
    },
    _toolbarList() {
      if (this.toolbar && Array.isArray(this.toolbar.list)) return this.toolbar.list
      return DEFAULT_TOOLBAR_LIST
    },
    // Same key set as _toolbarList, but for the disabled (grayed out, still visible) state
    // instead of visibility — see toolbar prop JSDoc.
    _toolbarDisabledList() {
      if (this.toolbar && Array.isArray(this.toolbar.disabled)) return this.toolbar.disabled
      return []
    },

    // Columns shown in the local-sync modal's preview table — action columns
    // are pure interactive UI (buttons), not printable/previewable data,
    // same exclusion printGrid()/exportToExcel() already apply.
    _localSyncPreviewColumns() {
      return this.leafCols.filter(col => col.type !== 'action')
    },

    // Passed to EgLocalSyncModal so it can render the snapshot preview as a
    // real, nested ExcelGrid instance — see the comment on ExcelGridComponent
    // above for why this is the module-level const and not `this.$options`.
    _selfComponentDef() {
      return ExcelGridComponent
    },

    _sizeConf() { return SIZE_CONFIG[this.internalSize] || SIZE_CONFIG.middle },

    sizeOptions() { return Object.keys(SIZE_CONFIG) },
    _rowH()     { return this._sizeConf.row },
    _headerRowH() { return this._sizeConf.header },
    _footerRowH() { return this._sizeConf.footer },
    _filterRowH() { return this.filterRow ? this._sizeConf.filter : 0 },

    headerRowHeight() { return this._headerRowH },
    footerRowHeight() { return this._footerRowH },

    // Pre-built cumulative height array — O(n) once, then cached by Vue.
    // findVisibleRange() uses binary search against this cached array → O(log n) per scroll.
    // Invalidated only when row count, custom heights, or hidden rows change.
    cumulativeHeights() {
      return buildCumulativeHeights(this.totalRows, this._rowH, this.rowHeights, this.hiddenRowSet, ROW_LIST_EDGE_PAD, ROW_LIST_EDGE_PAD)
    },

    // height prop omitted → fit header + filter row + all (visible) rows + footer exactly.
    _autoContentHeight() {
      const headerH = this._headerRowH * this.headerDepth + this._filterRowH
      const bodyH = this.cumulativeHeights[this.totalRows] || 0
      const footerH = this.hasFooter ? this._footerRowH : 0
      return headerH + bodyH + footerH
    },

    // Resolved grid-area height: explicit `height` prop wins as-is (old
    // behavior); omitted → auto-fit content, capped at 70% of the viewport.
    effectiveHeight() {
      if (this.height != null) return this.height
      return Math.min(this._autoContentHeight, this.windowInnerH * 0.7)
    },

    hiddenColSet() { return new Set(this.hiddenColumns) },

    hiddenRowSet() {
      const s = new Set(this.hiddenRows)
      // Also add rows hidden by collapsed row groups
      const collapsed = getCollapsedRowIndices(this.internalGroups, this.internalCollapsedGroups)
      collapsed.forEach(i => s.add(i))
      // Also add rows hidden by the filter row (see filteredRowIndices/_recomputeRowFilters)
      this.filteredRowIndices.forEach(i => s.add(i))
      // Also add rows the host's rowVisible(row, rowIndex) rejects — a static/
      // dynamic rule (status, parity, ...) independent of the toggleable
      // hiddenRows list and the interactive filter row.
      if (typeof this.rowVisible === 'function') {
        const rows = this.data
        for (let i = 0; i < rows.length; i++) {
          if (this.rowVisible(rows[i], i) === false) s.add(i)
        }
      }
      return s
    },

    hiddenColFromGroupSet() {
      return getCollapsedColIndices(this.internalGroups, this.internalCollapsedGroups)
    },

    effectiveHiddenColSet() {
      const s = new Set(this.hiddenColSet)
      this.hiddenColFromGroupSet.forEach(i => s.add(i))
      // col.visible === false — a schema-level hide, independent of the
      // toggleable hiddenColumns list. "Show All Columns" never reveals it.
      // Boolean or Function(column, colIndex) => boolean — like rowVisible (see
      // hiddenRowSet above), the function form is called fresh on every
      // evaluation of this computed, so it stays reactive to whatever host
      // state its closure reads even though leafCols itself (built by
      // flattenColumns' `{...col}` shallow clone) is only rebuilt when the
      // columns prop reference changes. A function value survives that clone
      // unchanged (functions copy by reference), so the closure keeps running
      // fresh — no need to restructure columns into a computed just to react.
      this.leafCols.forEach(col => {
        const v = typeof col.visible === 'function' ? col.visible(col, col._flatIndex) : col.visible
        if (v === false) s.add(col._flatIndex)
      })
      return s
    },

    rowGroups() { return this.internalGroups.filter(g => g.type === 'row') },
    colGroups() { return this.internalGroups.filter(g => g.type === 'column') },

    visibleRowRange() {
      const rows = []
      for (let i = this.virtualStartIndex; i <= this.virtualEndIndex; i++) rows.push(i)
      return rows
    },

    primaryRange() {
      return getPrimaryRange(this.selectionRanges, this.activeCell)
    },

    fillHandleVisible() {
      return this.primaryRange && !this.editingCell
    },

    fillHandleStyle() {
      if (!this.primaryRange) return {}
      const r = normalizeRange(this.primaryRange)
      // O(1) lookup via cumulativeHeights instead of O(endRow) getRowTop loop
      const bottom = this.cumulativeHeights[r.endRow + 1] || 0
      const right = this.getColLeft(r.endCol + 1)
      return {
        position: 'absolute',
        width: '6px',
        height: '6px',
        background: 'var(--eg-color-accent, var(--eg-color-accent-default))',
        border: '1px solid white',
        bottom: (this.totalVirtualHeight - bottom + 1) + 'px',
        right: (this.scrollContentWidth - right + 1) + 'px',
        cursor: 'crosshair',
        zIndex: 10
      }
    },


    invalidTooltipStyle() {
      if (!this.invalidCell || !this.invalidCell.rect) return {}
      const { rect } = this.invalidCell
      return {
        position: 'fixed',
        top: (rect.bottom + 4) + 'px',
        left: rect.left + 'px',
        zIndex: 9999
      }
    },

    dragGhostStyle() {
      if (!this.dragMove.active || this.dragMove.targetRow < 0) return {}
      const r = normalizeRange(this.dragMove.sourceRange)
      const rows = r.endRow - r.startRow
      const cols = r.endCol - r.startCol
      // O(1) lookup via cumulativeHeights instead of O(targetRow) getRowTop loop
      const top = this.cumulativeHeights[this.dragMove.targetRow] || 0
      const left = this.getColLeft(this.dragMove.targetCol)
      const width = this.getRangeWidth(this.dragMove.targetCol, this.dragMove.targetCol + cols)
      const height = this.getRangeHeight(this.dragMove.targetRow, this.dragMove.targetRow + rows)
      return {
        position: 'absolute',
        top: top + 'px',
        left: left + 'px',
        width: width + 'px',
        height: height + 'px',
        border: '2px dashed #1a73e8',
        pointerEvents: 'none',
        zIndex: 20
      }
    },

    // widthMode:'auto' — the grid's natural (max-content) width: row-number
    // gutter + outline gutter (when row groups exist) + every visible leaf
    // column's current width + the measured vertical scrollbar width (0 when
    // rows fit / overlay scrollbars). Fully reactive: column resize,
    // hide/show, col.visible, and group changes all re-derive it.
    naturalGridWidth() {
      const outlineW = this.rowGroups.length ? OUTLINE_GUTTER : 0
      return ROW_HEADER_WIDTH + outlineW + this.getColLeft(this.leafCols.length) + this.vScrollbarW + this.shellBorderW
    },

    // Reference width for resolving relative (%, css) column widths — always
    // hostContainerWidth (the grid's DOM parent), in both widthMode values.
    // See hostContainerWidth's declaration comment for why headerViewportWidth
    // (the grid's own scrollBody.clientWidth) isn't used for this in either
    // mode: circular in 'auto', and independently unstable in 'full' (a
    // vertical scrollbar toggling flips it without the shell's outer size
    // ever changing).
    _relativeWidthContainer() {
      return this.hostContainerWidth
    },

    // The CSS width both the shell and the wrapper use in non-fullscreen mode.
    _hostWidth() {
      if (this.widthMode === 'auto') return this.naturalGridWidth + 'px'
      return typeof this.width === 'number' ? this.width + 'px' : this.width
    },

    wrapperStyle() {
      if (this.isFullscreen) {
        return {
          width: '100%',
          height: 'auto',
          flex: '1 1 auto',
          minHeight: 0,
          position: 'relative',
          outline: 'none',
          userSelect: 'none'
        }
      }
      const style = {
        width: this._hostWidth,
        height: this.effectiveHeight + 'px',
        position: 'relative',
        outline: 'none',
        userSelect: 'none'
      }
      if (this.widthMode === 'auto') style.maxWidth = '100%'
      return style
    },

    shellStyle() {
      if (this.isFullscreen) return {}
      const style = {
        width: this._hostWidth,
        display: 'flex',
        flexDirection: 'column'
      }
      // The cap that keeps a too-wide column set at the host's edge
      // (internal horizontal scroll takes over from there).
      if (this.widthMode === 'auto') style.maxWidth = '100%'
      return style
    },

    canUndo() {
      // eslint-disable-next-line no-unused-expressions
      this.historyVersion
      return this._historyIndex >= 0
    },

    canRedo() {
      // eslint-disable-next-line no-unused-expressions
      this.historyVersion
      return this._historyIndex < this._history.length - 1
    },

    headerAreaStyle() {
      return {
        display: 'flex',
        flexDirection: 'row',
        position: 'sticky',
        top: 0,
        zIndex: 30,
        background: 'var(--eg-color-header-bg, var(--eg-color-header-bg-default))'
      }
    },

    cornerStyle() {
      const outlineW = this.rowGroups.length ? OUTLINE_GUTTER : 0
      return {
        width: (ROW_HEADER_WIDTH + outlineW) + 'px',
        minWidth: (ROW_HEADER_WIDTH + outlineW) + 'px',
        height: (this._headerRowH * this.headerDepth + this._filterRowH) + 'px',
        background: 'var(--eg-color-header-bg, var(--eg-color-header-bg-default))',
        borderRight: '1px solid var(--eg-color-border, var(--eg-color-border-default))',
        borderBottom: '1px solid var(--eg-color-border, var(--eg-color-border-default))',
        boxSizing: 'border-box',
        flexShrink: 0
      }
    },

    rowOutlineGutterStyle() {
      return { width: OUTLINE_GUTTER + 'px', flexShrink: 0 }
    },

    frozenColHeaderStyle() {
      const w = this.getFrozenWidth()
      return {
        width: w + 'px',
        minWidth: w + 'px',
        overflow: 'hidden',
        flexShrink: 0
      }
    },

    scrollColHeaderStyle() {
      // Once measured, lock the header to the body's exact clientWidth (flex: 0 0 <px>)
      // instead of growing independently via flex:1 — this guarantees identical
      // scrollWidth-clientWidth (max scrollLeft) on both, so syncing scrollLeft never clamps
      // one before the other. (padding-right can't do this: clientWidth always includes
      // padding, so padding never actually shrinks it.)
      //
      // The pinned zones must be subtracted from the measured clientWidth: in the
      // body they live INSIDE .eg-scroll-body as sticky overlays (so clientWidth
      // already spans them), but in the header/footer rows they are separate flex
      // siblings rendered BEFORE/AFTER this strip. Without the subtraction the
      // header/footer rows end up frozenWidth+pinnedRightWidth wider than the
      // container, giving .eg-container (overflow:auto) its own second horizontal
      // scrollbar. With it, this strip's viewport exactly matches the body's
      // scrollable window between the sticky zones, and — together with the strip
      // inner width being scrollableContentWidth — both max scrollLefts stay equal.
      // A falsy 0 (not just null/undefined) means "not really measured yet" — e.g. the grid
      // mounted while its container was display:none (a hidden v-show tab). Locking to '0 0 0px'
      // in that case would collapse the header/footer strip to invisible; fall back to the same
      // natural flex:1 used pre-measurement instead. The ResizeObserver in mounted() re-measures
      // once the container becomes visible, replacing this with a real px lock.
      if (this.headerViewportWidth) {
        const w = Math.max(
          0,
          this.headerViewportWidth - this.getFrozenWidth() - (this.hasPinnedRight ? this.pinnedRightWidth : 0)
        )
        return { flex: '0 0 ' + w + 'px', overflow: 'hidden' }
      }
      return { flex: 1, overflow: 'hidden' }
    },

    bodyAreaStyle() {
      // Fullscreen: let flexbox fill the viewport dynamically (mirrors
      // _containerH()'s fullscreen branch, which reads the resulting
      // clientHeight back for virtual-scroll math) — an explicit height
      // here would fight that.
      if (this.isFullscreen) {
        return {
          display: 'flex',
          flexDirection: 'row',
          flex: 1,
          position: 'relative'
        }
      }
      // Fixed/auto height: an explicit px height (matching _containerH()'s
      // non-fullscreen formula) instead of flex:1 growth. flex:1 here only
      // ever has ONE sibling competing for space mathematically, so it
      // should be exact — but nested flex cross-axis stretch (this box's
      // height flows down to .eg-scroll-body/.eg-row-header-col via
      // align-items:stretch) is vulnerable to sub-pixel rounding between
      // browser-rendered header/footer row heights and the integer px
      // this component assumes, occasionally landing 1px short. That 1px
      // shortfall is enough to make .eg-scroll-body's overflow:auto show a
      // vertical scrollbar even when content should fit exactly (reported
      // with a single data row and no `height` prop — content height ==
      // container height, so any shortfall trips overflow instantly).
      // flex: '0 0 auto' overrides the .eg-body-area class rule's own
      // `flex: 1` (flex-basis: 0%) — with a non-auto flex-basis, flexbox
      // ignores this element's own `height` entirely for main-axis sizing,
      // so basis must explicitly go back to `auto` for `height` to apply.
      const h = this.effectiveHeight - (this._headerRowH * this.headerDepth) - this._filterRowH - (this.hasFooter ? this._footerRowH : 0)
      return {
        display: 'flex',
        flexDirection: 'row',
        flex: '0 0 auto',
        height: Math.max(h, 0) + 'px',
        position: 'relative'
      }
    },

    rowHeaderColStyle() {
      return {
        width: ROW_HEADER_WIDTH + 'px',
        minWidth: ROW_HEADER_WIDTH + 'px',
        flexShrink: 0,
        display: 'flex',
        flexDirection: 'column',
        position: 'sticky',
        left: 0,
        zIndex: 20,
        background: 'var(--eg-color-header-bg, var(--eg-color-header-bg-default))'
      }
    },

    rowOutlineColStyle() {
      return {
        width: OUTLINE_GUTTER + 'px',
        minWidth: OUTLINE_GUTTER + 'px',
        flexShrink: 0,
        position: 'relative',
        background: 'var(--eg-color-cell-bg, var(--eg-color-cell-bg-default))'
      }
    },

    scrollBodyStyle() {
      return {
        flex: 1,
        overflow: 'auto',
        position: 'relative',
        overflowAnchor: 'none'   /* prevent Chrome scroll anchoring from fighting virtual scroll translateY */
      }
    },

    frozenColBodyStyle() {
      const w = this.getFrozenWidth()
      return {
        position: 'sticky',
        left: 0,
        width: w + 'px',
        flexShrink: 0,
        zIndex: 10,
        background: 'var(--eg-color-cell-bg, var(--eg-color-cell-bg-default))',
        overflow: 'hidden'
      }
    },

    mainCellsStyle() {
      const left = this.getFrozenWidth()
      return {
        position: 'absolute',
        left: left + 'px',
        top: 0,
        bottom: 0
      }
    },

    scrollContentWidth() {
      let w = 0
      for (let i = 0; i < this.leafCols.length; i++) {
        if (!this.isColHidden(i) && !this.pinnedRightSet.has(i)) w += this.getColW(i)
      }
      // Extra right padding so pinned-right zone doesn't cover the last scrollable column
      if (this.hasPinnedRight) w += this.pinnedRightWidth
      return w
    },

    scrollableContentWidth() {
      let w = 0
      for (let i = 0; i < this.leafCols.length; i++) {
        if (!this.isColHidden(i) && this.isColumnScrollable(i)) w += this.getColW(i)
      }
      return w
    },

    pinnedRightBodyStyle() {
      return {
        position: 'sticky',
        right: 0,
        // Natural position must be the inner's right edge for sticky right:0 to
        // engage (see the .eg-scroll-body-inner flex comment in the template).
        marginLeft: 'auto',
        width: this.pinnedRightWidth + 'px',
        zIndex: 10,
        background: 'white',
        overflow: 'hidden',
        flexShrink: 0
      }
    },

    pinnedRightHeaderStyle() {
      return {
        width: this.pinnedRightWidth + 'px',
        minWidth: this.pinnedRightWidth + 'px',
        overflow: 'hidden',
        flexShrink: 0,
        boxSizing: 'border-box',
        borderLeft: '1px solid var(--eg-color-border, var(--eg-color-border-default))'
      }
    },

    scrollRowHeadersStyle() {
      return { flex: 1, overflow: 'hidden', position: 'relative', overflowAnchor: 'none' }
    },

    footerAreaStyle() {
      return {
        display: 'flex',
        flexDirection: 'row',
        flexShrink: 0,
        position: 'sticky',
        bottom: 0,
        zIndex: 30,
        background: 'var(--eg-color-footer-bg, var(--eg-color-footer-bg-default))',
        // box-shadow (not a real border, like .eg-header-area's own
        // separator) — a real border would add an unaccounted extra 1px to
        // the footer's layout height (nothing in the height math knows
        // about it), throwing off effectiveHeight/_autoContentHeight and
        // tripping a phantom vertical scrollbar on .eg-scroll-body even
        // when content should fit exactly.
        boxShadow: '0 -2px 0 0 var(--eg-color-border-strong, var(--eg-color-border-strong-default))'
      }
    },

    footerLabelStyle() {
      const outlineW = this.rowGroups.length ? OUTLINE_GUTTER : 0
      return {
        width: (ROW_HEADER_WIDTH + outlineW) + 'px',
        minWidth: (ROW_HEADER_WIDTH + outlineW) + 'px',
        height: this._footerRowH + 'px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'var(--eg-color-footer-bg, var(--eg-color-footer-bg-default))',
        borderRight: '1px solid var(--eg-color-border, var(--eg-color-border-default))',
        borderTop: '1px solid var(--eg-color-border, var(--eg-color-border-default))',
        boxSizing: 'border-box',
        flexShrink: 0,
        fontSize: 'var(--eg-font-size-header, var(--eg-font-size-header-default))',
        fontWeight: 600
      }
    },

    frozenColFooterStyle() {
      const w = this.getFrozenWidth()
      return {
        width: w + 'px',
        minWidth: w + 'px',
        height: this._footerRowH + 'px',
        overflow: 'hidden',
        flexShrink: 0
      }
    },

    pinnedRightFooterStyle() {
      return {
        width: this.pinnedRightWidth + 'px',
        minWidth: this.pinnedRightWidth + 'px',
        height: this._footerRowH + 'px',
        overflow: 'hidden',
        flexShrink: 0,
        boxSizing: 'border-box',
        borderLeft: '1px solid var(--eg-color-border, var(--eg-color-border-default))'
      }
    },

    colOutlineRowStyle() {
      return {
        position: 'absolute',
        top: -OUTLINE_GUTTER + 'px',
        left: 0,
        right: 0,
        height: OUTLINE_GUTTER + 'px'
      }
    },

    resizeLineStyle() {
      if (!this.resizing.active) return {}
      if (this.resizing.type === 'col') {
        return {
          position: 'absolute',
          top: 0,
          left: (this.resizing.currentPos - (this.resizing.containerLeft || 0)) + 'px',
          width: '2px',
          height: '100%',
          background: 'var(--eg-color-accent, var(--eg-color-accent-default))',
          pointerEvents: 'none',
          zIndex: 9999
        }
      } else {
        return {
          position: 'absolute',
          left: 0,
          top: (this.resizing.currentPos - (this.resizing.containerTop || 0)) + 'px',
          height: '2px',
          width: '100%',
          background: 'var(--eg-color-accent, var(--eg-color-accent-default))',
          pointerEvents: 'none',
          zIndex: 9999
        }
      }
    }
  },

  watch: {
    size: {
      immediate: true,
      handler(v) { this.internalSize = v || 'middle' }
    },

    theme: {
      immediate: true,
      handler(v) { this.internalTheme = v || 'excel' }
    },

    // Runs before the `columns`/`data` watchers below (both call
    // _recomputeRowFilters()) so internalFilters already reflects the prop
    // by the time either of them fires during the initial immediate pass.
    filters: {
      immediate: true,
      handler(v) { this.internalFilters = v ? { ...v } : {} }
    },

    internalFilters() { this._scheduleFilterRecompute() },

    filterRow() {
      this._recomputeRowFilters()
      this.$nextTick(() => this.updateVirtualScroll())
    },

    sort: {
      immediate: true,
      handler(v) { this.internalSort = v ? { key: v.key, direction: v.direction } : null }
    },

    internalSize() {
      this.rowHeights = {}
      this.$nextTick(() => this.updateVirtualScroll())
    },

    autoWidth(v) {
      if (v) this._applyAutoWidth()
    },

    fitColumns(v) {
      if (v) {
        this.fitColumnsOverrides = {}
        this._applyFitColumns()
      } else {
        // Back to normal per-column resolution (same as the columns
        // watcher's non-fit branch, without keyToWidth — fitColumns already
        // discarded any remembered manual-resize widths when it turned on).
        const newColWidths = {}
        const newRelativeSpecs = {}
        this.leafCols.forEach(col => {
          newColWidths[col._flatIndex] = this.resolveColWidth(col.width, this._relativeWidthContainer)
          const parsed = parseColWidthSpec(col.width)
          if (parsed.type !== 'px') newRelativeSpecs[col._flatIndex] = col.width
        })
        this.colWidths = newColWidths
        this.relativeColSpecs = newRelativeSpecs
        this.fitColumnsOverrides = {}
        this._applyAutoWidth()
      }
    },

    columns: {
      immediate: true,
      handler(cols) {
        // Build key→width map from current state before rebuilding leafCols.
        // This preserves user-resized widths across column reorders: when columns
        // are moved, _flatIndex values shift but col.key stays the same.
        const keyToWidth = {}
        const keyToSpec = {}
        ;(this.leafCols || []).forEach(col => {
          if (this.colWidths[col._flatIndex] !== undefined) {
            keyToWidth[col.key] = this.colWidths[col._flatIndex]
          }
          if (this.relativeColSpecs[col._flatIndex] !== undefined) {
            keyToSpec[col.key] = this.relativeColSpecs[col._flatIndex]
          }
        })

        this.leafCols = flattenColumns(cols)
        this.headerDepth = columnTreeDepth(cols)
        this.headerRows = buildHeaderRows(cols, this.headerDepth)
        this._maskCache = {}

        if (this.fitColumns) {
          // fitColumns is the highest-priority width control — it overrides
          // even remembered manual-resize widths (keyToWidth above), so it
          // deliberately does NOT participate in that preservation logic.
          // fitColumnsOverrides (per-column fixed-width overrides set by
          // manually resizing while fitColumns is on) IS preserved, by key,
          // dropping any keys that no longer exist in the new column set.
          this.colWidths = {}
          this.relativeColSpecs = {}
          const validKeys = new Set(this.leafCols.map(c => c.key))
          const newOverrides = {}
          Object.keys(this.fitColumnsOverrides).forEach(k => {
            if (validKeys.has(k)) newOverrides[k] = true
          })
          this.fitColumnsOverrides = newOverrides
          this._applyFitColumns()
        } else {
          // Rebuild colWidths by new flat index, using col.key to look up saved widths
          const newColWidths = {}
          const newRelativeSpecs = {}
          this.leafCols.forEach(col => {
            if (keyToWidth[col.key] !== undefined) {
              newColWidths[col._flatIndex] = keyToWidth[col.key]
              if (keyToSpec[col.key] !== undefined) newRelativeSpecs[col._flatIndex] = keyToSpec[col.key]
            } else {
              newColWidths[col._flatIndex] = this.resolveColWidth(col.width, this._relativeWidthContainer)
              const parsed = parseColWidthSpec(col.width)
              if (parsed.type !== 'px') newRelativeSpecs[col._flatIndex] = col.width
            }
          })
          this.colWidths = newColWidths
          this.relativeColSpecs = newRelativeSpecs
        }

        this.computeColumnTotals()
        this._recomputeRowFilters()
        this.updateVirtualScroll()
        this._applyAutoWidth()

        // Merge col.pin entries for columns not yet tracked in internalPinnedColumns.
        // Existing entries (from prop or prior runtime pin/unpin) are not overwritten.
        const pinFromCols = this._colPinMap(this.leafCols)
        Object.keys(pinFromCols).forEach(key => {
          if (!(key in this.internalPinnedColumns)) this.$set(this.internalPinnedColumns, key, pinFromCols[key])
        })
      }
    },
    pinnedColumns: {
      immediate: true,
      handler(v) {
        // Rebuild: col.pin is the base default, prop value wins on conflict.
        this.internalPinnedColumns = { ...this._colPinMap(this.leafCols), ...(v || {}) }
      }
    },
    merges: {
      immediate: true,
      handler(v) { this.internalMerges = v ? [...v] : [] }
    },
    collapsedGroups: {
      immediate: true,
      handler(v) { this.internalCollapsedGroups = v ? [...v] : [] }
    },
    // `immediate: true` guarantees this fires once, synchronously, right at
    // setup regardless of `v` — that's the one reliable signal that THIS
    // particular call is the initial sync, not a real host-driven change
    // (e.g. via `:locked.sync`). Every call after the first is a genuine
    // change, so only those flash. (Watching internalLocked itself for this
    // instead — the previous approach — can't tell "initial value happened
    // to be true" from "the user's first-ever real toggle": both look like
    // "the first time internalLocked actually changed value".)
    locked: {
      immediate: true,
      handler(v) {
        this.internalLocked = !!v
        if (this._lockPropSynced) this._flashLock(this.internalLocked)
        this._lockPropSynced = true
      }
    },
    data: {
      immediate: true,
      handler(newData) {
        // Keep _dataRaw in sync so template uses fresh data without triggering dependArray
        this._dataRaw = newData || []
        this._recomputeRowFilters()
        this.updateVirtualScroll()
        this.computeColumnTotals()
        // Force re-render so cell values refresh even when virtualScroll indices don't change
        // (e.g. editing a cell: same row count, same scroll position, only content changed)
        this.$forceUpdate()
        this._applyAutoWidth()
      }
    },
    totalRows() { this.updateVirtualScroll() },
    hiddenRowSet() { this.updateVirtualScroll() },
    totalVirtualHeight() { this.$nextTick(this.syncHeaderViewportWidth) },
    // widthMode:'auto' — the shell resizes with its columns (resize, hide/
    // show), so the header/body viewport lock must be re-measured after the
    // DOM picks up the new width. (The runaway-loop safety net lives in
    // _widthSyncChainOk(), gating the actual colWidths mutation inside
    // syncHeaderViewportWidth() — not here — since that single choke point
    // catches every trigger path, not just this one.)
    naturalGridWidth() {
      if (this.widthMode === 'auto') this.$nextTick(this.syncHeaderViewportWidth)
    },
    widthMode() { this.$nextTick(this.syncHeaderViewportWidth) },

    // localSyncKey/tenant feature — mounted() only calls
    // _loadLocalVersionsOnMount() once, at mount time. Without these
    // watchers, a key/tenant that starts empty (a host conditionally
    // passing `:local-sync-key="ready ? id : null"`, or a `tenant` only
    // known after an async "current organization" load) and later becomes
    // truthy would never load its version list, never promote a leftover
    // buffer, and never show the toolbar badge — the feature would look
    // "broken" for the rest of that page's lifetime even though everything
    // else works. Both share _reloadLocalSyncForKeyChange() since either one
    // changing means the effective storage key changed.
    localSyncKey(newKey, oldKey) {
      if (newKey === oldKey) return
      this._reloadLocalSyncForKeyChange()
    },
    tenant(newTenant, oldTenant) {
      if (newTenant === oldTenant) return
      this._reloadLocalSyncForKeyChange()
    }
  },

  created() {
    // Non-reactive row data reference — avoids Vue 2 dependArray(data) O(n) loop.
    // Vue 2 calls dependArray() for EVERY `data[ri]` access in the template,
    // iterating all 50,000 rows each time. With 1200 cells per render that's
    // 60 million iterations per render (~600ms). _dataRaw bypasses this.
    this._dataRaw = this.data || []

    // Non-reactive caches: same (w,h) → same style object → Vue 2 skips DOM style writes
    this._cellStyleCache = Object.create(null)
    this._rowStyleCache = Object.create(null)
    this._rowHeaderStyleCache = Object.create(null)
    // rAF handles for scroll/resize throttle
    this._scrollRAF = null
    this._resizeRAF = null

    // Undo/redo history — non-reactive to avoid Vue overhead.
    // Each entry: { type: 'data'|'merges', before: {...}, after: {...} }
    // 'data' stores only diff rows: { indices: number[], rows: object[] }
    this._history = []
    this._historyIndex = -1
    this._historySkip = false   // true while undo/redo is in progress

    // Column drag preview offsets — non-reactive so direct DOM updates bypass Vue re-renders.
    // Keys are column keys, values are pixel offsets.
    this._dragOffsets = {}

    // Column drag internals (all non-reactive):
    // _dragBounds — snapshot of every visible leaf header's ORIGINAL viewport
    // rect taken once at drag start; drop-index math reads only this snapshot
    // (adjusted by scrollLeft delta), never live DOM rects — live rects carry
    // in-flight CSS transforms and give unstable intermediate positions.
    this._dragBounds = null
    this._dragStartScrollLeft = 0
    this._pendingDragHeaderRect = null
    this._lastDragClientX = 0
    this._dragScrollV = 0        // px/frame edge auto-scroll velocity (0 = idle)
    this._dragScrollRAF = null
    this._dragCleanupTimer = null

    // Fill-handle drag edge auto-scroll (see _updateFillDragAutoScroll) — same
    // idle-when-0 convention as _dragScrollV/_dragScrollRAF above, just for
    // both axes since a fill can extend down OR right.
    this._fillDragScrollV = 0
    this._fillDragScrollH = 0
    this._fillDragScrollRAF = null
    this._fillDragLastEvent = null

    // localSyncKey — the last `data` reference a version was actually saved
    // for. Initialized to the current (mount-time) value so an untouched grid
    // that's merely tab-switched away from doesn't spam a "nothing happened"
    // version on every hide — only a REAL edit (which replaces this array
    // reference, see _emitDataChange) makes the next hide event flush.
    this._lastFlushedDataRef = this.data
  },

  mounted() {
    this.updateVirtualScroll()
    this.$nextTick(this.syncHeaderViewportWidth)
    document.addEventListener('mousemove', this.onGlobalMouseMove)
    document.addEventListener('mouseup', this.onGlobalMouseUp)
    document.addEventListener('keydown', this.onGlobalKeyDown)
    document.addEventListener('mousedown', this._onDocMouseDownForDropdown, true)
    window.addEventListener('resize', this.syncHeaderViewportWidth)
    window.addEventListener('scroll', this._onWindowScrollForDropdown, true)
    // Self-heals the "mounted while display:none" case (e.g. a v-show tab that isn't
    // active yet) — scrollBody.clientWidth reads 0 at mount, and nothing but a real
    // window resize would otherwise ever re-measure it. ResizeObserver also fires when
    // the container regains real dimensions (tab becomes visible), so headers/footer
    // (scrollColHeaderStyle) get correctly re-locked with no host code changes needed.
    // rAF-batched like onBodyScroll's _scrollRAF, to avoid thrashing during a live drag-resize.
    if (typeof ResizeObserver !== 'undefined' && this.$refs.scrollBody) {
      this._scrollBodyResizeObserver = new ResizeObserver(() => {
        if (this._roRAF) return
        this._roRAF = requestAnimationFrame(() => {
          this._roRAF = null
          this.syncHeaderViewportWidth()
        })
      })
      this._scrollBodyResizeObserver.observe(this.$refs.scrollBody)
      // Also observe the grid's own DOM parent — needed in BOTH widthMode
      // values to keep hostContainerWidth (relative column widths' reference
      // in both modes) fresh when the host's layout changes.
      if (this.$el.parentElement) this._scrollBodyResizeObserver.observe(this.$el.parentElement)
    }
    this._loadLocalVersionsOnMount()
    // localSyncKey — save on page-hide, not per-edit (see _flushLocalVersionOnHide).
    // 'visibilitychange'->hidden is the primary trigger: it fires for tab
    // switches, minimizing, AND reliably before actual tab close/navigation on
    // both desktop and mobile, while the page is still very likely alive —
    // giving the async worker-hash + IndexedDB write a real chance to finish.
    // 'pagehide' is a backstop for the cases visibilitychange misses; it's
    // idempotent with visibilitychange (same content -> same hash -> no-op
    // beyond a timestamp touch) so firing both is harmless.
    document.addEventListener('visibilitychange', this._onVisibilityChangeForLocalSync)
    window.addEventListener('pagehide', this._onPageHideForLocalSync)
  },

  updated() {
    // After Vue re-renders (e.g., virtual scroll adds new rows during drag),
    // apply missing transforms to newly rendered cells that don't have one yet.
    // The transform lands with transitions disabled (a fresh cell must appear
    // in place, not fly in from its untransformed position); the drag
    // transition is re-armed on the next frame.
    if (!this.colDrag.active || !this.$el) return
    const offsets = this._dragOffsets
    if (!offsets || !Object.keys(offsets).length) return
    const fresh = []
    this.$el.querySelectorAll('[data-fi]').forEach(el => {
      if (el.style.transform) return
      const fi = parseInt(el.dataset.fi)
      const col = this.leafCols[fi]
      const dx = col ? (offsets[col.key] || 0) : 0
      el.style.transition = 'none'
      el.style.transform = `translateX(${dx}px)`
      fresh.push(el)
    })
    if (fresh.length) {
      requestAnimationFrame(() => {
        if (!this.colDrag.active) return
        fresh.forEach(el => { el.style.transition = COL_DRAG_TRANSITION })
      })
    }
  },

  beforeDestroy() {
    clearTimeout(this._filterRecomputeTimer)
    clearTimeout(this._onInputTimer)
    clearTimeout(this._dragCleanupTimer)
    clearTimeout(this._widthSyncChainResetTimer)
    clearTimeout(this._bufferWriteTimer)
    if (this._dragScrollRAF) cancelAnimationFrame(this._dragScrollRAF)
    if (this._fillDragScrollRAF) cancelAnimationFrame(this._fillDragScrollRAF)
    document.removeEventListener('mousemove', this.onGlobalMouseMove)
    document.removeEventListener('mouseup', this.onGlobalMouseUp)
    document.removeEventListener('keydown', this.onGlobalKeyDown)
    document.removeEventListener('mousedown', this._onDocMouseDownForDropdown, true)
    window.removeEventListener('resize', this.syncHeaderViewportWidth)
    window.removeEventListener('scroll', this._onWindowScrollForDropdown, true)
    document.removeEventListener('visibilitychange', this._onVisibilityChangeForLocalSync)
    window.removeEventListener('pagehide', this._onPageHideForLocalSync)
    // Best-effort — the component may be torn down (SPA route change) without
    // the page itself unloading, which visibilitychange/pagehide won't catch.
    // sync: true — see _flushLocalVersionOnHide()'s comment; a component
    // being destroyed is exactly the same "might not survive an async hop"
    // situation as the other two triggers.
    this._flushLocalVersionOnHide(false, true)
    if (this.isFullscreen) {
      document.body.style.overflow = this._prevBodyOverflow || ''
      document.removeEventListener('keydown', this._onFullscreenKeyDown)
    }
    if (this._widthProbeEl && this._widthProbeEl.parentNode) {
      this._widthProbeEl.parentNode.removeChild(this._widthProbeEl)
    }
    if (this._maskInput) { this._maskInput.destroy(); this._maskInput = null }
    if (this._scrollBodyResizeObserver) { this._scrollBodyResizeObserver.disconnect(); this._scrollBodyResizeObserver = null }
    if (this._roRAF) { cancelAnimationFrame(this._roRAF); this._roRAF = null }
  },

  methods: {
    // =========================================================
    // VIRTUAL SCROLL
    // =========================================================
    // In fullscreen, .eg-scroll-body's real height comes from flexbox filling
    // the viewport (which can be far taller than the `height` prop the host
    // originally passed for the fixed-size layout) — measure it directly
    // instead of trusting `height`, otherwise virtual scroll only ever
    // renders enough rows for the old fixed size, leaving the rest of the
    // (visually stretched) container blank.
    _containerH() {
      if (this.isFullscreen && this.$refs.scrollBody) return this.$refs.scrollBody.clientHeight
      const footerH = this.hasFooter ? this._footerRowH : 0
      return this.effectiveHeight - (this._headerRowH * this.headerDepth) - this._filterRowH - footerH
    },

    // Same fullscreen-aware measurement as _containerH(), but mirrors PageUp/
    // PageDown's pre-existing (footer-agnostic) row-span formula exactly for
    // the non-fullscreen case, so normal-mode behavior is unchanged.
    _pageRowSpan() {
      const h = this.isFullscreen && this.$refs.scrollBody
        ? this.$refs.scrollBody.clientHeight
        : (this.effectiveHeight - this._headerRowH * this.headerDepth - this._filterRowH)
      return Math.floor(h / this._rowH)
    },

    updateVirtualScroll() {
      // Use binary search against the Vue-cached cumulativeHeights → O(log n) per scroll.
      // overscan=8 (≈224px at default row height) gives enough buffer for fast scroll
      // without blank-band artifacts between rAF updates.
      const result = findVisibleRange(
        this.scrollTop, Math.max(this._containerH(), 100), this.totalRows, this.cumulativeHeights, 8
      )
      this.virtualStartIndex = result.startIndex
      this.virtualEndIndex = result.endIndex
      this.virtualOffsetTop = result.offsetTop
      this.totalVirtualHeight = result.totalHeight
    },

    onBodyScroll(e) {
      const target = e.target
      // Sync sibling scroll containers immediately (visual alignment, no layout trigger)
      if (this.$refs.scrollColHeader) this.$refs.scrollColHeader.scrollLeft = target.scrollLeft
      if (this.$refs.scrollFooter) this.$refs.scrollFooter.scrollLeft = target.scrollLeft
      if (this.$refs.scrollRowHeaders) this.$refs.scrollRowHeaders.scrollTop = target.scrollTop

      // Close dropdown on scroll — fixed-position dropdown drifts away from the moving cell
      if (this.selectDropdown) this.closeSelectDropdown()
      if (this.datePickerOverlay) this.closeDatePicker()

      // Throttle reactive state updates + virtual scroll recalc to one rAF per frame.
      // Read scrollTop from the DOM ref at rAF time (not from the stale event closure)
      // so that multiple scroll events arriving between frames still resolve to the
      // final position — eliminates the flickering caused by render/scroll mismatch.
      if (!this._scrollRAF) {
        this._scrollRAF = requestAnimationFrame(() => {
          this._scrollRAF = null
          const sb = this.$refs.scrollBody
          if (!sb) return
          this.scrollTop = sb.scrollTop
          this.scrollLeft = sb.scrollLeft
          this.updateVirtualScroll()
        })
      }
    },

    onScroll(e) {},

    // .eg-scroll-col-header (overflow:hidden, synced via JS) has no native scrollbar, but
    // .eg-scroll-body (overflow:auto) does — its real vertical scrollbar eats into its
    // clientWidth. If both containers just grow via flex:1, the header ends up wider than
    // the body, so its max scrollLeft is smaller and syncing clamps it before the body
    // reaches its rightmost scroll position — column borders desync right at the scroll
    // end. Locking the header to the body's exact measured clientWidth (scrollColHeaderStyle)
    // makes both max scrollLeft values identical.
    syncHeaderViewportWidth() {
      // Auto-height's 70vh cap tracks the real viewport — keep it current on resize.
      if (typeof window !== 'undefined' && this.windowInnerH !== window.innerHeight) {
        this.windowInnerH = window.innerHeight
      }
      const el = this.$refs.scrollBody
      if (!el) return
      // headerViewportWidth is still tracked in both modes (scrollColHeaderStyle/
      // virtual scroll need the grid's OWN viewport width) — but no longer
      // feeds relative column-width resolution at all (see
      // _relativeWidthContainer/hostContainerWidth's comments for why: it's
      // circular in 'auto' and independently scrollbar-toggle-unstable in
      // 'full'). _widthSyncChainOk() still guards the assignment itself,
      // since it's reactive (scrollColHeaderStyle reads it) — at fractional
      // page-zoom levels el.clientWidth can genuinely oscillate by ±1px
      // indefinitely (a vertical scrollbar toggling right at that subpixel
      // rounding boundary), which would otherwise re-render on every flip
      // forever even with nothing left downstream to actually resolve.
      if (this.headerViewportWidth !== el.clientWidth && this._widthSyncChainOk()) {
        this.headerViewportWidth = el.clientWidth
      }
      // Reference for relative (%, css) column widths, in BOTH widthMode
      // values — see hostContainerWidth's declaration comment. Measured from
      // the grid's DOM PARENT (not the grid itself, and not its scrollBody),
      // which is stable regardless of the grid's own rendered size or
      // internal scrollbar state — UNLESS the host's own layout also
      // auto-sizes around the grid (e.g. the parent shrink-wraps to its
      // content), which recreates a similar cycle outside our control.
      // _widthSyncChainOk() guards the assignment itself against that
      // residual case — the single choke point both a resized parent (this
      // block) and a resized shell (the naturalGridWidth watcher, via a
      // fresh call to this method, 'auto' mode only) funnel through.
      if (this.$el && this.$el.parentElement) {
        const pw = this.$el.parentElement.clientWidth
        if (pw !== this.hostContainerWidth && this._widthSyncChainOk()) {
          this.hostContainerWidth = pw
          if (this.fitColumns) this._applyFitColumns()
          else this._resolveRelativeColWidths()
        }
      }
      const sbw = el.offsetWidth - el.clientWidth
      if (sbw >= 0 && sbw !== this.vScrollbarW) this.vScrollbarW = sbw
      // Shell border total (see naturalGridWidth) — offsetWidth-clientWidth
      // is exactly the horizontal borders here (the shell itself never scrolls).
      const shell = this.$el
      if (shell && shell.offsetWidth) {
        const bw = shell.offsetWidth - shell.clientWidth
        if (bw >= 0 && bw !== this.shellBorderW) this.shellBorderW = bw
      }
      // Window resize while fullscreen changes the real available row-viewport
      // height too (see _containerH()) — recompute which rows are rendered.
      // Same for auto-height (height prop omitted): the 70vh cap just moved.
      if (this.isFullscreen || this.height == null) this.updateVirtualScroll()
    },

    // Runaway width-measurement guard — used in BOTH widthMode values.
    // In 'auto' mode, hostContainerWidth re-resolving colWidths is DESIGNED
    // to settle in 1-2 calls, but a host layout that also auto-sizes AROUND
    // the grid can recreate a circular dependency outside our control. In
    // 'full' mode there's no such circularity by construction, but
    // el.clientWidth is still a real browser measurement, and at fractional
    // page-zoom levels it can genuinely oscillate by ±1px indefinitely
    // (scrollbar toggling right at the rounding boundary, or ResizeObserver's
    // own well-known "callback reads a size that changes again" footgun).
    // Either way the symptom is the same: syncHeaderViewportWidth keeps
    // getting re-triggered forever. Caps consecutive calls instead of
    // chasing forever; 400ms of quiet resets the count, so a legitimately
    // slow (but finite) settle is never penalized — only a genuinely
    // runaway chain trips it.
    _widthSyncChainOk() {
      this._widthSyncChainCount = (this._widthSyncChainCount || 0) + 1
      clearTimeout(this._widthSyncChainResetTimer)
      this._widthSyncChainResetTimer = setTimeout(() => { this._widthSyncChainCount = 0 }, 400)
      if (this._widthSyncChainCount > 30) {
        if (!this._widthSyncChainWarned) {
          this._widthSyncChainWarned = true
          // eslint-disable-next-line no-console
          console.warn('[vue2-excel-grid] widthMode="' + this.widthMode + '": column width measurement did not stabilize after 30 consecutive re-measures (possibly fractional browser zoom, or a host layout that also auto-sizes around the grid) — freezing at the last measured size instead of re-rendering forever.')
        }
        return false // stop chasing; keep the last measured/resolved widths instead of looping forever
      }
      return true
    },

    // =========================================================
    // HELPERS
    // =========================================================
    isRowHidden(ri) { return this.hiddenRowSet.has(ri) },
    isColHidden(ci) { return this.effectiveHiddenColSet.has(ci) },

    getColW(ci) {
      return this.colWidths[ci] !== undefined ? this.colWidths[ci] : (this.leafCols[ci] ? this.resolveColWidth(this.leafCols[ci].width, this._relativeWidthContainer) : DEFAULT_COL_WIDTH)
    },

    // Turns a col.width spec (number, 'Npx', 'N%', or any other CSS length like
    // 'Nem'/'calc(...)') into a concrete px number. Percent is resolved against
    // containerWidth (see _relativeWidthContainer — always hostContainerWidth,
    // in both widthMode values); other CSS units are resolved via a hidden
    // DOM probe (_measureCssWidth).
    resolveColWidth(spec, containerWidth) {
      const parsed = parseColWidthSpec(spec)
      if (parsed.type === 'px') return Math.max(20, parsed.value)
      if (parsed.type === 'percent') {
        if (!containerWidth) return DEFAULT_COL_WIDTH
        return Math.max(20, (parsed.value / 100) * containerWidth)
      }
      const measured = this._measureCssWidth(parsed.value)
      return Math.max(20, measured || DEFAULT_COL_WIDTH)
    },

    // Measures an arbitrary CSS width string (em/rem/vw/calc/...) by applying it
    // to a hidden probe element, so it inherits ambient font-size for em/rem.
    // Parented in the grid's DOM PARENT (not the grid root or its scrollBody)
    // in both widthMode values, matching _relativeWidthContainer — a
    // %/calc(%...) value would otherwise resolve against the grid's own
    // rendered size, which is either circular ('auto') or independently
    // scrollbar-toggle-unstable ('full'). Falls back to the grid root if
    // there's no parent (e.g. a detached/test mount). Returns null before
    // mount (no DOM yet).
    _measureCssWidth(cssValue) {
      if (typeof document === 'undefined' || !this.$el || !this.$el.appendChild) return null
      const parent = this.$el.parentElement || this.$el
      if (!this._widthProbeEl || this._widthProbeEl.parentNode !== parent) {
        if (this._widthProbeEl && this._widthProbeEl.parentNode) {
          this._widthProbeEl.parentNode.removeChild(this._widthProbeEl)
        }
        const el = document.createElement('div')
        el.style.position = 'absolute'
        el.style.visibility = 'hidden'
        el.style.height = '0'
        el.style.overflow = 'hidden'
        el.style.pointerEvents = 'none'
        parent.appendChild(el)
        this._widthProbeEl = el
      }
      this._widthProbeEl.style.width = cssValue
      return this._widthProbeEl.offsetWidth
    },

    // Re-resolves every column whose width spec is relative (%, em, vw, ...)
    // against the current _relativeWidthContainer — called whenever that
    // reference width changes (initial mount + window resize), so
    // percent/relative columns stay responsive like real CSS, matching a
    // plain numeric/px width's stability.
    _resolveRelativeColWidths() {
      const specs = this.relativeColSpecs
      const keys = Object.keys(specs)
      if (!keys.length) return
      keys.forEach(ci => {
        this.$set(this.colWidths, ci, this.resolveColWidth(specs[ci], this._relativeWidthContainer))
      })
      this._cellStyleCache = Object.create(null)
    },

    getRowH(ri) {
      if (this.isRowHidden(ri)) return 0
      return this.rowHeights[ri] || this._rowH
    },

    getColLeft(ci) {
      let left = 0
      for (let i = 0; i < ci && i < this.leafCols.length; i++) {
        if (!this.isColHidden(i)) left += this.getColW(i)
      }
      return left
    },

    getFrozenWidth() {
      return this.hasPinnedLeft ? this.pinnedLeftWidth : 0
    },

    // Scroll-position-aware pinned-column edge shadow (mirrors Ant Design/AG Grid's own
    // convention): the shadow only appears while there's actually scrolled-away content
    // hiding under the pinned zone on that side, not as a permanent decoration — a static
    // shadow reads as background noise and the user stops noticing it exactly when it
    // matters (mid-scroll). Read scrollLeft (already tracked reactively, updated every
    // rAF tick in onBodyScroll) so template :class bindings re-evaluate on every scroll frame.
    hasHiddenScrollLeft() {
      return this.getFrozenWidth() > 0 && this.scrollLeft > 0
    },
    hasHiddenScrollRight() {
      if (!this.hasPinnedRight) return false
      const sb = this.$refs.scrollBody
      if (!sb) return false
      return this.scrollLeft < sb.scrollWidth - sb.clientWidth - 1
    },

    isColumnPinnedLeft(ci) {
      return this.pinnedLeftSet.has(ci)
    },

    isColumnPinnedRight(ci) {
      return this.pinnedRightSet.has(ci)
    },

    isColumnScrollable(ci) {
      return !this.isColumnPinnedLeft(ci) && !this.isColumnPinnedRight(ci)
    },

    getZoneColLeft(ci, zone) {
      let left = 0
      if (zone === 'left') {
        for (const col of this.pinnedLeftCols) {
          if (col._flatIndex === ci) break
          if (!this.isColHidden(col._flatIndex)) left += this.getColW(col._flatIndex)
        }
      } else if (zone === 'right') {
        for (const col of this.pinnedRightCols) {
          if (col._flatIndex === ci) break
          if (!this.isColHidden(col._flatIndex)) left += this.getColW(col._flatIndex)
        }
      } else {
        for (let i = 0; i < this.leafCols.length; i++) {
          const col = this.leafCols[i]
          if (col._flatIndex === ci) break
          if (!this.isColHidden(col._flatIndex) && this.isColumnScrollable(col._flatIndex)) {
            left += this.getColW(col._flatIndex)
          }
        }
      }
      return left
    },

    isCellInZone(cell, rowIdx, zone) {
      if (cell.isGroup) {
        const start = cell._firstLeafFlatIndex
        const end = start + cell.colspan - 1
        for (let i = start; i <= end; i++) {
          if (this.isColHidden(i)) continue
          const z = this.isColumnPinnedLeft(i) ? 'left' : (this.isColumnPinnedRight(i) ? 'right' : 'scroll')
          if (z === zone) return true
        }
        return false
      }
      const ci = cell.column._flatIndex
      if (this.isColHidden(ci)) return false
      const z = this.isColumnPinnedLeft(ci) ? 'left' : (this.isColumnPinnedRight(ci) ? 'right' : 'scroll')
      return z === zone
    },

    getHeaderCellStyleForZone(cell, rowIndex, zone) {
      let leftLeafIdx = cell._firstLeafFlatIndex
      if (cell.isGroup) {
        const end = leftLeafIdx + cell.colspan - 1
        for (let i = leftLeafIdx; i <= end; i++) {
          if (this.isColHidden(i)) continue
          const z = this.isColumnPinnedLeft(i) ? 'left' : (this.isColumnPinnedRight(i) ? 'right' : 'scroll')
          if (z === zone) { leftLeafIdx = i; break }
        }
      }
      const left = this.getZoneColLeft(leftLeafIdx, zone)
      let width = 0
      if (cell.isGroup) {
        const start = cell._firstLeafFlatIndex
        const end = start + cell.colspan - 1
        for (let i = start; i <= end; i++) {
          if (this.isColHidden(i)) continue
          const z = this.isColumnPinnedLeft(i) ? 'left' : (this.isColumnPinnedRight(i) ? 'right' : 'scroll')
          if (z !== zone) continue
          width += this.getColW(i)
        }
      } else {
        width = this.getColW(cell.column._flatIndex)
      }
      return {
        top: (this._headerRowH * rowIndex) + 'px',
        left: left + 'px',
        width: width + 'px',
        height: (this._headerRowH * cell.rowspan) + 'px'
      }
    },

    getRangeWidth(startCol, endCol) {
      let w = 0
      for (let i = startCol; i <= endCol && i < this.leafCols.length; i++) {
        if (!this.isColHidden(i)) w += this.getColW(i)
      }
      return w
    },

    getRangeHeight(startRow, endRow) {
      let h = 0
      for (let i = startRow; i <= endRow && i < this.totalRows; i++) {
        if (!this.isRowHidden(i)) h += this.getRowH(i)
      }
      return h
    },

    getCellValue(ri, ci) {
      const col = this.leafCols[ci]
      if (!col) return ''
      const row = this._dataRaw[ri]
      if (!row) return ''
      const v = row[col.key]
      return v !== undefined ? v : ''
    },

    isEditing(ri, ci) {
      return this.editingCell && this.editingCell.row === ri && this.editingCell.col === ci
    },

    isMergedAway(ri, ci) {
      const merge = findMergeAtCell(ri, ci, this.internalMerges)
      if (!merge) return false
      const nm = normalizeRange(merge)
      return !(nm.startRow === ri && nm.startCol === ci)
    },

    getMergeSpan(ri, ci) {
      const merge = findMergeAtCell(ri, ci, this.internalMerges)
      if (!merge) return { rowspan: 1, colspan: 1 }
      const nm = normalizeRange(merge)
      return {
        rowspan: nm.endRow - nm.startRow + 1,
        colspan: nm.endCol - nm.startCol + 1
      }
    },

    isSelected(ri, ci) {
      return isCellInAnyRange(ri, ci, this.selectionRanges)
    },

    isActiveCell(ri, ci) {
      return this.activeCell.row === ri && this.activeCell.col === ci
    },

    isCopyHighlighted(ri, ci) {
      if (!this.clipboardRange || this.clipboardMode !== 'copy') return false
      return isCellInRange(ri, ci, this.clipboardRange)
    },

    // =========================================================
    // STYLES
    // =========================================================
    getRowStyle(ri) {
      const h = this.getRowH(ri)
      const key = h
      if (this._rowStyleCache[key]) return this._rowStyleCache[key]
      const style = { height: h + 'px', minHeight: h + 'px' }
      this._rowStyleCache[key] = style
      return style
    },

    getRowHeaderStyle(ri) {
      const h = this.getRowH(ri)
      const key = h
      if (this._rowHeaderStyleCache[key]) return this._rowHeaderStyleCache[key]
      const style = { height: h + 'px' }
      this._rowHeaderStyleCache[key] = style
      return style
    },

    getCellStyle(ri, ci) {
      const merge = findMergeAtCell(ri, ci, this.internalMerges)
      const nm = merge ? normalizeRange(merge) : null
      let w = this.getColW(ci)
      let h = this.getRowH(ri)

      if (nm && nm.startRow === ri && nm.startCol === ci) {
        w = this.getRangeWidth(nm.startCol, nm.endCol)
        h = this.getRangeHeight(nm.startRow, nm.endRow)
      }

      // Position cells with the same absolute-left arithmetic the header uses
      // (getZoneColLeft), instead of relying on flex layout to accumulate widths —
      // flex and a JS integer sum can drift apart by a few px over many columns,
      // desyncing the body's column borders from the header's.
      const zone = this.isColumnPinnedLeft(ci) ? 'left' : (this.isColumnPinnedRight(ci) ? 'right' : 'scroll')
      const left = this.getZoneColLeft(ci, zone)

      // Cache by dimensions+position — same (w,h,left) → same object ref → Vue 2 skips DOM style writes
      const key = w + '_' + h + '_' + left
      if (this._cellStyleCache[key]) return this._cellStyleCache[key]
      const style = { position: 'absolute', left: left + 'px', top: '0px', width: w + 'px', minWidth: w + 'px', height: h + 'px' }
      this._cellStyleCache[key] = style
      return style
    },

    // rowStyle prop — deliberately NOT merged into getCellStyle()'s return value:
    // that object is cached/shared by (w,h,left) across unrelated rows/cells (see
    // comment above), so mutating it here would leak one row's style onto every
    // other cell that happens to share the same cache key. Kept as a second,
    // uncached :style array entry instead (see template) — cheap, and correctly
    // reactive to the row's actual data instead of just its geometry.
    getRowCustomStyle(ri) {
      if (!this.rowStyle) return null
      return this.rowStyle(this._dataRaw[ri], ri) || null
    },

    getCellClasses(ri, ci) {
      const col = this.leafCols[ci]
      const active = this.isActiveCell(ri, ci)
      // Non-active selected cell: border only on edges NOT shared with another
      // selected neighbor, so a multi-cell range gets one continuous outline
      // around its outer perimeter (Excel-style) instead of each cell only
      // getting a flat background tint. Works for disjoint multi-range
      // selections too (e.g. ctrl+click rows) since it's a pure neighbor check.
      const rangeSelected = this.isSelected(ri, ci) && !active
      return {
        'eg-cell-active': active,
        'eg-cell-selected': rangeSelected,
        'eg-cell-range-top': rangeSelected && !this.isSelected(ri - 1, ci),
        'eg-cell-range-bottom': rangeSelected && !this.isSelected(ri + 1, ci),
        'eg-cell-range-left': rangeSelected && !this.isSelected(ri, ci - 1),
        'eg-cell-range-right': rangeSelected && !this.isSelected(ri, ci + 1),
        'eg-cell-fill-preview': this.isInFillPreview(ri, ci),
        'eg-cell-copy': this.isCopyHighlighted(ri, ci),
        'eg-cell-merged-hidden': this.isMergedAway(ri, ci),
        'eg-cell-select': !!(col && this.isSelectLikeCol(col)),
        'eg-cell-date': !!(col && col.type === 'date'),
        'eg-cell-checkbox': !!(col && col.type === 'checkbox'),
        'eg-cell-action': !!(col && col.type === 'action'),
        'eg-cell-readonly': !this.isCellEditable(ri, ci),
        'eg-cell-invalid': !!(this.invalidCell && this.invalidCell.row === ri && this.invalidCell.col === ci),
        'eg-cell--has-suffix': !!(col && this.hasSuffixSlot(col)),
        'eg-cell--drag-source': this.colDrag.active && ci >= this.colDrag.sourceFirstLeaf && ci < this.colDrag.sourceFirstLeaf + this.colDrag.sourceLeafCount,
        'eg-cell-align-right':  !!(col && col.align === 'right'),
        'eg-cell-align-center': !!(col && col.align === 'center')
      }
    },

    isInFillPreview(ri, ci) {
      if (!this.fillDrag.active || !this.fillDrag.sourceRange) return false
      const src = this.fillDrag.sourceRange
      const targetRow = this.fillDrag.currentRow
      const targetCol = this.fillDrag.currentCol
      if (targetRow > src.endRow) {
        return ri > src.endRow && ri <= targetRow && ci >= src.startCol && ci <= src.endCol
      }
      if (targetCol > src.endCol) {
        return ci > src.endCol && ci <= targetCol && ri >= src.startRow && ri <= src.endRow
      }
      return false
    },

    getHeaderCellStyle(cell, rowIndex, isFrozen) {
      const zone = isFrozen ? 'left' : 'scroll'
      let leftLeafIdx = cell._firstLeafFlatIndex
      if (cell.isGroup) {
        const end = leftLeafIdx + cell.colspan - 1
        for (let i = leftLeafIdx; i <= end; i++) {
          if (this.isColHidden(i)) continue
          if (isFrozen ? this.isColumnPinnedLeft(i) : this.isColumnScrollable(i)) { leftLeafIdx = i; break }
        }
      }
      const left = this.getZoneColLeft(leftLeafIdx, zone)

      let width = 0
      if (cell.isGroup) {
        const start = cell._firstLeafFlatIndex
        const end = start + cell.colspan - 1
        for (let i = start; i <= end; i++) {
          if (this.isColHidden(i)) continue
          const inZone = isFrozen ? this.isColumnPinnedLeft(i) : this.isColumnScrollable(i)
          if (!inZone) continue
          width += this.getColW(i)
        }
      } else {
        width = this.getColW(cell.column._flatIndex)
      }

      return {
        top: (this._headerRowH * rowIndex) + 'px',
        left: left + 'px',
        width: width + 'px',
        height: (this._headerRowH * cell.rowspan) + 'px'
      }
    },

    getHeaderDragTransform(cell) {
      if (!this.colDrag.active) return null
      // Read from non-reactive _dragOffsets — no Vue dependency tracking, no re-render on offset change
      let key
      if (cell.isGroup) {
        const start = cell._firstLeafFlatIndex
        const end = start + cell.colspan - 1
        for (let i = start; i <= end; i++) {
          if (!this.isColHidden(i) && this.leafCols[i]) { key = this.leafCols[i].key; break }
        }
      } else {
        key = cell.column.key
      }
      if (!key) return null
      const dx = this._dragOffsets[key]
      if (!dx) return null
      return { transform: `translateX(${dx}px)` }
    },

    getCellDragTransform(ci) {
      if (!this.colDrag.active) return null
      // Read from non-reactive _dragOffsets — no Vue dependency tracking
      const col = this.leafCols[ci]
      if (!col) return null
      const dx = this._dragOffsets[col.key]
      if (!dx) return null
      return { transform: `translateX(${dx}px)` }
    },

    // =========================================================
    // FOOTER (column totals)
    // =========================================================

    // col.totalConfig.visible (boolean) takes priority over col.showTotal when present.
    isColumnTotalVisible(col) {
      if (col.totalConfig && typeof col.totalConfig.visible === 'boolean') return col.totalConfig.visible
      return !!col.showTotal
    },

    // Columns with a visible total are implicitly numeric — computeColumnTotals()
    // only sums typeof === 'number' cells, so a value written as a string (every
    // edit path hands over a string: the built-in text <input>, pasted TSV text,
    // fill-handle/drag-move source values) would silently drop out of the sum
    // with no error. Coerce user-entered values that fully parse as a number into
    // an actual Number for these columns; anything else (blank, non-numeric text)
    // passes through unchanged so it still fails validation/renders as typed.
    _coerceCellValue(ci, value) {
      if (typeof value !== 'string') return value
      const col = this.leafCols[ci]
      if (!col || !this.isColumnTotalVisible(col)) return value
      const trimmed = value.trim()
      if (trimmed === '' || isNaN(Number(trimmed))) return value
      return Number(trimmed)
    },

    // Default value for a column on a row auto-created by pasteGrowsRows.
    _blankValueForCol(col) {
      return col.type === 'checkbox' ? false : ''
    },

    // One `Mask` instance per masked flat column index, reused across calls
    // (maska memoizes internally too, but this avoids re-parsing col.mask on
    // every keystroke/paste/fill). Invalidated whenever columns changes (see
    // the `columns` watcher, which resets `_maskCache = {}`).
    _getColMask(ci) {
      if (!this._maskCache) this._maskCache = {}
      if (this._maskCache[ci] !== undefined) return this._maskCache[ci]
      const col = this.leafCols[ci]
      const spec = col && col.mask
      let mask = null
      if (spec) {
        const options = (typeof spec === 'string' || Array.isArray(spec)) ? { mask: spec } : spec
        mask = new Mask(options)
      }
      this._maskCache[ci] = mask
      return mask
    },

    // Reformats a value through col.mask, if the column has one. Used at every
    // path that writes a value without going through the live MaskInput-driven
    // editor input (commit of a custom edit slot, paste, fill handle/double-fill)
    // — the live-typing case is handled by MaskInput itself (see startEditing).
    // Idempotent: masking an already-masked value returns it unchanged.
    _applyColMask(ci, value) {
      const mask = this._getColMask(ci)
      if (!mask || value === '' || value === null || value === undefined) return value
      if (typeof value !== 'string' && typeof value !== 'number') return value
      return mask.masked(value)
    },

    computeColumnTotals() {
      const totals = {}
      const rows = this._dataRaw || []
      this.leafCols.forEach(col => {
        if (!this.isColumnTotalVisible(col)) return
        let sum = 0
        let hasNumber = false
        for (let ri = 0; ri < rows.length; ri++) {
          const row = rows[ri]
          const v = row ? row[col.key] : undefined
          if (typeof v === 'number' && isFinite(v)) {
            sum += v
            hasNumber = true
          }
        }
        totals[col._flatIndex] = hasNumber ? Math.round(sum * 1e6) / 1e6 : null
      })
      this.columnTotals = totals
    },

    getColumnTotalDisplay(ci) {
      const col = this.leafCols[ci]
      if (!col || !this.isColumnTotalVisible(col)) return ''
      const raw = this.columnTotals[ci]
      const cfg = col.totalConfig
      if (cfg && typeof cfg.formatter === 'function') {
        return cfg.formatter(raw, this._dataRaw, col, ci)
      }
      return raw === null || raw === undefined ? '-' : raw
    },

    getFooterCellStyle(ci) {
      const zone = this.isColumnPinnedLeft(ci) ? 'left' : (this.isColumnPinnedRight(ci) ? 'right' : 'scroll')
      const left = this.getZoneColLeft(ci, zone)
      const w = this.getColW(ci)
      const style = {
        position: 'absolute',
        left: left + 'px',
        top: '0px',
        width: w + 'px',
        minWidth: w + 'px',
        height: this._footerRowH + 'px'
      }
      const col = this.leafCols[ci]
      const extra = col && col.totalConfig && col.totalConfig.style
      return extra ? { ...style, ...extra } : style
    },

    getFooterCellClass(ci) {
      const col = this.leafCols[ci]
      if (!col) return null
      const classList = col.totalConfig && col.totalConfig.classList
      const base = this.isColumnTotalVisible(col) ? 'eg-footer-cell-total' : null
      if (!base) return classList || null
      return classList ? [base, classList] : base
    },

    isCellVisible(cell, rowIndex, isFrozen) {
      if (cell.isGroup) {
        const start = cell._firstLeafFlatIndex
        const end = start + cell.colspan - 1
        for (let i = start; i <= end; i++) {
          if (this.isColHidden(i)) continue
          const inZone = isFrozen ? this.isColumnPinnedLeft(i) : this.isColumnScrollable(i)
          if (inZone) return true
        }
        return false
      }
      const ci = cell.column._flatIndex
      if (this.isColHidden(ci)) return false
      return isFrozen ? this.isColumnPinnedLeft(ci) : this.isColumnScrollable(ci)
    },

    getRowGroupBtnStyle(group) {
      const top = getRowTop(group.startIndex, this._rowH, this.rowHeights, ROW_LIST_EDGE_PAD) - this.scrollTop
      return {
        position: 'absolute',
        top: top + 'px',
        left: '2px',
        width: '16px',
        height: '16px',
        lineHeight: '16px',
        textAlign: 'center',
        fontSize: '10px',
        cursor: 'pointer',
        background: 'var(--eg-color-accent-soft, var(--eg-color-accent-soft-default))',
        border: '1px solid var(--eg-color-group-border, var(--eg-color-group-border-default))',
        borderRadius: '2px',
        zIndex: 5
      }
    },

    getColGroupBtnStyle(group) {
      const left = this.getColLeft(group.startIndex) - this.scrollLeft
      return {
        position: 'absolute',
        left: left + 'px',
        top: '2px',
        width: '16px',
        height: '16px',
        lineHeight: '16px',
        textAlign: 'center',
        fontSize: '10px',
        cursor: 'pointer',
        background: 'var(--eg-color-accent-soft, var(--eg-color-accent-soft-default))',
        border: '1px solid var(--eg-color-group-border, var(--eg-color-group-border-default))',
        borderRadius: '2px'
      }
    },

    // =========================================================
    // CELL SELECTION (3.1)
    // =========================================================
    selectCell(row, col, addToSelection = false) {
      if (row < 0 || row >= this.totalRows || col < 0 || col >= this.leafCols.length) return
      this.activeCell = { row, col }
      if (addToSelection) {
        this.selectionRanges.push(singleCellRange(row, col))
      } else {
        this.selectionRanges = [singleCellRange(row, col)]
      }
      this.emitSelectionChange()
    },

    selectRange(startRow, startCol, endRow, endCol, replace = true) {
      const range = { startRow, startCol, endRow, endCol }
      if (replace) {
        this.selectionRanges = [range]
      } else {
        this.selectionRanges.push(range)
      }
      this.emitSelectionChange()
    },

    selectRow(ri) {
      this.activeCell = { row: ri, col: 0 }
      this.selectionRanges = [{ startRow: ri, endRow: ri, startCol: 0, endCol: this.leafCols.length - 1 }]
      this.emitSelectionChange()
    },

    selectColumn(ci) {
      this.activeCell = { row: 0, col: ci }
      this.selectionRanges = [{ startRow: 0, endRow: this.totalRows - 1, startCol: ci, endCol: ci }]
      this.emitSelectionChange()
    },

    selectAll() {
      this.activeCell = { row: 0, col: 0 }
      this.selectionRanges = [{ startRow: 0, endRow: this.totalRows - 1, startCol: 0, endCol: this.leafCols.length - 1 }]
      this.emitSelectionChange()
    },

    emitSelectionChange() {
      this.$emit('selection-change', {
        activeCell: { ...this.activeCell },
        ranges: this.selectionRanges.map(r => normalizeRange(r))
      })
    },

    onCellMouseDown(e, ri, ci) {
      this.invalidCell = null
      if (this.editingCell) {
        const editCol = this.leafCols[this.editingCell.col]
        if (editCol && this._hasCustomEdit(editCol)) {
          // Custom cell/edit slots commit via their own @blur/@done handler
          // (see commitEditSlot()), and the browser fires that native blur
          // *after* this mousedown listener returns (blur is the default
          // action of the focus shift, which runs post-dispatch). Cancelling
          // here immediately would null out editingCell before the slot's
          // blur handler gets to call done(), silently discarding the typed
          // value. Defer the cleanup instead, and only run it if the slot's
          // own commit hasn't already resolved editingCell by then.
          const staleEditingCell = this.editingCell
          this.$nextTick(() => {
            if (this.editingCell === staleEditingCell) this.cancelEdit()
          })
        } else {
          this.commitEdit()
        }
      }
      this.hideContextMenu()
      this.$refs.wrapper && this.$refs.wrapper.focus()

      if (e.ctrlKey || e.metaKey) {
        if (this.selectDropdown) this.closeSelectDropdown()
        if (this.datePickerOverlay) this.closeDatePicker()
        // Ctrl+click: start new independent range
        this.activeCell = { row: ri, col: ci }
        this.mouseDownRange = { startRow: ri, startCol: ci, endRow: ri, endCol: ci }
        this.selectionRanges.push(this.mouseDownRange)
        this.isCtrlDrag = true
      } else if (e.shiftKey && this.selectionRanges.length > 0) {
        if (this.selectDropdown) this.closeSelectDropdown()
        if (this.datePickerOverlay) this.closeDatePicker()
        // Shift+click: extend primary range to this cell
        this.selectionRanges = [buildRange(this.activeCell, { row: ri, col: ci })]
      } else {
        const wasActive = this.activeCell.row === ri && this.activeCell.col === ci
        this.activeCell = { row: ri, col: ci }
        this.mouseDownRange = { startRow: ri, startCol: ci, endRow: ri, endCol: ci }
        this.selectionRanges = [this.mouseDownRange]
        this.isCtrlDrag = false

        // Open select/date dropdown on click if cell was already active (2nd click)
        const col = this.leafCols[ci]
        if (wasActive && col && this.isSelectLikeCol(col) && !this._hasCustomEdit(col) && this.isCellEditable(ri, ci)) {
          this.openSelectDropdown(ri, ci, e)
          e.preventDefault()
          this.isMouseDown = true
          this.emitSelectionChange()
          return
        }
        if (wasActive && col && col.type === 'date' && !this._hasCustomEdit(col) && this.isCellEditable(ri, ci)) {
          this.openDatePickerForActive()
          e.preventDefault()
          this.isMouseDown = true
          this.emitSelectionChange()
          return
        }
        if (this.selectDropdown) this.closeSelectDropdown()
        if (this.datePickerOverlay) this.closeDatePicker()
      }

      this.isMouseDown = true
      this.emitSelectionChange()
      e.preventDefault()
    },

    onCellMouseOver(e, ri, ci) {
      if (!this.isMouseDown) return
      if (this.fillDrag.active) return
      if (this.dragMove.active) {
        this.dragMove.targetRow = ri
        this.dragMove.targetCol = ci
        return
      }

      // Extend current drag range
      if (this.mouseDownRange) {
        this.mouseDownRange.endRow = ri
        this.mouseDownRange.endCol = ci
        this.emitSelectionChange()
      }
    },

    onCellMouseUp() {
      this.isMouseDown = false
    },

    onCellDblClick(ri, ci) {
      const col = this.leafCols[ci]
      if (!this.isCellEditable(ri, ci)) return
      if (col && this.isSelectLikeCol(col) && !this._hasCustomEdit(col)) {
        this.openSelectDropdownForActive()
        return
      }
      if (col && col.type === 'date' && !this._hasCustomEdit(col)) {
        this.openDatePickerForActive()
        return
      }
      if (col && col.type === 'checkbox') return
      if (col && col.type === 'action') return
      this.startEditing(ri, ci, null, true)
    },

    onRowHeaderMouseDown(e, ri) {
      const endCol = this.leafCols.length - 1
      const fullRow = { startRow: ri, endRow: ri, startCol: 0, endCol }

      if (e.ctrlKey || e.metaKey) {
        if (e.shiftKey && this.selectionRanges.length > 0) {
          // Ctrl+Shift: active qatordan ri gacha yangi range qo'sh
          const sr = Math.min(this.activeCell.row, ri)
          const er = Math.max(this.activeCell.row, ri)
          this.selectionRanges = [...this.selectionRanges, { startRow: sr, endRow: er, startCol: 0, endCol }]
        } else {
          // Ctrl+click: qatorni toggle qil
          const idx = this.selectionRanges.findIndex(r =>
            r.startRow === ri && r.endRow === ri && r.startCol === 0 && r.endCol === endCol
          )
          if (idx >= 0) {
            const next = this.selectionRanges.filter((_, i) => i !== idx)
            this.selectionRanges = next.length ? next : [fullRow]
          } else {
            this.activeCell = { row: ri, col: 0 }
            this.selectionRanges = [...this.selectionRanges, fullRow]
          }
        }
      } else if (e.shiftKey && this.selectionRanges.length > 0) {
        const sr = Math.min(this.activeCell.row, ri)
        const er = Math.max(this.activeCell.row, ri)
        this.selectionRanges = [{ startRow: sr, endRow: er, startCol: 0, endCol }]
      } else {
        this.activeCell = { row: ri, col: 0 }
        this.selectionRanges = [fullRow]
      }

      this.mouseDownRange = this.selectionRanges[this.selectionRanges.length - 1]
      this.isMouseDown = true
      this.emitSelectionChange()
      e.preventDefault()
    },

    onColHeaderMouseDown(e, cell) {
      // Start pending drag (activates after 5 px horizontal movement)
      // Works for both leaf and group headers
      if (this.columnDraggable && !this.internalLocked && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
        this.colDrag.pending = true
        this.colDrag.active = false
        this.colDrag.sourceFirstLeaf = cell._firstLeafFlatIndex
        this.colDrag.sourceLeafCount = cell.isGroup ? cell.colspan : 1
        this.colDrag.startX = e.clientX
        this.colDrag.startY = e.clientY
        this.colDrag.ghostLabel = cell.column.title || ''
        // Grabbed header's rect sizes the ghost and anchors the grab point if
        // the 5px threshold later activates the drag (see _startColDrag).
        this._pendingDragHeaderRect = e.currentTarget ? e.currentTarget.getBoundingClientRect() : null
      }

      if (cell.isGroup) {
        // Group header click: select all leaf columns within the group
        const startCol = cell._firstLeafFlatIndex
        const endCol = startCol + cell.colspan - 1
        this.activeCell = { row: 0, col: startCol }
        this.selectionRanges = [{ startRow: 0, endRow: this.totalRows - 1, startCol, endCol }]
        this.isMouseDown = true
        this.mouseDownRange = this.selectionRanges[0]
        this.emitSelectionChange()
        e.preventDefault()
        return
      }

      const ci = cell.column._flatIndex
      if (e.shiftKey && this.selectionRanges.length > 0) {
        const sc = Math.min(this.activeCell.col, ci)
        const ec = Math.max(this.activeCell.col, ci)
        this.selectionRanges = [{ startRow: 0, endRow: this.totalRows - 1, startCol: sc, endCol: ec }]
      } else {
        this.activeCell = { row: 0, col: ci }
        this.selectionRanges = [{ startRow: 0, endRow: this.totalRows - 1, startCol: ci, endCol: ci }]
      }
      this.isMouseDown = true
      this.mouseDownRange = this.selectionRanges[0]
      this.emitSelectionChange()
      e.preventDefault()
    },

    onColHeaderDblClick(e, cell) {
      if (cell.isGroup) return
      this.autoFitColumn(cell.column._flatIndex)
    },

    onColHeaderContextMenu(e, cell) {
      if (!cell.isGroup) {
        this._openContextMenu(e, -1, cell.column._flatIndex)
      }
    },

    onRowContextMenu(e, ri) {
      this._openContextMenu(e, ri, -1)
    },

    onCellContextMenu(e, ri, ci) {
      if (!this.isSelected(ri, ci)) {
        this.selectCell(ri, ci)
      }
      this._openContextMenu(e, ri, ci)
    },

    _openContextMenu(e, row, col) {
      this.contextMenu = { visible: true, x: e.clientX, y: e.clientY, row, col }
      this.contextMenuPositioned = false
      this.$nextTick(this._positionContextMenu)
    },

    // Flips the menu up/left if it would overflow the viewport at the raw
    // click coordinates — measured against the actual rendered size (item
    // count varies with devMode/pin/row-vs-col context, so an estimate isn't
    // reliable). Rendered off-screen (left:-9999px, see template) while
    // unpositioned so this first measurement reflects the menu's true
    // natural (single-line) width — measuring it in place near a viewport
    // edge would let the browser's own shrink-to-fit sizing wrap the text
    // to fit the cramped space, which then "sticks" even after flipping to
    // a roomier position since we only move it, we don't force a width.
    // Stays hidden (visibility, not v-if) until repositioned so there's no
    // visible jump.
    _positionContextMenu() {
      const el = this.$refs.contextMenuEl
      if (!el) return
      const rect = el.getBoundingClientRect()
      const margin = 4
      let x = this.contextMenu.x
      let y = this.contextMenu.y
      if (x + rect.width > window.innerWidth - margin) {
        x = Math.max(margin, window.innerWidth - rect.width - margin)
      }
      if (y + rect.height > window.innerHeight - margin) {
        y = Math.max(margin, window.innerHeight - rect.height - margin)
      }
      this.contextMenu.x = x
      this.contextMenu.y = y
      this.contextMenuPositioned = true
    },

    hideContextMenu() {
      this.contextMenu.visible = false
    },

    // General click-anywhere-in-the-grid dismissal for both floating menus —
    // each menu item stops propagation (@click.stop) so a click *inside*
    // either menu never reaches this handler.
    hideFloatingMenus() {
      this.hideContextMenu()
      this.hideSortMenu()
    },

    // =========================================================
    // KEYBOARD NAVIGATION (3.2)
    // =========================================================
    onKeyDown(e) {
      // Delegate keyboard navigation to the active dropdown component
      if (this.selectDropdown) {
        const comp = this.$refs.selectDropdownComp
        if (comp && comp.handleKey) comp.handleKey(e)
        return
      }

      if (this.infoModal) {
        if (e.key === 'Escape') this.closeInfoModal()
        return
      }

      if (this.editingCell) {
        // Normally handled by onEditKeyDown on the built-in <input> (which stops
        // propagation, so this branch never runs for it). Custom #cell-{key} edit
        // slots own their own input and focus it themselves — if that focus didn't
        // land (e.g. the host relies on the unreliable HTML `autofocus` attribute
        // on a freshly-inserted element), Escape falls through to here instead.
        // Without this, editingCell stays stuck and even arrow-key navigation is
        // swallowed by this same guard on every subsequent keydown.
        if (e.key === 'Escape') this.cancelEdit()
        return
      }
      const key = e.key
      // Layout-independent letter for the Ctrl/Cmd shortcuts below (z/y/a/c/x/v/d/r).
      // e.key reports the character a layout PRODUCES — on a non-Latin layout
      // (Cyrillic, etc.) the physical C key can report e.key: 'с' (Cyrillic es)
      // even with Ctrl held and the physical key/position unchanged, silently
      // breaking `key === 'c'`. e.code is the physical key position and is
      // immune to layout, so it's used here instead wherever available;
      // falls back to e.key when e.code is missing (e.g. synthetic events in
      // tests that don't set it).
      const shortcutKey = (e.code && e.code.length === 4 && e.code.slice(0, 3) === 'Key')
        ? e.code.charAt(3).toLowerCase()
        : key

      if ((e.ctrlKey || e.metaKey) && shortcutKey === 'z' && !e.shiftKey) {
        e.preventDefault()
        this.undo()
        return
      }
      if ((e.ctrlKey || e.metaKey) && (shortcutKey === 'y' || (shortcutKey === 'z' && e.shiftKey))) {
        e.preventDefault()
        this.redo()
        return
      }

      if (shortcutKey === 'a' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.selectAll()
        return
      }

      if (shortcutKey === 'c' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.copySelection()
        return
      }
      if (shortcutKey === 'x' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.cutSelection()
        return
      }
      if (shortcutKey === 'v' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.pasteAt(this.activeCell.row, this.activeCell.col)
        return
      }

      if (shortcutKey === 'd' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.fillDown()
        return
      }
      if (shortcutKey === 'r' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        this.fillRight()
        return
      }

      if (key === 'Delete' || key === 'Backspace') {
        e.preventDefault()
        this.clearSelection()
        return
      }

      if (key === 'F2') {
        e.preventDefault()
        const activeCol = this.leafCols[this.activeCell.col]
        const activeEditable = this.isCellEditable(this.activeCell.row, this.activeCell.col)
        if (activeCol && this.isSelectLikeCol(activeCol) && !this._hasCustomEdit(activeCol) && activeEditable) {
          this.openSelectDropdownForActive()
        } else if (activeCol && activeCol.type === 'date' && !this._hasCustomEdit(activeCol) && activeEditable) {
          this.openDatePickerForActive()
        } else if (activeCol && activeCol.type === 'checkbox' && activeEditable) {
          this.toggleCheckbox(this.activeCell.row, this.activeCell.col)
        } else if (activeCol && activeCol.type === 'action' && activeEditable) {
          this.triggerCellAction(this.activeCell.row, this.activeCell.col, e)
        } else if (activeEditable) {
          this.startEditing(this.activeCell.row, this.activeCell.col, null, true)
        }
        return
      }

      if (key === ' ') {
        const activeCol = this.leafCols[this.activeCell.col]
        if (activeCol && activeCol.type === 'checkbox') {
          e.preventDefault()
          this.toggleCheckbox(this.activeCell.row, this.activeCell.col)
          return
        }
        if (activeCol && activeCol.type === 'action') {
          e.preventDefault()
          this.triggerCellAction(this.activeCell.row, this.activeCell.col, e)
          return
        }
      }

      if (key === 'Escape') {
        this.clipboardRange = null
        this.clipboardMatrix = null
        this.clipboardMode = null
        return
      }

      if (key === 'Tab') {
        e.preventDefault()
        this.moveActive(0, e.shiftKey ? -1 : 1, e)
        return
      }
      if (key === 'Enter') {
        e.preventDefault()
        this.moveActive(e.shiftKey ? -1 : 1, 0, e)
        return
      }

      const arrows = { ArrowUp: [-1,0], ArrowDown: [1,0], ArrowLeft: [0,-1], ArrowRight: [0,1] }
      if (arrows[key]) {
        e.preventDefault()
        const [dr, dc] = arrows[key]
        if (e.shiftKey) {
          this.extendSelection(dr, dc)
        } else {
          this.moveActive(dr, dc, e)
        }
        return
      }

      if (key === 'Home') {
        e.preventDefault()
        if (e.ctrlKey) {
          this.selectCell(0, 0)
        } else {
          this.selectCell(this.activeCell.row, 0)
        }
        return
      }
      if (key === 'End') {
        e.preventDefault()
        if (e.ctrlKey) {
          this.selectCell(this.totalRows - 1, this.leafCols.length - 1)
        } else {
          this.selectCell(this.activeCell.row, this.leafCols.length - 1)
        }
        return
      }
      if (key === 'PageUp') {
        e.preventDefault()
        if (e.shiftKey) {
          this.extendSelection(-this._pageRowSpan(), 0)
        } else {
          this.moveActive(-this._pageRowSpan(), 0, e)
        }
        return
      }
      if (key === 'PageDown') {
        e.preventDefault()
        if (e.shiftKey) {
          this.extendSelection(this._pageRowSpan(), 0)
        } else {
          this.moveActive(this._pageRowSpan(), 0, e)
        }
        return
      }
    },

    onKeyPress(e) {
      if (this.editingCell) return
      if (this.selectDropdown) return
      if (this.datePickerOverlay) return
      if (e.ctrlKey || e.metaKey || e.altKey) return
      if (e.key && e.key.length === 1) {
        const activeCol = this.leafCols[this.activeCell.col]
        const activeEditable = this.isCellEditable(this.activeCell.row, this.activeCell.col)
        if (activeCol && this.isSelectLikeCol(activeCol) && !this._hasCustomEdit(activeCol)) {
          e.preventDefault()
          if (activeEditable) this.openSelectDropdownForActive()
          return
        }
        if (activeCol && activeCol.type === 'date' && !this._hasCustomEdit(activeCol)) {
          e.preventDefault()
          if (activeEditable) this.openDatePickerForActive()
          return
        }
        if (activeCol && activeCol.type === 'checkbox') {
          e.preventDefault()
          return
        }
        if (activeCol && activeCol.type === 'action') {
          e.preventDefault()
          return
        }
        // Without this, the browser's own native "insert this character" action
        // (queued for whatever element ends up focused) still fires after
        // startEditing()'s $nextTick focuses the freshly-created edit <input> —
        // which is already seeded with this same character via editValue — so
        // the char gets inserted a second time (e.g. "1" -> "11").
        e.preventDefault()
        this.startEditing(this.activeCell.row, this.activeCell.col, e.key, false)
      }
    },

    onGlobalKeyDown(e) {
      if (e.key === 'Escape' && (this.colDrag.active || this.colDrag.pending)) {
        this._resetColDrag(true)
        e.preventDefault()
      }
    },

    // Shift+Arrow / Shift+PageUp/PageDown: extend or shrink the selection
    // relative to the FIXED anchor (activeCell) — not just always growing in
    // the pressed direction. The "far" corner is whichever end of the current
    // (normalized) range isn't the anchor; per axis, _extendAxis grows it
    // further out while it's already on the pressed side, or shrinks it back
    // toward the anchor (never past it in one step) while it's on the
    // opposite side — matching Excel/Sheets. Only the axis(es) with a
    // non-zero delta are touched, so a pure vertical extend preserves the
    // current column range untouched, and vice versa.
    extendSelection(dr, dc) {
      const anchor = this.activeCell
      const pr = this.primaryRange || singleCellRange(anchor.row, anchor.col)
      const nm = normalizeRange(pr)
      let farRow = nm.startRow === anchor.row ? nm.endRow : nm.startRow
      let farCol = nm.startCol === anchor.col ? nm.endCol : nm.startCol
      if (dr !== 0) farRow = this._extendAxis(anchor.row, farRow, dr, this.totalRows - 1)
      if (dc !== 0) farCol = this._extendAxis(anchor.col, farCol, dc, this.leafCols.length - 1)
      this.selectionRanges = [buildRange(anchor, { row: farRow, col: farCol })]
      this.emitSelectionChange()
      // Unlike moveActive(), this doesn't move the active cell — but the newly
      // extended (far) corner of the range must still be scrolled into view,
      // exactly like moveActive() does for the active cell itself.
      this.scrollToCell(farRow, farCol)
    },

    _extendAxis(anchorIdx, farIdx, delta, maxIdx) {
      if (delta > 0) {
        return farIdx >= anchorIdx ? Math.min(maxIdx, farIdx + delta) : Math.min(anchorIdx, farIdx + delta)
      }
      return farIdx <= anchorIdx ? Math.max(0, farIdx + delta) : Math.max(anchorIdx, farIdx + delta)
    },

    moveActive(dr, dc, e) {
      let row = this.activeCell.row + dr
      let col = this.activeCell.col + dc

      // Tab: wrap around rows
      if (e && e.key === 'Tab') {
        if (col >= this.leafCols.length) { col = 0; row++ }
        if (col < 0) { col = this.leafCols.length - 1; row-- }
      }

      row = Math.max(0, Math.min(this.totalRows - 1, row))
      col = Math.max(0, Math.min(this.leafCols.length - 1, col))

      // Skip hidden cols
      while (this.isColHidden(col) && col > 0 && col < this.leafCols.length - 1) {
        col += dc >= 0 ? 1 : -1
      }
      // Skip hidden rows
      while (this.isRowHidden(row) && row > 0 && row < this.totalRows - 1) {
        row += dr >= 0 ? 1 : -1
      }

      // Handle merge navigation
      const resolved = resolveMergeAnchor(row, col, this.internalMerges)
      row = resolved.row
      col = resolved.col

      this.activeCell = { row, col }
      this.selectionRanges = [singleCellRange(row, col)]
      this.emitSelectionChange()
      this.scrollToCell(row, col)
    },

    scrollToCell(ri, ci) {
      const scrollBody = this.$refs.scrollBody
      if (!scrollBody) return
      const rowTop = getRowTop(ri, this._rowH, this.rowHeights, ROW_LIST_EDGE_PAD)
      const rowBottom = rowTop + this.getRowH(ri)

      if (rowTop < scrollBody.scrollTop) scrollBody.scrollTop = rowTop
      if (rowBottom > scrollBody.scrollTop + scrollBody.clientHeight) {
        scrollBody.scrollTop = rowBottom - scrollBody.clientHeight
      }

      // Pinned columns are sticky — always horizontally in view, nothing to do.
      if (!this.isColumnScrollable(ci)) return
      const zoneLeft = this.getZoneColLeft(ci, 'scroll')
      const zoneRight = zoneLeft + this.getColW(ci)
      // A scrollable cell only counts as visible inside the window the sticky
      // pinned zones don't cover — without subtracting them, a cell could sit
      // fully underneath a pinned zone yet be treated as already in view.
      const visibleW = scrollBody.clientWidth - this.getFrozenWidth() - (this.hasPinnedRight ? this.pinnedRightWidth : 0)
      if (zoneLeft < scrollBody.scrollLeft) scrollBody.scrollLeft = zoneLeft
      if (zoneRight > scrollBody.scrollLeft + visibleW) {
        scrollBody.scrollLeft = zoneRight - visibleW
      }
    },

    // =========================================================
    // EDITING (used by 3.1 + 3.2)
    // =========================================================
    startEditing(ri, ci, initialChar = null, keepValue = false) {
      if (this.internalLocked) return
      const col = this.leafCols[ci]
      if (!col || !this.isCellEditable(ri, ci)) return
      if (ri < 0 || ri >= this.totalRows) return
      if (!this._hasCustomEdit(col)) {
        if (this.isSelectLikeCol(col)) { this.openSelectDropdownForActive(); return }
        if (col.type === 'date') { this.openDatePickerForActive(); return }
        if (col.type === 'checkbox') return
        if (col.type === 'action') return
      }

      this.invalidCell = null
      this.editingCell = { row: ri, col: ci }
      if (initialChar !== null) {
        this.editValue = initialChar
      } else if (keepValue) {
        this.editValue = String(this.getCellValue(ri, ci) || '')
      } else {
        this.editValue = ''
      }
      this.editOriginalValue = String(this.getCellValue(ri, ci) || '')

      this.$nextTick(() => {
        const inputs = this.$refs.editInput
        if (inputs) {
          const input = Array.isArray(inputs) ? inputs[0] : inputs
          if (input) {
            // col.mask: MaskInput owns the element's live formatting/caret while
            // typing and re-dispatches a corrected native 'input' event after
            // every keystroke, which the existing v-model="editValue" binding
            // picks up normally — no separate sync code needed. It also masks
            // whatever value is already in the input (seeded above) on attach.
            if (this._maskInput) { this._maskInput.destroy(); this._maskInput = null }
            if (col.mask) {
              const options = (typeof col.mask === 'string' || Array.isArray(col.mask)) ? { mask: col.mask } : col.mask
              this._maskInput = new MaskInput(input, options)
            }
            input.focus()
            if (keepValue) {
              input.setSelectionRange(input.value.length, input.value.length)
            }
          }
        }
      })
    },

    commitEdit() {
      if (!this.editingCell) return
      const { row, col } = this.editingCell
      const colDef = this.leafCols[col]
      if (this._maskInput) { this._maskInput.destroy(); this._maskInput = null }
      if (!colDef) { this.editingCell = null; return }

      // editValue is already masked live by MaskInput (see startEditing) — this
      // is a defensive final pass, cheap/idempotent, and covers any commit that
      // skipped the live-typing path (e.g. programmatic editValue changes).
      const value = this._coerceCellValue(col, this._applyColMask(col, this.editValue))
      if (!this.isCellValueValid(row, col, value)) {
        this._showInvalidCell(row, col, value)
        this.editingCell = null
        this.$refs.wrapper && this.$refs.wrapper.focus()
        return
      }

      this.invalidCell = null
      const oldData = this.data
      const newData = oldData.slice()
      newData[row] = { ...oldData[row], [colDef.key]: value }
      this._emitDataChange(oldData, newData)
      this._flushOnInput(row, col, value, newData[row])
      this.editingCell = null
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    cancelEdit() {
      clearTimeout(this._onInputTimer)
      if (this._maskInput) { this._maskInput.destroy(); this._maskInput = null }
      this.editingCell = null
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    // Fires while the user is actively typing in the plain-text edit input —
    // debounced (col.debounceMs, default 400ms) so col.onInput isn't called
    // on every keystroke. `row` is the pre-edit row (not yet committed);
    // `value` is the live in-progress text.
    onEditInput(e) {
      if (!this.editingCell) return
      const { row, col } = this.editingCell
      this._scheduleOnInput(row, col, e.target.value)
    },

    _scheduleOnInput(ri, ci, value) {
      const col = this.leafCols[ci]
      if (!col || typeof col.onInput !== 'function') return
      clearTimeout(this._onInputTimer)
      this._onInputPending = true
      const delay = typeof col.debounceMs === 'number' ? col.debounceMs : 400
      this._onInputTimer = setTimeout(() => {
        this._onInputPending = false
        const row = this._dataRaw[ri]
        if (row) {
          this._lastFiredOnInput = { ri, ci, value }
          col.onInput(value, row, ri, col)
          // col.onInput is a common place for a host to derive/write another
          // cell's value on the same (already-reactive) row object — but cell
          // rendering reads through the non-reactive _dataRaw (see created()),
          // so an in-place mutation like that is otherwise invisible until the
          // next time `data` itself gets a new reference (e.g. on commit).
          this.$forceUpdate()
        }
      }, delay)
    },

    // Cancels any pending debounced call and fires col.onInput immediately —
    // used at commit points (Enter/blur, date pick, checkbox toggle) so a
    // still-in-flight debounce timer never drops the final value. If nothing
    // is pending (the debounce already fired naturally with this exact
    // value), skip re-firing — commitEdit() calls this unconditionally, so
    // without this guard a slow typist would get onInput called twice for
    // the same settled value.
    _flushOnInput(ri, ci, value, row) {
      const col = this.leafCols[ci]
      if (!col || typeof col.onInput !== 'function') return
      const wasPending = this._onInputPending
      clearTimeout(this._onInputTimer)
      this._onInputPending = false
      const last = this._lastFiredOnInput
      if (!wasPending && last && last.ri === ri && last.ci === ci && last.value === value) return
      this._lastFiredOnInput = { ri, ci, value }
      col.onInput(value, row || this._dataRaw[ri], ri, col)
      // See _scheduleOnInput — a same-tick mutation to another cell on `row`
      // needs its own forceUpdate, since it happens after the data-watcher's
      // own forceUpdate (triggered by the commit that led here) already ran.
      this.$forceUpdate()
    },

    hasCellSlot(col) {
      return !!(col && col.key && this.$scopedSlots && this.$scopedSlots['cell-' + col.key])
    },
    hasLegacyEditSlot(col) {
      return !!(col && col.key && this.$scopedSlots && this.$scopedSlots['edit-' + col.key])
    },
    hasPrefixSlot(col) {
      return !!(col && col.key && this.$scopedSlots && this.$scopedSlots['prefix-' + col.key])
    },
    hasSuffixSlot(col) {
      return !!(col && col.key && this.$scopedSlots && this.$scopedSlots['suffix-' + col.key])
    },
    _hasCustomEdit(col) {
      // For select/treeSelect/date: cell-{key} slot only customizes display; picker still opens normally
      if (col.type === 'select' || col.type === 'treeSelect' || col.type === 'date') {
        return this.hasLegacyEditSlot(col)
      }
      return this.hasCellSlot(col) || this.hasLegacyEditSlot(col)
    },

    commitEditSlot(value) {
      if (!this.editingCell) return
      const { row, col } = this.editingCell
      const colDef = this.leafCols[col]
      if (this._maskInput) { this._maskInput.destroy(); this._maskInput = null }
      if (!colDef) { this.editingCell = null; return }
      value = this._coerceCellValue(col, this._applyColMask(col, value))
      if (!this.isCellValueValid(row, col, value)) {
        this._showInvalidCell(row, col, value)
        this.editingCell = null
        this.$refs.wrapper && this.$refs.wrapper.focus()
        return
      }
      this.invalidCell = null
      const oldData = this.data
      const newData = oldData.slice()
      newData[row] = { ...oldData[row], [colDef.key]: value }
      this._emitDataChange(oldData, newData)
      this._flushOnInput(row, col, value, newData[row])
      this.editingCell = null
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    // =========================================================
    // CHECKBOX CELLS
    // =========================================================

    isCheckboxChecked(ri, ci) {
      const v = this.getCellValue(ri, ci)
      if (v === true || v === 1) return true
      if (typeof v === 'string') return ['true', '1'].includes(v.trim().toLowerCase())
      return false
    },

    setCheckboxValue(ri, ci, value) {
      if (this.internalLocked) return
      const col = this.leafCols[ci]
      if (!col || !this.isCellEditable(ri, ci)) return
      if (!this.isCellValueValid(ri, ci, value)) {
        this._showInvalidCell(ri, ci, value)
        return
      }
      this.invalidCell = null
      const oldData = this.data
      const newData = oldData.slice()
      newData[ri] = { ...oldData[ri], [col.key]: value }
      this._emitDataChange(oldData, newData)
      this._flushOnInput(ri, ci, value, newData[ri])
    },

    toggleCheckbox(ri, ci) {
      this.setCheckboxValue(ri, ci, !this.isCheckboxChecked(ri, ci))
    },

    // =========================================================
    // ACTION CELLS (col.type === 'action')
    // =========================================================

    // Dynamic v-on argument expressions can't contain quotes/spaces in Vue 2.6
    // templates, so the 'click' fallback is resolved here instead of inline.
    actionHandlerEvent(col) {
      return (col && col.handlerType) || 'click'
    },

    triggerCellAction(ri, ci, e) {
      if (this.internalLocked) return
      const col = this.leafCols[ci]
      if (!col || col.type !== 'action' || typeof col.handler !== 'function') return
      if (!this.isCellEditable(ri, ci)) return
      col.handler(this._dataRaw[ri], ri, col, ci, e)
    },

    // =========================================================
    // CELL EDITABILITY (3.17)
    // =========================================================

    isCellEditable(ri, ci) {
      const col = this.leafCols[ci]
      if (!col) return false
      const row = this._dataRaw[ri] || {}
      if (typeof this.cellEditable === 'function') return !!this.cellEditable(row, ri, col, ci)
      if (typeof col.editable === 'function') return !!col.editable(row, ri)
      if (col.editable === false) return false
      return true
    },

    // =========================================================
    // CELL VALUE VALIDATION (cellValidator)
    // =========================================================

    isCellValueValid(ri, ci, value) {
      if (typeof this.cellValidator !== 'function') return true
      const col = this.leafCols[ci]
      if (!col) return true
      const row = this._dataRaw[ri] || {}
      return !!this.cellValidator(value, row, ri, col, ci)
    },

    _resolveValidationMessage(ri, ci, value) {
      const col = this.leafCols[ci]
      const row = this._dataRaw[ri] || {}
      if (typeof this.cellValidationMessage === 'function') return this.cellValidationMessage(value, row, ri, col, ci)
      if (typeof this.cellValidationMessage === 'string' && this.cellValidationMessage) return this.cellValidationMessage
      return this.t.invalidValue
    },

    // Find the on-screen rect of the cell currently being committed — the edit
    // input if still mounted (commitEdit, before editingCell is cleared), else
    // the active cell element (checkbox/select commits, which never enter edit mode).
    _invalidCellRect() {
      const inputs = this.$refs.editInput
      const input = Array.isArray(inputs) ? inputs[0] : inputs
      if (input) return input.getBoundingClientRect()
      const el = this.$el ? this.$el.querySelector('.eg-cell-active') : null
      return el ? el.getBoundingClientRect() : null
    },

    _showInvalidCell(ri, ci, value) {
      const message = this._resolveValidationMessage(ri, ci, value)
      this.invalidCell = { row: ri, col: ci, message, rect: this._invalidCellRect() }
      this.$emit('cell-validation-error', { row: ri, col: ci, value, message })
    },

    // Resolve+emit messages for a batch of rejected { row, col, value } entries
    // from a bulk write (paste / fill / clear). blocked=true means the whole
    // operation was aborted (strictBulkValidation); false means these cells
    // were skipped but the rest of the write still applied.
    _emitBulkValidationError(skipped, blocked) {
      const cells = skipped.map(c => ({
        row: c.row, col: c.col, value: c.value,
        message: this._resolveValidationMessage(c.row, c.col, c.value)
      }))
      this.$emit('bulk-validation-error', { blocked, cells })
    },

    // =========================================================
    // SELECT DROPDOWN (3.16) + TREE SELECT (3.22)
    // =========================================================

    isSelectLikeCol(col) {
      return !!(col && (col.type === 'select' || col.type === 'treeSelect'))
    },

    treeOptionKeys(col) {
      return {
        valueKey: col.optionValueKey || 'value',
        labelKey: col.optionLabelKey || 'label',
        childrenKey: col.optionChildrenKey || 'children'
      }
    },

    // Returns { [colKey]: 'left'|'right' } for columns that declare col.pin.
    _colPinMap(cols) {
      const map = {}
      ;(cols || []).forEach(col => {
        if (col.pin === 'left' || col.pin === 'right') map[col.key] = col.pin
      })
      return map
    },

    _treeFindLabel(nodes, keys, value) {
      for (const node of (nodes || [])) {
        // A malformed col.options (e.g. a host array with a hole/undefined entry,
        // often from an unguarded Array.prototype.find() result spread back in)
        // shouldn't crash the whole grid's render — skip it like a missing option.
        if (!node) continue
        if (String(node[keys.valueKey]) === value) {
          return node[keys.labelKey] != null ? node[keys.labelKey] : String(node[keys.valueKey])
        }
        const found = this._treeFindLabel(node[keys.childrenKey], keys, value)
        if (found != null) return found
      }
      return null
    },

    // col.options may be a static array OR a function (row, rowIndex, column, colIndex) => array,
    // letting hosts return a different option list per cell.
    hasOptionsSource(col) {
      return !!(col && (Array.isArray(col.options) || typeof col.options === 'function'))
    },

    resolveOptionsArray(col, ri, ci) {
      if (!col) return []
      if (typeof col.options === 'function') {
        const row = ri != null ? (this._dataRaw[ri] || {}) : {}
        const result = col.options(row, ri, col, ci != null ? ci : col._flatIndex)
        return Array.isArray(result) ? result : []
      }
      return Array.isArray(col.options) ? col.options : []
    },

    colOptions(ci, ri) {
      const col = this.leafCols[ci]
      const raw = this.resolveOptionsArray(col, ri, ci)
      if (!raw.length) return []
      // optionValueKey/optionLabelKey apply to type:'select' the same way they
      // already do for type:'treeSelect' — same config, same defaults.
      const { valueKey, labelKey } = this.treeOptionKeys(col)
      return raw.map(o =>
        typeof o === 'string' ? { value: o, label: o } : { value: o[valueKey], label: o[labelKey] != null ? o[labelKey] : String(o[valueKey]), color: o.color }
      )
    },

    getSelectLabel(ci, value, ri) {
      const col = this.leafCols[ci]
      const v = value == null ? '' : String(value)
      if (col && col.type === 'treeSelect') {
        const raw = this.resolveOptionsArray(col, ri, ci)
        if (!raw.length) return v
        const found = this._treeFindLabel(raw, this.treeOptionKeys(col), v)
        return found != null ? found : v
      }
      const opts = this.colOptions(ci, ri)
      if (!opts.length) return v
      const found = opts.find(o => String(o.value) === v)
      return found ? found.label : v
    },

    _buildSelectDropdownState(ri, ci, col, currentValue, rect) {
      const rectObj = { top: rect.top, bottom: rect.bottom, left: rect.left, width: rect.width }
      return {
        row: ri, col: ci,
        tree: col.type === 'treeSelect',
        // valueKey/labelKey apply to both select and treeSelect (childrenKey
        // only matters for the tree dropdown, harmlessly unused otherwise).
        keys: this.treeOptionKeys(col),
        rawOptions: this.resolveOptionsArray(col, ri, ci),
        currentValue,
        rect: rectObj,
        // Defaults to on (opt out with enableSearch: false) — same convention
        // as clearable below.
        enableSearch: col.enableSearch !== false,
        clearable: col.clearable !== false
      }
    },

    openSelectDropdown(ri, ci, e) {
      const col = this.leafCols[ci]
      if (!this.hasOptionsSource(col)) return
      const el = e.currentTarget
      const rect = el.getBoundingClientRect()
      const currentValue = String(this.getCellValue(ri, ci) != null ? this.getCellValue(ri, ci) : '')
      this.selectDropdown = this._buildSelectDropdownState(ri, ci, col, currentValue, rect)
    },

    openSelectDropdownForActive() {
      const { row, col } = this.activeCell
      const colDef = this.leafCols[col]
      if (!this.hasOptionsSource(colDef)) return
      this.$nextTick(() => {
        const el = this.$el ? this.$el.querySelector('.eg-cell-active') : null
        if (!el) return
        const rect = el.getBoundingClientRect()
        const currentValue = String(this.getCellValue(row, col) != null ? this.getCellValue(row, col) : '')
        this.selectDropdown = this._buildSelectDropdownState(row, col, colDef, currentValue, rect)
      })
    },

    onComponentSelect({ value, label }) {
      if (this.internalLocked) { this.closeSelectDropdown(); return }
      if (!this.selectDropdown) return
      const { row, col } = this.selectDropdown
      const colDef = this.leafCols[col]
      if (colDef) {
        // Clearing (value === '') always goes through, same as onDatePick()'s
        // empty-string bypass — "no selection" is a valid state regardless of
        // what cellValidator requires of a real picked value.
        if (value !== '' && !this.isCellValueValid(row, col, value)) {
          this._showInvalidCell(row, col, value)
          this.closeSelectDropdown()
          return
        }
        this.invalidCell = null
        const oldData = this.data
        const newData = oldData.slice()
        newData[row] = { ...oldData[row], [colDef.key]: value }
        this._emitDataChange(oldData, newData)
        if (typeof colDef.onSelect === 'function') {
          // Deferred the same way as _fireCellCallbacksForRange (paste/fill/drag-move) —
          // a host watching the emitted data (e.g. mirroring it into its own
          // store) needs that watcher to run first, or onSelect reads stale state.
          this.$nextTick(() => {
            colDef.onSelect({ value, label }, newData[row], row, colDef)
            // See _scheduleOnInput — picks up any same-tick mutation the callback
            // made to another cell on this (already-reactive) row object.
            this.$forceUpdate()
          })
        }
      }
      this.closeSelectDropdown()
    },

    // Always returns focus to the grid wrapper — the dropdown (especially with
    // enableSearch) can hold real DOM focus on its own search input, and every
    // close path (Escape, outside click, picking a value) must hand focus back
    // or keyboard navigation on the grid goes dead until the user clicks a cell.
    closeSelectDropdown() {
      this.selectDropdown = null
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    // =========================================================
    // DATE PICKER
    // =========================================================

    getCellDisplayValue(ci, val, ri) {
      const col = this.leafCols[ci]
      if (!col) return val == null ? '' : val
      if (typeof col.formatter === 'function') {
        const out = col.formatter(val, this._dataRaw[ri], ri, col, ci)
        return out == null ? '' : out
      }
      if (this.isSelectLikeCol(col)) return this.getSelectLabel(ci, val, ri)
      if (col.type === 'date') {
        const d = parseDateValue(val)
        return d ? formatDate(d, col.format || DEFAULT_DATE_FORMAT) : (val == null ? '' : val)
      }
      return val == null ? '' : val
    },

    // =========================================================
    // FILTER ROW
    // =========================================================

    // Which control the filter cell renders for this column.
    // 'none' cells still render (empty) so column alignment stays intact.
    filterControlType(col) {
      if (!col || col.filterable === false || col.type === 'action') return 'none'
      if (col.type === 'checkbox') return 'checkbox'
      // Function-based options can't be resolved into a fixed list outside a
      // specific row, so those columns fall back to the text control.
      if ((col.type === 'select' || col.type === 'treeSelect') && Array.isArray(col.options)) return 'select'
      return 'text'
    },

    // Flat { value, label } list for a select-control filter cell. treeSelect
    // options are recursively flattened, each depth indented for readability.
    filterOptionsFor(col) {
      if (!col) return []
      if (col.type === 'treeSelect') {
        const raw = this.resolveOptionsArray(col, null, col._flatIndex)
        const out = []
        this._flattenTreeOptionsForFilter(raw, this.treeOptionKeys(col), 0, out)
        return out
      }
      return this.colOptions(col._flatIndex, null)
    },

    _flattenTreeOptionsForFilter(nodes, keys, depth, out) {
      for (const node of (nodes || [])) {
        const value = node[keys.valueKey]
        const label = node[keys.labelKey] != null ? node[keys.labelKey] : String(value)
        out.push({ value: String(value), label: '  '.repeat(depth) + label })
        this._flattenTreeOptionsForFilter(node[keys.childrenKey], keys, depth + 1, out)
      }
    },

    getFilterCellStyle(ci) {
      const zone = this.isColumnPinnedLeft(ci) ? 'left' : (this.isColumnPinnedRight(ci) ? 'right' : 'scroll')
      const left = this.getZoneColLeft(ci, zone)
      const w = this.getColW(ci)
      return {
        position: 'absolute',
        left: left + 'px',
        top: (this._headerRowH * this.headerDepth) + 'px',
        width: w + 'px',
        height: this._filterRowH + 'px',
        boxSizing: 'border-box'
      }
    },

    setFilter(key, value) {
      if (!this.leafCols.some(c => c.key === key)) return
      const next = { ...this.internalFilters }
      if (value === '' || value === null || value === undefined) {
        delete next[key]
      } else {
        next[key] = value
      }
      this.internalFilters = next
      this.$emit('update:filters', { ...next })
      this.$emit('filter-change', { key, value, filters: { ...next } })
    },

    clearFilters() {
      if (!Object.keys(this.internalFilters).length) return
      this.internalFilters = {}
      // A deliberate, infrequent action (unlike typing) — recompute immediately
      // rather than waiting out the debounce, and drop any timer already pending.
      clearTimeout(this._filterRecomputeTimer)
      this._recomputeRowFilters()
      this.$emit('update:filters', {})
      this.$emit('filter-change', { key: null, value: null, filters: {} })
    },

    // Debounced — recomputing filteredRowIndices scans every row, so typing
    // in the text filter shouldn't trigger it on every keystroke.
    _scheduleFilterRecompute() {
      clearTimeout(this._filterRecomputeTimer)
      this._filterRecomputeTimer = setTimeout(() => { this._recomputeRowFilters() }, 150)
    },

    _activeFilterCols() {
      const cols = []
      for (const col of this.leafCols) {
        if (this.filterControlType(col) === 'none') continue
        const v = this.internalFilters[col.key]
        if (v === undefined || v === null || v === '') continue
        cols.push(col)
      }
      return cols
    },

    _cellMatchesFilter(row, ri, col) {
      const ci = col._flatIndex
      const filterValue = this.internalFilters[col.key]
      if (typeof col.filterFn === 'function') {
        return !!col.filterFn(this.getCellValue(ri, ci), filterValue, row, ri, col)
      }
      const kind = this.filterControlType(col)
      if (kind === 'checkbox') {
        const checked = this.isCheckboxChecked(ri, ci)
        return filterValue === 'true' ? checked : !checked
      }
      if (kind === 'select') {
        const raw = this.getCellValue(ri, ci)
        return String(raw == null ? '' : raw) === String(filterValue)
      }
      const display = this.getCellDisplayValue(ci, this.getCellValue(ri, ci), ri)
      return String(display == null ? '' : display).toLowerCase().indexOf(String(filterValue).toLowerCase()) !== -1
    },

    _recomputeRowFilters() {
      // Can be reached (via the `columns`/`filterRow` watchers) during initWatch(),
      // before created() has set up _dataRaw — getCellValue() depends on it. The
      // `data` watcher's own immediate handler sets _dataRaw first, then always
      // calls this again, so the initial mount still ends up correct.
      if (!this._dataRaw) return
      if (!this.filterRow) {
        if (this.filteredRowIndices.length) this.filteredRowIndices = []
        return
      }
      const activeCols = this._activeFilterCols()
      if (!activeCols.length) {
        if (this.filteredRowIndices.length) this.filteredRowIndices = []
        return
      }
      const rows = this.data
      const out = []
      for (let ri = 0; ri < rows.length; ri++) {
        const row = rows[ri]
        let matches = true
        for (const col of activeCols) {
          if (!this._cellMatchesFilter(row, ri, col)) { matches = false; break }
        }
        if (!matches) out.push(ri)
      }
      this.filteredRowIndices = out
    },

    // =========================================================
    // COLUMN SORTING
    // =========================================================

    isColSortable(col) {
      return !!(this.sortable && col && col.sortable !== false && col.type !== 'action')
    },

    sortIconClass(col) {
      const active = !!(this.internalSort && this.internalSort.key === col.key)
      return active ? 'eg-icon-sort-menu eg-sort-icon-active' : 'eg-icon-sort-menu'
    },

    sortIconTitle() {
      return this.t.sortMenuTooltip
    },

    // Opens the sort popup menu (A → Z / Z → A / Cancel) anchored to the
    // clicked header icon. Replaces the old direct cycle-on-click behavior.
    openSortMenu(e, col) {
      if (this.internalLocked) return
      this.sortMenu = { visible: true, x: e.clientX, y: e.clientY, key: col.key }
      this.sortMenuPositioned = false
      this.$nextTick(this._positionSortMenu)
    },

    // Same flip-to-fit reasoning as _positionContextMenu().
    _positionSortMenu() {
      const el = this.$refs.sortMenuEl
      if (!el) return
      const rect = el.getBoundingClientRect()
      const margin = 4
      let x = this.sortMenu.x
      let y = this.sortMenu.y
      if (x + rect.width > window.innerWidth - margin) {
        x = Math.max(margin, window.innerWidth - rect.width - margin)
      }
      if (y + rect.height > window.innerHeight - margin) {
        y = Math.max(margin, window.innerHeight - rect.height - margin)
      }
      this.sortMenu.x = x
      this.sortMenu.y = y
      this.sortMenuPositioned = true
    },

    hideSortMenu() {
      this.sortMenu.visible = false
    },

    // Marks whichever direction is currently applied to the menu's own
    // column so the popup shows which option is active (checkmark, see CSS).
    isSortMenuOptionActive(direction) {
      return !!(
        this.internalSort &&
        this.sortMenu.key &&
        this.internalSort.key === this.sortMenu.key &&
        this.internalSort.direction === direction
      )
    },

    sortMenuPickAsc() {
      this.setSort(this.sortMenu.key, 'asc')
      this.hideSortMenu()
    },

    sortMenuPickDesc() {
      this.setSort(this.sortMenu.key, 'desc')
      this.hideSortMenu()
    },

    sortMenuPickClear() {
      this.clearSort()
      this.hideSortMenu()
    },

    // Cycles a column through none → asc → desc → none. Kept as a public
    // method for programmatic/custom #header-{key} slot use — the built-in
    // header icon now opens the popup menu (openSortMenu) instead.
    toggleSort(key) {
      if (this.internalLocked) return
      const current = this.internalSort
      if (!current || current.key !== key) { this.setSort(key, 'asc'); return }
      if (current.direction === 'asc') { this.setSort(key, 'desc'); return }
      this.clearSort()
    },

    setSort(key, direction) {
      if (direction !== 'asc' && direction !== 'desc') { this.clearSort(); return }
      this.sortByColumn(key, direction)
    },

    // Clicking a third time (or calling this directly) clears the sort
    // indicator AND restores the row order from immediately before the
    // first sort of this session (see _preSortData in sortByColumn()) —
    // switching columns or direction mid-session doesn't move that
    // reference point, so this always lands back on the true original
    // order. Emitted as a normal data change (_emitDataChange), so it's
    // itself undoable/redoable like any other edit.
    clearSort() {
      if (!this.internalSort) return
      this.internalSort = null
      const oldData = this.data
      const restored = this._preSortData
      this._preSortData = null
      // Row count mismatch means rows were added/removed since the sort —
      // the snapshot no longer lines up with the current data, so skip the
      // restore rather than silently drop/duplicate rows (indicator still
      // clears either way).
      if (restored && restored.length === oldData.length) {
        this._emitDataChange(oldData, restored)
      }
      this.$emit('update:sort', null)
      this.$emit('sort-change', { key: null, direction: null })
    },

    sortByColumn(key, direction) {
      if (this.internalLocked) return
      // Merges and row groups are anchored to row *position* — a reorder
      // would silently invalidate them, so sorting is blocked while either
      // exists (same "blocked while locked" no-op convention as elsewhere).
      if (this.internalMerges.length || this.rowGroups.length) return
      const col = this.leafCols.find(c => c.key === key)
      if (!this.isColSortable(col)) return

      const oldData = this.data
      // Remember the order from before the *first* sort of this session —
      // re-sorting the same or a different column (asc<->desc, or switching
      // columns) without clearing first must not move this reference point,
      // so clearSort() always lands back on the true original order.
      if (!this.internalSort) this._preSortData = oldData
      const pairs = oldData.map((row, ri) => ({ row, ri }))
      pairs.sort((a, b) => this._compareForSort(a.row, a.ri, b.row, b.ri, col, direction))
      const newData = pairs.map(p => p.row)

      this.internalSort = { key, direction }
      this._emitDataChange(oldData, newData)
      this.$emit('update:sort', { key, direction })
      this.$emit('sort-change', { key, direction })

      this.scrollTop = 0
      this.$nextTick(() => {
        if (this.$refs.scrollBody) this.$refs.scrollBody.scrollTop = 0
      })
    },

    _sortValueFor(row, ri, col) {
      const ci = col._flatIndex
      if (col.type === 'checkbox') return this.isCheckboxChecked(ri, ci) ? 1 : 0
      if (col.type === 'date') {
        const d = parseDateValue(this.getCellValue(ri, ci))
        return d ? d.getTime() : null
      }
      if (this.isSelectLikeCol(col)) return this.getSelectLabel(ci, this.getCellValue(ri, ci), ri)
      return this.getCellValue(ri, ci)
    },

    _compareForSort(rowA, riA, rowB, riB, col, direction) {
      if (typeof col.sortFn === 'function') {
        const result = col.sortFn(rowA, rowB, col)
        return direction === 'desc' ? -result : result
      }
      const a = this._sortValueFor(rowA, riA, col)
      const b = this._sortValueFor(rowB, riB, col)
      const aEmpty = a === null || a === undefined || a === ''
      const bEmpty = b === null || b === undefined || b === ''
      if (aEmpty && bEmpty) return 0
      if (aEmpty) return 1
      if (bEmpty) return -1
      const cmp = (typeof a === 'number' && typeof b === 'number')
        ? a - b
        : String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: 'base' })
      return direction === 'desc' ? -cmp : cmp
    },

    openDatePickerForActive() {
      const { row, col } = this.activeCell
      const colDef = this.leafCols[col]
      if (!colDef || colDef.type !== 'date') return
      this.$nextTick(() => {
        const el = this.$el ? this.$el.querySelector('.eg-cell-active') : null
        if (!el) return
        const rect = el.getBoundingClientRect()
        const val = this.getCellValue(row, col)
        this.datePickerOverlay = {
          row, col,
          format: colDef.format || DEFAULT_DATE_FORMAT,
          value: val == null ? '' : String(val),
          rect: { top: rect.top, bottom: rect.bottom, left: rect.left, width: rect.width }
        }
      })
    },

    onDatePick(formattedVal) {
      if (!this.datePickerOverlay) return
      const { row, col } = this.datePickerOverlay
      const colDef = this.leafCols[col]
      if (colDef) {
        if (formattedVal !== '' && !this.isCellValueValid(row, col, formattedVal)) {
          this._showInvalidCell(row, col, formattedVal)
          this.closeDatePicker()
          return
        }
        this.invalidCell = null
        const oldData = this.data
        const newData = oldData.slice()
        newData[row] = { ...oldData[row], [colDef.key]: formattedVal }
        this._emitDataChange(oldData, newData)
        this._flushOnInput(row, col, formattedVal, newData[row])
      }
      this.closeDatePicker()
    },

    // Raw keystrokes while typing in the date picker's manual text field —
    // debounced, same as onEditInput(). onDatePick() above flushes the final,
    // validated value immediately when the date actually commits.
    onDateTyping(rawVal) {
      if (!this.datePickerOverlay) return
      const { row, col } = this.datePickerOverlay
      this._scheduleOnInput(row, col, rawVal)
    },

    // See closeSelectDropdown() — same reasoning: every close path must return
    // focus to the grid wrapper or keyboard navigation goes dead afterward.
    closeDatePicker() {
      clearTimeout(this._onInputTimer)
      this.datePickerOverlay = null
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    _onWindowScrollForDropdown(e) {
      if (this.contextMenu.visible) this.hideContextMenu()
      if (this.sortMenu.visible) this.hideSortMenu()
      if (this.selectDropdown) {
        const comp = this.$refs.selectDropdownComp
        const dd = comp && comp.$el ? comp.$el : null
        if (!(dd && dd.contains(e.target))) this.closeSelectDropdown()
      }
      if (this.datePickerOverlay) {
        const dp = this.$refs.datePickerComp
        const el = dp && dp.$el ? dp.$el : null
        if (!(el && el.contains(e.target))) this.closeDatePicker()
      }
    },

    _onDocMouseDownForDropdown(e) {
      if (this.selectDropdown) {
        const comp = this.$refs.selectDropdownComp
        const dd = comp && comp.$el ? comp.$el : null
        if (!(dd && dd.contains(e.target))) this.closeSelectDropdown()
      }
      if (this.datePickerOverlay) {
        const dp = this.$refs.datePickerComp
        const el = dp && dp.$el ? dp.$el : null
        if (!(el && el.contains(e.target))) this.closeDatePicker()
      }
    },

    onEditKeyDown(e) {
      if (e.key === 'Escape') {
        e.preventDefault()
        this.cancelEdit()
      } else if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        this.commitEdit()
        this.moveActive(1, 0, e)
      } else if (e.key === 'Tab') {
        e.preventDefault()
        this.commitEdit()
        this.moveActive(0, e.shiftKey ? -1 : 1, e)
      }
    },

    clearSelection() {
      if (this.internalLocked) return
      if (!this.selectionRanges.length) return
      const oldData = this.data
      const newData = oldData.slice()
      let hasChanges = false
      const skipped = []
      for (const range of this.selectionRanges) {
        const r = {
          startRow: Math.min(range.startRow, range.endRow),
          endRow:   Math.max(range.startRow, range.endRow),
          startCol: Math.min(range.startCol, range.endCol),
          endCol:   Math.max(range.startCol, range.endCol)
        }
        for (let ri = r.startRow; ri <= r.endRow && ri < newData.length; ri++) {
          let rowUpdated = null
          for (let ci = r.startCol; ci <= r.endCol; ci++) {
            const col = this.leafCols[ci]
            if (col && this.isCellEditable(ri, ci)) {
              if (!this.isCellValueValid(ri, ci, '')) { skipped.push({ row: ri, col: ci, value: '' }); continue }
              if (!rowUpdated) rowUpdated = { ...newData[ri] }
              rowUpdated[col.key] = ''
              hasChanges = true
            }
          }
          if (rowUpdated) newData[ri] = rowUpdated
        }
      }
      if (this.strictBulkValidation && skipped.length > 0) {
        this._emitBulkValidationError(skipped, true)
        return
      }
      if (hasChanges) this._emitDataChange(oldData, newData)
      if (skipped.length > 0) this._emitBulkValidationError(skipped, false)
    },

    // =========================================================
    // FILL HANDLE (3.3)
    // =========================================================
    startFillDrag(e) {
      if (this.internalLocked) return
      const pr = this.primaryRange
      if (!pr) return
      this.fillDrag.active = true
      this.fillDrag.sourceRange = normalizeRange(pr)
      this.fillDrag.currentRow = pr.endRow
      this.fillDrag.currentCol = pr.endCol
      e.preventDefault()
    },

    onGlobalMouseMove(e) {
      // Detect column drag threshold (5 px)
      if (this.colDrag.pending) {
        if (Math.abs(e.clientX - this.colDrag.startX) > 5) {
          this.colDrag.pending = false
          this.colDrag.active = true
          this.colDrag.dropIndex = this.colDrag.sourceFirstLeaf
          this.isMouseDown = false // cancel cell-selection drag
          this._startColDrag()
        }
      }
      if (this.colDrag.active) {
        this.handleColDragMove(e)
        return
      }

      if (this.resizing.active) {
        this.handleResizeMove(e)
        return
      }
      if (this.fillDrag.active) {
        this.handleFillDragMove(e)
        return
      }
      if (this.dragMove.active) {
        this.handleDragMoveMove(e)
        return
      }
    },

    onGlobalMouseUp(e) {
      if (this.colDrag.active) {
        this.commitColDrag()
        return
      }
      if (this.colDrag.pending) {
        this._resetColDrag()
        // fall through — normal mouseup
      }

      if (this.resizing.active) {
        this.commitResize()
        return
      }
      if (this.fillDrag.active) {
        this.commitFillDrag()
        return
      }
      if (this.dragMove.active) {
        this.commitDragMove(e)
        return
      }
      this.isMouseDown = false
    },

    // Resolves which (row, col) the mouse is currently over, given the
    // scroll body's CURRENT scrollTop/scrollLeft — called both directly from
    // mousemove and repeatedly from the edge-auto-scroll rAF loop below (as
    // scrollTop changes on its own, the row under a STATIONARY cursor changes
    // with it).
    _fillDragTargetFromEvent(e) {
      const scrollBody = this.$refs.scrollBody
      if (!scrollBody) return null
      const rect = scrollBody.getBoundingClientRect()
      const relY = e.clientY - rect.top + scrollBody.scrollTop
      const relX = e.clientX - rect.left + scrollBody.scrollLeft

      // Binary search on cumulativeHeights — O(log n) instead of O(n)
      const cum = this.cumulativeHeights
      const total = this.totalRows
      let lo = 0, hi = total - 1
      while (lo < hi) {
        const mid = (lo + hi) >> 1
        if (cum[mid + 1] <= relY) lo = mid + 1
        else hi = mid
      }
      const row = Math.min(lo, total - 1)

      // Columns are few — O(columns) is fast
      let left = this.getFrozenWidth()
      let col = 0
      for (let i = 0; i < this.leafCols.length; i++) {
        if (!this.isColumnScrollable(i)) continue
        left += this.getColW(i)
        if (relX < left) { col = i; break }
        col = i
      }
      return { row, col }
    },

    handleFillDragMove(e) {
      this._fillDragLastEvent = e
      const target = this._fillDragTargetFromEvent(e)
      if (!target) return
      this.fillDrag.currentRow = target.row
      this.fillDrag.currentCol = target.col
      // Covers the common case of a single big mousemove jump landing the
      // cursor (and its computed target row/col) outside the visible window.
      this.scrollToCell(target.row, target.col)
      // Covers the — far more common in practice — case of the cursor
      // PINNED at the container's edge (it usually can't travel further,
      // since the grid typically fills its host layout down to that edge):
      // keep scrolling for as long as it stays there. Same rAF/edge-zone
      // pattern as _updateDragAutoScroll (column-drag reordering) below.
      this._updateFillDragAutoScroll(e.clientX, e.clientY)
    },

    // Edge auto-scroll for fill-handle dragging — vertical AND horizontal
    // (column-drag's _updateDragAutoScroll is horizontal-only). Speed scales
    // with how deep into the 24px edge zone the cursor sits.
    _updateFillDragAutoScroll(clientX, clientY) {
      const sb = this.$refs.scrollBody
      if (!sb) { this._fillDragScrollV = 0; this._fillDragScrollH = 0; return }
      const rect = sb.getBoundingClientRect()
      const ZONE = FILL_DRAG_EDGE_ZONE

      let v = 0
      if (clientY < rect.top + ZONE) v = -Math.ceil((rect.top + ZONE - clientY) / 4)
      else if (clientY > rect.bottom - ZONE) v = Math.ceil((clientY - (rect.bottom - ZONE)) / 4)
      this._fillDragScrollV = Math.max(-FILL_DRAG_MAX_SPEED, Math.min(FILL_DRAG_MAX_SPEED, v))

      let h = 0
      if (clientX < rect.left + ZONE) h = -Math.ceil((rect.left + ZONE - clientX) / 4)
      else if (clientX > rect.right - ZONE) h = Math.ceil((clientX - (rect.right - ZONE)) / 4)
      this._fillDragScrollH = Math.max(-FILL_DRAG_MAX_SPEED, Math.min(FILL_DRAG_MAX_SPEED, h))

      if ((this._fillDragScrollV !== 0 || this._fillDragScrollH !== 0) && !this._fillDragScrollRAF) {
        const step = () => {
          this._fillDragScrollRAF = null
          if (!this.fillDrag.active) return
          const body = this.$refs.scrollBody
          if (body) {
            if (this._fillDragScrollV) body.scrollTop = Math.max(0, Math.min(body.scrollHeight - body.clientHeight, body.scrollTop + this._fillDragScrollV))
            if (this._fillDragScrollH) body.scrollLeft = Math.max(0, Math.min(body.scrollWidth - body.clientWidth, body.scrollLeft + this._fillDragScrollH))
            // The cursor itself hasn't moved, but the content under it has —
            // re-derive the fill target at the new scroll position.
            if (this._fillDragLastEvent) {
              const target = this._fillDragTargetFromEvent(this._fillDragLastEvent)
              if (target) { this.fillDrag.currentRow = target.row; this.fillDrag.currentCol = target.col }
            }
          }
          if (this._fillDragScrollV !== 0 || this._fillDragScrollH !== 0) this._fillDragScrollRAF = requestAnimationFrame(step)
        }
        this._fillDragScrollRAF = requestAnimationFrame(step)
      }
    },

    _stopFillDragAutoScroll() {
      this._fillDragScrollV = 0
      this._fillDragScrollH = 0
      this._fillDragLastEvent = null
      if (this._fillDragScrollRAF) {
        cancelAnimationFrame(this._fillDragScrollRAF)
        this._fillDragScrollRAF = null
      }
    },

    async commitFillDrag() {
      this._stopFillDragAutoScroll()
      if (this.internalLocked) { this.fillDrag.active = false; return }
      const src = this.fillDrag.sourceRange
      if (!src) { this.fillDrag.active = false; return }

      const targetRow = this.fillDrag.currentRow
      const targetCol = this.fillDrag.currentCol

      const oldData = this.data
      const newData = oldData.slice()  // only affected rows get new objects
      let targetRange
      const skipped = []

      if (targetRow > src.endRow) {
        // Fill down
        const count = targetRow - src.endRow
        for (let ci = src.startCol; ci <= src.endCol; ci++) {
          const col = this.leafCols[ci]
          if (!col) continue
          const srcValues = []
          for (let ri = src.startRow; ri <= src.endRow; ri++) {
            srcValues.push(oldData[ri] ? oldData[ri][col.key] : '')
          }
          const filled = generateFillValues(srcValues, count)
          for (let k = 0; k < count; k++) {
            const ri = src.endRow + 1 + k
            if (ri < this.totalRows && this.isCellEditable(ri, ci)) {
              const v = this._coerceCellValue(ci, this._applyColMask(ci, filled[k]))
              if (!this.isCellValueValid(ri, ci, v)) { skipped.push({ row: ri, col: ci, value: v }); continue }
              if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
              newData[ri][col.key] = v
            }
          }
        }
        targetRange = { startRow: src.endRow + 1, endRow: targetRow, startCol: src.startCol, endCol: src.endCol }
      } else if (targetCol > src.endCol) {
        // Fill right
        const count = targetCol - src.endCol
        for (let ri = src.startRow; ri <= src.endRow; ri++) {
          const srcValues = []
          for (let ci = src.startCol; ci <= src.endCol; ci++) {
            const col = this.leafCols[ci]
            srcValues.push(col && oldData[ri] ? oldData[ri][col.key] : '')
          }
          const filled = generateFillValues(srcValues, count)
          for (let k = 0; k < count; k++) {
            const ci = src.endCol + 1 + k
            if (ci < this.leafCols.length) {
              const col = this.leafCols[ci]
              if (col && this.isCellEditable(ri, ci)) {
                const v = this._coerceCellValue(ci, this._applyColMask(ci, filled[k]))
                if (!this.isCellValueValid(ri, ci, v)) { skipped.push({ row: ri, col: ci, value: v }); continue }
                if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
                newData[ri][col.key] = v
              }
            }
          }
        }
        targetRange = { startRow: src.startRow, endRow: src.endRow, startCol: src.endCol + 1, endCol: targetCol }
      }

      let fireOnSelect = false
      if (targetRange) {
        if (this.strictBulkValidation && skipped.length > 0) {
          this._emitBulkValidationError(skipped, true)
        } else {
          this._emitDataChange(oldData, newData)
          this.$emit('fill', { sourceRange: src, targetRange, values: newData })
          if (skipped.length > 0) this._emitBulkValidationError(skipped, false)
          fireOnSelect = true
        }
      }

      this.fillDrag.active = false
      this.fillDrag.sourceRange = null

      if (fireOnSelect) {
        // See pasteAt's _fireCellCallbacksForRange call — same nextTick deferral reasoning.
        await this.$nextTick()
        this._fireCellCallbacksForRange(oldData, newData, targetRange.startRow, targetRange.endRow, targetRange.startCol, targetRange.endCol)
      }
    },

    doubleFillDown() {
      const pr = this.primaryRange
      if (!pr) return
      const src = normalizeRange(pr)
      // Find adjacent column filled length
      const adjCol = src.startCol > 0 ? src.startCol - 1 : src.endCol + 1
      if (adjCol < 0 || adjCol >= this.leafCols.length) return
      const adjColDef = this.leafCols[adjCol]
      if (!adjColDef) return
      let lastFilledRow = src.endRow
      for (let ri = src.endRow + 1; ri < this.totalRows; ri++) {
        if (this.data[ri] && this.data[ri][adjColDef.key] !== '' && this.data[ri][adjColDef.key] !== undefined) {
          lastFilledRow = ri
        } else break
      }
      if (lastFilledRow <= src.endRow) return

      const count = lastFilledRow - src.endRow
      const oldData = this.data
      const newData = oldData.slice()
      const skipped = []
      for (let ci = src.startCol; ci <= src.endCol; ci++) {
        const col = this.leafCols[ci]
        if (!col) continue
        const srcValues = []
        for (let ri = src.startRow; ri <= src.endRow; ri++) {
          srcValues.push(oldData[ri] ? oldData[ri][col.key] : '')
        }
        const filled = generateFillValues(srcValues, count)
        for (let k = 0; k < count; k++) {
          const ri = src.endRow + 1 + k
          if (ri < this.totalRows && this.isCellEditable(ri, ci)) {
            const v = this._coerceCellValue(ci, this._applyColMask(ci, filled[k]))
            if (!this.isCellValueValid(ri, ci, v)) { skipped.push({ row: ri, col: ci, value: v }); continue }
            if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
            newData[ri][col.key] = v
          }
        }
      }
      if (this.strictBulkValidation && skipped.length > 0) {
        this._emitBulkValidationError(skipped, true)
        return
      }
      this._emitDataChange(oldData, newData)
      if (skipped.length > 0) this._emitBulkValidationError(skipped, false)
    },

    // =========================================================
    // Ctrl+D / Ctrl+R — Excel's standard fill-down/fill-right (3.96)
    // =========================================================
    // Plain copy, NOT the fill-handle's series continuation (generateFillValues,
    // 1,2,3->4,5,6) — matches real Excel: Ctrl+D/Ctrl+R just duplicates a row/
    // column's values, it never extrapolates a pattern.
    async _fillAxis(direction) {
      if (this.internalLocked) return
      if (!this.selectionRanges.length) return
      const oldData = this.data
      const newData = oldData.slice()
      const skipped = []
      const appliedRanges = []

      for (const range of this.selectionRanges) {
        const r = normalizeRange(range)
        if (direction === 'down') {
          let srcRow, firstTargetRow, lastTargetRow
          if (r.startRow === r.endRow) {
            // Single-row selection: Excel fills from the row directly above.
            srcRow = r.startRow - 1
            if (srcRow < 0) continue
            firstTargetRow = r.startRow
            lastTargetRow = r.startRow
          } else {
            srcRow = r.startRow
            firstTargetRow = r.startRow + 1
            lastTargetRow = r.endRow
          }
          for (let ci = r.startCol; ci <= r.endCol; ci++) {
            const col = this.leafCols[ci]
            if (!col) continue
            const srcVal = oldData[srcRow] ? oldData[srcRow][col.key] : ''
            for (let ri = firstTargetRow; ri <= lastTargetRow; ri++) {
              if (!this.isCellEditable(ri, ci)) continue
              const v = this._coerceCellValue(ci, this._applyColMask(ci, srcVal))
              if (!this.isCellValueValid(ri, ci, v)) { skipped.push({ row: ri, col: ci, value: v }); continue }
              if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
              newData[ri][col.key] = v
            }
          }
          appliedRanges.push({
            sourceRange: { startRow: srcRow, endRow: srcRow, startCol: r.startCol, endCol: r.endCol },
            targetRange: { startRow: firstTargetRow, endRow: lastTargetRow, startCol: r.startCol, endCol: r.endCol }
          })
        } else {
          let srcCol, firstTargetCol, lastTargetCol
          if (r.startCol === r.endCol) {
            // Single-column selection: Excel fills from the column directly to the left.
            srcCol = r.startCol - 1
            if (srcCol < 0) continue
            firstTargetCol = r.startCol
            lastTargetCol = r.startCol
          } else {
            srcCol = r.startCol
            firstTargetCol = r.startCol + 1
            lastTargetCol = r.endCol
          }
          const srcColDef = this.leafCols[srcCol]
          for (let ri = r.startRow; ri <= r.endRow; ri++) {
            const srcVal = srcColDef && oldData[ri] ? oldData[ri][srcColDef.key] : ''
            for (let ci = firstTargetCol; ci <= lastTargetCol; ci++) {
              const col = this.leafCols[ci]
              if (!col || !this.isCellEditable(ri, ci)) continue
              const v = this._coerceCellValue(ci, this._applyColMask(ci, srcVal))
              if (!this.isCellValueValid(ri, ci, v)) { skipped.push({ row: ri, col: ci, value: v }); continue }
              if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
              newData[ri][col.key] = v
            }
          }
          appliedRanges.push({
            sourceRange: { startRow: r.startRow, endRow: r.endRow, startCol: srcCol, endCol: srcCol },
            targetRange: { startRow: r.startRow, endRow: r.endRow, startCol: firstTargetCol, endCol: lastTargetCol }
          })
        }
      }

      if (!appliedRanges.length) return

      if (this.strictBulkValidation && skipped.length > 0) {
        this._emitBulkValidationError(skipped, true)
        return
      }

      this._emitDataChange(oldData, newData)
      for (const ar of appliedRanges) {
        this.$emit('fill', { sourceRange: ar.sourceRange, targetRange: ar.targetRange, values: newData })
      }
      if (skipped.length > 0) this._emitBulkValidationError(skipped, false)

      // See pasteAt's/commitFillDrag's _fireCellCallbacksForRange call — same
      // nextTick deferral reasoning (col.onInput/onSelect after the DOM settles).
      await this.$nextTick()
      for (const ar of appliedRanges) {
        this._fireCellCallbacksForRange(oldData, newData, ar.targetRange.startRow, ar.targetRange.endRow, ar.targetRange.startCol, ar.targetRange.endCol)
      }
    },

    fillDown() { return this._fillAxis('down') },
    fillRight() { return this._fillAxis('right') },

    // =========================================================
    // COPY / PASTE (3.4)
    // =========================================================
    copySelection() {
      const pr = this.primaryRange
      if (!pr) return
      const r = normalizeRange(pr)
      this.clipboardMatrix = extractMatrix(this.data, this.leafCols, r)
      this.clipboardRange = r
      this.clipboardMode = 'copy'

      // Write to system clipboard as TSV
      const tsv = matrixToTSV(this.clipboardMatrix)
      if (navigator.clipboard) {
        navigator.clipboard.writeText(tsv).catch(() => {})
      }
    },

    cutSelection() {
      this.copySelection()
      this.clipboardMode = 'cut'
    },

    // Bulk cell writes (paste, fill handle, drag-move) set row values directly
    // and skip the single-cell paths (onComponentSelect / commitEdit /
    // setCheckboxValue / onDatePick) — so col.onSelect / col.onInput never
    // fire for them unless we replay it here for every cell whose value
    // actually changed in the range. select/treeSelect columns get onSelect
    // (matching the single-pick shape); everything else gets onInput —
    // fired immediately, no debounce (this is already a single bulk commit,
    // not live keystrokes).
    _fireCellCallbacksForRange(oldData, newData, startRow, endRow, startCol, endCol) {
      let fired = false
      for (let ri = startRow; ri <= endRow; ri++) {
        const oldRow = oldData[ri]
        const newRow = newData[ri]
        if (!newRow || newRow === oldRow) continue
        for (let ci = startCol; ci <= endCol; ci++) {
          const col = this.leafCols[ci]
          if (!col) continue
          const oldVal = oldRow ? oldRow[col.key] : undefined
          const newVal = newRow[col.key]
          if (newVal === oldVal) continue
          if (this.isSelectLikeCol(col)) {
            if (typeof col.onSelect === 'function') {
              col.onSelect({ value: newVal, label: this.getSelectLabel(ci, newVal, ri) }, newRow, ri, col)
              fired = true
            }
          } else if (typeof col.onInput === 'function') {
            col.onInput(newVal, newRow, ri, col)
            fired = true
          }
        }
      }
      // See _scheduleOnInput — one forceUpdate covers the whole range instead of
      // one per cell (this can fire many callbacks for a large paste/fill range).
      if (fired) this.$forceUpdate()
    },

    async pasteAt(targetRow, targetCol, options = {}) {
      if (this.internalLocked) return
      const { mode = 'all', transpose = false } = options

      let matrix = null

      // Try system clipboard first
      if (navigator.clipboard) {
        try {
          const text = await navigator.clipboard.readText()
          if (text) matrix = tsvToMatrix(text)
        } catch (_) {}
      }

      // Fall back to internal clipboard
      if (!matrix && this.clipboardMatrix) {
        matrix = this.clipboardMatrix
      }

      if (!matrix) return

      if (transpose) matrix = transposeMatrix(matrix)

      // ── Excel-style selection broadcast / tiling ──────────────────────────
      // When pasting over a multi-cell selection and the clipboard matrix is
      // smaller than the selection, tile the matrix to fill the selection —
      // provided the selection dimensions are exact multiples of the matrix
      // dimensions (matches Excel's tiling rule exactly).
      // Cut-paste is never tiled (source must be cleared exactly once).
      const isCopyPaste = !this.clipboardMode || this.clipboardMode === 'copy'
      if (isCopyPaste) {
        const pr = this.primaryRange
        if (pr) {
          const sel = normalizeRange(pr)
          const selRows = sel.endRow - sel.startRow + 1
          const selCols = sel.endCol - sel.startCol + 1
          const matRows = matrix.length
          const matCols = matrix[0] ? matrix[0].length : 0

          // Only tile when selection is strictly larger than clipboard
          if ((selRows > matRows || selCols > matCols) &&
              selRows % matRows === 0 && selCols % matCols === 0) {
            matrix = tileMatrix(matrix, selRows, selCols)
            // Paste at selection origin, not just at the active cell
            targetRow = sel.startRow
            targetCol = sel.startCol
          }
        }
      }

      const oldData = this.data
      // pasteGrowsRows: pre-extend the working copy with blank rows so
      // applyMatrix's own data.length clamp naturally covers the full
      // pasted range instead of truncating it. `oldData` itself (used below
      // for _emitDataChange's undo/redo diff) stays untouched.
      let pasteBase = oldData
      let addedStartIndex = 0
      let addedCount = 0
      if (this.pasteGrowsRows) {
        const neededLength = targetRow + matrix.length
        if (neededLength > oldData.length) {
          const blankRows = []
          for (let i = oldData.length; i < neededLength; i++) {
            const row = {}
            this.leafCols.forEach(col => { row[col.key] = this._blankValueForCol(col) })
            if (this.pasteRowDefaults) {
              const extra = typeof this.pasteRowDefaults === 'function' ? this.pasteRowDefaults(i) : this.pasteRowDefaults
              if (extra) Object.assign(row, extra)
            }
            blankRows.push(row)
          }
          pasteBase = oldData.concat(blankRows)
          addedStartIndex = oldData.length
          addedCount = blankRows.length
        }
      }
      const { newData, affectedRange, skipped } = applyMatrix(
        pasteBase, this.leafCols, targetRow, targetCol, matrix, mode,
        (ri, ci) => this.isCellEditable(ri, ci),
        (ri, ci, v) => this.isCellValueValid(ri, ci, v),
        (ri, ci, v) => this._coerceCellValue(ci, this._applyColMask(ci, v))
      )

      if (this.strictBulkValidation && skipped.length > 0) {
        this._emitBulkValidationError(skipped, true)
        return
      }

      if (this.clipboardMode === 'cut' && this.clipboardRange) {
        // Clear source — ensure each source row is a new copy before mutation
        const src = this.clipboardRange
        for (let ri = src.startRow; ri <= src.endRow; ri++) {
          if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
          for (let ci = src.startCol; ci <= src.endCol; ci++) {
            const col = this.leafCols[ci]
            if (col && this.isCellEditable(ri, ci) && this.isCellValueValid(ri, ci, '')) {
              newData[ri][col.key] = ''
            }
          }
        }
        this.clipboardRange = null
        this.clipboardMode = null
      }

      this._emitDataChange(oldData, newData)
      // Fired once per paste operation (never per row), after 'input' — so by
      // the time hosts receive it, v-model already holds the final rows.
      // Lets hosts do a single aggregate action instead of reacting to
      // pasteRowDefaults' per-row calls.
      if (addedCount > 0) {
        this.$emit('rows-added', {
          startIndex: addedStartIndex,
          count: addedCount,
          rows: newData.slice(addedStartIndex, addedStartIndex + addedCount)
        })
      }
      if (skipped.length > 0) this._emitBulkValidationError(skipped, false)
      // Wait for Vue's reactivity queue to flush before firing onSelect — hosts
      // commonly react to the emitted 'input' with their own watcher (e.g. to
      // mirror the row into an external store); firing onSelect synchronously
      // would run it against that store's pre-paste, stale state.
      await this.$nextTick()
      this._fireCellCallbacksForRange(oldData, newData, affectedRange.startRow, affectedRange.endRow, affectedRange.startCol, affectedRange.endCol)
    },

    ctxCopy() { this.hideContextMenu(); this.copySelection() },
    ctxCut() { this.hideContextMenu(); this.cutSelection() },
    ctxPaste() { this.hideContextMenu(); this.pasteAt(this.activeCell.row, this.activeCell.col) },
    ctxPasteSpecial(mode, transpose = false) {
      this.hideContextMenu()
      this.pasteAt(this.activeCell.row, this.activeCell.col, { mode, transpose })
    },

    // =========================================================
    // COLUMN DRAG-AND-DROP
    // =========================================================

    _computeDragOffsets(dropIndex) {
      const { sourceFirstLeaf, sourceLeafCount } = this.colDrag
      if (dropIndex < 0 || (dropIndex >= sourceFirstLeaf && dropIndex <= sourceFirstLeaf + sourceLeafCount)) return {}

      const previewCols = moveColumnNodeInTree(this.columns, sourceFirstLeaf, sourceLeafCount, dropIndex)
      const previewLeaves = flattenColumns(previewCols)

      const byKey = {}
      this.leafCols.forEach(c => { byKey[c.key] = c })

      const offsets = {}
      for (const zone of ['left', 'scroll', 'right']) {
        const inZone = zone === 'left'
          ? ci => this.isColumnPinnedLeft(ci)
          : zone === 'right'
            ? ci => this.isColumnPinnedRight(ci)
            : ci => this.isColumnScrollable(ci)

        const origPos = {}
        let acc = 0
        this.leafCols.forEach(col => {
          const ci = col._flatIndex
          if (this.isColHidden(ci) || !inZone(ci)) return
          origPos[col.key] = acc
          acc += this.getColW(ci)
        })

        const previewPos = {}
        acc = 0
        for (const col of previewLeaves) {
          const origCol = byKey[col.key]
          if (!origCol) continue
          const ci = origCol._flatIndex
          if (this.isColHidden(ci) || !inZone(ci)) continue
          previewPos[col.key] = acc
          acc += this.getColW(ci)
        }

        for (const key of Object.keys(origPos)) {
          offsets[key] = (previewPos[key] !== undefined ? previewPos[key] : origPos[key]) - origPos[key]
        }
      }
      return offsets
    },

    // Called once when the 5px movement threshold flips the drag active:
    // snapshots the original header geometry the whole drag will be measured
    // against, sizes the ghost from the grabbed header, and arms the CSS
    // transitions on every column element.
    _startColDrag() {
      const sb = this.$refs.scrollBody
      this._dragStartScrollLeft = sb ? sb.scrollLeft : 0
      const bounds = []
      if (this.$el) {
        this.$el.querySelectorAll('.eg-header-cell:not(.eg-header-group)').forEach(el => {
          const fi = parseInt(el.dataset.fi)
          if (isNaN(fi)) return
          const rect = el.getBoundingClientRect()
          bounds.push({ fi, left: rect.left, right: rect.right, scrollable: this.isColumnScrollable(fi) })
        })
      }
      this._dragBounds = bounds
      this._dragScrollV = 0

      const hr = this._pendingDragHeaderRect
      if (hr && hr.width > 0) {
        this.colDrag.ghostWidth = Math.min(Math.round(hr.width), 320)
        this.colDrag.grabOffsetX = Math.min(
          Math.max(Math.round(this.colDrag.startX - hr.left), 12),
          this.colDrag.ghostWidth - 12
        )
      } else {
        this.colDrag.ghostWidth = 140
        this.colDrag.grabOffsetX = 70
      }

      this._setDragTransitions(true)
    },

    _setDragTransitions(on) {
      if (!this.$el) return
      this.$el.querySelectorAll('[data-fi], [data-start]').forEach(el => {
        el.style.transition = on ? COL_DRAG_TRANSITION : ''
      })
    },

    _applyDragTransforms(offsets) {
      if (!this.$el) return
      // Just retarget the transforms — the CSS transition set at drag start
      // animates each element from wherever it currently is. An explicit
      // translateX(0px) (not '') keeps returning columns gliding back instead
      // of snapping.
      this.$el.querySelectorAll('[data-fi]').forEach(el => {
        const fi = parseInt(el.dataset.fi)
        const col = this.leafCols[fi]
        const dx = col ? (offsets[col.key] || 0) : 0
        el.style.transform = 'translateX(' + dx + 'px)'
      })
      this.$el.querySelectorAll('[data-start]').forEach(el => {
        const start = parseInt(el.dataset.start)
        const end = parseInt(el.dataset.end)
        if (isNaN(start)) return
        let key = null
        for (let i = start; i <= end; i++) {
          if (!this.isColHidden(i) && this.leafCols[i]) { key = this.leafCols[i].key; break }
        }
        const dx = key ? (offsets[key] || 0) : 0
        el.style.transform = 'translateX(' + dx + 'px)'
      })
    },

    // Instant cleanup: transition and transform drop in the same style write,
    // so the (now transition-less) transform change never animates.
    _clearDragTransforms() {
      if (!this.$el) return
      this.$el.querySelectorAll('[data-fi], [data-start]').forEach(el => {
        el.style.transition = ''
        el.style.transform = ''
      })
    },

    handleColDragMove(e) {
      // Ghost follows the cursor with the original grab point preserved —
      // direct DOM writes, no Vue re-render per mousemove.
      const ghost = this.$refs.colDragGhost
      if (ghost) {
        ghost.style.left = (e.clientX - this.colDrag.grabOffsetX) + 'px'
        ghost.style.top = (e.clientY - 14) + 'px'
      }
      this._lastDragClientX = e.clientX
      this._refreshDragPreview(e.clientX)
      this._updateDragAutoScroll(e.clientX)
    },

    _refreshDragPreview(clientX) {
      const prevDrop = this.colDrag.dropIndex
      this._updateColDragDropIndex(clientX)
      if (this.colDrag.dropIndex !== prevDrop) {
        this._dragOffsets = this._computeDragOffsets(this.colDrag.dropIndex)
        this._applyDragTransforms(this._dragOffsets)
      }
    },

    _updateColDragDropIndex(clientX) {
      const bounds = this._dragBounds
      if (!bounds || !bounds.length) { this.colDrag.dropIndex = this.leafCols.length; return }

      // Boundaries come from the drag-start snapshot, shifted by how far the
      // body has scrolled since (pinned zones don't move with the scroll).
      // Live DOM rects are never read — they carry in-flight preview
      // transforms whose intermediate values would corrupt the math.
      const sb = this.$refs.scrollBody
      const scrollDelta = sb ? sb.scrollLeft - this._dragStartScrollLeft : 0
      const adjusted = bounds
        .map(b => ({
          fi: b.fi,
          left: b.scrollable ? b.left - scrollDelta : b.left,
          right: b.scrollable ? b.right - scrollDelta : b.right
        }))
        .sort((a, b) => a.left - b.left)

      let dropIndex = adjusted[adjusted.length - 1].fi + 1
      for (const { fi, left, right } of adjusted) {
        if (clientX < right) {
          dropIndex = clientX < (left + right) / 2 ? fi : fi + 1
          break
        }
      }
      this.colDrag.dropIndex = dropIndex
    },

    // Edge auto-scroll: dragging near the left/right edge of the visible
    // scrollable window (the part not covered by sticky pinned zones) scrolls
    // the body horizontally, speed proportional to how deep into the 40px
    // edge zone the cursor sits — so far-away drop targets are reachable.
    _updateDragAutoScroll(clientX) {
      const sb = this.$refs.scrollBody
      if (!sb) { this._dragScrollV = 0; return }
      const rect = sb.getBoundingClientRect()
      const leftEdge = rect.left + this.getFrozenWidth()
      const rightEdge = rect.left + sb.clientWidth - (this.hasPinnedRight ? this.pinnedRightWidth : 0)
      const ZONE = 40
      let v = 0
      if (clientX < leftEdge + ZONE) v = -Math.ceil((leftEdge + ZONE - clientX) / 4)
      else if (clientX > rightEdge - ZONE) v = Math.ceil((clientX - (rightEdge - ZONE)) / 4)
      this._dragScrollV = Math.max(-20, Math.min(20, v))

      if (this._dragScrollV !== 0 && !this._dragScrollRAF) {
        const step = () => {
          this._dragScrollRAF = null
          if (!this.colDrag.active || this._dragScrollV === 0) return
          const body = this.$refs.scrollBody
          if (body) {
            const before = body.scrollLeft
            body.scrollLeft += this._dragScrollV
            // Re-derive the drop slot at the new scroll position even though
            // the cursor itself hasn't moved.
            if (body.scrollLeft !== before) this._refreshDragPreview(this._lastDragClientX)
          }
          this._dragScrollRAF = requestAnimationFrame(step)
        }
        this._dragScrollRAF = requestAnimationFrame(step)
      }
    },

    _stopDragAutoScroll() {
      this._dragScrollV = 0
      if (this._dragScrollRAF) {
        cancelAnimationFrame(this._dragScrollRAF)
        this._dragScrollRAF = null
      }
    },

    commitColDrag() {
      const from = this.colDrag.sourceFirstLeaf
      const leafCount = this.colDrag.sourceLeafCount
      const to = this.colDrag.dropIndex

      if (from < 0 || to < 0 || leafCount < 1) { this._resetColDrag(true); return }
      if (to >= from && to <= from + leafCount) { this._resetColDrag(true); return }

      // KEEP the preview transforms in the DOM while Vue re-renders with the
      // new column order. After Vue updates left positions ($nextTick), we
      // instantly clear them — both steps run as microtasks before the browser
      // paints, so there is never a visible intermediate state.
      this._stopDragAutoScroll()
      clearTimeout(this._dragCleanupTimer)
      this._dragOffsets = {}
      this._dragBounds = null
      this.colDrag.pending = false
      this.colDrag.active = false
      this.colDrag.sourceFirstLeaf = -1
      this.colDrag.sourceLeafCount = 1
      this.colDrag.dropIndex = -1
      this.colDrag.ghostLabel = ''

      const newCols = moveColumnNodeInTree(this.columns, from, leafCount, to)
      this.$emit('update:columns', newCols)
      this.$emit('column-reorder', { fromIndex: from, toIndex: to, columns: newCols })

      // Clear transforms after Vue re-renders new column left positions
      this.$nextTick(() => { this._clearDragTransforms() })
    },

    // animateBack: cancelled drags (Escape, drop on the source slot) glide the
    // columns back to their original places instead of snapping.
    _resetColDrag(animateBack = false) {
      const wasActive = this.colDrag.active
      this._stopDragAutoScroll()
      this._dragOffsets = {}
      this._dragBounds = null
      this.colDrag.pending = false
      this.colDrag.active = false
      this.colDrag.sourceFirstLeaf = -1
      this.colDrag.sourceLeafCount = 1
      this.colDrag.dropIndex = -1
      this.colDrag.ghostLabel = ''
      clearTimeout(this._dragCleanupTimer)
      if (animateBack && wasActive && this.$el) {
        this._applyDragTransforms({}) // everything retargets to translateX(0) with transitions still on
        this._dragCleanupTimer = setTimeout(() => this._clearDragTransforms(), 230)
      } else {
        this._clearDragTransforms()
      }
    },

    // =========================================================
    // RESIZE (3.5)
    // =========================================================
    startColResize(e, ci) {
      // Under fitColumns, resizing a column turns IT into a fixed px
      // override (see commitResize/_applyFitColumns) — the rest keep
      // scaling proportionally to fill what's left, so this can reintroduce
      // horizontal scroll. That's an accepted tradeoff for letting a column
      // be pinned to an exact width while fitColumns is on.
      if (this.internalLocked) return
      const rect = this.$refs.container.getBoundingClientRect()
      this.resizing = {
        active: true,
        type: 'col',
        index: ci,
        startX: e.clientX,
        startY: e.clientY,
        startSize: this.getColW(ci),
        currentPos: e.clientX,
        containerLeft: rect.left,
        containerTop: rect.top
      }
      // Manual resize turns a relative-unit width ('20%', ...) into a fixed px
      // override — it should no longer rescale on window resize.
      this.$delete(this.relativeColSpecs, ci)
      e.preventDefault()
    },

    startRowResize(e, ri) {
      if (this.internalLocked) return
      const rect = this.$refs.container.getBoundingClientRect()
      this.resizing = {
        active: true,
        type: 'row',
        index: ri,
        startX: e.clientX,
        startY: e.clientY,
        startSize: this.getRowH(ri),
        currentPos: e.clientY,
        containerLeft: rect.left,
        containerTop: rect.top
      }
      e.preventDefault()
    },

    handleResizeMove(e) {
      if (this.resizing.type === 'col') {
        this.resizing.currentPos = e.clientX
        const newWidth = Math.max(20, this.resizing.startSize + (e.clientX - this.resizing.startX))
        this.$set(this.colWidths, this.resizing.index, newWidth)
        this._cellStyleCache = Object.create(null)
      } else {
        this.resizing.currentPos = e.clientY
        this._resizePreviewHeight = Math.max(10, this.resizing.startSize + (e.clientY - this.resizing.startY))
        // Batch $set + updateVirtualScroll to rAF — prevents O(n) cumulativeHeights rebuild
        // on every mousemove (200+ Hz). At most 60 rebuilds/sec instead of 200+.
        if (!this._resizeRAF) {
          this._resizeRAF = requestAnimationFrame(() => {
            this._resizeRAF = null
            this._rowStyleCache = Object.create(null)
            this._rowHeaderStyleCache = Object.create(null)
            this._cellStyleCache = Object.create(null)
            this.$set(this.rowHeights, this.resizing.index, this._resizePreviewHeight)
            this.updateVirtualScroll()
          })
        }
      }
    },

    commitResize() {
      if (this._resizeRAF) {
        cancelAnimationFrame(this._resizeRAF)
        this._resizeRAF = null
        // Apply the last pending preview height immediately on commit
        if (this.resizing.type === 'row' && this._resizePreviewHeight !== undefined) {
          this.$set(this.rowHeights, this.resizing.index, this._resizePreviewHeight)
        }
      }
      if (this.resizing.type === 'col') {
        this._cellStyleCache = Object.create(null)
        const newSize = this.colWidths[this.resizing.index]
        if (this.fitColumns) {
          const col = this.leafCols[this.resizing.index]
          if (col) this.$set(this.fitColumnsOverrides, col.key, true)
          this._applyFitColumns()
        }
        this.$emit('column-resize', { index: this.resizing.index, newSize })
      } else {
        this._rowStyleCache = Object.create(null)
        this._rowHeaderStyleCache = Object.create(null)
        this._cellStyleCache = Object.create(null)
        const newSize = this.rowHeights[this.resizing.index]
        this.$emit('row-resize', { index: this.resizing.index, newSize })
        this.updateVirtualScroll()
      }
      this.resizing.active = false
    },

    // Double-click-the-header "AutoFit column width" — same idea as Excel/Sheets'
    // double-click-the-border shortcut. Under fitColumns, same override
    // treatment as a manual drag-resize (see commitResize/_applyFitColumns):
    // this column becomes a fixed px width excluded from the proportional
    // fit, the rest keep scaling in what's left.
    autoFitColumn(ci) {
      const col = this.leafCols[ci]
      if (!col) return
      let maxLen = (col.title || '').length
      for (let ri = 0; ri < Math.min(this.totalRows, 500); ri++) {
        const v = this.data[ri] ? String(this.data[ri][col.key] || '') : ''
        if (v.length > maxLen) maxLen = v.length
      }
      const newWidth = Math.max(50, maxLen * 8 + 16)
      this.$set(this.colWidths, ci, newWidth)
      this.$delete(this.relativeColSpecs, ci)
      this._cellStyleCache = Object.create(null)
      if (this.fitColumns) {
        this.$set(this.fitColumnsOverrides, col.key, true)
        this._applyFitColumns()
      }
      this.$emit('column-resize', { index: ci, newSize: newWidth })
    },

    _applyAutoWidth() {
      // fitColumns is the higher-priority width control — see its own JSDoc.
      if (!this.autoWidth || this.fitColumns || !this.leafCols.length) return
      this.leafCols.forEach((col, ci) => {
        let maxLen = (col.title || '').length
        for (let ri = 0; ri < Math.min(this.totalRows, 500); ri++) {
          const v = this.data[ri] ? String(this.data[ri][col.key] || '') : ''
          if (v.length > maxLen) maxLen = v.length
        }
        this.$set(this.colWidths, ci, Math.max(50, maxLen * 8 + 16))
        this.$delete(this.relativeColSpecs, ci)
      })
      this._cellStyleCache = Object.create(null)
    },

    // fitColumns prop — ignores col.width as an absolute value, using it only
    // as a relative WEIGHT so every visible leaf column (pinned or not)
    // scales by one shared factor to exactly fill _relativeWidthContainer
    // (the same circular-dependency-safe reference %/CSS-length widths
    // already resolve against — see its declaration comment). Mirrors
    // naturalGridWidth's formula in reverse: that computed derives the
    // grid's natural width FROM the column widths; this derives the column
    // widths FROM the available width.
    //
    // Columns in fitColumnsOverrides (manually resized while fitColumns was
    // on — see commitResize) are excluded from the scaling pool and keep
    // their current colWidths px value untouched; the remaining columns
    // scale to fill whatever space is left after subtracting the overrides'
    // total width, which can go negative (horizontal scroll returns) if the
    // overrides alone exceed the available width.
    _applyFitColumns() {
      if (!this.fitColumns || !this.leafCols.length) return
      const containerWidth = this._relativeWidthContainer
      if (!containerWidth) return // not measured yet — re-run once hostContainerWidth arrives
      const outlineW = this.rowGroups.length ? OUTLINE_GUTTER : 0
      const available = containerWidth - ROW_HEADER_WIDTH - outlineW - this.vScrollbarW - this.shellBorderW
      if (available <= 0) return

      const visible = []
      let totalWeight = 0
      let overriddenWidth = 0
      this.leafCols.forEach((col, ci) => {
        if (this.isColHidden(ci)) return
        if (this.fitColumnsOverrides[col.key]) {
          const w = this.colWidths[ci] !== undefined ? this.colWidths[ci] : this.resolveColWidth(col.width, containerWidth)
          overriddenWidth += w
          return
        }
        const w = this.resolveColWidth(col.width, containerWidth)
        visible.push({ ci, weight: w })
        totalWeight += w
      })
      if (!visible.length || totalWeight <= 0) return

      const remaining = available - overriddenWidth
      const scale = remaining > 0 ? remaining / totalWeight : 0
      visible.forEach(({ ci, weight }) => {
        this.$set(this.colWidths, ci, Math.max(FIT_COLUMNS_MIN_WIDTH, weight * scale))
        this.$delete(this.relativeColSpecs, ci)
      })
      this._cellStyleCache = Object.create(null)
    },

    ctxHideRow() {
      const targetRow = this.contextMenu.row
      // Row header: row >= 0 AND col = -1 (no column context)
      const fromRowHeader = targetRow >= 0 && this.contextMenu.col < 0
      this.hideContextMenu()
      if (this.internalLocked) return
      const newHidden = [...this.hiddenRows]
      if (fromRowHeader) {
        if (!newHidden.includes(targetRow)) newHidden.push(targetRow)
      } else {
        const pr = this.primaryRange
        if (!pr) return
        const r = normalizeRange(pr)
        for (let ri = r.startRow; ri <= r.endRow; ri++) {
          if (!newHidden.includes(ri)) newHidden.push(ri)
        }
      }
      this.$emit('update:hiddenRows', newHidden)
    },

    ctxHideColumn() {
      const targetCol = this.contextMenu.col
      // Column header: col >= 0 AND row = -1 (no row context)
      const fromColHeader = targetCol >= 0 && this.contextMenu.row < 0
      this.hideContextMenu()
      if (this.internalLocked) return
      const newHidden = [...this.hiddenColumns]
      if (fromColHeader) {
        if (!newHidden.includes(targetCol)) newHidden.push(targetCol)
      } else {
        const pr = this.primaryRange
        if (!pr) return
        const r = normalizeRange(pr)
        for (let ci = r.startCol; ci <= r.endCol; ci++) {
          if (!newHidden.includes(ci)) newHidden.push(ci)
        }
      }
      this.$emit('update:hiddenColumns', newHidden)
    },

    ctxUnhideRows() {
      this.hideContextMenu()
      if (this.internalLocked) return
      this.$emit('update:hiddenRows', [])
    },

    ctxUnhideColumns() {
      this.hideContextMenu()
      if (this.internalLocked) return
      this.$emit('update:hiddenColumns', [])
    },

    ctxPinLeft() {
      const col = this.leafCols[this.contextMenu.col]
      this.hideContextMenu()
      if (!col) return
      this.$set(this.internalPinnedColumns, col.key, 'left')
      this.$emit('update:pinnedColumns', { ...this.internalPinnedColumns })
    },

    ctxPinRight() {
      const col = this.leafCols[this.contextMenu.col]
      this.hideContextMenu()
      if (!col) return
      this.$set(this.internalPinnedColumns, col.key, 'right')
      this.$emit('update:pinnedColumns', { ...this.internalPinnedColumns })
    },

    ctxUnpin() {
      const col = this.leafCols[this.contextMenu.col]
      this.hideContextMenu()
      if (!col) return
      this.$delete(this.internalPinnedColumns, col.key)
      this.$emit('update:pinnedColumns', { ...this.internalPinnedColumns })
    },

    isColPinned(ci) {
      const col = this.leafCols[ci]
      return !!(col && this.internalPinnedColumns[col.key])
    },

    // =========================================================
    // DEV MODE — column/row config info (context menu → modal)
    // =========================================================
    _stringifyForInfo(value) {
      const seen = new WeakSet()
      return JSON.stringify(value, (key, val) => {
        if (typeof val === 'function') return 'ƒ ' + (val.name || 'anonymous') + '()'
        if (val && typeof val === 'object') {
          if (seen.has(val)) return '[Circular]'
          seen.add(val)
        }
        return val
      }, 2)
    },

    ctxShowColumnInfo() {
      const ci = this.contextMenu.col
      this.hideContextMenu()
      const col = this.leafCols[ci]
      if (!col) return
      const { _flatIndex, ...rest } = col
      this.infoModal = { title: `${this.t.columnInfo}: ${col.title || col.key}`, json: this._stringifyForInfo(rest) }
    },

    ctxShowRowInfo() {
      const ri = this.contextMenu.row
      this.hideContextMenu()
      const row = this._dataRaw[ri]
      if (!row) return
      this.infoModal = { title: `${this.t.rowInfo} #${ri + 1}`, json: this._stringifyForInfo(row) }
    },

    closeInfoModal() {
      this.infoModal = null
    },

    // =========================================================
    // MERGE CELLS (3.8)
    // =========================================================
    mergeCells(range) {
      if (this.internalLocked) return false
      const oldMerges = this.internalMerges.slice()
      const { merges: newMerges, conflict } = addMerge(range, this.internalMerges)
      if (conflict) {
        this.$emit('merge-error', { range, reason: 'Overlaps existing merge' })
        return false
      }
      this.internalMerges = newMerges
      this._emitMergeChange(oldMerges, [...newMerges])
      return true
    },

    unmergeCells(row, col) {
      if (this.internalLocked) return
      const oldMerges = this.internalMerges.slice()
      const newMerges = removeMergeAt(row, col, this.internalMerges)
      this.internalMerges = newMerges
      this._emitMergeChange(oldMerges, [...newMerges])
    },

    ctxMerge() {
      this.hideContextMenu()
      const pr = this.primaryRange
      if (!pr) return
      this.mergeCells(normalizeRange(pr))
    },

    ctxUnmerge() {
      this.hideContextMenu()
      this.unmergeCells(this.activeCell.row, this.activeCell.col)
    },

    // =========================================================
    // GROUPING (3.7)
    // =========================================================
    groupRows(startIndex, endIndex) {
      this.internalGroups = addGroup('row', startIndex, endIndex, this.internalGroups)
    },

    groupColumns(startIndex, endIndex) {
      this.internalGroups = addGroup('column', startIndex, endIndex, this.internalGroups)
    },

    ungroupRows(startIndex, endIndex) {
      this.internalGroups = removeGroup('row', startIndex, endIndex, this.internalGroups)
    },

    ungroupColumns(startIndex, endIndex) {
      this.internalGroups = removeGroup('column', startIndex, endIndex, this.internalGroups)
    },

    toggleGroup(group) {
      this.internalCollapsedGroups = toggleGroupCollapse(group, this.internalCollapsedGroups)
      this.$emit('update:collapsedGroups', [...this.internalCollapsedGroups])
      this.$emit('group-toggle', { group, collapsed: _isGroupCollapsed(group, this.internalCollapsedGroups) })
      this.updateVirtualScroll()
    },

    isGroupCollapsed(group) {
      return _isGroupCollapsed(group, this.internalCollapsedGroups)
    },

    expandAll() {
      this.internalCollapsedGroups = []
      this.$emit('update:collapsedGroups', [])
      this.updateVirtualScroll()
    },

    collapseAll() {
      this.internalCollapsedGroups = [...this.internalGroups]
      this.$emit('update:collapsedGroups', [...this.internalGroups])
      this.updateVirtualScroll()
    },

    // =========================================================
    // DRAG AND DROP (3.9)
    // =========================================================
    startDragMove(e, ri, ci) {
      const pr = this.primaryRange
      if (!pr) return
      this.dragMove = {
        active: true,
        sourceRange: normalizeRange(pr),
        startX: e.clientX,
        startY: e.clientY,
        targetRow: ri,
        targetCol: ci,
        copyMode: e.ctrlKey || e.metaKey
      }
      this.$emit('cell-drag-start', { sourceRange: this.dragMove.sourceRange })
      e.preventDefault()
    },

    handleDragMoveMove(e) {
      this.dragMove.copyMode = e.ctrlKey || e.metaKey
      this.$emit('cell-drag-move', {
        sourceRange: this.dragMove.sourceRange,
        targetRow: this.dragMove.targetRow,
        targetCol: this.dragMove.targetCol
      })
    },

    async commitDragMove(e) {
      if (!this.dragMove.active) return
      const { sourceRange, targetRow, targetCol, copyMode } = this.dragMove

      const targetRange = {
        startRow: targetRow,
        startCol: targetCol,
        endRow: targetRow + (sourceRange.endRow - sourceRange.startRow),
        endCol: targetCol + (sourceRange.endCol - sourceRange.startCol)
      }

      let proceed = true
      if (this.beforeDrop) {
        proceed = await Promise.resolve(this.beforeDrop(sourceRange, targetRange))
      }

      let oldData = null
      let newData = null
      if (proceed) {
        oldData = this.data
        const matrix = extractMatrix(oldData, this.leafCols, sourceRange)
        newData = applyMatrix(oldData, this.leafCols, targetRow, targetCol, matrix, 'all', (ri, ci) => this.isCellEditable(ri, ci)).newData

        if (!copyMode) {
          // Clear source — ensure each source row is a new copy before mutation
          for (let ri = sourceRange.startRow; ri <= sourceRange.endRow; ri++) {
            if (newData[ri] === oldData[ri]) newData[ri] = { ...oldData[ri] }
            for (let ci = sourceRange.startCol; ci <= sourceRange.endCol; ci++) {
              const col = this.leafCols[ci]
              if (col && this.isCellEditable(ri, ci)) newData[ri][col.key] = ''
            }
          }
        }
        this._emitDataChange(oldData, newData)
        this.$emit('cell-drop', { sourceRange, targetRange })
      }

      this.dragMove = { active: false, sourceRange: null, startX: 0, startY: 0, targetRow: -1, targetCol: -1, copyMode: false }
      this.isMouseDown = false

      if (proceed) {
        // See pasteAt's _fireCellCallbacksForRange call — same nextTick deferral reasoning.
        await this.$nextTick()
        this._fireCellCallbacksForRange(oldData, newData, targetRange.startRow, targetRange.endRow, targetRange.startCol, targetRange.endCol)
      }
    },

    // =========================================================
    // EXCEL EXPORT (3.11)
    // =========================================================
    async exportToExcel(options = {}) {
      const {
        filename     = 'export.xlsx',
        sheetName    = 'Sheet1',
        scope        = 'all',
        includeHidden = false
      } = options

      this.$emit('export-start')
      this.exportState = { active: true }

      const workerPayload = {
        data:         this.data,
        columns:      this.columns,
        // width resolved to a concrete px number (getColW handles px/%/other CSS
        // units) — excelExport.js's char-width math needs a real number, and a
        // worker has no DOM to resolve a raw '20%'/'10em' spec itself.
        leafCols:     this.leafCols.map((col, ci) => ({ ...col, width: this.getColW(ci) })),
        merges:       this.internalMerges,
        hiddenCols:   [...this.effectiveHiddenColSet],
        hiddenRows:   [...this.hiddenRowSet],
        range:        scope === 'selection' ? this.primaryRange : null,
        filename,
        sheetName,
        scope,
        includeHidden
      }

      try {
        const worker = createExcelExportWorker()
        if (worker) {
          await this._exportViaWorker(worker, workerPayload)
        } else {
          // Fallback: synchronous export on main thread
          _exportToExcel({
            ...workerPayload,
            hiddenColSet: this.effectiveHiddenColSet,
            hiddenRowSet: this.hiddenRowSet
          })
        }
        this.$emit('export-success')
      } catch (err) {
        this.$emit('export-error', err)
      } finally {
        this.exportState = { active: false }
      }
    },

    /**
     * Print all (visible) grid data as a plain, theme-independent HTML
     * table — not the styled data-grid itself. Honors hidden columns/rows,
     * merged cells, and footer totals, same sources `exportToExcel()` uses.
     * `type: 'action'` columns (buttons — add/remove row, etc.) are always
     * excluded: they're interactive UI, not printable data.
     */
    printGrid() {
      const rowIndices = []
      for (let ri = 0; ri < this.totalRows; ri++) {
        if (!this.hiddenRowSet.has(ri)) rowIndices.push(ri)
      }
      const printExcludedColSet = new Set(this.effectiveHiddenColSet)
      this.leafCols.forEach(col => { if (col.type === 'action') printExcludedColSet.add(col._flatIndex) })
      const html = buildPrintTableHtml({
        columns: this.columns,
        leafCols: this.leafCols,
        rowIndices,
        merges: this.internalMerges,
        hiddenColSet: printExcludedColSet,
        // Resolved px width per column (same getColW() exportToExcel() uses)
        // so print columns stay proportional to their on-screen width.
        colWidths: this.leafCols.map((col, ci) => this.getColW(ci)),
        getCellText: (ri, ci) => {
          const col = this.leafCols[ci]
          if (col && col.type === 'checkbox') return this.isCheckboxChecked(ri, ci) ? '✓' : ''
          return String(this.getCellDisplayValue(ci, this.getCellValue(ri, ci), ri))
        },
        showFooter: this.hasFooter,
        getFooterText: ci => this.getColumnTotalDisplay(ci),
        printTitle: this.printTitle
      })
      this._openPrintFrame(html)
    },

    // Hidden same-origin <iframe> instead of window.open(): can't be
    // popup-blocked, and works the same when the host app itself runs
    // inside an iframe. srcdoc's document is fully self-contained (its own
    // <style>, nothing inherited from the host page), so the printed table
    // never picks up the grid's current theme.
    _openPrintFrame(html) {
      const iframe = document.createElement('iframe')
      iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;'
      document.body.appendChild(iframe)
      const cleanup = () => { if (iframe.parentNode) iframe.parentNode.removeChild(iframe) }
      iframe.onload = () => {
        const win = iframe.contentWindow
        win.addEventListener('afterprint', cleanup)
        win.focus()
        win.print()
        // Fallback in case `afterprint` never fires (observed on some
        // browsers when the print dialog is dismissed a certain way).
        setTimeout(cleanup, 2000)
      }
      iframe.srcdoc = html
    },

    _exportViaWorker(worker, payload) {
      return new Promise((resolve, reject) => {
        let done = false
        const finish = (fn, val) => {
          if (done) return
          done = true
          worker.terminate()
          fn(val)
        }

        worker.onmessage = (e) => {
          const { type, buffer, filename, message } = e.data
          if (type === 'result') {
            // Trigger browser download from the main thread (DOM required)
            const blob = new Blob([new Uint8Array(buffer)], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const url  = URL.createObjectURL(blob)
            const a    = document.createElement('a')
            a.href     = url
            a.download = filename
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(url)
            finish(resolve)
          } else if (type === 'error') {
            finish(reject, new Error(message))
          }
        }

        worker.onerror = (err) => finish(reject, new Error(err.message || 'Export worker xatosi'))

        worker.postMessage(payload)
      })
    },

    // =========================================================
    // EXCEL IMPORT (3.12)
    // =========================================================
    async importFromFile(file, options = {}) {
      this.importState = { active: true, percent: 5, message: "Fayl o'qilmoqda..." }

      try {
        let result
        const worker = createExcelImportWorker()

        if (worker) {
          result = await this._importViaWorker(worker, file, options)
        } else {
          // Fallback: chunked async on main thread
          result = await _importFromFile(
            file,
            this.columns,
            options,
            (percent, message) => { this.importState = { active: true, percent, message } }
          )
        }

        const { columns, merges } = result
        // Freeze each row so Vue 2 skips deep Object.defineProperty observation.
        // Vue 2 checks Object.isExtensible() — frozen objects are skipped entirely.
        // All edit paths already use spread ({ ...row }) so frozen rows are safe.
        const data = result.data.map(row => Object.freeze(row))
        this.$emit('input', data)
        this._scheduleBufferWrite(data)
        this.$emit('update:columns', columns)

        const hasMerges = merges && merges.length > 0
        this.internalMerges = hasMerges ? merges : []
        this.$emit('update:merges', hasMerges ? merges : [])
        this.$emit('update:collapsedGroups', [])
        this.$emit('update:hiddenRows', [])
        this.$emit('import-success', { data, columns, merges })

        // Reset scroll state and re-derive virtual scroll after DOM settles.
        // Without this, stale scrollTop + old rowHeights cause blank bands on scroll.
        this.rowHeights = {}
        this.scrollTop = 0
        this.scrollLeft = 0
        this.$nextTick(() => {
          if (this.$refs.scrollBody) {
            this.$refs.scrollBody.scrollTop = 0
            this.$refs.scrollBody.scrollLeft = 0
          }
          if (this.$refs.scrollColHeader) this.$refs.scrollColHeader.scrollLeft = 0
          if (this.$refs.scrollFooter) this.$refs.scrollFooter.scrollLeft = 0
          if (this.$refs.scrollRowHeaders) this.$refs.scrollRowHeaders.scrollTop = 0
          this.updateVirtualScroll()
        })
      } catch (err) {
        this.$emit('import-error', err)
      } finally {
        this.importState = { active: false, percent: 0, message: '' }
      }
    },

    _importViaWorker(worker, file, options) {
      return new Promise(async (resolve, reject) => {
        let done = false
        const finish = (fn, val) => {
          if (done) return
          done = true
          worker.terminate()
          fn(val)
        }

        worker.onmessage = (e) => {
          const { type, percent, message, data, columns, merges } = e.data
          if (type === 'progress') {
            this.importState = { active: true, percent, message }
          } else if (type === 'result') {
            finish(resolve, { data, columns, merges })
          } else if (type === 'error') {
            finish(reject, new Error(message))
          }
        }

        worker.onerror = (err) => finish(reject, new Error(err.message || 'Import worker xatosi'))

        try {
          // Transfer the ArrayBuffer zero-copy into the worker
          const buffer = await file.arrayBuffer()
          worker.postMessage(
            { buffer, existingColumns: this.columns, options },
            [buffer]
          )
        } catch (err) {
          finish(reject, err)
        }
      })
    },

    // =========================================================
    // UNDO / REDO (3.13)
    // =========================================================

    // Push one entry onto the non-reactive history stack.
    // Truncates the redo tail, caps at 100 entries.
    _pushHistory(entry) {
      if (this._historyIndex < this._history.length - 1) {
        this._history.splice(this._historyIndex + 1)
      }
      this._history.push(entry)
      if (this._history.length > 100) {
        this._history.shift()
        // historyIndex stays the same — it now points to the new last entry
      } else {
        this._historyIndex++
      }
      this.historyVersion++
    },

    // Emit 'input' and record a data diff entry (only changed row indices).
    // Use slice() + per-row spread in callers so unchanged rows keep the
    // same reference — then the identity check here catches only real changes.
    _emitDataChange(oldData, newData) {
      if (!this._historySkip) {
        const indices = []
        const beforeRows = []
        const afterRows = []
        const len = Math.max(oldData.length, newData.length)
        for (let i = 0; i < len; i++) {
          if (oldData[i] !== newData[i]) {
            indices.push(i)
            beforeRows.push(oldData[i])
            afterRows.push(newData[i])
          }
        }
        if (indices.length > 0) {
          // rowCount lets undo() truncate the array back down when this change
          // added rows (e.g. pasteGrowsRows) — a no-op for every change that
          // doesn't touch row count, since rowCount then matches on both sides.
          this._pushHistory({
            type: 'data',
            before: { indices, rows: beforeRows, rowCount: oldData.length },
            after:  { indices, rows: afterRows, rowCount: newData.length }
          })
        }
      }
      this.$emit('input', newData)
      this._scheduleBufferWrite(newData)
    },

    // Emit 'update:merges' and record a merges diff entry.
    _emitMergeChange(oldMerges, newMerges) {
      if (!this._historySkip) {
        this._pushHistory({
          type: 'merges',
          before: oldMerges,
          after:  newMerges
        })
      }
      this.$emit('update:merges', newMerges)
    },

    undo() {
      if (this.internalLocked) return
      if (this._historyIndex < 0) return
      const entry = this._history[this._historyIndex--]
      this._historySkip = true
      try {
        if (entry.type === 'data') {
          const newData = this.data.slice()
          for (let i = 0; i < entry.before.indices.length; i++) {
            newData[entry.before.indices[i]] = entry.before.rows[i]
          }
          // Assigning `undefined` to a trailing index doesn't shrink the
          // array — truncate explicitly when this entry added rows (e.g.
          // pasteGrowsRows), so undo actually removes them instead of
          // leaving `undefined` rows at the tail.
          if (entry.before.rowCount != null && entry.before.rowCount < newData.length) {
            newData.length = entry.before.rowCount
          }
          this.$emit('input', newData)
          this._scheduleBufferWrite(newData)
        } else if (entry.type === 'merges') {
          this.internalMerges = entry.before.slice()
          this.$emit('update:merges', entry.before.slice())
        }
      } finally {
        this._historySkip = false
        this.historyVersion++
      }
    },

    redo() {
      if (this.internalLocked) return
      if (this._historyIndex >= this._history.length - 1) return
      const entry = this._history[++this._historyIndex]
      this._historySkip = true
      try {
        if (entry.type === 'data') {
          const newData = this.data.slice()
          for (let i = 0; i < entry.after.indices.length; i++) {
            newData[entry.after.indices[i]] = entry.after.rows[i]
          }
          this.$emit('input', newData)
          this._scheduleBufferWrite(newData)
        } else if (entry.type === 'merges') {
          this.internalMerges = entry.after.slice()
          this.$emit('update:merges', entry.after.slice())
        }
      } finally {
        this._historySkip = false
        this.historyVersion++
      }
    },

    // =========================================================
    // TOOLBAR (fullscreen / lock / export / import / custom buttons)
    // =========================================================

    // Public, ref-callable: returns keyboard focus to the grid. Meant for
    // hosts whose action-cell `handler` opens a modal/popup outside the
    // grid's control — call this once that modal closes, otherwise the
    // browser leaves focus on document.body (its subtree was removed) and
    // arrow-key navigation goes dead until a cell is clicked again.
    focus() {
      this.$refs.wrapper && this.$refs.wrapper.focus()
    },

    // Public, ref-callable: formats a number with a custom thousands
    // separator (decimal point stays '.', no forced/padded decimals). Any
    // value that isn't a finite number — already-formatted text like
    // "6 000 000,00", arbitrary strings, etc. — is returned unchanged, so
    // hosts can call this on raw cell values without checking the type first.
    formatNumber(value, separator) {
      return _formatNumber(value, separator)
    },

    // =========================================================
    // LOCAL SYNC — save `data` as a local IndexedDB *version*, keyed by
    // localSyncKey (optionally namespaced by tenant), only when the page is
    // being left (not per-edit).
    // =========================================================

    // Shared by the localSyncKey and tenant watchers above — either one
    // changing means effectiveSyncKey now points at a (possibly) different
    // version history, so the badge/version-list state must be reloaded
    // from scratch rather than left stale.
    _reloadLocalSyncForKeyChange() {
      this.localSyncAvailable = false
      if (this.effectiveSyncKey) this._loadLocalVersionsOnMount()
    },

    // Internal, called once from mounted(): populates the toolbar "unseen
    // local versions" dot and emits local-sync-available if any versions
    // already exist for this key (e.g. saved in an earlier visit).
    async _loadLocalVersionsOnMount() {
      if (!this.localSyncKey) return
      await this._promoteBufferIfAny()
      try {
        const versions = await listVersions(this.effectiveSyncKey)
        if (!versions.length) return
        this.localSyncAvailable = true
        this.$emit('local-sync-available', {
          key: this.localSyncKey,
          versions: versions.length,
          mostRecentUpdatedAt: versions[0].updatedAt
        })
      } catch (error) {
        this.$emit('local-sync-error', { action: 'load', error })
      }
    },

    // Debounced (800ms), called from the grid's own real-change points
    // (_emitDataChange, import, undo, redo — the exact same "user worked"
    // signal _flushLocalVersionOnHide() relies on, never a $watch on `data`,
    // for the same reason spelled out on the localSyncKey prop's JSDoc: a
    // host loading rows from an API must never look like a user edit).
    //
    // Writes to IndexedDB's 'buffer' store (idbStore.js — one row per key, no
    // hash, no history) at a moment with no teardown race at all — the user
    // is actively still on the page. This is what actually fixes reload/
    // close data loss: a version-store write ATTEMPTED at the leave-signal
    // has no guarantee of finishing before an actual page teardown (verified
    // directly — even a trivial, unrelated IndexedDB write failed to survive
    // a real page.reload() in Chromium), but a buffer write that already
    // completed minutes or seconds earlier, during ordinary editing, needs no
    // such guarantee — it's already durably there. _promoteBufferIfAny()
    // turns it into a real version next time the grid mounts.
    _scheduleBufferWrite(data) {
      if (!this.localSyncKey) return
      const key = this.effectiveSyncKey // captured now, not re-read 800ms later —
      // a host that swaps localSyncKey/tenant mid-edit (rare, but now
      // reactive, see the watchers below) must not have this land under the
      // NEW key with the OLD key's data.
      clearTimeout(this._bufferWriteTimer)
      this._bufferWriteTimer = setTimeout(() => { this._writeBufferNow(key, data) }, 800)
    },

    async _writeBufferNow(key, data) {
      if (!key) return
      try {
        await putBuffer(key, data)
      } catch (error) {
        this.$emit('local-sync-error', { action: 'save', error })
      }
    },

    // Called once from _loadLocalVersionsOnMount(), before this key's version
    // list is read — folds a leftover buffer (from an edit that was saved
    // during the PREVIOUS visit but never made it into 'versions' — the
    // reload/close case this whole mechanism exists for) into a real version.
    // No time pressure here, so this uses the Worker-backed hashRowsAsync()
    // like any other non-leave-signal path.
    async _promoteBufferIfAny() {
      try {
        const buffered = await getBuffer(this.effectiveSyncKey)
        if (!buffered) return
        const hash = await hashRowsAsync(buffered.data)
        const { version, overwritten } = await saveOrTouchVersion(
          this.effectiveSyncKey, buffered.data, hash, this.localSyncMaxVersions
        )
        await clearBuffer(this.effectiveSyncKey)
        this.$emit('local-sync-save', {
          key: this.localSyncKey,
          id: version.id,
          rows: buffered.data.length,
          updatedAt: version.updatedAt,
          overwritten
        })
      } catch (error) {
        this.$emit('local-sync-error', { action: 'save', error })
      }
    },

    // `sync: true` — see _flushLocalVersionOnHide()'s comment on why the
    // passive leave-triggers can't afford a Worker round-trip.
    _onVisibilityChangeForLocalSync() {
      if (document.visibilityState === 'hidden') this._flushLocalVersionOnHide(false, true)
    },

    _onPageHideForLocalSync() {
      this._flushLocalVersionOnHide(false, true)
    },

    // The core save-on-leave path — replaces a per-edit autosave (see the
    // localSyncKey prop's JSDoc for why: an autosave tied to "data changed"
    // can't distinguish a user's edit from a host loading rows from an API,
    // and would silently overwrite a user's saved work the moment a host
    // does the latter). Triggered from mounted()'s visibilitychange/pagehide
    // listeners and beforeDestroy() — see those for the three trigger points.
    //
    // Content-hashes the current `data` and either touches an existing local
    // version with the same hash (just refreshes its timestamp — "ustiga
    // yoziladi, alohida versiya qilinmaydi") or creates a brand-new one,
    // evicting the oldest past localSyncMaxVersions (FIFO — see idbStore.js's
    // saveOrTouchVersion()). Never throws — IndexedDB failures become
    // local-sync-error.
    //
    // `force` skips the "nothing changed since the last flush" short-circuit
    // below. The passive triggers (visibilitychange/pagehide/beforeDestroy)
    // fire often on an idle tab and must NOT wake IndexedDB for no reason, so
    // they leave it in place. saveLocalVersionNow() — an explicit, infrequent,
    // host/modal-initiated "checkpoint now" action — passes force so it never
    // silently does nothing: even unchanged data still gets its existing
    // version's timestamp refreshed via the same hash-dedup path, rather than
    // the caller seeing no effect at all.
    //
    // `sync` picks hashRows() (main thread) over the Worker-based
    // hashRowsAsync(). This was a real, observed bug, not a theoretical one:
    // a Worker round-trip (postMessage out, worker computes, postMessage
    // back) is one more hop through the event loop than a page that's
    // actually being torn down (as opposed to merely hidden — e.g. a tab
    // switch, where the page stays alive indefinitely and the extra hop
    // costs nothing) can be relied on to survive. visibilitychange/pagehide/
    // beforeDestroy all fire in exactly that "might be torn down any moment"
    // window, so they hash synchronously to remove that hop — the whole
    // flush then only has the unavoidable async part (the IndexedDB write
    // itself) left, giving it the best realistic chance to land before
    // teardown. saveLocalVersionNow() (an explicit host/modal action with no
    // teardown racing it) keeps the Worker, so hashing a large `data` array
    // doesn't block the main thread during ordinary use.
    async _flushLocalVersionOnHide(force = false, sync = false) {
      if (!this.localSyncKey) return
      if (!force && this.data === this._lastFlushedDataRef) return // nothing changed since the last flush
      const data = this.data
      // Fires independently of the version-save attempt below, started as
      // early as possible — see _scheduleBufferWrite()'s comment. This is
      // the save that's actually likely to survive an imminent teardown;
      // the version-store write below is best-effort on top of it, reliable
      // for the common case (tab switch/background, page stays alive).
      clearTimeout(this._bufferWriteTimer)
      this._writeBufferNow(this.effectiveSyncKey, data)
      try {
        const hash = sync ? hashRows(data) : await hashRowsAsync(data)
        if (this.data !== data) return // data changed again mid-hash — a later flush will catch it
        const { version, overwritten } = await saveOrTouchVersion(
          this.effectiveSyncKey, data, hash, this.localSyncMaxVersions
        )
        this._lastFlushedDataRef = data
        // The version store now has this content durably — the buffer's job
        // for it is done. Best-effort like everything else here: if this
        // doesn't complete before teardown, _promoteBufferIfAny() finds the
        // (now-redundant but harmless, dedup makes it a no-op touch) buffer
        // on next mount anyway.
        clearBuffer(this.effectiveSyncKey).catch(() => {})
        this.$emit('local-sync-save', {
          key: this.localSyncKey,
          id: version.id,
          rows: data.length,
          updatedAt: version.updatedAt,
          overwritten
        })
      } catch (error) {
        this.$emit('local-sync-error', { action: 'save', error })
      }
    },

    // Public, ref-callable: runs the save-on-leave flow immediately, for a
    // host that wants its own explicit "save checkpoint" button instead of
    // waiting for a page-hide. Always goes through IndexedDB (force — see
    // _flushLocalVersionOnHide()), but still through the same hash-dedup
    // logic, so repeated calls with unchanged data don't spam duplicate
    // versions — they just refresh the existing matching version.
    async saveLocalVersionNow() {
      await this._flushLocalVersionOnHide(true)
    },

    // Public, ref-callable: lightweight metadata for every saved version of
    // this localSyncKey, newest first — no row data (use getLocalVersion(id)
    // for that). Powers the built-in modal's list; also usable to build a
    // custom UI.
    async listLocalVersions() {
      if (!this.localSyncKey) return []
      try {
        const versions = await listVersions(this.effectiveSyncKey)
        return versions.map(v => ({ id: v.id, createdAt: v.createdAt, updatedAt: v.updatedAt, rowCount: v.data.length }))
      } catch (error) {
        this.$emit('local-sync-error', { action: 'load', error })
        return []
      }
    },

    // Public, ref-callable: the full { id, data, createdAt, updatedAt } for
    // one saved version, WITHOUT applying it to v-model — the pure "Read"
    // for a custom UI (as opposed to restoreLocalVersion(), which reads AND
    // commits in one step).
    async getLocalVersion(id) {
      try {
        return await getVersion(id)
      } catch (error) {
        this.$emit('local-sync-error', { action: 'load', error })
        return null
      }
    },

    // Public, ref-callable: writes one saved version back into v-model
    // (input/update:data) — the modal's "Restore" button calls this too.
    async restoreLocalVersion(id) {
      try {
        const version = await this.getLocalVersion(id)
        if (!version) return
        this.$emit('input', version.data)
        this.$emit('update:data', version.data)
        this._lastFlushedDataRef = version.data // what's now on screen is already what's stored
        this.localSyncAvailable = false
        this.$emit('local-sync-restore', { key: this.localSyncKey, id, rows: version.data.length })
        this.closeLocalSyncModal()
      } catch (error) {
        this.$emit('local-sync-error', { action: 'restore', error })
      }
    },

    // Public, ref-callable: deletes one saved version — the modal's "Delete"
    // button calls this too (after its own inline confirm step).
    async deleteLocalVersion(id) {
      try {
        await deleteVersion(id)
        if (this.localSyncModal.selectedId === id) {
          this.localSyncModal.selectedId = null
          this.localSyncModal.selectedVersion = null
        }
        this.localSyncModal.versions = this.localSyncModal.versions.filter(v => v.id !== id)
        this.$emit('local-sync-clear', { key: this.localSyncKey, id })
      } catch (error) {
        this.$emit('local-sync-error', { action: 'clear', error })
      }
    },

    // Public, ref-callable: opens the local-sync modal (also reachable via
    // the toolbar button), loading the version list fresh each time.
    async openLocalSyncModal() {
      if (!this.localSyncKey) return
      this.localSyncModal.visible = true
      this.localSyncAvailable = false // the version(s) have now been seen
      const versions = await this.listLocalVersions()
      this.localSyncModal.versions = versions
      await this._selectLocalSyncModalVersion(versions.length ? versions[0].id : null)
    },

    // Internal: modal's list-selection handler — loads the selected
    // version's full data for the nested-grid preview (EgLocalSyncModal.vue).
    async _selectLocalSyncModalVersion(id) {
      this.localSyncModal.selectedId = id
      this.localSyncModal.selectedVersion = id ? await this.getLocalVersion(id) : null
    },

    // Modal's "Save" button — same as saveLocalVersionNow(), then refreshes
    // the modal's own list/selection in place so the user sees it happened.
    async _onLocalSyncModalSave() {
      await this.saveLocalVersionNow()
      const versions = await this.listLocalVersions()
      this.localSyncModal.versions = versions
      await this._selectLocalSyncModalVersion(versions.length ? versions[0].id : null)
    },

    // Modal's "Delete" button (after its own inline confirm) — deletes the
    // given version, then selects the next-most-recent one if the deleted
    // one was selected.
    async _onLocalSyncModalDelete(id) {
      await this.deleteLocalVersion(id)
      if (this.localSyncModal.selectedId == null) {
        const remaining = this.localSyncModal.versions
        await this._selectLocalSyncModalVersion(remaining.length ? remaining[0].id : null)
      }
    },

    // Public, ref-callable.
    closeLocalSyncModal() {
      this.localSyncModal.visible = false
    },

    toggleLock() {
      this.internalLocked = !this.internalLocked
      this.$emit('update:locked', this.internalLocked)
      this.$emit('lock-change', { locked: this.internalLocked })
      this._flashLock(this.internalLocked)
    },

    // Pops a big lock/unlock icon in the center of the grid and fades it
    // out — pure visual feedback, mirrors the video-player OSD pattern.
    // Triggered by the internalLocked watcher, so it covers every path that
    // can change the lock state (toolbar click, toggleLock(), :locked.sync).
    _flashLock(locked) {
      this.lockFlashLocked = locked
      this.lockFlashVisible = true
      this.$nextTick(() => {
        const el = this.$refs.lockFlashIconEl
        if (!el) return
        anime.remove(el)
        anime.set(el, { opacity: 0, scale: 0.5 })
        anime.timeline()
          .add({ targets: el, opacity: 1, scale: 1.12, duration: 180, easing: 'easeOutBack' })
          .add({ targets: el, scale: 1, duration: 120, easing: 'easeOutQuad' })
          .add({ targets: el, opacity: 0, duration: 350, easing: 'easeInQuad' }, '+=250')
          .finished.then(() => { this.lockFlashVisible = false })
      })
    },

    toolbarHas(key) {
      return this._toolbarList.indexOf(key) !== -1
    },

    toolbarDisabled(key) {
      return this._toolbarDisabledList.indexOf(key) !== -1
    },

    setSize(newSize) {
      if (!SIZE_CONFIG[newSize] || newSize === this.internalSize) return
      this.internalSize = newSize
      this.$emit('update:size', newSize)
      this.$emit('size-change', { size: newSize })
    },

    setTheme(newTheme) {
      if (THEME_LIST.indexOf(newTheme) === -1 || newTheme === this.internalTheme) return
      this.internalTheme = newTheme
      this.$emit('update:theme', newTheme)
      this.$emit('theme-change', { theme: newTheme })
    },

    sizeTitle(key) {
      return { small: this.t.sizeSmall, middle: this.t.sizeMiddle, large: this.t.sizeLarge }[key] || key
    },

    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      if (this.isFullscreen) {
        this._prevBodyOverflow = document.body.style.overflow
        document.body.style.overflow = 'hidden'
        document.addEventListener('keydown', this._onFullscreenKeyDown)
      } else {
        document.body.style.overflow = this._prevBodyOverflow || ''
        document.removeEventListener('keydown', this._onFullscreenKeyDown)
      }
      this.$emit('fullscreen-change', { fullscreen: this.isFullscreen })
      this.$nextTick(() => this.updateVirtualScroll())
    },

    _onFullscreenKeyDown(e) {
      if (e.key === 'Escape' && this.isFullscreen) this.toggleFullscreen()
    },

    toolbarExportClick() {
      this.exportToExcel()
    },

    toolbarImportClick() {
      if (this.internalLocked) return
      const input = this.$refs.toolbarImportInput
      if (input) input.click()
    },

    onToolbarImportFile(e) {
      const file = e.target.files && e.target.files[0]
      e.target.value = ''
      if (!file || this.internalLocked) return
      this.importFromFile(file)
    },

    onToolbarButtonClick(btn, event) {
      if (typeof btn.onClick === 'function') btn.onClick(event, this)
    }
  }
}

export default ExcelGridComponent
</script>

<style scoped>
.eg-shell {
  /* ── Design tokens (Excel 365 defaults) — override on :root or any ancestor of <excel-grid> ──
     Full reference: docs/theming.md
  */
  /* Tokens are defined on this element and cascade to all children */

  /* --- Typography --- */
  --eg-font-family-default: 'Calibri', 'Segoe UI', Arial, sans-serif;
  --eg-font-size-default: 14px;
  --eg-font-size-header-default: 11px;

  /* --- Shape --- */
  --eg-radius-default: 0px;
  --eg-cell-padding-x-default: 3px;

  /* --- Accent (Excel green) --- */
  --eg-color-accent-default: #217346;
  --eg-color-accent-dark-default: #185a30;
  --eg-color-accent-soft-default: rgba(33, 115, 70, 0.15);

  /* --- Error / Validation --- */
  --eg-color-error-default: #c00000;
  --eg-color-error-soft-default: #fff2f2;
  --eg-color-error-dark-default: #9b0000;

  /* --- Borders --- */
  --eg-color-border-default: #d9d9d9;
  --eg-color-border-cell-default: #d9d9d9;
  --eg-color-border-strong-default: #bfbfbf;

  /* --- Header --- */
  --eg-color-header-bg-default: #f2f2f2;
  --eg-color-header-group-bg-default: #f2f2f2;
  --eg-color-group-border-default: #92d050;
  --eg-color-group-bg-collapsed-default: #70ad47;

  /* --- Cell states --- */
  --eg-color-cell-bg-default: #ffffff;
  --eg-color-cell-selected-default: #bdd7ee;
  --eg-color-cell-fill-preview-default: #9bc2e6;
  --eg-color-cell-readonly-default: #f2f2f2;
  --eg-color-cell-readonly-selected-default: #a9c9e4;
  --eg-color-cell-readonly-pattern-default: rgba(0, 0, 0, 0.06);
  --eg-color-footer-bg-default: #f2f2f2;

  /* --- Text --- */
  --eg-color-text-default: #000000;
  --eg-color-text-secondary-default: #595959;
  --eg-color-text-muted-default: #767676;

  /* --- Shadows --- */
  --eg-shadow-dropdown-default: 1px 2px 8px rgba(0, 0, 0, 0.18);
  --eg-shadow-dialog-default: 0 2px 12px rgba(0, 0, 0, 0.22);
  --eg-shadow-tooltip-default: 0 1px 4px rgba(0, 0, 0, 0.18);
  --eg-color-freeze-shadow-default: rgba(0, 0, 0, 0.12);

  /* --- Overlay & dropdown options --- */
  --eg-color-overlay-bg-default: rgba(255, 255, 255, 0.88);
  --eg-color-option-hover-bg-default: #e2efda;
  --eg-color-option-active-hover-bg-default: #c6e0b4;

  /* --- Checkbox --- */
  --eg-color-checkbox-border-default: #767676;
  --eg-color-checkbox-disabled-checked-default: #bfbfbf;

  /* --- Row effects (off by default) --- */
  --eg-color-row-hover-default: transparent;
  --eg-color-row-stripe-default: transparent;

  box-sizing: border-box;
  font-family: var(--eg-font-family, var(--eg-font-family-default));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  overflow: hidden;
}

.eg-shell-fullscreen {
  position: fixed;
  inset: 0;
  z-index: 9999;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 0;
  overflow: hidden;
}

/* ── Material Design 3 — ko'k-ranglantirilgan header, 8px radius ── */
.eg-shell.eg-theme-material {
  --eg-font-family-default: 'Roboto', 'Google Sans', Arial, sans-serif;
  --eg-font-size-default: 13px;
  --eg-font-size-header-default: 11px;
  --eg-radius-default: 8px;
  --eg-cell-padding-x-default: 6px;

  --eg-color-accent-default: #1565C0;
  --eg-color-accent-dark-default: #0D47A1;
  --eg-color-accent-soft-default: #DBEAFE;

  --eg-color-error-default: #D32F2F;
  --eg-color-error-soft-default: #FFEBEE;
  --eg-color-error-dark-default: #B71C1C;

  /* Ko'k chegaralar — Excel'dan aniq farqli */
  --eg-color-border-default: #90CAF9;
  --eg-color-border-cell-default: #BBDEFB;
  --eg-color-border-strong-default: #64B5F6;

  /* Ko'k-ranglantirilgan header — eng ko'zga ko'rinuvchi farq */
  --eg-color-header-bg-default: #DBEAFE;
  --eg-color-header-group-bg-default: #BFDBFE;
  --eg-color-group-border-default: #1565C0;
  --eg-color-group-bg-collapsed-default: #0D47A1;

  --eg-color-cell-bg-default: #FFFFFF;
  --eg-color-cell-selected-default: #BFDBFE;
  --eg-color-cell-fill-preview-default: #93C5FD;
  --eg-color-cell-readonly-default: #EFF6FF;
  --eg-color-cell-readonly-selected-default: #DBEAFE;
  --eg-color-cell-readonly-pattern-default: rgba(21, 101, 192, 0.08);
  --eg-color-footer-bg-default: #EFF6FF;

  --eg-color-text-default: #1E3A5F;
  --eg-color-text-secondary-default: #4B7BA8;
  --eg-color-text-muted-default: #93C5FD;

  --eg-shadow-dropdown-default: 0 4px 12px rgba(21,101,192,0.20), 0 1px 4px rgba(21,101,192,0.12);
  --eg-shadow-dialog-default: 0 6px 24px rgba(21,101,192,0.18);
  --eg-shadow-tooltip-default: 0 2px 6px rgba(21,101,192,0.20);
  --eg-color-freeze-shadow-default: rgba(21,101,192,0.20);

  --eg-color-overlay-bg-default: rgba(239,246,255,0.94);
  --eg-color-option-hover-bg-default: #EFF6FF;
  --eg-color-option-active-hover-bg-default: #DBEAFE;

  --eg-color-checkbox-border-default: #64B5F6;
  --eg-color-checkbox-disabled-checked-default: #BBDEFB;

  /* Ko'k hover va stripe */
  --eg-color-row-hover-default: #EFF6FF;
  --eg-color-row-stripe-default: #F0F7FF;
}

/* ── Ant Design 5 — minimal, toza, 6px radius ─────────────────── */
.eg-shell.eg-theme-antd {
  --eg-font-family-default: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  --eg-font-size-default: 13px;
  --eg-font-size-header-default: 12px;
  --eg-radius-default: 6px;
  --eg-cell-padding-x-default: 8px;

  --eg-color-accent-default: #1677FF;
  --eg-color-accent-dark-default: #0958D9;
  --eg-color-accent-soft-default: #E6F4FF;

  --eg-color-error-default: #FF4D4F;
  --eg-color-error-soft-default: #FFF2F0;
  --eg-color-error-dark-default: #CF1322;

  /* Ant: ingichka kulrang chegaralar */
  --eg-color-border-default: #D9D9D9;
  --eg-color-border-cell-default: #F0F0F0;
  --eg-color-border-strong-default: #BFBFBF;

  /* Ant header: mo'tadil ko'k-kulrang, zamonaviy jadval uslubi */
  --eg-color-header-bg-default: #F0F5FF;
  --eg-color-header-group-bg-default: #E6EEFF;
  --eg-color-group-border-default: #1677FF;
  --eg-color-group-bg-collapsed-default: #0958D9;

  --eg-color-cell-bg-default: #FFFFFF;
  --eg-color-cell-selected-default: #E6F4FF;
  --eg-color-cell-fill-preview-default: #BAE0FF;
  --eg-color-cell-readonly-default: #FAFAFA;
  --eg-color-cell-readonly-selected-default: #D6EEFF;
  --eg-color-cell-readonly-pattern-default: rgba(0, 0, 0, 0.06);
  --eg-color-footer-bg-default: #F0F5FF;

  --eg-color-text-default: rgba(0,0,0,0.88);
  --eg-color-text-secondary-default: rgba(0,0,0,0.45);
  --eg-color-text-muted-default: rgba(0,0,0,0.25);

  --eg-shadow-dropdown-default: 0 6px 16px rgba(0,0,0,0.08), 0 3px 6px rgba(0,0,0,0.12), 0 9px 28px 8px rgba(0,0,0,0.05);
  --eg-shadow-dialog-default: 0 6px 16px rgba(0,0,0,0.08);
  --eg-shadow-tooltip-default: 0 2px 8px rgba(0,0,0,0.15);
  --eg-color-freeze-shadow-default: rgba(0,0,0,0.10);

  --eg-color-overlay-bg-default: rgba(255,255,255,0.92);
  --eg-color-option-hover-bg-default: #E6F4FF;
  --eg-color-option-active-hover-bg-default: #BAE0FF;

  --eg-color-checkbox-border-default: #D9D9D9;
  --eg-color-checkbox-disabled-checked-default: #BFBFBF;

  /* Ant hover: ko'zga ko'rinuvchi ko'k tint */
  --eg-color-row-hover-default: #E6F4FF;
  --eg-color-row-stripe-default: #FAFBFF;
}

/* ── Fluent UI / Office 365 — iliq kulrang, 2px radius ─────────── */
.eg-shell.eg-theme-fluent {
  --eg-font-family-default: 'Segoe UI', Calibri, Arial, sans-serif;
  --eg-font-size-default: 13px;
  --eg-font-size-header-default: 11px;
  --eg-radius-default: 2px;
  --eg-cell-padding-x-default: 5px;

  --eg-color-accent-default: #0078D4;
  --eg-color-accent-dark-default: #005EA6;
  --eg-color-accent-soft-default: #EBF3FB;

  --eg-color-error-default: #C50F1F;
  --eg-color-error-soft-default: #FDE7E9;
  --eg-color-error-dark-default: #A80000;

  /* Fluent: iliq kulrang chegaralar */
  --eg-color-border-default: #D2D0CE;
  --eg-color-border-cell-default: #EDEBE9;
  --eg-color-border-strong-default: #B3B0AD;

  /* Fluent header: iliq kulrang (Office 365 uslubi) */
  --eg-color-header-bg-default: #E9E7E4;
  --eg-color-header-group-bg-default: #DDD9D4;
  --eg-color-group-border-default: #0078D4;
  --eg-color-group-bg-collapsed-default: #005EA6;

  --eg-color-cell-bg-default: #FFFFFF;
  --eg-color-cell-selected-default: #DEECF9;
  --eg-color-cell-fill-preview-default: #C7E0F4;
  --eg-color-cell-readonly-default: #F3F2F1;
  --eg-color-cell-readonly-selected-default: #D0E8F8;
  --eg-color-cell-readonly-pattern-default: rgba(50, 49, 48, 0.06);
  --eg-color-footer-bg-default: #E9E7E4;

  --eg-color-text-default: #323130;
  --eg-color-text-secondary-default: #605E5C;
  --eg-color-text-muted-default: #A19F9D;

  --eg-shadow-dropdown-default: 0 3.2px 7.2px rgba(0,0,0,0.132), 0 0.6px 1.8px rgba(0,0,0,0.108);
  --eg-shadow-dialog-default: 0 8px 16px rgba(0,0,0,0.14);
  --eg-shadow-tooltip-default: 0 2px 6px rgba(0,0,0,0.12);
  --eg-color-freeze-shadow-default: rgba(0,0,0,0.14);

  --eg-color-overlay-bg-default: rgba(255,255,255,0.92);
  --eg-color-option-hover-bg-default: #F3F2F1;
  --eg-color-option-active-hover-bg-default: #DEECF9;

  --eg-color-checkbox-border-default: #8A8886;
  --eg-color-checkbox-disabled-checked-default: #C8C6C4;

  /* Fluent: iliq hover */
  --eg-color-row-hover-default: #F3F2F1;
  --eg-color-row-stripe-default: #FAF9F8;
}

/* ── IBM Carbon — to'q kulrang header, zebra stripe, 0px radius ── */
.eg-shell.eg-theme-carbon {
  --eg-font-family-default: 'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif;
  --eg-font-size-default: 14px;
  --eg-font-size-header-default: 12px;
  --eg-radius-default: 0px;
  --eg-cell-padding-x-default: 16px;

  --eg-color-accent-default: #0F62FE;
  --eg-color-accent-dark-default: #0043CE;
  --eg-color-accent-soft-default: #D0E2FF;

  --eg-color-error-default: #DA1E28;
  --eg-color-error-soft-default: #FFF1F1;
  --eg-color-error-dark-default: #A2191F;

  /* Carbon: og'ir kulrang chegaralar (Gray-20 / Gray-50) */
  --eg-color-border-default: #C6C6C6;
  --eg-color-border-cell-default: #E0E0E0;
  --eg-color-border-strong-default: #8D8D8D;

  /* Carbon: to'q kulrang header — Excel'dan eng aniq farq */
  --eg-color-header-bg-default: #C1C7CD;
  --eg-color-header-group-bg-default: #A2A9B0;
  --eg-color-group-border-default: #0F62FE;
  --eg-color-group-bg-collapsed-default: #0043CE;

  --eg-color-cell-bg-default: #FFFFFF;
  --eg-color-cell-selected-default: #D0E2FF;
  --eg-color-cell-fill-preview-default: #A6C8FF;
  --eg-color-cell-readonly-default: #F4F4F4;
  --eg-color-cell-readonly-selected-default: #BDD6FF;
  --eg-color-cell-readonly-pattern-default: rgba(0, 0, 0, 0.08);
  --eg-color-footer-bg-default: #C1C7CD;

  --eg-color-text-default: #161616;
  --eg-color-text-secondary-default: #525252;
  --eg-color-text-muted-default: #8D8D8D;

  --eg-shadow-dropdown-default: 0 2px 6px rgba(0,0,0,0.30);
  --eg-shadow-dialog-default: 0 2px 6px rgba(0,0,0,0.30);
  --eg-shadow-tooltip-default: 0 2px 6px rgba(0,0,0,0.30);
  --eg-color-freeze-shadow-default: rgba(0,0,0,0.25);

  --eg-color-overlay-bg-default: rgba(255,255,255,0.88);
  --eg-color-option-hover-bg-default: #E8E8E8;
  --eg-color-option-active-hover-bg-default: #D0E2FF;

  --eg-color-checkbox-border-default: #8D8D8D;
  --eg-color-checkbox-disabled-checked-default: #C6C6C6;

  /* Carbon: ko'zga ko'rinuvchi zebra stripe */
  --eg-color-row-hover-default: #E8E8E8;
  --eg-color-row-stripe-default: #F4F4F4;
}

.eg-wrapper {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  font-family: var(--eg-font-family, var(--eg-font-family-default));
}

.eg-toolbar {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
  height: 36px;
  padding: 0 8px;
  box-sizing: border-box;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  border-bottom: 1px solid var(--eg-color-border, var(--eg-color-border-default));
}

.eg-toolbar-group {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 0 4px;
}

.eg-toolbar-group + .eg-toolbar-group {
  border-left: 1px solid var(--eg-color-border, var(--eg-color-border-default));
}

.eg-toolbar-spacer {
  flex: 1 1 auto;
}

.eg-toolbar-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  padding: 0;
  border: 1px solid transparent;
  border-radius: 3px;
  background: transparent;
  cursor: pointer;
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default));
}

/* Anchors the "unseen local draft" dot (localSyncKey feature) — only the
   local-sync button carries it, but kept as its own class so any future
   badged tool gets the same positioning. */
.eg-toolbar-btn-badged {
  position: relative;
}
.eg-toolbar-badge {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--eg-color-accent, var(--eg-color-accent-default));
  pointer-events: none;
}
.eg-toolbar-btn:hover:not(:disabled) {
  background: var(--eg-color-option-hover-bg, var(--eg-color-option-hover-bg-default));
  border-color: var(--eg-color-border, var(--eg-color-border-default));
}

.eg-toolbar-btn:disabled {
  opacity: 0.4;
  cursor: default;
}

.eg-toolbar-btn-active {
  background: var(--eg-color-accent-soft, var(--eg-color-accent-soft-default));
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
  color: var(--eg-color-accent-dark, var(--eg-color-accent-dark-default));
}

.eg-toolbar-select {
  height: 26px;
  padding: 0 22px 0 8px;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: 3px;
  background-color: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  /* Stroke-based chevron (round caps/joins) instead of a solid triangle, to
     match the rounded-line language the rest of the toolbar icons use. */
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23888' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 7px center;
  background-size: 9px 6px;
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default));
  font-size: 12px;
  font-family: var(--eg-font-family, var(--eg-font-family-default));
  cursor: pointer;
  appearance: none;
  -webkit-appearance: none;
  outline: none;
}

.eg-toolbar-select:hover:not(:disabled) {
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
}

.eg-toolbar-select:focus {
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
  box-shadow: 0 0 0 2px var(--eg-color-accent-soft, var(--eg-color-accent-soft-default));
}

.eg-toolbar-select:disabled {
  opacity: 0.4;
  cursor: default;
}

.eg-toolbar-segmented {
  display: flex;
  align-items: center;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: 4px;
  overflow: hidden;
  padding: 1px;
  gap: 1px;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
}

.eg-toolbar-segment {
  border-radius: 2px;
}

/* Higher specificity than .eg-size-{x} .eg-toolbar-icon so each segment keeps its
   own progressively-sized icon regardless of the grid's current size variant. */
.eg-toolbar-segmented .eg-toolbar-segment-small .eg-toolbar-icon  { width: 12px; height: 12px; }
.eg-toolbar-segmented .eg-toolbar-segment-middle .eg-toolbar-icon { width: 15px; height: 15px; }
.eg-toolbar-segmented .eg-toolbar-segment-large .eg-toolbar-icon  { width: 18px; height: 18px; }

.eg-toolbar-icon {
  display: inline-block;
  width: 15px;
  height: 15px;
  background-color: currentColor;
  mask-size: contain;
  mask-repeat: no-repeat;
  mask-position: center;
  -webkit-mask-size: contain;
  -webkit-mask-repeat: no-repeat;
  -webkit-mask-position: center;
}

.eg-icon-undo    { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 15 4 10 9 5'/%3E%3Cpath d='M4 10h11a5 5 0 0 1 5 5'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 15 4 10 9 5'/%3E%3Cpath d='M4 10h11a5 5 0 0 1 5 5'/%3E%3C/svg%3E"); }
.eg-icon-redo    { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 15 20 10 15 5'/%3E%3Cpath d='M20 10H9a5 5 0 0 0-5 5'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 15 20 10 15 5'/%3E%3Cpath d='M20 10H9a5 5 0 0 0-5 5'/%3E%3C/svg%3E"); }
/* Cloud-upload / cloud-download — replaces the old "document with arrow" glyphs
   so Export/Import read as one coherent rounded-line icon family with the
   rest of the toolbar. */
.eg-icon-export  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M7 18a4.6 4.4 0 0 1 0-9a5 4.5 0 0 1 11 2h1a3.5 3.5 0 0 1 0 7h-1'/%3E%3Cpath d='M9 15l3-3 3 3'/%3E%3Cpath d='M12 12v9'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M7 18a4.6 4.4 0 0 1 0-9a5 4.5 0 0 1 11 2h1a3.5 3.5 0 0 1 0 7h-1'/%3E%3Cpath d='M9 15l3-3 3 3'/%3E%3Cpath d='M12 12v9'/%3E%3C/svg%3E"); }
.eg-icon-import  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M19 18a3.5 3.5 0 0 0 0-7h-1a5 4.5 0 0 0-11-2a4.6 4.4 0 0 0-1 9'/%3E%3Cpath d='M9 16l3 3 3-3'/%3E%3Cpath d='M12 10v9'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M19 18a3.5 3.5 0 0 0 0-7h-1a5 4.5 0 0 0-11-2a4.6 4.4 0 0 0-1 9'/%3E%3Cpath d='M9 16l3 3 3-3'/%3E%3Cpath d='M12 10v9'/%3E%3C/svg%3E"); }
.eg-icon-print   { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 6 2 18 2 18 9'/%3E%3Cpath d='M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2'/%3E%3Crect x='6' y='14' width='12' height='8'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 6 2 18 2 18 9'/%3E%3Cpath d='M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2'/%3E%3Crect x='6' y='14' width='12' height='8'/%3E%3C/svg%3E"); }
.eg-icon-local-sync { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cellipse cx='12' cy='5' rx='9' ry='3'/%3E%3Cpath d='M3 5v14a9 3 0 0 0 18 0V5'/%3E%3Cpath d='M3 12a9 3 0 0 0 18 0'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cellipse cx='12' cy='5' rx='9' ry='3'/%3E%3Cpath d='M3 5v14a9 3 0 0 0 18 0V5'/%3E%3Cpath d='M3 12a9 3 0 0 0 18 0'/%3E%3C/svg%3E"); }
.eg-icon-lock    { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='11' width='16' height='9' rx='2'/%3E%3Cpath d='M7 11V7a5 5 0 0 1 10 0v4'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='11' width='16' height='9' rx='2'/%3E%3Cpath d='M7 11V7a5 5 0 0 1 10 0v4'/%3E%3C/svg%3E"); }
.eg-icon-unlock  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='11' width='16' height='9' rx='2'/%3E%3Cpath d='M7 11V7a5 5 0 0 1 9.5-2'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='4' y='11' width='16' height='9' rx='2'/%3E%3Cpath d='M7 11V7a5 5 0 0 1 9.5-2'/%3E%3C/svg%3E"); }
/* Maximize / minimize — two diagonal corner arrows instead of four separate
   brackets, matching the export/import arrows' visual weight. */
.eg-icon-expand  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 4h5v5'/%3E%3Cpath d='M20 4l-7 7'/%3E%3Cpath d='M9 20H4v-5'/%3E%3Cpath d='M4 20l7-7'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 4h5v5'/%3E%3Cpath d='M20 4l-7 7'/%3E%3Cpath d='M9 20H4v-5'/%3E%3Cpath d='M4 20l7-7'/%3E%3C/svg%3E"); }
.eg-icon-compress{ mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 9h-5V4'/%3E%3Cpath d='M20 4l-7 7'/%3E%3Cpath d='M4 15h5v5'/%3E%3Cpath d='M4 20l7-7'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 9h-5V4'/%3E%3Cpath d='M20 4l-7 7'/%3E%3Cpath d='M4 15h5v5'/%3E%3Cpath d='M4 20l7-7'/%3E%3C/svg%3E"); }

/* Sort icon (header) — "more actions" trigger (kebab dots) that opens the sort
   popup menu; faint until hover/active, accent-colored while this column is
   the active sort (see .eg-sort-icon-active below). Same glyph in every
   state — direction is shown inside the popup menu, not on the icon. */
.eg-icon-sort-menu { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='5' r='2'/%3E%3Ccircle cx='12' cy='12' r='2'/%3E%3Ccircle cx='12' cy='19' r='2'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='5' r='2'/%3E%3Ccircle cx='12' cy='12' r='2'/%3E%3Ccircle cx='12' cy='19' r='2'/%3E%3C/svg%3E"); }

/* Size segmented control — each icon shows row density as three stroked lines
   (round caps, same visual language as the rest of the toolbar now — thin +
   tight spacing → small, thick + wide spacing → large), replacing the old
   filled-rect bars. */
.eg-icon-size-small  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.5' stroke-linecap='round'%3E%3Cpath d='M4 7h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 17h16'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.5' stroke-linecap='round'%3E%3Cpath d='M4 7h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 17h16'/%3E%3C/svg%3E"); }
.eg-icon-size-middle { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M4 6h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 18h16'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M4 6h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 18h16'/%3E%3C/svg%3E"); }
.eg-icon-size-large  { mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M4 5h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 19h16'/%3E%3C/svg%3E"); -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2.5' stroke-linecap='round'%3E%3Cpath d='M4 5h16'/%3E%3Cpath d='M4 12h16'/%3E%3Cpath d='M4 19h16'/%3E%3C/svg%3E"); }

.eg-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: auto;
  position: relative;
}

.eg-header-area {
  display: flex;
  flex-shrink: 0;
  box-shadow: 0 2px 0 0 var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  position: relative;
  z-index: 31;
}

.eg-header-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border-right: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-bottom: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
  font-size: var(--eg-font-size-header, var(--eg-font-size-header-default));
  font-weight: 600;
  overflow: hidden;
  white-space: nowrap;
  position: absolute;
  user-select: none;
  cursor: pointer;
}

.eg-header-cell:hover { background: var(--eg-color-border-cell, var(--eg-color-border-cell-default)); }
.eg-header-group { background: var(--eg-color-header-group-bg, var(--eg-color-header-group-bg-default)); }

.eg-sort-icon {
  display: inline-block;
  width: 11px;
  height: 11px;
  margin-left: 4px;
  vertical-align: middle;
  flex-shrink: 0;
  background-color: currentColor;
  mask-size: contain;
  mask-repeat: no-repeat;
  mask-position: center;
  -webkit-mask-size: contain;
  -webkit-mask-repeat: no-repeat;
  -webkit-mask-position: center;
  cursor: pointer;
  opacity: 0.3;
}
.eg-header-cell:hover .eg-sort-icon { opacity: 0.65; }
.eg-sort-icon:hover { opacity: 1; }
.eg-sort-icon.eg-sort-icon-active {
  opacity: 1;
  color: var(--eg-color-accent, var(--eg-color-accent-default));
}

/* ===== FILTER ROW ===== */
.eg-filter-cell {
  box-sizing: border-box;
  padding: 3px 4px;
  border-right: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-bottom: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
  position: absolute;
  display: flex;
  align-items: center;
}
.eg-filter-cell-empty { background: var(--eg-color-header-bg, var(--eg-color-header-bg-default)); }

.eg-filter-input,
.eg-filter-select {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  color: var(--eg-color-text, var(--eg-color-text-default));
  font-size: var(--eg-font-size-header, var(--eg-font-size-header-default));
  font-family: var(--eg-font-family, var(--eg-font-family-default));
  font-weight: 400;
  padding: 0 6px;
  outline: none;
}
.eg-filter-input:focus,
.eg-filter-select:focus {
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
  box-shadow: 0 0 0 2px var(--eg-color-accent-soft, var(--eg-color-accent-soft-default));
}
.eg-filter-select {
  appearance: none;
  -webkit-appearance: none;
  cursor: pointer;
  padding-right: 20px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%23888'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 6px center;
  background-size: 8px 5px;
}

.eg-col-resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 5px;
  cursor: col-resize;
  z-index: 5;
}

.eg-body-area {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* ===== FOOTER AREA (column totals) ===== */
.eg-frozen-col-footer,
.eg-scroll-col-footer,
.eg-pinned-right-footer {
  position: relative;
}

.eg-footer-cell {
  box-sizing: border-box;
  border-right: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  overflow: hidden;
  white-space: nowrap;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  font-weight: 600;
  padding: 0 var(--eg-cell-padding-x, var(--eg-cell-padding-x-default));
  position: absolute;
  top: 0;
  background: var(--eg-color-footer-bg, var(--eg-color-footer-bg-default));
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

/* Cells that actually show a computed total (col.showTotal / totalConfig.visible)
   stand out from the rest of the (otherwise mostly-empty) footer row. */
.eg-footer-cell-total {
  font-weight: 700;
}

.eg-row {
  position: relative;
}

.eg-cell {
  box-sizing: border-box;
  border-right: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-bottom: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  overflow: hidden;
  white-space: nowrap;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  padding: 0 var(--eg-cell-padding-x, var(--eg-cell-padding-x-default));
  position: absolute;
  top: 0;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  cursor: default;
  display: flex;
  align-items: center;
}

.eg-locked .eg-cell { cursor: not-allowed; }

.eg-cell-value {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}
.eg-cell-align-right  { justify-content: flex-end; }
.eg-cell-align-center { justify-content: center; }
/* .eg-cell-value is flex:1 (v1.1.126, to shrink/ellipsize correctly), so it
   always fills the cell's full width — .eg-cell-align-*'s justify-content
   above has no leftover space left to act on and never visibly moves it.
   Same root cause .eg-cell-action-wrap already works around below; apply the
   same fix here via text-align on the value span itself. */
.eg-cell-align-right  .eg-cell-value { text-align: right; }
.eg-cell-align-center .eg-cell-value { text-align: center; }
.eg-cell--has-suffix.eg-cell-select::after { display: none; }
.eg-cell-select-trigger-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  overflow: hidden;
  min-width: 0;
}
.eg-cell-select-caret-inline {
  flex-shrink: 0;
  color: var(--eg-color-text-muted, var(--eg-color-text-muted-default));
  font-size: 11px;
  margin-left: 2px;
}
.eg-cell-suffix-wrap {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
}
.eg-cell-active {
  outline: 2px solid var(--eg-color-accent, var(--eg-color-accent-default)) !important;
  outline-offset: -2px;
  z-index: 3;
}

.eg-cell-selected {
  background: var(--eg-color-cell-selected, var(--eg-color-cell-selected-default)) !important;
}

/* Outer-perimeter border for a multi-cell selection/paste range — .eg-cell
   already has box-sizing:border-box and its own border-right/border-bottom
   grid lines, so these directional overrides don't shift cell layout. */
.eg-cell-range-top {
  border-top: 2px solid var(--eg-color-accent, var(--eg-color-accent-default)) !important;
}
.eg-cell-range-bottom {
  border-bottom: 2px solid var(--eg-color-accent, var(--eg-color-accent-default)) !important;
}
.eg-cell-range-left {
  border-left: 2px solid var(--eg-color-accent, var(--eg-color-accent-default)) !important;
}
.eg-cell-range-right {
  border-right: 2px solid var(--eg-color-accent, var(--eg-color-accent-default)) !important;
}

.eg-cell-fill-preview {
  background: var(--eg-color-cell-fill-preview, var(--eg-color-cell-fill-preview-default)) !important;
  outline: 1px dashed var(--eg-color-accent-dark, var(--eg-color-accent-dark-default));
  outline-offset: -1px;
}

.eg-cell-copy {
  outline: 1px dashed var(--eg-color-accent, var(--eg-color-accent-default));
  outline-offset: -1px;
}

.eg-cell-merged-hidden {
  display: none !important;
}

.eg-cell-invalid {
  outline: 2px solid var(--eg-color-error, var(--eg-color-error-default)) !important;
  outline-offset: -2px;
  z-index: 4;
}

.eg-cell-input {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  font-family: inherit;
  padding: 0;
}

.eg-row-header-cell {
  box-sizing: border-box;
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
  border-bottom: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-right: 2px solid var(--eg-color-border-strong, var(--eg-color-border-strong-default));
  text-align: center;
  font-size: 11px;
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default));
  cursor: pointer;
  user-select: none;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.eg-row-resize-handle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  cursor: row-resize;
  z-index: 5;
}

.eg-fill-handle {
  position: absolute;
  width: 6px;
  height: 6px;
  background: var(--eg-color-accent, var(--eg-color-accent-default));
  border: 1px solid white;
  cursor: crosshair;
  z-index: 10;
}

.eg-context-menu {
  position: fixed;
  background: var(--eg-color-menu-bg, var(--eg-color-cell-bg, var(--eg-color-cell-bg-default)));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-top: 3px solid var(--eg-color-accent, var(--eg-color-accent-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-dropdown, var(--eg-shadow-dropdown-default));
  z-index: 9999;
  min-width: 160px;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  padding: 4px 0;
  color: var(--eg-color-text, var(--eg-color-text-default));
}

/* Only 3 short items ("A → Z" / "Z → A" / "Clear sort") — the generic
   160px context-menu min-width looks oversized next to it, especially
   at size="small" where rows/text are much smaller. */
.eg-sort-menu {
  min-width: 110px;
}

.eg-context-item {
  padding: 6px 16px;
  cursor: pointer;
  position: relative;
  white-space: nowrap;
}

.eg-context-item:hover {
  background: var(--eg-color-option-hover-bg, var(--eg-color-option-hover-bg-default));
  color: var(--eg-color-text, var(--eg-color-text-default));
}

/* Sort popup: marks whichever direction is currently applied (see
   isSortMenuOptionActive()) with a checkmark + accent color/weight. */
.eg-context-item-active {
  font-weight: 600;
  color: var(--eg-color-accent, var(--eg-color-accent-default));
}
.eg-context-item-active::before {
  content: '✓';
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
}

.eg-context-separator {
  height: 1px;
  background: var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  margin: 4px 0;
}

.eg-context-submenu-parent::after { content: ' ▶'; float: right; }

.eg-context-submenu {
  display: none;
  position: absolute;
  left: 100%;
  top: -4px;
  background: var(--eg-color-menu-bg, var(--eg-color-cell-bg, var(--eg-color-cell-bg-default)));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-top: 3px solid var(--eg-color-accent, var(--eg-color-accent-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-dropdown, var(--eg-shadow-dropdown-default));
  min-width: 160px;
  padding: 4px 0;
  z-index: 10000;
  color: var(--eg-color-text, var(--eg-color-text-default));
}

.eg-context-submenu-parent:hover .eg-context-submenu { display: block; }

/* devMode — column/row info modal */
.eg-info-modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 10001;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
}

.eg-info-modal {
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-dropdown, var(--eg-shadow-dropdown-default));
  width: 90%;
  max-width: 640px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  font-family: var(--eg-font-family, var(--eg-font-family-default));
}

.eg-info-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 14px;
  border-bottom: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  flex-shrink: 0;
}

.eg-info-modal-title {
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  font-weight: 600;
  color: var(--eg-color-text, var(--eg-color-text-default));
}

.eg-info-modal-close {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  line-height: 1;
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default));
  padding: 2px 6px;
}

.eg-info-modal-close:hover { color: var(--eg-color-text, var(--eg-color-text-default)); }

.eg-info-modal-body {
  margin: 0;
  padding: 14px;
  overflow: auto;
  flex: 1;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 12px;
  color: var(--eg-color-text, var(--eg-color-text-default));
  white-space: pre-wrap;
  word-break: break-word;
}

.eg-group-btn {
  position: absolute;
  width: 16px;
  height: 16px;
  line-height: 14px;
  text-align: center;
  font-size: 10px;
  cursor: pointer;
  background: var(--eg-color-header-group-bg, var(--eg-color-header-group-bg-default));
  border: 1px solid var(--eg-color-group-border, var(--eg-color-group-border-default));
  border-radius: 2px;
  z-index: 5;
  user-select: none;
}

.eg-group-btn.collapsed { background: var(--eg-color-group-bg-collapsed, var(--eg-color-group-bg-collapsed-default)); }

.eg-drag-ghost {
  position: absolute;
  border: 2px dashed var(--eg-color-accent, var(--eg-color-accent-default));
  pointer-events: none;
  z-index: 20;
}

/* Column drag-and-drop */
.eg-header-cell--drag-source {
  opacity: 0.5;
  outline: 1px solid var(--eg-color-accent, var(--eg-color-accent-default));
  outline-offset: -1px;
}
.eg-cell--drag-source {
  opacity: 0.4;
}
/* Header-shaped drag ghost: mirrors the grabbed header's width/height (set
   inline), so the user drags something that looks like the actual column
   header, AG Grid-style. */
.eg-col-drag-ghost {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 0 10px;
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
  border: 1px solid var(--eg-color-accent, var(--eg-color-accent-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.22);
  font-size: var(--eg-font-size-header, var(--eg-font-size-header-default));
  font-weight: 600;
  color: var(--eg-color-text, var(--eg-color-text-default));
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  pointer-events: none;
  z-index: 9999;
  opacity: 0.9;
}

/* While a column drag is in flight, everything under the cursor shows the
   grabbing cursor instead of per-cell cursors. */
.eg-container.eg-col-dragging,
.eg-container.eg-col-dragging * {
  cursor: grabbing !important;
}

.eg-resize-line {
  pointer-events: none;
  z-index: 9999;
}

/* Pin left/right separator shadow — only visible while there's actually scrolled-away
   content hiding under the pinned zone on that side (see hasHiddenScrollLeft/Right()),
   not a permanent decoration. Applies to all 3 row-bands (header/body/footer) on each side.
   Positioned INSIDE the zone's own box (right:0/left:0, not a negative offset) — every one
   of these 6 containers has overflow:hidden (needed to clip cell content during virtual
   scroll), so a pseudo-element placed outside the box's own edge gets silently clipped away
   and never paints at all, regardless of opacity/z-index. Cost: the gradient overlays the
   last ~24px of the pinned zone's own cell content instead of bleeding into the scrollable
   zone — same trade-off Ant Design/AG Grid make, and unavoidable given the clipping
   requirement. */
.eg-frozen-col-header, .eg-frozen-col-body, .eg-frozen-col-footer { position: relative; }
.eg-pinned-right-header, .eg-pinned-right-footer { position: relative; }

.eg-frozen-col-header::after, .eg-frozen-col-body::after, .eg-frozen-col-footer::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 24px;
  height: 100%;
  background: linear-gradient(to right, transparent, var(--eg-color-freeze-shadow, var(--eg-color-freeze-shadow-default)));
  opacity: 0;
  transition: opacity 0.15s ease;
  pointer-events: none;
}
.eg-frozen-col-header.eg-shadow-edge::after,
.eg-frozen-col-body.eg-shadow-edge::after,
.eg-frozen-col-footer.eg-shadow-edge::after {
  opacity: 1;
}

.eg-pinned-right-body {
  position: sticky;
  right: 0;
  z-index: 10;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  flex-shrink: 0;
}

.eg-pinned-right-header::before, .eg-pinned-right-body::before, .eg-pinned-right-footer::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 24px;
  background: linear-gradient(to right, var(--eg-color-freeze-shadow, var(--eg-color-freeze-shadow-default)), transparent);
  opacity: 0;
  transition: opacity 0.15s ease;
  pointer-events: none;
}
.eg-pinned-right-header.eg-shadow-edge::before,
.eg-pinned-right-body.eg-shadow-edge::before,
.eg-pinned-right-footer.eg-shadow-edge::before {
  opacity: 1;
}

.eg-pinned-right-header {
  overflow: hidden;
  flex-shrink: 0;
  border-left: 2px solid var(--eg-color-border-strong, var(--eg-color-border-strong-default));
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
}

.eg-import-overlay {
  position: absolute;
  inset: 0;
  background: var(--eg-color-overlay-bg, var(--eg-color-overlay-bg-default));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  border-radius: var(--eg-radius, var(--eg-radius-default));
}

.eg-lock-flash {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  z-index: 60;
}
.eg-lock-flash-icon {
  display: inline-block;
  width: 96px;
  height: 96px;
  background-color: var(--eg-color-text, var(--eg-color-text-default));
  mask-size: contain;
  mask-repeat: no-repeat;
  mask-position: center;
  -webkit-mask-size: contain;
  -webkit-mask-repeat: no-repeat;
  -webkit-mask-position: center;
  filter: drop-shadow(0 2px 10px rgba(0, 0, 0, 0.28));
}

.eg-import-dialog {
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  border: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-radius: 8px;
  padding: 24px 32px;
  min-width: 280px;
  box-shadow: var(--eg-shadow-dialog, var(--eg-shadow-dialog-default));
  text-align: center;
}

.eg-import-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--eg-color-text, var(--eg-color-text-default));
  margin-bottom: 16px;
}

.eg-import-bar-wrap {
  height: 8px;
  background: var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  overflow: hidden;
  margin-bottom: 10px;
}

.eg-import-bar {
  height: 100%;
  background: linear-gradient(to right, var(--eg-color-accent, var(--eg-color-accent-default)), #4caf50);
  border-radius: var(--eg-radius, var(--eg-radius-default));
  transition: width 0.15s ease;
}

.eg-import-msg {
  font-size: 12px;
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default));
  margin-bottom: 4px;
}

.eg-import-pct {
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  font-weight: 600;
  color: var(--eg-color-accent, var(--eg-color-accent-default));
}
.eg-export-spinner {
  width: 32px;
  height: 32px;
  margin: 12px auto 0;
  border: 3px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-top-color: var(--eg-color-accent, var(--eg-color-accent-default));
  border-radius: 50%;
  animation: eg-spin 0.8s linear infinite;
}
@keyframes eg-spin {
  to { transform: rotate(360deg); }
}

/* ===== LOADING OVERLAY (loading prop) ===== */
.eg-loading-overlay {
  position: absolute;
  inset: 0;
  background: var(--eg-color-overlay-bg, var(--eg-color-overlay-bg-default));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 90;
  overflow: hidden;
}
.eg-loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  border-top-color: var(--eg-color-accent, var(--eg-color-accent-default));
  border-radius: 50%;
  animation: eg-spin 0.8s linear infinite;
}
.eg-skeleton {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.eg-skeleton-row {
  display: flex;
  align-items: center;
  padding: 0 4px;
  box-sizing: border-box;
}
.eg-skeleton-row-header {
  background: var(--eg-color-header-bg, var(--eg-color-header-bg-default));
}
.eg-skeleton-block {
  height: 60%;
  margin: 0 2px;
  border-radius: var(--eg-radius, var(--eg-radius-default));
  background: linear-gradient(
    90deg,
    var(--eg-color-border-cell, var(--eg-color-border-cell-default)) 25%,
    var(--eg-color-cell-readonly, var(--eg-color-cell-readonly-default)) 37%,
    var(--eg-color-border-cell, var(--eg-color-border-cell-default)) 63%
  );
  background-size: 400% 100%;
  animation: eg-skeleton-shimmer 1.4s ease infinite;
}
@keyframes eg-skeleton-shimmer {
  0% { background-position: 100% 50%; }
  100% { background-position: 0 50%; }
}
@media (prefers-reduced-motion: reduce) {
  .eg-skeleton-block, .eg-loading-spinner { animation: none; }
}

/* ===== READONLY CELL ===== */
/* !important throughout: same-specificity as the base .eg-cell / .eg-cell-active /
   .eg-cell-selected rules, so which one wins would otherwise depend on source
   order — fragile against any CSS minifier/optimizer in a host build pipeline
   that reorders equal-specificity rules (observed in practice: a host project's
   build silently dropped these declarations outside the active-cell state). */
.eg-cell-readonly {
  background:
    repeating-linear-gradient(
      135deg,
      var(--eg-color-cell-readonly-pattern, var(--eg-color-cell-readonly-pattern-default)) 0px,
      var(--eg-color-cell-readonly-pattern, var(--eg-color-cell-readonly-pattern-default)) 1px,
      transparent 1px,
      transparent 7px
    ),
    var(--eg-color-cell-readonly, var(--eg-color-cell-readonly-default)) !important;
  /* text-secondary, not text-muted: muted is tuned for placeholders/disabled
     captions (very low contrast by design in every theme — e.g. antd's is
     rgba(0,0,0,0.25)) and read poorly as actual cell values, especially
     layered over the diagonal readonly pattern above. text-secondary is the
     same "readable but visually de-emphasized" tier already used for row
     numbers/toolbar icons/import messages — legible while still reading as
     distinct from a normal editable cell's full-strength text. */
  color: var(--eg-color-text-secondary, var(--eg-color-text-secondary-default)) !important;
  cursor: default;
}
.eg-cell-readonly.eg-cell-selected {
  background:
    repeating-linear-gradient(
      135deg,
      var(--eg-color-cell-readonly-pattern, var(--eg-color-cell-readonly-pattern-default)) 0px,
      var(--eg-color-cell-readonly-pattern, var(--eg-color-cell-readonly-pattern-default)) 1px,
      transparent 1px,
      transparent 7px
    ),
    var(--eg-color-cell-readonly-selected, var(--eg-color-cell-readonly-selected-default)) !important;
}
.eg-cell-readonly.eg-cell-active {
  outline-color: var(--eg-color-text-muted, var(--eg-color-text-muted-default)) !important;
}

/* ===== SELECT DROPDOWN ===== */
.eg-cell-select {
  cursor: pointer;
}
/* The caret (::after below) is an absolutely-positioned overlay pinned to the cell's
   right edge — it claims no layout space of its own. With the default left alignment
   that's fine (text hugs the left edge, away from the caret), but col.align:'right' (or
   long centered text) pushes the label into the same few pixels the caret occupies,
   causing visible overlap. Reserve room for it at the cell level so text never reaches
   that zone, regardless of alignment. Skipped when a #suffix-{key} slot is present
   (eg-cell--has-suffix) — that path already reserves space for its own inline caret via
   flex layout (.eg-cell-select-trigger-wrap), so the fixed pseudo-element is hidden there
   (see .eg-cell--has-suffix.eg-cell-select::after below) and no extra padding is needed. */
.eg-cell-select:not(.eg-cell--has-suffix) {
  padding-right: calc(var(--eg-cell-padding-x, var(--eg-cell-padding-x-default)) + 14px);
}
.eg-cell-select::after {
  content: '▾';
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--eg-color-text-muted, var(--eg-color-text-muted-default));
  font-size: 11px;
  pointer-events: none;
  line-height: 1;
}

/* ===== DATE CELL ICON ===== */
/* Same reasoning/placement as the select caret above — reserve room at the
   cell level so col.align:'right'/centered text never reaches the icon's
   zone, regardless of alignment. mask-image (not content:url()/an emoji) so
   the icon is a single flat color that follows --eg-color-text-muted in
   every theme, light and dark alike, instead of a fixed-color raster/emoji
   glyph that wouldn't match. */
.eg-cell-date:not(.eg-cell--has-suffix) {
  padding-right: calc(var(--eg-cell-padding-x, var(--eg-cell-padding-x-default)) + 16px);
}
.eg-cell--has-suffix.eg-cell-date::after { display: none; }
.eg-cell-date::after {
  content: '';
  position: absolute;
  right: 5px;
  top: 50%;
  width: 12px;
  height: 12px;
  transform: translateY(-50%);
  background-color: var(--eg-color-text-muted, var(--eg-color-text-muted-default));
  pointer-events: none;
  -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23000' stroke-width='1.3' stroke-linecap='round'%3E%3Crect x='1.5' y='3' width='13' height='11' rx='1.5'/%3E%3Cline x1='1.5' y1='6.3' x2='14.5' y2='6.3'/%3E%3Cline x1='4.5' y1='1.2' x2='4.5' y2='4.2'/%3E%3Cline x1='11.5' y1='1.2' x2='11.5' y2='4.2'/%3E%3C/svg%3E");
  mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23000' stroke-width='1.3' stroke-linecap='round'%3E%3Crect x='1.5' y='3' width='13' height='11' rx='1.5'/%3E%3Cline x1='1.5' y1='6.3' x2='14.5' y2='6.3'/%3E%3Cline x1='4.5' y1='1.2' x2='4.5' y2='4.2'/%3E%3Cline x1='11.5' y1='1.2' x2='11.5' y2='4.2'/%3E%3C/svg%3E");
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-size: contain;
  mask-size: contain;
}

/* ===== CHECKBOX CELL ===== */
.eg-cell-checkbox {
  justify-content: center;
  padding: 0 2px;
}

/* ===== ACTION CELL ===== */
.eg-cell-action-wrap {
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
  cursor: pointer;
}
/* The wrap fills the cell (100% width) so the whole cell area stays clickable —
   .eg-cell's own justify-content (from col.align) has no leftover space to act
   on, so col.align is re-applied here to position the slot content itself. */
.eg-cell-align-right .eg-cell-action-wrap { justify-content: flex-end; }
.eg-cell-align-center .eg-cell-action-wrap { justify-content: center; }
.eg-validation-tooltip {
  background: var(--eg-color-error-soft, var(--eg-color-error-soft-default));
  border: 1px solid var(--eg-color-error, var(--eg-color-error-default));
  color: var(--eg-color-error-dark, var(--eg-color-error-dark-default));
  font-size: 12px;
  padding: 4px 8px;
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-tooltip, var(--eg-shadow-tooltip-default));
  white-space: nowrap;
  pointer-events: none;
}

/* ===== ROW STRIPE & HOVER ===== */
.eg-row--even .eg-cell:not(.eg-cell-selected):not(.eg-cell-active):not(.eg-cell-fill-preview) {
  background: var(--eg-color-row-stripe, var(--eg-color-row-stripe-default));
}
.eg-row:hover .eg-cell:not(.eg-cell-selected):not(.eg-cell-active):not(.eg-cell-fill-preview) {
  background: var(--eg-color-row-hover, var(--eg-color-row-hover-default));
}

/* ===== SIZE VARIANTS ===== */

/* small */
.eg-size-small .eg-cell {
  font-size: 12px;
  padding: 0 3px;
}
.eg-size-small .eg-cell-input {
  font-size: 12px;
}
.eg-size-small .eg-header-cell {
  font-size: 11px;
}
.eg-size-small .eg-footer-cell {
  font-size: 12px;
}
.eg-size-small .eg-row-header-cell {
  font-size: 10px;
}
.eg-size-small .eg-context-menu,
.eg-size-small .eg-context-item {
  font-size: 12px;
}
.eg-size-small .eg-context-item {
  padding: 4px 14px;
}
.eg-size-small .eg-sort-menu {
  min-width: 90px;
}
.eg-size-small .eg-lock-flash-icon {
  width: 72px;
  height: 72px;
}
.eg-size-small .eg-filter-input,
.eg-size-small .eg-filter-select {
  font-size: 11px;
}
.eg-size-small .eg-sort-icon {
  width: 9px;
  height: 9px;
}

/* large */
.eg-size-large .eg-cell {
  font-size: 14px;
  padding: 0 6px;
}
.eg-size-large .eg-cell-input {
  font-size: 14px;
}
.eg-size-large .eg-header-cell {
  font-size: var(--eg-font-size, var(--eg-font-size-default));
}
.eg-size-large .eg-footer-cell {
  font-size: 14px;
}
.eg-size-large .eg-row-header-cell {
  font-size: 12px;
}
.eg-size-large .eg-context-menu,
.eg-size-large .eg-context-item {
  font-size: 14px;
}
.eg-size-large .eg-context-item {
  padding: 8px 18px;
}
.eg-size-large .eg-sort-menu {
  min-width: 130px;
}
.eg-size-large .eg-lock-flash-icon {
  width: 120px;
  height: 120px;
}
.eg-size-large .eg-filter-input,
.eg-size-large .eg-filter-select {
  font-size: 13px;
}
.eg-size-large .eg-sort-icon {
  width: 13px;
  height: 13px;
}
</style>

<style>
/* ── EgSelect / EgTreeSelect dropdown ──
   Deliberate duplicate of EgSelect.vue's own (also global) <style>, not
   dead copy-paste: Vue only injects a component's <style> the first time
   that component is actually instantiated (vue-runtime-helpers' inject-style
   runs from a beforeCreate hook), so a grid that only ever uses
   type:'treeSelect' columns (never type:'select') would never trigger
   EgSelect.vue's own style injection at all — EgTreeSelect.vue reuses
   EgSelect's dropdown/option classes but doesn't redefine them itself. This
   copy, living in ExcelGrid.vue (always instantiated first), guarantees the
   classes are styled regardless of which sibling component ends up
   rendering them. Keep every token here identical to EgSelect.vue's copy —
   a past mismatch (this file used --eg-color-border-cell for
   .eg-select-dropdown's border where EgSelect.vue's own rule used
   --eg-color-border) made the two equally-specific global rules visibly
   disagree depending on which one happened to load last, reported as the
   dropdown's border looking wrong / DevTools showing two conflicting rules
   for .eg-select-dropdown (fixed in v1.1.113). */
.eg-select-wrapper {
  position: relative;
  display: inline-block;
  min-width: 120px;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  font-family: inherit;
}
.eg-select-trigger {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
  min-height: 30px;
  padding: 4px 8px;
  box-sizing: border-box;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  cursor: pointer;
  user-select: none;
  color: var(--eg-color-text, var(--eg-color-text-default));
  transition: border-color .15s ease, box-shadow .15s ease;
}
.eg-select-trigger:hover { border-color: var(--eg-color-accent, var(--eg-color-accent-default)); }
.eg-select-trigger--open {
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
  box-shadow: 0 0 0 2px var(--eg-color-accent-soft, var(--eg-color-accent-soft-default));
}
.eg-select-trigger--disabled { background: var(--eg-color-cell-readonly, var(--eg-color-cell-readonly-default)); cursor: default; color: var(--eg-color-text-muted, var(--eg-color-text-muted-default)); }
.eg-select-trigger-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.eg-select-placeholder { color: var(--eg-color-text-muted, var(--eg-color-text-muted-default)); }
.eg-select-caret { flex-shrink: 0; color: var(--eg-color-text-muted, var(--eg-color-text-muted-default)); font-size: 12px; }
.eg-select-dropdown {
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-dropdown, var(--eg-shadow-dropdown-default));
  overflow-y: auto;
  max-height: 320px;
  padding: 4px 0;
}
.eg-select-dropdown--floating {
  position: absolute;
  top: 100%;
  left: 0;
  min-width: 100%;
  z-index: 999;
  margin-top: 2px;
}
.eg-select-search {
  padding: 6px 8px;
  border-bottom: 1px solid var(--eg-color-border-cell, var(--eg-color-border-cell-default));
  position: sticky;
  top: 0;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  z-index: 1;
}
.eg-select-search-input {
  width: 100%;
  box-sizing: border-box;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  padding: 4px 8px;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  outline: none;
  color: var(--eg-color-text, var(--eg-color-text-default));
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  font-family: inherit;
}
.eg-select-search-input:focus {
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
  box-shadow: 0 0 0 2px var(--eg-color-accent-soft, var(--eg-color-accent-soft-default));
}
.eg-select-option {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 6px 12px;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  cursor: pointer;
  white-space: normal;
  word-break: break-word;
  user-select: none;
  color: var(--eg-color-text, var(--eg-color-text-default));
}
.eg-select-option:hover,
.eg-select-option--highlighted { background: var(--eg-color-option-hover-bg, var(--eg-color-option-hover-bg-default)); }
.eg-select-option--active { font-weight: 600; color: var(--eg-color-accent, var(--eg-color-accent-default)); }
.eg-select-option--active.eg-select-option--highlighted,
.eg-select-option--active:hover { background: var(--eg-color-option-active-hover-bg, var(--eg-color-option-active-hover-bg-default)); }
.eg-select-empty {
  padding: 14px 12px;
  text-align: center;
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  color: var(--eg-color-text-muted, var(--eg-color-text-muted-default));
  user-select: none;
}
.eg-option-tooltip {
  position: fixed;
  max-width: 280px;
  background: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  box-shadow: var(--eg-shadow-tooltip, var(--eg-shadow-tooltip-default));
  color: var(--eg-color-text, var(--eg-color-text-default));
  font-size: var(--eg-font-size, var(--eg-font-size-default));
  padding: 6px 10px;
  pointer-events: none;
  white-space: normal;
  word-break: break-word;
  z-index: 10000;
}
.eg-select-footer {
  display: flex;
  justify-content: flex-end;
  padding: 4px 6px 6px;
  border-top: 1px solid var(--eg-color-border, var(--eg-color-border-default));
}
.eg-select-btn {
  background: none;
  border: 1px solid var(--eg-color-border, var(--eg-color-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  padding: 4px 10px;
  cursor: pointer;
  font-size: 12px;
  color: var(--eg-color-text, var(--eg-color-text-default));
}
.eg-select-btn:hover { background: var(--eg-color-option-hover-bg, var(--eg-color-option-hover-bg-default)); }
.eg-select-btn--clear { color: var(--eg-color-danger, #c62828); border-color: var(--eg-color-danger, #f1b0b0); }
.eg-select-btn--clear:hover { background: #fff0f0; }
/* Grid `size` overrides — must live in this *unscoped* style block, not the
   scoped one above: .eg-select-option is rendered by the separate EgSelect /
   EgTreeSelect components, so Vue's scoped-CSS attribute (added only to this
   SFC's own template elements) never lands on it — a scoped rule targeting
   it can never match. */
.eg-size-small .eg-select-option {
  font-size: 12px;
  padding: 4px 10px;
}
.eg-size-large .eg-select-option {
  font-size: 14px;
  padding: 8px 14px;
}
.eg-select-dot {
  width: 9px;
  height: 9px;
  border-radius: 50%;
  flex-shrink: 0;
  display: inline-block;
  margin-top: 3px;
}
/* Tree toggle */
.eg-tree-toggle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex-shrink: 0;
  font-size: 10px;
  color: var(--eg-color-text-muted, var(--eg-color-text-muted-default));
  margin-top: 1px;
}
.eg-tree-toggle--leaf { visibility: hidden; }
/* EgCheckbox */
.eg-checkbox {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.eg-checkbox-input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: pointer;
}
.eg-checkbox-box {
  position: relative;
  display: block;
  width: 19px;
  height: 19px;
  box-sizing: border-box;
  background-color: var(--eg-color-cell-bg, var(--eg-color-cell-bg-default));
  background-repeat: no-repeat;
  background-position: center;
  background-size: 0 0;
  border: 1.5px solid var(--eg-color-checkbox-border, var(--eg-color-checkbox-border-default));
  border-radius: var(--eg-radius, var(--eg-radius-default));
  transition: background-color .12s ease, border-color .12s ease, background-size .12s ease;
}
.eg-checkbox:hover .eg-checkbox-box { border-color: var(--eg-color-accent, var(--eg-color-accent-default)); }
.eg-checkbox-input:checked + .eg-checkbox-box {
  background-color: var(--eg-color-accent, var(--eg-color-accent-default));
  background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZD0iTTMuNSA4LjNsMyAzIDYtNi42IiBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg==");
  background-size: 70% 70%;
  border-color: var(--eg-color-accent, var(--eg-color-accent-default));
}
.eg-checkbox-input:focus-visible + .eg-checkbox-box { box-shadow: 0 0 0 3px var(--eg-color-accent-soft, var(--eg-color-accent-soft-default)); }
.eg-checkbox--disabled,
.eg-checkbox--disabled .eg-checkbox-input { cursor: default; }
.eg-checkbox-input:disabled + .eg-checkbox-box { background-color: var(--eg-color-cell-readonly, var(--eg-color-cell-readonly-default)); border-color: var(--eg-color-border-cell, var(--eg-color-border-cell-default)); }
.eg-locked .eg-checkbox,
.eg-locked .eg-checkbox-input { cursor: not-allowed; }
.eg-checkbox-input:disabled:checked + .eg-checkbox-box { background-color: var(--eg-color-checkbox-disabled-checked, var(--eg-color-checkbox-disabled-checked-default)); border-color: var(--eg-color-checkbox-disabled-checked, var(--eg-color-checkbox-disabled-checked-default)); }
</style>
