/* Orlina — main app shell, manages cart + checkout state */

const { useState, useEffect, useMemo } = React;

function App() {
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [confirmation, setConfirmation] = useState(null);

  const [items, setItems] = useState([]);
  const [promoCode, setPromoCode] = useState('');
  const [promoApplied, setPromoApplied] = useState(false);
  const [toast, setToast] = useState(null);

  // PDP state
  const [pdpPack, setPdpPack] = useState('three');
  const [pdpQty, setPdpQty] = useState(1);

  // sticky buy visibility
  const [showSticky, setShowSticky] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      const pdpEl = document.querySelector('.pdp');
      if (!pdpEl) return;
      const rect = pdpEl.getBoundingClientRect();
      // show when PDP scrolls off-screen
      setShowSticky(rect.bottom < 0 || rect.top > window.innerHeight);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const addToCart = (packId, qty) => {
    const pack = PACKS.find(p => p.id === packId);
    setItems(prev => {
      const existing = prev.find(it => it.packId === packId);
      if (existing) {
        return prev.map(it => it.packId === packId ? { ...it, qty: it.qty + qty } : it);
      }
      return [...prev, { packId, name: pack.name, price: pack.price, qty }];
    });
    setToast(`Added ${pack.name} × ${qty}`);
    setTimeout(() => setToast(null), 2200);
    setCartOpen(true);
  };

  const updateQty = (packId, newQty) => {
    if (newQty <= 0) return removeItem(packId);
    setItems(prev => prev.map(it => it.packId === packId ? { ...it, qty: newQty } : it));
  };
  const removeItem = (packId) => setItems(prev => prev.filter(it => it.packId !== packId));

  const subtotal = useMemo(() => items.reduce((s, it) => s + it.price * it.qty, 0), [items]);
  const discount = promoApplied ? Math.round(subtotal * 0.10) : 0;
  const freeShip = subtotal >= 1500;
  const shipping = freeShip ? 0 : (items.length > 0 ? 49 : 0);
  const total = Math.max(0, subtotal - discount + shipping);

  const applyPromo = () => {
    if (promoCode.trim().toUpperCase() === 'ORLINA10') {
      setPromoApplied(true);
    } else if (promoCode.trim()) {
      setToast('Invalid promo code');
      setTimeout(() => setToast(null), 2000);
    }
  };

  const handleCheckout = () => {
    setCartOpen(false);
    setTimeout(() => setCheckoutOpen(true), 200);
  };

  const handlePlaceOrder = (order) => {
    setCheckoutOpen(false);
    setConfirmation(order);
    setItems([]);
    setPromoApplied(false);
    setPromoCode('');
  };

  return (
    <>
      <Announce />
      <Nav cartCount={items.reduce((s, i) => s + i.qty, 0)} onCartOpen={() => setCartOpen(true)} />
      <Hero onShop={() => document.getElementById('shop').scrollIntoView({ behavior: 'smooth' })} />
      <Marquee />
      <Benefits />
      <PDP
        selectedPack={pdpPack}
        setPack={setPdpPack}
        qty={pdpQty}
        setQty={setPdpQty}
        onAdd={() => addToCart(pdpPack, pdpQty)}
      />
      <HowToConsume />
      <Origin />
      <Reviews />
      <FAQ />
      <Footer />

      {/* sticky buy */}
      <div className={`sticky-buy ${showSticky ? 'visible' : ''}`}>
        <div className="preview"><img src="assets/product-bottle-box.jpeg" style={{ mixBlendMode: 'multiply' }} alt="" /></div>
        <div>
          <b>Sea Buckthorn Juice</b>
          <div style={{ fontSize: 11, color: 'var(--cream-200)' }}>from ₹899 · 200ml</div>
        </div>
        <button className="btn btn-primary" onClick={() => addToCart(pdpPack, 1)}>Add to cart</button>
      </div>

      <CartDrawer
        open={cartOpen}
        onClose={() => setCartOpen(false)}
        items={items}
        updateQty={updateQty}
        removeItem={removeItem}
        subtotal={subtotal}
        discount={discount}
        total={total}
        freeShip={freeShip}
        onCheckout={handleCheckout}
        promoCode={promoCode}
        setPromoCode={setPromoCode}
        applyPromo={applyPromo}
        promoApplied={promoApplied}
      />

      <Checkout
        open={checkoutOpen}
        onClose={() => { setCheckoutOpen(false); setCartOpen(true); }}
        items={items}
        subtotal={subtotal}
        discount={discount}
        freeShip={freeShip}
        total={total}
        promoApplied={promoApplied}
        onPlaceOrder={handlePlaceOrder}
      />

      {confirmation && (
        <Confirmation order={confirmation} onContinue={() => setConfirmation(null)} />
      )}

      {/* toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 100, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--brown-900)', color: 'var(--cream-50)',
          padding: '12px 24px', borderRadius: 999, fontSize: 13, fontWeight: 500,
          zIndex: 80, boxShadow: '0 12px 30px rgba(0,0,0,0.25)',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <Icon.Check size={16} /> {toast}
        </div>
      )}

      <OrlinaTweaks />
    </>
  );
}

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