/**
 * Find `.flowchart-embed` divs (generated by backend from ```flowchart fences)
 * and replace them with live Flowchart iframes. Uses IntersectionObserver
 * for lazy loading.
 */

function loadFlowchartEmbed(div: HTMLElement) {
	const width = div.dataset.width || '100%';
	const height = div.dataset.height || '400px';
	const dataEl = div.querySelector('.flowchart-data');
	const flowchartData = dataEl?.textContent?.trim() || '';

	const wrapper = document.createElement('div');
	wrapper.className = 'flowchart-embed-wrapper';
	wrapper.style.width = width;
	wrapper.style.height = height;
    wrapper.style.position = 'relative';

	const iframe = document.createElement('iframe');
    // Using cb to avoid caching issues during development
	iframe.src = `/flowchart/?iframe=true&readonly=true&cb=${Date.now()}`;
	iframe.style.width = '100%';
	iframe.style.height = '100%';
	iframe.style.border = 'none';
	iframe.title = 'Flowchart Editor';

	const loadData = () => {
		if (!flowchartData) return;
		try {
            iframe.contentWindow?.postMessage({
                type: 'FLOWCHART_LOAD',
                payload: JSON.stringify({
                    initialData: flowchartData
                })
            }, '*');
		} catch (e) {
			console.error('Flowchart embed load error:', e);
		}
		const loadingEl = div.querySelector('.flowchart-embed-loading');
		if (loadingEl) loadingEl.remove();
	};

	window.addEventListener('message', (event) => {
        if (event.source === iframe.contentWindow && event.data?.type === 'FLOWCHART_READY') {
            loadData();
        }
    });

	wrapper.appendChild(iframe);
	div.appendChild(wrapper);
	div.dataset.rendered = 'true';
}

export function renderFlowchartEmbeds(container: HTMLElement) {
	const embeds = container.querySelectorAll('.flowchart-embed:not([data-rendered])');
	if (embeds.length === 0) return;

	const observer = new IntersectionObserver(
		(entries) => {
			entries.forEach((entry) => {
				if (entry.isIntersecting) {
					loadFlowchartEmbed(entry.target as HTMLElement);
					observer.unobserve(entry.target);
				}
			});
		},
		{ rootMargin: '200px' }
	);

	embeds.forEach((el) => observer.observe(el));
}
