export const COOKIE_PREFERENCES_STORAGE_KEY = "stylunique_cookie_preferences";

export type CookiePreferencesState = {
  necessary: true;
  analytics: boolean;
};

export const DEFAULT_COOKIE_PREFERENCES: CookiePreferencesState = {
  necessary: true,
  analytics: false,
};

export function readCookiePreferences(): CookiePreferencesState | null {
  if (typeof window === "undefined") {
    return null;
  }

  try {
    const raw = window.localStorage.getItem(COOKIE_PREFERENCES_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<CookiePreferencesState>;
    return {
      necessary: true,
      analytics: Boolean(parsed.analytics),
    };
  } catch {
    return null;
  }
}

export function writeCookiePreferences(preferences: CookiePreferencesState) {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.setItem(COOKIE_PREFERENCES_STORAGE_KEY, JSON.stringify(preferences));
}
