import { TestBed } from '@angular/core/testing';
import { vi } from 'vitest';
import { LocaleSwitcher } from './locale-switcher';

describe('LocaleSwitcher', () => {
  beforeEach(async () => {
    document.documentElement.lang = 'en';
    await TestBed.configureTestingModule({ imports: [LocaleSwitcher] }).compileComponents();
  });

  afterEach(() => {
    document.documentElement.lang = '';
  });

  it('renders a trigger labelled with the active locale display name', async () => {
    const fixture = TestBed.createComponent(LocaleSwitcher);
    await fixture.whenStable();
    const trigger = (fixture.nativeElement as HTMLElement).querySelector(
      'button[aria-haspopup="menu"]',
    ) as HTMLButtonElement | null;
    expect(trigger).not.toBeNull();
    expect(trigger?.textContent).toContain('English');
    expect(trigger?.getAttribute('aria-label')).toContain('English');
  });

  it('picks up the active locale from <html lang>', async () => {
    document.documentElement.lang = 'fr';
    const fixture = TestBed.createComponent(LocaleSwitcher);
    await fixture.whenStable();
    const trigger = (fixture.nativeElement as HTMLElement).querySelector(
      'button[aria-haspopup="menu"]',
    ) as HTMLButtonElement | null;
    expect(trigger?.textContent).toContain('Français');
  });

  it('builds the target URL by swapping the locale prefix and hard-navigates', () => {
    const fixture = TestBed.createComponent(LocaleSwitcher);
    const component = fixture.componentInstance as unknown as {
      select(code: 'fr' | 'en'): void;
    };
    const original = window.location;
    const assign = vi.fn();
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: { pathname: '/en/accessibility', search: '?from=footer', hash: '', assign },
    });
    component.select('fr');
    expect(assign).toHaveBeenCalledWith('/fr/accessibility?from=footer');
    Object.defineProperty(window, 'location', { configurable: true, value: original });
  });

  it('does nothing when the selected locale matches the current one', () => {
    const fixture = TestBed.createComponent(LocaleSwitcher);
    const component = fixture.componentInstance as unknown as {
      select(code: 'fr' | 'en'): void;
    };
    const original = window.location;
    const assign = vi.fn();
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: { pathname: '/en/', search: '', hash: '', assign },
    });
    component.select('en');
    expect(assign).not.toHaveBeenCalled();
    Object.defineProperty(window, 'location', { configurable: true, value: original });
  });
});
