{% extends 'app_base.html.twig' %}

{% block title %}{{ session.label }} — Scan Inventaire{% endblock %}

{% set statusColors = {
    'en_cours':  {bg: 'bg-blue-50',  text: 'text-blue-700',  border: 'border-blue-200'},
    'a_valider': {bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200'},
    'valide':    {bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200'},
    'annule':    {bg: 'bg-gray-100', text: 'text-gray-600',  border: 'border-gray-200'},
} %}
{% set c = statusColors[session.status] %}
{# Édition possible (photos, documents, véhicules) uniquement tant que le statut est « En cours ». #}
{% set canEditDocs = is_granted('SCAN_EDIT_DOCUMENTS', session) %}
{# Lieu modifiable tant que l'inventaire n'est pas validé (même portée que les concessions). #}
{% set canEditLocation = is_granted('SCAN_EDIT_CONCESSIONS', session) %}
{# Renommage : éditeur (En cours) OU valideur (statut quelconque). #}
{% set canRename = canEditDocs or is_granted('SCAN_CHANGE_STATUS', session) %}

{% block content %}
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-6" data-controller="inventaires" data-inventaires-s3-value="{{ session.isOnS3 ? '1' : '0' }}">
    <div>
        <a href="{{ path('app_inventaires') }}" class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-900 mb-3">
            <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>
            Retour à la liste
        </a>
        <div class="flex flex-wrap items-center justify-between gap-3">
            <div>
                <div class="flex items-center gap-2 flex-wrap mb-1">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-medium border {{ c.bg }} {{ c.text }} {{ c.border }}">{{ statusLabels[session.status] }}</span>
                    {% if canEditLocation %}
                        {# Type d'inventaire (VN/VO/VN & VO) modifiable tant que non validé (petit crayon). #}
                        <details class="relative">
                            <summary class="list-none cursor-pointer select-none inline-flex items-center gap-1 px-2.5 py-0.5 rounded-md text-xs font-semibold border bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100" title="Modifier le type">
                                {{ session.scanType|scan_type_label ?: 'Type ?' }}
                                <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
                            </summary>
                            <div class="absolute left-0 top-full z-30 mt-2 w-56 bg-white border border-gray-200 rounded-xl shadow-xl p-3 text-left space-y-1.5">
                                <p class="text-xs font-semibold text-gray-800 mb-1">Type d'inventaire</p>
                                <button type="button" data-action="inventaires#saveScanType" data-inventaires-id-param="{{ session.id }}" data-inventaires-type-param="VN"
                                        class="w-full text-left px-3 py-2 text-sm rounded-lg hover:bg-gray-100 {{ session.scanType == 'VN' ? 'bg-indigo-50 text-indigo-700 font-medium' }}">VN <span class="text-gray-500">(Véhicules neufs)</span></button>
                                <button type="button" data-action="inventaires#saveScanType" data-inventaires-id-param="{{ session.id }}" data-inventaires-type-param="VO"
                                        class="w-full text-left px-3 py-2 text-sm rounded-lg hover:bg-gray-100 {{ session.scanType == 'VO' ? 'bg-indigo-50 text-indigo-700 font-medium' }}">VO <span class="text-gray-500">(Véhicules d'occasion)</span></button>
                                <button type="button" data-action="inventaires#saveScanType" data-inventaires-id-param="{{ session.id }}" data-inventaires-type-param="VNVO"
                                        class="w-full text-left px-3 py-2 text-sm rounded-lg hover:bg-gray-100 {{ session.scanType == 'VNVO' ? 'bg-indigo-50 text-indigo-700 font-medium' }}">VN &amp; VO <span class="text-gray-500">(Véhicules neufs et d'occasions)</span></button>
                            </div>
                        </details>
                    {% elseif session.scanType %}
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-semibold border bg-indigo-50 text-indigo-700 border-indigo-200">{{ session.scanType|scan_type_label }}</span>
                    {% endif %}
                    <h1 class="font-display font-bold text-2xl text-gray-900">{{ session.label }}</h1>
                    {% if canRename %}
                        <details class="relative">
                            <summary class="list-none cursor-pointer select-none inline-flex items-center gap-1 text-xs text-gray-400 hover:text-gray-700" title="Renommer l'inventaire">
                                <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
                                Renommer
                            </summary>
                            <div class="absolute left-0 top-full z-30 mt-2 w-80 max-w-[85vw] bg-white border border-gray-200 rounded-xl shadow-xl p-4 text-left space-y-3">
                                <p class="text-sm font-semibold text-gray-800">Renommer l'inventaire</p>
                                <input type="text" value="{{ session.label }}" maxlength="255" placeholder="Nom de l'inventaire"
                                       class="block w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-brand">
                                <button type="button" data-action="inventaires#renameInventory" data-inventaires-id-param="{{ session.id }}"
                                        class="w-full px-3 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Enregistrer</button>
                            </div>
                        </details>
                    {% endif %}
                </div>
                <p class="text-sm text-gray-500">
                    {{ session.count }} véhicule{{ session.count > 1 ? 's' }} · {{ session.totalFiles }} fichier{{ session.totalFiles > 1 ? 's' }} ·
                    {{ session.createdAt|date('d/m/Y à H:i') }}
                    · par <span class="text-gray-700">{{ session.userEmail }}</span>
                    {% if session.locationNote %} · 📍 {{ session.locationNote }}{% endif %}
                    {% if session.concessions|length > 0 %} · {{ session.concessions|concession_names|join(' / ') }}{% endif %}
                </p>
            </div>
            {# Boutons groupés par fonction : Consultation · Statut · Gestion #}
            <div class="flex flex-wrap items-center gap-x-3 gap-y-2">
                {# ── Consultation / export ── #}
                <div class="flex items-center gap-1.5">
                    <button data-action="inventaires#export" data-inventaires-id-param="{{ session.id }}"
                            class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Export Excel</button>
                    {# « PDF + photos » réservé aux inventaires validés ; embarque les images côté serveur : impossible si elles sont sur S3. #}
                    {% if session.status == 'valide' and not session.isOnS3 %}
                        <button data-action="inventaires#exportPdfPhotos" data-inventaires-id-param="{{ session.id }}"
                                class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">PDF + photos</button>
                    {% endif %}
                    {# Inventaires sur S3 : « PDF + photos » via page imprimable navigateur (le serveur ne peut pas lire les octets S3). Réservé aux inventaires validés. #}
                    {% if session.isOnS3 %}
                        {% if session.status == 'valide' %}
                            <a href="{{ path('app_report_photos_web', {id: session.id}) }}" target="_blank" rel="noopener"
                               class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">PDF + photos</a>
                        {% else %}
                            <button type="button" data-action="inventaires#reportPhotosBlocked"
                                    class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">PDF + photos</button>
                        {% endif %}
                    {% endif %}
                </div>

                {# ── Statut (workflow) — SUBMIT ouvre « À valider » à l'opérateur sur un scan en cours ── #}
                {% set canChangeStatus = is_granted('SCAN_CHANGE_STATUS', session) %}
                {% set canSubmit = is_granted('SCAN_SUBMIT', session) %}
                {% if canChangeStatus or canSubmit %}
                    <div class="flex items-center gap-1.5 sm:border-l sm:border-gray-200 sm:pl-3">
                        {# Réouverture : un inventaire « À valider » peut être renvoyé en correction par
                           le SUPERVISEUR / AUDIT / ADMIN (porteurs de SCAN_CHANGE_STATUS). La réouverture
                           d'un inventaire « Validé » ou « Annulé » reste réservée à l'ADMIN. #}
                        {% if (session.status == 'a_valider' and canChangeStatus) or (is_granted('ROLE_ADMIN') and session.status != 'en_cours') %}
                            <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ session.id }}" data-inventaires-status-param="en_cours"
                                    class="px-3 py-1.5 text-xs font-medium text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors">Rouvrir</button>
                        {% endif %}
                        {% if session.status == 'en_cours' %}
                            {# En cours → passe à la relecture (« À valider »), pas directement validé. #}
                            {% if canSubmit %}
                                <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ session.id }}" data-inventaires-status-param="a_valider"
                                        class="px-3 py-1.5 text-xs font-medium bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors">À valider</button>
                            {% endif %}
                        {% elseif canChangeStatus and session.status != 'valide' %}
                            <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ session.id }}" data-inventaires-status-param="valide"
                                    class="px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">Valider</button>
                        {% endif %}
                        {% if canChangeStatus and session.status != 'annule' %}
                            <button data-action="inventaires#setStatus" data-inventaires-id-param="{{ session.id }}" data-inventaires-status-param="annule"
                                    class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Annuler</button>
                        {% endif %}
                    </div>
                {% endif %}

                {# ── Gestion (cycle de vie) ── #}
                {% if is_granted('SCAN_ARCHIVE', session) or is_granted('SCAN_DELETE', session) %}
                    <div class="flex items-center gap-1.5 sm:border-l sm:border-gray-200 sm:pl-3">
                        {% if is_granted('SCAN_ARCHIVE', session) %}
                            <button data-action="inventaires#archive" data-inventaires-id-param="{{ session.id }}"
                                    class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">{{ session.archived ? 'Désarchiver' : 'Archiver' }}</button>
                        {% endif %}
                        {% if is_granted('SCAN_DELETE', session) %}
                            <button data-action="inventaires#remove" data-inventaires-id-param="{{ session.id }}"
                                    class="px-3 py-1.5 text-xs font-medium text-red-700 border border-red-200 rounded-lg hover:bg-red-50 transition-colors">Supprimer</button>
                        {% endif %}
                    </div>
                {% endif %}
            </div>
        </div>
    </div>

    {# ─── Lieu de l'inventaire (modifiable tant que non validé ; toujours requis) ─── #}
    <div class="bg-amber-50 border border-amber-200 rounded-2xl p-4 flex items-start gap-2.5">
        <svg class="w-5 h-5 text-amber-500 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M17.657 16.657L13.414 20.9a2 2 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
        <div class="min-w-0 flex-1">
            <p class="text-xs font-medium text-amber-800 uppercase tracking-wide mb-0.5">Lieu</p>
            <div class="flex items-start gap-2">
                <p class="text-sm text-amber-900 break-words min-w-0 flex-1">{{ session.locationNote ?: '—' }}</p>
                {% if canEditLocation %}
                    <details class="relative shrink-0" data-location-edit>
                        <summary class="list-none cursor-pointer select-none inline-flex items-center gap-1 text-xs text-amber-700 hover:text-amber-900" title="Modifier le lieu">
                            <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
                            Modifier
                        </summary>
                        <div class="absolute right-0 top-full z-30 mt-2 w-80 max-w-[85vw] bg-white border border-gray-200 rounded-xl shadow-xl p-4 text-left space-y-2">
                            <p class="text-sm font-semibold text-gray-800">Modifier le lieu</p>
                            <input type="text" maxlength="255" value="{{ session.locationNote }}" placeholder="Ex : Parking nord, Atelier 2…"
                                   class="block w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-brand">
                            <p class="text-[11px] text-gray-400">Le lieu est obligatoire.</p>
                            <button type="button" data-action="inventaires#saveLocation" data-inventaires-id-param="{{ session.id }}"
                                    class="w-full px-3 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Enregistrer</button>
                        </div>
                    </details>
                {% endif %}
            </div>
        </div>
    </div>

    {# ─── Concessions associées (modifiables tant que l'inventaire n'est pas validé).
          Réutilise le picker avec recherche de la page Scan, replié par défaut. ─── #}
    {% if concessionChoices is not empty %}
        <div class="space-y-2" data-inventaires-target="concessionPicker">
            {% include 'partials/_concession_picker_inline.html.twig' with {
                concessions: concessionChoices,
                selectedConcessions: session.concessions,
                pickerTitle: 'Concessions :',
                pickerSummary: session.concessions|concession_names|join(' / ')|default('aucune'),
                pickerActionLabel: 'Modifier',
                pickerOpen: false,
            } only %}
            <div class="flex flex-wrap items-center justify-between gap-3 px-1">
                <p class="text-xs text-gray-500">Modifiables tant que l'inventaire n'est pas validé — chaque changement est tracé dans le journal.</p>
                <button type="button" data-action="inventaires#saveConcessions" data-inventaires-id-param="{{ session.id }}"
                        class="px-4 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors shrink-0">Enregistrer les concessions</button>
            </div>
        </div>
    {% endif %}

    {# ─── Doublons détectés (même plaque ou même VIN qu'un autre véhicule du scan) ─── #}
    {% if duplicateIndexes is not empty %}
        <div class="bg-orange-50 border border-orange-200 rounded-2xl p-4 flex items-start gap-2.5">
            <svg class="w-5 h-5 text-orange-500 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01M5.07 19h13.86c1.54 0 2.5-1.67 1.73-3L13.73 4a2 2 0 00-3.46 0L3.34 16c-.77 1.33.19 3 1.73 3z" /></svg>
            <div class="min-w-0 flex-1">
                <p class="text-xs font-medium text-orange-800 uppercase tracking-wide mb-0.5">Doublons détectés</p>
                <p class="text-sm text-orange-900 break-words">{{ duplicateIndexes|length }} véhicule{{ duplicateIndexes|length > 1 ? 's' }} en double (même plaque ou même VIN). Les véhicules concernés sont signalés ci-dessous (liseré orange).</p>
                {% if canEditDocs %}
                    <button type="button" data-action="inventaires#removeDuplicates" data-inventaires-id-param="{{ session.id }}"
                            class="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors">
                        <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" 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" /></svg>
                        Supprimer les doublons
                    </button>
                    <p class="text-[11px] text-orange-700 mt-1">La première occurrence de chaque véhicule est conservée ; les suivantes (et leurs photos) sont supprimées.</p>
                {% elseif is_granted('SCAN_CHANGE_STATUS', session) %}
                    <p class="text-[11px] text-orange-700 mt-1">Rouvrez l'inventaire (« En cours ») pour pouvoir supprimer les doublons.</p>
                {% endif %}
            </div>
        </div>
    {% endif %}

    {# ─── Paires ─── #}
    {% if session.results|length == 0 %}
        <div class="text-center py-16 bg-gray-50 border border-gray-200 rounded-2xl">
            <p class="text-gray-500 text-sm">Aucun résultat dans cette session.</p>
            {% if canEditDocs %}
                <button type="button" data-action="inventaires#addPair" data-inventaires-id-param="{{ session.id }}"
                        class="mt-4 inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">+ Ajouter un véhicule</button>
            {% endif %}
        </div>
    {% else %}
        {# Recherche + filtre erreurs sur les véhicules de cet inventaire (filtre instantané, client). #}
        <div class="flex flex-wrap items-center gap-3">
            <div class="relative flex-1 min-w-[240px]">
                <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-4.35-4.35M17 11A6 6 0 105 11a6 6 0 0012 0z" /></svg>
                <input type="search" data-action="input->inventaires#filterVehicles" placeholder="Rechercher une immatriculation ou un VIN…"
                       class="w-full pl-9 pr-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-brand text-sm">
            </div>
            <select data-action="change->inventaires#filterErrors" aria-label="Filtrer par erreur"
                    class="px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand text-sm shrink-0">
                <option value="">Tous</option>
                <option value="with">Erreurs</option>
                <option value="without">Aucune erreur</option>
            </select>
            <select data-action="change->inventaires#filterModel" aria-label="Filtrer par fiabilité du modèle"
                    class="px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-red-brand text-sm shrink-0">
                <option value="">Modèle : tous</option>
                <option value="exact">Modèle : exact</option>
                <option value="doute">Modèle : doute</option>
            </select>
            <span data-inventaires-target="searchCount" class="text-xs text-gray-500 shrink-0"></span>
        </div>
        <div data-inventaires-target="searchEmpty" class="hidden text-center py-10 bg-gray-50 border border-gray-200 rounded-2xl text-sm text-gray-500">Aucun véhicule ne correspond à votre recherche.</div>
        <ul class="space-y-3">
            {% for r in session.results %}
                {% set pairPos = loop.index0 %}
                {% set plateError = plate_in_error(r) %}
                {% set vinError = vin_in_error(r) %}
                {% set isDuplicate = pairPos in duplicateIndexes %}
                {# Catégorie de fiabilité du modèle : 'exact' = confiance ≥ 70 % OU valeur corrigée à la main
                   (confiance effacée mais marque/modèle renseignés) ; sinon 'doute' (confiance faible ou modèle non identifié). #}
                {% set hasModelValue = (r.make is defined and r.make) or (r.model is defined and r.model) %}
                {% set modelConf = r.modelConfidence is defined ? r.modelConfidence : null %}
                {% set modelCat = ((modelConf is not null and modelConf >= 70) or (modelConf is null and hasModelValue)) ? 'exact' : 'doute' %}
                <li class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm {{ isDuplicate ? 'border-l-4 border-l-orange-400' : ((plateError or vinError) ? 'border-l-4 border-l-yellow-400') }}"
                    data-inventaires-target="vehicle"
                    data-search="{{ (r.plate ?? '') ~ ' ' ~ (r.vin ?? '') ~ ' ' ~ (r.rawPlate ?? '') ~ ' ' ~ (r.rawVin ?? '') }}"
                    data-error="{{ (plateError or vinError) ? '1' : '0' }}"
                    data-model="{{ modelCat }}"
                    {% if canEditDocs %}
                        {# Zone de dépôt : on peut glisser ici la photo d'un autre véhicule pour la déplacer. #}
                        data-action="dragover->inventaires#dragOver dragleave->inventaires#dragLeave drop->inventaires#drop"
                        data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}"
                    {% endif %}>
                    <div class="flex flex-col md:flex-row gap-5">
                        {# Vignettes Plaque + VIN côte à côte #}
                        <div class="flex gap-3 shrink-0">
                            {% for kind in ['vin', 'plaque'] %}
                                {% set imageId = kind == 'plaque' ? r.plateImageId : r.vinImageId %}
                                {% set imgS3Key = kind == 'plaque' ? r.plateS3Key|default(null) : r.vinS3Key|default(null) %}
                                {% set imgSrc = imageId ? image_url(session, imageId, imgS3Key) : '' %}
                                {% set value = kind == 'plaque' ? r.plate : r.vin %}
                                {% set raw = kind == 'plaque' ? r.rawPlate|default('') : r.rawVin|default('') %}
                                {% set cellError = kind == 'plaque' ? plateError : vinError %}
                                {% set hl = cellError ? 'bg-yellow-200 px-1 rounded' %}
                                <figure class="w-36"
                                        {% if canEditDocs and imageId %}
                                            draggable="true" data-action="dragstart->inventaires#dragStart"
                                            data-inventaires-index-param="{{ pairPos }}" data-inventaires-slot-param="{{ kind }}"
                                            title="Glisser cette photo sur un autre véhicule pour la déplacer"
                                        {% endif %}>
                                    {% if imageId %}
                                        <a href="{{ imgSrc }}" target="_blank" rel="noopener" class="block">
                                            <img src="{{ imgSrc }}"
                                                 data-controller="image-fallback" data-action="error->image-fallback#fallback"
                                                 alt="{{ kind }} {{ value ?? '' }}" loading="lazy"
                                                 class="w-36 h-24 object-cover rounded-lg border border-gray-200 hover:border-red-brand transition-colors {{ canEditDocs ? 'cursor-grab' }}">
                                        </a>
                                    {% else %}
                                        <div class="w-36 h-24 rounded-lg border border-dashed border-gray-200 bg-gray-50 flex items-center justify-center">
                                            <span class="text-xs text-gray-400">Pas d'image</span>
                                        </div>
                                    {% endif %}
                                    <figcaption class="mt-1.5">
                                        <span class="block text-[11px] text-gray-400 uppercase tracking-wide">{{ kind == 'plaque' ? 'Plaque' : 'VIN' }}</span>
                                        {% if value %}
                                            <span class="inline-block font-mono {{ kind == 'plaque' ? 'text-sm font-semibold text-gray-900' : 'text-xs text-gray-700' }} break-all {{ hl }}">{{ value }}</span>
                                        {% elseif raw|trim %}
                                            {# Lecture OCR brute non validée (c'est elle qui sert de repli dans la comparaison) #}
                                            <span class="inline-block font-mono {{ kind == 'plaque' ? 'text-sm font-semibold' : 'text-xs' }} text-amber-700 break-all {{ hl }}">{{ raw }}</span>
                                            <span class="inline-flex items-center px-1.5 py-0.5 mt-0.5 rounded text-[10px] font-medium bg-amber-50 text-amber-700 border border-amber-200 normal-case">lecture incertaine</span>
                                        {% else %}
                                            <span class="inline-block font-mono {{ kind == 'plaque' ? 'text-sm font-semibold text-gray-900' : 'text-xs text-gray-700' }} {{ hl }}">{{ kind == 'vin' ? 'VIN manquant' : '-' }}</span>
                                        {% endif %}
                                    </figcaption>
                                    {% if canEditDocs %}
                                        {# flex-wrap : 3 actions (Remplacer/Déplacer…/Supprimer) ne tiennent pas sur les 144px de la vignette #}
                                        <div class="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px]">
                                            <details class="relative">
                                                <summary class="list-none cursor-pointer select-none text-blue-600 hover:text-blue-800">{{ imageId ? 'Remplacer' : 'Ajouter' }}</summary>
                                                <div class="absolute left-0 top-full z-30 mt-2 w-80 max-w-[85vw] bg-white border border-gray-200 rounded-xl shadow-xl p-4 text-left space-y-3">
                                                    <p class="text-sm font-semibold text-gray-800">{{ imageId ? 'Remplacer' : 'Ajouter' }} la photo {{ kind == 'plaque' ? 'plaque' : 'VIN' }}</p>
                                                    <input type="file" accept=".jpg,.jpeg,.png,.webp" class="block w-full text-sm text-gray-600 cursor-pointer file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-gray-100 file:text-gray-700 hover:file:bg-gray-200">
                                                    <p class="text-xs text-gray-400 leading-snug">JPEG, PNG ou WebP · 20 Mo max · l'OCR sera relancé automatiquement.</p>
                                                    <button type="button" data-action="inventaires#uploadPhoto"
                                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}" data-inventaires-slot-param="{{ kind }}"
                                                            class="w-full px-3 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Envoyer</button>
                                                </div>
                                            </details>
                                            <details class="relative">
                                                <summary class="list-none cursor-pointer select-none text-blue-600 hover:text-blue-800">Corriger</summary>
                                                <div class="absolute left-0 top-full z-30 mt-2 w-80 max-w-[85vw] bg-white border border-gray-200 rounded-xl shadow-xl p-4 text-left space-y-3">
                                                    <p class="text-sm font-semibold text-gray-800">Corriger {{ kind == 'plaque' ? 'la plaque' : 'le VIN' }}</p>
                                                    <input type="text" value="{{ value ?: raw }}" placeholder="{{ kind == 'plaque' ? 'AA-123-AA' : '17 caractères' }}"
                                                           class="block w-full px-3 py-2 text-sm font-mono uppercase border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-brand">
                                                    <p class="text-xs text-gray-400 leading-snug">Saisie manuelle (la photo n'est pas modifiée). Laisser vide pour effacer la valeur.</p>
                                                    <button type="button" data-action="inventaires#editValue"
                                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}" data-inventaires-slot-param="{{ kind }}"
                                                            class="w-full px-3 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Enregistrer</button>
                                                </div>
                                            </details>
                                            {% if imageId %}
                                                {% if session.results|length > 1 %}
                                                    <button type="button" data-action="inventaires#movePrompt"
                                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}" data-inventaires-slot-param="{{ kind }}"
                                                            data-inventaires-count-param="{{ session.results|length }}"
                                                            class="text-blue-600 hover:text-blue-800">Déplacer…</button>
                                                {% endif %}
                                                <button type="button" data-action="inventaires#deletePhoto"
                                                        data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}" data-inventaires-slot-param="{{ kind }}"
                                                        class="text-red-600 hover:text-red-800">Supprimer</button>
                                            {% endif %}
                                        </div>
                                    {% endif %}
                                </figure>
                            {% endfor %}

                            {# 3e photo (vue du véhicule), si fournie — lecture seule pour l'instant #}
                            {% if r.photoImageId %}
                                {% set photoSrc = image_url(session, r.photoImageId, r.photoS3Key|default(null)) %}
                                <figure class="w-36">
                                    <a href="{{ photoSrc }}" target="_blank" rel="noopener" class="block">
                                        <img src="{{ photoSrc }}" alt="Photo véhicule" loading="lazy"
                                             data-controller="image-fallback" data-action="error->image-fallback#fallback"
                                             class="w-36 h-24 object-cover rounded-lg border border-gray-200 hover:border-red-brand transition-colors">
                                    </a>
                                    <figcaption class="mt-1.5">
                                        <span class="block text-[11px] text-gray-400 uppercase tracking-wide">Véhicule</span>
                                    </figcaption>
                                </figure>
                            {% endif %}
                        </div>

                        {# Métadonnées en grille 2 colonnes #}
                        <div class="flex-1 min-w-0 md:border-l md:border-gray-100 md:pl-5">
                            <div class="flex items-center justify-between gap-2 mb-2">
                                <span class="inline-flex items-center gap-2 text-[11px] font-semibold text-gray-400 uppercase tracking-wide">
                                    Véhicule #{{ r.pairIndex + 1 }}
                                    {% if not r.vinImageId %}<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-50 text-red-700 border border-red-200 normal-case">VIN manquant</span>{% endif %}
                                    {% if (plateError or vinError) and r.vinImageId %}<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-yellow-100 text-yellow-800 border border-yellow-300 normal-case">à corriger</span>{% endif %}
                                    {% if isDuplicate %}<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-orange-100 text-orange-800 border border-orange-300 normal-case">doublon</span>{% endif %}
                                </span>
                                {# Suppression réservée aux véhicules ajoutés manuellement (les véhicules scannés ne sont pas supprimables individuellement). #}
                                {% if canEditDocs and r.manual %}
                                    <button type="button" data-action="inventaires#deletePair"
                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}"
                                            class="text-[11px] text-red-600 hover:text-red-800">Supprimer le véhicule</button>
                                {% endif %}
                            </div>
                            {# Marque / modèle déduits du VIN + des photos non-VIN, corrigeables (en cours) #}
                            {% if r.make or r.model or canEditDocs %}
                                <div class="mb-3">
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Marque / Modèle</dt>
                                    <dd class="text-sm text-gray-900 font-medium flex items-center gap-2 flex-wrap">
                                        {% if r.make or r.model %}
                                            <span>{{ ([r.make, r.model]|filter(v => v))|join(' ') }}</span>
                                            {% if r.modelConfidence is not null %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium normal-case border {{ r.modelConfidence >= 70 ? 'bg-green-50 text-green-700 border-green-200' : 'bg-yellow-100 text-yellow-800 border-yellow-300' }}">modèle {{ r.modelConfidence }}%</span>
                                            {% endif %}
                                        {% else %}
                                            <span class="text-gray-400 font-normal">—</span>
                                        {% endif %}
                                        {% if canEditDocs %}
                                            <details class="relative">
                                                <summary class="list-none cursor-pointer select-none text-blue-600 hover:text-blue-800 text-[11px] font-normal">Corriger</summary>
                                                <div class="absolute left-0 top-full z-30 mt-2 w-80 max-w-[85vw] bg-white border border-gray-200 rounded-xl shadow-xl p-4 text-left space-y-3">
                                                    <p class="text-sm font-semibold text-gray-800">Corriger la marque / le modèle</p>
                                                    <label class="block text-xs text-gray-500">Marque
                                                        <input type="text" data-model-make value="{{ r.make }}" placeholder="ex. Volkswagen"
                                                               class="mt-1 block w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-brand">
                                                    </label>
                                                    <label class="block text-xs text-gray-500">Modèle
                                                        <input type="text" data-model-model value="{{ r.model }}" placeholder="ex. Tiguan"
                                                               class="mt-1 block w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-brand">
                                                    </label>
                                                    <p class="text-xs text-gray-400 leading-snug">Laisser vide pour effacer. La correction manuelle retire le % de confiance.</p>
                                                    <button type="button" data-action="inventaires#saveModel"
                                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}"
                                                            class="w-full px-3 py-2 text-sm font-medium bg-red-brand text-white rounded-lg hover:bg-red-brand-dark transition-colors">Enregistrer</button>
                                                </div>
                                            </details>
                                        {% endif %}
                                    </dd>
                                </div>
                            {% endif %}
                            <dl class="grid grid-cols-2 gap-x-6 gap-y-2.5">
                                <div>
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Date VIN</dt>
                                    <dd class="text-xs text-gray-700 font-mono">{{ r.vinDate ?: '-' }}</dd>
                                </div>
                                <div>
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Date plaque</dt>
                                    <dd class="text-xs text-gray-700 font-mono">{{ r.plateDate ?: '-' }}</dd>
                                </div>
                                <div>
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Position VIN</dt>
                                    <dd class="text-xs">
                                        {% if r.vinLatitude and r.vinLongitude %}
                                            <a href="https://www.google.com/maps?q={{ r.vinLatitude }},{{ r.vinLongitude }}" target="_blank" rel="noopener" class="text-blue-600 hover:underline">Voir sur Maps</a>
                                        {% else %}<span class="text-gray-400 font-mono">-</span>{% endif %}
                                    </dd>
                                </div>
                                <div>
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Position plaque</dt>
                                    <dd class="text-xs">
                                        {% if r.plateLatitude and r.plateLongitude %}
                                            <a href="https://www.google.com/maps?q={{ r.plateLatitude }},{{ r.plateLongitude }}" target="_blank" rel="noopener" class="text-blue-600 hover:underline">Voir sur Maps</a>
                                        {% else %}<span class="text-gray-400 font-mono">-</span>{% endif %}
                                    </dd>
                                </div>
                                <div class="min-w-0">
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Fichier VIN</dt>
                                    <dd class="text-xs text-gray-500 font-mono truncate" title="{{ r.vinFilename }}">{{ r.vinFilename ?: '-' }}</dd>
                                </div>
                                <div class="min-w-0">
                                    <dt class="text-[11px] text-gray-400 uppercase tracking-wide">Fichier plaque</dt>
                                    <dd class="text-xs text-gray-500 font-mono truncate" title="{{ r.plateFilename }}">{{ r.plateFilename ?: '-' }}</dd>
                                </div>
                            </dl>

                            {# ─── Commentaire du véhicule ─── #}
                            <div class="mt-3 pt-3 border-t border-gray-100">
                                <dt class="text-[11px] text-gray-400 uppercase tracking-wide mb-1">Commentaire</dt>
                                {% if canEditDocs %}
                                    <div data-veh-comment>
                                        <textarea rows="3" placeholder="Commentaire pour ce véhicule…"
                                                  class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-brand text-xs font-mono whitespace-pre-wrap">{{ r.comment ?? '' }}</textarea>
                                        <div class="flex justify-end mt-1.5">
                                            <button type="button" data-action="inventaires#saveVehicleComment"
                                                    data-inventaires-id-param="{{ session.id }}" data-inventaires-index-param="{{ pairPos }}"
                                                    class="px-3 py-1.5 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">Enregistrer le commentaire</button>
                                        </div>
                                    </div>
                                {% elseif r.comment %}
                                    <p class="text-xs text-gray-700 whitespace-pre-wrap break-words">{{ r.comment }}</p>
                                {% else %}
                                    <p class="text-xs text-gray-400">—</p>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </li>
            {% endfor %}
        </ul>
        {% if canEditDocs %}
            <button type="button" data-action="inventaires#addPair" data-inventaires-id-param="{{ session.id }}"
                    class="mt-3 inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">+ Ajouter un véhicule</button>
        {% endif %}
    {% endif %}

    {# ─── Autres documents ─── #}
    <div class="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
        <div class="flex items-center gap-2 mb-1">
            <svg class="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" /></svg>
            <h2 class="font-display font-bold text-lg text-gray-900">Autres documents</h2>
        </div>
        <p class="text-sm text-gray-500 mb-4">Pièces jointes libres (PDF, images, Office…) et commentaire associés à cet inventaire.</p>

        {# canEditDocs est défini en tête de page (édition possible si statut « En cours »). #}
        {% if not canEditDocs %}
            <div class="bg-gray-50 border border-gray-200 rounded-xl p-3 mb-4 flex items-start gap-2.5">
                <svg class="w-4 h-4 text-gray-400 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                <p class="text-xs text-gray-600">Documents verrouillés : l'inventaire n'est plus « En cours ». {% if is_granted('SCAN_CHANGE_STATUS', session) %}Cliquez sur <span class="font-medium">Rouvrir</span> pour ajouter ou supprimer des fichiers.{% else %}Seuls les fichiers déjà joints restent consultables.{% endif %}</p>
            </div>
        {% endif %}

        {% if session.attachments|length > 0 %}
            <ul class="divide-y divide-gray-100 border border-gray-200 rounded-xl mb-4">
                {% for att in session.attachments %}
                    <li class="px-4 py-3">
                        <div class="flex items-center justify-between gap-3">
                            <a href="{{ path('app_attachment_download', {id: session.id, attId: att.id}) }}"
                               class="flex items-center gap-2 min-w-0 text-sm text-gray-700 hover:text-red-brand">
                                <svg class="w-4 h-4 shrink-0 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" 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" /></svg>
                                <span class="truncate">{{ att.originalName }}</span>
                                <span class="text-xs text-gray-400 shrink-0">({{ (att.size / 1024)|round }} Ko)</span>
                            </a>
                            <div class="flex items-center gap-3 shrink-0">
                                <span class="text-xs text-gray-400 hidden sm:inline">{{ att.uploadedAt|date('d/m/Y H:i') }}</span>
                                {% if canEditDocs %}
                                    <button type="button" data-action="inventaires#deleteDocument"
                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-att-param="{{ att.id }}"
                                            class="text-xs text-red-600 hover:text-red-800">Supprimer</button>
                                {% endif %}
                            </div>
                        </div>

                        {# Commentaire associé à ce document : modifiable en ligne si « En cours », sinon affiché en lecture seule. #}
                        {% if canEditDocs %}
                            <details class="mt-1.5">
                                <summary class="list-none cursor-pointer text-xs select-none">
                                    {% if att.comment %}
                                        <span class="inline-flex items-start gap-1.5 text-gray-600">
                                            <svg class="w-3.5 h-3.5 text-gray-400 shrink-0 mt-px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 4v-4z" /></svg>
                                            <span class="break-words">{{ att.comment }}</span>
                                        </span>
                                        <span class="text-gray-300 ml-1">· modifier</span>
                                    {% else %}
                                        <span class="text-gray-400 hover:text-gray-600">+ Ajouter un commentaire</span>
                                    {% endif %}
                                </summary>
                                <div class="mt-2 flex items-start gap-2">
                                    <textarea rows="2" placeholder="Commentaire pour ce document…"
                                              class="flex-1 px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-brand text-sm">{{ att.comment }}</textarea>
                                    <button type="button" data-action="inventaires#editComment"
                                            data-inventaires-id-param="{{ session.id }}" data-inventaires-att-param="{{ att.id }}"
                                            class="px-3 py-2 text-xs font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors shrink-0">Enregistrer</button>
                                </div>
                            </details>
                        {% elseif att.comment %}
                            <p class="mt-1.5 inline-flex items-start gap-1.5 text-xs text-gray-600">
                                <svg class="w-3.5 h-3.5 text-gray-400 shrink-0 mt-px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 4v-4z" /></svg>
                                <span class="break-words">{{ att.comment }}</span>
                            </p>
                        {% endif %}
                    </li>
                {% endfor %}
            </ul>
        {% else %}
            <p class="text-sm text-gray-400 mb-4">Aucun document joint pour le moment.</p>
        {% endif %}

        {% if canEditDocs %}
            <div data-doc-upload class="space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">Ajouter des fichiers</label>
                    <input type="file" multiple
                           accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx,.csv,.txt"
                           class="block w-full text-sm text-gray-600 file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-gray-100 file:text-gray-700 hover:file:bg-gray-200">
                    <p class="text-xs text-gray-400 mt-1">20 Mo max par fichier.</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">Commentaire <span class="text-gray-400 font-normal">(associé au(x) fichier(s) ajouté(s))</span></label>
                    <textarea rows="2" placeholder="Commentaire pour le(s) fichier(s) ci-dessus…"
                              class="w-full px-3 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-brand text-sm"></textarea>
                </div>
                <div class="flex justify-end">
                    <button type="button" data-action="inventaires#uploadDocuments" data-inventaires-id-param="{{ session.id }}"
                            class="px-4 py-2 bg-red-brand text-white text-sm font-medium rounded-lg hover:bg-red-brand-dark transition-colors">Enregistrer</button>
                </div>
            </div>
        {% endif %}
    </div>

    {# ─── Historique (journal d'audit du scan, visible des valideurs) ─── #}
    {% if history is not empty %}
        <div class="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm">
            <h2 class="text-sm font-display font-semibold text-gray-900 mb-3">Historique de l'inventaire</h2>
            <ul class="space-y-1.5">
                {% for l in history %}
                    <li class="text-xs text-gray-500 flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
                        <span class="text-gray-400 font-mono shrink-0">{{ l.createdAt|date('d/m/Y H:i') }}</span>
                        <span class="text-gray-700 font-medium">{{ l.actionLabel }}</span>
                        {% if l.action == 'scan.status' %}
                            <span>{{ statusLabels[l.details.from] ?? l.details.from }} → {{ statusLabels[l.details.to] ?? l.details.to }}</span>
                        {% elseif l.action == 'scan.rename' %}
                            <span>« {{ l.details.from }} » → « {{ l.details.to }} »</span>
                        {% elseif l.action == 'scan.concessions' %}
                            <span>{{ (l.details.from ?? [])|concession_names|join(' / ')|default('—') }} → {{ (l.details.to ?? [])|concession_names|join(' / ')|default('—') }}</span>
                        {% endif %}
                        <span class="text-gray-400">par {{ l.userEmail }}</span>
                    </li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}
</div>
{% endblock %}
