/**
 * WAHRB Calendar Script - Client Booking Modal
 *
 * @package DokanRentalsBookings
 */

(function ($) {
    'use strict';

    // Config
    var config = window.wahrbCalendarConfig || {};

    // State
    var state = {
        productId: null,
        bookingMode: 'day',         // day, slot, or service
        startDate: null,
        endDate: null,
        slotStart: null,            // Time slot start (HH:mm)
        slotEnd: null,              // Time slot end (HH:mm)
        appointmentTime: null,      // Appointment time (HH:mm)
        qty: 1,
        isChecking: false,
        isAvailable: false,
        priceData: null,
        paymentData: null,          // Payment breakdown from API
        startPicker: null,
        endPicker: null,
        phoneInput: null            // intl-tel-input instance
    };

    // Initialize
    function init() {
        var $trigger = $('.wahrb-open-modal');
        if (!$trigger.length) {
            return;
        }

        state.productId = $trigger.data('product-id');

        // Detect booking mode from config or DOM
        state.bookingMode = config.bookingMode || 'day';

        // Bind events
        bindEvents();

        // Initialize phone input with country selector
        initPhoneInput();

        // Fetch blocked dates and init pickers
        fetchBlockedDates(function (blockedDates) {
            initFlatpickr(blockedDates);
        });
    }

    // Initialize intl-tel-input for phone number with country selector
    function initPhoneInput() {
        var phoneInput = document.querySelector('#wahrb-phone');
        if (!phoneInput || typeof intlTelInput === 'undefined') {
            return;
        }

        // Build config object
        var phoneConfig = {
            // Default to Tunisia (no external IP lookup for WordPress.org compliance)
            initialCountry: 'tn',
            // Country order (Tunisia first, then France, Algeria, Morocco)
            countryOrder: ['tn', 'fr', 'dz', 'ma'],
            // Show dial code in selected flag
            separateDialCode: true,
            // Format on blur
            formatOnDisplay: true,
            // National mode - don't require country code in input
            nationalMode: true,
            // Auto placeholder
            autoPlaceholder: 'aggressive'
        };

        // Only add utilsScript if we have a valid plugin URL (local file, no CDN)
        if (typeof wahrbCalendarConfig !== 'undefined' && wahrbCalendarConfig.pluginUrl) {
            phoneConfig.utilsScript = wahrbCalendarConfig.pluginUrl + 'assets/vendor/intl-tel-input/utils.js';
        }

        state.phoneInput = intlTelInput(phoneInput, phoneConfig);

        // Update hidden field when number changes
        phoneInput.addEventListener('blur', function () {
            updatePhoneHiddenField();
        });
        phoneInput.addEventListener('countrychange', function () {
            updatePhoneHiddenField();
        });
    }

    // Update hidden phone field with full international number
    function updatePhoneHiddenField() {
        if (!state.phoneInput) return;
        var $hiddenPhone = $('#wahrb-phone-full');
        if ($hiddenPhone.length) {
            $hiddenPhone.val(state.phoneInput.getNumber());
        }
    }

    // Bind events
    function bindEvents() {
        // Open modal
        $(document).on('click', '.wahrb-open-modal', function () {
            $('#wahrb-booking-modal').fadeIn(200);
            $('body').css('overflow', 'hidden');
        });

        // Close modal - button and overlay click
        $(document).on('click', '.wahrb-close-btn', function (e) {
            e.preventDefault();
            closeModal();
        });

        $(document).on('click', '.wahrb-modal-overlay', function (e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // ESC key closes modal
        $(document).on('keydown', function (e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });

        // Qty buttons
        $(document).on('click', '.wahrb-qty-plus', function () {
            var $input = $('#wahrb-qty');
            var max = parseInt($input.attr('max')) || 999;
            var val = parseInt($input.val()) || 1;
            if (val < max) {
                $input.val(val + 1).trigger('change');
            }
        });

        $(document).on('click', '.wahrb-qty-minus', function () {
            var $input = $('#wahrb-qty');
            var min = parseInt($input.attr('min')) || 1;
            var val = parseInt($input.val()) || 1;
            if (val > min) {
                $input.val(val - 1).trigger('change');
            }
        });

        // Qty change
        $(document).on('change', '#wahrb-qty', function () {
            state.qty = parseInt($(this).val()) || 1;
            if (state.startDate && state.endDate) {
                checkAvailability();
            }
        });

        // Step navigation - Next button
        $(document).on('click', '.wahrb-btn-next', function () {
            if ($(this).prop('disabled')) return;

            var $currentStep = $('.wahrb-form-step:visible');
            var currentStepNum = parseInt($currentStep.data('step')) || 1;

            // Validate step 2 before going to step 3
            if (currentStepNum === 2) {
                if (!validateContactFields()) {
                    return; // Stop if validation fails
                }
            }

            goToStep(currentStepNum + 1);
        });

        // Step navigation - Back button
        $(document).on('click', '.wahrb-btn-back', function () {
            var $currentStep = $('.wahrb-form-step:visible');
            var currentStepNum = parseInt($currentStep.data('step')) || 1;
            if (currentStepNum > 1) {
                goToStep(currentStepNum - 1);
            }
        });

        // Submit button click (direct handler)
        $(document).on('click', '.wahrb-btn-submit', function (e) {
            e.preventDefault();
            submitBookingRequest();
        });

        // Form submit (fallback)
        $(document).on('submit', '.wahrb-booking-form', function (e) {
            e.preventDefault();
            submitBookingRequest();
        });

        // ========== SLOT MODE HANDLERS ==========
        // Click on time slot
        $(document).on('click', '.wahrb-slot-item:not(.disabled)', function () {
            var $this = $(this);
            $('.wahrb-slot-item').removeClass('selected');
            $this.addClass('selected');

            state.slotStart = $this.data('start');
            state.slotEnd = $this.data('end');
            $('#wahrb-slot-start').val(state.slotStart);
            $('#wahrb-slot-end').val(state.slotEnd);

            // Trigger availability check
            checkAvailability();
        });

        // ========== SERVICE MODE HANDLERS ==========
        // Click on appointment slot
        $(document).on('click', '.wahrb-appointment-item:not(.disabled)', function () {
            var $this = $(this);
            $('.wahrb-appointment-item').removeClass('selected');
            $this.addClass('selected');

            state.appointmentTime = $this.data('time');
            $('#wahrb-appointment-time').val(state.appointmentTime);

            // Trigger availability check
            checkAvailability();
        });
    }

    // Load available time slots for selected date (slot/service mode)
    function loadTimeSlots(selectedDate) {
        var $slotsSection = $('.wahrb-time-slots-section');
        var $appointmentsSection = $('.wahrb-appointment-section');
        var $grid = state.bookingMode === 'slot' ? $('#wahrb-time-slots') : $('#wahrb-appointments');

        // Show appropriate section
        if (state.bookingMode === 'slot') {
            $slotsSection.slideDown(200);
            $appointmentsSection.hide();
        } else if (state.bookingMode === 'service') {
            $appointmentsSection.slideDown(200);
            $slotsSection.hide();
        }

        // Show loading
        $grid.html('<div class="wahrb-slots-loading"><div class="wahrb-pulse-loader"></div><span>' + (config.i18n?.loadingSlots || 'Loading available slots...') + '</span></div>');

        // Fetch available slots from API
        $.ajax({
            url: config.apiUrl + '/time-slots',
            method: 'GET',
            data: {
                product_id: state.productId,
                date: selectedDate,
                mode: state.bookingMode
            },
            headers: {
                'X-WP-Nonce': config.nonce
            },
            success: function (response) {
                var slots = response.slots || [];
                var html = '';

                if (slots.length === 0) {
                    html = '<div class="wahrb-no-slots">' + (config.i18n?.noSlots || 'No slots available for this date') + '</div>';
                } else {
                    slots.forEach(function (slot) {
                        var disabledClass = slot.available ? '' : 'disabled';
                        if (state.bookingMode === 'slot') {
                            html += '<div class="wahrb-slot-item ' + disabledClass + '" data-start="' + slot.start + '" data-end="' + slot.end + '">';
                            html += '<span class="slot-time">' + slot.start + ' - ' + slot.end + '</span>';
                            if (slot.price) {
                                html += '<span class="slot-price">' + formatPrice(slot.price) + '</span>';
                            }
                            html += '</div>';
                        } else {
                            html += '<div class="wahrb-appointment-item ' + disabledClass + '" data-time="' + slot.time + '">';
                            html += '<span class="appt-time">' + slot.time + '</span>';
                            if (slot.spots_left) {
                                html += '<span class="appt-spots">' + slot.spots_left + ' ' + (config.i18n?.spots || 'spots') + '</span>';
                            }
                            html += '</div>';
                        }
                    });
                }

                $grid.html(html);
            },
            error: function () {
                $grid.html('<div class="wahrb-no-slots">' + (config.i18n?.errorLoading || 'Error loading slots') + '</div>');
            }
        });
    }

    // Navigate to specific step
    function goToStep(stepNum) {
        // Hide all steps
        $('.wahrb-form-step').hide();
        // Show target step
        $('.wahrb-form-step[data-step="' + stepNum + '"]').fadeIn(200);

        // Update step indicator (matches .wahrb-step in HTML)
        $('.wahrb-step').removeClass('active completed');
        $('.wahrb-step').each(function () {
            var itemStep = parseInt($(this).data('step'));
            if (itemStep < stepNum) {
                $(this).addClass('completed');
            } else if (itemStep === stepNum) {
                $(this).addClass('active');
            }
        });

        // If going to step 3 (summary), populate the fields
        if (stepNum === 3) {
            populateSummary();
        }
    }

    // Populate summary step with user's selections
    function populateSummary() {
        // Format dates
        var dateText = formatDateRange(state.startDate, state.endDate || state.startDate);
        if (state.qty > 1) {
            dateText += ' × ' + state.qty + ' unité(s)';
        }
        $('.wahrb-summary-dates').text(dateText);

        // Client info
        var name = $('#wahrb-name').val().trim();
        var email = $('#wahrb-email').val().trim();
        var phone = $('#wahrb-phone').val().trim();
        var clientText = name;
        if (email) clientText += '\n' + email;
        if (phone) clientText += '\n' + phone;
        $('.wahrb-summary-client').html(clientText.replace(/\n/g, '<br>'));

        // Total - use priceData from API response
        var totalAmount = 0;
        if (state.priceData && state.priceData.total) {
            totalAmount = state.priceData.total;
        }
        var totalText = formatPrice(totalAmount);
        $('.wahrb-summary-total').text(totalText);
    }

    // Close modal
    function closeModal() {
        $('#wahrb-booking-modal').fadeOut(200);
        $('body').css('overflow', '');
    }

    // Fetch blocked dates from API
    function fetchBlockedDates(callback) {
        $.ajax({
            url: config.apiUrl + '/blocked-dates',
            method: 'GET',
            data: {
                product_id: state.productId,
                months: 6
            },
            headers: {
                'X-WP-Nonce': config.nonce
            },
            success: function (response) {
                callback(response.blocked_dates || []);
            },
            error: function () {
                callback([]);
            }
        });
    }

    // Initialize Flatpickr
    function initFlatpickr(blockedDates) {
        var commonOptions = {
            dateFormat: 'Y-m-d',
            minDate: 'today',
            locale: config.locale || 'fr',
            disable: blockedDates,
            disableMobile: true
        };

        // Start date picker
        state.startPicker = flatpickr('#wahrb-start-date', $.extend({}, commonOptions, {
            onChange: function (selectedDates, dateStr) {
                state.startDate = dateStr;

                // Update end date min
                if (state.endPicker) {
                    state.endPicker.set('minDate', dateStr);
                }

                // For slot or service mode: load time slots
                if (state.bookingMode === 'slot' || state.bookingMode === 'service') {
                    loadTimeSlots(dateStr);
                }
                // For day mode: Auto-trigger availability check if both dates selected
                else if (state.startDate && (state.endDate || !$('#wahrb-end-date').length)) {
                    checkAvailability();
                }
            }
        }));

        // End date picker (if exists)
        if ($('#wahrb-end-date').length) {
            state.endPicker = flatpickr('#wahrb-end-date', $.extend({}, commonOptions, {
                onChange: function (selectedDates, dateStr) {
                    state.endDate = dateStr;
                    if (state.startDate) {
                        checkAvailability();
                    }
                }
            }));
        }
    }

    // Check availability
    function checkAvailability() {
        if (state.isChecking) return;

        // Use new CSS class names from modern template
        var $box = $('.wahrb-availability-box');
        var $checking = $box.find('.wahrb-avail-checking');
        var $success = $box.find('.wahrb-avail-success');
        var $error = $box.find('.wahrb-avail-error');
        var $btnNext = $('.wahrb-form-step[data-step="1"] .wahrb-btn-next');

        state.isChecking = true;
        state.isAvailable = false;

        // Show checking state
        $checking.show();
        $success.hide();
        $error.hide();
        $('.wahrb-price-preview').hide();
        $btnNext.prop('disabled', true);

        // Prepare dates (API expects Y-m-d format without time)
        var startDate = state.startDate;
        var endDate = state.endDate || state.startDate;

        // Make API call
        $.ajax({
            url: config.apiUrl + '/availability',
            method: 'GET',
            data: {
                product_id: state.productId,
                start_date: startDate,
                end_date: endDate,
                qty: state.qty
            },
            headers: {
                'X-WP-Nonce': config.nonce
            },
            success: function (response) {
                state.isChecking = false;
                $checking.hide();

                if (response.available) {
                    state.isAvailable = true;
                    $success.show();
                    $success.find('.wahrb-avail-dates').text(formatDateRange(startDate, endDate));
                    // Fetch price and enable continue button
                    calculatePrice(startDate, endDate);
                    $btnNext.prop('disabled', false);
                } else {
                    $error.show();
                    // Build helpful error message with hints
                    var errorMsg = buildErrorMessage(response);
                    $error.find('.wahrb-avail-reason').html(errorMsg);
                    $btnNext.prop('disabled', true);
                }
            },
            error: function (xhr) {
                state.isChecking = false;
                $checking.hide();
                $error.show();

                // Try to get error from response
                var errorMsg = config.strings.errorOccurred || 'An error occurred';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                }
                $error.find('.wahrb-avail-reason').text(errorMsg);
                $btnNext.prop('disabled', true);
            }
        });
    }

    // Build helpful error message with suggestions
    function buildErrorMessage(response) {
        var message = response.message || (config.strings.unavailable || 'Unavailable');
        var hint = '';

        switch (response.reason) {
            case 'invalid_dates':
                hint = '<br><small style="opacity:0.8">💡 La date de fin doit être après la date de début</small>';
                break;
            case 'min_duration':
                var minDays = response.min_duration || 2;
                hint = '<br><small style="opacity:0.8">💡 Choisissez au moins ' + minDays + ' jour(s)</small>';
                break;
            case 'max_duration':
                var maxDays = response.max_duration || 30;
                hint = '<br><small style="opacity:0.8">💡 Maximum ' + maxDays + ' jour(s) autorisé</small>';
                break;
            case 'min_booking_window':
                var minHours = response.min_hours || 24;
                hint = '<br><small style="opacity:0.8">💡 Réservez au moins ' + minHours + 'h à l\'avance</small>';
                break;
            case 'max_booking_window':
                var maxDaysFuture = response.max_days || 365;
                hint = '<br><small style="opacity:0.8">💡 Maximum ' + maxDaysFuture + ' jours à l\'avance</small>';
                break;
            case 'no_units':
            case 'overlap':
                hint = '<br><small style="opacity:0.8">💡 Essayez d\'autres dates</small>';
                break;
            case 'blackout':
                hint = '<br><small style="opacity:0.8">💡 Ces dates sont bloquées par le propriétaire</small>';
                break;
        }

        return message + hint;
    }

    // Format date range for display
    function formatDateRange(start, end) {
        var options = { day: 'numeric', month: 'short' };
        var startDate = new Date(start);
        var endDate = new Date(end);

        if (start === end) {
            return startDate.toLocaleDateString('fr-FR', options);
        }
        return startDate.toLocaleDateString('fr-FR', options) + ' → ' + endDate.toLocaleDateString('fr-FR', options);
    }


    // Calculate price
    function calculatePrice(startDate, endDate) {
        $.ajax({
            url: config.apiUrl + '/calculate-price',
            method: 'GET',
            data: {
                product_id: state.productId,
                start_date: startDate,
                end_date: endDate,
                qty: state.qty
            },
            headers: {
                'X-WP-Nonce': config.nonce
            },
            success: function (response) {
                // API returns { calculation: {...}, payment: {...} }
                var calculation = response.calculation || response;
                var payment = response.payment || {};

                // Merge payment data into calculation for displayPrice
                calculation.security_deposit = payment.security_deposit ? payment.security_deposit.amount : 0;
                calculation.deposit = payment.deposit ? payment.deposit.amount : 0;
                calculation.pay_now = payment.pay_now ? payment.pay_now.amount : calculation.total;

                state.priceData = calculation;
                state.paymentData = payment;
                displayPrice(calculation);

                // Show contact section and enable button
                $('.wahrb-contact-section').slideDown(200);
                $('.wahrb-btn-submit').prop('disabled', false);
            },
            error: function (xhr, status, error) {
                console.error('Price calculation failed:', error);
                // Still enable the button as fallback - user can proceed
                $('.wahrb-contact-section').slideDown(200);
                $('.wahrb-btn-submit').prop('disabled', false);
            }
        });
    }

    // Display price breakdown
    function displayPrice(data) {
        // Use correct selectors matching HTML template
        var $preview = $('.wahrb-price-preview');
        var $lines = $preview.find('.wahrb-price-lines');
        var $total = $preview.find('.wahrb-total-value');

        var html = '';

        // Duration - API returns "days" not "duration"
        var days = data.days || data.duration || 0;
        var baseTotal = data.subtotal || data.base_total || 0;

        if (days > 0) {
            html += '<div class="wahrb-price-line">';
            html += '<span>' + days + ' ' + (days > 1 ? 'jours' : 'jour') + '</span>';
            html += '<span>' + formatPrice(baseTotal) + '</span>';
            html += '</div>';
        }

        // Security deposit
        if (data.security_deposit && data.security_deposit > 0) {
            html += '<div class="wahrb-price-line">';
            html += '<span>Caution (remboursable)</span>';
            html += '<span>' + formatPrice(data.security_deposit) + '</span>';
            html += '</div>';
        }

        $lines.html(html);
        $total.text(formatPrice(data.total || baseTotal || 0));
        $preview.slideDown(200);
    }

    // Format price
    function formatPrice(amount) {
        return (config.currencySymbol || '€') + ' ' + parseFloat(amount).toFixed(2);
    }

    // Show field error message
    function showFieldError(selector, message) {
        if (selector) {
            var $field = $(selector);
            $field.addClass('wahrb-field-error');
            $field.closest('.wahrb-input-group').find('.wahrb-error-msg').remove();
            $field.closest('.wahrb-input-group').append(
                '<div class="wahrb-error-msg" style="color:#ef4444;font-size:12px;margin-top:4px;">⚠️ ' + message + '</div>'
            );
        } else {
            // General error (no field)
            alert(message);
        }
    }

    // Clear all field errors
    function clearFieldErrors() {
        $('.wahrb-field-error').removeClass('wahrb-field-error');
        $('.wahrb-error-msg').remove();
    }

    // Validate contact form fields (step 2)
    function validateContactFields() {
        clearFieldErrors();

        var name = $('#wahrb-name').val().trim();
        var email = $('#wahrb-email').val().trim();
        var phone = $('#wahrb-phone').val().trim();

        var hasError = false;

        // Regex patterns (phone uses intl-tel-input validation, fallback regex is defined inline)
        var nameRegex = /^[a-zA-ZÀ-ÿ\s\-']+$/;           // Letters, spaces, hyphens, accents ONLY
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;   // Basic email format

        // Validate name
        if (!name) {
            showFieldError('#wahrb-name', config.strings.nameRequired || 'Name is required');
            hasError = true;
        } else if (!nameRegex.test(name)) {
            showFieldError('#wahrb-name', config.strings.nameLettersOnly || 'Name must contain only letters');
            hasError = true;
        } else if (name.length < 2) {
            showFieldError('#wahrb-name', config.strings.nameMinLength || 'Name must be at least 2 characters');
            hasError = true;
        }

        // Validate email
        if (!email) {
            showFieldError('#wahrb-email', config.strings.emailRequired || 'Email is required');
            hasError = true;
        } else if (!emailRegex.test(email)) {
            showFieldError('#wahrb-email', config.strings.emailInvalid || 'Invalid email format');
            hasError = true;
        }

        // Validate phone (optional but must be valid if provided)
        // Use basic digit-count validation — strict intl-tel-input checks cause false
        // positives when users enter numbers without national prefix (e.g. 683169492 vs 0683169492)
        if (phone) {
            updatePhoneHiddenField(); // Sync hidden field first
            var phoneDigits = phone.replace(/[^\d]/g, '');
            // Also check the full international number from intl-tel-input
            var fullNumber = (state.phoneInput && typeof state.phoneInput.getNumber === 'function')
                ? state.phoneInput.getNumber().replace(/[^\d]/g, '')
                : phoneDigits;
            // Accept if either the input digits or the full number has enough digits
            var digitCount = Math.max(phoneDigits.length, fullNumber.length);
            if (digitCount < 6) {
                showFieldError('#wahrb-phone', config.strings.phoneInvalid || 'Invalid phone number');
                hasError = true;
            }
        }

        return !hasError;
    }

    // Submit booking request
    function submitBookingRequest() {
        var $form = $('.wahrb-booking-form');
        var $btn = $('.wahrb-btn-submit');

        // Get contact field values
        var name = $('#wahrb-name').val().trim();
        var email = $('#wahrb-email').val().trim();
        var phone = $('#wahrb-phone-full').val() || $('#wahrb-phone').val().trim();

        // Check if dates were selected
        if (!state.startDate) {
            showFieldError(null, config.strings.selectDatesFirst || 'Please select dates first.');
            return;
        }

        // Validate contact fields (reuse step 2 validation)
        if (!validateContactFields()) {
            return;
        }

        // Check terms accepted
        if (!$('#wahrb-accept-terms').is(':checked')) {
            showFieldError(null, config.strings.acceptTerms || 'Please accept the booking terms.');
            return;
        }

        $btn.prop('disabled', true).find('.wahrb-btn-text').text(config.strings.sending || 'Sending...');

        // Use WAhrb API to create booking (triggers email notifications)
        // Collect custom form fields (Form Builder)
        var formData = {};
        $('.wahrb-custom-fields [name^="wahrb_cf_"]').each(function() {
            var fieldName = $(this).attr('name').replace('wahrb_cf_', '');
            if ($(this).is(':checkbox') || $(this).is(':radio')) {
                if ($(this).is(':checked')) {
                    formData[fieldName] = $(this).val();
                }
            } else {
                formData[fieldName] = $(this).val();
            }
        });

        // Template ID for form validation on server
        var templateId = $('.wahrb-custom-fields').data('template-id') || 0;

        // Coupon data
        var couponCode = $('#wahrb-coupon-validated').val() || '';
        var couponDiscount = parseFloat($('#wahrb-coupon-discount-amount').val()) || 0;

        $.ajax({
            url: config.apiUrl + '/bookings/request',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                product_id: state.productId,
                start_date: state.startDate,
                end_date: state.endDate || state.startDate,
                qty: state.qty,
                customer_name: name,
                customer_email: email,
                customer_phone: phone,
                message: $('#wahrb-message').val().trim(),
                form_data: formData,
                form_template_id: templateId,
                coupon_code: couponCode
            }),
            headers: {
                'X-WP-Nonce': config.nonce
            },
            success: function (response) {
                if (response.success) {
                    // Show success message
                    $('.wahrb-form-step').hide();
                    $('.wahrb-form-success').fadeIn(300);
                    $('.wahrb-form-success').find('.wahrb-booking-ref').text(response.booking_number || '#' + response.booking_id);

                    // Optionally close modal after delay
                    setTimeout(function () {
                        location.reload();
                    }, 5000);
                } else {
                    var errorMsg = response.message || (config.strings.errorOccurred || 'An error occurred.');
                    alert(errorMsg);
                    $btn.prop('disabled', false).find('.wahrb-btn-text').text(config.strings.submitButton || 'Send request');
                }
            },
            error: function (xhr, status, error) {
                console.error('WAHRB booking request error:', error, xhr.responseText);
                var errorMsg = config.strings.errorOccurred || 'An error occurred.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                }
                alert(errorMsg);
                $btn.prop('disabled', false).find('.wahrb-btn-text').text(config.strings.submitButton || 'Send request');
            }
        });
    }

    // ── Coupon code handling ──────────────────────────────────
    function initCouponHandlers() {
        var $input = $('#wahrb-coupon-code');
        var $applyBtn = $('#wahrb-apply-coupon');
        var $result = $('.wahrb-coupon-result');
        var $success = $('.wahrb-coupon-success');
        var $error = $('.wahrb-coupon-error');

        if (!$input.length) return;

        // Enable/disable apply button based on input
        $input.on('input', function() {
            $applyBtn.prop('disabled', $(this).val().trim() === '');
        });

        // Apply coupon
        $applyBtn.on('click', function() {
            var code = $input.val().trim();
            if (!code) return;

            $applyBtn.prop('disabled', true).text(config.strings.validating || 'Validating...');

            $.ajax({
                url: config.apiUrl + '/coupons/validate',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    code: code,
                    product_id: state.productId,
                    subtotal: state.lastPrice || 0,
                    customer_email: $('#wahrb-email').val().trim()
                }),
                headers: { 'X-WP-Nonce': config.nonce },
                success: function(response) {
                    $result.show();
                    if (response.valid) {
                        $success.show();
                        $error.hide();
                        $success.find('.wahrb-coupon-message').text(response.message || 'Coupon applied!');
                        $success.find('.wahrb-coupon-discount').text('-' + (response.formatted_discount || response.discount_amount));
                        $('#wahrb-coupon-validated').val(code);
                        $('#wahrb-coupon-discount-amount').val(response.discount_amount);
                        $input.prop('readonly', true);
                        $applyBtn.hide();

                        // Update price preview if available
                        if (response.new_total !== undefined) {
                            updatePriceWithDiscount(response.discount_amount, response.new_total);
                        }
                    } else {
                        $success.hide();
                        $error.show();
                        $error.find('.wahrb-coupon-error-msg').text(response.message || 'Invalid coupon code.');
                        $applyBtn.prop('disabled', false).text(config.strings.apply || 'Apply');
                    }
                },
                error: function() {
                    $result.show();
                    $success.hide();
                    $error.show();
                    $error.find('.wahrb-coupon-error-msg').text(config.strings.errorOccurred || 'Error validating coupon.');
                    $applyBtn.prop('disabled', false).text(config.strings.apply || 'Apply');
                }
            });
        });

        // Remove coupon
        $(document).on('click', '.wahrb-remove-coupon', function() {
            $input.val('').prop('readonly', false);
            $applyBtn.show().prop('disabled', true).text(config.strings.apply || 'Apply');
            $result.hide();
            $success.hide();
            $error.hide();
            $('#wahrb-coupon-validated').val('');
            $('#wahrb-coupon-discount-amount').val('0');
            removePriceDiscount();
        });
    }

    function updatePriceWithDiscount(discountAmount, newTotal) {
        var $priceLines = $('.wahrb-price-lines');
        // Remove old discount line if any
        $priceLines.find('.wahrb-price-discount').remove();
        if (discountAmount > 0) {
            $priceLines.append('<div class="wahrb-price-line wahrb-price-discount" style="color: #16a34a;">' +
                '<span>' + (config.strings.couponDiscount || 'Coupon discount') + '</span>' +
                '<span>-' + formatPrice(discountAmount) + '</span></div>');
        }
    }

    function removePriceDiscount() {
        $('.wahrb-price-lines .wahrb-price-discount').remove();
    }

    function formatPrice(amount) {
        var symbol = config.currencySymbol || '';
        var pos = config.currencyPosition || 'before';
        var formatted = parseFloat(amount).toFixed(2);
        return pos === 'before' ? symbol + formatted : formatted + symbol;
    }

    // Init on ready
    $(document).ready(function() {
        init();
        initCouponHandlers();
    });

})(jQuery);
