import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { Rating } from './rating';
import React from 'react';

describe('Rating', () => {
  it('renders correctly with default max stars', () => {
    const { container } = render(<Rating />);
    const buttons = container.querySelectorAll('button');
    expect(buttons).toHaveLength(5);
  });

  it('renders custom max stars', () => {
    const { container } = render(<Rating max={10} />);
    const buttons = container.querySelectorAll('button');
    expect(buttons).toHaveLength(10);
  });

  it('highlights filled stars based on value', () => {
    const { container } = render(<Rating value={3} />);
    const filledStars = container.querySelectorAll('.fill-warning');
    expect(filledStars).toHaveLength(3);
  });

  it('calls onChange when a star is clicked', () => {
    const onChange = vi.fn();
    const { container } = render(<Rating onChange={onChange} />);
    const buttons = container.querySelectorAll('button');

    fireEvent.click(buttons[3]); // 4th star
    expect(onChange).toHaveBeenCalledWith(4);
  });

  it('does not call onChange when readonly', () => {
    const onChange = vi.fn();
    const { container } = render(<Rating value={3} readonly onChange={onChange} />);
    const buttons = container.querySelectorAll('button');

    fireEvent.click(buttons[4]);
    expect(onChange).not.toHaveBeenCalled();
    expect(buttons[4]).toBeDisabled();
  });

  it('shows value text when showValue is true', () => {
    render(<Rating value={4.5} showValue />);
    expect(screen.getByText('4.5')).toBeInTheDocument();
  });
});
