/* ds-patterns.jsx — Interactive patterns
   PDP · Cart drawer · Lookbook scroll · Drop hero
*/

const PDPInteractive = () => {
  const [variant, setVariant] = React.useState('Chrome');
  const [size, setSize] = React.useState('M');
  const [qty, setQty] = React.useState(1);
  const [bag, setBag] = React.useState([]);
  const [drawerOpen, setDrawerOpen] = React.useState(false);

  const variants = ['Chrome', 'Mirror', 'Midnight'];
  const sizes = ['S', 'M', 'L'];

  const addToBag = () => {
    setBag(b => [...b, { name:'Loop Bag', variant, size, qty, price: 620 }]);
    setDrawerOpen(true);
  };

  return (
    <div style={{ background:T.bone, border:`1px solid ${T.ink}`, position:'relative', overflow:'hidden' }}>
      <div style={{ display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:0 }}>
        {/* gallery */}
        <div style={{ background:T.n200, aspectRatio:'4/5', position:'relative', borderRight:`1px solid ${T.ink}` }}>
          <div style={{
            position:'absolute', inset:0,
            background: variant === 'Chrome'
              ? `linear-gradient(135deg, ${T.chrome} 0%, ${T.n300} 50%, ${T.n400} 100%)`
              : variant === 'Mirror'
                ? `linear-gradient(135deg, #e8e6e0 0%, #b8b6b0 50%, #6a6864 100%)`
                : `linear-gradient(135deg, #2a2a2a 0%, #0a0a0a 100%)`,
            transition: `background ${M.slow.d}ms ${M.slow.e}`,
          }}/>
          <div style={{
            position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
            fontFamily:"'Helvetica Neue', sans-serif", fontWeight:900, fontSize:96,
            color: variant === 'Midnight' ? T.bone : T.bone, opacity:.3, letterSpacing:'-0.04em',
          }}>LOOP</div>
          <div style={{ position:'absolute', top:S[4], left:S[4] }}>
            <Tag variant="neon">NEW · DROP 02</Tag>
          </div>
          <div style={{
            position:'absolute', bottom:S[4], left:S[4], right:S[4],
            display:'flex', gap:S[2],
          }}>
            {[1,2,3,4].map(i => (
              <div key={i} style={{
                flex:1, height:60, background:T.paper, border:`1px solid ${T.ink}`,
                opacity: i === 1 ? 1 : .55, cursor:'pointer',
              }}/>
            ))}
          </div>
        </div>

        {/* details */}
        <div style={{ padding:`${S[7]}px ${S[6]}px`, display:'flex', flexDirection:'column', gap:S[5] }}>
          <div className="mono" style={{ fontSize:11, letterSpacing:'.2em', textTransform:'uppercase', display:'flex', justifyContent:'space-between' }}>
            <span style={{opacity:.55}}>BAGS · LOOP</span>
            <span style={{color: T.positive}}>● IN STOCK</span>
          </div>
          <h2 style={{ fontWeight:900, fontSize:42, letterSpacing:'-0.03em', lineHeight:1, margin:0 }}>The Loop Bag</h2>
          <div style={{ fontSize:24, fontWeight:900 }}>€620,00</div>

          <p style={{ fontSize:14, lineHeight:1.6, color:T.n500, margin:0 }}>
            A folded chrome shell with a cast-aluminium handle. 17 × 24 × 6 cm. Made in Florence, edition of 200.
          </p>

          {/* color */}
          <div>
            <div className="mono" style={{ fontSize:10, letterSpacing:'.18em', textTransform:'uppercase', color:T.n500, marginBottom:S[2] }}>
              FINISH · {variant}
            </div>
            <div style={{ display:'flex', gap:S[2] }}>
              {variants.map(v => (
                <button key={v} onClick={() => setVariant(v)} style={{
                  padding:`${S[2]}px ${S[4]}px`, background:T.paper,
                  border:`1px solid ${variant === v ? T.ink : T.n300}`,
                  borderBottomWidth: variant === v ? 3 : 1,
                  cursor:'pointer', fontFamily:'inherit', fontSize:13,
                  letterSpacing:'.02em',
                }}>{v}</button>
              ))}
            </div>
          </div>

          {/* size */}
          <div>
            <div className="mono" style={{ fontSize:10, letterSpacing:'.18em', textTransform:'uppercase', color:T.n500, marginBottom:S[2], display:'flex', justifyContent:'space-between' }}>
              <span>SIZE · {size}</span>
              <a href="#" style={{ color:T.ink }}>SIZE GUIDE →</a>
            </div>
            <div style={{ display:'flex', gap:S[2] }}>
              {sizes.map(s => (
                <button key={s} onClick={() => setSize(s)} style={{
                  flex:1, padding:`${S[3]}px 0`, background:T.paper,
                  border:`1px solid ${size === s ? T.ink : T.n300}`,
                  borderBottomWidth: size === s ? 3 : 1,
                  cursor:'pointer', fontFamily:'inherit', fontSize:14, fontWeight:700,
                }}>{s}</button>
              ))}
            </div>
          </div>

          {/* qty + cta */}
          <div style={{ display:'flex', gap:S[3], marginTop:S[3] }}>
            <div style={{ display:'flex', border:`1px solid ${T.ink}` }}>
              <button onClick={() => setQty(q => Math.max(1, q-1))} style={{
                width:48, height:56, background:T.paper, border:'none', cursor:'pointer', fontSize:18,
              }}>−</button>
              <div style={{ width:48, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, borderLeft:`1px solid ${T.ink}`, borderRight:`1px solid ${T.ink}` }}>{qty}</div>
              <button onClick={() => setQty(q => q+1)} style={{
                width:48, height:56, background:T.paper, border:'none', cursor:'pointer', fontSize:18,
              }}>+</button>
            </div>
            <button onClick={addToBag} style={{
              flex:1, height:56, padding:`0 ${S[5]}px`,
              background:T.ink, color:T.bone, border:`1px solid ${T.ink}`,
              fontFamily:'inherit', fontWeight:700, fontSize:15, letterSpacing:'.02em',
              cursor:'pointer',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = T.neon; e.currentTarget.style.color = T.ink; }}
            onMouseLeave={e => { e.currentTarget.style.background = T.ink; e.currentTarget.style.color = T.bone; }}
            >Add to bag · €{620 * qty},00</button>
          </div>

          {/* meta */}
          <ul style={{ listStyle:'none', padding:0, margin:`${S[3]}px 0 0`, borderTop:`1px solid ${T.n200}` }}>
            {['Polished aluminium body','Hand-cast hardware','Edition of 200, numbered','Free EU shipping'].map(x => (
              <li key={x} style={{
                display:'flex', justifyContent:'space-between', padding:`${S[3]}px 0`,
                borderBottom:`1px solid ${T.n200}`, fontSize:13,
              }}>
                <span>{x}</span>
                <span className="mono" style={{ opacity:.4, fontSize:10, letterSpacing:'.18em' }}>✓</span>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Cart drawer */}
      <CartDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} items={bag}/>
    </div>
  );
};

const CartDrawer = ({ open, onClose, items }) => {
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <>
      <div onClick={onClose} style={{
        position:'absolute', inset:0,
        background:'rgba(10,10,10,.4)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: `opacity ${M.base.d}ms ${M.base.e}`,
        zIndex: Z.overlay,
      }}/>
      <aside style={{
        position:'absolute', top:0, right:0, bottom:0, width: 420,
        background:T.bone, borderLeft:`1px solid ${T.ink}`,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        transition: `transform ${M.spring.d}ms ${M.spring.e}`,
        zIndex: Z.drawer, display:'flex', flexDirection:'column',
      }}>
        <header style={{
          padding:`${S[5]}px ${S[5]}px`, borderBottom:`1px solid ${T.ink}`,
          display:'flex', justifyContent:'space-between', alignItems:'center',
        }}>
          <div className="mono" style={{ fontSize:11, letterSpacing:'.2em', textTransform:'uppercase' }}>YOUR BAG · {items.length}</div>
          <button onClick={onClose} style={{
            background:'none', border:'none', cursor:'pointer', fontSize:18,
          }}>✕</button>
        </header>
        <div style={{ flex:1, overflow:'auto', padding:S[5], display:'flex', flexDirection:'column', gap:S[4] }}>
          {items.length === 0 && (
            <div style={{ padding:`${S[8]}px 0`, textAlign:'center', color:T.n500 }}>
              <div style={{ fontWeight:900, fontSize:24, letterSpacing:'-0.02em', color:T.ink }}>Bag is empty.</div>
              <div className="mono" style={{ marginTop:S[3], fontSize:11, letterSpacing:'.18em', opacity:.6 }}>NOTHING HERE YET</div>
            </div>
          )}
          {items.map((it, i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'80px 1fr', gap:S[3], paddingBottom:S[4], borderBottom:`1px solid ${T.n200}` }}>
              <div style={{ aspectRatio:'1', background:`linear-gradient(135deg, ${T.chrome}, ${T.n400})` }}/>
              <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
                <div style={{ fontWeight:700, fontSize:14 }}>{it.name}</div>
                <div className="mono" style={{ fontSize:10, letterSpacing:'.18em', textTransform:'uppercase', opacity:.55 }}>
                  {it.variant} · {it.size} · QTY {it.qty}
                </div>
                <div style={{ marginTop:'auto', display:'flex', justifyContent:'space-between' }}>
                  <a href="#" className="mono" style={{ fontSize:10, letterSpacing:'.18em', color:T.n500 }}>REMOVE</a>
                  <span style={{ fontWeight:900, fontSize:14 }}>€{it.price * it.qty},00</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <footer style={{ padding:S[5], borderTop:`1px solid ${T.ink}`, background:T.paper }}>
            <div style={{ display:'flex', justifyContent:'space-between', marginBottom:S[3] }}>
              <span className="mono" style={{ fontSize:11, letterSpacing:'.18em', textTransform:'uppercase' }}>SUBTOTAL</span>
              <span style={{ fontWeight:900, fontSize:18 }}>€{total},00</span>
            </div>
            <button style={{
              width:'100%', height:56, background:T.ink, color:T.bone,
              border:`1px solid ${T.ink}`, fontFamily:'inherit', fontWeight:700, fontSize:15, cursor:'pointer',
              letterSpacing:'.02em',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = T.neon; e.currentTarget.style.color = T.ink; }}
            onMouseLeave={e => { e.currentTarget.style.background = T.ink; e.currentTarget.style.color = T.bone; }}
            >Checkout →</button>
          </footer>
        )}
      </aside>
    </>
  );
};

const DropHero = () => {
  const [t, setT] = React.useState({ d:2, h:14, m:32, s:11 });
  React.useEffect(() => {
    const x = setInterval(() => {
      setT(p => {
        let { d, h, m, s } = p;
        s--; if (s < 0) { s = 59; m--; }
        if (m < 0) { m = 59; h--; }
        if (h < 0) { h = 23; d--; }
        return { d, h, m, s };
      });
    }, 1000);
    return () => clearInterval(x);
  }, []);
  const pad = n => String(n).padStart(2, '0');
  return (
    <div style={{ background:T.ink, color:T.bone, padding:S[8], border:`1px solid ${T.ink}`, position:'relative', overflow:'hidden' }}>
      <div className="mono" style={{ fontSize:11, letterSpacing:'.2em', textTransform:'uppercase', color:T.neon, marginBottom:S[5] }}>
        ● DROP 02 · FW26 · GOES LIVE NOV 14, 18:00 CET
      </div>
      <h1 style={{ fontWeight:900, fontSize:120, letterSpacing:'-0.045em', lineHeight:.92, margin:0, position:'relative' }}>
        <span style={{ position:'relative', display:'inline-block' }}>
          <span aria-hidden style={{
            position:'absolute', left:'-0.04em', right:'-0.04em',
            top:'55%', height:'50%', background:T.neon, zIndex:0,
          }}/>
          <span style={{ position:'relative', zIndex:1 }}>Hand-fed.</span>
        </span>
      </h1>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4, auto) 1fr', gap:S[5], alignItems:'baseline', marginTop:S[7] }}>
        {[['DAYS', t.d], ['HRS', t.h], ['MIN', t.m], ['SEC', t.s]].map(([l, v]) => (
          <div key={l}>
            <div style={{ fontWeight:900, fontSize:64, letterSpacing:'-0.03em', lineHeight:1, fontVariantNumeric:'tabular-nums' }}>{pad(v)}</div>
            <div className="mono" style={{ fontSize:10, letterSpacing:'.2em', opacity:.55, marginTop:S[2] }}>{l}</div>
          </div>
        ))}
        <button style={{
          justifySelf:'end', alignSelf:'end',
          height:56, padding:`0 ${S[5]}px`,
          background:T.neon, color:T.ink, border:`1px solid ${T.neon}`,
          fontFamily:'inherit', fontWeight:700, fontSize:15, letterSpacing:'.02em', cursor:'pointer',
        }}>Get notified →</button>
      </div>
    </div>
  );
};

const Lookbook = () => {
  const ref = React.useRef(null);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const rect = ref.current.getBoundingClientRect();
      const vh = window.innerHeight;
      // 0 when entering bottom of viewport, 1 when leaving top
      const p = 1 - (rect.top + rect.height / 2) / vh;
      setProgress(Math.max(-1, Math.min(1, p)));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const tiles = [
    { c:'span 3', r:'span 3', bg:`linear-gradient(135deg, ${T.chrome}, ${T.n400})`, label:'01 · LOOP', depth: 0.3 },
    { c:'span 3', r:'span 2', bg:`linear-gradient(160deg, #e8e6e0, #6a6864)`,        label:'02 · CAST BELT', depth: -0.2 },
    { c:'span 2', r:'span 1', bg:T.ink, label:'03 · STUDIO', light:true, depth: 0.5 },
    { c:'span 1', r:'span 2', bg:T.neon, label:'04', neon:true, depth: -0.4 },
    { c:'span 2', r:'span 2', bg:`linear-gradient(135deg, #2a2a2a, #0a0a0a)`,        label:'05 · FRINGE', light:true, depth: 0.25 },
    { c:'span 4', r:'span 1', bg:T.bone2, label:'06 · ARCHIVE', depth: -0.15 },
  ];

  return (
    <div ref={ref} style={{ border:`1px solid ${T.ink}`, background:T.bone, overflow:'hidden' }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gridAutoRows:'120px', gap:0 }}>
        {tiles.map((tile, i) => (
          <div key={i} style={{
            gridColumn: tile.c, gridRow: tile.r,
            color: tile.light ? T.bone : T.ink,
            position:'relative', cursor:'pointer', overflow:'hidden',
            borderRight:`1px solid ${T.ink}`, borderBottom:`1px solid ${T.ink}`,
          }}>
            {/* parallax layer */}
            <div aria-hidden style={{
              position:'absolute', inset: '-20% -2%',
              background: tile.bg,
              transform: `translateY(${progress * tile.depth * 80}px)`,
              transition: 'transform 60ms linear',
              willChange: 'transform',
            }}/>
            <div style={{
              position:'relative', height:'100%', padding:S[4],
              display:'flex', flexDirection:'column', justifyContent:'space-between',
            }}>
              <span className="mono" style={{ fontSize:10, letterSpacing:'.18em', textTransform:'uppercase' }}>{tile.label}</span>
              {!tile.neon && (
                <span style={{ fontWeight:900, fontSize:32, letterSpacing:'-0.03em', alignSelf:'flex-end' }}>→</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const Patterns = () => (
  <Section no="04" title="Patterns" kicker="interactive · click around">
    <Sub no="4.1" title="PDP · click size, color, add to bag">
      <PDPInteractive/>
      <Note>↳ Color/size selection · live total · cart drawer slides in (spring 480ms)</Note>
    </Sub>
    <Sub no="4.2" title="Drop hero · live countdown">
      <DropHero/>
      <Note>↳ Used on landing during a drop window · neon bar metaphor scaled to display size</Note>
    </Sub>
    <Sub no="4.3" title="Lookbook tile grid">
      <Lookbook/>
      <Note>↳ Editorial mosaic · mix of imagery, ink panels, single neon accent tile</Note>
    </Sub>
  </Section>
);

Object.assign(window, { Patterns });
