<?php
$leadId = isset($leadId) ? (int)$leadId : (int)(($lead['id'] ?? null) ?: 0);
$currentUserId = isset($currentUserId) ? (int)$currentUserId : (int)(session()->get('user_id') ?: 0);
$agents   = $agents ?? [];
$bookings = $bookings ?? [];
$existingBookings = $existingBookings ?? $bookings;
$schedules = $schedules ?? [];
$defaultGuestName = isset($defaultGuestName) ? (string)$defaultGuestName : (string)($lead['name'] ?? '');
$error = $error ?? '';

$statusColorsMap = [
    'gray'    => 'bg-slate-100 text-slate-700 border-slate-200',
    'blue'    => 'bg-blue-100 text-blue-700 border-blue-200',
    'green'   => 'bg-emerald-100 text-emerald-700 border-emerald-200',
    'yellow'  => 'bg-amber-100 text-amber-700 border-amber-200',
    'orange'  => 'bg-orange-100 text-orange-700 border-orange-200',
    'red'     => 'bg-red-100 text-red-700 border-red-200',
    'purple'  => 'bg-purple-100 text-purple-700 border-purple-200',
    'pink'    => 'bg-pink-100 text-pink-700 border-pink-200',
    'indigo'  => 'bg-indigo-100 text-indigo-700 border-indigo-200',
    'cyan'    => 'bg-cyan-100 text-cyan-700 border-cyan-200',
];
$colorKey = strtolower($lead['status_color'] ?? 'gray');
$statusBadgeClass = $statusColorsMap[$colorKey] ?? $statusColorsMap['gray'];
$bookEndpoint   = $bookEndpoint   ?? site_url('/agent/leads/book/' . $leadId);
$leadViewUrl    = $leadViewUrl    ?? site_url('/agent/leads/view/' . $leadId);
$slotsEndpoint  = $slotsEndpoint  ?? site_url('/agent/bookings/slots/');
$bookingsViewUrl = $bookingsViewUrl ?? site_url('/agent/bookings/view/');
?>

<div class="mb-5 flex items-center gap-3 flex-wrap">
    <a href="<?= esc($leadViewUrl) ?>" class="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white border border-slate-200 text-sm text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all shadow-sm">
        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
        </svg>
        Back to Lead
    </a>
    <span class="inline-flex items-center px-3 py-1.5 rounded-xl text-xs font-mono font-semibold bg-slate-100 text-slate-700 border border-slate-200">
        <?= esc($lead['lead_number']) ?>
    </span>
    <span class="inline-flex items-center px-3 py-1.5 rounded-xl text-xs font-semibold border <?= $statusBadgeClass ?>">
        <?= esc($lead['status_name'] ?? 'Unknown') ?>
    </span>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <form id="booking-form" method="post" action="<?= esc($bookEndpoint) ?>" class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
            <?= csrf_field() ?>
            <input type="hidden" name="date" id="booking_date_hidden" value="<?= esc(old('date', date('Y-m-d'))) ?>">
            <input type="hidden" name="starts_at" id="hf_starts_at" value="<?= esc(old('starts_at', '')) ?>">
            <input type="hidden" name="ends_at" id="hf_ends_at" value="<?= esc(old('ends_at', '')) ?>">
            <input type="hidden" name="timezone" id="hf_timezone" value="<?= esc(old('timezone', '')) ?>">
            <input type="hidden" name="duration_minutes" id="hf_duration" value="<?= esc(old('duration_minutes', '')) ?>">

            <div class="px-6 py-5 bg-gradient-to-r from-indigo-50/60 via-white to-blue-50/60 border-b border-slate-200/60">
                <div class="flex items-start gap-4 flex-wrap">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-indigo-500 to-blue-600 flex items-center justify-center text-white font-bold text-xl shadow-lg shadow-indigo-500/25">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                    </div>
                    <div class="flex-1 min-w-0">
                        <h2 class="text-xl font-bold text-slate-800 mb-1">Schedule Assessment</h2>
                        <p class="text-sm text-slate-500">Select a schedule, date, and available time slot to book an assessment with <strong class="text-slate-700"><?= esc($lead['name']) ?></strong>.</p>
                    </div>
                </div>
            </div>

            <div class="p-6 space-y-6">
                <?php if ($error !== ''): ?>
                    <div class="rounded-xl border-2 border-rose-200 bg-rose-50 px-4 py-3">
                        <p class="text-sm font-semibold text-rose-700"><?= esc($error) ?></p>
                    </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Schedule</label>
                        <select id="schedule_id" name="schedule_id" required
                            class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition">
                            <option value="">— Select a schedule —</option>
                            <?php foreach ($schedules as $sch):
                                $sid  = (int)($sch['id'] ?? 0);
                                $sname = (string)($sch['title'] ?? $sch['name'] ?? 'Untitled Schedule #' . $sid);
                            ?>
                                <option value="<?= $sid ?>" <?= old('schedule_id') == $sid ? 'selected' : '' ?>>
                                    <?= esc($sname) ?><?php if (!empty($sch['timezone'])): ?> · <?= esc($sch['timezone']) ?><?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Date</label>
                        <input type="date" id="booking_date" name="date_shown" required value="<?= esc(old('date', date('Y-m-d'))) ?>" min="<?= date('Y-m-d') ?>"
                            class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition">
                    </div>
                </div>

                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="text-xs font-semibold text-slate-500 uppercase tracking-wide">Available Time Slots</label>
                        <span id="slots-count" class="text-xs text-slate-400">Select a schedule and date to load slots</span>
                    </div>
                    <div id="slots-loading" class="hidden p-8 text-center">
                        <div class="inline-block w-8 h-8 border-2 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-3"></div>
                        <p class="text-sm text-slate-500">Loading available slots…</p>
                    </div>
                    <div id="slots-empty" class="hidden p-8 text-center rounded-xl bg-slate-50 border border-slate-200 border-dashed">
                        <div class="mx-auto w-12 h-12 rounded-xl bg-slate-100 flex items-center justify-center mb-3">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <p class="text-sm font-medium text-slate-600 mb-1">No available slots</p>
                        <p class="text-xs text-slate-400">Try a different date or schedule.</p>
                    </div>
                    <div id="slots-grid" class="grid grid-cols-3 gap-2.5 max-h-80 overflow-y-auto p-1">
                    </div>
                    <input type="hidden" id="slot_start" name="slot_start" value="<?= esc(old('slot_start', '')) ?>">
                    <?php if (session()->getFlashdata('slot_error')): ?>
                        <p class="mt-2 text-xs text-rose-600 font-medium"><?= esc(session()->getFlashdata('slot_error')) ?></p>
                    <?php endif; ?>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Guest Name</label>
                        <input type="text" name="guest_name" value="<?= esc(old('guest_name', $defaultGuestName)) ?>"
                            class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition"
                            placeholder="Full name">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Guest Email</label>
                        <input type="email" name="guest_email" value="<?= esc(old('guest_email', $lead['email'] ?? '')) ?>"
                            class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition"
                            placeholder="email@example.com">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Guest Phone</label>
                        <input type="tel" name="guest_phone" value="<?= esc(old('guest_phone', $lead['phone'] ?? '')) ?>"
                            class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition"
                            placeholder="+1 555 000 0000">
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Assigned Agent</label>
                    <select name="assigned_agent_id" required
                        class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition">
                        <?php foreach ($agents as $ag):
                            $aid = (int)($ag['id'] ?? 0);
                            $aname = (string)($ag['full_name'] ?? ($ag['name'] ?? ($ag['username'] ?? 'User #' . $aid)));
                            $arole = (string)($ag['role'] ?? 'agent');
                            $aemail = (string)($ag['email'] ?? '');
                            $selected = (int)old('assigned_agent_id', ($assignedAgentDefaultId ?? $currentUserId)) === $aid;
                        ?>
                            <option value="<?= $aid ?>" <?= $selected ? 'selected' : '' ?>>
                                <?= esc($aname) ?><?= $aemail !== '' ? ' (' . esc($aemail) . ')' : '' ?><?= $arole !== 'agent' ? ' [' . esc(strtoupper($arole)) . ']' : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">Notes (optional)</label>
                    <textarea name="notes" rows="4"
                        class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400 transition resize-none"
                        placeholder="Meeting details, agenda, special requirements…"><?= esc(old('notes', '')) ?></textarea>
                </div>

                <div id="booking-summary" class="hidden rounded-2xl border-2 border-indigo-200/60 bg-gradient-to-br from-indigo-50/80 to-blue-50/80 p-5">
                    <p class="text-[11px] font-semibold text-slate-500 uppercase tracking-wide mb-3">Booking Summary</p>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Date</p>
                            <p id="sum-date" class="text-sm font-bold text-slate-800">—</p>
                        </div>
                        <div>
                            <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Time</p>
                            <p id="sum-time" class="text-sm font-bold text-slate-800">—</p>
                        </div>
                        <div>
                            <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Duration</p>
                            <p id="sum-duration" class="text-sm font-bold text-slate-800">—</p>
                        </div>
                        <div>
                            <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Schedule</p>
                            <p id="sum-schedule" class="text-sm font-bold text-slate-800 truncate">—</p>
                        </div>
                    </div>
                </div>

                <div class="pt-2 flex items-center gap-3 flex-wrap">
                    <button type="submit" id="book-btn"
                        class="inline-flex items-center justify-center gap-2 px-6 py-3.5 bg-gradient-to-r from-indigo-600 to-blue-600 text-white text-sm font-bold rounded-xl shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30 hover:-translate-y-0.5 active:translate-y-0 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0">
                        <span id="book-spinner" class="hidden inline-block w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin"></span>
                        <svg xmlns="http://www.w3.org/2000/svg" id="book-icon" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                        </svg>
                        <span id="book-text">Confirm Booking</span>
                    </button>
                    <a href="<?= esc($leadViewUrl) ?>" class="inline-flex items-center gap-1.5 px-5 py-3.5 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 transition">
                        Cancel
                    </a>
                </div>
            </div>
        </form>
    </div>

    <div class="space-y-6">
        <div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
            <div class="px-5 py-4 bg-gradient-to-r from-slate-50 via-white to-slate-50 border-b border-slate-200/60">
                <p class="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-0.5">Lead Information</p>
                <h3 class="font-bold text-slate-800"><?= esc($lead['name']) ?></h3>
            </div>
            <div class="p-5 space-y-4">
                <?php if (!empty($lead['company_name'])): ?>
                    <div>
                        <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Company</p>
                        <p class="text-sm font-medium text-slate-700"><?= esc($lead['company_name']) ?></p>
                    </div>
                <?php endif; ?>
                <?php if (!empty($lead['email'])): ?>
                    <div>
                        <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Email</p>
                        <a href="mailto:<?= esc($lead['email']) ?>" class="text-sm font-medium text-indigo-600 hover:text-indigo-700 break-all"><?= esc($lead['email']) ?></a>
                    </div>
                <?php endif; ?>
                <?php if (!empty($lead['phone'])): ?>
                    <div>
                        <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Phone</p>
                        <a href="tel:<?= esc($lead['phone']) ?>" class="text-sm font-medium text-emerald-600 hover:text-emerald-700 font-mono"><?= esc($lead['phone']) ?></a>
                    </div>
                <?php endif; ?>
                <?php if (!empty($lead['license_number'])): ?>
                    <div>
                        <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">License #</p>
                        <p class="text-sm font-medium text-slate-700 font-mono"><?= esc($lead['license_number']) ?></p>
                    </div>
                <?php endif; ?>
                <?php if (!empty($lead['assigned_name'])): ?>
                    <div>
                        <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Assigned To</p>
                        <p class="text-sm font-medium text-slate-700"><?= esc($lead['assigned_name']) ?></p>
                    </div>
                <?php endif; ?>
                <div class="pt-2 border-t border-slate-100">
                    <a href="<?= esc($leadViewUrl) ?>" class="inline-flex items-center gap-1.5 text-xs font-semibold text-indigo-600 hover:text-indigo-700">
                        View full lead profile →
                    </a>
                </div>
            </div>
        </div>

        <?php if (!empty($existingBookings)): ?>
            <div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-200/60">
                    <p class="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-0.5">Existing Bookings</p>
                    <h3 class="font-bold text-slate-800"><?= count($existingBookings) ?> assessment(s)</h3>
                </div>
                <div class="p-4 space-y-2.5">
                    <?php foreach ($existingBookings as $eb):
                        $statusClass = match (strtolower($eb['status'] ?? 'booked')) {
                            'booked'      => 'bg-emerald-100 text-emerald-700 border-emerald-200',
                            'completed'   => 'bg-blue-100 text-blue-700 border-blue-200',
                            'cancelled'   => 'bg-rose-100 text-rose-700 border-rose-200',
                            'rescheduled' => 'bg-amber-100 text-amber-700 border-amber-200',
                            default       => 'bg-slate-100 text-slate-700 border-slate-200',
                        };
                    ?>
                        <a href="<?= esc($bookingsViewUrl . ((int)($eb['id'] ?? 0))) ?>" class="block rounded-xl border border-slate-200 hover:border-indigo-300 hover:bg-indigo-50/30 transition p-3">
                            <div class="flex items-center justify-between gap-2 mb-1.5">
                                <p class="text-sm font-bold text-slate-800">
                                    <?= !empty($eb['booking_date']) ? date('M j, Y', strtotime($eb['booking_date'])) : (
                                        !empty($eb['starts_at']) ? date('M j, Y', strtotime($eb['starts_at'])) : '—'
                                    ) ?>
                                </p>
                                <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-bold border <?= $statusClass ?>">
                                    <?= esc(ucfirst($eb['status'] ?? 'booked')) ?>
                                </span>
                            </div>
                            <p class="text-xs text-slate-600">
                                <?php
                                $st = !empty($eb['start_time']) ? $eb['start_time'] : (!empty($eb['starts_at']) ? date('H:i:s', strtotime($eb['starts_at'])) : '');
                                $et = !empty($eb['ends_at']) ? date('H:i:s', strtotime($eb['ends_at'])) : '';
                                echo ($st !== '' ? date('g:i A', strtotime($st)) : '—')
                                    . ' — '
                                    . ($et !== '' ? date('g:i A', strtotime($et)) : '—');
                                ?>
                            </p>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
(function(){
    var scheduleSelect = document.getElementById('schedule_id');
    var dateInput = document.getElementById('booking_date');
    var dateHidden = document.getElementById('booking_date_hidden');
    var slotsGrid = document.getElementById('slots-grid');
    var slotsLoading = document.getElementById('slots-loading');
    var slotsEmpty = document.getElementById('slots-empty');
    var slotsCount = document.getElementById('slots-count');
    var slotStartInput = document.getElementById('slot_start');
    var summaryEl = document.getElementById('booking-summary');
    var sumDate = document.getElementById('sum-date');
    var sumTime = document.getElementById('sum-time');
    var sumDuration = document.getElementById('sum-duration');
    var sumSchedule = document.getElementById('sum-schedule');
    var form = document.getElementById('booking-form');
    var bookBtn = document.getElementById('book-btn');
    var bookSpinner = document.getElementById('book-spinner');
    var bookIcon = document.getElementById('book-icon');
    var bookText = document.getElementById('book-text');
    var hfStarts = document.getElementById('hf_starts_at');
    var hfEnds = document.getElementById('hf_ends_at');
    var hfTz = document.getElementById('hf_timezone');
    var hfDuration = document.getElementById('hf_duration');
    var currentSlots = [];
    var currentTz = '';

    function fmtDateNice(ymd) {
        if (!ymd) return '—';
        var d = new Date(ymd + 'T00:00:00');
        if (isNaN(d)) return ymd;
        return d.toLocaleDateString(undefined, { weekday:'short', month:'short', day:'numeric', year:'numeric' });
    }

    function normalizeSlot(s) {
        var out = {};
        out.start_str = (s.start_str || s.start || '');
        out.end_str   = (s.end_str   || s.end   || '');
        out.start_iso = (s.start_iso || s.startsAt || s.start_str || '');
        out.end_iso   = (s.end_iso   || s.endsAt   || s.end_str   || '');
        out.start_ut  = parseInt(s.start_ut || 0, 10);
        out.end_ut    = parseInt(s.end_ut   || 0, 10);
        if (!out.start_ut && out.start_iso) {
            var sd = new Date(out.start_iso);
            if (!isNaN(sd)) out.start_ut = Math.floor(sd.getTime() / 1000);
        }
        if (!out.end_ut && out.end_iso) {
            var ed = new Date(out.end_iso);
            if (!isNaN(ed)) out.end_ut = Math.floor(ed.getTime() / 1000);
        }
        out.available = !!s.available;
        out.reason = s.reason || null;
        return out;
    }

    function updateSummary() {
        var schId = scheduleSelect ? scheduleSelect.value : '';
        var dateVal = dateInput ? dateInput.value : '';
        var slotVal = slotStartInput ? slotStartInput.value : '';
        var slot = null;
        for (var i = 0; i < currentSlots.length; i++) {
            if (currentSlots[i].start_str === slotVal) { slot = currentSlots[i]; break; }
        }
        if (schId && dateVal && slot) {
            summaryEl.classList.remove('hidden');
            sumDate.textContent = fmtDateNice(dateVal);
            sumTime.textContent = slot.start_str + ' — ' + slot.end_str;
            var mins = slot.end_ut && slot.start_ut ? Math.round((slot.end_ut - slot.start_ut) / 60) : 0;
            sumDuration.textContent = (mins > 0 ? mins : '—') + (mins > 0 ? ' min' : '');
            var schOpt = scheduleSelect.options[scheduleSelect.selectedIndex];
            sumSchedule.textContent = schOpt ? schOpt.textContent.trim() : '—';
        } else {
            summaryEl.classList.add('hidden');
        }
    }

    function renderSlots(slots) {
        slotsGrid.innerHTML = '';
        if (!slots || slots.length === 0) {
            slotsEmpty.classList.remove('hidden');
            slotsCount.textContent = '0 slots';
            currentSlots = [];
            return;
        }
        slotsEmpty.classList.add('hidden');
        var availCount = 0;
        for (var i = 0; i < slots.length; i++) if (slots[i].available) availCount++;
        slotsCount.textContent = availCount + ' available / ' + slots.length + ' total';
        currentSlots = slots;
        var selected = slotStartInput.value;
        slots.forEach(function(slot){
            var btn = document.createElement('button');
            btn.type = 'button';
            var isAvail = !!slot.available;
            var isSel = slot.start_str === selected;
            var cls = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 ';
            if (!isAvail) {
                cls += 'bg-slate-100 text-slate-400 border-slate-200 opacity-60 cursor-not-allowed line-through';
                btn.disabled = true;
            } else if (isSel) {
                cls += 'bg-emerald-500 text-white border-emerald-500 shadow-lg shadow-emerald-500/25 scale-[1.02]';
            } else {
                cls += 'bg-emerald-300 text-emerald-900 border-emerald-300 hover:bg-emerald-400 hover:border-emerald-500';
            }
            btn.className = cls;
            btn.setAttribute('data-start', slot.start_str);
            btn.innerHTML = '<span class="block">' + slot.start_str + '</span><span class="block text-[10px] font-medium opacity-75 mt-0.5">' + slot.end_str + '</span>';
            if (isAvail) {
                btn.addEventListener('click', function(){
                    slotStartInput.value = slot.start_str;
                    if (hfStarts) hfStarts.value = slot.start_iso;
                    if (hfEnds) hfEnds.value = slot.end_iso;
                    if (hfTz) hfTz.value = currentTz;
                    if (hfDuration && slot.start_ut && slot.end_ut) {
                        hfDuration.value = String(Math.round((slot.end_ut - slot.start_ut) / 60));
                    }
                    var all = slotsGrid.querySelectorAll('button');
                    for (var i = 0; i < all.length; i++) {
                        if (all[i].disabled) continue;
                        all[i].className = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 bg-emerald-300 text-emerald-900 border-emerald-300 hover:bg-emerald-400 hover:border-emerald-500';
                    }
                    btn.className = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 bg-emerald-500 text-white border-emerald-500 shadow-lg shadow-emerald-500/25 scale-[1.02]';
                    updateSummary();
                });
            }
            slotsGrid.appendChild(btn);
        });
    }

    var slotsURLBase = <?= json_encode(rtrim($slotsEndpoint, '/') . '/') ?>;
    var csrfName  = <?= json_encode(csrf_token()) ?>;
    var csrfValue = <?= json_encode(csrf_hash()) ?>;

    function loadSlots() {
        var schId = scheduleSelect ? scheduleSelect.value : '';
        var dateVal = dateInput ? dateInput.value : '';
        slotStartInput.value = '';
        if (hfStarts) hfStarts.value = '';
        if (hfEnds) hfEnds.value = '';
        if (hfDuration) hfDuration.value = '';
        if (dateHidden && dateVal) dateHidden.value = dateVal;
        updateSummary();
        if (!schId || !dateVal) {
            slotsGrid.innerHTML = '';
            slotsEmpty.classList.add('hidden');
            slotsCount.textContent = schId ? 'Pick a date' : 'Select a schedule and date to load slots';
            return;
        }
        slotsGrid.innerHTML = '';
        slotsEmpty.classList.add('hidden');
        slotsLoading.classList.remove('hidden');
        var fd = new FormData();
        if (csrfName) fd.append(csrfName, csrfValue);
        fd.append('date', dateVal);
        fetch(slotsURLBase + encodeURIComponent(schId), {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd
        }).then(function(r){ return r.text(); }).then(function(t){
            slotsLoading.classList.add('hidden');
            var trimmed = (t || '').trim();
            var data = { ok: false };
            if (trimmed && /^\s*[\{\[]/.test(trimmed)) {
                try { data = JSON.parse(trimmed); } catch(e){ data = { ok: false, error: 'Bad server reply' }; }
            }
            if (data && data.ok) {
                currentTz = (data.timezone || '');
                if (hfTz) hfTz.value = currentTz;
                var raw = data.slots || [];
                var normalized = [];
                for (var i = 0; i < raw.length; i++) normalized.push(normalizeSlot(raw[i]));
                renderSlots(normalized);
            } else {
                slotsCount.textContent = (data && (data.error || data.message)) ? (data.error || data.message) : 'Error loading slots';
                slotsGrid.innerHTML = '';
            }
        }).catch(function(){
            slotsLoading.classList.add('hidden');
            slotsCount.textContent = 'Network error — retry';
        });
    }

    function renderSlots(slots, groupByDateLabel) {
        slotsGrid.innerHTML = '';
        if (!slots || slots.length === 0) {
            slotsEmpty.classList.remove('hidden');
            slotsCount.textContent = '0 slots';
            currentSlots = [];
            return;
        }
        slotsEmpty.classList.add('hidden');
        var availCount = 0;
        for (var i = 0; i < slots.length; i++) if (slots[i].available) availCount++;
        slotsCount.textContent = availCount + ' available / ' + slots.length + ' total';
        currentSlots = slots;
        var selected = slotStartInput.value;
        var lastDateKey = '';
        slots.forEach(function(slot){
            if (groupByDateLabel && slot.date_key && slot.date_key !== lastDateKey) {
                var sep = document.createElement('div');
                sep.className = 'col-span-3 flex items-center gap-2 my-1';
                sep.innerHTML = '<span class="flex-1 h-px bg-slate-200"></span><span class="text-[11px] font-bold text-slate-500 px-3 py-1 rounded-full bg-slate-100">' + (slot.date_label || '') + '</span><span class="flex-1 h-px bg-slate-200"></span>';
                slotsGrid.appendChild(sep);
                lastDateKey = slot.date_key;
            }
            var btn = document.createElement('button');
            btn.type = 'button';
            var isAvail = !!slot.available;
            var isSel = slot.start_str === selected;
            var cls = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 ';
            if (!isAvail) {
                cls += 'bg-slate-100 text-slate-400 border-slate-200 opacity-60 cursor-not-allowed line-through';
                btn.disabled = true;
            } else if (isSel) {
                cls += 'bg-emerald-500 text-white border-emerald-500 shadow-lg shadow-emerald-500/25 scale-[1.02]';
            } else {
                cls += 'bg-emerald-300 text-emerald-900 border-emerald-300 hover:bg-emerald-400 hover:border-emerald-500';
            }
            btn.className = cls;
            btn.setAttribute('data-start', slot.start_str);
            btn.innerHTML = '<span class="block">' + slot.start_str + '</span><span class="block text-[10px] font-medium opacity-75 mt-0.5">' + slot.end_str + '</span>' + (groupByDateLabel && slot.date_short ? '<span class="block text-[9.5px] font-bold text-emerald-800/70 mt-0.5">' + slot.date_short + '</span>' : '');
            if (isAvail) {
                btn.addEventListener('click', function(){
                    slotStartInput.value = slot.start_str;
                    if (hfStarts) hfStarts.value = slot.start_iso;
                    if (hfEnds) hfEnds.value = slot.end_iso;
                    if (hfTz) hfTz.value = currentTz;
                    if (hfDuration && slot.start_ut && slot.end_ut) {
                        hfDuration.value = String(Math.round((slot.end_ut - slot.start_ut) / 60));
                    }
                    if (dateInput && slot.date_key) {
                        dateInput.value = slot.date_key;
                        if (dateHidden) dateHidden.value = slot.date_key;
                    }
                    var all = slotsGrid.querySelectorAll('button');
                    for (var i = 0; i < all.length; i++) {
                        if (all[i].disabled) continue;
                        all[i].className = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 bg-emerald-300 text-emerald-900 border-emerald-300 hover:bg-emerald-400 hover:border-emerald-500';
                    }
                    btn.className = 'relative w-full px-2 py-2.5 rounded-xl text-xs font-bold transition-all border-2 bg-emerald-500 text-white border-emerald-500 shadow-lg shadow-emerald-500/25 scale-[1.02]';
                    updateSummary();
                });
            }
            slotsGrid.appendChild(btn);
        });
    }

    function loadSlotsForDate(dateVal, scheduleId, labelOverride) {
        return new Promise(function(resolve, reject){
            var fd = new FormData();
            if (csrfName) fd.append(csrfName, csrfValue);
            fd.append('date', dateVal);
            fetch(slotsURLBase + encodeURIComponent(scheduleId), {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: fd
            }).then(function(r){ return r.text(); }).then(function(t){
                var trimmed = (t || '').trim();
                var data = { ok: false };
                if (trimmed && /^\s*[\{\[]/.test(trimmed)) {
                    try { data = JSON.parse(trimmed); } catch(e){ data = { ok: false, error: 'Bad server reply' }; }
                }
                if (data && data.ok) {
                    var raw = data.slots || [];
                    var normalized = [];
                    for (var i = 0; i < raw.length; i++) {
                        var ns = normalizeSlot(raw[i]);
                        ns.date_key = dateVal;
                        ns.date_label = labelOverride || fmtDateNice(dateVal);
                        try {
                            var dp = new Date(dateVal + 'T00:00:00');
                            if (!isNaN(dp)) ns.date_short = (dp.getMonth()+1) + '/' + dp.getDate();
                        } catch(e){}
                        normalized.push(ns);
                    }
                    if (!currentTz && data.timezone) currentTz = data.timezone;
                    resolve({ ok: true, slots: normalized, date: dateVal });
                } else {
                    resolve({ ok: false, error: data.error || data.message || 'Error' });
                }
            }).catch(function(){ resolve({ ok: false, error: 'Network error' }); });
        });
    }

    function addDaysISO(isoDate, days) {
        var d = new Date(isoDate + 'T00:00:00');
        if (isNaN(d)) return isoDate;
        d.setDate(d.getDate() + days);
        var mm = String(d.getMonth()+1).padStart(2,'0');
        var dd = String(d.getDate()).padStart(2,'0');
        return d.getFullYear() + '-' + mm + '-' + dd;
    }

    async function preloadNextAvailable() {
        if (!scheduleSelect || !dateInput || !scheduleSelect.value) return;
        var schId = scheduleSelect.value;
        var startDate = dateInput.value || new Date().toISOString().slice(0,10);
        var MAX_DAYS = 14;
        var MIN_AVAIL = 2;
        var allSlots = [];
        var availCount = 0;
        var errMsg = null;
        slotsLoading.classList.remove('hidden');
        slotsEmpty.classList.add('hidden');
        slotsGrid.innerHTML = '';
        slotsCount.textContent = 'Finding earliest slots…';
        for (var dayOffset = 0; dayOffset < MAX_DAYS && availCount < MIN_AVAIL; dayOffset++) {
            var dv = addDaysISO(startDate, dayOffset);
            var res = await loadSlotsForDate(dv, schId);
            if (!res.ok) { errMsg = res.error; break; }
            var dayAvail = 0;
            for (var k = 0; k < res.slots.length; k++) if (res.slots[k].available) dayAvail++;
            availCount += dayAvail;
            allSlots = allSlots.concat(res.slots);
        }
        slotsLoading.classList.add('hidden');
        if (allSlots.length === 0) {
            slotsEmpty.classList.remove('hidden');
            slotsCount.textContent = errMsg || 'No available slots in the next 2 weeks';
            currentSlots = [];
            return;
        }
        renderSlots(allSlots, true);
    }

    if (scheduleSelect) scheduleSelect.addEventListener('change', preloadNextAvailable);
    if (dateInput) dateInput.addEventListener('change', function(){
        if (dateHidden) dateHidden.value = dateInput.value;
        preloadNextAvailable();
    });
    if (dateHidden && dateInput && dateInput.value) dateHidden.value = dateInput.value;
    if (scheduleSelect && scheduleSelect.options.length === 2 && scheduleSelect.value === '') {
        scheduleSelect.value = scheduleSelect.options[1].value || '';
    }
    if (scheduleSelect && dateInput && scheduleSelect.value) {
        preloadNextAvailable();
    } else if (scheduleSelect && dateInput && scheduleSelect.value && dateInput.value) {
        loadSlots();
    }

    function loadSlots() {
        preloadNextAvailable();
    }

    if (form) form.addEventListener('submit', function(e){
        if (!slotStartInput.value) {
            e.preventDefault();
            alert('Please select an available time slot.');
            return false;
        }
        if (dateHidden && dateInput && dateInput.value) dateHidden.value = dateInput.value;
        if ((!hfStarts || !hfStarts.value) || (!hfEnds || !hfEnds.value)) {
            var sv = slotStartInput.value;
            for (var j = 0; j < currentSlots.length; j++) {
                if (currentSlots[j].start_str === sv) {
                    if (hfStarts) hfStarts.value = currentSlots[j].start_iso;
                    if (hfEnds)   hfEnds.value   = currentSlots[j].end_iso;
                    if (hfTz && hfTz.value === '') hfTz.value = currentTz;
                    if (hfDuration && currentSlots[j].start_ut && currentSlots[j].end_ut) {
                        hfDuration.value = String(Math.round((currentSlots[j].end_ut - currentSlots[j].start_ut) / 60));
                    }
                    break;
                }
            }
        }
        if (bookBtn) bookBtn.disabled = true;
        if (bookSpinner) bookSpinner.classList.remove('hidden');
        if (bookIcon) bookIcon.classList.add('hidden');
        if (bookText) bookText.textContent = 'Booking…';
    });

    updateSummary();
})();
</script>
