import { afterEach, expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import { Route, Routes } from "react-router-dom";

import { renderApp } from "../test/render";
import { SearchPage } from "./search-page";
import { ObjectDetail } from "../objects/object-detail";
import { SelectSearchPrompt } from "./select-search-prompt";

function setViewport(wide: boolean) {
  Object.defineProperty(window, "matchMedia", {
    value: (query: string): MediaQueryList =>
      ({
        matches: wide && query === "(min-width: 1024px)",
        media: query,
        onchange: null,
        addEventListener: () => {},
        removeEventListener: () => {},
        addListener: () => {},
        removeListener: () => {},
        dispatchEvent: () => false,
      }) as MediaQueryList,
    writable: true,
  });
}

afterEach(() => vi.restoreAllMocks());

function tree() {
  return (
    <Routes>
      <Route path="/search" element={<SearchPage />}>
        <Route index element={<SelectSearchPrompt />} />
        <Route path=":id" element={<ObjectDetail />} />
      </Route>
    </Routes>
  );
}

test("narrow: a selected result's detail renders in a portaled drawer", async () => {
  setViewport(false);
  renderApp(tree(), { route: "/search/11111111-1111-1111-1111-111111111111" });

  const body = within(document.body);
  expect(
    await body.findByRole("button", { name: /close detail/i }, { timeout: 5000 }),
  ).toBeInTheDocument();
});

test("wide: a selected result renders inline, with no detail drawer", async () => {
  setViewport(true);
  renderApp(tree(), { route: "/search/11111111-1111-1111-1111-111111111111" });

  expect(await screen.findByRole("heading", { name: "Amphora" })).toBeInTheDocument();
  expect(screen.queryByRole("button", { name: /close detail/i })).toBeNull();
});
