jQuery(document).ready(function($) {
    
    // --- DASHBOARD JS ---
    if ($('#profwabr-dashboard-app').length > 0) {
        let performanceChart = null;

        function loadDashboard() {
            const btn = $('#profwabr-refresh-dashboard');
            const range = $('#profwabr-range-selector').val();
            const descText = {
                "1": "today",
                "7": "for the last 7 days",
                "30": "for the last 30 days",
                "365": "for the last year"
            };

            btn.prop('disabled', true).text('Loading...');
            $('.profwabr-dashboard-header p').text('Financial performance overview ' + descText[range] + '.');
            
            $.post(profwabrAdminData.ajaxurl, {
                action: 'profwabr_get_dashboard_data',
                _ajax_nonce: profwabrAdminData.reportNonce,
                days: range
            }, function(response) {
                if (response.success && response.data) {
                    const data = response.data;
                    $('#val-revenue').text(data.metrics.revenue + ' €');
                    $('#val-profit').text(data.metrics.profit + ' €');
                    $('#val-margin').text(data.metrics.margin + ' %');
                    $('#val-orders').text(data.metrics.orders);
                    
                    let adSpend = data.metrics.ad_spend !== undefined ? data.metrics.ad_spend : 0.0;
                    let realProfit = data.metrics.real_net_profit !== undefined ? data.metrics.real_net_profit : data.metrics.profit;
                    let roas = data.metrics.roas !== undefined && data.metrics.roas !== null ? data.metrics.roas : 0.0;
                    
                    $('#val-adspend').text(adSpend.toFixed(2) + ' €');
                    $('#val-realprofit').text(realProfit.toFixed(2) + ' €');
                    $('#val-roas').text(roas > 0 ? roas.toFixed(2) + 'x' : 'N/A');

                    let fixedCosts = data.fixed_costs_monthly || 0;
                    let avgMargin = data.metrics.margin || 0;
                    
                    let dailyBurnRate = fixedCosts / 30;
                    let rangeDays = parseInt(range);
                    let periodFixedCosts;
                    if (rangeDays === 365) {
                        periodFixedCosts = fixedCosts * 12;
                    } else {
                        periodFixedCosts = dailyBurnRate * rangeDays;
                    }
                    
                    let periodBreakevenPoint = avgMargin > 0 ? (periodFixedCosts / (avgMargin / 100)) : 0;
                    let monthlyBreakevenPoint = avgMargin > 0 ? (fixedCosts / (avgMargin / 100)) : 0;

                    $('#val-dbr').text(dailyBurnRate.toFixed(2) + ' €');
                    $('#val-bep').text(avgMargin > 0 ? periodBreakevenPoint.toFixed(2) + ' €' : 'N/A');

                    let isMonthly = rangeDays > 60;
                    let bepLineValue = isMonthly ? monthlyBreakevenPoint : (monthlyBreakevenPoint / 30);
                    let bepLineLabel = isMonthly ? 'Monthly Breakeven Point (€)' : 'Daily Breakeven Point (€)';

                    renderChart(data.chart_data, bepLineValue, bepLineLabel);
                    renderRankings(data.rankings);
                    if (data.recent_orders) {
                        renderRecentOrders(data.recent_orders);
                    }
                } else {
                    alert('Error loading data: ' + response.data);
                }
                btn.prop('disabled', false).text('🔄 Refresh Data');
            });
        }

        function renderRecentOrders(orders) {
            const feedList = $('#profwabr-recent-feed');
            feedList.empty();

            if (orders && orders.length > 0) {
                orders.forEach(o => {
                    let badgeClass = '';
                    let badgeText = '';
                    let badgePrefix = '';

                    if (o.profit <= 0) {
                        badgeClass = 'profwabr-badge-loss';
                        badgeText = 'LOSS';
                        badgePrefix = o.profit < 0 ? '-' : '';
                        o.profit = Math.abs(o.profit);
                    } else if (o.margin < 15) {
                        badgeClass = 'profwabr-badge-watch';
                        badgeText = 'WATCH';
                        badgePrefix = '+';
                    } else {
                        badgeClass = 'profwabr-badge-profit';
                        badgeText = 'PROFIT';
                        badgePrefix = '+';
                    }

                    feedList.append(`
                        <li class="profwabr-feed-item">
                            <span class="profwabr-feed-id">#${o.order_id}</span>
                            <span class="profwabr-feed-rev">
                                €${o.revenue.toFixed(2)} rev.
                                <span class="profwabr-feed-detail">VAT: €${o.vat.toFixed(2)} | COGS: €${o.cogs.toFixed(2)}</span>
                            </span>
                            <span class="profwabr-feed-badge ${badgeClass}">${badgeText} ${badgePrefix}€${o.profit.toFixed(2)}</span>
                        </li>
                    `);
                });
            } else {
                feedList.append('<li class="profwabr-feed-item">No recent orders</li>');
            }
        }

        function renderRankings(rankings) {
            const prodContainer = $('#list-products');
            const custContainer = $('#list-customers');
            
            prodContainer.empty();
            custContainer.empty();

            if (rankings.products && rankings.products.length > 0) {
                let tableHTML = `<table class="profwabr-table-full">
                    <thead><tr><th>Product</th><th>Qty</th><th>Rev</th><th>VAT</th><th>COGS</th></tr></thead>
                    <tbody>`;
                rankings.products.forEach(p => {
                    tableHTML += `<tr>
                        <td>${p.name}</td>
                        <td><span class="profwabr-mini-badge">${p.qty} pcs</span></td>
                        <td class="profwabr-table-val">€${p.revenue.toFixed(2)}</td>
                        <td class="profwabr-table-val">€${p.vat.toFixed(2)}</td>
                        <td class="profwabr-table-val">€${p.cogs.toFixed(2)}</td>
                    </tr>`;
                });
                tableHTML += `</tbody></table>`;
                prodContainer.html(tableHTML);
            } else {
                prodContainer.html('<p style="padding: 10px; color: var(--profwabr-text-muted);">No data available</p>');
            }

            if (rankings.customers && rankings.customers.length > 0) {
                let cTable = `<table class="profwabr-table-full">
                    <thead><tr><th>Customer</th><th>Orders</th><th>Revenue</th><th>Profit</th></tr></thead>
                    <tbody>`;
                rankings.customers.forEach(c => {
                    cTable += `<tr>
                        <td>${c.name}</td>
                        <td><span class="profwabr-mini-badge">${c.orders} ord</span></td>
                        <td class="profwabr-table-val">€${c.revenue.toFixed(2)}</td>
                        <td class="profwabr-table-val">€${c.profit.toFixed(2)}</td>
                    </tr>`;
                });
                cTable += `</tbody></table>`;
                custContainer.html(cTable);
            } else {
                custContainer.html('<p style="padding: 10px; color: var(--profwabr-text-muted);">No data available</p>');
            }
        }

        function renderChart(chartData, bepLineValue, bepLineLabel) {
            const ctx = document.getElementById('profwabr-performance-chart').getContext('2d');
            Chart.defaults.color = '#8b949e';
            Chart.defaults.font.family = '"Inter", sans-serif';
            
            if (performanceChart) {
                performanceChart.destroy();
            }

            const labels = chartData.map(d => d.day);
            const revenue = chartData.map(d => d.revenue);
            const profitGross = chartData.map(d => d.profit);
            const profitReal = chartData.map(d => d.real_profit !== undefined ? d.real_profit : d.profit);
            const adSpend = chartData.map(d => d.ad_spend !== undefined ? d.ad_spend : 0.0);

            performanceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: 'Revenue (€)',
                            data: revenue,
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            fill: true,
                            tension: 0.4
                        },
                        {
                            label: 'Ad Spend (€)',
                            data: adSpend,
                            borderColor: '#eab308',
                            backgroundColor: 'rgba(234, 179, 8, 0.1)',
                            fill: true,
                            tension: 0.4
                        },
                        {
                            label: 'Real Profit (€)',
                            data: profitReal,
                            borderColor: '#00e676',
                            backgroundColor: 'rgba(0, 230, 118, 0.1)',
                            fill: true,
                            tension: 0.4
                        },
                        {
                            label: bepLineLabel,
                            data: labels.map(() => bepLineValue.toFixed(2)),
                            borderColor: 'rgba(255, 77, 79, 1)',
                            backgroundColor: 'transparent',
                            borderWidth: 2,
                            borderDash: [5, 5],
                            pointRadius: 0,
                            fill: false,
                            tension: 0
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'top' },
                        tooltip: { mode: 'index', intersect: false }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(255, 255, 255, 0.05)' }
                        },
                        y: { 
                            beginAtZero: true,
                            grid: { color: 'rgba(255, 255, 255, 0.05)' }
                        }
                    }
                }
            });
        }

        $('#profwabr-refresh-dashboard').click(loadDashboard);
        $('#profwabr-range-selector').change(loadDashboard);
        loadDashboard();
    }

    // --- SETTINGS PAGE JS ---
    if ($('#profwabr-send-report-btn').length > 0) {
        $('#profwabr-send-report-btn').click(function() {
            var btn = $(this);
            var status = $('#profwabr-report-status');
            
            btn.prop('disabled', true).text('Sending...');
            status.text('').css('color', 'black');

            $.post(profwabrAdminData.ajaxurl, {
                action: 'profwabr_send_report',
                _ajax_nonce: profwabrAdminData.reportNonce
            }, function(response) {
                if (response.success) {
                    status.text('✅ ' + response.data).css('color', 'green');
                } else {
                    status.text('❌ ' + response.data).css('color', 'red');
                }
                btn.prop('disabled', false).text('📧 Send Full Report');
            });
        });

        $('#profwabr-test-smtp-btn').click(function() {
            var btn = $(this);
            var status = $('#profwabr-smtp-status');
            
            btn.prop('disabled', true).text('Testing...');
            status.text('').css('color', 'black');

            $.post(profwabrAdminData.ajaxurl, {
                action: 'profwabr_test_smtp',
                _ajax_nonce: profwabrAdminData.reportNonce
            }, function(response) {
                if (response.success) {
                    status.text('✅ ' + response.data).css('color', 'green');
                } else {
                    status.text('❌ ' + response.data).css('color', 'red');
                }
                btn.prop('disabled', false).text('🔧 Test Connection');
            });
        });
    }

    // --- COSTS / HEALTH CHECK JS ---
    if ($('#profwabr-refresh-check-btn').length > 0) {
        $('#profwabr-refresh-check-btn').click(function() {
            var btn = $(this);
            var container = $('#profwabr-config-results');
            
            btn.prop('disabled', true).text('Checking...');
            container.css('opacity', '0.5');

            $.post(profwabrAdminData.ajaxurl, {
                action: 'profwabr_ajax_config_check',
                _ajax_nonce: profwabrAdminData.reportNonce
            }, function(response) {
                if (response.success) {
                    container.html(response.data);
                }
                container.css('opacity', '1');
                btn.prop('disabled', false).text('🔄 Refresh Health Check');
            });
        });
    }

    // --- WOOCOMMERCE PRODUCT COST META BOX JS ---
    // Ricarica la pagina dopo il ricalcolo dei totali per forzare l'aggiornamento dell'analisi (WooCommerce)
    $(document.body).on('order-totals-recalculate-complete', function(){
        const params = new URLSearchParams(window.location.search);
        if (params.has('post')) { setTimeout(function(){ window.location.reload(); }, 500); }
    });

    // --- ADS DASHBOARD JS ---
    if ($('#profwabr-dashboard-app.profwabr-ads-dashboard-app').length > 0) {
        
        function loadAdSummary() {
            const btn = $('#profwabr-refresh-ads-dashboard');
            const range = $('#profwabr-ads-range-selector').val();
            
            btn.prop('disabled', true).text('Loading...');
            
            $.post(profwabrAdminData.ajaxurl, {
                action: 'profwabr_get_ad_summary',
                _ajax_nonce: profwabrAdminData.reportNonce,
                days: range
            }, function(response) {
                if (response.success && response.data) {
                    const data = response.data;
                    
                    // Update KPI cards
                    $('#ads-val-spend').text((data.total_ad_spend || 0).toFixed(2) + ' €');
                    $('#ads-val-revenue').text((data.total_revenue || 0).toFixed(2) + ' €');
                    
                    // Summarize attributed orders
                    let totalAttributedOrders = 0;
                    if (data.campaigns && data.campaigns.length > 0) {
                        totalAttributedOrders = data.campaigns.reduce((sum, c) => sum + (c.attributed_orders || 0), 0);
                    }
                    $('#ads-val-orders').text(totalAttributedOrders);
                    
                    let roasVal = data.global_roas !== undefined && data.global_roas !== null ? data.global_roas.toFixed(2) + 'x' : 'N/A';
                    $('#ads-val-roas').text(roasVal);

                    // Render table
                    renderAdCampaignsTable(data.campaigns);
                } else {
                    $('#list-ad-campaigns').html('<p style="color: var(--profwabr-loss-color);">Error loading data or no data available.</p>');
                }
                btn.prop('disabled', false).text('🔄 Refresh Ads Stats');
            });
        }

        function renderAdCampaignsTable(campaigns) {
            const container = $('#list-ad-campaigns');
            container.empty();

            if (campaigns && campaigns.length > 0) {
                let tableHTML = `<table class="profwabr-table-full">
                    <thead><tr><th>Platform</th><th>Campaign</th><th>Spend</th><th>Orders</th><th>Revenue</th><th>ROAS</th></tr></thead>
                    <tbody>`;
                
                campaigns.forEach(c => {
                    let platIcon = c.platform === 'meta' ? '🟦' : (c.platform === 'google' ? '🟥' : '◼️');
                    let platName = c.platform.charAt(0).toUpperCase() + c.platform.slice(1);
                    
                    let roasStr = c.roas !== undefined && c.roas !== null ? c.roas.toFixed(2) + 'x' : 'N/A';
                    
                    // Simple color coding for ROAS badge
                    let badgeClass = 'profwabr-badge-watch';
                    if (c.roas > 2) badgeClass = 'profwabr-badge-profit';
                    if (c.roas < 1 && c.roas !== null) badgeClass = 'profwabr-badge-loss';
                    
                    let roasHTML = c.roas !== null ? `<span class="profwabr-feed-badge ${badgeClass}">${roasStr}</span>` : '<span style="color:#888;">--</span>';

                    tableHTML += `<tr>
                        <td>${platIcon} ${platName}</td>
                        <td><strong>${c.campaign_name}</strong></td>
                        <td class="profwabr-table-val">€${c.spend.toFixed(2)}</td>
                        <td><span class="profwabr-mini-badge">${c.attributed_orders || 0}</span></td>
                        <td class="profwabr-table-val">€${(c.attributed_revenue || 0).toFixed(2)}</td>
                        <td>${roasHTML}</td>
                    </tr>`;
                });
                
                tableHTML += `</tbody></table>`;
                container.html(tableHTML);
            } else {
                container.html('<p style="padding: 10px; color: var(--profwabr-text-muted);">No ad spend data available for the selected period.</p>');
            }
        }

        $('#profwabr-refresh-ads-dashboard').click(loadAdSummary);
        $('#profwabr-ads-range-selector').change(loadAdSummary);
        loadAdSummary();
    }

});
