/* Loncin website — app shell that switches screens */
function App() {
  const [screen, setScreen] = React.useState('home');
  const {
    Nav, Footer, HomeScreen, KaartScreen, KreeftenScreen,
    TallShipsScreen, JubileumScreen, EventsScreen, ImpressieScreen,
    ContactScreen, ReserveScreen, CadeaubonScreen, LegalScreen,
  } = window;

  React.useEffect(() => {
    if (typeof window.scrollTo === 'function') window.scrollTo(0, 0);
  }, [screen]);

  const go = (s) => setScreen(s);

  const SCREENS = {
    home: HomeScreen,
    kaart: KaartScreen,
    kreeften: KreeftenScreen,
    tallships: TallShipsScreen,
    jubileum: JubileumScreen,
    events: EventsScreen,
    impressie: ImpressieScreen,
    contact: ContactScreen,
    reserve: ReserveScreen,
    cadeaubon: CadeaubonScreen,
    privacy: LegalScreen,
    cookies: LegalScreen,
    disclaimer: LegalScreen,
  };
  const Current = SCREENS[screen] || HomeScreen;

  return (
    <div>
      <Nav current={screen} onNavigate={go} />
      <Current onNavigate={go} screen={screen} />
      <Footer onNavigate={go} />
    </div>
  );
}
const _container = document.getElementById('root');

function mountLoncin() {
  const c = document.getElementById('root');
  if (!c) return;
  // If a root exists but the container was wiped (the host editor clears #root
  // when entering Edit/Comment mode), React's retained root still thinks its
  // tree is live, so re-rendering is a no-op and #root stays empty = black
  // screen. Tear the stale root down and mount fresh into the empty node.
  if (c._loncinRoot && c.childElementCount === 0) {
    try { c._loncinRoot.unmount(); } catch (e) { /* noop */ }
    c._loncinRoot = null;
  }
  if (!c._loncinRoot) c._loncinRoot = ReactDOM.createRoot(c);
  c._loncinRoot.render(<App />);
}

mountLoncin();

// Self-heal: if anything (e.g. the editor) empties #root after mount, re-mount.
if ('MutationObserver' in window && _container) {
  let scheduled = false;
  new MutationObserver(() => {
    if (_container.childElementCount === 0 && !scheduled) {
      scheduled = true;
      setTimeout(() => { scheduled = false; mountLoncin(); }, 0);
    }
  }).observe(_container, { childList: true });
}
