/* Danex Roofing — recent work gallery. Mosaic grid: wide feature tiles
   alternate with standard tiles for a less uniform rhythm.
   "View Gallery" opens a full-screen carousel over every real job photo. */
function Gallery() {
  const { Eyebrow, Badge, Button } = DS;
  const jobs = [
    { id: 'job1', label: 'Torch-On Flat Roof', place: 'Burnaby', tag: 'Flat', span: 1, photo: 'assets/photos/roof-03.jpg' },
    { id: 'job2', label: 'Laminate Shingle Re-Roof', place: 'Surrey', tag: 'Sloped', span: 1, photo: 'assets/photos/roof-05.jpg' },
    { id: 'job3', label: 'Architectural Shingle Roof', place: 'Coquitlam', tag: 'Sloped', span: 1, photo: 'assets/photos/roof-10.jpg' },
    { id: 'job4', label: 'Cedar Shingle Re-Roof', place: 'Mission', tag: 'Cedar', span: 1, photo: 'assets/photos/roof-21.jpg' },
    { id: 'job5', label: 'Commercial Flat Roof', place: 'Downtown Vancouver', tag: 'Commercial', span: 1, photo: 'assets/photos/roof-04.jpg', hideMobile: true },
    { id: 'job6', label: 'SBS Flat Roof', place: 'Vancouver', tag: 'Flat', span: 1, photo: 'assets/photos/roof-07.jpg', hideMobile: true },
  ];

  // all job photos (assets/photos/roof-NN.jpg) — shown in the carousel
  const photos = Array.from({ length: 22 }, (_, i) =>
    'assets/photos/roof-' + String(i + 1).padStart(2, '0') + '.jpg')
    .filter((src) => !src.endsWith('roof-11.jpg')); // removed: was Danny's portrait, not a job

  const [open, setOpen] = React.useState(false);
  const [idx, setIdx] = React.useState(0);
  const count = photos.length;
  const go = (n) => setIdx((i) => (i + n + count) % count);

  // redraw Lucide icons inside the modal, lock scroll + keyboard nav while open
  React.useEffect(() => {
    if (!open) return;
    if (window.lucide) window.lucide.createIcons();
    const onKey = (e) => {
      if (e.key === 'Escape') setOpen(false);
      else if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
    };
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener('keydown', onKey);
    };
  }, [open, count]);

  // pointer-events:none so a click on the swapped-in Lucide SVG still hits the button
  const icon = (name, size) => (
    <i data-lucide={name} style={{ width: size, height: size, pointerEvents: 'none' }}></i>
  );

  const navBtn = {
    width: 48, height: 48, borderRadius: 'var(--radius-full)', border: 'none', cursor: 'pointer',
    background: 'var(--surface-raised)', color: 'var(--text-strong)', boxShadow: 'var(--shadow-lg)',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
  };

  return (
    <section id="work" style={{ background: 'var(--surface-base)', padding: 'var(--section-y) 0' }}>
      <style>{`
        .dx-job-tile { transition: box-shadow var(--dur-base) var(--ease-out), transform var(--dur-base) var(--ease-out); }
        .dx-job-tile img { transition: transform var(--dur-slow, 0.5s) var(--ease-out); }
        .dx-job-tile:hover, .dx-job-tile:focus-visible { transform: translateY(-4px); box-shadow: var(--shadow-xl); outline: none; }
        .dx-job-tile:hover img, .dx-job-tile:focus-visible img { transform: scale(1.06); }
        .dx-job-zoom {
          position: absolute; top: 14px; right: 14px; width: 38px; height: 38px;
          display: inline-flex; align-items: center; justify-content: center;
          border-radius: var(--radius-full); background: rgba(15,17,21,0.55); color: var(--paper-100);
          backdrop-filter: blur(4px); opacity: 0; transform: scale(0.85);
          transition: opacity var(--dur-base) var(--ease-out), transform var(--dur-base) var(--ease-out);
          pointer-events: none; z-index: 2;
        }
        .dx-job-tile:hover .dx-job-zoom, .dx-job-tile:focus-visible .dx-job-zoom { opacity: 1; transform: scale(1); }
        @media (prefers-reduced-motion: reduce) {
          .dx-job-tile, .dx-job-tile img, .dx-job-zoom { transition: none; }
          .dx-job-tile:hover img, .dx-job-tile:focus-visible img { transform: none; }
        }
      `}</style>
      <div className="dx-container">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
          <div style={{ maxWidth: 560 }}>
            <Eyebrow>Recent Work</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 'clamp(2.25rem,4vw,3.25rem)', lineHeight: 0.98, margin: '14px 0 0', fontWeight: 800 }}>
              Roofs We're Proud Of
            </h2>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 22, marginTop: 44 }} className="dx-gallery-grid">
          {jobs.map((j) => (
            <figure key={j.id} className={'dx-job-tile' + (j.hideMobile ? ' dx-hide-mobile' : '')} role="button" tabIndex={0}
              aria-label={'Open ' + j.label + ' in gallery'}
              onClick={() => { setIdx(Math.max(0, photos.indexOf(j.photo))); setOpen(true); }}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setIdx(Math.max(0, photos.indexOf(j.photo))); setOpen(true); } }}
              style={{
                margin: 0, position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden',
                boxShadow: 'var(--shadow-md)', gridColumn: 'span ' + j.span, cursor: 'pointer',
              }}>
              <img src={j.photo} alt={j.label + ', ' + j.place} loading="lazy"
                style={{ width: '100%', height: 310, display: 'block', objectFit: 'cover' }} />
              <span className="dx-job-zoom" aria-hidden="true">{icon('maximize-2', 18)}</span>
              <figcaption style={{
                position: 'absolute', left: 0, right: 0, bottom: 0,
                background: 'linear-gradient(to top, rgba(15,17,21,0.9) 10%, rgba(15,17,21,0) 100%)',
                padding: '40px 20px 18px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12,
              }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontWeight: 700, fontSize: 20, color: 'var(--paper-100)', lineHeight: 1 }}>{j.label}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--slate-300)', fontSize: 13, marginTop: 7 }}>
                    <i data-lucide="map-pin" style={{ width: 13, height: 13 }}></i>{j.place}
                  </div>
                </div>
                <Badge variant="accent" size="sm">{j.tag}</Badge>
              </figcaption>
            </figure>
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 36 }}>
          <Button variant="outline" size="md" onClick={() => { setIdx(0); setOpen(true); }}
            iconLeft={icon('images', 18)}>
            View Gallery ({count} Photos)
          </Button>
        </div>
      </div>

      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(15,17,21,0.88)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
        }}>
          <div onClick={(e) => e.stopPropagation()} style={{
            position: 'relative', width: 'min(1040px, 100%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
          }}>
            <button onClick={() => setOpen(false)} aria-label="Close gallery" style={{
              position: 'absolute', top: -52, right: 0, width: 44, height: 44, cursor: 'pointer',
              borderRadius: 'var(--radius-full)', border: '1px solid rgba(255,255,255,0.22)',
              background: 'rgba(255,255,255,0.08)', color: 'var(--paper-100)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {icon('x', 20)}
            </button>

            <div style={{ display: 'flex', alignItems: 'center', gap: 18, width: '100%' }}>
              <button onClick={() => go(-1)} aria-label="Previous photo" style={navBtn}>
                {icon('chevron-left', 24)}
              </button>

              <figure style={{
                margin: 0, flex: 1, position: 'relative', borderRadius: 'var(--radius-lg)',
                overflow: 'hidden', boxShadow: 'var(--shadow-xl)', background: 'var(--slate-900)',
                height: 'min(64vh, 600px)',
              }}>
                <img src={photos[idx]} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
                <span style={{
                  position: 'absolute', right: 14, bottom: 12, padding: '4px 10px', fontFamily: 'var(--font-sans)',
                  fontWeight: 700, fontSize: 12.5, color: 'var(--paper-100)', background: 'rgba(15,17,21,0.6)',
                  border: '1px solid rgba(255,255,255,0.16)', borderRadius: 'var(--radius-full)',
                }}>{idx + 1} / {count}</span>
              </figure>

              <button onClick={() => go(1)} aria-label="Next photo" style={navBtn}>
                {icon('chevron-right', 24)}
              </button>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', justifyContent: 'center', maxWidth: 720 }}>
              {photos.map((src, i) => (
                <button key={i} onClick={() => setIdx(i)} aria-label={'Photo ' + (i + 1)} style={{
                  width: 54, height: 40, padding: 0, cursor: 'pointer', overflow: 'hidden',
                  borderRadius: 'var(--radius-sm)', flexShrink: 0,
                  border: i === idx ? '2px solid var(--accent)' : '2px solid transparent',
                  opacity: i === idx ? 1 : 0.55, transition: 'opacity var(--dur-fast) var(--ease-out)',
                }}>
                  <img src={src} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', pointerEvents: 'none' }} />
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

window.Gallery = Gallery;
