import { useState } from 'react'
import type { HeatmapMode } from '@/lib/colors'

const STORAGE_KEY = 'inq-roi:heatmap-mode'
const DEFAULT_MODE: HeatmapMode = 'percentile'

function isValidMode(value: string | null): value is HeatmapMode {
  return value === 'percentile' || value === 'minmax'
}

// Persiste la preferencia de modo de heatmap en localStorage. Nunca confía en el string
// crudo leído de localStorage sin validarlo contra los modos válidos.
export function useHeatmapMode(): [HeatmapMode, (mode: HeatmapMode) => void] {
  const [mode, setModeState] = useState<HeatmapMode>(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      return isValidMode(stored) ? stored : DEFAULT_MODE
    } catch {
      return DEFAULT_MODE
    }
  })

  function setMode(newMode: HeatmapMode) {
    try {
      localStorage.setItem(STORAGE_KEY, newMode)
    } catch {
      // localStorage no disponible (modo privado, cuota excedida) — continuar sin persistir
    }
    setModeState(newMode)
  }

  return [mode, setMode]
}
