// 3B Printing — full Finish Gallery page.
function GalleryPage({ lang, setLang, route, cms }) {
  const { GalleryGrid, Lightbox, CTAButton } = window.Ds3BPrintingDesignSystem_6b9cdf;
  const { t, Header, SectionTitle, SiteFooter, LINE_HREF } = window.Shared;
  const galleryItemsAll = cms.galleryItemsAll;
  const footerContent = cms.sections.footer && cms.sections.footer.content;
  const s = t[lang];
  const paperOf = (i) => (lang === 'th' ? i.paperTh : i.paperEn);
  const finishesOf = (i) => (lang === 'th' ? i.finishesTh : i.finishesEn) || [];
  const paperTags = Array.from(new Set(galleryItemsAll.map(paperOf)));
  const finishTags = Array.from(new Set(galleryItemsAll.flatMap(finishesOf)));
  const [selectedPapers, setSelectedPapers] = React.useState(new Set());
  const [selectedFinishes, setSelectedFinishes] = React.useState(new Set());
  const [lightbox, setLightbox] = React.useState(null);
  const paperRef = React.useRef(null);
  const finishRef = React.useRef(null);

  const scrollToFocus = () => {
    // Accepts both link forms: #/gallery/finish (hash routing) and /gallery#finish (paths).
    const focus = window.location.hash.replace(/^#\/?(gallery\/?)?/, '');
    const target = focus === 'paper' ? paperRef.current : focus === 'finish' ? finishRef.current : null;
    if (target) {
      const top = target.getBoundingClientRect().top + window.scrollY - 110;
      window.scrollTo(0, top);
    }
  };
  React.useEffect(() => {
    scrollToFocus();
    window.addEventListener('hashchange', scrollToFocus);
    return () => window.removeEventListener('hashchange', scrollToFocus);
  }, []);
  const toggle = (setFn) => (tag) => {
    setFn((prev) => {
      const next = new Set(prev);
      if (next.has(tag)) next.delete(tag); else next.add(tag);
      return next;
    });
  };
  const items = galleryItemsAll.filter((i) =>
    (selectedPapers.size === 0 || selectedPapers.has(paperOf(i))) &&
    (selectedFinishes.size === 0 || finishesOf(i).some((f) => selectedFinishes.has(f)))
  );
  const section = { maxWidth: 1120, margin: '0 auto', padding: 'var(--space-9) var(--space-6) var(--space-9)' };

  const chipStyle = (active, goldWhenActive) => ({
    padding: '8px 18px', borderRadius: 'var(--radius-ui)', cursor: 'pointer',
    border: `1px solid ${active ? (goldWhenActive ? 'var(--accent-gold)' : 'var(--ink)') : 'var(--line)'}`,
    background: active ? (goldWhenActive ? 'var(--gold-gradient)' : 'var(--ink)') : 'transparent',
    color: active ? (goldWhenActive ? '#FFFFFF' : 'var(--bg-light)') : 'var(--ink-faint)',
    fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 500,
    transition: 'all var(--duration-standard) var(--ease-standard)',
  });

  const gallerySection = cms.sections.gallery_teaser;

  return (
    <div className="page-mobile-pad" style={{ background: 'var(--bg-light)', fontFamily: 'var(--font-body)', color: 'var(--ink)', minHeight: '100vh' }}>
      <Header lang={lang} setLang={setLang} route={route} footerContent={footerContent} />

      <window.EditSection type="gallery_teaser" id={gallerySection && gallerySection.id}>
      <section style={section}>
        <a href={window.Shared.url('/')} style={{ display: 'inline-block', marginBottom: 'var(--space-5)', color: 'var(--ink-faint)', textDecoration: 'none', fontSize: 14 }}>
          {s.backHome}
        </a>
        <SectionTitle lang={lang}>{s.galleryPageTitle}</SectionTitle>
        <p style={{
          margin: '0 0 var(--space-6)', maxWidth: 620, fontSize: 'var(--text-body-size)',
          lineHeight: lang === 'th' ? 'var(--leading-body-thai)' : 'var(--leading-body)', color: 'var(--ink-soft)',
        }}>{s.galleryPageSub}</p>

        <div style={{ marginBottom: 'var(--space-5)' }} ref={paperRef}>
          <div style={{ fontSize: 14, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 'var(--space-2)' }}>
            {s.filterPaper}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)' }}>
            <button onClick={() => setSelectedPapers(new Set())} style={chipStyle(selectedPapers.size === 0, false)}>{s.filterAll}</button>
            {paperTags.map((tag) => (
              <button key={tag} onClick={() => toggle(setSelectedPapers)(tag)} style={chipStyle(selectedPapers.has(tag), false)}>{tag}</button>
            ))}
          </div>
        </div>

        <div style={{ marginBottom: 'var(--space-6)' }} ref={finishRef}>
          <div style={{ fontSize: 14, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 'var(--space-2)' }}>
            {s.filterFinish}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)' }}>
            <button onClick={() => setSelectedFinishes(new Set())} style={chipStyle(selectedFinishes.size === 0, true)}>{s.filterAll}</button>
            {finishTags.map((tag) => (
              <button key={tag} onClick={() => toggle(setSelectedFinishes)(tag)} style={chipStyle(selectedFinishes.has(tag), true)}>{tag}</button>
            ))}
          </div>
        </div>

        <GalleryGrid items={items} columns={3} lang={lang} onSelect={(item, i) => {
          // In edit mode a tile click selects the row for the Inspector instead of opening the lightbox.
          if (window.EDIT_MODE) {
            window.postToHost({
              type: 'select',
              sectionId: gallerySection && gallerySection.id,
              sectionType: 'gallery_teaser',
              item: { table: 'gallery_items', id: item.id },
            });
          } else setLightbox(i);
        }} />
      </section>
      </window.EditSection>

      <SiteFooter lang={lang} footer={footerContent} />

      {lightbox !== null && (
        <Lightbox items={items} lang={lang} index={lightbox} onNavigate={setLightbox} onClose={() => setLightbox(null)} ctaHref={LINE_HREF} ctaLabel={s.cta} />
      )}
    </div>
  );
}

window.GalleryPage = GalleryPage;
