<script setup>
import { ref, computed, onBeforeUnmount } from 'vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';

delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});

const props = defineProps({
  title: String,
  caso: Object,
  ajustadores: Array,
  talleres: Array,
  estados: Object
});

const form = useForm({
  ajustador_id: props.caso.ajustador_id || '',
  taller_id: props.caso.taller_id || '',
  tipo_ajuste: props.caso.tipo_ajuste || 'presencial',
  tarifa_ajustador_tipo: props.caso.tarifa_ajustador_tipo || 'liviano',
  tarifa_ajustador_valor: props.caso.tarifa_ajustador_valor || 0,
  kilometros: props.caso.kilometros || 0,
  tarifa_kilometro: props.caso.tarifa_kilometro || 0,
  ubicacion_vehiculo: props.caso.ubicacion_vehiculo || 'taller',
  ubicacion_vehiculo_otro: props.caso.ubicacion_vehiculo_otro || '',
  nombre_dp_rc: props.caso.nombre_dp_rc || 'DP',
  particular_ciudad: props.caso.particular_ciudad || '',
  fecha_inspeccion: props.caso.fecha_inspeccion || '',
  direccion_inspeccion: props.caso.direccion_inspeccion || '',
  lat_inspeccion: props.caso.lat_inspeccion || '',
  lng_inspeccion: props.caso.lng_inspeccion || '',
  observaciones: props.caso.observaciones || '',
  estado_actual: 'coordinado'
});

const showDatePicker = ref(false);

const adjustersTariffs = {
  liviano: 35,
  pesado: 55,
  express: 15,
  virtual: 20,
  particular: 20
};

const updateTariff = () => {
    form.tarifa_ajustador_valor = adjustersTariffs[form.tarifa_ajustador_tipo] || 0;
};

const totalTarifa = computed(() => {
    const tarifa = parseFloat(form.tarifa_ajustador_valor || 0);
    const km = parseFloat(form.kilometros || 0) * parseFloat(form.tarifa_kilometro || 0);
    return (tarifa + km).toFixed(2);
});

if (!form.tarifa_ajustador_valor) updateTariff();

const ECUADOR_CENTER = { lat: -0.180653, lng: -78.467838 };

const getInitialPosition = () => {
  if (props.caso.lat_inspeccion && props.caso.lng_inspeccion) {
    return {
      lat: parseFloat(props.caso.lat_inspeccion),
      lng: parseFloat(props.caso.lng_inspeccion),
    };
  }
  return null;
};

const showMapModal = ref(false);
const useDeviceLocation = ref(!getInitialPosition());
const mapLat = ref(getInitialPosition()?.lat ?? ECUADOR_CENTER.lat);
const mapLng = ref(getInitialPosition()?.lng ?? ECUADOR_CENTER.lng);
const mapAddress = ref(props.caso.direccion_inspeccion || '');
const resolvingAddress = ref(false);
let mapInstance = null;
let marker = null;

const openMapModal = () => {
  showMapModal.value = true;
  setTimeout(() => {
    initMap();
    if (useDeviceLocation.value) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          mapLat.value = pos.coords.latitude;
          mapLng.value = pos.coords.longitude;
          if (marker) {
            marker.setLatLng([mapLat.value, mapLng.value]);
            mapInstance.setView([mapLat.value, mapLng.value], 15);
          }
          reverseGeocode(mapLat.value, mapLng.value);
        },
        () => {
          useDeviceLocation.value = false;
        },
        { enableHighAccuracy: true, timeout: 10000 }
      );
    }
  }, 200);
};

const initMap = () => {
  const el = document.getElementById('map-picker');
  if (!el || mapInstance) return;

  mapInstance = L.map('map-picker', {
    center: [mapLat.value, mapLng.value],
    zoom: 15,
  });

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors',
    maxZoom: 19,
  }).addTo(mapInstance);

  marker = L.marker([mapLat.value, mapLng.value], { draggable: true }).addTo(mapInstance);

  marker.on('dragend', () => {
    const pos = marker.getLatLng();
    mapLat.value = pos.lat;
    mapLng.value = pos.lng;
    reverseGeocode(pos.lat, pos.lng);
  });

  mapInstance.on('click', (e) => {
    marker.setLatLng(e.latlng);
    mapLat.value = e.latlng.lat;
    mapLng.value = e.latlng.lng;
    reverseGeocode(e.latlng.lat, e.latlng.lng);
  });
};

const reverseGeocode = async (lat, lng) => {
  resolvingAddress.value = true;
  try {
    const res = await fetch(
      `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&addressdetails=1&accept-language=es`,
      { headers: { 'Accept-Language': 'es' } }
    );
    const data = await res.json();
    mapAddress.value = data.display_name || `${lat}, ${lng}`;
  } catch {
    mapAddress.value = `${lat}, ${lng}`;
  } finally {
    resolvingAddress.value = false;
  }
};

const saveLocation = () => {
  form.direccion_inspeccion = mapAddress.value;
  form.lat_inspeccion = mapLat.value;
  form.lng_inspeccion = mapLng.value;
  showMapModal.value = false;
  destroyMap();
};

const closeMapModal = () => {
  showMapModal.value = false;
  destroyMap();
};

const destroyMap = () => {
  if (mapInstance) {
    mapInstance.remove();
    mapInstance = null;
    marker = null;
  }
};

onBeforeUnmount(() => destroyMap());

const submitting = ref(false);

const submit = () => {
  submitting.value = true;
  form.post(route('coordinacion.asignar', props.caso.id), {
    onFinish: () => submitting.value = false
  });
};

// File helpers
const isPdf = (path) => typeof path === 'string' && path?.toLowerCase().endsWith('.pdf');
const isImage = (path) => typeof path === 'string' && /\.(jpg|jpeg|png|gif|webp)$/i.test(path);
const getFileName = (path) => typeof path === 'string' ? path?.split('/').pop() || 'Archivo' : 'Archivo';
const getFileType = (path) => {
  if (typeof path !== 'string') return 'Archivo';
  const ext = path?.split('.').pop()?.toUpperCase();
  return ext || 'Archivo';
};
const getFileIconClass = (path) => {
  if (typeof path !== 'string') return 'bg-slate-100 text-slate-600';
  if (isPdf(path)) return 'bg-red-100 text-red-600';
  if (isImage(path)) return 'bg-emerald-100 text-emerald-600';
  return 'bg-slate-100 text-slate-600';
};

// Preview modal
const showPreview = ref(false);
const previewFilePath = ref('');
const previewFileName = computed(() => typeof previewFilePath.value === 'string' ? previewFilePath.value?.split('/').pop() || '' : '');

const previewFile = (path) => {
  previewFilePath.value = path;
  showPreview.value = true;
};

// Normalize files array
const archivos = computed(() => {
  const paths = props.caso.aviso_siniestro_path;
  if (!paths) return [];
  if (Array.isArray(paths)) return paths.filter(p => typeof p === 'string');
  if (typeof paths === 'string') {
    try {
      const decoded = JSON.parse(paths);
      return (Array.isArray(decoded) ? decoded : [paths]).filter(p => typeof p === 'string');
    } catch {
      return [paths];
    }
  }
  return [];
});
</script>

<template>
  <Head :title="title" />

  <AppLayout :title="title">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Breadcrumbs / Navigation -->
      <div class="mb-6 flex justify-between items-center">
        <Link 
          :href="route('coordinacion')" 
          class="text-slate-500 hover:text-slate-900 flex items-center gap-2 font-bold text-xs uppercase tracking-widest transition-colors"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          Volver a Coordinación
        </Link>

        <div class="flex gap-2">
          <Link 
            :href="route('timeline')" 
            class="px-4 py-2 bg-white border border-slate-200 text-slate-700 rounded-none text-xs font-bold hover:bg-slate-50 hover:text-slate-900 transition-colors uppercase tracking-widest"
          >
            Línea de Tiempo
          </Link>
          <Link 
            :href="route('estados')" 
            class="px-4 py-2 bg-white border border-slate-200 text-slate-700 rounded-none text-xs font-bold hover:bg-slate-50 hover:text-slate-900 transition-colors uppercase tracking-widest"
          >
            Estados
          </Link>
        </div>
      </div>

      <div class="bg-white rounded-none shadow-sm border border-slate-200 overflow-hidden">
        <div class="bg-white px-4 sm:px-8 py-4 sm:py-6 border-b border-slate-200">
          <div class="flex flex-col sm:flex-row justify-between items-start gap-2">
            <div>
              <h1 class="text-lg sm:text-2xl font-bold text-slate-900 uppercase tracking-widest">Módulo 3 – Asignación de Ruta</h1>
              <p class="text-slate-500 text-xs sm:text-sm mt-1 uppercase">Caso: <span class="font-bold text-slate-900 border px-2 py-0.5 rounded-sm bg-slate-50 border-slate-200 ml-1">{{ caso.numero_reclamo }}</span><span class="ml-3">Placa:</span> <span class="font-bold text-slate-900 border px-2 py-0.5 rounded-sm bg-slate-50 border-slate-200 ml-1">{{ caso.vehiculo?.placa }}</span></p>
            </div>
            <div class="px-4 py-1.5 bg-slate-900 text-white rounded-none text-[10px] font-bold uppercase tracking-widest">
              Pendiente Coordinación
            </div>
          </div>
        </div>

        <form @submit.prevent="submit" class="p-4 sm:p-8 space-y-6 sm:space-y-10">
          <!-- Resumen del Caso -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6 bg-slate-50 p-4 sm:p-6 border border-slate-200">
            <div class="space-y-1">
              <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Aseguradora</label>
              <div class="text-sm font-bold text-slate-900">{{ caso.aseguradora?.nombre }}</div>
            </div>
            <div class="space-y-1">
              <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest block mb-1">Nombre: DP o RC</label>
              <div class="w-full bg-slate-50 border border-slate-300 rounded-none px-3 py-2 text-sm font-bold text-slate-900">
                {{ caso.cobertura === 'RC' ? (caso.afectado_nombre || 'Afectado (RC)') : (caso.cliente?.nombre || 'Asegurado (DP)') }}
              </div>
            </div>
            <div class="space-y-1">
              <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Taller Asignado</label>
              <div class="text-sm font-bold text-slate-900 border-b border-dashed border-slate-300 pb-1">{{ caso.taller?.razon_social || 'No asignado' }}</div>
              <div class="text-[10px] text-slate-400 font-bold uppercase">{{ caso.ciudad || 'Ciudad no definida' }}</div>
            </div>
          </div>

          <!-- Fecha de Inspección (CRÍTICO) -->
           <div class="bg-blue-50 p-4 sm:p-6 border border-blue-100 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
            <div class="flex items-center gap-4">
              <div class="w-12 h-12 rounded-2xl bg-blue-600 text-white flex items-center justify-center shadow-lg shadow-blue-600/20">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
              </div>
              <div class="flex flex-col">
                <span class="text-[10px] font-black text-blue-600 uppercase tracking-widest mb-1">Fecha de Inspección Programada</span>
                <div v-if="!showDatePicker && form.fecha_inspeccion" class="text-lg font-black text-blue-900 tracking-tight">
                  {{ form.fecha_inspeccion }}
                </div>
                <div v-else-if="!showDatePicker" class="text-sm font-bold text-blue-400 italic">
                  PENDIENTE DE DEFINIR
                </div>
                <input 
                  v-else 
                  v-model="form.fecha_inspeccion" 
                  type="date" 
                  class="bg-white border-2 border-blue-200 rounded-xl px-4 py-2 text-sm font-bold text-blue-900 focus:ring-4 focus:ring-blue-100 focus:border-blue-500 outline-none"
                  @blur="form.fecha_inspeccion ? showDatePicker = false : null"
                />
              </div>
            </div>
            <button 
              type="button" 
              @click="showDatePicker = !showDatePicker"
              class="px-4 py-2 bg-white border border-blue-100 text-blue-600 rounded-xl text-[10px] font-black uppercase tracking-widest hover:bg-blue-600 hover:text-white transition-all shadow-sm"
            >
              {{ showDatePicker ? 'Confirmar Fecha' : (form.fecha_inspeccion ? 'Cambiar Fecha' : 'Programar Ahora') }}
            </button>
          </div>

          <!-- Selección de Ajustador y Tarifas -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-8">
            <div class="space-y-4 sm:space-y-6 text-slate-800 border border-slate-200 p-4 sm:p-6">
              <h3 class="font-bold text-slate-900 uppercase tracking-widest border-b border-slate-200 pb-3 sm:pb-4 mb-4 sm:mb-6 text-sm flex items-center gap-3">
                <span class="w-6 h-6 bg-slate-900 text-white flex items-center justify-center text-xs">1</span>
                Información del Ajustador
              </h3>
              
              <div class="space-y-5">
                <div>
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Ajustador *</label>
                  <select v-model="form.ajustador_id" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" required>
                    <option value="">Seleccione ajustador...</option>
                    <option v-for="a in ajustadores" :key="a.id" :value="a.id">{{ a.nombre }}</option>
                  </select>
                </div>

                <div>
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Tarifa Ajustador (Abierta) *</label>
                  <div class="grid grid-cols-2 gap-3">
                    <select v-model="form.tarifa_ajustador_tipo" @change="updateTariff" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800">
                      <option value="liviano">Liviano</option>
                      <option value="pesado">Pesado</option>
                      <option value="express">Express</option>
                      <option value="virtual">Virtual</option>
                      <option value="particular">Particular</option>
                    </select>
                    <input v-model="form.tarifa_ajustador_valor" type="number" step="0.01" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 font-bold text-slate-900 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                  </div>
                </div>

                <div>
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Tipo de Ajuste</label>
                  <select v-model="form.tipo_ajuste" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800">
                    <option value="presencial">Presencial</option>
                    <option value="virtual">Virtual</option>
                    <option value="alcance">Alcance</option>
                    <option value="vh_reparado">VH Reparado</option>
                    <option value="inspeccion_cambio_taller">Inspección Cambio Taller</option>
                    <option value="re_inspeccion">Re Inspección</option>
                    <option value="repetir">Repetir / Mal realizado</option>
                  </select>
                </div>
              </div>
            </div>

            <div class="border border-slate-200 p-4 sm:p-6">
              <h3 class="font-bold text-slate-900 uppercase tracking-widest border-b border-slate-200 pb-3 sm:pb-4 mb-4 sm:mb-6 text-sm flex items-center gap-3">
                <span class="w-6 h-6 bg-slate-900 text-white flex items-center justify-center text-xs">2</span>
                Ruta y Ubicación
              </h3>

              <div class="space-y-5">
                <div class="grid grid-cols-2 gap-4">
                  <div>
                    <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Distancia Recorrida (KM)</label>
                    <input v-model="form.kilometros" type="number" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" placeholder="Ej: 150">
                  </div>
                  <div>
                    <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Tarifa KM</label>
                    <input v-model="form.tarifa_kilometro" type="number" step="0.01" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" placeholder="Ej: 0.50">
                  </div>
                </div>

                <div class="bg-slate-100 p-3 sm:p-4 rounded-none border border-slate-200">
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">Total a Pagar (Tarifa + KM)</label>
                  <div class="text-2xl font-black text-slate-900">$ {{ totalTarifa }}</div>
                </div>

                <div>
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Ubicación VH *</label>
                  <select v-model="form.ubicacion_vehiculo" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" required>
                    <option value="taller">Taller</option>
                    <option value="circulando">Circulando</option>
                    <option value="oficina">Oficina</option>
                    <option value="otro">Otro (Especificar)</option>
                  </select>
                </div>

                <div v-if="form.ubicacion_vehiculo === 'otro'">
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Cual ubicación?</label>
                  <input v-model="form.ubicacion_vehiculo_otro" type="text" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" placeholder="Especifique lugar...">
                </div>

                <!-- Ubicación de la Inspección con Mapa -->
                <div class="bg-slate-50 p-3 sm:p-4 border border-slate-200">
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2">Ubicación de la Inspección</label>
                  <div v-if="form.direccion_inspeccion" class="flex items-start gap-2 mb-3">
                    <svg class="w-5 h-5 mt-0.5 text-emerald-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                    <p class="text-sm text-slate-700 leading-tight">{{ form.direccion_inspeccion }}</p>
                  </div>
                  <div class="flex gap-2">
                    <button type="button" @click="openMapModal" class="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white text-[10px] font-black uppercase tracking-widest hover:bg-emerald-700 transition-colors">
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                      {{ form.direccion_inspeccion ? 'Cambiar Ubicación' : 'Seleccionar en Mapa' }}
                    </button>
                    <button v-if="form.direccion_inspeccion" type="button" @click="form.direccion_inspeccion = ''; form.lat_inspeccion = ''; form.lng_inspeccion = ''" class="px-3 py-2 bg-red-100 text-red-600 text-[10px] font-black uppercase tracking-widest hover:bg-red-200 transition-colors">
                      Limpiar
                    </button>
                  </div>
                </div>

                <div>
                  <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1.5">Estado de Asignación</label>
                  <select v-model="form.estado_actual" class="w-full bg-white border border-slate-300 rounded-none px-4 py-2.5 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800">
                    <option value="coordinado">Asignado</option>
                    <option value="no_asignado_ajustador_ocupado">No asignado - Ajustador ocupado</option>
                    <option value="no_asignado_falta_datos">No asignado - Faltan datos</option>
                    <option value="no_asignado_vehiculo_no_localizado">No asignado - VH no localizado</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          <!-- Archivos del Caso -->
          <div class="border border-slate-200 p-4 sm:p-6 bg-slate-50">
            <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-3">Archivos Cargados (Aviso de Siniestro)</label>
            
            <div v-if="archivos.length === 0" class="text-sm text-slate-400 italic flex items-center gap-2">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
              No hay archivos cargados para este caso.
            </div>

            <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div v-for="(path, index) in archivos" :key="index"
                   class="flex items-center gap-3 bg-white p-3 border border-slate-200 rounded-none hover:border-slate-300 transition-colors">
                
                <div :class="getFileIconClass(path)" class="w-10 h-10 rounded-none flex items-center justify-center flex-shrink-0">
                  <svg v-if="isPdf(path)" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                  <svg v-else-if="isImage(path)" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                  <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                </div>

                <div class="flex-1 min-w-0">
                  <p class="text-sm font-bold text-slate-800 truncate">{{ getFileName(path) }}</p>
                  <p class="text-[10px] text-slate-400 uppercase">{{ getFileType(path) }}</p>
                </div>

                <div class="flex gap-1">
                  <button type="button" @click="previewFile(path)" class="p-1.5 text-slate-400 hover:text-blue-600 transition-colors" title="Previsualizar">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                  </button>
                  <a :href="`/storage/${path}`" download class="p-1.5 text-slate-400 hover:text-emerald-600 transition-colors" title="Descargar">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                  </a>
                </div>
              </div>
            </div>
          </div>

          <!-- Observaciones -->
          <div class="border border-slate-200 p-4 sm:p-6 bg-slate-50">
            <label class="block text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2">Observaciones (Campo abierto 200 palabras)</label>
            <textarea 
              v-model="form.observaciones" 
              rows="4" 
              class="w-full bg-white border border-slate-300 rounded-none px-4 py-3 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-slate-800" 
              placeholder="Ingrese notas sobre la coordinación..."
            ></textarea>
          </div>

          <!-- Footer Actions -->
          <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 pt-6 border-t border-slate-200">
            <Link 
              :href="route('coordinacion')" 
              class="px-6 py-2.5 text-slate-500 font-bold hover:text-slate-900 transition-colors uppercase text-xs tracking-widest"
            >
              Cerrar
            </Link>
            
            <button 
              type="submit" 
              :disabled="submitting" 
              class="px-8 py-3 bg-slate-900 text-white rounded-none font-bold hover:bg-black transition-colors disabled:opacity-50 flex items-center gap-2 uppercase text-xs tracking-widest"
            >
              <svg v-if="!submitting" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
              </svg>
              {{ submitting ? 'Enviando...' : 'Grabar y Enviar Ruta' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Modal Previsualización -->
    <div v-if="showPreview" class="fixed inset-0 z-[100] overflow-y-auto">
      <div @click="showPreview = false" class="fixed inset-0 bg-slate-900/70 backdrop-blur-xl transition-opacity"></div>
      <div class="relative min-h-screen flex items-center justify-center p-4">
        <div class="relative bg-white rounded-none shadow-2xl max-w-5xl w-full max-h-[90vh] overflow-hidden border border-slate-200">
          <div class="flex items-center justify-between p-6 border-b border-slate-200">
            <h3 class="text-lg font-bold text-slate-900 uppercase tracking-widest truncate pr-4">{{ previewFileName }}</h3>
            <button @click="showPreview = false" class="w-10 h-10 rounded-none bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-900 transition-colors flex-shrink-0 border border-slate-200">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
          </div>
          <div class="p-6 overflow-auto max-h-[calc(90vh-80px)]">
            <img v-if="isImage(previewFilePath)" :src="`/storage/${previewFilePath}`" class="max-w-full h-auto mx-auto" />
            <iframe v-else-if="isPdf(previewFilePath)" :src="`/storage/${previewFilePath}`" class="w-full h-[70vh] border border-slate-200"></iframe>
            <div v-else class="text-center py-12">
              <svg class="w-16 h-16 mx-auto text-slate-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
              <p class="text-slate-400 mb-4 uppercase text-xs font-bold tracking-widest">Vista previa no disponible</p>
              <a :href="`/storage/${previewFilePath}`" download class="inline-flex items-center gap-2 px-6 py-3 bg-slate-900 text-white rounded-none font-bold hover:bg-black transition-colors uppercase text-xs tracking-widest">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                Descargar archivo
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal Mapa OSM -->
    <div v-if="showMapModal" class="fixed inset-0 z-[200] overflow-y-auto">
      <div @click="closeMapModal" class="fixed inset-0 bg-slate-900/70 backdrop-blur-xl transition-opacity"></div>
      <div class="relative min-h-screen flex items-center justify-center p-4">
        <div class="relative bg-white rounded-none shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden border border-slate-200">
          <div class="flex items-center justify-between p-6 border-b border-slate-200 bg-slate-900">
            <h3 class="text-lg font-bold text-white uppercase tracking-widest">Seleccionar Ubicación de Inspección</h3>
            <button @click="closeMapModal" class="w-10 h-10 rounded-none bg-slate-700 flex items-center justify-center text-white hover:bg-slate-600 transition-colors flex-shrink-0">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
          </div>
          <div class="p-6">
            <div class="mb-4">
              <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2">Arrastra el marcador o haz clic en el mapa para elegir la ubicación</p>
              <div id="map-picker" class="w-full h-[400px] border border-slate-200"></div>
            </div>
            <div class="flex items-center gap-4 bg-slate-50 p-4 border border-slate-200">
              <div class="flex-1">
                <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1 block">Dirección</label>
                <input v-model="mapAddress" type="text" class="w-full bg-white border border-slate-300 rounded-none px-3 py-2 text-sm text-slate-800" placeholder="Dirección de la inspección..." />
              </div>
              <div class="text-right text-[10px] text-slate-400 font-bold uppercase leading-tight">
                <div v-if="resolvingAddress" class="text-blue-600">Resolviendo dirección...</div>
                <div v-else>{{ mapLat.toFixed(6) }}, {{ mapLng.toFixed(6) }}</div>
              </div>
            </div>
          </div>
          <div class="flex items-center justify-between px-6 py-4 border-t border-slate-200 bg-slate-50">
            <button type="button" @click="closeMapModal" class="px-6 py-2.5 text-slate-500 font-bold hover:text-slate-900 transition-colors uppercase text-xs tracking-widest">
              Cancelar
            </button>
            <button type="button" @click="saveLocation" class="px-8 py-2.5 bg-emerald-600 text-white font-bold hover:bg-emerald-700 transition-colors uppercase text-xs tracking-widest flex items-center gap-2">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
              Confirmar Ubicación
            </button>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>
