(function($) {
    'use strict';

    var PCMembership = {
        stripe: null,

        init: function() {
            this.bindEvents();
            this.initStripe();
        },

        bindEvents: function() {
            $(document).on('click', '.pc-membership-select-plan-btn', $.proxy(this.selectPlan, this));
            $(document).on('submit', '#pc-membership-login-form', $.proxy(this.handleLogin, this));
            $(document).on('submit', '#pc-membership-register-form', $.proxy(this.handleRegister, this));
            $(document).on('submit', '#pc-membership-profile-form', $.proxy(this.handleProfileUpdate, this));
            $(document).on('click', '#pc-membership-cancel-subscription', $.proxy(this.cancelSubscription, this));
            $(document).on('click', '#pc-membership-update-payment-method', $.proxy(this.updatePaymentMethod, this));
        },

        initStripe: function() {
            if (typeof Stripe !== 'undefined' && pcMembership.stripe_key) {
                this.stripe = Stripe(pcMembership.stripe_key);
            }
        },

        selectPlan: function(e) {
            e.preventDefault();
            var planId = $(e.currentTarget).data('plan-id');

            if (!planId) {
                alert(pcMembership.i18n.selectPlan);
                return;
            }

            var $button = $(e.currentTarget);
            var originalText = $button.text();
            $button.text(pcMembership.i18n.processing).prop('disabled', true);

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_create_checkout',
                    plan_id: planId,
                    nonce: pcMembership.nonce
                },
                success: $.proxy(function(response) {
                    if (response.success && response.data.url) {
                        window.location.href = response.data.url;
                    } else {
                        alert(pcMembership.i18n.error + ': ' + (response.data || 'Unknown error'));
                        $button.text(originalText).prop('disabled', false);
                    }
                }, this),
                error: $.proxy(function() {
                    alert(pcMembership.i18n.error);
                    $button.text(originalText).prop('disabled', false);
                }, this)
            });
        },

        handleLogin: function(e) {
            e.preventDefault();
            var $form = $('#pc-membership-login-form');
            var $message = $('#pc-membership-login-message');
            var formData = $form.serialize();

            $message.removeClass('success error').hide();

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: formData + '&action=pc_membership_login&nonce=' + pcMembership.nonce,
                success: $.proxy(function(response) {
                    if (response.success) {
                        $message.addClass('success').text(pcMembership.i18n.success).show();
                        setTimeout(function() {
                            window.location.href = response.data.redirect || pcMembership.account_url;
                        }, 1000);
                    } else {
                        $message.addClass('error').text(response.data || pcMembership.i18n.error).show();
                    }
                }, this),
                error: function() {
                    $message.addClass('error').text(pcMembership.i18n.error).show();
                }
            });
        },

        handleRegister: function(e) {
            e.preventDefault();
            var $form = $('#pc-membership-register-form');
            var $message = $('#pc-membership-register-message');
            var formData = $form.serialize();

            var password = $('#user_password').val();
            var passwordConfirm = $('#user_password_confirm').val();

            if (password !== passwordConfirm) {
                $message.addClass('error').text('Passwords do not match').show();
                return;
            }

            if (password.length < 8) {
                $message.addClass('error').text('Password must be at least 8 characters').show();
                return;
            }

            $message.removeClass('success error').hide();

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: formData + '&action=pc_membership_register&nonce=' + pcMembership.nonce,
                success: $.proxy(function(response) {
                    if (response.success) {
                        $message.addClass('success').text(pcMembership.i18n.success).show();
                        setTimeout(function() {
                            window.location.href = response.data.redirect || pcMembership.account_url;
                        }, 1000);
                    } else {
                        $message.addClass('error').text(response.data || pcMembership.i18n.error).show();
                    }
                }, this),
                error: function() {
                    $message.addClass('error').text(pcMembership.i18n.error).show();
                }
            });
        },

        handleProfileUpdate: function(e) {
            e.preventDefault();
            var $form = $('#pc-membership-profile-form');

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: $form.serialize() + '&action=pc_membership_update_profile&nonce=' + pcMembership.nonce,
                success: function(response) {
                    if (response.success) {
                        alert('Profile updated successfully');
                    } else {
                        alert(response.data || 'Error updating profile');
                    }
                }
            });
        },

        cancelSubscription: function(e) {
            e.preventDefault();
            if (!confirm(pcMembership.i18n.confirmCancel)) return;

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

            $button.text(pcMembership.i18n.processing).prop('disabled', true);

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_cancel_subscription',
                    subscription_id: subscriptionId,
                    nonce: pcMembership.nonce
                },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        alert(pcMembership.i18n.error);
                        $button.text(pcMembership.i18n.cancel).prop('disabled', false);
                    }
                },
                error: function() {
                    alert(pcMembership.i18n.error);
                    $button.text(pcMembership.i18n.cancel).prop('disabled', false);
                }
            });
        },

        updatePaymentMethod: function(e) {
            e.preventDefault();

            $.ajax({
                url: pcMembership.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_update_payment_method',
                    nonce: pcMembership.nonce
                },
                success: function(response) {
                    if (response.success && response.data.url) {
                        window.location.href = response.data.url;
                    } else {
                        alert(pcMembership.i18n.error);
                    }
                }
            });
        }
    };

    $(document).ready(function() {
        PCMembership.init();
    });

})(jQuery);
