/* global React, ReactDOM, Header, Footer */

const { useState: useStateB, useEffect: useEffectB } = React;

/* ============================================================
   Tiny markdown parser (safe-ish: escapes HTML first)
   ============================================================ */
function escapeHtml(str) {
  return str.replace(/[&<>"']/g, (c) => ({
    "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
  })[c]);
}

function md(src) {
  if (!src) return "";
  let s = src;
  // Code blocks
  const blocks = [];
  s = s.replace(/```([\s\S]*?)```/g, (_, code) => {
    blocks.push(`<pre><code>${escapeHtml(code.trim())}</code></pre>`);
    return `\u0000BLOCK${blocks.length - 1}\u0000`;
  });
  // Images
  const imgs = [];
  s = s.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src2) => {
    imgs.push(`<figure class="post-figure"><img src="${src2}" alt="${escapeHtml(alt)}" loading="lazy"/>${alt ? `<figcaption>${escapeHtml(alt)}</figcaption>` : ""}</figure>`);
    return `\u0000IMG${imgs.length - 1}\u0000`;
  });
  s = escapeHtml(s);
  s = s.replace(/^### (.+)$/gm, "<h3>$1</h3>");
  s = s.replace(/^## (.+)$/gm, "<h2>$1</h2>");
  s = s.replace(/^# (.+)$/gm, "<h1>$1</h1>");
  s = s.replace(/^&gt; (.+)$/gm, "<blockquote>$1</blockquote>");
  s = s.replace(/(^|\n)((?:- [^\n]+(?:\n|$))+)/g, (m, pre, list) => {
    const items = list.trim().split(/\n/).map(l => l.replace(/^- /, "")).map(t => `<li>${t}</li>`).join("");
    return `${pre}<ul>${items}</ul>`;
  });
  s = s.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  s = s.replace(/\*(.+?)\*/g, "<em>$1</em>");
  s = s.replace(/`([^`]+)`/g, "<code>$1</code>");
  s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
  s = s.split(/\n{2,}/).map(block => {
    const trimmed = block.trim();
    if (!trimmed) return "";
    if (/^<(h\d|ul|ol|pre|blockquote)/.test(trimmed) || /\u0000(IMG|BLOCK)\d+\u0000/.test(trimmed)) return trimmed;
    return `<p>${trimmed.replace(/\n/g, "<br/>")}</p>`;
  }).join("\n");
  s = s.replace(/\u0000IMG(\d+)\u0000/g, (_, i) => imgs[+i]);
  s = s.replace(/\u0000BLOCK(\d+)\u0000/g, (_, i) => blocks[+i]);
  return s;
}

/* ============================================================
   Cover renderer — image if available, fallback SVG
   ============================================================ */
function CoverImg({ post, big }) {
  const c = post.cover;
  // Handle old format (number) and new (object)
  if (typeof c === "number") {
    return <CoverSVG kind={c} />;
  }
  if (c && c.image) {
    return <img src={c.image} alt={c.alt || ""} className={"cover-real " + (big ? "big" : "")} loading="lazy" />;
  }
  return <CoverSVG kind={(c && c.fallback) || 1} />;
}

function CoverSVG({ kind }) {
  if (kind === 1) {
    return (
      <svg width="100%" height="100%" viewBox="0 0 600 240" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        {[18, 42, 32, 60, 48, 84, 72, 96, 78, 108, 92, 124, 100, 132].map((h, i) =>
          <rect key={i} x={36 + i * 38} y={220 - h} width="24" height={h} rx="2"
                fill={i === 10 ? "#C9A24A" : "rgba(246,244,238,0.32)"} />
        )}
      </svg>
    );
  }
  if (kind === 2) {
    return (
      <svg width="100%" height="100%" viewBox="0 0 600 240" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        {[0, 1, 2].map((i) => (
          <g key={i} transform={`translate(${110 + i * 140}, 36)`}>
            <rect x="0" y="0" width="100" height="170" rx="6" fill="rgba(246,244,238,0.06)" stroke="rgba(246,244,238,0.18)" />
            <rect x="14" y="20" width="72" height="6" rx="2" fill="rgba(246,244,238,0.4)" />
            <rect x="14" y="34" width="52" height="6" rx="2" fill="rgba(246,244,238,0.25)" />
            <rect x="14" y="60" width="24" height="24" rx="3" fill={i === 1 ? "#C9A24A" : "rgba(246,244,238,0.2)"} />
            <rect x="46" y="68" width="40" height="6" rx="2" fill="rgba(246,244,238,0.3)" />
            <rect x="14" y="92" width="24" height="24" rx="3" fill="rgba(246,244,238,0.2)" />
            <rect x="46" y="100" width="40" height="6" rx="2" fill="rgba(246,244,238,0.3)" />
            <rect x="14" y="124" width="24" height="24" rx="3" fill="rgba(246,244,238,0.2)" />
            <rect x="46" y="132" width="40" height="6" rx="2" fill="rgba(246,244,238,0.3)" />
          </g>
        ))}
      </svg>
    );
  }
  return (
    <svg width="100%" height="100%" viewBox="0 0 600 240" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <g stroke="rgba(246,244,238,0.18)" fill="none" strokeWidth="1.5">
        <circle cx="300" cy="120" r="92" />
        <circle cx="300" cy="120" r="64" />
        <circle cx="300" cy="120" r="36" />
      </g>
      <circle cx="300" cy="120" r="6" fill="#C9A24A" />
      <circle cx="392" cy="120" r="5" fill="#F6F4EE" />
      <circle cx="208" cy="120" r="5" fill="#F6F4EE" />
      <circle cx="354" cy="68"  r="5" fill="#F6F4EE" />
      <circle cx="246" cy="172" r="5" fill="#F6F4EE" />
      <circle cx="368" cy="184" r="4" fill="rgba(246,244,238,0.6)" />
      <circle cx="232" cy="56"  r="4" fill="rgba(246,244,238,0.6)" />
    </svg>
  );
}

/* ============================================================
   SEO meta tag injection
   ============================================================ */
function setMetaTag(attr, key, value) {
  let el = document.querySelector(`meta[${attr}="${key}"]`);
  if (!value) { if (el) el.remove(); return; }
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute(attr, key);
    document.head.appendChild(el);
  }
  el.setAttribute("content", value);
}
function setLinkCanonical(href) {
  let el = document.querySelector('link[rel="canonical"]');
  if (!href) { if (el) el.remove(); return; }
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", "canonical");
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}
function setJsonLd(data) {
  let el = document.getElementById("ms-jsonld");
  if (el) el.remove();
  if (!data) return;
  el = document.createElement("script");
  el.type = "application/ld+json";
  el.id = "ms-jsonld";
  el.textContent = JSON.stringify(data);
  document.head.appendChild(el);
}
function applyPostSEO(post, siteUrl) {
  if (!post) {
    document.title = "Blog · MinerSuite";
    setMetaTag("name", "description", "Conteúdo técnico para consultorias em mineração.");
    setMetaTag("property", "og:title", "Blog · MinerSuite");
    setMetaTag("property", "og:description", "Conteúdo técnico para consultorias em mineração.");
    setMetaTag("property", "og:type", "website");
    setMetaTag("property", "og:image", "");
    setMetaTag("name", "twitter:card", "summary_large_image");
    setLinkCanonical(siteUrl + "/blog.html");
    setJsonLd(null);
    return;
  }
  const seo = post.seo || {};
  const url = siteUrl + "/blog.html#" + post.slug;
  const img = (post.cover && post.cover.image) ? (siteUrl + "/" + post.cover.image) : "";
  const title = seo.metaTitle || post.title;
  const desc = seo.metaDescription || post.excerpt;
  document.title = title;
  setMetaTag("name", "description", desc);
  setMetaTag("name", "keywords", (post.tags || []).join(", "));
  setMetaTag("name", "author", post.author);
  setMetaTag("property", "og:type", "article");
  setMetaTag("property", "og:title", title);
  setMetaTag("property", "og:description", desc);
  setMetaTag("property", "og:url", url);
  setMetaTag("property", "og:image", img);
  setMetaTag("property", "article:published_time", post.date);
  setMetaTag("property", "article:section", post.category);
  setMetaTag("name", "twitter:card", "summary_large_image");
  setMetaTag("name", "twitter:title", title);
  setMetaTag("name", "twitter:description", desc);
  setMetaTag("name", "twitter:image", img);
  setLinkCanonical(url);
  setJsonLd({
    "@context": "https://schema.org",
    "@type": "Article",
    "headline": post.title,
    "description": desc,
    "image": img || undefined,
    "datePublished": post.date,
    "dateModified": post.date,
    "author": { "@type": "Organization", "name": post.author },
    "publisher": {
      "@type": "Organization",
      "name": "MinerSuite",
      "logo": { "@type": "ImageObject", "url": siteUrl + "/assets/marca/favicon.svg" }
    },
    "mainEntityOfPage": url,
    "keywords": (post.tags || []).join(", ")
  });
}

function formatDate(iso) {
  const d = new Date(iso + "T00:00:00");
  const MES = ["JAN","FEV","MAR","ABR","MAI","JUN","JUL","AGO","SET","OUT","NOV","DEZ"];
  return `${String(d.getDate()).padStart(2,"0")} ${MES[d.getMonth()]} · ${d.getFullYear()}`;
}

/* ============================================================
   Hero
   ============================================================ */
function BlogHero({ count }) {
  return (
    <section className="blog-hero">
      <div className="container">
        <div className="blog-hero-inner">
          <div style={{ display: "grid", gap: 24 }}>
            <span className="eyebrow" style={{ color: "var(--ms-gold-soft)" }}>BLOG · MINERSUITE</span>
            <h1>
              Conteúdo técnico para <span className="gold">consultorias em mineração.</span>
            </h1>
            <p className="lede">
              Artigos sobre gestão operacional, propostas, contratos, projetos
              técnicos e organização de carteira minerária — escritos a partir
              da rotina real do setor.
            </p>
          </div>
          <div className="blog-hero-meta">
            <div className="m">
              <span className="k">ARTIGOS</span>
              <span className="v">{count}</span>
              <span className="s">Publicados até hoje.</span>
            </div>
            <div className="m">
              <span className="k">CATEGORIAS</span>
              <span className="v">Gestão · Operação · Dados</span>
              <span className="s">Conteúdo técnico do setor mineral.</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Post list
   ============================================================ */
function PostList({ posts }) {
  if (!posts.length) {
    return (
      <section className="section">
        <div className="container">
          <div className="empty-state">
            <span className="eyebrow">ARQUIVO VAZIO</span>
            <h3>Nenhum artigo publicado ainda.</h3>
            <p>Os primeiros conteúdos serão publicados em breve.</p>
          </div>
        </div>
      </section>
    );
  }
  const [featured, ...rest] = posts;
  return (
    <section className="section blog blog-list" id="artigos">
      <div className="container">
        <a href={`#${featured.slug}`} className="blog-featured">
          <div className="blog-featured-cover blog-cover">
            <span className="label">{featured.category}</span>
            <div className="deco"><CoverImg post={featured} big /></div>
          </div>
          <div className="blog-featured-body">
            <span className="eyebrow">DESTAQUE</span>
            <h2>{featured.title}</h2>
            <p className="lede">{featured.excerpt}</p>
            <div className="blog-featured-meta">
              <span>{formatDate(featured.date)}</span>
              <span className="dot-sep">·</span>
              <span>{featured.readTime} min de leitura</span>
              <span className="dot-sep">·</span>
              <span>{featured.author}</span>
            </div>
            <span className="read">Ler artigo <span className="arrow">→</span></span>
          </div>
        </a>

        {rest.length > 0 && (
          <>
            <div className="blog-divider">
              <span className="eyebrow">DEMAIS ARTIGOS</span>
            </div>
            <div className="blog-grid">
              {rest.map((p) => (
                <a key={p.id} href={`#${p.slug}`} className="blog-card">
                  <div className="blog-cover">
                    <span className="label">{p.category}</span>
                    <div className="deco"><CoverImg post={p} /></div>
                  </div>
                  <div className="blog-body">
                    <span className="date">{formatDate(p.date)} · {p.readTime} MIN</span>
                    <h4>{p.title}</h4>
                    <p>{p.excerpt}</p>
                    <span className="read">Ler artigo <span className="arrow">→</span></span>
                  </div>
                </a>
              ))}
            </div>
          </>
        )}
      </div>
    </section>
  );
}

/* ============================================================
   Single post view
   ============================================================ */
function PostView({ post, allPosts }) {
  const others = allPosts.filter((p) => p.id !== post.id && !p.draft).slice(0, 2);
  return (
    <article className="post-page">
      <header className="post-header">
        <div className="container">
          <div className="post-header-inner">
            <a href="blog.html" className="post-back">
              <span className="arrow">←</span> Voltar para o blog
            </a>
            <span className="post-cat">{post.category}</span>
            <h1>{post.title}</h1>
            <p className="post-excerpt">{post.excerpt}</p>
            <div className="post-meta">
              <span>{formatDate(post.date)}</span>
              <span className="dot-sep">·</span>
              <span>{post.readTime} min de leitura</span>
              <span className="dot-sep">·</span>
              <span>{post.author}</span>
            </div>
            {(post.tags && post.tags.length > 0) && (
              <div className="post-tags">
                {post.tags.map((t) => <span key={t} className="post-tag">{t}</span>)}
              </div>
            )}
          </div>
        </div>
      </header>

      <div className="post-cover-band">
        <div className="container">
          <div className="post-cover">
            <CoverImg post={post} big />
          </div>
        </div>
      </div>

      <div className="container">
        <div className="post-body" dangerouslySetInnerHTML={{ __html: md(post.body) }} />
      </div>

      <section className="section post-related">
        <div className="container">
          <div className="section-head">
            <span className="eyebrow">CONTINUE LENDO</span>
            <h2>Outros artigos do MinerSuite.</h2>
          </div>
          <div className="blog-grid">
            {others.map((p) => (
              <a key={p.id} href={`#${p.slug}`} className="blog-card">
                <div className="blog-cover">
                  <span className="label">{p.category}</span>
                  <div className="deco"><CoverImg post={p} /></div>
                </div>
                <div className="blog-body">
                  <span className="date">{formatDate(p.date)} · {p.readTime} MIN</span>
                  <h4>{p.title}</h4>
                  <p>{p.excerpt}</p>
                  <span className="read">Ler artigo <span className="arrow">→</span></span>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      <section className="section cta-final">
        <div className="container">
          <div className="cta-final-inner">
            <span className="eyebrow" style={{ color: "var(--ms-gold-soft)" }}>PRÓXIMO PASSO</span>
            <h2>
              Coloque o método em prática com <span style={{ color: "var(--ms-gold)" }}>uma plataforma feita para mineração.</span>
            </h2>
            <p className="lede">
              Centralize clientes, propostas, contratos, financeiro e projetos
              técnicos em uma única plataforma.
            </p>
            <div className="cta-buttons">
              <a href="contato.html" className="btn btn--primary">
                Solicitar demonstração <span className="arrow">→</span>
              </a>
              <a href="planos.html" className="btn btn--ghost btn--on-dark">
                Ver planos
              </a>
            </div>
          </div>
        </div>
      </section>
    </article>
  );
}

/* ============================================================
   Page
   ============================================================ */
function BlogPage() {
  const [posts, setPosts] = useStateB(null);
  const [siteUrl, setSiteUrl] = useStateB("");
  const [route, setRoute] = useStateB(window.location.hash.slice(1));
  const [error, setError] = useStateB(null);

  useEffectB(() => {
    fetch("assets/posts.json?v=" + Date.now())
      .then((r) => {
        if (!r.ok) throw new Error("HTTP " + r.status);
        return r.json();
      })
      .then((data) => {
        setPosts((data.posts || []).filter((p) => !p.draft).sort((a, b) => b.date.localeCompare(a.date)));
        setSiteUrl((data.config && data.config.siteUrl) || window.location.origin);
      })
      .catch((e) => {
        console.warn("posts.json não encontrado.", e);
        setPosts([]);
        setError(true);
      });
  }, []);

  useEffectB(() => {
    function onHash() {
      setRoute(window.location.hash.slice(1));
      window.scrollTo({ top: 0, behavior: "instant" });
    }
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Inject SEO meta tags whenever route or posts change
  useEffectB(() => {
    if (posts === null) return;
    const current = route ? posts.find((p) => p.slug === route) : null;
    applyPostSEO(current, siteUrl || window.location.origin);
  }, [posts, route, siteUrl]);

  if (posts === null) {
    return (
      <>
        <Header />
        <main>
          <div className="loading-page">
            <div className="loading-pulse">CARREGANDO ARTIGOS…</div>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  const current = route ? posts.find((p) => p.slug === route) : null;

  return (
    <>
      <Header />
      <main>
        {current ? (
          <PostView post={current} allPosts={posts} />
        ) : (
          <>
            <BlogHero count={posts.length} />
            <PostList posts={posts} />
          </>
        )}
      </main>
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<BlogPage />);
