/* Fusion WooDoo — My Account JS */
(function ($) {
    'use strict';

    /* ── Return form ──────────────────────────────────────────── */
    var ordersData = {};
    try {
        var raw = document.getElementById('fw-orders-data');
        if (raw) ordersData = JSON.parse(raw.textContent || '{}');
    } catch (e) {}

    // Populate item list when order changes
    $(document).on('change', '#fw-order-select', function () {
        var orderId = $(this).val();
        var $container = $('#fw-items-container');
        var $list = $('#fw-items-list');
        $list.empty();

        if (!orderId || !ordersData[orderId]) {
            $container.hide();
            return;
        }

        var items = ordersData[orderId];
        if (!items.length) {
            $container.hide();
            return;
        }

        items.forEach(function (item) {
            var $row = $('<div class="fw-return-item"></div>');
            $row.append(
                $('<input type="checkbox" />').attr({
                    name: 'items[' + item.product_id + '][select]',
                    'data-product-id': item.product_id,
                    value: '1',
                })
            );
            $row.append($('<span></span>').text(item.name));
            $row.append(
                $('<input type="number" class="fw-return-item-qty" />').attr({
                    name: 'items[' + item.product_id + '][qty]',
                    min: 1,
                    max: item.qty,
                    value: item.qty,
                    disabled: true,
                })
            );
            $list.append($row);
        });

        $container.show();
    });

    // Enable/disable qty field with checkbox
    $(document).on('change', '.fw-return-item input[type="checkbox"]', function () {
        var $qty = $(this).closest('.fw-return-item').find('.fw-return-item-qty');
        $qty.prop('disabled', !this.checked);
    });

    // Submit return form via AJAX
    $(document).on('submit', '#fusion-woodoo-return-form', function (e) {
        e.preventDefault();

        var $form   = $(this);
        var $notice = $('#fusion-woodoo-return-notice');
        var $submit = $form.find('[type=submit]');

        // Collect selected items
        var items = [];
        $form.find('.fw-return-item input[type="checkbox"]:checked').each(function () {
            var productId = $(this).data('product-id');
            var qty       = parseInt($(this).closest('.fw-return-item').find('.fw-return-item-qty').val(), 10) || 1;
            items.push({ product_id: productId, qty: qty });
        });

        var payload = {
            action:   'fusion_woodoo_submit_return',
            nonce:    fusionWooDoo.nonce,
            order_id: $form.find('[name=order_id]').val(),
            reason:   $form.find('[name=reason]').val(),
            items:    items,
        };

        $submit.prop('disabled', true).text('Submitting…');
        $notice.hide().removeClass('fusion-woodoo-notice--success fusion-woodoo-notice--error');

        $.post(fusionWooDoo.ajaxUrl, payload)
            .done(function (res) {
                if (res.success) {
                    $notice.addClass('fusion-woodoo-notice--success').text(res.data.message).show();
                    $form[0].reset();
                    $('#fw-items-container').hide();
                } else {
                    $notice.addClass('fusion-woodoo-notice--error').text(res.data.message || 'Submission failed.').show();
                }
            })
            .fail(function () {
                $notice.addClass('fusion-woodoo-notice--error').text('Request failed. Please try again.').show();
            })
            .always(function () {
                $submit.prop('disabled', false).text('Submit Return Request');
                $('html, body').animate({ scrollTop: $notice.offset().top - 40 }, 300);
            });
    });

    /* ── Reorder button ───────────────────────────────────────── */
    $(document).on('click', '.fusion-woodoo-reorder', function () {
        var $btn    = $(this);
        var orderId = $btn.data('order-id');
        var nonce   = $btn.data('nonce');

        $btn.prop('disabled', true).text('Adding…');

        $.post(fusionWooDoo.ajaxUrl, {
            action:   'fusion_woodoo_reorder',
            nonce:    nonce,
            order_id: orderId,
        })
        .done(function (res) {
            if (res.success && res.data.cart_url) {
                window.location.href = res.data.cart_url;
            } else {
                alert(res.data.message || 'Could not reorder. Please try again.');
                $btn.prop('disabled', false).text('Reorder');
            }
        })
        .fail(function () {
            alert('Request failed. Please try again.');
            $btn.prop('disabled', false).text('Reorder');
        });
    });

}(jQuery));
