// Drawer: cart, search, wishlist — right-side panel with scrim

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

function Drawer({ mode, onClose, cart, setCart, wish, onWish, openProduct, navigate }) {
  const open = mode != null;
  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'   && `Crate — ${(cart||[]).reduce((s,l)=>s+l.qty,0)} ${(cart||[]).reduce((s,l)=>s+l.qty,0) === 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} navigate={navigate} 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, navigate, openProduct }) {
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);

  const [checkingOut, setCheckingOut] = useStateD(false);
  const [confirmingDelete, setConfirmingDelete] = useStateD(null);

  const handleCheckout = async () => {
    if (checkingOut) return;
    const itemObjs = cart.map(l => {
      const vid = l.shirtColor?.variants?.[l.size];
      return vid ? { variantId: vid, qty: l.qty } : null;
    }).filter(Boolean);
    if (!itemObjs.length) return;
    setCheckingOut(true);
    const currency = window.shopCurrency || 'USD';
    try {
      const res = await fetch('/api/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: itemObjs, currency }),
      });
      if (!res.ok) throw new Error('api error');
      const { checkoutUrl, session } = await res.json();
      localStorage.setItem('pvl-checkout-session', session);
      onClose();
      window.location.href = checkoutUrl;
    } catch {
      // Fallback: direct products URL
      const products = itemObjs.map(i => `${i.variantId}:${i.qty}`).join(',');
      const session = Date.now().toString(36) + Math.random().toString(36).slice(2);
      localStorage.setItem('pvl-checkout-session', session);
      onClose();
      window.location.href = `https://checkout.peripheralvinyl.com/cart/checkout?products=${products}&currency=${currency}&utm_content=${session}`;
    }
  };

  const updateQty = (key, delta) => {
    setCart(prev => prev
      .map(l => l.key === key ? { ...l, qty: Math.max(0, l.qty + delta) } : l)
      .filter(l => l.qty > 0)
    );
  };

  if (cart.length === 0) {
    return (
      <div className="drawer-body">
        <div className="empty-cart">
          <Icon.cart width={48} height={48} style={{color:'var(--fg-dim)'}}/>
          <h3 className="h-2">Your crate is empty</h3>
          <p>Browse the collection and add something you love.</p>
          <button className="btn-primary" onClick={() => { navigate({name:'collection', id:'all'}, '/merch/collection/all'); onClose(); }} style={{maxWidth:220, marginTop:16}}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            Keep digging <Icon.arrow/>
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="drawer-body">
        {[...cart].reverse().map(line => {
          const img = line.shirtColor?.images?.[0] || line.colorway?.images?.[0];
          const product = (window.PRODUCTS || []).find(p => p.id === line.id);
          const goToProduct = () => { if (product) { onClose(); openProduct(product); } };
          return (
            <div className="cart-item" key={line.key} style={{position:'relative', overflow:'visible'}}>
              {confirmingDelete === line.key && (
                <div style={{
                  position:'absolute', inset:'0 -12px', zIndex:10, borderRadius:8,
                  background:'color-mix(in oklab, var(--bg-elev) 88%, transparent)',
                  backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)',
                  display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:14,
                }} onClick={() => setConfirmingDelete(null)}>
                  <span style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--fg)'}}>
                    {line.qty > 1 ? `Remove ${line.qty} items?` : 'Remove item?'}
                  </span>
                  <div style={{display:'flex', gap:10}} onClick={e => e.stopPropagation()}>
                    <button onClick={() => { setCart(prev => prev.filter(l => l.key !== line.key)); setConfirmingDelete(null); }}
                            onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}
                            className="btn-primary" style={{padding:'8px 18px', fontSize:11, letterSpacing:'0.1em', background:'#c0392b', borderColor:'#c0392b'}}>
                      Remove
                    </button>
                    <button onClick={() => setConfirmingDelete(null)}
                            onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}
                            className="btn-secondary" style={{padding:'8px 18px', fontSize:11, letterSpacing:'0.1em'}}>
                      Cancel
                    </button>
                  </div>
                </div>
              )}
              <CartThumb line={line} img={img} onClick={goToProduct}/>
              <div className="cart-info" onClick={goToProduct} style={{cursor:'none',flex:1}}>
                <div className="nm">{line.name}</div>
                <div className="vr">{line.colorway?.name} · {line.variantType === 'embroidered' ? 'Embroidered' : 'Print'}{line.shirtColor?.name ? ` · ${line.shirtColor.name}` : ''}</div>
                <div className="vr">Size: {line.size}</div>
                <div style={{display:'flex', alignItems:'center', gap:10, marginTop:10}} onClick={e => e.stopPropagation()}>
                  <div className="qty">
                    <button onClick={() => updateQty(line.key, -1)}
                            onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
                      <Icon.minus/>
                    </button>
                    <span className="v">{line.qty}</span>
                    <button onClick={() => updateQty(line.key, 1)}
                            onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
                      <Icon.plus/>
                    </button>
                  </div>
                  <button onClick={() => setConfirmingDelete(line.key)}
                          onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}
                          className="x-btn" style={{display:'grid', placeItems:'center'}}>
                    <Icon.trash width={15} height={15}/>
                  </button>
                </div>
              </div>
              <div className="cart-right" onClick={goToProduct} style={{cursor:'none'}}>
                <span className="num">{window.fmt ? window.fmt(line.price * line.qty) : `€${line.price * line.qty}`}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="drawer-foot">
        <div className="subtotal" style={{marginBottom:8}}>
          <div style={{display:'flex', flexDirection:'column', gap:4}}>
            <div className="l">Subtotal</div>
            <div className="label-mono" style={{fontSize:10, color:'var(--fg-dim)'}}>Tax & shipping calculated at checkout</div>
            {localStorage.getItem('pvl-currency') === 'EUR' && (
              <div className="label-mono" style={{fontSize:10, color:'var(--fg-dim)'}}>Free shipping on EU orders over €100</div>
            )}
          </div>
          <div className="r num">{window.fmt ? window.fmt(subtotal) : `€${subtotal}`}</div>
        </div>
        <button className="btn-primary" onClick={handleCheckout} disabled={checkingOut}
                onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          {checkingOut ? 'One moment…' : <span>Proceed to checkout <Icon.arrow/></span>}
        </button>
        <button className="btn-secondary" onClick={() => { navigate({name:'cart'}, '/merch/cart'); onClose(); }}
                onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          View crate
        </button>
      </div>
    </>
  );
}

// ───────────────────────── 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 (window.PRODUCTS || []).filter(p =>
      (p.name || '').toLowerCase().includes(lc) ||
      (p.type || '').toLowerCase().includes(lc) ||
      (p.category || '').toString().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 collection…" value={q} onChange={e=>setQ(e.target.value)}
               onMouseEnter={()=>onCursor('text')}
               onFocus={()=>onCursor('text')}
               onMouseLeave={()=>onCursor('default')}
               onBlur={()=>onCursor('default')}/>
        {q && <button onClick={()=>setQ('')} className="label-mono search-bar-clear">Clear</button>}
      </div>
      <div className="drawer-body" style={{padding:0}}>
        {!q && (
          <div className="search-hint">
            <h5>Popular searches</h5>
            <ul>
              {['Hoodies', 'Tees', 'Tote', 'Embroidered'].map(s => (
                <li key={s}><a onClick={() => setQ(s)}
                              onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>{s}</a></li>
              ))}
            </ul>
            <h5 style={{marginTop:24}}>All products</h5>
            <div className="search-results">
              {(window.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>
          </div>
        )}
      </div>
    </>
  );
}

function SearchResult({ p, onClick }) {
  const firstCw = p.printed?.[0] || p.embroidered?.[0];
  const img = firstCw?.shirtColors?.[0]?.images?.[0] || firstCw?.images?.[0];
  return (
    <a className="search-result" onClick={onClick}
       onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
      <div className="thumb" style={{background: 'var(--bg-elev-2)'}}>
        {img
          ? <img src={img} alt={p.name} style={{width:'100%',height:'100%',objectFit:'contain',padding:4}}/>
          : <div style={{width:'80%',height:'80%'}}><Garment kind={p.silhouette} color={firstCw?.hex||'#888'}/></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">{window.fmt ? window.fmt(firstCw?.price || p.price) : `€${p.price}`}</div>
    </a>
  );
}

// ───────────────────────── wish ─────────────────────────
function WishView({ wish, onWish, openProduct, onClose }) {
  const items = Array.from(wish).map(id => (window.PRODUCTS||[]).find(p => p.id === id)).filter(Boolean);
  if (items.length === 0) {
    return (
      <div className="drawer-body">
        <div className="empty-cart">
          <Icon.heart width={48} height={48} style={{color:'var(--fg-dim)'}}/>
          <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 => {
        const firstCw = p.printed?.[0] || p.embroidered?.[0];
        const img = firstCw?.shirtColors?.[0]?.images?.[0] || firstCw?.images?.[0];
        return (
          <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(); }}>
              {img
                ? <img src={img} alt={p.name} style={{width:'100%',height:'100%',objectFit:'contain',padding:4}}/>
                : <div style={{width:'80%',height:'80%'}}><Garment kind={p.silhouette} color={firstCw?.hex||'#888'}/></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)'}}>
                {window.fmt ? window.fmt(firstCw?.price || p.price) : `€${p.price}`}
              </div>
            </div>
            <button className="x-btn" onClick={() => onWish(p.id)}
                    onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
              Remove
            </button>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Drawer });
