/**
 * AIEO Waitlist — front-end client.
 *
 * Wires up the "Notify me when back in stock" form: email validation,
 * loading state, success/error messages, and WooCommerce variable-
 * product integration (listens for `found_variation` / `reset_data`
 * to flip the form's visibility in line with the picked variation's
 * stock status, and stamps the chosen variation_id into the hidden
 * field so the POST targets the exact SKU the shopper is waiting on).
 */
(function ($) {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    var CFG = window.aieoWaitlist || null;
    if (!CFG) return;

    var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    function showMessage($m, text, type) {
        $m.removeClass('success error').addClass(type).html(text).show();
        if ($m.length && $m.offset().top < $(window).scrollTop()) {
            $('html, body').animate({ scrollTop: $m.offset().top - 100 }, 300);
        }
    }

    function handleSubmit(e) {
        e.preventDefault();
        var $form     = $(e.currentTarget);
        var $container = $form.closest('.aieo-waitlist-container');
        var $btn      = $form.find('.aieo-waitlist-submit');
        var $overlay  = $container.find('.aieo-waitlist-overlay');
        var $message  = $form.find('.aieo-waitlist-message');

        var email       = ($form.find('input[name="email"]').val() || '').trim();
        var productId   = parseInt($form.find('input[name="product_id"]').val(), 10) || 0;
        var variationId = parseInt($form.find('.aieo-waitlist-variation-id').val(), 10) || 0;

        if (!EMAIL_RE.test(email)) {
            showMessage($message, CFG.i18n.invalidEmail || __('Invalid email', 'ai-eshop-optimizer'), 'error');
            return;
        }

        $overlay.addClass('is-loading');
        $btn.prop('disabled', true);
        $message.hide();

        $.ajax({
            url: CFG.ajaxUrl,
            type: 'POST',
            data: {
                action:       'aieo_waitlist_subscribe',
                email:        email,
                product_id:   productId,
                variation_id: variationId,
                nonce:        CFG.nonce,
            }
        }).done(function (resp) {
            $overlay.removeClass('is-loading');
            $btn.prop('disabled', false);
            if (resp && resp.success) {
                showMessage($message, resp.data.message, 'success');
                $form.find('input[type="email"]').val('');
            } else {
                var msg = (resp && resp.data && resp.data.message) ? resp.data.message : (CFG.i18n.genericError || __('Error', 'ai-eshop-optimizer'));
                showMessage($message, msg, 'error');
            }
        }).fail(function () {
            $overlay.removeClass('is-loading');
            $btn.prop('disabled', false);
            showMessage($message, CFG.i18n.genericError || __('Error', 'ai-eshop-optimizer'), 'error');
        });
    }

    /**
     * Variable products: WC fires `found_variation` when the shopper
     * picks a complete set of attributes. We pop the form open if the
     * resolved variation is out-of-stock and stamp its id into the
     * hidden field so the POST carries the exact SKU — critical for
     * restock notifications to target only the matching variation
     * later, not the parent product.
     */
    function bindVariations() {
        $(document).on('found_variation', 'form.variations_form', function (e, variation) {
            var $form = $(this);
            var $wl   = $form.closest('.product').find('.aieo-waitlist-container');
            if (!$wl.length) return;
            $wl.find('.aieo-waitlist-variation-id').val(variation.variation_id);
            if (!variation.is_in_stock) { $wl.addClass('show'); }
            else                         { $wl.removeClass('show'); }
        });
        $(document).on('reset_data', 'form.variations_form', function () {
            var $wl = $(this).closest('.product').find('.aieo-waitlist-container');
            if (!$wl.length) return;
            $wl.find('.aieo-waitlist-variation-id').val(0);
            $wl.removeClass('show');
        });
    }

    $(function () {
        $(document).on('submit', '.aieo-waitlist-form', handleSubmit);
        bindVariations();
    });
})(jQuery);
