(function (factory) {
  typeof define === 'function' && define.amd ? define(factory) : factory();
})((function () {
  'use strict';

  // ===============================================
  //    Utility Functions
  // ===============================================

  const { merge } = window._;

  const echartSetOption = (chart, userConfig, baseConfigGenerator, responsiveConfigs) => {
    const { breakpoints, resize } = window.phoenix.utils;
    const applyResponsiveConfigs = (configs) => {
      Object.keys(configs).forEach((breakpoint) => {
        if (window.innerWidth > breakpoints[breakpoint]) {
          chart.setOption(configs[breakpoint]);
        }
      });
    };

    const body = document.body;
    chart.setOption(merge(baseConfigGenerator(), userConfig));

    const navbarToggle = document.querySelector(".navbar-vertical-toggle");
    if (navbarToggle) {
      navbarToggle.addEventListener("navbar.vertical.toggle", () => {
        chart.resize();
        if (responsiveConfigs) applyResponsiveConfigs(responsiveConfigs);
      });
    }

    resize(() => {
      chart.resize();
      if (responsiveConfigs) applyResponsiveConfigs(responsiveConfigs);
    });

    body.addEventListener("clickControl", (({ detail: { control } }) => {
      if (control === "phoenixTheme") {
        chart.setOption(window._.merge(baseConfigGenerator(), userConfig));
        if (responsiveConfigs) applyResponsiveConfigs(responsiveConfigs);
      }
    }));
  };

  const echartTabs = document.querySelectorAll("[data-tab-has-echarts]");
  echartTabs && echartTabs.forEach((tab) => {
    tab.addEventListener("shown.bs.tab", (event) => {
      const target = event.target;
      const hash = target.hash || target.dataset.bsTarget;
      const chartElement = document.getElementById(hash.substring(1))?.querySelector("[data-echart-tab]");
      if (chartElement) {
        window.echarts.init(chartElement).resize();
      }
    });
  });

  const tooltipFormatter = (params, dateFormat = "MMM DD") => {
    let tooltipContent = '';
    params.forEach((param) => {
      tooltipContent += `<div class='ms-1'>
        <h6 class="text-body-tertiary"><span class="fas fa-circle me-1 fs-10" style="color:${param.borderColor ? param.borderColor : param.color}"></span>
          ${param.seriesName} : ${typeof param.value === 'object' ? param.value[1] : param.value}
        </h6>
      </div>`;
    });
    return `<div>
      <p class='mb-2 text-body-tertiary'>
        ${window.dayjs(params[0].axisValue).isValid() ? window.dayjs(params[0].axisValue).format(dateFormat) : params[0].axisValue}
      </p>
      ${tooltipContent}
    </div>`;
  };

  const handleTooltipPosition = ([pos, , event, , viewSize]) => {
    if (window.innerWidth <= 540) {
      const tooltipHeight = event.offsetHeight;
      const position = { top: pos[1] - tooltipHeight - 20 };
      position[pos[0] < viewSize[0] / 2 ? "left" : "right"] = 5;
      return position;
    }
    return null;
  };

  // ===============================================
  //    Chart 1: Today vs Yesterday (Hourly 7:00-22:00)
  // ===============================================

  const todayYesterdayChartInit = () => {
    const { getColor, getData } = window.phoenix.utils;
    const chartElement = document.querySelector(".echart-today-yesterday");
    
    if (!chartElement) return;

    // Get data from DashboardController
    const chartData = window.chartData?.today_vs_yesterday || {
      labels: Array.from({length: 16}, (_, i) => `${(i + 7).toString().padStart(2, '0')}:00`),
      today_sales: Array(16).fill(0),
      yesterday_sales: Array(16).fill(0)
    };

    const customTooltipFormatter = (params) => {
      const currentHour = params[0].axisValue;
      let tooltipContent = '';
      params.forEach((param, index) => {
        const label = param.seriesName === 'today' ? 'Today' : 'Yesterday';
        tooltipContent += `<h6 class="fs-9 text-body-tertiary ${index > 0 && "mb-0"}">
          <span class="fas fa-circle me-2" style="color:${param.color}"></span>
          ${label} ${currentHour} : Tshs ${param.value.toLocaleString()}
        </h6>`;
      });
      return `<div class='ms-1'>${tooltipContent}</div>`;
    };

    const userConfig = getData(chartElement, "echarts");
    const chart = window.echarts.init(chartElement);

    echartSetOption(chart, userConfig, () => ({
      color: [getColor("primary"), getColor("info")],
      tooltip: {
        trigger: "axis",
        padding: 10,
        backgroundColor: getColor("body-highlight-bg"),
        borderColor: getColor("border-color"),
        textStyle: { color: getColor("light-text-emphasis") },
        borderWidth: 1,
        transitionDuration: 0,
        axisPointer: { type: "none" },
        formatter: customTooltipFormatter,
        extraCssText: "z-index: 1000"
      },
      xAxis: [{
        type: "category",
        data: chartData.labels,
        axisLabel: {
          formatter: label => label,
          interval: 'auto',
          showMinLabel: true,
          showMaxLabel: false,
          color: getColor("secondary-color"),
          align: "left",
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8
        },
        axisLine: { show: true, lineStyle: { color: getColor("secondary-bg") } },
        axisTick: { show: false },
        splitLine: {
          show: true,
          interval: 0,
          lineStyle: { 
            color: window.config.config.phoenixTheme === "dark" ? 
              getColor("body-highlight-bg") : getColor("secondary-bg") 
          }
        },
        boundaryGap: false
      }],
    yAxis: {
    position: "left",
    axisPointer: { type: "none" },
    axisTick: "none",
    splitLine: { show: true },
    axisLine: { show: false },
    axisLabel: {
        show: true,  // <-- Added comma here
        fontFamily: "Nunito Sans",
        fontWeight: 600,
        fontSize: 12.8,
        color: getColor("secondary-color"),
        margin: 20,
        verticalAlign: "bottom",
        formatter: value => `Tshs ${value.toLocaleString()}`
    }
    },
      series: [{
        name: "today",
        type: "line",
        data: chartData.today_sales,
        showSymbol: false,
        symbol: "circle",
        smooth:false,
        lineStyle: { width: 1.5 },
        zlevel: 2
      }, {
        name: "yesterday",
        type: "line",
        smooth:false,
        data: chartData.yesterday_sales,
        lineStyle: { type: "dashed", width: 1, color: getColor("info") },
        showSymbol: false,
        symbol: "circle",
        zlevel: 1
      }],
      grid: { right: 15, left: 100, bottom: "20px", top: "4%", containLabel: false },
      animation: false
    }));
  };

  // ===============================================
  //    Chart 2: This Week vs Last Week
  // ===============================================

  const weekComparisonChartInit = () => {
    const { getColor, getData } = window.phoenix.utils;
    const chartElement = document.querySelector(".echart-week-comparison");
    
    if (!chartElement) return;

    const chartData = window.chartData?.this_week_vs_last_week || {
      labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      this_week_sales: Array(7).fill(0),
      last_week_sales: Array(7).fill(0)
    };

    const userConfig = getData(chartElement, "echarts");
    const chart = window.echarts.init(chartElement);

    echartSetOption(chart, userConfig, () => ({
      color: [getColor("primary"), getColor("warning")],
      tooltip: {
        trigger: "axis",
        padding: 10,
        backgroundColor: getColor("body-highlight-bg"),
        borderColor: getColor("border-color"),
        textStyle: { color: getColor("light-text-emphasis") },
        borderWidth: 1,
        transitionDuration: 0,
        axisPointer: { type: "none" },
        formatter: tooltipFormatter,
        extraCssText: "z-index: 1000"
      },
      legend: {
        data: ["This Week", "Last Week"],
        right: "right",
        width: "100%",
        itemWidth: 16,
        itemHeight: 8,
        itemGap: 20,
        top: 3,
        inactiveColor: getColor("quaternary-color"),
        textStyle: { color: getColor("body-color"), fontWeight: 600, fontFamily: "Nunito Sans" }
      },
      xAxis: {
        type: "category",
        data: chartData.labels,
        axisLabel: {
          color: getColor("secondary-color"),
          interval: 0,
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8
        },
        axisLine: { lineStyle: { color: getColor("tertiary-bg") } },
        axisTick: false
      },
      yAxis: {
        axisPointer: { type: "none" },
        axisTick: "none",
        splitLine: { interval: 5, lineStyle: { color: getColor("secondary-bg") } },
        axisLine: { show: false },
        axisLabel: {
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8,
          color: getColor("secondary-color"),
          margin: 20,
          verticalAlign: "bottom",
          formatter: value => `Tshs ${value.toLocaleString()}`
        }
      },
      series: [{
        name: "This Week",
        type: "line",
        data: chartData.this_week_sales,
        showSymbol: false,
        symbol: "circle",
        lineStyle: { width: 1.5 }
      }, {
        name: "Last Week",
        type: "line",
        data: chartData.last_week_sales,
        showSymbol: false,
        symbol: "circle",
        lineStyle: { type: "dashed", width: 1, color: getColor("warning") }
      }],
      grid: { right: 0, left: 3, bottom: 0, top: "15%", containLabel: true },
      animation: false
    }));
  };

  // ===============================================
  //    Chart 3: This Month vs Last Month
  // ===============================================

  const monthComparisonChartInit = () => {
    const { getColor, getData } = window.phoenix.utils;
    const chartElement = document.querySelector(".echart-month-comparison");
    
    if (!chartElement) return;

    const chartData = window.chartData?.this_month_vs_last_month || {
      labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
      this_month_sales: Array(4).fill(0),
      last_month_sales: Array(4).fill(0)
    };

    const userConfig = getData(chartElement, "echarts");
    const chart = window.echarts.init(chartElement);

    echartSetOption(chart, userConfig, () => ({
      color: [getColor("success"), getColor("danger")],
      tooltip: {
        trigger: "axis",
        padding: 10,
        backgroundColor: getColor("body-highlight-bg"),
        borderColor: getColor("border-color"),
        textStyle: { color: getColor("light-text-emphasis") },
        borderWidth: 1,
        transitionDuration: 0,
        axisPointer: { type: "none" },
        formatter: tooltipFormatter,
        extraCssText: "z-index: 1000"
      },
      legend: {
        data: ["This Month", "Last Month"],
        right: "right",
        width: "100%",
        itemWidth: 16,
        itemHeight: 8,
        itemGap: 20,
        top: 3,
        inactiveColor: getColor("quaternary-color"),
        textStyle: { color: getColor("body-color"), fontWeight: 600, fontFamily: "Nunito Sans" }
      },
      xAxis: {
        type: "category",
        data: chartData.labels,
        axisLabel: {
          color: getColor("secondary-color"),
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8
        },
        axisLine: { lineStyle: { color: getColor("tertiary-bg") } },
        axisTick: false
      },
      yAxis: {
        axisPointer: { type: "none" },
        axisTick: "none",
        splitLine: { lineStyle: { color: getColor("secondary-bg") } },
        axisLine: { show: false },
        axisLabel: {
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8,
          color: getColor("secondary-color"),
          formatter: value => `Tshs ${value.toLocaleString()}`
        }
      },
      series: [{
        name: "This Month",
        type: "line",
        data: chartData.this_month_sales,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 3,
        lineStyle: { width: 1.5 }
      }, {
        name: "Last Month",
        type: "line",
        data: chartData.last_month_sales,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 3,
        lineStyle: { type: "dashed", width: 1, color: getColor("danger") }
      }],
      grid: { right: 10, left: 10, bottom: 0, top: "15%", containLabel: true }
    }));
  };

  // ===============================================
  //    Chart 4: This Year vs Last Year
  // ===============================================

  const yearComparisonChartInit = () => {
    const { getColor, getData } = window.phoenix.utils;
    const chartElement = document.querySelector(".echart-year-comparison");
    
    if (!chartElement) return;

    const chartData = window.chartData?.this_year_vs_last_year || {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      this_year_sales: Array(12).fill(0),
      last_year_sales: Array(12).fill(0)
    };

    const userConfig = getData(chartElement, "echarts");
    const chart = window.echarts.init(chartElement);

    echartSetOption(chart, userConfig, () => ({
      color: [getColor("primary"), getColor("info")],
      tooltip: {
        trigger: "axis",
        padding: 10,
        backgroundColor: getColor("body-highlight-bg"),
        borderColor: getColor("border-color"),
        textStyle: { color: getColor("light-text-emphasis") },
        borderWidth: 1,
        transitionDuration: 0,
        axisPointer: { type: "none" },
        formatter: tooltipFormatter,
        extraCssText: "z-index: 1000"
      },
      legend: {
        data: ["This Year", "Last Year"],
        right: "right",
        width: "100%",
        itemWidth: 16,
        itemHeight: 8,
        itemGap: 20,
        top: 3,
        inactiveColor: getColor("quaternary-color"),
        textStyle: { color: getColor("body-color"), fontWeight: 600, fontFamily: "Nunito Sans" }
      },
      xAxis: {
        type: "category",
        data: chartData.labels,
        axisLabel: {
          color: getColor("secondary-color"),
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8
        },
        axisLine: { lineStyle: { color: getColor("tertiary-bg") } },
        axisTick: false
      },
      yAxis: {
        axisPointer: { type: "none" },
        axisTick: "none",
        splitLine: { lineStyle: { color: getColor("secondary-bg") } },
        axisLine: { show: false },
        axisLabel: {
          fontFamily: "Nunito Sans",
          fontWeight: 600,
          fontSize: 12.8,
          color: getColor("secondary-color"),
          formatter: value => `Tshs ${value.toLocaleString()}`
        }
      },
      series: [{
        name: "This Year",
        type: "line",
        data: chartData.this_year_sales,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 6,
        lineStyle: { width: 1 },
        smooth: true
      }, {
        name: "Last Year",
        type: "line",
        data: chartData.last_year_sales,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 6,
        lineStyle: { type: "dashed", width: 1, color: getColor("info") },
        smooth: true
      }],
      grid: { right: 10, left: 10, bottom: 0, top: "15%", containLabel: true }
    }));
  };

  // ===============================================
  //    Sales Status Chart (Pending vs Verified)
  // ===============================================

  const salesStatusChartInit = () => {
    const { getData, getColor } = window.phoenix.utils;
    const chartElement = document.querySelector(".echarts-sales-status-chart");
    
    if (!chartElement) return;

    const salesData = window.salesStatus || { verified: 0, pending: 0, total: 0 };
    const chart = window.echarts.init(chartElement);

    const chartOptions = {
      tooltip: {
        trigger: 'item',
        padding: [7, 10],
        backgroundColor: getColor('body-highlight-bg'),
        borderColor: getColor('border-color'),
        textStyle: { color: getColor('light-text-emphasis') },
        borderWidth: 1,
        position: (params) => handleTooltipPosition(params),
        transitionDuration: 0,
        formatter: (params) => `
          <div class="text-center">
            <strong>${params.name}:</strong><br/>
            ${params.value}% (${salesData.total} sales)
          </div>`,
        extraCssText: "z-index: 1000"
      },
      legend: { show: true },
      series: [{
        type: 'gauge',
        center: ['50%', '60%'],
        name: 'Sales Status',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 12,
        itemStyle: { color: getColor('success') },
        progress: {
          show: true,
          roundCap: true,
          width: 8,
          itemStyle: { shadowBlur: 0, shadowColor: "#0000" }
        },
        pointer: { show: false },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 8,
            color: [[1, getColor('primary-bg-subtle')]]
          }
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        title: { show: false },
        detail: { show: false },
        data: [{ value: salesData.verified, name: 'Verified' }],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      }]
    };

    echartSetOption(chart, getData(chartElement, "options"), () => chartOptions);

    // Update percentage labels
    const updatePercentageLabels = () => {
      const verifiedElement = document.getElementById('verified-percentage');
      const pendingElement = document.getElementById('pending-percentage');
      
      if (verifiedElement) verifiedElement.textContent = `${salesData.verified}%`;
      if (pendingElement) pendingElement.textContent = `${salesData.pending}%`;
    };

    updatePercentageLabels();
  };

  // ===============================================
  //    Original Charts (Maintained for compatibility)
  // ===============================================

  const totalSalesChartInit = todayYesterdayChartInit; // Alias for compatibility

  const newCustomersChartsInit = () => {
    // Original implementation maintained
    const { getColor, getData, getDates } = window.phoenix.utils;
    const chartElement = document.querySelector(".echarts-new-customers");
    
    if (!chartElement) return;

    // ... original implementation
  };

  const payingCustomerChartInit = () => {
    // Original implementation maintained
    const { getData, getColor } = window.phoenix.utils;
    const chartElement = document.querySelector(".echarts-paying-customer-chart");
    
    if (!chartElement) return;
    // ... original implementation
  };

  const projectionVsActualChartInit = () => {
    // Original implementation maintained
    // ... original implementation
  };

  const returningCustomerChartInit = () => {
    // Original implementation maintained
    // ... original implementation
  };

  const topCouponsChartInit = () => {
    // Original implementation maintained
    // ... original implementation
  };

  const totalOrdersChartInit = () => {
    // Original implementation maintained
    // ... original implementation
  };

  // ===============================================
  //    Map Functions (Unchanged)
  // ===============================================

  const revenueMapInit = () => {
    // Original implementation unchanged
    // ... original implementation
  };

  const leafletInit = () => {
    // Original implementation unchanged
    // ... original implementation
  };

  // ===============================================
  //    Main Initialization
  // ===============================================

  const { docReady } = window.phoenix.utils;

  // Make functions globally available
  window.revenueMapInit = revenueMapInit;

  // Initialize all charts when document is ready
  docReady(() => {
    // New comparison charts
    todayYesterdayChartInit();
    weekComparisonChartInit();
    monthComparisonChartInit();
    yearComparisonChartInit();
    salesStatusChartInit();

    // Original charts (for compatibility)
    newCustomersChartsInit();
    topCouponsChartInit();
    projectionVsActualChartInit();
    returningCustomerChartInit();
    payingCustomerChartInit();
    totalOrdersChartInit();
    leafletInit();
  });

}));