/** Pinia store for shuttle management (Intercity/Tourism) */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Shuttle } from '@/types'
import { shuttlesService, type ShuttleFilters } from '@/services/shuttlesService'

export const useShuttleStore = defineStore('shuttle', () => {
    const shuttles = ref<Shuttle[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)
    const filters = ref<ShuttleFilters>({})

    // Safety: nunca más de 12s cargando (protección contra thread congelado por OS al apagar pantalla)
    let _safetyTimer: ReturnType<typeof setTimeout> | null = null
    function _startSafetyTimer() {
        _clearSafetyTimer()
        _safetyTimer = setTimeout(() => {
            if (isLoading.value) {
                console.warn('SIB | shuttleStore: safety timeout — reseteando isLoading')
                isLoading.value = false
            }
        }, 12000)
    }
    function _clearSafetyTimer() {
        if (_safetyTimer) { clearTimeout(_safetyTimer); _safetyTimer = null }
    }

    async function loadShuttles(newFilters?: ShuttleFilters, isBackground = false) {
        if (!isBackground) isLoading.value = true
        error.value = null
        if (newFilters) {
            filters.value = newFilters
        }
        if (!isBackground) _startSafetyTimer()
        try {
            shuttles.value = await shuttlesService.getAllShuttles(filters.value)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load shuttles'
            console.error('Error loading shuttles:', e)
        } finally {
            if (!isBackground) {
                _clearSafetyTimer()
                isLoading.value = false
            }
        }
    }

    // Recarga silenciosa: no activa el spinner (para refocus desde background)
    async function silentReload() {
        if (shuttles.value.length === 0) { return loadShuttles() }
        error.value = null
        try {
            shuttles.value = await shuttlesService.getAllShuttles(filters.value)
        } catch (e) {
            console.error('Error silent-reloading shuttles:', e)
            // No mostrar error si ya hay datos
        }
    }

    return {
        shuttles,
        isLoading,
        error,
        filters,
        loadShuttles,
        silentReload,
    }
}, {
    persist: {
        pick: ['shuttles']
    }
})
