// app.jsx — root component, route switch, chrome, overlays, tweaks

function useDesktop() {
  const [desktop, setDesktop] = React.useState(function () {
    return window.matchMedia('(min-width: 721px)').matches;
  });
  React.useEffect(function () {
    const mq = window.matchMedia('(min-width: 721px)');
    const sync = function () { setDesktop(mq.matches); };
    sync();
    mq.addEventListener('change', sync);
    return function () { mq.removeEventListener('change', sync); };
  }, []);
  return desktop;
}

function Overlays() {
  const store = useStore();
  const drawer = store.state.drawer;
  const modal = store.state.modal;

  React.useEffect(() => {
    const esc = (e) => {
      if (e.key === 'Escape') {
        if (store.state.phoneOpen && store.isPhoneDesktop()) {
          store.closePhoneOverlay();
          return;
        }
        store.closeDrawer();
        store.closeModal();
        store.closeRinpoChat();
      }
    };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, []);

  React.useEffect(() => {
    const blocked = drawer || modal || store.state.rinpoChat
      || (store.state.phoneOpen && store.isPhoneDesktop());
    document.body.style.overflow = blocked ? 'hidden' : '';
  }, [drawer, modal, store.state.rinpoChat, store.state.phoneOpen]);

  return (
    <>
      {drawer && drawer !== 'rinpo' && (
        <div className="scrim" onClick={() => store.closeDrawer()}>
          {drawer === 'cart' && <CartDrawer />}
          {drawer === 'wish' && <WishlistDrawer />}
          {drawer === 'search' && <SearchDrawer />}
          {drawer === 'menu' && <MobileMenuDrawer />}
        </div>
      )}
      {modal && modal.kind === 'quickview' && <QuickViewModal />}
      <RinpoPhoneOverlay />
      <RinpoChatPanel />
      <NewsletterPopup />
      <Notif />
    </>
  );
}

function Page() {
  const route = useRoute();
  const store = useStore();
  const desktop = useDesktop();

  let effectiveRoute = route;
  if (desktop && route.name === 'phone') {
    effectiveRoute = HAPRouter.parseHash(store.state.phoneReturnHash || '#/');
  }

  switch (effectiveRoute.name) {
    case 'home': return <HomePage />;
    case 'phone': return desktop ? null : <RinpoPhoneShell />;
    case 'onboarding': return <OnboardingPage />;
    case 'collections-index': return <CollectionsIndexPage />;
    case 'collection': return <CollectionPage />;
    case 'product': return <ProductPage />;
    case 'cart': return <CartPage />;
    case 'checkout': return <CheckoutPage />;
    case 'wishlist': return <WishlistPage />;
    case 'search': return <SearchPage />;
    case 'track': return <TrackPage />;
    case 'login': return <LoginPage />;
    case 'register': return <RegisterPage />;
    case 'account': return <AccountPage />;
    case 'orders': return <OrdersPage />;
    case 'order-detail': return <OrderDetailPage />;
    case 'addresses': return <AddressesPage />;
    case 'my-reviews': return <MyReviewsPage />;
    case 'profile': return <ProfilePage />;
    case 'help': return <HelpPage />;
    case 'support-tickets': return <SupportTicketsPage />;
    case 'rinpo': return <CustomerRinpoPage />;
    case 'services': return <ServicesIndexPage />;
    case 'service': return <ServiceDetailPage />;
    case 'page': return <StaticPage />;
    case 'not-found': return <NotFoundPage homeHref="#/" />;
    default: return <NotFoundPage homeHref="#/" />;
  }
}

function AppChrome() {
  const route = useRoute();
  const store = useStore();
  const desktop = useDesktop();
  const shellOnly = route.name === 'onboarding' || (route.name === 'phone' && !desktop);
  // Re-key page so it remounts (and scrolls top) on navigation
  const pageRoute = desktop && route.name === 'phone'
    ? HAPRouter.parseHash(store.state.phoneReturnHash || '#/')
    : route;
  const key = pageRoute.name + (pageRoute.params.slug || '') + (pageRoute.query.q || '') + (pageRoute.params.id || '');

  React.useEffect(() => {
    if (window.HAPStore && typeof window.HAPStore.expireReservations === 'function') {
      window.HAPStore.expireReservations();
    }
  }, []);

  React.useEffect(() => {
    const hideNav = shellOnly || pageRoute.name === 'checkout';
    document.body.classList.toggle('has-bottom-nav', !hideNav && window.matchMedia('(max-width: 720px)').matches);
    document.body.classList.toggle('has-pdp-bar', pageRoute.name === 'product' && window.matchMedia('(max-width: 720px)').matches);
    document.body.classList.toggle('route-home', pageRoute.name === 'home');
  }, [pageRoute.name, shellOnly]);

  React.useEffect(() => {
    if (!window.CustomerRinpo || typeof window.CustomerRinpo.setContext !== 'function') return;
    const ctx = {
      page: pageRoute.name,
      productId: null,
      variantId: null,
      cartId: null,
      orderId: null,
      customerId: null,
    };
    if (pageRoute.name === 'product' && pageRoute.params.slug && window.HAP && HAP.productBySlug) {
      const p = HAP.productBySlug(pageRoute.params.slug);
      if (p) ctx.productId = p.id;
    }
    if (pageRoute.name === 'order-detail' && pageRoute.params.id) {
      ctx.orderId = pageRoute.params.id;
    }
    if (pageRoute.query && pageRoute.query.o) ctx.orderId = pageRoute.query.o;
    try {
      const user = (window.CustomerAccount && window.CustomerAccount.currentUser && window.CustomerAccount.currentUser())
        || (window.HAPStore && HAPStore.state && HAPStore.state.user)
        || null;
      if (user) ctx.customerId = user.id || user.email || null;
    } catch (_) {}
    window.CustomerRinpo.setContext(ctx);
  }, [pageRoute.name, pageRoute.params.slug, pageRoute.params.id, pageRoute.query.o]);

  if (shellOnly) {
    return (
      <div className="app-shell app-shell--phone" style={{ minHeight: '100vh' }} key={key}>
        <div className="app-shell__main"><Page /></div>
        <div className="app-shell__overlays"><Overlays /></div>
      </div>
    );
  }

  return (
    <div className="app-shell" style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <div className="app-shell__top"><Header /></div>
      <div className="app-shell__main" style={{ flex: 1 }} key={key}>
        <Page />
      </div>
      <div className="app-shell__footer"><Footer /></div>
      <div className="app-shell__overlays"><Overlays /></div>
      <div className="app-shell__nav"><StoreBottomNav /></div>
      <div className="app-shell__rinpo"><RinpoAvatar /></div>
      <div className="app-shell__fab-secondary"><FloatingWhatsApp /></div>
    </div>
  );
}

function FloatingWhatsApp() {
  return (
    <a href="https://wa.me/917559907176" target="_blank" rel="noreferrer"
       title="Chat on WhatsApp"
       className="wa-fab"
       style={{
         position: 'fixed', bottom: 20, left: 20, zIndex: 'var(--z-fab-secondary, 30)',
         width: 54, height: 54, borderRadius: 999, background: '#1f8a4c', color: '#fff',
         display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
         boxShadow: '0 10px 30px rgba(31,138,76,0.4)'
       }}>
      <Icon name="whatsapp" size={26} />
    </a>
  );
}

function AppRoot() {
  const [ready, setReady] = React.useState(!(window.APG_CONFIG && window.APG_CONFIG.useRemote));
  const route = useRoute();

  React.useEffect(() => {
    if (window.APG && window.APG.init) {
      window.APG.init().then(() => setReady(true)).catch(() => setReady(true));
    } else setReady(true);
  }, []);

  React.useEffect(function () {
    if (!ready) return;
    const desktop = window.matchMedia('(min-width: 721px)').matches;
    if (desktop && route.name === 'phone') {
      window.HAPStore.ensurePhoneOverlay(route.query.tab || 'apps');
    } else if (desktop && window.HAPStore.state.phoneOpen && route.name !== 'phone') {
      window.HAPStore.dismissPhoneOverlay();
    } else if (!desktop && route.name === 'phone' && route.query.tab) {
      window.HAPStore.setPhoneTab(route.query.tab);
    }
  }, [ready, route.name, route.query.tab]);

  if (!ready) {
    return (
      <div style={{ display: 'grid', placeItems: 'center', minHeight: '60vh', color: 'var(--muted)' }}>
        Loading store…
      </div>
    );
  }
  return (
    <AppErrorBoundary homeHref="#/">
      <AppChrome />
    </AppErrorBoundary>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<AppRoot />);
