const GALLERY_ITEMS = [
  { img: "assets/arlington-01.jpg",    city: "Arlington",    tall: false },
  { img: "assets/arlington-03.jpg",    city: "Arlington",    tall: false },
  { img: "assets/arlington-04.jpg",    city: "Arlington",    tall: false },
  { img: "assets/mukilteo-01.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/mukilteo-02.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/mukilteo-03.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/mukilteo-04.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/mukilteo-05.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/mukilteo-06.jpg",     city: "Mukilteo",     tall: false },
  { img: "assets/lakestevens-01.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/lakestevens-02.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/lakestevens-03.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/lakestevens-04.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/lakestevens-05.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/lakestevens-06.jpg",  city: "Lake Stevens", tall: false },
  { img: "assets/snohomish-01.jpg",    city: "Snohomish",   tall: false },
  { img: "assets/snohomish-02.jpg",    city: "Snohomish",   tall: false },
  { img: "assets/snohomish-03.jpg",    city: "Snohomish",   tall: false },
  { img: "assets/snohomish-04.jpg",    city: "Snohomish",   tall: false },
  { img: "assets/snohomish-05.jpg",    city: "Snohomish",   tall: false },
  { img: "assets/snohomish-06.jpg",    city: "Snohomish",   tall: false },
];

function GalleryLightbox({ items, index, onClose, onIndex }) {
  const item = items[index];
  const total = items.length;

  const prev = React.useCallback(() => onIndex((index - 1 + total) % total), [index, total, onIndex]);
  const next = React.useCallback(() => onIndex((index + 1) % total), [index, total, onIndex]);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft') prev();
      else if (e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, prev, next]);

  return ReactDOM.createPortal(
    <div className="lb-backdrop" onClick={onClose} role="dialog" aria-modal="true" aria-label="Project gallery">
      <button className="lb-close" onClick={onClose} aria-label="Close">
        <Ic.close size={20} />
      </button>

      <button className="lb-nav lb-nav--prev" onClick={(e) => { e.stopPropagation(); prev(); }} aria-label="Previous">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
      </button>
      <button className="lb-nav lb-nav--next" onClick={(e) => { e.stopPropagation(); next(); }} aria-label="Next">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
      </button>

      <div className="lb-stage" onClick={(e) => e.stopPropagation()}>
        <div className="lb-media">
          <img src={item.img} alt={`${item.city} kitchen remodel`} className="lb-image" />
        </div>

        <div className="lb-caption">
          <div className="lb-caption-main">
            <div className="lb-caption-title">{item.city} Residence</div>
            <div className="lb-caption-meta">Full kitchen remodel</div>
          </div>
          <div className="lb-counter">{index + 1} / {total}</div>
        </div>
      </div>
    </div>,
    document.body
  );
}

function Gallery({ tweaks, onCTA }) {
  const [filter, setFilter] = React.useState("All");
  const cities = ["All", "Arlington", "Mukilteo", "Lake Stevens", "Snohomish"];
  const allTiles = filter === "All" ? GALLERY_ITEMS : GALLERY_ITEMS.filter(t => t.city === filter);
  // For "All": interleave one photo per city, up to 8 total
  const tiles = (() => {
    if (filter !== "All") return allTiles;
    const cities = ["Arlington", "Mukilteo", "Lake Stevens", "Snohomish"];
    const byCity = {};
    cities.forEach(c => { byCity[c] = GALLERY_ITEMS.filter(t => t.city === c); });
    const result = [];
    let i = 0;
    while (result.length < 8) {
      const city = cities[i % cities.length];
      const idx = Math.floor(i / cities.length);
      if (byCity[city][idx]) result.push(byCity[city][idx]);
      i++;
      if (i > 100) break;
    }
    return result.slice(0, 8);
  })();
  const [lbIndex, setLbIndex] = React.useState(null);

  return (
    <section className="section" id="gallery">
      <div className="container">
        <div className="gallery-intro">
          <span className="eyebrow">Project Gallery</span>
          <h2 className="h2" style={{marginTop:16}}>250+ kitchens built across <em>Greater Seattle.</em></h2>
          <p className="lead gallery-sub">Hear from homeowners and see the transformations — before demo starts to the day we hand over the keys.</p>
        </div>

        <VideoTestimonial />

        <div className="gallery-tabs-row">
          <div className="gallery-tabs" role="tablist">
            {cities.map(c => (
              <button key={c} className={"gallery-tab " + (filter === c ? "is-active" : "")} onClick={() => { setFilter(c); }}>
                {c}
              </button>
            ))}
          </div>
        </div>

        <div className="masonry">
          {tiles.map((t, i) => (
            <div
              className="tile"
              key={i}
              style={{aspectRatio: t.tall ? "3/4" : "4/3"}}
              onClick={() => setLbIndex(i)}
            >
              <img src={t.img} alt={`${t.city} ${t.style} kitchen remodel`} style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}} />
              <div className="tile-meta">
                <span className="c">{t.city}</span>
              </div>
            </div>
          ))}
        </div>

        <div style={{display:'flex', justifyContent:'center', marginTop:48}}>
          <button className="btn btn-primary btn-lg" onClick={onCTA}>
            Get Free Estimate &amp; Offer <Ic.arrow />
          </button>
        </div>
      </div>

      {lbIndex !== null && (
        <GalleryLightbox
          items={tiles}
          index={lbIndex}
          onIndex={setLbIndex}
          onClose={() => setLbIndex(null)}
        />
      )}
    </section>
  );
}
window.Gallery = Gallery;
