// responsive-router.jsx — selects mobile vs desktop based on viewport.
// Both desktop-app and v2-app respect window.__AM_RESPONSIVE__ to skip self-mount,
// so this script does the final mount.

(function() {
  const MOBILE_BREAKPOINT = 900;
  const isMobile = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`).matches;

  // Set mode-specific body class for CSS hooks
  document.body.classList.add(isMobile ? 'is-mobile' : 'is-desktop');

  // Pick component
  const App = isMobile ? window.V2App : window.DesktopApp;
  if (!App) {
    console.error('[responsive-router] missing component', { isMobile, V2App: !!window.V2App, DesktopApp: !!window.DesktopApp });
    return;
  }

  // Apply mobile-specific styles (drop scrollbar, allow body scroll)
  if (isMobile) {
    const s = document.createElement('style');
    s.textContent = `
      html, body { overflow: auto !important; height: auto !important; min-height: 100% !important; background: #f5f1e8 !important; }
      ::-webkit-scrollbar { width: 0 !important; }
    `;
    document.head.appendChild(s);
  }

  ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(App));

  // If the user resizes/rotates and crosses the breakpoint, reload to swap apps.
  // Avoid swapping mid-session for stability.
  let lastIsMobile = isMobile;
  window.addEventListener('resize', () => {
    const nowMobile = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`).matches;
    if (nowMobile !== lastIsMobile) {
      lastIsMobile = nowMobile;
      location.reload();
    }
  });
})();
