/** Pinia store for taxi management */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Taxi } from '@/types'
import { taxisService, type TaxiFilters } from '@/services/taxisService'

export const useTaxiStore = defineStore('taxi', () => {
    const taxis = ref<Taxi[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)
    const filters = ref<TaxiFilters>({})

    // 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 | taxiStore: safety timeout — reseteando isLoading')
                isLoading.value = false
            }
        }, 12000)
    }
    function _clearSafetyTimer() {
        if (_safetyTimer) { clearTimeout(_safetyTimer); _safetyTimer = null }
    }

    async function loadTaxis(newFilters?: TaxiFilters, isBackground = false) {
        if (!isBackground) isLoading.value = true
        error.value = null
        if (newFilters) {
            filters.value = newFilters
        }
        if (!isBackground) _startSafetyTimer()
        try {
            taxis.value = await taxisService.getAllTaxis(filters.value)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load taxis'
            console.error('Error loading taxis:', e)
        } finally {
            if (!isBackground) {
                _clearSafetyTimer()
                isLoading.value = false
            }
        }
    }

    function setFilters(newFilters: TaxiFilters) {
        filters.value = newFilters
        loadTaxis()
    }

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

    return {
        taxis,
        isLoading,
        error,
        filters,
        loadTaxis,
        setFilters,
        silentReload,
    }
}, {
    persist: {
        pick: ['taxis']
    }
})

