/**
 * SuiteMkt3k coupon designer (React).
 *
 * Two-card layout: configuration on the left, sticky live preview on the right.
 * Supports product restriction, multiple currencies, CTA/Name/Marketing colours,
 * popup image with opacity overlay, and an opt-in flow with re-openable popup.
 */
import { createRoot, useState, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

const cfg = window.SuiteMkt3k || {};

function hexToRgba(hex, alpha) {
	const raw = String(hex || '#FFFFFF').replace('#', '').trim();
	let h = raw;
	if (h.length === 3) {
		h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
	}
	if (h.length !== 6) {
		return `rgba(255,255,255,${alpha})`;
	}
	const r = parseInt(h.slice(0, 2), 16);
	const g = parseInt(h.slice(2, 4), 16);
	const b = parseInt(h.slice(4, 6), 16);
	return `rgba(${r},${g},${b},${alpha})`;
}

function ColorField({ label, value, onChange, fallback = '#2AB2E5' }) {
	const v = (value || fallback).toUpperCase();
	const isHex = (x) => /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/.test(x || '');
	const toFull = (x) => x.length === 4 ? '#' + x[1]+x[1]+x[2]+x[2]+x[3]+x[3] : x;
	return (
		<label className="wmk-field">
			<span>{label}</span>
			<div className="wmk-color">
				<span className="wmk-color-swatch" style={{ '--swatch': v }}>
					<input type="color" value={isHex(v) ? toFull(v) : fallback} onChange={(e) => onChange(e.target.value.toUpperCase())} />
				</span>
				<input className="wmk-input" type="text" maxLength="7" value={v}
					onChange={(e) => onChange(e.target.value.toUpperCase())}
					pattern="^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$" />
			</div>
		</label>
	);
}

function api(path, method, body) {
	return fetch(cfg.restUrl + path.replace(/^\/+/, ''), {
		method: method || 'GET',
		credentials: 'same-origin',
		headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
		body: body ? JSON.stringify(body) : undefined,
	}).then((r) => r.json().then((data) => ({ ok: r.ok, status: r.status, data })));
}

function pickMedia(title, onPick) {
	if (!window.wp || !window.wp.media) {
		alert(__('Media library is not available on this screen.', 'suitemkt3k'));
		return;
	}
	const frame = window.wp.media({
		title,
		library: { type: ['image'] },
		multiple: false,
		button: { text: __('Use this image', 'suitemkt3k') },
	});
	frame.on('select', () => {
		const att = frame.state().get('selection').first().toJSON();
		onPick(att);
	});
	frame.open();
}

/** Canonical opt-in form fields (email is always visible). */
function defaultFormFields() {
	return [
		{ key: 'name', label: __('Name', 'suitemkt3k'), required: true, enabled: true },
		{ key: 'email', label: __('Email', 'suitemkt3k'), required: true, enabled: true },
		{ key: 'birth_date', label: __('Birth date', 'suitemkt3k'), required: false, enabled: true },
	];
}

/**
 * Resolve a display label for a form field. Stock English labels baked into
 * saved designs are remapped so the admin locale translation is used.
 */
function resolveFormFieldLabel(field) {
	const key = field?.key || '';
	const label = String(field?.label || '');
	const stock = {
		name: ['', 'Name', 'Nombre'],
		email: ['', 'Email', 'E-mail', 'Correo electrónico'],
		birth_date: ['', 'Birth date', 'Date of birth', 'Date of bith', 'Fecha de nacimiento'],
	};
	const translated = {
		name: __('Name', 'suitemkt3k'),
		email: __('Email', 'suitemkt3k'),
		birth_date: __('Birth date', 'suitemkt3k'),
	};
	if (stock[key] && stock[key].includes(label)) {
		return translated[key];
	}
	return label || translated[key] || label;
}

function isFormFieldEnabled(fields, key) {
	if (key === 'email') {
		return true;
	}
	const list = Array.isArray(fields) ? fields : [];
	const found = list.find((f) => f.key === key);
	// Missing entry (legacy campaigns) = shown.
	if (!found) {
		return true;
	}
	return found.enabled !== false;
}

function setFormFieldEnabled(fields, key, enabled) {
	const defaults = defaultFormFields();
	const byKey = {};
	defaults.forEach((d) => { byKey[d.key] = { ...d }; });
	(Array.isArray(fields) ? fields : []).forEach((f) => {
		if (f && f.key && byKey[f.key]) {
			byKey[f.key] = { ...byKey[f.key], ...f, label: resolveFormFieldLabel({ ...byKey[f.key], ...f }) };
		}
	});
	if (key !== 'email' && byKey[key]) {
		byKey[key].enabled = !!enabled;
	}
	byKey.email.enabled = true;
	return defaults.map((d) => byKey[d.key]);
}

const TABS = [
	{ id: 'basic',    label: __('Basic', 'suitemkt3k') },
	{ id: 'design',   label: __('Design', 'suitemkt3k') },
	{ id: 'display',  label: __('Display', 'suitemkt3k') },
	{ id: 'schedule', label: __('Schedule', 'suitemkt3k') },
];

function Tooltip({ text }) {
	return (
		<span className="wmk-tooltip" tabIndex="0">
			<span className="wmk-tooltip-trigger" aria-label={text}>?</span>
			<span className="wmk-tooltip-content">{text}</span>
		</span>
	);
}

function symbolFor(type, currencies) {
	if (type === 'percent') return '%';
	if (currencies && currencies[type]) return currencies[type].symbol;
	// Legacy "fixed" values fall back to the WP currency symbol provided by PHP.
	return (cfg.currency && cfg.currency.symbol) || '€';
}

function formatValue(value, type) {
	const v = Number(value);
	if (!isFinite(v)) return '';
	if (type === 'percent') return String(Math.round(v));
	let s = v.toFixed(2).replace(/0+$/, '').replace(/\.$/, '');
	return s === '' ? '0' : s;
}

function getCouponCode(name, id) {
	let code = String(name || '').trim().toUpperCase().replace(/\s+/g, '-').replace(/[^A-Z0-9\-]/g, '');
	if (!code) code = 'WMK-' + (id || 0);
	return code;
}

const CopyIcon = ({ color }) => (
	<svg className="wmk-cta-copy-icon" viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2" aria-hidden="true">
		<rect x="9" y="9" width="13" height="13" rx="2" />
		<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
	</svg>
);

function Designer({ initial, listUrl, products, currencies }) {
	const [data, setData] = useState(initial);
	const [saving, setSaving] = useState(false);
	const [savedFlash, setSavedFlash] = useState(false);
	const [tab, setTab] = useState('basic');

	function patch(updates) { setData((d) => ({ ...d, ...updates })); }
	function patchDesign(updates) { setData((d) => ({ ...d, design: { ...d.design, ...updates } })); }

	async function save() {
		setSaving(true);
		const res = await api('coupons', 'POST', data);
		setSaving(false);
		const row = res && res.data ? res.data : null;
		if (res.ok && row && row.id) {
			setData(row);
			setSavedFlash(true);
			if (window.wmk && typeof window.wmk.toast === 'function') {
				window.wmk.toast((cfg.i18n && cfg.i18n.saved) || __('Saved', 'suitemkt3k'), 'success');
			}
			setTimeout(() => setSavedFlash(false), 4000);
			window.scrollTo({ top: 0, behavior: 'smooth' });
			return;
		}
		const message = (row && row.message) || (cfg.i18n && cfg.i18n.error) || __('Something went wrong', 'suitemkt3k');
		if (window.wmk && typeof window.wmk.toast === 'function') {
			window.wmk.toast(message, 'error');
		}
	}

	const symbol = symbolFor(data.discount_type, currencies);
	const value = useMemo(() => {
		const f = formatValue(data.discount_value, data.discount_type);
		return data.discount_type === 'percent' ? `${f}%` : `${f} ${symbol}`;
	}, [data.discount_type, data.discount_value, symbol]);

	const opacity = Math.max(0, Math.min(1, Number(data.design.image_opacity ?? 1)));
	const bannerBg = `linear-gradient(135deg, ${data.design.bg_color} 0%, ${data.design.gradient_to} 100%)`;
	const popupRadius = Math.max(0, Math.min(99, Number(data.design.popup_radius ?? 18)));
	const popupBackdropStyle = {
		background: bannerBg,
		color: data.design.text_color,
		borderRadius: popupRadius + 'px',
	};
	const popupImageStyle = data.design.image_url
		? { backgroundImage: `url("${data.design.image_url}")`, backgroundSize: 'cover', backgroundPosition: 'center', opacity }
		: null;

	const formFields = (data.design.form_fields || [])
		.filter((f) => isFormFieldEnabled(data.design.form_fields, f.key))
		.map((f) => ({ ...f, label: resolveFormFieldLabel(f) }));
	const fieldLabelColor = data.design.field_label_color || data.design.text_color;
	const placeholderColor = data.design.field_placeholder_color || 'rgba(255,255,255,0.7)';
	const fieldBgOpacity = Math.max(0, Math.min(1, Number(data.design.field_bg_opacity ?? 0.14)));
	const fieldBg = hexToRgba(data.design.field_bg_color || '#FFFFFF', fieldBgOpacity);
	const fieldBorderOn = data.design.field_border_enabled !== false;
	const fieldBorderColor = data.design.field_border_color || '#FFFFFF';
	const fieldRadius = Math.max(0, Math.min(40, Number(data.design.field_radius ?? 8)));
	const fieldInputStyle = {
		color: data.design.field_text_color || '#FFFFFF',
		background: fieldBg,
		border: fieldBorderOn ? `1px solid ${fieldBorderColor}` : 'none',
		borderRadius: fieldRadius + 'px',
	};

	const ctaRadius = Math.max(0, Math.min(99, Number(data.design.cta_radius ?? 10)));
	const ctaStyle = {
		backgroundColor: data.design.cta_bg_color || '#FFFFFF',
		color: data.design.cta_text_color || data.design.bg_color || '#2AB2E5',
		borderRadius: ctaRadius + 'px',
	};
	const ctaCodeColor = data.design.cta_code_color || data.design.cta_text_color || data.design.bg_color || '#2AB2E5';
	const ctaIconColor = data.design.cta_icon_color || ctaCodeColor;
	const ctaClassicStyle = { ...ctaStyle, color: ctaCodeColor };
	const valueEnabled = data.design.value_enabled !== false;
	const consentColor = data.design.consent_text_color || fieldLabelColor;
	const isClassic = data.format_type !== 'optin';
	const ctaEnabled = isClassic ? (data.design.cta_enabled !== false) : true;
	const couponCode = getCouponCode(data.name, data.id);

	const productHelp = data.design.product_id
		? __('This coupon will only apply to the selected product.', 'suitemkt3k')
		: __('If no product is selected, this coupon applies to any product in the store.', 'suitemkt3k');

	return (
		<>
			{savedFlash && (
				<div className="wmk-flash wmk-flash-success">{__('Coupon saved.', 'suitemkt3k')}</div>
			)}

			<div className="wmk-designer-grid">
				<div className="wmk-card">
					<h3>{__('Coupon designer', 'suitemkt3k')}</h3>
					<p className="wmk-help">{__('Design, schedule and track your discount campaigns', 'suitemkt3k')}</p>

					<div className="wmk-tabs wmk-designer-tabs">
						{TABS.map((t) => (
							<button key={t.id} type="button"
								className={'wmk-tab' + (tab === t.id ? ' is-active' : '')}
								onClick={() => setTab(t.id)}>{t.label}</button>
						))}
					</div>

					{tab === 'basic' && (
						<div className="wmk-grid wmk-grid-2 wmk-grid-spacious">
							<label className="wmk-field wmk-field-full"><span>{__('Name', 'suitemkt3k')}</span>
								<input className="wmk-input" value={data.name || ''} onChange={(e) => patch({ name: e.target.value })} /></label>
							<label className="wmk-field wmk-field-full"><span>{__('Marketing text', 'suitemkt3k')}</span>
								<textarea className="wmk-input" rows="2" value={data.marketing_text || ''} onChange={(e) => patch({ marketing_text: e.target.value })} /></label>
							<label className="wmk-field"><span>{__('Discount type', 'suitemkt3k')}</span>
								<select className="wmk-input" value={data.discount_type} onChange={(e) => patch({ discount_type: e.target.value })}>
									<option value="percent">{__('Percent (%)', 'suitemkt3k')}</option>
									{Object.keys(currencies || {}).map((k) => (
										<option key={k} value={k}>{currencies[k].label}</option>
									))}
								</select>
							</label>
							<label className="wmk-field wmk-field-narrow"><span>{__('Value', 'suitemkt3k')}</span>
								<input className="wmk-input" type="number"
									step={data.discount_type === 'percent' ? '1' : '0.01'}
									min="0"
									value={data.discount_value}
									onChange={(e) => patch({ discount_value: e.target.value })}
									onBlur={(e) => patch({ discount_value: formatValue(e.target.value, data.discount_type) })} />
							</label>
							<label className="wmk-field wmk-field-narrow">
								<span>
									{__('Usage limit', 'suitemkt3k')}
									<Tooltip text={__('Maximum total number of times this coupon can be used across all customers. Leave empty for unlimited uses.', 'suitemkt3k')} />
								</span>
								<input className="wmk-input" type="number" min="0" value={data.usage_limit || ''} onChange={(e) => patch({ usage_limit: e.target.value })} placeholder={__('Unlimited', 'suitemkt3k')} />
							</label>
							<label className="wmk-field wmk-field-full">
								<span>
									{__('Restrict to product (optional)', 'suitemkt3k')}
									<Tooltip text={__('If no product is selected, this coupon applies to any product in the store. Otherwise it can only be redeemed when the chosen product is in the cart.', 'suitemkt3k')} />
								</span>
								<select className="wmk-input" value={data.design.product_id || 0} onChange={(e) => patchDesign({ product_id: Number(e.target.value) })}>
									<option value="0">{__('— Any product in the store —', 'suitemkt3k')}</option>
									{(products || []).map((p) => (
										<option key={p.id} value={p.id}>#{p.id} · {p.title}</option>
									))}
								</select>
								<small className="wmk-help">{productHelp}</small>
							</label>
							<label className="wmk-field wmk-field-full"><span>{__('Format', 'suitemkt3k')}</span>
								<select className="wmk-input" value={data.format_type} onChange={(e) => {
									const format_type = e.target.value;
									if (format_type === 'optin') {
										setData((prev) => ({
											...prev,
											format_type,
											design: { ...prev.design, cta_enabled: true },
										}));
									} else {
										patch({ format_type });
									}
								}}>
									<option value="classic">{__('Classic', 'suitemkt3k')}</option>
									<option value="optin">{__('Opt-in (popup with form)', 'suitemkt3k')}</option>
								</select>
							</label>
						</div>
					)}

					{tab === 'design' && (
						<div className="wmk-grid-spacious">
							<div className="wmk-grid wmk-grid-3">
								<ColorField label={__('Background', 'suitemkt3k')} value={data.design.bg_color} onChange={(v) => patchDesign({ bg_color: v })} />
								<ColorField label={__('Gradient to', 'suitemkt3k')} value={data.design.gradient_to} onChange={(v) => patchDesign({ gradient_to: v })} />
								<ColorField label={__('Default text', 'suitemkt3k')} value={data.design.text_color} onChange={(v) => patchDesign({ text_color: v })} />
							</div>
							<div className="wmk-grid wmk-grid-3">
								<ColorField label={__('Name color', 'suitemkt3k')} value={data.design.name_color} onChange={(v) => patchDesign({ name_color: v })} />
								<ColorField label={__('Marketing text color', 'suitemkt3k')} value={data.design.marketing_color} onChange={(v) => patchDesign({ marketing_color: v })} />
								<ColorField label={__('Value color', 'suitemkt3k')} value={data.design.value_color || data.design.text_color} onChange={(v) => patchDesign({ value_color: v })} />
							</div>

							<label className="wmk-field wmk-field-narrow" style={{ marginTop: 20 }}>
								<span>{__('Popup border radius', 'suitemkt3k')}</span>
								<input className="wmk-input" type="number" min="0" max="99" value={data.design.popup_radius ?? 18}
									onChange={(e) => patchDesign({ popup_radius: Math.max(0, Math.min(99, Number(e.target.value) || 0)) })} />
							</label>

							<h4 style={{ marginTop: 20 }}>{__('CTA appearance', 'suitemkt3k')}</h4>
							<div className="wmk-grid wmk-grid-3">
								<ColorField label={__('CTA background', 'suitemkt3k')} value={data.design.cta_bg_color} onChange={(v) => patchDesign({ cta_bg_color: v })} fallback="#FFFFFF" />
								<ColorField label={__('CTA text color', 'suitemkt3k')} value={data.design.cta_text_color} onChange={(v) => patchDesign({ cta_text_color: v })} fallback="#2AB2E5" />
								<ColorField label={__('Coupon code text', 'suitemkt3k')} value={data.design.cta_code_color || data.design.cta_text_color} onChange={(v) => patchDesign({ cta_code_color: v })} fallback="#2AB2E5" />
								<ColorField label={__('Copy icon color', 'suitemkt3k')} value={data.design.cta_icon_color || data.design.cta_code_color || data.design.cta_text_color} onChange={(v) => patchDesign({ cta_icon_color: v })} fallback="#2AB2E5" />
								<label className="wmk-field wmk-field-narrow"><span>{__('CTA border radius', 'suitemkt3k')}</span>
									<input className="wmk-input" type="number" min="0" max="99" value={data.design.cta_radius ?? 10}
										onChange={(e) => patchDesign({ cta_radius: Math.max(0, Math.min(99, Number(e.target.value) || 0)) })} />
								</label>
							</div>
							<div className="wmk-grid wmk-grid-2">
								<label className="wmk-field"><span>{__('CTA (opt-in step 1)', 'suitemkt3k')}</span>
									<input className="wmk-input" value={data.design.cta_optin_label} onChange={(e) => patchDesign({ cta_optin_label: e.target.value })} /></label>
								<label className="wmk-field wmk-field-full"><span>{__('CTA (opt-in step 2)', 'suitemkt3k')}</span>
									<input className="wmk-input" value={data.design.cta_step2_label} onChange={(e) => patchDesign({ cta_step2_label: e.target.value })} /></label>
							</div>
							{isClassic && (
								<p className="wmk-help">{__('Classic format shows the WooCommerce coupon code on the button with a copy icon (e.g. VERANO2026).', 'suitemkt3k')}</p>
							)}

							<h4 style={{ marginTop: 20 }}>{__('Popup background image', 'suitemkt3k')}</h4>
							<div className="wmk-field wmk-field-full">
								<small className="wmk-help">{__('Optional. The image is placed on top of the background colour only inside the popup — the top banner always uses the colours.', 'suitemkt3k')}</small>
								<div className="wmk-media">
									{data.design.image_url && <img src={data.design.image_url} alt="" className="wmk-media-preview" />}
									<button type="button" className="wmk-btn wmk-btn-ghost"
										onClick={() => pickMedia(__('Select popup background image', 'suitemkt3k'), (att) => patchDesign({ image_id: att.id, image_url: att.url }))}>
										{__('Choose image', 'suitemkt3k')}
									</button>
									{data.design.image_url && (
										<button type="button" className="wmk-btn wmk-btn-ghost" onClick={() => patchDesign({ image_id: 0, image_url: '' })}>{__('Remove', 'suitemkt3k')}</button>
									)}
								</div>
							</div>
							{data.design.image_url && (
								<label className="wmk-field wmk-field-full">
									<span>{__('Image opacity', 'suitemkt3k')} <small>({Math.round(opacity * 100)}%)</small></span>
									<input type="range" min="0" max="1" step="0.05" value={opacity}
										onChange={(e) => patchDesign({ image_opacity: Number(e.target.value) })} />
									<small className="wmk-help">{__('Lower the opacity to let the background colour show through behind the image.', 'suitemkt3k')}</small>
								</label>
							)}

							{data.format_type === 'optin' && (
								<>
									<h4 style={{ marginTop: 20 }}>{__('Opt-in form (Step 2)', 'suitemkt3k')}</h4>
									<div className="wmk-grid wmk-grid-3">
										<ColorField label={__('Field labels color', 'suitemkt3k')} value={data.design.field_label_color || data.design.text_color} onChange={(v) => patchDesign({ field_label_color: v })} />
										<ColorField label={__('Placeholder color', 'suitemkt3k')} value={data.design.field_placeholder_color || '#FFFFFF'} onChange={(v) => patchDesign({ field_placeholder_color: v })} />
										<ColorField label={__('Field text color', 'suitemkt3k')} value={data.design.field_text_color || '#FFFFFF'} onChange={(v) => patchDesign({ field_text_color: v })} />
										<ColorField label={__('Consent text color', 'suitemkt3k')} value={data.design.consent_text_color || '#FFFFFF'} onChange={(v) => patchDesign({ consent_text_color: v })} />
									</div>
									<div className="wmk-grid wmk-grid-3" style={{ marginTop: 12 }}>
										<ColorField label={__('Form field background', 'suitemkt3k')} value={data.design.field_bg_color || '#FFFFFF'} onChange={(v) => patchDesign({ field_bg_color: v })} />
										<label className="wmk-field wmk-field-full">
											<span>{__('Form field background opacity', 'suitemkt3k')} <small>({Math.round(fieldBgOpacity * 100)}%)</small></span>
											<input type="range" min="0" max="1" step="0.05" value={fieldBgOpacity}
												onChange={(e) => patchDesign({ field_bg_opacity: Number(e.target.value) })} />
										</label>
										<label className="wmk-field wmk-field-narrow">
											<span>{__('Field border radius', 'suitemkt3k')}</span>
											<input className="wmk-input" type="number" min="0" max="40" value={fieldRadius}
												onChange={(e) => patchDesign({ field_radius: Number(e.target.value) })} />
										</label>
									</div>
									<div className="wmk-grid wmk-grid-2" style={{ marginTop: 8 }}>
										<label className="wmk-toggle">
											<input type="checkbox" checked={fieldBorderOn}
												onChange={(e) => patchDesign({ field_border_enabled: e.target.checked })} />
											{__('Show field border', 'suitemkt3k')}
										</label>
										<ColorField label={__('Field border color', 'suitemkt3k')} value={fieldBorderColor}
											onChange={(v) => patchDesign({ field_border_color: v })} />
									</div>
									<label className="wmk-field wmk-field-full"><span>{__('Consent checkbox text (required)', 'suitemkt3k')}</span>
										<textarea className="wmk-input" rows="2" value={data.design.consent_text || __('I agree to receive marketing emails and discounts.', 'suitemkt3k')}
											onChange={(e) => patchDesign({ consent_text: e.target.value })} />
									</label>
								</>
							)}
						</div>
					)}

					{tab === 'display' && (
						<div className="wmk-toggle-row wmk-grid-spacious">
							<label className="wmk-toggle"><input type="checkbox" checked={!!data.design.banner_enabled} onChange={(e) => patchDesign({ banner_enabled: e.target.checked })} /> {__('Show as top banner', 'suitemkt3k')}</label>
							<label className="wmk-toggle"><input type="checkbox" checked={!!data.design.popup_enabled} onChange={(e) => patchDesign({ popup_enabled: e.target.checked })} /> {__('Show as popup', 'suitemkt3k')}</label>
							<label className="wmk-toggle">
								<input
									type="checkbox"
									checked={ctaEnabled}
									disabled={!isClassic}
									onChange={(e) => patchDesign({ cta_enabled: e.target.checked })}
								/>
								{__('Show call-to-action button', 'suitemkt3k')}
							</label>
							{!isClassic && (
								<small className="wmk-help">{__('In opt-in format the CTA button is required to open the signup form.', 'suitemkt3k')}</small>
							)}
							{isClassic && (
								<small className="wmk-help">{__('Disable the CTA to use the popup as a promotional announcement without a button.', 'suitemkt3k')}</small>
							)}
							<label className="wmk-toggle"><input type="checkbox" checked={valueEnabled} onChange={(e) => patchDesign({ value_enabled: e.target.checked })} /> {__('Show discount type and value', 'suitemkt3k')}</label>
							{!isClassic && (
								<>
									<small className="wmk-help" style={{ marginTop: 8 }}>{__('Opt-in form fields (step 2). Email is always required.', 'suitemkt3k')}</small>
									<label className="wmk-toggle">
										<input
											type="checkbox"
											checked={isFormFieldEnabled(data.design.form_fields, 'name')}
											onChange={(e) => patchDesign({ form_fields: setFormFieldEnabled(data.design.form_fields, 'name', e.target.checked) })}
										/>
										{__('Show name field', 'suitemkt3k')}
									</label>
									<label className="wmk-toggle">
										<input
											type="checkbox"
											checked={isFormFieldEnabled(data.design.form_fields, 'birth_date')}
											onChange={(e) => patchDesign({ form_fields: setFormFieldEnabled(data.design.form_fields, 'birth_date', e.target.checked) })}
										/>
										{__('Show birth date field', 'suitemkt3k')}
									</label>
								</>
							)}
							<label className="wmk-field"><span>{__('Popup delay (seconds)', 'suitemkt3k')}</span>
								<input className="wmk-input" type="number" min="0" max="60" value={data.design.popup_delay} onChange={(e) => patchDesign({ popup_delay: Number(e.target.value) })} /></label>
						</div>
					)}

					{tab === 'schedule' && (
						<div className="wmk-grid wmk-grid-2 wmk-grid-spacious">
							<label className="wmk-field"><span>{__('Starts at', 'suitemkt3k')}</span>
								<input className="wmk-input" type="datetime-local" value={(data.starts_at || '').replace(' ', 'T')} onChange={(e) => patch({ starts_at: e.target.value.replace('T', ' ') })} /></label>
							<label className="wmk-field"><span>{__('Ends at', 'suitemkt3k')}</span>
								<input className="wmk-input" type="datetime-local" value={(data.ends_at || '').replace(' ', 'T')} onChange={(e) => patch({ ends_at: e.target.value.replace('T', ' ') })} /></label>
							<label className="wmk-field wmk-field-full"><span>{__('Status', 'suitemkt3k')}</span>
								<select className="wmk-input" value={data.status} onChange={(e) => patch({ status: e.target.value })}>
									<option value="draft">{__('Draft', 'suitemkt3k')}</option>
									<option value="scheduled">{__('Scheduled', 'suitemkt3k')}</option>
									<option value="active">{__('Active', 'suitemkt3k')}</option>
									<option value="paused">{__('Paused', 'suitemkt3k')}</option>
								</select>
							</label>
						</div>
					)}

					<div className="wmk-form-actions">
						<a className="wmk-btn wmk-btn-ghost" href={listUrl}>{__('Back', 'suitemkt3k')}</a>
						<button className="wmk-btn wmk-btn-primary" disabled={saving} onClick={save}>{saving ? __('Saving…', 'suitemkt3k') : __('Save', 'suitemkt3k')}</button>
					</div>
				</div>

				<div className="wmk-designer-preview">
					<div className="wmk-card">
						<h3>{__('Preview', 'suitemkt3k')}</h3>
						<div className="wmk-preview-frame wmk-preview-coupon">
							<div
								className={'wmk-pc-banner' + (data.design.banner_enabled ? '' : ' wmk-pc-preview-off')}
								style={{ background: bannerBg, color: data.design.text_color }}
								aria-hidden={!data.design.banner_enabled}
							>
								<span className="wmk-pc-banner-text" style={{ color: data.design.marketing_color || data.design.text_color }}>{data.marketing_text || data.name}</span>
								{valueEnabled && (
									<span className="wmk-pc-banner-value" style={{ color: data.design.value_color || data.design.text_color }}>{value}</span>
								)}
								{ctaEnabled && (
									<button className="wmk-pc-cta-pill wmk-cta-copy-code" type="button" style={isClassic ? ctaClassicStyle : ctaStyle}>
										{isClassic ? (<><span className="wmk-cta-code" style={{ color: ctaCodeColor }}>{couponCode}</span><CopyIcon color={ctaIconColor} /></>) : data.design.cta_optin_label}
									</button>
								)}
							</div>

							<div
								className={'wmk-pc-popup' + (data.design.popup_enabled ? '' : ' wmk-pc-preview-off')}
								style={popupBackdropStyle}
								aria-hidden={!data.design.popup_enabled}
							>
								{popupImageStyle && <div className="wmk-pc-popup-image" style={popupImageStyle} aria-hidden="true"></div>}
								<div className="wmk-pc-popup-content">
									<h4 style={{ color: data.design.name_color || data.design.text_color }}>{data.name || __('Coupon', 'suitemkt3k')}</h4>
									<p style={{ color: data.design.marketing_color || data.design.text_color }}>{data.marketing_text}</p>
									{valueEnabled && (
										<div className="wmk-pc-popup-value" style={{ color: data.design.value_color || data.design.text_color }}>{value}</div>
									)}
									{ctaEnabled && (
										<button className="wmk-pc-cta wmk-cta-copy-code" type="button" style={isClassic ? ctaClassicStyle : ctaStyle}>
											{isClassic ? (<><span className="wmk-cta-code" style={{ color: ctaCodeColor }}>{couponCode}</span><CopyIcon color={ctaIconColor} /></>) : data.design.cta_optin_label}
										</button>
									)}
								</div>
							</div>

							{data.format_type === 'optin' && (
								<div
									className={'wmk-pc-popup wmk-pc-popup-step2' + (data.design.popup_enabled ? '' : ' wmk-pc-preview-off')}
									style={popupBackdropStyle}
									aria-hidden={!data.design.popup_enabled}
								>
									{popupImageStyle && <div className="wmk-pc-popup-image" style={popupImageStyle} aria-hidden="true"></div>}
									<div className="wmk-pc-popup-content">
										<style>{`
											.wmk-pc-step2-field input::placeholder { color: ${placeholderColor}; opacity: 1; }
											.wmk-pc-step2-field input::-webkit-input-placeholder { color: ${placeholderColor}; opacity: 1; }
										`}</style>
										{formFields.map((f) => (
											<div key={f.key} className="wmk-pc-form-field wmk-pc-step2-field">
												<span style={{ color: fieldLabelColor }}>{f.label}{f.required ? ' *' : ''}</span>
												<input
													disabled
													placeholder={f.label}
													style={fieldInputStyle} />
											</div>
										))}
										<label className="wmk-pc-consent">
											<input type="checkbox" disabled />
											<span style={{ color: consentColor }}>{data.design.consent_text || __('I agree to receive marketing emails and discounts.', 'suitemkt3k')}</span>
										</label>
										<button className="wmk-pc-cta" type="button" style={ctaStyle}>{data.design.cta_step2_label}</button>
									</div>
								</div>
							)}
						</div>
					</div>
				</div>
			</div>
		</>
	);
}

const mount = document.getElementById('suitemkt3k-coupon-designer');
if (mount) {
	const initial    = JSON.parse(mount.dataset.coupon || '{}');
	const listUrl    = mount.dataset.listUrl || '#';
	const products   = JSON.parse(mount.dataset.products || '[]');
	const currencies = JSON.parse(mount.dataset.currencies || '{}');
	createRoot(mount).render(<Designer initial={initial} listUrl={listUrl} products={products} currencies={currencies} />);
}
