/* global React */
// Explore Suffolk
const { useState, useEffect } = React;
const NS_E = window.GamekeepersCottageDesignSystem_070bc7;
const { Eyebrow, Button, Card, Badge } = NS_E;
const Photo = window.GKPhoto;
const IMG = window.GK_IMG;

// Filter categories are built dynamically from the places data (see ExploreContent).

// Places — read from assets/attractions.json (Decap-managed) on the live host;
// fall back to the embedded snapshot for local file:// previews.
let _attrCache = null, _attrPromise = null;
function loadAttractions() {
  if (_attrCache) return Promise.resolve(_attrCache);
  if (_attrPromise) return _attrPromise;
  _attrPromise = (async () => {
    try {
      const res = await fetch('assets/attractions.json', { cache: 'no-store' });
      if (res.ok) { const d = await res.json(); if (d && Array.isArray(d.places)) { _attrCache = d.places; return _attrCache; } }
    } catch (e) { /* fall through */ }
    if (window.GK_ATTRACTIONS && Array.isArray(window.GK_ATTRACTIONS.places)) { _attrCache = window.GK_ATTRACTIONS.places; return _attrCache; }
    _attrCache = [];
    return _attrCache;
  })();
  return _attrPromise;
}
function useAttractions() {
  const [list, setList] = useState(_attrCache || []);
  useEffect(() => { let live = true; loadAttractions().then(a => { if (live) setList(a); }); return () => { live = false; }; }, []);
  return list;
}

function ExploreContent() {
  const [filter, setFilter] = useState(() => new URLSearchParams(window.location.search).get('filter') || 'All');
  const places = useAttractions();
  const categories = ['All', ...places.reduce((acc, p) => { if (p.category && acc.indexOf(p.category) === -1) acc.push(p.category); return acc; }, [])];
  const list = places.filter(p => filter === 'All' || p.category === filter);
  // Arriving with a category from the nav dropdown? Jump to the filtered cards.
  useEffect(() => {
    if (filter !== 'All') {
      const el = document.getElementById('attractions');
      if (el) setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 120);
    }
  }, []);
  return (
    <React.Fragment>
      <section className="section--tight" style={{ paddingTop: 56 }}>
        <div className="container">
          <Eyebrow>Explore Suffolk</Eyebrow>
          <h1 className="h1" style={{ margin: '14px 0 14px' }}>Discover wonderful things to do in Suffolk</h1>
          <p className="lead muted" style={{ maxWidth: 620 }}>Make the most of your stay. These are our own recommended picks of local attractions, pubs, beaches and walks — all within easy reach of the cottage.</p>
          <div style={{ marginTop: 26 }}><Button variant="primary" size="lg" as="a" href="#attractions">See our selected attractions</Button></div>
        </div>
      </section>

      <section className="section" id="attractions" style={{ paddingTop: 48 }}>
        <div className="container">
          <Card padding="sm" style={{ marginBottom: 28 }}>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--text-muted)', fontWeight: 600, fontSize: 14, marginRight: 4 }}><i data-lucide="sliders-horizontal" style={{ width: 16, height: 16 }}></i>Filter</span>
              {categories.map(f => (
                <button key={f} onClick={() => setFilter(f)} className={'gk-btn gk-btn--sm ' + (filter === f ? 'gk-btn--primary' : 'gk-btn--ghost')}>{f}</button>
              ))}
            </div>
          </Card>
          <div className="grid grid-3">
            {list.map((p) => (
              <a key={p.slug} href={'attraction?slug=' + encodeURIComponent(p.slug)} style={{ textDecoration: 'none' }}>
                <Card interactive>
                  {p.photos && p.photos.length > 0
                    ? <Photo src={p.photos[0]} ratio="16 / 10" label={p.title} />
                    : <Photo variant={p.variant || 'interior'} ratio="16 / 10" label={p.title} />}
                  <div style={{ padding: 'var(--space-6)' }}>
                    <div style={{ marginBottom: 8 }}><Badge tone="moss">{p.category}</Badge></div>
                    <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', color: 'var(--color-primary)', marginBottom: 8 }}>{p.title}</h3>
                    <p className="muted" style={{ margin: '0 0 14px', fontSize: 15.5, lineHeight: 1.6 }}>{p.excerpt}</p>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', color: 'var(--text-muted)', fontSize: 13.5, borderTop: '1px solid var(--border-soft)', paddingTop: 12 }}>
                      <i data-lucide="map-pin" style={{ width: 15, height: 15, marginTop: 2, flex: 'none' }}></i>{p.location}
                    </div>
                  </div>
                </Card>
              </a>
            ))}
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

window.GKmount('explore', ExploreContent);
