/* V2 App router — simpler tree: home / compounds / product / how / insights / about / contact / checkout. */
function AppV2() {
  const [page, setPage] = React.useState('home');
  const [product, setProduct] = React.useState(null);

  const pushHistory = (p, prod) => {
    try {
      const state = { page: p, product: prod || null };
      const url = p === 'product' && prod
        ? `#/product/${encodeURIComponent(prod)}`
        : `#/${p === 'home' ? '' : p}`;
      window.history.pushState(state, '', url);
    } catch (_) {}
  };

  const go = (p) => { setPage(p); pushHistory(p, null); window.scrollTo({ top: 0, behavior: 'instant' }); };
  const openProduct = (name) => { setProduct(name); setPage('product'); pushHistory('product', name); window.scrollTo({ top: 0, behavior: 'instant' }); };

  React.useEffect(() => {
    const t = setTimeout(() => window.lucide && window.lucide.createIcons(), 40);
    return () => clearTimeout(t);
  });

  React.useEffect(() => {
    // Seed initial history entry so first Back doesn't leave the site.
    try { window.history.replaceState({ page: 'home', product: null }, '', window.location.href); } catch (_) {}
    const onPop = (e) => {
      const s = (e && e.state) || { page: 'home', product: null };
      setPage(s.page || 'home');
      setProduct(s.product || null);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    const handler = (e) => { if (e && e.detail) go(e.detail); };
    const prod = (e) => { if (e && e.detail) openProduct(e.detail); };
    window.addEventListener('popstate', onPop);
    window.addEventListener('vc-nav', handler);
    window.addEventListener('vc-open-product', prod);
    return () => {
      window.removeEventListener('popstate', onPop);
      window.removeEventListener('vc-nav', handler);
      window.removeEventListener('vc-open-product', prod);
    };
  }, []);



  let body;
  if      (page === 'home')      body = <HomeV2         onNav={go} onProduct={openProduct} />;
  else if (page === 'compounds') body = <CatalogV2      onProduct={openProduct} />;
  else if (page === 'product')   body = <ProductDetailV2 name={product} onProduct={openProduct} onNav={go} />;
  else if (page === 'how')       body = <HowV2          onNav={go} />;
  else if (page === 'insights')  body = <InsightsV2     onNav={go} />;
  else if (page === 'about')     body = <AboutV2        onNav={go} />;
  else if (page === 'contact')   body = <ContactV2      onNav={go} />;
  else if (page === 'policy')    body = <PolicyV2       onNav={go} />;
  else if (page === 'checkout')  body = <Checkout       onNav={go} />;
  else                            body = <HomeV2         onNav={go} onProduct={openProduct} />;

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <HeaderV2 page={page} onNav={go} />
      <main style={{ flex: 1 }}>{body}</main>
      <FooterV2 onNav={go} />
    </div>
  );
}
Object.assign(window, { AppV2 });
