import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, it } from "vitest";
import { KEYS } from "../../data/mock/keys";
import { I18nProvider } from "../../i18n/I18nContext";
import { translate } from "../../lib/i18n/messages";
import { PageHeader } from "./PageHeader";
import { PageHelpProvider } from "./PageHelp";

const t = (key: string) => translate("zh-TW", key);

function renderAt(path: string, title = "測試頁") {
  return render(
    <I18nProvider>
      <MemoryRouter initialEntries={[path]}>
        <Routes>
          <Route
            path="*"
            element={
              <PageHelpProvider>
                <PageHeader title={title} />
              </PageHelpProvider>
            }
          />
        </Routes>
      </MemoryRouter>
    </I18nProvider>,
  );
}

describe("PageHelp next to title", () => {
  beforeEach(() => {
    localStorage.setItem(
      KEYS.uiPrefs,
      JSON.stringify({ locale: "zh-TW", currency: "TWD", theme: "system" }),
    );
  });

  it("opens portaled drawer from the title-row trigger", async () => {
    renderAt("/app/radar/today", "頁面標題");

    expect(screen.getByRole("heading", { level: 1, name: "頁面標題" })).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: t("help.open") }));

    const dialog = await screen.findByRole("dialog");
    expect(document.body.contains(dialog)).toBe(true);
    expect(
      within(dialog).getByRole("heading", { name: t("help.page.radar_today.title") }),
    ).toBeTruthy();
    expect(within(dialog).getByText(t("help.page.radar_today.what"))).toBeTruthy();
  });

  it("keeps help off the page body until opened", () => {
    renderAt("/app/scout");
    expect(screen.queryByRole("dialog")).toBeNull();
    expect(screen.queryByText(t("help.page.scout.what"))).toBeNull();
    expect(screen.getByRole("button", { name: t("help.open") })).toBeTruthy();
  });

  it("closes on Escape", async () => {
    renderAt("/app/today");
    fireEvent.click(screen.getByRole("button", { name: t("help.open") }));
    expect(await screen.findByRole("dialog")).toBeTruthy();
    fireEvent.keyDown(document, { key: "Escape" });
    await waitFor(() => {
      expect(screen.queryByRole("dialog")).toBeNull();
    });
  });
});
