/**
 * Newsletter subscription form designer (React).
 */
import { createRoot, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

const cfg = window.SuiteMkt3k || {};

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());
}

function Designer({ initial }) {
	const [data, setData] = useState(initial);
	return (
		<div className="wmk-designer">
			<aside className="wmk-designer-left">
				<label className="wmk-field"><span>{__('Form name', 'suitemkt3k')}</span><input className="wmk-input" value={data.name || ''} onChange={(e) => setData({ ...data, name: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Title', 'suitemkt3k')}</span><input className="wmk-input" value={data.design.title || ''} onChange={(e) => setData({ ...data, design: { ...data.design, title: e.target.value } })} /></label>
				<label className="wmk-field"><span>{__('Description', 'suitemkt3k')}</span><textarea className="wmk-input" rows="2" value={data.design.description || ''} onChange={(e) => setData({ ...data, design: { ...data.design, description: e.target.value } })} /></label>
				<label className="wmk-field"><span>{__('CTA label', 'suitemkt3k')}</span><input className="wmk-input" value={data.design.cta_label || ''} onChange={(e) => setData({ ...data, design: { ...data.design, cta_label: e.target.value } })} /></label>
				<label className="wmk-field"><span>{__('Accent color', 'suitemkt3k')}</span><input type="color" value={data.design.accent || '#6366F1'} onChange={(e) => setData({ ...data, design: { ...data.design, accent: e.target.value } })} /></label>
			</aside>
			<section className="wmk-designer-right">
				<div className="wmk-form" style={{ '--wmk-accent': data.design.accent }}>
					<h3 className="wmk-form-title">{data.design.title}</h3>
					<p className="wmk-form-desc">{data.design.description}</p>
					{(data.design.fields || []).map((f) => (
						<label key={f.key} className="wmk-form-field"><span>{f.label}{f.required ? ' *' : ''}</span><input disabled /></label>
					))}
					<button className="wmk-form-cta">{data.design.cta_label}</button>
				</div>
			</section>
		</div>
	);
}

const mount = document.getElementById('suitemkt3k-form-designer');
if (mount) {
	const initial = JSON.parse(mount.dataset.form || '{"name":"","design":{"title":"","description":"","cta_label":"Subscribe","accent":"#6366F1","fields":[{"key":"name","label":"Name","required":false},{"key":"email","label":"Email","required":true}]}}');
	createRoot(mount).render(<Designer initial={initial} />);
}
