// Just Travel — Single article page (React via Babel)
// Loaded AFTER React UMD, landing-sections.jsx, landing-footer.jsx, blog-data.js.
// Shares ONE global scope with the other page scripts, so every top-level name
// here is prefixed AR_/ARApp and we reach for React.* directly (no destructuring,
// no import/export/require). Reuses the globals Navbar, Footer, SIcon, Reveal.

const AR_articleHref = (slug) => "Artigo.html?slug=" + encodeURIComponent(slug);

// Create-or-update a <meta name=...> or <link rel=...> in the document head.
// Used by the interim per-article meta effect below: the static Artigo.html head
// carries a blog-wide default, and this overwrites it in place once a post loads.
const AR_setMeta = (name, content) => {
  let el = document.head.querySelector('meta[name="' + name + '"]');
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute("name", name);
    document.head.appendChild(el);
  }
  el.setAttribute("content", content == null ? "" : content);
};
const AR_setLink = (rel, href) => {
  let el = document.head.querySelector('link[rel="' + rel + '"]');
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", rel);
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
};

// Decorative share buttons — no real sharing wired up.
const AR_SHARE = ["external", "chat", "plane"];
const AR_shareBtnStyle = {
  width: 40,
  height: 40,
  borderRadius: "50%",
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  border: "1.5px solid var(--ink-900)",
  background: "transparent",
  color: "var(--ink-900)",
  cursor: "pointer",
};

// Render one body block from the Post.body[] shape.
function AR_Block({ block }) {
  if (block.type === "h2") return <h2>{block.text}</h2>;
  if (block.type === "ul") {
    return (
      <ul>
        {block.items.map((it, i) => (
          <li key={i}>{it}</li>
        ))}
      </ul>
    );
  }
  if (block.type === "quote") {
    return (
      <blockquote className="ar-quote">
        <p>{block.text}</p>
        {block.cite && <cite>{block.cite}</cite>}
      </blockquote>
    );
  }
  return <p>{block.text}</p>;
}

function ARApp() {
  const posts = window.BLOG_POSTS || [];
  const slug = new URLSearchParams(location.search).get("slug");
  const post = posts.find((p) => p.slug === slug);

  // Interim per-article meta, client-side, until per-article static pages ship.
  // Called before the not-found return so the hook order is stable; it no-ops
  // when no post resolved, leaving the static blog-wide default head in place.
  React.useEffect(() => {
    if (!post) return;
    document.title = post.title + " | Just Travel";
    AR_setLink(
      "canonical",
      "https://justtraveltour.com/Artigo.html?slug=" + encodeURIComponent(slug)
    );
    AR_setMeta("description", post.excerpt);
  }, [post, slug]);

  // Not found — offer a way back to the listing.
  if (!post) {
    return (
      <PageShell>
        <main>
          <section className="section">
            <div className="container">
              <div className="ar-missing">
                <h1 className="ar-title" style={{ fontSize: "2rem" }}>
                  Artigo não encontrado
                </h1>
                <p className="lead" style={{ margin: "16px 0 28px" }}>
                  O artigo que você procura não existe ou foi movido.
                </p>
                <a className="btn btn--blue btn--md" href="Blog.html">
                  Voltar para o blog
                  <span className="btn__arrow">
                    <SIcon name="btnArrow" />
                  </span>
                </a>
              </div>
            </div>
          </section>
        </main>
        </PageShell>
    );
  }

  const related = posts.filter((p) => p.slug !== post.slug).slice(0, 3);

  return (
    <PageShell>
      <main>
        {/* HERO */}
        <section className="ar-hero">
          <Reveal as="div" className="ar-wrap">
            <a className="ar-back" href="Blog.html">
              <SIcon name="arrowRight" size={16} />
              Voltar para o blog
            </a>
            <span className="ar-cat">{post.category}</span>
            <h1 className="ar-title">{post.title}</h1>
            <div className="ar-byline">
              <span className="ar-avatar">{post.initials}</span>
              <div>
                <div className="ar-by__name">{post.author}</div>
                <div className="ar-by__meta">
                  {post.date} · {post.read}
                </div>
              </div>
            </div>
          </Reveal>
        </section>

        {/* COVER */}
        <div className="ar-wrap">
          <img className="ar-cover" src={post.cover} alt={post.title} />
        </div>

        {/* BODY */}
        <div className="ar-body">
          {post.body.map((block, i) => (
            <AR_Block key={i} block={block} />
          ))}

          <div className="ar-share">
            <span className="ar-share__lbl">Compartilhar</span>
            {AR_SHARE.map((name) => (
              <button
                key={name}
                type="button"
                aria-label="Compartilhar artigo"
                style={AR_shareBtnStyle}
              >
                <SIcon name={name} size={18} />
              </button>
            ))}
          </div>
        </div>

        {/* RELATED */}
        {related.length > 0 && (
          <section className="section">
            <div className="ar-wrap">
              <span className="eyebrow">Continue lendo</span>
              <div className="ar-rel">
                {related.map((p) => (
                  <a
                    key={p.slug}
                    className="ar-rel__card"
                    href={AR_articleHref(p.slug)}
                  >
                    <div
                      className="ar-rel__media"
                      style={{
                        backgroundImage: p.cover ? `url(${p.cover})` : undefined,
                      }}
                    ></div>
                    <div className="ar-rel__cat">{p.category}</div>
                    <div className="ar-rel__title">{p.title}</div>
                  </a>
                ))}
              </div>
            </div>
          </section>
        )}
      </main>
      </PageShell>
  );
}

(function () {
  const el = document.getElementById("app");
  if (!el) return;
  ReactDOM.createRoot(el).render(<ARApp />);
})();
