import { describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { render } from 'vitest-browser-react';
import { speak } from '@wordpress/a11y';
import { useState } from '@wordpress/element';
import { ColorPicker } from '..';

vi.mock( import( '@wordpress/a11y' ), async ( importOriginal ) => ( {
	...( await importOriginal() ),
	speak: vi.fn(),
} ) );

const hslaMatcher = expect.objectContaining( {
	h: expect.any( Number ),
	s: expect.any( Number ),
	l: expect.any( Number ),
	a: expect.any( Number ),
} );

const legacyColorMatcher = {
	hex: expect.any( String ),
	hsl: hslaMatcher,
	hsv: expect.objectContaining( {
		h: expect.any( Number ),
		s: expect.any( Number ),
		v: expect.any( Number ),
		a: expect.any( Number ),
	} ),
	rgb: expect.objectContaining( {
		r: expect.any( Number ),
		g: expect.any( Number ),
		b: expect.any( Number ),
		a: expect.any( Number ),
	} ),
	oldHue: expect.any( Number ),
	source: 'hex',
};

// Without the controlled component, slider values don't update after changes.
// Controlled component with state helps synchronize input box and slider during testing.
const ControlledColorPicker = ( {
	onChange: onChangeProp,
	initialColor = '#000000',
	...restProps
}: React.ComponentProps< typeof ColorPicker > & { initialColor?: string } ) => {
	const [ colorState, setColorState ] = useState( initialColor );

	const internalOnChange: typeof onChangeProp = ( newColor ) => {
		onChangeProp?.( newColor );
		setColorState( newColor );
	};

	return (
		<>
			<ColorPicker
				{ ...restProps }
				onChange={ internalOnChange }
				color={ colorState }
			/>

			<button onClick={ () => setColorState( '#4d87ba' ) }>
				Set color to #4d87ba
			</button>
		</>
	);
};

describe( 'ColorPicker', () => {
	describe( 'legacy props', () => {
		it( 'should fire onChangeComplete with the legacy color format', async () => {
			const user = userEvent.setup();
			const onChangeComplete = vi.fn();
			const color = '#000';

			await render(
				<ColorPicker
					onChangeComplete={ onChangeComplete }
					color={ color }
					enableAlpha={ false }
				/>
			);

			const formatSelector = screen.getByRole( 'combobox', {
				name: 'Color format',
			} );
			expect( formatSelector ).toBeVisible();

			await user.click( formatSelector );
			await user.click( screen.getByRole( 'option', { name: 'Hex' } ) );

			const hexInput = screen.getByRole( 'textbox' );
			expect( hexInput ).toBeVisible();

			await user.clear( hexInput );
			expect( onChangeComplete ).toHaveBeenCalledTimes( 1 );
			await user.keyboard( '1' );
			expect( onChangeComplete ).toHaveBeenCalledTimes( 2 );
			await user.keyboard( 'a' );
			expect( onChangeComplete ).toHaveBeenCalledTimes( 3 );
			await user.keyboard( 'b' );
			expect( onChangeComplete ).toHaveBeenCalledTimes( 4 );
			expect( onChangeComplete ).toHaveBeenLastCalledWith(
				legacyColorMatcher
			);
		} );
	} );
	describe( 'Hex input', () => {
		it( 'should fire onChange with the correct value from the hex input', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();
			const color = '#000';

			await render(
				<ColorPicker
					onChange={ onChange }
					color={ color }
					enableAlpha={ false }
				/>
			);

			const formatSelector = screen.getByRole( 'combobox', {
				name: 'Color format',
			} );
			expect( formatSelector ).toBeVisible();

			await user.click( formatSelector );
			await user.click( screen.getByRole( 'option', { name: 'Hex' } ) );

			const hexInput = screen.getByRole( 'textbox' );
			expect( hexInput ).toBeVisible();

			await user.clear( hexInput );
			expect( onChange ).toHaveBeenCalledTimes( 1 );
			await user.keyboard( '1' );
			expect( onChange ).toHaveBeenCalledTimes( 2 );
			await user.keyboard( 'a' );
			expect( onChange ).toHaveBeenCalledTimes( 3 );
			await user.keyboard( 'b' );
			expect( onChange ).toHaveBeenCalledTimes( 4 );
			expect( onChange ).toHaveBeenLastCalledWith( '#11aabb' );
		} );

		it( 'should reset color to black when the hex input is completely cleared', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();
			const color = '#11aabb';

			await render(
				<ColorPicker
					onChange={ onChange }
					color={ color }
					enableAlpha={ false }
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'Hex' } ) );

			const hexInput = screen.getByRole( 'textbox' );
			await user.clear( hexInput );

			expect( onChange ).toHaveBeenLastCalledWith( '#000000' );
		} );
	} );

	describe.each( [
		[ 'red', 'Red', '#7dffff' ],
		[ 'green', 'Green', '#ff7dff' ],
		[ 'blue', 'Blue', '#ffff7d' ],
	] )( 'RGB inputs', ( colorInput, inputLabel, expected ) => {
		it( `should fire onChange with the correct value when the ${ colorInput } value is updated`, async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();
			const color = '#fff';

			await render(
				<ColorPicker
					onChange={ onChange }
					color={ color }
					enableAlpha={ false }
				/>
			);

			const formatSelector = screen.getByRole( 'combobox', {
				name: 'Color format',
			} );
			expect( formatSelector ).toBeVisible();

			await user.click( formatSelector );
			await user.click( screen.getByRole( 'option', { name: 'RGB' } ) );

			const inputElement = screen.getByRole( 'spinbutton', {
				name: inputLabel,
			} );
			expect( inputElement ).toBeVisible();

			await user.clear( inputElement );
			expect( onChange ).toHaveBeenCalledTimes( 1 );
			await user.keyboard( '1' );
			expect( onChange ).toHaveBeenCalledTimes( 2 );
			await user.keyboard( '2' );
			expect( onChange ).toHaveBeenCalledTimes( 3 );
			await user.keyboard( '5' );
			expect( onChange ).toHaveBeenCalledTimes( 4 );
			expect( onChange ).toHaveBeenLastCalledWith( expected );
		} );
	} );

	describe( 'HSL inputs', () => {
		it( 'sliders should use accurate H and S values based on user interaction when possible', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
				/>
			);

			const formatSelector = screen.getByRole( 'combobox', {
				name: 'Color format',
			} );
			expect( formatSelector ).toBeVisible();

			await user.click( formatSelector );
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const hueSlider = screen.getByRole( 'slider', {
				name: 'Hue (HSL H value)',
			} );
			const saturationSlider = screen.getByRole( 'slider', {
				name: 'Saturation',
			} );
			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			const hueNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Hue (HSL H value)',
			} );
			const saturationNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Saturation',
			} );
			const lightnessNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Lightness',
			} );

			// All initial inputs should have a value of `0` since the color is black.
			expect( hueSlider ).toHaveValue( '0' );
			expect( saturationSlider ).toHaveValue( '0' );
			expect( lightnessSlider ).toHaveValue( '0' );
			expect( hueNumberInput ).toHaveValue( 0 );
			expect( saturationNumberInput ).toHaveValue( 0 );
			expect( lightnessNumberInput ).toHaveValue( 0 );

			// Interact with the Hue slider, it should change its value (and the
			// value of the associated number input), but it shouldn't cause the
			// `onChange` callback to fire, since the resulting color is still black.
			await userEvent.fill( hueSlider, '80' );

			expect( hueSlider ).toHaveValue( '80' );
			expect( hueNumberInput ).toHaveValue( 80 );
			expect( onChange ).not.toHaveBeenCalled();

			// Interact with the Saturation slider, it should change its value (and the
			// value of the associated number input), but it shouldn't cause the
			// `onChange` callback to fire, since the resulting color is still black.
			await userEvent.fill( saturationSlider, '50' );

			expect( saturationSlider ).toHaveValue( '50' );
			expect( saturationNumberInput ).toHaveValue( 50 );
			expect( onChange ).not.toHaveBeenCalled();

			// Interact with the Lightness slider, it should change its value (and the
			// value of the associated number input). It should also cause the
			// `onChange` callback to fire, since changing the lightness actually
			// causes the color to change.
			await userEvent.fill( lightnessSlider, '30' );

			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '30' )
			);
			expect( lightnessNumberInput ).toHaveValue( 30 );
			expect( onChange ).toHaveBeenCalledTimes( 1 );
			expect( onChange ).toHaveBeenLastCalledWith( '#597326' );

			// Interact with the Lightness slider, setting to 100 (ie. white).
			// It should also cause the `onChange` callback to fire. The hue and
			// saturation should be preserved (not reset to 0) since the user
			// explicitly set them earlier.
			await userEvent.fill( lightnessSlider, '100' );

			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '100' )
			);
			expect( lightnessNumberInput ).toHaveValue( 100 );
			expect( hueSlider ).toHaveValue( '80' );
			expect( saturationSlider ).toHaveValue( '50' );
			expect( hueNumberInput ).toHaveValue( 80 );
			expect( saturationNumberInput ).toHaveValue( 50 );
			expect( onChange ).toHaveBeenCalledTimes( 2 );
			expect( onChange ).toHaveBeenLastCalledWith( '#ffffff' );

			// Interact with the Hue slider, it should change its value (and the
			// value of the associated number input), but it shouldn't cause the
			// `onChange` callback to fire, since the resulting color is still white.
			await userEvent.fill( hueSlider, '147' );

			expect( hueSlider ).toHaveValue( '147' );
			expect( hueNumberInput ).toHaveValue( 147 );
			expect( onChange ).toHaveBeenCalledTimes( 2 );

			// Interact with the Saturation slider, it should change its value (and the
			// value of the associated number input), but it shouldn't cause the
			// `onChange` callback to fire, since the resulting color is still white.
			await userEvent.fill( saturationSlider, '82' );

			expect( saturationSlider ).toHaveValue( '82' );
			expect( saturationNumberInput ).toHaveValue( 82 );
			expect( onChange ).toHaveBeenCalledTimes( 2 );

			// Interact with the Lightness slider, it should change its value (and the
			// value of the associated number input). It should also cause the
			// `onChange` callback to fire, since changing the lightness actually
			// causes the color to change.
			await userEvent.fill( lightnessSlider, '14' );

			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '14' )
			);
			expect( lightnessNumberInput ).toHaveValue( 14 );
			expect( onChange ).toHaveBeenCalledTimes( 3 );
			expect( onChange ).toHaveBeenLastCalledWith( '#064121' );

			// Set the color externally. All inputs should update to match the H/S/L
			// value of the new color.
			const setColorButton = screen.getByRole( 'button', {
				name: /set color/i,
			} );
			await userEvent.click( setColorButton );

			expect( hueSlider ).toHaveValue( '208' );
			expect( hueNumberInput ).toHaveValue( 208 );
			expect( saturationSlider ).toHaveValue( '44' );
			expect( saturationNumberInput ).toHaveValue( 44 );
			expect( lightnessSlider ).toHaveValue( '52' );
			expect( lightnessNumberInput ).toHaveValue( 52 );
		} );

		it( 'should preserve hue and saturation when lightness is set to 0 (black)', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#2ad5d5" // hsl(180, 67%, 50%)
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const hueSliders = screen.getAllByRole( 'slider', {
				name: 'Hue (HSL H value)',
			} );
			const hueSlider = hueSliders.at( -1 )!;
			const saturationSlider = screen.getByRole( 'slider', {
				name: 'Saturation',
			} );
			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			const hueNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Hue (HSL H value)',
			} );
			const saturationNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Saturation',
			} );

			// Verify initial values
			expect( hueSlider ).toHaveValue( '180' );
			expect( saturationSlider ).toHaveValue( '67' );

			// Set lightness to 0 (black)
			await userEvent.fill( lightnessSlider, '0' );

			await waitFor( () => expect( lightnessSlider ).toHaveValue( '0' ) );

			// Hue and saturation should be preserved
			expect( hueSlider ).toHaveValue( '180' );
			expect( saturationSlider ).toHaveValue( '67' );
			expect( hueNumberInput ).toHaveValue( 180 );
			expect( saturationNumberInput ).toHaveValue( 67 );
			expect( onChange ).toHaveBeenLastCalledWith( '#000000' );
		} );

		it.each( [
			[ 'black', 0 ],
			[ 'white', 100 ],
		] )(
			'should allow saturation 50→0 at %s without firing onChange',
			async ( _label, lightness ) => {
				const onChange = vi.fn();

				await render(
					<ControlledColorPicker
						onChange={ onChange }
						enableAlpha={ false }
						initialColor="#000000"
					/>
				);

				const user = userEvent.setup();
				await user.click(
					screen.getByRole( 'combobox', { name: 'Color format' } )
				);
				await user.click(
					screen.getByRole( 'option', { name: 'HSL' } )
				);

				const hueSlider = screen
					.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
					.at( -1 )!;
				const saturationSlider = screen.getByRole( 'slider', {
					name: 'Saturation',
				} );
				const lightnessSlider = screen.getByRole( 'slider', {
					name: 'Lightness',
				} );
				const saturationNumberInput = screen.getByRole( 'spinbutton', {
					name: 'Saturation',
				} );

				// Build hsl(200, 50%, lightness%) via HSL controls.
				await userEvent.fill( hueSlider, '200' );
				await userEvent.fill( saturationSlider, '50' );
				await userEvent.fill( lightnessSlider, String( lightness ) );
				await waitFor( () =>
					expect( lightnessSlider ).toHaveValue( String( lightness ) )
				);

				expect( saturationSlider ).toHaveValue( '50' );
				expect( saturationNumberInput ).toHaveValue( 50 );
				onChange.mockClear();

				await userEvent.fill( saturationSlider, '0' );

				expect( saturationSlider ).toHaveValue( '0' );
				expect( saturationNumberInput ).toHaveValue( 0 );
				expect( onChange ).not.toHaveBeenCalled();
			}
		);

		it( 'should fire onChange once per real color change in controlled mode', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#2ad5d5" // hsl(180, 67%, 50%)
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );

			await userEvent.fill( lightnessSlider, '40' );
			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '40' )
			);
			expect( onChange ).toHaveBeenCalledTimes( 1 );

			await userEvent.fill( lightnessSlider, '30' );
			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '30' )
			);
			expect( onChange ).toHaveBeenCalledTimes( 2 );

			await userEvent.fill( lightnessSlider, '0' );
			await waitFor( () => expect( lightnessSlider ).toHaveValue( '0' ) );
			expect( onChange ).toHaveBeenCalledTimes( 3 );
			onChange.mockClear();

			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '90' );
			expect( onChange ).not.toHaveBeenCalled();
		} );

		it( 'should not change the RGB values when only the alpha slider moves', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha
					initialColor="#f66e04" // rgb(246, 110, 4)
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'RGB' } ) );

			// The alpha slider of the visual picker.
			const alphaSlider = screen
				.getAllByRole( 'slider', { name: 'Alpha' } )
				.at( -1 )!;
			alphaSlider.focus();
			await user.keyboard( '{ArrowLeft}' );

			await waitFor( () => expect( onChange ).toHaveBeenCalled() );
			expect(
				screen.getByRole( 'spinbutton', { name: 'Red' } )
			).toHaveValue( 246 );
			expect(
				screen.getByRole( 'spinbutton', { name: 'Green' } )
			).toHaveValue( 110 );
			expect(
				screen.getByRole( 'spinbutton', { name: 'Blue' } )
			).toHaveValue( 4 );
		} );

		it( 'should not change the RGB values of a gray with a retained hue when only the alpha slider moves', async () => {
			const user = userEvent.setup();

			await render(
				<ControlledColorPicker
					enableAlpha
					initialColor="#f66e04" // hsl(26, 97%, 49%)
				/>
			);

			// Enter a gray, which keeps the hue of the previous color.
			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'Hex' } ) );
			const hexInput = screen.getByRole( 'textbox' );
			await userEvent.fill( hexInput, 'eeeeee' );
			await waitFor( () => expect( hexInput ).toHaveValue( 'eeeeee' ) );

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'RGB' } ) );

			const alphaSlider = screen
				.getAllByRole( 'slider', { name: 'Alpha' } )
				.at( -1 )!;
			alphaSlider.focus();
			await user.keyboard( '{ArrowLeft}' );

			await waitFor( () =>
				expect(
					screen.getByRole( 'spinbutton', {
						name: 'Alpha (RGB A value)',
					} )
				).toHaveValue( 95 )
			);
			for ( const name of [ 'Red', 'Green', 'Blue' ] ) {
				expect(
					screen.getByRole( 'spinbutton', { name } )
				).toHaveValue( 238 );
			}
		} );

		it( 'should reset saturation to 0 when a mid-gray is entered via hex input', async () => {
			const user = userEvent.setup();

			await render(
				<ControlledColorPicker
					enableAlpha={ false }
					initialColor="#2ad5d5" // hsl(180, 67%, 50%)
				/>
			);

			// Start in hex mode and enter a mid-gray.
			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'Hex' } ) );
			const hexInput = screen.getByRole( 'textbox' );
			await userEvent.fill( hexInput, '808080' );
			await waitFor( () => expect( hexInput ).toHaveValue( '808080' ) );

			// Switch to HSL to inspect the values.
			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const saturationSlider = screen.getByRole( 'slider', {
				name: 'Saturation',
			} );
			const saturationNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Saturation',
			} );

			// #808080 is hsl(0, 0%, 50%) — a pure mid-gray.
			// Saturation must be 0, not the stale value from the
			// previous chromatic color.
			await waitFor( () =>
				expect( saturationSlider ).toHaveValue( '0' )
			);
			expect( saturationNumberInput ).toHaveValue( 0 );
		} );

		it( 'should preserve hue when saturation is set to 0', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#ff0000" // hsl(0, 100%, 50%) - pure red
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const hueSliders = screen.getAllByRole( 'slider', {
				name: 'Hue (HSL H value)',
			} );
			const hueSlider = hueSliders.at( -1 )!;
			const saturationSlider = screen.getByRole( 'slider', {
				name: 'Saturation',
			} );
			const hueNumberInput = screen.getByRole( 'spinbutton', {
				name: 'Hue (HSL H value)',
			} );

			// Set a specific hue first
			await userEvent.fill( hueSlider, '200' );

			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			// Set saturation to 0 (grayscale)
			await userEvent.fill( saturationSlider, '0' );

			await waitFor( () =>
				expect( saturationSlider ).toHaveValue( '0' )
			);

			// Hue should be preserved even though color is now gray
			expect( hueSlider ).toHaveValue( '200' );
			expect( hueNumberInput ).toHaveValue( 200 );

			// Increase saturation again - hue should still be 200
			await userEvent.fill( saturationSlider, '50' );

			await waitFor( () =>
				expect( saturationSlider ).toHaveValue( '50' )
			);

			expect( hueSlider ).toHaveValue( '200' );
			expect( hueNumberInput ).toHaveValue( 200 );
		} );
		describe.each( [
			[ 'hue', 'Hue (HSL H value)', '#aad52a' ],
			[ 'saturation', 'Saturation', '#20dfdf' ],
			[ 'lightness', 'Lightness', '#95eaea' ],
		] )( 'HSL inputs', ( colorInput, inputLabel, expected ) => {
			it( `should fire onChange with the correct value when the ${ colorInput } value is updated`, async () => {
				const user = userEvent.setup();
				const onChange = vi.fn();
				const color = '#2ad5d5';

				await render(
					<ColorPicker
						onChange={ onChange }
						color={ color }
						enableAlpha={ false }
					/>
				);

				const formatSelector = screen.getByRole( 'combobox', {
					name: 'Color format',
				} );
				expect( formatSelector ).toBeVisible();

				await user.click( formatSelector );
				await user.click(
					screen.getByRole( 'option', { name: 'HSL' } )
				);

				const inputElement = screen.getByRole( 'spinbutton', {
					name: inputLabel,
				} );
				expect( inputElement ).toBeVisible();

				await user.clear( inputElement );
				await user.type( inputElement, '75' );

				expect( onChange ).toHaveBeenCalledTimes( 3 );
				expect( onChange ).toHaveBeenLastCalledWith( expected );
			} );
		} );
	} );

	describe( 'visual picker', () => {
		const pointAt = ( element: HTMLElement, x: number, y: number ) => {
			const bounds = element.getBoundingClientRect();
			expect( bounds.width ).toBeGreaterThan( 0 );
			expect( bounds.height ).toBeGreaterThan( 0 );
			return { x: bounds.width * x, y: bounds.height * y };
		};

		const dragToBlack = async ( element: HTMLElement ) => {
			// Black is at the bottom boundary, just outside the slider's hit area.
			// Release over the picker below it so native mouse movement reaches v = 0.
			// eslint-disable-next-line testing-library/no-node-access -- The picker background has no accessible role.
			const picker = element.closest< HTMLElement >( '.react-colorful' )!;
			const bounds = element.getBoundingClientRect();
			const pickerBounds = picker.getBoundingClientRect();
			await userEvent.dragAndDrop( element, picker, {
				sourcePosition: pointAt( element, 0.8, 0.5 ),
				targetPosition: {
					x: bounds.left - pickerBounds.left + bounds.width * 0.8,
					y: bounds.bottom - pickerBounds.top + 1,
				},
			} );
		};

		const getPointerPosition = ( pointer: HTMLElement ) => {
			const surface = pointer.offsetParent as HTMLElement;
			return {
				left: ( pointer.offsetLeft / surface.clientWidth ) * 100,
				top: ( pointer.offsetTop / surface.clientHeight ) * 100,
			};
		};

		const expectPointerPosition = (
			pointer: HTMLElement,
			expected: { left?: number; top?: number }
		) => {
			const position = getPointerPosition( pointer );
			if ( expected.left !== undefined ) {
				expect( position.left ).toBeCloseTo( expected.left );
			}
			if ( expected.top !== undefined ) {
				expect( position.top ).toBeCloseTo( expected.top );
			}
		};

		it( 'preserves saturation when keyboard-navigating to black in controlled mode', async () => {
			const onChange = vi.fn();

			// Saturated red with mid brightness — HSVA s stays high at black.
			const { container } = await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			const colorSlider = screen.getByRole( 'slider', { name: 'Color' } );
			// Pointer is a presentational sibling; no accessible role.
			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			expect( pointer ).toBeTruthy();

			const { left: leftBefore } = getPointerPosition( pointer );
			expect( leftBefore ).toBeGreaterThan( 50 );

			// From v≈80, 5% steps need at least 16 ArrowDown presses to reach black.
			colorSlider.focus();
			for ( let i = 0; i < 20; i++ ) {
				await userEvent.keyboard( '{ArrowDown}' );
			}

			expectPointerPosition( pointer, { top: 100, left: leftBefore } );
			expect( onChange ).toHaveBeenLastCalledWith( '#000000' );
		} );

		it( 'preserves saturation when pointer selects black in controlled mode', async () => {
			const onChange = vi.fn();

			const { container } = await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			const interactive = screen.getByRole( 'slider', { name: 'Color' } );
			// Pointer is a presentational sibling; no accessible role.
			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			expect( parseFloat( pointer.style.left ) ).toBeGreaterThan( 50 );

			// Exact black is on the lower boundary, outside the native hit area.
			// Supply that coordinate without movement to retain click-only coverage.
			const bounds = interactive.getBoundingClientRect();
			fireEvent.mouseDown( interactive, {
				clientX: bounds.left + bounds.width * 0.8,
				clientY: bounds.bottom,
				buttons: 1,
			} );
			fireEvent.mouseUp( interactive );

			expectPointerPosition( pointer, { top: 100 } );
			// Lossy HSVA→HSLA→HSVA sync would snap left to 0%.
			expect( getPointerPosition( pointer ).left ).toBeGreaterThan( 50 );
			expect( onChange ).toHaveBeenLastCalledWith( '#000000' );
		} );

		it( 'preserves saturation after a full pointer drag to black then HSL hue edit', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			const { container } = await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			const interactive = screen.getByRole( 'slider', { name: 'Color' } );
			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;

			await dragToBlack( interactive );

			expectPointerPosition( pointer, { top: 100 } );
			expect( getPointerPosition( pointer ).left ).toBeGreaterThan( 50 );
			expect( onChange ).toHaveBeenLastCalledWith( '#000000' );
			const { left: leftAfterDrag } = getPointerPosition( pointer );

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '200' );
			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			// Stale prevHslaRef would mistake the hue edit for a saturation
			// change and snap the pointer to left: 0%.
			expectPointerPosition( pointer, {
				top: 100,
				left: leftAfterDrag,
			} );
		} );

		it( 'places the pointer at s:0 when HSL lightness is set to white', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			const { container } = await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			await userEvent.fill( lightnessSlider, '100' );
			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '100' )
			);
			expect( onChange ).toHaveBeenLastCalledWith( '#ffffff' );

			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			// Only v:100,s:0 is white; a preserved chromatic s leaves the
			// pointer at top-right and makes the next key step jump to red.
			expectPointerPosition( pointer, { top: 0, left: 0 } );

			const colorSlider = screen.getByRole( 'slider', { name: 'Color' } );
			colorSlider.focus();
			await userEvent.keyboard( '{ArrowDown}' );

			expect( onChange ).not.toHaveBeenLastCalledWith( '#f50000' );
			expect( onChange ).not.toHaveBeenLastCalledWith( '#cc0000' );
		} );

		it( 'preserves visual saturation when HSL hue is edited at black', async () => {
			const user = userEvent.setup();

			const { container } = await render(
				<ControlledColorPicker
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			await userEvent.fill( lightnessSlider, '0' );
			await waitFor( () => expect( lightnessSlider ).toHaveValue( '0' ) );

			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			const { left: leftBefore } = getPointerPosition( pointer );
			expect( leftBefore ).toBeGreaterThan( 50 );
			expectPointerPosition( pointer, { top: 100 } );

			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '200' );
			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			expectPointerPosition( pointer, {
				top: 100,
				left: leftBefore,
			} );
		} );

		it( 'keeps the white visual coordinate at s:0 when HSL hue is edited', async () => {
			const user = userEvent.setup();

			const { container } = await render(
				<ControlledColorPicker
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			await userEvent.fill( lightnessSlider, '100' );
			await waitFor( () =>
				expect( lightnessSlider ).toHaveValue( '100' )
			);

			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			expectPointerPosition( pointer, { top: 0, left: 0 } );

			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '200' );
			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			expectPointerPosition( pointer, { top: 0, left: 0 } );
		} );

		it( 'uses the HSL hue when leaving white through the visual surface', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );
			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			await userEvent.fill( lightnessSlider, '100' );

			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '200' );
			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			const colorSlider = screen.getByRole( 'slider', { name: 'Color' } );
			onChange.mockClear();
			await userEvent.click( colorSlider, {
				position: pointAt( colorSlider, 0.5, 0 ),
			} );

			expect( onChange ).toHaveBeenLastCalledWith( '#80d4ff' );
		} );

		it( 'uses the HSL hue when leaving a mid-gray through the visual surface', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha={ false }
					initialColor="#808080"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );
			const hueSlider = screen
				.getAllByRole( 'slider', { name: 'Hue (HSL H value)' } )
				.at( -1 )!;
			await userEvent.fill( hueSlider, '200' );
			await waitFor( () => expect( hueSlider ).toHaveValue( '200' ) );

			const colorSlider = screen.getByRole( 'slider', { name: 'Color' } );
			onChange.mockClear();
			await userEvent.click( colorSlider, {
				position: pointAt( colorSlider, 0.5, 0.5 ),
			} );

			expect( onChange ).toHaveBeenLastCalledWith( '#416c81' );
		} );

		it( 'updates visual saturation when HSL saturation is edited at black', async () => {
			const user = userEvent.setup();

			const { container } = await render(
				<ControlledColorPicker
					enableAlpha={ false }
					initialColor="#cc0000"
				/>
			);

			await user.click(
				screen.getByRole( 'combobox', { name: 'Color format' } )
			);
			await user.click( screen.getByRole( 'option', { name: 'HSL' } ) );

			const lightnessSlider = screen.getByRole( 'slider', {
				name: 'Lightness',
			} );
			await userEvent.fill( lightnessSlider, '0' );
			await waitFor( () => expect( lightnessSlider ).toHaveValue( '0' ) );

			// eslint-disable-next-line testing-library/no-node-access
			const pointer = container.querySelector(
				'.react-colorful__saturation-pointer'
			) as HTMLElement;
			expectPointerPosition( pointer, { top: 100 } );
			expect( getPointerPosition( pointer ).left ).toBeGreaterThan( 50 );

			const saturationSlider = screen.getByRole( 'slider', {
				name: 'Saturation',
			} );
			await userEvent.fill( saturationSlider, '25' );
			await waitFor( () =>
				expect( saturationSlider ).toHaveValue( '25' )
			);

			expectPointerPosition( pointer, { top: 100, left: 25 } );
		} );
	} );

	describe.each( [
		[ 'hsl', 'HSL' ],
		[ 'rgb', 'RGB' ],
	] as const )( 'Alpha-enabled %s format', ( _format, formatLabel ) => {
		it( `should update alpha correctly when ${ formatLabel } format is selected`, async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<ControlledColorPicker
					onChange={ onChange }
					enableAlpha
					initialColor="#ffffff80"
				/>
			);

			const formatSelector = screen.getByRole( 'combobox', {
				name: 'Color format',
			} );
			expect( formatSelector ).toBeVisible();
			await user.click( formatSelector );
			await user.click(
				screen.getByRole( 'option', { name: formatLabel } )
			);

			const alphaInput = screen.getByRole( 'spinbutton', {
				name: `Alpha (${ formatLabel } A value)`,
			} );
			expect( alphaInput ).toBeVisible();

			const alphaSlider = screen.getByRole( 'slider', {
				name: `Alpha (${ formatLabel } A value)`,
			} );

			expect( alphaSlider ).toHaveValue( '50' );
			expect( alphaInput ).toHaveValue( 50 );

			expect( onChange ).not.toHaveBeenCalled();

			// Test pattern 1: Update the slider
			await userEvent.fill( alphaSlider, '75' );

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

			expect( onChange ).toHaveBeenLastCalledWith( '#ffffffbf' );
			expect( alphaInput ).toHaveValue( 75 );
			expect( alphaSlider ).toHaveValue( '75' );

			onChange.mockClear();

			// Test pattern 2: Update the alphaInput one digit at a time.
			await user.clear( alphaInput );
			expect( onChange ).toHaveBeenCalledTimes( 1 );

			await user.keyboard( '7' );
			expect( onChange ).toHaveBeenCalledTimes( 2 );
			expect( onChange ).toHaveBeenNthCalledWith( 2, '#ffffff12' );

			await user.keyboard( '5' );

			expect( onChange ).toHaveBeenCalledTimes( 3 );
			expect( onChange ).toHaveBeenNthCalledWith( 3, '#ffffffbf' );
			await waitFor( () => {
				expect( alphaSlider ).toHaveValue( '75' );
				expect( alphaInput ).toHaveValue( 75 );
			} );
		} );
	} );

	describe( 'copy button', () => {
		it( 'copies the color in the copy format and announces it', async () => {
			const user = userEvent.setup();
			const writeText = vi
				.spyOn( navigator.clipboard, 'writeText' )
				.mockResolvedValue();

			await render( <ColorPicker color="#ff0000" copyFormat="rgb" /> );

			const copyButton = screen.getByRole( 'button', { name: 'Copy' } );
			await user.click( copyButton );

			expect( writeText ).toHaveBeenCalledWith( 'rgb(255, 0, 0)' );
			await waitFor( () =>
				expect( speak ).toHaveBeenCalledWith( 'Copied to clipboard' )
			);
			expect( copyButton ).toHaveAccessibleName( 'Copy' );
			expect( copyButton ).toHaveFocus();
		} );

		it( 'clears the copy feedback when the color changes', async () => {
			const user = userEvent.setup();
			vi.spyOn( navigator.clipboard, 'writeText' ).mockResolvedValue();

			await render( <ColorPicker defaultValue="#ffffff" /> );

			const copyButton = screen.getByRole( 'button', { name: 'Copy' } );
			const idleIcon = copyButton.innerHTML;
			await user.click( copyButton );
			await waitFor( () =>
				expect( copyButton.innerHTML ).not.toBe( idleIcon )
			);

			const hexInput = screen.getByRole( 'textbox' );
			await user.clear( hexInput );
			await user.type( hexInput, 'ff0000' );

			expect( copyButton.innerHTML ).toBe( idleIcon );
		} );

		it( 'announces a copy that failed', async () => {
			const user = userEvent.setup();
			vi.spyOn( navigator.clipboard, 'writeText' ).mockRejectedValue(
				new Error( 'Not allowed' )
			);

			await render( <ColorPicker color="#ff0000" /> );

			await user.click( screen.getByRole( 'button', { name: 'Copy' } ) );

			await waitFor( () =>
				expect( speak ).toHaveBeenCalledWith(
					"Couldn't copy to clipboard."
				)
			);
			expect( speak ).not.toHaveBeenCalledWith( 'Copied to clipboard' );
		} );
	} );
} );
