"use client";

// src/lib/table-state-lifecycle.ts
import * as React2 from "react";

// src/lib/persisted-state.ts
import * as React from "react";
var EXXAT_STORAGE_PREFIX = "exxat-ds:";
var DEFAULT_DEBOUNCE_MS = 400;
var isBrowser = () => typeof window !== "undefined";
function getDriverImpl(driver) {
  if (!isBrowser()) return null;
  try {
    return driver === "session" ? window.sessionStorage : window.localStorage;
  } catch {
    return null;
  }
}
function namespacedKey(key) {
  return key.startsWith(EXXAT_STORAGE_PREFIX) ? key : `${EXXAT_STORAGE_PREFIX}${key}`;
}
function getStorageItem(key, driver = "local") {
  const store = getDriverImpl(driver);
  if (!store) return null;
  try {
    return store.getItem(namespacedKey(key));
  } catch {
    return null;
  }
}
function setStorageItem(key, value, driver = "local") {
  const store = getDriverImpl(driver);
  if (!store) return;
  try {
    store.setItem(namespacedKey(key), value);
  } catch {
  }
}
var debounceTimers = /* @__PURE__ */ new Map();
function scheduleStorageWrite(key, value, options = {}) {
  if (!isBrowser()) return;
  const { debounceMs = DEFAULT_DEBOUNCE_MS, driver = "local" } = options;
  const fullKey = namespacedKey(key);
  const prev = debounceTimers.get(fullKey);
  if (prev) clearTimeout(prev);
  const t = setTimeout(() => {
    debounceTimers.delete(fullKey);
    setStorageItem(key, value, driver);
  }, debounceMs);
  debounceTimers.set(fullKey, t);
}

// src/lib/table-state-lifecycle.ts
var LIFECYCLE_SAVE_DEBOUNCE_MS = 400;
var PAGE_SAVE_DEBOUNCE_MS = 400;
function lifecycleStorageKey(namespace, tabId) {
  return `exxat-ds:${namespace}:lifecycle:v1:${tabId}`;
}
function pageStorageKey(namespace) {
  return `exxat-ds:${namespace}:page:v1`;
}
var VIEW_TYPES = ["table", "list", "board", "dashboard"];
function isViewType(v) {
  return typeof v === "string" && VIEW_TYPES.includes(v);
}
function parseViewTab(raw) {
  if (!raw || typeof raw !== "object") return null;
  const o = raw;
  if (typeof o.id !== "string" || typeof o.label !== "string") return null;
  if (!isViewType(o.viewType)) return null;
  if (typeof o.icon !== "string" || typeof o.filterId !== "string") return null;
  return { id: o.id, label: o.label, viewType: o.viewType, icon: o.icon, filterId: o.filterId };
}
function parsePersistedPage(raw) {
  if (!raw) return null;
  try {
    const j = JSON.parse(raw);
    if (!j || typeof j !== "object") return null;
    const o = j;
    if (o.v !== 1) return null;
    if (!o.displayOptions || typeof o.displayOptions !== "object") return null;
    if (typeof o.showMetrics !== "boolean") return null;
    if (!Array.isArray(o.tabs) || typeof o.activeTabId !== "string") return null;
    const tabs = o.tabs.map(parseViewTab).filter((t) => t !== null);
    if (tabs.length === 0) return null;
    return {
      v: 1,
      displayOptions: o.displayOptions,
      showMetrics: o.showMetrics,
      tabs,
      activeTabId: o.activeTabId
    };
  } catch {
    return null;
  }
}
function parsePersistedLifecycle(raw) {
  if (!raw) return null;
  try {
    const j = JSON.parse(raw);
    if (!j || typeof j !== "object") return null;
    const o = j;
    if (o.v !== 1) return null;
    if (!Array.isArray(o.sortRules)) return null;
    if (typeof o.search !== "string") return null;
    if (!Array.isArray(o.activeFilters)) return null;
    if (!o.filterConnectors || typeof o.filterConnectors !== "object") return null;
    if (o.groupBy !== null && typeof o.groupBy !== "string") return null;
    if (!Array.isArray(o.colOrder)) return null;
    if (!Array.isArray(o.hiddenCols)) return null;
    if (!o.colWidths || typeof o.colWidths !== "object") return null;
    if (!o.colPins || typeof o.colPins !== "object") return null;
    if (!o.colWrap || typeof o.colWrap !== "object") return null;
    if (!o.colMenuSearch || typeof o.colMenuSearch !== "object") return null;
    if (typeof o.rowHeight !== "string") return null;
    if (typeof o.showGridlines !== "boolean") return null;
    if (typeof o.filterBarVisible !== "boolean") return null;
    if (typeof o.searchOpen !== "boolean") return null;
    if (o.extras !== void 0 && (typeof o.extras !== "object" || o.extras === null)) return null;
    return o;
  } catch {
    return null;
  }
}
function mergeColOrder(saved, columnKeys) {
  const ordered = saved.filter((k) => columnKeys.has(k));
  for (const k of columnKeys) {
    if (!ordered.includes(k)) ordered.push(k);
  }
  return ordered;
}
function filterRecordKeys(obj, keys) {
  const out = { ...obj };
  for (const k of Object.keys(out)) {
    if (!keys.has(k)) delete out[k];
  }
  return out;
}
function sanitizeActiveFilters(filters, columnKeys) {
  return filters.filter((f) => columnKeys.has(f.fieldKey));
}
function sanitizeSortRules(rules, columnKeys) {
  return rules.filter((r) => columnKeys.has(r.fieldKey));
}
function applyLifecycleColumnLayout(ts, p, columnKeys) {
  const colOrder = mergeColOrder(p.colOrder, columnKeys);
  const hidden = new Set(p.hiddenCols.filter((k) => columnKeys.has(k)));
  const colWidths = filterRecordKeys(p.colWidths, columnKeys);
  const colPins = filterRecordKeys(p.colPins, columnKeys);
  const colWrap = filterRecordKeys(p.colWrap, columnKeys);
  const colMenuSearch = filterRecordKeys(p.colMenuSearch, columnKeys);
  ts.setColOrder(colOrder);
  ts.setHiddenCols(hidden);
  ts.setColWidths(colWidths);
  ts.setColPins(colPins);
  ts.setColWrap(colWrap);
  ts.setColMenuSearch(colMenuSearch);
  ts.setRowHeight(p.rowHeight);
  ts.setShowGridlines(p.showGridlines);
}
function applyLifecyclePersisted(ts, p, columnKeys) {
  applyLifecycleColumnLayout(ts, p, columnKeys);
  ts.setSortRules(sanitizeSortRules(p.sortRules, columnKeys));
  ts.setSearch(p.search);
  ts.setActiveFilters(sanitizeActiveFilters(p.activeFilters, columnKeys));
  ts.setFilterConnectors(p.filterConnectors);
  ts.setGroupBy(p.groupBy != null && columnKeys.has(p.groupBy) ? p.groupBy : null);
  ts.setFilterBarVisible(p.filterBarVisible);
  ts.setSearchOpen(p.searchOpen);
}
function serializeLifecycle(ts, extras) {
  return {
    v: 1,
    sortRules: ts.sortRules,
    search: ts.search,
    activeFilters: ts.activeFilters,
    filterConnectors: ts.filterConnectors,
    groupBy: ts.groupBy,
    colOrder: ts.colOrder,
    hiddenCols: [...ts.hiddenCols],
    colWidths: { ...ts.colWidths },
    colPins: { ...ts.colPins },
    colWrap: { ...ts.colWrap },
    colMenuSearch: { ...ts.colMenuSearch },
    rowHeight: ts.rowHeight,
    showGridlines: ts.showGridlines,
    filterBarVisible: ts.filterBarVisible,
    searchOpen: ts.searchOpen,
    extras
  };
}
function readLifecycleExtras(p) {
  if (p.extras) return p.extras;
  if (p.conditionalRules !== void 0 || p.pagination !== void 0 || p.paginationPage !== void 0 || p.paginationPageSize !== void 0) {
    const legacy = {};
    if (p.conditionalRules !== void 0) legacy.conditionalRules = p.conditionalRules;
    if (p.pagination !== void 0) legacy.pagination = p.pagination;
    if (p.paginationPage !== void 0) legacy.paginationPage = p.paginationPage;
    if (p.paginationPageSize !== void 0) legacy.paginationPageSize = p.paginationPageSize;
    return legacy;
  }
  return void 0;
}
function loadLifecycleFromStorage(namespace, tabId) {
  return parsePersistedLifecycle(getStorageItem(lifecycleStorageKey(namespace, tabId)));
}
function scheduleLifecycleSave(namespace, tabId, payload) {
  scheduleStorageWrite(
    lifecycleStorageKey(namespace, tabId),
    JSON.stringify(payload),
    { debounceMs: LIFECYCLE_SAVE_DEBOUNCE_MS }
  );
}
function seedTableStateLifecycle(namespace, tabId, partial) {
  if (typeof window === "undefined") return;
  const extras = {};
  if (partial.conditionalRules !== void 0) extras.conditionalRules = partial.conditionalRules;
  if (partial.displayOptions !== void 0) extras.displayOptions = partial.displayOptions;
  const payload = {
    v: 1,
    sortRules: partial.sortRules ?? [],
    search: "",
    activeFilters: partial.activeFilters ?? [],
    filterConnectors: {},
    groupBy: partial.groupBy ?? null,
    colOrder: partial.colOrder ?? [],
    hiddenCols: partial.hiddenCols ?? [],
    colWidths: {},
    colPins: {},
    colWrap: {},
    colMenuSearch: {},
    rowHeight: "default",
    showGridlines: false,
    filterBarVisible: true,
    searchOpen: false,
    ...Object.keys(extras).length > 0 ? { extras } : {}
  };
  setStorageItem(lifecycleStorageKey(namespace, tabId), JSON.stringify(payload));
}
function loadPageFromStorage(namespace) {
  return parsePersistedPage(getStorageItem(pageStorageKey(namespace)));
}
function schedulePageSave(namespace, payload) {
  scheduleStorageWrite(
    pageStorageKey(namespace),
    JSON.stringify(payload),
    { debounceMs: PAGE_SAVE_DEBOUNCE_MS }
  );
}
function useTableStateLifecycle(opts) {
  const { namespace, tabId, tableState, columnKeys, extras, onLoadExtras } = opts;
  const onLoadExtrasRef = React2.useRef(onLoadExtras);
  React2.useEffect(() => {
    onLoadExtrasRef.current = onLoadExtras;
  });
  const columnKeysFingerprint = React2.useMemo(
    () => [...columnKeys].sort().join("\0"),
    [columnKeys]
  );
  const loadedScopeRef = React2.useRef(null);
  const appliedColumnFingerprintRef = React2.useRef(null);
  React2.useLayoutEffect(() => {
    if (columnKeys.size === 0) return;
    const scope = `${namespace}:${tabId}`;
    const raw = loadLifecycleFromStorage(namespace, tabId);
    if (loadedScopeRef.current !== scope) {
      loadedScopeRef.current = scope;
      appliedColumnFingerprintRef.current = columnKeysFingerprint;
      if (!raw) return;
      applyLifecyclePersisted(tableState, raw, columnKeys);
      const e = readLifecycleExtras(raw);
      onLoadExtrasRef.current?.(e);
      return;
    }
    if (appliedColumnFingerprintRef.current === columnKeysFingerprint) return;
    appliedColumnFingerprintRef.current = columnKeysFingerprint;
    if (!raw) return;
    applyLifecycleColumnLayout(tableState, raw, columnKeys);
  }, [namespace, tabId, columnKeysFingerprint]);
  const extrasJson = React2.useMemo(() => extras ? JSON.stringify(extras) : "", [extras]);
  React2.useEffect(() => {
    const payload = serializeLifecycle(tableState, extras);
    scheduleLifecycleSave(namespace, tabId, payload);
  }, [
    namespace,
    tabId,
    extrasJson,
    tableState.sortRules,
    tableState.search,
    tableState.activeFilters,
    tableState.filterConnectors,
    tableState.groupBy,
    tableState.colOrder,
    tableState.hiddenCols,
    tableState.colWidths,
    tableState.colPins,
    tableState.colWrap,
    tableState.colMenuSearch,
    tableState.rowHeight,
    tableState.showGridlines,
    tableState.filterBarVisible,
    tableState.searchOpen
  ]);
}
export {
  applyLifecycleColumnLayout,
  applyLifecyclePersisted,
  lifecycleStorageKey,
  loadLifecycleFromStorage,
  loadPageFromStorage,
  pageStorageKey,
  parsePersistedLifecycle,
  parsePersistedPage,
  readLifecycleExtras,
  scheduleLifecycleSave,
  schedulePageSave,
  seedTableStateLifecycle,
  serializeLifecycle,
  useTableStateLifecycle
};
//# sourceMappingURL=table-state-lifecycle.js.map