import { describe, expect, it, test, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import { act, screen, waitFor, within } from '@testing-library/react';
import { render } from 'vitest-browser-react';
import { useState } from '@wordpress/element';
import PaletteEdit, {
	getNameAndSlugForPosition,
	deduplicateElementSlugs,
} from '..';
import Modal from '../../modal';
import type { Color, PaletteElement } from '../types';

const noop = () => {};

function getCompatibilityOverlaySlot() {
	return document.querySelector< HTMLDivElement >(
		'[data-wp-compat-overlay-slot]'
	);
}

async function clearInput( input: HTMLInputElement ) {
	await userEvent.clear( input );
}

describe( 'getNameAndSlugForPosition', () => {
	test( 'should return 1 by default', () => {
		const slugPrefix = 'test-';
		const elements: PaletteElement[] = [];

		expect( getNameAndSlugForPosition( elements, slugPrefix ) ).toEqual( {
			name: 'Color 1',
			slug: 'test-color-1',
		} );
	} );

	test( 'should return a new color name and slug with an incremented slug id', () => {
		const slugPrefix = 'test-';
		const elements = [
			{
				slug: 'test-color-1',
				color: '#ffffff',
				name: 'Test Color 1',
			},
		];

		expect( getNameAndSlugForPosition( elements, slugPrefix ) ).toEqual( {
			name: 'Color 2',
			slug: 'test-color-2',
		} );
	} );

	test( 'should ignore user-defined color name and slug', () => {
		const slugPrefix = 'test-';
		const elements = [
			{
				slug: 'a-sweet-color-2',
				color: '#ffffff',
				name: 'Test Color 1',
			},
		];

		expect( getNameAndSlugForPosition( elements, slugPrefix ) ).toEqual( {
			name: 'Color 1',
			slug: 'test-color-1',
		} );
	} );

	test( 'should return a new color name and slug with an incremented slug id one higher than the current highest', () => {
		const slugPrefix = 'test-';
		const elements = [
			{
				slug: 'test-color-1',
				color: '#ffffff',
				name: 'Test Color 1',
			},
			{
				slug: 'test-color-2',
				color: '#1a4548',
				name: 'Test Color 2',
			},
			{
				slug: 'test-color-150',
				color: '#f6f6f6',
				name: 'Test Color 150',
			},
			{
				slug: 'a-sweet-color-100',
				color: '#ffe2c7',
				name: 'A Sweet Color 100',
			},
		];

		expect( getNameAndSlugForPosition( elements, slugPrefix ) ).toEqual( {
			name: 'Color 151',
			slug: 'test-color-151',
		} );
	} );

	test( 'should return a duotone name and slug for the duotone variant', () => {
		const slugPrefix = 'custom-';
		const elements: PaletteElement[] = [];

		expect(
			getNameAndSlugForPosition( elements, slugPrefix, 'duotone' )
		).toEqual( {
			name: 'Duotone 1',
			slug: 'custom-duotone-1',
		} );
	} );

	test( 'should increment the duotone slug id independently of colors', () => {
		const slugPrefix = 'custom-';
		const elements = [
			{
				slug: 'custom-duotone-1',
				colors: [ '#000000', '#ffffff' ],
				name: 'Duotone 1',
			},
			{
				slug: 'custom-duotone-4',
				colors: [ '#8c00b7', '#fcff41' ],
				name: 'Duotone 4',
			},
			// A color preset sharing the prefix must not affect the count.
			{
				slug: 'custom-color-99',
				color: '#ffffff',
				name: 'Color 99',
			},
		];

		expect(
			getNameAndSlugForPosition( elements, slugPrefix, 'duotone' )
		).toEqual( {
			name: 'Duotone 5',
			slug: 'custom-duotone-5',
		} );
	} );
} );

describe( 'deduplicateElementSlugs', () => {
	it( 'handles an empty palette', () => {
		expect( deduplicateElementSlugs( [] ) ).toEqual( [] );
	} );

	it( 'should not change the slugs if they are unique', () => {
		const elements: PaletteElement[] = [
			{
				slug: 'test-color-1',
				color: '#ffffff',
				name: 'Test Color 1',
			},
			{
				slug: 'test-color-2',
				color: '#1a4548',
				name: 'Test Color 2',
			},
		];

		expect( deduplicateElementSlugs( elements ) ).toEqual( elements );
	} );
	it( 'should change the slugs if they are not unique', () => {
		const elements: PaletteElement[] = [
			{
				slug: 'test-color-1',
				color: '#ffffff',
				name: 'Test Color 1',
			},
			{
				slug: 'test-color-1',
				color: '#1a4548',
				name: 'Test Color 2',
			},
		];

		expect( deduplicateElementSlugs( elements ) ).toEqual( [
			{
				slug: 'test-color-1',
				color: '#ffffff',
				name: 'Test Color 1',
			},
			{
				slug: 'test-color-1-1',
				color: '#1a4548',
				name: 'Test Color 2',
			},
		] );
	} );

	it.each( [
		{
			slugs: [ 'red', 'red', 'red-1' ],
			expected: [ 'red', 'red-2', 'red-1' ],
		},
		{
			slugs: [ 'red-1', 'red', 'red' ],
			expected: [ 'red-1', 'red', 'red-2' ],
		},
		{
			slugs: [ 'red', 'red', 'red', 'red-1', 'red-3' ],
			expected: [ 'red', 'red-2', 'red-4', 'red-1', 'red-3' ],
		},
		{
			slugs: [ 'red', 'red-1', 'red-1', 'red-1-1' ],
			expected: [ 'red', 'red-1', 'red-1-2', 'red-1-1' ],
		},
		{
			slugs: [
				'constructor',
				'constructor',
				'constructor-1',
				'__proto__',
				'__proto__',
			],
			expected: [
				'constructor',
				'constructor-2',
				'constructor-1',
				'__proto__',
				'__proto__-1',
			],
		},
	] )(
		'avoids existing slug collisions for $slugs',
		( { slugs, expected } ) => {
			const elements = slugs.map( ( slug, index ) =>
				Object.freeze( {
					slug,
					color: '#123456',
					name: `Color ${ index + 1 }`,
				} )
			);
			const actual = deduplicateElementSlugs( elements );

			expect( actual ).toEqual(
				elements.map( ( element, index ) => ( {
					...element,
					slug: expected[ index ],
				} ) )
			);
			expect( elements.map( ( { slug } ) => slug ) ).toEqual( slugs );
			expect( deduplicateElementSlugs( actual ) ).toEqual( actual );
		}
	);
} );

describe( 'PaletteEdit', () => {
	const defaultProps = {
		paletteLabel: 'Test label',
		slugPrefix: '',
		onChange: noop,
	};

	const colors = [
		{ color: '#1a4548', name: 'Primary', slug: 'primary' },
		{ color: '#0000ff', name: 'Secondary', slug: 'secondary' },
	];

	const gradients = [
		{
			gradient:
				'linear-gradient(135deg,rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%)',
			name: 'Pale ocean',
			slug: 'pale-ocean',
		},
		{
			gradient:
				'linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%)',
			name: 'Midnight',
			slug: 'midnight',
		},
	];

	const duotones = [
		{
			colors: [ '#8c00b7', '#fcff41' ],
			name: 'Purple and yellow',
			slug: 'purple-yellow',
		},
		{
			colors: [ '#000097', '#ff4747' ],
			name: 'Blue and red',
			slug: 'blue-red',
		},
	];

	it( 'preserves existing slugs while deduplicating an edited palette', async () => {
		const initialColors: Color[] = [
			{ slug: 'red', color: '#ff0000', name: 'First red' },
			{ slug: 'red', color: '#ee0000', name: 'Duplicate red' },
			{ slug: 'red-1', color: '#dd0000', name: 'Existing suffix' },
		];
		const onChange = vi.fn();

		function ControlledPalette() {
			const [ value, setValue ] = useState( initialColors.slice( 0, 1 ) );
			return (
				<>
					<button
						type="button"
						onClick={ () => setValue( initialColors ) }
					>
						Load palette
					</button>
					<PaletteEdit
						{ ...defaultProps }
						colors={ value }
						onChange={ ( nextColors ) => {
							onChange( nextColors );
							setValue( nextColors ?? [] );
						} }
					/>
				</>
			);
		}

		await render( <ControlledPalette /> );
		await userEvent.click(
			screen.getByRole( 'button', { name: 'Color options' } )
		);
		await userEvent.click(
			await screen.findByRole( 'menuitem', { name: 'Show details' } )
		);
		// Load the duplicate definitions in details view, where items use their
		// position as the key rather than the currently duplicated slug.
		await userEvent.click(
			screen.getByRole( 'button', { name: 'Load palette' } )
		);

		const nameInputs = screen.getAllByRole( 'textbox', {
			name: 'Color name',
		} );
		await userEvent.fill( nameInputs[ 1 ], 'Edited duplicate' );

		const expected = [
			initialColors[ 0 ],
			{ ...initialColors[ 1 ], slug: 'red-2', name: 'Edited duplicate' },
			initialColors[ 2 ],
		];
		await waitFor( () =>
			expect( onChange ).toHaveBeenLastCalledWith( expected )
		);

		await userEvent.fill( nameInputs[ 2 ], 'Preserved preset' );
		await waitFor( () =>
			expect( onChange ).toHaveBeenLastCalledWith( [
				expected[ 0 ],
				expected[ 1 ],
				{ ...expected[ 2 ], name: 'Preserved preset' },
			] )
		);
		expect( initialColors.map( ( { slug } ) => slug ) ).toEqual( [
			'red',
			'red',
			'red-1',
		] );
	} );

	it( 'shows heading label', async () => {
		await render( <PaletteEdit { ...defaultProps } colors={ colors } /> );

		const paletteLabel = screen.getByRole( 'heading', {
			level: 2,
			name: 'Test label',
		} );

		expect( paletteLabel ).toBeVisible();
	} );

	it( 'shows heading label with custom heading level', async () => {
		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				paletteLabelHeadingLevel={ 5 }
			/>
		);

		expect(
			screen.getByRole( 'heading', {
				level: 5,
				name: 'Test label',
			} )
		).toBeVisible();
	} );

	it.each( [
		{
			name: 'color',
			props: { colors },
			buttonName: 'Primary',
			dialogName: 'Edit: Primary',
			editorRole: 'textbox' as const,
			editorName: 'Hex color',
		},
		{
			name: 'gradient',
			props: { gradients },
			buttonName: 'Gradient: Pale ocean',
			dialogName: 'Edit: Pale ocean',
			editorRole: 'combobox' as const,
			editorName: 'Type',
		},
		{
			name: 'duotone',
			props: { duotones, colorPalette: colors },
			buttonName: 'Duotone: Purple and yellow',
			dialogName: 'Edit: Purple and yellow',
			editorRole: 'button' as const,
			editorName: /Shadows/,
		},
	] )(
		'shows $name swatches as named command buttons that open the editor',
		async ( { props, buttonName, dialogName, editorRole, editorName } ) => {
			await render( <PaletteEdit { ...defaultProps } { ...props } /> );

			const group = screen.getByRole( 'group', { name: 'Test label' } );
			const swatch = within( group ).getByRole( 'button', {
				name: buttonName,
			} );
			expect(
				within( group ).queryByRole( 'listbox' )
			).not.toBeInTheDocument();
			expect(
				within( group ).queryByRole( 'option' )
			).not.toBeInTheDocument();
			expect( swatch.tagName ).toBe( 'BUTTON' );
			expect( swatch ).not.toHaveAttribute( 'aria-pressed' );

			await userEvent.click( swatch );
			await waitFor( () => {
				expect(
					screen.getByRole( 'dialog', { name: dialogName } )
				).toBeVisible();
				expect(
					screen.getByRole( editorRole, { name: editorName } )
				).toBeVisible();
			} );
		}
	);

	it.each( [
		{ view: 'swatches', action: 'Close' },
		{ view: 'details', action: 'Close' },
		{ view: 'swatches', action: 'Escape' },
		{ view: 'details', action: 'Escape' },
	] )(
		'retains live edits and returns focus when dismissed with $action in $view',
		async ( { view, action } ) => {
			const onChange = vi.fn();
			function ControlledPalette() {
				const [ value, setValue ] = useState< Color[] >( colors );
				return (
					<PaletteEdit
						{ ...defaultProps }
						colors={ value }
						onChange={ ( nextColors ) => {
							onChange( nextColors );
							setValue( nextColors ?? [] );
						} }
					/>
				);
			}
			await render( <ControlledPalette /> );
			if ( view === 'details' ) {
				await userEvent.click(
					screen.getByRole( 'button', { name: 'Color options' } )
				);
				await userEvent.click(
					await screen.findByRole( 'menuitem', {
						name: 'Show details',
					} )
				);
			}
			const swatch = screen.getByRole( 'button', {
				name: view === 'details' ? 'Edit: Primary' : 'Primary',
			} );
			swatch.focus();
			await userEvent.keyboard( '{Enter}' );
			const dialog = await screen.findByRole( 'dialog', {
				name: 'Edit: Primary',
			} );
			const closeButtons = within( dialog ).getAllByRole( 'button', {
				name: 'Close',
			} );
			expect( closeButtons ).toHaveLength( 2 );
			for ( const button of closeButtons ) {
				expect( button ).toHaveAttribute( 'tabindex', '-1' );
				const { width, height } = button.getBoundingClientRect();
				expect( width ).toBeLessThanOrEqual( 1 );
				expect( height ).toBeLessThanOrEqual( 1 );
			}
			const input = within( dialog ).getByRole( 'textbox', {
				name: 'Hex color',
			} );
			await userEvent.fill( input, 'ff0000' );
			await waitFor( () =>
				expect( onChange ).toHaveBeenCalledWith( [
					{ ...colors[ 0 ], color: '#ff0000' },
					colors[ 1 ],
				] )
			);
			if ( action === 'Close' ) {
				// Activate as assistive technology does, without moving the
				// pointer to a control that is intentionally visually hidden.
				act( () => closeButtons[ view === 'details' ? 1 : 0 ].click() );
			} else {
				await userEvent.keyboard( '{Escape}' );
			}
			await waitFor( () => {
				expect( dialog ).not.toBeInTheDocument();
				expect( swatch ).toHaveFocus();
			} );
			await userEvent.click( swatch );
			expect(
				await screen.findByRole( 'textbox', { name: 'Hex color' } )
			).toHaveValue( 'FF0000' );
		}
	);

	it( 'tabs between command swatches and opens one with Space', async () => {
		await render( <PaletteEdit { ...defaultProps } colors={ colors } /> );

		const primary = screen.getByRole( 'button', { name: 'Primary' } );
		const secondary = screen.getByRole( 'button', { name: 'Secondary' } );
		primary.focus();

		await userEvent.tab();
		expect( secondary ).toHaveFocus();

		await userEvent.keyboard( '{Space}' );
		await waitFor( () => {
			expect(
				screen.getByRole( 'textbox', { name: 'Hex color' } )
			).toBeVisible();
		} );
	} );

	it( 'opens a command swatch with Enter', async () => {
		await render( <PaletteEdit { ...defaultProps } colors={ colors } /> );

		screen.getByRole( 'button', { name: 'Primary' } ).focus();
		await userEvent.keyboard( '{Enter}' );

		await waitFor( () => {
			expect(
				screen.getByRole( 'textbox', { name: 'Hex color' } )
			).toBeVisible();
		} );
	} );

	it( 'shows empty message', async () => {
		await render(
			<PaletteEdit
				{ ...defaultProps }
				emptyMessage="Test empty message"
			/>
		);

		expect( screen.getByText( 'Test empty message' ) ).toBeVisible();
	} );

	it( 'shows an option to remove all colors', async () => {
		await render( <PaletteEdit { ...defaultProps } colors={ colors } /> );

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Color options',
			} )
		);

		await waitFor( () => {
			expect(
				screen.getByRole( 'menuitem', {
					name: 'Remove all colors',
				} )
			).toBeVisible();
		} );
	} );

	it( 'shows a reset option when the `canReset` prop is enabled', async () => {
		await render(
			<PaletteEdit { ...defaultProps } colors={ colors } canReset />
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Color options',
			} )
		);
		await waitFor( () => {
			expect(
				screen.getByRole( 'menuitem', {
					name: 'Reset colors',
				} )
			).toBeVisible();
		} );
	} );

	it( 'does not show a reset colors option when `canReset` is disabled', async () => {
		await render( <PaletteEdit { ...defaultProps } colors={ colors } /> );

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Color options',
			} )
		);
		expect(
			screen.queryByRole( 'menuitem', {
				name: 'Reset colors',
			} )
		).not.toBeInTheDocument();
	} );

	it( 'moves through palette options with arrow keys and activates a menu item with Enter', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				onChange={ onChange }
			/>
		);

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

		const showDetails = await screen.findByRole( 'menuitem', {
			name: 'Show details',
		} );
		const removeAll = screen.getByRole( 'menuitem', {
			name: 'Remove all colors',
		} );

		expect( showDetails ).toHaveFocus();
		await userEvent.keyboard( '{ArrowDown}' );
		expect( removeAll ).toHaveFocus();

		await userEvent.keyboard( '{Enter}' );
		expect( onChange ).toHaveBeenCalledWith();
		expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument();
	} );

	it( 'keeps the options menu usable above a Components modal for direct package consumers', async () => {
		const compatibilityWindow = window as typeof window & {
			wp?: unknown;
			__wpUiCompatOverlaySlotEnabled?: boolean;
		};
		const hadWp = Object.hasOwn( compatibilityWindow, 'wp' );
		const hadOptIn = Object.hasOwn(
			compatibilityWindow,
			'__wpUiCompatOverlaySlotEnabled'
		);
		const originalWp = compatibilityWindow.wp;
		const originalOptIn =
			compatibilityWindow.__wpUiCompatOverlaySlotEnabled;
		const originalSlot = getCompatibilityOverlaySlot();
		delete compatibilityWindow.wp;
		delete compatibilityWindow.__wpUiCompatOverlaySlotEnabled;

		try {
			await render(
				<Modal title="Palette" onRequestClose={ noop }>
					<PaletteEdit { ...defaultProps } colors={ colors } />
				</Modal>
			);

			await userEvent.click(
				screen.getByRole( 'button', {
					name: 'Color options',
				} )
			);
			const menu = await screen.findByRole( 'menu' );
			const slot = getCompatibilityOverlaySlot();
			expect( slot ).toContainElement( menu );
			await waitFor( () => expect( menu ).toBeVisible() );

			await userEvent.click(
				within( menu ).getByRole( 'menuitem', {
					name: 'Show details',
				} )
			);
			expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument();
		} finally {
			if ( hadWp ) {
				compatibilityWindow.wp = originalWp;
			} else {
				delete compatibilityWindow.wp;
			}
			if ( hadOptIn ) {
				compatibilityWindow.__wpUiCompatOverlaySlotEnabled =
					originalOptIn;
			} else {
				delete compatibilityWindow.__wpUiCompatOverlaySlotEnabled;
			}
			const currentSlot = getCompatibilityOverlaySlot();
			if ( currentSlot !== originalSlot ) {
				currentSlot?.remove();
			}
		}
	} );

	it( 'calls the `onChange` with the new color appended', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add color',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...colors,
				{
					color: '#000',
					name: 'Color 1',
					slug: 'color-1',
				},
			] );
		} );
	} );

	it( 'calls the `onChange` with the new gradient appended', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				gradients={ gradients }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add gradient',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...gradients,
				{
					gradient:
						'linear-gradient(135deg, rgba(6, 147, 227, 1) 0%, rgb(155, 81, 224) 100%)',
					name: 'Color 1',
					slug: 'color-1',
				},
			] );
		} );
	} );

	it( 'calls the `onChange` with the new duotone appended, seeded from the color palette', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				colorPalette={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add duotone',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...duotones,
				{
					// The darkest and lightest colors of `colors`.
					colors: [ '#0000ff', '#1a4548' ],
					name: 'Duotone 1',
					slug: 'duotone-1',
				},
			] );
		} );
	} );

	it( 'ignores palette colors a duotone cannot be built from when adding one', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				colorPalette={ [
					...colors,
					// Twenty Twenty-Five ships a color like this. `colord`
					// cannot parse it and treats it as black, which would
					// otherwise win as the duotone's shadow color and produce a
					// duotone that cannot be rendered.
					{
						color: 'color-mix(in srgb, currentColor 20%, transparent)',
						name: 'Contrast overlay',
						slug: 'contrast-overlay',
					},
				] }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add duotone',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...duotones,
				{
					colors: [ '#0000ff', '#1a4548' ],
					name: 'Duotone 1',
					slug: 'duotone-1',
				},
			] );
		} );
	} );

	// The front end parses duotone colors with a PHP port of colord that only
	// accepts hex, `rgb()` and `hsl()`, so a named color saved as-is would
	// render in the editor and be dropped on the front end.
	it( 'normalizes palette colors to hex when adding a duotone', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				colorPalette={ [
					{ color: 'black', name: 'Black', slug: 'black' },
					{ color: 'white', name: 'White', slug: 'white' },
				] }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add duotone',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...duotones,
				{
					colors: [ '#000000', '#ffffff' ],
					name: 'Duotone 1',
					slug: 'duotone-1',
				},
			] );
		} );
	} );

	it( 'falls back to black and white when adding a duotone without a color palette', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Add duotone',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				...duotones,
				{
					colors: [ '#000', '#fff' ],
					name: 'Duotone 1',
					slug: 'duotone-1',
				},
			] );
		} );
	} );

	it( 'can not add new colors when `canOnlyChangeValues` is enabled', async () => {
		await render( <PaletteEdit { ...defaultProps } canOnlyChangeValues /> );

		expect(
			screen.queryByRole( 'button', {
				name: 'Add color',
			} )
		).not.toBeInTheDocument();
	} );

	it( 'can remove a color', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Color options',
			} )
		);
		await userEvent.click(
			screen.getByRole( 'menuitem', {
				name: 'Show details',
			} )
		);
		await userEvent.click(
			screen.getByRole( 'button', { name: 'Edit: Primary' } )
		);
		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Remove color: Primary',
			} )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [ colors[ 1 ] ] );
		} );
	} );

	it( 'can update palette name without changing its slug', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByRole( 'button', {
				name: 'Color options',
			} )
		);
		await userEvent.click(
			screen.getByRole( 'menuitem', {
				name: 'Show details',
			} )
		);
		await userEvent.click(
			screen.getByRole( 'button', { name: 'Edit: Primary' } )
		);
		const nameInput = screen.getByDisplayValue( 'Primary' );

		await clearInput( nameInput as HTMLInputElement );

		await userEvent.keyboard( 'Primary Updated' );

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				{
					...colors[ 0 ],
					name: 'Primary Updated',
				},
				colors[ 1 ],
			] );
		} );
	} );

	it( 'can update color palette value', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				colors={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click( screen.getByLabelText( 'Primary' ) );
		const hexInput = screen.getByRole( 'textbox', {
			name: 'Hex color',
		} );

		await clearInput( hexInput as HTMLInputElement );

		await userEvent.keyboard( '000000' );

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				{
					...colors[ 0 ],
					color: '#000000',
				},
				colors[ 1 ],
			] );
		} );
	} );

	it( 'can update gradient palette value', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				gradients={ gradients }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByLabelText( 'Gradient: Pale ocean' )
		);

		// Select radial gradient option
		await userEvent.click(
			screen.getByRole( 'combobox', { name: 'Type' } )
		);
		await userEvent.click(
			screen.getByRole( 'option', { name: 'Radial' } )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				{
					...gradients[ 0 ],
					gradient:
						'radial-gradient(rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%)',
				},
				gradients[ 1 ],
			] );
		} );
	} );

	it( 'can update duotone palette value', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				colorPalette={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByLabelText( 'Duotone: Blue and red' )
		);
		await userEvent.click(
			screen.getByRole( 'button', { name: /Shadows/ } )
		);
		await userEvent.click(
			screen.getByRole( 'option', { name: 'Primary' } )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				duotones[ 0 ],
				{
					...duotones[ 1 ],
					colors: [ '#1a4548', duotones[ 1 ].colors[ 1 ] ],
				},
			] );
		} );
	} );

	// The same filtering and normalization that applies when adding a duotone
	// has to apply when editing one, or the shadows and highlights picker can
	// offer a color the saved duotone cannot be built from.
	it( 'hides unusable colors and saves named ones as hex when editing a duotone', async () => {
		const onChange = vi.fn();

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ duotones }
				colorPalette={ [
					{
						color: 'black',
						name: 'Named black',
						slug: 'named-black',
					},
					{
						color: 'color-mix(in srgb, currentColor 20%, transparent)',
						name: 'Contrast overlay',
						slug: 'contrast-overlay',
					},
				] }
				onChange={ onChange }
			/>
		);

		await userEvent.click(
			screen.getByLabelText( 'Duotone: Blue and red' )
		);
		await userEvent.click(
			screen.getByRole( 'button', { name: /Shadows/ } )
		);

		// The unusable color must not be offered at all.
		expect(
			screen.queryByRole( 'option', { name: 'Contrast overlay' } )
		).not.toBeInTheDocument();

		await userEvent.click(
			screen.getByRole( 'option', { name: 'Named black' } )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				duotones[ 0 ],
				{
					...duotones[ 1 ],
					colors: [ '#000000', duotones[ 1 ].colors[ 1 ] ],
				},
			] );
		} );
	} );

	// Adding two duotones with the `+` button seeds both from the palette's
	// darkest and lightest colors, so duplicate values are the normal case
	// rather than an edge one. The duotone that was clicked has to be the one
	// that gets edited.
	it( 'updates the clicked duotone when two share the same colors', async () => {
		const onChange = vi.fn();
		const twins = [
			{ colors: [ '#000000', '#ffffff' ], name: 'First', slug: 'first' },
			{
				colors: [ '#000000', '#ffffff' ],
				name: 'Second',
				slug: 'second',
			},
		];

		await render(
			<PaletteEdit
				{ ...defaultProps }
				duotones={ twins }
				colorPalette={ colors }
				onChange={ onChange }
			/>
		);

		await userEvent.click( screen.getByLabelText( 'Duotone: Second' ) );
		await userEvent.click(
			screen.getByRole( 'button', { name: /Shadows/ } )
		);
		await userEvent.click(
			screen.getByRole( 'option', { name: 'Primary' } )
		);

		await waitFor( () => {
			expect( onChange ).toHaveBeenCalledWith( [
				twins[ 0 ],
				{ ...twins[ 1 ], colors: [ '#1a4548', '#ffffff' ] },
			] );
		} );
	} );
} );
