@extends('layouts.provider')

@section('title', $appointment ? 'Modifier rendez-vous' : 'Nouveau rendez-vous')

@section('content')
<div class="px-4 py-6 sm:px-6 lg:px-8 pb-32">
    <div class="bg-white shadow-sm sm:rounded-lg">
        <div class="p-4 sm:p-6">
            <div id="appointment-stepper" x-data="appointmentStepper()" x-init="init()">
                <!-- Progress bar -->
                <div class="mb-6">
                    <div class="flex justify-between mb-2">
                        <span class="text-sm font-medium" :class="step >= 1 ? 'text-blue-600' : 'text-gray-500'">Service</span>
                        <span class="text-sm font-medium" :class="step >= 2 ? 'text-blue-600' : 'text-gray-500'">Horaire & Prix</span>
                        <span class="text-sm font-medium" :class="step >= 3 ? 'text-blue-600' : 'text-gray-500'">Client</span>
                        <span class="text-sm font-medium" :class="step >= 4 ? 'text-blue-600' : 'text-gray-500'">Confirmation</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-blue-600 h-2 rounded-full transition-all" :style="`width: ${(step / 4) * 100}%`"></div>
                    </div>
                </div>

                <!-- Step 1: Service -->
                <div x-show="step === 1">
                    <h2 class="text-xl font-bold mb-4">{{ $appointment ? 'Modifier le' : 'Choisir un' }} service</h2>
                    
                    <div class="flex gap-2 mb-4 overflow-x-auto">
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Date:</span> <span class="font-medium" x-text="form.date"></span>
                        </div>
                        <div x-show="form.service_id" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Service:</span> <span class="font-medium" x-text="getServiceName()"></span>
                        </div>
                        <div x-show="form.start_time" @click="form.service_id && (step = 2)" :class="form.service_id ? 'cursor-pointer hover:bg-gray-200' : 'cursor-not-allowed opacity-60'" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Horaire:</span> <span class="font-medium" x-text="form.start_time + ' → ' + (form.end_time || 'XX:XX')"></span>
                            <svg x-show="form.service_id" class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div x-show="form.price" @click="form.service_id && (step = 2)" :class="form.service_id ? 'cursor-pointer hover:bg-gray-200' : 'cursor-not-allowed opacity-60'" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Prix:</span> <span class="font-medium" x-text="formatPrice(form.price) + ' TND'"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div x-show="form.client_id" @click="step = 3" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Client:</span> <span class="font-medium" x-text="getClientName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Service *</label>
                            <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                @foreach($services as $service)
                                <div @click="selectService({{ $service->id }}, {{ $service->duration_minutes }}, {{ $service->base_price }})" 
                                     :class="form.service_id == {{ $service->id }} ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-blue-300'"
                                     class="border-2 rounded-lg p-3 cursor-pointer transition-all relative overflow-visible">
                                    <div class="flex items-start gap-2 mb-2">
                                        @if($service->color)
                                        <div class="w-3 h-3 rounded-full flex-shrink-0 mt-1" style="background-color: {{ $service->color }}"></div>
                                        @endif
                                        <div class="font-semibold text-sm text-gray-900 leading-tight">{{ $service->name }}</div>
                                    </div>
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <div class="text-xs text-gray-600">{{ $service->duration_minutes }}min</div>
                                            <div class="text-sm font-semibold text-gray-900 mt-1">{{ $service->base_price }} {{ $service->currency }}</div>
                                        </div>
                                        <div x-show="form.service_id == {{ $service->id }}" class="text-blue-600 ml-2 -mt-2">
                                            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-3 mt-6">
                        <a href="{{ route('provider.appointments.calendar') }}" class="px-4 py-2 bg-gray-300 rounded-lg">Annuler</a>
                        <button @click="nextStep()" :disabled="!form.service_id" :class="form.service_id ? 'bg-blue-600 text-white' : 'bg-gray-300 text-gray-500'" class="flex-1 py-2 rounded-lg font-medium">Horaire & Prix</button>
                    </div>
                </div>

                <!-- Step 2: Horaire & Prix -->
                <div x-show="step === 2">
                    <h2 class="text-xl font-bold mb-4">{{ $appointment ? 'Modifier l\'horaire & Prix' : 'Horaire & Prix' }}</h2>
                    
                    <div x-show="form.service_id" class="flex gap-2 mb-4 overflow-x-auto">
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Date:</span> <span class="font-medium" x-text="form.date"></span>
                        </div>
                        <div @click="step = 1" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Service:</span> <span class="font-medium" x-text="getServiceName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Horaire:</span> <span class="font-medium" x-text="form.start_time + ' → ' + form.end_time"></span>
                        </div>
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Prix:</span> <span class="font-medium" x-text="formatPrice(form.price) + ' TND'"></span>
                        </div>
                        <div x-show="form.client_id" @click="step = 3" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Client:</span> <span class="font-medium" x-text="getClientName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                    </div>

                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Horaire</label>
                            
                            <div class="relative pb-12">
                                <!-- Marqueurs d'heures -->
                                <div class="flex justify-between text-xs text-gray-500 mb-2">
                                    <span>6h</span>
                                    <span>9h</span>
                                    <span>12h</span>
                                    <span>15h</span>
                                    <span>18h</span>
                                    <span>21h</span>
                                </div>
                                
                                <!-- Barre de fond -->
                                <div class="relative h-2 bg-gray-300 rounded-full" x-ref="timeBar">
                                    <!-- Zone sélectionnée -->
                                    <div class="absolute h-full bg-blue-500 rounded-full" 
                                         :style="`left: ${((timeToMinutes(form.start_time) - 360) / 900) * 100}%; width: ${((timeToMinutes(form.end_time) - timeToMinutes(form.start_time)) / 900) * 100}%`"></div>
                                    
                                    <!-- Curseur Début -->
                                    <div class="absolute top-1/2 -translate-y-1/2" 
                                         :style="`left: ${((timeToMinutes(form.start_time) - 360) / 900) * 100}%`">
                                        <div class="relative" @mousedown="startDrag('start', $event)" @touchstart="startDrag('start', $event)">
                                            <div class="w-10 h-10 -ml-5 -mt-4 flex items-center justify-center cursor-pointer touch-manipulation">
                                                <div class="w-5 h-5 bg-blue-600 rounded-full shadow-lg border-2 border-white" style="margin-top: 14px;"></div>
                                            </div>
                                            <div class="absolute top-6 left-1/2 -translate-x-1/2 bg-blue-600 text-white text-xs font-bold px-2 py-1 rounded flex flex-col items-center leading-tight cursor-pointer" style="margin-top: 13px; margin-left: -9px;">
                                                <span x-text="form.start_time.split(':')[0]"></span>
                                                <span class="text-[8px]">· ·</span>
                                                <span x-text="form.start_time.split(':')[1]"></span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Curseur Fin -->
                                    <div class="absolute top-1/2 -translate-y-1/2" 
                                         :style="`left: ${((timeToMinutes(form.end_time) - 360) / 900) * 100}%`">
                                        <div class="relative" @mousedown="startDrag('end', $event)" @touchstart="startDrag('end', $event)">
                                            <div class="w-10 h-10 -ml-5 -mt-4 flex items-center justify-center cursor-pointer touch-manipulation">
                                                <div class="w-5 h-5 bg-purple-600 rounded-full shadow-lg border-2 border-white" style="margin-top: 14px;"></div>
                                            </div>
                                            <div class="absolute top-6 left-1/2 -translate-x-1/2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded flex flex-col items-center leading-tight cursor-pointer" style="margin-top: 13px; margin-left: -9px;">
                                                <span x-text="form.end_time.split(':')[0]"></span>
                                                <span class="text-[8px]">· ·</span>
                                                <span x-text="form.end_time.split(':')[1]"></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Alerte chevauchement -->
                        <div x-show="overlapError" class="bg-red-50 border-l-4 border-red-500 p-4 rounded-r-lg">
                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm font-medium text-red-800">
                                        ⚠️ Ce créneau horaire chevauche un rendez-vous existant.
                                    </p>
                                    <div x-show="overlapDetails" class="mt-2 text-sm text-red-700">
                                        <p><strong>Client:</strong> <span x-text="overlapDetails.client"></span></p>
                                        <p><strong>Service:</strong> <span x-text="overlapDetails.service"></span></p>
                                        <p><strong>Horaire:</strong> <span x-text="overlapDetails.time"></span></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Alerte ajustement prix -->
                        <div x-show="showPriceAlert" class="bg-yellow-50 border-l-4 border-yellow-500 p-4 rounded-r-lg">
                            <p class="text-sm text-yellow-800 mb-3">
                                ⚠️ La durée a changé (<span x-text="getActualDuration()"></span>min au lieu de <span x-text="getServiceDuration()"></span>min). 
                                Le prix suggéré est <strong x-text="suggestedPrice + ' TND'"></strong>.
                            </p>
                            <div class="flex gap-2">
                                <button @click="acceptPriceAdjustment()" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm">Accepter</button>
                                <button @click="rejectPriceAdjustment()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg text-sm">Garder le prix actuel</button>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium mb-2 text-center">Prix</label>
                            <div class="flex items-center justify-center gap-2">
                                <input type="text" inputmode="decimal" x-model="form.price" 
                                       class="text-5xl font-bold border-0 outline-none bg-transparent text-right" 
                                       style="-moz-appearance: textfield; width: auto; max-width: 200px;"
                                       placeholder="0">
                                <span class="text-5xl font-bold text-gray-700">TND</span>
                                <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/>
                                </svg>
                            </div>
                            <div class="text-center mt-2 text-sm text-gray-600">
                                <span>Durée: </span>
                                <span class="font-semibold" x-text="formatDuration(getActualDuration())"></span>
                            </div>
                        </div>
                        <style>
                            input[type="number"]::-webkit-inner-spin-button,
                            input[type="number"]::-webkit-outer-spin-button {
                                -webkit-appearance: none;
                                margin: 0;
                            }
                        </style>
                    </div>

                    <div class="flex gap-3 mt-6">
                        <button @click="prevStep()" class="px-4 py-2 bg-gray-300 rounded-lg">Retour</button>
                        <button @click="checkOverlapAndNext()" :disabled="!canGoToStep3() || showPriceAlert" :class="canGoToStep3() && !showPriceAlert ? 'bg-blue-600 text-white' : 'bg-gray-300 text-gray-500'" class="flex-1 py-2 rounded-lg font-medium">Suivant</button>
                    </div>
                </div>

                <!-- Step 3: Client -->
                <div x-show="step === 3">
                    <h2 class="text-xl font-bold mb-4">{{ $appointment ? 'Modifier le client' : 'Client' }}</h2>
                    
                    <div x-show="form.service_id" class="flex gap-2 mb-4 overflow-x-auto">
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Date:</span> <span class="font-medium" x-text="form.date"></span>
                        </div>
                        <div @click="step = 1" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Service:</span> <span class="font-medium" x-text="getServiceName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div @click="step = 2" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Horaire:</span> <span class="font-medium" x-text="form.start_time + ' → ' + form.end_time"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div @click="step = 2" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Prix:</span> <span class="font-medium" x-text="formatPrice(form.price) + ' TND'"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div x-show="form.client_id" @click="step = 3" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Client:</span> <span class="font-medium" x-text="getClientName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                    </div>

                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Rechercher un client *</label>
                            <input type="text" x-model="clientSearch" @input="filterClients()" placeholder="Nom, téléphone, email..." class="w-full px-4 py-2 border rounded-lg mb-2">
                            
                            <div class="max-h-48 overflow-y-auto border rounded-lg">
                                <template x-for="client in filteredClients" :key="client.id">
                                    <div @click="selectClient(client)" :class="form.client_id == client.id ? 'bg-blue-100 border-2 border-blue-500' : 'hover:bg-gray-50 border-b'" class="p-3 cursor-pointer">
                                        <p class="font-medium" x-text="(client.first_name || '') + ' ' + (client.last_name || '')"></p>
                                        <p class="text-sm text-gray-600" x-text="client.phone || ''"></p>
                                    </div>
                                </template>
                            </div>
                        </div>

                        <button @click="showNewClientForm = !showNewClientForm" class="text-blue-600 text-sm">+ Nouveau client</button>

                        <div x-show="showNewClientForm" class="border p-4 rounded-lg space-y-3">
                            <input type="text" x-model="newClient.first_name" placeholder="Prénom *" class="w-full px-4 py-2 border rounded-lg">
                            <input type="text" x-model="newClient.last_name" placeholder="Nom" class="w-full px-4 py-2 border rounded-lg">
                            <input type="tel" x-model="newClient.phone" placeholder="Téléphone *" class="w-full px-4 py-2 border rounded-lg">
                            <input type="email" x-model="newClient.email" placeholder="Email" class="w-full px-4 py-2 border rounded-lg">
                            <button @click="createClient()" class="w-full bg-green-600 text-white py-2 rounded-lg">Créer et sélectionner</button>
                        </div>
                    </div>

                    <div class="flex gap-3 mt-6">
                        <button @click="prevStep()" class="px-4 py-2 bg-gray-300 rounded-lg">Retour</button>
                        <button @click="nextStep()" :disabled="!form.client_id" :class="form.client_id ? 'bg-blue-600 text-white' : 'bg-gray-300 text-gray-500'" class="flex-1 py-2 rounded-lg font-medium">Suivant</button>
                    </div>
                </div>

                <!-- Step 4: Confirmation -->
                <div x-show="step === 4">
                    <h2 class="text-xl font-bold mb-4">Confirmation</h2>
                    
                    <div class="flex gap-2 mb-4 overflow-x-auto">
                        <div class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap">
                            <span class="text-gray-500">Date:</span> <span class="font-medium" x-text="form.date"></span>
                        </div>
                        <div @click="step = 1" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Service:</span> <span class="font-medium" x-text="getServiceName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div @click="step = 2" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Horaire:</span> <span class="font-medium" x-text="form.start_time + ' → ' + form.end_time"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div @click="step = 2" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Prix:</span> <span class="font-medium" x-text="formatPrice(form.price) + ' TND'"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                        <div @click="step = 3" class="bg-gray-50 px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors flex items-center gap-1">
                            <span class="text-gray-500">Client:</span> <span class="font-medium" x-text="getClientName()"></span>
                            <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </div>
                    </div>

                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Statut</label>
                            <div class="grid grid-cols-3 gap-3">
                                <div @click="!isPastAppointment() && (form.status = 'scheduled')" 
                                     :class="form.status === 'scheduled' ? 'border-blue-500 bg-blue-50' : isPastAppointment() ? 'border-gray-200 bg-gray-100 opacity-50 cursor-not-allowed' : 'border-gray-300 hover:border-blue-300 cursor-pointer'"
                                     class="border-2 rounded-lg p-3 text-center transition-all">
                                    <div class="text-2xl mb-1">📅</div>
                                    <div class="text-sm font-medium">Programmé</div>
                                </div>
                                <div @click="form.status = 'complete'" 
                                     :class="form.status === 'complete' ? 'border-green-500 bg-green-50' : 'border-gray-300 hover:border-green-300'"
                                     class="border-2 rounded-lg p-3 cursor-pointer text-center transition-all">
                                    <div class="text-2xl mb-1">✅</div>
                                    <div class="text-sm font-medium">Terminé</div>
                                </div>
                                <div @click="form.status = 'cancelled'" 
                                     :class="form.status === 'cancelled' ? 'border-red-500 bg-red-50' : 'border-gray-300 hover:border-red-300'"
                                     class="border-2 rounded-lg p-3 cursor-pointer text-center transition-all">
                                    <div class="text-2xl mb-1">❌</div>
                                    <div class="text-sm font-medium">Annulé</div>
                                </div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium mb-2">Notes</label>
                            <textarea x-model="form.notes" rows="3" class="w-full px-4 py-2 border rounded-lg" placeholder="Notes optionnelles sur ce rendez-vous..."></textarea>
                        </div>
                    </div>

                    <div class="flex gap-3 mt-6">
                        <button @click="prevStep()" class="px-4 py-2 bg-gray-300 rounded-lg">Retour</button>
                        <button @click="submitAppointment()" :disabled="loading" class="flex-1 py-2 bg-green-600 text-white rounded-lg font-medium">
                            <span x-show="!loading">{{ $appointment ? 'Modifier' : 'Enregistrer' }}</span>
                            <span x-show="loading">{{ $appointment ? 'Modification...' : 'Enregistrement...' }}</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function appointmentStepper() {
    return {
        step: 1,
        loading: false,
        showNewClientForm: false,
        showPriceAlert: false,
        suggestedPrice: 0,
        overlapError: false,
        overlapDetails: null,
        clientSearch: '',
        appointmentId: {{ $appointment->id ?? 'null' }},
        form: {
            date: '{{ $defaultDate }}',
            service_id: '{{ $appointment->service_id ?? "" }}',
            start_time: '{{ $appointment ? $appointment->start_time->format("H:i") : $defaultTime }}',
            end_time: '{{ $appointment ? $appointment->end_time->format("H:i") : "" }}',
            price: '{{ $appointment->price_at_booking ?? "" }}',
            client_id: '{{ $appointment->client_id ?? "" }}',
            notes: '{{ $appointment->notes ?? "" }}',
            status: '{{ $appointment->status ?? "scheduled" }}'
        },
        newClient: {
            first_name: '',
            last_name: '',
            phone: '',
            email: ''
        },
        services: @json($services),
        serviceDuration: {{ $appointment->service->duration_minutes ?? 0 }},
        serviceBasePrice: {{ $appointment->price_at_booking ?? 0 }},
        clients: @json($clients),
        filteredClients: [],
        dragging: null,
        
        init() {
            this.filteredClients = [...this.clients].reverse();
            if (this.form.price) {
                this.form.price = this.formatPrice(this.form.price);
            }
            document.addEventListener('mousemove', (e) => this.onDrag(e));
            document.addEventListener('mouseup', () => this.stopDrag());
            document.addEventListener('touchmove', (e) => this.onDrag(e));
            document.addEventListener('touchend', () => this.stopDrag());
        },
        
        startDrag(type, event) {
            this.dragging = type;
            event.preventDefault();
        },
        
        stopDrag() {
            this.dragging = null;
        },
        
        onDrag(event) {
            if (!this.dragging) return;
            
            const bar = this.$refs.timeBar;
            const rect = bar.getBoundingClientRect();
            const clientX = event.touches ? event.touches[0].clientX : event.clientX;
            const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
            const percent = x / rect.width;
            const minutes = Math.round((360 + percent * 900) / 15) * 15;
            
            if (this.dragging === 'start') {
                this.form.start_time = this.minutesToTime(Math.min(minutes, this.timeToMinutes(this.form.end_time) - 15));
            } else {
                this.form.end_time = this.minutesToTime(Math.max(minutes, this.timeToMinutes(this.form.start_time) + 15));
            }
            
            this.adjustPrice();
        },
        
        selectService(serviceId, duration, price) {
            this.form.service_id = serviceId;
            this.form.price = this.formatPrice(price);
            this.serviceDuration = duration;
            this.serviceBasePrice = price;
            this.calculateEndTime();
            this.showPriceAlert = false;
            this.overlapError = false;
        },
        
        timeToMinutes(time) {
            if (!time) return 360;
            const [h, m] = time.split(':');
            return parseInt(h) * 60 + parseInt(m);
        },
        
        minutesToTime(minutes) {
            const h = Math.floor(minutes / 60);
            const m = minutes % 60;
            return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
        },
        
        onStartTimeChange() {
            this.calculateEndTime();
            this.adjustPrice();
        },
        
        calculateEndTime() {
            if (!this.form.start_time || !this.serviceDuration) return;
            
            const [hours, minutes] = this.form.start_time.split(':');
            const start = new Date();
            start.setHours(parseInt(hours), parseInt(minutes), 0);
            start.setMinutes(start.getMinutes() + this.serviceDuration);
            
            this.form.end_time = start.toTimeString().slice(0, 5);
        },
        
        adjustPrice() {
            if (!this.form.start_time || !this.form.end_time || !this.form.service_id) return;
            
            const service = this.services.find(s => s.id == this.form.service_id);
            if (!service) return;
            
            const basePrice = parseFloat(service.base_price) || 0;
            const baseDuration = parseInt(service.duration_minutes) || 0;
            
            this.serviceDuration = baseDuration;
            this.serviceBasePrice = basePrice;
            
            const actualDuration = this.getActualDuration();
            
            if (actualDuration > 0 && baseDuration > 0) {
                if (actualDuration !== baseDuration) {
                    const calculated = (basePrice / baseDuration) * actualDuration;
                    this.suggestedPrice = this.formatPrice(calculated);
                    this.showPriceAlert = true;
                } else {
                    this.form.price = this.formatPrice(basePrice);
                    this.showPriceAlert = false;
                }
            }
        },
        
        acceptPriceAdjustment() {
            this.form.price = this.formatPrice(this.suggestedPrice);
            this.showPriceAlert = false;
        },
        
        rejectPriceAdjustment() {
            this.showPriceAlert = false;
        },
        
        getActualDuration() {
            if (!this.form.start_time || !this.form.end_time) return 0;
            const [startH, startM] = this.form.start_time.split(':');
            const [endH, endM] = this.form.end_time.split(':');
            const startMinutes = parseInt(startH) * 60 + parseInt(startM);
            const endMinutes = parseInt(endH) * 60 + parseInt(endM);
            return endMinutes - startMinutes;
        },
        
        formatDuration(minutes) {
            if (!minutes || minutes <= 0) return '0 min';
            const hours = Math.floor(minutes / 60);
            const mins = minutes % 60;
            if (hours > 0 && mins > 0) {
                return `${hours}h ${mins} min`;
            } else if (hours > 0) {
                return `${hours}h`;
            } else {
                return `${mins} min`;
            }
        },
        
        formatPrice(price) {
            if (!price) return '0';
            const num = parseFloat(price);
            return num % 1 === 0 ? num.toString() : num.toFixed(2);
        },
        
        getServiceDuration() {
            return this.serviceDuration || 0;
        },
        canGoToStep3() {
            return this.form.date && this.form.service_id && this.form.start_time && this.form.end_time && this.form.price && this.form.start_time !== this.form.end_time;
        },
        
        filterClients() {
            const search = this.clientSearch.toLowerCase();
            this.filteredClients = [...this.clients].filter(c => 
                (c.first_name || '').toLowerCase().includes(search) ||
                (c.last_name || '').toLowerCase().includes(search) ||
                (c.phone || '').includes(search)
            ).reverse();
        },
        
        selectClient(client) {
            this.form.client_id = client.id;
        },
        
        async createClient() {
            if (!this.newClient.first_name || !this.newClient.phone) {
                alert('Veuillez remplir le prénom et le téléphone');
                return;
            }
            
            try {
                const response = await fetch('{{ route("provider.clients.store") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(this.newClient)
                });
                
                const data = await response.json();
                if (response.ok && data.success) {
                    this.clients.push(data.client);
                    this.filteredClients = [...this.clients].reverse();
                    this.form.client_id = data.client.id;
                    this.showNewClientForm = false;
                    this.newClient = { first_name: '', last_name: '', phone: '', email: '' };
                } else {
                    alert(data.message || 'Erreur lors de la création du client');
                }
            } catch (error) {
                console.error(error);
                alert('Erreur lors de la création du client');
            }
        },
        
        getServiceName() {
            const service = this.services.find(s => s.id == this.form.service_id);
            return service ? service.name : '';
        },
        
        getClientName() {
            const client = this.clients.find(c => c.id == this.form.client_id);
            return client ? `${client.first_name || ''} ${client.last_name || ''}`.trim() : '';
        },
        
        async checkOverlapAndNext() {
            if (!this.canGoToStep3()) return;
            
            this.overlapError = false;
            
            try {
                const response = await fetch('{{ route("provider.appointments.store") }}/check-overlap', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        date: this.form.date,
                        start_time: this.form.start_time,
                        end_time: this.form.end_time,
                        appointment_id: {{ $appointment->id ?? 'null' }}
                    })
                });
                
                const data = await response.json();
                if (data.overlap) {
                    this.overlapError = true;
                    this.overlapDetails = data.details;
                } else {
                    this.overlapError = false;
                    this.overlapDetails = null;
                    this.nextStep();
                }
            } catch (error) {
                console.error(error);
                this.nextStep();
            }
        },
        
        isPastAppointment() {
            const appointmentDateTime = new Date(`${this.form.date}T${this.form.start_time}`);
            return appointmentDateTime < new Date();
        },
        
        nextStep() {
            if (this.step < 4) {
                this.step++;
                if (this.step === 4 && this.isPastAppointment() && this.form.status === 'scheduled') {
                    this.form.status = 'complete';
                }
            }
        },
        
        prevStep() {
            if (this.step > 1) this.step--;
        },
        
        async submitAppointment() {
            this.loading = true;
            
            const isEdit = {{ $appointment ? 'true' : 'false' }};
            const url = isEdit ? '{{ $appointment ? route("provider.appointments.update", $appointment->uuid) : "" }}' : '{{ route("provider.appointments.store") }}';
            const method = isEdit ? 'PUT' : 'POST';
            
            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(this.form)
                });
                
                const data = await response.json();
                if (response.ok && data.success) {
                    const appointmentDate = this.form.date;
                    const appointmentUuid = data.appointment.uuid;
                    window.location.href = `{{ route("provider.appointments.calendar") }}?date=${appointmentDate}&highlight=${appointmentUuid}`;
                } else {
                    console.error('Erreur:', data);
                    alert(data.message || JSON.stringify(data.errors || 'Erreur lors de l\'enregistrement du rendez-vous'));
                }
            } catch (error) {
                console.error('Exception:', error);
                alert('Erreur lors de l\'enregistrement du rendez-vous: ' + error.message);
            } finally {
                this.loading = false;
            }
        }
    }
}
</script>
@endsection
