"use client";

import dynamic from "next/dynamic";
import { useEffect, useRef } from "react";
import type { CSSProperties } from "react";
import type { EChartsInstance } from "echarts-for-react";

const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });

interface Props {
  option: Record<string, unknown>;
  height?: number;
  style?: CSSProperties;
  loading?: boolean;
  notMerge?: boolean;
}

export function ChartShell({
  option,
  height = 320,
  style,
  loading,
  notMerge,
}: Props) {
  const wrapRef = useRef<HTMLDivElement | null>(null);
  const instanceRef = useRef<EChartsInstance | null>(null);

  // ECharts canvas only reflows on window.resize by default. On mobile/tablet
  // the chart container width changes via CSS (sidebar grid collapse, flex
  // column) WITHOUT a window resize, so the canvas keeps its desktop width and
  // overflows. A ResizeObserver on the wrapper resizes the instance whenever its
  // box changes — covers every chart that goes through ChartShell (issue #66).
  // The instance is captured via onChartReady (a plain prop) rather than a ref,
  // because next/dynamic does not forward refs to the wrapped component.
  useEffect(() => {
    const el = wrapRef.current;
    if (el == null || typeof ResizeObserver === "undefined") return;

    const ro = new ResizeObserver(() => {
      instanceRef.current?.resize();
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  return (
    <div ref={wrapRef} style={{ width: "100%", height, ...style }}>
      <ReactECharts
        option={option}
        style={{ height: "100%", width: "100%" }}
        showLoading={loading}
        notMerge={notMerge}
        onChartReady={(instance: EChartsInstance) => {
          instanceRef.current = instance;
        }}
      />
    </div>
  );
}
