/**
 * Frontend JavaScript for Stripe Subscription Manager
 */

(function($) {
    'use strict';

    if (typeof strp_sub_params === 'undefined') { return; }

    /**
     * Show a temporary inline notice to the user.
     */
    function showNotice($context, message, type) {
        var cssClass = type === 'error' ? 'strp-sub-notice--error' : 'strp-sub-notice--success';
        var $notice = $('<div class="strp-sub-notice ' + cssClass + '" role="alert"></div>').text(message);
        $context.before($notice);
        setTimeout(function () { $notice.fadeOut(400, function () { $(this).remove(); }); }, 5000);
    }

    /**
     * ES5-compatible URL parameter retrieval.
     */
    function getUrlParam(name) {
        var match = window.location.search.match(new RegExp('[?&]' + name + '=([^&]*)'));
        return match ? decodeURIComponent(match[1]) : null;
    }

    /**
     * Get affiliate reference code from multiple sources
     * Priority: button data attribute > URL parameter > session storage > cookie
     */
    function getAffiliateRef($button) {
        // 1. Check if button has data-affiliate-ref attribute (theme can set this)
        var affiliateRef = $button.data('affiliate-ref');
        if (affiliateRef) {
            return affiliateRef;
        }

        // 2. Check URL for ?ref=CODE parameter
        affiliateRef = getUrlParam('ref');
        if (affiliateRef) {
            // Store in sessionStorage for future requests
            try {
                sessionStorage.setItem('strp_sub_affiliate_ref', affiliateRef);
            } catch (e) {
                // Ignore sessionStorage errors
            }
            return affiliateRef;
        }

        // 3. Check sessionStorage
        try {
            affiliateRef = sessionStorage.getItem('strp_sub_affiliate_ref');
            if (affiliateRef) {
                return affiliateRef;
            }
        } catch (e) {
            // Ignore sessionStorage errors
        }

        // 4. Check cookie as fallback
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.indexOf('strp_sub_affiliate_ref=') === 0) {
                return decodeURIComponent(cookie.substring('strp_sub_affiliate_ref='.length));
            }
        }

        return null;
    }

    $(document).ready(function() {
        // Handle subscription button click
        $(document).on('click', '.strp-sub-subscribe-button', function(e) {
            e.preventDefault();

            var $button = $(this);
            var productId = $button.data('product-id');
            var priceId = $button.data('price-id');
            var subscriptionType = $button.data('subscription-type');

            // Disable button and show loading state
            $button.prop('disabled', true).addClass('strp-sub-loading');

            // Get affiliate code from URL parameter or button data attribute
            var affiliateRef = getAffiliateRef($button);

            // Create checkout session
            var ajaxData = {
                action: 'strp_sub_create_checkout_session',
                nonce: strp_sub_params.nonce,
                product_id: productId,
                price_id: priceId,
                subscription_type: subscriptionType
            };

            // Add affiliate ref if present
            if (affiliateRef) {
                ajaxData.affiliate_ref = affiliateRef;
            }

            $.ajax({
                url: strp_sub_params.ajax_url,
                type: 'POST',
                timeout: 30000,
                data: ajaxData,
                success: function(response) {
                    if (response.success) {
                        // Redirect to Stripe Checkout (validate domain for security)
                        if (response.data.url && /^https:\/\/[a-z]+\.stripe\.com\//.test(response.data.url)) {
                            window.location.href = response.data.url;
                        } else if (response.data.url) {
                            showNotice($button, strp_sub_params.i18n_error || 'Unexpected checkout URL', 'error');
                            $button.prop('disabled', false).removeClass('strp-sub-loading');
                        } else {
                            showNotice($button, strp_sub_params.i18n_no_checkout_url || 'Error: No checkout URL received', 'error');
                            $button.prop('disabled', false).removeClass('strp-sub-loading');
                        }
                    } else {
                        showNotice($button, response.data.message || strp_sub_params.i18n_error || 'An error occurred', 'error');
                        $button.prop('disabled', false).removeClass('strp-sub-loading');
                    }
                },
                error: function() {
                    showNotice($button, strp_sub_params.i18n_error || 'An error occurred. Please try again.', 'error');
                    $button.prop('disabled', false).removeClass('strp-sub-loading');
                }
            });
        });

        // Handle cancel subscription button click
        $(document).on('click', '.strp-sub-cancel-subscription', function(e) {
            e.preventDefault();

            if (!confirm(strp_sub_params.i18n_confirm_cancel || 'Are you sure you want to cancel this subscription?')) {
                return;
            }

            var $button = $(this);
            var subscriptionId = $button.data('subscription-id');

            // Disable button and show loading state
            $button.prop('disabled', true).addClass('strp-sub-loading');

            // Cancel subscription
            $.ajax({
                url: strp_sub_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'strp_sub_cancel_subscription',
                    nonce: strp_sub_params.nonce,
                    subscription_id: subscriptionId
                },
                success: function(response) {
                    if (response.success) {
                        showNotice($button, response.data.message || strp_sub_params.i18n_cancelled || 'Subscription cancelled successfully', 'success');
                        setTimeout(function () { location.reload(); }, 1500);
                    } else {
                        showNotice($button, response.data.message || strp_sub_params.i18n_error || 'An error occurred', 'error');
                        $button.prop('disabled', false).removeClass('strp-sub-loading');
                    }
                },
                error: function() {
                    showNotice($button, strp_sub_params.i18n_error || 'An error occurred. Please try again.', 'error');
                    $button.prop('disabled', false).removeClass('strp-sub-loading');
                }
            });
        });
    });

})(jQuery);
