(function($) {
    'use strict';
    
    /**
     * Lean Cart Share and Save Frontend
     */
    window.lean_csns = {
        popup: {
            /**
             * Open popup with content
             *
             * @param {string} type    Popup type — drives the header title (share/save)
             * @param {string} content HTML content for the body area
             * @param {bool}   isPro   True when pro template is being used
             */
            open: function(type, content, isPro) {
                // Title lives in the core header; content goes into the body slot below it.
                var titleMap = {
                    share: lean_csns_params.i18n.share_title,
                    save:  lean_csns_params.i18n.save_title
                };
                $('.lean-csns-popup-title').text( titleMap[ type ] || '' );
                // Template ships with inline display:none (anti-flash); clear it so .is-open can show the popup.
                $('.lean-csns-popup-overlay, .lean-csns-popup').css('display', '').addClass('is-open');
                // Pro template already wraps its content in .lean-csns-pm-body; free gets it here.
                var body = isPro ? content : '<div class="lean-csns-pm-body">' + content + '</div>';
                $('.lean-csns-popup-content').html( body );
                if ( isPro ) {
                    $('.lean-csns-popup').addClass('lean-csns-popup--pro');
                }
            },

            /**
             * Close popup
             */
            close: function() {
                $('.lean-csns-popup-overlay, .lean-csns-popup').removeClass('is-open');
                $('.lean-csns-popup').removeClass('lean-csns-popup--pro');
            },
            
            /**
             * Update popup content
             * 
             * @param {string} content New HTML content
             */
            updateContent: function(content) {
                $('.lean-csns-popup-content').html(content);
            }
        },
        
        utils: {
            /**
             * Copy text to clipboard
             * 
             * @param {string} text Text to copy
             */
            copyToClipboard: function(text) {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(text).then(function() {
                        alert(lean_csns_params.i18n.link_copied);
                    }).catch(function() {
                        lean_csns.utils.fallbackCopyTextToClipboard(text);
                    });
                } else {
                    lean_csns.utils.fallbackCopyTextToClipboard(text);
                }
            },
            
            /**
             * Fallback method for copying text to clipboard
             * 
             * @param {string} text Text to copy
             */
            fallbackCopyTextToClipboard: function(text) {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed";
                textArea.style.top = "-9999px";
                textArea.style.left = "-9999px";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                
                try {
                    document.execCommand('copy');
                    alert(lean_csns_params.i18n.link_copied);
                } catch (err) {
                    alert('Failed to copy link');
                }
                
                document.body.removeChild(textArea);
            }
        },
        
        /**
         * Show loading state
         * 
         * @param {jQuery} button Button element
         */
        showLoading: function(button) {
            /* class-based lock — avoids WooCommerce overriding button[disabled] styles */
            button.addClass('lean-csns-is-loading').text('Loading...');
        },

        /**
         * Hide loading state
         *
         * @param {jQuery} button Button element
         * @param {string} originalText Original button text
         */
        hideLoading: function(button, originalText) {
            button.removeClass('lean-csns-is-loading').text(originalText);
        }
    };

    $(document).ready(function() {

        /**
         * Share Cart button click handler
         */
        $(document).on('click', '.lean-csns-share-btn', function() {
            var button = $(this);
            if ( button.hasClass('lean-csns-is-loading') ) return;
            var originalText = button.text();

            lean_csns.showLoading(button);
            
            $.ajax({
                url: lean_csns_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'lean_csns_share_cart',
                    nonce: lean_csns_params.nonce
                },
                success: function(response) {
                    lean_csns.hideLoading(button, originalText);

                    if (response.success) {
                        if ( response.popup_html ) {
                            // Pro template injected server-side — use it directly.
                            lean_csns.popup.open( 'share', response.popup_html, true );
                            $( document ).trigger( 'lean_csns_popup_opened', [ response.url, response.token ] );
                        } else {
                            // Free fallback: share URL + copy button. No inline onclick — delegated handlers below.
                            var shareUrl = response.url;
                            var content = '<input type="url" class="lean-csns-free-url-input" value="' + shareUrl + '" readonly>' +
                                        '<div class="lean-csns-popup-buttons">' +
                                        '<button type="button" class="lean-csns-free-copy-btn" data-url="' + shareUrl + '">' + lean_csns_params.i18n.copy_button + '</button>' +
                                        '<button type="button" class="lean-csns-free-close-btn">' + lean_csns_params.i18n.close_button + '</button>' +
                                        '</div>';
                            lean_csns.popup.open('share', content);
                        }
                    } else {
                        alert(response.message || 'Failed to share cart');
                    }
                },
                error: function() {
                    lean_csns.hideLoading(button, originalText);
                    alert('An error occurred while sharing the cart');
                }
            });
        });
        
        /**
         * Save Cart button click handler
         */
        $(document).on('click', '.lean-csns-save-btn', function() {
            var content = '<input type="text" id="cart-name-input" placeholder="' + lean_csns_params.i18n.enter_cart_name + '" maxlength="255">' +
                        '<div class="lean-csns-popup-buttons">' +
                        '<button type="button" id="save-cart-confirm">' + lean_csns_params.i18n.save_button + '</button>' +
                        '<button type="button" class="lean-csns-free-cancel-btn">' + lean_csns_params.i18n.cancel_button + '</button>' +
                        '</div>';
            lean_csns.popup.open('save', content);
            
            // Focus on input field
            setTimeout(function() {
                $('#cart-name-input').focus();
            }, 100);
        });
        
        /**
         * Save cart confirmation button click handler
         */
        $(document).on('click', '#save-cart-confirm', function() {
            var button = $(this);
            var originalText = button.text();
            var nameInput = $('#cart-name-input');
            var name = nameInput.val().trim();
            
            if (!name) {
                alert(lean_csns_params.i18n.cart_name_required);
                nameInput.focus();
                return;
            }
            
            lean_csns.showLoading(button);
            
            $.ajax({
                url: lean_csns_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'lean_csns_save_cart',
                    name: name,
                    nonce: lean_csns_params.nonce
                },
                success: function(response) {
                    lean_csns.hideLoading(button, originalText);
                    
                    alert(response.message || 'Cart operation completed');
                    
                    if (response.success) {
                        lean_csns.popup.close();
                    }
                },
                error: function() {
                    lean_csns.hideLoading(button, originalText);
                    alert('An error occurred while saving the cart');
                }
            });
        });
        
        /**
         * Handle Enter key in cart name input
         */
        $(document).on('keypress', '#cart-name-input', function(e) {
            if (e.which === 13) { // Enter key
                e.preventDefault();
                $('#save-cart-confirm').click();
            }
        });
        
        /**
         * Free fallback: copy button (delegated so it works after dynamic injection)
         */
        $(document).on('click', '.lean-csns-free-copy-btn', function() {
            lean_csns.utils.copyToClipboard( $(this).data('url') );
        });

        /**
         * Close popup: X button in core header + free text close/cancel buttons
         */
        $(document).on('click', '.lean-csns-close-popup, .lean-csns-free-close-btn, .lean-csns-free-cancel-btn', function() {
            lean_csns.popup.close();
        });

        /**
         * Close popup when clicking on overlay
         */
        $(document).on('click', '.lean-csns-popup-overlay', function(e) {
            if (e.target === this) {
                lean_csns.popup.close();
            }
        });
        
        /**
         * Close popup with Escape key
         */
        $(document).on('keydown', function(e) {
            if (e.keyCode === 27 && $('.lean-csns-popup').hasClass('is-open')) { // Escape key
                lean_csns.popup.close();
            }
        });
    });
    
})(jQuery);