/**
 * Recast Paywall Frontend JavaScript
 */

(function($) {
    'use strict';

    // Initialize when DOM is ready
    $(document).ready(function() {
        RecastPaywall.init();
    });

    var RecastPaywall = {
        /**
         * Initialize the paywall
         */
        init: function() {
            this.initPaywallWidgets();
            this.initEntitlementChecks();
        },

        /**
         * Initialize paywall widgets
         */
        initPaywallWidgets: function() {
            $('.recast-paywall-widget').each(function() {
                var $el = $(this);
                var brandId = $el.data('brand-id');
                var sandbox = $el.data('sandbox');
                var postId = $el.data('post-id');

                if (!brandId) {
                    $el.html('<p>Paywall not configured.</p>');
                    return;
                }

                // Prefer new Recast Browser SDK instance (purchase via popup)
                if (window.RecastBrowser) {
                    try {
                        var rb = new window.RecastBrowser({ brandId: brandId, sandbox: !!sandbox });

                        // Create a CTA button for popup purchase
                        var btn = document.createElement('button');
                        btn.type = 'button';
                        btn.className = 'button recast-purchase-btn';
                        btn.textContent = 'Unlock';
                        $el.empty().append(btn);

                        var purchasing = false;
                        btn.addEventListener('click', function() {
                            if (purchasing) return;
                            purchasing = true;
                            btn.disabled = true;
                            // Ask server to create purchase intent (mode external)
                            $.ajax({
                                url: recastPaywall.restUrl + 'purchase-intent',
                                method: 'POST',
                                data: { post_id: postId },
                                headers: { 'X-WP-Nonce': recastPaywall.nonce }
                            }).then(function(resp) {
                                var token = resp.intentToken;
                                if (!token) throw new Error('Missing intent token');
                                return rb.purchaseViaPopup(token);
                            }).then(function() {
                                // Clear entitlement cache before reload
                                $.ajax({
                                    url: recastPaywall.restUrl + 'clear-cache',
                                    method: 'POST',
                                    data: { post_id: postId },
                                    headers: { 'X-WP-Nonce': recastPaywall.nonce }
                                }).then(function() {
                                    window.location.reload();
                                }).catch(function() {
                                    // Even if cache clear fails, reload anyway
                                    window.location.reload();
                                });
                            }).catch(function(err) {
                                RecastPaywall.handleError(err, $el);
                            }).always(function() {
                                purchasing = false;
                                btn.disabled = false;
                            });
                        });
                        return;
                    } catch (e) {
                        RecastPaywall.handleError(e, $el);
                    }
                }

                // No compatible API found
                $el.html('<p>Paywall widget could not be loaded. Please refresh the page.</p>');
            });
        },

        /**
         * Initialize entitlement checks
         */
        initEntitlementChecks: function() {
            $('.recast-paywall-gated-content, .recast-paywall-section').each(function() {
                var container = $(this);
                var postId = container.data('post-id');

                if (postId) {
                    RecastPaywall.checkEntitlement(postId, container);
                }
            });
        },

        /**
         * Check entitlement for a post
         */
        checkEntitlement: function(postId, container) {
            $.ajax({
                url: recastPaywall.restUrl + 'entitlement',
                method: 'GET',
                data: {
                    post_id: postId
                },
                headers: {
                    'X-WP-Nonce': recastPaywall.nonce
                },
                success: function(response) {
                    if (response.entitled) {
                        RecastPaywall.revealContent(postId, container);
                    }
                },
                error: function() {
                    // On error, keep content gated
                }
            });
        },

        /**
         * Reveal content for entitled users
         */
        revealContent: function(postId, container) {
            // Get the full content from the server
            $.ajax({
                url: recastPaywall.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'recast_get_full_content',
                    post_id: postId,
                    nonce: recastPaywall.nonce
                },
                success: function(response) {
                    if (response.success) {
                        container.html(response.data.content);
                        container.addClass('recast-content-revealed');
                        
                        // Trigger event for other scripts
                        $(document).trigger('recast-content-revealed', [postId, container]);
                    }
                },
                error: function() {
                    // Failed to load content
                }
            });
        },

        /**
         * Handle purchase event
         */
        handlePurchase: function(data, postId) {
            // Recheck entitlement after purchase
            setTimeout(function() {
                $('.recast-paywall-gated-content[data-post-id="' + postId + '"], .recast-paywall-section[data-post-id="' + postId + '"]').each(function() {
                    RecastPaywall.checkEntitlement(postId, $(this));
                });
            }, 1000);
        },

        /**
         * Handle success event
         */
        handleSuccess: function(data, postId) {
            // Recheck entitlement
            setTimeout(function() {
                $('.recast-paywall-gated-content[data-post-id="' + postId + '"], .recast-paywall-section[data-post-id="' + postId + '"]').each(function() {
                    RecastPaywall.checkEntitlement(postId, $(this));
                });
            }, 1000);
        },

        /**
         * Handle error event
         */
        handleError: function(error, widget) {
            widget.html('<p>An error occurred. Please try again.</p>');
        },

        /**
         * Public method to check entitlement (for external use)
         */
        checkEntitlementForPost: function(postId) {
            return new Promise(function(resolve, reject) {
                $.ajax({
                    url: recastPaywall.restUrl + 'entitlement',
                    method: 'GET',
                    data: {
                        post_id: postId
                    },
                    headers: {
                        'X-WP-Nonce': recastPaywall.nonce
                    },
                    success: function(response) {
                        resolve(response);
                    },
                    error: function(xhr, status, error) {
                        reject(error);
                    }
                });
            });
        }
    };

    // Expose to global scope
    window.RecastPaywall = RecastPaywall;

    // Poll for entitlement after purchase
    window.pollForEntitlement = function(postId, maxAttempts = 60, interval = 2000, onEntitled = null) {
        let attempts = 0;
        let polling = true;
        
        const poll = () => {
            if (!polling) return;
            
            attempts++;
            
            // Build URL with proper query string
            let apiUrl = recastPaywall.restUrl + 'entitlement';
            
            // Add query parameter
            const separator = apiUrl.includes('?') ? '&' : '?';
            apiUrl += separator + 'post_id=' + encodeURIComponent(postId);
            
            fetch(apiUrl, {
                headers: {
                    'X-WP-Nonce': recastPaywall.nonce
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.entitled) {
                    polling = false;
                    
                    // Call callback immediately
                    if (onEntitled) {
                        onEntitled();
                    }
                } else if (attempts >= maxAttempts) {
                    polling = false;
                } else {
                    // Continue polling
                    setTimeout(poll, interval);
                }
            })
            .catch(error => {
                if (attempts < maxAttempts) {
                    // Continue despite error
                    setTimeout(poll, interval);
                } else {
                    polling = false;
                }
            });
        };
        
        // Start polling
        poll();
        
        // Return stop function
        return () => {
            polling = false;
        };
    };

    // Reveal content after purchase
    window.revealPurchasedContent = function(postId) {
        // Find all paywalled content containers
        const containers = document.querySelectorAll(
            '.recast-paywall-post[data-post-id="' + postId + '"], ' +
            '.recast-paywall-block[data-post-id="' + postId + '"], ' +
            '.recast-paywall-section[data-post-id="' + postId + '"]'
        );
        
        if (containers.length === 0) {
            window.location.reload();
            return;
        }
        
        // Fetch full content
        $.ajax({
            url: recastPaywall.ajaxUrl,
            method: 'POST',
            data: {
                action: 'recast_get_full_content',
                post_id: postId,
                nonce: recastPaywall.nonce
            },
            success: function(response) {
                if (response.success && response.data.content) {
                    // Replace each paywall with the full content
                    containers.forEach(function(container) {
                        const $container = $(container);
                        const $parent = $container.parent();
                        
                        // Create content element(s) from HTML string
                        const $newContent = $(response.data.content).hide();
                        
                        // Fade out the paywall
                        $container.fadeOut(300, function() {
                            // Remove the paywall container completely
                            $container.remove();
                            
                            // Insert the content directly into parent (no wrapper)
                            $parent.append($newContent);
                            
                            // Fade in the new content
                            $newContent.fadeIn(300);
                        });
                    });
                    
                    // Trigger event for other scripts
                    $(document).trigger('recast-content-unlocked', [postId]);
                } else {
                    window.location.reload();
                }
            },
            error: function() {
                window.location.reload();
            }
        });
    };

    // Global purchase function for inline onclick handlers
    window.recastPurchaseContent = function(postId, evt) {
        // Show loading state on the button
        const button = evt ? evt.target : null;
        const originalText = button ? button.textContent : '';
        let stopPolling = null;
        
        if (button) {
            button.textContent = 'Processing...';
            button.disabled = true;
        }
        
        // Create purchase intent
        fetch(recastPaywall.restUrl + 'purchase-intent', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': recastPaywall.nonce
            },
            body: JSON.stringify({
                post_id: postId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.intentToken && window.RecastBrowser) {
                // Update button state
                if (button) {
                    button.textContent = 'Verifying purchase...';
                }
                
                // Start polling IMMEDIATELY (120 seconds, 60 attempts)
                // Callback fires when entitlement is detected
                stopPolling = window.pollForEntitlement(postId, 60, 2000, function() {
                    if (button) {
                        button.textContent = 'Unlocking...';
                    }
                    
                    // Reveal content without page reload
                    window.revealPurchasedContent(postId);
                });
                
                // Open wallet popup (runs in parallel with polling)
                const rb = new window.RecastBrowser({ 
                    brandId: recastPaywall.brandId, 
                    sandbox: recastPaywall.sandbox 
                });
                
                return rb.purchaseViaPopup(data.intentToken);
            } else if (data.intentUrl) {
                // Fallback: redirect to purchase URL
                window.location.href = data.intentUrl;
                return Promise.resolve();
            } else {
                throw new Error('No purchase method available');
            }
        })
        .then(() => {
            // Wallet closed - polling continues in background
            // Reset button but keep polling active
            if (button && !button.textContent.includes('Unlocking')) {
                button.textContent = 'Verifying purchase...';
            }
        })
        .catch(error => {
            // Stop polling on error
            if (stopPolling) {
                stopPolling();
            }
            
            // Check if this is a user cancellation (not an error)
            if (error && error.message && (
                error.message.includes('cancel') || 
                error.message.includes('close') ||
                error.message.includes('abort')
            )) {
                if (button) {
                    button.textContent = originalText;
                    button.disabled = false;
                }
                return;
            }
            
            // Real error - restore button
            if (button) {
                button.textContent = 'Try Again';
                button.disabled = false;
            }
            
            // Show user-friendly error message
            alert('Purchase failed. Please try again.');
        });
    };

})(jQuery);
