import { jsx, Fragment, jsxs } from "react/jsx-runtime";
import React__default, { useState, useRef, useEffect, useMemo } from "react";
import default_1$1 from "../../node_modules/@mui/icons-material/FileDownloadOutlined.js";
import default_1 from "../../node_modules/@mui/icons-material/TableChartOutlined.js";
import Highcharts from "highcharts";
import Highcharts3D from "highcharts/highcharts-3d";
import HighchartsMore from "highcharts/highcharts-more";
import HighchartsHeatmap from "highcharts/modules/heatmap";
import HighchartsStock from "highcharts/modules/stock";
import HighchartsTreemap from "highcharts/modules/treemap";
import HighchartsVenn from "highcharts/modules/venn";
import borderRadiusModule from "highcharts-border-radius";
import HighchartsReact from "highcharts-react-official";
import { getAssetUrl } from "../../utils/assetBase.js";
import { Button } from "../Button/index.js";
import { Menu } from "../Menu/index.js";
/* empty css                  */
const ChartDropdownUrl = getAssetUrl("icons/Chart-dropdown.svg");
const CollapseIconUrl = getAssetUrl("icons/Collapse.svg");
const ExpandIconUrl = getAssetUrl("icons/expand-icon.svg");
const borderRadius = typeof borderRadiusModule === "function" ? borderRadiusModule : borderRadiusModule.default ?? (() => {
});
if (typeof Highcharts === "object" && "seriesTypes" in Highcharts && borderRadius) {
  const modules = [
    HighchartsMore,
    Highcharts3D,
    HighchartsHeatmap,
    HighchartsStock,
    HighchartsVenn,
    HighchartsTreemap,
    borderRadius
  ];
  modules.forEach((mod) => {
    if (typeof mod === "function") mod(Highcharts);
  });
}
function safeStringify(value, fallback) {
  try {
    if (value == null) return fallback;
    return JSON.stringify(value);
  } catch {
    return fallback;
  }
}
function isPromiseLike(value) {
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
}
function tryFullscreen(call) {
  try {
    const result = call();
    if (isPromiseLike(result)) {
      void Promise.resolve(result).catch(() => {
      });
    }
  } catch {
  }
}
function chartTypesToMenuOptions(chartTypesOptions) {
  if (!(chartTypesOptions == null ? void 0 : chartTypesOptions.length)) return [];
  return chartTypesOptions.map((opt) => ({
    label: opt.label,
    value: opt.value,
    onClick: opt.onClick ? (_opt, event) => {
      var _a;
      if (event) (_a = opt.onClick) == null ? void 0 : _a.call(opt, event);
    } : void 0
  }));
}
function Chart({
  graphType = "column",
  xAxisCategories,
  xAxisTitle = "X Axis",
  yAxisTitle = "Y Axis",
  seriesData,
  graphTitle,
  stackedColumn = false,
  is3D = false,
  showSubTitle = false,
  onChartDownload = () => {
  },
  fallbackContent = null,
  topRightOptions = null,
  showSwitchButton = false,
  showChartTypeDropdown = false,
  showDownloadButton = true,
  chartTypesOptions = [],
  selectedChart,
  chartMenuProps,
  showScrollX = false,
  topLeftOptions = null,
  cardContainer = true,
  subtitleText = "",
  legendXPosition = null,
  legendYPosition = null,
  xAxisTitlePositionY = null,
  customTooltipFormatter = null,
  sharedTooltip = false,
  showchart = true,
  setShowChart = () => {
  },
  plotOptionsEvents,
  customSystemButton = null,
  handleChartExpand = () => {
  },
  chartMarginBottom = 150,
  showHeader = true,
  height = null,
  width = null,
  showExpandButton = true,
  customLegend = null,
  customLegendStyle = null,
  yAxisTitleRight,
  chartOptions = {},
  titleOptions = {},
  xAxisOptions = {},
  yAxisOptions = {},
  yAxisLeftOptions = {},
  yAxisRightOptions = {},
  zAxisOptions = {},
  tooltipOptions = {},
  plotOptionsOptions = {},
  subtitleOptions = {},
  creditsOptions = {},
  legendOptions = {},
  colorAxisOptions = {},
  seriesOptions = null,
  additionalOptions = {},
  className,
  "data-testid": dataTestId
}) {
  var _a;
  const [isExpanded, setIsExpanded] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [showChartList, setShowChartList] = useState(false);
  const [selectMenuAnchor, setSelectMenuAnchor] = useState(null);
  const chartComponentRef = useRef(null);
  const containerRef = useRef(null);
  const enterFullscreen = () => {
    const elem = containerRef.current;
    if (!elem) return;
    setIsAnimating(true);
    elem.classList.add("fullscreen-animating");
    setTimeout(() => {
      if (!elem.isConnected) return;
      if (elem.requestFullscreen) {
        tryFullscreen(() => {
          return elem.requestFullscreen();
        });
      } else if (elem.webkitRequestFullscreen) {
        tryFullscreen(() => {
          return elem.webkitRequestFullscreen();
        });
      } else if (elem.msRequestFullscreen) {
        tryFullscreen(() => {
          return elem.msRequestFullscreen();
        });
      }
      setIsExpanded(true);
      handleChartExpand(true);
      elem.classList.remove("fullscreen-animating");
    }, 200);
  };
  const exitFullscreen = () => {
    const elem = containerRef.current;
    if (!elem) return;
    setIsAnimating(true);
    elem.classList.add("fullscreen-animating-out");
    setTimeout(() => {
      if (!elem.isConnected) return;
      if (document.exitFullscreen) {
        tryFullscreen(() => {
          return document.exitFullscreen();
        });
      } else if (document.webkitExitFullscreen) {
        tryFullscreen(() => {
          return document.webkitExitFullscreen();
        });
      } else if (document.msExitFullscreen) {
        tryFullscreen(() => {
          return document.msExitFullscreen();
        });
      }
      setIsExpanded(false);
      handleChartExpand(false);
      elem.classList.remove("fullscreen-animating-out");
    }, 200);
  };
  useEffect(() => {
    const handleFullscreenChange = () => {
      const fs = document.fullscreenElement ?? document.webkitFullscreenElement ?? document.msFullscreenElement;
      if (!fs) {
        setIsExpanded(false);
        handleChartExpand(false);
      }
    };
    document.addEventListener("fullscreenchange", handleFullscreenChange);
    document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
    return () => {
      document.removeEventListener("fullscreenchange", handleFullscreenChange);
      document.removeEventListener("webkitfullscreenchange", handleFullscreenChange);
    };
  }, [handleChartExpand]);
  useEffect(() => {
    var _a2;
    const chart = (_a2 = chartComponentRef.current) == null ? void 0 : _a2.chart;
    if (!chart) return;
    const updateSize = () => {
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      chart.setSize(
        windowWidth < 768 ? windowWidth - 40 : void 0,
        isExpanded ? windowHeight - 98 : void 0,
        false
      );
    };
    updateSize();
    window.addEventListener("resize", updateSize);
    return () => {
      window.removeEventListener("resize", updateSize);
    };
  }, [isExpanded]);
  const graphData = useMemo(
    () => ({
      chart: {
        type: graphType,
        scrollablePlotArea: {
          minWidth: showScrollX && (xAxisCategories == null ? void 0 : xAxisCategories.length) ? xAxisCategories.length * 80 : void 0,
          opacity: 1,
          scrollPositionX: 0
        },
        marginBottom: chartMarginBottom,
        width: width ?? void 0,
        style: { fontFamily: "Manrope, sans-serif" },
        height: isExpanded ? window.innerHeight - 108 : height ?? "auto",
        options3d: is3D ? { enabled: true, alpha: 10, beta: 30, depth: 550, viewDistance: 10 } : void 0,
        ...chartOptions || {}
      },
      title: { text: null, ...titleOptions || {} },
      xAxis: {
        categories: xAxisCategories,
        crosshair: true,
        lineColor: "#D9DDE7",
        title: {
          text: xAxisTitle,
          align: "middle",
          reserveSpace: true,
          y: xAxisTitlePositionY ?? (showScrollX ? graphType === "scatter3d" ? 130 : 40 : 3)
        },
        labels: {
          autoRotation: [-45, -60],
          rotation: void 0,
          style: { whiteSpace: "nowrap" }
        },
        ...xAxisOptions || {}
      },
      yAxis: [
        {
          title: { text: yAxisTitle, x: -12, align: "middle", margin: 16 },
          lineWidth: 1,
          lineColor: "#D9DDE7",
          gridLineDashStyle: "Dash",
          gridLineWidth: 1,
          gridLineColor: "#D9DDE7",
          labels: {},
          opposite: false,
          ...yAxisOptions || {},
          ...yAxisLeftOptions || {}
        },
        ...yAxisTitleRight ? [
          {
            title: { text: yAxisTitleRight, x: 12, align: "middle", margin: 16 },
            lineWidth: 1,
            lineColor: "#D9DDE7",
            gridLineDashStyle: "Dash",
            gridLineWidth: 1,
            gridLineColor: "#D9DDE7",
            labels: {},
            opposite: true,
            ...yAxisOptions || {},
            ...yAxisRightOptions || {}
          }
        ] : []
      ],
      zAxis: is3D ? { min: 0, max: 10, ...zAxisOptions || {} } : zAxisOptions && Object.keys(zAxisOptions).length ? zAxisOptions : void 0,
      tooltip: {
        useHTML: true,
        className: "custom-tooltip",
        backgroundColor: "#ffffff",
        borderRadius: 8,
        borderWidth: 0,
        borderColor: "transparent",
        outside: false,
        shared: sharedTooltip,
        shadow: { color: "rgba(0, 0, 0, 0.2)", offsetX: 2, offsetY: 2, opacity: 0.3 },
        style: { fontFamily: "'Manrope', sans-serif", color: "#1F2B4D" },
        positioner(labelWidth, labelHeight, point) {
          const chart = this.chart;
          const left = chart.plotLeft;
          const right = chart.plotLeft + chart.plotWidth;
          const top = chart.plotTop;
          const bottom = chart.plotTop + chart.plotHeight;
          let x = (point.plotX ?? 0) + left - labelWidth / 2;
          let y = (point.plotY ?? 0) + top - labelHeight - 10;
          if (x < left) x = left + 5;
          if (y < top) y = top + 5;
          if (x + labelWidth > right) x = right - labelWidth - 5;
          if (y + labelHeight > bottom) y = bottom - labelHeight - 5;
          return { x, y };
        },
        formatter() {
          if (customTooltipFormatter) {
            return customTooltipFormatter(
              this
            );
          }
          const pt = this.point;
          if (pt && pt.value !== void 0) {
            const v = pt.value;
            return `<span class="tooltip-key">X: ${pt.x} Y: ${pt.y}</span><br/><b class="tooltip-value">Value: ${v}</b>`;
          }
          const key = this.key ?? "";
          const y = this.y;
          const color = this.color ?? "";
          return `<span style="color:${color}">●</span><span class="tooltip-key">${key}: </span><b class="tooltip-value">${typeof y === "number" ? y.toLocaleString() : y}</b>`;
        },
        ...tooltipOptions || {}
      },
      plotOptions: {
        scatter3d: {
          width: 10,
          height: 10,
          depth: 10,
          marker: { radius: 4, symbol: "circle" }
        },
        column: {
          pointPadding: 0.2,
          groupPadding: 0.1,
          borderWidth: 0,
          borderRadius: 8,
          stacking: stackedColumn ? "normal" : void 0
        },
        areaspline: { fillOpacity: 0.25 },
        heatmap: { borderWidth: 1, borderColor: "#ffffff" },
        series: {
          states: { hover: { backgroundColor: null } },
          ...plotOptionsEvents ?? {}
        },
        pie: {
          startAngle: graphType === "semidonut" ? -90 : 0,
          endAngle: graphType === "semidonut" ? 90 : 360,
          center: ["50%", graphType === "semidonut" ? "75%" : "50%"],
          size: "100%",
          innerSize: "70%",
          borderRadius: 6,
          dataLabels: { enabled: true, distance: 20 }
        },
        bar: {
          stacking: "normal",
          pointWidth: 25,
          borderRadius: 5
        },
        ...plotOptionsOptions || {}
      },
      subtitle: showSubTitle ? {
        text: subtitleText,
        verticalAlign: "middle",
        floating: true,
        y: -10,
        style: { fontSize: "24px", fontWeight: "500", color: "#1F2B4D" },
        ...subtitleOptions || {}
      } : subtitleOptions && Object.keys(subtitleOptions).length ? subtitleOptions : void 0,
      credits: { enabled: false, ...creditsOptions || {} },
      legend: {
        enabled: !customLegend,
        symbolRadius: 2,
        layout: "horizontal",
        align: "center",
        verticalAlign: "bottom",
        itemDistance: 24,
        symbolPadding: 6,
        margin: 40,
        x: legendXPosition ?? void 0,
        y: legendYPosition ?? void 0,
        itemStyle: {
          color: "#60697D",
          fontFamily: "Manrope, sans-serif",
          fontSize: "12px",
          fontWeight: "500",
          lineHeight: "16px",
          padding: "20px"
        },
        itemHoverStyle: { color: "#0d152c" },
        navigation: { activeColor: "#3E576F", animation: true, arrowSize: 12 },
        ...legendOptions || {}
      },
      series: seriesOptions ?? seriesData ?? [],
      colorAxis: graphType === "heatmap" || graphType === "bubble" || graphType === "packedbubble" || graphType === "treemap" ? { minColor: "#ffffff", maxColor: "#658EC4", ...colorAxisOptions || {} } : colorAxisOptions && Object.keys(colorAxisOptions).length ? colorAxisOptions : void 0,
      ...additionalOptions || {}
    }),
    [
      graphType,
      xAxisCategories,
      xAxisTitle,
      yAxisTitle,
      seriesData,
      stackedColumn,
      is3D,
      isExpanded,
      showScrollX,
      height,
      width,
      customLegend,
      titleOptions,
      xAxisOptions,
      yAxisOptions,
      yAxisLeftOptions,
      yAxisRightOptions,
      zAxisOptions,
      tooltipOptions,
      plotOptionsOptions,
      subtitleOptions,
      creditsOptions,
      legendOptions,
      colorAxisOptions,
      seriesOptions,
      additionalOptions,
      chartMarginBottom,
      chartOptions,
      showSubTitle,
      subtitleText,
      legendXPosition,
      legendYPosition,
      xAxisTitlePositionY,
      customTooltipFormatter,
      sharedTooltip,
      plotOptionsEvents,
      subtitleOptions
    ]
  );
  const menuOptions = useMemo(
    () => chartTypesToMenuOptions(chartTypesOptions),
    [chartTypesOptions]
  );
  if (!showchart) {
    return /* @__PURE__ */ jsx(Fragment, { children: fallbackContent });
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: containerRef,
      className: `chart-container ${isExpanded ? "expanded" : ""} ${isAnimating ? "animating" : ""} ${cardContainer ? "card-container" : ""} ${className ?? ""}`.trim(),
      "data-testid": dataTestId,
      style: width ? { width } : void 0,
      children: [
        showHeader && /* @__PURE__ */ jsxs("div", { className: "chart-container-header", children: [
          /* @__PURE__ */ jsxs("div", { className: "chart-container-header-title", children: [
            /* @__PURE__ */ jsx("span", { className: "chart-container-header-title-text", children: graphTitle }),
            topLeftOptions != null && topLeftOptions !== false && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx("div", { className: "divider-line" }),
              topLeftOptions
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "chart-container-header-actions", children: [
            topRightOptions != null && /* @__PURE__ */ jsx("div", { className: "chart-custom-actions", children: React__default.isValidElement(topRightOptions) ? topRightOptions : null }),
            topRightOptions != null && /* @__PURE__ */ jsx("div", { className: "divider-line" }),
            showSwitchButton && !isExpanded && /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": "Switch to table view",
                icon: /* @__PURE__ */ jsx(default_1, {}),
                variant: "text",
                onClick: () => {
                  setShowChart(!showchart);
                }
              }
            ),
            showChartTypeDropdown && /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": "Chart type",
                icon: /* @__PURE__ */ jsx("img", { "aria-hidden": true, alt: "", src: ChartDropdownUrl }),
                variant: "text",
                onClick: (e) => {
                  setShowChartList((prev) => !prev);
                  setSelectMenuAnchor(e.currentTarget);
                }
              }
            ),
            showDownloadButton && /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": "Download chart",
                icon: /* @__PURE__ */ jsx(default_1$1, {}),
                variant: "text",
                onClick: onChartDownload
              }
            ),
            customSystemButton,
            showExpandButton && /* @__PURE__ */ jsx(
              Button,
              {
                "aria-label": isExpanded ? "Exit fullscreen" : "Expand chart",
                icon: isExpanded ? /* @__PURE__ */ jsx("img", { "aria-hidden": true, alt: "", src: CollapseIconUrl }) : /* @__PURE__ */ jsx("img", { "aria-hidden": true, alt: "", src: ExpandIconUrl }),
                variant: "text",
                onClick: () => {
                  if (isExpanded) exitFullscreen();
                  else enterFullscreen();
                }
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsx(
          Menu,
          {
            anchorEl: selectMenuAnchor,
            iconPlacement: "left",
            MenuProps: {
              transformOrigin: { vertical: "top", horizontal: "right" },
              anchorOrigin: { vertical: "bottom", horizontal: "right" }
            },
            open: showChartList,
            options: menuOptions,
            selected: selectedChart != null ? { value: selectedChart } : void 0,
            onClose: () => {
              setShowChartList(false);
            },
            ...chartMenuProps ?? {}
          }
        ),
        /* @__PURE__ */ jsx(
          HighchartsReact,
          {
            ref: chartComponentRef,
            highcharts: Highcharts,
            options: graphData
          },
          safeStringify(graphData, "graph") + isExpanded
        ),
        customLegend != null && /* @__PURE__ */ jsx(
          "div",
          {
            className: "chart-custom-legend",
            style: { marginBottom: 12, marginTop: -32, ...customLegendStyle ?? {} },
            children: React__default.isValidElement(customLegend) ? customLegend : typeof customLegend === "function" ? customLegend((_a = chartComponentRef.current) == null ? void 0 : _a.chart) : null
          }
        )
      ]
    }
  );
}
Chart.displayName = "Chart";
export {
  Chart
};
