// source --> https://www.blacktie.se/wp-content/plugins/fm-price-history//assets/js/main.js?ver=1.0.6 
jQuery(document).ready(function ($) {

    let fmphInitialLoaded = false;
    let fmphChartCount = $('.fmph-graph').length;
    let fmph_charts = [];

    if ( fmphChartCount ) {
        $('.fmph-graph').each(function() {
            loadGraph( $(this).data('id'), $(this)[0] );
        });
    }

    $( document.body ).on( 'found_variation', function( event, variation ) {
        $('.fmph-graph').each(function() {
            loadGraph( variation.variation_id, $(this)[0] );
        });
    });

    function loadGraph( product_id, chartElement ) {

        if ( ! $('.fmph-graph').length ) return;

        $.ajax({
            url: fmph.ajaxurl,
            type: 'POST',
            data: {
                action: 'fmph_get_graph_data', 
                product_id: product_id,
            },
            beforeSend: function () {
            },
            success: function ( res ) {

                const isMobile = window.innerWidth <= 768;

                let labels = res.labels || [];
                let prices = res.prices || [];

                if ( isMobile ) {
                    labels = res.labels.map(label => {
                        const date = new Date(label);
                        const options = { day: 'numeric', month: 'short' };
                        const formattedDate = date.toLocaleString('sv-SE', options).split(' ');
                        const day = formattedDate[0];
                        const month = formattedDate[1].charAt(0).toUpperCase() + formattedDate[1].slice(1);
                        return `${day} ${month}`;
                    });
                } else {
                    labels = res.labels.map(label => {
                        const date = new Date(label);
                        const options = { day: 'numeric', month: 'long' };
                        const formattedDate = date.toLocaleString('sv-SE', options).split(' ');
                        const day = formattedDate[0];
                        const month = formattedDate[1].charAt(0).toUpperCase() + formattedDate[1].slice(1);
                        return `${day} ${month}`;
                    });
                }

                
                const data = {
                    labels: labels,
                    datasets: [{
                        label: 'Pris',
                        data: prices,
                        fill: true,
                        backgroundColor: fmph.color+50,
                        borderColor: fmph.color,
                        tension: 0.1,
                        pointRadius: generatePointRadius(res.prices),
                        pointBackgroundColor: fmph.color,
                        pointBorderColor: fmph.color,
                        pointBorderWidth: 2, 
                    }]
                };

                const maxPrice = Math.max(...prices);
                const yMax = maxPrice > 0 
                ? (maxPrice <= 1000 
                    ? Math.ceil((maxPrice * 1.2) / 100) * 100 
                    : Math.ceil((maxPrice * 1.2) / 500) * 500)
                : 100;

                if ( fmph_charts.length && fmphInitialLoaded ) {

                    fmph_charts.forEach(function( chart ) {

                        $('.fmph-graph-info[data-id="'+product_id+'"] .name').html( res.product_name );
                        $('.fmph-graph-info[data-id="'+product_id+'"] .fmph-price').html( res.lowest_price );
    
                        chart.options.scales.y.max = yMax;
    
                        chart.data.labels.pop();
                        chart.data.labels = labels;
    
                        chart.data.datasets.forEach((dataset) => {
                            dataset.data.pop();
                        });
    
                        chart.data.datasets.forEach((dataset) => {
                            dataset.data = prices;
                        });
    
                        chart.update();

                    });

                    return;

                }

                let chart = new Chart( chartElement, {
                    type: 'line',
                    data: data,
                    options: {
                        scales: {
                            y: {
                                title: 'Pris',
                                min: 0,
                                max: yMax,
                                grid: {
                                    display: true,
                                },
                                ticks: {
                                    callback: function(value, index, ticks) {
                                        return value + ' kr';
                                    },
                                }
                            },
                            x: {
                                grid: {
                                    display: true,
                                },
                                ticks: {
                                    autoSkip: false,
                                    maxTicksLimit: 7,
                                    callback: function(value, index, ticks) {
                                        const labels = this.chart.data.labels;
                                        if ( labels.length === 2 && labels[0] === labels[1] ) {
                                            return this.getLabelForValue(value);
                                        }
                                        return index % 5 === 0 ? this.getLabelForValue(value) : '';
                                    },
                                    maxRotation: 0,
                                    minRotation: 0,
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false,
                            },
                            tooltip: {
                                mode: 'nearest',
                                axis: 'x',
                                intersect: false,
                                yAlign: 'top',
                                backgroundColor: fmph.color,
                                callbacks: {
                                    title: function() {
                                        return '';
                                    },
                                    label: function(context) {
                                        const price = new Intl.NumberFormat('sv-SE', {
                                            style: 'currency',
                                            currency: 'SEK',
                                            maximumFractionDigits: 0,
                                        }).format(context.parsed.y);
                                        
                                        return price;
                                    },
                                    footer: function(tooltipItems) {
                                        const date = tooltipItems[0].label;
                                        return [date];
                                    }
                                },
                                bodyFont: {
                                    size: 20,
                                    weight: 'bold'
                                },
                                footerFont: {
                                    size: 14,
                                },
                                bodyAlign: 'center',
                                padding: 10,
                                displayColors: false,
                                caretPadding: 10,
                            },
                        },
                    }
                }); 

                fmph_charts.push( chart );

                if ( fmph_charts.length >= fmphChartCount ) {
                    fmphInitialLoaded = true;
                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('AJAX Error: ' + textStatus + ' : ' + errorThrown);
            }
        });

    }

    function generatePointRadius(prices) {
        return prices.map((price, index) => {
            if (index === 0) return 4;
            if (index === prices.length - 1) return 4;
            return price !== prices[index - 1] ? 4 : 0;
        });
    }

    $(document).on('click', '.fmph-show-history', function() {

        let element;

        if ( $('.woocommerce-tabs').length ) {
            element = $('.woocommerce-tabs')[0];
            $('#tab-title-fmph > a').trigger('click');
        }else {
            $('#fmph-tab').trigger('click');
            element = $('.e-n-tabs-content > div.e-active')[0];
            setTimeout(function() {
                element = $('.e-n-tabs-content > div.e-active')[0];
            }, 150);
        }

        setTimeout(function() {
            element.scrollIntoView({
                behavior: "smooth",
                block: "start",
            });  
        }, 150);

    });

});