/* global React */
// Place detail — data-driven from assets/attractions.json (?slug=...)
const { useState, useEffect } = React;
const NS_A = window.GamekeepersCottageDesignSystem_070bc7;
const { Eyebrow, Button, Card, Badge, Rating } = NS_A;
const Photo = window.GKPhoto;
const useShell = window.GKuseShell;
const useReviews = window.GKuseReviews;
const reviewStats = window.GKreviewStats;
const IMG = window.GK_IMG;

// Places loader (mirrors Explore) — assets/attractions.json, then embedded fallback.
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 initial = _attrCache || (window.GK_ATTRACTIONS && window.GK_ATTRACTIONS.places) || [];
  const [list, setList] = useState(initial);
  useEffect(() => { let live = true; loadAttractions().then(a => { if (live) setList(a); }); return () => { live = false; }; }, []);
  return list;
}

function CottageRating() {
  const s = reviewStats(useReviews());
  return s.count > 0 ? <Rating value={s.average} count={s.count} /> : null;
}

// Photo header that adapts to how many photos are uploaded.
function PhotoHeader({ place }) {
  const imgs = (place.photos || []).filter(Boolean);
  const cell = { height: '100%', aspectRatio: 'auto' };
  if (imgs.length >= 3) {
    return (
      <div className="gk-photos" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gridTemplateRows: '200px 200px', gap: 12 }}>
        <div style={{ gridRow: 'span 2' }}><Photo src={imgs[0]} ratio="auto" radius={14} label={place.title} style={cell} /></div>
        <Photo src={imgs[1]} ratio="auto" radius={14} style={cell} />
        <Photo src={imgs[2]} ratio="auto" radius={14} style={cell} />
      </div>
    );
  }
  if (imgs.length === 2) {
    return (
      <div className="gk-photos" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '320px', gap: 12 }}>
        <Photo src={imgs[0]} ratio="auto" radius={14} label={place.title} style={cell} />
        <Photo src={imgs[1]} ratio="auto" radius={14} style={cell} />
      </div>
    );
  }
  if (imgs.length === 1) {
    return <Photo src={imgs[0]} ratio="16 / 7" radius={14} label={place.title} />;
  }
  return <Photo variant={place.variant || 'interior'} ratio="16 / 7" radius={14} label={place.title} />;
}

function NotFound() {
  return (
    <section className="section" style={{ textAlign: 'center' }}>
      <div className="container container--narrow">
        <h1 className="h2" style={{ marginBottom: 12 }}>Place not found</h1>
        <p className="lead muted" style={{ marginBottom: 24 }}>We couldn't find that place — it may have been moved or removed.</p>
        <Button variant="primary" size="lg" as="a" href="explore">Back to Explore Suffolk</Button>
      </div>
    </section>
  );
}

function AttractionContent() {
  const { openBooking } = useShell();
  const places = useAttractions();
  const slug = new URLSearchParams(window.location.search).get('slug');
  const place = places.find(p => p.slug === slug) || (!slug && places[0]) || null;
  useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [place]);

  if (places.length > 0 && !place) return <NotFound />;
  if (!place) return <section className="section"><div className="container" /></section>;

  const website = place.website ? (place.website.startsWith('http') ? place.website : 'https://' + place.website) : '';
  const hasContact = place.phone || place.website || place.location || place.map;
  return (
    <React.Fragment>
      <section className="section--tight" style={{ paddingTop: 56, paddingBottom: 0 }}>
        <div className="container">
          <a href="explore" className="chip-link" style={{ marginBottom: 14 }}><i data-lucide="arrow-left" style={{ width: 16, height: 16 }}></i>Back to Explore Suffolk</a>
          <Eyebrow>{place.category}{place.area ? ' · ' + place.area : ''}</Eyebrow>
          <h1 className="h1" style={{ margin: '12px 0 22px' }}>{place.title}</h1>
          <PhotoHeader place={place} />
        </div>
      </section>

      <section className="section">
        <div className={'container' + (hasContact ? ' gk-stack' : '')} style={hasContact ? { display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 320px', gap: 48, alignItems: 'start' } : {}}>
          <div>
            <h2 className="h2" style={{ marginBottom: 16 }}>{place.heading || ('About ' + place.title)}</h2>
            {place.intro && <p style={{ lineHeight: 1.75, marginBottom: 26 }}>{place.intro}</p>}
            {(place.sections || []).map((s, i) => (
              <div key={i} style={{ marginBottom: 26 }}>
                {s.title && <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', marginBottom: 10 }}>{s.title}</h3>}
                <p style={{ lineHeight: 1.75, margin: 0, color: 'var(--text-body)' }}>{s.text}</p>
              </div>
            ))}
          </div>
          {hasContact && (
            <Card padding="md" style={{ position: 'sticky', top: 'calc(var(--header-height) + 20px)' }}>
              <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', marginBottom: 16 }}>Contact details</h3>
              <div style={{ display: 'grid', gap: 12, fontSize: 15 }}>
                {place.phone && <a href={'tel:' + place.phone.replace(/\s/g, '')} style={{ display: 'flex', gap: 10, color: 'var(--text-body)', textDecoration: 'none' }}><i data-lucide="phone" style={{ width: 16, height: 16, color: 'var(--color-primary)', marginTop: 3, flex: 'none' }}></i>{place.phone}</a>}
                {website && <a href={website} target="_blank" rel="noopener" style={{ display: 'flex', gap: 10, color: 'var(--text-body)', textDecoration: 'none' }}><i data-lucide="globe" style={{ width: 16, height: 16, color: 'var(--color-primary)', marginTop: 3, flex: 'none' }}></i>{place.website}</a>}
                {place.location && <span style={{ display: 'flex', gap: 10 }}><i data-lucide="map-pin" style={{ width: 16, height: 16, color: 'var(--color-primary)', marginTop: 3, flex: 'none' }}></i>{place.location}</span>}
              </div>
              {place.map && (
                <div style={{ borderRadius: 'var(--radius-md)', overflow: 'hidden', border: '1px solid var(--border-soft)', marginTop: 16 }}>
                  <iframe title="Map" width="100%" height="200" style={{ border: 0, display: 'block' }} loading="lazy" src={place.map}></iframe>
                </div>
              )}
            </Card>
          )}
        </div>
      </section>

      <section className="section section--soft">
        <div className="container">
          <div style={{ maxWidth: 620, marginBottom: 28 }}>
            <Eyebrow>Stay nearby</Eyebrow>
            <h2 className="h2" style={{ margin: '14px 0 6px' }}>Looking for somewhere to stay?</h2>
            <p className="muted" style={{ margin: 0 }}>The Gamekeeper's Cottage is hidden in its own hundred-acre wood, an easy drive from here.</p>
          </div>
          <Card padding="none">
            <div className="gk-stack" style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 0, alignItems: 'stretch' }}>
              <div style={{ position: 'relative' }}>
                <Photo src={IMG.exterior1} ratio="auto" style={{ height: '100%', aspectRatio: 'auto', minHeight: 200 }} />
                <span style={{ position: 'absolute', top: 14, left: 14 }}><Badge tone="gold">Top offer</Badge></span>
              </div>
              <div style={{ padding: 'var(--space-8)', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 10 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
                  <div>
                    <h3 className="h3" style={{ marginBottom: 6 }}>The Gamekeeper's Cottage</h3>
                    <p className="muted" style={{ margin: 0, fontSize: 14.5 }}>The Wood, Southwold Rd, Brampton, Beccles NR34 8DW</p>
                  </div>
                  <CottageRating />
                </div>
                <div style={{ display: 'flex', gap: 22, color: 'var(--text-body)', fontSize: 15, margin: '6px 0', flexWrap: 'wrap' }}>
                  <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><i data-lucide="bed-double" style={{ width: 17, height: 17 }}></i>3 bedrooms</span>
                  <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><i data-lucide="bath" style={{ width: 17, height: 17 }}></i>1 bathroom</span>
                  <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><i data-lucide="users" style={{ width: 17, height: 17 }}></i>Sleeps 5</span>
                </div>
                <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 6 }}>
                  <Button variant="primary" size="md" onClick={openBooking}>Check rates &amp; reserve</Button>
                  <Button variant="secondary" size="md" as="a" href="cottage">Visit cottage</Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </section>
    </React.Fragment>
  );
}

window.GKmount('attraction', AttractionContent);
