/**
 * Tests for OnlineBoardStartPage component.
 *
 * Verifies page layout rendering with filter and info sections,
 * query param building from popular requests, and navigation on click.
 *
 * @vitest-environment jsdom
 */

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { OnlineBoardStartPage, buildPopularRequestQueryParams } from "./OnlineBoardStartPage.js";
import type { PopularRequest } from "@/features/popular-requests/types.js";

const mockNavigate = vi.fn();
const mockSearchParams = new URLSearchParams();

vi.mock("@modern-js/runtime/router", () => ({
  useNavigate: () => mockNavigate,
  useParams: () => ({ lang: "ru" }),
  useSearchParams: () => [mockSearchParams],
  Link: ({ children, to, ...props }: { children: React.ReactNode; to: string; className?: string; [k: string]: unknown }) => (
    <a href={to} {...props}>{children}</a>
  ),
}));

vi.mock("@/i18n/provider.js", () => ({
  useTranslation: () => ({
    t: (key: string) => key,
  }),
}));

vi.mock("@/features/popular-requests/components/PopularRequestsPanel.js", () => ({
  PopularRequestsPanel: ({ onRequestClick }: { onRequestClick?: (r: PopularRequest) => void }) => (
    <div data-testid="popular-requests">
      <button
        data-testid="popular-click"
        onClick={() => onRequestClick?.({ mode: "FlightNumber", carrier: "SU", flightNumber: "0654", type: "Onlineboard" })}
      >
        Popular
      </button>
    </div>
  ),
}));

vi.mock("@/shared/hooks/useCitySearch.js", () => ({
  useCitySearch: () => ({ suggestions: [], search: vi.fn() }),
}));

vi.mock("@/shared/hooks/useSearchHistory.js", () => ({
  useSearchHistory: () => ({ items: [], add: vi.fn(), clear: vi.fn() }),
}));

vi.mock("@/shared/dictionaries/index.js", () => ({
  useDictionaries: () => ({ dictionaries: null, loading: false, error: null }),
}));

vi.mock("@/ui/city-autocomplete/index.js", () => ({
  CityAutocomplete: (props: Record<string, unknown>) => (
    <input
      data-testid={`${(props["testIdPrefix"] as string) ?? "city-autocomplete"}-input`}
      placeholder={props["placeholder"] as string}
    />
  ),
}));

// ---------------------------------------------------------------------------
// Pure function: buildPopularRequestQueryParams
// ---------------------------------------------------------------------------

describe("buildPopularRequestQueryParams", () => {
  it("builds params for FlightNumber mode", () => {
    const request: PopularRequest = {
      mode: "FlightNumber",
      carrier: "SU",
      flightNumber: "0654",
      type: "Onlineboard",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("tab")).toBe("flight");
    expect(params.get("carrier")).toBe("SU");
    expect(params.get("flight")).toBe("0654");
    expect(params.has("departure")).toBe(false);
    expect(params.has("arrival")).toBe(false);
  });

  it("builds params for Departure mode", () => {
    const request: PopularRequest = {
      mode: "Departure",
      departure: "LED",
      type: "Onlineboard",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("tab")).toBe("route");
    expect(params.get("departure")).toBe("LED");
    expect(params.has("arrival")).toBe(false);
    expect(params.has("carrier")).toBe(false);
  });

  it("builds params for Arrival mode", () => {
    const request: PopularRequest = {
      mode: "Arrival",
      arrival: "VKO",
      type: "Onlineboard",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("tab")).toBe("route");
    expect(params.get("arrival")).toBe("VKO");
    expect(params.has("departure")).toBe(false);
  });

  it("builds params for Route mode (Onlineboard)", () => {
    const request: PopularRequest = {
      mode: "Route",
      departure: "LED",
      arrival: "KRR",
      type: "Onlineboard",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("tab")).toBe("route");
    expect(params.get("departure")).toBe("LED");
    expect(params.get("arrival")).toBe("KRR");
    expect(params.has("return")).toBe(false);
  });

  it("builds params for Route mode (Schedule)", () => {
    const request: PopularRequest = {
      mode: "Route",
      departure: "SVO",
      arrival: "LED",
      type: "Schedule",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("departure")).toBe("SVO");
    expect(params.get("arrival")).toBe("LED");
    expect(params.has("return")).toBe(false);
  });

  it("builds params for RouteWithBack mode (Schedule) with return flag", () => {
    const request: PopularRequest = {
      mode: "RouteWithBack",
      departure: "SVO",
      arrival: "LED",
      type: "Schedule",
    };
    const params = buildPopularRequestQueryParams(request);
    expect(params.get("departure")).toBe("SVO");
    expect(params.get("arrival")).toBe("LED");
    expect(params.get("return")).toBe("true");
  });
});

// ---------------------------------------------------------------------------
// Component tests
// ---------------------------------------------------------------------------

describe("OnlineBoardStartPage", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("renders start page with page layout structure", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("online-board-start")).toBeTruthy();
  });

  it("renders the page title as h1", () => {
    render(<OnlineBoardStartPage />);
    const heading = screen.getAllByText("BOARD.TITLE");
    const h1 = heading.find((el) => el.tagName === "H1");
    expect(h1).toBeTruthy();
  });

  it("renders the info section heading", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByText("BOARD.BOARD-START")).toBeTruthy();
  });

  it("renders 4 info tiles", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByText("BOARD.BOARD-START-TITLE1")).toBeTruthy();
    expect(screen.getByText("BOARD.BOARD-START-TITLE2")).toBeTruthy();
    expect(screen.getByText("BOARD.BOARD-START-TITLE3")).toBeTruthy();
    expect(screen.getByText("BOARD.BOARD-START-TITLE4")).toBeTruthy();
  });

  it("renders the filter component", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("flight-filter")).toBeTruthy();
  });

  it("renders page tabs", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("onlineboard-tab")).toBeTruthy();
    expect(screen.getByTestId("schedule-tab")).toBeTruthy();
  });

  it("renders the popular requests panel", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("popular-requests")).toBeTruthy();
  });

  it("renders breadcrumbs", () => {
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("breadcrumbs")).toBeTruthy();
  });

  it.skip("renders feedback button", () => {
    // Feedback button not yet implemented — stub kept for future Gap B.4 work
    render(<OnlineBoardStartPage />);
    expect(screen.getByTestId("feedback-button")).toBeTruthy();
  });

  it("navigates on popular request click (Onlineboard type)", () => {
    render(<OnlineBoardStartPage />);
    const btn = screen.getByTestId("popular-click");
    fireEvent.click(btn);
    expect(mockNavigate).toHaveBeenCalledWith(
      expect.objectContaining({
        search: expect.stringContaining("tab=flight"),
      }),
    );
  });
});
