"use client";

import { useEffect, useRef } from "react";
import { createChart, ColorType } from "lightweight-charts";

interface EquityChartProps {
  data: { t: number; v: number }[];
  color?: string;
  height?: number;
}

export function EquityChart({ data, color = "#3b82f6", height = 260 }: EquityChartProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<ReturnType<typeof createChart> | null>(null);
  const seriesRef = useRef<any>(null);

  const seriesColor = color.startsWith("#") ? color : "#3b82f6";

  useEffect(() => {
    if (!containerRef.current || data.length === 0) return;

    const chart = createChart(containerRef.current, {
      layout: {
        background: { type: ColorType.Solid, color: "transparent" },
        textColor: "#b0b7c0",
      },
      grid: {
        vertLines: { color: "rgba(255,255,255,0.03)" },
        horzLines: { color: "rgba(255,255,255,0.03)" },
      },
      rightPriceScale: { borderColor: "rgba(255,255,255,0.08)" },
      timeScale: { borderColor: "rgba(255,255,255,0.08)", timeVisible: true },
      crosshair: { mode: 0 },
      width: containerRef.current.clientWidth,
      height,
    });

    const series = chart.addAreaSeries({
      lineColor: seriesColor,
      topColor: `${seriesColor}26`,
      bottomColor: `${seriesColor}05`,
      lineWidth: 2,
    });

    const pts = data.map((d) => ({
      time: d.t as import("lightweight-charts").UTCTimestamp,
      value: d.v,
    }));
    series.setData(pts);
    chart.timeScale().fitContent();

    chartRef.current = chart;
    seriesRef.current = series;

    const handleResize = () => {
      if (containerRef.current && chartRef.current) {
        chartRef.current.applyOptions({ width: containerRef.current.clientWidth });
      }
    };
    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
      chart.remove();
    };
  }, [data, seriesColor, height]);

  useEffect(() => {
    if (seriesRef.current && data.length > 0) {
      const pts = data.map((d) => ({
        time: d.t as import("lightweight-charts").UTCTimestamp,
        value: d.v,
      }));
      seriesRef.current.setData(pts);
      chartRef.current?.timeScale().fitContent();
    }
  }, [data]);

  return <div ref={containerRef} style={{ width: "100%", height }} />;
}
