import { describe, expect, it, test, vi, type Mock } from 'vitest';
import { userEvent } from 'vitest/browser';
import { act, screen, waitFor, getByText } from '@testing-library/react';
import { render } from 'vitest-browser-react';
import type { CSSProperties } from 'react';
import { useState } from '@wordpress/element';
import {
	computePopoverPosition,
	positionToPlacement,
	placementToMotionAnimationProps,
} from '../utils';
import Popover from '..';
import '../style.scss';
import { Provider as SlotFillProvider } from '../../slot-fill';
import type { PopoverProps } from '../types';
import { PopoverInsideIframeRenderedInExternalSlot } from './utils';

type PositionToPlacementTuple = [
	NonNullable< PopoverProps[ 'position' ] >,
	NonNullable< PopoverProps[ 'placement' ] >,
];

type PlacementToAnimationOriginTuple = [
	NonNullable< PopoverProps[ 'placement' ] >,
	number,
	number,
];

type PlacementToInitialTranslationTuple = [
	NonNullable< PopoverProps[ 'placement' ] >,
	'translateY' | 'translateX',
	CSSProperties[ 'translate' ],
];

// There's no matching `placement` for 'middle center' positions,
// fallback to 'bottom' (same as `floating-ui`'s default.)
const FALLBACK_FOR_MIDDLE_CENTER_POSITIONS = 'bottom';

const ALL_POSITIONS_TO_EXPECTED_PLACEMENTS: PositionToPlacementTuple[] = [
	// Format: [yAxis]
	[ 'middle', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'bottom', 'bottom' ],
	[ 'top', 'top' ],
	// Format: [yAxis] [xAxis]
	[ 'middle left', 'left' ],
	[ 'middle center', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'middle right', 'right' ],
	[ 'bottom left', 'bottom-end' ],
	[ 'bottom center', 'bottom' ],
	[ 'bottom right', 'bottom-start' ],
	[ 'top left', 'top-end' ],
	[ 'top center', 'top' ],
	[ 'top right', 'top-start' ],
	// Format: [yAxis] [xAxis] [corner]
	[ 'middle left left', 'left' ],
	[ 'middle left right', 'left' ],
	[ 'middle left bottom', 'left-end' ],
	[ 'middle left top', 'left-start' ],
	[ 'middle center left', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'middle center right', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'middle center bottom', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'middle center top', FALLBACK_FOR_MIDDLE_CENTER_POSITIONS ],
	[ 'middle right left', 'right' ],
	[ 'middle right right', 'right' ],
	[ 'middle right bottom', 'right-end' ],
	[ 'middle right top', 'right-start' ],
	[ 'bottom left left', 'bottom-end' ],
	[ 'bottom left right', 'bottom-end' ],
	[ 'bottom left bottom', 'bottom-end' ],
	[ 'bottom left top', 'bottom-end' ],
	[ 'bottom center left', 'bottom' ],
	[ 'bottom center right', 'bottom' ],
	[ 'bottom center bottom', 'bottom' ],
	[ 'bottom center top', 'bottom' ],
	[ 'bottom right left', 'bottom-start' ],
	[ 'bottom right right', 'bottom-start' ],
	[ 'bottom right bottom', 'bottom-start' ],
	[ 'bottom right top', 'bottom-start' ],
	[ 'top left left', 'top-end' ],
	[ 'top left right', 'top-end' ],
	[ 'top left bottom', 'top-end' ],
	[ 'top left top', 'top-end' ],
	[ 'top center left', 'top' ],
	[ 'top center right', 'top' ],
	[ 'top center bottom', 'top' ],
	[ 'top center top', 'top' ],
	[ 'top right left', 'top-start' ],
	[ 'top right right', 'top-start' ],
	[ 'top right bottom', 'top-start' ],
	[ 'top right top', 'top-start' ],
];

describe( 'Popover', () => {
	describe( 'Component', () => {
		describe( 'basic behavior', () => {
			it( 'should render content', async () => {
				await render( <Popover>Hello</Popover> );

				await waitFor( () =>
					expect( screen.getByText( 'Hello' ) ).toBeVisible()
				);
			} );

			it( 'should forward additional props to portaled element', async () => {
				await render( <Popover role="tooltip">Hello</Popover> );

				await waitFor( () =>
					expect( screen.getByRole( 'tooltip' ) ).toBeVisible()
				);
			} );

			it( 'should render inline regardless of slot name', async () => {
				const { container } = await render(
					<Popover inline __unstableSlotName="Popover">
						Hello
					</Popover>
				);

				await waitFor( () =>
					// We want to explicitly check if it's within the container.
					expect( getByText( container, 'Hello' ) ).toBeVisible()
				);
			} );
		} );

		describe( 'anchor', () => {
			it( 'should render correctly when anchor is provided', async () => {
				const PopoverWithAnchor = ( args: PopoverProps ) => {
					// Use internal state instead of a ref to make sure that the component
					// re-renders when the popover's anchor updates.
					const [ anchor, setAnchor ] =
						useState< HTMLParagraphElement | null >( null );

					return (
						<div>
							<p ref={ setAnchor }>Anchor</p>
							<Popover { ...args } anchor={ anchor } />
						</div>
					);
				};

				await render(
					<PopoverWithAnchor>Popover content</PopoverWithAnchor>
				);

				await waitFor( () =>
					expect(
						screen.getByText( 'Popover content' )
					).toBeVisible()
				);
			} );
		} );

		describe( 'offset', () => {
			it( 'should displace the popover along its cross axis when passed an offset object', async () => {
				await render(
					<>
						<Popover
							placement="right-start"
							offset={ { mainAxis: 0, crossAxis: 0 } }
							animate={ false }
							flip={ false }
							shift={ false }
							data-testid="baseline-popover"
						>
							Baseline
						</Popover>
						<Popover
							placement="right-start"
							offset={ { mainAxis: 16, crossAxis: 24 } }
							animate={ false }
							flip={ false }
							shift={ false }
							data-testid="offset-popover"
						>
							Offset
						</Popover>
					</>
				);
				const baseline = screen.getByTestId( 'baseline-popover' );
				const offset = screen.getByTestId( 'offset-popover' );

				await waitFor( () => {
					expect( baseline ).toBeVisible();
					expect( offset ).toBeVisible();
				} );

				const baselineRect = baseline.getBoundingClientRect();
				const offsetRect = offset.getBoundingClientRect();
				expect( offsetRect.left - baselineRect.left ).toBeCloseTo( 16 );
				expect( offsetRect.top - baselineRect.top ).toBeCloseTo( 24 );
			} );
		} );

		describe( 'style', () => {
			it( 'outputs inline styles added through the style prop in addition to built-in popover positioning styles', async () => {
				await render(
					<Popover
						style={ { zIndex: 0 } }
						data-testid="popover-element"
					>
						Hello
					</Popover>
				);
				const popover = screen.getByTestId( 'popover-element' );

				await waitFor( () => expect( popover ).toBeVisible() );
				const style = getComputedStyle( popover );
				expect( style.position ).toBe( 'absolute' );
				expect( style.top ).toBe( '0px' );
				expect( style.left ).toBe( '0px' );
				expect( style.zIndex ).toBe( '0' );
			} );

			it( 'is not possible to override built-in popover positioning styles via the style prop', async () => {
				await render(
					<Popover
						style={ { position: 'static' } }
						data-testid="popover-element"
					>
						Hello
					</Popover>
				);
				const popover = screen.getByTestId( 'popover-element' );

				await waitFor( () => expect( popover ).toBeVisible() );
				expect( getComputedStyle( popover ).position ).not.toBe(
					'static'
				);
			} );
		} );

		describe( 'focus behavior', () => {
			it( 'should focus the popover container when opened', async () => {
				await render(
					<Popover focusOnMount data-testid="popover-element">
						Popover content
					</Popover>
				);

				const popover = screen.getByTestId( 'popover-element' );

				await waitFor( () => expect( popover ).toBeVisible() );

				expect( popover ).toHaveFocus();
			} );

			it( 'should allow focus-on-open behavior to be disabled', async () => {
				await render(
					<Popover focusOnMount={ false }>Popover content</Popover>
				);

				await waitFor( () =>
					expect(
						screen.getByText( 'Popover content' )
					).toBeVisible()
				);

				expect( document.body ).toHaveFocus();
			} );
		} );

		describe( 'tab constraint behavior', () => {
			// `constrainTabbing` is implicitly controlled by `focusOnMount`.
			// By default, when `focusOnMount` is false, `constrainTabbing` will
			// also be false; otherwise, `constrainTabbing` will be true.

			const setup = async (
				props?: Partial< React.ComponentProps< typeof Popover > >
			) => {
				const user = userEvent.setup();
				function Test() {
					const [ isOpen, setIsOpen ] = useState( false );
					return (
						<>
							<button onClick={ () => setIsOpen( true ) }>
								Before popover
							</button>
							<Popover.Slot />
							{ isOpen && (
								<Popover
									data-testid="popover-element"
									{ ...props }
								>
									<button>Button 1</button>
									<button>Button 2</button>
									<button>Button 3</button>
								</Popover>
							) }
							<button>After popover</button>
						</>
					);
				}
				const view = await render(
					<SlotFillProvider>
						<Test />
					</SlotFillProvider>
				);
				const beforeButton = screen.getByRole( 'button', {
					name: 'Before popover',
				} );
				const afterButton = screen.getByRole( 'button', {
					name: 'After popover',
				} );
				await user.click( beforeButton );

				const popover = screen.getByTestId( 'popover-element' );
				await waitFor( () => expect( popover ).toBeVisible() );

				const firstButton = screen.getByRole( 'button', {
					name: 'Button 1',
				} );
				const secondButton = screen.getByRole( 'button', {
					name: 'Button 2',
				} );
				const thirdButton = screen.getByRole( 'button', {
					name: 'Button 3',
				} );

				return {
					...view,
					beforeButton,
					afterButton,
					popover,
					firstButton,
					secondButton,
					thirdButton,
					user,
				};
			};

			describe( 'constrains tabbing', () => {
				test( 'by default', async () => {
					// The default value for `focusOnMount` is 'firstElement',
					// which means the default value for `constrainTabbing` is
					// 'true'.

					const { user, firstButton, secondButton, thirdButton } =
						await setup();

					await waitFor( () => expect( firstButton ).toHaveFocus() );
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is true', async () => {
					const {
						user,
						popover,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( { focusOnMount: true } );

					expect( popover ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is "firstElement"', async () => {
					const { user, firstButton, secondButton, thirdButton } =
						await setup( { focusOnMount: 'firstElement' } );

					await waitFor( () => expect( firstButton ).toHaveFocus() );
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is false if `constrainTabbing` is true', async () => {
					const {
						user,
						beforeButton,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( {
						focusOnMount: false,
						constrainTabbing: true,
					} );

					expect( beforeButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
				} );
			} );

			describe( 'does not constrain tabbing', () => {
				test( 'when `constrainTabbing` is false', async () => {
					// The default value for `focusOnMount` is 'firstElement',
					// which means the default value for `constrainTabbing` is
					// 'true', but the provided value should override this.

					const {
						user,
						beforeButton,
						afterButton,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( { constrainTabbing: false } );

					await waitFor( () => expect( firstButton ).toHaveFocus() );
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( afterButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( secondButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( beforeButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is false', async () => {
					const {
						user,
						beforeButton,
						afterButton,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( { focusOnMount: false } );

					expect( beforeButton ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( afterButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( secondButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( beforeButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is true if `constrainTabbing` is false', async () => {
					const {
						user,
						beforeButton,
						afterButton,
						popover,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( {
						focusOnMount: true,
						constrainTabbing: false,
					} );

					expect( popover ).toHaveFocus();
					await user.tab();
					expect( firstButton ).toHaveFocus();
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( afterButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( secondButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( beforeButton ).toHaveFocus();
				} );

				test( 'when `focusOnMount` is "firstElement" if `constrainTabbing` is false', async () => {
					const {
						user,
						beforeButton,
						afterButton,
						firstButton,
						secondButton,
						thirdButton,
					} = await setup( {
						focusOnMount: 'firstElement',
						constrainTabbing: false,
					} );

					await waitFor( () => expect( firstButton ).toHaveFocus() );
					await user.tab();
					expect( secondButton ).toHaveFocus();
					await user.tab();
					expect( thirdButton ).toHaveFocus();
					await user.tab();
					expect( afterButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( thirdButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( secondButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( firstButton ).toHaveFocus();
					await user.tab( { shift: true } );
					expect( beforeButton ).toHaveFocus();
				} );
			} );
		} );
	} );

	describe( 'Slot outside iframe', () => {
		it( 'should support cross-document rendering', async () => {
			await render(
				<PopoverInsideIframeRenderedInExternalSlot>
					<span>content</span>
				</PopoverInsideIframeRenderedInExternalSlot>
			);
			await waitFor( async () =>
				expect( screen.getByText( 'content' ) ).toBeVisible()
			);
		} );
	} );

	describe( 'positionToPlacement', () => {
		it.each( ALL_POSITIONS_TO_EXPECTED_PLACEMENTS )(
			'converts `%s` to `%s`',
			( inputPosition, expectedPlacement ) => {
				expect( positionToPlacement( inputPosition ) ).toEqual(
					expectedPlacement
				);
			}
		);
	} );

	describe( 'placementToMotionAnimationProps', () => {
		describe( 'animation origin', () => {
			it.each( [
				[ 'top', 0.5, 1 ],
				[ 'top-start', 0, 1 ],
				[ 'top-end', 1, 1 ],
				[ 'right', 0, 0.5 ],
				[ 'right-start', 0, 0 ],
				[ 'right-end', 0, 1 ],
				[ 'bottom', 0.5, 0 ],
				[ 'bottom-start', 0, 0 ],
				[ 'bottom-end', 1, 0 ],
				[ 'left', 1, 0.5 ],
				[ 'left-start', 1, 0 ],
				[ 'left-end', 1, 1 ],
			] as PlacementToAnimationOriginTuple[] )(
				'for the `%s` placement computes an animation origin of (%d, %d)',
				( inputPlacement, expectedOriginX, expectedOriginY ) => {
					expect(
						placementToMotionAnimationProps( inputPlacement )
					).toEqual(
						expect.objectContaining( {
							style: expect.objectContaining( {
								originX: expectedOriginX,
								originY: expectedOriginY,
							} ),
						} )
					);
				}
			);
		} );
		describe( 'initial translation', () => {
			it.each( [
				[ 'top', 'translateY', '4px' ],
				[ 'top-start', 'translateY', '4px' ],
				[ 'top-end', 'translateY', '4px' ],
				[ 'right', 'translateX', '-4px' ],
				[ 'right-start', 'translateX', '-4px' ],
				[ 'right-end', 'translateX', '-4px' ],
				[ 'bottom', 'translateY', '-4px' ],
				[ 'bottom-start', 'translateY', '-4px' ],
				[ 'bottom-end', 'translateY', '-4px' ],
				[ 'left', 'translateX', '4px' ],
				[ 'left-start', 'translateX', '4px' ],
				[ 'left-end', 'translateX', '4px' ],
			] as PlacementToInitialTranslationTuple[] )(
				'for the `%s` placement computes an initial `%s` of `%s',
				(
					inputPlacement,
					expectedTranslationProp,
					expectedTranslationValue
				) => {
					expect(
						placementToMotionAnimationProps( inputPlacement )
					).toEqual(
						expect.objectContaining( {
							initial: expect.objectContaining( {
								[ expectedTranslationProp ]:
									expectedTranslationValue,
							} ),
						} )
					);
				}
			);
		} );
	} );

	describe( 'computePopoverPosition', () => {
		it.each( [
			[ 14, 14 ], // valid integers shouldn't be changes
			[ 14.02, 14 ], // floating numbers are parsed to integers
			[ 0, 0 ], // zero remains zero
			[ null, undefined ],
			[ NaN, undefined ],
		] )(
			'converts `%s` to `%s`',
			( inputCoordinate, expectedCoordinated ) => {
				expect( computePopoverPosition( inputCoordinate ) ).toEqual(
					expectedCoordinated
				);
			}
		);
	} );

	describe( 'closing all nested popovers', () => {
		// Test component that simulates the nested popover scenario:
		// A parent popover (like ColorGradient dropdown) containing a trigger
		// that opens a nested popover (like custom color picker dropdown)
		function NestedPopoverTestComponent( {
			onParentFocusOutside,
			onNestedFocusOutside,
		}: {
			onParentFocusOutside: Mock;
			onNestedFocusOutside: Mock;
		} ) {
			const [ isNestedOpen, setIsNestedOpen ] = useState( false );

			return (
				<>
					<button data-testid="external-button">
						External Button
					</button>
					<Popover
						data-testid="parent-popover"
						onFocusOutside={ onParentFocusOutside }
						focusOnMount={ false }
					>
						<button
							data-testid="parent-button"
							onClick={ () => setIsNestedOpen( ! isNestedOpen ) }
						>
							Open Nested
						</button>
						{ isNestedOpen && (
							<Popover
								data-testid="nested-popover"
								onFocusOutside={ onNestedFocusOutside }
								focusOnMount={ false }
							>
								<button data-testid="nested-dummy-button">
									Nested Dummy Button
								</button>
							</Popover>
						) }
					</Popover>
				</>
			);
		}

		it( 'should call parent onFocusOutside when focus moves from nested popover to external element', async () => {
			const user = userEvent.setup();
			const onParentFocusOutside = vi.fn();
			const onNestedFocusOutside = vi.fn();

			await render(
				<NestedPopoverTestComponent
					onParentFocusOutside={ onParentFocusOutside }
					onNestedFocusOutside={ onNestedFocusOutside }
				/>
			);

			await waitFor( () => {
				expect(
					screen.getByTestId( 'parent-popover' )
				).toBeInTheDocument();
			} );

			await user.click( screen.getByTestId( 'parent-button' ) );

			await waitFor( () => {
				expect(
					screen.getByTestId( 'nested-popover' )
				).toBeInTheDocument();
			} );

			await user.click( screen.getByTestId( 'nested-dummy-button' ) );

			await user.click( screen.getByTestId( 'external-button' ) );

			await waitFor( () => {
				expect( onNestedFocusOutside ).toHaveBeenCalledTimes( 1 );
			} );

			await waitFor( () => {
				expect( onParentFocusOutside ).toHaveBeenCalledTimes( 1 );
			} );
		} );
	} );

	describe( 'wp compat overlay slot', () => {
		function createOverlaySlot() {
			const slot = document.createElement( 'div' );
			slot.setAttribute( 'data-wp-compat-overlay-slot', '' );
			const slotButton = document.createElement( 'button' );
			slotButton.textContent = 'Slotted item';
			slot.appendChild( slotButton );
			document.body.appendChild( slot );
			return { slot, slotButton };
		}

		it( 'should not call onFocusOutside when focus moves into the wp compat overlay slot', async () => {
			const user = userEvent.setup();
			const onFocusOutside = vi.fn();
			const { slot, slotButton } = createOverlaySlot();

			await render(
				<Popover onFocusOutside={ onFocusOutside }>
					<button>Inside popover</button>
				</Popover>
			);

			await user.click( screen.getByText( 'Inside popover' ) );
			await user.click( slotButton );

			await new Promise( ( resolve ) => setTimeout( resolve, 50 ) );
			expect( onFocusOutside ).not.toHaveBeenCalled();

			document.body.removeChild( slot );
		} );

		it( 'should not call onFocusOutside when focus returns from the slot to a popover descendant', async () => {
			const user = userEvent.setup();
			const onFocusOutside = vi.fn();
			const { slot, slotButton } = createOverlaySlot();

			await render(
				<Popover onFocusOutside={ onFocusOutside }>
					<button>Inside popover</button>
				</Popover>
			);

			const insideButton = screen.getByText( 'Inside popover' );
			await user.click( insideButton );
			await user.click( slotButton );
			insideButton.focus();

			await new Promise( ( resolve ) => setTimeout( resolve, 50 ) );
			expect( onFocusOutside ).not.toHaveBeenCalled();

			document.body.removeChild( slot );
		} );

		it( 'should not call onFocusOutside when focus is restored to a popover descendant by the time the blur check runs', async () => {
			// Mimics the base-ui `Select` backdrop dismissal: focus drops
			// to `body` (so the captured `relatedTarget` is `null`), then
			// is synchronously restored to the popover before the blur
			// check runs.
			const onFocusOutside = vi.fn();
			const { slot, slotButton } = createOverlaySlot();

			await render(
				<Popover
					data-testid="popover"
					onFocusOutside={ onFocusOutside }
				>
					<button>Trigger</button>
				</Popover>
			);

			const trigger = screen.getByText( 'Trigger' );
			const floating = screen.getByTestId( 'popover' );

			await act( async () => {
				slotButton.focus();
				floating.dispatchEvent(
					new FocusEvent( 'blur', {
						bubbles: true,
						relatedTarget: null,
					} )
				);
				trigger.focus();
				await new Promise( ( resolve ) => setTimeout( resolve, 50 ) );
			} );

			expect( onFocusOutside ).not.toHaveBeenCalled();

			document.body.removeChild( slot );
		} );

		it( 'should still call onFocusOutside when focus moves to a sibling outside the slot', async () => {
			const user = userEvent.setup();
			const onFocusOutside = vi.fn();

			await render(
				<>
					<Popover onFocusOutside={ onFocusOutside }>
						<button>Inside popover</button>
					</Popover>
					<button>Outside</button>
				</>
			);

			await user.click( screen.getByText( 'Inside popover' ) );
			await user.click( screen.getByText( 'Outside' ) );

			await waitFor( () => {
				expect( onFocusOutside ).toHaveBeenCalledTimes( 1 );
			} );
		} );
	} );

	it( 'hints at transform only while it is being repositioned', async () => {
		await render(
			<Popover animate={ false } data-testid="popover-element">
				Inside popover
			</Popover>
		);

		const popover = screen.getByTestId( 'popover-element' );

		// Positioning has just run, so the compositing hint is on.
		expect( getComputedStyle( popover ).willChange ).toBe( 'transform' );

		// Once the popover settles, the hint is dropped so the popover stops
		// occupying a compositing layer of its own, which is what makes
		// Chrome render it blurry.
		await waitFor( () =>
			expect( getComputedStyle( popover ).willChange ).toBe( 'auto' )
		);
	} );

	it( 'hints at transform again when a settled popover moves, until it stops moving', async () => {
		const Test = ( { mainAxis }: { mainAxis: number } ) => (
			<Popover
				placement="right-start"
				offset={ { mainAxis, crossAxis: 0 } }
				animate={ false }
				flip={ false }
				shift={ false }
				data-testid="popover-element"
			>
				Inside popover
			</Popover>
		);
		const { rerender } = await render( <Test mainAxis={ 0 } /> );

		const popover = screen.getByTestId( 'popover-element' );
		await waitFor( () =>
			expect( getComputedStyle( popover ).willChange ).toBe( 'auto' )
		);

		vi.useFakeTimers( { toFake: [ 'setTimeout', 'clearTimeout' ] } );
		try {
			const moveTo = async ( mainAxis: number ) => {
				const { left } = popover.getBoundingClientRect();
				await rerender( <Test mainAxis={ mainAxis } /> );
				// `waitFor` stalls on the fake timers and `vi.waitFor` advances
				// them, so poll on real timers instead.
				await expect
					.poll( () => popover.getBoundingClientRect().left )
					.toBeCloseTo( left + 10 );
			};

			// Moving the settled popover brings the hint back.
			await moveTo( 10 );
			expect( getComputedStyle( popover ).willChange ).toBe(
				'transform'
			);

			// Moving again before the idle timeout keeps the hint on past the
			// first timeout.
			vi.advanceTimersByTime( 150 );
			await moveTo( 20 );
			vi.advanceTimersByTime( 150 );
			expect( getComputedStyle( popover ).willChange ).toBe(
				'transform'
			);

			// Once the popover stops moving, the hint is dropped.
			vi.advanceTimersByTime( 50 );
			expect( getComputedStyle( popover ).willChange ).toBe( 'auto' );
		} finally {
			vi.useRealTimers();
		}
	} );

	it( 'drops the transform hint when the popover moves into a slot without repositioning', async () => {
		const Test = ( { hasSlot }: { hasSlot: boolean } ) => (
			<SlotFillProvider>
				<Popover animate={ false } data-testid="popover-element">
					Inside popover
				</Popover>
				{ hasSlot && <Popover.Slot /> }
			</SlotFillProvider>
		);
		const { rerender } = await render( <Test hasSlot={ false } /> );

		const inlinePopover = screen.getByTestId( 'popover-element' );
		await waitFor( () =>
			expect( getComputedStyle( inlinePopover ).willChange ).toBe(
				'auto'
			)
		);

		// Mounting the slot swaps in a new floating element at the same
		// coordinates, and that one has to lose the hint too.
		await rerender( <Test hasSlot /> );

		const slottedPopover = screen.getByTestId( 'popover-element' );
		expect( slottedPopover ).not.toBe( inlinePopover );
		await waitFor( () =>
			expect( getComputedStyle( slottedPopover ).willChange ).toBe(
				'auto'
			)
		);
	} );

	it( 'should call a consumer-provided onKeyDown alongside close-on-Escape', async () => {
		const user = userEvent.setup();
		const onClose = vi.fn();
		const onKeyDown = vi.fn();

		await render(
			<Popover onClose={ onClose } onKeyDown={ onKeyDown }>
				<button>Inside popover</button>
			</Popover>
		);

		await user.click( screen.getByText( 'Inside popover' ) );
		await user.keyboard( '[Escape]' );

		expect( onKeyDown ).toHaveBeenCalled();
		expect( onKeyDown.mock.calls[ 0 ][ 0 ].key ).toBe( 'Escape' );
		expect( onClose ).toHaveBeenCalledTimes( 1 );
	} );
} );
