// REQ-USR-003: HomePage 落地页区域组合（KPI 头条 / 角色树 / 常用操作 / 页脚，BR8/BR11）
import { describe, it, expect } from 'vitest';
import { screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Routes, Route, useLocation } from 'react-router-dom';
import { renderShell } from './renderShell';
import HomePage from '../../src/pages/home/HomePage/HomePage';

function LocationProbe() {
  const loc = useLocation();
  return <div data-testid="loc">{loc.pathname}</div>;
}

function renderHome() {
  return renderShell(
    <>
      <LocationProbe />
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/usr/users" element={<div data-testid="users-sentinel">users</div>} />
      </Routes>
    </>,
    {
      initialEntries: ['/'],
      preloadedAuth: {
        token: 't',
        user: { id: 1, sUserName: '朱子纯', sUserType: '超级管理员', sLanguage: '中文' },
      },
    },
  );
}

describe('HomePage', () => {
  it('renders KPI head with title and stats', () => {
    renderHome();
    expect(screen.getByText('KPI监控')).toBeInTheDocument();
    expect(screen.getByText('今日未处理：')).toBeInTheDocument();
    expect(screen.getByText('37428')).toBeInTheDocument();
    expect(screen.getByText('未清总数：')).toBeInTheDocument();
    expect(screen.getByText('56433')).toBeInTheDocument();
    expect(screen.getByText('小ai同学,请帮我安排今日工作')).toBeInTheDocument();
  });

  it('renders role/process tree groups', () => {
    renderHome();
    const tree = within(screen.getByTestId('role-tree'));
    expect(tree.getByText('按角色')).toBeInTheDocument();
    expect(tree.getByText('按流程')).toBeInTheDocument();
    expect(tree.getByText(/所有部门/)).toBeInTheDocument();
    expect(tree.getByText(/客服部/)).toBeInTheDocument();
  });

  it('tree item click highlights without navigation', async () => {
    renderHome();
    const tree = within(screen.getByTestId('role-tree'));
    const item = tree.getByRole('button', { name: /核价人员/ });
    await userEvent.click(item);
    // 高亮（aria-pressed），不触发路由跳转
    expect(item).toHaveAttribute('aria-pressed', 'true');
    expect(screen.getByTestId('loc').textContent).toBe('/');
  });

  it('common ops user-list click navigates to /usr/users', async () => {
    renderHome();
    // 常用操作卡内「用户列表」
    const opsUserList = screen.getByRole('button', { name: '用户列表' });
    await userEvent.click(opsUserList);
    expect(screen.getByTestId('loc').textContent).toBe('/usr/users');
  });

  it('renders footer copyright text', () => {
    renderHome();
    expect(screen.getByText(/©Copyright Antler Software/)).toBeInTheDocument();
    expect(screen.getByText(/沪ICP备14034791号-1/)).toBeInTheDocument();
  });
});
