/**
 * Tests for ScheduleStartPage component.
 *
 * Verifies query param building from popular requests and
 * form state initialization from URL search params.
 *
 * @vitest-environment jsdom
 */

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

const mockNavigate = vi.fn();
let 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-route"
        onClick={() => onRequestClick?.({ mode: "Route", departure: "SVO", arrival: "LED", type: "Schedule" })}
      >
        Route
      </button>
      <button
        data-testid="popular-click-onlineboard"
        onClick={() => onRequestClick?.({ mode: "Departure", departure: "LED", type: "Onlineboard" })}
      >
        Onlineboard
      </button>
    </div>
  ),
}));

vi.mock("@/features/online-board/components/OnlineBoardStartPage.js", () => ({
  buildPopularRequestQueryParams: (request: PopularRequest) => {
    const params = new URLSearchParams();
    if (request.mode === "Departure") {
      params.set("tab", "route");
      params.set("departure", (request as { departure: string }).departure);
    }
    return params;
  },
}));

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

vi.mock("@/ui/layout/SearchHistory.js", () => ({
  SearchHistory: () => <div data-testid="search-history" />,
}));

// ---------------------------------------------------------------------------
// Pure function: buildSchedulePopularRequestQueryParams
// ---------------------------------------------------------------------------

describe("buildSchedulePopularRequestQueryParams", () => {
  it("builds params for Route mode with departure and arrival", () => {
    const request: PopularRequest = {
      mode: "Route",
      departure: "SVO",
      arrival: "LED",
      type: "Schedule",
    };
    const params = buildSchedulePopularRequestQueryParams(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 with return flag", () => {
    const request: PopularRequest = {
      mode: "RouteWithBack",
      departure: "SVO",
      arrival: "LED",
      type: "Schedule",
    };
    const params = buildSchedulePopularRequestQueryParams(request);
    expect(params.get("departure")).toBe("SVO");
    expect(params.get("arrival")).toBe("LED");
    expect(params.get("return")).toBe("true");
  });

  it("returns empty params for non-route modes", () => {
    const request: PopularRequest = {
      mode: "Arrival",
      arrival: "VKO",
      type: "Onlineboard",
    };
    const params = buildSchedulePopularRequestQueryParams(request);
    expect(params.toString()).toBe("");
  });
});

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

describe("ScheduleStartPage", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockSearchParams = new URLSearchParams();
  });

  it("renders the start page", () => {
    render(<ScheduleStartPage />);
    expect(screen.getByTestId("schedule-start")).toBeTruthy();
  });

  it("navigates to schedule page on Schedule-type popular request click", () => {
    render(<ScheduleStartPage />);
    fireEvent.click(screen.getByTestId("popular-click-route"));
    expect(mockNavigate).toHaveBeenCalledWith(
      expect.objectContaining({
        pathname: "/ru/schedule",
        search: expect.stringContaining("departure=SVO"),
      }),
    );
  });

  it("navigates to onlineboard on Onlineboard-type popular request click", () => {
    render(<ScheduleStartPage />);
    fireEvent.click(screen.getByTestId("popular-click-onlineboard"));
    expect(mockNavigate).toHaveBeenCalledWith(
      expect.objectContaining({
        pathname: "/ru/onlineboard",
      }),
    );
  });

  it("initializes form from search params", () => {
    mockSearchParams = new URLSearchParams("departure=SVO&arrival=LED&return=true");
    render(<ScheduleStartPage />);
    const roundTripCheckbox = screen.getByTestId("round-trip-toggle");
    expect((roundTripCheckbox as HTMLInputElement).checked).toBe(true);
  });
});
