import React from "react";
import { MemoryRouter } from "react-router-dom";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DashboardPage } from "./DashboardPage";

const { useAuthMock, useOrderGroupsMock } = vi.hoisted(() => ({
  useAuthMock: vi.fn(),
  useOrderGroupsMock: vi.fn(),
}));

vi.mock("../context/AuthContext", () => ({
  useAuth: useAuthMock,
}));

vi.mock("../hooks/useOrderGroups", () => ({
  useOrderGroups: useOrderGroupsMock,
}));

vi.mock("../layouts/AppShell", () => ({
  AppShell: ({ children, navItems, onOpenGuide, isGuideOpen }) => (
    <div>
      <nav>{navItems.map((item) => <span key={item.key}>{item.label}</span>)}</nav>
      <button type="button" onClick={onOpenGuide} aria-label="Справка">
        {isGuideOpen ? "Назад" : "?"}
      </button>
      {children}
    </div>
  ),
}));

const baseGroup = {
  id: "group-1",
  groupKey: "9780001231|16.04.26",
  displayTitle: "Мария Волкова",
  displaySubtitle: "+7 978 000-12-31 · 16.04.26",
  customerName: "Мария Волкова",
  customerPhone: "+7 978 000-12-31",
  customerDate: "16.04.26",
  ordersCount: 1,
  readyCount: 1,
  notReadyCount: 0,
  orderNumbers: ["CD-240031"],
  status: "ready_for_notification",
  deliveryStatus: "agreed",
  delivery_status: "agreed",
  deliveryDate: "2026-04-16",
  deliveryTime: "Первая половина дня",
  updatedAt: "2026-04-15T09:00:00Z",
};

const mockOrderGroupsState = {
  orderGroups: [baseGroup],
  allOrderGroups: [baseGroup],
  filteredOrderGroups: [baseGroup],
  visibleOrderGroups: [baseGroup],
  selectedOrderGroup: baseGroup,
  selectedOrderGroupId: baseGroup.id,
  setSelectedOrderGroupId: vi.fn(),
  filters: {
    query: "",
    displayStatus: "all",
  },
  setFilters: vi.fn(),
  deliverySetBuckets: {
    ready_to_launch: [baseGroup],
    sms_sent: [],
    manual_work: [],
  },
  statusOptions: [
    { value: "all", label: "Все статусы" },
    { value: "status:ready_for_notification", label: "Готово к уведомлению" },
    { value: "delivery:agreed", label: "Согласовано" },
  ],
  isLoading: false,
  loadError: "",
  saveManualDeliveryChoice: vi.fn(),
  isSavingDeliveryChoice: false,
};

describe("DashboardPage", () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-04-15T09:00:00Z"));
    useOrderGroupsMock.mockReturnValue(mockOrderGroupsState);
  });

  it("keeps the manager dashboard on the group registry only", () => {
    useAuthMock.mockReturnValue({
      user: { id: "u-manager", name: "Анна", role: "manager" },
      signOut: vi.fn(),
    });

    const markup = renderToStaticMarkup(
      <MemoryRouter>
        <DashboardPage />
      </MemoryRouter>,
    );

    expect(markup).toContain("Группы доставки");
    expect(markup).toContain("Поиск по группе, клиенту, телефону и дате доставки.");
    expect(markup).toContain("aria-label=\"Справка\"");
    expect(markup).not.toContain("<span>Справка</span>");
    expect(markup).not.toContain("доставочный контур");
    expect(markup).not.toContain("Поиск по заказу, клиенту и телефону");
    expect(markup).not.toContain("Интерфейс показывает");
    expect(markup).not.toContain("Производство");
    expect(markup).not.toContain("Администрирование");
    expect(markup).not.toContain("Справочники");
    expect(markup).not.toContain("Календарь");
    expect(markup).not.toContain("Канбан");
    expect(markup).not.toContain("История");
    expect(markup).not.toContain("Архив");
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("keeps the logistician dashboard free of bot control and extra workspace", () => {
    useAuthMock.mockReturnValue({
      user: { id: "u-logistics", name: "Ольга", role: "logistician" },
      signOut: vi.fn(),
    });

    const markup = renderToStaticMarkup(
      <MemoryRouter>
        <DashboardPage />
      </MemoryRouter>,
    );

    expect(markup).toContain("Наборы доставки");
    expect(markup).toContain("Готовы к уведомлению");
    expect(markup).not.toContain("Управление ботами");
    expect(markup).not.toContain("рабочая панель");
    expect(markup).not.toContain("Сегодня");
    expect(markup).not.toContain("Производство");
    expect(markup).not.toContain("Администрирование");
    expect(markup).not.toContain("Справочники");
  });

  it("keeps the driver dashboard on the deliveries list only", () => {
    useOrderGroupsMock.mockReturnValue({
      ...mockOrderGroupsState,
      orderGroups: [baseGroup],
      allOrderGroups: [baseGroup],
      filteredOrderGroups: [baseGroup],
      visibleOrderGroups: [baseGroup],
      selectedOrderGroup: baseGroup,
      selectedOrderGroupId: baseGroup.id,
    });
    useAuthMock.mockReturnValue({
      user: { id: "u-driver", name: "Иван", role: "driver" },
      signOut: vi.fn(),
    });

    const markup = renderToStaticMarkup(
      <MemoryRouter>
        <DashboardPage />
      </MemoryRouter>,
    );

    expect(markup).toContain("Мои доставки");
    expect(markup).toContain("Мария Волкова");
    expect(markup).toContain("CD-240031");
    expect(markup).not.toContain("Канбан");
    expect(markup).not.toContain("Календарь");
    expect(markup).not.toContain("История");
    expect(markup).not.toContain("Архив");
    expect(markup).not.toContain("Производство");
  });
});
