/**
 * TrackSharp Pricing Page - External Checkout Links
 * Replaces Freemius internal checkout links with external checkout URLs
 * and fixes the disabled "YOUR PLAN" button for trial users.
 */
(function() {
    'use strict';

    // Currency from PHP (eur for Dutch sites, usd for everyone else)
    var currency = (typeof TRACKSHARP_PRICING !== 'undefined' && TRACKSHARP_PRICING.currency) || 'usd';

    /**
     * Build a Freemius checkout URL for a given billing cycle and license count.
     */
    function buildCheckoutUrl(billingCycle, licenses) {
        return 'https://checkout.freemius.com/plugin/21630/plan/36087/licenses/' + licenses +
               '/?billing_cycle=' + billingCycle + '&currency=' + currency;
    }

    /**
     * Build a Freemius checkout URL with billing cycle selector (for Account page buttons).
     */
    function buildCheckoutUrlWithSelector(licenses) {
        return 'https://checkout.freemius.com/plugin/21630/plan/36087/licenses/' + (licenses || 1) +
               '/?billing_cycle_selector=list&currency=' + currency;
    }

    /**
     * Get current billing cycle from the page
     */
    function getCurrentBillingCycle() {
        var selected = document.querySelector('.fs-selected-billing-cycle');
        if (selected) {
            var cycle = selected.getAttribute('data-billing-cycle');
            if (cycle === 'monthly') return 'monthly';
            if (cycle === 'annual' || cycle === 'annually') return 'annually';
        }
        // Default to annual if can't determine
        return 'annually';
    }

    /**
     * Extract the first number from a text string.
     */
    function extractNumber(text) {
        var match = text.match(/\d+/);
        return match ? parseInt(match[0], 10) : 0;
    }

    /**
     * Get license count from package element
     */
    function getLicenseCount(packageEl) {
        // Try to find license quantity text
        var quantityEl = packageEl.querySelector('.fs-selected-pricing-license-quantity');
        if (quantityEl) {
            var text = quantityEl.textContent.toLowerCase();
            if (text.indexOf('single') !== -1) return 1;
            var num = extractNumber(text);
            if (num > 0) return num;
        }

        // Try plan title
        var titleEl = packageEl.querySelector('.fs-plan-title');
        if (titleEl) {
            var titleText = titleEl.textContent.toLowerCase();
            if (titleText.indexOf('single') !== -1) return 1;
            var titleNum = extractNumber(titleText);
            if (titleNum > 0) return titleNum;
        }

        // Fallback: first package = 1 license, second = higher tier
        var packages = document.querySelectorAll('.fs-package');
        for (var i = 0; i < packages.length; i++) {
            if (packages[i] === packageEl) {
                return i === 0 ? 1 : 10;
            }
        }

        return 1;
    }

    /**
     * Fix disabled "YOUR PLAN" buttons for trial users.
     * Only runs when the user is on an active trial.
     */
    function fixTrialDisabledButtons() {
        if (typeof TRACKSHARP_PRICING === 'undefined' || !TRACKSHARP_PRICING.is_trial) {
            return;
        }

        var packages = document.querySelectorAll('.fs-package');
        packages.forEach(function(pkg) {
            var buttons = pkg.querySelectorAll(
                '.fs-upgrade-button-container a, .fs-upgrade-button-container button'
            );
            buttons.forEach(function(btn) {
                // Remove disabled attribute
                if (btn.hasAttribute('disabled')) {
                    btn.removeAttribute('disabled');
                }
                // Fix text if it says "YOUR PLAN"
                var text = (btn.textContent || '').trim().toUpperCase();
                if (text === 'YOUR PLAN' || text === 'YOUR CURRENT PLAN') {
                    btn.textContent = 'Upgrade';
                }
                // Remove pointer-events:none from inline styles
                if (btn.style.pointerEvents === 'none') {
                    btn.style.pointerEvents = '';
                }
                // Remove disabled-related CSS classes
                btn.classList.remove('fs-disabled', 'fs-selected-plan', 'fs-current-plan');
            });
        });
    }

    /**
     * Update all checkout links on the Pricing page
     */
    function updateCheckoutLinks() {
        var cycle = getCurrentBillingCycle();
        var packages = document.querySelectorAll('.fs-package');

        packages.forEach(function(pkg) {
            var licenses = getLicenseCount(pkg);
            var button = pkg.querySelector('.fs-upgrade-button-container a, .fs-upgrade-button-container button');

            if (button) {
                var newUrl = buildCheckoutUrl(cycle, licenses);

                // If it's a button, convert to link
                if (button.tagName === 'BUTTON') {
                    var link = document.createElement('a');
                    link.href = newUrl;
                    link.target = '_blank';
                    link.rel = 'noopener noreferrer';
                    link.className = button.className;
                    link.textContent = 'Upgrade';
                    // Ensure the converted link is not disabled
                    link.removeAttribute('disabled');
                    link.classList.remove('fs-disabled', 'fs-selected-plan', 'fs-current-plan');
                    button.parentNode.replaceChild(link, button);
                } else {
                    button.href = newUrl;
                    button.target = '_blank';
                    button.rel = 'noopener noreferrer';
                    // Fix text if needed
                    var text = (button.textContent || '').trim().toUpperCase();
                    if (text === 'YOUR PLAN' || text === 'YOUR CURRENT PLAN') {
                        button.textContent = 'Upgrade';
                    }
                }

                // Prevent Freemius JS from overriding
                button.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            }
        });

        // Also fix any remaining disabled buttons (trial-specific)
        fixTrialDisabledButtons();
    }

    // Debounce timer to avoid running updateCheckoutLinks too frequently
    var debounceTimer = null;
    function debouncedUpdate() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(updateCheckoutLinks, 50);
    }

    /**
     * Initialize pricing page watchers
     */
    function init() {
        // Initial update
        updateCheckoutLinks();

        // Watch for billing cycle changes
        var billingCycles = document.querySelectorAll('.fs-billing-cycles li');
        billingCycles.forEach(function(cycle) {
            cycle.addEventListener('click', function() {
                // Small delay to let Freemius update the DOM
                setTimeout(updateCheckoutLinks, 100);
                setTimeout(updateCheckoutLinks, 300);
            });
        });

        // Observe DOM changes (in case Freemius re-renders and reverts our changes)
        var observer = new MutationObserver(function() {
            debouncedUpdate();
        });

        // Watch the entire pricing wrapper so we catch Freemius React re-renders
        var wrapper = document.querySelector('#fs_pricing_wrapper') ||
                      document.querySelector('.fs-section--packages');
        if (wrapper) {
            observer.observe(wrapper, {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ['href', 'disabled', 'class', 'style']
            });
        }

        // Persistent polling fallback: Freemius React app can re-render at unpredictable times,
        // so poll for a while after page load to catch any late reverts.
        var pollCount = 0;
        var pollInterval = setInterval(function() {
            updateCheckoutLinks();
            pollCount++;
            if (pollCount >= 20) {
                clearInterval(pollInterval);
            }
        }, 500);
    }

    /**
     * Fix upgrade buttons/links on the Freemius Account page.
     * Handles both the green "Upgrade" button in the Plan row
     * and the "Upgrade" tab in the nav-tab-wrapper.
     */
    function fixAccountPageUpgradeButtons() {
        var checkoutUrl = buildCheckoutUrlWithSelector(1);

        // 1. Green upgrade button in the Plan row
        var upgradeBtn = document.querySelector('a.button-upgrade, a.fs-upgrade');
        if (upgradeBtn && upgradeBtn.href.indexOf('checkout.freemius.com') === -1) {
            upgradeBtn.href = checkoutUrl;
            upgradeBtn.target = '_blank';
            upgradeBtn.rel = 'noopener noreferrer';
            upgradeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
            });
        }

        // 2. "Upgrade" nav tab at the top of the Account page
        var navTabs = document.querySelectorAll('.nav-tab-wrapper a.nav-tab');
        navTabs.forEach(function(tab) {
            var text = (tab.textContent || '').trim().toLowerCase();
            if (text === 'upgrade' && tab.href.indexOf('checkout.freemius.com') === -1) {
                tab.href = checkoutUrl;
                tab.target = '_blank';
                tab.rel = 'noopener noreferrer';
            }
        });
    }

    // Detect which page we're on
    var isPricingPage = document.querySelector('#fs_pricing_wrapper') ||
                        document.querySelector('.fs-section--packages');

    // Run when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            if (document.querySelector('#fs_pricing_wrapper') || document.querySelector('.fs-section--packages')) {
                init();
            }
            fixAccountPageUpgradeButtons();
        });
    } else {
        if (isPricingPage) {
            init();
        }
        fixAccountPageUpgradeButtons();
    }

    // Also run after delays to catch late Freemius rendering
    if (isPricingPage) {
        setTimeout(init, 500);
        setTimeout(init, 1500);
        setTimeout(init, 3000);
    }
    setTimeout(fixAccountPageUpgradeButtons, 500);
    setTimeout(fixAccountPageUpgradeButtons, 1500);
})();
