import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from './resizable';
import React from 'react';

describe('Resizable', () => {
  it('renders correctly with panels and handles', () => {
    const { container } = render(
      <ResizablePanelGroup direction="horizontal">
        <ResizablePanel defaultSize={30}>One</ResizablePanel>
        <ResizableHandle />
        <ResizablePanel defaultSize={70}>Two</ResizablePanel>
      </ResizablePanelGroup>
    );

    expect(screen.getByText('One')).toBeInTheDocument();
    expect(screen.getByText('Two')).toBeInTheDocument();
    expect(container.querySelector('[data-slot="resizable-handle"]')).toBeInTheDocument();
  });

  it('applies initial sizes correctly', () => {
    render(
      <ResizablePanelGroup direction="horizontal">
        <ResizablePanel defaultSize={30}>One</ResizablePanel>
        <ResizableHandle />
        <ResizablePanel defaultSize={70}>Two</ResizablePanel>
      </ResizablePanelGroup>
    );

    const panel1 = screen.getByText('One').closest('[data-slot="resizable-panel"]');
    const panel2 = screen.getByText('Two').closest('[data-slot="resizable-panel"]');

    expect(panel1).toHaveStyle('flex: 30 1 0%');
    expect(panel2).toHaveStyle('flex: 70 1 0%');
  });

  it('updates sizes on handle drag', () => {
    Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
      configurable: true,
      value: 1000,
    });

    const { container } = render(
      <ResizablePanelGroup direction="horizontal">
        <ResizablePanel defaultSize={50}>One</ResizablePanel>
        <ResizableHandle />
        <ResizablePanel defaultSize={50}>Two</ResizablePanel>
      </ResizablePanelGroup>
    );

    const handle = container.querySelector('[data-slot="resizable-handle"]') as HTMLElement;
    const panel1 = screen.getByText('One').closest('[data-slot="resizable-panel"]');

    fireEvent.mouseDown(handle, { clientX: 500, clientY: 0 });
    fireEvent.mouseMove(window, { clientX: 600, clientY: 0 });

    expect(panel1).toHaveStyle('flex: 60 1 0%');

    fireEvent.mouseUp(window);
  });
});
