// HOS — House of Sheylas — App entry + hash router

function useHashRoute() {
  const routeFromPath = () => {
    const path = window.location.pathname.replace(/^\/+|\/+$/g, '');
    if (!path) return 'home';
    if (path === 'shop') return 'shop';
    if (path.startsWith('shop/')) return path;
    if (path === 'collections') return 'collections';
    if (path === 'about') return 'about';
    if (path === 'contact') return 'contact';
    if (path.startsWith('product/')) return path;
    return 'home';
  };
  const routeFromLocation = () => window.location.hash.slice(1) || routeFromPath();
  const routeToPath = (route) => {
    if (!route || route === 'home') return '/';
    return `/${route}`;
  };
  const [route, setRoute] = useState(routeFromLocation);

  useEffect(() => {
    const shouldNormalizePath = () => window.location.pathname.replace(/\/+$/g, '') === '/claude/index.html';
    const onRoute = () => {
      const r = routeFromLocation();
      setRoute(r);
      if (window.location.hash || shouldNormalizePath()) {
        window.history.replaceState(null, '', routeToPath(r));
      }
      // Reset scroll on route change
      window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    };
    const onClick = (event) => {
      const link = event.target.closest?.('a[href^="#"]');
      if (!link) return;
      const route = link.getAttribute('href').slice(1) || 'home';
      event.preventDefault();
      setRoute(route);
      window.history.pushState(null, '', routeToPath(route));
      window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    };
    window.addEventListener('hashchange', onRoute);
    window.addEventListener('popstate', onRoute);
    document.addEventListener('click', onClick);
    onRoute();
    return () => {
      window.removeEventListener('hashchange', onRoute);
      window.removeEventListener('popstate', onRoute);
      document.removeEventListener('click', onClick);
    };
  }, []);
  return route;
}

function HomePage() {
  return (
    <>
      <Hero />
      <Categories />
      <NewArrivals />
      <BrandStory />
      <BestSellers />
      <Instagram />
      <Newsletter />
    </>
  );
}

function StorefrontRouter() {
  const route = useHashRoute();
  const [head, ...rest] = route.split('/');

  // Re-run reveal observer on route change (new elements in DOM)
  useReveal(route);

  let Page;
  switch (head) {
    case 'home':
    case '':
      Page = <HomePage />;
      break;
    case 'shop':
      Page = <ShopPage subPath={rest[0] || 'all'} />;
      break;
    case 'collections':
      Page = <CollectionsPage />;
      break;
    case 'product':
      Page = <ProductPage productId={rest[0]} />;
      break;
    case 'about':
      Page = <AboutPage />;
      break;
    case 'contact':
      Page = <ContactPage />;
      break;
    case 'order':
      Page = <OrderTrackingPage prefillOrder={rest[0]} />;
      break;
    default:
      Page = <NotFoundPage />;
  }

  // Wrap in fade-in keyed to route for smooth transitions
  return <div key={route} className="animate-fade-in">{Page}</div>;
}

function Storefront({ route = 'home' }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [dataVersion, setDataVersion] = useState(0);

  useEffect(() => {
    const onSiteDataReady = () => setDataVersion(v => v + 1);
    window.addEventListener('site-data-ready', onSiteDataReady);
    return () => window.removeEventListener('site-data-ready', onSiteDataReady);
  }, []);

  return (
    <CartProvider>
      <Announcement />
      <Nav route={route} onOpenMenu={() => setMenuOpen(true)} />
      <main>
        <StorefrontRouter key={dataVersion} />
      </main>
      <Footer />
      <CartDrawer />
      <MainMenu open={menuOpen} onClose={() => setMenuOpen(false)} />
      <CartToast />
    </CartProvider>
  );
}

function App() {
  const route = useHashRoute();
  const [head] = route.split('/');
  const isAdmin = head === 'admin';

  useEffect(() => {
    if (isAdmin) window.location.href = '/admin';
  }, [isAdmin]);

  return (
    <SiteDataProvider>
      <CurrencyProvider>
        <LangProvider>
          {isAdmin ? null : <Storefront route={route} />}
        </LangProvider>
      </CurrencyProvider>
    </SiteDataProvider>
  );
}

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