@extends('layouts.app')
@section('title', isset($appointment) ? __('vetClinic::lang.edit') . ' Appointment' : 'New Appointment')

@section('css')
<style>
/* ── Item #3 - Select2 loading state ──────────────────────────────
   Wraps the Select2 .selection container in a spinner overlay while
   AJAX is in flight so the doctor can't click into a half-populated
   dropdown. Pairs with lockSelectLoading() / unlockSelect() helpers. */
.select2-container.vc-select-loading .select2-selection {
    background: #f8fafc !important;
    color: #94a3b8 !important;
    cursor: wait !important;
    pointer-events: none;
    position: relative;
}
.select2-container.vc-select-loading .select2-selection::after {
    content: '';
    position: absolute;
    right: 12px; top: 50%;
    width: 14px; height: 14px;
    margin-top: -7px;
    border: 2px solid #cbd5e1;
    border-top-color: #3498db;
    border-radius: 50%;
    animation: vcSelectSpin .8s linear infinite;
    pointer-events: none;
}
.select2-container.vc-select-loading .select2-selection__arrow { display: none; }
@keyframes vcSelectSpin { to { transform: rotate(360deg); } }

/* ── Slot grid ──────────────────────────────────────────────────── */
.slot-grid        { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }
.slot-btn {
    padding:6px 14px; border-radius:6px; border:1.5px solid #cbd5e1;
    background:#fff; font-size:12px; font-weight:600; cursor:pointer;
    transition:all .15s; color:#334155; min-width:110px; text-align:center;
    user-select:none;
}
.slot-btn:hover:not(.unavailable):not(.selected) { border-color:#3498db; color:#3498db; background:#eff6ff; }
.slot-btn.selected   { background:#3498db; color:#fff; border-color:#2471a3; }
.slot-btn.booked-warn{ background:#fff7ed; color:#c2410c; border-color:#fed7aa; }
.slot-btn.unavailable{ background:#fee2e2; color:#ef4444; border-color:#fca5a5;
                        cursor:not-allowed; opacity:.75; text-decoration:line-through; }
.overlap-alert { padding:8px 12px; background:#fff7ed; border:1px solid #fed7aa;
                 border-radius:6px; color:#c2410c; font-size:12px; margin-top:6px; display:none; }
/* ── Step badges ───────────────────────────────────────────────── */
.step-badge { display:inline-flex; align-items:center; justify-content:center;
    width:22px; height:22px; background:#3498db; color:#fff; border-radius:50%;
    font-size:11px; font-weight:700; margin-right:6px; flex-shrink:0; }
.scheduling-label { display:flex; align-items:center; font-weight:600; margin-bottom:4px; }
.cascade-hint { font-size:11px; color:#94a3b8; margin-top:3px; min-height:14px; }
/* ── Disabled Select2 options ──────────────────────────────────── */
.select2-results__option--disabled,
.select2-results__option[aria-disabled="true"] {
    color:#adb5bd !important; font-style:italic; cursor:not-allowed !important; background:#f8f9fa !important;
}
/* ── Preferred-doctor note ─────────────────────────────────────── */
.vc-doc-note { font-size:12px; margin-top:6px; padding:7px 10px; border-radius:6px;
    background:#eff6ff; border:1px solid #bfdbfe; color:#1e40af; line-height:1.5; }
.vc-doc-note.vc-doc-locked { background:#fef3c7; border-color:#fde68a; color:#92400e; }
.vc-doc-note i { margin-right:4px; }
</style>
@include('vetClinic::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-calendar-plus"></i>
        {{ isset($appointment) ? __('vetClinic::lang.edit') . ' Appointment' : 'New Appointment' }}
    </h1>
</section>

<section class="content">
@if(!empty($editViaRequest))
<div class="alert alert-warning" style="border-radius:9px;display:flex;align-items:center;gap:10px;">
    <i class="fa fa-unlock-alt fa-2x" style="color:#d97706;"></i>
    <div style="font-size:13px;">
        <strong>Editing under approved request #{{ $editViaRequest->id }}.</strong>
        This is a single-use edit — once you save, the appointment re-locks and a new request is required for further changes.
    </div>
</div>
@endif
<form method="POST"
      action="{{ isset($appointment) ? route('vc.appointments.update', $appointment->id) : route('vc.appointments.store') }}"
      id="apt_form">
    @csrf
    <div class="row">

        {{-- ── LEFT COLUMN ────────────────────────────────────────────── --}}
        <div class="col-md-8">

            {{-- Patient --}}
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Patient'])
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.pet_owner') <span class="text-danger">*</span></label>
                            <select name="contact_id" id="apt_contact_id" class="form-control select2" style="width:100%" required
                                {{ isset($preselectedContact) ? 'disabled' : '' }}>
                                @if(isset($preselectedContact))
                                    <option value="{{ $preselectedContact->id }}" selected>
                                        {{ trim($preselectedContact->name ?: ($preselectedContact->supplier_business_name ?? '')) }}
                                        {{ $preselectedContact->mobile ? '(' . $preselectedContact->mobile . ')' : '' }}
                                    </option>
                                @elseif(isset($appointment) && $appointment->owner)
                                    <option value="{{ $appointment->contact_id }}" selected>{{ $appointment->owner->name }}</option>
                                @endif
                            </select>
                            @if(isset($preselectedContact))
                                <input type="hidden" name="contact_id" value="{{ $preselectedContact->id }}">
                            @endif
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.pet') <span class="text-danger">*</span></label>
                            <select name="pet_id" id="apt_pet_id" class="form-control select2" style="width:100%" required
                                {{ isset($preselectedPet) ? 'disabled' : '' }}>
                                @if(isset($preselectedPet))
                                    <option value="{{ $preselectedPet->id }}" selected>
                                        {{ $preselectedPet->petname }}{{ $preselectedPet->species ? ' (' . $preselectedPet->species . ')' : '' }}
                                    </option>
                                @elseif(isset($appointment) && $appointment->pet)
                                    <option value="{{ $appointment->pet_id }}" selected>{{ $appointment->pet->petname }}</option>
                                @endif
                            </select>
                            @if(isset($preselectedPet))
                                <input type="hidden" name="pet_id" value="{{ $preselectedPet->id }}">
                            @endif
                        </div>
                    </div>
                </div>
            @endcomponent

            {{-- Scheduling --}}
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Scheduling'])

                {{-- Step 1: Date + Duration --}}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="scheduling-label">
                                <span class="step-badge">1</span> @lang('vetClinic::lang.appointment_date') <span class="text-danger">*</span>
                            </label>
                            <input type="text" id="apt_date_display" class="form-control" autocomplete="off" required
                                placeholder="{{ session('business.date_format', 'd/m/Y') }}" style="max-width:220px;">
                            <input type="hidden" name="appointment_date" id="apt_date_iso"
                                value="{{ old('appointment_date', isset($appointment) ? $appointment->appointment_date->format('Y-m-d') : date('Y-m-d')) }}">
                        </div>
                    </div>
                    <input type="hidden" name="duration_minutes" id="apt_duration"
                        value="{{ old('duration_minutes', isset($appointment) ? $appointment->duration_minutes : 30) }}">
                </div>

                {{-- Step 2: Location + Department --}}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="scheduling-label">
                                <span class="step-badge">2</span> <i class="fa fa-map-marker" style="margin-right:4px;"></i> Clinic Location
                            </label>
                            <select name="location_id" id="apt_location_id" class="form-control select2" style="width:100%">
                                <option value="">— Select date first —</option>
                                @if(isset($appointment) && $appointment->location_id)
                                    <option value="{{ $appointment->location_id }}" selected>{{ optional($appointment->location)->name }}</option>
                                @endif
                            </select>
                            <div class="cascade-hint" id="loc_hint">Select a date to load available locations.</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="scheduling-label">
                                <i class="fa fa-hospital" style="margin-right:4px;"></i> @lang('vetClinic::lang.department')
                            </label>
                            <select name="department_id" id="apt_department_id" class="form-control select2" style="width:100%">
                                <option value="">— Select location first —</option>
                                @if(isset($appointment) && $appointment->department_id)
                                    <option value="{{ $appointment->department_id }}" selected>{{ optional($appointment->department)->name }}</option>
                                @endif
                            </select>
                            <div class="cascade-hint" id="dept_hint">Select a location to load departments.</div>
                        </div>
                    </div>
                </div>

                {{-- Step 3: Doctor --}}
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="scheduling-label">
                                <span class="step-badge">3</span> <i class="fa fa-user-md" style="margin-right:4px;"></i> @lang('vetClinic::lang.doctor')
                            </label>
                            <select name="doctor_id" id="apt_doctor_id" class="form-control select2" style="width:100%">
                                <option value="">— Select department first —</option>
                                @if(isset($appointment) && $appointment->doctor_id)
                                    <option value="{{ $appointment->doctor_id }}" selected>{{ optional($appointment->doctor)->name }}</option>
                                @endif
                            </select>
                            <div class="cascade-hint" id="doctor_hint">Select a department to load available doctors.</div>
                            <div class="vc-doc-note" id="preferred_doc_note" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                {{-- Step 4: Slot picker --}}
                <div id="slot_picker_section" style="display:none; margin-top:4px;">
                    <label class="scheduling-label">
                        <span class="step-badge">4</span> <i class="fa fa-clock" style="margin-right:4px;"></i> Available Time Slots
                    </label>
                    <p style="font-size:11px;color:#64748b;margin:0 0 6px;">
                        Click one slot or multiple consecutive slots to set the appointment duration.
                    </p>
                    <div class="slot-grid" id="slot_grid"></div>
                    <div class="overlap-alert" id="overlap_alert">
                        <i class="fa fa-exclamation-triangle"></i>
                        Selected slot(s) overlap an existing appointment for this doctor.
                    </div>
                </div>

                {{-- Hidden time + fallback manual entry --}}
                <input type="hidden" name="appointment_time" id="apt_time"
                    value="{{ old('appointment_time', isset($appointment) ? $appointment->appointment_time : '') }}">
                <input type="hidden" name="schedule_id" id="apt_schedule_id" value="">

                <div id="manual_time_group" style="margin-top:12px; {{ isset($appointment) ? '' : 'display:none;' }}">
                    <label>@lang('vetClinic::lang.appointment_time') <span class="text-danger">*</span></label>
                    <input type="time" id="apt_time_manual" class="form-control" style="width:180px;"
                        value="{{ old('appointment_time', isset($appointment) ? $appointment->appointment_time : '09:00') }}"
                        oninput="document.getElementById('apt_time').value = this.value">
                    <small class="text-muted" id="manual_time_hint">No schedule found for this doctor — enter time manually.</small>
                </div>

            @endcomponent

            {{-- Visit Details --}}
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Visit Details'])
                <div class="form-group">
                    <label>@lang('vetClinic::lang.type') <span class="text-danger">*</span></label>
                    @if($aptTypes->isNotEmpty())
                        <select name="type_ids[]" id="apt_type_ids" class="form-control select2" style="width:100%" multiple required>
                            @foreach($aptTypes as $at)
                            <option value="{{ $at->id }}"
                                {{ in_array($at->id, old('type_ids', isset($appointment) && !empty($appointment->type_ids) ? (array)$appointment->type_ids : [])) ? 'selected' : '' }}>
                                {{ $at->name }}
                            </option>
                            @endforeach
                        </select>
                        <input type="hidden" name="type" value="other">
                    @else
                        <select name="type" class="form-control select2" style="width:100%">
                            @foreach(['checkup','vaccination','surgery','grooming','emergency','other'] as $t)
                            <option value="{{ $t }}" {{ old('type', isset($appointment) ? $appointment->type : 'checkup') == $t ? 'selected' : '' }}>
                                {{ ucfirst($t) }}
                            </option>
                            @endforeach
                        </select>
                        <small class="text-muted">
                            <a href="{{ route('vc.apt-types.index') }}"><i class="fa fa-cog"></i> Manage appointment types in Settings</a>
                        </small>
                    @endif
                </div>

                <div class="form-group">
                    <label>@lang('vetClinic::lang.reason')</label>
                    @if($aptReasons->isNotEmpty())
                        <select name="reason_ids[]" id="apt_reason_ids" class="form-control select2" style="width:100%" multiple>
                            @foreach($aptReasons as $ar)
                            <option value="{{ $ar->id }}"
                                {{ in_array($ar->id, old('reason_ids', isset($appointment) && !empty($appointment->reason_ids) ? (array)$appointment->reason_ids : [])) ? 'selected' : '' }}>
                                {{ $ar->name }}
                            </option>
                            @endforeach
                        </select>
                        <input type="hidden" name="reason" value="">
                    @else
                        <input type="text" name="reason" class="form-control"
                            value="{{ old('reason', isset($appointment) ? $appointment->reason : '') }}"
                            placeholder="Describe the reason for visit…">
                    @endif
                </div>

                <div class="form-group">
                    <label>@lang('vetClinic::lang.notes')</label>
                    <textarea name="notes" class="form-control" rows="2">{{ old('notes', isset($appointment) ? $appointment->notes : '') }}</textarea>
                </div>

                @if(isset($appointment))
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.status')</label>
                            <select name="status" class="form-control">
                                @foreach(['pending'=>'Scheduled','confirmed'=>'Confirmed','in_progress'=>'In Consultation','completed'=>'Completed','cancelled'=>'Cancelled','no_show'=>'No Show'] as $s => $sl)
                                <option value="{{ $s }}" {{ $appointment->status == $s ? 'selected' : '' }}>{{ $sl }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.doctor_notes')</label>
                            <textarea name="doctor_notes" class="form-control" rows="2">{{ $appointment->doctor_notes }}</textarea>
                        </div>
                    </div>
                </div>
                @endif
            @endcomponent

        </div>

        {{-- ── RIGHT COLUMN ──────────────────────────────────────────── --}}
        <div class="col-md-4">
            <div class="box box-default">
                <div class="box-body">
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-save"></i>
                        {{ isset($appointment) ? __('vetClinic::lang.update') : __('vetClinic::lang.save') }}
                    </button>
                    <a href="{{ route('vc.appointments.index') }}" class="btn btn-default btn-block">@lang('vetClinic::lang.cancel')</a>
                </div>
            </div>

            <div class="box box-default">
                <div class="box-header with-border" style="padding:10px 14px;">
                    <h3 class="box-title" style="font-size:13px;"><i class="fa fa-map-marker"></i> Location Info</h3>
                </div>
                <div class="box-body" id="location_info" style="font-size:12px;color:#555;">
                    <span class="text-muted">Select a location to see details.</span>
                </div>
            </div>

            <div class="box box-default">
                <div class="box-header with-border" style="padding:10px 14px;">
                    <h3 class="box-title" style="font-size:13px;"><i class="fa fa-user-md"></i> Doctor Schedule</h3>
                </div>
                <div class="box-body" id="doctor_schedule_info" style="font-size:12px;color:#555;">
                    <span class="text-muted">Select a doctor to see schedule.</span>
                </div>
            </div>

            <div class="box box-info" id="selection_summary" style="display:none;">
                <div class="box-header with-border" style="padding:10px 14px;">
                    <h3 class="box-title" style="font-size:13px;"><i class="fa fa-calendar-check"></i> Selection</h3>
                </div>
                <div class="box-body" id="selection_detail" style="font-size:12px;"></div>
            </div>
        </div>

    </div>
</form>
</section>
@endsection

@section('javascript')
<script>
$(document).ready(function () {

    /* ── Config ─────────────────────────────────────────────────── */
    var allowOverlap  = {{ $allowOverlap ? 'true' : 'false' }};
    var urlLocations  = '{{ route('vc.appointments.locations-by-date') }}';
    var urlDepts      = '{{ route('vc.appointments.depts-by-location') }}';
    var urlDoctors    = '{{ route('vc.appointments.doctors-by-dept') }}';
    var urlSlots      = '{{ route('vc.appointments.slots') }}';
    var urlSched      = '{{ route('vc.doctors.schedule-summary') }}';
    var urlPets       = '{{ url('vet-clinic/pets/by-owner') }}';
    var urlPetBase    = '{{ url('vet-clinic/pets') }}';

    /* ── Preferred-doctor state ─────────────────────────────────── */
    var canChangeDoctor = {{ !empty($canChangeDoctor) ? 'true' : 'false' }};
    var preferredDoctor = null;   // { id, name, source } — pet's effective preferred doctor

    function renderPreferredDoctorNote() {
        var $note = $('#preferred_doc_note');
        if (!preferredDoctor) { $note.hide().empty().removeClass('vc-doc-locked'); return; }
        if (preferredDoctor.source === 'assigned') {
            $note.addClass('vc-doc-locked')
                 .html('<i class="fa fa-lock"></i> Doctor is locked to this appointment\'s assigned doctor: <strong>'
                     + preferredDoctor.name + '</strong>. You do not have permission to change it — '
                     + 'submit a doctor-change request from the appointment page.')
                 .show();
            return;
        }
        var who = preferredDoctor.source === 'pet' ? "this pet's" : "the owner's";
        if (canChangeDoctor) {
            $note.removeClass('vc-doc-locked')
                 .html('<i class="fa fa-star"></i> Preferred doctor (' + who + '): <strong>' + preferredDoctor.name
                     + '</strong> — pre-selected. You may change it if needed.')
                 .show();
        } else {
            $note.addClass('vc-doc-locked')
                 .html('<i class="fa fa-lock"></i> Doctor is fixed to ' + who + ' preferred doctor: <strong>'
                     + preferredDoctor.name + '</strong>. You do not have permission to change it — '
                     + 'you can submit a doctor-change request after the appointment is created.')
                 .show();
        }
    }

    function fetchPreferredDoctor(petId, done) {
        preferredDoctor = null;
        if (!petId) { renderPreferredDoctorNote(); applyPreferredDoctorToSelect(false); if (done) done(); return; }
        $.getJSON(urlPetBase + '/' + petId + '/preferred-doctor', function (res) {
            if (res && res.doctor_id) {
                preferredDoctor = { id: String(res.doctor_id), name: res.doctor_name, source: res.source };
            }
            renderPreferredDoctorNote();
            applyPreferredDoctorToSelect(true);
            if (done) done();
        }).fail(function () { renderPreferredDoctorNote(); if (done) done(); });
    }

    function lockDoctorSelect(docId) {
        $('#apt_doctor_id').prop('disabled', true).trigger('change.select2');
        if ($('#apt_doctor_id_hidden').length) {
            $('#apt_doctor_id_hidden').val(docId);
        } else {
            $('#apt_doctor_id').after('<input type="hidden" id="apt_doctor_id_hidden" name="doctor_id" value="' + docId + '">');
        }
    }

    function unlockDoctorSelect() {
        $('#apt_doctor_id').prop('disabled', false).trigger('change.select2');
        $('#apt_doctor_id_hidden').remove();
    }

    // Apply the preferred doctor to the (re)built doctor select.
    function applyPreferredDoctorToSelect(autoLoadSlots) {
        if (!preferredDoctor) {
            unlockDoctorSelect();   // nothing to force — leave the field open
            return;
        }
        var $sel = $('#apt_doctor_id');
        var $opt = $sel.find('option[value="' + preferredDoctor.id + '"]');
        if (!$opt.length) {
            $sel.append($('<option>').val(preferredDoctor.id).text(preferredDoctor.name));
        } else {
            $opt.prop('disabled', false);   // ensure selectable even if marked unavailable
        }
        $sel.val(preferredDoctor.id).trigger('change.select2');

        if (canChangeDoctor) {
            unlockDoctorSelect();
        } else {
            lockDoctorSelect(preferredDoctor.id);
        }

        if (autoLoadSlots && $('#apt_department_id').val()) {
            var date = $('#apt_date_iso').val();
            if (date) { loadSlots($('#apt_department_id').val(), preferredDoctor.id, date); }
            loadScheduleSummary(preferredDoctor.id);
        }
    }

    /* ── Slot selection state ───────────────────────────────────── */
    var selectedSlots = []; // [{start, end, duration, schedule_id, booked}]

    /* ── Date picker ────────────────────────────────────────────── */
    var existingIso = $('#apt_date_iso').val();
    var dateReady   = false;

    $('#apt_date_display').datepicker({
        todayHighlight: true, autoclose: true, format: datepicker_date_format
    }).on('changeDate', function (e) {
        if (!dateReady || !e.dates.length) return;
        var d   = e.dates[0];
        var iso = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
        $('#apt_date_iso').val(iso);
        onDateChange(iso);
    });

    if (existingIso) {
        $('#apt_date_display').datepicker('setDate', new Date(existingIso + 'T00:00:00'));
    }
    dateReady = true;
    if (existingIso) {
        onDateChange(existingIso);
    }

    /* ── Select2 inits ──────────────────────────────────────────── */
    $('#apt_contact_id').select2({
        width: '100%', placeholder: '— Search owner —', minimumInputLength: 1,
        ajax: {
            url: '{{ route('vc.pet-owners.search') }}', dataType: 'json', delay: 250,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return { results: d }; }
        }
    });

    $('#apt_pet_id').select2({ width: '100%', placeholder: '— Select pet —' });
    $('#apt_type_ids, #apt_reason_ids').select2({ width: '100%', placeholder: '— Select —' });

    // Location & department use custom rendering for disabled options
    function makeSelect2WithDisabled(selector) {
        $(selector).select2({
            width: '100%',
            templateResult: function (data) {
                if (!data.id) return data.text;
                var $el = $(data.element);
                if ($el.prop('disabled')) {
                    return $('<span style="color:#adb5bd;font-style:italic;">'+data.text+'</span>');
                }
                return data.text;
            }
        });
    }
    makeSelect2WithDisabled('#apt_location_id');
    makeSelect2WithDisabled('#apt_department_id');
    makeSelect2WithDisabled('#apt_doctor_id');

    /* ── Pet owner → pets ───────────────────────────────────────── */
    $('#apt_contact_id').on('change', function () {
        var cid = $(this).val();
        fetchPreferredDoctor(null);   // clear — pet is about to be reset
        if (!cid) {
            $('#apt_pet_id').empty().append('<option value="">— Select pet —</option>').trigger('change.select2');
            unlockSelect('#apt_pet_id');
            return;
        }
        lockSelectLoading('#apt_pet_id', '— Loading pets… —');
        $.getJSON(urlPets + '/' + cid, function (pets) {
            $('#apt_pet_id').empty().append('<option value="">— Select pet —</option>');
            pets.forEach(function (p) {
                $('#apt_pet_id').append('<option value="' + p.id + '">' + p.text + '</option>');
            });
            unlockSelect('#apt_pet_id');
        }).fail(function () {
            unlockSelect('#apt_pet_id');
            toastr.error('Could not load pets for this owner.');
        });
    });

    /* ── Pet → preferred doctor ─────────────────────────────────── */
    $('#apt_pet_id').on('change', function () {
        fetchPreferredDoctor($(this).val());
    });

    /* ── Cascade chain ──────────────────────────────────────────── */

    function onDateChange(iso) {
        resetSlots();
        loadLocations(iso);
    }

    $('#apt_location_id').on('change', function () {
        var locId = $(this).val();
        var date  = $('#apt_date_iso').val();
        resetSlots();
        loadDepartments(locId, date);
        showLocationInfo(locId);
    });

    $('#apt_department_id').on('change', function () {
        var deptId = $(this).val();
        var locId  = $('#apt_location_id').val();
        var date   = $('#apt_date_iso').val();
        resetSlots();
        loadDoctors(deptId, locId, date);
    });

    $('#apt_doctor_id').on('change', function () {
        var docId = $(this).val();
        resetSlots();
        if (docId) {
            loadSlots($('#apt_department_id').val(), docId, $('#apt_date_iso').val());
            loadScheduleSummary(docId);
        } else {
            $('#doctor_schedule_info').html('<span class="text-muted">Select a doctor to see schedule.</span>');
        }
    });

    /* ── Load functions ─────────────────────────────────────────── */

    function loadLocations(date) {
        // Lock all three downstream selects up-front so the user can't
        // click into a partly-loaded dropdown while the chain refreshes.
        setDropdown('#apt_department_id', null, '— Select location first —');
        setDropdown('#apt_doctor_id',     null, '— Select department first —');
        $('#loc_hint').text('');

        if (!date) { setDropdown('#apt_location_id', null, '— Select a date first —'); return; }

        lockSelectLoading('#apt_location_id', '— Loading locations… —');
        $.getJSON(urlLocations, { date: date }, function (locs) {
            rebuildSelect('#apt_location_id', locs, 'id', 'name', '— Select Location —', 'has_available',
                function (loc) { return loc.has_available ? '' : ' (no availability)'; });
            unlockSelect('#apt_location_id');
            $('#loc_hint').text(
                locs.some(function(l){ return l.has_available; })
                    ? '' : 'No locations have available slots on this date.');
        }).fail(function () {
            unlockSelect('#apt_location_id');
            toastr.error('Could not load locations.');
        });
    }

    function loadDepartments(locId, date) {
        setDropdown('#apt_doctor_id',     null, '— Select department first —');
        $('#dept_hint').text('');

        if (!locId) { setDropdown('#apt_department_id', null, '— Select location first —'); return; }

        lockSelectLoading('#apt_department_id', '— Loading departments… —');
        $.getJSON(urlDepts, { location_id: locId, date: date }, function (depts) {
            rebuildSelect('#apt_department_id', depts, 'id', 'name', '— Select Department —', 'has_available',
                function (d) { return d.has_available ? '' : ' (no availability)'; });
            unlockSelect('#apt_department_id');
            $('#dept_hint').text(
                depts.some(function(d){ return d.has_available; })
                    ? '' : 'No departments have available slots on this date.');
        }).fail(function () {
            unlockSelect('#apt_department_id');
            toastr.error('Could not load departments.');
        });
    }

    function loadDoctors(deptId, locId, date) {
        $('#doctor_hint').text('');

        if (!deptId) { setDropdown('#apt_doctor_id', null, '— Select department first —'); return; }

        lockSelectLoading('#apt_doctor_id', '— Loading doctors… —');
        $.getJSON(urlDoctors, { department_id: deptId, location_id: locId, date: date }, function (docs) {
            rebuildSelect('#apt_doctor_id', docs, 'id', 'text', '— Select Doctor —', 'has_available',
                function (d) { return d.has_available ? '' : ' (no availability)'; });
            unlockSelect('#apt_doctor_id');
            $('#doctor_hint').text(
                docs.some(function(d){ return d.has_available; })
                    ? '' : 'No doctors have available slots on this date.');
            applyPreferredDoctorToSelect(true);
        }).fail(function () {
            unlockSelect('#apt_doctor_id');
            toastr.error('Could not load doctors.');
        });
    }

    function loadSlots(deptId, docId, date) {
        if (!docId || !date) return;

        $.getJSON(urlSlots, { doctor_id: docId, department_id: deptId, date: date }, function (slots) {
            if (!slots.length) {
                $('#slot_picker_section').hide();
                $('#manual_time_group').show();
                $('#manual_time_hint').text('No schedule for this doctor on the selected day — enter time manually.');
                return;
            }

            $('#slot_picker_section').show();
            $('#manual_time_group').hide();
            $('#overlap_alert').hide();

            var html = '';
            slots.forEach(function (s) {
                var cls = 'slot-btn';
                if (!s.available) {
                    cls += ' unavailable';
                } else if (s.booked) {
                    cls += ' booked-warn';
                }
                html += '<button type="button" class="' + cls + '"'
                    + ' data-start="' + s.start + '"'
                    + ' data-end="'   + s.end   + '"'
                    + ' data-duration="' + s.duration + '"'
                    + ' data-booked="'  + (s.booked ? '1' : '0') + '"'
                    + ' data-schedule="'+ (s.schedule_id || '') + '"'
                    + (s.available ? '' : ' disabled') + '>'
                    + s.start + ' – ' + s.end
                    + (s.booked && s.available ? ' <i class="fa fa-exclamation-circle" style="font-size:10px;"></i>' : '')
                    + '</button>';
            });
            $('#slot_grid').html(html);

            // Re-highlight if apt_time already set (edit mode)
            var existing = $('#apt_time').val();
            if (existing) {
                var btn = $('.slot-btn[data-start="' + existing.substring(0,5) + '"]');
                if (btn.length) btn.trigger('click');
            }
        });
    }

    /* ── Slot click — consecutive multi-select ──────────────────── */
    $(document).on('click', '.slot-btn:not([disabled])', function () {
        var $btn = $(this);
        var clickedStart = $btn.data('start');

        if (selectedSlots.length === 0) {
            // First selection
            selectedSlots = [slotDataFrom($btn)];
        } else {
            var lastSlot = selectedSlots[selectedSlots.length - 1];
            if (lastSlot.end === clickedStart) {
                // Consecutive — extend
                selectedSlots.push(slotDataFrom($btn));
            } else if (selectedSlots[0].start === clickedStart) {
                // Clicked first slot again — deselect all
                selectedSlots = [];
            } else {
                // Non-consecutive — reset to this slot
                selectedSlots = [slotDataFrom($btn)];
            }
        }

        applySlotSelection();
    });

    function slotDataFrom($btn) {
        return {
            start:       $btn.data('start'),
            end:         $btn.data('end'),
            duration:    parseInt($btn.data('duration')) || 30,
            schedule_id: $btn.data('schedule') || '',
            booked:      $btn.data('booked') == '1',
        };
    }

    function applySlotSelection() {
        // Reset visual
        $('.slot-btn').removeClass('selected');

        if (!selectedSlots.length) {
            $('#apt_time').val('');
            $('#apt_schedule_id').val('');
            $('#apt_duration').val(30);
            $('#overlap_alert').hide();
            $('#selection_summary').hide();
            return;
        }

        // Highlight selected range
        var firstStart = selectedSlots[0].start;
        var lastEnd    = selectedSlots[selectedSlots.length - 1].end;
        var slotDur    = selectedSlots[0].duration;
        var totalMins  = selectedSlots.length * slotDur;
        var anyBooked  = selectedSlots.some(function (s) { return s.booked; });

        $('.slot-btn').each(function () {
            var s = $(this).data('start');
            var e = $(this).data('end');
            // Mark selected if its start >= firstStart and its end <= lastEnd
            if (s >= firstStart && e <= lastEnd) {
                $(this).addClass('selected');
            }
        });

        $('#apt_time').val(firstStart);
        $('#apt_schedule_id').val(selectedSlots[0].schedule_id || '');
        $('#apt_duration').val(totalMins);

        if (anyBooked) {
            $('#overlap_alert').show();
        } else {
            $('#overlap_alert').hide();
        }

        // Summary box
        $('#selection_detail').html(
            '<i class="fa fa-clock"></i> <strong>' + firstStart + ' – ' + lastEnd + '</strong><br>' +
            '<i class="fa fa-hourglass-half"></i> ' + totalMins + ' min' +
            (anyBooked ? ' &nbsp;<span class="label label-warning">Overlap</span>' : '')
        );
        $('#selection_summary').show();
    }

    function resetSlots() {
        selectedSlots = [];
        $('#slot_picker_section').hide();
        $('#manual_time_group').hide();
        $('#overlap_alert').hide();
        $('#selection_summary').hide();
        $('#slot_grid').html('');
        $('#apt_time').val('');
        $('#apt_schedule_id').val('');
    }

    /* ── Helpers ────────────────────────────────────────────────── */

    function rebuildSelect(selector, items, idKey, textKey, placeholder, availKey, suffixFn) {
        var $sel = $(selector);
        $sel.empty().append('<option value="">' + placeholder + '</option>');
        items.forEach(function (item) {
            var avail   = item[availKey] !== false;
            var suffix  = suffixFn ? suffixFn(item) : '';
            var $opt    = $('<option>').val(item[idKey]).text(item[textKey] + suffix).prop('disabled', !avail);
            $sel.append($opt);
        });
        $sel.trigger('change.select2');
    }

    function setDropdown(selector, val, placeholder) {
        var $sel = $(selector);
        $sel.empty().append('<option value="">' + placeholder + '</option>');
        if (val) $sel.val(val);
        $sel.trigger('change.select2');
    }

    // Item #3 — disable a Select2 + show a spinning loading indicator
    // until the data arrives. Belt-and-braces guard against clicks on
    // partly-populated lists or stale-state submissions while AJAX is
    // still in flight. Pairs with unlockSelect() after the data lands.
    function lockSelectLoading(selector, loadingText) {
        var $sel = $(selector);
        $sel.empty()
            .append('<option value="">' + (loadingText || '— loading… —') + '</option>')
            .prop('disabled', true)
            .trigger('change.select2');
        // Visually mark the Select2 container so the CSS overlays
        // the spinner and applies disabled styling.
        $sel.next('.select2-container').addClass('vc-select-loading');
    }
    function unlockSelect(selector) {
        var $sel = $(selector);
        $sel.prop('disabled', false).trigger('change.select2');
        $sel.next('.select2-container').removeClass('vc-select-loading');
    }

    function showLocationInfo(locId) {
        if (!locId) {
            $('#location_info').html('<span class="text-muted">Select a location to see details.</span>');
            return;
        }
        // Read from already-loaded option data attribute (we'll fetch inline)
        // Simple: just show name from select text
        var name = $('#apt_location_id option:selected').text();
        $('#location_info').html('<strong>' + name + '</strong>');
    }

    function loadScheduleSummary(docId) {
        $.getJSON(urlSched, { doctor_id: docId }, function (data) {
            if (!data.length) {
                $('#doctor_schedule_info').html('<span class="text-muted">No schedule defined.</span>');
                return;
            }
            var html = '<table class="table table-condensed" style="font-size:11px;margin:0;">';
            data.forEach(function (row) {
                html += '<tr><td><strong>' + row.day + '</strong></td><td>' + row.dept + '</td><td>' + row.start + ' – ' + row.end + '</td><td>' + row.slot + 'min</td></tr>';
            });
            html += '</table>';
            $('#doctor_schedule_info').html(html);
        });
    }

    /* ── Form submit validation ─────────────────────────────────── */
    $('#apt_form').on('submit', function (e) {
        if (!$('#apt_time').val()) {
            e.preventDefault();
            toastr.error('Please select a time slot or enter a time manually.');
            return false;
        }
    });

    /* ── Edit mode: pre-populate dropdowns ──────────────────────── */
    @if(isset($appointment))
    (function () {
        var date   = '{{ $appointment->appointment_date->format('Y-m-d') }}';
        var locId  = '{{ $appointment->location_id ?? '' }}';
        var deptId = '{{ $appointment->department_id ?? '' }}';
        var docId  = '{{ $appointment->doctor_id ?? '' }}';

        // No-permission users cannot change the assigned doctor when editing.
        @if(empty($canChangeDoctor))
        if (docId) {
            preferredDoctor = { id: docId, name: '{{ addslashes(optional($appointment->doctor)->name ?? 'Assigned doctor') }}', source: 'assigned' };
            renderPreferredDoctorNote();
        }
        @endif

        // Load locations for edit date
        $.getJSON(urlLocations, { date: date }, function (locs) {
            rebuildSelect('#apt_location_id', locs, 'id', 'name', '— Select Location —', 'has_available',
                function (l) { return l.has_available ? '' : ' (no availability)'; });
            if (locId) $('#apt_location_id').val(locId).trigger('change.select2');
        });

        if (locId) {
            $.getJSON(urlDepts, { location_id: locId, date: date }, function (depts) {
                rebuildSelect('#apt_department_id', depts, 'id', 'name', '— Select Department —', 'has_available',
                    function (d) { return d.has_available ? '' : ' (no availability)'; });
                if (deptId) $('#apt_department_id').val(deptId).trigger('change.select2');
            });
        }

        if (deptId) {
            $.getJSON(urlDoctors, { department_id: deptId, location_id: locId, date: date }, function (docs) {
                rebuildSelect('#apt_doctor_id', docs, 'id', 'text', '— Select Doctor —', 'has_available',
                    function (d) { return d.has_available ? '' : ' (no availability)'; });
                if (docId) {
                    var $opt = $('#apt_doctor_id').find('option[value="' + docId + '"]');
                    if (!$opt.length) {
                        $('#apt_doctor_id').append($('<option>').val(docId).text(preferredDoctor ? preferredDoctor.name : 'Assigned doctor'));
                    } else {
                        $opt.prop('disabled', false);
                    }
                    $('#apt_doctor_id').val(docId).trigger('change.select2');
                    @if(empty($canChangeDoctor))
                    lockDoctorSelect(docId);
                    @endif
                    loadSlots(deptId, docId, date);
                    loadScheduleSummary(docId);
                }
            });
        }
    })();
    @endif

    /* ── Preselected pet: resolve its preferred doctor on load ──── */
    @if(isset($preselectedPet))
    fetchPreferredDoctor('{{ $preselectedPet->id }}');
    @endif

});
</script>
@endsection
