<!-- Morris -->
<script src="/js/plugins/morris/raphael-2.1.0.min.js"></script>
<script src="/js/plugins/morris/morris.min.js"></script>

<script>
    const colorArray = [
        "#ff8167", // Vibrant orange
        "#66ff81", // Bright lime green
        "#6681ff", // Deep sky blue
        "#ff66fc", // Vivid magenta
        "#96ff80", // Light green
        "#ff6681", // Strong pink
        "#66dbff", // Light sky blue
        "#db66ff", // Light purple
        "#ffdb66", // Golden yellow
        "#66ffdb", // Turquoise
        "#a266ff", // Medium purple
        "#ffa266", // Burnt orange
        "#66ffa2", // Mint green
        "#ff66a2", // Hot pink
        "#66a2ff", // Cornflower blue
        "#a2ff66", // Neon green
        "#ff66a0", // Deep rose
        "#66a0ff", // Cerulean blue
        "#b0ff80", // Bright chartreuse
        "#ffa066", // Dark tangerine
        "#d25a87", // Maroon
        "#ff6a33", // Orange Red
        "#3bb16f", // Sea Green
        "#e4b849", // Golden Rod
        "#e4843f", // Chocolate
        "#7fb1b3", // Cadet Blue
        "#aed75b", // Yellow Green
        "#2cd9d0", // Light Sea Green
        "#94a2af", // Light Slate Gray
        "#cdc88e"  // Dark Khaki
    ];

    $(function() {
        // Initialize datepickers
        $('.data_1 .input-group.date').datepicker().on('changeDate clearDate', function(e) {
            updateGraph();
        });

        $('.testHistory, .categoryHistory').each(function () {
            if ($(this).hasClass('active')) {
                $(this).find('span').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border:0;');

                var legend = $(this).attr('data-legend');
                var id = $(this).attr('data-id');

                var targetElement = $('.legend[data-legend="' + legend + '"][data-id="' + id + '"]');

                if (targetElement.length > 0) {
                    targetElement.addClass('active');
                    targetElement.addClass('show');
                    targetElement.find('span:first').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border:0;');
                }
            }
        });

        // Event handler for testHistory and categoryHistory
        $(".testHistory, .categoryHistory").click(function(e) {
            e.preventDefault();

            var legend = $(this).attr('data-legend');
            var id = $(this).attr('data-id');

            var targetElement = $('.legend[data-legend="' + legend + '"][data-id="' + id + '"]');

            if ($(this).hasClass('active')) {
                $(this).find('span').removeAttr('style');
                if (targetElement.length > 0) {
                    targetElement.find('span:first').removeAttr('style');
                    targetElement.removeClass('active');
                }
            } else {
                $(this).find('span').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border: 0');

                if (targetElement.length > 0) {
                    if (!targetElement.is(':visible')) {
                        targetElement.insertAfter($(".legend:visible:last"));
                    }
                    targetElement.addClass('active');
                    targetElement.addClass('show');
                    targetElement.find('span:first').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border:0;');
                }
            }

            $(this).toggleClass('active');

            updateGraph();
        });

        $(".legend").on('click', function(e){
            e.preventDefault();

            var legend = $(this).attr('data-legend');
            var id = $(this).attr('data-id');

            var targetElement = $('.history[data-legend="' + legend + '"][data-id="' + id + '"]');

            if ($(this).hasClass('active')) {
                $(this).find('span:first').removeAttr('style');
                $(this).toggleClass('active');

                if (targetElement.length > 0) {
                    targetElement.find('span').removeAttr('style');
                    targetElement.toggleClass('active');
                }
            } else {
                $(this).find('span:first').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border: 0');
                $(this).addClass('active');
                $(this).addClass('show');

                if (targetElement.length > 0) {

                    targetElement.addClass('active');
                    targetElement.find('span').attr('style', 'background-color: ' + $(this).find('span').attr('data-background') + '; border:0;');
                }
            }

            updateGraph();
        });

        $('.close-icon').on('click', function (e) {
            e.stopPropagation();
            var parent = $(this).parents('.legend');
            var legend = parent.attr('data-legend');
            var id = parent.attr('data-id');

            var targetElement = $('.history[data-legend="' + legend + '"][data-id="' + id + '"]');

            if (parent.hasClass('active')) {
                parent.find('span:first').removeAttr('style');
                parent.toggleClass('active');
                parent.toggleClass('show');

                if (targetElement.length > 0) {
                    targetElement.find('span').removeAttr('style');
                    targetElement.toggleClass('active');
                }
            } else {
                parent.find('span:first').attr('style', 'background-color: ' + parent.find('span:first').attr('data-background') + '; border: 0');
                parent.removeClass('active');
                parent.removeClass('show');
            }

            updateGraph();
        });

        // Initial graph display
        showHealthHistoryGraph(null, ['all']);
    });


    function updateGraph() {
        var activeTestIds = getActiveIds('.testHistory');
        var activeCategoryIds = getActiveIds('.categoryHistory');
        var dateFrom = $('#date_from').val() || null;
        var dateTo = $('#date_to').val() || null;

        showHealthHistoryGraph(activeTestIds, activeCategoryIds, dateFrom, dateTo);
    }

    function getActiveIds(selector) {
        return $(selector + '.active').map(function() {
            return $(this).data('id');
        }).get();
    }

    function showHealthHistoryGraph(inputTestIds, inputCategoryIds, dateFrom, dateTo) {
        $.ajax({
            url: "/assets-health-history-data-filter",
            method: "POST",
            data: {
                testIds: inputTestIds,
                categoryIds: inputCategoryIds,
                from_date: dateFrom,
                to_date: dateTo,
            },
            dataType: "json",
            success: function(data) {
                $("#weekly-assets-issues").html("");
                if (data['labels'].length) {
                    Morris.Line({
                        element: 'weekly-assets-issues',
                        data: data['graphData'],
                        xkey: 'weekDate',
                        ykeys: data['ykeys'],
                        labels: data['labels'],
                        parseTime: false,
                        smooth: false,
                        resize: true,
                        lineColors: data['colorArray']
                    });
                    $("div svg text").attr("style", "font-family: Roboto");
                    $("div svg").attr("height", "400px");
                }

            }
        });
    }

</script>