/* global React */
// Blog post — data-driven from assets/posts.json (?post=slug)
const { useState, useEffect } = React;
const NS_BP = window.GamekeepersCottageDesignSystem_070bc7;
const { Button, Badge, Eyebrow, Card } = NS_BP;
const Photo = window.GKPhoto;
const useShell = window.GKuseShell;
const IMG = window.GK_IMG;

let _postsCache = null, _postsPromise = null;
function loadPosts() {
  if (_postsCache) return Promise.resolve(_postsCache);
  if (_postsPromise) return _postsPromise;
  _postsPromise = (async () => {
    try {
      const res = await fetch('assets/posts.json', { cache: 'no-store' });
      if (res.ok) { const d = await res.json(); if (d && Array.isArray(d.posts)) { _postsCache = d.posts; return _postsCache; } }
    } catch (e) { /* fall through */ }
    if (window.GK_POSTS && Array.isArray(window.GK_POSTS.posts)) { _postsCache = window.GK_POSTS.posts; return _postsCache; }
    _postsCache = [];
    return _postsCache;
  })();
  return _postsPromise;
}
function usePosts() {
  const initial = _postsCache || (window.GK_POSTS && window.GK_POSTS.posts) || [];
  const [list, setList] = useState(initial);
  useEffect(() => { let live = true; loadPosts().then(p => { if (live) setList(p); }); return () => { live = false; }; }, []);
  return list;
}

function Starfield({ count = 160, height = 460 }) {
  let seed = 11;
  const rnd = () => (seed = (seed * 9301 + 49297) % 233280) / 233280;
  const shadows = [];
  for (let i = 0; i < count; i++) shadows.push(`${(rnd() * 100).toFixed(2)}vw ${Math.round(rnd() * height)}px rgba(255,255,255,${(0.25 + rnd() * 0.75).toFixed(2)})`);
  const big = [];
  for (let i = 0; i < 6; i++) big.push(`${(rnd() * 100).toFixed(2)}vw ${Math.round(rnd() * height)}px rgba(180,205,255,0.95)`);
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }} aria-hidden="true">
      <div style={{ position: 'absolute', top: 0, left: 0, width: 1, height: 1, borderRadius: 999, boxShadow: shadows.join(', ') }}></div>
      <div style={{ position: 'absolute', top: 0, left: 0, width: 2, height: 2, borderRadius: 999, boxShadow: big.join(', ') }}></div>
    </div>
  );
}

function PostHero({ post }) {
  const eyebrow = (post.category || '') ;
  if (post.night) {
    return (
      <section style={{ position: 'relative', height: 460, background: 'radial-gradient(130% 120% at 60% 0%, #1c2e4d 0%, #11203a 45%, #080d18 100%)', display: 'grid', placeItems: 'center', textAlign: 'center', overflow: 'hidden' }}>
        <Starfield height={460} />
        <div style={{ position: 'relative', padding: '0 24px' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(200,215,245,0.9)' }}>{eyebrow}</span>
          <h1 className="h-display" style={{ color: '#fff', margin: '16px 0 0', maxWidth: 820, textShadow: '0 2px 30px rgba(0,0,0,0.5)' }}>{post.title}</h1>
        </div>
      </section>
    );
  }
  if (post.cover) {
    return (
      <section style={{ position: 'relative', minHeight: 420, display: 'grid', placeItems: 'center', textAlign: 'center', overflow: 'hidden' }}>
        <img src={post.cover} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(20,30,18,0.30) 0%, rgba(20,30,18,0.30) 40%, rgba(20,30,18,0.70) 100%)' }}></div>
        <div style={{ position: 'relative', padding: '60px 24px' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.92)' }}>{eyebrow}</span>
          <h1 className="h-display" style={{ color: '#fff', margin: '16px 0 0', maxWidth: 820, textShadow: '0 2px 28px rgba(0,0,0,0.45)' }}>{post.title}</h1>
        </div>
      </section>
    );
  }
  return (
    <section style={{ position: 'relative', minHeight: 320, background: 'var(--surface-dark)', display: 'grid', placeItems: 'center', textAlign: 'center' }}>
      <div style={{ padding: '56px 24px' }}>
        <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--accent-sage)' }}>{eyebrow}</span>
        <h1 className="h-display" style={{ color: '#fff', margin: '16px 0 0', maxWidth: 820 }}>{post.title}</h1>
      </div>
    </section>
  );
}

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

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

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

  const related = posts.filter((p) => p.slug !== post.slug).slice(0, 3);

  return (
    <React.Fragment>
      <PostHero post={post} />
      <article className="section">
        <div className="container prose">
          {(post.body || []).map((b, i) => (
            <React.Fragment key={i}>
              {b.heading ? <h2>{b.heading}</h2> : null}
              {b.text ? <p>{b.text}</p> : null}
              {b.items && b.items.length > 0 ? <ul>{b.items.map((it, j) => <li key={j}>{it}</li>)}</ul> : null}
            </React.Fragment>
          ))}
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 36, paddingTop: 28, borderTop: '1px solid var(--border-soft)' }}>
            <Button variant="secondary" size="md" as="a" href="blog"><i data-lucide="arrow-left" style={{ width: 16, height: 16 }}></i> Back to the blog</Button>
            <Button variant="primary" size="md" onClick={openBooking}>{post.night ? 'Come and see the stars — check dates' : 'Check rates & reserve'}</Button>
          </div>
        </div>
      </article>

      {related.length > 0 && (
        <section className="section section--soft">
          <div className="container">
            <Eyebrow>More from the wood</Eyebrow>
            <h2 className="h2" style={{ margin: '14px 0 22px' }}>More stories to read</h2>
            <div className="grid grid-3">
              {related.map((rp) => (
                <a key={rp.slug} href={'blog-post?post=' + encodeURIComponent(rp.slug)} style={{ textDecoration: 'none' }}>
                  <Card interactive>
                    {rp.cover
                      ? <Photo src={rp.cover} ratio="16 / 10" />
                      : <div style={{ aspectRatio: '16 / 10', background: 'var(--surface-strong)' }} />}
                    <div style={{ padding: 'var(--space-5)' }}>
                      <b style={{ fontFamily: 'var(--font-display)', fontSize: 17, color: 'var(--text-strong)' }}>{rp.title}</b>
                      {rp.excerpt ? <p className="muted" style={{ margin: '6px 0 0', fontSize: 14.5, lineHeight: 1.55 }}>{rp.excerpt}</p> : null}
                    </div>
                  </Card>
                </a>
              ))}
            </div>
          </div>
        </section>
      )}

      <section className="section">
        <div className="container">
          <div style={{ maxWidth: 620, marginBottom: 24 }}>
            <Eyebrow>Stay nearby</Eyebrow>
            <h2 className="h2" style={{ margin: '14px 0 6px' }}>Come and stay in the wood</h2>
            <p className="muted" style={{ margin: 0 }}>The Gamekeeper's Cottage is hidden in its own hundred-acre Suffolk wood, near Southwold — a perfect base for exploring all of this.</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">Book direct</Badge></span>
              </div>
              <div style={{ padding: 'var(--space-8)', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 10 }}>
                <h3 className="h3" style={{ marginBottom: 2 }}>The Gamekeeper's Cottage</h3>
                <p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Sleeps 5 · 3 bedrooms · four acres of private woodland</p>
                <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 10 }}>
                  <Button variant="primary" size="md" onClick={openBooking}>Check rates &amp; reserve</Button>
                  <Button variant="secondary" size="md" as="a" href="cottage">Visit the cottage</Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </section>
    </React.Fragment>
  );
}

window.GKmount('blog-post', BlogPostContent);
