// Karavi Studio · App shell + router (with page transitions)
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [route, setRoute] = useStateApp("home");
  const [cartOpen, setCartOpen] = useStateApp(false);
  const [cart, setCart] = useStateApp([]);

  const goto = (r) => {
    setRoute(r);
    setCartOpen(false);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  const addToCart = (p, size) => {
    setCart(c => {
      const i = c.findIndex(x => x.p.id === p.id && x.size === size);
      if (i >= 0) {
        const next = [...c];
        next[i] = { ...next[i], qty: next[i].qty + 1 };
        return next;
      }
      return [...c, { p, size, qty: 1 }];
    });
    setCartOpen(true);
  };

  const onRemove = (i) => setCart(c => c.filter((_, x) => x !== i));
  const onQty = (i, d) => setCart(c =>
    c.map((it, x) => x === i ? { ...it, qty: Math.max(1, it.qty + d) } : it)
  );

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

  // Resolve route to a page
  const renderPage = () => {
    const [base, param] = route.split(":");
    if (base === "product")  return <Product id={param} goto={goto} addToCart={addToCart}/>;
    if (base === "category") return <Category name={param} goto={goto}/>;
    if (base === "shop") {
      const topCats = ["All", "Bedding", "Rugs", "Cushions", "Lighting", "Décor"];
      if (param && topCats.includes(param))      return <Shop goto={goto} initialCat={param}/>;
      if (param) {
        const found = window.KARAVI_PRODUCTS.find(p => p.subcat === param);
        return <Shop goto={goto} initialCat={found ? found.category : "All"} initialSub={param}/>;
      }
      return <Shop goto={goto} initialCat="All"/>;
    }
    if (route === "story")   return <Story goto={goto}/>;
    if (route === "contact") return <Contact/>;
    return <Home goto={goto} addToCart={addToCart}/>;
  };

  return (
    <div>
      <Header goto={goto} openCart={() => setCartOpen(true)} cartCount={cartCount}/>

      {/* Page transition wrapper */}
      <AnimatePresence mode="wait">
        <motion.div
          key={route}
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -8 }}
          transition={{ duration: 0.36, ease: [0.22, 0.61, 0.36, 1] }}
        >
          {renderPage()}
        </motion.div>
      </AnimatePresence>

      <Footer goto={goto}/>
      <Cart
        open={cartOpen}
        onClose={() => setCartOpen(false)}
        items={cart}
        onRemove={onRemove}
        onQty={onQty}
      />
    </div>
  );
}

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