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

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

@section('content')
<div class="max-w-6xl mx-auto px-6 py-16">
    <h1 class="text-3xl font-bold text-slate-900 mb-8">Réserver</h1>

    <div class="grid lg:grid-cols-[380px_1fr] gap-10 lg:gap-12 mb-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">Cliquez sur une date en vert : accès direct au service ou filtre des cartes à droite.</p>
            <button type="button" id="cal-clear-date" class="hidden mt-3 text-sm text-slate-600 underline hover:text-slate-900">Afficher tous les services</button>
        </div>

        {{-- Services --}}
        <div id="reservation-services-panel" class="scroll-mt-24">
            <p id="reservation-date-hint" class="hidden mb-4 p-3 rounded-xl bg-primary-50 border border-primary-100 text-sm text-primary-900"></p>
            <h2 class="text-xl font-semibold text-slate-800 mb-6">Services</h2>
            <div class="grid md:grid-cols-2 gap-6">
        @forelse(($services ?? []) as $service)
        @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
        <a href="{{ route('reservation.book', $service, false) }}"
           data-book-href="{{ route('reservation.book', $service, false) }}"
           data-service-id="{{ $service->id }}"
           class="reservation-service-card block bg-white rounded-2xl border border-slate-200 hover:border-primary-500 hover:shadow-lg transition overflow-hidden">
            @if($service->image_url)
            <div class="aspect-video bg-slate-100">
                <img src="{{ $service->image_url }}" alt="{{ $serviceName }}" class="w-full h-full object-cover">
            </div>
            @endif
            <div class="p-6">
                <h2 class="text-xl font-semibold text-slate-900">{{ $serviceName }}</h2>
                @if($serviceDesc)
                <p class="text-slate-600 mt-2">{{ Str::limit(strip_tags(html_entity_decode($serviceDesc, ENT_QUOTES | ENT_HTML5, 'UTF-8')), 100) }}</p>
                @endif
                <div class="mt-4 flex items-center gap-4">
                    <span class="text-sm text-slate-500">{{ $service->duration_minutes }} min</span>
                    @if($service->price)
                    <span class="font-bold text-primary-500">{{ number_format($service->price, 2, ',', ' ') }} €</span>
                    @endif
                </div>
            </div>
        </a>
        @empty
        <div class="col-span-full text-center py-16 text-slate-500">
            <p class="text-xl">Aucun service de réservation disponible pour le moment.</p>
        </div>
        @endforelse
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    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 calClearBtn = document.getElementById('cal-clear-date');
    const dateHint = document.getElementById('reservation-date-hint');
    {{-- Chemins relatifs : évite mixed content si APP_URL est en http et le site en https --}}
    {{-- json_encode ici : @json(rtrim(..., '/')) casse le parseur Blade (guillemet /) --}}
    const reservationBookBase = {!! json_encode(rtrim(route('reservation.index', [], false), '/')) !!};

    let availableDates = [];
    let servicesByDate = {};
    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 formatFr(dateStr) {
        const p = dateStr.split('-');
        if (p.length !== 3) return dateStr;
        const dt = new Date(parseInt(p[0],10), parseInt(p[1],10)-1, parseInt(p[2],10));
        return dt.toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
    }

    function resetServiceFilter() {
        selectedDate = null;
        document.querySelectorAll('a.reservation-service-card').forEach(a => {
            a.classList.remove('hidden', 'ring-2', 'ring-primary-400');
            const base = a.getAttribute('data-book-href');
            if (base) a.setAttribute('href', base);
        });
        if (dateHint) { dateHint.classList.add('hidden'); dateHint.textContent = ''; }
        if (calClearBtn) calClearBtn.classList.add('hidden');
        renderCalendar();
    }

    function applySelectedDate(dateStr) {
        const svcList = servicesByDate[dateStr] || [];
        if (svcList.length === 0) return;

        if (svcList.length === 1) {
            window.location.href = reservationBookBase + '/' + svcList[0].id + '?date=' + encodeURIComponent(dateStr) + '#reservation-agenda';
            return;
        }

        selectedDate = dateStr;
        const ids = new Set(svcList.map(s => String(s.id)));
        document.querySelectorAll('a.reservation-service-card').forEach(a => {
            const sid = a.getAttribute('data-service-id');
            const base = a.getAttribute('data-book-href');
            if (ids.has(String(sid))) {
                a.classList.remove('hidden');
                a.classList.add('ring-2', 'ring-primary-400');
                if (base) a.setAttribute('href', base + (base.indexOf('?') >= 0 ? '&' : '?') + 'date=' + encodeURIComponent(dateStr) + '#reservation-agenda');
            } else {
                a.classList.add('hidden');
                a.classList.remove('ring-2', 'ring-primary-400');
            }
        });
        if (dateHint) {
            dateHint.textContent = 'Pour le ' + formatFr(dateStr) + ', choisissez un service ci-dessous : le lien inclut la date pour afficher les créneaux.';
            dateHint.classList.remove('hidden');
        }
        if (calClearBtn) calClearBtn.classList.remove('hidden');
        renderCalendar();
        document.getElementById('reservation-services-panel')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    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-all', [], false)) + '?from=' + from + '&to=' + to)
            .then(r => r.json())
            .then(data => {
                availableDates = data.dates || [];
                servicesByDate = data.services_by_date || {};
                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.indexOf(dateStr) !== -1;
            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';
                html += '<span class="' + cls + '">' + d + '</span>';
            } else if (isAvailable) {
                cls += 'cursor-pointer font-medium ';
                if (isSelected) cls += 'bg-slate-800 text-white hover:bg-slate-700';
                else cls += 'bg-emerald-50 text-slate-800 hover:bg-emerald-100';
                html += '<button type="button" class="cal-day ' + cls + '" data-date="' + dateStr + '">' + d + '</button>';
            } else {
                cls += 'text-slate-400 cursor-default';
                html += '<span class="' + cls + '">' + d + '</span>';
            }
        }
        calDaysEl.innerHTML = html;

        calDaysEl.querySelectorAll('.cal-day').forEach(btn => {
            btn.addEventListener('click', function() {
                applySelectedDate(this.getAttribute('data-date'));
            });
        });
    }

    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();
    });
    if (calClearBtn) {
        calClearBtn.addEventListener('click', resetServiceFilter);
    }

    fetchAvailableDates().then(() => {
        renderCalendar();
    });
});
</script>
@endsection
