/* Project detail modal — fullscreen takeover with masonry gallery + lightbox */

function ProjectModal({ project, onClose }) {
  const open = !!project;

  // Keep last project in memory so the close animation can play with content
  const [last, setLast] = React.useState(project);
  const [lightbox, setLightbox] = React.useState(null);
  React.useEffect(() => {
    if (project) setLast(project);
    else setLightbox(null);
  }, [project]);
  const p = project || last;
  const images = (p && p.images) || [];
  const count = images.length;

  const lbRef = React.useRef(null);
  lbRef.current = lightbox;

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') {
        if (lbRef.current !== null) setLightbox(null);
        else onClose();
      } else if (lbRef.current !== null && count > 1 && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
        e.preventDefault();
        const dir = e.key === 'ArrowRight' ? 1 : -1;
        setLightbox(i => (i + dir + count) % count);
      }
    };
    window.addEventListener('keydown', onKey);
    document.body.classList.add('modal-open');
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.classList.remove('modal-open');
    };
  }, [open, onClose, count]);

  if (!p) return null;

  const lbImg = lightbox !== null ? images[lightbox] : null;

  return (
    <React.Fragment>
      <div className={`modal-backdrop ${open ? 'open' : ''}`} onClick={onClose}></div>
      <div className={`modal ${open ? 'open' : ''}`} style={{ '--m-grad': p.grad }}>
        <div className="modal-header">
          <div className="title-block">
            <div className="crumb">
              <span className="chip" style={{ '--chip-bg': 'rgba(0,0,0,0.05)' }}>{p.n} · {p.tag}</span>
              <span>{p.year}</span>
              {p.agency ? (
                p.agency.url ? (
                  <a
                    className="chip" href={p.agency.url} target="_blank" rel="noopener noreferrer"
                    style={{ '--chip-bg': 'rgba(0,0,0,0.85)', '--chip-c': '#fff' }}
                  >per {p.agency.name} ↗</a>
                ) : (
                  <span className="chip" style={{ '--chip-bg': 'rgba(0,0,0,0.85)', '--chip-c': '#fff' }}>
                    per {p.agency.name}
                  </span>
                )
              ) : null}
            </div>
            <h3>
              {p.name}<span className="accent">.</span>
            </h3>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Chiudi">✕</button>
        </div>

        <div className="modal-body">
          <div className="modal-body-inner">
            <div className="desc">
              <h4>Il progetto</h4>
              <p>{p.description}</p>
              {p.description2 ? <p>{p.description2}</p> : null}
              {count > 0 ? (
                <div className="desc-hint">⤢ Clicca uno screen per vederlo a tutto schermo</div>
              ) : null}
            </div>

            {count > 0 ? (
              <div className="gallery-col">
                <h4>Screen del progetto</h4>
                <div className="modal-gallery">
                  {images.map((img, i) => (
                    <button className="shot" key={img.id} onClick={() => setLightbox(i)} aria-label={`Apri screen ${i + 1} a tutto schermo`}>
                      <img src={img.url} alt={img.label || p.name} loading="lazy" />
                      <span className="zoom-hint">⤢</span>
                    </button>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
        </div>

        <div className="modal-footer">
          <div className="left">
            Vuoi un progetto simile? <a href="#contatti" onClick={() => { onClose(); setTimeout(() => { document.querySelector('#contatti')?.scrollIntoView({ behavior:'smooth' }); }, 350); }}>Scrivimi</a>
          </div>
          <div className="actions">
            <button className="btn-ghost" onClick={onClose}>Chiudi</button>
            <a className="btn-primary" href={p.url} target="_blank" rel="noopener noreferrer">
              Visita il sito <span className="arr">↗</span>
            </a>
          </div>
        </div>
      </div>

      {lbImg ? (
        <div className="lightbox" onClick={() => setLightbox(null)}>
          <img key={lightbox} src={lbImg.url} alt={lbImg.label || p.name} onClick={(e) => e.stopPropagation()} />
          {count > 1 ? (
            <React.Fragment>
              <button className="lb-nav lb-prev" onClick={(e) => { e.stopPropagation(); setLightbox((lightbox - 1 + count) % count); }} aria-label="Screen precedente">←</button>
              <button className="lb-nav lb-next" onClick={(e) => { e.stopPropagation(); setLightbox((lightbox + 1) % count); }} aria-label="Screen successivo">→</button>
            </React.Fragment>
          ) : null}
          <button className="lb-close" onClick={(e) => { e.stopPropagation(); setLightbox(null); }} aria-label="Chiudi anteprima">✕</button>
          <div className="lb-count">
            {lightbox + 1} / {count}{lbImg.label ? ` — ${lbImg.label}` : ''}
          </div>
          {count > 1 ? (
            <div style={{ display: 'none' }} aria-hidden="true">
              <img src={images[(lightbox + 1) % count].url} alt="" />
              <img src={images[(lightbox - 1 + count) % count].url} alt="" />
            </div>
          ) : null}
        </div>
      ) : null}
    </React.Fragment>
  );
}

Object.assign(window, { ProjectModal });
