/**
 * userPrefs.ts
 * Global, reactive user-preference store persisted in localStorage.
 * All components that call `loadPrefs()` get the same snapshot.
 * Emit the `checkflow:prefsChanged` event to notify all listeners.
 */

export interface LabsFeatures {
  /** Each flag independently enables/disables a Labs feature */
  kanbanBoard: boolean;        // List ↔ Kanban view switcher shown in header
  // Add more feature flags here as Labs grows
}

export interface UserPrefs {
  /** Layout */
  sidebarWidth: number;          // 160–420px
  detailWidth: number;           // 300–760px
  density: "compact" | "default" | "comfortable";
  detailBlockOrder: ("subtasks" | "note")[];
  detailSplitRatio: number;      // 15–85 %

  /** View (driven by Labs kanbanBoard flag) */
  viewMode: "list" | "kanban";

  /** Labs feature toggles */
  labs: LabsFeatures;

  /** Appearance */
  fontSize: "small" | "default" | "large";
  accentHue: number;             // 0–360 (HSL)
  saturation: number;            // 20–100 (%)
  roundness: "sharp" | "default" | "round";
  animationSpeed: "none" | "fast" | "default" | "slow";
}

export const DEFAULT_PREFS: UserPrefs = {
  sidebarWidth: 260,
  detailWidth: 520,
  density: "default",
  detailBlockOrder: ["subtasks", "note"],
  detailSplitRatio: 45,
  viewMode: "list",
  labs: {
    kanbanBoard: false,
  },
  fontSize: "default",
  accentHue: 220,
  saturation: 75,
  roundness: "default",
  animationSpeed: "default",
};

const KEY = "checkflow_prefs_v2";
const EVENT = "checkflow:prefsChanged";

export function loadPrefs(): UserPrefs {
  if (typeof window === "undefined") return { ...DEFAULT_PREFS };
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return { ...DEFAULT_PREFS };
    const parsed = JSON.parse(raw);
    // Deep merge labs to ensure new feature flags get defaults
    return {
      ...DEFAULT_PREFS,
      ...parsed,
      labs: { ...DEFAULT_PREFS.labs, ...(parsed.labs || {}) },
    };
  } catch {
    return { ...DEFAULT_PREFS };
  }
}

export function savePrefs(patch: Partial<UserPrefs>): UserPrefs {
  const current = loadPrefs();
  const next: UserPrefs = {
    ...current,
    ...patch,
    // Deep merge labs
    labs: patch.labs ? { ...current.labs, ...patch.labs } : current.labs,
  };
  try {
    localStorage.setItem(KEY, JSON.stringify(next));
    window.dispatchEvent(new CustomEvent(EVENT, { detail: next }));
  } catch { /* storage full */ }
  return next;
}

export function resetPrefs(): UserPrefs {
  try {
    localStorage.removeItem(KEY);
    // Also remove legacy keys from v0.5
    localStorage.removeItem("checkflow_block_order");
    localStorage.removeItem("checkflow_split_ratio");
    localStorage.removeItem("checkflow_view_mode");
    window.dispatchEvent(new CustomEvent(EVENT, { detail: { ...DEFAULT_PREFS } }));
  } catch { /* ignore */ }
  return { ...DEFAULT_PREFS };
}

/** Compute CSS variable overrides from a UserPrefs snapshot */
export function prefsToCssVars(p: UserPrefs): Record<string, string> {
  const sat = Math.round(p.saturation * 0.9);
  const accent = `hsl(${p.accentHue}, ${sat}%, 54%)`;
  const accentHover = `hsl(${p.accentHue}, ${sat}%, 46%)`;
  const accentLight = `hsla(${p.accentHue}, ${sat}%, 54%, 0.1)`;
  const accentMedium = `hsla(${p.accentHue}, ${sat}%, 54%, 0.18)`;

  const radMap = {
    sharp:   { xs: "2px",  sm: "4px",  md: "6px",  lg: "8px",  xl: "10px" },
    default: { xs: "4px",  sm: "8px",  md: "12px", lg: "16px", xl: "20px" },
    round:   { xs: "8px",  sm: "14px", md: "18px", lg: "24px", xl: "28px" },
  };
  const r = radMap[p.roundness];

  const fontMap = { small: "12px", default: "14px", large: "15px" };

  const durMap = {
    none:    { fast: "0ms",   normal: "0ms",   slow: "0ms" },
    fast:    { fast: "60ms",  normal: "100ms", slow: "160ms" },
    default: { fast: "120ms", normal: "200ms", slow: "300ms" },
    slow:    { fast: "220ms", normal: "360ms", slow: "500ms" },
  };
  const d = durMap[p.animationSpeed];

  const densityMap = {
    compact:     { taskPad: "6px 20px",  gap: "2px" },
    default:     { taskPad: "10px 20px", gap: "4px" },
    comfortable: { taskPad: "14px 20px", gap: "8px" },
  };
  const dn = densityMap[p.density];

  return {
    "--accent": accent,
    "--accent-hover": accentHover,
    "--accent-light": accentLight,
    "--accent-medium": accentMedium,
    "--radius-xs": r.xs,
    "--radius-sm": r.sm,
    "--radius-md": r.md,
    "--radius-lg": r.lg,
    "--radius-xl": r.xl,
    "--font-size-base": fontMap[p.fontSize],
    "--dur-fast": d.fast,
    "--dur-normal": d.normal,
    "--dur-slow": d.slow,
    "--task-item-padding": dn.taskPad,
    "--task-item-gap": dn.gap,
    "--sidebar-width": `${p.sidebarWidth}px`,
    "--detail-width": `${p.detailWidth}px`,
  };
}
