import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
	Button,
	ComboboxControl,
	Notice,
	Spinner,
	TabPanel,
	TextControl,
	ToggleControl,
} from '@wordpress/components';
import ColorControl from '@cliqui/admin/src/components/builder/ColorControl';
import MapField from '../../admin-common/src/fields/MapField';
import IconPickerField from '../../admin-common/src/fields/IconPickerField';
import BannerArt from '../../admin-common/src/BannerArt';
import SharedBannerLinks from '../../admin-common/src/BannerLinks';
import Onboarding from '../../admin-common/src/Onboarding';
import BannerBrand from './BannerBrand';
import Dashboard from './Dashboard';
import OnboardingGuide from './Guide';
import {
	TemplateEditor,
	SlugFieldsEditor,
} from './TemplateEditor';
import {
	DashboardIcon,
	SettingsIcon,
} from './icons';
import './style.scss';

const namespace = () =>
	window.CLIQTHEMES_UI?.app?.adminNamespace || 'cliq-store-locator/v1';

const settingsPath = () => `/${ namespace() }/admin/settings`;

const BannerLinks = () => (
	<SharedBannerLinks upgradeUrl="https://cliqthemes.com/store-locator" />
);

const NumberField = ( { label, value, onChange, min, max, help } ) => (
	<TextControl
		__nextHasNoMarginBottom
		label={ label }
		help={ help }
		type="number"
		min={ min }
		max={ max }
		value={ value ?? '' }
		onChange={ ( next ) => onChange( next === '' ? '' : Number( next ) ) }
	/>
);

// Swatches shown in the palette editor's picker — the accent of each built-in
// scheme preset (kept in sync with THEME_PRESETS below) plus a few neutrals, so
// a quick pick maps to a recognizable scheme colour. Custom hex is always
// available under the swatches.
const SCHEME_SWATCHES = [
	{ name: __( 'Indigo', 'cliq-store-locator' ), color: '#3858e9' },
	{ name: __( 'Ocean', 'cliq-store-locator' ), color: '#0284c7' },
	{ name: __( 'Forest', 'cliq-store-locator' ), color: '#047857' },
	{ name: __( 'Ember', 'cliq-store-locator' ), color: '#c2410c' },
	{ name: __( 'Midnight', 'cliq-store-locator' ), color: '#38bdf8' },
	{ name: __( 'Ink', 'cliq-store-locator' ), color: '#0f172a' },
	{ name: __( 'Slate', 'cliq-store-locator' ), color: '#475569' },
	{ name: __( 'White', 'cliq-store-locator' ), color: '#ffffff' },
];

// The palette editor uses the WP-native colour control, so it looks and behaves
// like the rest of the admin. Storage stays solid hex (sanitize_hex_color), so
// alpha is disabled; swatches are seeded from the built-in scheme presets above.
const ColorField = ( { label, value, onChange } ) => (
	<ColorControl
		label={ label }
		value={ value }
		onChange={ ( next ) => onChange( next || '' ) }
		colors={ SCHEME_SWATCHES }
		enableAlpha={ false }
	/>
);

const SelectControl = ( { onChange, ...props } ) => (
	<ComboboxControl
		__nextHasNoMarginBottom
		{ ...props }
		onChange={ ( value ) => {
			if ( value !== null && value !== undefined ) {
				onChange( value );
			}
		} }
	/>
);

const THEME_COLORS = [
	[ 'theme_primary', __( 'Primary', 'cliq-store-locator' ) ],
	[ 'theme_primary_strong', __( 'Primary hover', 'cliq-store-locator' ) ],
	[ 'theme_on_primary', __( 'Text on primary', 'cliq-store-locator' ) ],
	[ 'theme_canvas', __( 'Locator background', 'cliq-store-locator' ) ],
	[ 'theme_surface', __( 'Surface', 'cliq-store-locator' ) ],
	[ 'theme_text', __( 'Body text', 'cliq-store-locator' ) ],
	[ 'theme_heading', __( 'Headings', 'cliq-store-locator' ) ],
	[ 'theme_text_soft', __( 'Secondary text', 'cliq-store-locator' ) ],
	[ 'theme_label', __( 'Labels', 'cliq-store-locator' ) ],
	[ 'theme_muted', __( 'Muted text', 'cliq-store-locator' ) ],
	[ 'theme_faint', __( 'Faint text', 'cliq-store-locator' ) ],
	[ 'theme_border', __( 'Border', 'cliq-store-locator' ) ],
	[ 'theme_border_soft', __( 'Soft border', 'cliq-store-locator' ) ],
	[ 'theme_divider', __( 'Divider', 'cliq-store-locator' ) ],
	[ 'theme_danger', __( 'Error', 'cliq-store-locator' ) ],
	[ 'theme_danger_bg', __( 'Error background', 'cliq-store-locator' ) ],
];

const THEME_PRESETS = [
	{
		name: 'indigo',
		label: __( 'Indigo', 'cliq-store-locator' ),
		colors: {
			theme_primary: '#3858e9',
			theme_primary_strong: '#1d4ed8',
			theme_on_primary: '#ffffff',
			theme_canvas: '#f8fafc',
			theme_surface: '#ffffff',
			theme_text: '#1e293b',
			theme_heading: '#0f172a',
			theme_text_soft: '#334155',
			theme_label: '#475569',
			theme_muted: '#64748b',
			theme_faint: '#94a3b8',
			theme_border: '#d5d8dc',
			theme_border_soft: '#e2e8f0',
			theme_divider: '#f1f5f9',
			theme_danger: '#b91c1c',
			theme_danger_bg: '#fef2f2',
		},
	},
	{
		name: 'ocean',
		label: __( 'Ocean', 'cliq-store-locator' ),
		colors: {
			theme_primary: '#0284c7',
			theme_primary_strong: '#0369a1',
			theme_on_primary: '#ffffff',
			theme_canvas: '#f0f9ff',
			theme_surface: '#ffffff',
			theme_text: '#1e293b',
			theme_heading: '#0c4a6e',
			theme_text_soft: '#334155',
			theme_label: '#475569',
			theme_muted: '#64748b',
			theme_faint: '#94a3b8',
			theme_border: '#cbd5e1',
			theme_border_soft: '#e0f2fe',
			theme_divider: '#f0f9ff',
			theme_danger: '#be123c',
			theme_danger_bg: '#fff1f2',
		},
	},
	{
		name: 'forest',
		label: __( 'Forest', 'cliq-store-locator' ),
		colors: {
			theme_primary: '#047857',
			theme_primary_strong: '#065f46',
			theme_on_primary: '#ffffff',
			theme_canvas: '#f0fdf4',
			theme_surface: '#ffffff',
			theme_text: '#1f2937',
			theme_heading: '#064e3b',
			theme_text_soft: '#374151',
			theme_label: '#4b5563',
			theme_muted: '#6b7280',
			theme_faint: '#9ca3af',
			theme_border: '#d1d5db',
			theme_border_soft: '#d1fae5',
			theme_divider: '#ecfdf5',
			theme_danger: '#b91c1c',
			theme_danger_bg: '#fef2f2',
		},
	},
	{
		name: 'ember',
		label: __( 'Ember', 'cliq-store-locator' ),
		colors: {
			theme_primary: '#c2410c',
			theme_primary_strong: '#9a3412',
			theme_on_primary: '#ffffff',
			theme_canvas: '#fff7ed',
			theme_surface: '#fffbeb',
			theme_text: '#292524',
			theme_heading: '#431407',
			theme_text_soft: '#44403c',
			theme_label: '#57534e',
			theme_muted: '#78716c',
			theme_faint: '#a8a29e',
			theme_border: '#d6d3d1',
			theme_border_soft: '#fed7aa',
			theme_divider: '#ffedd5',
			theme_danger: '#b91c1c',
			theme_danger_bg: '#fef2f2',
		},
	},
	{
		name: 'midnight',
		label: __( 'Midnight', 'cliq-store-locator' ),
		colors: {
			theme_primary: '#38bdf8',
			theme_primary_strong: '#0ea5e9',
			theme_on_primary: '#082f49',
			theme_canvas: '#020617',
			theme_surface: '#0f172a',
			theme_text: '#e2e8f0',
			theme_heading: '#ffffff',
			theme_text_soft: '#cbd5e1',
			theme_label: '#e2e8f0',
			theme_muted: '#94a3b8',
			theme_faint: '#94a3b8',
			theme_border: '#475569',
			theme_border_soft: '#334155',
			theme_divider: '#1e293b',
			theme_danger: '#fda4af',
			theme_danger_bg: '#4c0519',
		},
	},
];

const ESSENTIAL_THEME_KEYS = new Set( [
	'theme_primary',
	'theme_primary_strong',
	'theme_on_primary',
	'theme_canvas',
	'theme_surface',
	'theme_text',
	'theme_heading',
] );

const contrastTextColor = ( hex = '' ) => {
	const value = String( hex ).replace( '#', '' );
	if ( ! /^[0-9a-f]{6}$/i.test( value ) ) {
		return '#0f172a';
	}
	const channels = [ 0, 2, 4 ].map( ( offset ) => {
		const channel = parseInt( value.slice( offset, offset + 2 ), 16 ) / 255;
		return channel <= 0.04045
			? channel / 12.92
			: ( ( channel + 0.055 ) / 1.055 ) ** 2.4;
	} );
	const luminance =
		0.2126 * channels[ 0 ] +
		0.7152 * channels[ 1 ] +
		0.0722 * channels[ 2 ];
	return luminance > 0.42 ? '#0f172a' : '#f8fafc';
};

const SETTINGS_TABS = [
	{
		name: 'appearance',
		title: __( 'Appearance', 'cliq-store-locator' ),
	},
	{
		name: 'theme',
		title: __( 'Theme', 'cliq-store-locator' ),
	},
	{
		name: 'template',
		title: __( 'Template', 'cliq-store-locator' ),
	},
	{
		name: 'map-search',
		title: __( 'Map & Search', 'cliq-store-locator' ),
	},
	{
		name: 'details',
		title: __( 'Details Page', 'cliq-store-locator' ),
	},
];

const TEMPLATE_TABS = [
	{
		name: 'card',
		title: __( 'Store List Card', 'cliq-store-locator' ),
	},
	{
		name: 'infobox',
		title: __( 'Map Infobox', 'cliq-store-locator' ),
	},
	{
		name: 'detail',
		title: __( 'Store Detail Card', 'cliq-store-locator' ),
	},
];

const SettingsScreen = () => {
	const [ values, setValues ] = useState( null );
	const [ defaults, setDefaults ] = useState( {} );
	const [ pages, setPages ] = useState( [] );
	const [ customFields, setCustomFields ] = useState( [] );
	const [ saving, setSaving ] = useState( false );
	const [ notice, setNotice ] = useState( null );

	useEffect( () => {
		let active = true;
		apiFetch( { path: settingsPath() } )
			.then( ( response ) => {
				if ( active ) {
					setValues( response?.settings || {} );
					setDefaults( response?.defaults || {} );
				}
			} )
			.catch( ( error ) => {
				if ( active ) {
					setValues( {} );
					setNotice( {
						status: 'error',
						message:
							error?.message ||
							__(
								'Settings could not be loaded.',
								'cliq-store-locator'
							),
					} );
				}
			} );
		apiFetch( {
			path: '/wp/v2/pages?per_page=100&status=publish&_fields=id,title',
		} )
			.then( ( response ) => {
				if ( active && Array.isArray( response ) ) {
					setPages( response );
				}
			} )
			.catch( () => {} );
		apiFetch( { path: `/${ namespace() }/admin/custom-fields` } )
			.then( ( response ) => {
				if ( active ) {
					setCustomFields(
						( response?.items || [] ).filter(
							( field ) =>
								( field.entity || 'store' ) === 'store' &&
								field.field_key
						)
					);
				}
			} )
			.catch( () => {} );
		return () => {
			active = false;
		};
	}, [] );

	const set = ( key, value ) =>
		setValues( ( current ) => ( {
			...( current || {} ),
			[ key ]: value,
		} ) );

	const applyTheme = ( colors, message ) => {
		setValues( ( current ) => ( {
			...( current || {} ),
			...colors,
		} ) );
		setNotice( {
			status: 'info',
			message,
		} );
	};

	const resetTheme = () => {
		const colors = Object.fromEntries(
			THEME_COLORS.map( ( [ key ] ) => [ key, defaults[ key ] ] ).filter(
				( [ , value ] ) => value
			)
		);
		applyTheme(
			colors,
			__(
				'Theme colors restored to their defaults. Save settings to apply them.',
				'cliq-store-locator'
			)
		);
	};

	const save = () => {
		setSaving( true );
		setNotice( null );
		apiFetch( { path: settingsPath(), method: 'POST', data: values } )
			.then( ( response ) => {
				setValues( response?.settings || values );
				setNotice( {
					status: 'success',
					message: __(
						'Locator settings saved.',
						'cliq-store-locator'
					),
				} );
			} )
			.catch( ( error ) =>
				setNotice( {
					status: 'error',
					message:
						error?.message ||
						__(
							'Settings could not be saved.',
							'cliq-store-locator'
						),
				} )
			)
			.finally( () => setSaving( false ) );
	};

	if ( values === null ) {
		return (
			<div className="cliqthemes-ui-loading">
				<Spinner />
			</div>
		);
	}

	return (
		<div className="cliq-sl-settings">
			{ notice && (
				<Notice
					status={ notice.status }
					onRemove={ () => setNotice( null ) }
				>
					{ notice.message }
				</Notice>
			) }

			<TabPanel
				className="cliq-sl-settings__tabs"
				tabs={ SETTINGS_TABS }
			>
				{ ( activeTab ) => (
					<div className="cliq-sl-settings__sections">
						{ activeTab.name === 'appearance' && (
							<section className="cliq-sl-settings__section">
								<header>
									<h2>
										{ __(
											'Locator appearance',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ __(
											'Colours, spacing, labels and map behaviour for the built-in layout.',
											'cliq-store-locator'
										) }
									</p>
								</header>
								<div className="cliq-sl-settings__grid">
									<SelectControl
										__nextHasNoMarginBottom
										label={ __(
											'Layout',
											'cliq-store-locator'
										) }
										value={
											values.locator_map_position || 'right'
										}
										options={ [
											{
												value: 'left',
												label: __(
													'Map left, stores right',
													'cliq-store-locator'
												),
											},
											{
												value: 'right',
												label: __(
													'Stores left, map right',
													'cliq-store-locator'
												),
											},
											{
												value: 'none',
												label: __(
													'Store list only (no map)',
													'cliq-store-locator'
												),
											},
										] }
										onChange={ ( value ) =>
											set( 'locator_map_position', value )
										}
									/>
									{ values.locator_map_position !== 'none' && (
										<SelectControl
											__nextHasNoMarginBottom
											label={ __(
												'Map / store width',
												'cliq-store-locator'
											) }
											value={ String(
												values.locator_map_columns ?? 7
											) }
											options={ [
												{
													value: '4',
													label: __(
														'1/3 map · 2/3 stores',
														'cliq-store-locator'
													),
												},
												{
													value: '5',
													label: __(
														'5/12 map · 7/12 stores',
														'cliq-store-locator'
													),
												},
												{
													value: '6',
													label: __(
														'Equal width',
														'cliq-store-locator'
													),
												},
												{
													value: '7',
													label: __(
														'7/12 map · 5/12 stores',
														'cliq-store-locator'
													),
												},
												{
													value: '8',
													label: __(
														'2/3 map · 1/3 stores',
														'cliq-store-locator'
													),
												},
												{
													value: '9',
													label: __(
														'3/4 map · 1/4 stores',
														'cliq-store-locator'
													),
												},
											] }
											onChange={ ( value ) =>
												set(
													'locator_map_columns',
													Number( value )
												)
											}
										/>
									) }
									<NumberField
										label={ __(
											'Store columns',
											'cliq-store-locator'
										) }
										help={ __(
											'Maximum number of store cards per row. Fewer columns are used automatically when space is limited, so a list shown beside the map may still use one.',
											'cliq-store-locator'
										) }
										value={
											values.locator_list_columns ?? 3
										}
										min={ 1 }
										max={ 6 }
										onChange={ ( value ) =>
											set( 'locator_list_columns', value )
										}
									/>
									<NumberField
										label={ __(
											'Minimum card width (px)',
											'cliq-store-locator'
										) }
										help={ __(
											'Cards wrap onto a new row before becoming narrower than this value.',
											'cliq-store-locator'
										) }
										value={
											values.locator_list_min_width ?? 260
										}
										min={ 160 }
										max={ 600 }
										onChange={ ( value ) =>
											set(
												'locator_list_min_width',
												value
											)
										}
									/>
									<NumberField
										label={ __(
											'Map height (px)',
											'cliq-store-locator'
										) }
										value={ values.locator_map_height }
										min={ 240 }
										max={ 1200 }
										onChange={ ( value ) =>
											set( 'locator_map_height', value )
										}
									/>
									<NumberField
										label={ __(
											'Results per page',
											'cliq-store-locator'
										) }
										value={ values.locator_results_per_page }
										min={ 1 }
										max={ 100 }
										onChange={ ( value ) =>
											set(
												'locator_results_per_page',
												value
											)
										}
									/>
									<NumberField
										label={ __(
											'Default map zoom',
											'cliq-store-locator'
										) }
										value={ values.map_default_zoom }
										min={ 1 }
										max={ 22 }
										onChange={ ( value ) =>
											set( 'map_default_zoom', value )
										}
									/>
									<SelectControl
										__nextHasNoMarginBottom
										label={ __(
											'Default marker',
											'cliq-store-locator'
										) }
										value={
											values.locator_marker_preset || 'store'
										}
										options={ [
											{
												value: 'store',
												label: __(
													'Store',
													'cliq-store-locator'
												),
											},
											{
												value: 'home',
												label: __(
													'Home',
													'cliq-store-locator'
												),
											},
											{
												value: 'info',
												label: __(
													'Information',
													'cliq-store-locator'
												),
											},
											{
												value: 'car',
												label: __(
													'Car',
													'cliq-store-locator'
												),
											},
										] }
										onChange={ ( value ) =>
											set( 'locator_marker_preset', value )
										}
									/>
								</div>
								<div className="cliq-sl-settings__toggles">
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Enable search',
											'cliq-store-locator'
										) }
										checked={
											values.locator_show_search !== false
										}
										onChange={ ( value ) =>
											set( 'locator_show_search', value )
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Show category filter',
											'cliq-store-locator'
										) }
										checked={
											!! values.locator_show_category_filter
										}
										onChange={ ( value ) =>
											set(
												'locator_show_category_filter',
												value
											)
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Show print button',
											'cliq-store-locator'
										) }
										checked={ !! values.locator_show_print }
										disabled={
											! values.locator_show_result_count
										}
										onChange={ ( value ) =>
											set( 'locator_show_print', value )
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Show Load More button',
											'cliq-store-locator'
										) }
										checked={
											values.locator_show_load_more !== false
										}
										onChange={ ( value ) =>
											set( 'locator_show_load_more', value )
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Show distance filter',
											'cliq-store-locator'
										) }
										checked={
											!! values.locator_show_radius_filter
										}
										onChange={ ( value ) =>
											set(
												'locator_show_radius_filter',
												value
											)
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Show result count',
											'cliq-store-locator'
										) }
										checked={
											!! values.locator_show_result_count
										}
										onChange={ ( value ) =>
											set(
												'locator_show_result_count',
												value
											)
										}
									/>
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Cluster nearby markers',
											'cliq-store-locator'
										) }
										checked={ !! values.enable_clustering }
										onChange={ ( value ) =>
											set( 'enable_clustering', value )
										}
									/>
								</div>
								<div className="cliq-sl-settings__grid cliq-sl-settings__subgrid">
									{ values.locator_show_load_more !== false && (
										<TextControl
											__nextHasNoMarginBottom
											label={ __(
												'Load More button label',
												'cliq-store-locator'
											) }
											value={
												values.locator_load_more_label ||
												'Load more'
											}
											onChange={ ( value ) =>
												set(
													'locator_load_more_label',
													value
												)
											}
										/>
									) }
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Location field label',
											'cliq-store-locator'
										) }
										value={
											values.locator_location_label ||
											'Location'
										}
										onChange={ ( value ) =>
											set( 'locator_location_label', value )
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Location placeholder',
											'cliq-store-locator'
										) }
										value={
											values.locator_location_placeholder ||
											'City, postcode or address'
										}
										onChange={ ( value ) =>
											set(
												'locator_location_placeholder',
												value
											)
										}
									/>
									{ values.locator_show_category_filter && (
										<TextControl
											__nextHasNoMarginBottom
											label={ __(
												'Category field label',
												'cliq-store-locator'
											) }
											value={
												values.locator_category_label ||
												'Category'
											}
											onChange={ ( value ) =>
												set(
													'locator_category_label',
													value
												)
											}
										/>
									) }
									{ values.locator_show_radius_filter && (
										<TextControl
											__nextHasNoMarginBottom
											label={ __(
												'Distance field label',
												'cliq-store-locator'
											) }
											value={
												values.locator_distance_label ||
												'Distance'
											}
											onChange={ ( value ) =>
												set(
													'locator_distance_label',
													value
												)
											}
										/>
									) }
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Search button label',
											'cliq-store-locator'
										) }
										value={
											values.locator_search_button_label ||
											'Search'
										}
										onChange={ ( value ) =>
											set(
												'locator_search_button_label',
												value
											)
										}
									/>
									{ values.locator_show_result_count && (
										<TextControl
											__nextHasNoMarginBottom
											label={ __(
												'Result count label',
												'cliq-store-locator'
											) }
											value={
												values.locator_result_count_label ||
												'Stores'
											}
											onChange={ ( value ) =>
												set(
													'locator_result_count_label',
													value
												)
											}
										/>
									) }
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'No results message',
											'cliq-store-locator'
										) }
										value={
											values.locator_empty_results_message ||
											'No stores found.'
										}
										onChange={ ( value ) =>
											set(
												'locator_empty_results_message',
												value
											)
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Phone link label',
											'cliq-store-locator'
										) }
										help={ __(
											'Leave blank to show the actual phone number.',
											'cliq-store-locator'
										) }
										placeholder={ __(
											'Call us',
											'cliq-store-locator'
										) }
										value={ values.locator_phone_label ?? '' }
										onChange={ ( value ) =>
											set( 'locator_phone_label', value )
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Email link label',
											'cliq-store-locator'
										) }
										help={ __(
											'Leave blank to show the actual email address.',
											'cliq-store-locator'
										) }
										placeholder={ __(
											'Email us',
											'cliq-store-locator'
										) }
										value={ values.locator_email_label ?? '' }
										onChange={ ( value ) =>
											set( 'locator_email_label', value )
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Website link label',
											'cliq-store-locator'
										) }
										help={ __(
											'Leave blank to show the actual website URL.',
											'cliq-store-locator'
										) }
										placeholder={ __(
											'Visit our website',
											'cliq-store-locator'
										) }
										value={
											values.locator_website_label ?? ''
										}
										onChange={ ( value ) =>
											set( 'locator_website_label', value )
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Directions button label',
											'cliq-store-locator'
										) }
										value={
											values.locator_directions_button_label ||
											'Directions'
										}
										onChange={ ( value ) =>
											set(
												'locator_directions_button_label',
												value
											)
										}
									/>
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Details button label',
											'cliq-store-locator'
										) }
										value={
											values.locator_details_button_label ||
											'View More'
										}
										onChange={ ( value ) =>
											set(
												'locator_details_button_label',
												value
											)
										}
									/>
								</div>
							</section>
						) }

						{ activeTab.name === 'theme' && (
							<section className="cliq-sl-settings__section">
								<header>
									<h2>
										{ __( 'Theme', 'cliq-store-locator' ) }
									</h2>
									<p>
										{ __(
											'These colors are used by the built-in store cards, search form, map infobox, and store detail template.',
											'cliq-store-locator'
										) }
									</p>
								</header>
								<div className="cliq-sl-theme">
									<div className="cliq-sl-theme__toolbar">
										<div>
											<h3>
												{ __(
													'Start with a palette',
													'cliq-store-locator'
												) }
											</h3>
											<p>
												{ __(
													'Choose a complete, accessible color set, then adjust only what you need.',
													'cliq-store-locator'
												) }
											</p>
										</div>
										<Button
											variant="secondary"
											onClick={ resetTheme }
										>
											{ __(
												'Reset theme',
												'cliq-store-locator'
											) }
										</Button>
									</div>
									<div className="cliq-sl-theme__presets">
										{ THEME_PRESETS.map( ( preset ) => {
											const selected = Object.entries(
												preset.colors
											).every(
												( [ key, color ] ) =>
													values[ key ] === color
											);
											return (
												<button
													key={ preset.name }
													type="button"
													className={
														selected
															? 'is-selected'
															: ''
													}
													aria-pressed={ selected }
													onClick={ () =>
														applyTheme(
															preset.colors,
															__(
																'Palette applied. Save settings to publish it.',
																'cliq-store-locator'
															)
														)
													}
												>
													<span
														className="cliq-sl-theme__swatches"
														aria-hidden="true"
													>
														<i
															style={ {
																background:
																	preset
																		.colors
																		.theme_primary,
															} }
														/>
														<i
															style={ {
																background:
																	preset
																		.colors
																		.theme_surface,
															} }
														/>
														<i
															style={ {
																background:
																	preset
																		.colors
																		.theme_heading,
															} }
														/>
													</span>
													<strong>
														{ preset.label }
													</strong>
												</button>
											);
										} ) }
									</div>
									<div
										className="cliq-sl-theme__preview"
										style={ {
											'--preview-primary':
												values.theme_primary,
											'--preview-primary-strong':
												values.theme_primary_strong,
											'--preview-on-primary':
												values.theme_on_primary,
											'--preview-canvas':
												values.theme_canvas,
											'--preview-on-canvas':
												contrastTextColor(
													values.theme_canvas
												),
											'--preview-surface':
												values.theme_surface,
											'--preview-text': values.theme_text,
											'--preview-heading':
												values.theme_heading,
											'--preview-soft':
												values.theme_text_soft,
											'--preview-label':
												values.theme_label,
											'--preview-muted':
												values.theme_muted,
											'--preview-border':
												values.theme_border,
											'--preview-border-soft':
												values.theme_border_soft,
										} }
									>
										<div className="cliq-sl-theme__preview-search">
											<label>
												{ __(
													'Location',
													'cliq-store-locator'
												) }
											</label>
											<span>
												{ __(
													'Search a city or postcode',
													'cliq-store-locator'
												) }
											</span>
											<button type="button">
												{ __(
													'Search',
													'cliq-store-locator'
												) }
											</button>
										</div>
										<article>
											<img
												src={
													window.CLIQTHEMES_UI?.app
														?.assets?.demoHero ||
													''
												}
												alt=""
											/>
											<div>
												<small>
													{ __(
														'Featured store',
														'cliq-store-locator'
													) }
												</small>
												<h4>
													{ __(
														'Willow & Pine',
														'cliq-store-locator'
													) }
												</h4>
												<p>
													{ __(
														'14 Market Street',
														'cliq-store-locator'
													) }
												</p>
												<button type="button">
													{ __(
														'View More',
														'cliq-store-locator'
													) }
												</button>
											</div>
										</article>
									</div>
									<div className="cliq-sl-theme__fields">
										{ THEME_COLORS.filter( ( [ key ] ) =>
											ESSENTIAL_THEME_KEYS.has( key )
										).map( ( [ key, label ] ) => (
										<ColorField
											key={ key }
											id={ `cliq-sl-${ key }` }
											label={ label }
											value={ values[ key ] }
											onChange={ ( value ) =>
												set( key, value )
											}
										/>
									) ) }
									</div>
									<details className="cliq-sl-theme__advanced">
										<summary>
											{ __(
												'Advanced colors',
												'cliq-store-locator'
											) }
										</summary>
										<p>
											{ __(
												'Fine-tune labels, secondary text, borders, dividers and error states.',
												'cliq-store-locator'
											) }
										</p>
										<div className="cliq-sl-theme__fields">
											{ THEME_COLORS.filter(
												( [ key ] ) =>
													! ESSENTIAL_THEME_KEYS.has(
														key
													)
											).map( ( [ key, label ] ) => (
												<ColorField
													key={ key }
													id={ `cliq-sl-${ key }` }
													label={ label }
													value={ values[ key ] }
													onChange={ ( value ) =>
														set( key, value )
													}
												/>
											) ) }
										</div>
									</details>
								</div>
							</section>
						) }

						{ activeTab.name === 'template' && (
							<section className="cliq-sl-settings__section">
								<header>
									<h2>
										{ __(
											'Template content',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ __(
											'Choose what the built-in store card, map infobox and detail page display. Reorder fields and add an optional icon to each.',
											'cliq-store-locator'
										) }
									</p>
								</header>
								<TabPanel
									className="cliq-sl-template-tabs"
									tabs={ TEMPLATE_TABS }
								>
									{ ( templateTab ) => (
										<div className="cliq-sl-template-grid">
											{ templateTab.name === 'card' && (
												<TemplateEditor
													type="card"
													title={ __(
														'Store list card',
														'cliq-store-locator'
													) }
													description={ __(
														'Controls every store shown in the results list.',
														'cliq-store-locator'
													) }
													value={
														values.locator_card_fields
													}
													columns={
														values.locator_card_columns ||
														1
													}
													onColumnsChange={ (
														value
													) =>
														set(
															'locator_card_columns',
															value
														)
													}
													customFields={
														customFields
													}
													onChange={ ( value ) =>
														set(
															'locator_card_fields',
															value
														)
													}
												/>
											) }
											{ templateTab.name ===
												'infobox' && (
												<TemplateEditor
													type="infobox"
													title={ __(
														'Map infobox',
														'cliq-store-locator'
													) }
													description={ __(
														'Shown after a visitor selects a map marker.',
														'cliq-store-locator'
													) }
													value={
														values.locator_infobox_fields
													}
													customFields={
														customFields
													}
													onChange={ ( value ) =>
														set(
															'locator_infobox_fields',
															value
														)
													}
												/>
											) }
											{ templateTab.name === 'detail' && (
												<TemplateEditor
													type="detail"
													title={ __(
														'Store detail page',
														'cliq-store-locator'
													) }
													description={ __(
														'Controls the content column on individual store pages.',
														'cliq-store-locator'
													) }
													value={
														values.locator_detail_fields
													}
													columns={
														values.locator_detail_columns ||
														1
													}
													onColumnsChange={ (
														value
													) =>
														set(
															'locator_detail_columns',
															value
														)
													}
													customFields={
														customFields
													}
													onChange={ ( value ) =>
														set(
															'locator_detail_fields',
															value
														)
													}
												/>
											) }
										</div>
									) }
								</TabPanel>
							</section>
						) }

						{ activeTab.name === 'map-search' && (
							<section className="cliq-sl-settings__section">
								<header>
									<h2>
										{ __(
											'Map and search',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ __(
											'Choose the map service and configure address search defaults.',
											'cliq-store-locator'
										) }
									</p>
								</header>
								<div className="cliq-sl-settings__grid">
									<SelectControl
										__nextHasNoMarginBottom
										label={ __(
											'Map provider',
											'cliq-store-locator'
										) }
										value={
											values.map_provider || 'leaflet'
										}
										options={ [
											{
												value: 'leaflet',
												label: __(
													'Leaflet (OpenStreetMap)',
													'cliq-store-locator'
												),
											},
											{
												value: 'google',
												label: __(
													'Google Maps',
													'cliq-store-locator'
												),
											},
										] }
										onChange={ ( value ) =>
											set( 'map_provider', value )
										}
									/>
									{ values.map_provider === 'google' && (
										<>
											<SelectControl
												__nextHasNoMarginBottom
												label={ __(
													'Map type',
													'cliq-store-locator'
												) }
												value={
													values.map_type || 'roadmap'
												}
												options={ [
													{
														value: 'roadmap',
														label: __(
															'Road map',
															'cliq-store-locator'
														),
													},
													{
														value: 'satellite',
														label: __(
															'Satellite',
															'cliq-store-locator'
														),
													},
													{
														value: 'hybrid',
														label: __(
															'Hybrid',
															'cliq-store-locator'
														),
													},
													{
														value: 'terrain',
														label: __(
															'Terrain',
															'cliq-store-locator'
														),
													},
												] }
												onChange={ ( value ) =>
													set( 'map_type', value )
												}
											/>
											<SelectControl
												__nextHasNoMarginBottom
												label={ __(
													'Map theme',
													'cliq-store-locator'
												) }
												help={ __(
													'Available for Google road maps.',
													'cliq-store-locator'
												) }
												value={
													values.map_style ||
													'standard'
												}
												options={ [
													{
														value: 'standard',
														label: __(
															'Standard',
															'cliq-store-locator'
														),
													},
													{
														value: 'silver',
														label: __(
															'Silver · light',
															'cliq-store-locator'
														),
													},
													{
														value: 'retro',
														label: __(
															'Retro · light',
															'cliq-store-locator'
														),
													},
													{
														value: 'dark',
														label: __(
															'Dark',
															'cliq-store-locator'
														),
													},
													{
														value: 'night',
														label: __(
															'Night',
															'cliq-store-locator'
														),
													},
												] }
												onChange={ ( value ) =>
													set( 'map_style', value )
												}
											/>
										</>
									) }
									<SelectControl
										__nextHasNoMarginBottom
										label={ __(
											'Distance unit',
											'cliq-store-locator'
										) }
										value={ values.distance_unit || 'mi' }
										options={ [
											{
												value: 'mi',
												label: __(
													'Miles',
													'cliq-store-locator'
												),
											},
											{
												value: 'km',
												label: __(
													'Kilometres',
													'cliq-store-locator'
												),
											},
										] }
										onChange={ ( value ) =>
											set( 'distance_unit', value )
										}
									/>
									{ values.map_provider === 'google' && (
										<>
											<TextControl
												__nextHasNoMarginBottom
												label={ __(
													'Google Maps browser API key',
													'cliq-store-locator'
												) }
												value={
													values.google_maps_api_key ||
													''
												}
												onChange={ ( value ) =>
													set(
														'google_maps_api_key',
														value
													)
												}
												help={ __(
													'Used by Maps JavaScript and Places. Restrict this key by HTTP referrer.',
													'cliq-store-locator'
												) }
											/>
											<TextControl
												__nextHasNoMarginBottom
												label={ __(
													'Google server geocoding key',
													'cliq-store-locator'
												) }
												value={
													values.google_server_api_key ||
													''
												}
												onChange={ ( value ) =>
													set(
														'google_server_api_key',
														value
													)
												}
												help={ __(
													'Used only on the server. Restrict this key by server IP.',
													'cliq-store-locator'
												) }
											/>
										</>
									) }
									<TextControl
										__nextHasNoMarginBottom
										label={ __(
											'Restrict address search to countries',
											'cliq-store-locator'
										) }
										value={ values.restrict_country || '' }
										onChange={ ( value ) =>
											set( 'restrict_country', value )
										}
										help={ __(
											'Optional ISO-2 codes separated by commas, for example US,CA.',
											'cliq-store-locator'
										) }
									/>
									<NumberField
										label={ __(
											'Default latitude',
											'cliq-store-locator'
										) }
										value={ values.map_default_lat }
										onChange={ ( value ) =>
											set( 'map_default_lat', value )
										}
									/>
									<NumberField
										label={ __(
											'Default longitude',
											'cliq-store-locator'
										) }
										value={ values.map_default_lng }
										onChange={ ( value ) =>
											set( 'map_default_lng', value )
										}
									/>
									<NumberField
										label={ __(
											'Zoom after location search',
											'cliq-store-locator'
										) }
										value={ values.search_zoom }
										min={ 1 }
										max={ 22 }
										onChange={ ( value ) =>
											set( 'search_zoom', value )
										}
									/>
									<NumberField
										label={ __(
											'Zoom after selecting a store',
											'cliq-store-locator'
										) }
										value={ values.clicked_zoom }
										min={ 1 }
										max={ 22 }
										onChange={ ( value ) =>
											set( 'clicked_zoom', value )
										}
									/>
								</div>
								<div className="cliq-sl-settings__toggles">
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Enable address autocomplete',
											'cliq-store-locator'
										) }
										checked={
											!! values.enable_autocomplete
										}
										onChange={ ( value ) =>
											set( 'enable_autocomplete', value )
										}
									/>
									{ values.map_provider === 'google' && (
										<ToggleControl
											__nextHasNoMarginBottom
											label={ __(
												'Google Maps API is loaded by another plugin or theme',
												'cliq-store-locator'
											) }
											checked={
												!! values.google_maps_api_loaded_externally
											}
											onChange={ ( value ) =>
												set(
													'google_maps_api_loaded_externally',
													value
												)
											}
										/>
									) }
								</div>
							</section>
						) }
						{ activeTab.name === 'details' && (
							<section className="cliq-sl-settings__section">
								<header>
									<h2>
										{ __(
											'Store detail pages',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ __(
											'Use the bundled responsive detail template for individual store URLs. It shows the hero image and the core store fields.',
											'cliq-store-locator'
										) }
									</p>
								</header>
								<div className="cliq-sl-settings__grid">
									<ToggleControl
										__nextHasNoMarginBottom
										label={ __(
											'Enable store detail pages',
											'cliq-store-locator'
										) }
										checked={ !! values.store_detail_pages }
										onChange={ ( value ) =>
											set( 'store_detail_pages', value )
										}
									/>
									{ values.store_detail_pages && (
										<>
											<SelectControl
												__nextHasNoMarginBottom
												label={ __(
													'Store detail base page',
													'cliq-store-locator'
												) }
												help={ __(
													'Choose the page that should display individual stores. The store detail template is inserted automatically.',
													'cliq-store-locator'
												) }
												value={ String(
													values.store_detail_page ||
														0
												) }
												options={ [
													{
														value: '0',
														label: __(
															'— Select a page —',
															'cliq-store-locator'
														),
													},
													...pages.map(
														( page ) => ( {
															value: String(
																page.id
															),
															label:
																page.title
																	?.rendered ||
																`#${ page.id }`,
														} )
													),
												] }
												onChange={ ( value ) =>
													set(
														'store_detail_page',
														Number( value )
													)
												}
											/>
											<SlugFieldsEditor
												value={
													values.store_detail_slug_fields
												}
												onChange={ ( value ) =>
													set(
														'store_detail_slug_fields',
														value
													)
												}
											/>
										</>
									) }
								</div>
							</section>
						) }
					</div>
				) }
			</TabPanel>

			<div className="cliq-sl-settings__footer">
				<div>
					<strong>
						{ __( 'Save locator settings', 'cliq-store-locator' ) }
					</strong>
					<p>
						{ __(
							'Apply the changes made across all settings tabs.',
							'cliq-store-locator'
						) }
					</p>
				</div>
				<Button
					variant="primary"
					onClick={ save }
					isBusy={ saving }
					disabled={ saving }
				>
					{ __( 'Save settings', 'cliq-store-locator' ) }
				</Button>
			</div>
		</div>
	);
};

const cliqUI = typeof window !== 'undefined' ? window.cliqUI : null;
if ( cliqUI ) {
	cliqUI.registerScreen( 'dashboard', {
		label: __( 'Dashboard', 'cliq-store-locator' ),
		icon: DashboardIcon,
		Component: Dashboard,
	} );
	cliqUI.registerScreen( 'settings', {
		label: __( 'Locator settings', 'cliq-store-locator' ),
		icon: SettingsIcon,
		Component: SettingsScreen,
	} );
	cliqUI.registerField( 'map', MapField );
	cliqUI.registerField( 'icon-picker', IconPickerField );
	if ( typeof cliqUI.registerToolbarItem === 'function' ) {
		cliqUI.registerToolbarItem( {
			id: 'cliq-sl-onboarding-guide',
			Component: OnboardingGuide,
			order: 0,
		} );
		cliqUI.registerToolbarItem( {
			id: 'onboarding',
			Component: Onboarding,
			order: 1,
		} );
		cliqUI.registerToolbarItem( {
			id: 'cliq-sl-banner-links',
			Component: BannerLinks,
			order: 5,
		} );
	}
	if ( typeof cliqUI.registerBannerBrand === 'function' ) {
		cliqUI.registerBannerBrand( BannerBrand );
	}
	if ( typeof cliqUI.registerBannerArt === 'function' ) {
		cliqUI.registerBannerArt( BannerArt );
	}
}
