{% load i18n unfold static %}

{% component "unfold/components/card.html" %}
    {% component "unfold/components/title.html" %}
        {{ daily_title|default:_('Daily sales') }}
    {% endcomponent %}
    <div class="w-full">
        <canvas id="dailySalesChart" height="120"></canvas>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    {{ daily_labels|json_script:"daily-labels" }}
    {{ daily_orders|json_script:"daily-orders" }}
    {{ daily_gross|json_script:"daily-gross" }}
    <script>
        (function () {
            try {
                let labels = [];
                let orders = [];
                let gross = [];
                const elL = document.getElementById('daily-labels');
                const elO = document.getElementById('daily-orders');
                const elG = document.getElementById('daily-gross');
                if (elL && elO && elG) {
                    labels = JSON.parse(elL.textContent || '[]');
                    orders = JSON.parse(elO.textContent || '[]');
                    gross = JSON.parse(elG.textContent || '[]');
                }
                if (!labels || labels.length === 0) {
                    const now = new Date();
                    labels = [];
                    orders = [];
                    gross = [];
                    for (let i = 29; i >= 0; i--) {
                        const d = new Date(now);
                        d.setDate(now.getDate() - i);
                        const day = String(d.getDate()).padStart(2, '0');
                        const month = d.toLocaleString(undefined, {month: 'short'});
                        labels.push(`${day} ${month}`);
                        orders.push(0);
                        gross.push(0);
                    }
                }

                const ctx = document.getElementById('dailySalesChart').getContext('2d');
                const green = 'rgb(34,197,94)';
                const blue = 'rgb(59,130,246)';

                const currency = "{% if currency_symbol %}{{ currency_symbol }}{% endif %}";

                const allZeroOrders = (orders || []).every(function (v) { return Number(v || 0) === 0; });
                const allZeroGross = (gross || []).every(function (v) { return Number(v || 0) === 0; });

                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: '{{ _("Orders (FINISHED)") }}',
                                data: orders,
                                borderColor: allZeroOrders ? 'rgba(0,0,0,0)' : green,
                                backgroundColor: allZeroOrders ? 'rgba(0,0,0,0)' : green,
                                borderWidth: allZeroOrders ? 0 : 2,
                                tension: 0.25,
                                pointRadius: allZeroOrders ? 0 : 2,
                                yAxisID: 'yOrders',
                            },
                            {
                                label: '{{ _("Gross revenue") }}',
                                data: gross,
                                borderColor: allZeroGross ? 'rgba(0,0,0,0)' : blue,
                                backgroundColor: allZeroGross ? 'rgba(0,0,0,0)' : blue,
                                borderWidth: allZeroGross ? 0 : 2,
                                tension: 0.25,
                                pointRadius: allZeroGross ? 0 : 2,
                                yAxisID: 'yRevenue',
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: {mode: 'index', intersect: false},
                        plugins: {
                            legend: {display: true},
                            tooltip: {
                                callbacks: {
                                    label: function (context) {
                                        const label = context.dataset.label || '';
                                        const val = context.parsed.y;
                                        if (context.dataset.yAxisID === 'yRevenue') {
                                            return `${label}: ${currency}${val}`;
                                        }
                                        return `${label}: ${val}`;
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                grid: {display: false}
                            },
                            yOrders: {
                                type: 'linear',
                                position: 'left',
                                title: {display: true, text: '{{ _("Orders") }}'},
                                grid: {color: 'rgba(0,0,0,0.06)'},
                                ticks: {precision: 0}
                            },
                            yRevenue: {
                                type: 'linear',
                                position: 'right',
                                title: {display: true, text: '{{ _("Gross") }}'},
                                grid: {drawOnChartArea: false},
                                ticks: {
                                    callback: function (value) {
                                        return `${currency}${value}`;
                                    }
                                }
                            }
                        }
                    }
                });
            } catch (e) {
                console && console.warn && console.warn('Chart init failed', e);
            }
        })();
    </script>
{% endcomponent %}
