export type ChartBoardId = "joborder" | "process" | "equipment";

export interface ChartBoardRefreshPrefs {
  autoRefreshOn: boolean;
  refreshIntervalSec: number;
}

export const CHART_BOARD_REFRESH_INTERVAL_SEC_OPTIONS = [30, 45, 60, 90, 120, 300] as const;
export const CHART_BOARD_DEFAULT_REFRESH_INTERVAL_SEC = 45;

const ALLOWED_INTERVALS = new Set<number>(CHART_BOARD_REFRESH_INTERVAL_SEC_OPTIONS);

function storageKeySession(boardId: ChartBoardId): string {
  return `fpsms:chartBoardRefresh:${boardId}`;
}

function storageKeyUser(boardId: ChartBoardId, userKey: string): string {
  return `fpsms:chartBoardRefresh:${boardId}:user:${userKey}`;
}

export function sanitizeChartBoardRefreshInterval(sec: number): number {
  const n = Number(sec);
  if (ALLOWED_INTERVALS.has(n)) return n;
  return CHART_BOARD_DEFAULT_REFRESH_INTERVAL_SEC;
}

function parsePrefs(raw: string | null): ChartBoardRefreshPrefs | null {
  if (!raw) return null;
  try {
    const p = JSON.parse(raw) as Partial<ChartBoardRefreshPrefs>;
    return {
      autoRefreshOn: Boolean(p.autoRefreshOn),
      refreshIntervalSec: sanitizeChartBoardRefreshInterval(Number(p.refreshIntervalSec)),
    };
  } catch {
    return null;
  }
}

/**
 * Logged in: read/write **localStorage** per account key.
 * Not logged in: **sessionStorage** for this browser tab/session.
 */
export function loadChartBoardRefreshPrefs(
  boardId: ChartBoardId,
  userKeyPart: string | undefined,
): ChartBoardRefreshPrefs {
  const defaults: ChartBoardRefreshPrefs = {
    autoRefreshOn: false,
    refreshIntervalSec: CHART_BOARD_DEFAULT_REFRESH_INTERVAL_SEC,
  };
  if (typeof window === "undefined") {
    return defaults;
  }
  try {
    if (userKeyPart) {
      const u = parsePrefs(localStorage.getItem(storageKeyUser(boardId, userKeyPart)));
      if (u) return u;
    }
    const s = parsePrefs(sessionStorage.getItem(storageKeySession(boardId)));
    if (s) return s;
  } catch {
    /* ignore quota / private mode */
  }
  return defaults;
}

export function saveChartBoardRefreshPrefs(
  boardId: ChartBoardId,
  userKeyPart: string | undefined,
  prefs: ChartBoardRefreshPrefs,
): void {
  if (typeof window === "undefined") return;
  const payload = JSON.stringify({
    autoRefreshOn: prefs.autoRefreshOn,
    refreshIntervalSec: sanitizeChartBoardRefreshInterval(prefs.refreshIntervalSec),
  });
  try {
    if (userKeyPart) {
      localStorage.setItem(storageKeyUser(boardId, userKeyPart), payload);
      sessionStorage.removeItem(storageKeySession(boardId));
    } else {
      sessionStorage.setItem(storageKeySession(boardId), payload);
    }
  } catch {
    /* ignore */
  }
}
