/* ====================== App ====================== */

function CartDrawer({ open, cart, onClose, onRemove }) {
  const total = cart.reduce((s, p) => s + p.price, 0);
  return (
    <React.Fragment>
      <div className={`drawer-scrim ${open ? "show" : ""}`} onClick={onClose} />
      <aside className={`drawer ${open ? "show" : ""}`} aria-hidden={!open}>
        <div className="drawer-head">
          <span className="display">Your cart</span>
          <button className="drawer-x mono" onClick={onClose} aria-label="Close cart">✕</button>
        </div>
        {cart.length === 0 ? (
          <div className="drawer-empty mono">
            <Icon name="cart" size={30} />
            <p>Your cart is empty.<br/>Go find a treasure →</p>
          </div>
        ) : (
          <React.Fragment>
            <div className="drawer-items">
              {cart.map((p, i) => (
                <div className="drawer-item" key={p.id + i}>
                  <Placeholder label="" tone={p.tone} className="drawer-thumb" />
                  <div className="drawer-item-body">
                    <span className="drawer-item-name">{p.name}</span>
                    <span className="mono drawer-item-price">${p.price}</span>
                  </div>
                  <button className="drawer-rm mono" onClick={() => onRemove(i)} aria-label="Remove">✕</button>
                </div>
              ))}
            </div>
            <div className="drawer-foot">
              <div className="drawer-total mono">
                <span>SUBTOTAL</span><span>${total}</span>
              </div>
              <a href="#contact" className="btn btn-primary" onClick={onClose}>Request these items</a>
              <p className="mono drawer-fine">Reserve online — local pickup or delivery across DFW. We'll confirm availability & details by email.</p>
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

function App() {
  const [cart, setCart] = useState([]);
  const [drawer, setDrawer] = useState(false);
  const [lightbox, setLightbox] = useState(null);
  const [active, setActive] = useState("top");
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);

  useReveals();

  const addToCart = useCallback((p) => {
    setCart(c => c.find(x => x.id === p.id) ? c : [...c, p]);
    setToast(`Added “${p.name}” to cart`);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 2200);
  }, []);
  const removeFromCart = useCallback((idx) => setCart(c => c.filter((_, i) => i !== idx)), []);

  // scroll-spy
  useEffect(() => {
    const ids = ["top", "services", "sales", "gallery", "shop", "about", "learn", "faq", "contact"];
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: "-45% 0px -50% 0px" });
    ids.forEach(id => { const el = document.getElementById(id); if (el) io.observe(el); });
    return () => io.disconnect();
  }, []);

  return (
    <React.Fragment>
      <Nav active={active} />
      <button className={`cart-fab ${cart.length ? "has" : ""}`} onClick={() => setDrawer(true)} aria-label="Open cart">
        <Icon name="cart" size={22} />
        {cart.length > 0 && <span className="cart-count mono">{cart.length}</span>}
      </button>

      <main>
        <Hero />
        <Stats />
        <Services />
        <UpcomingSales />
        <Gallery onOpen={setLightbox} />
        <Shop onAdd={addToCart} cart={cart} />
        <About />
        <WhatIs />
        <FAQ />
        <Contact />
      </main>
      <ServiceAreas />
      <Footer />

      <CartDrawer open={drawer} cart={cart} onClose={() => setDrawer(false)} onRemove={removeFromCart} />
      <Lightbox item={lightbox} onClose={() => setLightbox(null)} />
      {toast && <div className="toast mono"><Icon name="check" size={16} /> {toast}</div>}
    </React.Fragment>
  );
}

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