// Drawer: cart, search, wishlist (single right-side drawer with mode switching)

const { useState: useStateD, useEffect: useEffectD, useMemo: useMemoD, useRef: useRefD } = React;

function Drawer({ mode, onClose, cart, setCart, wish, onWish, openProduct }) {
  const open = mode != null;
  // lock body scroll
  useEffectD(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  return (
    <>
      <div className={`drawer-scrim ${open ? 'on':''}`} onClick={onClose}/>
      <aside className={`drawer ${open ? 'on':''}`} role="dialog" aria-modal="true">
        <div className="drawer-head">
          <div className="eyebrow" style={{color:'var(--fg)'}}>
            {mode === 'cart' && `Bag — ${cart.length} ${cart.length === 1 ? 'item':'items'}`}
            {mode === 'search' && 'Search'}
            {mode === 'wish' && `Wishlist — ${wish.size} saved`}
          </div>
          <button className="nav-icon" onClick={onClose}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            <Icon.close/>
          </button>
        </div>

        {mode === 'cart' && <CartView cart={cart} setCart={setCart} onClose={onClose} openProduct={openProduct}/>}
        {mode === 'search' && <SearchView openProduct={openProduct} onClose={onClose}/>}
        {mode === 'wish' && <WishView wish={wish} onWish={onWish} openProduct={openProduct} onClose={onClose}/>}
      </aside>
    </>
  );
}

// ───────────────────────── cart ─────────────────────────
function CartView({ cart, setCart, onClose, openProduct }) {
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);
  const freeAt = 120;
  const remaining = Math.max(0, freeAt - subtotal);
  const progress = Math.min(1, subtotal / freeAt);

  if (cart.length === 0) {
    return (
      <>
        <div className="drawer-body">
          <div className="empty-cart">
            <div style={{ fontSize:48, color:'var(--fg-dim)' }}>
              <Icon.bag width={48} height={48}/>
            </div>
            <h3 className="h-2">Your bag is empty</h3>
            <p>Browse the Volume 02 capsule or our archive of essentials below.</p>
            <button className="btn-primary" onClick={onClose} style={{maxWidth:240, marginTop:16}}
                    onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
              Start browsing <Icon.arrow/>
            </button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <div style={{padding:'14px 24px 0'}}>
        <div className="label-mono" style={{fontSize:11, marginBottom:8}}>
          {remaining > 0 ? `€${remaining.toFixed(0)} away from free worldwide shipping` : 'Free worldwide shipping unlocked ✓'}
        </div>
        <div style={{height:2, background:'var(--bg-elev-2)', position:'relative', overflow:'hidden'}}>
          <div style={{position:'absolute', inset:0, width:`${progress*100}%`, background:'var(--accent)', transition:'width 400ms cubic-bezier(.2,.6,.2,1)'}}/>
        </div>
      </div>

      <div className="drawer-body">
        {cart.map((line) => (
          <div className="cart-item" key={line.key}>
            <div className="cart-thumb">
              <div style={{width:'80%', height:'80%', color: line.color.hex === '#0a0908' ? 'var(--fg)':'var(--bg)'}}>
                <Garment kind={line.silhouette} color={line.color.hex} graphic={false}/>
              </div>
            </div>
            <div className="cart-info">
              <div className="nm">{line.name}</div>
              <div className="vr">{line.type}</div>
              <div className="vr">{line.color.name} · Size {line.size}</div>
              <div className="qty" style={{marginTop:10}}>
                <button onClick={() => updateQty(line.key, -1, cart, setCart)}
                        onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
                  <Icon.minus/>
                </button>
                <span className="v">{line.qty}</span>
                <button onClick={() => updateQty(line.key, 1, cart, setCart)}
                        onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
                  <Icon.plus/>
                </button>
              </div>
            </div>
            <div className="cart-right">
              <span className="num">€{(line.price * line.qty).toFixed(0)}</span>
              <button className="x-btn" onClick={() => setCart(cart.filter(c => c.key !== line.key))}
                      onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>Remove</button>
            </div>
          </div>
        ))}
      </div>

      <div className="drawer-foot">
        <div className="subtotal">
          <div>
            <div className="l">Subtotal</div>
            <div className="label-mono" style={{fontSize:10, color:'var(--fg-dim)', marginTop:2}}>Tax & shipping at checkout</div>
          </div>
          <div className="r num">€{subtotal.toFixed(0)}</div>
        </div>
        <button className="btn-primary"
                onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          Checkout via Fourthwall <Icon.arrow/>
        </button>
        <button className="btn-secondary" onClick={onClose}
                onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          Continue shopping
        </button>
      </div>
    </>
  );
}

function updateQty(key, delta, cart, setCart) {
  setCart(cart.map(c => c.key === key ? { ...c, qty: Math.max(1, c.qty + delta) } : c));
}

// ───────────────────────── search ─────────────────────────
function SearchView({ openProduct, onClose }) {
  const [q, setQ] = useStateD('');
  const inputRef = useRefD();
  useEffectD(() => { setTimeout(() => inputRef.current?.focus(), 200); }, []);

  const results = useMemoD(() => {
    if (!q.trim()) return [];
    const lc = q.toLowerCase();
    return PRODUCTS.filter(p =>
      p.name.toLowerCase().includes(lc) ||
      p.type.toLowerCase().includes(lc) ||
      p.category.includes(lc) ||
      (p.collection || '').toLowerCase().includes(lc) ||
      p.description.toLowerCase().includes(lc)
    );
  }, [q]);

  return (
    <>
      <div className="search-bar">
        <Icon.search width={24} height={24}/>
        <input ref={inputRef} placeholder="Search the catalogue…" value={q} onChange={e=>setQ(e.target.value)}
               onFocus={()=>onCursor('text')} onBlur={()=>onCursor('default')}/>
        {q && <button onClick={()=>setQ('')} className="label-mono">Clear</button>}
      </div>
      <div className="drawer-body" style={{padding:0}}>
        {!q && (
          <div className="search-hint">
            <h5>Popular searches</h5>
            <ul>
              {['Volume 02', 'Hoodies', 'Tees', 'Wax Crate', 'Cap', 'Cream'].map(s => (
                <li key={s}><a onClick={() => setQ(s)}
                              onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>{s}</a></li>
              ))}
            </ul>
            <h5 style={{marginTop:24}}>Recently popular</h5>
            <div className="search-results">
              {PRODUCTS.slice(0, 4).map(p => (
                <SearchResult key={p.id} p={p} onClick={() => { openProduct(p); onClose(); }}/>
              ))}
            </div>
          </div>
        )}
        {q && results.length > 0 && (
          <div className="search-results">
            <div className="label-mono" style={{padding:'12px 24px 6px', color:'var(--fg-dim)'}}>
              {results.length} {results.length === 1 ? 'result':'results'}
            </div>
            {results.map(p => (
              <SearchResult key={p.id} p={p} onClick={() => { openProduct(p); onClose(); }}/>
            ))}
          </div>
        )}
        {q && results.length === 0 && (
          <div className="search-hint">
            <p style={{color:'var(--fg-mute)'}}>No matches for <em style={{color:'var(--fg)'}}>"{q}"</em>.</p>
            <p style={{color:'var(--fg-dim)', fontSize:13, marginTop:8}}>Try a category like "tees" or a collection name like "Volume 02".</p>
          </div>
        )}
      </div>
    </>
  );
}

function SearchResult({ p, onClick }) {
  return (
    <a className="search-result" onClick={onClick}
       onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
      <div className="thumb">
        <div style={{width:'82%', height:'82%', color: p.colors[0].hex === '#0a0908' ? 'var(--fg)':'var(--bg)'}}>
          <Garment kind={p.silhouette} color={p.colors[0].hex} graphic={false}/>
        </div>
      </div>
      <div>
        <div className="nm">{p.name}</div>
        <div className="label-mono" style={{fontSize:11, marginTop:2}}>{p.type}</div>
      </div>
      <div className="pr">€{p.price}</div>
    </a>
  );
}

// ───────────────────────── wish ─────────────────────────
function WishView({ wish, onWish, openProduct, onClose }) {
  const items = Array.from(wish).map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean);
  if (items.length === 0) {
    return (
      <div className="drawer-body">
        <div className="empty-cart">
          <div style={{ fontSize:48, color:'var(--fg-dim)' }}>
            <Icon.heart width={48} height={48}/>
          </div>
          <h3 className="h-2">No saves yet</h3>
          <p>Tap the heart on any piece to save it for later.</p>
        </div>
      </div>
    );
  }
  return (
    <div className="drawer-body" style={{padding:'0 0 24px'}}>
      {items.map(p => (
        <div key={p.id} style={{display:'grid', gridTemplateColumns:'80px 1fr auto', gap:16, padding:'18px 24px', borderBottom:'1px solid var(--line)', alignItems:'center'}}
             onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          <div className="cart-thumb" onClick={() => { openProduct(p); onClose(); }}>
            <div style={{width:'80%', height:'80%', color: p.colors[0].hex === '#0a0908' ? 'var(--fg)':'var(--bg)'}}>
              <Garment kind={p.silhouette} color={p.colors[0].hex} graphic={false}/>
            </div>
          </div>
          <div className="cart-info" onClick={() => { openProduct(p); onClose(); }}>
            <div className="nm">{p.name}</div>
            <div className="vr">{p.type}</div>
            <div className="vr num" style={{marginTop:6, color:'var(--fg)'}}>€{p.price}</div>
          </div>
          <button className="x-btn" onClick={() => onWish(p.id)}>Remove</button>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Drawer });
