// GalleryPage.jsx — ovens in real homes, restaurants and resorts. Filter chips + lightbox.
(function () {
  const { useState, useEffect, useCallback } = React;
  const { GALLERY } = window.TF_DATA;

  const CATEGORIES = ['All', 'Restaurants', 'Homes', 'Resorts'];

  function Lightbox({ items, index, onClose, onIndex }) {
    const item = items[index];
    const prev = useCallback(() => onIndex((index - 1 + items.length) % items.length), [index, items.length, onIndex]);
    const next = useCallback(() => onIndex((index + 1) % items.length), [index, items.length, onIndex]);

    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);
      const prevOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; };
    }, [prev, next, onClose]);

    if (!item) return null;
    const navBtn = {
      width: 52, height: 52, borderRadius: '50%', flex: 'none', cursor: 'pointer',
      display: 'grid', placeItems: 'center', color: '#F6ECDD',
      background: 'rgba(40,27,17,.55)', border: '1px solid rgba(246,236,221,.22)',
      backdropFilter: 'blur(6px)', transition: 'all .22s cubic-bezier(.2,.7,.3,1)',
    };
    return (
      <div onClick={onClose} data-section="ember"
        style={{ position: 'fixed', inset: 0, zIndex: 90, background: 'rgba(16,11,6,.92)', backdropFilter: 'blur(8px)', display: 'grid', gridTemplateRows: 'auto 1fr auto', padding: 'clamp(16px,3vw,32px)' }}>
        <div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
          <span className="tf-small" style={{ color: '#A2917C', letterSpacing: '.04em' }}>{String(index + 1).padStart(2, '0')} / {String(items.length).padStart(2, '0')}</span>
          <button aria-label="Close" onClick={onClose} style={{ ...navBtn, width: 44, height: 44 }}><Icon name="x" size={20} /></button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 'clamp(10px,2vw,28px)', minHeight: 0, paddingBlock: 'clamp(12px,2vw,24px)' }}>
          <button aria-label="Previous" className="tf-lb-nav" onClick={(e) => { e.stopPropagation(); prev(); }} style={navBtn}><Icon name="arrowLeft" size={22} /></button>
          <figure onClick={(e) => e.stopPropagation()} style={{ margin: 0, display: 'flex', flexDirection: 'column', minHeight: 0, maxHeight: '100%', maxWidth: 'min(1000px, 80vw)', flex: '1 1 auto' }}>
            <Photo tone={item.tone} label={`${item.oven} · ${item.place}`} icon={item.icon}
              style={{ width: '100%', aspectRatio: '16/10', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-glow)' }} />
            <figcaption style={{ marginTop: 18, textAlign: 'center' }}>
              <div className="tf-h3" style={{ color: '#FBF3E6', fontSize: '1.4rem', margin: 0 }}>{item.caption}</div>
              <div className="tf-small" style={{ color: '#A2917C', marginTop: 6 }}>
                <span style={{ color: 'var(--tf-flame)' }}>{item.oven}</span> · {item.place}
              </div>
            </figcaption>
          </figure>
          <button aria-label="Next" className="tf-lb-nav" onClick={(e) => { e.stopPropagation(); next(); }} style={navBtn}><Icon name="arrowRight" size={22} /></button>
        </div>
        <div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', gap: 10, justifyContent: 'center', overflowX: 'auto', paddingTop: 6 }}>
          {items.map((it, i) => (
            <button key={it.id} onClick={() => onIndex(i)} aria-label={it.caption}
              style={{ padding: 0, border: 0, background: 'none', cursor: 'pointer', flex: 'none', borderRadius: 'var(--r-sm)', outline: i === index ? '2px solid var(--tf-flame)' : '2px solid transparent', outlineOffset: 2, opacity: i === index ? 1 : .5, transition: 'opacity .2s' }}>
              <Photo tone={it.tone} label="" icon={it.icon} grain={false} style={{ width: 64, height: 44, borderRadius: 'var(--r-sm)' }} />
            </button>
          ))}
        </div>
      </div>
    );
  }

  function Tile({ item, onOpen }) {
    return (
      <button className="tf-gtile tf-reveal" onClick={onOpen} aria-label={`Open ${item.caption}`}>
        <Photo tone={item.tone} label={`${item.oven} · ${item.place}`} icon={item.icon}
          style={{ width: '100%', aspectRatio: '4/3', borderRadius: 0, border: 0 }} />
        <span className="tf-gtile__scrim" />
        <span className="tf-gtile__meta">
          <span className="tf-gtile__cap">{item.caption}</span>
          <span className="tf-gtile__place"><Icon name="mapPin" size={13} /> {item.place}</span>
        </span>
        <span className="tf-gtile__expand"><Icon name="arrowUpRight" size={16} /></span>
      </button>
    );
  }

  function GalleryPage({ go }) {
    const root = useReveal();
    const [filter, setFilter] = useState('All');
    const [lb, setLb] = useState(-1);

    const items = filter === 'All' ? GALLERY : GALLERY.filter((g) => g.category === filter);

    return (
      <div ref={root}>
        {/* hero */}
        <section data-section="ember" style={{ position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(70% 90% at 50% -10%, rgba(232,122,62,.28), transparent 60%)' }} />
          <div className="tf-wrap" style={{ position: 'relative', paddingTop: 'clamp(120px,14vw,150px)', paddingBottom: 'clamp(48px,7vw,96px)', textAlign: 'center', maxWidth: 860 }}>
            <Eyebrow style={{ justifyContent: 'center' }}>The gallery</Eyebrow>
            <h1 className="tf-display" style={{ color: '#FBF3E6', margin: '6px 0 0', fontSize: 'clamp(2.6rem,5vw,5rem)' }}>Fires that found a <span style={{ fontStyle: 'italic', color: 'var(--tf-flame)' }}>home</span>.</h1>
            <p className="tf-lead" style={{ color: '#D8C6AE', maxWidth: 540, margin: '22px auto 0' }}>Every oven we build goes somewhere real — a family home, a restaurant, a resort kitchen. Here are a few of the fires our customers have lit.</p>
          </div>
        </section>

        {/* filter + grid */}
        <section className="tf-section--tight tf-section">
          <div className="tf-wrap">
            <div className="tf-gfilter" role="tablist" aria-label="Filter gallery">
              {CATEGORIES.map((c) => {
                const count = c === 'All' ? GALLERY.length : GALLERY.filter((g) => g.category === c).length;
                const on = filter === c;
                return (
                  <button key={c} role="tab" aria-selected={on} onClick={() => setFilter(c)}
                    className={'tf-chip' + (on ? ' is-on' : '')}>
                    {c}<span className="tf-chip__n">{count}</span>
                  </button>
                );
              })}
            </div>
            <div className="tf-ggrid">
              {items.map((item) => (
                <Tile key={item.id} item={item} onOpen={() => setLb(GALLERY.indexOf(item))} />
              ))}
            </div>
          </div>
        </section>

        {/* closing CTA */}
        <section className="tf-section" data-section="ember" style={{ position: 'relative', overflow: 'hidden', textAlign: 'center' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(60% 80% at 50% 120%, rgba(232,122,62,.4), transparent 65%)' }} />
          <div className="tf-wrap tf-wrap--narrow" style={{ position: 'relative' }}>
            <h2 className="tf-h1" style={{ color: '#FBF3E6', margin: 0 }}>Picture your own fire.</h2>
            <p className="tf-lead" style={{ color: '#D8C6AE', maxWidth: 460, margin: '18px auto 0' }}>Tell us where it will live — home, restaurant, or resort. We'll help you choose the right oven and get it there.</p>
            <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 32, flexWrap: 'wrap' }}>
              <TFButton variant="primary" size="lg" arrow onClick={() => go('contact')}>Get a quote</TFButton>
              <TFButton variant="outline" size="lg" onClick={() => go('product')} style={{ color: '#F6ECDD', borderColor: 'rgba(246,236,221,.4)' }}>Browse ovens</TFButton>
            </div>
          </div>
        </section>

        {lb >= 0 && (
          <Lightbox items={GALLERY} index={lb} onClose={() => setLb(-1)} onIndex={setLb} />
        )}
      </div>
    );
  }

  window.GalleryPage = GalleryPage;
})();
