/**
 * Regression: DraftProvider with both Đơn and Đóng góp mounted (like the applicant dashboard tabs)
 * must not hit React maximum update depth, and debounced persist callbacks should not storm.
 */
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import InitiativeApplicationForm from '@/components/InitiativeApplicationForm';
import ContributionConfirmationForm from '@/components/ContributionConfirmationForm';
import { DraftProvider } from '@/components/applicant/initiative-draft/DraftContext';
import { LS_KEY } from '@/components/applicant/initiative-draft/types';

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)),
  );
}

describe('DraftProvider + dual applicant forms (dashboard-style)', () => {
  beforeEach(() => {
    localStorage.removeItem(LS_KEY);
  });

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

  it('keyboard input with autosave mocks does not cause max-depth or excessive persist calls', async () => {
    const user = userEvent.setup({ delay: 3 });
    const errorSpy = vi.spyOn(console, 'error');

    const persistApp = vi.fn(async () => {});
    const persistContribution = vi.fn(async () => {});

    render(
      <DraftProvider preferLocalSnapshot={false}>
        <InitiativeApplicationForm
          readOnly={false}
          autoSaveDebounceMs={350}
          onSaveDraft={persistApp}
        />
        <ContributionConfirmationForm
          readOnly={false}
          autoSaveDebounceMs={350}
          onSaveDraft={persistContribution}
        />
      </DraftProvider>,
    );

    const nameFields = screen.getAllByPlaceholderText('Nhập tên sáng kiến...');
    const nameInput = nameFields.find((el) => el.tagName === 'INPUT') ?? nameFields[0];
    const summary = document.querySelector('textarea.min-h-32');
    expect(summary).not.toBeNull();

    await user.type(nameInput, 'Đồng bộ ');
    await user.type(summary!, 'Mục 4 ');

    await waitFor(
      () => {
        expect(persistApp.mock.calls.length + persistContribution.mock.calls.length).toBeGreaterThan(0);
      },
      { timeout: 5000 },
    );

    expect(persistApp.mock.calls.length).toBeLessThan(40);
    expect(persistContribution.mock.calls.length).toBeLessThan(40);
    expect(errorSpy.mock.calls.some(isReactDepthPanic)).toBe(false);
  });
});
