import { create } from 'zustand'; import { persist } from 'zustand/middleware'; export const CURRENT_CONSENT_VERSION = '1.0'; export interface CookiePreferences { necessary: boolean; analytics: boolean; marketing: boolean; } export interface CookieConsentRecord { hasResponded: boolean; version: string; timestamp: string | null; preferences: CookiePreferences; } interface CookieConsentState { record: CookieConsentRecord; isPreferencesOpen: boolean; isHydrated: boolean; // Actions setHydrated: (hydrated: boolean) => void; openPreferences: () => void; closePreferences: () => void; acceptAll: () => void; rejectAll: () => void; savePreferences: (preferences: Partial) => void; resetConsent: () => void; } const DEFAULT_RECORD: CookieConsentRecord = { hasResponded: false, version: CURRENT_CONSENT_VERSION, timestamp: null, preferences: { necessary: true, analytics: false, marketing: false, }, }; export const useCookieConsentStore = create()( persist( (set) => ({ record: DEFAULT_RECORD, isPreferencesOpen: false, isHydrated: false, setHydrated: (hydrated: boolean) => set({ isHydrated: hydrated }), openPreferences: () => set({ isPreferencesOpen: true }), closePreferences: () => set({ isPreferencesOpen: false }), acceptAll: () => { const now = new Date().toISOString(); set({ record: { hasResponded: true, version: CURRENT_CONSENT_VERSION, timestamp: now, preferences: { necessary: true, analytics: true, marketing: true, }, }, isPreferencesOpen: false, }); }, rejectAll: () => { const now = new Date().toISOString(); set({ record: { hasResponded: true, version: CURRENT_CONSENT_VERSION, timestamp: now, preferences: { necessary: true, analytics: false, marketing: false, }, }, isPreferencesOpen: false, }); }, savePreferences: (userPrefs: Partial) => { const now = new Date().toISOString(); set((state) => ({ record: { hasResponded: true, version: CURRENT_CONSENT_VERSION, timestamp: now, preferences: { necessary: true, analytics: Boolean(userPrefs.analytics), marketing: Boolean(userPrefs.marketing), }, }, isPreferencesOpen: false, })); }, resetConsent: () => { set({ record: DEFAULT_RECORD, isPreferencesOpen: false, }); }, }), { name: 'homaroma-cookie-consent', partialize: (state) => ({ record: state.record }), skipHydration: true, onRehydrateStorage: () => (state) => { state?.setHydrated(true); }, } ) );