/**
 * Yatoon Manage Booking - Customer self-service JS
 * Handles cancel and reschedule interactions on the [yatoon_manage_booking] page.
 */
(function ($) {
    'use strict';

    var cfg     = window.yatoonManage || {};
    var ajaxurl = cfg.ajaxurl || '';
    var nonce   = cfg.nonce   || '';
    var token   = cfg.token   || '';
    var i18n    = cfg.i18n    || {};

    var $actions         = $('#yatoon-manage-actions');
    var $reschedulePanel = $('#yatoon-reschedule-panel');
    var $manageMSG       = $('#yatoon-manage-msg');
    var $slotsMSG        = $('#yatoon-slots-msg');
    var $slotsWrap       = $('#yatoon-slots-wrap');
    var $slotsList       = $('#yatoon-slots-list');
    var $confirmRow      = $('#yatoon-reschedule-confirm-row');

    var selectedSlot = null;
    var overlayInjected = false;

    function ensureOverlay() {
        if (overlayInjected) return;

        $('body').append(
            '<div id="yatoon-manage-overlay" style="display:none;position:fixed;inset:0;background:rgba(17,24,39,.55);z-index:99999;padding:20px;box-sizing:border-box;align-items:center;justify-content:center;">' +
                '<div style="width:100%;max-width:420px;background:#fff;border-radius:18px;box-shadow:0 25px 80px rgba(0,0,0,.25);overflow:hidden;">' +
                    '<div style="padding:22px 22px 18px;">' +
                        '<h3 id="yatoon-manage-overlay-title" style="margin:0 0 10px;font-size:20px;line-height:1.2;color:#111827;"></h3>' +
                        '<div id="yatoon-manage-overlay-body" style="font-size:15px;line-height:1.6;color:#4b5563;"></div>' +
                    '</div>' +
                    '<div id="yatoon-manage-overlay-actions" style="display:flex;gap:10px;justify-content:flex-end;padding:0 22px 22px;"></div>' +
                '</div>' +
            '</div>'
        );

        $(document).on('click', '#yatoon-manage-overlay', function (e) {
            if (e.target === this) {
                hideOverlay();
            }
        });

        overlayInjected = true;
    }

    function hideOverlay() {
        $('#yatoon-manage-overlay').hide();
        $('#yatoon-manage-overlay-actions').empty();
    }

    function showDialog(opts) {
        ensureOverlay();

        var options = opts || {};
        var $overlay = $('#yatoon-manage-overlay');
        var $title = $('#yatoon-manage-overlay-title');
        var $body = $('#yatoon-manage-overlay-body');
        var $actions = $('#yatoon-manage-overlay-actions');
        var buttons = options.buttons || [];

        $title.text(options.title || '');
        $body.html(options.body || '');
        $actions.empty();

        $.each(buttons, function (_, button) {
            var $btn = $('<button type="button">')
                .text(button.label || 'OK')
                .attr('style', button.style || 'padding:11px 16px;border-radius:10px;border:none;background:#ec4899;color:#fff;font-weight:600;cursor:pointer;')
                .on('click', function () {
                    hideOverlay();
                    if (typeof button.onClick === 'function') {
                        button.onClick();
                    }
                });
            $actions.append($btn);
        });

        $overlay.css('display', 'flex');
    }

    function showInfo(title, body) {
        showDialog({
            title: title,
            body: body,
            buttons: [
                {
                    label: i18n.ok || 'OK'
                }
            ]
        });
    }

    function showAfterCancelActions() {
        $('#yatoon-after-cancel-actions').remove();
        var bookUrl = cfg.bookUrl || '/';
        var $wrap = $('<div id="yatoon-after-cancel-actions" class="yatoon-after-cancel-actions">');
        $('<a class="yatoon-btn yatoon-btn-primary">')
            .attr('href', bookUrl)
            .text('Book another appointment')
            .appendTo($wrap);
        $('<button type="button" class="yatoon-btn yatoon-btn-ghost">')
            .text('View updated status')
            .on('click', function () {
                window.location.reload();
            })
            .appendTo($wrap);
        $manageMSG.after($wrap);
    }

    function confirmAction(title, body, onConfirm) {
        showDialog({
            title: title,
            body: body,
            buttons: [
                {
                    label: i18n.cancel || 'Keep Appointment',
                    style: 'padding:11px 16px;border-radius:10px;border:1px solid #d1d5db;background:#fff;color:#374151;font-weight:600;cursor:pointer;'
                },
                {
                    label: i18n.confirm || 'Confirm',
                    style: 'padding:11px 16px;border-radius:10px;border:none;background:#ec4899;color:#fff;font-weight:600;cursor:pointer;',
                    onClick: onConfirm
                }
            ]
        });
    }

    // ── Cancel ────────────────────────────────────────────────────────────────
    $('#yatoon-cancel-btn').on('click', function () {
        var $btn = $(this);
        var originalText = $btn.text();
        var $choices = $('.yatoon-cancel-item');
        var selectedIds = [];

        $choices.filter(':checked').each(function () {
            selectedIds.push($(this).val());
        });

        if ($choices.length && !selectedIds.length) {
            showInfo(
                i18n.cancel_title || 'Cancel appointment?',
                'Please select at least one service to cancel.'
            );
            return;
        }

        var totalChoices = $choices.length;
        var isPartialCancel = totalChoices && selectedIds.length < totalChoices;
        var confirmBody = i18n.cancel_confirm || 'Are you sure you want to cancel this appointment? This cannot be undone.';

        if (totalChoices) {
            confirmBody = isPartialCancel
                ? 'Cancel the selected ' + selectedIds.length + ' item(s)? The remaining item(s) will stay booked.'
                : 'Cancel all selected appointment items? This cannot be undone.';
        }

        confirmAction(
            i18n.cancel_title || 'Cancel appointment?',
            confirmBody,
            function () {
                $btn.prop('disabled', true).text(i18n.loading || 'Processing...');

                $.post(ajaxurl, {
                    action: 'yatoon_customer_cancel',
                    nonce:  nonce,
                    token:  token,
                    booking_ids: totalChoices ? JSON.stringify(selectedIds) : ''
                }, function (resp) {
                    if (resp.success) {
                        showMsg($manageMSG, resp.data.message, 'success');
                        if (isPartialCancel) {
                            window.setTimeout(function () {
                                window.location.reload();
                            }, 900);
                        } else {
                            $actions.hide();
                            $reschedulePanel.hide();
                            showAfterCancelActions();
                        }
                    } else {
                        showMsg($manageMSG, resp.data.message, 'error');
                        $btn.prop('disabled', false).text(originalText);
                    }
                }).fail(function () {
                    showMsg($manageMSG, 'Request failed. Please try again.', 'error');
                    $btn.prop('disabled', false).text(originalText);
                });
            }
        );
    });

    // -- Open reschedule panel ─────────────────────────────────────────────────
    $('#yatoon-reschedule-btn').on('click', function () {
        $reschedulePanel.slideDown(200);
        $(this).hide();
    });

    $('#yatoon-cancel-reschedule-btn').on('click', function () {
        $reschedulePanel.slideUp(200);
        $('#yatoon-reschedule-btn').show();
        resetSlots();
    });

    // ── Load available slots ──────────────────────────────────────────────────
    $('#yatoon-load-slots-btn').on('click', function () {
        var date = $('#yatoon-reschedule-date').val();
        if (!date) {
            showInfo(
                i18n.date_required_title || 'Select a date',
                i18n.date_required || 'Please choose a date before loading available times.'
            );
            return;
        }

        var $btn = $(this).prop('disabled', true).text(i18n.loading || 'Loading...');
        resetSlots();

        $.post(ajaxurl, {
            action: 'yatoon_get_reschedule_slots',
            nonce:  nonce,
            token:  token,
            date:   date,
        }, function (resp) {
            $btn.prop('disabled', false).text('Show Available Times');
            if (resp.success && resp.data.slots && resp.data.slots.length) {
                renderSlots(resp.data.slots);
            } else {
                var msg = (resp.data && resp.data.message) ? resp.data.message : 'No times available on this date.';
                showMsg($slotsMSG, msg, 'info');
                $slotsMSG.show();
            }
        }).fail(function () {
            $btn.prop('disabled', false).text('Show Available Times');
            showMsg($slotsMSG, 'Request failed. Please try again.', 'error');
            $slotsMSG.show();
        });
    });

    function renderSlots(slots) {
        $slotsList.empty();
        selectedSlot = null;
        $confirmRow.hide();

        $.each(slots, function (i, slot) {
            var $chip = $('<button type="button" class="yatoon-slot-chip">')
                .text(slot.display || slot.time)
                .attr('data-time', slot.datetime)
                .on('click', function () {
                    $('.yatoon-slot-chip').removeClass('selected');
                    $(this).addClass('selected');
                    selectedSlot = slot.datetime;
                    $confirmRow.show();
                });
            $slotsList.append($chip);
        });

        $slotsWrap.show();
    }

    function resetSlots() {
        $slotsList.empty();
        $slotsWrap.hide();
        $confirmRow.hide();
        $slotsMSG.hide();
        selectedSlot = null;
    }

    // ── Confirm reschedule ────────────────────────────────────────────────────
    $('#yatoon-confirm-reschedule-btn').on('click', function () {
        if (!selectedSlot) {
            showInfo(
                i18n.slot_required_title || 'Select a time',
                i18n.select_slot || 'Please select a new time slot.'
            );
            return;
        }

        var $btn = $(this);

        confirmAction(
            i18n.reschedule_title || 'Confirm reschedule?',
            i18n.reschedule_confirm || 'Confirm reschedule to the selected time?',
            function () {
                $btn.prop('disabled', true).text(i18n.loading || 'Processing...');

                $.post(ajaxurl, {
                    action:   'yatoon_customer_reschedule',
                    nonce:    nonce,
                    token:    token,
                    new_time: selectedSlot,
                }, function (resp) {
                    if (resp.success) {
                        $actions.hide();
                        $reschedulePanel.hide();
                        showMsg($manageMSG, resp.data.message, 'success');
                        window.setTimeout(function () {
                            window.location.reload();
                        }, 600);
                    } else {
                        showMsg($manageMSG, resp.data.message, 'error');
                        $btn.prop('disabled', false).text('Yes Confirm Reschedule');
                        resetSlots();
                    }
                }).fail(function () {
                    showMsg($manageMSG, 'Request failed. Please try again.', 'error');
                    $btn.prop('disabled', false).text('Yes Confirm Reschedule');
                });
            }
        );
    });

    // ── Helpers ───────────────────────────────────────────────────────────────
    function showMsg($el, msg, type) {
        $el.removeClass('yatoon-notice-success yatoon-notice-error yatoon-notice-info yatoon-notice-warning')
           .addClass('yatoon-notice-' + type)
           .html(msg)
           .show();
    }

})(jQuery);
