import { expect, test } from "vitest";
import { screen } from "@testing-library/react";

import { renderApp } from "../test/render";
import { FlexibleFieldValue } from "./flexible-field-value";
import { fieldDefinitions } from "../test/fixtures";

function def(key: string) {
  return fieldDefinitions.find((d) => d.key === key)!;
}

test("term id resolves to its label", async () => {
  renderApp(<FlexibleFieldValue def={def("material")} value="t-bronze" lang="en" />);

  expect(await screen.findByText("Bronze")).toBeInTheDocument();
});

test("authority id resolves to its label", async () => {
  renderApp(<FlexibleFieldValue def={def("maker")} value="a-ada" lang="en" />);

  expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
});

test("unknown term id renders <id> (unknown)", async () => {
  renderApp(<FlexibleFieldValue def={def("material")} value="t-missing" lang="en" />);

  expect(await screen.findByText(/t-missing\s*\(unknown\)/)).toBeInTheDocument();
});

test("localized_text picks the active language string", () => {
  renderApp(
    <FlexibleFieldValue
      def={def("title_ml")}
      value={{ sv: "Brons-amfora", en: "Bronze amphora" }}
      lang="sv"
    />,
  );

  expect(screen.getByText("Brons-amfora")).toBeInTheDocument();
  expect(screen.queryByText("Bronze amphora")).not.toBeInTheDocument();
});

test("date is formatted, not the raw ISO string", () => {
  renderApp(<FlexibleFieldValue def={def("made_on")} value="2024-01-05" lang="en" />);

  expect(screen.queryByText("2024-01-05")).not.toBeInTheDocument();
  expect(screen.getByText(/Jan.*5.*2024/)).toBeInTheDocument();
});

test("boolean true renders Yes", () => {
  renderApp(<FlexibleFieldValue def={def("is_fragment")} value={true} lang="en" />);

  expect(screen.getByText("Yes")).toBeInTheDocument();
});
