/* Yatoon Customer Portal - Frontend JS */
(function ($) {
    'use strict';

    if (typeof yatoonPortal === 'undefined') return;

    const cfg   = yatoonPortal;
    const $wrap = $('#sbs-portal-wrap');
    if (!$wrap.length) return;

    /* Apply brand colors */
    document.documentElement.style.setProperty('--portal-primary', cfg.primaryColor);
    if (cfg.bannerBg)   document.documentElement.style.setProperty('--portal-banner-bg',   cfg.bannerBg);
    if (cfg.bannerText) document.documentElement.style.setProperty('--portal-banner-text', cfg.bannerText);

    /* ── State ────────────────────────────────────────────── */
    let currentCustomer = null;
    let currentTab      = 'upcoming';
    let allData         = null;        // cached response from get_bookings
    let rescheduleBookingId = null;

    /* ── Helpers ──────────────────────────────────────────── */
    function ajax(action, data, done, fail) {
        $.post(cfg.ajaxurl, Object.assign({ action, nonce: cfg.nonce }, data))
            .done(function (r) {
                if (r.success) done(r.data);
                else (fail || defaultFail)(r.data);
            })
            .fail(function () { (fail || defaultFail)({ message: 'Request failed' }); });
    }

    function defaultFail(d) {
        showMsg($wrap.find('.sbs-portal-msg'), d && d.message ? d.message : 'Something went wrong.', 'error');
    }

    function showMsg($el, msg, type) {
        $el.text(msg).removeClass('success error').addClass(type || '');
    }

    function loading(show) {
        $wrap.find('.sbs-portal-loading').toggle(show);
    }

    function parseMonth(dateStr) {
        // dateStr e.g. "Tuesday, February 24, 2026"
        const parts = dateStr.split(' ');
        return { month: parts[1].slice(0, 3).toUpperCase(), day: parseInt(parts[2]) };
    }

    function statusClass(status) {
        const map = {
            ACCEPTED: 'confirmed', PENDING: 'pending',
            CANCELLED_BY_CUSTOMER: 'cancelled', CANCELLED_BY_SELLER: 'cancelled',
            DECLINED: 'cancelled', NO_SHOW: 'no_show',
            confirmed: 'confirmed', pending: 'pending', completed: 'confirmed',
            cancelled: 'cancelled', no_show: 'no_show'
        };
        return 'sbs-status-' + (map[status] || 'pending');
    }

    function moneyLabel(value) {
        return value || '-';
    }

    /* ══════════════════════════════════════════════════════
       RENDER: LOGIN FORM (step 1 - phone)
    ══════════════════════════════════════════════════════ */
    function renderPhoneStep() {
        $wrap.find('#sbs-portal-inner').html(`
            <div class="sbs-portal-card sbs-portal-login">
                <div class="sbs-portal-login-icon">💅</div>
                <h2>${cfg.strings.loginTitle}</h2>
                ${cfg.strings.loginBrand ? `<p class="brand-subtitle">${escHtml(cfg.strings.loginBrand)}</p>` : ''}
                <p class="subtitle">${cfg.strings.loginSubtitle}</p>
                <input type="tel" id="sbs-portal-phone" class="sbs-portal-input"
                       placeholder="${cfg.strings.phonePlaceholder}" autocomplete="tel" inputmode="numeric">
                <button id="sbs-portal-send-otp" class="sbs-portal-btn">${cfg.strings.sendCode}</button>
                <p class="sbs-portal-msg" id="sbs-portal-phone-msg"></p>
            </div>
        `);

        $('#sbs-portal-phone').on('keydown', function (e) {
            if (e.key === 'Enter') $('#sbs-portal-send-otp').trigger('click');
        });

        $('#sbs-portal-send-otp').on('click', function () {
            const phone = $('#sbs-portal-phone').val().trim().replace(/\D/g, '');
            if (!phone || phone.length < 10) { showMsg($('#sbs-portal-phone-msg'), 'Please enter a valid phone number.', 'error'); return; }
            const $btn = $(this).prop('disabled', true).text(cfg.strings.sending);
            showMsg($('#sbs-portal-phone-msg'), '', '');

            ajax('yatoon_portal_send_otp', { phone }, function (data) {
                $btn.prop('disabled', false).text(cfg.strings.sendCode);
                renderCodeStep(phone, data && data.masked_email ? data.masked_email : null);
            }, function (d) {
                $btn.prop('disabled', false).text(cfg.strings.sendCode);
                showMsg($('#sbs-portal-phone-msg'), d && d.message ? d.message : 'Error', 'error');
            });
        });
    }

    /* ══════════════════════════════════════════════════════
       RENDER: CODE ENTRY (step 2)
    ══════════════════════════════════════════════════════ */
    function renderCodeStep(phone, maskedEmail) {
        const hint = maskedEmail ? maskedEmail : phone;
        $wrap.find('#sbs-portal-inner').html(`
            <div class="sbs-portal-card sbs-portal-login">
                <div class="sbs-portal-login-icon">📧</div>
                <h2>${cfg.strings.loginTitle}</h2>
                <p class="subtitle">${cfg.strings.codeSent}<br>
                    <small style="color:#9ca3af">${hint}</small>
                </p>
                <input type="text" id="sbs-portal-code" class="sbs-portal-input"
                       placeholder="${cfg.strings.codePlaceholder}" maxlength="6"
                       inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code">
                <button id="sbs-portal-verify" class="sbs-portal-btn">${cfg.strings.verify}</button>
                <p class="sbs-portal-msg" id="sbs-portal-code-msg"></p>
                <p style="text-align:center;margin-top:12px;">
                    <button class="sbs-portal-link" id="sbs-portal-resend">${cfg.strings.resendCode}</button>
                    &nbsp;·&nbsp;
                    <button class="sbs-portal-link" id="sbs-portal-change-phone">${cfg.strings.changePhone}</button>
                </p>
            </div>
        `);

        $('#sbs-portal-code').focus().on('keydown', function (e) {
            if (e.key === 'Enter') $('#sbs-portal-verify').trigger('click');
        });

        $('#sbs-portal-change-phone').on('click', renderPhoneStep);

        $('#sbs-portal-resend').on('click', function () {
            const $btn = $(this).prop('disabled', true).text('Sending...');
            ajax('yatoon_portal_send_otp', { phone }, function () {
                showMsg($('#sbs-portal-code-msg'), cfg.strings.codeSent, 'success');
                $btn.prop('disabled', false).text(cfg.strings.resendCode);
            }, function (d) {
                $btn.prop('disabled', false).text(cfg.strings.resendCode);
                showMsg($('#sbs-portal-code-msg'), d && d.message ? d.message : 'Error', 'error');
            });
        });

        $('#sbs-portal-verify').on('click', function () {
            const code = $('#sbs-portal-code').val().replace(/\D/g, '');
            if (code.length !== 6) { showMsg($('#sbs-portal-code-msg'), 'Please enter the 6-digit code.', 'error'); return; }
            const $btn = $(this).prop('disabled', true).text(cfg.strings.verifying);

            ajax('yatoon_portal_verify_otp', { code }, function (data) {
                currentCustomer = data.customer;
                loadDashboard();
            }, function (d) {
                $btn.prop('disabled', false).text(cfg.strings.verify);
                showMsg($('#sbs-portal-code-msg'), d && d.message ? d.message : 'Invalid code', 'error');
            });
        });
    }

    /* ══════════════════════════════════════════════════════
       LOAD DASHBOARD DATA
    ══════════════════════════════════════════════════════ */
    function loadDashboard() {
        renderLoading();
        ajax('yatoon_portal_get_bookings', {}, function (data) {
            allData         = data;
            currentCustomer = data.customer;
            currentTab      = data.upcoming && data.upcoming.length ? 'upcoming' : 'past';
            renderDashboard();
        }, function (d) {
            if (d && d.code === 'not_logged_in') { renderPhoneStep(); return; }
            $wrap.find('#sbs-portal-inner').html('<p style="color:red;text-align:center;padding:24px;">' + (d && d.message ? d.message : 'Error loading data.') + '</p>');
        });
    }

    function renderLoading() {
        $wrap.find('#sbs-portal-inner').html('<div class="sbs-portal-loading" style="display:flex;"><span class="sbs-portal-spinner"></span></div>');
    }

    /* ══════════════════════════════════════════════════════
       RENDER: DASHBOARD
    ══════════════════════════════════════════════════════ */
    function renderDashboard() {
        const d    = allData;
        const name = d.customer.name || 'there';
        const next = d.upcoming && d.upcoming.length ? d.upcoming[0] : null;

        const html = `
            <div class="sbs-portal-card">
                <div class="sbs-portal-header">
                    <div>
                        <h2>👋 Hi, ${escHtml(name.split(' ')[0])}!</h2>
                        <div class="greeting">${escHtml(d.customer.email || d.customer.phone)}</div>
                    </div>
                    <button id="sbs-portal-logout-btn" class="sbs-portal-btn-sm sbs-portal-btn-outline"
                            style="color:#6b7280;border-color:#d1d5db;">
                        ${cfg.strings.logout}
                    </button>
                </div>

                <!-- Stats -->
                <div class="sbs-portal-stats">
                    <div class="sbs-portal-stat">
                        <div class="value">${d.visit_count}</div>
                        <div class="label">${cfg.strings.visits}</div>
                    </div>
                    <div class="sbs-portal-stat">
                        <div class="value">${d.upcoming.length}</div>
                        <div class="label">Upcoming</div>
                    </div>
                    <div class="sbs-portal-stat">
                        <div class="value">${escHtml(d.total_spent || '$0.00')}</div>
                        <div class="label">${cfg.strings.totalSpent}</div>
                    </div>
                </div>

                ${next ? `
                <div class="sbs-portal-next">
                    <div>
                        <span class="sbs-portal-kicker">Next appointment</span>
                        <strong>${escHtml(next.services)}</strong>
                        <span>${escHtml(next.date)} · ${escHtml(next.time)}</span>
                    </div>
                    <span class="sbs-status-badge ${statusClass(next.status)}">${escHtml(next.status_label)}</span>
                </div>` : ''}

                <!-- Tabs -->
                <div class="sbs-portal-tabs">
                    <button class="sbs-portal-tab ${currentTab==='upcoming'?'active':''}" data-tab="upcoming">
                        ${cfg.strings.upcoming} (${d.upcoming.length})
                    </button>
                    <button class="sbs-portal-tab ${currentTab==='past'?'active':''}" data-tab="past">
                        ${cfg.strings.past}
                    </button>
                </div>

                <!-- Booking list -->
                <div id="sbs-portal-booking-list">
                    ${renderBookingList(currentTab === 'upcoming' ? d.upcoming : d.past, currentTab)}
                </div>

                <!-- Book new -->
                ${cfg.bookNewUrl ? `
                <div class="sbs-portal-book-new">
                    <a href="${cfg.bookNewUrl}" class="sbs-portal-btn-sm sbs-portal-btn-outline"
                       style="display:inline-block;text-decoration:none;padding:9px 20px;">
                        ✨ ${cfg.strings.bookNew}
                    </a>
                </div>` : ''}
            </div>
        `;

        $wrap.find('#sbs-portal-inner').html(html);
        bindDashboardEvents();
    }

    function renderBookingList(bookings, tab) {
        if (!bookings.length) {
            return `<div class="sbs-portal-empty">
                <div class="icon">${tab === 'upcoming' ? '📅' : '🗓'}</div>
                ${tab === 'upcoming' ? cfg.strings.noUpcoming : cfg.strings.noPast}
            </div>`;
        }

        return bookings.map(function (b) {
            const { month, day } = parseMonth(b.date);
            const statusCls = statusClass(b.status);
            const isCancelled = b.is_cancelled;

            const rebook = cfg.bookNewUrl && tab === 'past' ? `<a class="sbs-portal-btn-sm sbs-portal-btn-outline" href="${cfg.bookNewUrl}" style="text-decoration:none;">${cfg.strings.rebook}</a>` : '';
            const actions = b.can_cancel || b.can_reschedule || rebook ? `
                <div class="sbs-portal-booking-actions">
                    ${b.can_reschedule ? `<button class="sbs-portal-btn-sm" style="background:${cfg.primaryColor};color:#fff;"
                        data-action="reschedule" data-id="${b.id}">${cfg.strings.reschedule}</button>` : ''}
                    ${b.can_cancel ? `<button class="sbs-portal-btn-sm" style="background:#fee2e2;color:#991b1b;"
                        data-action="cancel" data-id="${b.id}">${cfg.strings.cancel}</button>` : ''}
                    ${rebook}
                </div>` : '';

            return `
                <div class="sbs-portal-booking ${b.is_upcoming ? 'upcoming' : 'past'} ${isCancelled ? 'cancelled' : ''}"
                     data-booking-id="${b.id}">
                    <div class="sbs-portal-date-badge">
                        <div class="month">${month}</div>
                        <div class="day">${day}</div>
                    </div>
                    <div class="sbs-portal-booking-info">
                        <div class="service-name">${escHtml(b.services)}</div>
                        <div class="staff-name">👤 ${escHtml(b.staff || 'Any Staff')}</div>
                        <div class="time">⏰ ${escHtml(b.time)}</div>
                        <div class="sbs-portal-booking-meta">
                            <span class="sbs-status-badge ${statusCls}">${escHtml(b.status_label)}</span>
                            <span class="sbs-portal-mini-pill">${escHtml(b.duration_min || 0)} min</span>
                            <span class="sbs-portal-mini-pill">${escHtml(moneyLabel(b.price))}</span>
                            ${b.payment_label ? `<span class="sbs-portal-mini-pill">${escHtml(b.payment_label)}</span>` : ''}
                        </div>
                        ${actions}
                    </div>
                </div>`;
        }).join('');
    }

    function bindDashboardEvents() {
        /* Tab switch */
        $(document).off('click.sbsPortalTab', '.sbs-portal-tab').on('click.sbsPortalTab', '.sbs-portal-tab', function () {
            currentTab = $(this).data('tab');
            $('.sbs-portal-tab').removeClass('active');
            $(this).addClass('active');
            const bookings = currentTab === 'upcoming' ? allData.upcoming : allData.past;
            $('#sbs-portal-booking-list').html(renderBookingList(bookings, currentTab));
        });

        /* Logout */
        $('#sbs-portal-logout-btn').off('click.sbsPortal').on('click.sbsPortal', function () {
            ajax('yatoon_portal_logout', {}, function () {
                currentCustomer = null;
                allData = null;
                currentTab = 'upcoming';
                renderPhoneStep();
            });
        });

        /* Cancel */
        $(document).off('click.sbsPortalCancel', '[data-action="cancel"]').on('click.sbsPortalCancel', '[data-action="cancel"]', function () {
            const id   = $(this).data('id');
            const $btn = $(this);

            // Build confirm modal with notify checkbox
            const $modal = $(`
                <div id="yn-portal-cancel-modal" style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;display:flex;align-items:center;justify-content:center;">
                  <div style="background:#fff;border-radius:10px;padding:28px 30px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(0,0,0,.2);">
                    <h3 style="margin:0 0 10px;font-size:16px;">Cancel Appointment</h3>
                    <p style="margin:0 0 14px;color:#555;font-size:14px;">${escHtml(cfg.strings.confirmCancel)}</p>
                    <label style="display:flex;align-items:center;gap:8px;font-size:14px;margin-bottom:18px;cursor:pointer;">
                      <input type="checkbox" id="yn-portal-notify" checked style="width:16px;height:16px;">
                      Send me a confirmation email
                    </label>
                    <div style="display:flex;gap:10px;justify-content:flex-end;">
                      <button id="yn-pcm-no"  style="padding:8px 16px;border:1px solid #ccc;border-radius:6px;background:#f5f5f5;cursor:pointer;">Keep</button>
                      <button id="yn-pcm-yes" style="padding:8px 16px;border:none;border-radius:6px;background:#e53e3e;color:#fff;cursor:pointer;">Yes, Cancel</button>
                    </div>
                  </div>
                </div>`);

            $('body').append($modal);
            $modal.find('#yn-pcm-no').on('click', function () { $modal.remove(); });
            $modal.on('click', function (ev) { if ($(ev.target).is($modal)) $modal.remove(); });

            $modal.find('#yn-pcm-yes').on('click', function () {
                const notify = $modal.find('#yn-portal-notify').is(':checked') ? 1 : 0;
                $modal.remove();
                $btn.prop('disabled', true).text('Cancelling...');
                ajax('yatoon_portal_cancel_booking', { booking_id: id, notify_customer: notify }, function () {
                    loadDashboard();
                }, function (d) {
                    $btn.prop('disabled', false).text(cfg.strings.cancel);
                    alert(d && d.message ? d.message : 'Failed to cancel');
                });
            });
        });

        /* Reschedule */
        $(document).off('click.sbsPortalReschedule', '[data-action="reschedule"]').on('click.sbsPortalReschedule', '[data-action="reschedule"]', function () {
            rescheduleBookingId = $(this).data('id');
            openRescheduleModal(rescheduleBookingId);
        });
    }

    /* ══════════════════════════════════════════════════════
       RESCHEDULE MODAL
    ══════════════════════════════════════════════════════ */
    function openRescheduleModal(bookingId) {
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];

        $('body').append(`
            <div class="sbs-portal-modal-overlay" id="sbs-reschedule-overlay">
                <div class="sbs-portal-modal">
                    <button class="sbs-portal-modal-close" id="sbs-modal-close">✕</button>
                    <h3>${cfg.strings.rescheduleTitle}</h3>
                    <input type="date" id="sbs-reschedule-date" class="sbs-portal-input"
                           value="${todayStr}" min="${todayStr}" style="margin-bottom:0;">
                    <div id="sbs-reschedule-slots" style="margin-top:14px;min-height:60px;">
                        <p style="color:#9ca3af;font-size:13px;text-align:center;">Select a date to see available times.</p>
                    </div>
                    <label style="display:flex;align-items:center;gap:8px;font-size:13px;margin-top:12px;cursor:pointer;">
                        <input type="checkbox" id="sbs-reschedule-notify" checked style="width:15px;height:15px;">
                        Send me a confirmation email
                    </label>
                    <p class="sbs-portal-msg" id="sbs-reschedule-msg" style="margin-top:10px;"></p>
                </div>
            </div>
        `);

        $('#sbs-modal-close, #sbs-reschedule-overlay').on('click', function (e) {
            if (e.target.id === 'sbs-reschedule-overlay' || e.target.id === 'sbs-modal-close') {
                $('#sbs-reschedule-overlay').remove();
            }
        });

        $('#sbs-reschedule-date').on('change', function () {
            loadRescheduleSlots(bookingId, $(this).val());
        });

        // Load today's slots immediately
        loadRescheduleSlots(bookingId, todayStr);
    }

    function loadRescheduleSlots(bookingId, date) {
        $('#sbs-reschedule-slots').html('<div style="text-align:center;padding:16px;"><span class="sbs-portal-spinner" style="display:inline-block;"></span></div>');

        ajax('yatoon_portal_get_reschedule_slots', { booking_id: bookingId, date }, function (data) {
            if (!data.slots.length) {
                $('#sbs-reschedule-slots').html('<p style="color:#9ca3af;font-size:13px;text-align:center;padding:12px 0;">No available times on this date.</p>');
                return;
            }
            let html = '<div class="sbs-portal-slot-grid">';
            data.slots.forEach(function (s) {
                html += `<div class="sbs-portal-slot" data-start="${s.start_at}" data-staff="${(s.staff_ids||[])[0]||''}">${s.display}</div>`;
            });
            html += '</div>';
            html += `<div style="margin-top:16px;text-align:right;">
                <button id="sbs-confirm-reschedule" class="sbs-portal-btn" style="width:auto;padding:10px 24px;" disabled>
                    Confirm Reschedule
                </button>
            </div>`;
            $('#sbs-reschedule-slots').html(html);

            // Slot selection
            let selectedStart = null, selectedStaff = null;
            $(document).on('click', '.sbs-portal-slot', function () {
                $('.sbs-portal-slot').removeClass('selected');
                $(this).addClass('selected');
                selectedStart = $(this).data('start');
                selectedStaff = $(this).data('staff');
                $('#sbs-confirm-reschedule').prop('disabled', false);
            });

            // Confirm
            $('#sbs-confirm-reschedule').off('click').on('click', function () {
                if (!selectedStart) return;
                const $btn = $(this).prop('disabled', true).text('Rescheduling...');
                const notify = $('#sbs-reschedule-notify').is(':checked') ? 1 : 0;
                ajax('yatoon_portal_reschedule_booking', {
                    booking_id:      bookingId,
                    new_start_at:    selectedStart,
                    staff_id:        selectedStaff || '',
                    notify_customer: notify,
                }, function () {
                    $('#sbs-reschedule-overlay').remove();
                    loadDashboard();
                }, function (d) {
                    $btn.prop('disabled', false).text('Confirm Reschedule');
                    showMsg($('#sbs-reschedule-msg'), d && d.message ? d.message : 'Reschedule failed.', 'error');
                });
            });
        }, function (d) {
            $('#sbs-reschedule-slots').html('<p style="color:red;font-size:13px;text-align:center;">' + (d && d.message ? d.message : 'Error loading slots') + '</p>');
        });
    }

    /* ══════════════════════════════════════════════════════
       SECURITY HELPER
    ══════════════════════════════════════════════════════ */
    function escHtml(str) {
        return String(str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    /* ══════════════════════════════════════════════════════
       INIT: check if already logged in
    ══════════════════════════════════════════════════════ */
    function init() {
        renderLoading();
        // Try to get bookings - if session exists, it'll succeed
        ajax('yatoon_portal_get_bookings', {}, function (data) {
            allData         = data;
            currentCustomer = data.customer;
            currentTab      = data.upcoming && data.upcoming.length ? 'upcoming' : 'past';
            renderDashboard();
        }, function (d) {
            // Not logged in or error - show phone step
            currentTab = 'upcoming';
            renderPhoneStep();
        });
    }

    init();

})(jQuery);
