import { useCallback, useEffect, useRef } from "react";
import {
  createChart,
  LineSeries,
  ColorType,
  type IChartApi,
  type ISeriesApi,
  type LineData,
  type UTCTimestamp,
} from "lightweight-charts";

function chartPrefs() {
  const w = window.innerWidth;
  const compact = w <= 768;
  const tiny = w <= 480;
  return {
    fontSize: tiny ? 9 : compact ? 10 : 11,
    lineWidth: (tiny ? 1.25 : compact ? 1.5 : 2) as 1 | 2 | 3 | 4,
    scaleMargins: { top: compact ? 0.16 : 0.14, bottom: compact ? 0.12 : 0.1 },
    priceScaleWidth: compact ? 40 : 48,
  };
}

// 套用八方旅人色票的折線圖；高度由 CSS 控制，縮小時字體/線寬自動變細。
export default function SeriesChart({
  data,
  color = "#e7c66b",
}: {
  data: { date: string; val: number }[];
  height?: number;
  color?: string;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const chartRef = useRef<IChartApi | null>(null);
  const seriesRef = useRef<ISeriesApi<"Line"> | null>(null);

  const applyPrefs = useCallback(() => {
    const prefs = chartPrefs();
    chartRef.current?.applyOptions({
      layout: { fontSize: prefs.fontSize },
      rightPriceScale: {
        scaleMargins: prefs.scaleMargins,
        minimumWidth: prefs.priceScaleWidth,
      },
    });
    seriesRef.current?.applyOptions({ lineWidth: prefs.lineWidth });
  }, []);

  useEffect(() => {
    if (!ref.current) return;
    const prefs = chartPrefs();
    const chart = createChart(ref.current, {
      height: ref.current.clientHeight || 168,
      layout: {
        background: { type: ColorType.Solid, color: "transparent" },
        textColor: "#8b92b0",
        fontFamily: "'Noto Sans TC', 'Pixelify Sans', sans-serif",
        fontSize: prefs.fontSize,
        attributionLogo: false,
      },
      grid: {
        vertLines: { color: "rgba(231,198,107,.05)" },
        horzLines: { color: "rgba(231,198,107,.05)" },
      },
      rightPriceScale: {
        borderVisible: false,
        scaleMargins: prefs.scaleMargins,
        minimumWidth: prefs.priceScaleWidth,
      },
      timeScale: {
        borderVisible: false,
        fixLeftEdge: true,
        fixRightEdge: true,
        rightOffset: 4,
        barSpacing: 0.6,
      },
      crosshair: {
        vertLine: { color: "rgba(231,198,107,.25)", width: 1, style: 2 },
        horzLine: { color: "rgba(231,198,107,.25)", width: 1, style: 2 },
      },
      autoSize: true,
      handleScroll: false,
      handleScale: false,
    });
    const series = chart.addSeries(LineSeries, {
      color,
      lineWidth: prefs.lineWidth,
      priceLineVisible: false,
      lastValueVisible: true,
      crosshairMarkerRadius: 3,
    });
    chartRef.current = chart;
    seriesRef.current = series;

    const ro = new ResizeObserver(() => {
      const h = ref.current?.clientHeight ?? 0;
      if (h > 0) chart.applyOptions({ height: h });
    });
    ro.observe(ref.current);

    const onResize = () => applyPrefs();
    window.addEventListener("resize", onResize);

    return () => {
      ro.disconnect();
      window.removeEventListener("resize", onResize);
      chart.remove();
      chartRef.current = null;
      seriesRef.current = null;
    };
  }, [color, applyPrefs]);

  useEffect(() => {
    if (!seriesRef.current) return;
    const points: LineData[] = data
      .filter((p) => p.val != null && !Number.isNaN(p.val))
      .map((p) => ({ time: toTime(p.date), value: p.val }));
    seriesRef.current.setData(points);
    chartRef.current?.timeScale().fitContent();
  }, [data]);

  return <div ref={ref} className="px-chart" />;
}

function toTime(date: string): UTCTimestamp {
  return (Date.parse(date + "T00:00:00Z") / 1000) as UTCTimestamp;
}