import { expect, test } from "vitest";
import { screen, within } from "@testing-library/react";
import { Routes, Route } from "react-router-dom";
import { renderApp } from "../test/render";
import { AppShell } from "./app-shell";
import { ObjectNewPage } from "../objects/object-new-page";
import { BreadcrumbProvider } from "./breadcrumb-provider";
import { Breadcrumb } from "./breadcrumb";
import { useBreadcrumb } from "./use-breadcrumb";

function Setter() {
  useBreadcrumb([
    { label: "Objects", to: "/objects" },
    { label: "LM-0042" },
  ]);
  return null;
}

test("renders the trail with a link on non-leaf crumbs", async () => {
  renderApp(
    <BreadcrumbProvider>
      <Breadcrumb />
      <Setter />
    </BreadcrumbProvider>,
  );
  const link = await screen.findByRole("link", { name: "Objects" });
  expect(link).toHaveAttribute("href", "/objects");
  expect(screen.getByText("LM-0042")).toBeInTheDocument();
  expect(screen.getByRole("navigation", { name: /breadcrumb/i })).toBeInTheDocument();
});

test("a nested route sets the header breadcrumb inside AppShell", async () => {
  renderApp(
    <Routes>
      <Route element={<AppShell />}>
        <Route path="/objects/new" element={<ObjectNewPage />} />
      </Route>
    </Routes>,
    { route: "/objects/new" },
  );

  const nav = await screen.findByRole("navigation", { name: "Breadcrumb" });
  const within_nav = within(nav);

  const objectsLink = within_nav.getByRole("link", { name: "Objects" });
  expect(objectsLink).toHaveAttribute("href", "/objects");
  expect(within_nav.getByText("New object")).toBeInTheDocument();
});
