(function () {
    'use strict';

    var dateInput = document.getElementById('bookingDate');
    var slotsContainer = document.getElementById('slotsContainer');
    var slotsGrid = document.getElementById('slotsGrid');
    var slotsLoading = document.getElementById('slotsLoading');
    var noSlots = document.getElementById('noSlots');
    var slotDatetimeInput = document.getElementById('slotDatetime');
    var slotDurationInput = document.getElementById('slotDuration');
    var submitBtn = document.getElementById('btnSubmitBooking');
    var typeSelect = document.getElementById('appointmentTypeSelect');
    var selectedSlotBtn = null;

    var weekContainer = document.getElementById('weekCalendarContainer');
    var weekLoading = document.getElementById('weekCalendarLoading');
    var weekGrid = document.getElementById('weekCalendarGrid');
    var weekHeader = document.getElementById('weekCalendarHeader');
    var weekBody = document.getElementById('weekCalendarBody');
    var weekEmpty = document.getElementById('weekCalendarEmpty');

    function getAppointmentTypeId() {
        if (typeSelect) return typeSelect.value;
        var hidden = document.querySelector('input[name="appointment_type_id"]');
        return hidden ? hidden.value : null;
    }

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function truncate(str, max) {
        if (!str) return '';
        return str.length > max ? str.substring(0, max) + '...' : str;
    }

    function fetchWeekEvents(date) {
        if (!weekContainer || !date) return;

        weekContainer.style.display = 'block';
        weekLoading.style.display = 'block';
        weekGrid.style.display = 'none';
        weekEmpty.style.display = 'none';

        fetch('/my/schedule/week-events', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                jsonrpc: '2.0',
                method: 'call',
                params: { selected_date: date },
            }),
        })
        .then(function (resp) { return resp.json(); })
        .then(function (data) {
            weekLoading.style.display = 'none';
            var result = data.result || {};
            var events = result.events || [];
            var weekDays = result.week_days || [];

            if (result.error || !weekDays.length) {
                weekEmpty.style.display = 'block';
                return;
            }

            renderWeekCalendar(weekDays, events, date);
        })
        .catch(function () {
            weekLoading.style.display = 'none';
            weekEmpty.textContent = 'Failed to load calendar. Please try again.';
            weekEmpty.style.display = 'block';
        });
    }

    function renderWeekCalendar(weekDays, events, selectedDate) {
        weekHeader.innerHTML = '';
        weekBody.innerHTML = '';

        var eventsByDate = {};
        events.forEach(function (ev) {
            if (!eventsByDate[ev.date]) eventsByDate[ev.date] = [];
            eventsByDate[ev.date].push(ev);
        });

        var hasAnyEvents = events.length > 0;

        weekDays.forEach(function (day) {
            var isSelected = day.date === selectedDate;
            var isWeekend = day.label === 'Sat' || day.label === 'Sun';
            var dayEvents = eventsByDate[day.date] || [];

            var headerCell = document.createElement('div');
            headerCell.className = 'text-center py-2 flex-fill';
            headerCell.style.cssText = 'min-width: 0; font-size: 12px; border-right: 1px solid #dee2e6;';
            if (isSelected) {
                headerCell.style.backgroundColor = '#e8f4fd';
            }
            if (isWeekend) {
                headerCell.style.opacity = '0.6';
            }

            var labelEl = document.createElement('div');
            labelEl.className = 'fw-semibold text-muted';
            labelEl.textContent = day.label;

            var numEl = document.createElement('div');
            numEl.className = isSelected ? 'fw-bold text-primary' : 'fw-semibold';
            numEl.style.fontSize = '14px';
            numEl.textContent = day.day_num;

            headerCell.appendChild(labelEl);
            headerCell.appendChild(numEl);
            weekHeader.appendChild(headerCell);

            var bodyCell = document.createElement('div');
            bodyCell.className = 'flex-fill p-1';
            bodyCell.style.cssText = 'min-width: 0; min-height: 70px; border-right: 1px solid #dee2e6; overflow: hidden;';
            if (isSelected) {
                bodyCell.style.backgroundColor = '#f0f8ff';
            }

            if (dayEvents.length) {
                dayEvents.forEach(function (ev) {
                    var card = document.createElement('div');
                    card.className = 'mb-1 px-1 py-1 rounded';
                    card.style.cssText = 'font-size: 11px; background: #eef6ff; border-left: 3px solid #3a8fb7; overflow: hidden; cursor: default;';
                    card.title = ev.start_time + ' - ' + ev.end_time + '\n' + ev.name + (ev.location ? '\n' + ev.location : '');

                    var timeEl = document.createElement('div');
                    timeEl.className = 'fw-semibold text-primary';
                    timeEl.style.fontSize = '10px';
                    timeEl.textContent = ev.start_time;

                    var nameEl = document.createElement('div');
                    nameEl.className = 'text-truncate';
                    nameEl.style.fontSize = '10px';
                    nameEl.textContent = truncate(ev.name, 18);

                    card.appendChild(timeEl);
                    card.appendChild(nameEl);
                    bodyCell.appendChild(card);
                });
            }

            weekBody.appendChild(bodyCell);
        });

        if (hasAnyEvents) {
            weekGrid.style.display = 'block';
            weekEmpty.style.display = 'none';
        } else {
            weekGrid.style.display = 'none';
            weekEmpty.style.display = 'block';
        }
    }

    function fetchSlots(date) {
        var typeId = getAppointmentTypeId();
        if (!typeId || !date) return;

        slotsContainer.style.display = 'block';
        slotsLoading.style.display = 'block';
        slotsGrid.innerHTML = '';
        noSlots.style.display = 'none';
        slotDatetimeInput.value = '';
        if (submitBtn) submitBtn.disabled = true;
        selectedSlotBtn = null;

        fetch('/my/schedule/available-slots', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                method: 'call',
                params: {
                    appointment_type_id: parseInt(typeId),
                    selected_date: date,
                },
            }),
        })
        .then(function (resp) { return resp.json(); })
        .then(function (data) {
            slotsLoading.style.display = 'none';
            var result = data.result || {};
            var slots = result.slots || [];

            if (result.error) {
                noSlots.textContent = result.error;
                noSlots.style.display = 'block';
                return;
            }

            if (!slots.length) {
                noSlots.style.display = 'block';
                return;
            }

            var morningSlots = [];
            var afternoonSlots = [];
            slots.forEach(function (slot) {
                var hour = parseInt(slot.start_hour);
                if (isNaN(hour)) {
                    var match = slot.start_hour.match(/(\d+)/);
                    hour = match ? parseInt(match[1]) : 0;
                    if (slot.start_hour.toLowerCase().indexOf('pm') > -1 && hour !== 12) hour += 12;
                    if (slot.start_hour.toLowerCase().indexOf('am') > -1 && hour === 12) hour = 0;
                }
                if (hour < 12) {
                    morningSlots.push(slot);
                } else {
                    afternoonSlots.push(slot);
                }
            });

            function renderGroup(label, icon, groupSlots) {
                if (!groupSlots.length) return;
                var header = document.createElement('div');
                header.className = 'w-100 mt-2 mb-1';
                header.innerHTML = '<small class="text-muted fw-semibold"><i class="fa ' + icon + ' me-1"></i>' + label + '</small>';
                slotsGrid.appendChild(header);

                groupSlots.forEach(function (slot) {
                    var btn = document.createElement('button');
                    btn.type = 'button';
                    btn.className = 'btn btn-outline-primary btn-sm slot-btn';
                    btn.style.cssText = 'min-width: 100px; border-radius: 8px; padding: 8px 14px;';
                    btn.textContent = slot.start_hour;
                    btn.dataset.datetime = slot.datetime;
                    btn.dataset.duration = slot.duration;
                    btn.addEventListener('click', function () {
                        if (selectedSlotBtn) {
                            selectedSlotBtn.classList.remove('btn-primary');
                            selectedSlotBtn.classList.add('btn-outline-primary');
                        }
                        btn.classList.remove('btn-outline-primary');
                        btn.classList.add('btn-primary');
                        selectedSlotBtn = btn;
                        slotDatetimeInput.value = slot.datetime;
                        slotDurationInput.value = slot.duration;
                        if (submitBtn) submitBtn.disabled = false;
                    });
                    slotsGrid.appendChild(btn);
                });
            }

            renderGroup('Morning', 'fa-sun-o', morningSlots);
            renderGroup('Afternoon', 'fa-cloud', afternoonSlots);
        })
        .catch(function (err) {
            slotsLoading.style.display = 'none';
            noSlots.textContent = 'Failed to load slots. Please try again.';
            noSlots.style.display = 'block';
        });
    }

    if (dateInput) {
        dateInput.addEventListener('change', function () {
            var val = this.value;
            fetchWeekEvents(val);
            fetchSlots(val);
        });
    }

    if (typeSelect) {
        typeSelect.addEventListener('change', function () {
            if (dateInput && dateInput.value) {
                fetchSlots(dateInput.value);
            }
        });
    }

    var bookingForm = document.getElementById('bookingForm');
    if (bookingForm) {
        bookingForm.addEventListener('submit', function (e) {
            if (!slotDatetimeInput || !slotDatetimeInput.value) {
                e.preventDefault();
                alert('Please select a time slot before booking.');
                return false;
            }
            var clientName = bookingForm.querySelector('input[name="client_name"]');
            if (!clientName || !clientName.value.trim()) {
                e.preventDefault();
                alert('Please enter the client name.');
                return false;
            }
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin me-1"></i> Booking...';
            }
        });
    }

    window.initScheduleAddressAutocomplete = function () {
        var streetInput = document.getElementById('clientStreet');
        if (!streetInput) return;

        var autocomplete = new google.maps.places.Autocomplete(streetInput, {
            componentRestrictions: { country: 'ca' },
            types: ['address'],
        });

        autocomplete.addListener('place_changed', function () {
            var place = autocomplete.getPlace();
            if (!place.address_components) return;

            var streetNumber = '';
            var streetName = '';
            var city = '';
            var province = '';
            var postalCode = '';

            for (var i = 0; i < place.address_components.length; i++) {
                var component = place.address_components[i];
                var types = component.types;

                if (types.indexOf('street_number') > -1) {
                    streetNumber = component.long_name;
                } else if (types.indexOf('route') > -1) {
                    streetName = component.long_name;
                } else if (types.indexOf('locality') > -1) {
                    city = component.long_name;
                } else if (types.indexOf('administrative_area_level_1') > -1) {
                    province = component.long_name;
                } else if (types.indexOf('postal_code') > -1) {
                    postalCode = component.long_name;
                }
            }

            streetInput.value = (streetNumber + ' ' + streetName).trim();
            var cityInput = document.getElementById('clientCity');
            if (cityInput) cityInput.value = city;
            var provInput = document.getElementById('clientProvince');
            if (provInput) provInput.value = province;
            var postalInput = document.getElementById('clientPostal');
            if (postalInput) postalInput.value = postalCode;
        });
    };

})();
