// Mobile bootstrap — adapts the design-canvas screens to production:
//   • Provides a `nav` function that does real URL navigation
//   • Manages `menuOpen` for the slide-out drawer per page
//   • Exposes window.MarsanMobile.{Home,Properties,Property,…} as small
//     wrapper components each desktop page can delegate to on mobile.

(function () {
  const SLUG_DEFAULT = 'evara-estates';

  // Map screen-id → URL. Allows passing { slug } for property/article.
  function urlFor(name, params = {}) {
    switch (name) {
      case 'home':       return '/';
      case 'properties': return '/properties.html';
      case 'property':   return '/property.html?slug=' + encodeURIComponent(params.slug || SLUG_DEFAULT);
      case 'insights':   return '/insights.html';
      case 'article':    return '/article.html?slug=' + encodeURIComponent(params.slug || '');
      case 'contact':    return '/contact.html';
      case 'about':      return '/about.html';
      case 'gallery':    return '/gallery.html';
      case 'faq':        return '/faq.html';
      case 'enquire':    return '/enquire.html';
      case 'thanks':     return '/thank-you.html';
      case 'notfound':   return '/404.html';
      case 'privacy':    return '/privacy.html';
      case 'tools':      return '/tools.html';
      default:           return '/';
    }
  }
  function realNav(name, params) {
    if (typeof name !== 'string') return;
    const url = urlFor(name, params);
    if (url === window.location.pathname || url === window.location.pathname + window.location.search) return;
    window.location.href = url;
  }

  // Each screen takes { nav, menuOpen, setMenuOpen }. Wrap them so a desktop
  // page can simply render <window.MarsanMobile.Home /> and get full chrome.
  // Also mounts a portal-rendered HolographicCard so the mobile footer's
  // designer-credit button works (the desktop Footer that owns the same
  // popup is skipped on mobile).
  function wrap(getScreen) {
    return function MobileWrapper(_props) {
      const Screen = getScreen();
      const [menuOpen, setMenuOpen] = React.useState(false);
      const [holoOpen, setHoloOpen] = React.useState(false);
      // Reset scroll on every mount — fixes "back from a long page leaves
      // me at the bottom" behaviour when navigating between mobile screens.
      React.useEffect(() => {
        try { window.scrollTo(0, 0); } catch (_) {}
        if (window.history && 'scrollRestoration' in window.history) {
          try { window.history.scrollRestoration = 'manual'; } catch (_) {}
        }
        // Wire the global designer-credit opener.
        window.MS_HOLO_OPEN = () => setHoloOpen(true);
        return () => { delete window.MS_HOLO_OPEN; };
      }, []);
      if (!Screen) {
        return (
          <div style={{ padding: 32, fontFamily: 'JetBrains Mono', fontSize: 12, color: '#a13530' }}>
            Mobile screen not yet loaded — refresh in a moment.
          </div>
        );
      }
      return (
        <React.Fragment>
          <Screen nav={realNav} menuOpen={menuOpen} setMenuOpen={setMenuOpen} />
          {holoOpen && <MobileHoloCard onClose={() => setHoloOpen(false)} />}
        </React.Fragment>
      );
    };
  }

  // Lightweight holographic-card popup (mobile build — uses the same
  // .ms-holo-* CSS classes from design-system.css the desktop one uses).
  function MobileHoloCard({ onClose }) {
    const cardRef = React.useRef(null);
    const onMove = (e) => {
      const card = cardRef.current; if (!card) return;
      const rect = card.getBoundingClientRect();
      const point = e.touches ? e.touches[0] : e;
      const x = point.clientX - rect.left;
      const y = point.clientY - rect.top;
      const cx = rect.width / 2, cy = rect.height / 2;
      card.style.setProperty('--x', `${x}px`);
      card.style.setProperty('--y', `${y}px`);
      card.style.setProperty('--bg-x', `${(x / rect.width) * 100}%`);
      card.style.setProperty('--bg-y', `${(y / rect.height) * 100}%`);
      card.style.transform = `perspective(1000px) rotateX(${(y - cy) / 12}deg) rotateY(${(cx - x) / 12}deg)`;
    };
    const onLeave = () => {
      const card = cardRef.current; if (!card) return;
      card.style.transform = 'perspective(1000px) rotateX(0deg) rotateY(0deg)';
    };
    React.useEffect(() => {
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', onKey);
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
    }, [onClose]);
    return ReactDOM.createPortal(
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 99999, background: 'rgba(10,15,12,0.92)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
        <button onClick={(e) => { e.stopPropagation(); onClose(); }} aria-label="Close"
          style={{ position: 'absolute', top: 24, right: 24, width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,255,255,0.08)', color: '#e2bd6b', border: '1px solid rgba(201,165,92,0.4)', fontSize: 20, cursor: 'pointer' }}>×</button>
        <div onClick={(e) => e.stopPropagation()} style={{ position: 'relative' }}>
          <div className="ms-holo-glow" />
          <div ref={cardRef} className="ms-holo-card"
            onMouseMove={onMove} onMouseLeave={onLeave} onTouchMove={onMove} onTouchEnd={onLeave}>
            <div className="ms-holo-content">
              <div className="ms-holo-eyebrow">Designed &amp; built by</div>
              <div>
                <div className="ms-holo-name">VASISHTA REDDY<br/>AILENI</div>
              </div>
              <div className="ms-holo-row">
                <div>
                  <div className="ms-holo-eyebrow" style={{ marginBottom: 4 }}>Phone</div>
                  <a href="tel:+919441430088" className="ms-holo-phone">9441430088</a>
                </div>
                <a href="https://wa.me/919441430088" target="_blank" rel="noopener" aria-label="WhatsApp"
                  style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(201,165,92,0.18)', border: '1px solid rgba(201,165,92,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#e2bd6b', textDecoration: 'none' }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3a9 9 0 0 0-7.7 13.6L3 21l4.5-1.2A9 9 0 1 0 12 3z" /><path d="M8.5 9c0 4 2.5 6.5 6.5 6.5l1.5-1.5-2-2-1.5 1c-1-.5-2-1.5-2.5-2.5l1-1.5-2-2z" /></svg>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>,
      document.body
    );
  }

  window.MarsanMobile = {
    Home:       wrap(() => window.HomeScreen),
    Properties: wrap(() => window.PropertiesScreen),
    Property:   wrap(() => window.PropertyScreen),
    Insights:   wrap(() => window.InsightsScreen),
    Article:    wrap(() => window.ArticleScreen),
    Contact:    wrap(() => window.ContactScreen),
    About:      wrap(() => window.AboutScreen),
    Gallery:    wrap(() => window.GalleryScreen),
    FAQ:        wrap(() => window.FAQScreen),
    Enquire:    wrap(() => window.EnquireScreen),
    Thanks:     wrap(() => window.ThankYouScreen),
    NotFound:   wrap(() => window.NotFoundScreen),
    Privacy:    wrap(() => window.PrivacyScreen),
    Tools:      wrap(() => window.ToolsScreen),
    nav:        realNav,
  };

  // Helper: should the current viewport render the mobile experience?
  // Calling code uses this in the desktop page components:
  //   if (window.MarsanMobile.isMobile()) return <window.MarsanMobile.Home />;
  // Two-channel detection — viewport width OR mobile-class user agent. Either
  // signal is enough so weird clients (in-app browsers, lying viewports,
  // Reader-mode renderers) still get the right experience.
  window.MarsanMobile.isMobile = function () {
    if (typeof window === 'undefined') return false;
    try {
      if (window.matchMedia('(max-width: 900px)').matches) return true;
    } catch (_) {}
    const ua = (navigator && navigator.userAgent) || '';
    return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
  };

  // Self-test diagnostic — leaves a single console line and a tiny
  // unobtrusive badge so we can verify mobile is firing. Remove after launch.
  try {
    const screensLoaded = !!(window.HomeScreen && window.PropertiesScreen && window.PropertyScreen
      && window.InsightsScreen && window.ArticleScreen && window.ContactScreen
      && window.AboutScreen && window.GalleryScreen && window.FAQScreen
      && window.EnquireScreen && window.ThankYouScreen && window.NotFoundScreen
      && window.PrivacyScreen && window.ToolsScreen);
    const mobileNow = window.MarsanMobile.isMobile();
    console.log('[marsan-mobile]', { screensLoaded, mobileNow, vw: window.innerWidth, ua: navigator.userAgent });

    if (location.search.includes('mobile-debug')) {
      const badge = document.createElement('div');
      badge.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:99999;padding:6px 10px;background:#0a1f17;color:#e2bd6b;font:11px/1.3 monospace;letter-spacing:0.05em;text-align:center;';
      badge.textContent = `marsan-mobile · screens=${screensLoaded ? 'OK' : 'MISSING'} · mobile=${mobileNow ? 'YES' : 'NO'} · vw=${window.innerWidth}`;
      (document.body || document.documentElement).appendChild(badge);
    }
  } catch (e) { console.error('[marsan-mobile] self-test failed:', e); }
})();
