// Cookie consent storage utility
// Manages user cookie preferences with a single consent cookie

export const CONSENT_COOKIE_NAME = 'mbhs_cookie_consent';
export const CONSENT_VERSION = 1;
export const CONSENT_EXPIRY_DAYS = 180; // 6 months

export interface CookieConsent {
  analytics: boolean;
  preferences: boolean;
  marketing: boolean;
  version: number;
  timestamp: string;
}

const DEFAULT_CONSENT: CookieConsent = {
  analytics: false,
  preferences: false,
  marketing: false,
  version: CONSENT_VERSION,
  timestamp: '',
};

/**
 * Read the consent cookie. Returns null if no consent has been given.
 */
export function getConsentCookie(): CookieConsent | null {
  if (typeof window === 'undefined') return null;

  const match = document.cookie.match(
    new RegExp(`(^| )${CONSENT_COOKIE_NAME}=([^;]+)`)
  );
  if (!match) return null;

  try {
    const consent = JSON.parse(decodeURIComponent(match[2])) as CookieConsent;
    // If consent version doesn't match, treat as no consent
    if (consent.version !== CONSENT_VERSION) return null;
    return consent;
  } catch {
    return null;
  }
}

/**
 * Write the consent cookie.
 */
export function setConsentCookie(consent: CookieConsent): void {
  if (typeof window === 'undefined') return;

  const maxAge = 60 * 60 * 24 * CONSENT_EXPIRY_DAYS;
  const secure = window.location.protocol === 'https:' ? '; Secure' : '';
  const value = encodeURIComponent(JSON.stringify(consent));
  document.cookie = `${CONSENT_COOKIE_NAME}=${value}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;

  // Dispatch event so AnalyticsGate can react without a page reload
  window.dispatchEvent(new CustomEvent('cookie-consent-changed', { detail: consent }));
}

/**
 * Accept all cookie categories.
 */
export function acceptAllCookies(): void {
  setConsentCookie({
    analytics: true,
    preferences: true,
    marketing: true,
    version: CONSENT_VERSION,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Reject all non-essential cookies.
 */
export function rejectAllCookies(): void {
  setConsentCookie({
    ...DEFAULT_CONSENT,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Save specific preferences.
 */
export function saveConsentPreferences(
  prefs: Pick<CookieConsent, 'analytics' | 'preferences' | 'marketing'>
): void {
  setConsentCookie({
    ...prefs,
    version: CONSENT_VERSION,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Check if a specific category is consented.
 */
export function hasConsent(category: 'analytics' | 'preferences' | 'marketing'): boolean {
  const consent = getConsentCookie();
  if (!consent) return false;
  return consent[category];
}
