// Project detail modal with gallery placeholder

function PlaceholderArt({ caption, aspect = '16/9', tag = 'DRAWING', src }) {
  // Try to pull image from localStorage (from Project Editor uploads) via data-lookup key
  const [resolved, setResolved] = React.useState(src);
  React.useEffect(() => {
    if (src) { setResolved(src); return; }
    if (!caption) return;
    try {
      const raw = localStorage.getItem('proj_editor_data');
      if (!raw) return;
      const data = JSON.parse(raw);
      for (const k of Object.keys(data)) {
        const found = (data[k].drawings || []).find(d => d && d.caption === caption && d.dataUrl);
        if (found) { setResolved(found.dataUrl); break; }
      }
    } catch {}
  }, [src, caption]);

  return (
    <div style={{ width: '100%' }}>
      <div className="ph-art" data-tag={tag} style={{ aspectRatio: aspect, width: '100%', position: 'relative', overflow: 'hidden' }}>
        {resolved && <img src={resolved} alt={caption} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', background: 'var(--bg)' }} />}
      </div>
      {caption && (
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-muted)', marginTop: 6, paddingLeft: 2, letterSpacing: '0.04em' }}>
          {caption}
        </div>
      )}
    </div>
  );
}

function ProjectModal({ project, onClose }) {
  const [activeIdx, setActiveIdx] = React.useState(0);

  React.useEffect(() => {
    if (!project) return;
    document.body.classList.add('modal-open');
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight' && project.gallery) setActiveIdx(i => Math.min(i + 1, project.gallery.length - 1));
      if (e.key === 'ArrowLeft') setActiveIdx(i => Math.max(i - 1, 0));
    };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.classList.remove('modal-open');
      window.removeEventListener('keydown', onKey);
    };
  }, [project, onClose]);

  React.useEffect(() => { setActiveIdx(0); }, [project]);

  if (!project) return null;

  const gallery = project.gallery || [];
  const active = gallery[activeIdx];

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-shell" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>

        {/* Header strip */}
        <div style={{
          padding: '22px 32px 18px',
          borderBottom: '1px solid var(--line)',
          display: 'grid',
          gridTemplateColumns: '1fr auto',
          gap: 24,
          alignItems: 'end',
        }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.12em', marginBottom: 8 }}>
              // PROJECT DOSSIER
            </div>
            <div className="serif" style={{ fontSize: 32, lineHeight: 1.1, letterSpacing: '-0.01em', marginBottom: 8, paddingRight: 40 }}>
              {project.name}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
              {project.client} · {project.year}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono faint" style={{ fontSize: 9, marginBottom: 4 }}>VALUE</div>
            <div className="serif" style={{ fontSize: 24, color: 'var(--ink)' }}>{project.value}</div>
            <div className="mono faint" style={{ fontSize: 10, marginTop: 4 }}>SCOPE · {project.scope}</div>
          </div>
        </div>

        {/* Gallery + meta grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 0 }} className="grid-2">
          {/* Left: gallery or confidential */}
          <div style={{ padding: '20px 24px 20px 32px', borderRight: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.12em' }}>
                DRAWINGS
              </span>
              {gallery.length > 0 && (
                <span className="mono faint" style={{ fontSize: 10 }}>
                  {String(activeIdx + 1).padStart(2, '0')} / {String(gallery.length).padStart(2, '0')}
                </span>
              )}
            </div>

            {gallery.length > 0 && active ? (
              <>
                <PlaceholderArt
                  caption={active.caption}
                  aspect={active.aspect}
                  src={active.src}
                  tag={`EXHIBIT-${String(activeIdx + 1).padStart(2, '0')}`}
                />
                {gallery.length > 1 && (
                  <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                    {gallery.map((g, i) => (
                      <button
                        key={i}
                        onClick={() => setActiveIdx(i)}
                        style={{
                          width: 52, height: 36,
                          background: i === activeIdx ? 'var(--ink)' : 'var(--bg-elevated)',
                          border: '1px solid ' + (i === activeIdx ? 'var(--ink)' : 'var(--line)'),
                          color: i === activeIdx ? 'var(--bg)' : 'var(--ink-muted)',
                          fontFamily: 'var(--font-mono)',
                          fontSize: 10,
                          cursor: 'pointer',
                          borderRadius: 3,
                          transition: 'all 0.15s',
                        }}
                      >{String(i + 1).padStart(2, '0')}</button>
                    ))}
                  </div>
                )}
              </>
            ) : (
              <div style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 8,
                padding: '44px 20px',
                border: '1px solid var(--line)',
                borderRadius: 'var(--radius)',
                background: 'var(--bg-elevated)',
                minHeight: 160,
                textAlign: 'center',
              }}>
                <div className="mono" style={{
                  fontSize: 10,
                  color: 'var(--ink-muted)',
                  letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  padding: '5px 14px',
                  border: '1px solid var(--line-strong)',
                  borderRadius: 3,
                  background: 'var(--bg)',
                }}>Confidential</div>
              </div>
            )}
          </div>

          {/* Right: meta */}
          <div style={{ padding: '20px 32px 20px 24px' }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.12em', marginBottom: 12 }}>
              BRIEF
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink)', marginBottom: 20 }}>
              {project.summary}
            </p>

            <div style={{
              padding: '10px 12px',
              background: 'var(--bg-elevated)',
              borderLeft: '2px solid var(--accent)',
              fontSize: 12.5,
              lineHeight: 1.5,
              marginBottom: 20,
            }}>
              <div className="mono" style={{ fontSize: 9, color: 'var(--accent)', marginBottom: 4 }}>OUTCOME</div>
              {project.outcome}
            </div>

            {project.role && (
              <div style={{ marginBottom: 16 }}>
                <div className="mono faint" style={{ fontSize: 10, marginBottom: 4 }}>ROLE</div>
                <div style={{ fontSize: 13 }}>{project.role}</div>
              </div>
            )}

            {project.deliverables && (
              <div style={{ marginBottom: 16 }}>
                <div className="mono faint" style={{ fontSize: 10, marginBottom: 6 }}>DELIVERABLES</div>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                  {project.deliverables.map((d, i) => (
                    <li key={i} style={{
                      fontSize: 12.5,
                      padding: '3px 0',
                      paddingLeft: 14,
                      position: 'relative',
                      color: 'var(--ink)',
                    }}>
                      <span style={{
                        position: 'absolute', left: 0, top: 3,
                        color: 'var(--accent)',
                        fontFamily: 'var(--font-mono)',
                        fontSize: 10,
                      }}>→</span>
                      {d}
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {project.tools && (
              <div style={{ marginBottom: 16 }}>
                <div className="mono faint" style={{ fontSize: 10, marginBottom: 6 }}>TOOLS</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {project.tools.map(t => (
                    <span key={t} className="mono" style={{
                      fontSize: 10,
                      padding: '2px 7px',
                      background: 'var(--paper-tint)',
                      border: '1px solid var(--line)',
                      borderRadius: 3,
                      color: 'var(--ink-muted)',
                    }}>{t}</span>
                  ))}
                </div>
              </div>
            )}

            <div>
              <div className="mono faint" style={{ fontSize: 10, marginBottom: 6 }}>SYSTEMS</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {project.systems.map(s => (
                  <span key={s} className="mono" style={{
                    fontSize: 10,
                    padding: '2px 7px',
                    border: '1px solid var(--line-strong)',
                    borderRadius: 3,
                    color: 'var(--ink)',
                  }}>{s}</span>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: '14px 32px',
          borderTop: '1px solid var(--line)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          fontFamily: 'var(--font-mono)',
          fontSize: 10,
          color: 'var(--ink-faint)',
          letterSpacing: '0.08em',
          textTransform: 'uppercase',
        }}>
          <span>DOC · PROJ-{String(project.year).slice(-2)}-{(project.name || '').split(' ').map(w=>w[0]).join('').slice(0,3).toUpperCase()}</span>
          <span>ESC TO CLOSE · ←/→ TO NAVIGATE</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProjectModal, PlaceholderArt });
