// shop.jsx — product listing + filter bottom sheet

function ShopScreen({ onOpenProduct, onNav }) {
  const [filterOpen, setFilterOpen] = React.useState(false);
  const [sort, setSort] = React.useState('featured');
  const [activeCat, setActiveCat] = React.useState('All');
  const [stickyTop, setStickyTop] = React.useState(false);

  const cats = ['All', 'Trigger Kits', 'Safeties', 'Components', 'Accessories'];

  const filtered = FF_PRODUCTS.filter(p => activeCat === 'All' || p.category === activeCat);
  const sorted = [...filtered].sort((a, b) => {
    if (sort === 'price-low') return a.price - b.price;
    if (sort === 'price-high') return b.price - a.price;
    if (sort === 'rating') return b.rating - a.rating;
    return 0;
  });

  return (
    <div>
      {/* Header */}
      <section style={{ padding: '24px 16px 16px' }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>SHOP</div>
        <h1 className="display" style={{ fontSize: 32, margin: 0, fontWeight: 700, letterSpacing: '-0.025em' }}>
          All Products
        </h1>
        <p style={{ marginTop: 8, marginBottom: 0, color: 'var(--ff-text-2)', fontSize: 14 }}>
          {sorted.length} item{sorted.length === 1 ? '' : 's'} · machined in Texas
        </p>
      </section>

      {/* Sticky filter/sort bar */}
      <div style={{
        position: 'sticky', top: 'calc(56px + var(--safe-top))', zIndex: 20,
        background: 'rgba(10,10,10,0.92)', backdropFilter: 'blur(14px)',
        borderTop: '1px solid var(--ff-border)', borderBottom: '1px solid var(--ff-border)',
      }}>
        {/* category chips horizontal scroll */}
        <div className="no-scrollbar" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '12px 16px' }}>
          {cats.map(c => (
            <button key={c} onClick={() => setActiveCat(c)}
              style={{
                flex: '0 0 auto', padding: '8px 14px', minHeight: 36, borderRadius: 999,
                border: '1px solid', borderColor: activeCat === c ? 'var(--ff-orange)' : 'var(--ff-border)',
                background: activeCat === c ? 'var(--ff-orange-dim)' : 'transparent',
                color: activeCat === c ? 'var(--ff-orange)' : 'var(--ff-text-2)',
                fontSize: 13, fontWeight: 500, cursor: 'pointer',
                whiteSpace: 'nowrap', transition: 'all 180ms',
              }}>
              {c}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', borderTop: '1px solid var(--ff-border)' }}>
          <button onClick={() => setFilterOpen(true)}
            style={{ flex: 1, padding: '14px 16px', background: 'none', border: 'none',
              borderRight: '1px solid var(--ff-border)', color: 'var(--ff-text)',
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              fontSize: 13, fontWeight: 500, minHeight: 48 }}>
            <IconFilter size={16}/> Filter
          </button>
          <button onClick={() => setFilterOpen('sort')}
            style={{ flex: 1, padding: '14px 16px', background: 'none', border: 'none', color: 'var(--ff-text)',
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              fontSize: 13, fontWeight: 500, minHeight: 48 }}>
            <IconSort size={16}/> Sort: {sort === 'featured' ? 'Featured' : sort === 'price-low' ? 'Price ↑' : sort === 'price-high' ? 'Price ↓' : 'Rating'}
          </button>
        </div>
      </div>

      {/* Grid 2-col */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1, background: 'var(--ff-border)', padding: 0 }}>
        {sorted.map(p => (
          <div key={p.id} style={{ background: 'var(--ff-bg)', padding: '14px 12px' }}>
            <ProductCard p={p} onOpen={onOpenProduct} compact/>
          </div>
        ))}
      </div>

      <div style={{ height: 'calc(120px + var(--safe-bottom))' }}/>

      {filterOpen && (
        <BottomSheet onClose={() => setFilterOpen(false)} title={filterOpen === 'sort' ? 'Sort by' : 'Filters'}>
          {filterOpen === 'sort' ? (
            <SortSheet sort={sort} setSort={(s) => { setSort(s); setFilterOpen(false); }}/>
          ) : (
            <FilterSheet onApply={() => setFilterOpen(false)}/>
          )}
        </BottomSheet>
      )}
    </div>
  );
}

function SortSheet({ sort, setSort }) {
  const opts = [
    { k: 'featured', l: 'Featured' },
    { k: 'price-low', l: 'Price: Low to High' },
    { k: 'price-high', l: 'Price: High to Low' },
    { k: 'rating', l: 'Top Rated' },
  ];
  return (
    <div style={{ padding: '8px 0 16px' }}>
      {opts.map((o, i) => (
        <button key={o.k} onClick={() => setSort(o.k)}
          style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '16px 20px', minHeight: 56,
            borderTop: i === 0 ? 'none' : '1px solid var(--ff-border)',
            background: 'none', border: 'none', color: 'var(--ff-text)', cursor: 'pointer',
            fontSize: 16, fontFamily: 'var(--ff-body)',
          }}>
          <span>{o.l}</span>
          {sort === o.k && <IconCheck size={18} color="var(--ff-orange)"/>}
        </button>
      ))}
    </div>
  );
}

function FilterSheet({ onApply }) {
  const [price, setPrice] = React.useState([0, 300]);
  const [picks, setPicks] = React.useState([]);
  const toggle = (v) => setPicks(p => p.includes(v) ? p.filter(x => x !== v) : [...p, v]);

  return (
    <div style={{ padding: '20px 20px 24px' }}>
      <div style={{ marginBottom: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>PLATFORM</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['AR-15', 'AR-10', 'Mil-Spec'].map(t => (
            <button key={t} onClick={() => toggle(t)} className="tap"
              style={{
                padding: '10px 16px', minHeight: 44, borderRadius: 999,
                border: '1px solid', borderColor: picks.includes(t) ? 'var(--ff-orange)' : 'var(--ff-border)',
                background: picks.includes(t) ? 'var(--ff-orange-dim)' : 'transparent',
                color: picks.includes(t) ? 'var(--ff-orange)' : 'var(--ff-text)',
                fontSize: 14, fontWeight: 500, cursor: 'pointer',
              }}>{t}</button>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>FINISH</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['Black Nitride', 'Tungsten', 'FDE', 'Stonewashed'].map(t => (
            <button key={t} onClick={() => toggle(t)} className="tap"
              style={{
                padding: '10px 16px', minHeight: 44, borderRadius: 999,
                border: '1px solid', borderColor: picks.includes(t) ? 'var(--ff-orange)' : 'var(--ff-border)',
                background: picks.includes(t) ? 'var(--ff-orange-dim)' : 'transparent',
                color: picks.includes(t) ? 'var(--ff-orange)' : 'var(--ff-text)',
                fontSize: 14, fontWeight: 500, cursor: 'pointer',
              }}>{t}</button>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>PRICE RANGE</div>
        <div className="mono" style={{ fontSize: 14, color: 'var(--ff-text)', marginBottom: 12 }}>
          ${price[0]} – ${price[1]}+
        </div>
        <input type="range" min={0} max={300} value={price[1]}
          onChange={(e) => setPrice([0, +e.target.value])}
          style={{ width: '100%', accentColor: 'var(--ff-orange)' }}/>
      </div>

      <div style={{ marginBottom: 24 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>AVAILABILITY</div>
        {['In stock only', 'Includes install kit'].map(t => (
          <label key={t} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', borderTop: '1px solid var(--ff-border)' }}>
            <input type="checkbox" style={{ width: 20, height: 20, accentColor: 'var(--ff-orange)' }}/>
            <span style={{ fontSize: 15 }}>{t}</span>
          </label>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 10 }}>
        <button className="btn btn-secondary tap" style={{ flex: 1 }}>Reset</button>
        <button className="btn btn-primary tap" style={{ flex: 2 }} onClick={onApply}>Apply filters</button>
      </div>
    </div>
  );
}

// Bottom Sheet — drag-to-dismiss, snaps
function BottomSheet({ onClose, title, children }) {
  const [drag, setDrag] = React.useState(0);
  const [snap, setSnap] = React.useState('half'); // half | full

  const onTouchStart = React.useRef(null);
  const handleStart = (e) => {
    const y = e.touches?.[0]?.clientY ?? e.clientY;
    onTouchStart.current = y;
  };
  const handleMove = (e) => {
    if (onTouchStart.current === null) return;
    const y = e.touches?.[0]?.clientY ?? e.clientY;
    const dy = y - onTouchStart.current;
    setDrag(Math.max(-100, dy));
  };
  const handleEnd = () => {
    if (drag > 100) onClose();
    else if (drag < -50 && snap === 'half') setSnap('full');
    else if (drag > 50 && snap === 'full') setSnap('half');
    setDrag(0);
    onTouchStart.current = null;
  };

  const height = snap === 'full' ? '92svh' : '70svh';

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 80 }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)',
        backdropFilter: 'blur(4px)', animation: 'ff-fade-in 220ms',
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height, maxHeight: '92svh',
        background: 'var(--ff-bg)',
        borderTop: '1px solid var(--ff-border)',
        borderRadius: '16px 16px 0 0',
        transform: `translateY(${drag}px)`,
        transition: drag === 0 ? 'transform 280ms var(--ff-ease-out), height 220ms' : 'none',
        animation: drag === 0 ? 'ff-slide-up 320ms var(--ff-ease-out)' : 'none',
        display: 'flex', flexDirection: 'column',
        paddingBottom: 'var(--safe-bottom)',
        boxShadow: '0 -16px 48px rgba(0,0,0,0.5)',
      }}>
        <div onTouchStart={handleStart} onTouchMove={handleMove} onTouchEnd={handleEnd}
          onMouseDown={handleStart} onMouseMove={(e) => e.buttons && handleMove(e)} onMouseUp={handleEnd}
          style={{ padding: '12px 0 4px', cursor: 'grab', flexShrink: 0 }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--ff-border-strong)', margin: '0 auto' }}/>
        </div>
        <div style={{
          padding: '8px 20px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          borderBottom: '1px solid var(--ff-border)', flexShrink: 0,
        }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600 }}>{title}</div>
          <button onClick={onClose} className="tap"
            style={{ background: 'none', border: 'none', color: 'var(--ff-text-2)', padding: 8, marginRight: -8, cursor: 'pointer' }}>
            <IconClose size={20}/>
          </button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {children}
        </div>
      </div>
      <style>{`@keyframes ff-slide-up { from { transform: translateY(100%) } to { transform: translateY(0) } }`}</style>
    </div>
  );
}

Object.assign(window, { ShopScreen, BottomSheet });
