/* ─── GRAPHIC DESIGN GALLERY ───
   Pieces come from window.GD_NEWSLETTER / window.GD_FLYERS (gd-data.js).
   Each has a baked-in `thumb` data URI and a sharper `full` file path;
   the lightbox falls back to the thumb if the file isn't deployed. */
const GDLightbox = ({ items, index, onClose, onStep }) => {
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onStep(1);
      if (e.key === 'ArrowLeft') onStep(-1);
    };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [onClose, onStep]);
  if (index == null) return null;
  const item = items[index];
  const fullSrc = (window.assetUrl ? window.assetUrl(item.full) : item.full);
  const arrow = (dir) => ({
    position: 'absolute', top: '50%', transform: 'translateY(-50%)',
    [dir < 0 ? 'left' : 'right']: 'clamp(12px, 4vw, 48px)',
    width: '48px', height: '48px', borderRadius: '50%', border: '1px solid rgba(255,255,255,0.25)',
    background: 'rgba(0,0,0,0.35)', color: '#fff', cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px', lineHeight: 1,
  });
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(10,10,10,0.94)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '5vh 8vw',
    }}>
      <img src={fullSrc} alt="" onClick={(e) => e.stopPropagation()}
        onError={(e) => { if (e.target.src !== item.thumb) e.target.src = item.thumb; }}
        style={{ maxWidth: '100%', maxHeight: '90vh', objectFit: 'contain', boxShadow: '0 30px 90px rgba(0,0,0,0.6)' }} />
      <button onClick={(e) => { e.stopPropagation(); onStep(-1); }} style={arrow(-1)} aria-label="Previous">‹</button>
      <button onClick={(e) => { e.stopPropagation(); onStep(1); }} style={arrow(1)} aria-label="Next">›</button>
      <button onClick={onClose} aria-label="Close" style={{
        position: 'absolute', top: 'clamp(12px, 3vw, 32px)', right: 'clamp(12px, 3vw, 32px)',
        width: '40px', height: '40px', borderRadius: '50%', border: '1px solid rgba(255,255,255,0.25)',
        background: 'rgba(0,0,0,0.35)', color: '#fff', cursor: 'pointer', fontSize: '16px',
      }}>✕</button>
      <div style={{
        position: 'absolute', bottom: 'clamp(12px, 3vw, 28px)', left: 0, right: 0, textAlign: 'center',
        color: 'rgba(255,255,255,0.55)', fontSize: '11px', letterSpacing: '0.14em',
      }}>{index + 1} / {items.length}</div>
    </div>,
    document.body
  );
};

const GDGroup = ({ label, count, items, onOpen }) => (
  <section style={{ marginBottom: '84px' }}>
    <header style={{ display: 'flex', alignItems: 'baseline', gap: '14px', marginBottom: '28px' }}>
      <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: '30px', fontWeight: 400, margin: 0 }}>{label}</h3>
      <span style={{ fontSize: '11px', letterSpacing: '0.16em', textTransform: 'uppercase', color: '#aaa' }}>
        {count} {count === 1 ? 'piece' : 'pieces'}
      </span>
    </header>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(200px, 100%), 1fr))', gap: '22px' }}>
      {items.map((it, i) => (
        <button key={i} onClick={() => onOpen(i)} style={{
          padding: 0, border: '1px solid #e6e6e6', background: '#f7f7f7', cursor: 'zoom-in',
          overflow: 'hidden', display: 'block', lineHeight: 0, transition: 'box-shadow 0.25s, transform 0.25s',
        }}
          onMouseEnter={(e) => { e.currentTarget.style.boxShadow = '0 14px 34px rgba(0,0,0,0.16)'; e.currentTarget.style.transform = 'translateY(-3px)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
          <img src={it.thumb} alt="" loading="lazy" style={{ width: '100%', height: 'auto', display: 'block' }} />
        </button>
      ))}
    </div>
  </section>
);

const GraphicDesign = () => {
  const groups = React.useMemo(() => [
    { label: 'Newsletter', items: window.GD_NEWSLETTER || [] },
    { label: 'Flyers', items: window.GD_FLYERS || [] },
  ].filter(g => g.items.length > 0), []);
  const [open, setOpen] = useState(null); // { group, index }

  const activeItems = open ? groups[open.group].items : [];
  const step = (d) => setOpen(o => o && ({ ...o, index: (o.index + d + activeItems.length) % activeItems.length }));

  if (groups.length === 0) {
    return <p style={{ fontSize: '15px', color: '#777', fontWeight: 300 }}>Design work coming soon.</p>;
  }
  return (
    <div>
      <p style={{ fontSize: '14px', lineHeight: 1.75, color: '#555', fontWeight: 300, maxWidth: '460px', marginBottom: '56px' }}>
        Editorial and print design — newsletter issues and event flyers. Click any piece to view it full size.
      </p>
      {groups.map((g, gi) => (
        <GDGroup key={g.label} label={g.label} count={g.items.length} items={g.items}
          onOpen={(i) => setOpen({ group: gi, index: i })} />
      ))}
      {open && (
        <GDLightbox items={activeItems} index={open.index} onClose={() => setOpen(null)} onStep={step} />
      )}
    </div>
  );
};

Object.assign(window, { GraphicDesign });
