/* ============================================================ APP ROUTER ============================================================ */
function App(){
  const [route,setRoute] = useState(()=>{
    if(window.RRSEO) return RRSEO.resolveInitialRoute();
    try{ const s = JSON.parse(sessionStorage.getItem('rr_route')); if(s&&s.page) return s; }catch(e){}
    return { page:'home', params:{} };
  });
  RRSEO.usePageSeo(route);
  const go = (page, params={})=>{
    setRoute({ page, params });
    try{ sessionStorage.setItem('rr_route', JSON.stringify({page,params})); }catch(e){}
    if(window.RRSEO) RRSEO.pushRoute(page, params);
    window.scrollTo({ top:0, behavior:'instant' in window ? 'instant' : 'auto' });
  };
  useEffect(()=>{ window.scrollTo(0,0); },[route.page, JSON.stringify(route.params)]);
  useEffect(()=>{
    const onPop = ()=>{ if(window.RRSEO) setRoute(RRSEO.resolveInitialRoute()); };
    window.addEventListener('popstate', onPop);
    return ()=>window.removeEventListener('popstate', onPop);
  },[]);

  const pages = {
    home:           <HomePage/>,
    shop:           <ShopPage params={route.params}/>,
    product:        <ProductPage params={route.params}/>,
    consultation:   <ConsultationPage/>,
    'pyrite-landing': <PyriteLandingPage/>,
    contact:        <ContactPage/>,
  };

  return (
    <Nav.Provider value={{ go, route }}>
      <Header/>
      {pages[route.page] || <HomePage/>}
      <Footer/>
      <FloatingWA/>
    </Nav.Provider>
  );
}

/* floating whatsapp button */
function FloatingWA(){
  const [show,setShow] = useState(false);
  useEffect(()=>{ const t=setTimeout(()=>setShow(true),900); return ()=>clearTimeout(t); },[]);
  return (
    <a className={`float-wa ${show?'in':''}`} href={RR.wa("Hi Rudraa Ratna, I'd like some guidance.")} target="_blank" rel="noopener" aria-label="Chat on WhatsApp">
      <WaGlyph size={28}/>
      <span className="float-wa__pulse"/>
    </a>
  );
}

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