// src/stores/theme.ts

import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { ThemeOption } from '../types/models'

const STORAGE_KEY = 'user_theme'
const DEFAULT_THEME = 'dark'

export const AVAILABLE_THEMES: ThemeOption[] = [
  { name: 'dark', label: 'Dark', preview: '#ff6600' },
  { name: 'vscode-dark', label: 'VS Code Dark', preview: '#569CD6' },
  { name: 'grok-dark', label: 'Grok Dark', preview: '#F05A28' },
  { name: 'arctic', label: 'Arctic', preview: '#06b6d4' },
  { name: 'midnight', label: 'Midnight', preview: '#a78bfa' },
  { name: 'high-contrast', label: 'High Contrast', preview: '#FFD700' },
  { name: 'atom-one-dark', label: 'Atom One Dark', preview: '#61AFEF' },
  { name: 'cobalt2', label: 'Cobalt2', preview: '#FFC600' },
  { name: 'jellyfish', label: 'Jellyfish', preview: '#FF6AC1' },
]

export const useThemeStore = defineStore('theme', () => {
  // --- STATE ---
  const currentTheme = ref(localStorage.getItem(STORAGE_KEY) || DEFAULT_THEME)

  // --- ACTIONS ---
  function setTheme(theme: string) {
    const validTheme = AVAILABLE_THEMES.find(t => t.name === theme)
    if (validTheme) {
      currentTheme.value = theme
      localStorage.setItem(STORAGE_KEY, theme)
      document.documentElement.setAttribute('data-theme', theme)
    }
  }

  function initTheme(serverDefault?: string) {
    // Validate stored theme is still valid
    const storedTheme = localStorage.getItem(STORAGE_KEY)
    const validTheme = AVAILABLE_THEMES.find(t => t.name === storedTheme)
    if (validTheme) {
      currentTheme.value = storedTheme!
    } else {
      const fallback = serverDefault || DEFAULT_THEME
      currentTheme.value = fallback
      localStorage.setItem(STORAGE_KEY, fallback)
    }
    document.documentElement.setAttribute('data-theme', currentTheme.value)
  }

  // --- RETURN ---
  return {
    currentTheme,
    setTheme,
    initTheme,
    AVAILABLE_THEMES,
  }
})
