/* Build Core Supply — Website UI Kit · hash router + home page */
const { useState: uSA, useEffect: uEA } = React;

/* ---- Home page (single-scroll) ---- */
function HomePage({go, onEnquire, onOpenProduct}){
  return (
    <main>
      <Hero go={go}/>
      <Marquee/>
      <Stats/>
      <Services go={go} onCard={()=>go("/services")}/>
      <About go={go}/>
      <FoundersSection go={go}/>
      <Products onEnquire={onEnquire} onOpen={onOpenProduct}/>
      <Projects onOpen={()=>go("/projects")}/>
      <Contact prefill={null}/>
    </main>
  );
}

/* ---- parse hash route ---- */
function parseHash(){
  let h = window.location.hash.replace(/^#/, '');
  if(!h || h==='/') return {path:'/'};
  const parts = h.split('/').filter(Boolean);   // e.g. ['products','birla-shakti-cement']
  if(parts[0]==='products' && parts[1]) return {path:'/product', slug:parts[1]};
  return {path:'/'+parts[0]};
}

function App(){
  const [route, setRoute] = uSA(parseHash());
  const [prefill, setPrefill] = uSA(null);

  uEA(()=>{
    const onHash=()=>{ setRoute(parseHash()); window.scrollTo(0,0); };
    window.addEventListener('hashchange', onHash);
    return ()=>window.removeEventListener('hashchange', onHash);
  },[]);

  // futuristic motion engine — re-bind on every route change
  uEA(()=>{
    let cleanup=()=>{};
    const t=setTimeout(()=>{ if(window.bcsMotion) cleanup=window.bcsMotion(); }, 30);
    return ()=>{ clearTimeout(t); cleanup&&cleanup(); };
  },[route.path, route.slug]);

  const go = (path)=>{
    if(window.location.hash === '#'+path){ setRoute(parseHash()); }
    else { window.location.hash = path; }
    window.scrollTo(0,0);
  };
  const onEnquire = (name)=>{ setPrefill(name+" · "+Date.now()); go("/contact"); };
  const onOpenProduct = (slug)=>{ go("/products/"+slug); };

  const p = route.path;
  let page;
  if(p==='/about') page = <AboutPage go={go}/>;
  else if(p==='/services') page = <ServicesPage go={go}/>;
  else if(p==='/products') page = <ProductsPage go={go} onEnquire={onEnquire} onOpen={onOpenProduct}/>;
  else if(p==='/product') page = <ProductDetailPage go={go} slug={route.slug} onEnquire={onEnquire} onOpen={onOpenProduct}/>;
  else if(p==='/projects') page = <ProjectsPage go={go}/>;
  else if(p==='/gallery') page = <GalleryPage go={go}/>;
  else if(p==='/contact') page = <ContactPage go={go} prefill={prefill}/>;
  else page = <HomePage go={go} onEnquire={onEnquire} onOpenProduct={onOpenProduct}/>;

  const navPath = p==='/product' ? '/products' : p;
  return (
    <React.Fragment>
      <Header go={go} route={navPath} dark={p!=='/'}/>
      {page}
      <Footer go={go}/>
    </React.Fragment>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
