import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { PasswordField } from "./PasswordField";

describe("PasswordField", () => {
  it("should render without errors", () => {
    const { container } = render(<PasswordField label="Password" />);
    expect(container).toBeInTheDocument();
  });

  it("should hide the password by default", () => {
    render(<PasswordField label="Password" data-testid="password-field" />);
    expect(screen.getByTestId("password-field")).toHaveAttribute(
      "type",
      "password",
    );
  });

  it("should show the password on request", async () => {
    render(<PasswordField label="Password" data-testid="password-field" />);
    await userEvent.click(screen.getByTestId("show-hide-button"));
    expect(screen.getByTestId("password-field")).toHaveAttribute(
      "type",
      "text",
    );
  });

  it("preserves cursor position when toggling visibility", async () => {
    render(<PasswordField label="Password" />);
    const input = screen.getByLabelText<HTMLInputElement>("Password");
    const toggleButton = screen.getByRole("button", { name: /show/i });

    // Type text and position cursor
    await userEvent.type(input, "password123");
    input.setSelectionRange(4, 4); // cursor after "pass"

    // Toggle visibility
    await userEvent.click(toggleButton);

    // Verify cursor position preserved
    await waitFor(() => {
      expect(input.selectionStart).toBe(4);
    });
    await waitFor(() => {
      expect(input.selectionEnd).toBe(4);
    });
  });

  it("should return focus to input after pressing show/hide", async () => {
    render(<PasswordField label="Password" data-testid="password-field" />);
    await userEvent.tab();
    expect(screen.getByTestId("password-field")).toHaveFocus();

    // Press Show button with keyboard
    await userEvent.tab();
    await userEvent.keyboard("{enter}");

    await waitFor(() => {
      expect(screen.getByTestId("password-field")).toHaveFocus();
    });
  });

  describe("autocomplete", () => {
    it('defaults autoComplete to "current-password"', () => {
      render(<PasswordField label="Password" data-testid="password-field" />);
      expect(screen.getByTestId("password-field")).toHaveAttribute(
        "autocomplete",
        "current-password",
      );
    });

    it("allows autoComplete to be overridden", () => {
      render(
        <PasswordField
          label="Password"
          autoComplete="new-password"
          data-testid="password-field"
        />,
      );
      expect(screen.getByTestId("password-field")).toHaveAttribute(
        "autocomplete",
        "new-password",
      );
    });
  });
});
