// OnCatch blog post renderer.
// Fetches a markdown file at /blog/_drafts/<slug>.md and renders it inline with
// the site's Header/Footer + a post header. Markdown rendering via marked.js
// (loaded via CDN in each blog HTML page).

const parseFrontmatter = (md) => {
  const match = md.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
  if (!match) return { meta: {}, body: md };
  const [, fm, body] = match;
  const meta = {};
  fm.split("\n").forEach((line) => {
    const m = line.match(/^([^:]+):\s*(.*)$/);
    if (m) meta[m[1].trim()] = m[2].trim();
  });
  return { meta, body };
};

const BlogPost = ({ slug }) => {
  const [meta, setMeta] = React.useState({});
  const [bodyHtml, setBodyHtml] = React.useState("");

  React.useEffect(() => {
    fetch(`_drafts/${slug}.md`)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.text();
      })
      .then((md) => {
        const { meta: m, body } = parseFrontmatter(md);
        setMeta(m);
        setBodyHtml(window.marked.parse(body));
      })
      .catch((e) => setBodyHtml(`<p>Failed to load post: ${e.message}</p>`));
  }, [slug]);

  return (
    <div className="page blog-page">
      <Header active="blog" />

      <main id="main-content">
        <article className="container blog-article">
          <header className="blog-header">
            <SectionEyebrow>
              <a href="index.html" style={{ color: "inherit" }}>← All comparisons</a>
            </SectionEyebrow>
            <div className="blog-meta">
              <span className="mono blog-meta-date">{meta.date || ""}</span>
              {meta.competitor && (
                <>
                  <span className="blog-meta-sep">·</span>
                  <span className="blog-meta-cat">vs. {meta.competitor}</span>
                </>
              )}
              {meta.competitor_url && (
                <>
                  <span className="blog-meta-sep">·</span>
                  <a href={meta.competitor_url} target="_blank" rel="noreferrer" className="blog-meta-link mono">
                    {meta.competitor_url.replace(/^https?:\/\//, "")}
                  </a>
                </>
              )}
            </div>
            <h1 className="h-display blog-title">{meta.title || "Loading…"}</h1>
            {meta.tagline && <p className="lede blog-subtitle">{meta.tagline}</p>}
          </header>

          <div
            className="blog-body"
            dangerouslySetInnerHTML={{ __html: bodyHtml || '<p class="muted">Loading…</p>' }}
          />

          <div className="blog-cta">
            <h2 className="h-1">Try OnCatch yourself.</h2>
            <p className="lede">
              Free during pilot. No credit card. Pilot teams are typically up
              and running the same day. If we're not the right fit, the
              alternatives we've covered are good — go try them. We'd rather
              have you on the right tool than the wrong one.
            </p>
            <SignupForm />
          </div>

          <nav className="blog-other">
            <h3 className="h-3">Other comparisons</h3>
            <ul>
              <li><a href="oncatch-vs-userback.html">OnCatch vs. Userback</a></li>
              <li><a href="oncatch-vs-marker-io.html">OnCatch vs. Marker.io</a></li>
              <li><a href="oncatch-vs-bugherd.html">OnCatch vs. BugHerd</a></li>
              <li><a href="oncatch-vs-bird-eats-bug.html">OnCatch vs. Bird Eats Bug</a></li>
              <li><a href="oncatch-vs-jam-dev.html">OnCatch vs. Jam.dev</a></li>
              <li><a href="oncatch-vs-gleap.html">OnCatch vs. Gleap</a></li>
              <li><a href="oncatch-vs-feedbear.html">OnCatch vs. FeedBear</a></li>
            </ul>
            <p className="muted" style={{ marginTop: 16, fontSize: 14 }}>
              Or see the <a href="../compare.html">full feature matrix</a> across all 7 competitors.
            </p>
          </nav>
        </article>
      </main>

      <Footer />
    </div>
  );
};

const BlogIndex = () => {
  const POSTS = [
    { slug: "oncatch-vs-userback", competitor: "Userback", url: "https://userback.io",
      tagline: "The category benchmark — most complete feature set, biggest integrations roster, mature pricing tiers. Here's where we line up." },
    { slug: "oncatch-vs-marker-io", competitor: "Marker.io", url: "https://marker.io",
      tagline: "Best-in-class for Jira shops. We're built for teams that aren't on Jira (or want to leave)." },
    { slug: "oncatch-vs-bugherd", competitor: "BugHerd", url: "https://bugherd.com",
      tagline: "Pin-to-element pioneer, agency favorite. We're going after teams that need more than visual feedback." },
    { slug: "oncatch-vs-bird-eats-bug", competitor: "Bird Eats Bug", url: "https://birdeatsbug.com",
      tagline: "Screen-recording-first capture for internal QA. We're the embedded widget on your customers' sites." },
    { slug: "oncatch-vs-jam-dev", competitor: "Jam.dev", url: "https://jam.dev",
      tagline: "Browser-extension-first, free tier. We're the embed-first option for end-user feedback." },
    { slug: "oncatch-vs-gleap", competitor: "Gleap", url: "https://gleap.io",
      tagline: "All-in-one feedback platform with chat + roadmap. We're the focused bug-reporting tool." },
    { slug: "oncatch-vs-feedbear", competitor: "FeedBear", url: "https://feedbear.com",
      tagline: "Public feedback boards (different category — feature requests, not bugs). When you'd run both." },
  ];
  return (
    <div className="page blog-page">
      <Header active="blog" />
      <main>
        <section className="container page-hero">
          <div>
            <SectionEyebrow>Blog · Honest comparisons</SectionEyebrow>
            <h1 className="h-display" style={{ marginTop: 16 }}>
              How we compare to the competition.
            </h1>
          </div>
          <div>
            <p className="lede">
              Seven posts, one per major competitor. Each one is honest about
              what they do well, where we beat them, and where we're catching
              up. Written for engineers and team leads picking the right tool —
              not for SEO.
            </p>
            <p className="lede" style={{ marginTop: 12 }}>
              Want the data view instead?{" "}
              <a href="../compare.html" style={{ color: "var(--accent)", fontWeight: 600 }}>
                Full feature matrix across all 7 →
              </a>
            </p>
          </div>
        </section>

        <section className="container section">
          <div className="blog-list">
            {POSTS.map(({ slug, competitor, url, tagline }) => (
              <a key={slug} href={`${slug}.html`} className="blog-list-cell">
                <div className="blog-list-meta">
                  <span className="blog-list-vs">vs.</span>
                  <span className="blog-list-name">{competitor}</span>
                  <span className="blog-list-url mono muted">{url.replace(/^https?:\/\//, "")}</span>
                </div>
                <h2 className="h-2 blog-list-title">{tagline}</h2>
                <span className="blog-list-arrow mono">Read →</span>
              </a>
            ))}
          </div>
        </section>

        <section className="container section-tight" id="signup">
          <div className="cta-band">
            <div>
              <SectionEyebrow><span style={{ color: "var(--accent-soft)" }}>● </span>Early access · Free during pilot</SectionEyebrow>
              <h2 className="h-1" style={{ marginTop: 18 }}>Try OnCatch.</h2>
              <p className="lede" style={{ marginTop: 12 }}>
                Pilot teams are up and running the same day. Free until GA.
              </p>
            </div>
            <SignupForm />
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
};

Object.assign(window, { BlogPost, BlogIndex });
