/* portfolio.jsx — Image-heavy grid + lightbox modal */

const { useState: _useState, useEffect: _useEffect, useMemo: _useMemo } = React;

function PortfolioPage({ onNavigate, initialProject = null }) {
  const { t, lang } = useLang();
  const { PORTFOLIO, FILTERS } = window.JMC_DATA;
  const [filter, setFilter] = _useState('all');
  const [sort, setSort] = _useState('recent');
  const [openId, setOpenId] = _useState(initialProject);

  _useEffect(() => { if (initialProject) setOpenId(initialProject); }, [initialProject]);

  const filtered = _useMemo(() => {
    let list = filter === 'all' ? PORTFOLIO : PORTFOLIO.filter(p => p.type === filter);
    list = [...list];
    if (sort === 'recent') list.sort((a, b) => b.year - a.year);
    if (sort === 'capacity') list.sort((a, b) => {
      const num = s => parseFloat((s || '').replace(/[^\d.]/g, '')) || 0;
      return num(b.capacity) - num(a.capacity);
    });
    if (sort === 'alpha') list.sort((a, b) => a.name.localeCompare(b.name));
    return list;
  }, [filter, sort, PORTFOLIO]);

  const openProject = openId ? PORTFOLIO.find(p => p.id === openId) : null;

  return (
    <div className="dc-page-enter" data-screen-label="Portfolio">
      {/* Hero strip — full-bleed image */}
      <section style={{ position: 'relative', minHeight: 520,
                         padding: '160px 0 100px',
                         borderBottom: '1px solid var(--hairline)',
                         overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0,
                      backgroundImage: `url("${window.RES('assets/portfolio/bess-01.png')}")`,
                      backgroundSize: 'cover', backgroundPosition: 'center',
                      opacity: 0.55 }} />
        <div style={{ position: 'absolute', inset: 0,
                      background: 'linear-gradient(to bottom, rgba(10,10,10,0.85) 0%, rgba(10,10,10,0.55) 50%, var(--canvas) 100%)' }} />
        <div className="dc-container" style={{ position: 'relative' }}>
          <div className="dc-eyebrow" style={{ marginBottom: 24 }}>{t.portfolio.eyebrow}</div>
          <h1 style={{ fontSize: 'clamp(48px, 7vw, 96px)', fontWeight: 700, lineHeight: 0.98,
                        margin: 0, letterSpacing: '-1.5px', maxWidth: 1000 }}>
            {t.portfolio.title.map((l, i) => <span key={i} style={{ display: 'block' }}>{l}</span>)}
          </h1>
          <p style={{ fontSize: 18, fontWeight: 300, lineHeight: 1.6,
                       color: 'var(--body)', margin: '32px 0 0', maxWidth: 760 }}>
            {t.portfolio.sub}
          </p>
        </div>
      </section>

      {/* Filter + sort */}
      <section style={{ background: 'var(--canvas)', padding: '24px 0',
                         borderBottom: '1px solid var(--hairline)',
                         position: 'sticky', top: 104, zIndex: 10,
                         backdropFilter: 'blur(20px)',
                         backgroundColor: 'rgba(10,10,10,0.78)' }}>
        <div className="dc-container" style={{ display: 'flex',
                                                justifyContent: 'space-between',
                                                alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {FILTERS.map(f => (
              <button
                key={f.id}
                className={'dc-tag' + (filter === f.id ? ' active' : '')}
                onClick={() => setFilter(f.id)}
              >
                {t.portfolio.filters[f.labelKey]}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                            textTransform: 'uppercase', color: 'var(--muted)' }}>{t.portfolio.sort}</span>
            <select
              value={sort}
              onChange={e => setSort(e.target.value)}
              style={{ height: 36, fontSize: 11, fontWeight: 700, letterSpacing: '1.5px',
                       padding: '0 32px 0 12px', border: '1px solid var(--hairline-strong)',
                       background: 'transparent',
                       color: 'var(--ink)',
                       textTransform: 'uppercase', appearance: 'none',
                       fontFamily: 'inherit',
                       backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='none' stroke='%23ffffff' stroke-width='1.5' d='m1 1 5 5 5-5'/%3E%3C/svg%3E")`,
                       backgroundRepeat: 'no-repeat',
                       backgroundPosition: 'right 12px center' }}
            >
              <option value="recent" style={{background: '#111'}}>{t.portfolio.sortOptions.recent}</option>
              <option value="capacity" style={{background: '#111'}}>{t.portfolio.sortOptions.capacity}</option>
              <option value="alpha" style={{background: '#111'}}>{t.portfolio.sortOptions.alpha}</option>
            </select>
            <span style={{ fontSize: 11, color: 'var(--muted)', marginLeft: 8, letterSpacing: '1px' }}>
              {filtered.length} {t.portfolio.countOf} {PORTFOLIO.length}
            </span>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{ background: 'var(--canvas)', padding: '64px 0 96px' }}>
        <div className="dc-container">
          {filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--muted)' }}>
              {t.portfolio.empty}
            </div>
          ) : (
            <div className="dc-grid-3">
              {filtered.map((p, i) => (
                <DcReveal key={p.id} delay={(i % 3) * 60}>
                  <PortfolioCard project={p} onOpen={() => setOpenId(p.id)} />
                </DcReveal>
              ))}
            </div>
          )}
        </div>
      </section>

      <DcCTABand
        eyebrow={t.portfolio.ndaCta.eyebrow}
        title={t.portfolio.ndaCta.title}
        body={t.portfolio.ndaCta.body}
        primaryLabel={t.portfolio.ndaCta.primary}
        onPrimary={() => onNavigate('contact')}
        image="assets/portfolio/bess-03.png"
      />

      {openProject && (
        <PortfolioModal project={openProject}
                        onClose={() => setOpenId(null)}
                        onContact={() => { setOpenId(null); onNavigate('contact'); }} />
      )}
    </div>
  );
}

/* ─────────────────────── Card ───────────────────── */

function PortfolioCard({ project, onOpen }) {
  const { lang } = useLang();
  return (
    <article className="dc-card" onClick={onOpen}>
      <DcPhoto src={project.image} aspectRatio="4/3" tag={project.tag} tagAccent={!!project.tag} />
      <div className="dc-card-body">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                          textTransform: 'uppercase', color: 'var(--accent)' }}>
            {project.typeLabel[lang]}
          </span>
          <span style={{ fontSize: 12, color: 'var(--muted)', fontVariantNumeric: 'tabular-nums' }}>
            {project.year}
          </span>
        </div>
        <h3 style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.2, margin: '8px 0 0' }}>
          {project.name}
        </h3>
        <p style={{ fontSize: 14, fontWeight: 300, lineHeight: 1.55,
                     color: 'var(--body)', margin: '10px 0 0' }}>
          {project.summary[lang]}
        </p>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                       marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--hairline)' }}>
          <div style={{ display: 'flex', gap: 16, fontSize: 12, color: 'var(--muted)' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <DcIcon name="map" size={14} />
              {project.locationLabel[lang]}
            </span>
          </div>
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                          textTransform: 'uppercase', color: 'var(--accent)' }}>
            {lang === 'es' ? 'Ver' : 'View'} →
          </span>
        </div>
      </div>
    </article>
  );
}

/* ─────────────────────── Modal ───────────────────── */

function PortfolioModal({ project, onClose, onContact }) {
  const { t, lang } = useLang();
  const [imgIdx, setImgIdx] = _useState(0);
  const images = project.images || [project.image];

  _useEffect(() => {
    const onKey = e => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setImgIdx(i => (i + 1) % images.length);
      if (e.key === 'ArrowLeft') setImgIdx(i => (i - 1 + images.length) % images.length);
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose, images.length]);

  return (
    <div className="dc-modal-scrim" onClick={onClose}>
      <div className="dc-modal" onClick={e => e.stopPropagation()}>
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 20, right: 20, zIndex: 5,
            width: 44, height: 44,
            background: 'rgba(0,0,0,0.6)', border: '1px solid var(--hairline-strong)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', color: 'var(--ink)',
            backdropFilter: 'blur(10px)',
          }}
        >
          <DcIcon name="x" size={22} />
        </button>

        {/* Hero image */}
        <div style={{ position: 'relative', background: '#000' }}>
          <DcPhoto src={images[imgIdx]} aspectRatio="21/9"
                   caption={project.name + ' · ' + (imgIdx + 1) + '/' + images.length}
                   tag={project.tag || 'UE5 · Path Traced'}
                   tagAccent={!!project.tag} />
          {images.length > 1 && (
            <>
              <button onClick={() => setImgIdx((imgIdx - 1 + images.length) % images.length)}
                      style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                                width: 44, height: 44, background: 'rgba(0,0,0,0.6)',
                                border: '1px solid var(--hairline-strong)', color: 'var(--ink)',
                                cursor: 'pointer', display: 'flex', alignItems: 'center',
                                justifyContent: 'center', backdropFilter: 'blur(10px)' }}>
                <DcIcon name="chevronLeft" size={20} />
              </button>
              <button onClick={() => setImgIdx((imgIdx + 1) % images.length)}
                      style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)',
                                width: 44, height: 44, background: 'rgba(0,0,0,0.6)',
                                border: '1px solid var(--hairline-strong)', color: 'var(--ink)',
                                cursor: 'pointer', display: 'flex', alignItems: 'center',
                                justifyContent: 'center', backdropFilter: 'blur(10px)' }}>
                <DcIcon name="chevronRight" size={20} />
              </button>
            </>
          )}
        </div>

        {/* Thumb strip */}
        {images.length > 1 && (
          <div style={{ display: 'flex', gap: 8, padding: 16,
                         background: 'var(--surface-soft)',
                         borderBottom: '1px solid var(--hairline)' }}>
            {images.map((src, i) => {
              const vid = /\.(mp4|webm|mov)$/i.test(src);
              return (
                <button key={i} onClick={() => setImgIdx(i)}
                        style={{ flex: 1, aspectRatio: '16/10', position: 'relative',
                                  border: '2px solid ' + (i === imgIdx ? 'var(--accent)' : 'transparent'),
                                  background: vid ? '#000' : `url("${window.RES(src)}") center / cover`,
                                  cursor: 'pointer', padding: 0, overflow: 'hidden',
                                  opacity: i === imgIdx ? 1 : 0.6,
                                  transition: 'opacity 160ms' }}>
                  {vid && (
                    <>
                      <video src={window.RES(src)} muted playsInline preload="metadata"
                             style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                                      objectFit: 'cover' }} />
                      <span style={{ position: 'absolute', inset: 0, display: 'flex',
                                     alignItems: 'center', justifyContent: 'center',
                                     color: '#fff', background: 'rgba(0,0,0,0.25)' }}>
                        <DcIcon name="play" size={18} />
                      </span>
                    </>
                  )}
                </button>
              );
            })}
          </div>
        )}

        <div style={{ padding: 48 }}>
          <div className="dc-eyebrow">{project.typeLabel[lang]} · {project.year}</div>
          <h2 style={{ fontSize: 'clamp(32px, 4vw, 48px)', fontWeight: 700, lineHeight: 1.05,
                        margin: '16px 0 0', letterSpacing: '-0.5px' }}>{project.name}</h2>
          <p style={{ fontSize: 18, fontWeight: 300, lineHeight: 1.6,
                       color: 'var(--body)', margin: '24px 0 0', maxWidth: 760 }}>
            {project.summary[lang]}
          </p>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
                         margin: '40px 0',
                         borderTop: '1px solid var(--hairline)',
                         borderBottom: '1px solid var(--hairline)' }}>
            {[
              [t.portfolio.modal.client, project.clientLabel[lang]],
              [t.portfolio.modal.location, project.locationLabel[lang]],
              [t.portfolio.modal.capacity, project.capacity],
              [t.portfolio.modal.delivered, project.year],
            ].map(([k, v], i) => (
              <div key={k} style={{ padding: '24px',
                                     borderLeft: i === 0 ? 'none' : '1px solid var(--hairline)' }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                              textTransform: 'uppercase', color: 'var(--muted)' }}>{k}</div>
                <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink)', marginTop: 8 }}>
                  {v}
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginBottom: 40 }}>
            <h4 style={{ fontSize: 12, fontWeight: 700, letterSpacing: '2px',
                          textTransform: 'uppercase', color: 'var(--ink)', marginBottom: 16 }}>
              {t.portfolio.modal.deliverables}
            </h4>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {project.deliverables[lang].map(d => (
                <div key={d} style={{ display: 'flex', alignItems: 'center', gap: 14,
                                       padding: '14px 18px',
                                       background: 'var(--surface-soft)',
                                       border: '1px solid var(--hairline)' }}>
                  <DcIcon name="check" size={18} style={{ color: 'var(--accent)' }} />
                  <span style={{ fontSize: 14, fontWeight: 400, color: 'var(--body)' }}>{d}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 12 }}>
            <DcBtn onClick={onContact}>{t.portfolio.modal.primary}</DcBtn>
            <DcBtn variant="secondary" onClick={onClose}>{t.portfolio.modal.secondary}</DcBtn>
          </div>
        </div>
      </div>
    </div>
  );
}

window.PortfolioPage = PortfolioPage;
