import { describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MantineProvider } from "@mantine/core";
import { CardForm } from "./CardForm";

function renderForm(overrides: Partial<Parameters<typeof CardForm>[0]> = {}) {
  const onSubmit = vi.fn();
  const onCancel = vi.fn();
  render(
    <MantineProvider>
      <CardForm
        requesterOptions={["Alice", "Anna", "Bob", "Enmanuel"]}
        onSubmit={onSubmit}
        onCancel={onCancel}
        {...overrides}
      />
    </MantineProvider>
  );
  return { onSubmit, onCancel };
}

describe("CardForm — requester input (issue 0088)", () => {
  it("solicitante entra vacio cuando initial.requester no se pasa", () => {
    renderForm();
    const requesterInput = (document.querySelector('input[data-field="requester"]') as HTMLInputElement) as HTMLInputElement;
    expect(requesterInput.value).toBe("");
  });

  it("Enter dentro del requester NO dispara onSubmit (dropdown cerrado o abierto)", async () => {
    const user = userEvent.setup();
    const { onSubmit } = renderForm();

    // Necesita un titulo valido para que un eventual submit no se ignore por el guard.
    const title = screen.getByLabelText(/Tarea/i);
    await user.type(title, "Mi tarea");

    const requester = (document.querySelector('input[data-field="requester"]') as HTMLInputElement);
    await user.click(requester);
    await user.keyboard("{Enter}");
    expect(onSubmit).not.toHaveBeenCalled();

    await user.type(requester, "An");
    await user.keyboard("{Enter}");
    expect(onSubmit).not.toHaveBeenCalled();
  });

  // Navegacion ArrowDown + Enter del dropdown la maneja Mantine internamente.
  // Validar eso en jsdom es fragil (portals + virtual focus). Cubierto en e2e
  // Playwright donde corre browser real.

  it("submit solo via boton Crear", async () => {
    const user = userEvent.setup();
    const { onSubmit } = renderForm({ submitLabel: "Crear" });

    const title = screen.getByLabelText(/Tarea/i);
    await user.type(title, "Mi tarea");
    const requester = (document.querySelector('input[data-field="requester"]') as HTMLInputElement);
    await user.type(requester, "Anna");

    await user.click(screen.getByRole("button", { name: /Crear/i }));

    await waitFor(() => {
      expect(onSubmit).toHaveBeenCalledTimes(1);
    });
    expect(onSubmit.mock.calls[0][0]).toMatchObject({
      title: "Mi tarea",
      requester: "Anna",
    });
  });
});
