// PROJECT DETAIL — full-screen overlay con galería + texto.
// Mantiene el sistema NOMEN: tipografía Oswald + Archivo, rojo NOMEN, page-no.
// Navegación: clicks en thumbs, ← / → entre imágenes, Esc para cerrar.

function ProjectDetail({ project, onClose, onNav }) {
  const [imgIdx, setImgIdx] = React.useState(0);
  const overlayRef = React.useRef(null);

  // Reset image when project changes
  React.useEffect(() => { setImgIdx(0); }, [project?.id]);

  // Lock body scroll while open
  React.useEffect(() => {
    if (!project) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [project]);

  // Keyboard navigation
  React.useEffect(() => {
    if (!project) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') {
        setImgIdx((i) => Math.min(project.gallery.length - 1, i + 1));
      } else if (e.key === 'ArrowLeft') {
        setImgIdx((i) => Math.max(0, i - 1));
      } else if (e.key === 'j' || e.key === 'J') {
        onNav && onNav(1);
      } else if (e.key === 'k' || e.key === 'K') {
        onNav && onNav(-1);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [project, onClose, onNav]);

  if (!project) return null;

  const p = project;
  const totalImg = p.gallery.length;
  const currentImg = p.gallery[imgIdx];

  // Split description by paragraphs for readable layout
  const paragraphs = (p.description || '').split('\n\n').filter(Boolean);

  return (
    <div
      ref={overlayRef}
      role="dialog"
      aria-modal="true"
      aria-label={`Proyecto ${p.title}`}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'var(--grey-paper)',
        overflowY: 'auto',
        animation: 'pd-fade .35s ease both'
      }}
    >
      <style>{`
        @keyframes pd-fade {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes pd-img-fade {
          from { opacity: 0; transform: scale(.985); }
          to   { opacity: 1; transform: scale(1); }
        }
        .pd-thumb {
          cursor: pointer;
          border: 1px solid rgba(10,10,10,.18);
          background: #fff;
          aspect-ratio: 4/5;
          overflow: hidden;
          position: relative;
          transition: border-color .2s, transform .3s;
        }
        .pd-thumb:hover { border-color: var(--ink); }
        .pd-thumb.active { border-color: var(--red); }
        .pd-thumb.active::after {
          content:""; position:absolute; inset: 0;
          box-shadow: inset 0 0 0 2px var(--red);
          pointer-events: none;
        }
        .pd-thumb img {
          width:100%; height:100%; object-fit: cover;
          transition: transform .5s ease;
        }
        .pd-thumb:hover img { transform: scale(1.06); }
        .pd-arrow {
          position: absolute; top: 50%; transform: translateY(-50%);
          width: 52px; height: 52px;
          display: grid; place-items: center;
          background: rgba(255,255,255,.92);
          border: 1px solid var(--ink);
          color: var(--ink);
          cursor: pointer;
          transition: background .2s, color .2s;
          font-family: var(--font-body);
          font-size: 18px;
          z-index: 4;
        }
        .pd-arrow:hover { background: var(--red); color: #fff; border-color: var(--red); }
        .pd-arrow:disabled { opacity: .3; cursor: not-allowed; pointer-events: none; }
        .pd-arrow.left { left: 16px; }
        .pd-arrow.right { right: 16px; }
        @media (max-width: 900px) {
          .pd-grid-main { grid-template-columns: 1fr !important; }
          .pd-side { position: static !important; }
        }
      `}</style>

      {/* Page number badge — like the rest of the site */}
      <span className="page-no" style={{ color: 'var(--ink)', mixBlendMode: 'normal' }}>
        FICHA · NMN-{p.id.toUpperCase()}
      </span>

      {/* Top bar */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 5,
        background: 'var(--grey-paper)',
        borderBottom: '1px solid var(--ink)',
        padding: '18px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 18
      }}>
        <span className="eyebrow" style={{ color: 'var(--red)', fontWeight: 600 }}>
          ARCHIVO / {p.cat}
        </span>
        <span className="eyebrow" style={{ opacity: .6 }}>
          {p.year} · {totalImg} {totalImg === 1 ? 'pieza' : 'piezas'}
        </span>
        <button
          onClick={onClose}
          aria-label="Cerrar ficha"
          style={{
            background: 'transparent',
            border: '1px solid var(--ink)',
            padding: '8px 14px',
            fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            fontWeight: 500, cursor: 'pointer',
            fontFamily: 'var(--font-body)',
            display: 'inline-flex', alignItems: 'center', gap: 8
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--ink)'; e.currentTarget.style.color = 'var(--grey-paper)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink)'; }}
        >
          <span aria-hidden>✕</span> Cerrar
        </button>
      </div>

      {/* Header / Title block */}
      <div style={{ padding: '60px 48px 40px', borderBottom: '1px solid rgba(10,10,10,.2)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 18, marginBottom: 18 }}>
          <span className="eyebrow" style={{ opacity: .55 }}>NMN-{p.id.toUpperCase()}</span>
          <span className="eyebrow" style={{ opacity: .55 }}>{p.subtitle}</span>
        </div>
        <h1 className="titular" style={{
          fontSize: 'clamp(48px, 9vw, 132px)',
          margin: 0,
          color: 'var(--ink)',
          lineHeight: 0.92,
          letterSpacing: '-0.02em'
        }}>
          {p.title}
        </h1>
        <div style={{
          marginTop: 28,
          display: 'flex', flexWrap: 'wrap', gap: 8
        }}>
          {p.tags.map((t, i) => (
            <span key={i} style={{
              fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', fontWeight: 600,
              border: '1px solid var(--ink)', padding: '5px 10px',
              background: 'transparent'
            }}>{t}</span>
          ))}
        </div>
      </div>

      {/* Hero image with arrows */}
      <div style={{
        position: 'relative',
        background: '#fff',
        borderBottom: '1px solid rgba(10,10,10,.2)',
        padding: '40px 48px'
      }}>
        <div style={{
          position: 'relative',
          width: '100%',
          maxWidth: 1280,
          margin: '0 auto',
          aspectRatio: '4 / 3',
          background: 'var(--grey-soft)',
          overflow: 'hidden'
        }}>
          <img
            key={imgIdx}
            src={imgUrl(p, currentImg)}
            alt={`${p.title} — imagen ${imgIdx + 1}`}
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%', objectFit: 'contain',
              background: '#fff',
              animation: 'pd-img-fade .4s ease both'
            }}
          />

          {/* Image counter */}
          <span style={{
            position: 'absolute', bottom: 14, right: 14,
            background: 'var(--ink)', color: '#fff',
            padding: '6px 10px',
            fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', fontWeight: 600
          }}>
            {String(imgIdx + 1).padStart(2,'0')} / {String(totalImg).padStart(2,'0')}
          </span>

          {/* Image ID */}
          <span style={{
            position: 'absolute', top: 14, left: 14,
            background: 'rgba(255,255,255,.92)', color: 'var(--ink)',
            padding: '5px 9px',
            fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', fontWeight: 600
          }}>
            NMN-{p.id.toUpperCase()}/{String(imgIdx + 1).padStart(2,'0')}
          </span>

          <button
            className="pd-arrow left"
            onClick={() => setImgIdx(i => Math.max(0, i - 1))}
            disabled={imgIdx === 0}
            aria-label="Imagen anterior"
          >←</button>
          <button
            className="pd-arrow right"
            onClick={() => setImgIdx(i => Math.min(totalImg - 1, i + 1))}
            disabled={imgIdx === totalImg - 1}
            aria-label="Imagen siguiente"
          >→</button>
        </div>
      </div>

      {/* Body: description + side meta */}
      <div className="pd-grid-main" style={{
        display: 'grid', gridTemplateColumns: '1fr 320px',
        gap: 56,
        padding: '70px 48px 40px',
        borderBottom: '1px solid rgba(10,10,10,.2)'
      }}>
        {/* Description */}
        <div>
          <span className="eyebrow" style={{ color: 'var(--red)', display: 'block', marginBottom: 18 }}>
            01 · Concepto
          </span>
          {paragraphs.length === 0 && (
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, opacity: .55 }}>
              Sin descripción extensa registrada para esta ficha.
            </p>
          )}
          {paragraphs.map((para, i) => (
            <p key={i} style={{
              fontFamily: 'var(--font-body)',
              fontSize: 17,
              lineHeight: 1.55,
              margin: '0 0 18px',
              color: 'var(--ink)',
              maxWidth: '62ch',
              textWrap: 'pretty'
            }}>
              {i === 0 && (
                <span style={{
                  display: 'inline-block',
                  width: 32, height: 1, background: 'var(--red)',
                  verticalAlign: 'middle', marginRight: 12
                }}/>
              )}
              {para}
            </p>
          ))}
        </div>

        {/* Side meta */}
        <aside className="pd-side" style={{ position: 'sticky', top: 100, alignSelf: 'start' }}>
          <span className="eyebrow" style={{ color: 'var(--red)', display: 'block', marginBottom: 18 }}>
            02 · Ficha técnica
          </span>
          <dl style={{ margin: 0 }}>
            {[
              ['Año', p.year],
              ['Categoría', p.cat],
              ['Cliente', p.client],
              ['Subtítulo', p.subtitle],
              ['Piezas', `${totalImg} imágenes`],
              ['ID', `NMN-${p.id.toUpperCase()}`]
            ].map(([k, v], i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '90px 1fr',
                gap: 12,
                padding: '11px 0',
                borderTop: i === 0 ? '1px solid var(--ink)' : '1px solid rgba(10,10,10,.15)'
              }}>
                <dt style={{
                  fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
                  fontWeight: 600, opacity: .6
                }}>{k}</dt>
                <dd style={{ margin: 0, fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.4 }}>
                  {v}
                </dd>
              </div>
            ))}
          </dl>
        </aside>
      </div>

      {/* Gallery thumbs */}
      <div style={{ padding: '60px 48px 40px', borderBottom: '1px solid rgba(10,10,10,.2)' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          alignItems: 'baseline', marginBottom: 22, flexWrap: 'wrap', gap: 10
        }}>
          <span className="eyebrow" style={{ color: 'var(--red)' }}>
            03 · Galería completa
          </span>
          <span className="eyebrow" style={{ opacity: .5 }}>
            click para ver · ← → para navegar
          </span>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
          gap: 12
        }}>
          {p.gallery.map((g, i) => (
            <button
              key={i}
              className={'pd-thumb' + (i === imgIdx ? ' active' : '')}
              onClick={() => {
                setImgIdx(i);
                window.scrollTo({ top: 0, behavior: 'smooth' });
              }}
              style={{ padding: 0 }}
              aria-label={`Ver imagen ${i + 1}`}
            >
              <img src={imgUrl(p, g)} alt="" loading="lazy" />
              <span style={{
                position: 'absolute', bottom: 6, left: 6,
                background: 'rgba(255,255,255,.92)', color: 'var(--ink)',
                padding: '2px 6px',
                fontSize: 9, letterSpacing: '0.2em', fontWeight: 600
              }}>
                {String(i + 1).padStart(2,'0')}
              </span>
            </button>
          ))}
        </div>
      </div>

      {/* Footer / nav between projects */}
      <div style={{
        padding: '40px 48px 80px',
        display: 'flex', justifyContent: 'space-between',
        alignItems: 'center', flexWrap: 'wrap', gap: 18
      }}>
        <button
          onClick={() => onNav && onNav(-1)}
          style={{
            background: 'transparent', border: 'none',
            fontFamily: 'var(--font-body)',
            fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            fontWeight: 500, cursor: 'pointer', padding: 0,
            display: 'inline-flex', alignItems: 'center', gap: 10,
            color: 'var(--ink)'
          }}
          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--red)'}
          onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ink)'}
        >
          ← Ficha anterior
        </button>

        <button
          onClick={onClose}
          className="btn btn-red"
          style={{ background: 'var(--red)', color: '#fff', borderColor: 'var(--red)' }}
        >
          Volver al archivo
        </button>

        <button
          onClick={() => onNav && onNav(1)}
          style={{
            background: 'transparent', border: 'none',
            fontFamily: 'var(--font-body)',
            fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            fontWeight: 500, cursor: 'pointer', padding: 0,
            display: 'inline-flex', alignItems: 'center', gap: 10,
            color: 'var(--ink)'
          }}
          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--red)'}
          onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ink)'}
        >
          Ficha siguiente →
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ProjectDetail });
