export const TABLE_VIEW_MODE_STORAGE_KEY = "forgeflow.tableViewMode";
export const TABLE_VIEW_MODE_DEFAULT_VERSION_KEY = "forgeflow.tableViewModeDefaultVersion";

const DEFAULT_TABLE_VIEW_MODE = "wide";
const CURRENT_DEFAULT_VERSION = "wide-v1";

export function normalizeTableViewMode(value) {
  return value === "overview" || value === "wide" ? value : DEFAULT_TABLE_VIEW_MODE;
}

export function readStoredTableMode(storage = typeof window !== "undefined" ? window.localStorage : null) {
  if (!storage) {
    return DEFAULT_TABLE_VIEW_MODE;
  }

  try {
    const hasMigratedToWideDefault = storage.getItem(TABLE_VIEW_MODE_DEFAULT_VERSION_KEY) === CURRENT_DEFAULT_VERSION;

    if (!hasMigratedToWideDefault) {
      storage.setItem(TABLE_VIEW_MODE_STORAGE_KEY, DEFAULT_TABLE_VIEW_MODE);
      storage.setItem(TABLE_VIEW_MODE_DEFAULT_VERSION_KEY, CURRENT_DEFAULT_VERSION);
      return DEFAULT_TABLE_VIEW_MODE;
    }

    return normalizeTableViewMode(storage.getItem(TABLE_VIEW_MODE_STORAGE_KEY));
  } catch {
    return DEFAULT_TABLE_VIEW_MODE;
  }
}
