import { render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";

import { ProductDetailGrid } from "../product-detail-grid";

describe("ProductDetailGrid", () => {
  it("renders available product facts and measurements for complete data", () => {
    render(
      <ProductDetailGrid
        id="item-123456789abcdef"
        brand="Levis"
        size="M"
        condition="EUC"
        conditionLabel="Excellent used condition"
        colors={["Blue", " White "]}
        category={{ name: "Tops" }}
        measurements={{
          length: "27 in",
          chest_width: "19 in",
        }}
        created_at="2026-05-09T15:30:00Z"
      />,
    );

    const details = screen.getByRole("region", { name: "Item details" });

    expect(within(details).getByText("Levis")).toBeInTheDocument();
    expect(within(details).getByText("M")).toBeInTheDocument();
    expect(within(details).getByText("Excellent used condition")).toBeInTheDocument();
    expect(within(details).getByText("(EUC)")).toBeInTheDocument();
    expect(within(details).getByText("Blue, White")).toBeInTheDocument();
    expect(within(details).getByText("Tops")).toBeInTheDocument();
    expect(within(details).getByText("May 9, 2026")).toBeInTheDocument();
    expect(within(details).getByText("Chest Width")).toBeInTheDocument();
    expect(within(details).getByText("19 in")).toBeInTheDocument();
    expect(within(details).getByText("Length")).toBeInTheDocument();
    expect(within(details).getByText("27 in")).toBeInTheDocument();

    const itemId = within(details).getByTestId("item-id");
    expect(within(itemId).getByText("item-123...cdef")).toHaveAttribute(
      "title",
      "item-123456789abcdef",
    );
  });

  it("omits sparse or invalid fields without rendering empty labels", () => {
    render(
      <ProductDetailGrid
        id="item-2"
        brand={null}
        size=" "
        condition={null}
        conditionLabel={null}
        colors={["", "  "]}
        category={{ name: "" }}
        measurements={{
          waist: "",
          inseam: null,
        }}
        created_at="not-a-date"
      />,
    );

    const details = screen.getByRole("region", { name: "Item details" });

    expect(within(details).queryByText("Brand")).toBeNull();
    expect(within(details).queryByText("Size")).toBeNull();
    expect(within(details).queryByText("Condition")).toBeNull();
    expect(within(details).queryByText("Color")).toBeNull();
    expect(within(details).queryByText("Category")).toBeNull();
    expect(within(details).queryByText("Listed")).toBeNull();
    expect(within(details).queryByText("Measurements")).toBeNull();
    expect(within(details).getByText("item-2")).toBeInTheDocument();
  });

  it("renders nothing when no details are available", () => {
    const { container } = render(<ProductDetailGrid />);

    expect(container).toBeEmptyDOMElement();
  });
});
