import { map } from 'nanostores';

export interface ConsentState {
  analytics: boolean;
  marketing: boolean;
  functional: boolean;
  hasConsented: boolean;
  timestamp?: string;
}

export interface ConsentLogData extends ConsentState {
  ip?: string;
  userAgent?: string;
}

export const defaultConsent: ConsentState = {
  analytics: false,
  marketing: false,
  functional: false,
  hasConsented: false,
};

export const consentStore = map<ConsentState>(defaultConsent);
export const STORAGE_KEY = 'pdpa_consent';

export function loadConsent(): ConsentState {
  if (typeof localStorage === 'undefined') {
    return defaultConsent;
  }

  const stored = localStorage.getItem(STORAGE_KEY);
  if (stored) {
    try {
      const parsed = JSON.parse(stored) as ConsentState;
      consentStore.set(parsed);
      return parsed;
    } catch {
      return defaultConsent;
    }
  }
  return defaultConsent;
}

export function saveConsentLocally(state: ConsentState): void {
  if (typeof localStorage === 'undefined') return;
  
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
  consentStore.set(state);
}

export function hasAnalyticsConsent(): boolean {
  const state = consentStore.get();
  return state.hasConsented && state.analytics;
}

export function hasMarketingConsent(): boolean {
  const state = consentStore.get();
  return state.hasConsented && state.marketing;
}

export function hasFunctionalConsent(): boolean {
  const state = consentStore.get();
  return state.hasConsented;
}

export function resetConsent(): void {
  if (typeof localStorage === 'undefined') return;
  
  localStorage.removeItem(STORAGE_KEY);
  consentStore.set(defaultConsent);
}

export function hasConsented(): boolean {
  return consentStore.get().hasConsented;
}