// D_full_collection.jsx — Direction D · Collection + PDP

// ── Constants ─────────────────────────────────────────────────────────────
const D_COLLECTION_EVENTS = [
  { id:'dam-cuoi',     label:'Đám cưới' },
  { id:'le-hoi',       label:'Lễ hỏi' },
  { id:'da-tiec',      label:'Dạ tiệc' },
  { id:'tot-nghiep',   label:'Tốt nghiệp' },
  { id:'phong-van',    label:'Phỏng vấn' },
  { id:'gala',         label:'Gala' },
  { id:'tiec-cong-ty', label:'Tiệc công ty' },
  { id:'ky-niem',      label:'Kỷ niệm' },
];

const D_PRICE_RANGES = [
  { id:'under2m', label:'Dưới 2M', fn: p => p < 2000000 },
  { id:'2m-3m',   label:'2M–3M',   fn: p => p >= 2000000 && p <= 3000000 },
  { id:'over3m',  label:'Trên 3M', fn: p => p > 3000000 },
];

const D_SORT_OPTIONS = [
  { id:'recommended', label:'Đề xuất' },
  { id:'newest',      label:'Mới nhất' },
  { id:'price-asc',   label:'Giá thấp→cao' },
  { id:'price-desc',  label:'Giá cao→thấp' },
  { id:'name-az',     label:'Tên A→Z' },
];

const D_PER_PAGE = 9;

// ── Wishlist helpers ──────────────────────────────────────────────────────
function getWishlist() {
  try { return JSON.parse(localStorage.getItem('f2f-wishlist') || '[]'); } catch { return []; }
}
function toggleWishlistItem(id) {
  const wl = getWishlist();
  const next = wl.includes(id) ? wl.filter(x => x !== id) : [...wl, id];
  try { localStorage.setItem('f2f-wishlist', JSON.stringify(next)); } catch {}
  return next;
}

// ── GarmentCard ───────────────────────────────────────────────────────────
function GarmentCard({ g, go, onQuickView }) {
  const [hov, setHov] = React.useState(false);
  const [wishlisted, setWishlisted] = React.useState(() => getWishlist().includes(g.id));
  const imgs = g.images && g.images.length ? g.images : [g.img];

  const handleWishlist = (e) => {
    e.stopPropagation();
    const next = toggleWishlistItem(g.id);
    setWishlisted(next.includes(g.id));
  };

  const handleQV = (e) => {
    e.stopPropagation();
    onQuickView(g);
  };

  return (
    <div
      onClick={() => go('pdp', { id: g.id })}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{ cursor:'pointer', overflow:'hidden', position:'relative' }}
    >
      <div style={{ aspectRatio:'4/5', overflow:'hidden', position:'relative' }}>

        {/* Primary image */}
        <div style={{
          position:'absolute', inset:0,
          backgroundImage:`url('${imgs[0]}')`,
          backgroundSize:'cover', backgroundPosition:'center top',
          filter: D.imgCard,
          transform: hov && !imgs[1] ? 'scale(1.025)' : 'scale(1)',
          opacity: hov && imgs[1] ? 0 : 1,
          transition:'transform .5s cubic-bezier(.4,0,.2,1), opacity .32s ease',
        }}/>

        {/* Hover image crossfade */}
        {imgs[1] && (
          <div style={{
            position:'absolute', inset:0,
            backgroundImage:`url('${imgs[1]}')`,
            backgroundSize:'cover', backgroundPosition:'center top',
            filter: D.imgCard,
            opacity: hov ? 1 : 0,
            transition:'opacity .32s ease',
          }}/>
        )}

        {/* Darken overlay */}
        <div style={{
          position:'absolute', inset:0,
          background:'rgba(14,10,8,.15)',
          opacity: hov ? 1 : 0,
          transition:'opacity .3s', pointerEvents:'none',
        }}/>

        {/* Bottom gradient */}
        <div style={{
          position:'absolute', bottom:0, left:0, right:0, height:'56%',
          background:'linear-gradient(to top, rgba(14,10,8,.78) 0%, transparent 100%)',
          pointerEvents:'none',
        }}/>

        {/* Badge top-left */}
        {g.badge && (
          <div style={{
            position:'absolute', top:14, left:14,
            fontFamily: g.badge === 'CÒN 2 BỘ' ? D.serif : D.sans,
            fontStyle: g.badge === 'CÒN 2 BỘ' ? 'italic' : 'normal',
            fontSize: g.badge === 'CÒN 2 BỘ' ? 12 : 8,
            fontWeight: g.badge === 'CÒN 2 BỘ' ? 400 : 700,
            letterSpacing: g.badge === 'CÒN 2 BỘ' ? '.02em' : '.24em',
            textTransform: g.badge === 'CÒN 2 BỘ' ? 'none' : 'uppercase',
            color: g.badge === 'CÒN 2 BỘ' ? 'rgba(255,210,185,.92)' : D.gold,
          }}>
            {g.badge}
          </div>
        )}

        {/* Availability */}
        <div style={{
          position:'absolute', top: g.badge ? 34 : 14, left:14,
          fontFamily:D.serif, fontStyle:'italic', fontSize:11,
          color:'rgba(255,210,185,.72)',
        }}>
          Còn · {g.next}
        </div>

        {/* Wishlist heart top-right */}
        <div onClick={handleWishlist} style={{
          position:'absolute', top:12, right:12, width:32, height:32,
          display:'flex', alignItems:'center', justifyContent:'center',
          background:'rgba(14,10,8,.25)', backdropFilter:'blur(6px)',
          cursor:'pointer',
          opacity: hov || wishlisted ? 1 : 0,
          transition:'opacity .25s',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24"
            fill={wishlisted ? D.bord : 'none'}
            stroke={wishlisted ? D.bord : 'rgba(255,255,255,.85)'}
            strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
          </svg>
        </div>

        {/* Size chips on hover */}
        <div style={{
          position:'absolute', bottom:60, left:14, right:40,
          display:'flex', gap:5,
          opacity: hov ? 1 : 0,
          transform: hov ? 'translateY(0)' : 'translateY(5px)',
          transition:'opacity .22s, transform .22s',
        }}>
          {(g.sizes || []).slice(0,4).map(sz => (
            <div key={sz} onClick={e => e.stopPropagation()} style={{
              fontFamily:D.sans, fontSize:8, fontWeight:700, letterSpacing:'.18em', textTransform:'uppercase',
              padding:'3px 6px',
              background:'rgba(255,255,255,.13)', color:'rgba(255,255,255,.82)',
              border:'1px solid rgba(255,255,255,.2)',
            }}>{sz}</div>
          ))}
        </div>

        {/* Bottom text */}
        <div style={{ position:'absolute', bottom:14, left:15, right:15, color:'#fff' }}>
          <div style={{ fontFamily:D.serif, fontWeight:300, fontSize:25, lineHeight:1.05, letterSpacing:'-.015em' }}>
            {g.name}
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginTop:5 }}>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:11, color:'rgba(255,255,255,.62)' }}>
              {g.mill}
            </div>
            <div style={{ fontFamily:"'JetBrains Mono','IBM Plex Mono',monospace", fontSize:11, color:'rgba(255,255,255,.8)' }}>
              {formatVND(g.price)}<span style={{ fontSize:9, opacity:.55 }}> /{g.days}N</span>
            </div>
          </div>
        </div>

        {/* Quick-view eye button hover */}
        <div onClick={handleQV} style={{
          position:'absolute', bottom:14, right:14,
          width:30, height:30, borderRadius:'50%',
          background:'rgba(255,255,255,.14)', backdropFilter:'blur(6px)',
          display:'flex', alignItems:'center', justifyContent:'center',
          border:'1px solid rgba(255,255,255,.25)', cursor:'pointer',
          opacity: hov ? 1 : 0,
          transform: hov ? 'scale(1)' : 'scale(.75)',
          transition:'opacity .22s, transform .22s',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
            stroke="rgba(255,255,255,.88)" strokeWidth="2" strokeLinecap="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
            <circle cx="12" cy="12" r="3"/>
          </svg>
        </div>

      </div>
    </div>
  );
}

// ── Quick-view modal ───────────────────────────────────────────────────────
function DQuickView({ g, go, onClose }) {
  const [imgIdx, setImgIdx] = React.useState(0);
  const [size, setSize]     = React.useState(null);
  const [wishlisted, setWishlisted] = React.useState(() => getWishlist().includes(g.id));
  const imgs = g.images && g.images.length ? g.images : [g.img];

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.documentElement.style.overflowY = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.documentElement.style.overflowY = '';
    };
  }, [onClose]);

  const handleWishlist = () => {
    const next = toggleWishlistItem(g.id);
    setWishlisted(next.includes(g.id));
  };

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:200,
      background:'rgba(14,10,8,.65)',
      display:'flex', alignItems:'center', justifyContent:'center', padding:24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background:D.paper, width:'min(860px, 92vw)', maxHeight:'90vh',
        display:'grid', gridTemplateColumns:'1fr 1fr',
        overflow:'hidden', position:'relative',
      }}>
        {/* Close */}
        <div onClick={onClose} style={{
          position:'absolute', top:12, right:12, zIndex:10,
          width:34, height:34, display:'flex', alignItems:'center', justifyContent:'center',
          border:`1px solid ${D.line}`, cursor:'pointer', background:D.paper,
          fontFamily:D.sans, fontSize:18, color:D.stone,
        }}>×</div>

        {/* Images */}
        <div style={{ background:'#EAE4DA', display:'flex', flexDirection:'column' }}>
          <div style={{
            flex:1, backgroundImage:`url('${imgs[imgIdx]}')`,
            backgroundSize:'cover', backgroundPosition:'center top',
            minHeight:280,
          }}/>
          {imgs.length > 1 && (
            <div style={{ display:'flex', gap:6, padding:'8px 10px' }}>
              {imgs.map((src, i) => (
                <div key={i} onClick={() => setImgIdx(i)} style={{
                  width:42, height:42,
                  backgroundImage:`url('${src}')`, backgroundSize:'cover', backgroundPosition:'center top',
                  cursor:'pointer',
                  border: i===imgIdx ? `2px solid ${D.bord}` : `1px solid ${D.line}`,
                  opacity: i===imgIdx ? 1 : .65, transition:'all .2s',
                }}/>
              ))}
            </div>
          )}
        </div>

        {/* Info */}
        <div style={{ padding:'38px 30px 28px', display:'flex', flexDirection:'column', gap:16, overflowY:'auto' }}>
          <div>
            <DEyebrow>{g.mill}</DEyebrow>
            <h2 style={{ fontFamily:D.serif, fontWeight:300, fontSize:40, margin:'10px 0 2px',
              letterSpacing:'-.03em', color:D.ink, lineHeight:1 }}>{g.name}</h2>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:17, color:D.bord }}>{g.sub}</div>
          </div>

          <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:14, color:D.stone, lineHeight:1.65 }}>
            {g.desc}
          </div>

          <div>
            <DLabel style={{ marginBottom:10 }}>Kích cỡ</DLabel>
            <div style={{ display:'flex', gap:7 }}>
              {(g.sizes || ['S','M','L','XL']).map(sz => (
                <div key={sz} onClick={() => setSize(sz===size ? null : sz)} style={{
                  width:40, height:40, display:'flex', alignItems:'center', justifyContent:'center',
                  border: sz===size ? `1.5px solid ${D.bord}` : `1px solid ${D.line}`,
                  background: sz===size ? D.bord : 'transparent',
                  color: sz===size ? '#fff' : D.ink,
                  fontFamily:D.serif, fontSize:15, cursor:'pointer', transition:'all .2s',
                }}>{sz}</div>
              ))}
            </div>
          </div>

          <div style={{ paddingTop:14, borderTop:`1px solid ${D.line}` }}>
            <div style={{ fontFamily:"'JetBrains Mono','IBM Plex Mono',monospace", fontSize:24, color:D.ink }}>
              {formatVND(g.price)}
            </div>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:12, color:D.stone, marginTop:3 }}>
              cho {g.days} ngày · bao gồm giặt, ủi · Còn: {g.next}
            </div>
          </div>

          <div style={{ marginTop:'auto', display:'flex', flexDirection:'column', gap:9 }}>
            <DBtn kind="bord" size="lg" fullWidth onClick={() => { onClose(); go('booking', { id:g.id }); }}>
              Giữ một tối
            </DBtn>
            <DBtn kind="ink" size="md" fullWidth onClick={() => { onClose(); go('pdp', { id:g.id }); }}>
              Xem chi tiết →
            </DBtn>
            <div onClick={handleWishlist} style={{
              textAlign:'center', cursor:'pointer', paddingTop:6,
              fontFamily:D.serif, fontStyle:'italic', fontSize:13,
              color: wishlisted ? D.bord : D.stone, transition:'color .2s',
            }}>
              {wishlisted ? '♥ Đã lưu vào Tủ của tôi' : '♡ Lưu vào Tủ của tôi'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── DCollection ───────────────────────────────────────────────────────────
function DCollection({ go }) {
  const [activeEvent, setActiveEvent]         = React.useState(null);
  const [activeSizes, setActiveSizes]         = React.useState([]);
  const [activePriceRange, setActivePriceRange] = React.useState(null);
  const [sortBy, setSortBy]                   = React.useState('recommended');
  const [showSort, setShowSort]               = React.useState(false);
  const [mounted, setMounted]                 = React.useState(false);
  const [navH, setNavH]                       = React.useState(103);
  const [quickView, setQuickView]             = React.useState(null);
  const [visibleCount, setVisibleCount]       = React.useState(D_PER_PAGE);

  React.useEffect(() => {
    const t = setTimeout(() => setMounted(true), 80);
    return () => clearTimeout(t);
  }, []);

  React.useEffect(() => {
    const t = setTimeout(() => {
      const el = document.querySelector('.f2f-desktop-only');
      if (el) setNavH(el.offsetHeight);
    }, 200);
    return () => clearTimeout(t);
  }, []);

  // Close sort dropdown on outside click
  React.useEffect(() => {
    if (!showSort) return;
    const h = () => setShowSort(false);
    window.addEventListener('click', h);
    return () => window.removeEventListener('click', h);
  }, [showSort]);

  // Reset pagination when filters change
  React.useEffect(() => { setVisibleCount(D_PER_PAGE); }, [activeEvent, activeSizes, activePriceRange, sortBy]);

  const allFiltered = React.useMemo(() => {
    let r = [...GARMENTS];
    if (activeEvent) r = r.filter(g => Array.isArray(g.events) && g.events.includes(activeEvent));
    if (activeSizes.length) r = r.filter(g => Array.isArray(g.sizes) && activeSizes.some(s => g.sizes.includes(s)));
    if (activePriceRange) {
      const range = D_PRICE_RANGES.find(x => x.id === activePriceRange);
      if (range) r = r.filter(g => range.fn(g.price));
    }
    if (sortBy === 'price-asc')  r.sort((a,b) => a.price - b.price);
    if (sortBy === 'price-desc') r.sort((a,b) => b.price - a.price);
    if (sortBy === 'name-az')    r.sort((a,b) => a.name.localeCompare(b.name));
    return r;
  }, [activeEvent, activeSizes, activePriceRange, sortBy]);

  const displayed = allFiltered.slice(0, visibleCount);
  const hasMore   = visibleCount < allFiltered.length;

  const activeFilterCount = (activeEvent ? 1 : 0) + activeSizes.length + (activePriceRange ? 1 : 0);
  const eventLabel = activeEvent ? D_COLLECTION_EVENTS.find(e => e.id === activeEvent)?.label : null;
  const sortLabel  = D_SORT_OPTIONS.find(o => o.id === sortBy)?.label || 'Đề xuất';

  const handleEventChip = (id) => {
    const next = id === activeEvent ? null : id;
    if (next === activeEvent) return;
    setActiveEvent(next);
  };
  const handleSize  = (sz) => setActiveSizes(prev => prev.includes(sz) ? prev.filter(s=>s!==sz) : [...prev,sz]);
  const handlePrice = (id) => setActivePriceRange(prev => prev===id ? null : id);
  const clearAll    = () => { setActiveEvent(null); setActiveSizes([]); setActivePriceRange(null); };

  return (
    <div style={{ background:D.paper, minHeight:'100%' }}>

      {/* Breadcrumb */}
      <div style={{ maxWidth:1440, margin:'0 auto', padding:'10px 60px 0',
        display:'flex', gap:8, alignItems:'center',
        fontFamily:D.serif, fontStyle:'italic', fontSize:12, color:D.stone }}>
        <span onClick={() => go('home')} style={{ cursor:'pointer' }}>Trang chủ</span>
        <span style={{ color:D.bord, fontStyle:'normal', margin:'0 2px' }}>/</span>
        <span style={{ color: eventLabel ? D.stone : D.ink, cursor: eventLabel ? 'pointer' : 'default' }}
          onClick={() => eventLabel && setActiveEvent(null)}>Tủ đồ</span>
        {eventLabel && <>
          <span style={{ color:D.bord, fontStyle:'normal', margin:'0 2px' }}>/</span>
          <span style={{ color:D.ink }}>{eventLabel}</span>
        </>}
      </div>

      {/* ── Sticky filter bar — 2 rows ── */}
      <div style={{ position:'sticky', top:navH, zIndex:40,
        background:D.paper, borderTop:`1px solid ${D.line}`, borderBottom:`1px solid ${D.line}` }}>

        {/* Row 1: Occasion chips */}
        <div className="d-chip-scroll" style={{
          maxWidth:1440, margin:'0 auto', padding:'6px 60px',
          display:'flex', alignItems:'center', gap:6,
          overflowX:'auto', scrollbarWidth:'none',
          borderBottom:`1px solid ${D.line}`,
        }}>
          <DChip active={activeEvent===null} onClick={() => handleEventChip(null)} style={{ flexShrink:0, padding:'4px 10px', fontSize:9 }}>
            Tất cả{' '}
            <span style={{ opacity:.4, marginLeft:3, fontFamily:D.serif, fontStyle:'italic', fontWeight:300, fontSize:10 }}>
              {GARMENTS.length}
            </span>
          </DChip>
          {D_COLLECTION_EVENTS.map(ev => {
            const cnt = GARMENTS.filter(g => Array.isArray(g.events) && g.events.includes(ev.id)).length;
            return (
              <DChip key={ev.id} active={activeEvent===ev.id} onClick={() => handleEventChip(ev.id)} style={{ flexShrink:0, padding:'4px 10px', fontSize:9 }}>
                {ev.label}{' '}
                <span style={{ opacity:.4, marginLeft:3, fontFamily:D.serif, fontStyle:'italic', fontWeight:300, fontSize:10 }}>
                  {cnt}
                </span>
              </DChip>
            );
          })}
        </div>

        {/* Row 2: Sort + Size + Price + Count */}
        <div className="d-chip-scroll" style={{
          maxWidth:1440, margin:'0 auto', padding:'6px 60px',
          display:'flex', alignItems:'center', gap:10, overflowX:'auto', scrollbarWidth:'none',
        }}>

          {/* Sort dropdown */}
          <div style={{ position:'relative', flexShrink:0 }} onClick={e => e.stopPropagation()}>
            <div onClick={() => setShowSort(s => !s)} style={{
              fontFamily:D.sans, fontSize:9, letterSpacing:'.22em', textTransform:'uppercase', fontWeight:600,
              color:D.ink, cursor:'pointer', whiteSpace:'nowrap',
              padding:'5px 11px', border:`1px solid ${D.line}`,
              display:'flex', alignItems:'center', gap:6,
            }}>
              {sortLabel} <span style={{ fontSize:7, opacity:.55 }}>▼</span>
            </div>
            {showSort && (
              <div style={{
                position:'absolute', top:'calc(100% + 4px)', left:0, zIndex:100,
                background:D.paper, border:`1px solid ${D.line}`,
                boxShadow:'0 8px 28px rgba(61,40,23,.11)', minWidth:160,
              }}>
                {D_SORT_OPTIONS.map(opt => (
                  <div key={opt.id} onClick={() => { setSortBy(opt.id); setShowSort(false); }} style={{
                    padding:'9px 14px', cursor:'pointer',
                    fontFamily:D.sans, fontSize:9, letterSpacing:'.2em', textTransform:'uppercase', fontWeight:600,
                    color: sortBy===opt.id ? D.bord : D.ink,
                    background: sortBy===opt.id ? 'rgba(107,31,36,.05)' : 'transparent',
                  }}>{opt.label}</div>
                ))}
              </div>
            )}
          </div>

          <span style={{ width:1, height:16, background:D.line, flexShrink:0 }}/>

          {/* Size chips */}
          <div style={{ display:'flex', gap:5, alignItems:'center', flexShrink:0 }}>
            <span style={{ fontFamily:D.sans, fontSize:8, letterSpacing:'.22em', textTransform:'uppercase', fontWeight:600, color:D.stone }}>
              Size
            </span>
            {['S','M','L','XL'].map(sz => (
              <DChip key={sz} active={activeSizes.includes(sz)} onClick={() => handleSize(sz)}
                style={{ padding:'4px 8px', fontSize:9, flexShrink:0 }}>{sz}</DChip>
            ))}
          </div>

          <span style={{ width:1, height:16, background:D.line, flexShrink:0 }}/>

          {/* Price chips */}
          <div style={{ display:'flex', gap:5, alignItems:'center', flexShrink:0 }}>
            <span style={{ fontFamily:D.sans, fontSize:8, letterSpacing:'.22em', textTransform:'uppercase', fontWeight:600, color:D.stone }}>
              Giá
            </span>
            {D_PRICE_RANGES.map(r => (
              <DChip key={r.id} active={activePriceRange===r.id} onClick={() => handlePrice(r.id)}
                style={{ padding:'4px 8px', fontSize:9, flexShrink:0 }}>{r.label}</DChip>
            ))}
          </div>

          {/* Count right */}
          <div style={{ marginLeft:'auto', fontFamily:"'JetBrains Mono','IBM Plex Mono',monospace",
            fontSize:10, color:D.stone, fontStyle:'italic', whiteSpace:'nowrap', flexShrink:0 }}>
            {allFiltered.length} / {GARMENTS.length} bộ
          </div>
        </div>
      </div>

      {/* Active filter tags */}
      {activeFilterCount > 0 && (
        <div style={{ maxWidth:1440, margin:'0 auto', padding:'6px 60px',
          display:'flex', gap:6, alignItems:'center', flexWrap:'wrap',
          borderBottom:`1px solid ${D.line}` }}>
          {activeEvent && (
            <span onClick={() => setActiveEvent(null)} style={{
              fontFamily:D.sans, fontSize:8, letterSpacing:'.2em', fontWeight:600, textTransform:'uppercase',
              padding:'5px 10px', border:`1px solid ${D.bord}`, color:D.bord, cursor:'pointer',
              display:'inline-flex', alignItems:'center', gap:7,
            }}>
              {eventLabel} <span style={{ fontSize:13, lineHeight:1 }}>×</span>
            </span>
          )}
          {activeSizes.map(sz => (
            <span key={sz} onClick={() => handleSize(sz)} style={{
              fontFamily:D.sans, fontSize:8, letterSpacing:'.2em', fontWeight:600, textTransform:'uppercase',
              padding:'5px 10px', border:`1px solid ${D.bord}`, color:D.bord, cursor:'pointer',
              display:'inline-flex', alignItems:'center', gap:7,
            }}>
              Size {sz} <span style={{ fontSize:13, lineHeight:1 }}>×</span>
            </span>
          ))}
          {activePriceRange && (
            <span onClick={() => setActivePriceRange(null)} style={{
              fontFamily:D.sans, fontSize:8, letterSpacing:'.2em', fontWeight:600, textTransform:'uppercase',
              padding:'5px 10px', border:`1px solid ${D.bord}`, color:D.bord, cursor:'pointer',
              display:'inline-flex', alignItems:'center', gap:7,
            }}>
              {D_PRICE_RANGES.find(r=>r.id===activePriceRange)?.label} <span style={{ fontSize:13, lineHeight:1 }}>×</span>
            </span>
          )}
          <span onClick={clearAll} style={{
            fontFamily:D.sans, fontSize:8, letterSpacing:'.2em', fontWeight:600, textTransform:'uppercase',
            color:D.stone, cursor:'pointer', borderBottom:`1px solid ${D.stone}`, paddingBottom:1,
          }}>Xoá tất cả</span>
        </div>
      )}

      {/* Product grid */}
      <section style={{ padding:'20px 60px 60px', maxWidth:1440, margin:'0 auto' }}>
        {allFiltered.length === 0 ? (
          <div style={{ textAlign:'center', padding:'80px 0' }}>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:24, color:D.stone, lineHeight:1.6 }}>
              Chưa có bộ vest nào phù hợp với bộ lọc này.
            </div>
            <div style={{ marginTop:24 }}>
              <DBtn kind="hair" size="md" onClick={clearAll}>Xoá bộ lọc</DBtn>
            </div>
          </div>
        ) : (
          <>
            <div className="collection-grid" data-keep-grid="true"
              style={{ opacity:mounted?1:0, transition:'opacity .25s ease' }}>
              {displayed.map(g => (
                <GarmentCard key={g.id} g={g} go={go} onQuickView={setQuickView}/>
              ))}
            </div>

            {hasMore && (
              <div style={{ textAlign:'center', marginTop:52 }}>
                <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:13, color:D.stone, marginBottom:16 }}>
                  Đang hiển thị{' '}
                  <span style={{ fontFamily:"'JetBrains Mono','IBM Plex Mono',monospace" }}>{displayed.length}</span>
                  {' '}/{' '}
                  <span style={{ fontFamily:"'JetBrains Mono','IBM Plex Mono',monospace" }}>{allFiltered.length}</span>
                  {' '}bộ
                </div>
                <DBtn kind="ink" size="md" onClick={() => setVisibleCount(c => c + 6)}>
                  Xem thêm
                </DBtn>
              </div>
            )}
          </>
        )}
      </section>

      {/* Tailor's note */}
      <section style={{ background:D.inkDeep, color:'#fff', padding:'80px 60px' }}>
        <div style={{ maxWidth:1000, margin:'0 auto', display:'grid', gridTemplateColumns:'auto 1fr', gap:48, alignItems:'center' }}>
          <div style={{ width:160, height:160, backgroundImage:"url('assets/photos/detail_05.jpg')",
            backgroundSize:'cover', filter:D.imgDeep,
            border:`1px solid ${D.gold}`, position:'relative' }}>
            <div style={{ position:'absolute', inset:5, border:`1px solid rgba(168,134,74,.3)` }}/>
          </div>
          <div>
            <DLabel tone="gold" style={{ color:D.gold }}>Ghi chú · Master tailor · Bạn Lâm</DLabel>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:26, lineHeight:1.4, marginTop:12 }}>
              "Mỗi buổi tối có ngôn ngữ riêng — và một bộ vest đúng vải, đúng cắt, sẽ nói thay bạn trước khi bạn mở miệng."
            </div>
            <DLabel tone="gold" style={{ color:D.gold, marginTop:18 }}>— XIV năm Savile Row · hồi hương MMXXII</DLabel>
          </div>
        </div>
      </section>

      {quickView && <DQuickView g={quickView} go={go} onClose={() => setQuickView(null)}/>}
    </div>
  );
}

function DPDP({ go, params }) {
  const g = GARMENTS.find(x=>x.id===params?.id) || GARMENTS[0];
  const [view, setView] = React.useState(0);
  const views = [g.img, 'assets/photos/detail_02.jpg', 'assets/photos/detail_03.jpg', 'assets/photos/detail_04.jpg'];
  const sizes = ['48','50','52','54','56','58'];
  const [size, setSize] = React.useState('52');

  return (
    <div style={{ background: D.paper }}>
      {/* Breadcrumb / chapter */}
      <section style={{ padding:'40px 60px 0', maxWidth:1440, margin:'0 auto' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
          <DLabel>— III — Một bộ vest</DLabel>
          <div style={{ fontFamily:D.sans, fontSize:10, letterSpacing:'.24em', textTransform:'uppercase', color:D.stone, fontWeight:600 }}>
            <span onClick={()=>go('home')} style={{ cursor:'pointer' }}>Sự kiện</span>
            <span style={{ margin:'0 10px', color:D.bord }}>/</span>
            <span onClick={()=>go('collection')} style={{ cursor:'pointer' }}>Tủ đồ</span>
            <span style={{ margin:'0 10px', color:D.bord }}>/</span>
            <span style={{ color:D.bord }}>{g.name}</span>
          </div>
        </div>
      </section>

      {/* Main spread */}
      <section style={{ padding:'40px 60px 80px', maxWidth:1440, margin:'0 auto' }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:64, alignItems:'start' }}>
          <div>
            <div style={{ aspectRatio:'3/4', backgroundImage:`url('${views[view]}')`, backgroundSize:'cover', backgroundPosition:'center', filter:D.imgEd,
              border:`1px solid ${D.line}`, position:'relative' }}>
              <div style={{ position:'absolute', inset:10, border:`1px solid rgba(255,255,255,.18)`, pointerEvents:'none' }}/>
              <div style={{ position:'absolute', top:18, left:18, background:D.paper, padding:'6px 12px', fontFamily:D.sans, fontSize:9, letterSpacing:'.28em', color:D.bord, fontWeight:700 }}>
                {toRoman(view+1)} · {['trước','sau','chi tiết','vải'][view]}
              </div>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:8, marginTop:10 }}>
              {views.map((src,i)=>(
                <div key={i} onClick={()=>setView(i)} style={{ aspectRatio:'1/1', backgroundImage:`url('${src}')`, backgroundSize:'cover', backgroundPosition:'center',
                  filter:D.imgCard, cursor:'pointer', border: i===view ? `1.5px solid ${D.bord}` : `1px solid ${D.line}` }}/>
              ))}
            </div>
          </div>

          <div style={{ paddingTop: 6 }}>
            <DEyebrow>{g.mill}</DEyebrow>
            <h1 style={{ fontFamily:D.serif, fontWeight:300, fontSize:116, margin:'14px 0 12px', letterSpacing:'-.035em', lineHeight:.92, color:D.ink }}>
              {g.name}
            </h1>
            <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:44, color:D.bord, fontWeight:300, lineHeight:1, marginBottom:28 }}>
              {g.sub}
            </div>
            <div style={{ fontFamily:D.body, fontSize:18, color:D.inkSoft, lineHeight:1.65, marginBottom:32, maxWidth:520 }}>
              {g.desc}
            </div>

            {/* Tailor quote — reverse block */}
            <div style={{ padding:'28px 32px', background:D.inkDeep, color:'#fff', marginBottom:36, position:'relative' }}>
              <div style={{ position:'absolute', inset:6, border:`1px solid rgba(168,134,74,.22)`, pointerEvents:'none' }}/>
              <DLabel tone="gold" style={{ color:D.gold }}>Ghi chú · Master tailor</DLabel>
              <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:22, lineHeight:1.45, marginTop:12, color:'rgba(255,255,255,.94)' }}>
                "Trong {GARMENTS.length} bộ vest của tủ đồ, đây là bộ chúng tôi để dành cho một lời chúc lễ hỏi hoặc một buổi sáng hội nghị."
              </div>
              <DLabel tone="gold" style={{ color:D.gold, marginTop:14 }}>— Bạn Lâm · Master tailor</DLabel>
            </div>

            {/* Sizes */}
            <div style={{ marginBottom:28 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:14 }}>
                <DLabel>Kích cỡ</DLabel>
                <span style={{ fontFamily:D.sans, fontSize:10, letterSpacing:'.22em', textTransform:'uppercase', color:D.bord, fontWeight:700, cursor:'pointer' }}>Bảng đo →</span>
              </div>
              <div style={{ display:'flex', gap:6 }}>
                {sizes.map(s => (
                  <div key={s} onClick={()=>setSize(s)} style={{ width:54, height:54, display:'flex', alignItems:'center', justifyContent:'center',
                    border: size===s ? `1.5px solid ${D.bord}` : `1px solid ${D.line}`, background: size===s ? D.bord : 'transparent',
                    color: size===s ? '#fff' : D.ink, fontFamily:D.serif, fontSize:18, cursor:'pointer' }}>{s}</div>
                ))}
              </div>
            </div>

            {/* Price + CTA */}
            <div style={{ padding:'24px 0', borderTop:`1px solid ${D.bord}`, borderBottom:`1px solid ${D.bord}`, marginBottom:28,
              display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
              <div>
                <div style={{ fontFamily:D.serif, fontSize:42, lineHeight:1, color:D.ink }}>{formatVND(g.price)}</div>
                <div style={{ fontFamily:D.body, fontSize:13, color:D.stone, marginTop:4, fontStyle:'italic' }}>cho {g.days} ngày · bao gồm giặt, ủi, bảo hiểm</div>
              </div>
              <div style={{ textAlign:'right' }}>
                <DLabel>Còn trống gần nhất</DLabel>
                <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:22, color:D.bord, marginTop:4 }}>{g.next}</div>
              </div>
            </div>

            <div style={{ display:'flex', gap:12 }}>
              <DBtn kind="bord" size="lg" onClick={()=>go('booking',{ id:g.id })}>Giữ một tối</DBtn>
              <DBtn kind="ink" size="lg">Lưu vào danh sách</DBtn>
            </div>

            <div style={{ marginTop:20, fontFamily:D.serif, fontSize:13, color:D.stone, fontStyle:'italic' }}>
              ✦ Trong 24 giờ qua, 3 người khác đã xem {g.name}. Tối 3 Thg 5 còn trống cho một khách duy nhất.
            </div>
          </div>
        </div>
      </section>

      {/* Specs strip */}
      <section style={{ padding:'40px 60px 40px', maxWidth:1440, margin:'0 auto' }}>
        <DRule style={{ marginBottom:40 }} wide/>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:44 }}>
          {[
            ['Vải',        g.mill,               'Dệt tại Huddersfield, UK'],
            ['Cấu trúc',   'Ba mảnh · canvas nổi','Không keo, toàn cổ điển'],
            ['Cắt',        'Sài Gòn · MMXXV',      'Bạn Lâm, master tailor'],
            ['Chăm sóc',   'Hấp · ủi hơi',         'Trả về trong 24h sau buổi tối'],
          ].map(([k,v,s],i)=>(
            <div key={k} style={{ borderTop:`1px solid ${D.lineBord}`, paddingTop:22 }}>
              <DLabel>{toRoman(i+1)} · {k}</DLabel>
              <div style={{ fontFamily:D.serif, fontSize:24, color:D.ink, marginTop:10 }}>{v}</div>
              <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:14, color:D.stone, marginTop:4 }}>{s}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Also for this occasion */}
      <section style={{ padding:'80px 60px 120px', background:D.paperAlt }}>
        <div style={{ maxWidth:1440, margin:'0 auto' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:36 }}>
            <div>
              <DLabel>Cũng cho sự kiện này</DLabel>
              <h2 style={{ fontFamily:D.serif, fontWeight:300, fontSize:44, margin:'10px 0 0', color:D.ink, letterSpacing:'-.02em' }}>
                Hai phương án <span style={{ fontStyle:'italic', color:D.bord }}>thay thế</span>.
              </h2>
            </div>
            <DBtn kind="link" onClick={()=>go('collection')}>Xem tất cả →</DBtn>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:24 }}>
            {GARMENTS.filter(x=>x.id!==g.id).slice(0,3).map((x, i)=>(
              <div key={x.id} onClick={()=>{ setView(0); go('pdp',{ id:x.id }); }} style={{ cursor:'pointer', background:D.paper, border:`1px solid ${D.line}`, padding:16 }}>
                <div style={{ aspectRatio:'4/5', backgroundImage:`url('${x.img}')`, backgroundSize:'cover', filter:D.imgCard, border:`1px solid ${D.line}` }}/>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginTop:14 }}>
                  <div>
                    <div style={{ fontFamily:D.serif, fontSize:24, color:D.ink }}>{x.name}</div>
                    <div style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:14, color:D.stone }}>{x.sub}</div>
                  </div>
                  <span style={{ fontFamily:D.serif, fontStyle:'italic', fontSize:16, color:D.bord }}>{toRoman(i+1)}</span>
                </div>
                <div style={{ fontFamily:D.serif, fontSize:18, color:D.bord, marginTop:8 }}>{formatVND(x.price)}</div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { DCollection, DPDP });
