// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import PhoneInput from "./PhoneInput";

function hidden(name: string) {
  return document.querySelector(
    `input[type="hidden"][name="${name}"]`
  ) as HTMLInputElement;
}

describe("PhoneInput", () => {
  it("defaults to India (+91) with empty E.164 value", () => {
    render(<PhoneInput id="t-phone" />);
    expect(hidden("phone").value).toBe("");
    expect(hidden("phoneCountry").value).toBe("IN");
    expect(screen.getByRole("button", { name: /country code/i })).toHaveTextContent("+91");
  });

  it("accepts digits only and posts E.164", async () => {
    const user = userEvent.setup();
    render(<PhoneInput id="t-phone" />);
    const input = screen.getByLabelText(/phone/i);
    await user.type(input, "98a189b93537!!!");
    expect((input as HTMLInputElement).value).toBe("9818993537");
    expect(hidden("phone").value).toBe("+919818993537");
  });

  it("caps entry at the country's max length", async () => {
    const user = userEvent.setup();
    render(<PhoneInput id="t-phone" />);
    const input = screen.getByLabelText(/phone/i);
    await user.type(input, "98189935379999");
    expect((input as HTMLInputElement).value).toHaveLength(10);
  });

  it("switches country via search and resets digits", async () => {
    const user = userEvent.setup();
    render(<PhoneInput id="t-phone" />);
    const input = screen.getByLabelText(/phone/i);
    await user.type(input, "9818993537");
    expect(hidden("phone").value).toBe("+919818993537");

    await user.click(screen.getByRole("button", { name: /country code/i }));
    await user.type(screen.getByLabelText(/search countries/i), "971");
    const list = screen.getByRole("listbox");
    await user.click(
      within(list).getByRole("button", { name: /united arab emirates/i })
    );

    expect(hidden("phoneCountry").value).toBe("AE");
    expect((input as HTMLInputElement).value).toBe("");
    expect(hidden("phone").value).toBe("");
  });
});
