/** Paletas de acento del rancho (persistidas en localStorage). */
export const THEME_COLOR_KEY = 'ranch_theme_color'

export const themeColorPresets = [
  { id: 'verde', label: 'Verde rancho', hex: '#2d6a4f', light: '#40916c', dark: '#1b4332' },
  { id: 'azul', label: 'Azul', hex: '#1d4ed8', light: '#3b82f6', dark: '#1e3a8a' },
  { id: 'teal', label: 'Teal', hex: '#0f766e', light: '#14b8a6', dark: '#115e59' },
  { id: 'ambar', label: 'Ámbar', hex: '#b45309', light: '#d97706', dark: '#92400e' },
  { id: 'rojo', label: 'Rojo tierra', hex: '#b91c1c', light: '#ef4444', dark: '#7f1d1d' },
  { id: 'morado', label: 'Morado', hex: '#6d28d9', light: '#8b5cf6', dark: '#4c1d95' },
  { id: 'slate', label: 'Pizarra', hex: '#334155', light: '#64748b', dark: '#0f172a' },
]

export const DEFAULT_THEME_COLOR = themeColorPresets[0]

export function findThemePreset(idOrHex) {
  if (!idOrHex) return DEFAULT_THEME_COLOR
  return (
    themeColorPresets.find((p) => p.id === idOrHex || p.hex.toLowerCase() === String(idOrHex).toLowerCase())
    || DEFAULT_THEME_COLOR
  )
}

export function hexToRgb(hex) {
  const h = String(hex).replace('#', '')
  const full = h.length === 3 ? h.split('').map((c) => c + c).join('') : h
  const n = parseInt(full, 16)
  return {
    r: (n >> 16) & 255,
    g: (n >> 8) & 255,
    b: n & 255,
  }
}

/**
 * Aplica variables CSS de acento en :root
 */
export function applyThemeColorVars(preset) {
  const p = preset || DEFAULT_THEME_COLOR
  const root = document.documentElement
  const { r, g, b } = hexToRgb(p.hex)
  root.style.setProperty('--ranch-accent', p.hex)
  root.style.setProperty('--ranch-accent-light', p.light)
  root.style.setProperty('--ranch-accent-dark', p.dark)
  root.style.setProperty('--ranch-accent-rgb', `${r}, ${g}, ${b}`)
  root.style.setProperty('--bs-primary', p.hex)
  root.style.setProperty('--bs-primary-rgb', `${r}, ${g}, ${b}`)
  root.setAttribute('data-theme-color', p.id)
}
