/* eslint-disable import-x/order */
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, beforeEach, vi } from 'vitest';

// ─── Mock preferences-store before module load ───────────────────────────────
const toggleDensityMock = vi.fn();
const setDensityMock = vi.fn();
let mockDensity: 'compact' | 'regular' = 'regular';

vi.mock('@/lib/preferences-store', () => ({
  usePreferencesStore: () => ({
    density: mockDensity,
    toggleDensity: toggleDensityMock,
    setDensity: setDensityMock,
  }),
}));

import { DensityToggle } from '../density-toggle';

describe('DensityToggle', () => {
  beforeEach(() => {
    mockDensity = 'regular';
    toggleDensityMock.mockReset();
    toggleDensityMock.mockImplementation(() => {
      mockDensity = mockDensity === 'compact' ? 'regular' : 'compact';
    });
  });

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

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

  it('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(toggleDensityMock).toHaveBeenCalledOnce();
  });

  it('shows custom aria-label when provided', () => {
    render(<DensityToggle label="Custom label" />);
    expect(screen.getByLabelText('Custom label')).toBeInTheDocument();
  });
});
