import {
	afterEach,
	beforeEach,
	describe,
	expect,
	it,
	vi,
	type Mock,
} from 'vitest';
import { useState } from '@wordpress/element';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ToolsPanel, ToolsPanelContext, ToolsPanelItem } from '../';
import { createSlotFill, Provider as SlotFillProvider } from '../../slot-fill';
import type {
	ToolsPanelContext as ToolsPanelContextType,
	ResetAllFilter,
} from '../types';

globalThis.wpVitest.mockMatchMedia();

const { Fill: ToolsPanelItems, Slot } = createSlotFill( 'ToolsPanelSlot' );
const resetAll = vi.fn();
const noop = () => undefined;

type ControlValue = boolean | undefined;

// Default props for the tools panel.
const defaultProps = {
	label: 'Panel header',
	resetAll,
};

// Default props for an enabled control to be rendered within panel.
let controlValue: ControlValue = true;
const controlProps = {
	hasValue: vi.fn().mockImplementation( () => {
		return !! controlValue;
	} ),
	label: 'Example',
	onDeselect: vi.fn().mockImplementation( () => {
		controlValue = undefined;
	} ),
	onSelect: vi.fn(),
	onShownChange: vi.fn(),
};

// Default props without a value for an alternate control to be rendered within
// the panel.
let altControlValue: ControlValue = false;
const altControlProps = {
	hasValue: vi.fn().mockImplementation( () => {
		return !! altControlValue;
	} ),
	label: 'Alt',
	onDeselect: vi.fn(),
	onSelect: vi.fn(),
	onShownChange: vi.fn(),
};

// Default props for wrapped or grouped panel items.
let nestedControlValue: ControlValue = true;
const nestedControlProps = {
	hasValue: vi.fn().mockImplementation( () => {
		return !! nestedControlValue;
	} ),
	label: 'Nested Control 1',
	onDeselect: vi.fn().mockImplementation( () => {
		nestedControlValue = undefined;
	} ),
	onSelect: vi.fn(),
	isShownByDefault: true,
};

// Alternative props for wrapped or grouped panel items.
const altNestedControlValue: ControlValue = false;
const altNestedControlProps = {
	hasValue: vi.fn().mockImplementation( () => {
		return !! altNestedControlValue;
	} ),
	label: 'Nested Control 2',
	onDeselect: vi.fn(),
	onSelect: vi.fn(),
};

// Simple custom component grouping panel items. Used to test panel item
// registration and display when not an immediate child of `ToolsPanel`.
const GroupedItems = ( {
	defaultGroupedProps = nestedControlProps,
	altGroupedProps = altNestedControlProps,
} ) => {
	return (
		<>
			<ToolsPanelItem { ...defaultGroupedProps }>
				<div>Grouped control</div>
			</ToolsPanelItem>
			<ToolsPanelItem { ...altGroupedProps }>
				<div>Alt grouped control</div>
			</ToolsPanelItem>
		</>
	);
};

// This context object is used to help simulate different scenarios in which
// `ToolsPanelItem` registration or deregistration requires testing.
const panelContext: ToolsPanelContextType = {
	panelId: '1234',
	menuItems: {
		default: {},
		optional: { [ altControlProps.label ]: true },
	},
	hasMenuItems: false,
	isResetting: false,
	shouldRenderPlaceholderItems: false,
	registerPanelItem: vi.fn(),
	deregisterPanelItem: vi.fn(),
	registerResetAllFilter: vi.fn(),
	deregisterResetAllFilter: vi.fn(),
	flagItemCustomization: noop,
	areAllOptionalControlsHidden: true,
};

// Renders a tools panel including panel items that have been grouped within
// a custom component.
const renderGroupedItemsInPanel = () => {
	return render(
		<ToolsPanel { ...defaultProps }>
			<GroupedItems />
		</ToolsPanel>
	);
};

// Custom component rendering a panel item within a wrapping element. Also used
// to test panel item registration and rendering.
const WrappedItem = ( {
	text,
	...props
}: React.ComponentProps< typeof ToolsPanelItem > & { text: string } ) => {
	return (
		<div>
			<span>Wrapper</span>
			<ToolsPanelItem { ...props }>
				<div>{ text }</div>
			</ToolsPanelItem>
		</div>
	);
};

// Renders a `ToolsPanel` with single wrapped panel item via a custom component.
const renderWrappedItemInPanel = () => {
	return render(
		<ToolsPanel { ...defaultProps }>
			<WrappedItem { ...nestedControlProps } text="Wrapped 1" />
			<WrappedItem { ...altNestedControlProps } text="Wrapped 2" />
		</ToolsPanel>
	);
};

// Renders a default tools panel including children that are
// not to be represented within the panel's menu.
const renderPanel = () => {
	return render(
		<ToolsPanel { ...defaultProps }>
			<ToolsPanelItem { ...controlProps }>
				<div>Example control</div>
			</ToolsPanelItem>
			<ToolsPanelItem { ...altControlProps }>
				<div>Alt control</div>
			</ToolsPanelItem>
			<span>Visible</span>
		</ToolsPanel>
	);
};

/**
 * Retrieves the panel's dropdown menu toggle button.
 *
 * @return {HTMLElement} The menu button.
 */
const getMenuButton = () => {
	return screen.getByRole( 'button', {
		name: /Panel([\w\s]+)header([\w\s]+)options/i,
	} );
};

/**
 * Helper to find the menu button and simulate a user click.
 *
 */
const openDropdownMenu = async () => {
	const user = userEvent.setup();
	const menuButton = getMenuButton();
	await user.click( menuButton );
	return menuButton;
};

// Opens dropdown then selects the menu item by label before simulating a click.
const selectMenuItem = async ( label: string ) => {
	const user = userEvent.setup();
	const menuItem = await screen.findByText( label );
	await user.click( menuItem );
};

describe( 'ToolsPanel', () => {
	beforeEach( () => {
		controlProps.hasValue.mockImplementation( () => !! controlValue );
		controlProps.onDeselect.mockImplementation( () => {
			controlValue = undefined;
		} );
		altControlProps.hasValue.mockImplementation( () => !! altControlValue );
		nestedControlProps.hasValue.mockImplementation(
			() => !! nestedControlValue
		);
		nestedControlProps.onDeselect.mockImplementation( () => {
			nestedControlValue = undefined;
		} );
		altNestedControlProps.hasValue.mockImplementation(
			() => !! altNestedControlValue
		);
	} );

	afterEach( () => {
		controlValue = true;
		altControlValue = false;
		nestedControlValue = true;
	} );

	describe( 'basic rendering', () => {
		it( 'should render panel', () => {
			renderPanel();

			const menuButton = getMenuButton();
			const label = screen.getByText( defaultProps.label );
			const control = screen.getByText( 'Example control' );
			const nonToolsPanelItem = screen.getByText( 'Visible' );

			expect( menuButton ).toBeInTheDocument();
			expect( label ).toBeInTheDocument();
			expect( control ).toBeInTheDocument();
			expect( nonToolsPanelItem ).toBeInTheDocument();
		} );

		it( 'should render panel item flagged as default control even without value', () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...controlProps }>
						<div>Example control</div>
					</ToolsPanelItem>
					<ToolsPanelItem { ...altControlProps } isShownByDefault>
						<div>Alt control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const altControl = screen.getByText( 'Alt control' );

			expect( altControl ).toBeInTheDocument();
		} );

		it( 'should not render panel menu when there are no panel items', () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<span>Visible but insignificant</span>
				</ToolsPanel>
			);

			const menu = screen.queryByLabelText( defaultProps.label );
			expect( menu ).not.toBeInTheDocument();
		} );

		it( 'should render panel menu when at least one panel item', async () => {
			renderPanel();

			const menuButton = await openDropdownMenu();
			expect( menuButton ).toBeInTheDocument();
		} );

		it( 'should render reset all item in menu', async () => {
			renderPanel();
			await openDropdownMenu();

			const resetAllItem = await screen.findByRole( 'menuitem' );

			expect( resetAllItem ).toBeInTheDocument();
		} );

		it( 'should render panel menu items correctly', async () => {
			renderPanel();
			await openDropdownMenu();

			const menuItems = await screen.findAllByRole( 'menuitemcheckbox' );

			expect( menuItems.length ).toEqual( 2 );
			expect( menuItems[ 0 ] ).toBeChecked();
			expect( menuItems[ 1 ] ).not.toBeChecked();
		} );

		it( 'should render panel label as header text', () => {
			renderPanel();
			const header = screen.getByText( defaultProps.label );

			expect( header ).toBeInTheDocument();
		} );

		it( 'should apply public class names to the panel and its items', () => {
			render(
				<ToolsPanel { ...defaultProps } data-testid="tools-panel">
					<ToolsPanelItem
						{ ...controlProps }
						className="custom-item"
						data-testid="tools-panel-item"
					>
						<div>Example control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			expect( screen.getByTestId( 'tools-panel' ) ).toHaveClass(
				'components-tools-panel'
			);
			expect( screen.getByTestId( 'tools-panel-item' ) ).toHaveClass(
				'components-tools-panel-item',
				'custom-item'
			);

			const heading = screen.getByRole( 'heading', {
				name: defaultProps.label,
			} );

			// Disable reason: Semantic queries can't reach the header wrapper.
			// eslint-disable-next-line testing-library/no-node-access
			expect( heading.parentElement ).toHaveClass(
				'components-tools-panel-header'
			);
		} );
	} );

	describe( 'conditional rendering of panel items', () => {
		it( 'should render panel item when it has a value', () => {
			renderPanel();

			const exampleControl = screen.getByText( 'Example control' );
			const altControl = screen.queryByText( 'Alt control' );

			expect( exampleControl ).toBeInTheDocument();
			expect( altControl ).not.toBeInTheDocument();
		} );

		it( 'shows a hidden optional control with the setting followed by the action', async () => {
			renderPanel();
			await openDropdownMenu();
			const menuItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Alt, show',
				checked: false,
			} );
			expect( menuItem ).toHaveTextContent( 'Alt' );
			await selectMenuItem( altControlProps.label );
			const control = await screen.findByText( 'Alt control' );
			expect( menuItem ).toHaveAccessibleName( 'Alt, hide and reset' );
			expect( menuItem ).toBeChecked();

			expect( control ).toBeInTheDocument();

			// Test the aria live announcement.
			const announcement = screen.getByText( 'Alt is now visible' );
			expect( announcement ).toHaveAttribute( 'aria-live', 'assertive' );
		} );

		it( 'hides and resets an optional control with the setting followed by the action', async () => {
			renderPanel();
			await openDropdownMenu();
			const menuItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Example, hide and reset',
				checked: true,
			} );
			expect( menuItem ).toHaveTextContent( 'Example' );
			await selectMenuItem( controlProps.label );
			const control = screen.queryByText( 'Example control' );
			expect( menuItem ).toHaveAccessibleName( 'Example, show' );
			expect( menuItem ).not.toBeChecked();
			expect( controlProps.onDeselect ).toHaveBeenCalledTimes( 1 );

			expect( control ).not.toBeInTheDocument();

			// Test the aria live announcement.
			const announcement = screen.getByText(
				'Example hidden and reset to default'
			);
			expect( announcement ).toHaveAttribute( 'aria-live', 'assertive' );
		} );

		it( 'should render optional panel item when value is updated externally and panel has an ID', async () => {
			const ToolsPanelOptional = ( {
				toolsPanelItemValue,
			}: {
				toolsPanelItemValue?: number;
			} ) => {
				const itemProps = {
					attributes: { value: toolsPanelItemValue },
					hasValue: () => !! toolsPanelItemValue,
					label: 'Alt',
					onDeselect: vi.fn(),
					onSelect: vi.fn(),
				};

				return (
					<ToolsPanel { ...defaultProps }>
						<ToolsPanelItem { ...itemProps }>
							<div>Optional control</div>
						</ToolsPanelItem>
					</ToolsPanel>
				);
			};
			const { rerender } = render( <ToolsPanelOptional /> );

			const control = screen.queryByText( 'Optional control' );

			expect( control ).not.toBeInTheDocument();

			rerender( <ToolsPanelOptional toolsPanelItemValue={ 100 } /> );

			const controlRerendered = screen.getByText( 'Optional control' );

			expect( controlRerendered ).toBeInTheDocument();
		} );

		it( 'should render optional item when value is updated externally and panelId is null', async () => {
			// This test partially covers: https://github.com/WordPress/gutenberg/issues/47368
			const ToolsPanelOptional = ( {
				toolsPanelItemValue,
			}: {
				toolsPanelItemValue?: number;
			} ) => {
				const itemProps = {
					attributes: { value: toolsPanelItemValue },
					hasValue: () => !! toolsPanelItemValue,
					label: 'Alt',
					onDeselect: vi.fn(),
					onSelect: vi.fn(),
				};

				// The null panelId below simulates the panel prop when there
				// are multiple blocks selected.
				return (
					<ToolsPanel { ...defaultProps } panelId={ null }>
						<ToolsPanelItem { ...itemProps }>
							<div>Optional control</div>
						</ToolsPanelItem>
					</ToolsPanel>
				);
			};

			const { rerender } = render( <ToolsPanelOptional /> );
			const control = screen.queryByText( 'Optional control' );

			expect( control ).not.toBeInTheDocument();

			rerender( <ToolsPanelOptional toolsPanelItemValue={ 99 } /> );

			const controlRerendered = screen.getByText( 'Optional control' );

			expect( controlRerendered ).toBeInTheDocument();
		} );

		it( 'should not render optional item without a value by default', () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps }>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			expect(
				screen.queryByText( 'Optional control' )
			).not.toBeInTheDocument();
		} );

		it( 'should render optional item on first render when defaultShown is true', () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps } defaultShown>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			expect(
				screen.getByText( 'Optional control' )
			).toBeInTheDocument();
		} );

		it( 'should render optional item with a value even when defaultShown is false', () => {
			altControlValue = true;

			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem
						{ ...altControlProps }
						defaultShown={ false }
					>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			expect(
				screen.getByText( 'Optional control' )
			).toBeInTheDocument();
		} );

		// `defaultShown` only seeds the item's initial visibility. A change
		// after mount must leave the item as it is, and must not be reported
		// as though the user had used the menu.
		describe( 'changing defaultShown after mount', () => {
			const onDeselect = vi.fn();
			const onSelect = vi.fn();
			const onShownChange = vi.fn();

			const ToolsPanelOptional = ( {
				defaultShown,
			}: {
				defaultShown: boolean;
			} ) => (
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem
						defaultShown={ defaultShown }
						hasValue={ () => false }
						label="Alt"
						onDeselect={ onDeselect }
						onSelect={ onSelect }
						onShownChange={ onShownChange }
					>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			beforeEach( () => {
				vi.clearAllMocks();
			} );

			it( 'should keep a hidden item hidden when it changes to true', () => {
				const { rerender } = render(
					<ToolsPanelOptional defaultShown={ false } />
				);

				rerender( <ToolsPanelOptional defaultShown /> );

				expect(
					screen.queryByText( 'Optional control' )
				).not.toBeInTheDocument();
				expect( onShownChange ).not.toHaveBeenCalled();
				expect( onSelect ).not.toHaveBeenCalled();
				expect( onDeselect ).not.toHaveBeenCalled();
			} );

			it( 'should keep a shown item visible when it changes to false', () => {
				const { rerender } = render(
					<ToolsPanelOptional defaultShown />
				);

				rerender( <ToolsPanelOptional defaultShown={ false } /> );

				expect(
					screen.getByText( 'Optional control' )
				).toBeInTheDocument();
				expect( onShownChange ).not.toHaveBeenCalled();
				expect( onSelect ).not.toHaveBeenCalled();
				expect( onDeselect ).not.toHaveBeenCalled();
			} );
		} );

		it( 'should keep an item the user hid hidden when another item registers', async () => {
			// Registering an item regenerates the panel's menu state. An item
			// the user hid is stored as `false`, which must be preserved
			// rather than treated as unregistered and reseeded from
			// `defaultShown`.
			const TestPanel = ( { showExtra }: { showExtra: boolean } ) => (
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps } defaultShown>
						<div>Optional control</div>
					</ToolsPanelItem>
					{ showExtra && (
						<ToolsPanelItem
							hasValue={ () => false }
							label="Extra"
							onDeselect={ noop }
							onSelect={ noop }
						>
							<div>Extra control</div>
						</ToolsPanelItem>
					) }
				</ToolsPanel>
			);

			const { rerender } = render( <TestPanel showExtra={ false } /> );
			expect(
				screen.getByText( 'Optional control' )
			).toBeInTheDocument();

			await openDropdownMenu();
			await selectMenuItem( altControlProps.label );
			expect(
				screen.queryByText( 'Optional control' )
			).not.toBeInTheDocument();

			rerender( <TestPanel showExtra /> );

			expect(
				screen.queryByText( 'Optional control' )
			).not.toBeInTheDocument();
		} );

		it( 'resets a default control with a name explaining the visible reset action', async () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...controlProps } isShownByDefault>
						<div>Default control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const control = screen.getByText( 'Default control' );

			expect( control ).toBeInTheDocument();

			await openDropdownMenu();
			const menuItem = screen.getByRole( 'menuitem', {
				name: 'Example, reset to default',
			} );
			const resetSuffix = within( menuItem ).getByText( 'Reset' );
			expect( resetSuffix ).toBeVisible();
			expect( resetSuffix ).toHaveAttribute( 'aria-hidden', 'true' );
			await selectMenuItem( controlProps.label );
			const resetControl = screen.getByText( 'Default control' );
			const disabledItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Example',
				checked: true,
			} );
			expect( disabledItem ).toHaveAttribute( 'aria-disabled', 'true' );
			controlProps.onDeselect.mockClear();
			await selectMenuItem( controlProps.label );
			expect( controlProps.onDeselect ).not.toHaveBeenCalled();

			expect( resetControl ).toBeInTheDocument();

			// Test the aria live announcement.
			const announcement = screen.getByText( 'Example reset to default' );
			expect( announcement ).toHaveAttribute( 'aria-live', 'assertive' );
		} );

		it( 'should render appropriate menu groups', async () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...controlProps } isShownByDefault>
						<div>Default control</div>
					</ToolsPanelItem>
					<ToolsPanelItem { ...altControlProps }>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);
			await openDropdownMenu();

			const menuGroups = screen.getAllByRole( 'group' );

			// There are now only two groups controls & reset all.
			expect( menuGroups.length ).toEqual( 2 );
		} );

		it( 'should not render contents of items when in placeholder state', () => {
			render(
				<ToolsPanel { ...defaultProps } shouldRenderPlaceholderItems>
					<ToolsPanelItem
						{ ...altControlProps }
						className="custom-item"
						data-testid="placeholder-item"
					>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const optionalItem = screen.queryByText( 'Optional control' );
			const placeholderItem = screen.getByTestId( 'placeholder-item' );

			// When rendered as a placeholder a ToolsPanelItem will just omit
			// all the item's children. So the container element will still be
			// there holding its position but the inner text etc should not be
			// there.
			expect( optionalItem ).not.toBeInTheDocument();
			expect( placeholderItem ).not.toHaveClass(
				'components-tools-panel-item',
				'custom-item'
			);
		} );

		it( 'should render default controls with conditional isShownByDefault', async () => {
			const linkedControlValue = false;
			const linkedControlProps = {
				hasValue: vi.fn().mockImplementation( () => {
					return !! linkedControlValue;
				} ),
				label: 'Linked',
				onDeselect: vi.fn(),
				onSelect: vi.fn(),
			};

			const TestPanel = () => (
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps } isShownByDefault>
						<div>Default control</div>
					</ToolsPanelItem>
					<ToolsPanelItem
						{ ...linkedControlProps }
						isShownByDefault={ !! altControlValue }
					>
						<div>Linked control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const { rerender } = render( <TestPanel /> );

			// The linked control should start out as an optional control and is
			// not rendered because it does not have a value.
			let linkedItem = screen.queryByText( 'Linked control' );
			expect( linkedItem ).not.toBeInTheDocument();

			await openDropdownMenu();

			let menuGroups = screen.getAllByRole( 'group' );

			// The linked control should be in the first group of controls.
			expect(
				within( menuGroups[ 0 ] ).getByText( 'Linked' )
			).toBeInTheDocument();

			// Simulate the main control having a value set which should
			// trigger the linked control becoming a default control via the
			// conditional `isShownByDefault` prop.
			altControlValue = true;

			rerender( <TestPanel /> );

			// The linked control should now be a default control and rendered
			// despite not having a value.
			linkedItem = screen.getByText( 'Linked control' );
			expect( linkedItem ).toBeInTheDocument();

			// The linked control should still appear in the controls
			// menu group but as a default control.
			menuGroups = screen.getAllByRole( 'group' );

			// The new default control item for the Linked control should still
			// be within the first menu group.
			const defaultItem = within( menuGroups[ 0 ] ).getByText( 'Linked' );
			expect( defaultItem ).toBeInTheDocument();

			// Default controls without a custom value stay checked and disabled.
			const defaultMenuItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Linked',
				checked: true,
			} );
			expect( defaultMenuItem ).toHaveAttribute(
				'aria-disabled',
				'true'
			);
			expect( defaultMenuItem ).not.toHaveAccessibleDescription();
		} );

		it( 'should handle conditionally rendered default control', async () => {
			const conditionalControlValue = false;
			const conditionalControlProps = {
				hasValue: vi.fn().mockImplementation( () => {
					return !! conditionalControlValue;
				} ),
				label: 'Conditional',
				onDeselect: vi.fn(),
				onSelect: vi.fn(),
			};

			const TestPanel = () => (
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps } isShownByDefault>
						<div>Default control</div>
					</ToolsPanelItem>
					{ !! altControlValue && (
						<ToolsPanelItem
							{ ...conditionalControlProps }
							isShownByDefault
						>
							<div>Conditional control</div>
						</ToolsPanelItem>
					) }
				</ToolsPanel>
			);

			const { rerender } = render( <TestPanel /> );

			// The conditional control should not yet be rendered.
			let conditionalItem = screen.queryByText( 'Conditional control' );
			expect( conditionalItem ).not.toBeInTheDocument();

			// The conditional control should not yet appear in the controls
			// menu group.
			await openDropdownMenu();
			let menuGroups = screen.getAllByRole( 'group' );
			let defaultItem = within( menuGroups[ 0 ] ).queryByText(
				'Conditional'
			);
			expect( defaultItem ).not.toBeInTheDocument();

			// Simulate the main control having a value set which will now
			// render the new default control into the ToolsPanel.
			altControlValue = true;

			rerender( <TestPanel /> );

			// The conditional control should now be rendered and included in
			// the panel's menu.
			conditionalItem = screen.getByText( 'Conditional control' );
			expect( conditionalItem ).toBeInTheDocument();

			// The conditional control should now appear in the controls
			// menu group.
			menuGroups = screen.getAllByRole( 'group' );

			// The new default control item for the Conditional control should
			// be within the first menu group.
			defaultItem = within( menuGroups[ 0 ] ).getByText( 'Conditional' );
			expect( defaultItem ).toBeInTheDocument();
		} );
	} );

	describe( 'registration of panel items', () => {
		beforeEach( () => {
			vi.clearAllMocks();
		} );

		it( 'should register and deregister items when panelId changes', () => {
			// This test simulates switching block selection, which causes the
			// `ToolsPanel` to rerender with a new panelId, necessitating the
			// registration and deregistration of appropriate `ToolsPanelItem`
			// children.
			//
			// When the `panelId` changes, only items matching the new ID register
			// themselves, while those for the old panelId deregister.
			//
			// See: https://github.com/WordPress/gutenberg/pull/36588
			const context: ToolsPanelContextType = { ...panelContext };
			const TestPanel = () => (
				<ToolsPanelContext.Provider value={ context }>
					<ToolsPanelItem { ...altControlProps } panelId="1234">
						<div>Item</div>
					</ToolsPanelItem>
				</ToolsPanelContext.Provider>
			);

			// On the initial render of the panel, the ToolsPanelItem should
			// be registered.
			const { rerender } = render( <TestPanel /> );

			expect( context.registerPanelItem ).toHaveBeenCalledWith(
				expect.objectContaining( {
					label: altControlProps.label,
					panelId: '1234',
				} )
			);
			expect( context.deregisterPanelItem ).not.toHaveBeenCalled();

			// Simulate a change in panel, e.g. a switch of block selection.
			context.panelId = '4321';
			context.menuItems.optional[ altControlProps.label ] = false;

			// Rerender the panel item. Because we have a new panelId, this
			// panelItem should NOT be registered, but it SHOULD be
			// deregistered.
			rerender( <TestPanel /> );

			// registerPanelItem has still only been called once.
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 1 );
			// deregisterPanelItem is called, given that we have switched panels.
			expect( context.deregisterPanelItem ).toHaveBeenCalledWith(
				altControlProps.label,
				expect.objectContaining( { label: altControlProps.label } )
			);

			// Simulate switching back to the original panelId, e.g. by selecting
			// the original block again.
			context.panelId = '1234';
			context.menuItems.optional[ altControlProps.label ] = true;

			// Rerender the panel and ensure that the panelItem is registered
			// again, and it is not de-registered.
			rerender( <TestPanel /> );

			expect( context.registerPanelItem ).toHaveBeenCalledWith(
				expect.objectContaining( {
					label: altControlProps.label,
					panelId: '1234',
				} )
			);
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 2 );
			// deregisterPanelItem has still only been called once.
			expect( context.deregisterPanelItem ).toHaveBeenCalledTimes( 1 );
		} );

		it( 'should register with the latest defaultShown when panelId changes', () => {
			// A consumer that persists the user's choice feeds it back in
			// through `defaultShown`. A change to that prop must not
			// re-register the item on its own, but a re-registration caused by
			// something else has to seed from the saved preference rather than
			// the value the item mounted with.
			const context: ToolsPanelContextType = {
				...panelContext,
				registerPanelItem: vi.fn(),
				deregisterPanelItem: vi.fn(),
			};
			const TestPanel = ( {
				defaultShown,
			}: {
				defaultShown: boolean;
			} ) => (
				<ToolsPanelContext.Provider value={ context }>
					<ToolsPanelItem
						{ ...altControlProps }
						defaultShown={ defaultShown }
						panelId="1234"
					>
						<div>Item</div>
					</ToolsPanelItem>
				</ToolsPanelContext.Provider>
			);

			const { rerender } = render( <TestPanel defaultShown={ false } /> );

			expect( context.registerPanelItem ).toHaveBeenCalledWith(
				expect.objectContaining( { defaultShown: false } )
			);

			// Let registration settle, so that any further calls can only
			// have been caused by the changes made below.
			rerender( <TestPanel defaultShown={ false } /> );
			const settledCalls = ( context.registerPanelItem as Mock ).mock
				.calls.length;

			// The user shows the item and the consumer saves that preference.
			// The updated prop alone must not re-register the item, which
			// would discard the visibility the user chose.
			rerender( <TestPanel defaultShown /> );

			expect( context.registerPanelItem ).toHaveBeenCalledTimes(
				settledCalls
			);

			// Simulate switching block selection away and back again, which
			// deregisters and re-registers the item.
			context.panelId = '4321';
			rerender( <TestPanel defaultShown /> );
			context.panelId = '1234';
			rerender( <TestPanel defaultShown /> );

			expect( context.deregisterPanelItem ).toHaveBeenCalledWith(
				altControlProps.label,
				expect.objectContaining( { label: altControlProps.label } )
			);
			// The item registers again with the saved preference rather than
			// the value it mounted with.
			expect( context.registerPanelItem ).toHaveBeenLastCalledWith(
				expect.objectContaining( { defaultShown: true } )
			);
		} );

		it( 'should register items when ToolsPanel panelId is null', () => {
			// This test simulates when a panel spans multiple block selections.
			// Multi-selection means a panel can't have a single id to match
			// against the item's. Instead the panel gets an id of `null` and
			// individual items should still render themselves in this case.
			//
			// See: https://github.com/WordPress/gutenberg/pull/37216
			const context: ToolsPanelContextType = {
				...panelContext,
				panelId: null,
			};
			const TestPanel = () => (
				<ToolsPanelContext.Provider value={ context }>
					<ToolsPanelItem { ...altControlProps } panelId="1234">
						<div>Item</div>
					</ToolsPanelItem>
				</ToolsPanelContext.Provider>
			);

			// On the initial render of the panel, the ToolsPanelItem should
			// be registered.
			const { rerender, unmount } = render( <TestPanel /> );

			expect( context.registerPanelItem ).toHaveBeenCalledWith(
				expect.objectContaining( {
					label: altControlProps.label,
					panelId: '1234',
				} )
			);
			expect( context.deregisterPanelItem ).not.toHaveBeenCalled();

			// Simulate a further block selection being added to the
			// multi-selection. The panelId will remain `null` in this case.
			rerender( <TestPanel /> );
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 1 );
			expect( context.deregisterPanelItem ).not.toHaveBeenCalled();

			// Simulate a change in panel back to single block selection for
			// which the item matches panelId.
			context.panelId = '1234';
			rerender( <TestPanel /> );
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 1 );
			expect( context.deregisterPanelItem ).not.toHaveBeenCalled();

			// Simulate another multi-selection where the panelId is `null`.
			// Still matches the panel, so the registration stands rather than
			// churning through a deregister/register pair.
			context.panelId = null;
			rerender( <TestPanel /> );
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 1 );
			expect( context.deregisterPanelItem ).not.toHaveBeenCalled();

			// Simulate a change in panel e.g. back to a single block selection
			// Where the item's panelId is not a match.
			context.panelId = '4321';
			rerender( <TestPanel /> );

			// No longer matches, so it has already deregistered. Unmounting
			// must not deregister again.
			expect( context.deregisterPanelItem ).toHaveBeenCalledTimes( 1 );
			unmount();
			expect( context.registerPanelItem ).toHaveBeenCalledTimes( 1 );
			expect( context.deregisterPanelItem ).toHaveBeenCalledTimes( 1 );
		} );
	} );

	describe( 'callbacks on menu item selection', () => {
		beforeEach( () => {
			vi.clearAllMocks();
		} );

		it( 'should call onDeselect callback when menu item is toggled off', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( controlProps.label );

			expect( controlProps.onSelect ).not.toHaveBeenCalled();
			expect( controlProps.onDeselect ).toHaveBeenCalledTimes( 1 );
		} );

		it( 'should call onSelect callback when menu item is toggled on', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( altControlProps.label );

			expect( altControlProps.onSelect ).toHaveBeenCalledTimes( 1 );
			expect( altControlProps.onDeselect ).not.toHaveBeenCalled();
		} );

		it( 'should call resetAll callback when its menu item is selected', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( 'Reset all' );

			expect( resetAll ).toHaveBeenCalledTimes( 1 );
			expect( controlProps.onSelect ).not.toHaveBeenCalled();
			expect( controlProps.onDeselect ).not.toHaveBeenCalled();
			expect( altControlProps.onSelect ).not.toHaveBeenCalled();
			expect( altControlProps.onDeselect ).not.toHaveBeenCalled();
		} );

		// This confirms the internal `isResetting` state when resetting all
		// controls does not prevent subsequent individual reset requests.
		// i.e. onDeselect callbacks are called correctly after a resetAll.
		it( 'should call onDeselect after previous reset all', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( 'Reset all' ); // Initial control is displayed by default.
			await selectMenuItem( controlProps.label ); // Re-display control.

			expect( controlProps.onDeselect ).not.toHaveBeenCalled();

			await selectMenuItem( controlProps.label ); // Reset control.

			expect( controlProps.onDeselect ).toHaveBeenCalled();
		} );
	} );

	describe( 'shown change callback', () => {
		beforeEach( () => {
			vi.clearAllMocks();
		} );

		it( 'should call onShownChange with true when an optional item is shown via the menu', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( altControlProps.label );

			expect( altControlProps.onShownChange ).toHaveBeenCalledTimes( 1 );
			expect( altControlProps.onShownChange ).toHaveBeenCalledWith(
				true
			);
		} );

		it( 'should call onShownChange with false when an optional item without a value is hidden via the menu', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( altControlProps.label );
			await selectMenuItem( altControlProps.label );

			expect( altControlProps.onShownChange ).toHaveBeenCalledTimes( 2 );
			expect( altControlProps.onShownChange ).toHaveBeenLastCalledWith(
				false
			);
			// The item never had a value, so there was nothing to reset.
			expect( altControlProps.onDeselect ).not.toHaveBeenCalled();
		} );

		it( 'should call both onShownChange and onDeselect when an optional item with a value is hidden via the menu', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( controlProps.label );

			expect( controlProps.onShownChange ).toHaveBeenCalledTimes( 1 );
			expect( controlProps.onShownChange ).toHaveBeenCalledWith( false );
			expect( controlProps.onDeselect ).toHaveBeenCalledTimes( 1 );
		} );

		it( 'should not call onShownChange for default items', async () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...controlProps } isShownByDefault>
						<div>Example control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			await openDropdownMenu();
			await selectMenuItem( controlProps.label );

			// Default items stay visible when toggled off; the action resets
			// them rather than hiding them.
			expect( controlProps.onDeselect ).toHaveBeenCalledTimes( 1 );
			expect( controlProps.onShownChange ).not.toHaveBeenCalled();
		} );

		it( 'should not call onShownChange when items are hidden by Reset all', async () => {
			renderPanel();

			await openDropdownMenu();
			await selectMenuItem( 'Reset all' );

			expect( controlProps.onShownChange ).not.toHaveBeenCalled();
			expect( altControlProps.onShownChange ).not.toHaveBeenCalled();
		} );

		it( 'should not call onShownChange when the value changes programmatically', () => {
			const onShownChange = vi.fn();
			const ToolsPanelOptional = ( { value }: { value?: number } ) => (
				<ToolsPanel { ...defaultProps } panelId="1234">
					<ToolsPanelItem
						hasValue={ () => !! value }
						label="Alt"
						onShownChange={ onShownChange }
						panelId="1234"
					>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const { rerender } = render( <ToolsPanelOptional /> );
			expect(
				screen.queryByText( 'Optional control' )
			).not.toBeInTheDocument();

			// Gaining a value shows the item, but that is not a menu action.
			rerender( <ToolsPanelOptional value={ 100 } /> );
			expect(
				screen.getByText( 'Optional control' )
			).toBeInTheDocument();

			// Losing it again is not a menu action either.
			rerender( <ToolsPanelOptional /> );

			expect( onShownChange ).not.toHaveBeenCalled();
		} );

		it( 'should not call any callback when an item is mounted with defaultShown', () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...altControlProps } defaultShown>
						<div>Alt control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			// Registering an item as shown is not a menu action, so none of
			// the item's callbacks should fire.
			expect( screen.getByText( 'Alt control' ) ).toBeInTheDocument();
			expect( altControlProps.onShownChange ).not.toHaveBeenCalled();
			expect( altControlProps.onSelect ).not.toHaveBeenCalled();
		} );
	} );

	describe( 'grouped panel items within custom components', () => {
		it( 'should render grouped items correctly', () => {
			renderGroupedItemsInPanel();

			const defaultItem = screen.getByText( 'Grouped control' );
			const altItem = screen.queryByText( 'Alt grouped control' );

			expect( defaultItem ).toBeInTheDocument();
			expect( altItem ).not.toBeInTheDocument();
		} );

		it( 'should render grouped items within the menu', async () => {
			renderGroupedItemsInPanel();
			await openDropdownMenu();

			const defaultItem = screen.getByText( 'Nested Control 1' );
			const defaultMenuItem = screen.getByRole( 'menuitem', {
				name: 'Nested Control 1, reset to default',
			} );

			const altItem = screen.getByText( 'Nested Control 2' );
			const altMenuItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Nested Control 2, show',
				checked: false,
			} );

			expect( defaultItem ).toBeInTheDocument();
			expect( defaultMenuItem ).toBeInTheDocument();

			expect( altItem ).toBeInTheDocument();
			expect( altMenuItem ).toBeInTheDocument();
		} );
	} );

	describe( 'wrapped panel items within custom components', () => {
		it( 'should render wrapped items correctly', () => {
			renderWrappedItemInPanel();

			const wrappers = screen.getAllByText( 'Wrapper' );
			const defaultItem = screen.getByText( 'Wrapped 1' );
			const altItem = screen.queryByText( 'Wrapped 2' );

			// Both wrappers should be rendered but only the panel item
			// displayed by default should be within the document.
			expect( wrappers.length ).toEqual( 2 );
			expect( defaultItem ).toBeInTheDocument();
			expect( altItem ).not.toBeInTheDocument();
		} );

		it( 'should render wrapped items within the menu', async () => {
			renderWrappedItemInPanel();
			await openDropdownMenu();

			const defaultItem = screen.getByText( 'Nested Control 1' );
			const defaultMenuItem = screen.getByRole( 'menuitem', {
				name: 'Nested Control 1, reset to default',
			} );

			const altItem = screen.getByText( 'Nested Control 2' );
			const altMenuItem = screen.getByRole( 'menuitemcheckbox', {
				name: 'Nested Control 2, show',
				checked: false,
			} );

			expect( defaultItem ).toBeInTheDocument();
			expect( defaultMenuItem ).toBeInTheDocument();

			expect( altItem ).toBeInTheDocument();
			expect( altMenuItem ).toBeInTheDocument();
		} );
	} );

	describe( 'rendering via SlotFills', () => {
		beforeEach( () => {
			vi.clearAllMocks();
		} );

		it( 'should maintain visual order of controls when toggled on and off', async () => {
			// Multiple fills are added to better simulate panel items being
			// injected from different locations.
			render(
				<SlotFillProvider>
					<ToolsPanelItems>
						<ToolsPanelItem { ...altControlProps }>
							<div>Item 1</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanelItems>
						<ToolsPanelItem { ...controlProps }>
							<div>Item 2</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel { ...defaultProps }>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			// Only the second item should be shown initially as it has a value.
			const firstItem = screen.queryByText( 'Item 1' );
			const secondItem = screen.getByText( 'Item 2' );

			expect( firstItem ).not.toBeInTheDocument();
			expect( secondItem ).toBeInTheDocument();

			// Toggle on the first item.
			await openDropdownMenu();
			await selectMenuItem( altControlProps.label );

			// The order of items should be as per their original source order.
			let items = screen.getAllByText( /Item [1-2]/ );

			expect( items ).toHaveLength( 2 );
			expect( items[ 0 ] ).toHaveTextContent( 'Item 1' );
			expect( items[ 1 ] ).toHaveTextContent( 'Item 2' );

			// Then toggle off both items.
			await selectMenuItem( controlProps.label );
			await selectMenuItem( altControlProps.label );

			// Toggle on controls again and ensure order remains.
			await selectMenuItem( controlProps.label );
			await selectMenuItem( altControlProps.label );

			items = screen.getAllByText( /Item [1-2]/ );

			expect( items ).toHaveLength( 2 );
			expect( items[ 0 ] ).toHaveTextContent( 'Item 1' );
			expect( items[ 1 ] ).toHaveTextContent( 'Item 2' );
		} );

		it( 'should maintain menu item order', async () => {
			const InconsistentItems = () => (
				<ToolsPanelItems>
					<ToolsPanelItem
						label="Item 1"
						hasValue={ () => false }
						isShownByDefault
					>
						<div>Item 1</div>
					</ToolsPanelItem>
					<ToolsPanelItem
						label="Item 2"
						hasValue={ () => false }
						isShownByDefault
					>
						<div>Item 2</div>
					</ToolsPanelItem>
				</ToolsPanelItems>
			);

			const { rerender } = render(
				<SlotFillProvider>
					<InconsistentItems key="order-test-step-1" />
					<ToolsPanelItems>
						<ToolsPanelItem
							label="Item 3"
							hasValue={ () => false }
							isShownByDefault
						>
							<div>Item 3</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel { ...defaultProps }>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			// Open dropdown menu.
			const user = userEvent.setup();
			let menuButton = getMenuButton();
			await user.click( menuButton );

			// Confirm all the existing menu items are present and in the
			// expected order.
			let menuItems = await screen.findAllByRole( 'menuitemcheckbox' );

			expect( menuItems.length ).toEqual( 3 );
			expect( menuItems[ 0 ] ).toHaveTextContent( 'Item 1' );
			expect( menuItems[ 1 ] ).toHaveTextContent( 'Item 2' );
			expect( menuItems[ 2 ] ).toHaveTextContent( 'Item 3' );

			// Close the dropdown menu.
			await user.click( menuButton );

			rerender(
				<SlotFillProvider>
					<InconsistentItems key="order-test-step-2" />
					<ToolsPanelItems>
						<ToolsPanelItem
							label="Item 3"
							hasValue={ () => false }
							isShownByDefault
						>
							<div>Item 3</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel { ...defaultProps }>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			// Reopen dropdown menu.
			menuButton = getMenuButton();
			await user.click( menuButton );

			// Confirm the menu item order has been maintained.
			menuItems = await screen.findAllByRole( 'menuitemcheckbox' );

			expect( menuItems.length ).toEqual( 3 );
			expect( menuItems[ 0 ] ).toHaveTextContent( 'Item 1' );
			expect( menuItems[ 1 ] ).toHaveTextContent( 'Item 2' );
			expect( menuItems[ 2 ] ).toHaveTextContent( 'Item 3' );
		} );

		it( 'should not trigger callback when fill has not updated yet when panel has', () => {
			// Fill provided controls can update independently to the panel.
			// A `panelId` prop was added to both panels and items
			// so it could prevent erroneous registrations and calls to
			// `onDeselect` etc.
			//
			// See: https://github.com/WordPress/gutenberg/pull/35375
			//
			// This test simulates this issue by rendering an item within a
			// contrived `ToolsPanelContext` to reflect the changes the panel
			// item needs to protect against.
			const context = {
				panelId: '1234',
				menuItems: {
					default: {},
					optional: { [ altControlProps.label ]: true },
				},
				hasMenuItems: false,
				isResetting: false,
				shouldRenderPlaceholderItems: false,
				registerPanelItem: noop,
				deregisterPanelItem: noop,
				registerResetAllFilter: noop,
				deregisterResetAllFilter: noop,
				flagItemCustomization: noop,
				areAllOptionalControlsHidden: true,
			};

			// This initial render gives the tools panel item a chance to
			// set its internal state to reflect it was previously selected.
			// This later forms part of the condition used to determine if an
			// item is being deselected and thus call the onDeselect callback.
			const { rerender } = render(
				<ToolsPanelContext.Provider value={ context }>
					<ToolsPanelItem { ...altControlProps } panelId="1234">
						<div>Item</div>
					</ToolsPanelItem>
				</ToolsPanelContext.Provider>
			);

			// Simulate a change in panel separate to the rendering of fills.
			// e.g. a switch of block selection.
			context.panelId = '4321';
			context.menuItems.optional[ altControlProps.label ] = false;

			// Rerender the panel item and ensure that it skips any check
			// for deselection given it still belongs to a different panelId.
			rerender(
				<ToolsPanelContext.Provider value={ context }>
					<ToolsPanelItem { ...altControlProps } panelId="1234">
						<div>Item</div>
					</ToolsPanelItem>
				</ToolsPanelContext.Provider>
			);

			expect( altControlProps.onDeselect ).not.toHaveBeenCalled();
		} );

		it( 'should not contain menu items for an item belonging to another panel', async () => {
			// A fill can mount after the panel it is rendered into has already
			// settled. An item whose `panelId` doesn't match must stay out of
			// that panel's menu entirely, including out of the value flagging
			// that populates it.
			const Panel = ( { withForeign }: { withForeign: boolean } ) => (
				<ToolsPanel { ...defaultProps } panelId="1234">
					<ToolsPanelItem
						label="Mine"
						panelId="1234"
						isShownByDefault
						hasValue={ () => false }
					>
						<div>My control</div>
					</ToolsPanelItem>
					{ withForeign && (
						<ToolsPanelItem
							label="Foreign"
							panelId="9999"
							hasValue={ () => true }
						>
							<div>Foreign control</div>
						</ToolsPanelItem>
					) }
				</ToolsPanel>
			);

			// Let the panel settle with only its own item registered, then
			// bring in an item that belongs to a different panel.
			const { rerender } = render( <Panel withForeign={ false } /> );
			rerender( <Panel withForeign /> );

			await openDropdownMenu();

			expect(
				screen.queryByRole( 'menuitemcheckbox', { name: /Foreign/i } )
			).not.toBeInTheDocument();
		} );

		it( "should not let a replacement item inherit the outgoing one's state", async () => {
			// Two blocks can each contribute a control of the same name. When
			// selection moves between them, the incoming item starts from its
			// own value rather than the visibility the user chose for the one
			// it replaced.
			const SameLabelInTwoPanels = ( {
				panelId,
			}: Pick<
				React.ComponentProps< typeof ToolsPanelItem >,
				'panelId'
			> ) => (
				<SlotFillProvider>
					<ToolsPanelItems>
						<ToolsPanelItem
							label="Shared"
							panelId="1234"
							hasValue={ () => false }
						>
							<div>Item 1</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanelItems>
						<ToolsPanelItem
							label="Shared"
							panelId="9999"
							hasValue={ () => false }
						>
							<div>Item 2</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel { ...defaultProps } panelId={ panelId }>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			const { rerender } = render(
				<SameLabelInTwoPanels panelId="1234" />
			);

			// Show the first block's control.
			await openDropdownMenu();
			await selectMenuItem( 'Shared' );
			expect( screen.getByText( 'Item 1' ) ).toBeInTheDocument();

			// Move to the other block. Its control has no value and was never
			// shown, so it stays hidden.
			// The menu stays open across the rerender.
			rerender( <SameLabelInTwoPanels panelId="9999" /> );

			expect(
				await screen.findByRole( 'menuitemcheckbox', {
					name: 'Shared, show',
				} )
			).toBeInTheDocument();
			expect( screen.queryByText( 'Item 2' ) ).not.toBeInTheDocument();
		} );

		it( 'should not contain orphaned menu items when panelId changes', async () => {
			// As fills and the panel can update independently this aims to
			// test that no orphaned items appear registered in the panel menu.
			//
			// See: https://github.com/WordPress/gutenberg/pull/34085
			const TestSlotFillPanel = ( {
				panelId,
			}: Pick<
				React.ComponentProps< typeof ToolsPanelItem >,
				'panelId'
			> ) => (
				<SlotFillProvider>
					<ToolsPanelItems>
						<ToolsPanelItem { ...altControlProps } panelId="1234">
							<div>Item 1</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanelItems>
						<ToolsPanelItem { ...controlProps } panelId="9999">
							<div>Item 2</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel { ...defaultProps } panelId={ panelId }>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			const { rerender } = render( <TestSlotFillPanel panelId="1234" /> );
			await openDropdownMenu();

			// Only the item matching the panelId should have been registered
			// and appear in the panel menu.
			expect(
				screen.getByRole( 'menuitemcheckbox', {
					name: 'Alt, show',
				} )
			).toBeInTheDocument();
			expect(
				screen.queryByRole( 'menuitemcheckbox', {
					name: 'Example, hide and reset',
				} )
			).not.toBeInTheDocument();

			// Re-render the panel with different panelID simulating a block
			// selection change.
			rerender( <TestSlotFillPanel panelId="9999" /> );
			expect(
				screen.queryByRole( 'menuitemcheckbox', {
					name: 'Alt, show',
				} )
			).not.toBeInTheDocument();
			expect(
				screen.getByRole( 'menuitemcheckbox', {
					name: 'Example, hide and reset',
				} )
			).toBeInTheDocument();
		} );
	} );

	describe( 'panel header icon toggle', () => {
		const defaultControlsValue = false;
		const defaultControls = {
			hasValue: vi.fn().mockImplementation( () => {
				return !! defaultControlsValue;
			} ),
			label: 'Default',
			onDeselect: vi.fn(),
			onSelect: vi.fn(),
			isShownByDefault: true,
		};

		const optionalControlsValue = false;
		const optionalControls = {
			hasValue: vi.fn().mockImplementation( () => {
				return !! optionalControlsValue;
			} ),
			label: 'Optional',
			onDeselect: vi.fn(),
			onSelect: vi.fn(),
			isShownByDefault: false,
		};

		it( 'should render appropriate labels and descriptions for the dropdown menu where there are default controls', async () => {
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...defaultControls }>
						<div>Default control</div>
					</ToolsPanelItem>
					<ToolsPanelItem { ...optionalControls }>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const optionsDisplayedIcon = screen.getByRole( 'button', {
				name: 'Panel header options',
			} );

			expect( optionsDisplayedIcon ).toBeInTheDocument();

			// The dropdown toggle doesn't have a description when an option is displayed.
			// In this case the default control is displayed.
			expect( optionsDisplayedIcon ).not.toHaveAccessibleDescription();
		} );

		it( 'should render appropriate labels and descriptions for the dropdown menu where there are no default controls', async () => {
			// All options are inactive.
			render(
				<ToolsPanel { ...defaultProps }>
					<ToolsPanelItem { ...optionalControls }>
						<div>Optional control</div>
					</ToolsPanelItem>
				</ToolsPanel>
			);

			const optionsHiddenIcon = screen.getByRole( 'button', {
				name: 'Panel header options',
			} );

			// The dropdown toggle has a description indicating that all options are hidden.
			expect( optionsHiddenIcon ).toBeInTheDocument();
			expect( optionsHiddenIcon ).toHaveAccessibleDescription(
				'All options are currently hidden'
			);

			// Activate one of the options.
			await openDropdownMenu();
			await selectMenuItem( optionalControls.label );

			const optionsDisplayedIcon = screen.getByRole( 'button', {
				name: 'Panel header options',
			} );

			// The dropdown toggle no longer has a description.
			expect( optionsDisplayedIcon ).not.toHaveAccessibleDescription();
		} );

		it( 'should pass reset all filters that see the latest props', async () => {
			let received: unknown[] = [];
			const ChangingFilter = () => {
				const [ count, setCount ] = useState( 1 );
				return (
					<ToolsPanel
						label="Panel header"
						resetAll={ ( filters ) => {
							received = ( filters ?? [] ).map( ( filter ) =>
								filter()
							);
						} }
					>
						<ToolsPanelItem
							label="Filtered"
							isShownByDefault
							hasValue={ () => true }
							resetAllFilter={ () => count }
						>
							<button onClick={ () => setCount( 2 ) }>
								bump
							</button>
						</ToolsPanelItem>
					</ToolsPanel>
				);
			};

			const user = userEvent.setup();
			render( <ChangingFilter /> );

			// The panelId never changes, which is where a filter frozen at
			// registration goes stale.
			await user.click( screen.getByText( 'bump' ) );
			await openDropdownMenu();
			await selectMenuItem( 'Reset all' );

			expect( received ).toEqual( [ 2 ] );
		} );

		it( 'should not call reset all for different panelIds', async () => {
			const resetItem = vi.fn();
			const resetItemB = vi.fn();

			const children = (
				<>
					<ToolsPanelItem
						label="a"
						hasValue={ () => true }
						panelId="a"
						resetAllFilter={ resetItem }
						isShownByDefault
					>
						<div>Example control</div>
					</ToolsPanelItem>
					<ToolsPanelItem
						label="b"
						hasValue={ () => true }
						panelId="b"
						resetAllFilter={ resetItemB }
						isShownByDefault
					>
						<div>Alt control</div>
					</ToolsPanelItem>
				</>
			);

			const resetAllCallback = (
				filters: ResetAllFilter[] | undefined
			) => filters?.forEach( ( f ) => f() );

			const { rerender } = render(
				<ToolsPanel
					{ ...defaultProps }
					panelId="a"
					resetAll={ resetAllCallback }
				>
					{ children }
				</ToolsPanel>
			);

			await openDropdownMenu();
			await selectMenuItem( 'Reset all' );
			expect( resetItem ).toHaveBeenCalled();
			expect( resetItemB ).not.toHaveBeenCalled();

			resetItem.mockClear();

			rerender(
				<ToolsPanel
					{ ...defaultProps }
					panelId="b"
					resetAll={ resetAllCallback }
				>
					{ children }
				</ToolsPanel>
			);

			await selectMenuItem( 'Reset all' );
			expect( resetItem ).not.toHaveBeenCalled();
			expect( resetItemB ).toHaveBeenCalled();
		} );
	} );

	describe( 'reset all button', () => {
		it( "should disable the reset all button when there's nothing to reset", async () => {
			await renderPanel();
			await openDropdownMenu();

			const resetAllItem = await screen.findByRole( 'menuitem', {
				name: 'Reset all',
			} );
			expect( resetAllItem ).toBeInTheDocument();
			expect( resetAllItem ).toHaveAttribute( 'aria-disabled', 'false' );

			await selectMenuItem( 'Reset all' );

			// Test the aria live announcement.
			const announcement = screen.getByText( 'All options reset' );
			expect( announcement ).toHaveAttribute( 'aria-live', 'assertive' );

			const disabledResetAllItem = await screen.findByRole( 'menuitem', {
				name: 'Reset all',
			} );
			expect( disabledResetAllItem ).toBeInTheDocument();
			expect( disabledResetAllItem ).toHaveAttribute(
				'aria-disabled',
				'true'
			);
		} );
	} );

	describe( 'reset all with values the reset leaves in place', () => {
		it( 'should keep a default control resettable when its value survives', async () => {
			// The value arrives after mount, like block library controls whose
			// `hasValue` closes over an attribute: false at mount, true once
			// edited. A value read back from registration time misses it.
			const GainsAValue = () => {
				const [ hasVal, setHasVal ] = useState( false );
				return (
					<ToolsPanel label="Panel header" resetAll={ () => {} }>
						<ToolsPanelItem
							label="Survivor"
							isShownByDefault
							hasValue={ () => hasVal }
						>
							<button onClick={ () => setHasVal( true ) }>
								set a value
							</button>
						</ToolsPanelItem>
					</ToolsPanel>
				);
			};

			const user = userEvent.setup();
			render( <GainsAValue /> );

			await user.click( screen.getByText( 'set a value' ) );
			await openDropdownMenu();
			await selectMenuItem( 'Reset all' );

			// `resetAll` clears nothing here, so the value is still set and
			// must stay resettable from both menu entries.
			expect(
				await screen.findByRole( 'menuitem', { name: 'Reset all' } )
			).toHaveAttribute( 'aria-disabled', 'false' );
			expect(
				await screen.findByRole( 'menuitem', {
					name: 'Survivor, reset to default',
				} )
			).toBeInTheDocument();
		} );
	} );

	describe( 'first and last panel items', () => {
		it( 'should apply first/last classes to appropriate items', () => {
			render(
				<SlotFillProvider>
					<ToolsPanelItems>
						<ToolsPanelItem { ...altControlProps }>
							<div>Item 1</div>
						</ToolsPanelItem>
						<ToolsPanelItem
							{ ...controlProps }
							data-testid="item-2"
						>
							<div>Item 2</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanelItems>
						<ToolsPanelItem
							{ ...altControlProps }
							label="Item 3"
							data-testid="item-3"
							isShownByDefault
						>
							<div>Item 3</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanelItems>
						<ToolsPanelItem { ...altControlProps } label="Item 4">
							<div>Item 4</div>
						</ToolsPanelItem>
					</ToolsPanelItems>
					<ToolsPanel
						{ ...defaultProps }
						hasInnerWrapper
						shouldRenderPlaceholderItems
						__experimentalFirstVisibleItemClass="first"
						__experimentalLastVisibleItemClass="last"
					>
						<Slot />
					</ToolsPanel>
				</SlotFillProvider>
			);

			const item2 = screen.getByText( 'Item 2' );
			const item3 = screen.getByText( 'Item 3' );

			expect( screen.queryByText( 'Item 1' ) ).not.toBeInTheDocument();
			expect( item2 ).toBeInTheDocument();
			expect( item3 ).toBeInTheDocument();
			expect( screen.queryByText( 'Item 4' ) ).not.toBeInTheDocument();

			expect( screen.getByTestId( 'item-2' ) ).toHaveClass( 'first' );
			expect( screen.getByTestId( 'item-3' ) ).toHaveClass( 'last' );
		} );
	} );
} );
