
const PLACEMENTS = [
  { col:1,  row:1,  cs:4, rs:6 },   // 0: cols 1-4,  rows 1-6
  { col:6,  row:2,  cs:3, rs:3 },   // 1: cols 6-8,  rows 2-4
  { col:9,  row:1,  cs:4, rs:3 },   // 2: cols 9-12, rows 1-3
  { col:10, row:5,  cs:3, rs:5 },   // 3: cols 10-12, rows 5-9
  { col:6,  row:6,  cs:3, rs:3 },   // 4: cols 6-8,  rows 6-8
  { col:1,  row:8,  cs:4, rs:3 },   // 5: cols 1-4,  rows 8-10
  { col:1,  row:12, cs:3, rs:5 },   // 6: cols 1-3,  rows 12-16
  { col:5,  row:10, cs:3, rs:3 },   // 7: cols 5-7,  rows 10-12
  { col:9,  row:10, cs:4, rs:3 },   // 8: cols 9-12, rows 10-12
  { col:4,  row:13, cs:8, rs:4 },   // 9: cols 4-11, rows 13-16
];

function GalleriaItem({ item, idx, placement, onOpen }){
  const [ref, inView] = useInView({threshold:.1});
  const [pRef, pY] = useParallax(.3 + (idx%3)*.15);
  const tilt = (idx % 2 ? 1 : -1) * (0.8 + (idx%3)*0.4);
  const tints = ['warm','deep','red','warm','none','deep','warm','red','warm','deep'];
  return (
    <div ref={ref} style={{
      gridColumn: `${placement.col} / span ${placement.cs}`,
      gridRow: `${placement.row} / span ${placement.rs}`,
      position:'relative',
    }}>
      <div ref={pRef} onClick={() => onOpen(idx)} className={`reveal reveal-slow ${inView?'in':''}`} style={{
        position:'relative', width:'100%', height:'100%', cursor:'pointer',
        transform:`translateY(${pY}px) rotate(${tilt}deg)`,
        boxShadow:'0 40px 70px -30px rgba(0,0,0,.7)', overflow:'hidden',
        transition:'transform .6s cubic-bezier(.2,.6,.2,1), box-shadow .4s',
        transitionDelay: `${(idx%4)*.1}s`,
      }}
      onMouseEnter={(e) => e.currentTarget.style.transform = `translateY(${pY}px) rotate(0deg) scale(1.03)`}
      onMouseLeave={(e) => e.currentTarget.style.transform = `translateY(${pY}px) rotate(${tilt}deg) scale(1)`}>
        <Photo src={PHOTOS[item.photo_key]} tint={tints[idx]} index={idx+1}/>
      </div>
    </div>
  );
}

function Lightbox({ idx, onClose, onNav }){
  const { t } = useLang();
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onNav(1);
      if (e.key === 'ArrowLeft') onNav(-1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, onNav]);

  if (idx == null) return null;
  const item = CONFIG.galleria[idx];
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:10000, background:'rgba(5,3,2,.97)', backdropFilter:'blur(10px)',
      display:'flex', alignItems:'center', justifyContent:'center', padding:'6vh 6vw',
      animation:'fadeUp .3s ease',
    }}>
      <button onClick={(e) => { e.stopPropagation(); onClose(); }} className="italiana" style={{
        position:'absolute', top:24, right:24, background:'transparent', border:'1px solid rgba(244,237,216,.3)',
        color:'var(--cream)', padding:'8px 14px', fontSize:10,
        letterSpacing:3, textTransform:'uppercase', cursor:'pointer',
      }}>{t('galleria.lightbox_close')}</button>

      <button onClick={(e) => { e.stopPropagation(); onNav(-1); }} style={{
        position:'absolute', left:24, top:'50%', background:'transparent', border:'none', color:'var(--cream)',
        fontSize:48, cursor:'pointer', opacity:.7, fontFamily:'Fraunces,serif', fontStyle:'italic',
      }}>‹</button>
      <button onClick={(e) => { e.stopPropagation(); onNav(1); }} style={{
        position:'absolute', right:24, top:'50%', background:'transparent', border:'none', color:'var(--cream)',
        fontSize:48, cursor:'pointer', opacity:.7, fontFamily:'Fraunces,serif', fontStyle:'italic',
      }}>›</button>

      <div onClick={(e) => e.stopPropagation()} style={{maxWidth:'74vw', maxHeight:'82vh', aspectRatio:'3/4', boxShadow:'0 60px 120px -30px rgba(0,0,0,.9)'}}>
        <Photo src={PHOTOS[item.photo_key]} tint="warm" index={idx+1}/>
      </div>

      <div style={{position:'absolute', bottom:40, left:0, right:0, textAlign:'center', color:'var(--cream)'}}>
        <div className="script" style={{fontSize:40, marginBottom:8, color:'var(--passion)'}}>{t(`galleria.captions.${item.photo_key}`)}</div>
        <div className="italiana" style={{fontSize:11, letterSpacing:4, opacity:.6}}>
          · {String(idx+1).padStart(2,'0')} / {CONFIG.galleria.length} ·
        </div>
      </div>
    </div>
  );
}

function Galleria(){
  const { t } = useLang();
  const [ref, inView] = useInView({threshold:.05});
  const y = useScrollY();
  const isMobile = useIsMobile();
  const [open, setOpen] = React.useState(null);
  const onNav = (d) => setOpen(i => (i+d+CONFIG.galleria.length) % CONFIG.galleria.length);

  return (
    <section ref={ref} data-screen-label="05 Galleria" style={{
      position:'relative', background:'var(--ink)', color:'var(--cream)',
      padding:'20vh 4vw 16vh', overflow:'hidden',
    }}>
      <div style={{position:'absolute', top:'6vh', left:0, right:0, overflow:'hidden', pointerEvents:'none', opacity:.09}}>
        <div className="script" style={{
          fontSize:'clamp(160px, 24vw, 380px)', whiteSpace:'nowrap', display:'inline-block',
          animation:'marquee 50s linear infinite', color:'var(--passion)',
        }}>
          {Array(6).fill(null).map((_, i) => `${t('galleria.marquee_word')} · `).join('')}&nbsp;
        </div>
      </div>

      <div style={{position:'relative', zIndex:2, maxWidth:1600, margin:'0 auto'}}>
        <div className={`reveal ${inView?'in':''}`} style={{display:'flex', alignItems:'baseline', gap:20, marginBottom:30}}>
          <div style={{width:60, height:1, background:'var(--cream)', opacity:.4}}/>
          <span className="italiana" style={{fontSize:11, letterSpacing:5, opacity:.65}}>
            {t('galleria.section_label')}
          </span>
        </div>
        <DecodeText
          tag="h2" className="display"
          text={t('galleria.title')}
          endPct={60}
          style={{
            fontSize:'clamp(56px, 9vw, 160px)', lineHeight:.88, fontWeight:200, letterSpacing:'-.04em',
            fontStyle:'italic', fontVariationSettings:'"SOFT" 100',
            marginBottom:20,
          }}
        />
        <p className={`reveal ${inView?'in':''} cormorant`} style={{fontSize:18, opacity:.7, maxWidth:560, marginBottom:90, transitionDelay:'.2s', lineHeight:1.6, fontStyle:'italic'}}>
          {t('galleria.desc')}
        </p>

        {isMobile ? (
          // Layout a colonna singola su mobile
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {CONFIG.galleria.map((item, i) => (
              <div key={i} onClick={() => setOpen(i)} style={{cursor:'pointer', width:'100%', aspectRatio:'4/3', overflow:'hidden'}}>
                <Photo src={PHOTOS[item.photo_key]} tint={['warm','deep','red','warm','none','deep','warm','red','warm','deep'][i]} index={i+1}/>
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            display:'grid', gridTemplateColumns:'repeat(12, 1fr)',
            gridAutoRows:'clamp(40px, 5vw, 80px)', gap:'clamp(10px, 1.2vw, 20px)',
          }}>
            {CONFIG.galleria.map((item, i) => (
              <GalleriaItem key={i} item={item} idx={i} placement={PLACEMENTS[i]} onOpen={setOpen}/>
            ))}
          </div>
        )}
      </div>

      <Lightbox idx={open} onClose={() => setOpen(null)} onNav={onNav}/>
    </section>
  );
}

window.Galleria = Galleria;
