window.BlogApp = (function(){
const { useState, useEffect } = React;

const WP_HOST = "https://blog.vivamed.com";
const POSTS_PER_PAGE = 20;

function getSlugFromUrl(){
  return new URLSearchParams(window.location.search).get("slug");
}

function formatDate(iso){
  if (!iso) return "";
  try {
    return new Date(iso).toLocaleDateString("en-US", { year:"numeric", month:"long", day:"numeric" });
  } catch (_) { return ""; }
}

function sanitize(html){
  if (!html) return "";
  if (window.DOMPurify) return window.DOMPurify.sanitize(html);
  return "";
}

function pickFeaturedImage(post){
  const media = post?._embedded?.["wp:featuredmedia"]?.[0];
  if (!media) return null;
  const sizes = media.media_details?.sizes || {};
  const pick = sizes.large || sizes.medium_large || sizes.medium || sizes.full;
  return { src: pick?.source_url || media.source_url, alt: media.alt_text || "" };
}

function pickAuthor(post){
  return post?._embedded?.author?.[0]?.name || "";
}

function pickCategories(post){
  const terms = post?._embedded?.["wp:term"] || [];
  const cats = (terms[0] || []).map(t => t.name);
  return cats;
}

function BlogHero({ children }){
  return (
    <section className="subpage-hero blog-hero">
      <div className="subpage-hero-inner">
        {children}
      </div>
    </section>
  );
}

function StateBlock({ kind, message, retry }){
  return (
    <div className={`blog-state blog-state-${kind}`} role="status" aria-live="polite">
      <p>{message}</p>
      {retry && <button className="btn btn-ghost" onClick={retry}>Try again</button>}
    </div>
  );
}

function BlogCard({ post }){
  const img = pickFeaturedImage(post);
  const cats = pickCategories(post);
  const href = `blog.html?slug=${encodeURIComponent(post.slug)}`;
  return (
    <a className="blog-card" href={href}>
      <div className="blog-card-media">
        {img
          ? <img src={img.src} alt={img.alt} loading="lazy"/>
          : <div className="blog-card-media-placeholder" aria-hidden="true"/>}
      </div>
      <div className="blog-card-body">
        {cats.length > 0 && (
          <div className="blog-card-cats">{cats.slice(0,2).join(" · ")}</div>
        )}
        <h3 className="blog-card-title" dangerouslySetInnerHTML={{__html: sanitize(post.title?.rendered)}}/>
        <div className="blog-card-excerpt" dangerouslySetInnerHTML={{__html: sanitize(post.excerpt?.rendered)}}/>
        <div className="blog-card-meta">
          <span>{formatDate(post.date)}</span>
        </div>
      </div>
    </a>
  );
}

function BlogIndex(){
  const [state, setState] = useState({ status:"loading", posts:[], error:null });

  const load = () => {
    setState({ status:"loading", posts:[], error:null });
    const url = `${WP_HOST}/wp-json/wp/v2/posts?_embed&per_page=${POSTS_PER_PAGE}`;
    fetch(url, { credentials:"omit" })
      .then(r => {
        if (!r.ok) throw new Error(`WordPress responded ${r.status}`);
        return r.json();
      })
      .then(posts => setState({ status:"ready", posts, error:null }))
      .catch(err => setState({ status:"error", posts:[], error: err.message || "Failed to load posts" }));
  };

  useEffect(load, []);

  return (
    <>
      <BlogHero>
        <div className="subpage-eyebrow"><span className="dot"/>Blog</div>
        <h1 className="subpage-h1">Notes from the lab and the clinic.</h1>
        <p className="subpage-lede">Research, platform updates, and clinical perspectives from the VivaMed team.</p>
      </BlogHero>

      <section className="section blog-list-section">
        <div className="section-inner">
          {state.status === "loading" && (
            <div className="blog-grid blog-grid-skeleton" aria-hidden="true">
              {Array.from({length:6}).map((_,i)=>(
                <div key={i} className="blog-card blog-card-skeleton">
                  <div className="blog-card-media"/>
                  <div className="blog-card-body">
                    <div className="sk sk-line sk-line-cat"/>
                    <div className="sk sk-line sk-line-title"/>
                    <div className="sk sk-line"/>
                    <div className="sk sk-line sk-line-short"/>
                  </div>
                </div>
              ))}
            </div>
          )}

          {state.status === "error" && (
            <StateBlock
              kind="error"
              message={`Couldn't reach the blog right now. ${state.error}`}
              retry={load}
            />
          )}

          {state.status === "ready" && state.posts.length === 0 && (
            <StateBlock kind="empty" message="No posts yet. Check back soon."/>
          )}

          {state.status === "ready" && state.posts.length > 0 && (
            <div className="blog-grid">
              {state.posts.map(p => <BlogCard key={p.id} post={p}/>)}
            </div>
          )}
        </div>
      </section>
    </>
  );
}

function BlogPost({ slug }){
  const [state, setState] = useState({ status:"loading", post:null, error:null });

  useEffect(() => {
    const url = `${WP_HOST}/wp-json/wp/v2/posts?slug=${encodeURIComponent(slug)}&_embed`;
    fetch(url, { credentials:"omit" })
      .then(r => {
        if (!r.ok) throw new Error(`WordPress responded ${r.status}`);
        return r.json();
      })
      .then(arr => {
        const post = Array.isArray(arr) ? arr[0] : null;
        if (!post) {
          setState({ status:"notfound", post:null, error:null });
          return;
        }
        setState({ status:"ready", post, error:null });
        document.title = `${stripHtml(post.title?.rendered || "Post")} — VivaMed BioPharma`;
      })
      .catch(err => setState({ status:"error", post:null, error: err.message || "Failed to load post" }));
  }, [slug]);

  if (state.status === "loading") {
    return (
      <section className="section blog-post-section">
        <div className="section-inner blog-post-inner">
          <div className="sk sk-line sk-line-cat"/>
          <div className="sk sk-line sk-line-h1"/>
          <div className="sk sk-line sk-line-h1"/>
          <div className="sk sk-line"/>
          <div className="sk sk-line sk-line-short"/>
        </div>
      </section>
    );
  }

  if (state.status === "error") {
    return (
      <section className="section blog-post-section">
        <div className="section-inner blog-post-inner">
          <StateBlock kind="error" message={`Couldn't load this post. ${state.error}`}/>
          <p><a className="btn btn-ghost" href="/blog">← Back to all posts</a></p>
        </div>
      </section>
    );
  }

  if (state.status === "notfound") {
    return (
      <section className="section blog-post-section">
        <div className="section-inner blog-post-inner">
          <h1 className="subpage-h1">Post not found.</h1>
          <p className="subpage-lede">The post you're looking for has moved or doesn't exist.</p>
          <p><a className="btn btn-ghost" href="/blog">← Back to all posts</a></p>
        </div>
      </section>
    );
  }

  const post = state.post;
  const img = pickFeaturedImage(post);
  const cats = pickCategories(post);
  const author = pickAuthor(post);

  return (
    <article className="section blog-post-section">
      <div className="section-inner blog-post-inner">
        <div className="blog-post-back">
          <a href="/blog">← All posts</a>
        </div>
        {cats.length > 0 && (
          <div className="blog-post-cats">{cats.join(" · ")}</div>
        )}
        <h1 className="blog-post-title" dangerouslySetInnerHTML={{__html: sanitize(post.title?.rendered)}}/>
        <div className="blog-post-meta">
          {author && <span>{author}</span>}
          {author && <span aria-hidden="true">·</span>}
          <span>{formatDate(post.date)}</span>
        </div>
        {img && (
          <div className="blog-post-media">
            <img src={img.src} alt={img.alt}/>
          </div>
        )}
        <div className="blog-post-body prose" dangerouslySetInnerHTML={{__html: sanitize(post.content?.rendered)}}/>
      </div>
    </article>
  );
}

function stripHtml(html){
  if (!html) return "";
  const tmp = document.createElement("div");
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || "";
}

function App(){
  const slug = getSlugFromUrl();
  return (
    <>
      {slug ? <BlogPost slug={slug}/> : <BlogIndex/>}
      <PageFooter/>
    </>
  );
}

return App;
})();
