// BlogPage.jsx — Field Notes list + single-post view, backed by PostsStore (postsData.js).

const BlogPage = () => {
  useReveal();
  const store = usePostsStore();
  const posts = store.posts;
  const categoryColor = (cat) => {
    const c = String(cat || '').toLowerCase();
    if (c.includes('cook')) return 'var(--wbbq-flame)';
    if (c.includes('debrief')) return 'var(--wbbq-blue)';
    if (c.includes('recipe')) return 'var(--wbbq-slime)';
    if (c.includes('rant')) return 'var(--wbbq-flame)';
    if (c.includes('gear')) return 'var(--wbbq-blue)';
    if (c.includes('strategy')) return 'var(--wbbq-slime)';
    if (c.includes('lore')) return 'var(--wbbq-pig)';
    return 'var(--wbbq-flame)';
  };

  const [featured, ...rest] = posts;

  return (
    <>
      <PageHero
        eyebrow="Dispatches"
        title={<>Field <span style={{ color: 'var(--wbbq-flame)' }}>Notes.</span></>}
        subtitle="Cook journals, debriefs, and rants written at 4am next to an offset smoker."
        mascot="robot-monkey.svg"
      />
      <section className="section">
        <div className="wrap" style={{ maxWidth: 900 }}>
          {store.loading && posts.length === 0 && <PostsLoading />}
          {!store.loading && posts.length === 0 && <PostsEmpty connected={store.connected} error={store.error} />}

          {featured && (
            <article className="reveal blog-featured" style={{
              background: 'var(--wbbq-ink)', border: `3px solid ${categoryColor(featured.category)}`,
              boxShadow: `10px 10px 0 var(--wbbq-blue)`,
              padding: 36, marginBottom: 48,
              display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'center',
            }}>
              <div>
                <div className="eyebrow">Latest · {featured.category || 'FIELD NOTE'}</div>
                <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(1.6rem, 3vw, 2.4rem)', color: 'var(--wbbq-bone)', margin: '14px 0 12px', lineHeight: 1.05, textTransform: 'uppercase', letterSpacing: '0.01em' }}>{featured.title}</h2>
                <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', color: 'var(--fg3)', fontSize: 12, fontFamily: 'var(--font-mono)' }}>
                  <span>{featured.date}</span><span>·</span><span>{featured.category}</span><span>·</span><span>{featured.readMinutes} min read</span>
                </div>
                {featured.excerpt && (
                  <p style={{ marginTop: 18, color: 'var(--fg2)', fontSize: 16 }}>{featured.excerpt}</p>
                )}
                <a href={`#/blog/${featured.slug || featured.id}`} className="btn btn-primary" style={{ marginTop: 20 }}>Read It →</a>
              </div>
              {featured.cover && (
                <img className="blog-cover" src={`${window.ASSETS}mascots/${featured.cover}`} alt="" style={{ height: 180, animation: 'wiggle 5s ease-in-out infinite' }} />
              )}
            </article>
          )}

          {rest.length > 0 && (
            <div style={{ display: 'grid', gap: 16 }}>
              {rest.map((p, i) => (
                <a key={p.id} href={`#/blog/${p.slug || p.id}`} className="reveal blog-row" style={{
                  display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 24, alignItems: 'center',
                  padding: '24px 20px',
                  background: 'var(--wbbq-ink)', border: '1px solid var(--border)',
                  textDecoration: 'none', color: 'var(--fg1)',
                  transition: 'all 220ms var(--ease-snap)',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = categoryColor(p.category); e.currentTarget.style.transform = 'translateX(4px)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = 'translateX(0)'; }}
                >
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 40, color: categoryColor(p.category), lineHeight: 1 }}>
                    {String(posts.indexOf(p) + 1).padStart(2, '0')}
                  </div>
                  <div>
                    <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: categoryColor(p.category), fontWeight: 800, marginBottom: 6 }}>{p.category}</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, letterSpacing: '0.02em', color: 'var(--wbbq-bone)' }}>{p.title}</div>
                  </div>
                  <div className="blog-meta" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', textAlign: 'right' }}>
                    <div>{p.date}</div>
                    <div style={{ marginTop: 4 }}>{p.readMinutes} min</div>
                  </div>
                </a>
              ))}
            </div>
          )}
        </div>
      </section>
    </>
  );
};

const PostsLoading = () => (
  <div style={{ padding: 48, textAlign: 'center', color: 'var(--fg3)', fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.12em' }}>
    LOADING FIELD NOTES…
  </div>
);

const PostsEmpty = ({ connected, error }) => (
  <div style={{ padding: 32, border: '2px dashed var(--border)', background: 'var(--wbbq-ink)', color: 'var(--fg2)' }}>
    <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.14em', color: 'var(--wbbq-flame)', textTransform: 'uppercase', marginBottom: 10 }}>
      {error ? 'Field Notes Error' : (connected ? 'No posts yet' : 'Field Notes Coming Online')}
    </div>
    <div style={{ fontSize: 14 }}>
      {error
        ? error
        : connected
          ? 'Write your first post in Google Docs, register it in the admin panel, and it\'ll show up here.'
          : 'Backend not wired up yet. See POSTS_SETUP.md for the step-by-step.'}
    </div>
  </div>
);

window.BlogPage = BlogPage;

// ---------- Single-post page ----------

const BlogPostPage = () => {
  useReveal();
  const route = useRoute();
  const id = route.startsWith('blog/') ? route.slice(5) : '';
  const [post, setPost] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    if (!id) return;
    setPost(null); setErr(null);
    // Resolve id either directly or via slug from the list
    const resolved = resolvePostId(id);
    window.PostsStore.fetchPost(resolved)
      .then(setPost)
      .catch(e => setErr(e.message || String(e)));
  }, [id]);

  if (!id) {
    return <BlogPage />;
  }

  return (
    <>
      <section className="section" style={{ paddingTop: 48 }}>
        <div className="wrap" style={{ maxWidth: 760 }}>
          <a href="#/blog" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', textDecoration: 'none', letterSpacing: '0.1em' }}>
            ← FIELD NOTES
          </a>
          {err && <PostError msg={err} />}
          {!err && !post && <PostsLoading />}
          {post && <PostBody post={post} />}
        </div>
      </section>
    </>
  );
};

const resolvePostId = (slugOrId) => {
  const list = (window.PostsStore && window.PostsStore.get().posts) || [];
  const match = list.find(p => p.slug === slugOrId) || list.find(p => p.id === slugOrId);
  return match ? match.id : slugOrId;
};

const PostError = ({ msg }) => (
  <div style={{ marginTop: 20, padding: 20, border: '2px solid var(--wbbq-blood)', background: 'var(--wbbq-ink)' }}>
    <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.14em', color: 'var(--wbbq-blood)', textTransform: 'uppercase', marginBottom: 8 }}>Post Error</div>
    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg2)' }}>{msg}</div>
  </div>
);

const PostBody = ({ post }) => {
  const cat = post.category || 'FIELD NOTE';
  return (
    <article style={{ marginTop: 28 }}>
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', letterSpacing: '0.1em' }}>
        <span style={{ color: 'var(--wbbq-flame)', fontWeight: 700 }}>{cat}</span>
        {post.date && <><span>·</span><span>{post.date}</span></>}
      </div>
      <h1 style={{
        fontFamily: 'var(--font-display)', fontSize: 'clamp(1.8rem, 4vw, 3rem)',
        color: 'var(--wbbq-bone)', margin: '18px 0 20px', lineHeight: 1.05, letterSpacing: '0.01em',
        textTransform: 'uppercase',
      }}>{post.title}</h1>
      {post.excerpt && (
        <div style={{ fontSize: 18, color: 'var(--fg2)', marginBottom: 32, lineHeight: 1.55, maxWidth: 640 }}>{post.excerpt}</div>
      )}
      {post.cover && (
        <img src={`${window.ASSETS}mascots/${post.cover}`} alt="" style={{ height: 160, margin: '0 auto 32px', display: 'block' }} />
      )}
      <BlockRenderer blocks={post.blocks} />
      <div style={{ marginTop: 48, paddingTop: 20, borderTop: '1px dashed var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <a href="#/blog" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', textDecoration: 'none', letterSpacing: '0.1em' }}>← BACK TO FIELD NOTES</a>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)' }}>WARPED BBQ · EASTERN CT</div>
      </div>
    </article>
  );
};

// ---------- Block renderer ----------

const BlockRenderer = ({ blocks }) => {
  if (!blocks || !blocks.length) {
    return <div style={{ color: 'var(--fg3)', fontStyle: 'italic', padding: 24 }}>This post has no body yet.</div>;
  }
  const out = [];
  let listBuffer = null;
  const flushList = () => {
    if (!listBuffer) return;
    const Tag = listBuffer.ordered ? 'ol' : 'ul';
    out.push(
      <Tag key={`list-${out.length}`} style={{ paddingLeft: 24, margin: '16px 0', color: 'var(--fg1)', fontSize: 17, lineHeight: 1.65 }}>
        {listBuffer.items.map((it, i) => <li key={i} style={{ marginBottom: 6 }}>{renderRuns(it.runs || [{ text: it.text }])}</li>)}
      </Tag>
    );
    listBuffer = null;
  };
  blocks.forEach((b, i) => {
    if (b.type === 'li') {
      if (!listBuffer || !!listBuffer.ordered !== !!b.ordered) { flushList(); listBuffer = { ordered: !!b.ordered, items: [] }; }
      listBuffer.items.push(b);
      return;
    }
    flushList();
    if (b.type === 'h1') out.push(<h2 key={i} style={headingStyle(28)}>{b.text}</h2>);
    else if (b.type === 'h2') out.push(<h2 key={i} style={headingStyle(24)}>{b.text}</h2>);
    else if (b.type === 'h3') out.push(<h3 key={i} style={headingStyle(20)}>{b.text}</h3>);
    else if (b.type === 'h4') out.push(<h4 key={i} style={headingStyle(16)}>{b.text}</h4>);
    else if (b.type === 'hr') out.push(<hr key={i} style={{ border: 0, borderTop: '2px dashed var(--border)', margin: '32px 0' }} />);
    else if (b.type === 'img') out.push(
      <figure key={i} style={{ margin: '28px 0', textAlign: 'center' }}>
        <img src={b.src} alt={b.alt || ''} style={{ maxWidth: '100%', height: 'auto', border: '1px solid var(--border)' }}
          onError={(e) => { if (b.fallback && e.currentTarget.src !== b.fallback) e.currentTarget.src = b.fallback; }} />
        {b.alt && <figcaption style={{ marginTop: 8, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', letterSpacing: '0.08em' }}>{b.alt}</figcaption>}
      </figure>
    );
    else if (b.type === 'p') out.push(
      <p key={i} style={{ color: 'var(--fg1)', fontSize: 17, lineHeight: 1.7, margin: '14px 0' }}>{renderRuns(b.runs || [])}</p>
    );
  });
  flushList();
  return <div style={{ marginTop: 8 }}>{out}</div>;
};

const headingStyle = (size) => ({
  fontFamily: 'var(--font-display)', fontSize: size, color: 'var(--wbbq-bone)',
  letterSpacing: '0.02em', textTransform: 'uppercase',
  margin: '36px 0 14px', lineHeight: 1.2,
});

const renderRuns = (runs) => runs.map((r, i) => {
  let content = r.text;
  let style = {};
  if (r.bold) style.fontWeight = 700;
  if (r.italic) style.fontStyle = 'italic';
  if (r.underline) style.textDecoration = 'underline';
  if (r.link) {
    return <a key={i} href={r.link} target="_blank" rel="noreferrer noopener" style={{ ...style, color: 'var(--wbbq-flame)', textDecoration: 'underline' }}>{content}</a>;
  }
  return <span key={i} style={style}>{content}</span>;
});

window.BlogPostPage = BlogPostPage;
