// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /assets/js/amai-dashboard.js
// Description: Dashboard tab — SVG bar charts, async Stripe subscription fetch
// Last Edited: 2026-04-22
// ==================================================

(function () {
    'use strict';

    var data = window.amaiDashData || {};

    // ── SVG bar chart — posts published ──────────────────────────────
    function renderPostsChart() {
        var wrap = document.getElementById('amai-chart-posts');
        if (!wrap) { return; }

        var days   = data.days   || [];
        var counts = data.counts || [];
        if (days.length === 0) { return; }

        var maxVal = Math.max.apply(null, counts.concat([1]));
        var W      = 700;
        var H      = 130;
        var padL   = 10;
        var padR   = 10;
        var padT   = 14;
        var padB   = 22;
        var n      = days.length;
        var slotW  = (W - padL - padR) / n;
        var barW   = Math.max(4, slotW - 3);
        var chartH = H - padT - padB;

        var bars   = '';
        var labels = '';
        var vals   = '';

        // X-axis labels — show every 5th day only to avoid crowding
        for (var i = 0; i < n; i++) {
            var x     = padL + i * slotW + slotW / 2;
            var val   = counts[i] || 0;
            var barH  = val > 0 ? Math.max(4, (val / maxVal) * chartH) : 0;
            var barY  = padT + chartH - barH;

            bars += '<rect class="amai-chart-bar" x="' + (x - barW / 2).toFixed(1) + '" y="' + barY.toFixed(1) + '" width="' + barW.toFixed(1) + '" height="' + Math.max(0, barH).toFixed(1) + '" rx="3"><title>' + escHtml(days[i]) + ': ' + val + ' post' + (val === 1 ? '' : 's') + '</title></rect>';

            if (i % 5 === 0 || i === n - 1) {
                labels += '<text class="amai-chart-label" x="' + x.toFixed(1) + '" y="' + (H - 4) + '">' + escHtml(days[i]) + '</text>';
            }

            if (val > 0) {
                vals += '<text class="amai-chart-val" x="' + x.toFixed(1) + '" y="' + (barY - 3).toFixed(1) + '">' + val + '</text>';
            }
        }

        var svg = '<svg class="amai-chart-svg" viewBox="0 0 ' + W + ' ' + H + '" preserveAspectRatio="none" aria-hidden="true">' + bars + labels + vals + '</svg>';
        wrap.innerHTML = svg;
    }

    // ── SVG bar chart — engagement by channel ────────────────────────
    function renderChannelChart() {
        var wrap = document.getElementById('amai-chart-channels');
        if (!wrap) { return; }

        var rows = data.channelEngagement || [];
        if (rows.length === 0) { return; }

        var maxScore = 1;
        for (var i = 0; i < rows.length; i++) {
            var s = parseFloat(rows[i].score || 0);
            if (s > maxScore) { maxScore = s; }
        }

        var W     = 380;
        var H     = 130;
        var padL  = 80;
        var padR  = 50;
        var padT  = 8;
        var padB  = 8;
        var n     = rows.length;
        var slotH = (H - padT - padB) / n;
        var barH  = Math.max(8, slotH - 6);
        var chartW = W - padL - padR;

        var channelColors = {
            'facebook':  '#1877F2',
            'instagram': '#E1306C',
            'x':         '#000000',
            'tiktok':    '#010101',
            'linkedin':  '#0A66C2',
            'google':    '#4285F4'
        };

        var bars   = '';
        var labels = '';
        var vals   = '';

        for (var j = 0; j < n; j++) {
            var row     = rows[j];
            var channel = (row.channel || '').toLowerCase();
            var score   = parseFloat(row.score || 0);
            var posts   = parseInt(row.post_count || 0, 10);
            var barW    = score > 0 ? Math.max(6, (score / maxScore) * chartW) : 6;
            var y       = padT + j * slotH;
            var barY    = y + (slotH - barH) / 2;
            var color   = channelColors[channel] || '#D97757';
            var label   = channel.charAt(0).toUpperCase() + channel.slice(1);

            bars   += '<rect fill="' + color + '" x="' + padL + '" y="' + barY.toFixed(1) + '" width="' + barW.toFixed(1) + '" height="' + barH + '" rx="3" opacity="0.85"><title>' + escHtml(label) + ': ' + posts + ' post' + (posts === 1 ? '' : 's') + '</title></rect>';
            labels += '<text class="amai-chart-label--channel" x="0" y="' + (barY + barH / 2 + 4).toFixed(1) + '" style="font-family:\'DM Sans\',sans-serif;font-size:11px;fill:#57534E;">' + escHtml(label) + '</text>';
            vals   += '<text style="font-family:\'DM Mono\',monospace;font-size:10px;fill:#A8A29E;text-anchor:start;" x="' + (padL + barW + 6).toFixed(1) + '" y="' + (barY + barH / 2 + 4).toFixed(1) + '">' + posts + 'p</text>';
        }

        var svg = '<svg class="amai-chart-svg" viewBox="0 0 ' + W + ' ' + H + '" preserveAspectRatio="xMidYMid meet" aria-hidden="true">' + bars + labels + vals + '</svg>';
        wrap.innerHTML = svg;
    }

    // ── Async Stripe subscription fetch ──────────────────────────────
    function fetchSubscription() {
        if (data.mrrOverride !== null && data.mrrOverride !== undefined) {
            var mrrEl = document.getElementById('amai-mrr-value');
            if (mrrEl) { mrrEl.textContent = '$' + parseFloat(data.mrrOverride).toFixed(2); }
            var metaEl = document.getElementById('amai-mrr-meta');
            if (metaEl) { metaEl.textContent = '100% discount applied'; }
            return;
        }
        if (!data.hasStripe) { return; }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', data.ajaxUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) { return; }
            if (xhr.status !== 200) { return; }

            var resp;
            try {
                resp = JSON.parse(xhr.responseText);
            } catch (e) {
                return;
            }

            if (!resp.success || !resp.data) { return; }

            var d = resp.data;

            // MRR
            var mrrEl = document.getElementById('amai-mrr-value');
            if (mrrEl) {
                mrrEl.innerHTML = escHtml(d.mrr_formatted || '$0.00');
            }

            // Meta line
            var metaEl = document.getElementById('amai-mrr-meta');
            if (metaEl) {
                var metaText = d.billing_period || '';
                if (d.plan_name) {
                    metaText = escHtml(d.plan_name) + (metaText ? ' &middot; ' + escHtml(metaText) : '');
                }
                metaEl.innerHTML = metaText || 'Active subscription';
            }

            // Next billing
            var nextEl = document.getElementById('amai-next-bill');
            if (nextEl && d.next_billing) {
                var parts  = d.next_billing.split('-');
                var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                var month  = months[parseInt(parts[1], 10) - 1] || parts[1];
                nextEl.innerHTML = 'Next billing: <span>' + escHtml(month + ' ' + parseInt(parts[2], 10) + ', ' + parts[0]) + '</span>';
            }

            // Member since
            var sinceEl = document.getElementById('amai-member-since');
            if (sinceEl && d.customer_since) {
                var sp    = d.customer_since.split('-');
                var smon  = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                var smonth = smon[parseInt(sp[1], 10) - 1] || sp[1];
                sinceEl.textContent = 'Customer since ' + smonth + ' ' + sp[0];
            }
        };

        var body = 'action=amai_dashboard_subscription&_ajax_nonce=' + encodeURIComponent(data.nonce || '');
        if (data.subId) {
            body += '&sub_id=' + encodeURIComponent(data.subId);
        }
        if (data.custId) {
            body += '&cust_id=' + encodeURIComponent(data.custId);
        }

        xhr.send(body);
    }

    // ── HTML escape helper ────────────────────────────────────────────
    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    // ── Init ──────────────────────────────────────────────────────────
    document.addEventListener('DOMContentLoaded', function () {
        renderPostsChart();
        renderChannelChart();
        fetchSubscription();
    });

}());