/**
 * GT BOGO Engine — Admin JavaScript
 * Metric counters, modal system, animations, AJAX handlers
 */
(function($) {
    'use strict';

    // ── Metric Counter Animation ──────────────────────────────
    function animateCounter(el) {
        var target = parseFloat(el.dataset.value || el.textContent.replace(/[^0-9.]/g, ''));
        var prefix = el.dataset.prefix || '';
        var suffix = el.dataset.suffix || '';
        var decimals = (el.dataset.value || '0').includes('.') ? 2 : 0;
        var duration = 1200;
        var start = performance.now();
        var from = 0;

        el.classList.add('counting');

        function tick(now) {
            var elapsed = now - start;
            var progress = Math.min(elapsed / duration, 1);
            // Ease out cubic
            var eased = 1 - Math.pow(1 - progress, 3);
            var current = from + (target - from) * eased;
            el.textContent = prefix + (decimals ? current.toFixed(decimals) : Math.round(current).toLocaleString()) + suffix;

            if (progress < 1) {
                requestAnimationFrame(tick);
            } else {
                el.textContent = prefix + (decimals ? target.toFixed(decimals) : target.toLocaleString()) + suffix;
                el.classList.remove('counting');
            }
        }
        requestAnimationFrame(tick);
    }

    // Observe metric cards entering viewport
    var counterObserver = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                var value = entry.target;
                if (!value.dataset.animated) {
                    value.dataset.animated = '1';
                    setTimeout(function() { animateCounter(value); }, 100);
                }
                counterObserver.unobserve(value);
            }
        });
    }, { threshold: 0.3 });

    document.querySelectorAll('.gt-metric-value[data-value]').forEach(function(el) {
        counterObserver.observe(el);
    });

    // ── Modal System ──────────────────────────────────────────
    window.gtBogoOpenModal = function(id) {
        var overlay = document.getElementById(id);
        if (!overlay) return;
        overlay.style.display = 'flex';
        document.body.style.overflow = 'hidden';

        // Render PayPal button if needed
        var container = overlay.querySelector('.gt-paypal-wrap[data-btn]');
        if (container && !container.dataset.rendered && typeof paypal !== 'undefined') {
            container.dataset.rendered = '1';
            paypal.HostedButtons({ hostedButtonId: container.dataset.btn })
                .render(container);
        }

        // Trap focus
        overlay.querySelector('.gt-modal-close, .gt-btn, [tabindex]')?.focus();
    };

    window.gtBogoCloseModal = function(id) {
        var overlay = document.getElementById(id);
        if (!overlay) return;
        overlay.style.opacity = '0';
        overlay.style.transition = 'opacity 0.2s';
        setTimeout(function() {
            overlay.style.display = 'none';
            overlay.style.opacity = '';
            overlay.style.transition = '';
            document.body.style.overflow = '';
        }, 200);
    };

    // Close on overlay click
    document.querySelectorAll('.gt-modal-overlay').forEach(function(el) {
        el.addEventListener('click', function(e) {
            if (e.target === el) gtBogoCloseModal(el.id);
        });
    });

    // Close on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            document.querySelectorAll('.gt-modal-overlay[style*="flex"]').forEach(function(el) {
                gtBogoCloseModal(el.id);
            });
        }
    });

    // ── Pack Download Handler ─────────────────────────────────
    window.gtBogoDownloadPack = function(packId, btn) {
        btn.disabled = true;
        btn.classList.add('loading');
        var original = btn.textContent;
        btn.textContent = 'Downloading…';

        $.post(ajaxurl, {
            action: 'gtbogo_download_pack',
            pack_id: packId,
            nonce: gtBogoData.nonce
        })
        .done(function(data) {
            if (data.success) {
                btn.textContent = '✓ Imported!';
                btn.style.background = 'var(--gt-success)';
                btn.classList.remove('loading');
                setTimeout(function() { location.reload(); }, 1500);
            } else {
                showError(btn, original, data.data?.message || 'Download failed');
            }
        })
        .fail(function() {
            showError(btn, original, 'Connection error. Please retry.');
        });

        function showError(btn, original, msg) {
            btn.textContent = '✗ Error';
            btn.style.background = 'var(--gt-red)';
            btn.classList.remove('loading');
            btn.disabled = false;
            alert('GT BOGO: ' + msg);
            setTimeout(function() {
                btn.textContent = original;
                btn.style.background = '';
            }, 3000);
        }
    };

    // ── Settings Autosave ─────────────────────────────────────
    var autosaveTimer;
    $(document).on('change', '.gt-autosave', function() {
        var key = $(this).attr('name') || $(this).data('key');
        var val = $(this).is(':checkbox') ? ($(this).is(':checked') ? 1 : 0) : $(this).val();
        clearTimeout(autosaveTimer);
        autosaveTimer = setTimeout(function() {
            $.post(ajaxurl, {
                action: 'gtbogo_autosave_settings',
                option_key: key,
                option_value: val,
                nonce: gtBogoData.nonce
            }).done(function(r) {
                if (r.success) gtBogoToast('Settings saved', 'success');
            });
        }, 600);
    });

    // ── Toast Notifications ───────────────────────────────────
    window.gtBogoToast = function(msg, type) {
        type = type || 'info';
        var colors = {
            success: 'var(--gt-success)',
            error: 'var(--gt-red)',
            info: '#60a5fa',
            warn: 'var(--gt-warning)'
        };
        var toast = document.createElement('div');
        toast.style.cssText = [
            'position:fixed', 'bottom:24px', 'right:24px',
            'background:#0D1526', 'border:1px solid ' + (colors[type]||colors.info),
            'color:#fff', 'padding:12px 18px', 'border-radius:10px',
            'font-family:var(--gt-font)', 'font-size:13px', 'font-weight:500',
            'z-index:999999', 'box-shadow:0 8px 32px rgba(0,0,0,0.4)',
            'display:flex', 'align-items:center', 'gap:8px',
            'animation:gt-fade-up 0.3s ease both',
            'max-width:320px'
        ].join(';');
        var dot = document.createElement('span');
        dot.style.cssText = 'width:8px;height:8px;border-radius:50%;background:' + (colors[type]||colors.info) + ';flex-shrink:0';
        toast.appendChild(dot);
        toast.appendChild(document.createTextNode(msg));
        document.body.appendChild(toast);
        setTimeout(function() {
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.3s';
            setTimeout(function() { toast.remove(); }, 300);
        }, 3000);
    };

    // ── Tab System ────────────────────────────────────────────
    $(document).on('click', '.gt-tab', function() {
        var target = $(this).data('tab');
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        $(this).closest('.gt-card').find('.gt-tab-content').hide();
        $(this).closest('.gt-card').find('[data-tab-content="' + target + '"]').show();
    });

    // Activate first tab
    $('.gt-tabs').each(function() {
        $(this).find('.gt-tab:first').addClass('active');
        $(this).closest('.gt-card').find('.gt-tab-content:first').show();
        $(this).closest('.gt-card').find('.gt-tab-content').not(':first').hide();
    });

    // ── Smooth page load ──────────────────────────────────────
    document.querySelectorAll('.gt-fade').forEach(function(el, i) {
        el.style.animationDelay = (i * 0.05) + 's';
    });

    // ── License status live check ─────────────────────────────
    var $licenseStatus = $('#gt-license-status-live');
    if ($licenseStatus.length) {
        $.post(ajaxurl, { action: 'gtbogo_check_license', nonce: gtBogoData.nonce })
        .done(function(r) {
            if (r.success && r.data) {
                var status = r.data.status || 'unknown';
                var colors = { active: 'var(--gt-success)', expired: 'var(--gt-red)', inactive: 'var(--gt-warning)' };
                $licenseStatus
                    .text(status.charAt(0).toUpperCase() + status.slice(1))
                    .css('color', colors[status] || 'var(--gt-slate)');
            }
        });
    }

})(jQuery);
