/**
 * Component-level E2E: real DraftProvider + per-keystroke `updateApplication` must not trigger
 * React "Maximum update depth" or other console.error spam (regression guard for autosave/sync effects).
 *
 * Paste and one-shot fills differ because they apply fewer intermediate draft snapshots than typing.
 */
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import InitiativeApplicationForm from "@/components/InitiativeApplicationForm";
import { DraftProvider } from "@/components/applicant/initiative-draft/DraftContext";
import { LS_KEY } from "@/components/applicant/initiative-draft/types";

describe("InitiativeApplicationForm + DraftProvider (typing hygiene)", () => {
  beforeEach(() => {
    localStorage.removeItem(LS_KEY);
  });

  afterEach(() => {
    vi.restoreAllMocks();
    localStorage.removeItem(LS_KEY);
  });

  it("keyboard typing into section-4 textarea and initiative name yields no Maximum update depth / error spam", async () => {
    const user = userEvent.setup({ delay: 4 });
    const errorSpy = vi.spyOn(console, "error");

    render(
      <DraftProvider preferLocalSnapshot={false}>
        <InitiativeApplicationForm readOnly={false} autoSaveDebounceMs={undefined} />
      </DraftProvider>,
    );

    const nameInput = screen.getByPlaceholderText("Nhập tên sáng kiến...");
    const summary = document.querySelector("textarea.min-h-32");
    expect(summary).not.toBeNull();

    await user.type(nameInput, "Đánh máy ");
    await user.type(summary!, "Mô tả từng ký tự ");

    function isReactDepthPanic(args: unknown[]) {
      return args.some(
        (a) =>
          typeof a === "string" &&
          (/Maximum update depth exceeded/i.test(a) || /Too many re-renders/i.test(a)),
      );
    }

    expect(errorSpy.mock.calls.some(isReactDepthPanic)).toBe(false);
  });
});
