// components/drawers.jsx — cart, wishlist, search, mobile-menu, quickview, notif

/** Focus trap + Escape + initial focus for drawer/dialog roots. */
function useFocusTrap(active) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!active) return undefined;
    const root = ref.current;
    if (!root) return undefined;
    const FOCUSABLE = 'a[href],button:not([disabled]),textarea,input,select,[tabindex]:not([tabindex="-1"])';
    const nodes = () => Array.from(root.querySelectorAll(FOCUSABLE)).filter((el) => el.offsetParent !== null || el === document.activeElement);
    const prev = document.activeElement;
    const first = nodes()[0];
    if (first && typeof first.focus === 'function') {
      setTimeout(() => first.focus(), 40);
    }
    const onKey = (e) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        if (window.HAPStore) {
          window.HAPStore.closeDrawer && window.HAPStore.closeDrawer();
          window.HAPStore.closeModal && window.HAPStore.closeModal();
        }
        return;
      }
      if (e.key !== 'Tab') return;
      const list = nodes();
      if (!list.length) return;
      const i = list.indexOf(document.activeElement);
      if (e.shiftKey) {
        if (i <= 0) {
          e.preventDefault();
          list[list.length - 1].focus();
        }
      } else if (i === list.length - 1 || i < 0) {
        e.preventDefault();
        list[0].focus();
      }
    };
    root.addEventListener('keydown', onKey);
    return () => {
      root.removeEventListener('keydown', onKey);
      if (prev && typeof prev.focus === 'function') {
        try { prev.focus(); } catch (_) {}
      }
    };
  }, [active]);
  return ref;
}

function CartDrawer() {
  const store = useStore();
  const trapRef = useFocusTrap(true);
  const lines = store.cartLines().filter((l) => l.ok !== false);
  const subtotal = store.cartSubtotal();
  const freeThreshold = window.CustomerCommerce.shippingSettings().freeAbove;
  const progress = Math.min(1, subtotal / freeThreshold);

  React.useEffect(() => {
    if (store.expireReservations) store.expireReservations();
  }, []);

  return (
    <div ref={trapRef} className="drawer" role="dialog" aria-modal="true" aria-label="Shopping bag" onClick={(e) => e.stopPropagation()}>
      <div className="drawer__head">
        <h2 className="drawer__title">Your bag <span style={{ color: 'var(--muted)', fontSize: '.85rem' }}>· {store.cartCount()}</span></h2>
        <button className="icon-btn" onClick={() => store.closeDrawer()} aria-label="Close"><Icon name="close" /></button>
      </div>

      <div className="drawer__body">
        {/* Free shipping progress */}
        <div style={{ background: 'var(--cream)', padding: '14px 16px', borderRadius: 12, marginBottom: 16 }}>
          <div style={{ fontSize: '.82rem', marginBottom: 8 }}>
            {subtotal >= freeThreshold
              ? <span style={{ color: 'var(--success)' }}>✓ Free shipping unlocked</span>
              : <span>Add <b>{HAP.formatPrice(freeThreshold - subtotal)}</b> for free shipping</span>}
          </div>
          <div style={{ height: 4, background: 'rgba(0,0,0,0.08)', borderRadius: 4, overflow: 'hidden' }}>
            <div style={{ width: `${progress*100}%`, height: '100%', background: 'var(--forest)', transition: 'width 280ms' }}></div>
          </div>
        </div>

        {lines.length === 0 ? (
          <EmptyState
            icon="cart"
            title="Your bag is empty"
            note="Add some pebbles, a pot or a statue to get started."
            cta={{ label: 'Browse pebbles', href: '#/collections/pebbles' }}
            onCta={() => store.closeDrawer()}
          />
        ) : (
          lines.map(l => (
            <div key={l.productId + l.variant} className="cart-line">
              <a className="cart-line__thumb" href={'#/products/' + l.product.slug} onClick={() => store.closeDrawer()}>
                <img src={l.product.image} alt={l.product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </a>
              <div className="cart-line__body">
                <a className="cart-line__title" href={'#/products/' + l.product.slug} onClick={() => store.closeDrawer()}>{l.product.name}</a>
                <div className="cart-line__variant">{l.variant}</div>
                <div className="cart-line__qty">
                  <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty - 1)} aria-label="Decrease quantity"><Icon name="minus" size={14}/></button>
                  <span className="count">{l.qty}</span>
                  <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty + 1)} aria-label="Increase quantity"><Icon name="plus" size={14}/></button>
                </div>
                <button className="cart-line__remove" onClick={() => store.removeCart(l.productId, l.variant)}>Remove</button>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="cart-line__price">{HAP.formatPrice(l.line)}</div>
                {l.qty > 1 && <div style={{ fontSize: '.72rem', color: 'var(--muted)' }}>{HAP.formatPrice(l.unit)} ea</div>}
              </div>
            </div>
          ))
        )}

        {/* Recently viewed */}
        {lines.length > 0 && <RecentlyViewedStrip />}
      </div>

      {lines.length > 0 && (
        <div className="drawer__foot">
          <div className="spread" style={{ fontFamily: 'var(--serif)', fontSize: '1.15rem' }}>
            <span>Subtotal</span>
            <span>{HAP.formatPrice(subtotal)}</span>
          </div>
          <div style={{ fontSize: '.78rem', color: 'var(--muted)' }}>Shipping & taxes calculated at checkout.</div>
          <a className="btn btn--primary btn--full" href="#/checkout" onClick={() => store.closeDrawer()}>Checkout · {HAP.formatPrice(subtotal)}</a>
          <a className="btn btn--ghost btn--full" href="#/cart" onClick={() => store.closeDrawer()}>View bag</a>
        </div>
      )}
    </div>
  );
}

function WishlistDrawer() {
  const store = useStore();
  const trapRef = useFocusTrap(true);
  const items = store.wishProducts();
  return (
    <div ref={trapRef} className="drawer" role="dialog" aria-modal="true" aria-label="Wishlist" onClick={(e) => e.stopPropagation()}>
      <div className="drawer__head">
        <h2 className="drawer__title">Wishlist <span style={{ color: 'var(--muted)', fontSize: '.85rem' }}>· {items.length}</span></h2>
        <button className="icon-btn" onClick={() => store.closeDrawer()} aria-label="Close"><Icon name="close" /></button>
      </div>
      <div className="drawer__body">
        {items.length === 0 ? (
          <EmptyState
            icon="heart"
            title="Save the ones you love"
            note="Tap the heart on any product to keep it here."
            cta={{ label: 'Discover pebbles', href: '#/collections/pebbles' }}
            onCta={() => store.closeDrawer()}
          />
        ) : items.map(p => (
          <div key={p.id} className="cart-line">
            <a className="cart-line__thumb" href={'#/products/' + p.slug} onClick={() => store.closeDrawer()}>
              <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </a>
            <div className="cart-line__body">
              <a className="cart-line__title" href={'#/products/' + p.slug} onClick={() => store.closeDrawer()}>{p.name}</a>
              <div className="cart-line__variant">{HAP.formatPrice(p.price)}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                <button className="btn btn--sm btn--secondary"
                        onClick={() => { store.addToCart(p.id, p.variants[0], 1); }}>Add to bag</button>
                <button className="btn btn--sm btn--ghost" onClick={() => store.toggleWishlist(p.id)}>Remove</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function SearchDrawer() {
  const store = useStore();
  const trapRef = useFocusTrap(true);
  const [q, setQ] = React.useState('');
  const results = React.useMemo(() => {
    if (window.CustomerSearch && window.CustomerSearch.suggestions) {
      return window.CustomerSearch.suggestions(q).products || [];
    }
    return HAP.search(q);
  }, [q]);
  const emptyHelp = React.useMemo(() => {
    if (!q || results.length > 0) return null;
    if (window.CustomerSearch && window.CustomerSearch.emptyStateHelp) {
      return window.CustomerSearch.emptyStateHelp(q);
    }
    return { message: 'No products found.', popularProducts: [] };
  }, [q, results.length]);
  const inputRef = React.useRef(null);
  React.useEffect(() => { setTimeout(() => inputRef.current && inputRef.current.focus(), 80); }, []);
  const onResultClick = () => {
    if (window.CustomerSearch && window.CustomerSearch.pushRecent) window.CustomerSearch.pushRecent(q);
    store.closeDrawer();
  };

  return (
    <div ref={trapRef} className="drawer" role="dialog" aria-modal="true" aria-label="Search products" style={{ width: 'min(560px, 96vw)' }} onClick={(e) => e.stopPropagation()}>
      <div className="drawer__head">
        <div style={{ position: 'relative', flex: 1 }}>
          <Icon name="search" size={18} style={{ position: 'absolute', top: '50%', left: 14, transform: 'translateY(-50%)', color: 'var(--muted)' }} />
          <input ref={inputRef} className="input input--lg" placeholder="Search pebbles, stones, pots…"
                 value={q} onChange={(e) => setQ(e.target.value)}
                 aria-label="Search products"
                 style={{ paddingLeft: 42, width: '100%' }} />
        </div>
        <button className="icon-btn" onClick={() => store.closeDrawer()} aria-label="Close"><Icon name="close" /></button>
      </div>
      <div className="drawer__body">
        {!q ? (
          <>
            <h4 style={{ fontSize: '.72rem', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--moss)', marginBottom: 12 }}>Trending searches</h4>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
              {HAP.TRENDING_SEARCHES.map(t => (
                <button key={t} className="tag" onClick={() => setQ(t)}>{t}</button>
              ))}
            </div>
            <h4 style={{ fontSize: '.72rem', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--moss)', marginBottom: 12 }}>Popular categories</h4>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {['Coloured Pebbles', 'White Pebbles', 'Black Pebbles', 'Marble Chips', 'Buddha Statues', 'Glass Pebbles'].map((t, i) => {
                const slugs = ['coloured-pebbles', 'white-pebbles', 'black-pebbles', 'marble-chips', 'buddha', 'glass-pebbles'];
                return (
                  <a key={t} href={'#/collections/' + slugs[i]} onClick={() => store.closeDrawer()}
                     style={{ padding: '12px 14px', background: 'var(--cream)', borderRadius: 12, fontSize: '.9rem' }}>{t}</a>
                );
              })}
            </div>
          </>
        ) : results.length === 0 ? (
          <div>
            <EmptyState icon="search" title="No products found." note={emptyHelp && emptyHelp.query ? `Nothing matched "${emptyHelp.query}".` : `No matches for "${q}".`} />
            {(emptyHelp && emptyHelp.popularProducts && emptyHelp.popularProducts.length > 0) && (
              <div style={{ marginTop: 8 }}>
                <h4 style={{ fontSize: '.72rem', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--moss)', marginBottom: 12 }}>Popular</h4>
                {emptyHelp.popularProducts.map((p) => (
                  <a key={p.id} href={'#/products/' + p.slug} onClick={onResultClick} className="cart-line" style={{ alignItems: 'center' }}>
                    <div className="cart-line__thumb">
                      <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    </div>
                    <div className="cart-line__body">
                      <div className="cart-line__title">{p.name}</div>
                    </div>
                    <div>{HAP.formatPrice(p.price)}</div>
                  </a>
                ))}
              </div>
            )}
          </div>
        ) : (
          <>
            <div style={{ fontSize: '.78rem', color: 'var(--muted)', marginBottom: 12 }}>{results.length} match{results.length > 1 ? 'es' : ''} for “{q}”</div>
            {results.map(p => (
              <a key={p.id} href={'#/products/' + p.slug} onClick={onResultClick} className="cart-line" style={{ alignItems: 'center' }}>
                <div className="cart-line__thumb">
                  <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
                <div className="cart-line__body">
                  <div className="cart-line__title">{p.name}</div>
                  <div className="cart-line__variant">{p.latin || p.type}</div>
                </div>
                <div>{HAP.formatPrice(p.price)}</div>
              </a>
            ))}
            <a href={'#/search?q=' + encodeURIComponent(q)} onClick={() => store.closeDrawer()}
               className="btn btn--secondary btn--full" style={{ marginTop: 12 }}>
              See all results
            </a>
          </>
        )}
      </div>
    </div>
  );
}

function MobileMenuDrawer() {
  const store = useStore();
  const trapRef = useFocusTrap(true);
  const [open, setOpen] = React.useState({});
  const toggle = (s) => setOpen(p => ({ ...p, [s]: !p[s] }));
  return (
    <div ref={trapRef} className="drawer" role="dialog" aria-modal="true" aria-label="Navigation menu" style={{ left: 0, right: 'auto', boxShadow: '20px 0 60px rgba(0,0,0,0.18)', width: 'min(360px, 92vw)' }}
         onClick={(e) => e.stopPropagation()}>
      <div className="drawer__head">
        <span className="drawer__title">Menu</span>
        <button className="icon-btn" onClick={() => store.closeDrawer()} aria-label="Close"><Icon name="close" /></button>
      </div>
      <div className="drawer__body" style={{ padding: 0 }}>
        {HAP.CATEGORIES.map(top => (
          <div key={top.slug} style={{ borderBottom: '1px solid var(--line)' }}>
            <button onClick={() => toggle(top.slug)}
                    style={{ width: '100%', padding: '18px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '.95rem' }}>
              <span>{top.name}</span>
              <Icon name={open[top.slug] ? 'chev-up' : 'chev-down'} size={16} />
            </button>
            {open[top.slug] && (
              <div style={{ paddingBlock: 4, paddingInline: 20, paddingBottom: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <a href={'#/collections/' + top.slug} onClick={() => store.closeDrawer()} style={{ padding: '8px 0', fontSize: '.88rem', color: 'var(--forest)' }}>All {top.name.toLowerCase()} →</a>
                {(top.sub || []).map(s => (
                  <a key={s.slug} href={'#/collections/' + s.slug} onClick={() => store.closeDrawer()}
                     style={{ padding: '8px 0', fontSize: '.88rem', color: 'var(--ink-2)' }}>{s.name}</a>
                ))}
              </div>
            )}
          </div>
        ))}
        <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <a href="#/services" onClick={() => store.closeDrawer()} style={{ padding: '10px 0' }}>Services</a>
          <a href="#/pages/about" onClick={() => store.closeDrawer()} style={{ padding: '10px 0' }}>About</a>
          <a href="#/pages/contact" onClick={() => store.closeDrawer()} style={{ padding: '10px 0' }}>Contact</a>
          <a href="#/account" onClick={() => store.closeDrawer()} style={{ padding: '10px 0' }}>Account</a>
        </div>
      </div>
    </div>
  );
}

function EmptyState({ icon, title, note, cta, onCta }) {
  return (
    <div style={{ padding: '48px 20px', textAlign: 'center' }}>
      <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--cream)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--moss)', marginBottom: 14 }}>
        <Icon name={icon} size={24} />
      </div>
      <h3 className="serif" style={{ fontSize: '1.4rem', marginBottom: 6 }}>{title}</h3>
      <p style={{ color: 'var(--muted)', maxWidth: 280, margin: '0 auto 18px' }}>{note}</p>
      {cta && <a href={cta.href} onClick={onCta} className="btn btn--primary">{cta.label}</a>}
    </div>
  );
}

function RecentlyViewedStrip() {
  const store = useStore();
  const items = store.recentProducts();
  if (items.length === 0) return null;
  return (
    <div style={{ marginTop: 28 }}>
      <h4 style={{ fontSize: '.72rem', letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--moss)', marginBottom: 12 }}>Recently viewed</h4>
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 8 }}>
        {items.slice(0, 6).map(p => (
          <a key={p.id} href={'#/products/' + p.slug} onClick={() => store.closeDrawer()}
             style={{ minWidth: 96, flexShrink: 0 }}>
            <div style={{ aspectRatio: '4/5', borderRadius: 8, overflow: 'hidden', background: 'var(--cream)' }}>
              <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
            <div style={{ fontSize: '.74rem', marginTop: 6, color: 'var(--ink-2)' }}>{HAP.formatPrice(p.price)}</div>
          </a>
        ))}
      </div>
    </div>
  );
}

function QuickViewModal() {
  const store = useStore();
  const trapRef = useFocusTrap(true);
  const m = store.state.modal;
  const p = m && m.kind === 'quickview'
    ? HAP.PRODUCTS.find(x => x.id === m.productId)
    : null;
  const [variant, setVariant] = React.useState(() => (p && p.variants && p.variants[0]) || '1 kg');
  const [qty, setQty] = React.useState(1);

  React.useEffect(() => {
    if (p && p.variants && p.variants[0]) setVariant(p.variants[0]);
    setQty(1);
  }, [p && p.id]);

  if (!m || m.kind !== 'quickview' || !p) return null;

  return (
    <div className="modal" onClick={() => store.closeModal()}>
      <div ref={trapRef} className="modal__inner" role="dialog" aria-modal="true" aria-label={'Quick view: ' + p.name} onClick={(e) => e.stopPropagation()}>
        <button className="modal__close" onClick={() => store.closeModal()} aria-label="Close"><Icon name="close" /></button>
        <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', minHeight: 480 }} className="quick-view-grid">
          <div style={{ background: 'var(--cream)', minHeight: 420 }}>
            <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          </div>
          <div style={{ padding: 'clamp(24px, 3vw, 40px)', display: 'flex', flexDirection: 'column', gap: 14, overflowY: 'auto' }}>
            <div className="eyebrow">{p.vendor} · {p.type}</div>
            <h2 className="serif" style={{ fontSize: '1.8rem', lineHeight: 1.1 }}>{p.name}</h2>
            {p.latin && <div style={{ fontStyle: 'italic', color: 'var(--muted)' }}>{p.latin}</div>}
            <Rating value={p.rating} count={p.ratingCount} />
            <PriceTag p={p} big />
            <p style={{ color: 'var(--ink-2)', fontSize: '.92rem' }}>{p.blurb}</p>

            <div>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Size</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {p.variants.map(v => (
                  <button key={v}
                    onClick={() => setVariant(v)}
                    className={'tag' + (variant === v ? '' : ' tag--soft')}
                    style={{
                      background: variant === v ? 'var(--forest)' : 'var(--cream)',
                      color: variant === v ? 'var(--paper)' : 'var(--ink)',
                      border: 'none', padding: '8px 14px', cursor: 'pointer'
                    }}>{v}</button>
                ))}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <div className="cart-line__qty" style={{ height: 44 }}>
                <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 38, height: 44 }} aria-label="Decrease quantity"><Icon name="minus" size={14}/></button>
                <span className="count" style={{ width: 38 }}>{qty}</span>
                <button onClick={() => setQty(q => q + 1)} style={{ width: 38, height: 44 }} aria-label="Increase quantity"><Icon name="plus" size={14}/></button>
              </div>
              <button className="btn btn--primary" style={{ flex: 1 }} onClick={() => {
                store.addToCart(p.id, variant, qty);
                store.markViewed(p.id);
                store.closeModal();
              }}>Add to bag · {HAP.formatPrice(p.price * qty)}</button>
            </div>
            <a href={'#/products/' + p.slug} onClick={() => store.closeModal()}
               style={{ fontSize: '.85rem', color: 'var(--forest)', textDecoration: 'underline', textUnderlineOffset: 4 }}>
              View full details →
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

function Notif() {
  const store = useStore();
  const n = store.state.notif;
  if (!n) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      zIndex: 300, background: 'var(--ink)', color: 'var(--paper)',
      padding: '12px 20px', borderRadius: 999, boxShadow: '0 12px 40px rgba(0,0,0,0.18)',
      display: 'flex', alignItems: 'center', gap: 10, fontSize: '.88rem',
      animation: 'pop 240ms cubic-bezier(.2,.7,.2,1)'
    }}>
      <span style={{ width: 18, height: 18, borderRadius: 999, background: 'var(--success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name="check" size={12} />
      </span>
      {n.msg}
    </div>
  );
}

function NewsletterPopup() {
  const store = useStore();
  const [show, setShow] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const trapRef = useFocusTrap(show);
  React.useEffect(() => {
    if (!HAPStore.shouldShowNewsletter()) return;
    const t = setTimeout(() => setShow(true), 6000);
    return () => clearTimeout(t);
  }, []);
  if (!show) return null;
  const close = () => { setShow(false); HAPStore.dismissNewsletter(); };
  const subscribe = () => {
    const res = window.CustomerForms && window.CustomerForms.subscribeNewsletter
      ? window.CustomerForms.subscribeNewsletter(email, 'popup')
      : { ok: false, message: 'Newsletter unavailable' };
    if (!res.ok) {
      HAPStore.notify(res.message || 'Check your email');
      return;
    }
    HAPStore.notify(res.message || 'Thanks — you are on the list');
    close();
  };
  return (
    <div className="modal" onClick={close}>
      <div ref={trapRef} className="modal__inner" role="dialog" aria-modal="true" aria-label="Newsletter signup" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 740 }}>
        <button className="modal__close" onClick={close} aria-label="Close"><Icon name="close" /></button>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', minHeight: 440 }} className="newsletter-grid">
          <div style={{ background: 'var(--forest)', color: 'var(--paper)', padding: 36, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <span className="eyebrow" style={{ color: 'var(--sage)' }}>Welcome offer</span>
            <h2 className="serif" style={{ fontSize: '2.4rem', lineHeight: 1.05, marginTop: 6 }}>New colours,<br/>first notice.</h2>
            <p style={{ color: 'rgba(255,255,255,0.7)', marginTop: 12, fontSize: '.9rem' }}>Subscribe for arrival notes. Coupons are not invented here — we only store your email locally until an ESP is connected.</p>
          </div>
          <div style={{ padding: 36, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 14 }}>
            <label htmlFor="newsletter-popup-email" className="eyebrow">Email</label>
            <input id="newsletter-popup-email" className="input input--lg" type="email" placeholder="Your email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} />
            <button className="btn btn--primary" onClick={subscribe}>Subscribe</button>
            <button className="btn btn--ghost btn--sm" onClick={close}>No thanks</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.CartDrawer = CartDrawer;
window.WishlistDrawer = WishlistDrawer;
window.SearchDrawer = SearchDrawer;
window.MobileMenuDrawer = MobileMenuDrawer;
window.QuickViewModal = QuickViewModal;
window.NewsletterPopup = NewsletterPopup;
window.Notif = Notif;
window.EmptyState = EmptyState;
window.RecentlyViewedStrip = RecentlyViewedStrip;
window.RinpoDrawer = RinpoDrawer;

function RinpoDrawer() {
  const store = useStore();
  React.useEffect(() => {
    store.closeDrawer();
    if (window.RinpoRuntime) {
      window.RinpoRuntime.open({ tab: 'chat', source: 'legacy_drawer', surface: 'store' });
    }
  }, []);
  return null;
}
