/* global React, Icon */
const { useState: useStateGal, useEffect: useEffectGal } = React;

const PHOTOS = [
  { src: 'uploads/IMG_4286.png', title: 'Cedar Deck Restoration',    location: 'St. Catharines' },
  { src: 'uploads/IMG_4285.png', title: 'Premium Stain Finish',       location: 'Niagara Falls' },
  { src: 'uploads/IMG_4294.png', title: 'Weathered Wood Revival',     location: 'Welland' },
  { src: 'uploads/IMG_4308.png', title: 'Deck & Fence Package',       location: 'Niagara-on-the-Lake' },
  { src: 'uploads/IMG_4305.png', title: 'Residential Deck Stain',     location: 'Pelham' },
  { src: 'uploads/IMG_4303.png', title: 'Wood Restoration',           location: 'Fort Erie' },
  { src: 'uploads/IMG_4301.png', title: 'Professional Finish',        location: 'Thorold' },
  { src: 'uploads/IMG_4306.png', title: 'Deck Renewal',               location: 'Fonthill' },
  { src: 'uploads/IMG_4298.png', title: 'Premium Restoration',        location: 'Grimsby' },
  { src: 'uploads/IMG_4296.png', title: 'Quality Craftsmanship',      location: 'Hamilton' },
  { src: 'uploads/IMG_2945.PNG', title: 'Wood Refinishing',           location: 'Burlington' },
  { src: 'uploads/IMG_2944.PNG', title: 'Expert Restoration',         location: 'Oakville' },
  { src: 'uploads/IMG_2943.PNG', title: 'Master Craftsmanship',       location: 'Port Colborne' },
];

function GalleryCard({ photo, onClick, view }) {
  const isMasonry = view === 'masonry';
  return (
    <div
      style={galCardStyles.card}
      onClick={onClick}
      role="button"
      tabIndex={0}
      onKeyDown={e => e.key === 'Enter' && onClick()}
    >
      <div style={isMasonry ? galCardStyles.imgWrapNatural : galCardStyles.imgWrap}>
        <img
          src={photo.src}
          alt={photo.title}
          style={isMasonry ? galCardStyles.imgNatural : galCardStyles.img}
          loading="lazy"
        />
      </div>
      <div style={galCardStyles.info}>
        <div style={galCardStyles.title}>{photo.title}</div>
        <div style={galCardStyles.location}>
          <Icon name="mapPin" size={12} color="var(--ink-500)" />
          <span>{photo.location}</span>
        </div>
      </div>
    </div>
  );
}

const galCardStyles = {
  card: {
    background: 'var(--paper)',
    border: '1px solid var(--border)',
    borderRadius: 18,
    overflow: 'hidden',
    boxShadow: 'var(--shadow-sm)',
    cursor: 'pointer',
    transition: 'transform var(--transition-base), box-shadow var(--transition-base)',
  },
  imgWrap: { aspectRatio: '4/3', overflow: 'hidden', position: 'relative' },
  img: {
    width: '100%', height: '100%',
    objectFit: 'cover', display: 'block',
    transition: 'transform 0.4s cubic-bezier(.2,.6,.2,1)',
  },
  imgWrapNatural: { overflow: 'hidden' },
  imgNatural: { width: '100%', height: 'auto', display: 'block' },
  info: {
    padding: '14px 18px',
    display: 'flex', flexDirection: 'column', gap: 5,
  },
  title: {
    fontFamily: 'var(--font-display)', fontSize: 15.5, fontWeight: 700,
    color: 'var(--ink-900)',
  },
  location: {
    display: 'flex', alignItems: 'center', gap: 5,
    fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-500)',
  },
};

function Gallery() {
  const [view, setView] = useStateGal('grid');
  const [lightbox, setLightbox] = useStateGal(null);

  useEffectGal(() => {
    if (lightbox === null) return;
    const handler = (e) => {
      if (e.key === 'Escape') setLightbox(null);
      if (e.key === 'ArrowRight') setLightbox(i => (i + 1) % PHOTOS.length);
      if (e.key === 'ArrowLeft') setLightbox(i => (i - 1 + PHOTOS.length) % PHOTOS.length);
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [lightbox]);

  // Lock body scroll when lightbox open
  useEffectGal(() => {
    document.body.style.overflow = lightbox !== null ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [lightbox]);

  const views = [
    { id: 'grid',     label: 'Grid' },
    { id: 'masonry',  label: 'Masonry' },
    { id: 'carousel', label: 'Carousel' },
  ];

  return (
    <>
      <section id="work" style={galStyles.wrap}>
        <div style={galStyles.inner}>

          {/* Section header */}
          <div style={galStyles.header}>
            <div>
              <div className="ds-eyebrow" style={{ marginBottom: 10 }}>OUR WORK</div>
              <h2 style={galStyles.h2}>Recent Projects</h2>
            </div>
            <div style={galStyles.toggle}>
              {views.map(v => (
                <button
                  key={v.id}
                  onClick={() => setView(v.id)}
                  style={{
                    ...galStyles.toggleBtn,
                    ...(view === v.id ? galStyles.toggleBtnActive : {}),
                  }}
                >
                  {v.label}
                </button>
              ))}
            </div>
          </div>

          {/* Grid */}
          {view === 'grid' && (
            <div style={galStyles.grid}>
              {PHOTOS.map((p, i) => (
                <GalleryCard key={p.src} photo={p} view="grid" onClick={() => setLightbox(i)} />
              ))}
            </div>
          )}

          {/* Masonry */}
          {view === 'masonry' && (
            <div style={galStyles.masonry}>
              {PHOTOS.map((p, i) => (
                <div key={p.src} style={{ breakInside: 'avoid', marginBottom: 20 }}>
                  <GalleryCard photo={p} view="masonry" onClick={() => setLightbox(i)} />
                </div>
              ))}
            </div>
          )}

          {/* Carousel */}
          {view === 'carousel' && (
            <div style={galStyles.carousel}>
              {PHOTOS.map((p, i) => (
                <div key={p.src} style={galStyles.carouselSlide}>
                  <GalleryCard photo={p} view="carousel" onClick={() => setLightbox(i)} />
                </div>
              ))}
            </div>
          )}

        </div>
      </section>

      {/* Lightbox */}
      {lightbox !== null && (
        <div style={lbStyles.overlay} onClick={() => setLightbox(null)}>
          {/* Close */}
          <button
            style={lbStyles.closeBtn}
            onClick={() => setLightbox(null)}
            aria-label="Close"
          >
            <Icon name="close" size={20} color="#fff" />
          </button>

          {/* Prev */}
          <button
            style={{ ...lbStyles.navBtn, left: 20 }}
            onClick={e => { e.stopPropagation(); setLightbox(i => (i - 1 + PHOTOS.length) % PHOTOS.length); }}
            aria-label="Previous"
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
          </button>

          {/* Image */}
          <div style={lbStyles.imgWrap} onClick={e => e.stopPropagation()}>
            <img
              src={PHOTOS[lightbox].src}
              alt={PHOTOS[lightbox].title}
              style={lbStyles.img}
            />
          </div>

          {/* Caption */}
          <div style={lbStyles.caption}>
            <strong>{PHOTOS[lightbox].title}</strong>
            <span style={{ margin: '0 8px', opacity: 0.45 }}>·</span>
            <span>{PHOTOS[lightbox].location}</span>
            <span style={{ marginLeft: 16, opacity: 0.5, fontSize: 12 }}>
              {lightbox + 1} / {PHOTOS.length}
            </span>
          </div>

          {/* Next */}
          <button
            style={{ ...lbStyles.navBtn, right: 20 }}
            onClick={e => { e.stopPropagation(); setLightbox(i => (i + 1) % PHOTOS.length); }}
            aria-label="Next"
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>
        </div>
      )}
    </>
  );
}

const galStyles = {
  wrap: {
    background: 'var(--cream)', padding: '96px 0',
    borderTop: '1px solid var(--border)',
  },
  inner: { maxWidth: 'var(--container)', margin: '0 auto', padding: '0 32px' },
  header: {
    display: 'flex', justifyContent: 'space-between',
    alignItems: 'flex-end', marginBottom: 40,
    flexWrap: 'wrap', gap: 16,
  },
  h2: {
    fontFamily: 'var(--font-display)', fontWeight: 700,
    fontSize: 'clamp(2rem, 3.6vw, 3rem)', lineHeight: 1.1,
    letterSpacing: '-0.02em', color: 'var(--ink-900)', margin: 0,
  },
  toggle: { display: 'flex', gap: 8 },
  toggleBtn: {
    padding: '9px 20px',
    border: '1px solid var(--border-strong)',
    background: 'var(--paper)',
    borderRadius: 10,
    fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600,
    color: 'var(--ink-700)', cursor: 'pointer',
    transition: 'all var(--transition-fast)',
  },
  toggleBtnActive: {
    background: 'var(--forest-700)',
    color: '#fff',
    borderColor: 'var(--forest-700)',
  },
  grid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
    gap: 20,
  },
  masonry: {
    columnCount: 3,
    columnGap: 20,
  },
  carousel: {
    display: 'flex', gap: 20,
    overflowX: 'auto',
    scrollSnapType: 'x mandatory',
    paddingBottom: 12,
    scrollbarWidth: 'thin',
    scrollbarColor: 'var(--ink-300) transparent',
  },
  carouselSlide: {
    flexShrink: 0, width: 360,
    scrollSnapAlign: 'start',
  },
};

const lbStyles = {
  overlay: {
    position: 'fixed', inset: 0,
    background: 'rgba(14,11,8,0.96)',
    zIndex: 200,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  },
  closeBtn: {
    position: 'absolute', top: 20, right: 20,
    background: 'rgba(255,255,255,0.12)',
    border: '1px solid rgba(255,255,255,0.18)',
    borderRadius: '50%', width: 44, height: 44,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', zIndex: 201,
  },
  navBtn: {
    position: 'absolute', top: '50%',
    transform: 'translateY(-50%)',
    background: 'rgba(255,255,255,0.12)',
    border: '1px solid rgba(255,255,255,0.18)',
    borderRadius: '50%', width: 52, height: 52,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', zIndex: 201,
  },
  imgWrap: {
    maxWidth: '84vw', maxHeight: '82vh',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  },
  img: {
    maxWidth: '84vw', maxHeight: '78vh',
    objectFit: 'contain',
    borderRadius: 14,
    boxShadow: '0 40px 80px rgba(0,0,0,0.6)',
    display: 'block',
  },
  caption: {
    position: 'absolute', bottom: 28,
    left: '50%', transform: 'translateX(-50%)',
    background: 'rgba(20,17,13,0.75)', backdropFilter: 'blur(10px)',
    color: '#fff', padding: '8px 20px', borderRadius: 999,
    fontFamily: 'var(--font-body)', fontSize: 13.5,
    whiteSpace: 'nowrap', display: 'flex', alignItems: 'center',
  },
};

window.Gallery = Gallery;
