/**
 * Newsletter designer (React): template picker + editable fields + iframe preview + test send button.
 */
import { createRoot, useState, useEffect } 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, listUrl }) {
	const [data, setData] = useState(initial);
	const [saving, setSaving] = useState(false);

	function patch(updates) { setData((d) => ({ ...d, ...updates })); }
	function patchContent(updates) { setData((d) => ({ ...d, content: { ...d.content, ...updates } })); }

	async function save() {
		setSaving(true);
		const res = await api('newsletters', 'POST', data);
		setSaving(false);
		if (res && res.id) setData(res);
	}

	return (
		<div className="wmk-designer">
			<aside className="wmk-designer-left">
				<label className="wmk-field"><span>{__('Campaign name', 'suitemkt3k')}</span><input className="wmk-input" value={data.name || ''} onChange={(e) => patch({ name: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Subject', 'suitemkt3k')}</span><input className="wmk-input" value={data.subject || ''} onChange={(e) => patch({ subject: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Template', 'suitemkt3k')}</span>
					<select className="wmk-input" value={data.template_key} onChange={(e) => patch({ template_key: e.target.value })}>
						<option value="classic">{__('Classic promo', 'suitemkt3k')}</option>
						<option value="welcome">{__('Welcome', 'suitemkt3k')}</option>
						<option value="reminder">{__('Reminder', 'suitemkt3k')}</option>
						<option value="announce">{__('Announcement', 'suitemkt3k')}</option>
					</select>
				</label>
				<label className="wmk-field"><span>{__('Heading', 'suitemkt3k')}</span><input className="wmk-input" value={data.content.heading || ''} onChange={(e) => patchContent({ heading: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Preheader', 'suitemkt3k')}</span><input className="wmk-input" value={data.content.preheader || ''} onChange={(e) => patchContent({ preheader: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Body', 'suitemkt3k')}</span><textarea className="wmk-input" rows="6" value={data.content.body || ''} onChange={(e) => patchContent({ body: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('CTA label', 'suitemkt3k')}</span><input className="wmk-input" value={data.content.cta_label || ''} onChange={(e) => patchContent({ cta_label: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('CTA URL', 'suitemkt3k')}</span><input className="wmk-input" type="url" value={data.content.cta_url || ''} onChange={(e) => patchContent({ cta_url: e.target.value })} /></label>
				<label className="wmk-field"><span>{__('Accent', 'suitemkt3k')}</span><input type="color" value={data.content.accent || '#6366F1'} onChange={(e) => patchContent({ accent: e.target.value })} /></label>

				<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>
			</aside>

			<section className="wmk-designer-right">
				<div className="wmk-card" style={{ background: '#F4F4F7', padding: 16 }}>
					<div style={{ background: '#fff', padding: 24, borderRadius: 12, maxWidth: 600, margin: '0 auto', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
						<div style={{ background: data.content.accent, color: '#fff', padding: 20, borderRadius: '8px 8px 0 0', marginBottom: 16 }}>
							<strong>{data.content.heading}</strong>
						</div>
						<div style={{ color: '#475569', whiteSpace: 'pre-wrap' }}>{data.content.body}</div>
						<div style={{ marginTop: 24 }}>
							<a style={{ background: data.content.accent, color: '#fff', padding: '12px 24px', borderRadius: 8, textDecoration: 'none', display: 'inline-block' }}>{data.content.cta_label}</a>
						</div>
					</div>
				</div>
			</section>
		</div>
	);
}

const mount = document.getElementById('suitemkt3k-newsletter-designer');
if (mount && mount.dataset.campaign) {
	const initial = JSON.parse(mount.dataset.campaign || '{}');
	const listUrl = mount.dataset.listUrl || '#';
	createRoot(mount).render(<Designer initial={initial} listUrl={listUrl} />);
}
