/* Main app + simple state-based router */

const { useState: useStateA, useEffect: useEffectA } = React;

function App() {
  const [route, setRoute] = useStateA("home");
  const [params, setParams] = useStateA({});
  const [cart, setCart] = useStateA([]);
  const [favs, setFavs] = useStateA(new Set());
  const [cartOpen, setCartOpen] = useStateA(false);

  const navigate = (r, p = {}) => {
    setRoute(r);
    setParams(p);
    setCartOpen(false);
    window.scrollTo({ top: 0, behavior: "instant" });
  };
  const openProduct = (p) => navigate("product", { handle: p.handle });

  const addToCart = (p) => {
    setCart(prev => {
      const found = prev.find(ci => ci.handle === p.handle);
      if (found) return prev.map(ci => ci.handle === p.handle ? { ...ci, qty: ci.qty + 1 } : ci);
      return [...prev, { ...p, qty: 1 }];
    });
    setCartOpen(true);
  };
  const removeFromCart = (handle) => setCart(prev => prev.filter(ci => ci.handle !== handle));

  const toggleFav = (handle) => {
    setFavs(prev => {
      const next = new Set(prev);
      if (next.has(handle)) next.delete(handle); else next.add(handle);
      return next;
    });
  };

  const cartCount = cart.reduce((s, ci) => s + ci.qty, 0);

  let page = null;
  switch (route) {
    case "home":        page = <HomePage navigate={navigate} addToCart={addToCart} toggleFav={toggleFav} favs={favs} openProduct={openProduct} />; break;
    case "collections": page = <CollectionsPage navigate={navigate} />; break;
    case "collection":  page = <CollectionDetailPage navigate={navigate} params={params} openProduct={openProduct} favs={favs} toggleFav={toggleFav} />; break;
    case "product":     page = <ProductPage navigate={navigate} params={params} addToCart={addToCart} favs={favs} toggleFav={toggleFav} openProduct={openProduct} />; break;
    case "bespoke":     page = <BespokePage navigate={navigate} />; break;
    case "projects":    page = <ProjectsPage navigate={navigate} />; break;
    case "craft":       page = <CraftPage navigate={navigate} />; break;
    case "showroom":    page = <ShowroomPage navigate={navigate} />; break;
    case "contact":     page = <ContactPage navigate={navigate} />; break;
    default:            page = <HomePage navigate={navigate} addToCart={addToCart} toggleFav={toggleFav} favs={favs} openProduct={openProduct} />;
  }

  return (
    <div data-screen-label={"Hands / " + route}>
      <Navbar route={route} navigate={navigate} cartCount={cartCount} openCart={() => setCartOpen(true)} />
      {page}
      <Footer navigate={navigate} />
      <WhatsAppFab />
      <CartDrawer open={cartOpen} close={() => setCartOpen(false)} cart={cart} removeFromCart={removeFromCart} navigate={navigate} />
    </div>
  );
}

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