// ─── Post Page App ───

function getSlugFromPath() {
  // URL pattern: /blog/some-slug/ → extract "some-slug"
  const path = window.location.pathname.replace(/\/$/, "");
  const parts = path.split("/");
  return parts[parts.length - 1];
}

function PostHero({ post }) {
  return (
    <section className="post-hero">
      <div className="container">
        <div className="post-hero-inner">
          <h1>{post.title}</h1>
          {post.deck && <p className="deck">{post.deck}</p>}
          <div className="author-row">
            <img src="/assets/logomark.png" alt="vialprep" className="author-avatar" />
            <div>
              <span className="author-name">vialprep</span>
              <span className="author-meta">{formatDate(post.date)}{post.updated && post.updated !== post.date ? ` · Updated ${formatDate(post.updated)}` : ""} · {post.readingTime} min read</span>
            </div>
          </div>
          {post.heroImage && (
            <img
              src={post.heroImage}
              alt={post.heroAlt || post.title}
              className="post-hero-img"
            />
          )}
        </div>
      </div>
    </section>
  );
}

function TableOfContents({ body }) {
  const headings = body.filter(b => b.type === "h2" || b.type === "h2-numbered").map(b => b.text);
  const [open, setOpen] = React.useState(false);
  if (headings.length < 3) return null;

  return (
    <nav className="toc">
      <button className="toc-toggle" onClick={() => setOpen(!open)}>
        <span className="toc-label">Contents</span>
        <span className="toc-arrow" style={{ transform: open ? "rotate(180deg)" : "none" }}>▾</span>
      </button>
      {open && (
        <ol className="toc-list">
          {headings.map((text, i) => (
            <li key={i}><a href={`#${text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-$/, "")}`}>{text}</a></li>
          ))}
        </ol>
      )}
    </nav>
  );
}

function EndCTA() {
  return (
    <div className="end-cta">
      <h3>Ready to stop sourcing supplies?</h3>
      <p>Everything you need, packed and sealed, at your door every month.</p>
      <a
        className="btn btn-accent"
        href="/waitlist/"
        onClick={() => gtag("event", "waitlist_click", { event_category: "conversion", link_location: "blog_end_cta" })}
      >
        Join the waitlist <IArrow size={14} />
      </a>
    </div>
  );
}

function RelatedPosts({ posts, currentSlug, currentCategory }) {
  if (!posts || posts.length === 0) return null;

  // 1 from same category, 2 from others, exclude current
  const others = posts.filter(p => p.slug !== currentSlug);
  const sameCategory = others.filter(p => p.category === currentCategory);
  const diffCategory = others.filter(p => p.category !== currentCategory);

  const related = [];
  if (sameCategory.length > 0) related.push(sameCategory[0]);
  for (const p of diffCategory) {
    if (related.length >= 3) break;
    related.push(p);
  }
  // Fill remaining from same category if needed
  for (const p of sameCategory.slice(1)) {
    if (related.length >= 3) break;
    related.push(p);
  }

  if (related.length === 0) return null;

  return (
    <section className="related-section">
      <div className="container" style={{ maxWidth: 1080 }}>
        <h3>Keep reading.</h3>
        <div className="post-grid">
          {related.map(post => <PostCard key={post.slug} post={post} />)}
        </div>
      </div>
    </section>
  );
}

function ScrollTracker() {
  React.useEffect(() => {
    const thresholds = [25, 50, 75, 100];
    const fired = new Set();
    const handleScroll = () => {
      const scrollPct = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
      for (const t of thresholds) {
        if (scrollPct >= t && !fired.has(t)) {
          fired.add(t);
          gtag("event", "article_scroll", { event_category: "engagement", scroll_depth: t });
        }
      }
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);
  return null;
}

function PostApp() {
  const [post, setPost] = React.useState(null);
  const [allPosts, setAllPosts] = React.useState([]);
  const [error, setError] = React.useState(false);

  const slug = React.useMemo(getSlugFromPath, []);

  React.useEffect(() => {
    fetch(`/blog/posts/${slug}.json`)
      .then(r => { if (!r.ok) throw new Error("Not found"); return r.json(); })
      .then(data => {
        setPost(data);
        // Update document title and meta
        document.title = `${data.title} | The Long Game by vialprep`;
        const desc = document.querySelector('meta[name="description"]');
        if (desc) desc.setAttribute("content", data.deck || "");
        const ogTitle = document.querySelector('meta[property="og:title"]');
        if (ogTitle) ogTitle.setAttribute("content", data.title);
        const ogDesc = document.querySelector('meta[property="og:description"]');
        if (ogDesc) ogDesc.setAttribute("content", data.deck || "");
        if (data.heroImage) {
          const ogImg = document.querySelector('meta[property="og:image"]');
          if (ogImg) ogImg.setAttribute("content", `https://vialprep.com${data.heroImage}`);
        }

        // Inject Article schema
        const schema = {
          "@context": "https://schema.org",
          "@type": "Article",
          "headline": data.title,
          "datePublished": data.date,
          "dateModified": data.updated || data.date,
          "author": { "@type": "Organization", "name": "vialprep", "url": "https://vialprep.com/" },
          "publisher": {
            "@type": "Organization", "name": "vialprep",
            "logo": { "@type": "ImageObject", "url": "https://vialprep.com/assets/logomark.png" }
          },
          "image": data.heroImage ? `https://vialprep.com${data.heroImage}` : undefined,
          "description": data.deck,
          "mainEntityOfPage": { "@type": "WebPage", "@id": `https://vialprep.com/blog/${data.slug}/` },
          "breadcrumb": {
            "@type": "BreadcrumbList",
            "itemListElement": [
              { "@type": "ListItem", "position": 1, "name": "Home", "item": "https://vialprep.com/" },
              { "@type": "ListItem", "position": 2, "name": "The Long Game", "item": "https://vialprep.com/blog/" },
              { "@type": "ListItem", "position": 3, "name": data.title }
            ]
          }
        };
        const script = document.createElement("script");
        script.type = "application/ld+json";
        script.textContent = JSON.stringify(schema);
        document.head.appendChild(script);

        // Inject FAQPage schema if post has FAQ data
        if (data.faq && data.faq.length > 0) {
          const faqSchema = {
            "@context": "https://schema.org",
            "@type": "FAQPage",
            "mainEntity": data.faq.map(q => ({
              "@type": "Question",
              "name": q.question,
              "acceptedAnswer": {
                "@type": "Answer",
                "text": q.answer
              }
            }))
          };
          const faqScript = document.createElement("script");
          faqScript.type = "application/ld+json";
          faqScript.textContent = JSON.stringify(faqSchema);
          document.head.appendChild(faqScript);
        }
      })
      .catch(() => setError(true));

    fetch("/blog/posts.json")
      .then(r => r.json())
      .then(data => setAllPosts(data))
      .catch(() => {});
  }, [slug]);

  if (error) {
    return (
      <>
        <BlogNav />
        <section className="post-hero" style={{ textAlign: "center", paddingBottom: 80 }}>
          <div className="container">
            <h1 style={{ color: "#F4F1EA", fontFamily: "var(--font-display)", fontSize: 36, fontWeight: 800, marginBottom: 16 }}>Not found.</h1>
            <p style={{ color: "rgba(244,241,234,0.5)", fontSize: 17 }}>This post doesn't exist or has been moved.</p>
            <a href="/blog/" className="btn btn-ghost-dark" style={{ marginTop: 24 }}>Back to The Long Game</a>
          </div>
        </section>
        <BlogFooter />
      </>
    );
  }

  if (!post) return null;

  return (
    <>
      <BlogNav />
      <ScrollTracker />
      <PostHero post={post} />

      <div className="container">
        <div className="article-wrap">
          <TableOfContents body={post.body} />
          <ArticleRenderer body={post.body} />
          <EndCTA />
        </div>
      </div>

      <RelatedPosts posts={allPosts} currentSlug={slug} currentCategory={post.category} />
      <NewsletterCTA />
      <BlogFooter />
    </>
  );
}

// ─── Mount ───
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<PostApp />);
