/**
 * Cookie Consent Management
 * GDPR-compliant cookie consent with granular category controls.
 * Preferences are stored in localStorage under "alzar_cookie_consent".
 */

export interface CookiePreferences {
  essential: boolean; // Always true — required for site functionality
  analytics: boolean; // Google Analytics, page tracking
  marketing: boolean; // Future: remarketing, ad pixels
}

export interface ConsentRecord {
  preferences: CookiePreferences;
  timestamp: number; // Unix ms when consent was given/updated
  version: string; // Consent policy version for audit trail
}

const STORAGE_KEY = "alzar_cookie_consent";
const CONSENT_VERSION = "1.0";

/**
 * Default preferences — only essential cookies enabled
 */
export function getDefaultPreferences(): CookiePreferences {
  return {
    essential: true,
    analytics: false,
    marketing: false,
  };
}

/**
 * Read stored consent from localStorage
 */
export function getStoredConsent(): ConsentRecord | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as ConsentRecord;
    // Validate structure
    if (
      parsed &&
      typeof parsed.preferences === "object" &&
      typeof parsed.timestamp === "number" &&
      typeof parsed.version === "string"
    ) {
      // Ensure essential is always true
      parsed.preferences.essential = true;
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
}

/**
 * Save consent preferences to localStorage
 */
export function saveConsent(preferences: CookiePreferences): ConsentRecord {
  const record: ConsentRecord = {
    preferences: { ...preferences, essential: true },
    timestamp: Date.now(),
    version: CONSENT_VERSION,
  };
  localStorage.setItem(STORAGE_KEY, JSON.stringify(record));
  return record;
}

/**
 * Accept all cookies
 */
export function acceptAll(): ConsentRecord {
  return saveConsent({
    essential: true,
    analytics: true,
    marketing: true,
  });
}

/**
 * Reject all optional cookies (keep essential only)
 */
export function rejectAll(): ConsentRecord {
  return saveConsent({
    essential: true,
    analytics: false,
    marketing: false,
  });
}

/**
 * Check if user has given consent (any decision made)
 */
export function hasConsent(): boolean {
  return getStoredConsent() !== null;
}

/**
 * Check if a specific category is allowed
 */
export function isCategoryAllowed(category: keyof CookiePreferences): boolean {
  const consent = getStoredConsent();
  if (!consent) return category === "essential";
  return consent.preferences[category] ?? false;
}

/**
 * Clear all consent data (for testing or user request)
 */
export function clearConsent(): void {
  localStorage.removeItem(STORAGE_KEY);
}
