<script setup>
import { ref, watch, computed } from 'vue';
import { Link, router } from '@inertiajs/vue3';
import AjustadorLayout from '@/Pages/Ajustador/AjustadorLayout.vue';
import 'leaflet/dist/leaflet.css';
import ChatWidget from '@/Components/ChatWidget.vue';

const props = defineProps({
  caso: Object,
  title: String,
  ajustador: Object,
});

const showToast = (msg, type = 'success') => {
  // Using global event (could also use a toast library)
  const evt = new CustomEvent('toast', { detail: { message: msg, type } });
  window.dispatchEvent(evt);
};

const estadosAjustador = [
  { value: 'caso_en_ruta', label: 'Caso en Ruta', icon: 'truck' },
  { value: 'inspeccion_realizada', label: 'Inspección Realizada', icon: 'clipboard-check' },
  { value: 'inspeccion_no_realizada', label: 'Inspección No Realizada', icon: 'clipboard-x' },
  { value: 'elaboracion_informe', label: 'Elaboración Informe', icon: 'file-text' },
  { value: 'envio_informe', label: 'Envío de Informe', icon: 'send' },
  { value: 'analisis', label: 'Análisis', icon: 'search' },
];

const estadoIcon = (name) => {
  const icons = {
    truck: 'M9 17a2 2 0 11-4 0 2 2 0 014 0zM19 17a2 2 0 11-4 0 2 2 0 014 0z',
    'clipboard-check': 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4',
    'clipboard-x': 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4',
    'file-text': 'M9 12h6m-6 4h6m2 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',
    send: 'M12 19l9 2-9-18-9 18 9-2zm0 0v-8',
    search: 'M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z',
  };
  return icons[name] || 'M9 12h6m-6 4h6m2 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';
};

const hasLocation = computed(() => props.caso?.lat_inspeccion && props.caso?.lng_inspeccion);

const statusForm = useForm({
  estado: '',
  nota: '',
});
import { useForm } from '@inertiajs/vue3';

const showStatusModal = ref(false);
const selectedEstado = ref('');
const uploading = ref(false);

const openStatusModal = (value) => {
  selectedEstado.value = value;
  statusForm.estado = value;
  statusForm.nota = '';
  showStatusModal.value = true;
};

const confirmStatus = () => {
  statusForm.post(route('ajustador.casos.estado', props.caso.id), {
    preserveScroll: true,
    onSuccess: () => {
      showStatusModal.value = false;
      statusForm.reset('nota', 'estado');
      showToast('Estado actualizado correctamente');
    },
    onError: () => {
      showToast('Error al actualizar el estado', 'error');
    },
  });
};

// Pending files awaiting upload
const pendingFiles = ref([]);
const fileInputRef = ref(null);

const addFiles = (e) => {
  const files = Array.from(e.target.files || []);
  if (files.length === 0) return;

  files.forEach((file) => {
    pendingFiles.value.push({
      file,
      descripcion: '',
      preview: URL.createObjectURL(file),
    });
  });

  e.target.value = '';
};

const removePendingFile = (index) => {
  URL.revokeObjectURL(pendingFiles.value[index].preview);
  pendingFiles.value.splice(index, 1);
};

const uploadPendingFiles = () => {
  if (pendingFiles.value.length === 0) return;

  uploading.value = true;
  const formData = new FormData();

  pendingFiles.value.forEach((item, i) => {
    formData.append('files[]', item.file);
    formData.append('descripciones[]', item.descripcion);
  });

  router.post(route('ajustador.casos.archivos', props.caso.id), formData, {
    preserveScroll: true,
    onSuccess: () => {
      showToast('Archivos subidos correctamente');
      pendingFiles.value.forEach((item) => URL.revokeObjectURL(item.preview));
      pendingFiles.value = [];
    },
    onError: () => {
      showToast('Error al subir archivos', 'error');
    },
    onFinish: () => {
      uploading.value = false;
    },
  });
};

// Delete
const showDeleteModal = ref(false);
const deleteIndex = ref(null);

const openDeleteModal = (index) => {
  deleteIndex.value = index;
  showDeleteModal.value = true;
};

const confirmDelete = () => {
  router.post(route('ajustador.casos.archivos.eliminar', [props.caso.id, deleteIndex.value]), {}, {
    preserveScroll: true,
    onSuccess: () => {
      showDeleteModal.value = false;
      deleteIndex.value = null;
      showToast('Archivo eliminado correctamente');
    },
    onError: () => {
      showToast('Error al eliminar archivo', 'error');
    },
  });
};

const isPdf = (path) => path?.toLowerCase().endsWith('.pdf');
const isImage = (path) => /\.(jpg|jpeg|png|gif|webp)$/i.test(path);
const getFileName = (path) => path?.split('/').pop() || 'Archivo';
const getFileType = (path) => {
  const ext = path?.split('.').pop()?.toUpperCase();
  return ext || 'Archivo';
};
const getFileIconClass = (path) => {
  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';
};

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

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

const placa = computed(() => props.caso?.vehiculo?.placa || '');

const adminDocs = computed(() => {
  const paths = props.caso.aviso_siniestro_path;
  if (!paths) return [];
  if (Array.isArray(paths)) return paths;
  return [];
});

const misArchivos = computed(() => {
  const a = props.caso.ajustador_archivos;
  if (!a) return [];
  if (Array.isArray(a)) return a;
  return [];
});

const getFilePath = (item) => typeof item === 'string' ? item : item?.path;

const getItemLabel = (item) => {
  const prefix = placa.value ? `${placa.value} - ` : '';
  if (typeof item === 'string') {
    return `${prefix}${item.split('/').pop()}`;
  }
  const desc = item?.descripcion || item?.nombre || item?.path?.split('/').pop() || 'Archivo';
  return `${prefix}${desc}`;
};

const getFileDate = (item) => typeof item === 'string' ? '' : item?.uploaded_at || '';

const confirmandoLlegada = ref(false);

const confirmarLlegada = () => {
  confirmandoLlegada.value = true;
  router.post(route('ajustador.casos.confirmar-llegada', props.caso.id), {}, {
    preserveScroll: true,
    onSuccess: () => {
      showToast('Llegada confirmada correctamente');
    },
    onError: () => {
      showToast('Error al confirmar llegada', 'error');
    },
    onFinish: () => {
      confirmandoLlegada.value = false;
    },
  });
};

// Mini map
let mapInstance = null;
const initMap = () => {
  if (!hasLocation.value) return;
  import('leaflet').then((L) => {
    if (mapInstance) {
      mapInstance.remove();
      mapInstance = null;
    }
    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 map = L.map('mini-map').setView([props.caso.lat_inspeccion, props.caso.lng_inspeccion], 15);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    }).addTo(map);
    L.marker([props.caso.lat_inspeccion, props.caso.lng_inspeccion]).addTo(map);
    mapInstance = map;
  });
};

watch(hasLocation, (val) => {
  if (val) setTimeout(initMap, 200);
}, { immediate: true });

const getFileName_ = (item) => {
  if (typeof item === 'string') return item.split('/').pop();
  return item?.nombre || item?.path?.split('/').pop() || 'Archivo';
};

// Informe de Análisis
const showInformeModal = ref(false);
const informeEnviado = computed(() => props.caso?.informe_enviado ?? false);
const informeData = computed(() => props.caso?.informe_data ?? null);

const informeForm = useForm({
  tipo_inspeccion: '',
  fecha_inspeccion: '',
  lugar_inspeccion: '',
  danos_externos: '',
  danos_internos: '',
  danos_mecanicos: '',
  danos_electricos: '',
  clasificacion_dano: '',
  costo_estimado_reparacion: '',
  tiempo_estimato_reparacion_dias: '',
  observaciones_tecnicas: '',
  conclusion_recomendacion: '',
  piezas_reemplazar: [],
});

const addPieza = () => {
  informeForm.piezas_reemplazar.push({ nombre: '', codigo: '', cantidad: 1, costo_unitario: '' });
};

const removePieza = (index) => {
  informeForm.piezas_reemplazar.splice(index, 1);
};

const openInformeModal = () => {
  if (informeEnviado.value && informeData.value) {
    const d = informeData.value;
    informeForm.tipo_inspeccion = d.tipo_inspeccion || '';
    informeForm.fecha_inspeccion = d.fecha_inspeccion || '';
    informeForm.lugar_inspeccion = d.lugar_inspeccion || '';
    informeForm.danos_externos = d.danos_externos || '';
    informeForm.danos_internos = d.danos_internos || '';
    informeForm.danos_mecanicos = d.danos_mecanicos || '';
    informeForm.danos_electricos = d.danos_electricos || '';
    informeForm.clasificacion_dano = d.clasificacion_dano || '';
    informeForm.costo_estimado_reparacion = d.costo_estimado_reparacion || '';
    informeForm.tiempo_estimato_reparacion_dias = d.tiempo_estimato_reparacion_dias || '';
    informeForm.observaciones_tecnicas = d.observaciones_tecnicas || '';
    informeForm.conclusion_recomendacion = d.conclusion_recomendacion || '';
    informeForm.piezas_reemplazar = d.piezas_reemplazar ? [...d.piezas_reemplazar] : [];
  } else {
    informeForm.reset();
  }
  showInformeModal.value = true;
};

const enviarInforme = () => {
  informeForm.post(route('ajustador.casos.informe', props.caso.id), {
    preserveScroll: true,
    onSuccess: () => {
      showInformeModal.value = false;
      showToast('Informe enviado correctamente');
    },
    onError: () => {
      showToast('Error al enviar el informe', 'error');
    },
  });
};
</script>

<template>
  <AjustadorLayout :title="title" :ajustador="ajustador">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 py-8">

      <!-- Back navigation -->
      <Link :href="route('ajustador.dashboard')" class="inline-flex items-center gap-2 text-sm font-semibold text-slate-500 hover:text-blue-600 transition-colors mb-4 group">
        <svg class="w-4 h-4 group-hover:-translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
        Volver a Mis Casos
      </Link>

      <!-- Toast Notifications -->
      <div id="toast-container" class="fixed bottom-6 right-6 z-[200] space-y-2"></div>

      <!-- Status Actions Grid -->
      <div class="grid grid-cols-3 sm:grid-cols-6 gap-2 mb-6">
        <button
          v-for="est in estadosAjustador"
          :key="est.value"
          @click="openStatusModal(est.value)"
          class="flex flex-col items-center gap-2 p-4 bg-white rounded-xl border border-slate-200 hover:border-blue-300 hover:shadow-md transition-all hover:-translate-y-0.5"
          :class="{ 'ring-2 ring-blue-500 border-blue-500': caso.estado_actual === est.value }"
        >
          <div class="w-10 h-10 rounded-lg flex items-center justify-center" :class="caso.estado_actual === est.value ? 'bg-blue-600 text-white' : 'bg-blue-50 text-blue-600'">
            <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="estadoIcon(est.icon)"></path></svg>
          </div>
          <span class="text-[10px] font-bold text-slate-600 text-center leading-tight">{{ est.label }}</span>
        </button>
      </div>

      <!-- Informe de Análisis -->
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest">Informe de Análisis</h3>
            <p class="text-sm text-slate-500 mt-1">Informe detallado de la inspección del siniestro vehicular</p>
          </div>
          <button v-if="!informeEnviado" @click="openInformeModal"
                  class="px-8 py-3 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-600/20 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 12h6m-6 4h6m2 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>
            Enviar Informe
          </button>
          <div v-else class="flex items-center gap-3">
            <div class="flex items-center gap-2 px-4 py-2 bg-emerald-100 text-emerald-700 font-bold rounded-xl">
              <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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
              Informe Enviado
            </div>
            <button @click="openInformeModal"
                    class="px-6 py-3 bg-slate-100 text-slate-600 font-bold rounded-xl hover:bg-slate-200 transition-colors 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="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>
              Ver Informe
            </button>
          </div>
        </div>
      </div>

      <!-- File Upload Zone -->
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
        <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Subir Fotos / Documentos</h3>

        <div class="border-2 border-dashed border-slate-300 rounded-xl p-6 text-center hover:border-blue-400 transition-colors cursor-pointer"
             @click="fileInputRef?.click()">
          <svg class="w-10 h-10 mx-auto text-slate-400 mb-2" 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>
          <p class="text-sm font-semibold text-slate-600">Seleccionar archivos</p>
          <p class="text-xs text-slate-400 mt-1">JPG, PNG, PDF hasta 20MB</p>
          <input ref="fileInputRef" type="file" multiple accept=".jpg,.jpeg,.png,.pdf,.gif,.webp" @change="addFiles" class="hidden" />
        </div>

        <!-- Pending files with descriptions -->
        <div v-if="pendingFiles.length > 0" class="mt-4 space-y-3">
          <p class="text-xs font-bold text-slate-400 uppercase tracking-widest">Archivos por subir ({{ pendingFiles.length }})</p>
          <div v-for="(item, index) in pendingFiles" :key="index"
               class="flex items-start gap-4 bg-blue-50 p-4 rounded-xl border border-blue-200">
            <div class="w-14 h-14 rounded-lg bg-white flex items-center justify-center flex-shrink-0 border border-blue-100 overflow-hidden">
              <img v-if="item.file.type.startsWith('image/')" :src="item.preview" class="w-full h-full object-cover" />
              <svg v-else class="w-6 h-6 text-blue-500" 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-medium text-slate-700 truncate">{{ item.file.name }}</p>
              <input v-model="item.descripcion" type="text"
                     class="mt-2 w-full px-3 py-2 bg-white border border-blue-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                     :placeholder="`Ej: Frente, Lateral, Daño ${placa ? '- ' + placa : ''}`" />
            </div>
            <button type="button" @click="removePendingFile(index)" class="p-1.5 text-slate-400 hover:text-red-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>
          <button @click="uploadPendingFiles" :disabled="uploading"
                  class="w-full py-3 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2">
            <svg v-if="uploading" class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
            {{ uploading ? 'Subiendo...' : `Subir ${pendingFiles.length} archivo(s)` }}
          </button>
        </div>
      </div>

      <!-- Ubicación de la Inspección -->
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
          <div class="flex-1">
            <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
              <svg class="w-5 h-5 text-emerald-500" 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>
              Ubicación de la Inspección
            </h3>
            <p v-if="caso.direccion_inspeccion" class="text-sm text-slate-700 mb-3 leading-relaxed">{{ caso.direccion_inspeccion }}</p>
            <p v-else class="text-sm text-slate-400 mb-3 italic">No se ha definido una ubicación de inspección para este caso.</p>
            <div v-if="hasLocation" id="mini-map" class="w-full h-[200px] rounded-xl border border-slate-200 overflow-hidden"></div>
          </div>
          <div v-if="hasLocation && !caso.confirmo_llegada" class="flex-shrink-0 sm:mt-0 mt-4">
            <button
              @click="confirmarLlegada"
              :disabled="confirmandoLlegada"
              class="inline-flex items-center gap-2 px-6 py-3 bg-emerald-600 text-white font-bold rounded-xl hover:bg-emerald-700 transition-colors disabled:opacity-50 shadow-lg shadow-emerald-600/20"
            >
              <svg v-if="!confirmandoLlegada" 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="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>
              <svg v-else class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
              {{ confirmandoLlegada ? 'Confirmando...' : 'Llegué al Lugar' }}
            </button>
          </div>
          <div v-if="hasLocation && caso.confirmo_llegada" class="flex-shrink-0 sm:mt-0 mt-4">
            <div class="flex items-center gap-2 px-6 py-3 bg-emerald-100 text-emerald-700 font-bold rounded-xl">
              <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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
              Llegada Confirmada
            </div>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
          <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Cliente / Asegurado</h3>
          <dl class="space-y-3">
            <div><dt class="text-xs text-slate-500">Nombre</dt><dd class="font-semibold text-slate-700">{{ caso.cliente?.nombre || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Teléfono</dt><dd class="font-semibold text-slate-700">{{ caso.cliente?.telefono || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Email</dt><dd class="font-semibold text-slate-700">{{ caso.cliente?.email || 'N/A' }}</dd></div>
          </dl>
        </div>

        <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
          <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Vehículo</h3>
          <dl class="space-y-3">
            <div><dt class="text-xs text-slate-500">Placa</dt><dd class="font-bold text-slate-800 text-lg">{{ caso.vehiculo?.placa || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Marca / Modelo</dt><dd class="font-semibold text-slate-700">{{ caso.vehiculo?.marca }} {{ caso.vehiculo?.modelo }}</dd></div>
            <div><dt class="text-xs text-slate-500">Año</dt><dd class="font-semibold text-slate-700">{{ caso.vehiculo?.anio || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Color</dt><dd class="font-semibold text-slate-700">{{ caso.vehiculo?.color || 'N/A' }}</dd></div>
          </dl>
        </div>

        <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
          <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Aseguradora</h3>
          <dl class="space-y-3">
            <div><dt class="text-xs text-slate-500">Nombre</dt><dd class="font-semibold text-slate-700">{{ caso.aseguradora?.nombre || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Cobertura</dt><dd class="font-semibold text-slate-700">{{ caso.cobertura || 'N/A' }}</dd></div>
          </dl>
        </div>

        <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
          <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Taller</h3>
          <dl class="space-y-3">
            <div><dt class="text-xs text-slate-500">Nombre</dt><dd class="font-semibold text-slate-700">{{ caso.taller?.razon_social || 'N/A' }}</dd></div>
            <div><dt class="text-xs text-slate-500">Teléfono</dt><dd class="font-semibold text-slate-700">{{ caso.taller?.telefono || 'N/A' }}</dd></div>
          </dl>
        </div>
      </div>

      <!-- Admin Documents (read-only) -->
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
        <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Documentos</h3>
        <div v-if="adminDocs.length === 0" class="text-center py-8">
          <svg class="w-12 h-12 mx-auto text-slate-300 mb-3" 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">No hay documentos</p>
        </div>
            <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div v-for="(item, index) in adminDocs" :key="index"
               class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
            <div :class="getFileIconClass(getFilePath(item))" class="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0">
              <svg v-if="isPdf(getFilePath(item))" 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="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(getFilePath(item))" 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="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-6 h-6" 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-semibold text-slate-800 truncate">{{ getItemLabel(item) }}</p>
              <p class="text-xs text-slate-400">{{ getFileType(getFilePath(item)) }} <span v-if="getFileDate(item)" class="ml-2">• {{ getFileDate(item) }}</span></p>
            </div>
            <div class="flex gap-2">
              <button @click="previewFile(getFilePath(item))" class="p-2 text-slate-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-blue-50" title="Previsualizar">
                <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="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/${getFilePath(item)}`" download class="p-2 text-slate-400 hover:text-emerald-600 transition-colors rounded-lg hover:bg-emerald-50" title="Descargar">
                <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="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>

      <!-- Mis Fotos (adjuster's files) -->
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
        <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Mis Fotos / Archivos</h3>
        <div v-if="misArchivos.length === 0" class="text-center py-8">
          <svg class="w-12 h-12 mx-auto text-slate-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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>
          <p class="text-slate-400">Aún no has subido archivos</p>
        </div>
        <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div v-for="(item, index) in misArchivos" :key="index"
               class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100 hover:border-slate-200 transition-colors">
            <div :class="getFileIconClass(getFilePath(item))" class="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0">
              <svg v-if="isPdf(getFilePath(item))" 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="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(getFilePath(item))" 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="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-6 h-6" 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-semibold text-slate-800 truncate">{{ getItemLabel(item) }}</p>
              <p class="text-xs text-slate-400">{{ getFileType(getFilePath(item)) }} <span v-if="getFileDate(item)" class="ml-2">• {{ getFileDate(item) }}</span></p>
            </div>
            <div class="flex gap-2">
              <button @click="previewFile(getFilePath(item))" class="p-2 text-slate-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-blue-50" title="Previsualizar">
                <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="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/${getFilePath(item)}`" download class="p-2 text-slate-400 hover:text-emerald-600 transition-colors rounded-lg hover:bg-emerald-50" title="Descargar">
                <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
              </a>
              <button @click="openDeleteModal(index)" class="p-2 text-slate-400 hover:text-red-600 transition-colors rounded-lg hover:bg-red-50" title="Eliminar">
                <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
        <h3 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Observaciones</h3>
        <p class="text-slate-600">{{ caso.observaciones || 'Sin observaciones' }}</p>
      </div>

      <!-- Status Confirmation Modal -->
      <div v-if="showStatusModal" class="fixed inset-0 z-[100] overflow-y-auto">
        <div @click="showStatusModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"></div>
        <div class="relative min-h-screen flex items-center justify-center p-4">
          <div class="relative bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200">
            <div class="p-6">
              <div class="text-center mb-6">
                <div class="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center mx-auto mb-4">
                  <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                </div>
                <h3 class="text-lg font-bold text-slate-800">Actualizar Estado</h3>
                <p class="text-sm text-slate-500 mt-1">¿Estás seguro de cambiar el estado del caso?</p>
                <p class="text-sm font-bold text-blue-600 mt-2">{{ estadosAjustador.find(e => e.value === selectedEstado)?.label }}</p>
              </div>
              <div class="space-y-4">
                <div>
                  <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Nota (opcional)</label>
                  <input v-model="statusForm.nota" type="text" class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-blue-500 outline-none transition-shadow" placeholder="Comentario..." />
                </div>
                <div class="flex gap-3 pt-2">
                  <button @click="showStatusModal = false" class="flex-1 py-3 font-bold text-slate-500 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors">Cancelar</button>
                  <button @click="confirmStatus" :disabled="statusForm.processing" class="flex-1 py-3 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-700 transition-colors disabled:opacity-50">
                    {{ statusForm.processing ? 'Actualizando...' : 'Confirmar' }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Delete Confirmation Modal -->
      <div v-if="showDeleteModal" class="fixed inset-0 z-[100] overflow-y-auto">
        <div @click="showDeleteModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"></div>
        <div class="relative min-h-screen flex items-center justify-center p-4">
          <div class="relative bg-white rounded-2xl shadow-2xl max-w-sm w-full overflow-hidden border border-slate-200">
            <div class="p-6 text-center">
              <div class="w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"></path></svg>
              </div>
              <h3 class="text-lg font-bold text-slate-800 mb-2">Eliminar Archivo</h3>
              <p class="text-sm text-slate-500 mb-6">¿Estás seguro de eliminar este archivo?</p>
              <div class="flex gap-3">
                <button @click="showDeleteModal = false" class="flex-1 px-4 py-3 text-sm font-bold text-slate-400 bg-slate-50 rounded-xl hover:bg-slate-100 transition-colors">Cancelar</button>
                <button @click="confirmDelete" class="flex-1 px-4 py-3 bg-red-600 text-white font-bold rounded-xl hover:bg-red-700 transition-colors">Eliminar</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Preview Modal -->
      <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-3xl shadow-2xl max-w-5xl w-full max-h-[90vh] overflow-hidden">
            <div class="flex items-center justify-between p-6 border-b border-slate-100">
              <h3 class="text-lg font-bold text-slate-800 truncate pr-4">{{ previewFileName }}</h3>
              <button @click="showPreview = false" class="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-900 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 overflow-auto max-h-[calc(90vh-80px)]">
              <img v-if="isImage(previewFilePath)" :src="`/storage/${previewFilePath}`" class="max-w-full h-auto rounded-xl mx-auto" />
              <iframe v-else-if="isPdf(previewFilePath)" :src="`/storage/${previewFilePath}`" class="w-full h-[70vh] rounded-xl border border-slate-200"></iframe>
              <div v-else class="text-center py-12">
                <p class="text-slate-400 mb-4">Vista previa no disponible</p>
                <a :href="`/storage/${previewFilePath}`" download class="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition-colors">Descargar</a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Informe Modal -->
      <div v-if="showInformeModal" class="fixed inset-0 z-[100] overflow-y-auto">
        <div @click="showInformeModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"></div>
        <div class="relative min-h-screen flex items-start justify-center p-4 pt-12">
          <div class="relative bg-white rounded-2xl shadow-2xl max-w-4xl w-full overflow-hidden border border-slate-200 my-8">
            <div class="flex items-center justify-between p-6 border-b border-slate-100 bg-gradient-to-r from-indigo-600 to-purple-600">
              <div>
                <h3 class="text-lg font-bold text-white">Informe de Análisis de Siniestro Vehicular</h3>
                <p class="text-sm text-indigo-200 mt-0.5">Completa todos los campos del informe técnico</p>
              </div>
              <button @click="showInformeModal = false" class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center text-white hover:bg-white/30 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 overflow-y-auto max-h-[calc(100vh-220px)]">
              <form @submit.prevent="enviarInforme">
                <!-- Datos Generales -->
                <div class="mb-8">
                  <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    Datos Generales
                  </h4>
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Tipo de Inspección</label>
                      <select v-model="informeForm.tipo_inspeccion" :disabled="informeEnviado"
                              class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow">
                        <option value="">Seleccionar...</option>
                        <option value="presencial">Presencial</option>
                        <option value="virtual">Virtual</option>
                        <option value="mixta">Mixta</option>
                      </select>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Fecha de Inspección</label>
                      <input v-model="informeForm.fecha_inspeccion" type="date" :disabled="informeEnviado"
                             class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow" />
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Lugar de Inspección</label>
                      <input v-model="informeForm.lugar_inspeccion" type="text" :disabled="informeEnviado"
                             class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow"
                             placeholder="Dirección o referencia" />
                    </div>
                  </div>
                </div>

                <!-- Daños del Vehículo -->
                <div class="mb-8">
                  <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"></path></svg>
                    Daños del Vehículo
                  </h4>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Daños Externos</label>
                      <textarea v-model="informeForm.danos_externos" :disabled="informeEnviado" rows="4"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Describe los daños externos..."></textarea>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Daños Internos</label>
                      <textarea v-model="informeForm.danos_internos" :disabled="informeEnviado" rows="4"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Describe los daños internos..."></textarea>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Daños Mecánicos</label>
                      <textarea v-model="informeForm.danos_mecanicos" :disabled="informeEnviado" rows="4"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Describe los daños mecánicos..."></textarea>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Daños Eléctricos</label>
                      <textarea v-model="informeForm.danos_electricos" :disabled="informeEnviado" rows="4"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Describe los daños eléctricos..."></textarea>
                    </div>
                  </div>
                </div>

                <!-- Clasificación y Costos -->
                <div class="mb-8">
                  <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    Clasificación y Costos
                  </h4>
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Clasificación del Daño</label>
                      <select v-model="informeForm.clasificacion_dano" :disabled="informeEnviado"
                              class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow">
                        <option value="">Seleccionar...</option>
                        <option value="leve">Leve</option>
                        <option value="moderado">Moderado</option>
                        <option value="severo">Severo</option>
                        <option value="perdida_total">Pérdida Total</option>
                      </select>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Costo Est. Reparación ($)</label>
                      <input v-model="informeForm.costo_estimado_reparacion" type="number" min="0" step="0.01" :disabled="informeEnviado"
                             class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow"
                             placeholder="0.00" />
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Tiempo Est. Reparación (días)</label>
                      <input v-model="informeForm.tiempo_estimato_reparacion_dias" type="number" min="0" step="1" :disabled="informeEnviado"
                             class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow"
                             placeholder="0" />
                    </div>
                  </div>
                </div>

                <!-- Piezas a Reemplazar -->
                <div class="mb-8">
                  <div class="flex items-center justify-between mb-4">
                    <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
                      <svg class="w-4 h-4 text-sky-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                      Piezas a Reemplazar
                    </h4>
                    <button v-if="!informeEnviado" type="button" @click="addPieza"
                            class="flex items-center gap-2 px-4 py-2 bg-sky-100 text-sky-700 font-bold rounded-xl hover:bg-sky-200 transition-colors text-sm">
                      <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="M12 4v16m8-8H4"></path></svg>
                      Agregar Pieza
                    </button>
                  </div>
                  <div v-if="informeForm.piezas_reemplazar.length === 0" class="text-center py-8 bg-slate-50 rounded-xl border border-dashed border-slate-300">
                    <svg class="w-10 h-10 mx-auto text-slate-300 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path></svg>
                    <p class="text-sm text-slate-400">No hay piezas registradas</p>
                  </div>
                  <div v-else class="overflow-x-auto">
                    <table class="w-full text-sm">
                      <thead>
                        <tr class="border-b border-slate-200">
                          <th class="text-left text-xs font-bold text-slate-400 uppercase tracking-widest pb-2 pr-2">Nombre</th>
                          <th class="text-left text-xs font-bold text-slate-400 uppercase tracking-widest pb-2 pr-2">Código</th>
                          <th class="text-center text-xs font-bold text-slate-400 uppercase tracking-widest pb-2 pr-2 w-20">Cant.</th>
                          <th class="text-right text-xs font-bold text-slate-400 uppercase tracking-widest pb-2 pr-2 w-32">Costo Unit.</th>
                          <th class="text-right text-xs font-bold text-slate-400 uppercase tracking-widest pb-2 w-24">Subtotal</th>
                          <th v-if="!informeEnviado" class="w-10 pb-2"></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(pieza, index) in informeForm.piezas_reemplazar" :key="index" class="border-b border-slate-100">
                          <td class="py-2 pr-2">
                            <input v-model="pieza.nombre" type="text" :disabled="informeEnviado"
                                   class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none"
                                   placeholder="Parachoques, faro..." />
                          </td>
                          <td class="py-2 pr-2">
                            <input v-model="pieza.codigo" type="text" :disabled="informeEnviado"
                                   class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none"
                                   placeholder="Código" />
                          </td>
                          <td class="py-2 pr-2">
                            <input v-model.number="pieza.cantidad" type="number" min="1" step="1" :disabled="informeEnviado"
                                   class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none text-center" />
                          </td>
                          <td class="py-2 pr-2">
                            <input v-model.number="pieza.costo_unitario" type="number" min="0" step="0.01" :disabled="informeEnviado"
                                   class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none text-right"
                                   placeholder="0.00" />
                          </td>
                          <td class="py-2 text-right font-semibold text-slate-700">
                            ${{ ((pieza.cantidad || 0) * (pieza.costo_unitario || 0)).toFixed(2) }}
                          </td>
                          <td v-if="!informeEnviado" class="py-2 text-center">
                            <button type="button" @click="removePieza(index)" class="p-1.5 text-slate-400 hover:text-red-600 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="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                          </td>
                        </tr>
                      </tbody>
                      <tfoot>
                        <tr>
                          <td colspan="3" class="pt-3 text-right font-bold text-slate-500 uppercase tracking-widest text-xs">Total Estimado:</td>
                          <td class="pt-3 text-right font-bold text-indigo-600 text-lg">
                            ${{ informeForm.piezas_reemplazar.reduce((sum, p) => sum + ((p.cantidad || 0) * (p.costo_unitario || 0)), 0).toFixed(2) }}
                          </td>
                          <td></td>
                        </tr>
                      </tfoot>
                    </table>
                  </div>
                </div>

                <!-- Observaciones y Conclusión -->
                <div class="mb-6">
                  <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    Observaciones y Conclusión
                  </h4>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Observaciones Técnicas</label>
                      <textarea v-model="informeForm.observaciones_tecnicas" :disabled="informeEnviado" rows="5"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Observaciones técnicas adicionales..."></textarea>
                    </div>
                    <div>
                      <label class="text-xs font-bold text-slate-400 uppercase tracking-widest">Conclusión / Recomendación</label>
                      <textarea v-model="informeForm.conclusion_recomendacion" :disabled="informeEnviado" rows="5"
                                class="w-full mt-1.5 px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow resize-none"
                                placeholder="Conclusión y recomendación del ajustador..."></textarea>
                    </div>
                  </div>
                </div>

                <!-- Actions -->
                <div v-if="!informeEnviado" class="flex gap-3 pt-4 border-t border-slate-100">
                  <button type="button" @click="showInformeModal = false"
                          class="flex-1 py-3 font-bold text-slate-500 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors">
                    Cancelar
                  </button>
                  <button type="submit" :disabled="informeForm.processing"
                          class="flex-1 py-3 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2">
                    <svg v-if="informeForm.processing" class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    {{ informeForm.processing ? 'Enviando...' : 'Enviar Informe' }}
                  </button>
                </div>
                <div v-else class="pt-4 border-t border-slate-100 text-center">
                  <p class="text-sm text-slate-400">Este informe ya fue enviado</p>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>

    </div>
    <ChatWidget
      :caso-id="caso.id"
      :fetch-url="`/ajustador/casos/${caso.id}/chat`"
      :store-url="`/ajustador/casos/${caso.id}/chat`"
      current-user-type="ajustador"
      :current-user-name="ajustador?.nombre || 'Ajustador'"
      other-party-name="Administrador"
    />
  </AjustadorLayout>
</template>
