/**
 * Front-end entry: mounts the booking wizard on every widget root the plugin
 * printed, and wires any element with data-bp-open="wizard" (or the legacy
 * .bp-open-wizard class) to open it.
 */
import React from 'react';
import { createRoot } from 'react-dom/client';
import Widget, { PaymentReturn } from './Widget';
import '../../shared/ds/index.css';
import './booking.css';

const mounted = new WeakSet();

function mountWidget(el) {
	if (mounted.has(el)) return;
	mounted.add(el);
	const root = createRoot(el);
	if (el.dataset.bpWidget === 'payment-return') {
		root.render(<PaymentReturn />);
	} else {
		root.render(<Widget el={el} />);
	}
}

/** A widget that exists only to open the dialog (custom trigger without a shortcode root). */
function openStandalone() {
	let el = document.querySelector('[data-bp-standalone]');
	if (el && typeof el.__bpOpen === 'function') {
		el.__bpOpen();
		return;
	}
	const wrap = document.createElement('div');
	wrap.className = 'bp-ui bp-booking-embed';
	wrap.setAttribute('data-bp-theme', (window.pointlybooking_FRONT?.brand || {}).theme || 'auto');
	el = document.createElement('div');
	el.className = 'bp-front-root';
	el.setAttribute('data-bp-widget', 'wizard');
	el.setAttribute('data-bp-mode', 'button');
	el.setAttribute('data-bp-fallback', '1');
	el.setAttribute('data-bp-auto-open', '1');
	el.setAttribute('data-bp-standalone', '1');
	wrap.appendChild(el);
	document.body.appendChild(wrap);
	mountWidget(el);
}

function nearestRoot(trigger) {
	const sibling = trigger.nextElementSibling;
	if (sibling && sibling.classList.contains('bp-front-root') && sibling.dataset.bpWidget === 'wizard') return sibling;
	const own = trigger.closest('.bp-front-root');
	if (own) return own;
	return document.querySelector('.bp-front-root[data-bp-widget="wizard"]:not([data-bp-standalone])');
}

function onDocumentClick(e) {
	const target = e.target;
	if (!(target instanceof Element)) return;
	const trigger = target.closest('.bp-fallback-btn, [data-bp-open="wizard"], .bp-open-wizard');
	if (!trigger) return;
	const root = nearestRoot(trigger);
	e.preventDefault();
	if (root && typeof root.__bpOpen === 'function') root.__bpOpen();
	else if (!root || root.dataset.bpMode !== 'inline') openStandalone();
}

function boot() {
	document.querySelectorAll('.bp-front-root[data-bp-widget]').forEach(mountWidget);
	document.addEventListener('click', onDocumentClick);
}

if (document.readyState === 'loading') {
	document.addEventListener('DOMContentLoaded', boot);
} else {
	boot();
}
