"use client";

export const COOKIE_CONSENT_STORAGE_KEY = "videohaus:cookie-consent-v1";
export const COOKIE_CONSENT_UPDATED_EVENT = "videohaus:cookie-consent-updated";

interface CookieConsentState {
  version: 1;
  essential: true;
  analytics: boolean;
  consentedAt: number;
}

function isCookieConsentState(value: unknown): value is CookieConsentState {
  if (!value || typeof value !== "object") {
    return false;
  }

  const candidate = value as Partial<CookieConsentState>;
  return (
    candidate.version === 1 &&
    candidate.essential === true &&
    typeof candidate.analytics === "boolean" &&
    typeof candidate.consentedAt === "number"
  );
}

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

  const rawValue = window.localStorage.getItem(COOKIE_CONSENT_STORAGE_KEY);
  if (!rawValue) {
    return null;
  }

  try {
    const parsedValue = JSON.parse(rawValue) as unknown;
    return isCookieConsentState(parsedValue) ? parsedValue : null;
  } catch {
    return null;
  }
}

export function writeCookieConsent({ analytics }: { analytics: boolean }) {
  if (typeof window === "undefined") {
    return;
  }

  const nextConsent: CookieConsentState = {
    version: 1,
    essential: true,
    analytics,
    consentedAt: Date.now()
  };

  window.localStorage.setItem(COOKIE_CONSENT_STORAGE_KEY, JSON.stringify(nextConsent));
  window.dispatchEvent(new CustomEvent(COOKIE_CONSENT_UPDATED_EVENT));
}

export function clearCookieConsent() {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(COOKIE_CONSENT_STORAGE_KEY);
  window.dispatchEvent(new CustomEvent(COOKIE_CONSENT_UPDATED_EVENT));
}

