document.addEventListener('DOMContentLoaded', function() {
    if (typeof window.packshotphotoConfig === 'undefined') {
        console.warn('PMM: packshotphotoConfig not found during DOMContentLoaded');
        return;
    }

    var config    = window.packshotphotoConfig;
    var restUrl   = (config.restUrl || '').replace(/\/$/, '');
    var restNonce = config.restNonce || '';

    if (!restUrl) {
        console.error('PMM: restUrl missing from packshotphotoConfig');
        return;
    }

    function updateBalanceUI(balance) {
        var el   = document.getElementById('packshotphoto-balance-number');
        var bar  = document.getElementById('packshotphoto-balance-bar');
        var meta = document.getElementById('packshotphoto-balance-meta');
        if (el)   el.textContent = balance.toLocaleString();
        if (bar) {
            var pct = Math.min(100, Math.round(balance / 5000 * 100));
            bar.style.width      = pct + '%';
            bar.style.background = balance > 500 ? '#22c55e' : balance > 50 ? '#f59e0b' : '#ef4444';
        }
        if (meta) meta.textContent = packshotphotoConfig.i18n.creditGeneration + ' \u00b7 ' + pct + '% ' + packshotphotoConfig.i18n.maxPlan;
    }

    function renderTransactions(txs) {
        var tbody = document.getElementById('packshotphoto-tx-body');
        if (!tbody) return;
        if (!txs || !txs.length) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:#888;padding:20px;">' + packshotphotoConfig.i18n.noTransactions + '</td></tr>';
            return;
        }
        
        // Group transactions within 5 minutes of the same type
        var groupedTxs = [];
        var currentGroup = null;
        
        // Group transactions if they are the same type ('deduct') and within 5 minutes (300000 ms)
        for (var i = 0; i < txs.length; i++) {
            var tx = txs[i];
            var txDate = new Date(tx.created_at);
            
            if (!currentGroup) {
                currentGroup = Object.assign({}, tx);
                currentGroup.group_count = 1;
                currentGroup.lastDate = txDate;
            } else {
                var diffMs = Math.abs(currentGroup.lastDate - txDate);
                if (diffMs <= 300000 && currentGroup.type === tx.type && tx.type === 'deduct') {
                    currentGroup.amount += tx.amount;
                    currentGroup.group_count++;
                    currentGroup.lastDate = txDate; 
                } else {
                    groupedTxs.push(currentGroup);
                    currentGroup = Object.assign({}, tx);
                    currentGroup.group_count = 1;
                    currentGroup.lastDate = txDate;
                }
            }
        }
        if (currentGroup) {
            groupedTxs.push(currentGroup);
        }

        tbody.innerHTML = groupedTxs.map(function(tx) {
            var date      = new Date(tx.created_at).toLocaleDateString('pl-PL', { year:'numeric', month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' });
            var amt       = tx.amount > 0 ? '<span style="color:#22c55e;">+' + tx.amount + '</span>' : '<span style="color:#ef4444;">' + tx.amount + '</span>';
            var typeLabel = { purchase: '🛒 ' + packshotphotoConfig.i18n.purchase, deduct: '⚡ ' + packshotphotoConfig.i18n.aiUse, refund: '↩️ ' + packshotphotoConfig.i18n.refund, manual: '✎ ' + packshotphotoConfig.i18n.manual }[tx.type] || tx.type;
            
            if (tx.group_count > 1) {
                typeLabel += ' <span style="background:#e2e8f0;color:#475569;border-radius:12px;padding:2px 6px;font-size:10px;margin-left:4px;">x' + tx.group_count + '</span>';
            }

            return '<tr><td>' + date + '</td><td>' + typeLabel + '</td><td>' + amt + '</td><td>' + tx.balance_after + '</td><td>' + (tx.description || '-') + '</td></tr>';
        }).join('');
    }

    function loadStatus(force) {
        var url = restUrl + '/credits/status' + (force ? '?refresh=1' : '');
        url += (url.indexOf('?') !== -1 ? '&' : '?') + '_=' + Date.now();
        fetch(url, { headers: { 'X-WP-Nonce': restNonce } })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.credits_balance !== undefined) updateBalanceUI(data.credits_balance);
                if (data.transactions) renderTransactions(data.transactions);
            })
            .catch(function() {});
    }

    function runManualSync() {
        var statusDiv = document.getElementById('packshotphoto-checkout-status');
        var statusMsg = document.getElementById('packshotphoto-checkout-msg');
        var syncBtn   = document.getElementById('packshotphoto-refresh-balance');

        if (statusDiv) { statusDiv.style.display = 'flex'; statusDiv.style.background = ''; }
        if (statusMsg) statusMsg.textContent = packshotphotoConfig.i18n.syncSupabase;
        if (syncBtn) {
            syncBtn.innerHTML = '<span class="packshotphoto-spinner-inline" style="width:12px;height:12px;margin-right:5px;border-color:#888;border-top-color:transparent;"></span> ' + packshotphotoConfig.i18n.syncing;
            syncBtn.disabled = true;
        }

        fetch(restUrl + '/credits/sync', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': restNonce }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success) {
                if (data.balance !== undefined) updateBalanceUI(data.balance);
                if (statusDiv) statusDiv.style.background = '#d1fae5';
                if (statusMsg) statusMsg.textContent = '\u2705 ' + data.message;
                setTimeout(function() {
                    fetch(restUrl + '/credits/status?_=' + Date.now(), { headers: { 'X-WP-Nonce': restNonce } })
                        .then(function(r) { return r.json(); })
                        .then(function(status) {
                            if (status.credits_balance !== undefined) updateBalanceUI(status.credits_balance);
                            if (status.transactions) renderTransactions(status.transactions);
                            setTimeout(function() { if (statusDiv) statusDiv.style.display = 'none'; }, 2000);
                        })
                        .catch(function() { if (statusDiv) statusDiv.style.display = 'none'; });
                }, 500);
                // Clean URL if it was a success redirect
                if (window.location.search.indexOf('packshotphoto_checkout=success') !== -1) {
                    window.history.replaceState({}, document.title, window.location.pathname + '?page=pro-media-manager&tab=dev');
                }
            } else {
                if (statusMsg) statusMsg.textContent = '\u274c ' + (data.message || 'Nie znaleziono platnosci.');
                setTimeout(function() { if (statusDiv) statusDiv.style.display = 'none'; }, 3000);
            }
        })
        .catch(function(err) {
            if (statusMsg) statusMsg.textContent = 'Blad: ' + err.message;
            setTimeout(function() { if (statusDiv) statusDiv.style.display = 'none'; }, 3000);
        })
        .finally(function() {
            if (syncBtn) { syncBtn.textContent = '\u21bb Refresh Credits'; syncBtn.disabled = false; }
        });
    }

    function initBilling() {
        console.log('PMM Billing: initialized, restUrl=' + restUrl);

        // Refresh Credits button
        var refreshBtn = document.getElementById('packshotphoto-refresh-balance');
        if (refreshBtn && !refreshBtn.dataset.pmmInit) {
            refreshBtn.dataset.pmmInit = '1';
            refreshBtn.addEventListener('click', function(e) {
                e.preventDefault();
                runManualSync();
            });
        }

        // Buy buttons
        document.querySelectorAll('.packshotphoto-buy-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var statusDiv = document.getElementById('packshotphoto-checkout-status');
                var statusMsg = document.getElementById('packshotphoto-checkout-msg');
                if (statusDiv) {
                    statusDiv.style.display = 'block';
                    statusMsg.textContent = 'Trwa przekierowanie do platnosci...';
                }
                this.style.pointerEvents = 'none';
                this.style.opacity = '0.5';
            });
        });

        // Auto-detect checkout success after redirect
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('packshotphoto_checkout') === 'success') {
            var statusDiv2 = document.getElementById('packshotphoto-checkout-status');
            var statusMsg2 = document.getElementById('packshotphoto-checkout-msg');
            if (statusDiv2) statusDiv2.style.display = 'flex';
            if (statusMsg2) statusMsg2.textContent = 'Trwa weryfikacja platnosci...';

            var polls = 0;
            var autoPollInterval = setInterval(function() {
                polls++;
                if (polls > 12) {
                    clearInterval(autoPollInterval);
                    if (statusMsg2) {
                        statusMsg2.innerHTML = 'Weryfikacja trwa dluzej... <a href="#" id="packshotphoto-retry-sync" style="color:#6366f1;font-weight:700;">Sprobuj synchronizacji recznej</a>';
                        var retryBtn = document.getElementById('packshotphoto-retry-sync');
                        if (retryBtn) retryBtn.onclick = function(e) { e.preventDefault(); runManualSync(); };
                    }
                    return;
                }
                fetch(restUrl + '/credits/sync', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': restNonce }
                })
                .then(function(r) { return r.json(); })
                .then(function(syncData) {
                    if (syncData.success && syncData.balance !== undefined) {
                        var balEl = document.getElementById('packshotphoto-balance-number');
                        var currentBalance = parseInt((balEl ? balEl.textContent : '0').replace(/[^\d]/g, '') || '0');
                        if (syncData.balance > currentBalance || polls >= 3) {
                            clearInterval(autoPollInterval);
                            if (statusDiv2) statusDiv2.style.background = '#d1fae5';
                            if (statusMsg2) statusMsg2.textContent = '\u2705 Platnosc potwierdzona! Kredyty dodane.';
                            updateBalanceUI(syncData.balance);
                            fetch(restUrl + '/credits/status?_=' + Date.now(), { headers: { 'X-WP-Nonce': restNonce } })
                                .then(function(r) { return r.json(); })
                                .then(function(status) {
                                    if (status.transactions) renderTransactions(status.transactions);
                                    if (status.credits_balance !== undefined) updateBalanceUI(status.credits_balance);
                                    setTimeout(function() { if (statusDiv2) statusDiv2.style.display = 'none'; }, 3000);
                                });
                        }
                    }
                })
                .catch(function() {});
            }, 5000);
        }

        // Countdown timer for 50% Welcome Promo
        var promoBanner = document.getElementById('packshotphoto-welcome-promo');
        var promoDigits = document.getElementById('packshotphoto-promo-countdown');
        if (promoBanner && promoDigits) {
            var expireTimestamp = parseInt(promoBanner.getAttribute('data-expire') || '0', 10);
            function updateTimer() {
                var now = Math.floor(Date.now() / 1000);
                var diff = expireTimestamp - now;
                if (diff <= 0) {
                    promoBanner.style.display = 'none';
                    return;
                }
                var hours = Math.floor(diff / 3600);
                var mins  = Math.floor((diff % 3600) / 60);
                var secs  = diff % 60;
                var pad   = function(n) { return n < 10 ? '0' + n : n; };
                promoDigits.textContent = pad(hours) + ':' + pad(mins) + ':' + pad(secs);
            }
            updateTimer();
            setInterval(updateTimer, 1000);
        }

        // Initial balance load
        loadStatus(true);
    }

    initBilling();
});
