import { useEffect, useMemo, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	BaseControl,
	Button,
	ColorIndicator,
	Dropdown,
	FontSizePicker,
	TextControl,
	ToggleControl,
	__experimentalDropdownContentWrapper as DropdownContentWrapper,
} from '@wordpress/components';
import { api } from '../api';
import PreviewFrame from '../components/PreviewFrame';
import ConfirmModal from '../components/ui/ConfirmModal';
import IconLibrariesPanel from '../components/IconLibrariesPanel';
import SearchableSelect from '../../components/SearchableSelect';
import ThemeColorPalette from '../../components/ThemeColorPalette';
import { broadcastThemeUpdate } from '../../hooks/useThemeTokens';
import { DEFAULT_COLORS, DEFAULT_FONT_SIZES, isLockedFont, isLockedFontSize } from '../../styleFieldDefaults';
import { defaultIconLibraries } from '../../shared/iconRegistry';
import { syncConfiguredFontStylesheets } from '../../shared/themeFonts';
import LibrarySkeleton from '../components/LibrarySkeleton';

function slugify( value ) {
	return String( value || '' )
		.toLowerCase()
		.replace( /[^a-z0-9]+/g, '-' )
		.replace( /^-|-$/g, '' );
}

/**
 * CSS font-family value from a Global Settings family string.
 *
 * @param {string} family Family name or stack.
 * @return {string|undefined}
 */
function toCssFontFamily( family ) {
	const value = String( family || '' ).trim();
	if ( ! value ) {
		return undefined;
	}
	if ( value.includes( ',' ) || value === 'system-ui' ) {
		return value;
	}
	return `"${ value }", system-ui, sans-serif`;
}

/**
 * Stable key for a config font row.
 *
 * @param {Object} font  Font row.
 * @param {number} index Index.
 * @return {string}
 */
function fontRowKey( font, index ) {
	return String( font?.slug || font?.family || `font-${ index }` );
}

function emptyFontSizeDraft() {
	return {
		name: '',
		slug: '',
		size: '16px',
		lineHeight: '1.5',
	};
}

function emptyFontDraft() {
	return {
		family: '',
		slug: '',
		source: '',
	};
}

function emptyColorDraft() {
	return {
		name: '',
		slug: '',
		color: '#888888',
	};
}

function ThemeColorSwatch( { value, onChange, colors, label } ) {
	return (
		<Dropdown
			className="bm-theme-color-swatch"
			contentClassName="bm-color-dropdown__content"
			popoverProps={ { placement: 'bottom-start', offset: 8 } }
			renderToggle={ ( { isOpen, onToggle } ) => (
				<Button
					className="bm-theme-color-swatch__toggle"
					onClick={ onToggle }
					aria-expanded={ isOpen }
					aria-label={ label || __( 'Select color', 'joc-blockora-morph' ) }
					variant="secondary"
				>
					<ColorIndicator
						className="bm-theme-color-swatch__indicator"
						colorValue={ value || undefined }
					/>
				</Button>
			) }
			renderContent={ () => (
				<DropdownContentWrapper paddingSize="medium">
					<div className="bm-color-dropdown__panel">
						<ThemeColorPalette
							value={ value || '' }
							onChange={ ( next ) => onChange( next || '' ) }
							clearable={ false }
							enableAlpha
							palettes={ colors }
						/>
					</div>
				</DropdownContentWrapper>
			) }
		/>
	);
}

export default function ThemeConfig( { onNavigate } ) {
	const [ config, setConfig ] = useState( null );
	const [ saving, setSaving ] = useState( false );
	const [ fontSizeEditor, setFontSizeEditor ] = useState( null );
	const [ fontEditor, setFontEditor ] = useState( null );
	const [ colorEditor, setColorEditor ] = useState( null );
	const [ settingsTab, setSettingsTab ] = useState( 'general' );
	const [ generalSection, setGeneralSection ] = useState( 'brand' );
	const [ resetOpen, setResetOpen ] = useState( false );
	const [ resetConfirm, setResetConfirm ] = useState( '' );
	const [ resetting, setResetting ] = useState( false );
	const [ systemSettings, setSystemSettings ] = useState( null );
	const [ savingSystem, setSavingSystem ] = useState( false );
	const [ iconLibraries, setIconLibraries ] = useState( null );
	const [ savingIcons, setSavingIcons ] = useState( false );
	const [ previewFontIndex, setPreviewFontIndex ] = useState( 0 );

	useEffect( () => {
		api.get( '/theme-config' ).then( setConfig );
		api.get( '/system/settings' )
			.then( ( saved ) => {
				setSystemSettings( saved );
				setIconLibraries(
					Array.isArray( saved?.iconLibraries ) &&
						saved.iconLibraries.length
						? saved.iconLibraries
						: defaultIconLibraries()
				);
			} )
			.catch( () => {
				setSystemSettings( { frontendEditor: true } );
				setIconLibraries( defaultIconLibraries() );
			} );
	}, [] );

	// Keep preview font index in range as fonts are added/removed.
	useEffect( () => {
		const count = config?.fonts?.length || 0;
		if ( count === 0 ) {
			setPreviewFontIndex( 0 );
			return;
		}
		if ( previewFontIndex > count - 1 ) {
			setPreviewFontIndex( count - 1 );
		}
	}, [ config?.fonts?.length, previewFontIndex ] );

	// Keep parent-document font stylesheets in sync (dropdown previews + this page).
	useEffect( () => {
		syncConfiguredFontStylesheets( config?.fonts || [] );
	}, [ config?.fonts ] );

	const paletteColors = useMemo( () => {
		const jbm = ( config?.colors || [] )
			.filter( ( c ) => c?.color )
			.map( ( c ) => ( {
				name: c.name || c.slug,
				slug: c.slug,
				color: c.color,
			} ) );
		const theme = ( config?.themeColors || [] )
			.filter( ( c ) => c?.color )
			.map( ( c ) => ( {
				name: c.name || c.slug,
				slug: c.slug,
				color: c.color,
			} ) );
		return [
			{
				name: 'default',
				title: __( 'Default', 'joc-blockora-morph' ),
				colors: jbm.length ? jbm : DEFAULT_COLORS,
			},
			{
				name: 'theme',
				title: __( 'Theme', 'joc-blockora-morph' ),
				colors: theme,
			},
		];
	}, [ config?.colors, config?.themeColors ] );

	const pickerSizes = useMemo( () => {
		const list = ( config?.fontSizes || [] ).filter( ( s ) => s?.size );
		return list.length ? list : DEFAULT_FONT_SIZES;
	}, [ config?.fontSizes ] );

	const previewFontOptions = useMemo( () => {
		return ( config?.fonts || [] )
			.map( ( font, index ) => {
				const family = String( font?.family || '' ).trim();
				return {
					label: family || __( 'Untitled font', 'joc-blockora-morph' ),
					value: String( index ),
					fontFamily: toCssFontFamily( family ),
				};
			} )
			.filter( ( opt ) => opt.label );
	}, [ config?.fonts ] );

	const themeFontFamilies = useMemo( () => {
		const list = Array.isArray( config?.themeFontFamilies )
			? config.themeFontFamilies
			: [];
		return list.filter( ( f ) => f?.fontFamily || f?.name );
	}, [ config?.themeFontFamilies ] );

	const save = async () => {
		setSaving( true );
		try {
			const updated = await api.put( '/theme-config', config );
			setConfig( updated );
			broadcastThemeUpdate( updated );
		} catch ( e ) {
			window.alert( e?.message || __( 'Save failed.', 'joc-blockora-morph' ) );
		}
		setSaving( false );
	};

	const runReset = async () => {
		if ( resetConfirm !== 'DELETE' || resetting ) {
			return;
		}
		setResetting( true );
		try {
			const result = await api.post( '/system/reset-data', {
				confirm: 'DELETE',
			} );
			setResetOpen( false );
			setResetConfirm( '' );
			const refreshed =
				result?.themeConfig || ( await api.get( '/theme-config' ) );
			setConfig( refreshed );
			broadcastThemeUpdate( refreshed );
			setSettingsTab( 'general' );
			if ( typeof window.jocbmAdmin === 'object' && window.jocbmAdmin ) {
				window.jocbmAdmin.welcomeSeen = false;
			}
			if ( typeof onNavigate === 'function' ) {
				onNavigate( 'welcome' );
			} else {
				window.location.hash = 'welcome';
			}
		} catch ( e ) {
			window.alert(
				e?.message || __( 'Could not reset Blockora Morph data.', 'joc-blockora-morph' )
			);
		}
		setResetting( false );
	};

	if ( ! config ) {
		return <LibrarySkeleton variant="settings" />;
	}

	const openAddColor = () => {
		setColorEditor( {
			index: null,
			draft: emptyColorDraft(),
		} );
	};

	const openEditColor = ( index ) => {
		const color = config.colors[ index ];
		setColorEditor( {
			index,
			draft: {
				name: color.name || '',
				slug: color.slug || '',
				color: color.color || '#888888',
			},
		} );
	};

	const closeColorEditor = () => setColorEditor( null );

	const updateColorDraft = ( key, value ) => {
		setColorEditor( ( prev ) => {
			if ( ! prev ) {
				return prev;
			}
			const draft = { ...prev.draft, [ key ]: value };
			if ( key === 'name' ) {
				draft.slug = slugify( value ) || prev.draft.slug;
			}
			return { ...prev, draft };
		} );
	};

	const saveColorEditor = () => {
		if ( ! colorEditor ) {
			return;
		}
		const { index, draft } = colorEditor;
		const name =
			( draft.name || '' ).trim() || __( 'New color', 'joc-blockora-morph' );
		const next = {
			name,
			slug:
				slugify( draft.slug || name ) ||
				`color-${ ( config.colors?.length || 0 ) + 1 }`,
			color: draft.color || '#888888',
		};
		const colors = [ ...( config.colors || [] ) ];
		if ( index === null ) {
			colors.push( next );
		} else {
			colors[ index ] = next;
		}
		setConfig( { ...config, colors } );
		setColorEditor( null );
	};

	const removeColor = ( index ) => {
		setConfig( {
			...config,
			colors: config.colors.filter( ( _, i ) => i !== index ),
		} );
	};

	const openAddFontSize = () => {
		setFontSizeEditor( {
			index: null,
			draft: emptyFontSizeDraft(),
		} );
	};

	const openEditFontSize = ( index ) => {
		const size = config.fontSizes[ index ];
		if ( isLockedFontSize( size ) ) {
			return;
		}
		setFontSizeEditor( {
			index,
			draft: {
				name: size.name || '',
				slug: size.slug || '',
				size: size.size || '16px',
				lineHeight: size.lineHeight || '',
			},
		} );
	};

	const closeFontSizeEditor = () => setFontSizeEditor( null );

	const updateFontSizeDraft = ( key, value ) => {
		setFontSizeEditor( ( prev ) => {
			if ( ! prev ) {
				return prev;
			}
			const draft = { ...prev.draft, [ key ]: value };
			if ( key === 'name' ) {
				draft.slug = slugify( value ) || prev.draft.slug;
			}
			return { ...prev, draft };
		} );
	};

	const saveFontSizeEditor = () => {
		if ( ! fontSizeEditor ) {
			return;
		}
		const { index, draft } = fontSizeEditor;
		if ( index !== null && isLockedFontSize( config.fontSizes?.[ index ] ) ) {
			setFontSizeEditor( null );
			return;
		}
		const name = ( draft.name || '' ).trim() || __( 'Custom', 'joc-blockora-morph' );
		const next = {
			name,
			slug:
				slugify( draft.slug || name ) ||
				`size-${ ( config.fontSizes?.length || 0 ) + 1 }`,
			size: ( draft.size || '' ).trim() || '16px',
			lineHeight: ( draft.lineHeight || '' ).trim(),
		};
		if ( isLockedFontSize( next ) ) {
			// Do not allow custom rows to collide with built-in slugs.
			next.slug = `custom-${ next.slug }`;
		}
		const fontSizes = [ ...( config.fontSizes || [] ) ];
		if ( index === null ) {
			fontSizes.push( next );
		} else {
			fontSizes[ index ] = next;
		}
		setConfig( { ...config, fontSizes } );
		setFontSizeEditor( null );
	};

	const removeFontSize = ( index ) => {
		if ( isLockedFontSize( config.fontSizes?.[ index ] ) ) {
			return;
		}
		setConfig( {
			...config,
			fontSizes: config.fontSizes.filter( ( _, i ) => i !== index ),
		} );
	};

	const openAddFont = () => {
		setFontEditor( {
			index: null,
			draft: emptyFontDraft(),
		} );
	};

	const openEditFont = ( index ) => {
		const font = config.fonts[ index ];
		if ( isLockedFont( font ) ) {
			return;
		}
		setPreviewFontIndex( index );
		setFontEditor( {
			index,
			draft: {
				family: font.family || '',
				slug: font.slug || '',
				source: font.source || '',
			},
		} );
	};

	const closeFontEditor = () => setFontEditor( null );

	const updateFontDraft = ( key, value ) => {
		setFontEditor( ( prev ) => {
			if ( ! prev ) {
				return prev;
			}
			const draft = { ...prev.draft, [ key ]: value };
			if ( key === 'family' ) {
				draft.slug = slugify( value ) || prev.draft.slug;
			}
			return { ...prev, draft };
		} );
	};

	const saveFontEditor = () => {
		if ( ! fontEditor ) {
			return;
		}
		const { index, draft } = fontEditor;
		if ( index !== null && isLockedFont( config.fonts?.[ index ] ) ) {
			setFontEditor( null );
			return;
		}
		const family =
			( draft.family || '' ).trim() || __( 'New Font', 'joc-blockora-morph' );
		const next = {
			family,
			slug:
				slugify( draft.slug || family ) ||
				`font-${ ( config.fonts?.length || 0 ) + 1 }`,
			source: ( draft.source || '' ).trim(),
		};
		if ( isLockedFont( next ) ) {
			next.slug = `custom-${ next.slug || 'font' }`;
			if ( String( next.family ).trim().toLowerCase() === 'inter' ) {
				next.family = `${ next.family } Custom`;
			}
		}
		const fonts = [ ...( config.fonts || [] ) ];
		if ( index === null ) {
			fonts.push( next );
			setPreviewFontIndex( fonts.length - 1 );
		} else {
			fonts[ index ] = next;
			setPreviewFontIndex( index );
		}
		setConfig( { ...config, fonts } );
		setFontEditor( null );
	};

	const removeFont = ( index ) => {
		if ( isLockedFont( config.fonts?.[ index ] ) ) {
			return;
		}
		setConfig( {
			...config,
			fonts: config.fonts.filter( ( _, i ) => i !== index ),
		} );
	};

	const primaryColor =
		config.colors?.find(
			( c ) => /primary/i.test( c.slug ) || /primary/i.test( c.name )
		)?.color ||
		config.colors?.[ 0 ]?.color ||
		'#4f46e5';
	const textColor =
		config.colors?.find( ( c ) =>
			/text|ink|foreground|on-surface/i.test( c.slug )
		)?.color || '#131b2e';
	const mutedColor =
		config.colors?.find( ( c ) => /muted|secondary|outline/i.test( c.slug ) )
			?.color || '#464555';
	const previewFont =
		config?.fonts?.[ previewFontIndex ] || config?.fonts?.[ 0 ];

	const fontFamily = toCssFontFamily( previewFont?.family );
	const headingSize =
		config.fontSizes?.find( ( s ) => s.slug === 'large' || s.slug === 'x-large' )
			?.size || '1.75rem';
	const bodySize =
		config.fontSizes?.find( ( s ) => s.slug === 'medium' || s.slug === 'normal' )
			?.size || '1rem';

	return (
		<div className="bm-theme-page bm-rise mx-auto flex w-full max-w-[1600px] flex-col px-gutter py-stack-lg font-sans">
			<nav
				className="bm-settings-tabs"
				aria-label={ __( 'Settings sections', 'joc-blockora-morph' ) }
			>
				<button
					type="button"
					className={
						settingsTab === 'general'
							? 'bm-settings-tab is-active'
							: 'bm-settings-tab'
					}
					onClick={ () => setSettingsTab( 'general' ) }
				>
					{ __( 'General', 'joc-blockora-morph' ) }
				</button>
				<button
					type="button"
					className={
						settingsTab === 'system'
							? 'bm-settings-tab is-active'
							: 'bm-settings-tab'
					}
					onClick={ () => setSettingsTab( 'system' ) }
				>
					{ __( 'System', 'joc-blockora-morph' ) }
				</button>
			</nav>

			{ settingsTab === 'system' ? (
			<>
			<header className="mb-stack-md flex flex-col justify-between gap-4 sm:flex-row sm:items-start">
				<div className="min-w-0 space-y-1">
					<p className="text-caps-micro font-bold uppercase tracking-widest text-outline">
						{ __( 'Global Settings', 'joc-blockora-morph' ) }
					</p>
					<h1 className="text-display-sm text-on-background">
						{ __( 'System', 'joc-blockora-morph' ) }
					</h1>
					<p className="max-w-2xl text-body-lg text-on-surface-variant">
						{ __(
							'Maintenance tools for this plugin. Destructive actions cannot be undone.',
							'joc-blockora-morph'
						) }
					</p>
				</div>
			</header>
				<section className="bm-system-panel bm-card">
					<div className="bm-system-feature">
						<div className="bm-system-feature__copy">
							<h2 className="bm-system-feature__title">
								{ __( 'Frontend editor', 'joc-blockora-morph' ) }
							</h2>
							<p className="bm-system-feature__text">
								{ __(
									'Allow logged-in users with edit permission to open Blockora Morph’s pencil editor on the front of singular posts and pages.',
									'joc-blockora-morph'
								) }
							</p>
						</div>
						<ToggleControl
							label={ __( 'Enable frontend editor', 'joc-blockora-morph' ) }
							checked={ Boolean( systemSettings?.frontendEditor ) }
							disabled={ ! systemSettings || savingSystem }
							onChange={ async ( next ) => {
								const enabled = Boolean( next );
								setSystemSettings( ( prev ) => ( {
									...( prev || {} ),
									frontendEditor: enabled,
								} ) );
								setSavingSystem( true );
								try {
									const saved = await api.put( '/system/settings', {
										frontendEditor: enabled,
									} );
									setSystemSettings( saved );
								} catch ( e ) {
									setSystemSettings( ( prev ) => ( {
										...( prev || {} ),
										frontendEditor: ! enabled,
									} ) );
									window.alert(
										e?.message ||
											__(
												'Could not update system settings.',
												'joc-blockora-morph'
											)
									);
								} finally {
									setSavingSystem( false );
								}
							} }
							__nextHasNoMarginBottom
						/>
					</div>
					<div className="bm-system-danger">
						<div className="bm-system-danger__icon" aria-hidden="true">
							<span className="dashicons dashicons-warning" />
						</div>
						<div className="bm-system-danger__copy">
							<h2 className="bm-system-danger__title">
								{ __( 'Delete all Blockora Morph data', 'joc-blockora-morph' ) }
							</h2>
							<p className="bm-system-danger__text">
								{ __(
									'Permanently removes Gutenberg blocks, shortcodes, library rows, generated CSS, and brand settings from the database. The template library is re-seeded afterward so you can start fresh.',
									'joc-blockora-morph'
								) }
							</p>
							<ul className="bm-system-danger__list">
								<li>{ __( 'My Gutenberg blocks', 'joc-blockora-morph' ) }</li>
								<li>{ __( 'Shortcode blocks', 'joc-blockora-morph' ) }</li>
								<li>{ __( 'Library / category data (then re-seeded)', 'joc-blockora-morph' ) }</li>
								<li>
									{ __(
										'Global settings (fonts, colors, sizes → factory defaults)',
										'joc-blockora-morph'
									) }
								</li>
								<li>{ __( 'Generated CSS files', 'joc-blockora-morph' ) }</li>
							</ul>
							<button
								type="button"
								className="bm-btn bm-btn--danger"
								onClick={ () => {
									setResetConfirm( '' );
									setResetOpen( true );
								} }
							>
								{ __( 'Delete all data…', 'joc-blockora-morph' ) }
							</button>
						</div>
					</div>
				</section>
			</>
			) : (
			<div className="bm-general-shell">
				<nav
					className="bm-general-nav"
					aria-label={ __( 'General sections', 'joc-blockora-morph' ) }
				>
					<button
						type="button"
						className={
							generalSection === 'brand'
								? 'bm-general-nav__item is-active'
								: 'bm-general-nav__item'
						}
						onClick={ () => setGeneralSection( 'brand' ) }
					>
						<span
							className="bm-general-nav__icon"
							aria-hidden="true"
						>
							<span className="dashicons dashicons-art" />
						</span>
						<span className="bm-general-nav__copy">
							<span className="bm-general-nav__label">
								{ __( 'Brand', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-general-nav__hint">
								{ __(
									'Fonts, colors & sizes',
									'joc-blockora-morph'
								) }
							</span>
						</span>
					</button>
					<button
						type="button"
						className={
							generalSection === 'icons'
								? 'bm-general-nav__item is-active'
								: 'bm-general-nav__item'
						}
						onClick={ () => setGeneralSection( 'icons' ) }
					>
						<span
							className="bm-general-nav__icon"
							aria-hidden="true"
						>
							<span className="dashicons dashicons-star-filled" />
						</span>
						<span className="bm-general-nav__copy">
							<span className="bm-general-nav__label">
								{ __( 'Icons', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-general-nav__hint">
								{ __(
									'Libraries & catalogs',
									'joc-blockora-morph'
								) }
							</span>
						</span>
					</button>
				</nav>

				<div className="bm-general-main">
					<header className="bm-general-main__header">
						<div className="bm-general-main__heading">
							<p className="text-caps-micro font-bold uppercase tracking-widest text-outline">
								{ __( 'Global Settings', 'joc-blockora-morph' ) }
							</p>
							<h1 className="text-display-sm text-on-background">
								{ generalSection === 'icons'
									? __( 'Icons', 'joc-blockora-morph' )
									: __( 'Brand tokens', 'joc-blockora-morph' ) }
							</h1>
							<p className="max-w-2xl text-body-lg text-on-surface-variant">
								{ generalSection === 'icons'
									? __(
											'Enable icon libraries for button and content pickers. Dashicons and Lucide stay on; add a stylesheet URL to load Font Awesome, Material, or a custom set.',
											'joc-blockora-morph'
									  )
									: __(
											'Brand tokens for Blockora Morph pickers and optional Gutenberg presets. Your active theme keeps its own colors and fonts — Blockora Morph adds prefixed tokens and does not replace the theme.',
											'joc-blockora-morph'
									  ) }
							</p>
						</div>
						{ generalSection === 'brand' ? (
							<button
								type="button"
								className="bm-btn bm-btn--primary shrink-0"
								onClick={ save }
								disabled={ saving }
							>
								{ saving
									? __( 'Saving…', 'joc-blockora-morph' )
									: __( 'Save theme', 'joc-blockora-morph' ) }
							</button>
						) : null }
					</header>

			{ generalSection === 'icons' ? (
			<IconLibrariesPanel
				libraries={ iconLibraries || defaultIconLibraries() }
				onChange={ setIconLibraries }
				saving={ savingIcons }
				onSave={ async () => {
					setSavingIcons( true );
					try {
						const saved = await api.put( '/system/settings', {
							iconLibraries:
								iconLibraries || defaultIconLibraries(),
						} );
						setSystemSettings( saved );
						setIconLibraries(
							Array.isArray( saved?.iconLibraries )
								? saved.iconLibraries
								: iconLibraries
						);
						if ( typeof window !== 'undefined' ) {
							window.jocbmAdmin = {
								...( window.jocbmAdmin || {} ),
								iconLibraries: {
									libraries:
										saved?.iconLibraries ||
										iconLibraries,
								},
							};
						}
					} catch ( e ) {
						window.alert(
							e?.message ||
								__(
									'Could not save icon libraries.',
									'joc-blockora-morph'
								)
						);
					} finally {
						setSavingIcons( false );
					}
				} }
			/>
			) : (
			<>
			<div className="bm-theme-layout">
				<aside className="bm-theme-sidebar">
					<section className="bm-theme-section">
						<div className="bm-theme-section__head">
							<strong className="bm-theme-section__title">
								{ __( 'Fonts', 'joc-blockora-morph' ) }
							</strong>
							<button
								type="button"
								className="bm-btn bm-btn--ghost bm-btn--sm"
								onClick={ openAddFont }
							>
								{ __( 'Add', 'joc-blockora-morph' ) }
							</button>
						</div>
						<div className="bm-theme-font-table-wrap">
							<table className="bm-theme-font-table">
								<thead>
									<tr>
										<th scope="col">
											{ __( 'Family', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											{ __( 'Source', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											<span className="screen-reader-text">
												{ __( 'Actions', 'joc-blockora-morph' ) }
											</span>
										</th>
									</tr>
								</thead>
								<tbody>
									{ config.fonts.map( ( font, i ) => {
										const locked = isLockedFont( font );
										return (
										<tr
											key={ font.slug || i }
											className={
												[
													previewFontIndex === i
														? 'is-previewing'
														: '',
													locked ? 'is-locked' : '',
												]
													.filter( Boolean )
													.join( ' ' ) || undefined
											}
											onClick={ () =>
												setPreviewFontIndex( i )
											}
										>
											<td className="bm-theme-font-table__name">
												<span
													className="bm-theme-font-table__face"
													style={ {
														fontFamily:
															toCssFontFamily(
																font.family
															),
													} }
												>
													{ font.family || '—' }
												</span>
												{ locked ? (
													<span className="bm-theme-font-table__badge">
														{ __(
															'Built-in',
															'joc-blockora-morph'
														) }
													</span>
												) : null }
											</td>
											<td>
												<code
													className="bm-theme-font-table__source"
													title={ font.source || '' }
												>
													{ font.source
														? font.source.replace(
																/^https?:\/\//i,
																''
														  )
														: '—' }
												</code>
											</td>
											<td className="bm-theme-font-table__actions">
												{ locked ? (
													<span
														className="bm-theme-font-table__locked"
														title={ __(
															'Built-in fonts cannot be edited or removed',
															'joc-blockora-morph'
														) }
													>
														<span
															className="dashicons dashicons-lock"
															aria-hidden="true"
														/>
														<span className="screen-reader-text">
															{ __(
																'Locked',
																'joc-blockora-morph'
															) }
														</span>
													</span>
												) : (
													<>
														<button
															type="button"
															className="bm-theme-font-table__btn"
															onClick={ ( e ) => {
																e.stopPropagation();
																openEditFont( i );
															} }
															aria-label={ __(
																'Edit font',
																'joc-blockora-morph'
															) }
															title={ __(
																'Edit',
																'joc-blockora-morph'
															) }
														>
															<span
																className="dashicons dashicons-edit"
																aria-hidden="true"
															/>
														</button>
														<button
															type="button"
															className="bm-theme-font-table__btn is-danger"
															onClick={ ( e ) => {
																e.stopPropagation();
																removeFont( i );
															} }
															aria-label={ __(
																'Delete font',
																'joc-blockora-morph'
															) }
															title={ __(
																'Delete',
																'joc-blockora-morph'
															) }
														>
															<span
																className="dashicons dashicons-trash"
																aria-hidden="true"
															/>
														</button>
													</>
												) }
											</td>
										</tr>
										);
									} ) }
								</tbody>
							</table>
						</div>
					</section>

					{ themeFontFamilies.length ? (
						<section className="bm-theme-section">
							<div className="bm-theme-section__head">
								<strong className="bm-theme-section__title">
									{ __(
										'Theme fonts',
										'joc-blockora-morph'
									) }
								</strong>
								<span className="bm-theme-font-table__badge">
									{ __( 'Read-only', 'joc-blockora-morph' ) }
								</span>
							</div>
							<p className="bm-theme-section__hint">
								{ __(
									'Fonts from your active WordPress theme. Available in all Blockora Morph font pickers; manage them in the theme or Site Editor.',
									'joc-blockora-morph'
								) }
							</p>
							<div className="bm-theme-font-table-wrap">
								<table className="bm-theme-font-table bm-theme-font-table--theme">
									<thead>
										<tr>
											<th scope="col">
												{ __(
													'Family',
													'joc-blockora-morph'
												) }
											</th>
											<th scope="col">
												{ __(
													'CSS',
													'joc-blockora-morph'
												) }
											</th>
										</tr>
									</thead>
									<tbody>
										{ themeFontFamilies.map( ( font, i ) => (
											<tr
												key={
													font.slug ||
													font.fontFamily ||
													`theme-font-${ i }`
												}
											>
												<td className="bm-theme-font-table__name">
													<span
														className="bm-theme-font-table__face"
														style={ {
															fontFamily:
																font.fontFamily,
														} }
													>
														{ font.name ||
															font.slug ||
															'—' }
													</span>
													<span className="bm-theme-font-table__badge">
														{ __(
															'Theme',
															'joc-blockora-morph'
														) }
													</span>
												</td>
												<td>
													<code
														className="bm-theme-font-table__source"
														title={
															font.fontFamily ||
															''
														}
													>
														{ font.fontFamily ||
															'—' }
													</code>
												</td>
											</tr>
										) ) }
									</tbody>
								</table>
							</div>
						</section>
					) : null }

					<section className="bm-theme-section">
						<div className="bm-theme-section__head">
							<strong className="bm-theme-section__title">
								{ __( 'Colors', 'joc-blockora-morph' ) }
							</strong>
							<button
								type="button"
								className="bm-btn bm-btn--ghost bm-btn--sm"
								onClick={ openAddColor }
							>
								{ __( 'Add', 'joc-blockora-morph' ) }
							</button>
						</div>
						<div className="bm-theme-font-table-wrap">
							<table className="bm-theme-font-table bm-theme-font-table--colors">
								<thead>
									<tr>
										<th scope="col">
											<span className="screen-reader-text">
												{ __( 'Swatch', 'joc-blockora-morph' ) }
											</span>
										</th>
										<th scope="col">
											{ __( 'Name', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											{ __( 'Color', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											<span className="screen-reader-text">
												{ __( 'Actions', 'joc-blockora-morph' ) }
											</span>
										</th>
									</tr>
								</thead>
								<tbody>
									{ config.colors.map( ( color, i ) => (
										<tr key={ color.slug || i }>
											<td className="bm-theme-font-table__swatch">
												<span
													className="bm-theme-table-swatch"
													style={ {
														background:
															color.color ||
															'#888888',
													} }
													title={ color.color }
												/>
											</td>
											<td className="bm-theme-font-table__name">
												{ color.name || '—' }
											</td>
											<td>
												<code>
													{ color.color || '—' }
												</code>
											</td>
											<td className="bm-theme-font-table__actions">
												<button
													type="button"
													className="bm-theme-font-table__btn"
													onClick={ () =>
														openEditColor( i )
													}
													aria-label={ __(
														'Edit color',
														'joc-blockora-morph'
													) }
													title={ __(
														'Edit',
														'joc-blockora-morph'
													) }
												>
													<span
														className="dashicons dashicons-edit"
														aria-hidden="true"
													/>
												</button>
												<button
													type="button"
													className="bm-theme-font-table__btn is-danger"
													onClick={ () =>
														removeColor( i )
													}
													disabled={
														config.colors.length <=
														1
													}
													aria-label={ __(
														'Delete color',
														'joc-blockora-morph'
													) }
													title={ __(
														'Delete',
														'joc-blockora-morph'
													) }
												>
													<span
														className="dashicons dashicons-trash"
														aria-hidden="true"
													/>
												</button>
											</td>
										</tr>
									) ) }
								</tbody>
							</table>
						</div>
					</section>

					<section className="bm-theme-section">
						<div className="bm-theme-section__head">
							<strong className="bm-theme-section__title">
								{ __( 'Font sizes', 'joc-blockora-morph' ) }
							</strong>
							<button
								type="button"
								className="bm-btn bm-btn--ghost bm-btn--sm"
								onClick={ openAddFontSize }
							>
								{ __( 'Add', 'joc-blockora-morph' ) }
							</button>
						</div>
						<div className="bm-theme-font-table-wrap">
							<table className="bm-theme-font-table">
								<thead>
									<tr>
										<th scope="col">
											{ __( 'Name', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											{ __( 'Size', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											{ __( 'Line height', 'joc-blockora-morph' ) }
										</th>
										<th scope="col">
											<span className="screen-reader-text">
												{ __( 'Actions', 'joc-blockora-morph' ) }
											</span>
										</th>
									</tr>
								</thead>
								<tbody>
									{ config.fontSizes.map( ( size, i ) => {
										const locked = isLockedFontSize( size );
										return (
										<tr
											key={ size.slug || i }
											className={
												locked ? 'is-locked' : undefined
											}
										>
											<td className="bm-theme-font-table__name">
												{ size.name || '—' }
												{ locked ? (
													<span className="bm-theme-font-table__badge">
														{ __(
															'Built-in',
															'joc-blockora-morph'
														) }
													</span>
												) : null }
											</td>
											<td>
												<code>{ size.size || '—' }</code>
											</td>
											<td>
												<code>
													{ size.lineHeight || '—' }
												</code>
											</td>
											<td className="bm-theme-font-table__actions">
												{ locked ? (
													<span
														className="bm-theme-font-table__locked"
														title={ __(
															'Built-in sizes cannot be edited or removed',
															'joc-blockora-morph'
														) }
													>
														<span
															className="dashicons dashicons-lock"
															aria-hidden="true"
														/>
														<span className="screen-reader-text">
															{ __(
																'Locked',
																'joc-blockora-morph'
															) }
														</span>
													</span>
												) : (
													<>
														<button
															type="button"
															className="bm-theme-font-table__btn"
															onClick={ () =>
																openEditFontSize( i )
															}
															aria-label={ __(
																'Edit font size',
																'joc-blockora-morph'
															) }
															title={ __(
																'Edit',
																'joc-blockora-morph'
															) }
														>
															<span
																className="dashicons dashicons-edit"
																aria-hidden="true"
															/>
														</button>
														<button
															type="button"
															className="bm-theme-font-table__btn is-danger"
															onClick={ () =>
																removeFontSize( i )
															}
															aria-label={ __(
																'Delete font size',
																'joc-blockora-morph'
															) }
															title={ __(
																'Delete',
																'joc-blockora-morph'
															) }
														>
															<span
																className="dashicons dashicons-trash"
																aria-hidden="true"
															/>
														</button>
													</>
												) }
											</td>
										</tr>
										);
									} ) }
								</tbody>
							</table>
						</div>
					</section>
				</aside>

				<section className="bm-theme-preview">
					<div className="bm-theme-preview__head">
						<div className="bm-theme-preview__head-copy">
							<h2 className="m-0 text-headline-md text-on-surface">
								{ __( 'Live preview', 'joc-blockora-morph' ) }
							</h2>
							<p className="mt-1 mb-0 text-body-md text-on-surface-variant">
								{ __(
									'Sample text using your brand tokens.',
									'joc-blockora-morph'
								) }
							</p>
						</div>
						{ previewFontOptions.length ? (
							<div className="bm-theme-preview__font">
								<SearchableSelect
									label={ __( 'Preview font', 'joc-blockora-morph' ) }
									value={ String( previewFontIndex ) }
									options={ previewFontOptions }
									onChange={ ( next ) => {
										const index = Number.parseInt( next, 10 );
										if ( Number.isFinite( index ) ) {
											setPreviewFontIndex( index );
										}
									} }
								/>
							</div>
						) : null }
					</div>
					<div className="bm-theme-preview__stage">
						<PreviewFrame
							className="bm-theme-preview__frame min-h-0 flex-1 border-0"
							frameClassName="min-h-[420px]"
							showLabel={ false }
							minHeight={ 420 }
						>
							<div className="bm-theme-preview__sample" style={ { fontFamily } }>
								<p
									className="m-0 mb-3 text-caps-micro font-bold uppercase tracking-widest"
									style={ { color: mutedColor } }
								>
									{ __( 'Brand sample', 'joc-blockora-morph' ) }
								</p>
								<h3
									className="m-0 mb-3 font-semibold leading-tight"
									style={ {
										color: primaryColor,
										fontSize: headingSize,
									} }
								>
									{ __( 'Heading sample', 'joc-blockora-morph' ) }
								</h3>
								<p
									className="m-0 max-w-[42ch] leading-relaxed"
									style={ { color: textColor, fontSize: bodySize } }
								>
									{ __(
										'These tokens appear in the block editor color and typography pickers across JOC Blockora Morph.',
										'joc-blockora-morph'
									) }
								</p>
								<div className="mt-6 flex flex-wrap gap-2">
									{ ( config.colors || [] ).map( ( color ) => (
										<div
											key={ color.slug }
											className="h-9 w-9 rounded-full border border-white/80 shadow-sm"
											style={ { background: color.color } }
											title={ color.name }
										/>
									) ) }
								</div>
								<div className="mt-6 flex flex-wrap gap-3">
									{ ( config.fontSizes || [] ).map( ( size ) => (
										<span
											key={ size.slug }
											className="rounded-md border border-outline-variant/40 bg-white/70 px-2.5 py-1 text-[11px] font-semibold text-on-surface"
											style={ {
												fontFamily,
												fontSize: size.size,
												lineHeight: size.lineHeight || undefined,
											} }
										>
											{ size.name }
										</span>
									) ) }
								</div>
							</div>
						</PreviewFrame>
					</div>
				</section>
			</div>
			</>
			) }
				</div>
			</div>
			) }

			<ConfirmModal
				open={ resetOpen }
				title={ __( 'Delete all Blockora Morph data?', 'joc-blockora-morph' ) }
				description={ __(
					'This cannot be undone. Gutenberg blocks, shortcodes, brand settings, and generated CSS will be removed. The library will be re-seeded.',
					'joc-blockora-morph'
				) }
				icon="warning"
				tone="danger"
				busy={ resetting }
				confirmDisabled={ resetConfirm !== 'DELETE' }
				confirmLabel={ __( 'Delete everything', 'joc-blockora-morph' ) }
				onConfirm={ runReset }
				onCancel={ () => {
					if ( ! resetting ) {
						setResetOpen( false );
						setResetConfirm( '' );
					}
				} }
			>
				<div className="space-y-3">
					<div className="bm-confirm-modal__meta">
						<div className="bm-confirm-modal__meta-row">
							<span className="bm-confirm-modal__meta-label">
								{ __( 'Action', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-confirm-modal__meta-value">
								{ __( 'Full database wipe', 'joc-blockora-morph' ) }
							</span>
						</div>
					</div>
					<TextControl
						label={ __(
							'Type DELETE to confirm',
							'joc-blockora-morph'
						) }
						className="bm-style-field"
						value={ resetConfirm }
						onChange={ ( next ) => setResetConfirm( next || '' ) }
						placeholder="DELETE"
						__nextHasNoMarginBottom
						__next40pxDefaultSize
					/>
					{ resetConfirm && resetConfirm !== 'DELETE' ? (
						<p className="m-0 text-label-md" style={ { color: 'var(--bm-color-danger)' } }>
							{ __(
								'Confirmation text must match DELETE exactly.',
								'joc-blockora-morph'
							) }
						</p>
					) : null }
				</div>
			</ConfirmModal>

			<ConfirmModal
				open={ !! fontEditor }
				title={
					fontEditor?.index === null
						? __( 'Add font', 'joc-blockora-morph' )
						: __( 'Edit font', 'joc-blockora-morph' )
				}
				icon="editor-textcolor"
				confirmLabel={ __( 'Save', 'joc-blockora-morph' ) }
				onConfirm={ saveFontEditor }
				onCancel={ closeFontEditor }
			>
				{ fontEditor ? (
					<div className="bm-theme-font-editor space-y-3">
						<TextControl
							label={ __( 'Family', 'joc-blockora-morph' ) }
							className="bm-style-field"
							value={ fontEditor.draft.family }
							onChange={ ( next ) =>
								updateFontDraft( 'family', next || '' )
							}
							placeholder={ __( 'e.g. Chango', 'joc-blockora-morph' ) }
							__nextHasNoMarginBottom
							__next40pxDefaultSize
						/>
						<TextControl
							label={ __( 'CSS source URL', 'joc-blockora-morph' ) }
							className="bm-style-field"
							type="url"
							value={ fontEditor.draft.source }
							onChange={ ( next ) =>
								updateFontDraft( 'source', next || '' )
							}
							placeholder="https://example.com/fonts/my-font.css"
							help={ __(
								'Optional stylesheet URL (Google Fonts, Adobe Fonts, self-hosted CSS). Leave empty for system fonts.',
								'joc-blockora-morph'
							) }
							__nextHasNoMarginBottom
							__next40pxDefaultSize
						/>
					</div>
				) : null }
			</ConfirmModal>

			<ConfirmModal
				open={ !! colorEditor }
				title={
					colorEditor?.index === null
						? __( 'Add color', 'joc-blockora-morph' )
						: __( 'Edit color', 'joc-blockora-morph' )
				}
				icon="art"
				confirmLabel={ __( 'Save', 'joc-blockora-morph' ) }
				onConfirm={ saveColorEditor }
				onCancel={ closeColorEditor }
			>
				{ colorEditor ? (
					<div className="bm-theme-font-editor bm-theme-color-editor space-y-3">
						<TextControl
							label={ __( 'Name', 'joc-blockora-morph' ) }
							className="bm-style-field"
							value={ colorEditor.draft.name }
							onChange={ ( next ) =>
								updateColorDraft( 'name', next || '' )
							}
							placeholder={ __( 'e.g. Primary', 'joc-blockora-morph' ) }
							__nextHasNoMarginBottom
							__next40pxDefaultSize
						/>
						<div className="bm-theme-color-editor__swatch-row">
							<ThemeColorSwatch
								label={
									colorEditor.draft.name ||
									__( 'Color', 'joc-blockora-morph' )
								}
								value={ colorEditor.draft.color }
								onChange={ ( next ) =>
									updateColorDraft( 'color', next || '#888888' )
								}
								colors={ paletteColors }
							/>
							<TextControl
								label={ __( 'Hex', 'joc-blockora-morph' ) }
								className="bm-style-field bm-theme-color-editor__hex"
								value={ colorEditor.draft.color }
								onChange={ ( next ) =>
									updateColorDraft(
										'color',
										next || '#888888'
									)
								}
								placeholder="#888888"
								__nextHasNoMarginBottom
								__next40pxDefaultSize
							/>
						</div>
					</div>
				) : null }
			</ConfirmModal>

			<ConfirmModal
				open={ !! fontSizeEditor }
				title={
					fontSizeEditor?.index === null
						? __( 'Add font size', 'joc-blockora-morph' )
						: __( 'Edit font size', 'joc-blockora-morph' )
				}
				icon="editor-textcolor"
				confirmLabel={ __( 'Save', 'joc-blockora-morph' ) }
				onConfirm={ saveFontSizeEditor }
				onCancel={ closeFontSizeEditor }
			>
				{ fontSizeEditor ? (
					<div className="bm-theme-font-editor space-y-3">
						<TextControl
							label={ __( 'Name', 'joc-blockora-morph' ) }
							className="bm-style-field"
							value={ fontSizeEditor.draft.name }
							onChange={ ( next ) =>
								updateFontSizeDraft( 'name', next || '' )
							}
							placeholder={ __( 'e.g. Medium', 'joc-blockora-morph' ) }
							__nextHasNoMarginBottom
							__next40pxDefaultSize
						/>
						<BaseControl
							label={ __( 'Font size', 'joc-blockora-morph' ) }
							className="bm-style-field bm-style-field--font-size"
						>
							<FontSizePicker
								fontSizes={ pickerSizes }
								value={ fontSizeEditor.draft.size || undefined }
								onChange={ ( next ) =>
									updateFontSizeDraft( 'size', next || '' )
								}
								withReset
								__nextHasNoMarginBottom
								__next40pxDefaultSize
							/>
						</BaseControl>
						<TextControl
							label={ __( 'Line height', 'joc-blockora-morph' ) }
							className="bm-style-field"
							value={ fontSizeEditor.draft.lineHeight }
							onChange={ ( next ) =>
								updateFontSizeDraft( 'lineHeight', next || '' )
							}
							placeholder={ __( 'e.g. 1.5', 'joc-blockora-morph' ) }
							__nextHasNoMarginBottom
							__next40pxDefaultSize
						/>
					</div>
				) : null }
			</ConfirmModal>
		</div>
	);
}
