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

import { Field, FieldControl, FieldDescription, FieldError } from "./field";
import { InputGroup, InputGroupPrefix, InputGroupSuffix } from "./input-group";
import { Input } from "./input";
import { Label } from "./label";

describe("InputGroup", () => {
  it("renders affix slots and propagates grouped state to the input", () => {
    render(
      <InputGroup disabled invalid readOnly required size="lg">
        <InputGroupPrefix>
          <span aria-hidden="true">#</span>
        </InputGroupPrefix>
        <Input aria-label="Search launches" />
        <InputGroupSuffix>
          <span>⌘K</span>
        </InputGroupSuffix>
      </InputGroup>
    );

    const input = screen.getByRole("textbox", { name: "Search launches" });
    const control = input.closest('[data-slot="control"]');

    expect(control).toHaveAttribute("data-slot", "control");
    expect(control).toHaveAttribute("data-disabled", "");
    expect(control).toHaveAttribute("data-invalid", "");
    expect(control).toHaveAttribute("data-readonly", "");
    expect(control).toHaveAttribute("data-required", "");
    expect(control).toHaveAttribute("data-size", "lg");
    expect(input).toHaveAttribute("data-slot", "input");
    expect(input).toHaveAttribute("data-size", "lg");
    expect(input).toBeDisabled();
    expect(input).toHaveAttribute("aria-invalid", "true");
    expect(input).toHaveAttribute("readonly");
    expect(input).toBeRequired();
    expect(screen.getByText("#").closest('[data-slot="prefix"]')).toBeInTheDocument();
    expect(screen.getByText("⌘K").closest('[data-slot="suffix"]')).toBeInTheDocument();
  });

  it("keeps field ids and described-by wiring when grouped inside a field control", () => {
    render(
      <Field invalid required>
        <Label requiredIndicator>Lane search</Label>
        <FieldControl>
          <InputGroup>
            <InputGroupPrefix aria-hidden="true">
              <span>#</span>
            </InputGroupPrefix>
            <Input />
          </InputGroup>
          <FieldDescription>Find the right routing lane before queuing.</FieldDescription>
          <FieldError>Search query is required.</FieldError>
        </FieldControl>
      </Field>
    );

    const input = screen.getByRole("textbox", { name: "Lane search" });
    const description = screen.getByText("Find the right routing lane before queuing.");
    const error = screen.getByText("Search query is required.");

    expect(input).toHaveAttribute("aria-describedby", `${description.id} ${error.id}`);
    expect(input).toHaveAttribute("aria-invalid", "true");
    expect(input).toBeRequired();
    expect(input.closest('[data-slot="control"]')).toHaveAttribute("data-invalid", "");
  });
});
