/* global React */
// Blog index — data-driven from assets/posts.json
const { useState, useEffect } = React;
const NS_B = window.GamekeepersCottageDesignSystem_070bc7;
const { Eyebrow, Button, Card, Badge } = NS_B;
const Photo = window.GKPhoto;
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 Stars() {
  let seed = 7;
  const rnd = () => (seed = (seed * 9301 + 49297) % 233280) / 233280;
  const shadows = [];
  for (let i = 0; i < 90; i++) shadows.push(`${Math.round(rnd() * 100)}vw ${Math.round(rnd() * 320)}px rgba(255,255,255,${(0.3 + rnd() * 0.7).toFixed(2)})`);
  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, background: 'transparent', boxShadow: shadows.join(', ') }}></div>
  </div>;
}

function BlogContent() {
  const posts = usePosts();
  const featured = posts.find(p => p.featured);
  const rest = posts.filter(p => !p.featured);
  return (
    <React.Fragment>
      <section className="section--tight" style={{ paddingTop: 56 }}>
        <div className="container">
          <Eyebrow>From the wood</Eyebrow>
          <h1 className="h1" style={{ margin: '14px 0 14px' }}>Stories, wildlife & things to do</h1>
          <p className="lead muted" style={{ maxWidth: 600 }}>Notes from the cottage and the wood around it — the birds and moths at the feeders, the night sky, and our favourite corners of Suffolk.</p>
        </div>
      </section>

      {featured && (
        <section className="section--tight" style={{ paddingTop: 24 }}>
          <div className="container">
            <a href={'blog-post?post=' + encodeURIComponent(featured.slug)} style={{ textDecoration: 'none' }}>
              <Card interactive>
                <div className="gk-stack" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr' }}>
                  {featured.cover ? (
                    <div style={{ position: 'relative', minHeight: 320 }}>
                      <Photo src={featured.cover} ratio="auto" style={{ height: '100%', aspectRatio: 'auto', minHeight: 320 }} />
                      <span style={{ position: 'absolute', top: 18, left: 18 }}><Badge tone="gold">Featured</Badge></span>
                    </div>
                  ) : (
                    <div style={{ position: 'relative', minHeight: 320, background: 'radial-gradient(140% 120% at 70% 10%, #1b2c4a 0%, #0e1726 60%, #070b14 100%)' }}>
                      <Stars />
                      <span style={{ position: 'absolute', top: 18, left: 18 }}><Badge tone="gold">Featured</Badge></span>
                    </div>
                  )}
                  <div style={{ padding: 'var(--space-10)', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                    <div style={{ marginBottom: 12 }}><Badge tone="moss">{featured.category}</Badge></div>
                    <h2 className="h2" style={{ marginBottom: 12 }}>{featured.title}</h2>
                    <p className="muted" style={{ margin: '0 0 20px', fontSize: 16, lineHeight: 1.65 }}>{featured.excerpt}</p>
                    <span className="chip-link">Read the story <i data-lucide="arrow-right" style={{ width: 16, height: 16 }}></i></span>
                  </div>
                </div>
              </Card>
            </a>
          </div>
        </section>
      )}

      <section className="section" style={{ paddingTop: 36 }}>
        <div className="container">
          <div className="grid grid-3">
            {rest.map((p) => (
              <a key={p.slug} href={'blog-post?post=' + encodeURIComponent(p.slug)} style={{ textDecoration: 'none' }}>
                <Card interactive>
                  <Photo src={p.cover || undefined} variant={p.cover ? undefined : 'wood'} ratio="16 / 10" label={p.cover ? null : p.category} />
                  <div style={{ padding: 'var(--space-6)' }}>
                    <div style={{ marginBottom: 10 }}><Badge tone="moss">{p.category}</Badge></div>
                    <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', marginBottom: 8 }}>{p.title}</h3>
                    <span className="chip-link" style={{ fontSize: 14 }}>Read more <i data-lucide="arrow-right" style={{ width: 15, height: 15 }}></i></span>
                  </div>
                </Card>
              </a>
            ))}
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

window.GKmount('blog', BlogContent);
