'use client';

export const COOKIE_CONSENT_KEY = 'rm_cookie_consent';
export const COOKIE_CONSENT_EVENT = 'rm:cookie-consent';
const COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;

export type CookieConsentState = 'pending' | 'accepted' | 'rejected';

function hasSecureContext(): boolean {
  return typeof window !== 'undefined' && window.location.protocol === 'https:';
}

function readCookieValue(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
  if (!match) return null;
  try {
    return decodeURIComponent(match[1]);
  } catch {
    return match[1];
  }
}

function writeCookieValue(name: string, value: string): void {
  if (typeof document === 'undefined') return;
  const secure = hasSecureContext() ? ' Secure;' : '';
  document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax;${secure}`;
}

export function readCookieConsent(): CookieConsentState {
  if (typeof window === 'undefined') return 'pending';

  try {
    const value = window.localStorage.getItem(COOKIE_CONSENT_KEY);
    if (value === 'accepted' || value === 'rejected') return value;
  } catch {
    // Fall through to cookie lookup when localStorage is blocked.
  }

  const cookieValue = readCookieValue(COOKIE_CONSENT_KEY);
  return cookieValue === 'accepted' || cookieValue === 'rejected' ? cookieValue : 'pending';
}

export function writeCookieConsent(value: Exclude<CookieConsentState, 'pending'>): void {
  try {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(COOKIE_CONSENT_KEY, value);
    }
  } catch {
    // Cookie mirror still lets the backend read consent for server-side tracking.
  }

  writeCookieValue(COOKIE_CONSENT_KEY, value);
  window.dispatchEvent(new Event(COOKIE_CONSENT_EVENT));
}

export function hasAnalyticsConsent(): boolean {
  return readCookieConsent() === 'accepted';
}
