import { createRoot } from 'react-dom/client';
import App from './App';
import './settings.pcss';

const SLOT_ID = 'pdfdraft-settings-section--woocommerce-invoices';

/**
 * Attempt to mount the WooCommerce settings app into the slot div that the
 * main PDFDraft settings page renders.  Returns true when successful.
 *
 * The slot div is rendered by the main settings React app (asynchronously in
 * React 18), so we use a MutationObserver to retry once the div appears.
 */
function tryMount(): boolean {
	const rootEl = document.getElementById(SLOT_ID);
	if (!rootEl || rootEl.dataset.pdfdraftMounted) return false;

	rootEl.dataset.pdfdraftMounted = 'true';
	createRoot(rootEl).render(<App />);
	return true;
}

if (!tryMount()) {
	const observer = new MutationObserver(() => {
		if (tryMount()) observer.disconnect();
	});
	observer.observe(document.documentElement, { childList: true, subtree: true });

	// Safety net: disconnect after 15 s to avoid leaking the observer.
	window.setTimeout(() => observer.disconnect(), 15_000);
}
