/// <reference types="vitest" />
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import TradingViewChart from "../TradingViewChart";

// Use vi.hoisted to define mock functions that will be available during hoisting
const { mockSetData, mockCreateChart } = vi.hoisted(() => ({
  mockSetData: vi.fn(),
  mockCreateChart: vi.fn(() => ({
    addSeries: vi.fn(() => ({
      setData: vi.fn(),
    })),
    remove: vi.fn(),
  })),
}));

vi.mock("lightweight-charts", () => ({
  createChart: mockCreateChart,
  CandlestickSeries: {},
}));

describe("TradingViewChart", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    // Update the mock's setData to track calls
    const mockSeries = { setData: mockSetData };
    mockCreateChart.mockReturnValue({
      timeScale: () => ({ applyOptions: vi.fn(), fitContent: vi.fn() }),
      addSeries: vi.fn(() => mockSeries),
      remove: vi.fn(),
    });
  });

  it("renders the ticker symbol as heading", () => {
    render(<TradingViewChart ticker="AAPL" />);
    expect(screen.getByText("AAPL Price Chart")).toBeInTheDocument();
  });

  it("renders without data prop", () => {
    render(<TradingViewChart ticker="MSFT" />);
    expect(screen.getByText("MSFT Price Chart")).toBeInTheDocument();
    expect(mockSetData).not.toHaveBeenCalled();
  });

  it("calls setData with correct data format when data is provided", () => {
    const data = [
      { time: "2024-01-01", open: 100, high: 110, low: 95, close: 105 },
      { time: "2024-01-02", open: 105, high: 115, low: 100, close: 110 },
    ];
    render(<TradingViewChart ticker="GOOGL" data={data} />);
    
    expect(screen.getByText("GOOGL Price Chart")).toBeInTheDocument();
    expect(mockSetData).toHaveBeenCalledWith(data);
  });

  it("does not call setData when data array is empty", () => {
    render(<TradingViewChart ticker="TSLA" data={[]} />);
    
    expect(screen.getByText("TSLA Price Chart")).toBeInTheDocument();
    expect(mockSetData).not.toHaveBeenCalled();
  });

  it("creates chart with autoSize option for responsive sizing", () => {
    render(<TradingViewChart ticker="TEST" />);
    
    expect(mockCreateChart).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({
        autoSize: true,
      })
    );
  });

  it("creates candlestick series with explicit colors", () => {
    const mockAddSeries = vi.fn();
    mockCreateChart.mockReturnValue({
      timeScale: () => ({ applyOptions: vi.fn(), fitContent: vi.fn() }),
      addSeries: mockAddSeries,
      remove: vi.fn(),
    });

    render(<TradingViewChart ticker="TEST" />);

    expect(mockAddSeries).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({
        upColor: "#26a69a",
        downColor: "#ef5350",
      })
    );
  });
});