/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * Authoritative EULA: EULA-v5.1.md / https://castconductor.com/eula
 * Module: zones-grid.js (Phase 2.7 Step 7 extraction)
 */

export async function openZoneGridSettings(editor, containerId, zoneId) {
	try {
		const layout = await fetchContainerLayout(containerId);
		const z = (layout?.zones || []).find(z => String(z.id) === String(zoneId));
		if (!z) { editor.showNotification('Zone not found', 'error'); return; }
		const body = `
				<form id="cc-zone-grid-form" class="cc-form">
					<div class="cc-form-grid">
						<div class="cc-form-row"><label>Columns</label><input type="number" id="cc-grid-cols" value="${parseInt(z.grid?.cols||12,10)}" min="1" max="48" /></div>
						<div class="cc-form-row"><label>Gutter (px)</label><input type="number" id="cc-grid-gutter" value="${parseInt(z.grid?.gutter||24,10)}" min="0" max="128" /></div>
						<div class="cc-form-row"><label>Snap (px)</label><input type="number" id="cc-grid-snap" value="${parseInt(z.grid?.snap||8,10)}" min="1" max="128" /></div>
					</div>
					<div class="cc-form-actions"><button type="button" id="cc-zone-cancel">Cancel</button><button type="submit" class="primary">Save</button></div>
				</form>`;
		editor.showModal(`Grid Settings — Zone ${editor.escapeHtml(zoneId)}`, body);
		document.getElementById('cc-zone-cancel')?.addEventListener('click', () => editor.closeModal());
		document.getElementById('cc-zone-grid-form')?.addEventListener('submit', async (e) => {
			e.preventDefault();
			const cols = parseInt(document.getElementById('cc-grid-cols')?.value||'12',10);
			const gutter = parseInt(document.getElementById('cc-grid-gutter')?.value||'24',10);
			const snap = parseInt(document.getElementById('cc-grid-snap')?.value||'8',10);
			const updated = { ...(layout||{}), zones: (layout?.zones||[]).map(zz => String(zz.id)===String(zoneId) ? ({...zz, grid:{ cols, gutter, snap }}) : zz) };
			await putContainerLayout(containerId, updated);
			editor.closeModal();
			editor.showNotification('Zone grid updated', 'success');
			await editor.loadContainerData();
			const toggle = document.getElementById('toggle-grid');
			if (toggle && toggle.checked) editor.toggleCanvasGrid(true);
		});
	} catch (e) {
		console.error('Zone grid settings failed:', e);
		editor.showNotification('Failed to load grid settings', 'error');
	}
}

export async function fetchContainerLayout(containerId) {
	const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/zones`, { headers: { 'X-WP-Nonce': castconductorCanvasAjax.nonce } });
	if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
	return await resp.json();
}

export async function putContainerLayout(containerId, layout) {
	const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}`, {
		method: 'PUT',
		headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': castconductorCanvasAjax.nonce },
		body: JSON.stringify({ layout })
	});
	if (!resp.ok) {
		let err; try { err = await resp.json(); } catch {}
		throw new Error(err?.message || `HTTP ${resp.status}`);
	}
	return await resp.json();
}

export const zonesGridApi = { openZoneGridSettings, fetchContainerLayout, putContainerLayout };
