import type { SpreadsheetLayoutState } from '../types';

function storageKey(tableName: string, sheetKey?: string) {
  return `xk_spreadsheet_layout_${tableName}_${sheetKey ?? 'default'}`;
}

export function readSpreadsheetLayout(
  tableName: string,
  sheetKey?: string,
): SpreadsheetLayoutState | null {
  try {
    const raw = localStorage.getItem(storageKey(tableName, sheetKey));
    if (!raw) return null;
    return JSON.parse(raw) as SpreadsheetLayoutState;
  } catch {
    return null;
  }
}

export function writeSpreadsheetLayout(
  tableName: string,
  sheetKey: string | undefined,
  state: SpreadsheetLayoutState,
) {
  localStorage.setItem(storageKey(tableName, sheetKey), JSON.stringify(state));
}

let saveTimer: ReturnType<typeof setTimeout> | null = null;

export function debouncedWriteSpreadsheetLayout(
  tableName: string,
  sheetKey: string | undefined,
  state: SpreadsheetLayoutState,
  delayMs = 400,
) {
  if (saveTimer) clearTimeout(saveTimer);
  saveTimer = setTimeout(() => {
    writeSpreadsheetLayout(tableName, sheetKey, state);
    saveTimer = null;
  }, delayMs);
}
