/**
 * useUpdater — checks for a new BIBIVIDI desktop version on startup.
 *
 * Only active when running inside Tauri (window.__TAURI__ is defined).
 * In a plain browser / web mode the hook is a no-op.
 */
import { useCallback, useEffect, useState } from 'react'

export interface UpdateState {
  available: boolean
  version: string | null
  installing: boolean
  error: string | null
}

export function useUpdater() {
  const [state, setState] = useState<UpdateState>({
    available: false,
    version: null,
    installing: false,
    error: null,
  })

  const isTauri = typeof window !== 'undefined' && '__TAURI__' in window

  useEffect(() => {
    if (!isTauri) return

    // Delay 3 s so the app is fully loaded before hitting the network
    const timer = setTimeout(async () => {
      try {
        const { invoke } = await import('@tauri-apps/api/core')
        const version: string | null = await invoke('check_for_update')
        if (version) {
          setState(s => ({ ...s, available: true, version }))
        }
      } catch {
        // Silently ignore — update check is best-effort
      }
    }, 3000)

    return () => clearTimeout(timer)
  }, [isTauri])

  const install = useCallback(async () => {
    if (!isTauri) return
    setState(s => ({ ...s, installing: true, error: null }))
    try {
      const { invoke } = await import('@tauri-apps/api/core')
      await invoke('install_update')
      // install_update restarts the app — code below is never reached
    } catch (err) {
      setState(s => ({ ...s, installing: false, error: String(err) }))
    }
  }, [isTauri])

  const dismiss = useCallback(() => {
    setState(s => ({ ...s, available: false }))
  }, [])

  return { ...state, install, dismiss }
}
