{% set price_history_model = model|default(product|default({})) %}
{% set price_history = price_history_model.price_history|default([]) %}
{% set price_history_id = 'priceHistory_' ~ (price_history_model.model_id|default(price_history_model.id|default(section.id|default(random())))) %}

{% if price_history is not empty %}
<section class="price-history-widget">
    <div class="section-title mt-8 mb-4 mx-0 lg:mx-0 pb-2 border-b">
        <div class="text-primary uppercase font-semibold">Cronologia Prezzi</div>
    </div>

    <div class="lg:max-w-[668px] mb-12">
        <canvas id="{{ price_history_id|raw }}"></canvas>
    </div>

{% if not user_agent.is_pagespeed %}
    <script>
        (function () {
            var ctx = document.getElementById('{{ price_history_id|raw }}');
            var chartRendered = false;

            if (!ctx) {
                return;
            }

            var salesData = JSON.parse('{{ price_history|json_encode|raw }}');
            var recentSalesData = salesData.slice(-10);
            var labels = recentSalesData.map(function (entry) {
                return new Date(entry.date).toLocaleString('it-IT', { day: 'numeric', month: 'short' });
            });
            var data = recentSalesData.map(function (entry) {
                return entry.price || entry.sold;
            });

            var loadChartJs = function () {
                if (window.Chart) {
                    return Promise.resolve();
                }

                if (window.hdChartJsLoading) {
                    return window.hdChartJsLoading;
                }

                window.hdChartJsLoading = new Promise(function (resolve, reject) {
                    var script = document.createElement('script');
                    script.src = '{{ scripts_dir|raw }}/chart.umd.js';
                    script.defer = true;
                    script.onload = resolve;
                    script.onerror = reject;
                    document.body.appendChild(script);
                });

                return window.hdChartJsLoading;
            };

            var renderChart = function () {
                if (chartRendered) {
                    return;
                }

                chartRendered = true;

                loadChartJs().then(function () {
                    if (typeof Chart === 'undefined') {
                        return;
                    }

                    new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: labels,
                            datasets: [{
                                fill: true,
                                label: '',
                                data: data,
                                borderWidth: 3,
                                borderColor: '#06b6d4',
                                backgroundColor: 'rgba(228, 240, 248, 0.5)',
                                tension: 0.4
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return 'Prezzo: ' + context.raw + '&euro;';
                                        }
                                    },
                                    displayColors: false
                                }
                            },
                            scales: {
                                x: {
                                    grid: {
                                        display: false
                                    },
                                    ticks: {
                                        font: {
                                            size: 12
                                        },
                                        rotation: -45,
                                        padding: 10
                                    },
                                    offset: false
                                },
                                y: {
                                    grid: {
                                        display: true
                                    },
                                    beginAtZero: false,
                                    ticks: {
                                        font: {
                                            size: 12
                                        }
                                    }
                                }
                            }
                        }
                    });
                }).catch(function () {
                    chartRendered = false;
                });
            };

            if ('IntersectionObserver' in window) {
                var observer = new IntersectionObserver(function (entries) {
                    if (entries[0].isIntersecting) {
                        observer.disconnect();
                        renderChart();
                    }
                }, { rootMargin: '600px 0px' });

                observer.observe(ctx);
            } else {
                var renderOnScroll = function () {
                    window.removeEventListener('scroll', renderOnScroll);
                    window.removeEventListener('wheel', renderOnScroll);
                    window.removeEventListener('touchstart', renderOnScroll);
                    renderChart();
                };

                window.addEventListener('scroll', renderOnScroll, { once: true, passive: true });
                window.addEventListener('wheel', renderOnScroll, { once: true, passive: true });
                window.addEventListener('touchstart', renderOnScroll, { once: true, passive: true });
            }
        }());
    </script>
{% endif %}

</section>
{% endif %}
