/**
 * TamRank GSC Dashboard
 * Handles the GSC dashboard widget on the main dashboard page
 */
(function ($) {
    'use strict';

    class GSC_Dashboard {
        constructor() {
            this.chart = null;
            this.data = null;
            this.init();
        }

        init() {
            // Only run when there is an actual chart to render. The connect
            // empty-state also carries .tam-gsc-section but has no #gsc-chart,
            // so guarding on the chart avoids a pointless (failing) fetch there.
            if (!$('#gsc-chart').length) {
                return;
            }

            this.bindEvents();
            this.fetchData();
        }

        bindEvents() {
            $('#gsc-date-range').on('change', () => this.fetchData());
        }

        fetchData(force = false) {
            const range = $('#gsc-date-range').val() || 28;

            // Show loading state
            $('.tam-gsc-chart-loading').show();

            $.ajax({
                url: tamrank_gsc.ajax_url,
                type: 'POST',
                data: {
                    action: 'tamrank_gsc_fetch_data',
                    nonce: tamrank_gsc.nonce,
                    range: range,
                    force: force
                },
                success: (response) => {
                    if (response.success) {
                        this.data = response.data;
                        this.updateDashboard(response.data);
                    } else {
                        const errorMsg = response.data?.message || (tamrank_gsc.strings && tamrank_gsc.strings.error_fetching_data) || 'Error fetching data';
                        console.error('GSC Error:', errorMsg);
                        if (typeof tamRank !== 'undefined' && tamRank.toast) {
                            tamRank.toast.error(errorMsg);
                        }
                    }
                },
                error: () => {
                    console.error('GSC Connection error');
                    if (typeof tamRank !== 'undefined' && tamRank.toast) {
                        tamRank.toast.error((tamrank_gsc.strings && tamrank_gsc.strings.connection_error) || 'Connection error');
                    }
                },
                complete: () => {
                    $('.tam-gsc-chart-loading').hide();
                }
            });
        }

        updateDashboard(data) {
            // Update metric values
            $('#gsc-clicks').text(this.formatNumber(data.totals.clicks));
            $('#gsc-impressions').text(this.formatNumber(data.totals.impressions));
            $('#gsc-ctr').text(data.totals.ctr + '%');
            $('#gsc-position').text(data.totals.position);

            // Update change indicators
            this.updateChange('clicks', data.changes.clicks, '%');
            this.updateChange('impressions', data.changes.impressions, '%');
            this.updateChange('ctr', data.changes.ctr, '%');
            this.updateChange('position', data.changes.position, '', true);

            // Update chart
            this.renderChart(data.series);
        }

        updateChange(metric, change, suffix = '', invertColors = false) {
            const $el = $(`#gsc-${metric}-change`);
            const changeVal = parseFloat(change);
            let isPositive = changeVal >= 0;

            // For position, lower is better
            if (invertColors) {
                isPositive = changeVal <= 0;
            }

            const changeStr = changeVal >= 0 ? `+${changeVal}` : changeVal;
            const colorClass = isPositive ? 'positive' : 'negative';

            const trendIcon = isPositive
                ? `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>`
                : `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></svg>`;

            $el.removeClass('positive negative').addClass(colorClass);
            $el.html(`${trendIcon} ${changeStr}${suffix}`);
        }

        formatNumber(value) {
            if (typeof value === 'string') return value;
            if (value >= 1000000) {
                return (value / 1000000).toFixed(1) + 'M';
            } else if (value >= 1000) {
                return (value / 1000).toFixed(1) + 'K';
            }
            return value;
        }

        renderChart(series) {
            // Collapse to one point per calendar day. GSC normally returns daily rows, but a
            // transient/malformed response carrying intraday or duplicate-date rows would plot
            // many points inside a single day — and since ApexCharts renders one datetime tick
            // per point with a 'dd MMM' format, the whole x-axis would read the same day
            // (e.g. a wall of "17 Jun"). Keying by YYYY-MM-DD keeps the clean daily case
            // byte-identical while making a bad response degrade to correct daily labels.
            const byDay = {};
            (series || []).forEach((item) => {
                const day = String(item.date).slice(0, 10);
                byDay[day] = Object.assign({}, item, { date: day });
            });
            series = Object.keys(byDay).sort().map((d) => byDay[d]);

            const chartSeries = [
                {
                    name: 'Clicks',
                    type: 'area',
                    data: series.map(item => ({ x: item.date, y: item.clicks }))
                },
                {
                    name: 'Impressions',
                    type: 'line',
                    data: series.map(item => ({ x: item.date, y: item.impressions }))
                }
            ];

            const options = {
                series: chartSeries,
                chart: {
                    height: 300,
                    type: 'line',
                    toolbar: { show: false },
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 400
                    }
                },
                stroke: {
                    curve: 'smooth',
                    width: [2, 2]
                },
                fill: {
                    type: ['gradient', 'solid'],
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.5,
                        opacityTo: 0.1,
                        stops: [0, 90, 100]
                    }
                },
                colors: ['#10b981', '#1e293b'],
                dataLabels: { enabled: false },
                xaxis: {
                    type: 'datetime',
                    tooltip: { enabled: false },
                    labels: {
                        datetimeUTC: false,
                        format: 'dd MMM'
                    }
                },
                yaxis: [
                    {
                        seriesName: 'Clicks',
                        title: { text: '' },
                        labels: {
                            style: { colors: '#10b981' },
                            formatter: (val) => {
                                if (val >= 1000) return (val / 1000).toFixed(0) + 'K';
                                return val ? val.toFixed(0) : '0';
                            }
                        }
                    },
                    {
                        seriesName: 'Impressions',
                        opposite: true,
                        title: { text: '' },
                        labels: {
                            style: { colors: '#1e293b' },
                            formatter: (val) => {
                                if (val >= 1000) return (val / 1000).toFixed(0) + 'K';
                                return val ? val.toFixed(0) : '0';
                            }
                        }
                    }
                ],
                tooltip: {
                    shared: true,
                    intersect: false,
                    x: { format: 'dd MMM yyyy' },
                    y: {
                        formatter: (y) => y ? y.toLocaleString() : '0'
                    }
                },
                legend: {
                    show: true,
                    position: 'top',
                    horizontalAlign: 'right'
                },
                grid: {
                    borderColor: '#f1f1f1',
                    strokeDashArray: 3
                }
            };

            // Destroy and recreate chart
            if (this.chart) {
                this.chart.destroy();
            }

            $('#gsc-chart').html('');
            this.chart = new ApexCharts(document.querySelector('#gsc-chart'), options);
            this.chart.render();
        }
    }

    $(document).ready(function () {
        new GSC_Dashboard();

        // Dismiss the Search Console connect empty-state (per user). Hide
        // immediately and persist the choice fire-and-forget so the prompt
        // stays gone on the next dashboard load.
        $(document).on('click', '.tam-gsc-connect-dismiss', function () {
            var $card = $(this).closest('.tam-gsc-section--connect');
            $card.slideUp(150, function () {
                $(this).remove();
            });
            $.post(tamrank_gsc.ajax_url, {
                action: 'tamrank_gsc_dismiss_connect',
                nonce: tamrank_gsc.nonce
            });
        });
    });

})(jQuery);
