// filepath: src/stores/settings.ts
import { defineStore } from 'pinia'
import { invoke } from '@tauri-apps/api/core'
import { ref } from 'vue'

export interface Settings {
  download_path: string
  cookies_path?: string
  theme: 'light' | 'dark' | 'system'
  last_updated: string | null
}

export const useSettingsStore = defineStore('settings', () => {
  const settings = ref<Settings>({
    download_path: '',
    cookies_path: '',
    theme: 'system',
    last_updated: null
  })

  const ytdlpVersion = ref('Checking...')
  const quickjsVersion = ref('Checking...')
  const ffmpegVersion = ref('Checking...')
  const isInitializing = ref(true)

  async function loadSettings() {
    try {
      const s = await invoke<Settings>('get_settings')
      settings.value = s
      applyTheme(s.theme)
    } catch (e) {
      console.error("Failed to load settings", e)
    }
  }

  async function save() {
    try {
      await invoke('save_settings', { settings: settings.value })
      applyTheme(settings.value.theme)
    } catch (e) {
      console.error("Failed to save settings", e)
    }
  }

  async function initYtdlp() {
    try {
        isInitializing.value = true
        // check/download
        await invoke('init_ytdlp')
        await refreshVersions()
    } catch (e) {
        console.error(e)
        ytdlpVersion.value = 'Error'
        quickjsVersion.value = 'Error'
      ffmpegVersion.value = 'Error'
    } finally {
        isInitializing.value = false
    }
  }

  async function refreshVersions() {
      ytdlpVersion.value = await invoke('get_ytdlp_version')
      quickjsVersion.value = await invoke('get_quickjs_version')
      ffmpegVersion.value = await invoke('get_ffmpeg_version')
  }

  function applyTheme(theme: string) {
    const root = document.documentElement
    const isDark = theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
    if (isDark) {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
  }

  // Watch system preference changes if theme is system
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
      if (settings.value.theme === 'system') {
          applyTheme('system')
      }
  })

  return { settings, loadSettings, save, initYtdlp, refreshVersions, ytdlpVersion, quickjsVersion, ffmpegVersion, isInitializing }
})