const STORAGE_KEY = 'calctext-theme'
const ACCENT_KEY = 'calctext-accent'

export type ThemeId = 'system' | 'light' | 'dark' | 'matrix' | 'midnight' | 'warm'

export const THEMES: { id: ThemeId; name: string; icon: string }[] = [
  { id: 'light', name: 'Light', icon: '☀️' },
  { id: 'dark', name: 'Dark', icon: '🌙' },
  { id: 'matrix', name: 'Matrix', icon: '💻' },
  { id: 'midnight', name: 'Midnight', icon: '🌊' },
  { id: 'warm', name: 'Warm', icon: '📜' },
]

export const ACCENT_COLORS = [
  { name: 'Indigo', light: '#6366f1', dark: '#818cf8' },
  { name: 'Teal', light: '#14b8a6', dark: '#2dd4bf' },
  { name: 'Rose', light: '#f43f5e', dark: '#fb7185' },
  { name: 'Amber', light: '#f59e0b', dark: '#fbbf24' },
  { name: 'Emerald', light: '#10b981', dark: '#34d399' },
  { name: 'Sky', light: '#0ea5e9', dark: '#38bdf8' },
]

function getStoredTheme(): ThemeId {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored && ['system', 'light', 'dark', 'matrix', 'midnight', 'warm'].includes(stored)) {
      return stored as ThemeId
    }
  } catch { /* localStorage unavailable */ }
  return 'system'
}

function getStoredAccent(): string | null {
  try {
    return localStorage.getItem(ACCENT_KEY)
  } catch { return null }
}

function resolveSystemTheme(): 'light' | 'dark' {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

function isDarkTheme(theme: ThemeId): boolean {
  if (theme === 'system') return resolveSystemTheme() === 'dark'
  return theme === 'dark' || theme === 'matrix' || theme === 'midnight'
}

import { useState, useEffect, useCallback } from 'react'

export function useTheme() {
  const [theme, setThemeState] = useState<ThemeId>(getStoredTheme)
  const [accentColor, setAccentState] = useState<string | null>(getStoredAccent)

  const resolvedTheme = theme === 'system' ? resolveSystemTheme() : theme

  const setTheme = useCallback((id: ThemeId) => {
    setThemeState(id)
    try { localStorage.setItem(STORAGE_KEY, id) } catch { /* */ }
    applyTheme(id, accentColor)
  }, [accentColor])

  const setAccent = useCallback((color: string | null) => {
    setAccentState(color)
    try {
      if (color) localStorage.setItem(ACCENT_KEY, color)
      else localStorage.removeItem(ACCENT_KEY)
    } catch { /* */ }
    applyTheme(theme, color)
  }, [theme])

  // Listen for system theme changes
  useEffect(() => {
    if (theme !== 'system') return
    const mq = window.matchMedia('(prefers-color-scheme: dark)')
    const handler = () => applyTheme('system', accentColor)
    mq.addEventListener('change', handler)
    return () => mq.removeEventListener('change', handler)
  }, [theme, accentColor])

  // Apply on mount
  useEffect(() => {
    applyTheme(theme, accentColor)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  return {
    theme,
    resolvedTheme,
    setTheme,
    accentColor,
    setAccent,
    isDark: isDarkTheme(theme),
    themes: THEMES,
    accentColors: ACCENT_COLORS,
  }
}

function applyTheme(theme: ThemeId, accent: string | null) {
  const resolved = theme === 'system'
    ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
    : theme

  document.documentElement.setAttribute('data-theme', resolved)

  // Apply custom accent if set
  if (accent) {
    const dark = isDarkTheme(theme)
    document.documentElement.style.setProperty('--accent', accent)
    document.documentElement.style.setProperty('--accent-bg', hexToRgba(accent, dark ? 0.15 : 0.1))
    document.documentElement.style.setProperty('--accent-border', hexToRgba(accent, 0.5))
  } else {
    document.documentElement.style.removeProperty('--accent')
    document.documentElement.style.removeProperty('--accent-bg')
    document.documentElement.style.removeProperty('--accent-border')
  }

  // Update PWA theme-color
  const meta = document.querySelector('meta[name="theme-color"]')
  if (meta) {
    const bgColors: Record<string, string> = {
      light: '#ffffff',
      dark: '#16171d',
      matrix: '#0a0a0a',
      midnight: '#0f172a',
      warm: '#fffbf5',
    }
    meta.setAttribute('content', bgColors[resolved] ?? '#ffffff')
  }
}

function hexToRgba(hex: string, alpha: number): string {
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}
