'use client'

export type CookieConsent = {
  essential: true
  analytics: boolean
  decidedAt: string
}

const STORAGE_KEY = 'ov-cookie-consent'

export function getConsent(): CookieConsent | null {
  if (typeof window === 'undefined') return null
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as CookieConsent) : null
  } catch {
    return null
  }
}

export function saveConsent(analytics: boolean): CookieConsent {
  const consent: CookieConsent = {
    essential: true,
    analytics,
    decidedAt: new Date().toISOString(),
  }
  localStorage.setItem(STORAGE_KEY, JSON.stringify(consent))
  return consent
}

export function clearConsent(): void {
  localStorage.removeItem(STORAGE_KEY)
}
