import { useState, useEffect, useMemo, render } from '@wordpress/element';

const SUPPORT_URL = 'https://www.codesmade.com/contact-us/';

const QUICK_FILTER_OPTIONS = [
	{ value: 'all', label: 'All Products' },
	{ value: 'featured', label: 'Featured' },
	{ value: 'sale', label: 'On Sale' },
	{ value: 'bestsellers', label: 'Best Sellers' },
];

const LAYOUT_OPTIONS = [
	{ value: 'list', label: 'List', icon: '☰' },
	{ value: 'grid', label: 'Grid', icon: '▦' },
	{ value: 'table', label: 'Table', icon: '☷' },
];

const PAGINATION_OPTIONS = [
	{ value: 'loadmore', label: 'Load More Button' },
	{ value: 'numbered', label: 'Numbered Pages' },
	{ value: 'none', label: 'No Pagination' },
];

const HOVER_OPTIONS = [
	{ value: 'lift', label: 'Lift' },
	{ value: 'zoom', label: 'Zoom Image' },
	{ value: 'none', label: 'None' },
];

const COLUMN_LABELS = {
	image: 'Image',
	name: 'Product',
	sku: 'SKU',
	price: 'Price',
	categories: 'Categories',
	tags: 'Tags',
	attributes: 'Attributes',
	variations: 'Variations',
	rating: 'Rating',
	stock: 'Stock',
	cart: 'Add to Cart',
};

const ADDABLE_COLUMN_KEYS = Object.keys( COLUMN_LABELS );

const DEFAULT_COLUMNS = [
	{ key: 'image', label: 'Image', enabled: true },
	{ key: 'name', label: 'Product', enabled: true },
	{ key: 'sku', label: 'SKU', enabled: false },
	{ key: 'price', label: 'Price', enabled: true },
	{ key: 'categories', label: 'Categories', enabled: false },
	{ key: 'tags', label: 'Tags', enabled: false },
	{ key: 'attributes', label: 'Attributes', enabled: false },
	{ key: 'variations', label: 'Variations', enabled: false },
	{ key: 'rating', label: 'Rating', enabled: true },
	{ key: 'stock', label: 'Stock', enabled: false },
	{ key: 'cart', label: 'Add to Cart', enabled: false },
];

const DEFAULT_SETTINGS = {
	name: '',
	layout: 'list',

	select_type: 'all',
	select_tax_val: '',
	category_ids: [],
	tag_ids: [],
	attribute_taxonomy: '',
	attribute_term_ids: [],
	product_show: 5,
	order_by: 'post_title',
	order: 'ASC',
	in_stock_only: 'no',
	price_min: '',
	price_max: '',
	exclude_ids: '',

	columns: DEFAULT_COLUMNS,

	per_column: 3,
	columns_tablet: 2,
	columns_mobile: 1,
	title_length: 0,
	button_text: 'Add to Cart',
	show_count: 'no',
	empty_message: 'No products found.',
	container_width: '',
	card_gap: 18,
	pagination_mode: 'loadmore',
	custom_class: '',

	enable_search: 'no',
	enable_filters: 'no',
	sortable_columns: 'no',
	floating_cart: 'no',

	accent_color: '#6C4CF1',
	text_color: '#1E1B2E',
	border_color: '#E7E3F3',
	font_size: 13,
	border_radius: 12,
	border_width: 1,
	hover_effect: 'lift',
};

function apiGet( path ) {
	return fetch( gmwplwAdminData.restRoot + path, {
		headers: { 'X-WP-Nonce': gmwplwAdminData.nonce },
	} ).then( ( r ) => r.json() );
}

function apiPost( path, body ) {
	return fetch( gmwplwAdminData.restRoot + path, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			'X-WP-Nonce': gmwplwAdminData.nonce,
		},
		body: JSON.stringify( body ),
	} ).then( ( r ) => r.json() );
}

function apiDelete( path ) {
	return fetch( gmwplwAdminData.restRoot + path, {
		method: 'DELETE',
		headers: { 'X-WP-Nonce': gmwplwAdminData.nonce },
	} ).then( ( r ) => r.json() );
}

/* ---------------------------------------------------------------------- */
/* Shared bits                                                             */
/* ---------------------------------------------------------------------- */

function Icon( { name } ) {
	const paths = {
		plus: 'M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z',
		copy: 'M8 3h9a2 2 0 012 2v9h-2V5H8V3zM5 7h9a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V9a2 2 0 012-2z',
		trash: 'M9 3h6l1 2h4v2H4V5h4l1-2zM6 8h12l-1 12a2 2 0 01-2 2H9a2 2 0 01-2-2L6 8z',
		edit: 'M4 17.25V20h2.75L17.81 8.94l-2.75-2.75L4 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z',
		life: 'M12 2a10 10 0 100 20 10 10 0 000-20zm0 3.5a1.5 1.5 0 110 3 1.5 1.5 0 010-3zM13 17h-2v-6h2v6z',
		grip: 'M9 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm6-12a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm0 6a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z',
	};
	return (
		<svg className="gmwplw-icon" viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
			<path fill="currentColor" d={ paths[ name ] || '' } />
		</svg>
	);
}

function PageHeader() {
	return (
		<div className="gmwplw-page-header">
			<div className="gmwplw-page-header__brand">
				<span className="gmwplw-page-header__logo">▦</span>
				<div>
					<h1 className="gmwplw-page-header__title">Product Builders</h1>
					<p className="gmwplw-page-header__desc">
						Build reusable Table, Grid, and List layouts for WooCommerce products.
					</p>
				</div>
			</div>
			<a
				className="gmwplw-admin-btn gmwplw-admin-btn--outline gmwplw-page-header__support"
				href={ SUPPORT_URL }
				target="_blank"
				rel="noopener noreferrer"
			>
				<Icon name="life" /> Support
			</a>
		</div>
	);
}

function Toggle( { checked, onChange, label } ) {
	return (
		<button
			type="button"
			role="switch"
			aria-checked={ checked }
			className={ 'gmwplw-toggle' + ( checked ? ' is-on' : '' ) }
			onClick={ () => onChange( ! checked ) }
		>
			<span className="gmwplw-toggle__track">
				<span className="gmwplw-toggle__thumb" />
			</span>
			{ label && <span className="gmwplw-toggle__label">{ label }</span> }
		</button>
	);
}

function PillGroup( { options, value, onChange, name } ) {
	return (
		<div className="gmwplw-admin-pills" role="radiogroup" aria-label={ name }>
			{ options.map( ( option ) => (
				<button
					key={ option.value }
					type="button"
					className={ 'gmwplw-admin-pill' + ( option.value === value ? ' is-active' : '' ) }
					onClick={ () => onChange( option.value ) }
				>
					{ option.icon && <span className="gmwplw-admin-pill__icon">{ option.icon }</span> }
					{ option.label }
				</button>
			) ) }
		</div>
	);
}

function Field( { label, hint, children } ) {
	return (
		<div className="gmwplw-admin-field">
			{ label && <label className="gmwplw-admin-field__label">{ label }</label> }
			{ children }
			{ hint && <p className="gmwplw-admin-field__hint">{ hint }</p> }
		</div>
	);
}

function CheckboxList( { options, selected, onChange } ) {
	const toggle = ( value ) => {
		const num = parseInt( value, 10 );
		if ( selected.includes( num ) ) {
			onChange( selected.filter( ( v ) => v !== num ) );
		} else {
			onChange( [ ...selected, num ] );
		}
	};

	if ( ! options.length ) {
		return <p className="gmwplw-admin-field__hint">None found.</p>;
	}

	return (
		<div className="gmwplw-checkbox-list">
			{ options.map( ( opt ) => (
				<label key={ opt.value } className="gmwplw-checkbox-item">
					<input
						type="checkbox"
						checked={ selected.includes( parseInt( opt.value, 10 ) ) }
						onChange={ () => toggle( opt.value ) }
					/>
					{ opt.label }
				</label>
			) ) }
		</div>
	);
}

function LayoutBadge( { layout } ) {
	return <span className={ 'gmwplw-admin-badge gmwplw-admin-badge--' + layout }>{ layout }</span>;
}

function ConfirmModal( { title, message, confirmLabel, onConfirm, onCancel } ) {
	return (
		<div className="gmwplw-modal-overlay" onClick={ onCancel }>
			<div className="gmwplw-modal" onClick={ ( e ) => e.stopPropagation() }>
				<h3 className="gmwplw-modal__title">{ title }</h3>
				<p className="gmwplw-modal__message">{ message }</p>
				<div className="gmwplw-modal__actions">
					<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--outline" onClick={ onCancel }>
						Cancel
					</button>
					<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--danger" onClick={ onConfirm }>
						{ confirmLabel }
					</button>
				</div>
			</div>
		</div>
	);
}

/* ---------------------------------------------------------------------- */
/* Builder list (no search/sort — kept intentionally simple)               */
/* ---------------------------------------------------------------------- */

function BuilderList( { onEdit, onCreate } ) {
	const [ loading, setLoading ] = useState( true );
	const [ builders, setBuilders ] = useState( [] );
	const [ pendingDelete, setPendingDelete ] = useState( null );
	const [ busyId, setBusyId ] = useState( null );

	const loadBuilders = () => {
		setLoading( true );
		apiGet( 'gmwplw/v1/builders' ).then( ( data ) => {
			setBuilders( data || [] );
			setLoading( false );
		} );
	};

	useEffect( () => {
		loadBuilders();
	}, [] );

	const handleDelete = ( id ) => {
		setBusyId( id );
		apiDelete( 'gmwplw/v1/builders/' + id ).then( () => {
			setPendingDelete( null );
			setBusyId( null );
			loadBuilders();
		} );
	};

	const handleDuplicate = ( id ) => {
		setBusyId( id );
		apiPost( 'gmwplw/v1/builders/' + id + '/duplicate', {} ).then( () => {
			setBusyId( null );
			loadBuilders();
		} );
	};

	const counts = useMemo( () => {
		const byLayout = { list: 0, grid: 0, table: 0 };
		builders.forEach( ( b ) => {
			if ( byLayout[ b.layout ] !== undefined ) {
				byLayout[ b.layout ]++;
			}
		} );
		return byLayout;
	}, [ builders ] );

	if ( loading ) {
		return (
			<div className="gmwplw-admin-card gmwplw-admin-loading">
				<span className="gmwplw-admin-spinner" />
			</div>
		);
	}

	return (
		<>
			<div className="gmwplw-stats-row">
				<div className="gmwplw-stat-card">
					<span className="gmwplw-stat-card__value">{ builders.length }</span>
					<span className="gmwplw-stat-card__label">Total Builders</span>
				</div>
				<div className="gmwplw-stat-card">
					<span className="gmwplw-stat-card__value">{ counts.list }</span>
					<span className="gmwplw-stat-card__label">List Layouts</span>
				</div>
				<div className="gmwplw-stat-card">
					<span className="gmwplw-stat-card__value">{ counts.grid }</span>
					<span className="gmwplw-stat-card__label">Grid Layouts</span>
				</div>
				<div className="gmwplw-stat-card">
					<span className="gmwplw-stat-card__value">{ counts.table }</span>
					<span className="gmwplw-stat-card__label">Table Layouts</span>
				</div>
			</div>

			<div className="gmwplw-admin-card">
				<div className="gmwplw-admin-listhead">
					<h2 className="gmwplw-admin-listhead__title">All Builders</h2>
					<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--primary" onClick={ onCreate }>
						<Icon name="plus" /> New Builder
					</button>
				</div>

				{ builders.length === 0 ? (
					<p className="gmwplw-admin-empty">No builders yet. Create your first one to get a shortcode.</p>
				) : (
					<table className="gmwplw-admin-table">
						<thead>
							<tr>
								<th>Name</th>
								<th>Layout</th>
								<th>Shortcode</th>
								<th />
							</tr>
						</thead>
						<tbody>
							{ builders.map( ( builder ) => (
								<tr key={ builder.id }>
									<td>{ builder.name }</td>
									<td><LayoutBadge layout={ builder.layout } /></td>
									<td>
										<code>{ '[gmwplw_product_layout id="' + builder.id + '"]' }</code>
									</td>
									<td className="gmwplw-admin-table__actions">
										<button
											type="button"
											className="gmwplw-admin-icon-btn"
											title="Edit"
											onClick={ () => onEdit( builder.id ) }
										>
											<Icon name="edit" />
										</button>
										<button
											type="button"
											className="gmwplw-admin-icon-btn"
											title="Duplicate"
											disabled={ busyId === builder.id }
											onClick={ () => handleDuplicate( builder.id ) }
										>
											<Icon name="copy" />
										</button>
										<button
											type="button"
											className="gmwplw-admin-icon-btn gmwplw-admin-icon-btn--danger"
											title="Delete"
											onClick={ () => setPendingDelete( builder ) }
										>
											<Icon name="trash" />
										</button>
									</td>
								</tr>
							) ) }
						</tbody>
					</table>
				) }
			</div>

			{ pendingDelete && (
				<ConfirmModal
					title="Delete builder?"
					message={ 'Delete “' + pendingDelete.name + '”? This cannot be undone and any shortcode using it will stop working.' }
					confirmLabel="Delete"
					onConfirm={ () => handleDelete( pendingDelete.id ) }
					onCancel={ () => setPendingDelete( null ) }
				/>
			) }
		</>
	);
}

/* ---------------------------------------------------------------------- */
/* Column builder (drag-and-drop, enable/disable, custom fields)          */
/* ---------------------------------------------------------------------- */

function ColumnBuilder( { columns, onChange } ) {
	const [ dragIndex, setDragIndex ] = useState( null );
	const [ newColumnKey, setNewColumnKey ] = useState( 'sku' );
	const [ customLabel, setCustomLabel ] = useState( '' );
	const [ customMetaKey, setCustomMetaKey ] = useState( '' );

	const move = ( from, to ) => {
		if ( to < 0 || to >= columns.length ) {
			return;
		}
		const next = columns.slice();
		const [ item ] = next.splice( from, 1 );
		next.splice( to, 0, item );
		onChange( next );
	};

	const toggleEnabled = ( index ) => {
		const next = columns.slice();
		next[ index ] = { ...next[ index ], enabled: ! next[ index ].enabled };
		onChange( next );
	};

	const removeColumn = ( index ) => {
		onChange( columns.filter( ( _, i ) => i !== index ) );
	};

	const addColumn = () => {
		if ( columns.some( ( c ) => c.key === newColumnKey ) ) {
			return;
		}
		onChange( [ ...columns, { key: newColumnKey, label: COLUMN_LABELS[ newColumnKey ], enabled: true } ] );
	};

	const addCustomField = () => {
		if ( ! customMetaKey.trim() ) {
			return;
		}
		onChange( [
			...columns,
			{
				key: 'custom',
				meta_key: customMetaKey.trim(),
				label: customLabel.trim() || customMetaKey.trim(),
				enabled: true,
			},
		] );
		setCustomLabel( '' );
		setCustomMetaKey( '' );
	};

	const availableKeys = ADDABLE_COLUMN_KEYS.filter( ( key ) => ! columns.some( ( c ) => c.key === key ) );

	return (
		<div className="gmwplw-column-builder">
			<p className="gmwplw-admin-field__hint">
				Drag rows (or use the arrows) to reorder columns. Toggle a column on/off, or remove it entirely.
			</p>

			<div className="gmwplw-column-list">
				{ columns.map( ( col, index ) => (
					<div
						key={ index }
						className={ 'gmwplw-column-row' + ( dragIndex === index ? ' is-dragging' : '' ) }
						draggable
						onDragStart={ () => setDragIndex( index ) }
						onDragOver={ ( e ) => e.preventDefault() }
						onDrop={ () => {
							if ( dragIndex !== null && dragIndex !== index ) {
								move( dragIndex, index );
							}
							setDragIndex( null );
						} }
						onDragEnd={ () => setDragIndex( null ) }
					>
						<span className="gmwplw-column-row__grip"><Icon name="grip" /></span>
						<span className="gmwplw-column-row__label">
							{ col.label || COLUMN_LABELS[ col.key ] || col.key }
							{ col.key === 'custom' && <span className="gmwplw-column-row__tag">custom field: { col.meta_key }</span> }
						</span>
						<span className="gmwplw-column-row__actions">
							<button type="button" className="gmwplw-mini-btn" onClick={ () => move( index, index - 1 ) } disabled={ index === 0 } title="Move up">↑</button>
							<button type="button" className="gmwplw-mini-btn" onClick={ () => move( index, index + 1 ) } disabled={ index === columns.length - 1 } title="Move down">↓</button>
							<Toggle checked={ !! col.enabled } onChange={ () => toggleEnabled( index ) } />
							<button type="button" className="gmwplw-mini-btn gmwplw-mini-btn--danger" onClick={ () => removeColumn( index ) } title="Remove">
								<Icon name="trash" />
							</button>
						</span>
					</div>
				) ) }
			</div>

			<div className="gmwplw-column-add">
				{ availableKeys.length > 0 && (
					<div className="gmwplw-column-add__row">
						<select className="gmwplw-admin-select" value={ newColumnKey } onChange={ ( e ) => setNewColumnKey( e.target.value ) }>
							{ availableKeys.map( ( key ) => (
								<option key={ key } value={ key }>{ COLUMN_LABELS[ key ] }</option>
							) ) }
						</select>
						<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--outline" onClick={ addColumn }>
							<Icon name="plus" /> Add Column
						</button>
					</div>
				) }

				<div className="gmwplw-column-add__row">
					<input
						type="text"
						className="gmwplw-admin-input"
						placeholder="Custom field meta key (e.g. _size_chart)"
						value={ customMetaKey }
						onChange={ ( e ) => setCustomMetaKey( e.target.value ) }
					/>
					<input
						type="text"
						className="gmwplw-admin-input"
						placeholder="Column label (optional)"
						value={ customLabel }
						onChange={ ( e ) => setCustomLabel( e.target.value ) }
					/>
					<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--outline" onClick={ addCustomField }>
						<Icon name="plus" /> Add Custom Field
					</button>
				</div>
			</div>
		</div>
	);
}

/* ---------------------------------------------------------------------- */
/* Builder editor                                                          */
/* ---------------------------------------------------------------------- */

const TABS = [
	{ key: 'general', label: 'General' },
	{ key: 'filters', label: 'Filters' },
	{ key: 'display', label: 'Display' },
	{ key: 'appearance', label: 'Appearance' },
	{ key: 'advanced', label: 'Advanced' },
];

function BuilderEditor( { builderId, onBack } ) {
	const isNew = ! builderId;

	const [ loading, setLoading ] = useState( ! isNew );
	const [ saving, setSaving ] = useState( false );
	const [ toast, setToast ] = useState( '' );
	const [ tab, setTab ] = useState( 'general' );
	const [ settings, setSettings ] = useState( DEFAULT_SETTINGS );
	const [ taxonomies, setTaxonomies ] = useState( [] );
	const [ terms, setTerms ] = useState( [] );
	const [ categories, setCategories ] = useState( [] );
	const [ tags, setTags ] = useState( [] );
	const [ attributeTaxonomies, setAttributeTaxonomies ] = useState( [] );
	const [ attributeTerms, setAttributeTerms ] = useState( [] );
	const [ shortcode, setShortcode ] = useState( '' );

	useEffect( () => {
		if ( isNew ) {
			return;
		}
		apiGet( 'gmwplw/v1/builders/' + builderId ).then( ( data ) => {
			setSettings( { ...DEFAULT_SETTINGS, ...data.settings } );
			setTaxonomies( data.taxonomies || [] );
			setTerms( data.terms || [] );
			setCategories( data.categories || [] );
			setTags( data.tags || [] );
			setAttributeTaxonomies( data.attributeTaxonomies || [] );
			setAttributeTerms( data.attributeTerms || [] );
			setShortcode( data.shortcode || '' );
			setLoading( false );
		} );
	}, [ builderId ] );

	const update = ( key, value ) => {
		setSettings( ( prev ) => ( { ...prev, [ key ]: value } ) );
	};

	const handleTypeChange = ( value ) => {
		update( 'select_type', value );
		update( 'select_tax_val', '' );

		const isCustomTaxonomy = taxonomies.some( ( tax ) => tax.value === value );
		if ( isCustomTaxonomy ) {
			apiGet( 'gmwplw/v1/taxonomy-terms/' + value ).then( ( data ) => setTerms( data || [] ) );
		} else {
			setTerms( [] );
		}
	};

	const handleAttributeTaxonomyChange = ( value ) => {
		update( 'attribute_taxonomy', value );
		update( 'attribute_term_ids', [] );
		if ( value ) {
			apiGet( 'gmwplw/v1/taxonomy-terms/' + value ).then( ( data ) => setAttributeTerms( data || [] ) );
		} else {
			setAttributeTerms( [] );
		}
	};

	const handleSave = () => {
		setSaving( true );

		const request = isNew
			? apiPost( 'gmwplw/v1/builders', { settings } )
			: apiPost( 'gmwplw/v1/builders/' + builderId, { settings } );

		request.then( ( data ) => {
			setSaving( false );
			if ( isNew && data && data.settings ) {
				setToast( 'Builder created!' );
				setShortcode( data.shortcode || '' );
				window.setTimeout( () => onBack(), 900 );
			} else {
				setToast( data && data.success ? 'Settings saved!' : 'Failed to save settings.' );
				window.setTimeout( () => setToast( '' ), 2400 );
			}
		} );
	};

	if ( loading ) {
		return (
			<div className="gmwplw-admin-card gmwplw-admin-loading">
				<span className="gmwplw-admin-spinner" />
			</div>
		);
	}

	const isCustomTaxonomySelected = taxonomies.some( ( tax ) => tax.value === settings.select_type );

	return (
		<div className="gmwplw-admin-card">
			<button type="button" className="gmwplw-admin-back" onClick={ onBack }>
				&larr; Back to Builders
			</button>

			<Field label="Builder Name">
				<input
					type="text"
					className="gmwplw-admin-input"
					value={ settings.name }
					placeholder="e.g. Homepage Featured Products"
					onChange={ ( e ) => update( 'name', e.target.value ) }
				/>
			</Field>

			{ shortcode && (
				<div className="gmwplw-admin-shortcode">
					<span>Shortcode</span>
					<code>{ shortcode }</code>
					<button
						type="button"
						className="gmwplw-copy-link"
						onClick={ () => {
							navigator.clipboard && navigator.clipboard.writeText( shortcode );
							setToast( 'Shortcode copied!' );
							window.setTimeout( () => setToast( '' ), 1800 );
						} }
					>
						<Icon name="copy" /> Copy
					</button>
				</div>
			) }

			<div className="gmwplw-tabs" role="tablist">
				{ TABS.map( ( t ) => (
					<button
						key={ t.key }
						type="button"
						role="tab"
						aria-selected={ tab === t.key }
						className={ 'gmwplw-tab' + ( tab === t.key ? ' is-active' : '' ) }
						onClick={ () => setTab( t.key ) }
					>
						{ t.label }
					</button>
				) ) }
			</div>

			{ tab === 'general' && (
				<div className="gmwplw-tabpanel">
					<Field label="Display Layout">
						<PillGroup name="Display Layout" options={ LAYOUT_OPTIONS } value={ settings.layout } onChange={ ( v ) => update( 'layout', v ) } />
					</Field>

					<Field label="Number of Products" hint="Use -1 to show all matching products.">
						<input
							type="number"
							className="gmwplw-admin-input"
							value={ settings.product_show }
							onChange={ ( e ) => update( 'product_show', e.target.value ) }
						/>
					</Field>

					{ settings.layout === 'grid' && (
						<>
							<Field label="Products Per Row (Desktop)">
								<input type="number" min="1" className="gmwplw-admin-input" value={ settings.per_column } onChange={ ( e ) => update( 'per_column', e.target.value ) } />
							</Field>
							<Field label="Products Per Row (Tablet)">
								<input type="number" min="1" className="gmwplw-admin-input" value={ settings.columns_tablet } onChange={ ( e ) => update( 'columns_tablet', e.target.value ) } />
							</Field>
							<Field label="Products Per Row (Mobile)">
								<input type="number" min="1" className="gmwplw-admin-input" value={ settings.columns_mobile } onChange={ ( e ) => update( 'columns_mobile', e.target.value ) } />
							</Field>
						</>
					) }

					<Field label="Order By">
						<select className="gmwplw-admin-select" value={ settings.order_by } onChange={ ( e ) => update( 'order_by', e.target.value ) }>
							<option value="post_title">Product Name</option>
							<option value="id">Product ID</option>
							<option value="date">Date Published</option>
							<option value="modified">Last Modified</option>
							<option value="price">Price</option>
							<option value="rand">Random</option>
							<option value="total_sales">Total Sales</option>
							<option value="none">None</option>
						</select>
					</Field>

					<Field label="Order">
						<PillGroup name="Order" options={ [ { value: 'ASC', label: 'Ascending' }, { value: 'DESC', label: 'Descending' } ] } value={ settings.order } onChange={ ( v ) => update( 'order', v ) } />
					</Field>
				</div>
			) }

			{ tab === 'filters' && (
				<div className="gmwplw-tabpanel">
					<Field label="Quick Filter">
						<PillGroup
							name="Quick Filter"
							options={ QUICK_FILTER_OPTIONS.concat( taxonomies.map( ( tax ) => ( { value: tax.value, label: tax.label } ) ) ) }
							value={ settings.select_type }
							onChange={ handleTypeChange }
						/>
					</Field>

					{ isCustomTaxonomySelected && (
						<Field label="Select Taxonomy Value">
							<select className="gmwplw-admin-select" value={ settings.select_tax_val } onChange={ ( e ) => update( 'select_tax_val', e.target.value ) }>
								<option value="">&mdash; choose &mdash;</option>
								{ terms.map( ( term ) => (
									<option key={ term.value } value={ term.value }>{ term.label }</option>
								) ) }
							</select>
						</Field>
					) }

					<Field label="Filter by Category" hint="Advanced query builder — leave empty to include all categories.">
						<CheckboxList options={ categories } selected={ settings.category_ids } onChange={ ( v ) => update( 'category_ids', v ) } />
					</Field>

					<Field label="Filter by Tag" hint="Leave empty to include all tags.">
						<CheckboxList options={ tags } selected={ settings.tag_ids } onChange={ ( v ) => update( 'tag_ids', v ) } />
					</Field>

					<Field label="Filter by Attribute">
						<select
							className="gmwplw-admin-select"
							value={ settings.attribute_taxonomy }
							onChange={ ( e ) => handleAttributeTaxonomyChange( e.target.value ) }
						>
							<option value="">&mdash; none &mdash;</option>
							{ attributeTaxonomies.map( ( attr ) => (
								<option key={ attr.value } value={ attr.value }>{ attr.label }</option>
							) ) }
						</select>
					</Field>

					{ settings.attribute_taxonomy && (
						<Field label="Attribute Values">
							<CheckboxList options={ attributeTerms } selected={ settings.attribute_term_ids } onChange={ ( v ) => update( 'attribute_term_ids', v ) } />
						</Field>
					) }

					<Field label="In Stock Only">
						<Toggle
							checked={ settings.in_stock_only === 'yes' }
							onChange={ ( v ) => update( 'in_stock_only', v ? 'yes' : 'no' ) }
							label={ settings.in_stock_only === 'yes' ? 'Only in-stock products' : 'Include out-of-stock products' }
						/>
					</Field>

					<Field label="Price Range" hint="Leave blank for no limit.">
						<div className="gmwplw-range-inputs">
							<input type="number" className="gmwplw-admin-input" placeholder="Min" value={ settings.price_min } onChange={ ( e ) => update( 'price_min', e.target.value ) } />
							<span className="gmwplw-range-sep">&mdash;</span>
							<input type="number" className="gmwplw-admin-input" placeholder="Max" value={ settings.price_max } onChange={ ( e ) => update( 'price_max', e.target.value ) } />
						</div>
					</Field>

					<Field label="Exclude Products" hint="Comma-separated product IDs to leave out of the results, e.g. 12, 45, 108.">
						<input type="text" className="gmwplw-admin-input" placeholder="e.g. 12, 45, 108" value={ settings.exclude_ids } onChange={ ( e ) => update( 'exclude_ids', e.target.value ) } />
					</Field>
				</div>
			) }

			{ tab === 'display' && (
				<div className="gmwplw-tabpanel">
					<Field label="Columns">
						<ColumnBuilder columns={ settings.columns } onChange={ ( v ) => update( 'columns', v ) } />
					</Field>

					<Field label="Title Length" hint="Number of words before truncating the product name. Use 0 for the full title.">
						<input type="number" min="0" className="gmwplw-admin-input" value={ settings.title_length } onChange={ ( e ) => update( 'title_length', e.target.value ) } />
					</Field>

					<Field label="Add to Cart Button Text">
						<input type="text" className="gmwplw-admin-input" value={ settings.button_text } onChange={ ( e ) => update( 'button_text', e.target.value ) } />
					</Field>

					<Field label="Show Results Count" hint="Displays “Showing X of Y products” above the list.">
						<Toggle checked={ settings.show_count === 'yes' } onChange={ ( v ) => update( 'show_count', v ? 'yes' : 'no' ) } />
					</Field>

					<Field label="Empty State Message" hint="Shown when no products match the filters above.">
						<input type="text" className="gmwplw-admin-input" value={ settings.empty_message } onChange={ ( e ) => update( 'empty_message', e.target.value ) } />
					</Field>

					<Field label="Container Max Width" hint="CSS value, e.g. 960px or 100%. Leave blank to fill the parent.">
						<input type="text" className="gmwplw-admin-input" placeholder="e.g. 960px" value={ settings.container_width } onChange={ ( e ) => update( 'container_width', e.target.value ) } />
					</Field>

					{ settings.layout === 'grid' && (
						<Field label="Card Gap (px)">
							<input type="number" min="0" className="gmwplw-admin-input" value={ settings.card_gap } onChange={ ( e ) => update( 'card_gap', e.target.value ) } />
						</Field>
					) }
				</div>
			) }

			{ tab === 'appearance' && (
				<div className="gmwplw-tabpanel">
					<Field label="Accent Color" hint="Used for prices, buttons, and highlights.">
						<div className="gmwplw-color-input">
							<input type="color" value={ settings.accent_color } onChange={ ( e ) => update( 'accent_color', e.target.value ) } />
							<input type="text" className="gmwplw-admin-input" value={ settings.accent_color } onChange={ ( e ) => update( 'accent_color', e.target.value ) } />
						</div>
					</Field>
					<Field label="Text Color">
						<div className="gmwplw-color-input">
							<input type="color" value={ settings.text_color } onChange={ ( e ) => update( 'text_color', e.target.value ) } />
							<input type="text" className="gmwplw-admin-input" value={ settings.text_color } onChange={ ( e ) => update( 'text_color', e.target.value ) } />
						</div>
					</Field>
					<Field label="Border Color">
						<div className="gmwplw-color-input">
							<input type="color" value={ settings.border_color } onChange={ ( e ) => update( 'border_color', e.target.value ) } />
							<input type="text" className="gmwplw-admin-input" value={ settings.border_color } onChange={ ( e ) => update( 'border_color', e.target.value ) } />
						</div>
					</Field>
					<Field label="Font Size (px)">
						<input type="number" min="10" max="24" className="gmwplw-admin-input" value={ settings.font_size } onChange={ ( e ) => update( 'font_size', e.target.value ) } />
					</Field>
					<Field label="Border Radius (px)">
						<input type="number" min="0" className="gmwplw-admin-input" value={ settings.border_radius } onChange={ ( e ) => update( 'border_radius', e.target.value ) } />
					</Field>
					<Field label="Border Width (px)">
						<input type="number" min="0" className="gmwplw-admin-input" value={ settings.border_width } onChange={ ( e ) => update( 'border_width', e.target.value ) } />
					</Field>
					<Field label="Hover Effect">
						<PillGroup name="Hover Effect" options={ HOVER_OPTIONS } value={ settings.hover_effect } onChange={ ( v ) => update( 'hover_effect', v ) } />
					</Field>
				</div>
			) }

			{ tab === 'advanced' && (
				<div className="gmwplw-tabpanel">
					<Field label="Pagination Style">
						<PillGroup name="Pagination Style" options={ PAGINATION_OPTIONS } value={ settings.pagination_mode } onChange={ ( v ) => update( 'pagination_mode', v ) } />
					</Field>

					<Field label="Front-end Search" hint="Lets visitors search within this widget's products.">
						<Toggle checked={ settings.enable_search === 'yes' } onChange={ ( v ) => update( 'enable_search', v ? 'yes' : 'no' ) } />
					</Field>

					<Field label="Front-end Filters" hint="Adds category, tag, attribute, price range, and in-stock filters above the widget.">
						<Toggle checked={ settings.enable_filters === 'yes' } onChange={ ( v ) => update( 'enable_filters', v ? 'yes' : 'no' ) } />
					</Field>

					<Field label="Sortable Columns" hint="Table layout only — lets visitors click Name/Price headers to sort.">
						<Toggle checked={ settings.sortable_columns === 'yes' } onChange={ ( v ) => update( 'sortable_columns', v ? 'yes' : 'no' ) } />
					</Field>

					<Field label="Floating Cart" hint="Shows a floating cart bubble so shoppers always see what they've added.">
						<Toggle checked={ settings.floating_cart === 'yes' } onChange={ ( v ) => update( 'floating_cart', v ? 'yes' : 'no' ) } />
					</Field>

					<Field label="Custom CSS Class" hint="Added to the widget's wrapper element for custom styling.">
						<input type="text" className="gmwplw-admin-input" placeholder="e.g. my-custom-widget" value={ settings.custom_class } onChange={ ( e ) => update( 'custom_class', e.target.value ) } />
					</Field>
				</div>
			) }

			<div className="gmwplw-admin-actionbar">
				<button type="button" className="gmwplw-admin-btn gmwplw-admin-btn--primary" disabled={ saving } onClick={ handleSave }>
					{ saving ? 'Saving\u2026' : isNew ? 'Create Builder' : 'Save Settings' }
				</button>
			</div>

			{ toast && <div className="gmwplw-admin-toast">{ toast }</div> }
		</div>
	);
}

function App() {
	const [ view, setView ] = useState( { mode: 'list', builderId: null } );

	return (
		<div className="gmwplw-page">
			<PageHeader />
			{ view.mode === 'edit' ? (
				<BuilderEditor
					builderId={ view.builderId }
					onBack={ () => setView( { mode: 'list', builderId: null } ) }
				/>
			) : (
				<BuilderList
					onEdit={ ( id ) => setView( { mode: 'edit', builderId: id } ) }
					onCreate={ () => setView( { mode: 'edit', builderId: null } ) }
				/>
			) }
			<div className="gmwplw-page-footer">
				Need help? Reach out any time via our{ ' ' }
				<a href={ SUPPORT_URL } target="_blank" rel="noopener noreferrer">support page</a>.
			</div>
		</div>
	);
}

render( <App />, document.getElementById( 'gmwplw-builder-app-root' ) );
