// REQ-USR-003: useTabStack 标签栈逻辑（BR4/BR5/BR6）
import { describe, it, expect } from 'vitest';
import { act, renderHook } from '@testing-library/react';
import { useTabStack } from '../../src/layouts/AppLayout/useTabStack';

describe('useTabStack', () => {
  it('starts with fixed home tab only (closable false, leftmost)', () => {
    const { result } = renderHook(() => useTabStack());
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home']);
    expect(result.current.activeKey).toBe('home');
    expect(result.current.tabs[0].closable).toBe(false);
    expect(result.current.tabs[0].title).toBe('主页');
    expect(result.current.tabs[0].routePath).toBe('/');
  });

  it('openTab userlist appends userlist and activates it', () => {
    const { result } = renderHook(() => useTabStack());
    act(() => result.current.openTab('userlist'));
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home', 'userlist']);
    expect(result.current.activeKey).toBe('userlist');
    const ul = result.current.tabs.find((t) => t.key === 'userlist')!;
    expect(ul.closable).toBe(true);
    expect(ul.routePath).toBe('/usr/users');
    expect(ul.title).toBe('用户列表');
  });

  it('openTab userdetail ensures userlist exists then appends userdetail', () => {
    const { result } = renderHook(() => useTabStack());
    act(() => result.current.openTab('userdetail'));
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home', 'userlist', 'userdetail']);
    expect(result.current.activeKey).toBe('userdetail');
    const ud = result.current.tabs.find((t) => t.key === 'userdetail')!;
    expect(ud.title).toBe('用户信息单据');
    expect(ud.closable).toBe(true);
  });

  it('closeTab userlist also removes userdetail and activates home', () => {
    const { result } = renderHook(() => useTabStack());
    act(() => result.current.openTab('userdetail'));
    act(() => result.current.closeTab('userlist'));
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home']);
    expect(result.current.activeKey).toBe('home');
  });

  it('closeTab userdetail activates userlist', () => {
    const { result } = renderHook(() => useTabStack());
    act(() => result.current.openTab('userdetail'));
    act(() => result.current.closeTab('userdetail'));
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home', 'userlist']);
    expect(result.current.activeKey).toBe('userlist');
  });

  it('open existing tab does not duplicate', () => {
    const { result } = renderHook(() => useTabStack());
    act(() => result.current.openTab('userlist'));
    act(() => result.current.openTab('userlist'));
    expect(result.current.tabs.map((t) => t.key)).toEqual(['home', 'userlist']);
  });
});
