/**
 * Chart.js Initialization Helper
 * Provides utilities for creating charts with Chart.js v4.4.1
 * Requires: Chart.js loaded globally (window.Chart)
 */

(function() {
  'use strict';

  /**
   * Initialize all charts on the page with data-chart attributes
   */
  window.initializeCharts = function() {
    const chartElements = document.querySelectorAll('[data-chart-config]');

    if (!chartElements.length) return;

    if (typeof window.Chart === 'undefined') {
      console.error('Chart.js library not loaded');
      return;
    }

    chartElements.forEach(initializeChart);
  };

  /**
   * Initialize a single chart element
   * @param {HTMLElement} element - Canvas element with data-chart-config attribute
   */
  function initializeChart(element) {
    try {
      const config = JSON.parse(element.dataset.chartConfig);

      // Apply theme defaults if not specified
      if (!config.options) config.options = {};
      if (!config.options.responsive) config.options.responsive = true;
      if (!config.options.maintainAspectRatio === undefined) {
        config.options.maintainAspectRatio = true;
      }

      // Create the chart
      new Chart(element, config);

    } catch (error) {
      console.error('Error initializing chart:', error);
      element.parentElement?.insertAdjacentHTML('beforeend',
        '<p style="color: #d32f2f; padding: 1rem;">Error loading chart. Please check configuration.</p>'
      );
    }
  }

  /**
   * Helper function to create a chart programmatically
   * @param {string|HTMLElement} target - Canvas element or selector
   * @param {object} config - Chart.js configuration object
   * @returns {Chart} Chart instance
   */
  window.createChart = function(target, config) {
    const element = typeof target === 'string' ? document.querySelector(target) : target;

    if (!element) {
      console.error('Chart target element not found:', target);
      return null;
    }

    if (typeof window.Chart === 'undefined') {
      console.error('Chart.js library not loaded');
      return null;
    }

    return new Chart(element, config);
  };

  /**
   * Common chart configurations for quick setup
   */
  window.ChartPresets = {
    /**
     * Create a simple bar chart
     */
    bar: function(labels, data, options = {}) {
      return {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: options.label || 'Dataset',
            data: data,
            backgroundColor: options.backgroundColor || 'rgba(54, 162, 235, 0.5)',
            borderColor: options.borderColor || 'rgba(54, 162, 235, 1)',
            borderWidth: options.borderWidth || 2
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: true,
          plugins: {
            legend: {
              display: options.showLegend !== false
            },
            tooltip: {
              enabled: options.showTooltip !== false
            }
          },
          ...options.chartOptions
        }
      };
    },

    /**
     * Create a simple line chart
     */
    line: function(labels, data, options = {}) {
      return {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: options.label || 'Dataset',
            data: data,
            backgroundColor: options.backgroundColor || 'rgba(75, 192, 192, 0.2)',
            borderColor: options.borderColor || 'rgba(75, 192, 192, 1)',
            borderWidth: options.borderWidth || 2,
            tension: options.tension || 0.4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: true,
          plugins: {
            legend: {
              display: options.showLegend !== false
            },
            tooltip: {
              enabled: options.showTooltip !== false
            }
          },
          ...options.chartOptions
        }
      };
    },

    /**
     * Create a simple pie/doughnut chart
     */
    pie: function(labels, data, options = {}) {
      return {
        type: options.doughnut ? 'doughnut' : 'pie',
        data: {
          labels: labels,
          datasets: [{
            data: data,
            backgroundColor: options.colors || [
              'rgba(255, 99, 132, 0.7)',
              'rgba(54, 162, 235, 0.7)',
              'rgba(255, 206, 86, 0.7)',
              'rgba(75, 192, 192, 0.7)',
              'rgba(153, 102, 255, 0.7)',
              'rgba(255, 159, 64, 0.7)'
            ],
            borderWidth: options.borderWidth || 2
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: true,
          plugins: {
            legend: {
              display: options.showLegend !== false,
              position: options.legendPosition || 'top'
            },
            tooltip: {
              enabled: options.showTooltip !== false
            }
          },
          ...options.chartOptions
        }
      };
    }
  };

  // Auto-initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', window.initializeCharts);
  } else {
    window.initializeCharts();
  }

})();
