@extends('themes.classic.layouts.app')

@php
    $locale = $multilang_current ?? app()->getLocale();
    $defaultLocale = $multilang_default ?? 'fr';
    $serviceName = method_exists($service, 'getTranslatedName') ? $service->getTranslatedName($locale, $defaultLocale) : $service->name;
    $serviceDesc = method_exists($service, 'getTranslatedDescription') ? $service->getTranslatedDescription($locale, $defaultLocale) : $service->description;
@endphp

@section('title', 'Réserver '.$serviceName.' - '.($site_name ?? 'Mon Site'))

@section('content')
<div class="max-w-6xl mx-auto px-6 py-16">
    <nav class="mb-8">
        <a href="{{ route('reservation.index', [], false) }}" class="text-slate-500 hover:text-slate-900">← Réservation</a>
        <span class="text-slate-400 mx-2">/</span>
        <span class="text-slate-900 font-medium">{{ $serviceName }}</span>
    </nav>

    <div class="grid lg:grid-cols-[380px_1fr] gap-10 lg:gap-12">
        {{-- Calendrier --}}
        <div id="reservation-agenda" class="bg-white rounded-2xl border border-slate-200 p-6 h-fit scroll-mt-24">
            <h2 class="font-semibold text-slate-800 mb-4">Calendrier</h2>
            <div class="flex items-center justify-between mb-4">
                <button type="button" id="cal-prev" class="p-2 rounded-lg hover:bg-slate-100 text-slate-600 transition">&larr;</button>
                <span id="cal-month" class="font-medium text-slate-800">—</span>
                <button type="button" id="cal-next" class="p-2 rounded-lg hover:bg-slate-100 text-slate-600 transition">&rarr;</button>
            </div>
            <div id="cal-weekdays" class="grid grid-cols-7 gap-1 text-center text-xs text-slate-500 mb-2">
                <span>Lun</span><span>Mar</span><span>Mer</span><span>Jeu</span><span>Ven</span><span>Sam</span><span>Dim</span>
            </div>
            <div id="cal-days" class="grid grid-cols-7 gap-1 text-sm">
                {{-- Rempli par JS --}}
            </div>
            <p class="text-slate-500 text-xs mt-3">Dates en vert = disponibles. La première date disponible est sélectionnée automatiquement avec ses créneaux.</p>
        </div>

        {{-- Formulaire --}}
        <div>
            @if($service->image_url)
            <div class="aspect-video rounded-2xl overflow-hidden bg-slate-100 mb-6 max-w-2xl">
                <img src="{{ $service->image_url }}" alt="{{ $serviceName }}" class="w-full h-full object-cover">
            </div>
            @endif
            <h1 class="text-3xl font-bold text-slate-900 mb-2">Réserver : {{ $serviceName }}</h1>
            <p class="text-slate-600 mb-2">{{ $service->duration_minutes }} min @if($service->price) • {{ number_format($service->price, 2, ',', ' ') }} € @endif</p>
            @if($serviceDesc)
            <div class="prose prose-slate prose-sm max-w-none mb-6 text-slate-600">{!! \App\Support\SafeHtml::richText($serviceDesc) !!}</div>
            @endif

            @if(session('success'))
            <div class="mb-6 p-4 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl">{{ session('success') }}</div>
            @endif
            @if($errors->any())
            <div class="mb-6 p-4 bg-red-50 border border-red-200 text-red-800 rounded-xl">
                <ul class="list-disc list-inside">
                    @foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach
                </ul>
            </div>
            @endif

            <form method="POST" action="{{ route('reservation.store', [], false) }}" id="reservation-form">
                @csrf
                <input type="hidden" name="reservation_slot_id" id="reservation_slot_id" value="">
                <input type="hidden" id="slot-date" name="slot_date" value="">

                <div class="mb-6" id="slots-section" style="display:none;">
                    <label class="block text-sm font-medium text-slate-700 mb-1">Créneau *</label>
                    <div id="slots-container" class="flex flex-wrap gap-2">
                        <span class="text-slate-500 text-sm">Sélectionnez une date dans le calendrier.</span>
                    </div>
                </div>

                <div class="space-y-4 mb-8">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Nom complet *</label>
                        <input type="text" name="customer_name" value="{{ old('customer_name') }}" required class="w-full px-4 py-2 border border-slate-200 rounded-xl focus:ring-2 focus:ring-slate-400">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Email *</label>
                        <input type="email" name="customer_email" value="{{ old('customer_email') }}" required class="w-full px-4 py-2 border border-slate-200 rounded-xl focus:ring-2 focus:ring-slate-400">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Téléphone</label>
                        <input type="tel" name="customer_phone" value="{{ old('customer_phone') }}" class="w-full px-4 py-2 border border-slate-200 rounded-xl focus:ring-2 focus:ring-slate-400">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Notes</label>
                        <textarea name="notes" rows="2" class="w-full px-4 py-2 border border-slate-200 rounded-xl focus:ring-2 focus:ring-slate-400">{{ old('notes') }}</textarea>
                    </div>
                </div>

                @include('partials.captcha-widget', ['context' => 'reservation'])

                <button type="submit" id="submit-btn" disabled class="w-full py-4 bg-slate-700 text-white rounded-xl font-semibold hover:bg-slate-800 transition disabled:opacity-50 disabled:cursor-not-allowed">
                    Confirmer la réservation
                </button>
            </form>

            <p class="mt-6"><a href="{{ route('reservation.index', [], false) }}" class="text-slate-500 hover:text-slate-900">← Retour</a></p>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const dateInput = document.getElementById('slot-date');
    const slotsSection = document.getElementById('slots-section');
    const slotsContainer = document.getElementById('slots-container');
    const slotIdInput = document.getElementById('reservation_slot_id');
    const submitBtn = document.getElementById('submit-btn');
    const calMonthEl = document.getElementById('cal-month');
    const calDaysEl = document.getElementById('cal-days');
    const calPrevBtn = document.getElementById('cal-prev');
    const calNextBtn = document.getElementById('cal-next');

    const urlParams = new URLSearchParams(window.location.search);
    const prefillDate = urlParams.get('date');

    let availableDates = [];
    let currentCalDate = new Date();
    currentCalDate.setDate(1);
    let selectedDate = null;

    const toYmd = (d) => d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
    const todayYmd = () => toYmd(new Date());

    function fetchAvailableDates() {
        const from = todayYmd();
        const toDate = new Date();
        toDate.setDate(toDate.getDate() + 90);
        const to = toYmd(toDate);
        return fetch(@json(route('reservation.available-dates', $service, false)) + '?from=' + from + '&to=' + to)
            .then(r => r.json())
            .then(data => { availableDates = data.dates || []; return availableDates; });
    }

    function renderCalendar() {
        const y = currentCalDate.getFullYear();
        const m = currentCalDate.getMonth();
        calMonthEl.textContent = new Date(y, m).toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' });

        const first = new Date(y, m, 1);
        const last = new Date(y, m + 1, 0);
        const startPad = (first.getDay() + 6) % 7;
        const daysInMonth = last.getDate();

        let html = '';
        for (let i = 0; i < startPad; i++) html += '<span class="aspect-square p-1"></span>';
        for (let d = 1; d <= daysInMonth; d++) {
            const dateStr = y + '-' + String(m+1).padStart(2,'0') + '-' + String(d).padStart(2,'0');
            const isPast = dateStr < todayYmd();
            const isAvailable = availableDates.includes(dateStr);
            const isSelected = selectedDate === dateStr;
            let cls = 'aspect-square p-1 flex items-center justify-center rounded-lg text-center ';
            if (isPast) cls += 'text-slate-300 cursor-default';
            else if (isAvailable) {
                cls += 'cursor-pointer hover:bg-emerald-100 text-slate-800 ';
                if (isSelected) cls += 'bg-slate-700 text-white hover:bg-slate-700';
                else cls += 'bg-emerald-50 font-medium';
            } else cls += 'text-slate-400 cursor-default';

            if (isPast || !isAvailable) {
                html += '<span class="' + cls + '">' + d + '</span>';
            } else {
                html += '<button type="button" class="cal-day ' + cls + '" data-date="' + dateStr + '">' + d + '</button>';
            }
        }
        calDaysEl.innerHTML = html;

        calDaysEl.querySelectorAll('.cal-day').forEach(btn => {
            btn.addEventListener('click', function() {
                selectedDate = this.dataset.date;
                dateInput.value = selectedDate;
                renderCalendar();
                loadSlots(selectedDate);
            });
        });
    }

    calPrevBtn.addEventListener('click', function() {
        currentCalDate = new Date(currentCalDate.getFullYear(), currentCalDate.getMonth() - 1, 1);
        renderCalendar();
    });
    calNextBtn.addEventListener('click', function() {
        currentCalDate = new Date(currentCalDate.getFullYear(), currentCalDate.getMonth() + 1, 1);
        renderCalendar();
    });

    fetchAvailableDates().then(() => {
        availableDates = (availableDates || []).slice().sort();
        let pick = null;
        if (prefillDate && availableDates.indexOf(prefillDate) !== -1) {
            pick = prefillDate;
        } else {
            pick = availableDates.find(d => d >= todayYmd()) || null;
        }
        if (pick) {
            selectedDate = pick;
            dateInput.value = pick;
            const p = pick.split('-');
            if (p.length === 3) {
                currentCalDate = new Date(parseInt(p[0], 10), parseInt(p[1], 10) - 1, 1);
            }
            renderCalendar();
            loadSlots(pick);
        } else {
            renderCalendar();
        }
    });

    function loadSlots(date) {
        if (!date) {
            slotsSection.style.display = 'none';
            slotIdInput.value = '';
            submitBtn.disabled = true;
            return;
        }
        slotsSection.style.display = 'block';
        slotsContainer.innerHTML = '<span class="text-slate-500 text-sm">Chargement...</span>';
        slotIdInput.value = '';
        submitBtn.disabled = true;

        fetch(@json(route('reservation.slots', $service, false)) + '?date=' + encodeURIComponent(date))
            .then(r => r.json())
            .then(data => {
                if (data.slots && data.slots.length > 0) {
                    slotsContainer.innerHTML = data.slots.map(s => {
                        const start = s.start.length >= 5 ? s.start.substring(0, 5) : s.start;
                        const end = s.end.length >= 5 ? s.end.substring(0, 5) : s.end;
                        const places = s.remaining !== null ? ' (' + s.remaining + ' pl.)' : '';
                        return '<button type="button" class="slot-btn px-4 py-2 rounded-xl border border-slate-200 hover:border-slate-400 hover:bg-slate-100 transition text-slate-800" data-id="' + s.id + '">' + start + ' - ' + end + places + '</button>';
                    }).join('');
                    slotsContainer.querySelectorAll('.slot-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            slotsContainer.querySelectorAll('.slot-btn').forEach(b => b.classList.remove('border-slate-600', 'bg-slate-700', 'text-white'));
                            this.classList.add('border-slate-600', 'bg-slate-700', 'text-white');
                            slotIdInput.value = this.dataset.id;
                            submitBtn.disabled = false;
                        });
                    });
                } else {
                    slotsContainer.innerHTML = '<span class="text-slate-500 text-sm">Aucun créneau disponible pour cette date.</span>';
                }
            })
            .catch(() => {
                slotsContainer.innerHTML = '<span class="text-red-500 text-sm">Erreur lors du chargement.</span>';
            });
    }
});
</script>
@endsection
