function InsightsPage({ onGo, onOpenPost }) {
  const D = window.DATA;
  const [filter, setFilter] = useState("All");
  const [posts, setPosts] = useState(D.posts || []);
  const filters = ["All", "Strategy", "Performance", "SEO", "Creative", "Teardown", "Thinking", "Playbook"];
  const shown = filter === "All" ? posts : posts.filter(p => p.tag === filter);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const wp = await getWordPressPosts();
        if (!mounted || !wp) return;
        const mapped = wp.map(p => ({
          tag: (p._embedded && p._embedded['wp:term'] && p._embedded['wp:term'][0] && p._embedded['wp:term'][0][0] && p._embedded['wp:term'][0][0].name) || 'Thinking',
          date: new Date(p.date).toLocaleString(undefined, { month: 'short', year: 'numeric' }),
          title: p.title || '',
          read: p.excerpt ? p.excerpt.replace(/<[^>]+>/g, '').slice(0, 120) + '...' : '',
          feature: false,
          img: p.coverImage || null,
          content: p.content || '',
        }));
        if (mapped.length) setPosts(mapped);
      } catch (e) {
        console.warn('WP posts load failed', e);
      }
    })();
    return () => { mounted = false };
  }, []);
  return (
    <>
      <section className="wrap">
        <div style={{padding: "clamp(40px, 6vw, 80px) 0 clamp(32px, 5vw, 60px)"}}>
          <Reveal><span className="hero__kicker">Insights · long-form</span></Reveal>
          <Reveal delay={80}>
            <h1 className="about-hero__title" style={{marginTop: 24, maxWidth: 1200}}>
              Notes from inside the <em>growth machine</em>.
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p style={{color: "var(--fg-2)", fontSize: 18, maxWidth: 640, lineHeight: 1.55}}>
              Monthly essays on strategy, performance, SEO, and the craft of building brands that compound.
              Written for operators, read by founders.
            </p>
          </Reveal>

          <Reveal delay={200}>
            <div className="chips" style={{marginTop: 32}}>
              {filters.map((t) => (
                <button key={t} className={filter === t ? "is-active" : ""} onClick={() => setFilter(t)}>{t}</button>
              ))}
            </div>
          </Reveal>
        </div>
      </section>

      <section>
        <div className="posts">
          {shown.map((p, i) => (
            <Reveal key={p.title} delay={i * 50} className={"post" + (p.feature ? " post--feature" : "")} as="div">
              <div
                className="post__img"
                onClick={() => onOpenPost(p)}
                style={p.img ? { backgroundImage: `url(${p.img})` } : undefined}
              />
              <div className="post__meta">
                <span>{p.tag}</span>
                <span>{p.date}</span>
              </div>
              <h3 className="post__title" onClick={() => onOpenPost(p)}>{p.title}</h3>
              <div className="post__read" onClick={() => onOpenPost(p)}>{p.read}</div>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="cta-big">
        <div className="wrap">
          <Reveal><h2 className="cta-big__title">Get the <em>monthly note.</em></h2></Reveal>
          <Reveal delay={120}>
            <p style={{fontSize: 18, maxWidth: 540, color: "color-mix(in oklab, var(--bg) 70%, transparent)", marginBottom: 32}}>
              One essay a month. No tips & tricks. No funnel hacks. Just sharp thinking about growth.
            </p>
          </Reveal>
          <Reveal delay={160}>
            <div className="cta-big__row">
              <div style={{display: "flex", gap: 0, alignItems: "stretch", border: "1px solid color-mix(in oklab, var(--bg) 40%, transparent)", borderRadius: 999, overflow: "hidden", background: "transparent", maxWidth: 480, width: "100%"}}>
                <input placeholder="your@email.com" style={{
                  flex: 1, background: "transparent", border: "none", padding: "14px 22px",
                  color: "var(--bg)", font: "inherit", fontSize: 14, outline: "none"
                }} />
                <button className="btn btn--primary" style={{borderRadius: 0, margin: 0}} onClick={() => alert("subscribe placeholder")}>
                  Subscribe <span className="arr">↗</span>
                </button>
              </div>
            </div>
          </Reveal>
        </div>
      </section>
    </>
  );
}

function PostPage({ post, onGo, onOpenPost }) {
  const D = window.DATA;
  const related = D.posts.filter(p => p.title !== post.title).slice(0, 3);
  const [tocItems, setTocItems] = useState([]);
  const [bodyHtml, setBodyHtml] = useState(post.content || '');
  const bodyClassName = tocItems.length > 0 ? 'post-body' : 'post-body post-body--no-toc';

  function slugifyHeading(text) {
    return String(text || '')
      .toLowerCase()
      .trim()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }

  useEffect(() => {
    if (!post.content) {
      setTocItems([]);
      setBodyHtml('');
      return;
    }
    const parser = new DOMParser();
    const doc = parser.parseFromString(post.content, 'text/html');
    const headings = Array.from(doc.querySelectorAll('h2, h3'));
    const items = headings.map((heading, index) => {
      const text = heading.textContent.trim();
      const id = heading.id || `heading-${index}-${slugifyHeading(text)}`;
      heading.id = id;
      return {
        id,
        text: text || `Section ${index + 1}`,
        level: heading.tagName.toLowerCase() === 'h3' ? 3 : 2,
      };
    });
    setTocItems(items);
    setBodyHtml(doc.body.innerHTML);
  }, [post.content]);

  // Generate reading progress
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const el = document.getElementById("article-body");
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      const scrolled = Math.min(Math.max(-rect.top, 0), total);
      setProgress(total > 0 ? (scrolled / total) * 100 : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [post.title]);

  return (
    <>
      {/* Reading progress */}
      <div style={{position: "fixed", top: 72, left: 0, right: 0, height: 2, zIndex: 45, background: "transparent"}}>
        <div style={{height: "100%", width: progress + "%", background: "var(--accent)", transition: "width .1s linear"}} />
      </div>

      <article>
        {/* Hero */}
        <section className="wrap">
          <div style={{padding: "clamp(40px, 5vw, 72px) 0 clamp(24px, 3vw, 48px)"}}>
            <Reveal>
              <button className="post-back" onClick={() => onGo("insights")}>← All essays</button>
            </Reveal>
            <Reveal delay={80}>
              <div className="post-meta-row">
                <span className="post-meta-row__tag">{post.tag}</span>
                <span>·</span>
                <span>{post.date}</span>
                <span>·</span>
                <span>{post.read}</span>
              </div>
            </Reveal>
            <Reveal delay={160}>
              <h1 className="post-title">{post.title}</h1>
            </Reveal>
            <Reveal delay={220}>
              <div className="post-author">
                <div className="post-author__avatar">S</div>
                <div>
                  <div className="post-author__name">Stanzin</div>
                  <div className="post-author__role">Growth Partner · Bengaluru</div>
                </div>
              </div>
            </Reveal>
          </div>
        </section>

        {/* Feature image */}
        <section className="wrap">
          <Reveal>
            <div
              className="post-hero-img"
              style={post.img ? { backgroundImage: `url(${post.img})` } : undefined}
            />
          </Reveal>
        </section>

        {/* Body */}
        <section className="wrap">
          <div id="article-body" className={bodyClassName}>
            {tocItems.length > 0 && (
              <aside className="post-toc">
                <div className="post-toc__label">On this page</div>
                {tocItems.map(item => (
                  <a
                    key={item.id}
                    href={`#${item.id}`}
                    className={item.level === 3 ? 'post-toc__sub' : ''}
                    onClick={(e) => {
                      e.preventDefault();
                      const el = document.getElementById(item.id);
                      if (el) {
                        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        // update URL hash without triggering history navigation
                        window.history.replaceState(window.history.state, '', `#${item.id}`);
                      }
                    }}
                  >
                    {item.text}
                  </a>
                ))}
              </aside>
            )}

            {/* Article */}
            <div className="post-prose">
              {bodyHtml ? (
                <div dangerouslySetInnerHTML={{ __html: bodyHtml }} />
              ) : (
                <>
                  <p className="post-lede">No post body available yet.</p>
                  <p>Please publish the post with valid body content from the WordPress CMS.</p>
                </>
              )}
            </div>
          </div>
        </section>

        {/* Author card */}
        <section className="wrap">
          <div className="post-author-card">
            <div className="post-author-card__avatar">S</div>
            <div>
              <div className="post-author-card__name">Stanzin</div>
              <p className="post-author-card__bio">Independent growth partner for D2C brands and B2B SaaS teams. Seven years inside growth functions. Currently consulting with six brands from Bengaluru.</p>
              <div className="post-author-card__cta">
                <button className="btn btn--ghost" onClick={() => onGo("about")}>About <span className="arr">→</span></button>
                <button className="btn btn--primary" onClick={() => onGo("contact")}>Work with me <span className="arr">↗</span></button>
              </div>
            </div>
          </div>
        </section>

        {/* Related */}
        <section className="section">
          <div className="wrap">
            <SectionHead num="· Keep reading" titleHtml="More <em>essays</em>." />
            <div className="posts" style={{border: "none"}}>
              {related.map((p, i) => (
                <Reveal key={p.title} delay={i * 50} className="post" as="div">
                  <div
                    className="post__img"
                    onClick={() => onOpenPost(p)}
                    style={p.img ? { backgroundImage: `url(${p.img})` } : undefined}
                  />
                  <div className="post__meta">
                    <span>{p.tag}</span>
                    <span>{p.date}</span>
                  </div>
                  <h3 className="post__title" onClick={() => onOpenPost(p)}>{p.title}</h3>
                  <div className="post__read" onClick={() => onOpenPost(p)}>{p.read}</div>
                </Reveal>
              ))}
            </div>
          </div>
        </section>

        <section className="cta-big">
          <div className="wrap">
            <Reveal><h2 className="cta-big__title">Get the <em>monthly note.</em></h2></Reveal>
            <Reveal delay={120}>
              <div className="cta-big__row">
                <button className="btn btn--primary" onClick={() => onGo("contact")}>Subscribe ↗</button>
                <button className="btn btn--ghost" onClick={() => onGo("insights")}>All essays →</button>
              </div>
            </Reveal>
          </div>
        </section>
      </article>
    </>
  );
}

window.InsightsPage = InsightsPage;
window.PostPage = PostPage;
