const POST_DETAILS = {};

function BlogArticlePage({ slug: rawSlug }) {
  const slug = React.useMemo(() => {
    try { return decodeURIComponent(rawSlug); } catch (e) { return rawSlug; }
  }, [rawSlug]);

  const [post, setPost] = React.useState(() => window.POST_DETAILS[slug]);
  const [loading, setLoading] = React.useState(!post);
  const [error, setError] = React.useState(null);

  window.useSEO({
    title: post ? `${post.title} | Stories` : "Loading Story...",
    description: post ? (post.deck ? post.deck.slice(0, 155) : post.title) : "Loading article..."
  });

  React.useEffect(() => {
    if (window.POST_DETAILS[slug]) {
      setPost(window.POST_DETAILS[slug]);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    const basePath = window.location.hostname.endsWith("github.io") ? "/borderux.com" : "";
    fetch(`${basePath}/content/posts/${slug}/${slug}.md`)
      .then((res) => {
        if (!res.ok) throw new Error("Article not found");
        return res.text();
      })
      .then((text) => {
        const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
        let data = {};
        let body = text;
        if (m) {
          try {
            data = window.jsyaml ? window.jsyaml.load(m[1]) : {};
            body = m[2] || "";
          } catch (err) {
            console.warn("YAML parse error:", err);
          }
        }
        const parsedPost = {
          kind: data.kind || "",
          date: data.date || "",
          read: data.read || "",
          author: data.author || "",
          title: data.title || "",
          deck: data.deck || "",
          image: data.image || "",
          images: data.images || [],
          html: (() => {
            if (!window.marked) {
              const mailtoUrl = `mailto:support@borderux.com?subject=Markdown%20Processor%20Load%20Failure&body=Hi%20Border%20UX%20Support,%0A%0AThe%20markdown%20processor%20failed%20to%20load%20on%20this%20page:%20${encodeURIComponent(window.location.href)}%0A%0ABrowser:%20${encodeURIComponent(navigator.userAgent)}`;
              return `
                <div class="art-error-banner" style="border: 1px solid var(--bx-light-tile-border, rgba(244,236,220,0.15)); padding: 24px; border-radius: 12px; background: rgba(180,45,69,0.08); margin: 32px 0;">
                  <h3 style="color: var(--ink); margin-top: 0; font-family: var(--font-display); font-size: 20px; font-weight: 500;">Failed to load markdown processor</h3>
                  <p style="color: var(--ink-2); font-size: 14px; margin-bottom: 16px; font-family: var(--font-mono); opacity: 0.85;">We were unable to load the required library to render this article's content. This is usually caused by temporary network issues or CDN outages.</p>
                  <a href="${mailtoUrl}" class="err-btn primary" style="display: inline-block; background: var(--ink); color: var(--paper); padding: 10px 20px; border-radius: 6px; text-decoration: none; font-size: 13px; font-weight: 500; border: 1px solid var(--bx-light-tile-border, rgba(244,236,220,0.25)); transition: opacity 0.2s;">Report to support@borderux.com</a>
                </div>
              `;
            }
            const renderer = new window.marked.Renderer();
            renderer.link = function(hrefOrObj, title, text) {
              let href = hrefOrObj;
              let linkTitle = title;
              let linkText = text;
              if (typeof hrefOrObj === 'object' && hrefOrObj !== null) {
                href = hrefOrObj.href;
                linkTitle = hrefOrObj.title;
                linkText = hrefOrObj.text;
              }
              return `<a href="${href}" target="_blank" rel="noopener noreferrer"${linkTitle ? ` title="${linkTitle}"` : ''}>${linkText}</a>`;
            };
            renderer.image = function(hrefOrObj, title, text) {
              let src = hrefOrObj;
              let imgTitle = title;
              let imgAlt = text;
              if (typeof hrefOrObj === 'object' && hrefOrObj !== null) {
                src = hrefOrObj.href;
                imgTitle = hrefOrObj.title;
                imgAlt = hrefOrObj.text;
              }
              const hasCaption = imgAlt && imgAlt !== 'Image' && imgAlt !== 'image';
              const imgHtml = `<a href="${src}" target="_blank" rel="noopener noreferrer" class="art-img-link"><img src="${src}" alt="${imgAlt || ''}"${imgTitle ? ` title="${imgTitle}"` : ''}></a>`;
              if (hasCaption) {
                return `<div class="art-inline-shot">${imgHtml}<div class="art-inline-caption">${imgAlt}</div></div>`;
              }
              return imgHtml;
            };
            renderer.paragraph = function(textOrObj) {
              let textContent = '';
              let renderedHtml = '';
              
              if (typeof textOrObj === 'string') {
                textContent = textOrObj;
                renderedHtml = textOrObj;
              } else if (textOrObj && typeof textOrObj === 'object') {
                textContent = textOrObj.text || '';
                if (this && this.parser && textOrObj.tokens) {
                  renderedHtml = this.parser.parseInline(textOrObj.tokens);
                } else {
                  renderedHtml = textOrObj.text || '';
                }
              }
              
              if (renderedHtml.includes('class="art-inline-shot"') || renderedHtml.includes('class="art-img-link"')) {
                return renderedHtml;
              }
              
              return `<p>${renderedHtml}</p>`;
            };
            return window.marked.parse(body, { renderer });
          })(),
          related: data.related || []
        };

        window.POST_DETAILS[slug] = parsedPost;
        setPost(parsedPost);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Failed to load article:", err);
        setError("Failed to load article.");
        setLoading(false);
      });
  }, [slug]);

  if (loading) {
    return (
      <div className="bx-page site-page">
        <Nav />
        <div className="sp-frame" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
          <div style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink)', fontSize: 16 }}>Loading article...</div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !post) {
    return <Page404 message="Article Not Found" />;
  }

  const rawAuthors = (post.author || "").split(/,|\band\b|&/i).map(s => s.trim()).filter(Boolean);
  if (rawAuthors.length === 0) {
    rawAuthors.push("");
  }
  const authors = rawAuthors.map(name => {
    const key = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
    return {
      key,
      name,
      role: window.AUTHOR_INFO[key]?.role || "",
      bio: window.AUTHOR_INFO[key]?.bio || "",
      avatar: window.AUTHOR_INFO[key]?.avatar || ""
    };
  });

  const cat = (post.kind || "").toLowerCase();
  const catClass = ["design", "culture", "dev", "art", "rip", "w3w"].includes(cat) ? `cat-${cat}` : "cat-default";

  return (
    <div className="bx-page site-page">
      <Nav />
      <div className="art-main-split">
        {/* Left Side: Sticky Cover Card */}
        <aside className="art-cover-aside">
          <div className={`post-card ${catClass} featured`} style={{ display: 'flex', flexDirection: 'column', border: '1px solid var(--bx-foot-border, rgba(244,236,220,0.1))' }}>
            {post.image && (
              <div className="post-card-img-wrap" style={{ marginBottom: 24, flexShrink: 0 }}>
                <img src={post.image} className="post-card-img" alt={post.title} />
              </div>
            )}
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{post.date}</span>
              <a href={`/blog/tag/${cat}`} className="kind" style={{ fontWeight: 600 }}>{post.kind}</a>
            </div>

            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 2.5vw, 42px)', lineHeight: 1.1, margin: '0 0 16px', fontWeight: 500 }}>
              {post.title}
            </h1>

            {post.deck && (
              <p style={{ fontSize: 15, lineHeight: 1.5, opacity: 0.85, margin: '0 0 24px' }}>
                {post.deck}
              </p>
            )}

            {/* Embedded stacked Author Cards */}
            <div className="art-author-stack" style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 12, borderTop: '1px solid var(--bx-foot-border, rgba(244,236,220,0.15))', paddingTop: 16 }}>
              {authors.map(auth => (
                <div key={auth.key} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                  <img src={auth.avatar} className="art-author-avatar" alt={auth.name} style={{ width: 66, height: 66, borderRadius: '50%' }} />
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 13, color: 'inherit' }}>
                      By <a href={`/author/${auth.key}`} style={{ color: 'inherit', textDecoration: 'underline' }}>{auth.name}</a>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 16, borderTop: '1px solid var(--bx-foot-border, rgba(244,236,220,0.15))', paddingTop: 12, fontSize: 12, opacity: 0.7, fontFamily: 'var(--font-mono)' }}>
              <span>{post.read} read</span>
            </div>
          </div>
        </aside>

        {/* Right Side: Vertical Scroll Columns */}
        <main className="art-vertical-body">
          <div className="art-markdown" dangerouslySetInnerHTML={{ __html: post.html }} />

          {/* Related Articles Column */}
          {post.related && post.related.length > 0 && (
            <section className="art-section-col" style={{ marginTop: 32 }}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500, margin: '0 0 24px', color: 'var(--paper)' }}>Related.</h2>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                {post.related.map(relSlug => {
                  const bxContent = (typeof window !== "undefined" && window.__BX_CONTENT) || {};
                  const csMeta = bxContent[`case-${relSlug}`] || {};
                  const loadedDetails = window.CASE_DETAILS[relSlug] || {};

                  const eyebrow = loadedDetails.eyebrow || csMeta.eyebrow || `Case study / ${relSlug.toUpperCase()}`;
                  const title = loadedDetails.title || csMeta.title || "";
                  const theme = loadedDetails.theme || csMeta.theme || `cs-${relSlug}`;

                  if (!title) return null;
                  return (
                    <a key={relSlug} href={`/work/${relSlug}`} className={`art-related-card ${theme}`} style={{ display: 'block', padding: 20, borderRadius: 12, textDecoration: 'none' }}>
                      <div className="art-related-lbl" dangerouslySetInnerHTML={{ __html: eyebrow }} />
                      <div className="art-related-title" dangerouslySetInnerHTML={{ __html: title }} style={{ fontSize: 18, fontWeight: 500, marginTop: 8 }} />
                      <div className="art-related-arrow" style={{ marginTop: 12, textAlign: 'right' }}>→</div>
                    </a>
                  );
                })}
              </div>
            </section>
          )}
        </main>
      </div>
      <Footer />
    </div>
  );
}

Object.assign(window, { POST_DETAILS, BlogArticlePage });
