// site/page-blog.jsx, Blog index + article view.
// Routing: `#blog` shows the index, `#blog/<slug>` shows a single post.
// Post data lives in site/blog-posts.jsx (window.BLOG_POSTS), generated
// from the fairs.com CMS export. Bodies are rendered verbatim.

function PageBlog({ onNav }) {
  const [hash, setHash] = React.useState(typeof location !== 'undefined' ? location.hash : '');
  React.useEffect(() => {
    const onHash = () => setHash(location.hash);
    window.addEventListener('hashchange', onHash);
    window.addEventListener('popstate', onHash);
    return () => {
      window.removeEventListener('hashchange', onHash);
      window.removeEventListener('popstate', onHash);
    };
  }, []);

  const parts = (hash || '').replace(/^#/, '').split('/');
  const slug = parts.length > 1 ? parts.slice(1).join('/') : null;
  const post = slug ? BLOG_POSTS.find(p => p.slug === slug) : null;

  if (slug && !post) {
    return <BlogNotFound onNav={onNav} slug={slug} />;
  }
  return post ? <BlogArticle post={post} onNav={onNav} /> : <BlogIndex onNav={onNav} />;
}

// ─── Index view ─────────────────────────────────────────────
function getExcerpt(post, max = 160) {
  if (post.summary && post.summary.trim()) return post.summary.trim();
  const stripped = (post.body || '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
  return stripped.length > max ? stripped.slice(0, max).trim() + '…' : stripped;
}

function BlogIndex({ onNav }) {
  const cats = ['All', ...Array.from(new Set(BLOG_POSTS.map(p => p.category || 'Insights')))];
  const [filter, setFilter] = React.useState('All');
  const visible = filter === 'All' ? BLOG_POSTS : BLOG_POSTS.filter(p => (p.category || 'Insights') === filter);
  const featured = visible[0];
  const rest = visible.slice(1);

  const goToPost = (slug) => onNav('blog/' + slug);

  return (
    <div>
      <PageHero
        eyebrow="Resources"
        title="Practical, on-the-ground"
        titleAccent="fair operations writing."
        lead="Stories, playbooks and tactics from running fairs across the country. Real lessons from the team behind Fairs.com."
        cowSize={220}
      />

      {/* Featured post */}
      {featured && (
        <section style={{ background: S.cream2, padding: '72px 64px', position: 'relative' }}>
          <div className="has-grain" style={{ position: 'absolute', inset: 0 }} />
          <div style={{ position: 'relative', maxWidth: 1280, margin: '0 auto' }}>
            <button onClick={() => goToPost(featured.slug)} style={{
              display: 'block', width: '100%', textAlign: 'left', fontFamily: 'inherit',
              cursor: 'pointer', background: 'transparent', border: 0, padding: 0,
            }}>
              <div style={{
                background: S.cream, border: `1.5px solid ${S.ink}`, borderRadius: 18, overflow: 'hidden',
                boxShadow: `8px 8px 0 0 ${S.red}`, display: 'grid', gridTemplateColumns: '1fr 1fr',
              }}>
                <div style={{ position: 'relative', minHeight: 380, background: S.cream3 }}>
                  {featured.image && (
                    <img src={featured.image} alt={featured.imageAlt || featured.title}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                  )}
                  <div style={{ position: 'absolute', top: 16, left: 16, transform: 'rotate(-4deg)', background: S.red, color: S.ink, padding: '6px 12px', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                    Featured · {featured.category || 'Insights'}
                  </div>
                </div>
                <div style={{ padding: 48 }}>
                  <SectionEyebrow>{featured.category || 'Insights'}</SectionEyebrow>
                  <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.08, letterSpacing: '-0.025em', color: S.ink, margin: '14px 0 14px' }}>
                    {featured.title}
                  </h2>
                  {featured.summary && (
                    <p style={{ fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.72, margin: '0 0 24px' }}>
                      {featured.summary}
                    </p>
                  )}
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderTop: `1px dashed ${S.border}`, paddingTop: 18 }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.mute, letterSpacing: '0.06em' }}>
                      {featured.date}
                    </div>
                    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: S.red, fontWeight: 700, fontSize: 16 }}>
                      Read article <Ico name="arrowRight" size={14} strokeWidth={2.4} />
                    </div>
                  </div>
                </div>
              </div>
            </button>
          </div>
        </section>
      )}

      {/* Filters */}
      <section style={{ background: S.cream, padding: '48px 64px 0', position: 'relative' }}>
        <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 1280, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.05, letterSpacing: '-0.025em', color: S.ink, margin: 0 }}>
            All <em style={{ fontStyle: 'italic', color: S.red }}>articles</em>
          </h2>
          <div style={{ display: 'inline-flex', gap: 6, padding: 4, background: S.cream2, border: `1.5px solid ${S.ink}`, borderRadius: 999 }}>
            {cats.map(c => {
              const active = filter === c;
              return (
                <button key={c} onClick={() => setFilter(c)} style={{
                  border: 0, padding: '8px 16px', borderRadius: 999, cursor: 'pointer',
                  fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
                  background: active ? S.ink : 'transparent', color: active ? S.cream : S.ink,
                  textTransform: 'capitalize',
                }}>{c}</button>
              );
            })}
          </div>
        </div>
      </section>

      {/* Article grid */}
      <section style={{ background: S.cream, padding: '32px 64px 96px', position: 'relative' }}>
        <div style={{ position: 'relative', maxWidth: 1280, margin: '0 auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28, alignItems: 'stretch' }}>
            {rest.map((a, i) => (
              <button key={a.slug} onClick={() => goToPost(a.slug)} style={{
                background: S.cream, border: `1.5px solid ${S.ink}`, borderRadius: 16,
                overflow: 'hidden', boxShadow: `4px 4px 0 0 ${i % 3 === 1 ? S.red : S.ink}`,
                cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', padding: 0,
                display: 'flex', flexDirection: 'column', height: '100%',
              }}>
                {/* Image — fixed height, contain so badges/text near edges aren't cropped */}
                <div style={{ position: 'relative', width: '100%', height: 200, background: S.cream2, flex: '0 0 auto', borderBottom: `1px solid ${S.border}` }}>
                  {a.image && (
                    <img src={a.image} alt={a.imageAlt || a.title}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain' }} />
                  )}
                </div>
                {/* Body — flex column so footer pins to bottom */}
                <div style={{ padding: 22, display: 'flex', flexDirection: 'column', flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.red, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                    {a.category || 'Insights'}
                  </div>
                  {/* Title — clamped to 2 lines, reserved height */}
                  <h3 style={{
                    fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22, lineHeight: 1.3,
                    color: S.ink, margin: '8px 0 12px', letterSpacing: '-0.02em',
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                    overflow: 'hidden', minHeight: '2.6em',
                  }}>{a.title}</h3>
                  {/* Excerpt — clamped to 3 lines, always present */}
                  <p style={{
                    fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.72, margin: '0 0 16px',
                    display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
                    overflow: 'hidden', flex: 1,
                  }}>{getExcerpt(a)}</p>
                  {/* Footer — pinned to bottom */}
                  <div style={{ borderTop: `1px dashed ${S.border}`, paddingTop: 12, fontFamily: 'var(--font-mono)', fontSize: 12, color: S.mute, letterSpacing: '0.06em', display: 'flex', justifyContent: 'space-between', marginTop: 'auto' }}>
                    <span>{a.date}</span>
                    <span style={{ color: S.red, fontWeight: 700 }}>Read →</span>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      <CTAStrip onNav={onNav} />
    </div>
  );
}

// ─── Article view (renders one post body verbatim) ──────────
function BlogArticle({ post, onNav }) {
  const otherPosts = BLOG_POSTS.filter(p => p.slug !== post.slug).slice(0, 3);

  return (
    <div>
      {/* Inline styles for the article body so the CMS-exported HTML reads well */}
      <style>{`
        .blog-body { font-family: var(--font-display); font-size: 16px; line-height: 1.65; color: ${S.ink}; }
        .blog-body p { margin: 0 0 1.25em; }
        .blog-body h1 { font-family: var(--font-display); font-weight: 600; font-size: 36px; line-height: 1.1; letter-spacing: -0.025em; margin: 2em 0 0.6em; }
        .blog-body h2 { font-family: var(--font-display); font-weight: 600; font-size: 36px; line-height: 1.15; letter-spacing: -0.02em; margin: 1.8em 0 0.6em; }
        .blog-body h3 { font-family: var(--font-display); font-weight: 600; font-size: 22px; line-height: 1.2; letter-spacing: -0.02em; margin: 1.6em 0 0.5em; }
        .blog-body h4 { font-family: var(--font-display); font-weight: 600; font-size: 22px; line-height: 1.25; letter-spacing: -0.015em; margin: 1.4em 0 0.4em; }
        .blog-body h1:first-child, .blog-body h2:first-child, .blog-body h3:first-child { margin-top: 0; }
        .blog-body a { color: ${S.red}; text-decoration: underline; text-underline-offset: 3px; text-decoration-thickness: 1.5px; }
        .blog-body a:hover { text-decoration-thickness: 2.5px; }
        .blog-body ul, .blog-body ol { margin: 0 0 1.25em; padding-left: 1.5em; }
        .blog-body li { margin: 0 0 0.5em; }
        .blog-body strong, .blog-body b { font-weight: 700; }
        .blog-body em, .blog-body i { font-style: italic; }
        .blog-body img { max-width: 100%; height: auto; display: block; margin: 1.6em auto; border-radius: 12px; }
        .blog-body figure { margin: 1.6em 0; }
        .blog-body figure img { margin: 0; }
        .blog-body figcaption { font-family: var(--font-mono); font-size: 12px; color: ${S.mute}; text-align: center; margin-top: 0.5em; letter-spacing: 0.04em; }
        .blog-body blockquote {
          border-left: 4px solid ${S.red};
          padding: 0.4em 0 0.4em 1.4em;
          margin: 1.8em 0;
          font-style: italic;
          font-size: 22px;
          color: ${S.ink};
        }
        .blog-body hr { border: 0; border-top: 1px dashed ${S.border}; margin: 2.4em 0; }
        .blog-body code { font-family: var(--font-mono); font-size: 0.9em; background: ${S.cream2}; padding: 2px 6px; border-radius: 4px; }
        .blog-body pre { background: ${S.cream2}; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: var(--font-mono); font-size: 16px; line-height: 1.55; }
        .blog-body table { width: 100%; border-collapse: collapse; margin: 1.6em 0; font-size: 16px; }
        .blog-body th, .blog-body td { border: 1px solid ${S.border}; padding: 10px 14px; text-align: left; }
        .blog-body th { background: ${S.cream2}; font-weight: 700; }
      `}</style>

      {/* Article hero */}
      <section style={{ background: S.cream, padding: '64px 64px 24px', position: 'relative' }}>
        <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'relative', maxWidth: 820, margin: '0 auto' }}>
          <button onClick={() => onNav('blog')} style={{
            background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
            color: S.ink, opacity: 0.65, fontFamily: 'inherit', fontSize: 16, fontWeight: 600,
            display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 24,
          }}>
            <Ico name="chevronLeft" size={14} strokeWidth={2.2} /> All articles
          </button>
          <SectionEyebrow>{post.category || 'Insights'}</SectionEyebrow>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 56, lineHeight: 1.08,
            letterSpacing: '-0.03em', color: S.ink, margin: '14px 0 18px',
          }}>{post.title}</h1>
          {post.summary && (
            <p style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 22, lineHeight: 1.45, color: S.ink, opacity: 0.78, margin: '0 0 24px' }}>
              {post.summary}
            </p>
          )}
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.mute, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
            {post.date}
          </div>
        </div>
      </section>

      {/* Main image */}
      {post.image && (
        <section style={{ background: S.cream, padding: '24px 64px 48px' }}>
          <div style={{ maxWidth: 1100, margin: '0 auto' }}>
            <img src={post.image} alt={post.imageAlt || post.title}
              style={{ width: '100%', height: 'auto', display: 'block', borderRadius: 16, border: `1.5px solid ${S.ink}`, boxShadow: `6px 6px 0 0 ${S.red}` }} />
          </div>
        </section>
      )}

      {/* Article body */}
      <section style={{ background: S.cream, padding: '24px 64px 96px' }}>
        <div style={{ maxWidth: 760, margin: '0 auto' }}>
          <div className="blog-body" dangerouslySetInnerHTML={{ __html: post.body }} />
          <div style={{ marginTop: 56, paddingTop: 32, borderTop: `1px dashed ${S.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
            <button onClick={() => onNav('blog')} style={{
              background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
              color: S.red, fontFamily: 'inherit', fontSize: 16, fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Ico name="chevronLeft" size={14} strokeWidth={2.4} /> Back to all articles
            </button>
            <StubBtn size="md" onClick={() => onNav('contact')}>Book a demo</StubBtn>
          </div>
        </div>
      </section>

      {/* Related posts */}
      {otherPosts.length > 0 && (
        <section style={{ background: S.cream2, padding: '72px 64px', position: 'relative' }}>
          <div className="has-grain" style={{ position: 'absolute', inset: 0 }} />
          <div style={{ position: 'relative', maxWidth: 1280, margin: '0 auto' }}>
            <div style={{ marginBottom: 32 }}>
              <SectionEyebrow>Keep reading</SectionEyebrow>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.05, letterSpacing: '-0.025em', color: S.ink, margin: '12px 0 0' }}>
                More from the <em style={{ fontStyle: 'italic', color: S.red }}>fair-day</em> dispatch.
              </h2>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
              {otherPosts.map((p, i) => {
                const tilts = [-0.4, 0.4, -0.3];
                return (
                  <button key={p.slug} onClick={() => onNav('blog/' + p.slug)} style={{
                    background: S.cream, border: `1.5px solid ${S.ink}`, borderRadius: 14,
                    overflow: 'hidden', boxShadow: `4px 4px 0 0 ${i === 1 ? S.red : S.ink}`,
                    transform: `rotate(${tilts[i]}deg)`, cursor: 'pointer',
                    textAlign: 'left', fontFamily: 'inherit', padding: 0, display: 'block',
                  }}>
                    <div style={{ position: 'relative', width: '100%', height: 160, background: S.cream3 }}>
                      {p.image && (
                        <img src={p.image} alt={p.imageAlt || p.title}
                          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                      )}
                    </div>
                    <div style={{ padding: 20 }}>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: S.red, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                        {p.category || 'Insights'}
                      </div>
                      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 16, lineHeight: 1.25, color: S.ink, margin: '6px 0 0', letterSpacing: '-0.015em' }}>{p.title}</h3>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        </section>
      )}

      <CTAStrip onNav={onNav} />
    </div>
  );
}

// ─── Slug not found fallback ────────────────────────────────
function BlogNotFound({ onNav, slug }) {
  return (
    <section style={{ background: S.cream, padding: '160px 64px', position: 'relative', textAlign: 'center', minHeight: '60vh' }}>
      <div className="has-grain light" style={{ position: 'absolute', inset: 0 }} />
      <div style={{ position: 'relative', maxWidth: 640, margin: '0 auto' }}>
        <SectionEyebrow>Article not found</SectionEyebrow>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 36, lineHeight: 1.1, letterSpacing: '-0.025em', color: S.ink, margin: '12px 0 16px' }}>
          We couldn't find <em style={{ fontStyle: 'italic', color: S.red }}>that article.</em>
        </h1>
        <p style={{ fontSize: 16, lineHeight: 1.55, color: S.ink, opacity: 0.72, margin: '0 0 32px' }}>
          The slug <code style={{ background: S.cream2, padding: '2px 6px', borderRadius: 4 }}>{slug}</code> doesn't match any post on file.
        </p>
        <StubBtn onClick={() => onNav('blog')}>Back to all articles</StubBtn>
      </div>
    </section>
  );
}

Object.assign(window, { PageBlog });
