import { describe, it, expect, beforeEach } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from '../../test/utils';
import SettingsLayout, { menuForRole } from './SettingsLayout';
import { useAuthStore } from '../../stores/authStore';

beforeEach(() => {
  useAuthStore.setState({ primaryRole: 'doctor' });
});

describe('SettingsLayout', () => {
  it('renders the shared settings sidebar and the content', () => {
    renderWithProviders(
      <SettingsLayout active="subscription">
        <div>محتوای اشتراک</div>
      </SettingsLayout>,
    );
    expect(screen.getByText('خرید اشتراک')).toBeInTheDocument();
    expect(screen.getByText('محتوای اشتراک')).toBeInTheDocument();
  });

  it('marks the active item with aria-current=page', () => {
    renderWithProviders(<SettingsLayout active="subscription"><div /></SettingsLayout>);
    const active = screen.getByText('خرید اشتراک').closest('a');
    expect(active).toHaveAttribute('aria-current', 'page');
    expect(active).toHaveAttribute('href', '/admin/subscription');
  });

  it('renders the tauri-sourced items as navigable links', () => {
    renderWithProviders(<SettingsLayout active="subscription"><div /></SettingsLayout>);
    expect(screen.getByText('مدیریت نوبت دهی').closest('a')).toHaveAttribute('href', '/admin/appointment-settings');
    expect(screen.getByText('تگ ها').closest('a')).toHaveAttribute('href', '/admin/tags-settings');
    // 'مدیریت پزشک' lives in the main nav, not the settings menu
    expect(screen.queryByText('مدیریت پزشک')).not.toBeInTheDocument();
  });

  it('shows the same menu to every role (ungated, mirroring tauri)', () => {
    // the desktop sidebar is not role-gated: مدیریت مطب shows even for a doctor
    renderWithProviders(<SettingsLayout active="subscription"><div /></SettingsLayout>);
    expect(screen.getByText('مدیریت مطب')).toBeInTheDocument();
  });

  it('filters the menu by the search query', () => {
    renderWithProviders(<SettingsLayout active="subscription"><div /></SettingsLayout>);
    fireEvent.change(screen.getByLabelText('جستجو در تنظیمات'), { target: { value: 'اشتراک' } });
    expect(screen.getByText('خرید اشتراک')).toBeInTheDocument();
    expect(screen.queryByText('خدمات')).not.toBeInTheDocument();
  });

  it('menuForRole still role-gates the mobile settings list', () => {
    // SettingsMenuPage (mobile) keeps using menuForRole / SETTINGS_MENU
    expect(menuForRole('clinic').map((i) => i.key)).toContain('clinic');
    expect(menuForRole('clinic').map((i) => i.key)).not.toContain('doctor');
    expect(menuForRole('clinic').map((i) => i.key)).not.toContain('appointment');
  });
});
