import { render, screen, fireEvent } from '@testing-library/react';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { DensityToggle } from '../density-toggle';

// Mock the zustand store to avoid localStorage/persist issues in jsdom
const mockToggleDensity = vi.fn();
let mockDensity = 'regular';

vi.mock('@/lib/preferences-store', () => ({
  usePreferencesStore: () => ({
    get density() {
      return mockDensity;
    },
    toggleDensity: mockToggleDensity,
  }),
}));

describe('DensityToggle', () => {
  beforeEach(() => {
    mockDensity = 'regular';
    mockToggleDensity.mockClear();
  });

  it('renders a button with role="switch"', () => {
    render(<DensityToggle />);
    expect(screen.getByRole('switch')).toBeInTheDocument();
  });

  it('has aria-checked="false" when density is regular', () => {
    render(<DensityToggle />);
    expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false');
  });

  it('has aria-checked="true" when density is compact', () => {
    mockDensity = 'compact';
    render(<DensityToggle />);
    expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
  });

  it('calls toggleDensity on click', () => {
    render(<DensityToggle />);
    fireEvent.click(screen.getByRole('switch'));
    expect(mockToggleDensity).toHaveBeenCalledOnce();
  });

  it('applies custom aria-label via label prop', () => {
    render(<DensityToggle label="Toggle view" />);
    expect(screen.getByRole('switch')).toHaveAttribute('aria-label', 'Toggle view');
  });

  it('has a default aria-label', () => {
    render(<DensityToggle />);
    expect(screen.getByRole('switch')).toHaveAttribute('aria-label');
  });

  it('merges custom className', () => {
    render(<DensityToggle className="extra" />);
    expect(screen.getByRole('switch')).toHaveClass('extra');
  });
});
