/**
 * Calendar screen (Yatoon > Calendar).
 *
 * Lifted out of admin/views/calendar.php. The booking detail map, the nonce
 * and the current date arrive on yatoonCalendarData, localized from the view
 * once it has computed them -- the same pattern the Reports screen uses.
 */
/* global jQuery, ajaxurl, yatoonCalendarData */
jQuery(function($){
    const nonce = yatoonCalendarData.nonce;

    function showCardMessage($card, message, isError) {
        const $msg = $card.find('.yc-reschedule-msg').first();
        $msg.text(message || '').toggleClass('is-error', !!isError);
    }

    function moveBooking($card, staffId, startAt, notifyMethod) {
        $card.addClass('is-saving');
        showCardMessage($card, 'Saving move...', false);
        return $.post(ajaxurl, {
            action: 'yatoon_admin_reschedule_booking',
            nonce,
            booking_id: $card.data('booking-id'),
            staff_id: staffId,
            start_at: startAt,
            notify_method: notifyMethod || 'none'
        }, function(res) {
            if (!res.success) {
                const msg = res.data && res.data.message ? res.data.message : 'Could not reschedule booking.';
                showCardMessage($card, msg, true);
                return;
            }
            location.href = yatoonCalendarData.dateBaseUrl + encodeURIComponent(res.data.date || yatoonCalendarData.date);
        }).fail(function() {
            showCardMessage($card, 'Network error while rescheduling.', true);
        }).always(function() {
            $card.removeClass('is-saving is-dragging');
            $('.yc-col').removeClass('is-drop-target');
        });
    }

    function loadRescheduleSlots($card) {
        const $panel = $card.find('.yc-reschedule-panel');
        const date = $panel.find('.yc-reschedule-date').val();
        const staffId = $card.data('staff-id') || $card.closest('.yc-col').data('staff-id');
        const $slots = $panel.find('.yc-slot-list');
        const $save = $panel.find('.yc-reschedule-save');

        $save.prop('disabled', true).removeData('start-at');
        $slots.html('<span class="description">Loading times...</span>');
        showCardMessage($card, '', false);

        $.post(ajaxurl, {
            action: 'yatoon_get_admin_reschedule_slots',
            nonce,
            booking_id: $card.data('booking-id'),
            staff_id: staffId,
            date
        }, function(res) {
            if (!res.success) {
                const msg = res.data && res.data.message ? res.data.message : 'Could not load times.';
                $slots.html('<span class="description">' + msg + '</span>');
                return;
            }
            const slots = (res.data && res.data.slots) ? res.data.slots : [];
            if (!slots.length) {
                $slots.html('<span class="description">No available times for this date.</span>');
                return;
            }
            $slots.html(slots.map(function(slot) {
                return '<button type="button" class="yc-slot-chip" data-start-at="' + String(slot.datetime || '').replace(/"/g, '&quot;') + '">' + String(slot.display || '') + '</button>';
            }).join(''));
        }).fail(function() {
            $slots.html('<span class="description">Network error while loading times.</span>');
        });
    }

    let draggedCard = null;
    $(document).on('dragstart', '.yc-card[draggable="true"]', function(e) {
        draggedCard = this;
        $(this).addClass('is-dragging');
        e.originalEvent.dataTransfer.effectAllowed = 'move';
        e.originalEvent.dataTransfer.setData('text/plain', $(this).data('booking-id'));
    });

    $(document).on('dragend', '.yc-card[draggable="true"]', function() {
        $(this).removeClass('is-dragging');
        $('.yc-col').removeClass('is-drop-target');
        draggedCard = null;
    });

    $(document).on('dragover', '.yc-col', function(e) {
        if (!draggedCard) return;
        e.preventDefault();
        $('.yc-col').removeClass('is-drop-target');
        $(this).addClass('is-drop-target');
    });

    $(document).on('drop', '.yc-col', function(e) {
        if (!draggedCard) return;
        e.preventDefault();
        const $card = $(draggedCard);
        const staffId = $(this).data('staff-id');
        if (!staffId || Number(staffId) === Number($card.data('staff-id'))) return;
        const staffName = $(this).data('staff-name') || 'this staff member';
        if (!window.confirm('Move this booking to ' + staffName + ' at the same time?')) return;
        window.yatoonPromptNotifyMethod({
            title: 'Notify the customer about this move?'
        }, function(method) {
            moveBooking($card, staffId, $card.data('start-time'), method);
        });
    });

    let touchDrag = null;
    $(document).on('pointerdown', '.yc-card[draggable="true"]', function(e) {
        if (e.pointerType === 'mouse' || $(e.target).closest('select,button,input,a,label').length) return;
        touchDrag = { card: this, pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, active: false };
    });
    $(document).on('pointermove', function(e) {
        if (!touchDrag || touchDrag.pointerId !== e.pointerId) return;
        const moved = Math.abs(e.clientX - touchDrag.startX) + Math.abs(e.clientY - touchDrag.startY);
        if (moved > 18) {
            touchDrag.active = true;
            $(touchDrag.card).addClass('is-dragging');
            const el = document.elementFromPoint(e.clientX, e.clientY);
            $('.yc-col').removeClass('is-drop-target');
            $(el).closest('.yc-col').addClass('is-drop-target');
        }
    });
    $(document).on('pointerup pointercancel', function(e) {
        if (!touchDrag || touchDrag.pointerId !== e.pointerId) return;
        const $card = $(touchDrag.card);
        if (touchDrag.active) {
            const el = document.elementFromPoint(e.clientX, e.clientY);
            const $col = $(el).closest('.yc-col');
            const staffId = $col.data('staff-id');
            if (staffId && Number(staffId) !== Number($card.data('staff-id')) && window.confirm('Move this booking to ' + ($col.data('staff-name') || 'this staff member') + ' at the same time?')) {
                window.yatoonPromptNotifyMethod({
                    title: 'Notify the customer about this move?'
                }, function(method) {
                    moveBooking($card, staffId, $card.data('start-time'), method);
                });
            }
        }
        $card.removeClass('is-dragging');
        $('.yc-col').removeClass('is-drop-target');
        touchDrag = null;
    });

    $(document).on('click', '.yc-reschedule-toggle', function() {
        const $card = $(this).closest('.yc-card');
        const $panel = $card.find('.yc-reschedule-panel');
        $('.yc-reschedule-panel').not($panel).removeClass('is-open');
        $panel.toggleClass('is-open');
        if ($panel.hasClass('is-open')) loadRescheduleSlots($card);
    });

    $(document).on('change', '.yc-reschedule-date', function() {
        loadRescheduleSlots($(this).closest('.yc-card'));
    });

    $(document).on('click', '.yc-slot-chip', function() {
        const $chip = $(this);
        const $panel = $chip.closest('.yc-reschedule-panel');
        $panel.find('.yc-slot-chip').removeClass('is-selected');
        $chip.addClass('is-selected');
        $panel.find('.yc-reschedule-save').prop('disabled', false).data('start-at', $chip.data('start-at'));
    });

    $(document).on('click', '.yc-reschedule-save', function() {
        const $btn = $(this);
        const $card = $btn.closest('.yc-card');
        const staffId = $card.data('staff-id') || $card.closest('.yc-col').data('staff-id');
        const startAt = $btn.data('start-at');
        if (!startAt) return;
        window.yatoonPromptNotifyMethod({
            title: 'Notify the customer about this move?'
        }, function(method) {
            moveBooking($card, staffId, startAt, method);
        });
    });

    $(document).on('change', '.yc-status-select', function(){
        const $sel = $(this);
        $.post(ajaxurl, {
            action: 'yatoon_update_booking_status',
            nonce,
            booking_id: $sel.data('booking-id'),
            status: $sel.val()
        }, function(res){
            if (!res.success) {
                alert('Could not update booking status.');
            } else {
                const $card = $sel.closest('.yc-card');
                $card.removeClass('yc-status-pending yc-status-confirmed yc-status-completed yc-status-no_show yc-status-cancelled')
                    .addClass('yc-status-' + $sel.val());
            }
        });
    });

    $(document).on('change', '.yc-payment-select', function(){
        const $sel = $(this);
        const note = $sel.val() === 'paid_square_pos' ? 'Paid in Square POS' : '';
        $.post(ajaxurl, {
            action: 'yatoon_update_payment_status',
            nonce,
            booking_id: $sel.data('booking-id'),
            payment_status: $sel.val(),
            payment_note: note
        }, function(res){
            if (!res.success) {
                alert('Could not update payment status.');
            }
        });
    });

    $(document).on('click', '.yc-no-show-fee', function(){
        const $btn = $(this);
        const status = $btn.data('status');
        const note = status === 'no_show_fee_charged' ? 'No-show fee charged in Square' : 'No-show fee waived';
        $btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'yatoon_update_payment_status',
            nonce,
            booking_id: $btn.data('booking-id'),
            payment_status: status,
            payment_note: note
        }, function(res){
            if (!res.success) {
                alert('Could not update no-show fee status.');
            } else {
                $btn.closest('.yc-card').find('.yc-payment-select').val(status);
            }
        }).always(function(){
            $btn.prop('disabled', false);
        });
    });

    // ── Staff column toggle ───────────────────────────────────────────────────
    $(document).on('change', '.yc-staff-toggle', function() {
        const hiddenIds = [];
        $('.yc-staff-toggle').each(function() {
            if (!$(this).is(':checked')) hiddenIds.push($(this).data('staff-id'));
        });
        $.post(ajaxurl, {
            action: 'yatoon_save_calendar_staff_filter',
            nonce,
            hidden_staff: hiddenIds.join(',')
        }, function(res) {
            if (res.success) location.reload();
        });
    });

    $(document).on('click', '[data-calendar-staff-target]', function() {
        const staffId = $(this).data('calendar-staff-target');
        const $grid = $('.yc-grid');
        const $target = $('.yc-col[data-staff-id="' + staffId + '"]').first();
        if (!$grid.length || !$target.length) return;
        $('[data-calendar-staff-target]').removeClass('is-active');
        $(this).addClass('is-active');
        $target.get(0).scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
    $('[data-calendar-staff-target]').first().addClass('is-active');

    // ── Booking detail modal ─────────────────────────────────────────────────
    function ycEscapeHTML(str) {
        return String(str == null ? '' : str).replace(/[&<>"']/g, function(m) {
            return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m];
        });
    }

    function ycStatusLabel(status) {
        const labels = { pending: 'Pending', confirmed: 'Confirmed', completed: 'Completed', no_show: 'No-show', cancelled: 'Cancelled' };
        return labels[status] || status;
    }

    $(document).on('click', '.yc-view-details', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const id = $(this).data('booking-id');
        const b = ((yatoonCalendarData && yatoonCalendarData.bookings) || {})[id];
        if (!b) return;
        let html = '';
        html += '<h2>' + ycEscapeHTML(b.customer_name || 'Appointment') + '</h2>';
        html += '<div class="yc-detail-row"><strong>Service</strong><span>' + ycEscapeHTML(b.service_name) + ' - $' + ycEscapeHTML(b.total_price) + '</span></div>';
        html += '<div class="yc-detail-row"><strong>Staff</strong><span>' + ycEscapeHTML(b.staff_name) + '</span></div>';
        html += '<div class="yc-detail-row"><strong>Time</strong><span>' + ycEscapeHTML(b.start_time) + ' - ' + ycEscapeHTML(b.end_time) + '</span></div>';
        html += '<div class="yc-detail-row"><strong>Status</strong><span>' + ycEscapeHTML(ycStatusLabel(b.status)) + '</span></div>';
        html += '<div class="yc-detail-row"><strong>Payment</strong><span>' + ycEscapeHTML(ycStatusLabel(b.payment_status)) + (b.payment_note ? ' (' + ycEscapeHTML(b.payment_note) + ')' : '') + '</span></div>';
        if (b.customer_phone) html += '<div class="yc-detail-row"><strong>Phone</strong><span>' + ycEscapeHTML(b.customer_phone) + '</span></div>';
        if (b.customer_email) html += '<div class="yc-detail-row"><strong>Email</strong><span>' + ycEscapeHTML(b.customer_email) + '</span></div>';
        if (b.consent_accepted) html += '<div class="yc-detail-row"><strong>Consent</strong><span>Signed</span></div>';
        if (b.policy_acknowledged) html += '<div class="yc-detail-row"><strong>Policy</strong><span>Acknowledged</span></div>';
        if (b.notes) html += '<div class="yc-detail-note"><strong>Appointment note</strong><p>' + ycEscapeHTML(b.notes) + '</p></div>';
        if (b.design_image_url) {
            html += '<div class="yc-detail-design"><strong>Design reference</strong><br>' +
                '<a href="' + ycEscapeHTML(b.design_image_url) + '" target="_blank" rel="noopener"><img src="' + ycEscapeHTML(b.design_image_url) + '" alt=""></a></div>';
        }
        $('#yc-detail-body').html(html);
        $('#yc-detail-overlay').addClass('is-open').attr('aria-hidden', 'false');
    });

    function ycCloseDetail() {
        $('#yc-detail-overlay').removeClass('is-open').attr('aria-hidden', 'true');
    }
    $('#yc-detail-close').on('click', ycCloseDetail);
    $('#yc-detail-overlay').on('click', function(e) {
        if (e.target === this) ycCloseDetail();
    });
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') ycCloseDetail();
    });

});
