import React from 'react';
import { render } from '@testing-library/react';
import { PageContext } from '../..';
import { Modal } from '../index';

// Guards the flaky `ReferenceError: document is not defined` from react-modal's
// deferred removePortal firing after jsdom teardown. Forces the race to always
// lose (delete `document`, wait past the old 150ms) and asserts nothing threw.
describe('Modal close-timeout teardown safety', () => {
    test('does not defer a portal removal that touches document after teardown', async () => {
        const errors: unknown[] = [];
        const onUncaught = (err: unknown) => errors.push(err);
        process.on('uncaughtException', onUncaught);
        const realDocument = globalThis.document;

        try {
            const { unmount } = render(
                <Modal isOpen onRequestClose={() => undefined} header="repro">
                    body
                </Modal>,
                {
                    wrapper: ({ children }) => (
                        <div className="TestPage PageContainer">
                            <PageContext.Provider value={{ className: 'TestPage' }}>
                                {children}
                            </PageContext.Provider>
                        </div>
                    ),
                }
            );

            unmount();

            // Mimic vitest tearing down the jsdom environment before any deferred
            // removePortal timer can fire.
            // @ts-expect-error intentionally removing document to mimic env teardown
            delete globalThis.document;

            await new Promise((resolve) => setTimeout(resolve, 300));

            expect(errors).toEqual([]);
        } finally {
            // Restore so testing-library cleanup (afterEach) still works, even if
            // the assertion above throws.
            globalThis.document = realDocument;
            process.off('uncaughtException', onUncaught);
        }
    });
});
