"use client";

/** Shared launcher preferences — favorites/recent/pinned (local + sync-ready). */
const KEY = "commercial.ux.launcher_prefs";

export type LauncherPrefs = {
  favorites: string[];
  pinned: string[];
  recent: string[];
};

const EMPTY: LauncherPrefs = { favorites: [], pinned: [], recent: [] };

export function loadLauncherPrefs(): LauncherPrefs {
  if (typeof window === "undefined") return EMPTY;
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return EMPTY;
    const parsed = JSON.parse(raw) as Partial<LauncherPrefs>;
    return {
      favorites: parsed.favorites || [],
      pinned: parsed.pinned || [],
      recent: parsed.recent || [],
    };
  } catch {
    return EMPTY;
  }
}

export function saveLauncherPrefs(prefs: LauncherPrefs) {
  localStorage.setItem(KEY, JSON.stringify(prefs));
}

export function toggleFavorite(productCode: string): LauncherPrefs {
  const prefs = loadLauncherPrefs();
  const set = new Set(prefs.favorites);
  if (set.has(productCode)) set.delete(productCode);
  else set.add(productCode);
  const next = { ...prefs, favorites: Array.from(set) };
  saveLauncherPrefs(next);
  return next;
}

export function togglePinned(productCode: string): LauncherPrefs {
  const prefs = loadLauncherPrefs();
  const set = new Set(prefs.pinned);
  if (set.has(productCode)) set.delete(productCode);
  else set.add(productCode);
  const next = { ...prefs, pinned: Array.from(set) };
  saveLauncherPrefs(next);
  return next;
}

export function pushRecent(productCode: string): LauncherPrefs {
  const prefs = loadLauncherPrefs();
  const recent = [productCode, ...prefs.recent.filter((c) => c !== productCode)].slice(0, 12);
  const next = { ...prefs, recent };
  saveLauncherPrefs(next);
  return next;
}
