<div class="dealflow-dashboard-widget" id="dealflow-revenue-{{ random() }}" style="display:flex;flex-direction:column;overflow:hidden;min-width:0;position:relative;flex:1 1 0;min-height:0;">
    <div style="text-align:right;margin-bottom:8px;">
        <div style="display:inline-flex;border:1px solid var(--border-subtle-01, #ddd);border-radius:4px;overflow:hidden;font-size:11px;">
            <button type="button" class="dealflow-rev-toggle" data-mode="weekly"
                style="padding:3px 10px;border:none;cursor:pointer;font-size:11px;
                    background:var(--brand-primary, #4e79a7);color:#fff;">
                By Week
            </button>
            <button type="button" class="dealflow-rev-toggle" data-mode="cumulative"
                style="padding:3px 10px;border:none;cursor:pointer;font-size:11px;
                    background:transparent;color:var(--text-secondary, #666);">
                Cumulative
            </button>
        </div>
    </div>

    {% set hasRevenue = false %}
    {% for week in weeklyData %}
        {% if week.revenue != '0' %}
            {% set hasRevenue = true %}
        {% endif %}
    {% endfor %}

    {% if hasRevenue or cumulativeData|last.revenue != '0' %}
        <div class="dealflow-rev-view" data-view="weekly" style="display:block;position:relative;">
            <canvas class="dealflow-rev-canvas" data-chart="weekly" height="140"></canvas>
        </div>
        <div class="dealflow-rev-view" data-view="cumulative" style="display:none;position:relative;">
            <canvas class="dealflow-rev-canvas" data-chart="cumulative" height="140"></canvas>
        </div>

        <div style="border-top:1px solid var(--border-subtle-01, #eee);margin-top:8px;padding-top:8px;display:flex;justify-content:space-between;font-size:12px;color:var(--text-secondary);">
            <span>Last {{ weeks * 7 }} days</span>
            <a href="{{ path('mautic_dealflow_reports') }}" style="color:var(--brand-primary, #4e79a7);text-decoration:none;">
                View reports &rarr;
            </a>
        </div>
    {% else %}
        <p style="color:var(--text-secondary);font-size:13px;">No closed-won revenue in this period.</p>
    {% endif %}
    {% include '@DealFlow/Dashboard/_config_popover.html.twig' with {showDateRange: true, currentWeeks: currentWeeks|default(13)} %}
</div>

<script>
(function() {
    var allWidgets = document.querySelectorAll('.dealflow-dashboard-widget[id^="dealflow-revenue-"]');
    var widget = allWidgets[allWidgets.length - 1];
    if (!widget) return;

    var weeklyLabels = {{ weeklyData|map(w => w.weekStart)|json_encode|raw }};
    var weeklyValues = {{ weeklyData|map(w => w.revenue)|json_encode|raw }};
    var weeklyRanges = [
        {% for week in weeklyData %}
            "{{ week.weekStart }} – {{ week.weekEnd }}"{{ not loop.last ? ',' : '' }}
        {% endfor %}
    ];

    var cumulativeLabels = {{ cumulativeData|map(w => w.weekStart)|json_encode|raw }};
    var cumulativeValues = {{ cumulativeData|map(w => w.revenue)|json_encode|raw }};
    var cumulativeRanges = [
        {% for week in cumulativeData %}
            "{{ week.weekStart }} – {{ week.weekEnd }}"{{ not loop.last ? ',' : '' }}
        {% endfor %}
    ];

    function formatCurrency(val) {
        return '$' + Number(val).toLocaleString('en-US', {maximumFractionDigits: 0});
    }

    function createChart(canvas, labels, values, ranges, color, fillColor) {
        var ctx = canvas.getContext('2d');
        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    data: values.map(Number),
                    borderColor: color,
                    backgroundColor: fillColor,
                    borderWidth: 2.5,
                    pointRadius: 3.5,
                    pointBackgroundColor: color,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 1.5,
                    pointHoverRadius: 5,
                    pointHoverBackgroundColor: color,
                    pointHoverBorderColor: '#fff',
                    pointHoverBorderWidth: 2,
                    fill: true,
                    lineTension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: { display: false },
                scales: {
                    xAxes: [{
                        gridLines: { display: false },
                        ticks: {
                            fontSize: 10,
                            fontColor: '#999',
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 7
                        }
                    }],
                    yAxes: [{
                        gridLines: {
                            color: 'rgba(0,0,0,0.06)',
                            drawBorder: false,
                            zeroLineColor: 'rgba(0,0,0,0.06)'
                        },
                        ticks: {
                            fontSize: 10,
                            fontColor: '#999',
                            beginAtZero: true,
                            callback: function(val) { return formatCurrency(val); },
                            maxTicksLimit: 5
                        }
                    }]
                },
                tooltips: {
                    backgroundColor: 'rgba(0,0,0,0.8)',
                    titleFontSize: 12,
                    bodyFontSize: 13,
                    bodyFontStyle: 'bold',
                    xPadding: 10,
                    yPadding: 8,
                    cornerRadius: 4,
                    displayColors: false,
                    callbacks: {
                        title: function(items) {
                            return ranges[items[0].index] || items[0].xLabel;
                        },
                        label: function(item) {
                            return formatCurrency(item.yLabel);
                        }
                    }
                },
                hover: {
                    mode: 'index',
                    intersect: false
                }
            }
        });
    }

    var weeklyCanvas = widget.querySelector('[data-chart="weekly"]');
    var cumulativeCanvas = widget.querySelector('[data-chart="cumulative"]');
    var weeklyChart = null;
    var cumulativeChart = null;

    if (weeklyCanvas) {
        weeklyChart = createChart(
            weeklyCanvas, weeklyLabels, weeklyValues, weeklyRanges,
            '#4e79a7', 'rgba(78, 121, 167, 0.12)'
        );
    }

    // Toggle handling
    var toggles = widget.querySelectorAll('.dealflow-rev-toggle');
    var views = widget.querySelectorAll('.dealflow-rev-view');

    toggles.forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var mode = this.getAttribute('data-mode');

            toggles.forEach(function(b) {
                b.style.background = 'transparent';
                b.style.color = 'var(--text-secondary, #666)';
            });
            this.style.background = 'var(--brand-primary, #4e79a7)';
            this.style.color = '#fff';

            views.forEach(function(v) {
                v.style.display = v.getAttribute('data-view') === mode ? 'block' : 'none';
            });

            // Lazy-init cumulative chart on first toggle
            if (mode === 'cumulative' && !cumulativeChart && cumulativeCanvas) {
                cumulativeChart = createChart(
                    cumulativeCanvas, cumulativeLabels, cumulativeValues, cumulativeRanges,
                    '#28a745', 'rgba(40, 167, 69, 0.12)'
                );
            }

            // Resize charts after toggle (Chart.js needs this when container was hidden)
            if (mode === 'weekly' && weeklyChart) {
                weeklyChart.resize();
            }
            if (mode === 'cumulative' && cumulativeChart) {
                cumulativeChart.resize();
            }
        });
    });
})();
</script>
