<div>
    {{-- Styles --}}
    <style>
        /* ========================================
           MODAL OVERLAY - HIGHEST Z-INDEX
           ======================================== */
        
        /* Backdrop - covers everything */
        .panel-backdrop {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            width: 100vw !important;
            height: 100vh !important;
            background: rgba(0,0,0,0.6) !important;
            z-index: 99999 !important;
            animation: fadeIn 0.2s ease;
        }
        
        /* Modal Panel - above backdrop */
        .dossier-results-panel {
            position: fixed !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            z-index: 100000 !important;
            background: white !important;
            border-radius: 12px;
            box-shadow: 0 25px 80px rgba(0,0,0,0.4) !important;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            animation: slideUp 0.3s ease;
        }
        
        .dossier-results-panel .panel-header {
            padding: 16px 20px;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }
        
        .dossier-results-panel .panel-body {
            overflow-y: auto;
            flex: 1;
            padding: 0;
            background: white;
        }
        
        .dossier-results-panel .close-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s ease;
        }
        
        .dossier-results-panel .close-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideUp {
            from { 
                opacity: 0;
                transform: translate(-50%, -45%);
            }
            to { 
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }
        
        /* Result items inside modal */
        .dossier-results-panel .result-item {
            padding: 14px 20px;
            border-bottom: 1px solid #f1f5f9;
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
            background: white;
        }
        
        .dossier-results-panel .result-item:hover {
            background: linear-gradient(135deg, rgba(16,185,129,0.08) 0%, rgba(5,150,105,0.08) 100%);
            padding-left: 24px;
        }
        
        .dossier-results-panel .result-item:last-child {
            border-bottom: none;
        }
        
        .dossier-results-panel .result-header {
            font-weight: 600;
            color: #1e293b;
            font-size: 14px;
        }
        
        .dossier-results-panel .result-meta {
            font-size: 12px;
            color: #64748b;
            margin-top: 2px;
        }
        
        .dossier-results-panel .result-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 500;
            background: #e0f2fe;
            color: #0369a1;
        }
        
        /* Import hint on hover */
        .dossier-results-panel .result-item::after {
            content: 'Cliquez pour importer';
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 11px;
            color: #10b981;
            opacity: 0;
            transition: opacity 0.2s ease;
            pointer-events: none;
        }
        
        .dossier-results-panel .result-item:hover::after {
            opacity: 1;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .dossier-results-panel {
                width: 95% !important;
                max-height: 85vh !important;
            }
            
            .dossier-results-panel .panel-header {
                padding: 12px 16px;
            }
            
            .dossier-results-panel .result-item {
                padding: 10px 12px;
            }
            
            .dossier-results-panel .result-item::after {
                display: none;
            }
        }
        
        @media (max-width: 576px) {
            .dossier-results-panel {
                width: 100% !important;
                max-width: 100% !important;
                border-radius: 16px 16px 0 0 !important;
                top: auto !important;
                bottom: 0 !important;
                left: 0 !important;
                right: 0 !important;
                transform: none !important;
                max-height: 75vh !important;
                animation: slideUpMobile 0.3s ease !important;
            }
            
            .dossier-results-panel .result-item .d-flex {
                flex-direction: column;
            }
            
            .dossier-results-panel .result-item .text-end {
                text-align: left !important;
                margin-top: 8px;
            }
        }
        
        @keyframes slideUpMobile {
            from { 
                opacity: 0;
                transform: translateY(100%);
            }
            to { 
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* ========================================
           FORM ELEMENTS - LOWER Z-INDEX
           ======================================== */
        
        /* Ensure form elements stay below modal */
        .card,
        .card-body,
        .form-control,
        .form-select,
        .selectpicker,
        .bootstrap-select,
        .select2-container,
        .tab-content,
        .tab-pane {
            z-index: auto !important;
        }
        
        /* Select dropdowns should be below modal */
        .bootstrap-select.show > .dropdown-menu,
        .select2-dropdown,
        .dropdown-menu.show {
            z-index: 1050 !important;
        }
        
        /* ========================================
           SEARCH RESULTS DROPDOWN (inline)
           ======================================== */
        .search-results-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 1060;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            max-height: 300px;
            overflow-y: auto;
            margin-top: 4px;
        }
        
        /* ========================================
           BRAND AUTOCOMPLETE
           ======================================== */
        .autocomplete-wrapper {
            position: relative;
        }
        
        .autocomplete-input {
            width: 100%;
            padding: 10px 40px 10px 14px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s ease;
            background: #f8fafc;
        }
        
        .autocomplete-input:focus {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16,185,129,0.1);
            background: #fff;
            outline: none;
        }
        
        .autocomplete-input.has-value {
            background: #fff;
            border-color: #10b981;
        }
        
        .autocomplete-clear {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: #e2e8f0;
            border: none;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #64748b;
            transition: all 0.2s ease;
        }
        
        .autocomplete-clear:hover {
            background: #cbd5e1;
            color: #334155;
        }
        
        .autocomplete-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 2000;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            max-height: 280px;
            overflow-y: auto;
            margin-top: 4px;
        }
        
        .autocomplete-item {
            padding: 10px 14px;
            cursor: pointer;
            transition: all 0.15s ease;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
        }
        
        .autocomplete-item:last-child {
            border-bottom: none;
        }
        
        .autocomplete-item:hover {
            background: linear-gradient(135deg, rgba(16,185,129,0.1) 0%, rgba(5,150,105,0.1) 100%);
            padding-left: 18px;
        }
        
        .autocomplete-item.active {
            background: linear-gradient(135deg, rgba(16,185,129,0.15) 0%, rgba(5,150,105,0.15) 100%);
            padding-left: 18px;
        }
        
        .autocomplete-item i {
            margin-right: 10px;
            color: #10b981;
        }
        
        .autocomplete-item .brand-name {
            font-weight: 500;
            color: #1e293b;
        }
        
        .autocomplete-item .brand-match {
            background: #fef3c7;
            padding: 0 2px;
            border-radius: 2px;
        }
        
        .autocomplete-hint {
            padding: 8px 14px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            font-size: 11px;
            color: #64748b;
        }
        
        .autocomplete-empty {
            padding: 16px;
            text-align: center;
            color: #94a3b8;
            font-size: 13px;
        }
        
        /* Selected brand badge */
        .selected-brand-badge {
            display: inline-flex;
            align-items: center;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
            margin-top: 6px;
        }
        
        .selected-brand-badge i {
            margin-right: 6px;
        }
        
        .selected-brand-badge .remove-brand {
            margin-left: 8px;
            background: rgba(255,255,255,0.2);
            border: none;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 10px;
        }
        
        .selected-brand-badge .remove-brand:hover {
            background: rgba(255,255,255,0.3);
        }
        
        /* ========================================
           FILE UPLOAD SECTION
           ======================================== */
        .file-upload-zone {
            border: 2px dashed #cbd5e1;
            border-radius: 12px;
            padding: 30px 20px;
            text-align: center;
            background: #f8fafc;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .file-upload-zone:hover {
            border-color: #10b981;
            background: rgba(16,185,129,0.05);
        }
        
        .file-upload-zone.drag-over {
            border-color: #10b981;
            background: rgba(16,185,129,0.1);
            transform: scale(1.01);
        }
        
        .file-upload-zone i {
            font-size: 48px;
            color: #94a3b8;
            margin-bottom: 12px;
        }
        
        .file-upload-zone:hover i {
            color: #10b981;
        }
        
        .file-upload-zone h5 {
            color: #475569;
            margin-bottom: 8px;
        }
        
        .file-upload-zone p {
            color: #94a3b8;
            font-size: 13px;
            margin: 0;
        }
        
        .file-upload-zone input[type="file"] {
            display: none;
        }
        
        /* Uploaded files list */
        .uploaded-files-list {
            margin-top: 16px;
        }
        
        .uploaded-file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 16px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            margin-bottom: 8px;
            transition: all 0.2s ease;
        }
        
        .uploaded-file-item:hover {
            border-color: #10b981;
            box-shadow: 0 2px 8px rgba(16,185,129,0.1);
        }
        
        .uploaded-file-info {
            display: flex;
            align-items: center;
            flex: 1;
            min-width: 0;
        }
        
        .uploaded-file-info i {
            font-size: 24px;
            color: #10b981;
            margin-right: 12px;
            flex-shrink: 0;
        }
        
        .uploaded-file-info .file-name {
            font-weight: 500;
            color: #1e293b;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 200px;
        }
        
        .uploaded-file-info .file-size {
            font-size: 12px;
            color: #94a3b8;
            margin-left: 8px;
        }
        
        .uploaded-file-type {
            margin: 0 12px;
            min-width: 150px;
        }
        
        .uploaded-file-type select {
            width: 100%;
            padding: 6px 10px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 13px;
            background: white;
            cursor: pointer;
        }
        
        .uploaded-file-type select:focus {
            border-color: #10b981;
            outline: none;
        }
        
        .uploaded-file-type select.assigned {
            border-color: #10b981;
            background: #ecfdf5;
        }
        
        .uploaded-file-remove {
            background: #fee2e2;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ef4444;
            transition: all 0.2s ease;
            flex-shrink: 0;
        }
        
        .uploaded-file-remove:hover {
            background: #fecaca;
        }
        
        /* File type badges */
        .file-type-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .file-type-badge.pv {
            background: #dbeafe;
            color: #1d4ed8;
        }
        
        .file-type-badge.constat {
            background: #fef3c7;
            color: #b45309;
        }
        
        .file-type-badge.declaration {
            background: #dcfce7;
            color: #166534;
        }
        
        @media (max-width: 768px) {
            .uploaded-file-item {
                flex-wrap: wrap;
                gap: 10px;
            }
            
            .uploaded-file-info {
                width: 100%;
            }
            
            .uploaded-file-type {
                flex: 1;
                margin: 0;
            }
        }
        
        /* Matricule Input Styling */
        .matricule-input-group {
            position: relative;
        }
        
        .matricule-badge {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 11px;
            padding: 3px 8px;
            border-radius: 4px;
            background: #f1f5f9;
            color: #64748b;
            font-family: monospace;
            letter-spacing: 1px;
        }
        
        .matricule-badge.valid {
            background: #dcfce7;
            color: #166534;
        }
        
        .matricule-badge.invalid {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .matricule-badge.searching {
            background: #fef3c7;
            color: #92400e;
        }
        
        .matricule-input {
            padding-right: 100px !important;
            font-family: monospace;
            letter-spacing: 2px;
            text-transform: uppercase;
        }
        
        /* Search indicator */
        .search-indicator {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
        }
        
        .search-indicator .spinner {
            width: 18px;
            height: 18px;
            border: 2px solid #e2e8f0;
            border-top-color: #10b981;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        
        @keyframes spin {
            to { transform: translateY(-50%) rotate(360deg); }
        }
        
        /* Quick action buttons */
        .quick-search-hint {
            font-size: 11px;
            color: #94a3b8;
            margin-top: 4px;
        }
        
        .quick-search-hint kbd {
            background: #f1f5f9;
            padding: 1px 5px;
            border-radius: 3px;
            font-size: 10px;
        }
        
        /* Enhanced form controls */
        .form-control-enhanced {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 10px 14px;
            transition: all 0.2s ease;
        }
        
        .form-control-enhanced:focus {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16,185,129,0.1);
        }
        
        /* Dossier found alert */
        .dossier-found-alert {
            background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
            border: 1px solid #10b981;
            border-radius: 8px;
            padding: 10px 14px;
            margin-top: 8px;
        }
        
        .dossier-found-alert .count-badge {
            background: #10b981;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
    </style>

    <div class="card mb-3">
        <div class="card-body">
            <form wire:submit.prevent="createStep()" method="post" enctype="multipart/form-data" autocomplete="off">
                @csrf
                <div id="basicwizard">
                    {{-- Navigation Tabs --}}
                    <ul class="nav nav-pills nav-justified form-wizard-header mb-4">
                        <li class="nav-item">
                            <a data-bs-toggle="tab" data-toggle="tab"
                                class="nav-link rounded-0 pt-2 pb-2 {{ $count == 0 ? 'active' : '' }}">
                                <i class="mdi mdi-car me-1"></i>
                                <span class="d-none d-sm-inline">Assuré, Véhicule & Documents</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a data-bs-toggle="tab" data-toggle="tab"
                                class="nav-link rounded-0 pt-2 pb-2 {{ $count == 1 ? 'active' : '' }}">
                                <i class="mdi mdi-human-handsup me-1"></i>
                                <span class="d-none d-sm-inline">Adversaire</span>
                            </a>
                        </li>
                    </ul>

                    <div class="tab-content b-0 mb-0">
                        {{-- Step 1: Assuré & Véhicule --}}
                        <div class="tab-pane {{ $count == 0 ? 'active' : '' }}" id="basictab1">
                            <div class="row g-2">

                                {{-- WW Matricule --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">
                                        Matricule WW
                                        <span class="text-muted small">(Format: WW-XXXXXX)</span>
                                    </label>
                                    <div class="matricule-input-group position-relative">
                                        <input type="text" 
                                            id="matriculeWW"
                                            name="new_matricule"
                                            class="form-control form-control-enhanced matricule-input @error('new_matricule') is-invalid @enderror"
                                            placeholder="WW-"
                                            wire:model.lazy="new_matricule"
                                            maxlength="9">
                                        <span id="wwBadge" class="matricule-badge">WW-XXXXXX</span>
                                        
                                        @if($searchingMatricule)
                                            <div class="search-indicator">
                                                <div class="spinner"></div>
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @error('new_matricule')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror

                                    {{-- Results alert and modal --}}
                                    @if($dossiers1 && count($dossiers1) > 0)
                                        <div class="dossier-found-alert">
                                            <span class="count-badge">{{ count($dossiers1) }}</span>
                                            <span class="ms-2 small">dossier(s) avec ce matricule</span>
                                            <a href="#" wire:click.prevent="toggleTable" class="float-end small text-success fw-bold">
                                                <i class="mdi mdi-eye me-1"></i>{{ $hidden ? 'Afficher' : 'Masquer' }}
                                            </a>
                                        </div>
                                        
                                        {{-- Modal Panel for results --}}
                                        @if(!$hidden)
                                            <div class="panel-backdrop" wire:click="toggleTable"></div>
                                            <div class="dossier-results-panel">
                                                <div class="panel-header">
                                                    <div>
                                                        <i class="mdi mdi-folder-search me-2"></i>
                                                        <strong>{{ count($dossiers1) }}</strong> dossier(s) trouvé(s)
                                                        <small class="d-block opacity-75">Matricule WW: {{ $new_matricule }}</small>
                                                    </div>
                                                    <button type="button" class="close-btn" wire:click="toggleTable">
                                                        <i class="mdi mdi-close"></i>
                                                    </button>
                                                </div>
                                                <div class="panel-body">
                                                    @foreach($dossiers1 as $d)
                                                        <div class="result-item" wire:click="importDossier1({{ $d->id }})">
                                                            <div class="d-flex justify-content-between align-items-start">
                                                                <div>
                                                                    <div class="result-header">
                                                                        <i class="mdi mdi-folder me-1 text-primary"></i>
                                                                        {{ $d->new_matricule ?? $d->matricule }}
                                                                    </div>
                                                                    <div class="result-meta mt-1">
                                                                        @if($d->insured)
                                                                            <i class="mdi mdi-account me-1"></i>{{ $d->insured->name }}
                                                                        @endif
                                                                        @if($d->vehiculemodel)
                                                                            <span class="mx-1">•</span>
                                                                            <i class="mdi mdi-car me-1"></i>{{ $d->vehiculemodel->brand->brand ?? '' }} {{ $d->vehiculemodel->name }}
                                                                        @endif
                                                                    </div>
                                                                    @if($d->company)
                                                                        <div class="result-meta">
                                                                            <i class="mdi mdi-domain me-1"></i>{{ $d->company->company }}
                                                                        </div>
                                                                    @endif
                                                                </div>
                                                                <div class="text-end">
                                                                    <span class="result-badge">Réf: {{ $d->ref }}</span>
                                                                    <div class="mt-1">
                                                                        <small class="text-muted">{{ $d->created_at ? $d->created_at->format('d/m/Y') : '' }}</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        @endif
                                    @endif
                                    
                                    <div class="quick-search-hint">
                                        <i class="mdi mdi-information-outline me-1"></i>
                                        Tapez le matricule, la recherche se fait automatiquement
                                    </div>
                                </div>

                                {{-- Old Matricule --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">
                                        Matricule Ancien
                                        <span class="text-muted small">(Format: XXXXX-X-XX)</span>
                                    </label>
                                    <div class="matricule-input-group position-relative">
                                        <input type="text" 
                                            id="matriculeOld"
                                            name="matricule"
                                            class="form-control form-control-enhanced matricule-input @error('matricule') is-invalid @enderror"
                                            placeholder="00000-A-00"
                                            wire:model.lazy="matricule"
                                            maxlength="10">
                                        <span id="oldBadge" class="matricule-badge">XXXXX-X-XX</span>
                                    </div>
                                    
                                    @error('matricule')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror

                                    {{-- Results alert and modal --}}
                                    @if($dossiers && count($dossiers) > 0)
                                        <div class="dossier-found-alert">
                                            <span class="count-badge">{{ count($dossiers) }}</span>
                                            <span class="ms-2 small">dossier(s) avec ce matricule</span>
                                            <a href="#" wire:click.prevent="toggleTable" class="float-end small text-success fw-bold">
                                                <i class="mdi mdi-eye me-1"></i>{{ $hidden ? 'Afficher' : 'Masquer' }}
                                            </a>
                                        </div>
                                        
                                        {{-- Modal Panel for results --}}
                                        @if(!$hidden)
                                            <div class="panel-backdrop" wire:click="toggleTable"></div>
                                            <div class="dossier-results-panel">
                                                <div class="panel-header">
                                                    <div>
                                                        <i class="mdi mdi-folder-search me-2"></i>
                                                        <strong>{{ count($dossiers) }}</strong> dossier(s) trouvé(s)
                                                        <small class="d-block opacity-75">Matricule: {{ $matricule }}</small>
                                                    </div>
                                                    <button type="button" class="close-btn" wire:click="toggleTable">
                                                        <i class="mdi mdi-close"></i>
                                                    </button>
                                                </div>
                                                <div class="panel-body">
                                                    @foreach($dossiers as $d)
                                                        <div class="result-item" wire:click="importDossier({{ $d->id }})">
                                                            <div class="d-flex justify-content-between align-items-start">
                                                                <div>
                                                                    <div class="result-header">
                                                                        <i class="mdi mdi-folder me-1 text-primary"></i>
                                                                        {{ $d->matricule ?? $d->new_matricule }}
                                                                    </div>
                                                                    <div class="result-meta mt-1">
                                                                        @if($d->insured)
                                                                            <i class="mdi mdi-account me-1"></i>{{ $d->insured->name }}
                                                                        @endif
                                                                        @if($d->vehiculemodel)
                                                                            <span class="mx-1">•</span>
                                                                            <i class="mdi mdi-car me-1"></i>{{ $d->vehiculemodel->brand->brand ?? '' }} {{ $d->vehiculemodel->name }}
                                                                        @endif
                                                                    </div>
                                                                    @if($d->company)
                                                                        <div class="result-meta">
                                                                            <i class="mdi mdi-domain me-1"></i>{{ $d->company->company }}
                                                                        </div>
                                                                    @endif
                                                                </div>
                                                                <div class="text-end">
                                                                    <span class="result-badge">Réf: {{ $d->ref }}</span>
                                                                    <div class="mt-1">
                                                                        <small class="text-muted">{{ $d->created_at ? $d->created_at->format('d/m/Y') : '' }}</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        @endif
                                    @endif
                                </div>

                                {{-- Date Sinistre --}}
                                <div class="mb-3 col-md-4 position-relative">
                                    <label class="form-label" for="date_sinistre">
                                        Date de Sinistre <span class="text-danger">*</span>
                                    </label>
                                    <input type="date"
                                        class="form-control form-control-enhanced @error('date_sinistre') is-invalid @enderror"
                                        name="date_sinistre" id="date_sinistre" wire:model="date_sinistre">
                                    @error('date_sinistre')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <hr class="my-3">

                                {{-- Civilité --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Civilité</label>
                                    <select name="civility" wire:model="civility"
                                        class="form-control form-control-enhanced @error('civility') is-invalid @enderror">
                                        <option value="" selected>Sélectionner</option>
                                        <option value="Mr">Monsieur</option>
                                        <option value="Mme">Madame</option>
                                        <option value="Sociéte">Société</option>
                                    </select>
                                    @error('civility')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Nom Assuré with search --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">
                                        Nom Assuré <span class="text-danger">*</span>
                                    </label>
                                    <div class="position-relative">
                                        <input type="text" 
                                            id="insuredName"
                                            name="name"
                                            class="form-control form-control-enhanced @error('name') is-invalid @enderror"
                                            placeholder="Entrer le nom de l'assuré" 
                                            wire:model.lazy="name">
                                        
                                        @if($searchingName)
                                            <div class="search-indicator">
                                                <div class="spinner"></div>
                                            </div>
                                        @endif
                                        
                                        {{-- Name search results --}}
                                        @if($dossiersByName && count($dossiersByName) > 0)
                                            {{-- Always show alert when results found --}}
                                            <div class="dossier-found-alert mt-2">
                                                <span class="count-badge">{{ count($dossiersByName) }}</span>
                                                <span class="ms-2 small">client(s) trouvé(s)</span>
                                                <a href="#" wire:click.prevent="toggleNameResults" class="float-end small text-success fw-bold">
                                                    <i class="mdi mdi-eye me-1"></i>Afficher
                                                </a>
                                            </div>
                                            
                                            {{-- Modal Panel - only when user clicks Afficher --}}
                                            @if($showNameResults)
                                                <div class="panel-backdrop" wire:click="toggleNameResults"></div>
                                                <div class="dossier-results-panel">
                                                    <div class="panel-header">
                                                        <div>
                                                            <i class="mdi mdi-account-search me-2"></i>
                                                            <strong>{{ count($dossiersByName) }}</strong> client(s) trouvé(s)
                                                            <small class="d-block opacity-75">Recherche: {{ $name }}</small>
                                                        </div>
                                                        <button type="button" class="close-btn" wire:click="toggleNameResults">
                                                            <i class="mdi mdi-close"></i>
                                                        </button>
                                                    </div>
                                                    <div class="panel-body">
                                                        @foreach($dossiersByName as $d)
                                                            <div class="result-item" wire:click="importDossierByName({{ $d->id }})">
                                                                <div class="d-flex justify-content-between align-items-start">
                                                                    <div>
                                                                        <div class="result-header">
                                                                            <i class="mdi mdi-account me-1 text-success"></i>
                                                                            {{ $d->insured->name ?? 'N/A' }}
                                                                        </div>
                                                                        <div class="result-meta mt-1">
                                                                            <i class="mdi mdi-car me-1"></i>{{ $d->matricule ?? $d->new_matricule }}
                                                                            @if($d->vehiculemodel)
                                                                                <span class="mx-1">•</span>
                                                                                {{ $d->vehiculemodel->brand->brand ?? '' }} {{ $d->vehiculemodel->name }}
                                                                            @endif
                                                                        </div>
                                                                        @if($d->company)
                                                                            <div class="result-meta">
                                                                                <i class="mdi mdi-domain me-1"></i>{{ $d->company->company }}
                                                                            </div>
                                                                        @endif
                                                                    </div>
                                                                    <div class="text-end">
                                                                        <span class="result-badge">Réf: {{ $d->ref }}</span>
                                                                        <div class="mt-1">
                                                                            <small class="text-muted">{{ $d->created_at ? $d->created_at->format('d/m/Y') : '' }}</small>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            @endif
                                        @endif
                                    </div>
                                    @error('name')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                    <div class="quick-search-hint">
                                        <i class="mdi mdi-magnify me-1"></i>
                                        Recherche automatique des clients existants
                                    </div>
                                </div>

                                {{-- Téléphone --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Téléphone Assuré</label>
                                    <input type="tel" name="telephone"
                                        class="form-control form-control-enhanced @error('telephone') is-invalid @enderror"
                                        placeholder="0611223355"
                                        wire:model="telephone"
                                        maxlength="10">
                                    @error('telephone')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Numero de Police --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Numéro de Police</label>
                                    <input type="text" name="numero_police"
                                        class="form-control form-control-enhanced @error('numero_police') is-invalid @enderror"
                                        placeholder="Entrer le numéro de police" 
                                        wire:model="numero_police">
                                    @error('numero_police')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Type de Vehicule --}}
                                <div class="mb-3 col-md-4">
                                    <label for="type_vehicule_id" class="form-label">Type de Véhicule</label>
                                    <select name="type_vehicule_id" id="type_vehicule_id"
                                        class="form-control selectpicker @error('type_vehicule_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="type_vehicule_id">
                                        <option value="" selected>Sélectionner un Type</option>
                                        @foreach ($typevehicules as $type)
                                            <option value="{{ $type->id }}">{{ $type->type }}</option>
                                        @endforeach
                                    </select>
                                    @error('type_vehicule_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Marque de Vehicule with Fast Autocomplete --}}
                                <div class="mb-3 col-md-4">
                                    <label for="brand_id" class="form-label">Marque de Véhicule</label>
                                    
                                    {{-- Fast Autocomplete Input --}}
                                    <div class="autocomplete-wrapper" wire:ignore.self>
                                        <input type="text" 
                                            id="brandAutocomplete"
                                            class="autocomplete-input {{ $selectedBrand ? 'has-value' : '' }}"
                                            placeholder="Tapez pour rechercher une marque..."
                                            wire:model.debounce.150ms="brandSearch"
                                            wire:focus="$set('showBrandDropdown', true)"
                                            autocomplete="off">
                                        
                                        @if($selectedBrand)
                                            <button type="button" class="autocomplete-clear" wire:click="clearBrand" title="Effacer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        @endif
                                        
                                        {{-- Autocomplete Dropdown --}}
                                        @if($showBrandDropdown && strlen($brandSearch) > 0)
                                            <div class="autocomplete-dropdown">
                                                @if(count($brandResults) > 0)
                                                    <div class="autocomplete-hint">
                                                        <i class="mdi mdi-information-outline me-1"></i>
                                                        {{ count($brandResults) }} marque(s) trouvée(s) - Cliquez pour sélectionner
                                                    </div>
                                                    @foreach($brandResults as $brand)
                                                        <div class="autocomplete-item" wire:click="selectBrand({{ $brand->id }}, '{{ addslashes($brand->brand) }}')">
                                                            <i class="mdi mdi-car"></i>
                                                            <span class="brand-name">{{ $brand->brand }}</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="autocomplete-empty">
                                                        <i class="mdi mdi-magnify-close me-1"></i>
                                                        Aucune marque trouvée pour "{{ $brandSearch }}"
                                                    </div>
                                                @endif
                                            </div>
                                        @endif
                                    </div>
                                    
                                    {{-- Selected Brand Badge --}}
                                    @if($selectedBrand && $selectedBrandName)
                                        <div class="selected-brand-badge">
                                            <i class="mdi mdi-check-circle"></i>
                                            {{ $selectedBrandName }}
                                            <button type="button" class="remove-brand" wire:click="clearBrand" title="Supprimer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        </div>
                                    @endif
                                    
                                    {{-- Hidden input for form submission --}}
                                    <input type="hidden" name="brand_id" wire:model="selectedBrand">
                                    
                                    @error('selectedBrand')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- API Year Select (hidden by default) --}}
                                <div id="apiYearContainer" class="mb-3 col-md-4 d-none">
                                    <label class="form-label">Année du véhicule</label>
                                    <select id="apiYear" class="form-control selectpicker" data-live-search="true">
                                        <option value="">Sélectionner l'année</option>
                                    </select>
                                </div>

                                {{-- Modele de Vehicule --}}
                                <div class="mb-3 col-md-4">
                                    <label for="vehicule_model_id" class="form-label">Modèle de Véhicule</label>
                                    
                                    {{-- Local Database Model Select --}}
                                    <div id="localModelContainer">
                                        <select name="vehicule_model_id" id="vehicule_model_id"
                                            class="form-control selectpicker @error('vehicule_model_id') is-invalid @enderror"
                                            data-live-search="true"
                                            wire:model="vehicule_model_id">
                                            <option value="" selected>Sélectionner un modèle</option>
                                            @if ($models)
                                                @foreach ($models as $model)
                                                    <option value="{{ $model->id }}">{{ $model->name }}</option>
                                                @endforeach
                                            @endif
                                        </select>
                                    </div>
                                    
                                    {{-- API Model Select --}}
                                    <div id="apiModelContainer" class="d-none">
                                        <select id="apiModel" class="form-control selectpicker" data-live-search="true">
                                            <option value="">Sélectionner d'abord une marque</option>
                                        </select>
                                    </div>

                                    @error('vehicule_model_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                                
                                {{-- Hidden inputs for API --}}
                                <input type="hidden" id="apiBrandName" name="api_brand_name" wire:model="api_brand_name">
                                <input type="hidden" id="apiModelName" name="api_model_name" wire:model="api_model_name">
                                <input type="hidden" id="apiYearValue" name="api_year" wire:model="api_year">

                                {{-- Garantie --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Garantie</label>
                                    <select id="guarantee_id" name="guarantee_id"
                                        class="form-control selectpicker @error('guarantee_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="guarantee_id">
                                        <option value="" selected>Sélectionner la garantie</option>
                                        @foreach ($warranties as $warranty)
                                            <option value="{{ $warranty->id }}">{{ $warranty->guarantee }}</option>
                                        @endforeach
                                    </select>
                                    @error('guarantee_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Numero de sinistre --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label" for="numero_sinistre">
                                        Numéro de sinistre <span class="text-danger">*</span>
                                    </label>
                                    <input type="text"
                                        class="form-control form-control-enhanced @error('numero_sinistre') is-invalid @enderror"
                                        name="numero_sinistre" id="numero_sinistre" wire:model="numero_sinistre">
                                    @error('numero_sinistre')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Intermédiaire with Fast Autocomplete --}}
                                <div class="mb-3 col-md-4">
                                    <label for="intermidiaire_id" class="form-label">Nom Intermédiaire</label>
                                    
                                    <div class="autocomplete-wrapper" wire:ignore.self>
                                        <input type="text" 
                                            id="intermediaireAutocomplete"
                                            class="autocomplete-input {{ $intermidiaire_id ? 'has-value' : '' }}"
                                            placeholder="Tapez pour rechercher..."
                                            wire:model.debounce.150ms="intermediaireSearch"
                                            wire:focus="$set('showIntermediaireDropdown', true)"
                                            autocomplete="off">
                                        
                                        @if($intermidiaire_id)
                                            <button type="button" class="autocomplete-clear" wire:click="clearIntermediaire" title="Effacer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        @endif
                                        
                                        {{-- Autocomplete Dropdown --}}
                                        @if($showIntermediaireDropdown && strlen($intermediaireSearch) > 0)
                                            <div class="autocomplete-dropdown">
                                                @if(count($intermediaireResults) > 0)
                                                    <div class="autocomplete-hint">
                                                        <i class="mdi mdi-information-outline me-1"></i>
                                                        {{ count($intermediaireResults) }} intermédiaire(s) trouvé(s)
                                                    </div>
                                                    @foreach($intermediaireResults as $interm)
                                                        <div class="autocomplete-item" wire:click="selectIntermediaire({{ $interm->id }}, '{{ addslashes($interm->company) }}')">
                                                            <i class="mdi mdi-account-tie"></i>
                                                            <span class="brand-name">{{ $interm->company }}</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="autocomplete-empty">
                                                        <i class="mdi mdi-magnify-close me-1"></i>
                                                        Aucun intermédiaire trouvé pour "{{ $intermediaireSearch }}"
                                                    </div>
                                                @endif
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @if($intermidiaire_id && $selectedIntermediaireName)
                                        <div class="selected-brand-badge" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
                                            <i class="mdi mdi-account-tie"></i>
                                            {{ $selectedIntermediaireName }}
                                            <button type="button" class="remove-brand" wire:click="clearIntermediaire" title="Supprimer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        </div>
                                    @endif
                                    
                                    <input type="hidden" name="intermidiaire_id" wire:model="intermidiaire_id">
                                    
                                    @error('intermidiaire_id')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Compagnie --}}
                                <div class="mb-3 col-md-4">
                                    <label for="company_id" class="form-label">
                                        Compagnie <span class="text-danger">*</span>
                                    </label>
                                    <select name="company_id" id="company_id"
                                        class="form-control selectpicker @error('company_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="company_id">
                                        <option value="" selected>Sélectionner la Compagnie</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}">{{ $company->company }}</option>
                                        @endforeach
                                    </select>
                                    @error('company_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Date de Reception --}}
                                <div class="mb-3 col-md-4 position-relative">
                                    <label class="form-label" for="date_reception">
                                        Date de Réception <span class="text-danger">*</span>
                                    </label>
                                    <input type="date"
                                        class="form-control form-control-enhanced @error('date_reception') is-invalid @enderror"
                                        name="date_reception" id="date_reception" wire:model="date_reception">
                                    @error('date_reception')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Vehicle Details Section --}}
                                <div class="col-12">
                                    <hr class="my-3">
                                    <h6 class="text-muted mb-3">
                                        <i class="mdi mdi-car-info me-1"></i>Détails du Véhicule
                                    </h6>
                                </div>

                                {{-- Mode --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Mode <span class="text-danger">*</span></label>
                                    <select id="mode_id" name="mode_id"
                                        class="form-control selectpicker @error('mode_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="mode_id">
                                        <option value="" selected>Sélectionner Mode</option>
                                        @foreach ($dossierTypes as $type)
                                            <option value="{{ $type->id }}">{{ $type->mode }}</option>
                                        @endforeach
                                    </select>
                                    @error('mode_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Type Expertise --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Type Expertise <span class="text-danger">*</span></label>
                                    <select id="type_expertise_id" name="type_expertise_id"
                                        class="form-control selectpicker @error('type_expertise_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="type_expertise_id">
                                        <option value="" selected>Sélectionner le Type Expertise</option>
                                        @foreach ($typeexpertises as $type)
                                            <option value="{{ $type->id }}">{{ $type->type }}</option>
                                        @endforeach
                                    </select>
                                    @error('type_expertise_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Garage with Fast Autocomplete --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Garage</label>
                                    
                                    <div class="autocomplete-wrapper" wire:ignore.self>
                                        <input type="text" 
                                            id="garageAutocomplete"
                                            class="autocomplete-input {{ $garage_id ? 'has-value' : '' }}"
                                            placeholder="Tapez pour rechercher un garage..."
                                            wire:model.debounce.150ms="garageSearch"
                                            wire:focus="$set('showGarageDropdown', true)"
                                            autocomplete="off">
                                        
                                        @if($garage_id)
                                            <button type="button" class="autocomplete-clear" wire:click="clearGarage" title="Effacer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        @endif
                                        
                                        {{-- Autocomplete Dropdown --}}
                                        @if($showGarageDropdown && strlen($garageSearch) > 0)
                                            <div class="autocomplete-dropdown">
                                                @if(count($garageResults) > 0)
                                                    <div class="autocomplete-hint">
                                                        <i class="mdi mdi-information-outline me-1"></i>
                                                        {{ count($garageResults) }} garage(s) trouvé(s)
                                                    </div>
                                                    @foreach($garageResults as $garage)
                                                        <div class="autocomplete-item" wire:click="selectGarage({{ $garage->id }}, '{{ addslashes($garage->libelle) }}')">
                                                            <i class="mdi mdi-garage"></i>
                                                            <span class="brand-name">{{ $garage->libelle }}</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="autocomplete-empty">
                                                        <i class="mdi mdi-magnify-close me-1"></i>
                                                        Aucun garage trouvé pour "{{ $garageSearch }}"
                                                    </div>
                                                @endif
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @if($garage_id && $selectedGarageName)
                                        <div class="selected-brand-badge" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);">
                                            <i class="mdi mdi-garage"></i>
                                            {{ $selectedGarageName }}
                                            <button type="button" class="remove-brand" wire:click="clearGarage" title="Supprimer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        </div>
                                    @endif
                                    
                                    <input type="hidden" name="garage_id" wire:model="garage_id">
                                    
                                    @error('garage_id')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Numero de chassis (VIN) with search --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">
                                        Numéro de Châssis (VIN)
                                        <span class="text-muted small">(17 caractères)</span>
                                    </label>
                                    <div class="position-relative">
                                        <input type="text" 
                                            id="chassisNumber"
                                            name="chassis_number"
                                            class="form-control form-control-enhanced @error('chassis_number') is-invalid @enderror"
                                            placeholder="Ex: WVWZZZ3CZWE123456"
                                            wire:model.lazy="chassis_number"
                                            maxlength="17"
                                            style="text-transform: uppercase; font-family: monospace; letter-spacing: 1px;">
                                        
                                        @if($searchingChassis)
                                            <div class="search-indicator">
                                                <div class="spinner"></div>
                                            </div>
                                        @endif
                                        
                                        {{-- Chassis search results --}}
                                        @if($dossiersByChassis && count($dossiersByChassis) > 0)
                                            {{-- Always show alert when results found --}}
                                            <div class="dossier-found-alert mt-2">
                                                <span class="count-badge">{{ count($dossiersByChassis) }}</span>
                                                <span class="ms-2 small">véhicule(s) trouvé(s)</span>
                                                <a href="#" wire:click.prevent="toggleChassisResults" class="float-end small text-success fw-bold">
                                                    <i class="mdi mdi-eye me-1"></i>Afficher
                                                </a>
                                            </div>
                                            
                                            {{-- Modal Panel - only when user clicks Afficher --}}
                                            @if($showChassisResults)
                                                <div class="panel-backdrop" wire:click="toggleChassisResults"></div>
                                                <div class="dossier-results-panel">
                                                    <div class="panel-header">
                                                        <div>
                                                            <i class="mdi mdi-car-key me-2"></i>
                                                            <strong>{{ count($dossiersByChassis) }}</strong> véhicule(s) trouvé(s)
                                                            <small class="d-block opacity-75">VIN: {{ $chassis_number }}</small>
                                                        </div>
                                                        <button type="button" class="close-btn" wire:click="toggleChassisResults">
                                                            <i class="mdi mdi-close"></i>
                                                        </button>
                                                    </div>
                                                    <div class="panel-body">
                                                        @foreach($dossiersByChassis as $d)
                                                            <div class="result-item" wire:click="importDossierByChassis({{ $d->id }})">
                                                                <div class="d-flex justify-content-between align-items-start">
                                                                    <div>
                                                                        <div class="result-header">
                                                                            <i class="mdi mdi-car-key me-1 text-warning"></i>
                                                                            {{ $d->numero_chassis }}
                                                                        </div>
                                                                        <div class="result-meta mt-1">
                                                                            <i class="mdi mdi-car me-1"></i>{{ $d->matricule ?? $d->new_matricule }}
                                                                            @if($d->insured)
                                                                                <span class="mx-1">•</span>
                                                                                <i class="mdi mdi-account me-1"></i>{{ $d->insured->name }}
                                                                            @endif
                                                                        </div>
                                                                        @if($d->vehiculemodel)
                                                                            <div class="result-meta">
                                                                                <i class="mdi mdi-car-side me-1"></i>
                                                                                {{ $d->vehiculemodel->brand->brand ?? '' }} {{ $d->vehiculemodel->name }}
                                                                            </div>
                                                                        @endif
                                                                    </div>
                                                                    <div class="text-end">
                                                                        <span class="result-badge">Réf: {{ $d->ref }}</span>
                                                                        <div class="mt-1">
                                                                            <small class="text-muted">{{ $d->created_at ? $d->created_at->format('d/m/Y') : '' }}</small>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                            @endif
                                        @endif
                                    </div>
                                    @error('chassis_number')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                    <div class="quick-search-hint">
                                        <i class="mdi mdi-magnify me-1"></i>
                                        Recherche automatique des véhicules par VIN
                                    </div>
                                </div>

                                {{-- Numero d'attestation --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Numéro d'attestation</label>
                                    <input type="text" name="numero_attestation"
                                        class="form-control form-control-enhanced @error('numero_attestation') is-invalid @enderror"
                                        placeholder="Entrer le numéro d'attestation" 
                                        wire:model="numero_attestation">
                                    @error('numero_attestation')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Date de mise en circulation --}}
                                <div class="mb-3 col-md-4 position-relative">
                                    <label class="form-label" for="circulation_date">Date de mise en circulation</label>
                                    <input type="date"
                                        class="form-control form-control-enhanced @error('circulation_date') is-invalid @enderror"
                                        name="circulation_date" id="circulation_date" wire:model="circulation_date">
                                    @error('circulation_date')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Kilométrage --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label" for="kilometrage">Kilométrage</label>
                                    <input type="number" min="0"
                                        class="form-control form-control-enhanced @error('kilometrage') is-invalid @enderror"
                                        placeholder="Ex: 125000" name="kilometrage" id="kilometrage"
                                        wire:model="kilometrage">
                                    @error('kilometrage')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Puissance Fiscale --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label" for="puissance_fiscale">Puissance Fiscale</label>
                                    <input type="number" min="1"
                                        class="form-control form-control-enhanced @error('puissance_fiscale') is-invalid @enderror"
                                        placeholder="Ex: 7" name="puissance_fiscale"
                                        id="puissance_fiscale" wire:model="puissance_fiscale">
                                    @error('puissance_fiscale')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Carburant --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label" for="carburant">Carburant</label>
                                    <select id="carburant" name="carburant"
                                        class="form-control selectpicker @error('carburant') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="carburant">
                                        <option value="" selected>Sélectionner Carburant</option>
                                        @foreach ($carburants as $carb)
                                            <option value="{{ $carb->id }}">{{ $carb->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('carburant')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Ville with Fast Autocomplete --}}
                                <div class="mb-3 col-md-4">
                                    <label class="form-label" for="city_id">Ville</label>
                                    
                                    <div class="autocomplete-wrapper" wire:ignore.self>
                                        <input type="text" 
                                            id="cityAutocomplete"
                                            class="autocomplete-input {{ $city_id ? 'has-value' : '' }}"
                                            placeholder="Tapez pour rechercher une ville..."
                                            wire:model.debounce.150ms="citySearch"
                                            wire:focus="$set('showCityDropdown', true)"
                                            autocomplete="off">
                                        
                                        @if($city_id)
                                            <button type="button" class="autocomplete-clear" wire:click="clearCity" title="Effacer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        @endif
                                        
                                        {{-- Autocomplete Dropdown --}}
                                        @if($showCityDropdown && strlen($citySearch) > 0)
                                            <div class="autocomplete-dropdown">
                                                @if(count($cityResults) > 0)
                                                    <div class="autocomplete-hint">
                                                        <i class="mdi mdi-information-outline me-1"></i>
                                                        {{ count($cityResults) }} ville(s) trouvée(s)
                                                    </div>
                                                    @foreach($cityResults as $city)
                                                        <div class="autocomplete-item" wire:click="selectCity({{ $city->id }}, '{{ addslashes($city->city) }}')">
                                                            <i class="mdi mdi-map-marker"></i>
                                                            <span class="brand-name">{{ $city->city }}</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="autocomplete-empty">
                                                        <i class="mdi mdi-magnify-close me-1"></i>
                                                        Aucune ville trouvée pour "{{ $citySearch }}"
                                                    </div>
                                                @endif
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @if($city_id && $selectedCityName)
                                        <div class="selected-brand-badge" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                                            <i class="mdi mdi-map-marker"></i>
                                            {{ $selectedCityName }}
                                            <button type="button" class="remove-brand" wire:click="clearCity" title="Supprimer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        </div>
                                    @endif
                                    
                                    <input type="hidden" name="city_id" wire:model="city_id">
                                    
                                    @error('city_id')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Documents Section --}}
                                <div class="col-12">
                                    <hr class="my-3">
                                    <h6 class="text-muted mb-3">
                                        <i class="mdi mdi-file-document-multiple me-1"></i>Documents
                                    </h6>
                                </div>

                                <div class="col-12">
                                    {{-- File Upload Zone --}}
                                    <div class="file-upload-zone" 
                                         onclick="document.getElementById('fileUploadInput').click()"
                                         id="dropZone">
                                        <i class="mdi mdi-cloud-upload"></i>
                                        <h5>Glissez vos fichiers ici</h5>
                                        <p>ou cliquez pour sélectionner (PV, Constat, Déclaration)</p>
                                        <input type="file" 
                                               id="fileUploadInput" 
                                               wire:model="uploadedFiles" 
                                               multiple 
                                               accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
                                    </div>
                                    
                                    {{-- Loading indicator --}}
                                    <div wire:loading wire:target="uploadedFiles" class="text-center mt-3">
                                        <div class="spinner-border text-success" role="status">
                                            <span class="visually-hidden">Chargement...</span>
                                        </div>
                                        <p class="text-muted mt-2">Téléchargement en cours...</p>
                                    </div>
                                    
                                    {{-- Uploaded Files List --}}
                                    @if($uploadedFiles && count($uploadedFiles) > 0)
                                        <div class="uploaded-files-list">
                                            <div class="d-flex justify-content-between align-items-center mb-3">
                                                <span class="text-muted">
                                                    <i class="mdi mdi-paperclip me-1"></i>
                                                    {{ count($uploadedFiles) }} fichier(s) sélectionné(s)
                                                </span>
                                                <small class="text-warning">
                                                    <i class="mdi mdi-alert-circle me-1"></i>
                                                    Assignez un type à chaque fichier
                                                </small>
                                            </div>
                                            
                                            @foreach($uploadedFiles as $index => $file)
                                                <div class="uploaded-file-item">
                                                    <div class="uploaded-file-info">
                                                        <i class="mdi mdi-file-document"></i>
                                                        <div>
                                                            <span class="file-name">{{ $file->getClientOriginalName() }}</span>
                                                            <span class="file-size">{{ number_format($file->getSize() / 1024, 1) }} KB</span>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="uploaded-file-type">
                                                        <select wire:change="setFileType({{ $index }}, $event.target.value)"
                                                                class="{{ isset($fileTypes[$index]) && $fileTypes[$index] ? 'assigned' : '' }}">
                                                            <option value="">-- Type --</option>
                                                            <option value="1" {{ (isset($fileTypes[$index]) && $fileTypes[$index] == '1') ? 'selected' : '' }}>
                                                                📋 PV
                                                            </option>
                                                            <option value="2" {{ (isset($fileTypes[$index]) && $fileTypes[$index] == '2') ? 'selected' : '' }}>
                                                                📝 Constat
                                                            </option>
                                                            <option value="3" {{ (isset($fileTypes[$index]) && $fileTypes[$index] == '3') ? 'selected' : '' }}>
                                                                📄 Déclaration
                                                            </option>
                                                        </select>
                                                    </div>
                                                    
                                                    <button type="button" 
                                                            class="uploaded-file-remove" 
                                                            wire:click="removeUploadedFile({{ $index }})"
                                                            title="Supprimer">
                                                        <i class="mdi mdi-delete"></i>
                                                    </button>
                                                </div>
                                            @endforeach
                                            
                                            {{-- Summary badges --}}
                                            <div class="mt-3 d-flex gap-2 flex-wrap">
                                                @php
                                                    $pvCount = collect($fileTypes)->filter(fn($v) => $v == '1')->count();
                                                    $constatCount = collect($fileTypes)->filter(fn($v) => $v == '2')->count();
                                                    $declarationCount = collect($fileTypes)->filter(fn($v) => $v == '3')->count();
                                                    $unassigned = count($uploadedFiles) - $pvCount - $constatCount - $declarationCount;
                                                @endphp
                                                
                                                @if($pvCount > 0)
                                                    <span class="file-type-badge pv">
                                                        <i class="mdi mdi-file me-1"></i>PV: {{ $pvCount }}
                                                    </span>
                                                @endif
                                                @if($constatCount > 0)
                                                    <span class="file-type-badge constat">
                                                        <i class="mdi mdi-file-document me-1"></i>Constat: {{ $constatCount }}
                                                    </span>
                                                @endif
                                                @if($declarationCount > 0)
                                                    <span class="file-type-badge declaration">
                                                        <i class="mdi mdi-file-check me-1"></i>Déclaration: {{ $declarationCount }}
                                                    </span>
                                                @endif
                                                @if($unassigned > 0)
                                                    <span class="file-type-badge" style="background: #fee2e2; color: #991b1b;">
                                                        <i class="mdi mdi-alert me-1"></i>Non assigné: {{ $unassigned }}
                                                    </span>
                                                @endif
                                            </div>
                                        </div>
                                    @endif
                                </div>

                            </div>
                        </div>

                        {{-- Step 2: Adversaire --}}
                        <div class="tab-pane {{ $count == 1 ? 'active' : '' }}" id="basictab2">
                            <div class="row g-2">
                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Civilité</label>
                                    <select name="civilityop" wire:model="civilityop"
                                        class="form-control form-control-enhanced @error('civilityop') is-invalid @enderror">
                                        <option value="" selected>Sélectionner</option>
                                        <option value="Mr">Monsieur</option>
                                        <option value="Mme">Madame</option>
                                        <option value="Sociéte">Société</option>
                                    </select>
                                    @error('civilityop')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Nom Adversaire</label>
                                    <input type="text" name="nameop"
                                        class="form-control form-control-enhanced @error('nameop') is-invalid @enderror"
                                        placeholder="Entrer le nom de l'adversaire" wire:model="nameop">
                                    @error('nameop')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Téléphone Adversaire</label>
                                    <input type="tel" name="telephoneop"
                                        class="form-control form-control-enhanced @error('telephoneop') is-invalid @enderror"
                                        placeholder="0611223355" wire:model="telephoneop"
                                        maxlength="10">
                                    @error('telephoneop')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Matricule Adversaire</label>
                                    <input type="text" name="matriculeop"
                                        class="form-control form-control-enhanced @error('matriculeop') is-invalid @enderror"
                                        placeholder="Matricule adversaire" wire:model="matriculeop">
                                    @error('matriculeop')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Compagnie Adversaire</label>
                                    <select name="companyop_id"
                                        class="form-control selectpicker @error('companyop_id') is-invalid @enderror"
                                        data-live-search="true"
                                        wire:model="companyop_id">
                                        <option value="" selected>Sélectionner Compagnie</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}">{{ $company->company }}</option>
                                        @endforeach
                                    </select>
                                    @error('companyop_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <div class="mb-3 col-md-4">
                                    <label class="form-label">Numéro Attestation Adversaire</label>
                                    <input type="text" name="numero_attestationop"
                                        class="form-control form-control-enhanced @error('numero_attestationop') is-invalid @enderror"
                                        placeholder="Numéro attestation" wire:model="numero_attestationop">
                                    @error('numero_attestationop')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Marque Adversaire with Fast Autocomplete --}}
                                <div class="mb-3 col-md-4">
                                    <label for="brand_idop" class="form-label">Marque Véhicule Adversaire</label>
                                    
                                    <div class="autocomplete-wrapper" wire:ignore.self>
                                        <input type="text" 
                                            id="brandOpAutocomplete"
                                            class="autocomplete-input {{ $selectedBrandop ? 'has-value' : '' }}"
                                            placeholder="Tapez pour rechercher une marque..."
                                            wire:model.debounce.150ms="brandSearchOp"
                                            wire:focus="$set('showBrandDropdownOp', true)"
                                            autocomplete="off">
                                        
                                        @if($selectedBrandop)
                                            <button type="button" class="autocomplete-clear" wire:click="clearBrandOp" title="Effacer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        @endif
                                        
                                        {{-- Autocomplete Dropdown --}}
                                        @if($showBrandDropdownOp && strlen($brandSearchOp) > 0)
                                            <div class="autocomplete-dropdown">
                                                @if(count($brandResultsOp) > 0)
                                                    <div class="autocomplete-hint">
                                                        <i class="mdi mdi-information-outline me-1"></i>
                                                        {{ count($brandResultsOp) }} marque(s) trouvée(s)
                                                    </div>
                                                    @foreach($brandResultsOp as $brand)
                                                        <div class="autocomplete-item" wire:click="selectBrandOp({{ $brand->id }}, '{{ addslashes($brand->brand) }}')">
                                                            <i class="mdi mdi-car"></i>
                                                            <span class="brand-name">{{ $brand->brand }}</span>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <div class="autocomplete-empty">
                                                        <i class="mdi mdi-magnify-close me-1"></i>
                                                        Aucune marque trouvée pour "{{ $brandSearchOp }}"
                                                    </div>
                                                @endif
                                            </div>
                                        @endif
                                    </div>
                                    
                                    @if($selectedBrandop && $selectedBrandNameOp)
                                        <div class="selected-brand-badge">
                                            <i class="mdi mdi-car"></i>
                                            {{ $selectedBrandNameOp }}
                                            <button type="button" class="remove-brand" wire:click="clearBrandOp" title="Supprimer">
                                                <i class="mdi mdi-close"></i>
                                            </button>
                                        </div>
                                    @endif
                                    
                                    <input type="hidden" name="brand_idop" wire:model="selectedBrandop">
                                    
                                    @error('brand_idop')
                                        <span class="invalid-feedback d-block" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                {{-- Modèle Adversaire --}}
                                <div class="mb-3 col-md-4">
                                    <label for="vehicule_modelop_id" class="form-label">Modèle Véhicule Adversaire</label>
                                    <select name="vehicule_modelop_id" id="vehicule_modelop_id"
                                        class="form-control form-control-enhanced @error('vehicule_modelop_id') is-invalid @enderror"
                                        wire:model="vehicule_modelop_id"
                                        {{ !$selectedBrandop ? 'disabled' : '' }}>
                                        <option value="" selected>
                                            {{ $selectedBrandop ? 'Sélectionner un modèle' : 'Sélectionnez d\'abord une marque' }}
                                        </option>
                                        @if ($modelsop)
                                            @foreach ($modelsop as $model)
                                                <option value="{{ $model->id }}">{{ $model->name }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                    @if($selectedBrandop && $modelsop && count($modelsop) > 0)
                                        <small class="text-muted">{{ count($modelsop) }} modèle(s) disponible(s)</small>
                                    @endif
                                    @error('vehicule_modelop_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Navigation Buttons --}}
                    <ul class="list-inline wizard mb-0 mt-4">
                        <li class="previous list-inline-item">
                            @if ($count > 0)
                                <button type="button" wire:click="previousStep()"
                                    class="btn btn-secondary">
                                    <i class="mdi mdi-arrow-left me-1"></i> Précédent
                                </button>
                            @endif
                        </li>
                        <li class="next list-inline-item float-end">
                            @if ($count == 0)
                                <button type="button" wire:click="vehiculeStep()"
                                    class="btn btn-primary">
                                    Suivant <i class="mdi mdi-arrow-right ms-1"></i>
                                </button>
                            @elseif($count == 1)
                                <button type="submit" class="btn btn-success">
                                    <i class="mdi mdi-check me-1"></i> Créer le Dossier
                                </button>
                            @endif
                        </li>
                    </ul>
                </div>
            </form>
        </div>
    </div>

    {{-- JavaScript for enhanced UX --}}
    <script>
    document.addEventListener('livewire:load', function() {
        initEnhancedInputs();
        initBrandAutocomplete();
        
        // Re-initialize after Livewire updates
        Livewire.hook('message.processed', function() {
            setTimeout(initEnhancedInputs, 100);
        });
        
        // Handle dossier import event
        Livewire.on('dossierImported', function() {
            // Refresh bootstrap-select pickers
            if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
                jQuery('.selectpicker').selectpicker('refresh');
            }
        });
    });
    
    // ========================================
    // BRAND AUTOCOMPLETE
    // ========================================
    function initBrandAutocomplete() {
        // Close all autocomplete dropdowns when clicking outside
        document.addEventListener('click', function(e) {
            const wrappers = document.querySelectorAll('.autocomplete-wrapper');
            wrappers.forEach(wrapper => {
                if (!wrapper.contains(e.target)) {
                    // Close this dropdown
                    const input = wrapper.querySelector('input');
                    if (input) {
                        const fieldName = input.id.replace('Autocomplete', '');
                        if (fieldName === 'brand') @this.set('showBrandDropdown', false);
                        if (fieldName === 'city') @this.set('showCityDropdown', false);
                        if (fieldName === 'garage') @this.set('showGarageDropdown', false);
                        if (fieldName === 'intermediaire') @this.set('showIntermediaireDropdown', false);
                        if (fieldName === 'brandOp') @this.set('showBrandDropdownOp', false);
                    }
                }
            });
        });
        
        // Initialize keyboard navigation for all autocomplete fields
        initAutocompleteKeyboard('brandAutocomplete', 'showBrandDropdown');
        initAutocompleteKeyboard('cityAutocomplete', 'showCityDropdown');
        initAutocompleteKeyboard('garageAutocomplete', 'showGarageDropdown');
        initAutocompleteKeyboard('intermediaireAutocomplete', 'showIntermediaireDropdown');
        initAutocompleteKeyboard('brandOpAutocomplete', 'showBrandDropdownOp');
        
        // Initialize drag and drop for file upload
        initDragAndDrop();
    }
    
    function initAutocompleteKeyboard(inputId, dropdownProp) {
        const input = document.getElementById(inputId);
        if (!input || input.hasAttribute('data-keyboard-init')) return;
        input.setAttribute('data-keyboard-init', 'true');
        
        input.addEventListener('keydown', function(e) {
            const dropdown = this.closest('.autocomplete-wrapper').querySelector('.autocomplete-dropdown');
            if (!dropdown) return;
            
            const items = dropdown.querySelectorAll('.autocomplete-item');
            const current = dropdown.querySelector('.autocomplete-item.active');
            let index = Array.from(items).indexOf(current);
            
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (index < items.length - 1) index++;
                else index = 0;
                items.forEach(i => i.classList.remove('active'));
                items[index]?.classList.add('active');
                items[index]?.scrollIntoView({ block: 'nearest' });
            }
            
            if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (index > 0) index--;
                else index = items.length - 1;
                items.forEach(i => i.classList.remove('active'));
                items[index]?.classList.add('active');
                items[index]?.scrollIntoView({ block: 'nearest' });
            }
            
            if (e.key === 'Enter') {
                e.preventDefault();
                const active = dropdown.querySelector('.autocomplete-item.active');
                if (active) active.click();
                else if (items.length === 1) items[0].click();
            }
            
            if (e.key === 'Escape') {
                @this.set(dropdownProp, false);
                input.blur();
            }
        });
    }
    
    // ========================================
    // DRAG AND DROP FILE UPLOAD
    // ========================================
    function initDragAndDrop() {
        const dropZone = document.getElementById('dropZone');
        if (!dropZone || dropZone.hasAttribute('data-drop-init')) return;
        dropZone.setAttribute('data-drop-init', 'true');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.add('drag-over');
            }, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.remove('drag-over');
            }, false);
        });
        
        dropZone.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            // Trigger Livewire file upload
            const input = document.getElementById('fileUploadInput');
            if (input) {
                // Create a new DataTransfer to set files
                const dataTransfer = new DataTransfer();
                
                // Add existing files if any
                if (input.files) {
                    for (let i = 0; i < input.files.length; i++) {
                        dataTransfer.items.add(input.files[i]);
                    }
                }
                
                // Add new dropped files
                for (let i = 0; i < files.length; i++) {
                    dataTransfer.items.add(files[i]);
                }
                
                input.files = dataTransfer.files;
                
                // Trigger change event for Livewire
                const event = new Event('change', { bubbles: true });
                input.dispatchEvent(event);
            }
        }
    }
    
    function initEnhancedInputs() {
        // ========================================
        // WW MATRICULE AUTO-FORMAT
        // ========================================
        const wwInput = document.getElementById('matriculeWW');
        const wwBadge = document.getElementById('wwBadge');
        
        if (wwInput && !wwInput.hasAttribute('data-enhanced')) {
            wwInput.setAttribute('data-enhanced', 'true');
            
            let wwDebounce = null;
            
            wwInput.addEventListener('input', function(e) {
                let val = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
                
                // Auto-add WW- prefix
                if (val.length >= 2 && val.substring(0, 2) === 'WW') {
                    val = 'WW-' + val.substring(2, 8);
                } else if (val.length > 0 && /^[0-9]/.test(val)) {
                    // If starts with number, assume WW prefix intended
                    val = 'WW-' + val.substring(0, 6);
                }
                
                this.value = val;
                
                // Update badge
                if (/^WW-[0-9]{1,6}$/.test(val)) {
                    wwBadge.className = 'matricule-badge valid';
                    wwBadge.innerHTML = '<i class="fas fa-check"></i> Valide';
                } else if (val.length > 0) {
                    wwBadge.className = 'matricule-badge invalid';
                    wwBadge.innerHTML = '<i class="fas fa-times"></i> Format WW-XXXXXX';
                } else {
                    wwBadge.className = 'matricule-badge';
                    wwBadge.textContent = 'WW-XXXXXX';
                }
                
                // Debounced search
                clearTimeout(wwDebounce);
                if (val.length >= 4) {
                    wwBadge.className = 'matricule-badge searching';
                    wwBadge.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Recherche...';
                    wwDebounce = setTimeout(() => {
                        @this.call('searchNewMatricule', val);
                    }, 400);
                }
            });
            
            // Search on blur
            wwInput.addEventListener('blur', function() {
                if (this.value.length >= 4) {
                    @this.call('searchNewMatricule', this.value);
                }
            });
        }
        
        // ========================================
        // OLD MATRICULE AUTO-FORMAT
        // ========================================
        const oldInput = document.getElementById('matriculeOld');
        const oldBadge = document.getElementById('oldBadge');
        
        if (oldInput && !oldInput.hasAttribute('data-enhanced')) {
            oldInput.setAttribute('data-enhanced', 'true');
            
            let oldDebounce = null;
            
            oldInput.addEventListener('input', function(e) {
                let val = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
                let formatted = '';
                
                // Format: XXXXX-X-XX (5 digits, 1 letter, 2 digits)
                if (val.length > 0) {
                    // First 5 digits
                    formatted = val.substring(0, Math.min(5, val.length));
                    
                    if (val.length > 5) {
                        // Letter part
                        const letter = val.substring(5, 6);
                        if (/[A-Z]/.test(letter)) {
                            formatted += '-' + letter;
                        }
                    }
                    
                    if (val.length > 6) {
                        // Last 2 digits
                        const digits = val.substring(6, 8);
                        if (/[0-9]/.test(digits)) {
                            formatted += '-' + digits;
                        }
                    }
                }
                
                this.value = formatted;
                
                // Update badge
                if (/^[0-9]{1,5}-[A-Z]-[0-9]{1,2}$/.test(formatted)) {
                    oldBadge.className = 'matricule-badge valid';
                    oldBadge.innerHTML = '<i class="fas fa-check"></i> Valide';
                } else if (formatted.length > 0) {
                    oldBadge.className = 'matricule-badge invalid';
                    oldBadge.innerHTML = '<i class="fas fa-times"></i> Format XXXXX-X-XX';
                } else {
                    oldBadge.className = 'matricule-badge';
                    oldBadge.textContent = 'XXXXX-X-XX';
                }
                
                // Debounced search
                clearTimeout(oldDebounce);
                if (formatted.length >= 4) {
                    oldBadge.className = 'matricule-badge searching';
                    oldBadge.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Recherche...';
                    oldDebounce = setTimeout(() => {
                        @this.call('searchMatricule', formatted);
                    }, 400);
                }
            });
            
            // Search on blur
            oldInput.addEventListener('blur', function() {
                if (this.value.length >= 4) {
                    @this.call('searchMatricule', this.value);
                }
            });
        }
        
        // ========================================
        // CHASSIS NUMBER SEARCH
        // ========================================
        const chassisInput = document.getElementById('chassisNumber');
        
        if (chassisInput && !chassisInput.hasAttribute('data-enhanced')) {
            chassisInput.setAttribute('data-enhanced', 'true');
            
            let chassisDebounce = null;
            
            chassisInput.addEventListener('input', function(e) {
                this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
                
                clearTimeout(chassisDebounce);
                if (this.value.length >= 5) {
                    chassisDebounce = setTimeout(() => {
                        @this.call('searchChassis', this.value);
                    }, 500);
                }
            });
            
            // Search on blur
            chassisInput.addEventListener('blur', function() {
                if (this.value.length >= 5) {
                    @this.call('searchChassis', this.value);
                }
            });
        }
        
        // ========================================
        // CLIENT NAME SEARCH
        // ========================================
        const nameInput = document.getElementById('insuredName');
        
        if (nameInput && !nameInput.hasAttribute('data-enhanced')) {
            nameInput.setAttribute('data-enhanced', 'true');
            
            let nameDebounce = null;
            
            nameInput.addEventListener('input', function(e) {
                clearTimeout(nameDebounce);
                if (this.value.length >= 2) {
                    nameDebounce = setTimeout(() => {
                        @this.call('searchByName', this.value);
                    }, 500);
                }
            });
            
            // Search on blur
            nameInput.addEventListener('blur', function() {
                if (this.value.length >= 2) {
                    // Small delay to allow click on dropdown items
                    setTimeout(() => {
                        @this.call('searchByName', this.value);
                    }, 200);
                }
            });
        }
        
        // ========================================
        // VEHICLE API INTEGRATION
        // ========================================
        const apiToggle = document.getElementById('useCarQueryApi');
        
        if (apiToggle && !apiToggle.hasAttribute('data-enhanced')) {
            apiToggle.setAttribute('data-enhanced', 'true');
            
            apiToggle.addEventListener('change', function() {
                const useApi = this.checked;
                
                // Toggle containers
                document.getElementById('localBrandContainer').classList.toggle('d-none', useApi);
                document.getElementById('apiBrandContainer').classList.toggle('d-none', !useApi);
                document.getElementById('localModelContainer').classList.toggle('d-none', useApi);
                document.getElementById('apiModelContainer').classList.toggle('d-none', !useApi);
                document.getElementById('apiYearContainer').classList.toggle('d-none', !useApi);
                
                if (useApi) {
                    loadMakes();
                    loadYears();
                }
            });
        }
        
        // API Brand change handler
        const apiBrand = document.getElementById('apiBrand');
        if (apiBrand && !apiBrand.hasAttribute('data-enhanced')) {
            apiBrand.setAttribute('data-enhanced', 'true');
            
            apiBrand.addEventListener('change', function() {
                const makeId = this.value;
                const makeName = this.options[this.selectedIndex]?.textContent || '';
                const year = document.getElementById('apiYear')?.value;
                
                document.getElementById('apiBrandName').value = makeName;
                @this.set('api_brand_name', makeName);
                
                if (makeId) {
                    loadModels(makeId, makeName, year);
                }
            });
        }
        
        // API Model change handler
        const apiModel = document.getElementById('apiModel');
        if (apiModel && !apiModel.hasAttribute('data-enhanced')) {
            apiModel.setAttribute('data-enhanced', 'true');
            
            apiModel.addEventListener('change', function() {
                const modelName = this.value;
                document.getElementById('apiModelName').value = modelName;
                @this.set('api_model_name', modelName);
            });
        }
        
        // API Year change handler
        const apiYear = document.getElementById('apiYear');
        if (apiYear && !apiYear.hasAttribute('data-enhanced')) {
            apiYear.setAttribute('data-enhanced', 'true');
            
            apiYear.addEventListener('change', function() {
                const year = this.value;
                document.getElementById('apiYearValue').value = year;
                @this.set('api_year', year);
                
                // Reload models if brand selected
                const makeSelect = document.getElementById('apiBrand');
                if (makeSelect?.value) {
                    loadModels(makeSelect.value, makeSelect.options[makeSelect.selectedIndex]?.textContent, year);
                }
            });
        }
    }
    
    // Load years for API dropdown
    function loadYears() {
        const select = document.getElementById('apiYear');
        if (!select) return;
        
        select.innerHTML = '<option value="">Année (optionnel)</option>';
        const currentYear = new Date().getFullYear();
        for (let y = currentYear; y >= 1980; y--) {
            const option = document.createElement('option');
            option.value = y;
            option.textContent = y;
            select.appendChild(option);
        }
        
        if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
            jQuery('#apiYear').selectpicker('refresh');
        }
    }
    
    // Load makes from NHTSA API
    function loadMakes() {
        const select = document.getElementById('apiBrand');
        if (!select) return;
        
        select.innerHTML = '<option value="">Chargement...</option>';
        if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
            jQuery('#apiBrand').selectpicker('refresh');
        }
        
        fetch('https://vpic.nhtsa.dot.gov/api/vehicles/GetAllMakes?format=json')
            .then(response => response.json())
            .then(data => {
                select.innerHTML = '<option value="">Sélectionner une marque</option>';
                
                if (data.Results && data.Results.length > 0) {
                    // Sort with common makes first
                    const commonMakes = ['TOYOTA', 'HONDA', 'FORD', 'CHEVROLET', 'NISSAN', 'BMW', 
                        'MERCEDES-BENZ', 'AUDI', 'VOLKSWAGEN', 'HYUNDAI', 'KIA', 'MAZDA', 
                        'PEUGEOT', 'RENAULT', 'CITROEN', 'FIAT', 'DACIA', 'OPEL', 'SEAT', 'SKODA'];
                    
                    const sorted = data.Results.sort((a, b) => {
                        const aCommon = commonMakes.includes(a.Make_Name.toUpperCase());
                        const bCommon = commonMakes.includes(b.Make_Name.toUpperCase());
                        if (aCommon && !bCommon) return -1;
                        if (!aCommon && bCommon) return 1;
                        return a.Make_Name.localeCompare(b.Make_Name);
                    });
                    
                    sorted.forEach(make => {
                        const option = document.createElement('option');
                        option.value = make.Make_ID;
                        option.textContent = make.Make_Name;
                        select.appendChild(option);
                    });
                }
                
                if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
                    jQuery('#apiBrand').selectpicker('refresh');
                }
            })
            .catch(error => {
                console.error('Error loading makes:', error);
                select.innerHTML = '<option value="">Erreur de chargement</option>';
            });
    }
    
    // Load models from NHTSA API
    function loadModels(makeId, makeName, year) {
        const select = document.getElementById('apiModel');
        if (!select) return;
        
        select.innerHTML = '<option value="">Chargement...</option>';
        if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
            jQuery('#apiModel').selectpicker('refresh');
        }
        
        let url = `https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMakeId/${makeId}?format=json`;
        if (year) {
            url = `https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMakeIdYear/makeId/${makeId}/modelyear/${year}?format=json`;
        }
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                select.innerHTML = '<option value="">Sélectionner un modèle</option>';
                
                if (data.Results && data.Results.length > 0) {
                    // Remove duplicates and sort
                    const unique = [...new Map(data.Results.map(m => [m.Model_Name, m])).values()];
                    unique.sort((a, b) => a.Model_Name.localeCompare(b.Model_Name));
                    
                    unique.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model.Model_Name;
                        option.textContent = model.Model_Name;
                        select.appendChild(option);
                    });
                }
                
                if (typeof jQuery !== 'undefined' && jQuery.fn.selectpicker) {
                    jQuery('#apiModel').selectpicker('refresh');
                }
            })
            .catch(error => {
                console.error('Error loading models:', error);
                select.innerHTML = '<option value="">Erreur de chargement</option>';
            });
    }
    </script>
</div>