/**
 * Service for managing cookie and tracking consent preferences
 */

import Clarity from '@microsoft/clarity';

// Cookie consent levels
export const CONSENT_LEVELS = {
  NECESSARY: 'necessary',
  FUNCTIONAL: 'functional',
  ANALYTICS: 'analytics',
  ALL: 'all'
};

// Local storage key for tracking consent
export const CONSENT_STORAGE_KEY = 'rocks_bones_sticks_cookie_consent';

/**
 * Get stored consent level
 * @returns {Object|null} Stored consent data or null if not set
 */
export const getStoredConsent = () => {
  const storedConsent = localStorage.getItem(CONSENT_STORAGE_KEY);
  return storedConsent ? JSON.parse(storedConsent) : null;
};

/**
 * Check if user has given analytics consent
 * @returns {boolean} Whether analytics is allowed
 */
export const hasAnalyticsConsent = () => {
  const consent = getStoredConsent();
  if (!consent) return false;
  
  return consent.level === CONSENT_LEVELS.ANALYTICS || 
         consent.level === CONSENT_LEVELS.ALL;
};

/**
 * Check if user has given functional cookies consent
 * @returns {boolean} Whether functional cookies are allowed
 */
export const hasFunctionalConsent = () => {
  const consent = getStoredConsent();
  if (!consent) return false;
  
  return consent.level === CONSENT_LEVELS.FUNCTIONAL || 
         consent.level === CONSENT_LEVELS.ANALYTICS || 
         consent.level === CONSENT_LEVELS.ALL;
};

/**
 * Apply consent settings to tracking tools
 * @param {string} level - Consent level to apply
 */
export const applyConsentSettings = (level) => {
  // Determine if analytics is allowed based on consent level
  const allowAnalytics = level === CONSENT_LEVELS.ANALYTICS || level === CONSENT_LEVELS.ALL;
  
  if (allowAnalytics) {
    // Enable Clarity tracking
    Clarity.consent();
  } else {
    // Disable Clarity tracking
    Clarity.consent({ clarity: false });
  }

  console.log(`Applied consent level: ${level}, analytics ${allowAnalytics ? 'enabled' : 'disabled'}`);
};

/**
 * Save user consent preferences
 * @param {string} level - Consent level to save
 */
export const saveConsent = (level) => {
  // Save consent to local storage
  localStorage.setItem(
    CONSENT_STORAGE_KEY, 
    JSON.stringify({
      level,
      timestamp: new Date().toISOString()
    })
  );
  
  // Apply the consent settings
  applyConsentSettings(level);
};

/**
 * Clear stored consent preferences
 */
export const clearConsent = () => {
  localStorage.removeItem(CONSENT_STORAGE_KEY);
  
  // Reset to most restrictive level
  applyConsentSettings(CONSENT_LEVELS.NECESSARY);
};

export default {
  CONSENT_LEVELS,
  getStoredConsent,
  hasAnalyticsConsent,
  hasFunctionalConsent,
  applyConsentSettings,
  saveConsent,
  clearConsent
};