import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { Sidebar } from './sidebar';

describe('Sidebar', () => {
  beforeEach(async () => {
    localStorage.clear();
    await TestBed.configureTestingModule({
      imports: [Sidebar],
      providers: [provideRouter([])],
    }).compileComponents();
  });

  it('renders the three v1 menu groups', async () => {
    const fixture = TestBed.createComponent(Sidebar);
    await fixture.whenStable();
    const text = (fixture.nativeElement as HTMLElement).textContent ?? '';
    expect(text).toContain('General');
    expect(text).toContain('Establishments');
    expect(text).toContain('Communication');
  });

  it('does not render the accessibility links (now lives in the footer)', async () => {
    const fixture = TestBed.createComponent(Sidebar);
    await fixture.whenStable();
    const root = fixture.nativeElement as HTMLElement;
    expect(root.querySelector('a[href="/accessibility"]')).toBeNull();
    expect(root.querySelector('a[href="/accessibilite"]')).toBeNull();
  });

  it('no longer renders the role widget (moved into the user menu)', async () => {
    const fixture = TestBed.createComponent(Sidebar);
    await fixture.whenStable();
    expect(
      (fixture.nativeElement as HTMLElement).querySelector('[data-testid="sidebar-role"]'),
    ).toBeNull();
  });

  it('starts expanded and collapses on toggle, persisting to localStorage', async () => {
    const fixture = TestBed.createComponent(Sidebar);
    fixture.detectChanges();
    await fixture.whenStable();
    const root = fixture.nativeElement as HTMLElement;
    const aside = root.querySelector('aside');
    expect(aside?.classList.contains('sidebar--collapsed')).toBe(false);

    const toggle = root.querySelector('button.sidebar__toggle') as HTMLButtonElement;
    toggle.click();
    fixture.detectChanges();
    await fixture.whenStable();

    expect(aside?.classList.contains('sidebar--collapsed')).toBe(true);
    expect(toggle.getAttribute('aria-expanded')).toBe('false');
    expect(localStorage.getItem('portal-shell:sidebar-collapsed')).toBe('1');
  });

  it('restores the collapsed state from localStorage on init', async () => {
    localStorage.setItem('portal-shell:sidebar-collapsed', '1');
    const fixture = TestBed.createComponent(Sidebar);
    fixture.detectChanges();
    await fixture.whenStable();
    const aside = (fixture.nativeElement as HTMLElement).querySelector('aside');
    expect(aside?.classList.contains('sidebar--collapsed')).toBe(true);
  });
});
