(function () {
    'use strict';

    var cfg = typeof window.zertiHomeChart === 'object' && window.zertiHomeChart !== null ? window.zertiHomeChart : {};

    /** Match #zertiAdmin tokens (Vazirmatn + chart palette). */
    var ZERTI_CHART_FONT = "'Vazirmatn', system-ui, -apple-system, 'Segoe UI', sans-serif";

    function chartToken(name, fallback) {
        var admin = document.getElementById('zertiAdmin');
        if (!admin || typeof getComputedStyle !== 'function') {
            return fallback;
        }
        var value = getComputedStyle(admin).getPropertyValue(name);
        return value && String(value).trim() !== '' ? String(value).trim() : fallback;
    }

    function usesWesternChartDigits() {
        if (typeof window.zertiShouldLocalizeDigits === 'function') {
            return !window.zertiShouldLocalizeDigits();
        }
        var admin = document.getElementById('zertiAdmin');
        if (admin) {
            if (admin.getAttribute('data-zerti-digits-format') === 'western') {
                return true;
            }
            if (admin.getAttribute('data-zerti-digit-script') === 'western') {
                return true;
            }
        }
        var digitCfg = window.zertiDigitLocale;
        return !!(digitCfg && (digitCfg.format === 'western' || digitCfg.script === 'western'));
    }

    function toChartDigits(str) {
        var normalized =
            typeof window.zertiToLatinDigits === 'function' ? window.zertiToLatinDigits(String(str)) : String(str);
        if (usesWesternChartDigits()) {
            return normalized;
        }
        if (typeof window.zertiLocalizeDigits === 'function') {
            return window.zertiLocalizeDigits(normalized);
        }
        return normalized.replace(/[0-9]/g, function (d) {
            return '۰۱۲۳۴۵۶۷۸۹'.charAt(parseInt(d, 10));
        });
    }

    var PERSIAN_CURRENCY_CODES = ['IRR', 'IRT', 'IRHT', 'IRHR'];

    function isAmountFirst() {
        if (cfg.amountFirst === true || cfg.amountFirst === 1 || cfg.amountFirst === '1') {
            return true;
        }
        var code = String(cfg.currencyCode || '').toUpperCase();
        return PERSIAN_CURRENCY_CODES.indexOf(code) !== -1;
    }

    /** Amount + currency for chart (tooltips, axis, peak label); RTL isolate when Persian. */
    function formatAmount(n) {
        var x = Number(n);
        if (!isFinite(x)) {
            x = 0;
        }
        var decimals = typeof cfg.decimals === 'number' && cfg.decimals >= 0 ? cfg.decimals : 0;
        var s = x.toLocaleString('en-US', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
        });
        var out = toChartDigits(s);
        var sym = typeof cfg.currencySymbol === 'string' ? cfg.currencySymbol.trim() : '';
        if (sym === '') {
            return out;
        }
        var combined = isAmountFirst() ? out + '\u00a0' + sym : sym + '\u00a0' + out;
        if (isAmountFirst()) {
            return '\u2067' + combined + '\u2069';
        }
        return combined;
    }

    function coerceTotals(arr) {
        if (!Array.isArray(arr)) {
            return [];
        }
        return arr.map(function (v) {
            var n = Number(v);
            return isFinite(n) ? n : 0;
        });
    }

    function readChartPayload(wrap) {
        var dataEl = wrap.querySelector('script.zerti-home-revenue-chart__data');
        var raw = dataEl ? dataEl.textContent : wrap.getAttribute('data-zerti-revenue-json');
        if (!raw) {
            return null;
        }
        try {
            return JSON.parse(raw.trim());
        } catch (e) {
            return null;
        }
    }

    function formatPointLabel(n) {
        var x = Number(n);
        if (!isFinite(x) || x === 0) {
            return toChartDigits('0');
        }
        return formatAmount(x);
    }

    function chartColors(isLight) {
        if (isLight) {
            return {
                border: chartToken('--zerti-chart-brand-border', 'rgba(113, 44, 249, 0.85)'),
                fill: chartToken('--zerti-chart-brand-fill', 'rgba(113, 44, 249, 0.12)'),
                grid: chartToken('--zerti-chart-grid-light', 'rgba(33, 37, 41, 0.12)'),
                text: chartToken('--zerti-chart-text-light', 'rgba(33, 37, 41, 0.75)'),
                label: chartToken('--zerti-chart-label-light', 'rgba(33, 37, 41, 0.92)'),
                labelBg: chartToken('--zerti-chart-label-bg-light', 'rgba(255, 255, 255, 0.92)'),
            };
        }
        return {
            border: chartToken('--zerti-chart-brand-border-dark', 'rgba(171, 136, 255, 0.95)'),
            fill: chartToken('--zerti-chart-brand-fill-dark', 'rgba(171, 136, 255, 0.15)'),
            grid: chartToken('--zerti-chart-grid-dark', 'rgba(255, 255, 255, 0.08)'),
            text: chartToken('--zerti-chart-text-dark', 'rgba(255, 255, 255, 0.65)'),
            label: chartToken('--zerti-chart-label-dark', 'rgba(255, 255, 255, 0.92)'),
            labelBg: chartToken('--zerti-chart-label-bg-dark', 'rgba(33, 37, 41, 0.88)'),
        };
    }

    var WEEK_DAYS = 7;

    /** Index of the highest sell day (> 0) within [start, end), or -1 if none. */
    function findPeakValueIndexInRange(values, start, end) {
        var peakIdx = -1;
        var peakVal = -Infinity;
        for (var i = start; i < end; i++) {
            var n = Number(values[i]);
            if (!isFinite(n) || n <= 0) {
                continue;
            }
            if (n > peakVal) {
                peakVal = n;
                peakIdx = i;
            }
        }
        return peakIdx;
    }

    /** One peak index per 7-day window (30-day chart → up to 5 labels). */
    function findWeeklyPeakIndices(values) {
        var indices = [];
        if (!Array.isArray(values) || values.length === 0) {
            return indices;
        }
        for (var start = 0; start < values.length; start += WEEK_DAYS) {
            var end = Math.min(start + WEEK_DAYS, values.length);
            var peakIdx = findPeakValueIndexInRange(values, start, end);
            if (peakIdx >= 0) {
                indices.push(peakIdx);
            }
        }
        return indices;
    }

    function drawPeakLabel(ctx, chart, point, value, colors) {
        var text = formatPointLabel(value);
        var fontSize = 9;
        var lineHeight = fontSize + 4;
        var padX = 4;
        var padY = 2;
        var gap = 6;

        ctx.font = '600 ' + fontSize + 'px ' + ZERTI_CHART_FONT;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        if (isAmountFirst() && 'direction' in ctx) {
            ctx.direction = 'rtl';
        }

        var textW = ctx.measureText(text).width;
        var boxW = textW + padX * 2;
        var boxH = lineHeight + padY * 2;
        var x = point.x;
        var boxTop = point.y - gap - boxH;
        var boxLeft = x - boxW / 2;

        if (boxTop < chart.chartArea.top) {
            boxTop = chart.chartArea.top + 2;
        }

        ctx.fillStyle = colors.labelBg;
        ctx.beginPath();
        if (typeof ctx.roundRect === 'function') {
            ctx.roundRect(boxLeft, boxTop, boxW, boxH, 3);
        } else {
            ctx.rect(boxLeft, boxTop, boxW, boxH);
        }
        ctx.fill();

        ctx.fillStyle = colors.label;
        ctx.fillText(text, x, boxTop + boxH / 2);
    }

    /**
     * Draw sell amount above the peak day in each 7-day window.
     *
     * @param {{ label: string, labelBg: string }} colors
     * @returns {object}
     */
    function createPointLabelPlugin(colors) {
        return {
            id: 'zertiRevenuePointLabels',
            afterDatasetsDraw: function (chart) {
                var dataset = chart.data.datasets[0];
                if (!dataset || !Array.isArray(dataset.data)) {
                    return;
                }
                var meta = chart.getDatasetMeta(0);
                if (!meta || !meta.data || meta.hidden) {
                    return;
                }

                var peakIndices = findWeeklyPeakIndices(dataset.data);
                if (peakIndices.length === 0) {
                    return;
                }

                var ctx = chart.ctx;
                ctx.save();
                if (isAmountFirst() && 'direction' in ctx) {
                    ctx.direction = 'rtl';
                }

                peakIndices.forEach(function (peakIdx) {
                    var point = meta.data[peakIdx];
                    if (!point || point.skip || typeof point.x !== 'number' || typeof point.y !== 'number') {
                        return;
                    }
                    drawPeakLabel(ctx, chart, point, dataset.data[peakIdx], colors);
                });

                ctx.restore();
            },
        };
    }

    window.zertiInitHomeRevenueChart = function (root) {
        root = root || document.getElementById('zertiAdmin') || document;
        var wrap = root.querySelector('.zerti-home-revenue-chart');
        if (!wrap || typeof Chart === 'undefined') {
            return;
        }
        var data = readChartPayload(wrap);
        if (!data || !Array.isArray(data.labels) || !Array.isArray(data.totals)) {
            return;
        }
        data.totals = coerceTotals(data.totals);
        var canvas = wrap.querySelector('canvas.zerti-home-revenue-chart__canvas');
        if (!canvas) {
            return;
        }
        var payloadKey = JSON.stringify({ labels: data.labels, totals: data.totals });
        var existing = Chart.getChart(canvas);
        if (existing) {
            var currentKey = wrap.getAttribute('data-zerti-chart-key') || '';
            if (currentKey === payloadKey) {
                return;
            }
            existing.destroy();
        }
        wrap.setAttribute('data-zerti-chart-key', payloadKey);

        var admin = document.getElementById('zertiAdmin');
        var isLight = admin && admin.getAttribute('data-bs-theme') === 'light';
        var colors = chartColors(isLight);

        var datasetLabel = typeof cfg.datasetLabel === 'string' ? cfg.datasetLabel : '';
        var pointLabelPlugin = createPointLabelPlugin(colors);

        new Chart(canvas.getContext('2d'), {
            type: 'line',
            plugins: [pointLabelPlugin],
            data: {
                labels: data.labels,
                datasets: [
                    {
                        label: datasetLabel,
                        data: data.totals,
                        borderColor: colors.border,
                        backgroundColor: colors.fill,
                        borderWidth: 2,
                        fill: true,
                        tension: 0.25,
                        pointRadius: 0,
                        pointHitRadius: 8,
                        pointHoverRadius: 4,
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                layout: {
                    padding: { top: 22, left: 6, right: 6 },
                },
                font: {
                    family: ZERTI_CHART_FONT,
                    size: 11,
                },
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        titleFont: { family: ZERTI_CHART_FONT, size: 12, weight: '600' },
                        bodyFont: { family: ZERTI_CHART_FONT, size: 12 },
                        footerFont: { family: ZERTI_CHART_FONT, size: 11 },
                        callbacks: {
                            label: function (ctx) {
                                var v = ctx.parsed && typeof ctx.parsed.y === 'number' ? ctx.parsed.y : 0;
                                return formatAmount(v);
                            },
                        },
                    },
                },
                scales: {
                    x: {
                        grid: { color: colors.grid },
                        ticks: {
                            color: colors.text,
                            font: { family: ZERTI_CHART_FONT, size: 10 },
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 8,
                        },
                    },
                    y: {
                        beginAtZero: true,
                        grace: '12%',
                        grid: { color: colors.grid },
                        ticks: {
                            color: colors.text,
                            font: { family: ZERTI_CHART_FONT, size: 10 },
                            callback: function (v) {
                                return formatAmount(v);
                            },
                        },
                    },
                },
            },
        });
    };
})();
