<script setup>
import { computed, ref, onErrorCaptured } from 'vue';

const props = defineProps({
    caso: Object
});

const hasError = ref(false);
const errorMsg = ref('');

onErrorCaptured((err) => {
    console.error("CarTimeline Error:", err);
    hasError.value = true;
    errorMsg.value = err.message;
    return false; // Stop propagation
});

const safeCompute = (fn, fallback) => {
    try {
        return fn();
    } catch (e) {
        console.error("Compute error:", e);
        return fallback;
    }
};

const stages = [
    { key: 'pendiente_coordinacion', label: 'Asignación' },
    { key: 'coordinado', label: 'Coordinación' },
    { key: 'inspeccion_realizada', label: 'Insp. Realiz' },
    { key: 'caso_en_ruta', label: 'En ruta' },
    { key: 'elaboracion_informe', label: 'Infor. Elabor' },
    { key: 'mesa_compras', label: 'Mesa Compras' },
    { key: 'en_reparacion', label: 'Reparación' },
    { key: 'facturacion', label: 'Facturación' },
];

const stageMapping = {
    'pendiente_coordinacion': 'pendiente_coordinacion',
    'coordinado': 'coordinado',
    'recoordinacion': 'coordinado',
    'no_contesta': 'coordinado',
    'llamar_despues': 'coordinado',
    'vehiculo_retenido': 'coordinado',
    'vehiculo_circulando': 'coordinado',
    'vehiculo_no_taller': 'coordinado',
    'inspeccion_realizada': 'inspeccion_realizada',
    'caso_en_ruta': 'caso_en_ruta',
    'elaboracion_informe': 'elaboracion_informe',
    'mesa_compras': 'mesa_compras',
    'en_reparacion': 'en_reparacion',
    'facturacion': 'facturacion',
    'finalizado': 'facturacion',
    'rechazado': 'facturacion'
};

const currentStageIndex = computed(() => safeCompute(() => {
    const estado = props.caso?.estado_actual || '';
    const currentMapped = stageMapping[estado] || estado;
    const curIdx = stages.findIndex(s => s.key === currentMapped);
    if (curIdx !== -1) return curIdx;

    const hist = props.caso?.estados_historicos || [];
    const states = hist.map(h => h ? (stageMapping[h.estado] || h.estado) : '') || [];
    let highIdx = 0;
    stages.forEach((s, idx) => {
        if (states.includes(s.key)) highIdx = idx;
    });
    return highIdx;
}, 0));

const activeStyle = computed(() => safeCompute(() => {
    const estado = props.caso?.estado_actual || '';
    if (stageMapping[estado] === estado) {
        return {
            node: 'bg-blue-600 ring-4 ring-blue-100',
            label: 'text-blue-700',
            carBg: 'bg-blue-600 shadow-blue-400/50',
            pulse: 'bg-blue-400/20'
        };
    }
    
    const mapping = {
        'recoordinacion': { node: 'bg-amber-500 ring-4 ring-amber-100', label: 'text-amber-600', carBg: 'bg-amber-500 shadow-amber-400/50', pulse: 'bg-amber-400/20' },
        'no_contesta': { node: 'bg-red-500 ring-4 ring-red-100', label: 'text-red-600', carBg: 'bg-red-500 shadow-red-400/50', pulse: 'bg-red-400/20' },
        'llamar_despues': { node: 'bg-orange-500 ring-4 ring-orange-100', label: 'text-orange-600', carBg: 'bg-orange-500 shadow-orange-400/50', pulse: 'bg-orange-400/20' },
        'vehiculo_retenido': { node: 'bg-red-600 ring-4 ring-red-100', label: 'text-red-700', carBg: 'bg-red-600 shadow-red-500/50', pulse: 'bg-red-500/20' },
        'vehiculo_circulando': { node: 'bg-emerald-500 ring-4 ring-emerald-100', label: 'text-emerald-600', carBg: 'bg-emerald-500 shadow-emerald-400/50', pulse: 'bg-emerald-400/20' },
        'vehiculo_no_taller': { node: 'bg-indigo-500 ring-4 ring-indigo-100', label: 'text-indigo-600', carBg: 'bg-indigo-500 shadow-indigo-400/50', pulse: 'bg-indigo-400/20' }
    };
    
    return mapping[estado] || {
        node: 'bg-blue-600 ring-4 ring-blue-100',
        label: 'text-blue-700',
        carBg: 'bg-blue-600 shadow-blue-400/50',
        pulse: 'bg-blue-400/20'
    };
}, { node: 'bg-blue-600 ring-4 ring-blue-100', label: 'text-blue-700', carBg: 'bg-blue-600 shadow-blue-400/50', pulse: 'bg-blue-400/20' }));

const getStageLabel = (stage, index) => safeCompute(() => {
    if (index === currentStageIndex.value) {
        const estado = props.caso?.estado_actual || '';
        const currentMapped = stageMapping[estado] || estado;
        if (currentMapped === stage.key && estado !== stage.key) {
            const labels = {
                'recoordinacion': 'Re-coord.',
                'no_contesta': 'No Contesta',
                'llamar_despues': 'Llamar Desp.',
                'vehiculo_retenido': 'Retenido',
                'vehiculo_circulando': 'Circulando',
                'vehiculo_no_taller': 'No en Taller'
            };
            return labels[estado] || estado.replace(/_/g, ' ');
        }
    }
    return stage.label;
}, stage.label);

const formatDurationJS = (mins) => {
    if (!mins || isNaN(mins)) return '0m';
    if (mins < 1) return '< 1m';
    if (mins < 60) return `${mins}m`;
    if (mins < 1440) {
        const h = Math.floor(mins / 60);
        const m = mins % 60;
        return `${h}h ${m}m`;
    }
    if (mins < 10080) {
        const d = Math.floor(mins / 1440);
        const h = Math.floor((mins % 1440) / 60);
        return `${d}d ${h}h`;
    }
    const w = Math.floor(mins / 10080);
    const d = Math.floor((mins % 10080) / 1440);
    return `${w}sem ${d}d`;
};

const getStageLog = (stageKey) => safeCompute(() => {
    const hist = props.caso?.estados_historicos;
    if (!hist || !Array.isArray(hist)) return null;
    for (let i = hist.length - 1; i >= 0; i--) {
        const log = hist[i];
        if (log && stageMapping[log.estado] === stageKey) {
            return log;
        }
    }
    return null;
}, null);

const isCurrentStage = (stageKey) => safeCompute(() => {
    const estado = props.caso?.estado_actual || '';
    const currentMapped = stageMapping[estado] || estado;
    return currentMapped === stageKey;
}, false);

const parseSafeDate = (d) => {
    try {
        if (!d) return new Date();
        if (typeof d === 'string') return new Date(d.replace(' ', 'T'));
        return new Date(d);
    } catch (e) {
        return new Date();
    }
};

const getDuration = (stageKey) => safeCompute(() => {
    const log = getStageLog(stageKey);
    if (!log) return '0m';
    
    let mins = log.duracion_minutas;
    if (isCurrentStage(stageKey)) {
        const start = log.fecha_ingreso || log.created_at;
        if (start) {
            const startDate = parseSafeDate(start);
            const endDate = new Date();
            const diffMs = endDate - startDate;
            if (diffMs > 0 && !isNaN(diffMs)) {
                mins = Math.floor(diffMs / 60000);
            }
        }
    } else if (!mins) {
        const start = log.fecha_ingreso || log.created_at;
        if (start) {
            const startDate = parseSafeDate(start);
            const endDate = log.fecha_salida ? parseSafeDate(log.fecha_salida) : new Date();
            const diffMs = endDate - startDate;
            if (diffMs > 0 && !isNaN(diffMs)) {
                mins = Math.floor(diffMs / 60000);
            }
        }
    }
    
    return formatDurationJS(mins || 0);
}, '0m');

const getStateDate = (stateKey) => safeCompute(() => {
    const log = getStageLog(stageKey);
    const date = log?.fecha_ingreso || log?.created_at;
    if (!date) return '';
    try {
        const parsedDate = parseSafeDate(date);
        if (isNaN(parsedDate.getTime())) return '';
        return parsedDate.toLocaleString('es-EC', {
            day: '2-digit',
            month: 'short',
            hour: '2-digit',
            minute: '2-digit'
        }).replace(',', '');
    } catch (e) {
        return '';
    }
}, '');
</script>

<template>
    <div v-if="hasError" class="p-4 bg-red-50 text-red-600 rounded-xl text-xs font-mono">
        Error renderizando gráfico: {{ errorMsg }}
    </div>
    <div v-else class="bg-slate-50 rounded-2xl border border-slate-100 overflow-x-auto hide-scrollbar">
        <div class="min-w-[600px] relative pt-20 pb-8 px-6">
            <!-- Track Line -->
            <div class="absolute left-6 right-6 top-1/2 h-1 bg-slate-200 -translate-y-1/2 rounded-full"></div>
            <div class="absolute left-6 top-1/2 h-1 bg-blue-500 -translate-y-1/2 rounded-full transition-all duration-1000"
                 :style="{ width: `calc(${(currentStageIndex / Math.max(1, stages.length - 1)) * 100}%)` }">
            </div>

            <div class="relative flex justify-between items-center z-10">
            <div v-for="(stage, index) in stages" :key="index" class="relative group flex flex-col items-center">
                <!-- Node -->
                <div :class="[
                    'w-4 h-4 rounded-full border-2 border-white shadow-sm transition-all duration-300',
                    index < currentStageIndex ? 'bg-blue-600 ring-4 ring-blue-100' :
                    index === currentStageIndex ? activeStyle.node :
                    'bg-slate-300 ring-4 ring-transparent'
                ]"></div>
                
                <!-- Label -->
                <div class="h-8 mt-2 flex items-start justify-center">
                    <span :class="[
                        'text-[9px] font-bold uppercase tracking-tight transition-colors text-center w-16 leading-tight break-words',
                        index < currentStageIndex ? 'text-blue-700' :
                        index === currentStageIndex ? activeStyle.label :
                        'text-slate-400'
                    ]">
                        {{ getStageLabel(stage, index) }}
                    </span>
                </div>

                <!-- Duration Tooltip -->
                <div class="absolute -top-12 scale-0 group-hover:scale-100 transition-transform origin-bottom bg-slate-900 text-white px-2 py-1.5 rounded text-[9px] font-bold text-center shadow-xl z-50 flex flex-col gap-0.5 whitespace-nowrap">
                    <span v-if="getStateDate(stage.key)" class="text-slate-400 font-medium">
                        {{ isCurrentStage(stage.key) ? 'Activo desde:' : 'Ingresó:' }} {{ getStateDate(stage.key) }}
                    </span>
                    <span>
                        {{ isCurrentStage(stage.key) ? 'Tiempo actual:' : 'Duración:' }} {{ getDuration(stage.key) }}
                    </span>
                    <div class="absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-slate-900 rotate-45"></div>
                </div>

                <!-- Car Icon -->
                <div v-if="index === currentStageIndex" class="absolute -top-14 animate-bounce">
                    <div class="relative">
                        <!-- Radar Pulse -->
                        <div class="absolute inset-0 w-12 h-12 -left-3 -top-3 rounded-full animate-ping" :class="activeStyle.pulse"></div>
                        <div class="text-white p-2.5 rounded-xl shadow-lg flex items-center justify-center transition-colors" :class="activeStyle.carBg">
                            <font-awesome-icon :icon="['fas', 'car-side']" class="w-5 h-5" />
                        </div>
                    </div>
                </div>
            </div>
            </div>
        </div>
    </div>
</template>
