// RIFTR storefront — app shell wiring the views together.
(() => {
const { useState, useEffect } = React;

function App() {
  const [view, setView] = useState({ name: 'home' });
  const [cat, setCat] = useState('All');
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [confirm, setConfirm] = useState(false);

  useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const addToCart = (p, qty) => {
    setCart((c) => {
      const e = c.find((x) => x.id === p.id);
      if (e) return c.map((x) => (x.id === p.id ? { ...x, qty: x.qty + qty } : x));
      return [...c, { id: p.id, name: p.name, price: p.price, img: p.img, qty }];
    });
    setCartOpen(true);
  };
  const changeQty = (id, d) => setCart((c) => c.map((x) => (x.id === id ? { ...x, qty: x.qty + d } : x)).filter((x) => x.qty > 0));
  const home = () => setView({ name: 'home' });

  const { Header, Hero, Grid, ProductPage, Checkout, CartDrawer, Confirm, Footer } = window;

  return (
    <React.Fragment>
      <Header cart={cart} cat={cat} setCat={setCat} onCart={() => setCartOpen(true)} onHome={home} />
      <main style={{ flex: 1 }}>
        {view.name === 'home' && (
          <React.Fragment>
            <Hero
              product={window.RIFTR_PRODUCTS[0]}
              onShop={() => { const g = document.getElementById('grid'); if (g) window.scrollTo({ top: g.getBoundingClientRect().top + window.pageYOffset - 70, behavior: 'smooth' }); }}
              onProduct={(p) => setView({ name: 'product', p })}
            />
            <div id="grid"><Grid cat={cat} onProduct={(p) => setView({ name: 'product', p })} /></div>
          </React.Fragment>
        )}
        {view.name === 'product' && (
          <ProductPage p={view.p} onBack={home} onAdd={addToCart} />
        )}
        {view.name === 'checkout' && (
          <Checkout cart={cart} onBack={home} onClearCart={() => setCart([])} />
        )}
      </main>
      <Footer />
      <CartDrawer open={cartOpen} cart={cart} onClose={() => setCartOpen(false)} onQty={changeQty}
        onCheckout={() => { setCartOpen(false); setView({ name: 'checkout' }); }} />
      <Confirm open={confirm} onClose={() => setConfirm(false)} />
    </React.Fragment>
  );
}

// Load products from the API before mounting, so the catalogue + category
// filter are populated on first render. Mount defensively: even if RIFTR_LOAD
// is missing (e.g. a stale cached data.js) or the fetch rejects, still render
// the app rather than leaving a blank page.
const boot = () => ReactDOM.createRoot(document.getElementById('root')).render(<App />);
const loader = (typeof window.RIFTR_LOAD === 'function') ? window.RIFTR_LOAD() : Promise.resolve();
loader.then(boot).catch(boot);
})();
