// Main app — routing, state, chrome wiring

const { useState, useEffect } = React;

function CustomCursor() {
  const dotRef  = React.useRef(null);
  const ringRef = React.useRef(null);
  const mx = React.useRef(-100), my = React.useRef(-100);
  const rx = React.useRef(-100), ry = React.useRef(-100);
  const raf = React.useRef(null);
  const stateRef = React.useRef('default');
  const [state, setState] = React.useState('default');
  const [ripples, setRipples] = React.useState([]);
  const [visible, setVisible] = React.useState(true);

  React.useEffect(() => {
    if (!window.matchMedia('(hover: hover) and (pointer: fine)').matches) return;

    const onMove = (e) => { mx.current = e.clientX; my.current = e.clientY; setVisible(true); };
    const onLeave = () => setVisible(false);
    const onEnter = () => setVisible(true);
    const onDown = () => { stateRef.current = 'click'; setState('click'); };
    const onUp   = () => { stateRef.current = 'default'; setState('default'); };
    const onOver = (e) => {
      if (stateRef.current === 'click') return;
      const s = e.target.closest('button,a,input,select,[role="button"]') ? 'hover' : 'default';
      stateRef.current = s; setState(s);
    };
    const onClick = (e) => {
      const id = Date.now() + Math.random();
      setRipples(r => [...r, { x: e.clientX, y: e.clientY, id }]);
      setTimeout(() => setRipples(r => r.filter(p => p.id !== id)), 650);
    };

    const loop = () => {
      rx.current += (mx.current - rx.current) * 0.18;
      ry.current += (my.current - ry.current) * 0.18;
      if (dotRef.current)
        dotRef.current.style.transform = `translate(calc(${mx.current}px - 50%), calc(${my.current}px - 50%))`;
      if (ringRef.current)
        ringRef.current.style.transform = `translate(calc(${rx.current}px - 50%), calc(${ry.current}px - 50%))`;
      raf.current = requestAnimationFrame(loop);
    };

    document.addEventListener('mousemove', onMove, { passive: true });
    document.addEventListener('mousedown', onDown);
    document.addEventListener('mouseup',   onUp);
    document.addEventListener('mouseover', onOver, { passive: true });
    document.addEventListener('click',     onClick);
    document.documentElement.addEventListener('mouseleave', onLeave);
    document.documentElement.addEventListener('mouseenter', onEnter);
    raf.current = requestAnimationFrame(loop);

    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('mouseup',   onUp);
      document.removeEventListener('mouseover', onOver);
      document.removeEventListener('click',     onClick);
      document.documentElement.removeEventListener('mouseleave', onLeave);
      document.documentElement.removeEventListener('mouseenter', onEnter);
      cancelAnimationFrame(raf.current);
    };
  }, []);

  if (!window.matchMedia('(hover: hover) and (pointer: fine)').matches) return null;

  const dotSize  = state === 'click' ? 12 : 7;
  const ringSize = state === 'hover' ? 44 : state === 'click' ? 20 : 32;

  return (
    <>
      <div ref={dotRef} style={{
        position: 'fixed', zIndex: 10000, pointerEvents: 'none', top: 0, left: 0,
        width: dotSize, height: dotSize, borderRadius: '50%',
        background: state === 'hover' ? '#b8945e' : '#1a1410',
        willChange: 'transform',
        opacity: visible ? 1 : 0,
        transition: 'width 0.12s, height 0.12s, background 0.2s, opacity 0.4s',
      }}/>
      {ripples.map(r => (
        <div key={r.id} style={{
          position: 'fixed', zIndex: 9998, pointerEvents: 'none',
          width: 36, height: 36, borderRadius: '50%', border: '1.5px solid #7a2628',
          top: 0, left: 0, willChange: 'transform, opacity',
          transform: `translate(calc(${r.x}px - 50%), calc(${r.y}px - 50%))`,
          animation: 'cursorRipple 0.65s cubic-bezier(0.22,1,0.36,1) forwards',
        }}/>
      ))}
    </>
  );
};

function App() {
  const [tweaks, setTweak] = window.useTweaks({
    theme: 'light',
    accent: '#7a2628',
    density: 'comfortable',
    buttonShape: 'pill',
  });

  const [viewport, setViewport] = useState('desktop');
  const getInitialPage = () => {
    const path = (window.WP_PATH || '/').toLowerCase();
    if (path.includes('order-received')) return 'ThankYou';
    if (path.includes('order-pay')) return 'Home'; // let woocommerce.php handle CC Avenue pay page
    if (path.includes('/checkout')) return 'Checkout';
    if (path.includes('/cart')) return 'Cart';
    if (path.includes('/shop')) return 'Shop';
    if (path.includes('/my-account')) return 'Account';
    return 'Home';
  };
  // Extract order ID from URL like /checkout/order-received/12345/
  const getOrderId = () => {
    const match = (window.WP_PATH || '').match(/order-received\/(\d+)/);
    return match ? match[1] : null;
  };
  const [page, setPage] = useState(getInitialPage());
  const [productId, setProductId] = useState('classic-chyawanprash');
  const [cart, setCart] = useState([]);
  const [wishlist, setWishlist] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [quizOpen, setQuizOpen] = useState(false);
  const [chatOpen, setChatOpen] = useState(false);
  const [stickyATC, setStickyATC] = useState(null);
  const [stickyVisible, setStickyVisible] = useState(false);
  const [selectedIngredient, setSelectedIngredient] = useState(null);
  const [ingredientClosing, setIngredientClosing] = useState(false);
  const closeIngredient = () => { setIngredientClosing(true); setTimeout(() => { setIngredientClosing(false); setSelectedIngredient(null); }, 250); };
  const [zoomImg, setZoomImg] = useState(null);
  const [zoomClosing, setZoomClosing] = useState(false);
  const closeZoom = () => { setZoomClosing(true); setTimeout(() => { setZoomClosing(false); setZoomImg(null); }, 250); };
  const stickyTimerRef = React.useRef(null);

  const handleStickyATC = (data) => {
    if (data) {
      clearTimeout(stickyTimerRef.current);
      setStickyATC(data);
      setStickyVisible(true);
    } else {
      setStickyVisible(false);
      stickyTimerRef.current = setTimeout(() => setStickyATC(null), 280);
    }
  };

  // Theme application
  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute('data-theme', tweaks.theme || 'light');
    // accent
    const a = { accent: tweaks.accent && tweaks.accent.startsWith('#') ? tweaks.accent : '#7a2628', gold: '#b8945e' };
    // Apply on viewport element rather than root so dark theme tokens still win
    document.querySelectorAll('.viewport').forEach(v => {
      v.style.setProperty('--accent', a.accent);
      v.style.setProperty('--gold', a.gold);
    });
  }, [tweaks.theme, tweaks.accent]);

  const goto = (p, pid) => {
    setPage(p);
    if (pid) setProductId(pid);
    window.scrollTo({ top: 0, behavior: 'instant' });
    const v = document.querySelector('.viewport');
    if (v) v.scrollTop = 0;
  };

  const addToCart = (p, qty = 1, sub = false) => {
    setCart(curr => {
      const existing = curr.find(x => x.id === p.id);
      if (existing) {
        return curr.map(x => x.id === p.id ? { ...x, qty: x.qty + qty } : x);
      }
      return [...curr, { ...p, qty, sub }];
    });
    setCartOpen(true);
  };
  const updateQty = (id, qty) => setCart(c => c.map(x => x.id === id ? { ...x, qty } : x));
  const removeItem = (id) => setCart(c => c.filter(x => x.id !== id));
  const clearCart = () => setCart([]);
  const toggleWish = (id) => setWishlist(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]);

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

  const renderPage = () => {
    const common = { vp: viewport, goto, addToCart, wishlist, toggleWish, openQuiz: () => setQuizOpen(true) };
    switch (page) {
      case 'Home': return <window.HomePage {...common} onIngredientSelect={setSelectedIngredient}/>;
      case 'Shop': return <window.ShopPage {...common}/>;
      case 'Product': return <window.ProductPage {...common} productId={productId} onStickyATC={handleStickyATC} openQuiz={() => setQuizOpen(true)} onZoom={setZoomImg}/>;
      case 'Cart': return <window.CartPage vp={viewport} goto={goto} items={cart} updateQty={updateQty} removeItem={removeItem}/>;
      case 'Checkout': return <window.CheckoutPage vp={viewport} goto={goto} items={cart} clearCart={clearCart} addToCart={addToCart}/>;
      case 'ThankYou': return <window.ThankYouPage vp={viewport} goto={goto} orderId={getOrderId()}/>;
      case 'About': return <window.AboutPage vp={viewport} goto={goto}/>;
      case 'Ingredients': return <window.IngredientsPage vp={viewport} goto={goto}/>;
      case 'Journal': return <window.JournalPage vp={viewport} goto={goto}/>;
      case 'Contact': return <window.ContactPage vp={viewport}/>;
      case 'Account': return <window.AccountPage vp={viewport} goto={goto}/>;
      default: return <window.HomePage {...common}/>;
    }
  };

  const Tweaks = window.TweaksPanel;
  const TS = window.TweakSection;
  const TR = window.TweakRadio;
  const TC = window.TweakColor;

  // WordPress mode: no design chrome, full-page layout
  if (window.IS_WORDPRESS) {
    return (
      <>
        <div style={{ background: 'var(--bg)', color: 'var(--ink)', minHeight: '100vh' }}>
          <window.Header vp="desktop" page={page} goto={goto} openCart={() => setCartOpen(true)} openSearch={() => setSearchOpen(true)} cartCount={cartCount} openQuiz={() => setQuizOpen(true)}/>
          <style>{`.page-wrap { animation: pageIn 0.35s cubic-bezier(0.22,1,0.36,1) both; } @keyframes pageIn { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:translateY(0); } }`}</style>
          <div key={page + productId} className="page-wrap">{renderPage()}</div>
          <window.Footer vp="desktop" goto={goto}/>
          <a href="https://wa.me/919867800415" target="_blank" rel="noopener noreferrer" className="chat-fab" aria-label="WhatsApp us" style={{ background: '#25D366', textDecoration: 'none', bottom: stickyVisible ? 86 : 24, transition: 'bottom 0.3s cubic-bezier(0.22,1,0.36,1)' }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
          </a>
        </div>

        {/* Modals outside main div */}
        {selectedIngredient && (
          <div className="modal-back" onClick={closeIngredient} style={{ animation: ingredientClosing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.2s' }}>
            <div onClick={e => e.stopPropagation()} style={{ width: 'min(480px, 100%)', background: 'var(--bg)', borderRadius: 20, padding: 0, animation: ingredientClosing ? 'slideUpOut 0.25s forwards' : 'slideUp 0.3s', overflow: 'hidden' }}>
              <div style={{ position: 'relative' }}>
                {selectedIngredient.img ? <img src={window.imgSrc ? window.imgSrc(selectedIngredient.img) : selectedIngredient.img} alt={selectedIngredient.name} style={{ width: '100%', height: 220, objectFit: 'cover', display: 'block' }}/> : <div className="ph product" style={{ height: 220 }}>{selectedIngredient.name}</div>}
                <button onClick={closeIngredient} style={{ position: 'absolute', top: 12, right: 12, width: 32, height: 32, borderRadius: 999, background: 'rgba(0,0,0,0.4)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon name="close" size={14}/></button>
              </div>
              <div style={{ padding: '24px 28px 32px' }}>
                <div className="mono" style={{ color: 'var(--accent)', marginBottom: 6, fontSize: 10 }}>{selectedIngredient.role}</div>
                <h3 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 4 }}>{selectedIngredient.name}</h3>
                <div className="serif" style={{ fontStyle: 'italic', color: 'var(--muted)', fontSize: 14, marginBottom: 16 }}>{selectedIngredient.latin}</div>
                <div style={{ padding: '14px 16px', background: 'var(--surface)', borderRadius: 10, marginBottom: 16 }}><div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 4 }}>Sourcing</div><div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{selectedIngredient.note}</div></div>
                <button onClick={closeIngredient} className="btn btn-ghost" style={{ width: '100%' }}>Close</button>
              </div>
            </div>
          </div>
        )}
        {zoomImg && (
          <div onClick={closeZoom} style={{ position: 'fixed', inset: 0, zIndex: 1100, background: 'rgba(10,8,6,0.6)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, cursor: 'zoom-out', animation: zoomClosing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.25s' }}>
            <img src={zoomImg} alt="Product zoom" onClick={e => e.stopPropagation()} style={{ maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain', borderRadius: 12, animation: zoomClosing ? 'slideUpOut 0.25s forwards' : 'imageReveal 0.35s cubic-bezier(0.22,1,0.36,1)', cursor: 'default', boxShadow: '0 32px 80px rgba(0,0,0,0.4)' }}/>
            <button onClick={closeZoom} style={{ position: 'fixed', top: 24, right: 24, width: 40, height: 40, borderRadius: 999, background: 'rgba(255,255,255,0.12)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(8px)', zIndex: 1101 }}><window.Icon name="close" size={16}/></button>
          </div>
        )}
        {stickyATC && (
          <div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 200, background: 'var(--bg)', borderTop: '1px solid var(--line-soft)', padding: '12px 24px', display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between', boxShadow: '0 -4px 24px rgba(0,0,0,0.1)', animation: `${stickyVisible ? 'fadeInUp' : 'fadeOutDown'} 0.28s cubic-bezier(0.22,1,0.36,1) both` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
              <div className="ph product" style={{ width: 40, height: 50, borderRadius: 6, flexShrink: 0 }}/>
              <div style={{ minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--ink)' }}>{stickyATC.p.name}</div><div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>₹{stickyATC.price.toLocaleString('en-IN')}</div></div>
            </div>
            <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
              <button className="btn btn-ghost btn-sm" onClick={() => { stickyATC.addToCart(stickyATC.p, stickyATC.qty, stickyATC.subscribe); stickyATC.goto('Checkout'); }}>Buy now</button>
              <button className="btn btn-primary btn-sm" onClick={() => stickyATC.addToCart(stickyATC.p, stickyATC.qty, stickyATC.subscribe)}>Add to basket</button>
            </div>
          </div>
        )}
        <window.CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} items={cart} updateQty={updateQty} removeItem={removeItem} goto={(p) => { setCartOpen(false); goto(p); }}/>
        <window.SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} goto={(p) => { setSearchOpen(false); goto(p); }}/>
        <window.QuizModal open={quizOpen} onClose={() => setQuizOpen(false)} goto={goto} addToCart={addToCart}/>
      </>
    );
  }

  return (
    <>
<window.TopChrome viewport={viewport} setViewport={setViewport} page={page} setPage={goto} theme={tweaks.theme} toggleTheme={() => setTweak('theme', tweaks.theme === 'dark' ? 'light' : 'dark')}/>

      <div className="stage" data-screen-label={`${page} · ${viewport}`}>
        <div className="viewport" data-vp={viewport}>
          <window.Header vp={viewport} page={page} goto={goto} openCart={() => setCartOpen(true)} openSearch={() => setSearchOpen(true)} cartCount={cartCount} openQuiz={() => setQuizOpen(true)}/>
          <style>{`
            @keyframes pageIn {
              from { opacity: 0; transform: translateY(14px); }
              to   { opacity: 1; transform: translateY(0); }
            }
            .page-wrap { animation: pageIn 0.35s cubic-bezier(0.22, 1, 0.36, 1) both; }
          `}</style>
          <div key={page + productId} className="page-wrap">
            {renderPage()}
          </div>
          <window.Footer vp={viewport} goto={goto}/>

          {/* WhatsApp FAB */}
          <a href="https://wa.me/919867800415" target="_blank" rel="noopener noreferrer" className="chat-fab" aria-label="WhatsApp us" style={{ background: '#25D366', textDecoration: 'none', bottom: stickyVisible ? 86 : 24, transition: 'bottom 0.3s cubic-bezier(0.22,1,0.36,1)' }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
          </a>
        </div>
      </div>

      {/* Image zoom lightbox */}
      {zoomImg && (
        <div onClick={closeZoom} style={{ position: 'fixed', inset: 0, zIndex: 1100, background: 'rgba(10,8,6,0.6)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, cursor: 'zoom-out', animation: zoomClosing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.25s' }}>
          <img src={zoomImg} alt="Product zoom" onClick={e => e.stopPropagation()} style={{ maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain', borderRadius: 12, animation: zoomClosing ? 'slideUpOut 0.25s forwards' : 'imageReveal 0.35s cubic-bezier(0.22,1,0.36,1)', cursor: 'default', boxShadow: '0 32px 80px rgba(0,0,0,0.4)' }}/>
          <button onClick={closeZoom} style={{ position: 'fixed', top: 64, right: 24, width: 40, height: 40, borderRadius: 999, background: 'rgba(255,255,255,0.12)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(8px)', zIndex: 1101, transition: 'background 0.2s' }}
            onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.22)'}
            onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.12)'}>
            <window.Icon name="close" size={16}/>
          </button>
        </div>
      )}

      {/* Ingredient detail modal — outside viewport so position:fixed works correctly */}
      {selectedIngredient && (
        <div className="modal-back" onClick={closeIngredient} style={{ animation: ingredientClosing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.2s' }}>
          <div onClick={e => e.stopPropagation()} style={{ width: 'min(480px, 100%)', background: 'var(--bg)', borderRadius: 20, padding: 0, animation: ingredientClosing ? 'slideUpOut 0.25s forwards' : 'slideUp 0.3s', overflow: 'hidden' }}>
            <div style={{ position: 'relative' }}>
              {selectedIngredient.img
                ? <img src={window.imgSrc ? window.imgSrc(selectedIngredient.img) : selectedIngredient.img} alt={selectedIngredient.name} style={{ width: '100%', height: 220, objectFit: 'cover', display: 'block' }}/>
                : <div className="ph product" style={{ height: 220 }}>{selectedIngredient.name}</div>
              }
              <button onClick={closeIngredient} style={{ position: 'absolute', top: 12, right: 12, width: 32, height: 32, borderRadius: 999, background: 'rgba(0,0,0,0.4)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <window.Icon name="close" size={14}/>
              </button>
            </div>
            <div style={{ padding: '24px 28px 32px' }}>
              <div className="mono" style={{ color: 'var(--accent)', marginBottom: 6, fontSize: 10 }}>{selectedIngredient.role}</div>
              <h3 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 4 }}>{selectedIngredient.name}</h3>
              <div className="serif" style={{ fontStyle: 'italic', color: 'var(--muted)', fontSize: 14, marginBottom: 16 }}>{selectedIngredient.latin}</div>
              <div style={{ padding: '14px 16px', background: 'var(--surface)', borderRadius: 10, marginBottom: 16 }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginBottom: 4 }}>Sourcing</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{selectedIngredient.note}</div>
              </div>
              <button onClick={closeIngredient} className="btn btn-ghost" style={{ width: '100%' }}>Close</button>
            </div>
          </div>
        </div>
      )}

      {/* Sticky ATC bar — outside viewport so position:fixed works correctly */}
      {stickyATC && (
        <div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 200, background: 'var(--bg)', borderTop: '1px solid var(--line-soft)', padding: '12px 24px', display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between', boxShadow: '0 -4px 24px rgba(0,0,0,0.1)', animation: `${stickyVisible ? 'fadeInUp' : 'fadeOutDown'} 0.28s cubic-bezier(0.22,1,0.36,1) both` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
            <div className="ph product" style={{ width: 40, height: 50, borderRadius: 6, flexShrink: 0 }}/>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--ink)' }}>{stickyATC.p.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>₹{stickyATC.price.toLocaleString('en-IN')}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => { stickyATC.addToCart(stickyATC.p, stickyATC.qty, stickyATC.subscribe); stickyATC.goto('Checkout'); }}>Buy now</button>
            <button className="btn btn-primary btn-sm" onClick={() => stickyATC.addToCart(stickyATC.p, stickyATC.qty, stickyATC.subscribe)}>Add to basket</button>
          </div>
        </div>
      )}

      {/* Global overlays (outside viewport) */}
      <window.CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} items={cart} updateQty={updateQty} removeItem={removeItem} goto={(p) => { setCartOpen(false); goto(p); }}/>
      <window.SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} goto={(p) => { setSearchOpen(false); goto(p); }}/>
      <window.QuizModal open={quizOpen} onClose={() => setQuizOpen(false)} goto={goto} addToCart={addToCart}/>

      {/* Tweaks Panel */}
      {Tweaks && (
        <Tweaks title="Tweaks">
          <TS title="Appearance">
            <TR label="Theme" value={tweaks.theme} onChange={(v) => setTweak('theme', v)} options={['light','dark']}/>
            <TC label="Accent" value={tweaks.accent} onChange={(v) => setTweak('accent', v)} options={['#7a2628','#8a4d3e','#b8945e','#3d5240']}/>
          </TS>
          <TS title="Layout">
            <TR label="Density" value={tweaks.density} onChange={(v) => setTweak('density', v)} options={['compact','comfortable']}/>
          </TS>
          <TS title="Try the flow">
            <window.TweakButton label="Open find-my-paste quiz" onClick={() => setQuizOpen(true)}/>
            <window.TweakButton label="Open AI assistant" onClick={() => setChatOpen(true)}/>
            <window.TweakButton label="Add classic to cart" onClick={() => addToCart(window.PRODUCTS[0])}/>
          </TS>
        </Tweaks>
      )}
    </>
  );
};

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