const CONSENT_COOKIE_NAME = 'cookie_consent';
const CATEGORIES_COOKIE_NAME = 'cookie_consent_categories';
const CONSENT_EXPIRY_DAYS = 365;

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

type ConsentStatus = 'accepted' | 'declined' | null;

export function getConsentStatus(): ConsentStatus {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${CONSENT_COOKIE_NAME}=([^;]*)`));
  if (!match) return null;
  const value = decodeURIComponent(match[1]);
  if (value === 'accepted' || value === 'declined') return value;
  return null;
}

export function setCookieConsent(name: string, value: string): void {
  const expires = new Date();
  expires.setDate(expires.getDate() + CONSENT_EXPIRY_DAYS);
  document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
}

export function getCategoryConsent(category: keyof ConsentCategories): boolean {
  if (typeof document === 'undefined') return false;
  if (category === 'necessary') return true;

  const status = getConsentStatus();
  if (status === null) return false;

  const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${CATEGORIES_COOKIE_NAME}=([^;]*)`));
  if (!match) return status === 'accepted';

  try {
    const cats = JSON.parse(decodeURIComponent(match[1])) as Record<string, boolean>;
    return cats[category] === true;
  } catch {
    return status === 'accepted';
  }
}

/**
 * Reset PostHog identity when analytics consent is revoked (GDPR requirement).
 * Must be called whenever analytics consent transitions from granted to revoked.
 */
export function resetAnalyticsIdentity(): void {
  if (typeof window === 'undefined') return;
  // PostHog SDK sets window.posthog after init
  const ph = (window as unknown as Record<string, unknown>).posthog as { reset?: () => void } | undefined;
  if (ph?.reset) {
    ph.reset();
  }
}

export { CONSENT_COOKIE_NAME, CATEGORIES_COOKIE_NAME };
