export const CONSENT_KEY = "quto-consent";
export const CONSENT_PREFS_KEY = "quto-cookie-preferences";
export const CONSENT_EVENT = "quto:open-cookie-settings";

export type Consent = "accepted" | "declined";

export interface CookiePreferences {
  necessary: true;
  analytics: boolean;
  marketing: boolean;
}

export const DEFAULT_PREFERENCES: CookiePreferences = {
  necessary: true,
  analytics: false,
  marketing: false,
};

/** Re-open the cookie banner or preferences modal (wired to the footer "Cookie settings" control). */
export function openCookieSettings() {
  if (typeof window !== "undefined") {
    window.dispatchEvent(new Event(CONSENT_EVENT));
  }
}

export function getPreferences(): CookiePreferences {
  if (typeof window === "undefined") return DEFAULT_PREFERENCES;
  try {
    const raw = window.localStorage.getItem(CONSENT_PREFS_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      return {
        necessary: true,
        analytics: Boolean(parsed.analytics),
        marketing: Boolean(parsed.marketing),
      };
    }
    const legacy = window.localStorage.getItem(CONSENT_KEY);
    if (legacy === "accepted") {
      return { necessary: true, analytics: true, marketing: true };
    }
    if (legacy === "declined") {
      return { necessary: true, analytics: false, marketing: false };
    }
    return DEFAULT_PREFERENCES;
  } catch {
    return DEFAULT_PREFERENCES;
  }
}

export function savePreferences(prefs: CookiePreferences) {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(CONSENT_PREFS_KEY, JSON.stringify(prefs));
    const allAccepted = prefs.analytics && prefs.marketing;
    const allDeclined = !prefs.analytics && !prefs.marketing;
    window.localStorage.setItem(
      CONSENT_KEY,
      allAccepted ? "accepted" : allDeclined ? "declined" : "custom"
    );
  } catch {}
}

export function getConsent(): Consent | null {
  if (typeof window === "undefined") return null;
  try {
    const v = window.localStorage.getItem(CONSENT_KEY);
    return v === "accepted" || v === "declined" ? v : null;
  } catch {
    return null;
  }
}
