/* MCA, Blog (CMS) index + Article detail
 *
 * - BlogPage    → /blog index
 * - ArticlePage → /blog/<slug> and /article/<slug>
 *
 * The article page is intentionally simple: terminal-style breadcrumb,
 * centered title, small author chip, single-column prose, light end-card
 * with a quiet CTA, then a "Continue Reading" list.
 */

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

function fmtDate(iso) {
  const d = new Date(iso + "T12:00:00Z");
  return d.toLocaleDateString("en-US", { year: "long", month: "short", day: "numeric" })
    .replace(/(\d{4}),?\s?(\w{3})\s?(\d+),?\s?/, "");
}
function fmtDateLong(iso) {
  const d = new Date(iso + "T12:00:00Z");
  return d.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
}

/* ============================================================
 * BLOG INDEX  (/blog)
 * ============================================================ */
function BlogPage({ navigate }) {
  const posts = window.BLOG_POSTS || [];
  const cats = window.BLOG_CATEGORIES || ["All"];
  const featured = posts.find((p) => p.featured) || posts[0];

  const [filter, setFilter] = useStateB("All");

  const rest = useMemoB(() => {
    return posts
      .filter((p) => p !== featured)
      .filter((p) => filter === "All" || p.category === filter)
      .slice()
      .sort((a, b) => (a.date < b.date ? 1 : -1));
  }, [posts, featured, filter]);

  return (
    <React.Fragment>
      <section className="blog-hero blog-hero--centered">
        <div className="blog-hero__bg" aria-hidden="true">
          <div className="blog-hero__orb blog-hero__orb--1"></div>
          <div className="blog-hero__orb blog-hero__orb--2"></div>
          <div className="blog-hero__orb blog-hero__orb--3"></div>
          <div className="blog-hero__grid"></div>
          <div className="blog-hero__noise"></div>
          <div className="blog-hero__vignette"></div>
        </div>
        <div className="blog-hero__inner">
          <h1 className="blog-hero__title">
            Strategic Thinking Across
            <br/>
            <span className="blog-hero__title-accent">AI &amp; Emerging Technology</span>
          </h1>
          <p className="blog-hero__sub">
            A collection of research, strategic thinking, market analysis, and growth insights
            across AI, emerging technologies, and digital ecosystems.
          </p>
          <div style={{ marginTop: 32 }}>
            <Button variant="teal" size="lg" onClick={() => window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener")} withArrow>Schedule a Free Consultation</Button>
          </div>
        </div>
      </section>

      {featured && (
        <section className="section section--tight">
          <div className="container">
            <div className="section-num" style={{ marginBottom: 20 }}>FEATURED ARTICLE</div>
            <div className="blog-featured" onClick={() => navigate("/blog/" + featured.slug)}>
              <div
                className="blog-featured__media"
                style={{
                  background: featured.image
                    ? `linear-gradient(180deg, rgba(0,0,0,0.05), rgba(0,0,0,0.55)), url(${featured.image}) center/cover no-repeat`
                    : featured.cover,
                }}
              >
                <div className="blog-featured__media-tag">{featured.category.toUpperCase()}</div>
                <div className="blog-featured__media-title">{featured.title}</div>
              </div>
              <div className="blog-featured__body">
                <div className="blog-meta">
                  <span>{fmtDateLong(featured.date)}</span>
                  <span>·</span>
                  <span>{featured.read}</span>
                </div>
                <h2 className="blog-featured__title">{featured.title}</h2>
                <p className="blog-featured__excerpt">{featured.excerpt}</p>
                <div className="blog-featured__cta">
                  <span className="linklike">Read full article <ArrowUpRight /></span>
                </div>
              </div>
            </div>
          </div>
        </section>
      )}

      <section className="section">
        <div className="container">
          <div className="blog-listing-head blog-listing-head--centered">
            <div className="section-num">ALL ARTICLES · {rest.length}</div>
            <h2 className="h2" style={{ marginTop: 12 }}>Recent Writing.</h2>
          </div>

          <div className="blog-filters blog-filters--centered">
            {cats.map((c) => (
              <button
                key={c}
                className={`blog-chip ${filter === c ? "blog-chip--active" : ""}`}
                onClick={() => setFilter(c)}
              >{c}</button>
            ))}
          </div>

          {rest.length === 0 ? (
            <div className="blog-empty">
              <div className="blog-empty__title">Nothing to show.</div>
              <div className="blog-empty__sub">Try a different category or search term.</div>
            </div>
          ) : (
            <div className="blog-grid">
              {rest.map((p) => (
                <article key={p.slug} className="blog-card" onClick={() => navigate("/blog/" + p.slug)}>
                  <div
                    className="blog-card__cover"
                    style={{
                      background: p.image
                        ? `linear-gradient(180deg, rgba(0,0,0,0.05), rgba(0,0,0,0.55)), url(${p.image}) center/cover no-repeat`
                        : p.cover,
                    }}
                  >
                    <span className="blog-card__cat">{p.category}</span>
                    <span className="blog-card__cover-title">{p.title}</span>
                  </div>
                  <div className="blog-card__body">
                    <div className="blog-meta">
                      <span>{fmtDateLong(p.date)}</span>
                      <span>·</span>
                      <span>{p.read}</span>
                    </div>
                    <h3 className="blog-card__title">{p.title}</h3>
                    <p className="blog-card__excerpt">{p.excerpt}</p>
                    <div className="blog-card__foot">
                      <span className="linklike">Read article <ArrowUpRight /></span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}
        </div>
      </section>

      <FinalCTA navigate={navigate} />
    </React.Fragment>
  );
}

/* ============================================================
 * ARTICLE DETAIL, minimal, editorial
 * ============================================================ */
function ArticlePage({ slug, navigate }) {
  const posts = window.BLOG_POSTS || [];
  const post = posts.find((p) => p.slug === slug);

  useEffectB(() => {
    document.title = post ? `${post.title} · MCA` : "Article not found · MCA";
    return () => { document.title = "MCA · MultiChain Advisors"; };
  }, [post]);

  if (!post) {
    return (
      <section className="page-hero">
        <div className="page-hero__inner" style={{ textAlign: "center" }}>
          <div className="page-hero__crumb">ARTICLE · 404</div>
          <h1 className="page-hero__title" style={{ margin: "0 auto" }}>Article not found.</h1>
          <p className="page-hero__sub" style={{ margin: "24px auto 0" }}>
            The article you're looking for doesn't exist or has been moved.
          </p>
          <div style={{ marginTop: 32 }}>
            <Button variant="primary" onClick={() => navigate("/blog")} withArrow>Back to blog</Button>
          </div>
        </div>
      </section>
    );
  }

  const isReport = post.kind === "report";
  const backTo = isReport ? "/reports" : "/blog";
  const backLabel = isReport ? "reports" : "blog";
  const authorMeta = (window.BLOG_AUTHORS || {})[post.author] || {};
  const kindLabel = isReport ? "Report" : "Article";

  const sameCat = posts.filter((p) => p.slug !== post.slug && p.category === post.category);
  const others = posts.filter((p) => p.slug !== post.slug && p.category !== post.category);
  const related = [...sameCat, ...others].slice(0, 3);

  const teamPhotos = ["assets/team/niro.png", "assets/team/hash.png", "assets/team/ali.png"];

  return (
    <article className="art2">
      {/* Terminal-style breadcrumb */}
      <div className="art2-crumb">
        <div className="container">
          <div className="art2-crumb__row">
            <span className="art2-crumb__back" onClick={() => navigate(backTo)}>
              <i className="art2-crumb__back-arrow" aria-hidden="true"></i>
              <span>../{backLabel}</span>
            </span>
            <span className="art2-crumb__sep">/</span>
            <span className="art2-crumb__path">./{post.slug}</span>
          </div>
        </div>
      </div>

      {/* Header */}
      <header className="art2-head">
        <div className="container">
          <div className="art2-head__inner">
            <div className="art2-head__meta">
              <span className="art2-head__kind">MCA Reports</span>
            </div>

            <h1 className="art2-head__title">{post.title}</h1>
            {post.excerpt && <p className="art2-head__lede">{post.excerpt}</p>}
          </div>
        </div>
      </header>

      {/* Optional hero image */}
      {post.image && (
        <figure className="art2-hero-img">
          <div className="art2-hero-img__wrap">
            <img src={post.image} alt={post.title} />
          </div>
        </figure>
      )}

      {/* Body */}
      <section className="art2-body-section">
        <div className="art2-body">
          {(post.body || []).map((b, i) => {
            if (b.kind === "h2") return <h2 key={i}>{b.text}</h2>;
            if (b.kind === "h3") return <h3 key={i}>{b.text}</h3>;
            if (b.kind === "ul")
              return <ul key={i}>{b.items.map((it, j) => <li key={j}>{it}</li>)}</ul>;
            if (b.kind === "quote")
              return <blockquote key={i}><p>{b.text}</p></blockquote>;
            if (b.kind === "callout")
              return <div key={i} className="art2-callout">{b.text}</div>;
            if (b.kind === "image")
              return (
                <figure key={i} className="art2-figure">
                  <div className="art2-figure__frame">
                    <img src={b.src} alt={b.alt || ""} loading="lazy" />
                  </div>
                  {b.caption && <figcaption className="art2-figure__cap">{b.caption}</figcaption>}
                </figure>
              );
            if (b.kind === "stat")
              return (
                <div key={i} className="art2-stats">
                  {b.items.map((s, j) => (
                    <div key={j} className="art2-stat">
                      <div className="art2-stat__value">{s.value}</div>
                      <div className="art2-stat__label">{s.label}</div>
                    </div>
                  ))}
                </div>
              );
            if (b.kind === "table")
              return (
                <div key={i} className="art2-tablewrap">
                  <table className="art2-table">
                    {b.head && (
                      <thead>
                        <tr>{b.head.map((h, j) => <th key={j}>{h}</th>)}</tr>
                      </thead>
                    )}
                    <tbody>
                      {b.rows.map((r, j) => (
                        <tr key={j}>{r.map((c, k) => <td key={k}>{c}</td>)}</tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              );
            return <p key={i}>{b.text}</p>;
          })}

          {/* Footer: tags + share */}
          <div className="art2-foot">
            <div className="art2-foot__row">
              {post.tags && post.tags.length > 0 ? (
                <div className="art2-foot__tags">
                  {post.tags.map((t) => (
                    <span key={t} className="art2-foot__tag">{t}</span>
                  ))}
                </div>
              ) : <div />}
              <ArtShare title={post.title} />
            </div>
          </div>

        </div>
      </section>

      {/* Continue Reading + Talk to team */}
      {related.length > 0 && (
        <section className="art2-related">
          <div className="art2-related__inner">
            <div className="art2-related__grid">
              <div className="art2-related__main">
                <div className="art2-related__head">
                  <div className="art2-related__eyebrow">CONTINUE READING</div>
                  <h2 className="art2-related__title">More to explore.</h2>
                </div>
                <div className="art2-related__list">
                  {related.map((p) => (
                    <a
                      key={p.slug}
                      className="art2-rel"
                      onClick={() => navigate((p.kind === "report" ? "/article/" : "/blog/") + p.slug)}
                    >
                      <div className="art2-rel__thumb">
                        {p.image ? (
                          <img src={p.image} alt={p.title} />
                        ) : (
                          <div className="art2-rel__thumb-bg" style={{ background: p.cover }}>
                            {(p.category || "MCA").slice(0, 2).toUpperCase()}
                          </div>
                        )}
                      </div>
                      <div className="art2-rel__body">
                        <div className="art2-rel__meta">
                          <span>{p.category}</span>
                          <span className="art2-rel__meta-dot">·</span>
                          <span className="art2-rel__meta-read">{p.read}</span>
                        </div>
                        <h3 className="art2-rel__title">{p.title}</h3>
                      </div>
                      <span className="art2-rel__cta">
                        Read
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                          <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      </span>
                    </a>
                  ))}
                </div>
                <div className="art2-related__more">
                  <span className="art2-related__more-link" onClick={() => navigate(backTo)}>
                    View all {backLabel}
                    <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                      <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                </div>
              </div>

              <aside className="art2-teambox">
                <div className="art2-teambox__avatars">
                  {teamPhotos.map((src, i) => (
                    <span key={i} className="art2-teambox__avatar" style={{ zIndex: teamPhotos.length - i }}>
                      <img src={src} alt="" loading="lazy" />
                    </span>
                  ))}
                </div>
                <div className="art2-teambox__eyebrow">WHAT'S NEXT</div>
                <h3 className="art2-teambox__title">Talk With Our Team</h3>
                <p className="art2-teambox__sub">
                  We're here to listen, understand what you're building, and explore
                  where we can create the most impact. Share your goals, challenges,
                  and ambitions, and let's discuss what the next stage of growth could
                  look like together.
                </p>
                <button
                  className="art2-teambox__btn"
                  onClick={() => window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener")}
                >
                  Let's Talk
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                    <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
              </aside>
            </div>
          </div>
        </section>
      )}
    </article>
  );
}

/* ---------- Small building blocks ---------- */

function ArtAvatar({ author, meta }) {
  const m = meta || {};
  const initial = m.initial || (author ? author[0] : "M");
  if (m.photo) {
    return (
      <div className="art2-avatar art2-avatar--img">
        <img src={m.photo} alt={author} />
      </div>
    );
  }
  return <div className="art2-avatar">{initial}</div>;
}

function ArtShare({ title }) {
  const [copied, setCopied] = useStateB(false);
  const url = typeof window !== "undefined" ? window.location.href : "";
  const copyLink = () => {
    try {
      navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch (e) { /* noop */ }
  };
  return (
    <div className="art2-foot__share">
      <a
        className="art2-share-btn"
        href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`}
        target="_blank" rel="noreferrer noopener"
      >
        <svg width="12" height="12" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
          <path d="M9.5 1.5h2.3l-5 5.7 5.9 7.8h-4.6l-3.6-4.7-4.1 4.7H-2L3.4 8.7-2.3 1.5h4.7l3.2 4.3 3.9-4.3z" transform="translate(1.5 -.5)"/>
        </svg>
        <span>Share</span>
      </a>
      <a
        className="art2-share-btn"
        href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`}
        target="_blank" rel="noreferrer noopener"
      >
        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
          <path d="M20.5 2h-17A1.5 1.5 0 002 3.5v17A1.5 1.5 0 003.5 22h17a1.5 1.5 0 001.5-1.5v-17A1.5 1.5 0 0020.5 2zM8 19H5v-9h3zM6.5 8.25A1.75 1.75 0 118.3 6.5a1.78 1.78 0 01-1.8 1.75zM19 19h-3v-4.74c0-1.42-.6-1.93-1.38-1.93A1.74 1.74 0 0013 14.19V19h-3v-9h2.9v1.3a3.11 3.11 0 012.7-1.4c1.55 0 3.36.86 3.36 3.66z"/>
        </svg>
        <span>LinkedIn</span>
      </a>
      <button className="art2-share-btn" onClick={copyLink}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M10 13a5 5 0 007.07 0l3-3a5 5 0 00-7.07-7.07l-1 1"/>
          <path d="M14 11a5 5 0 00-7.07 0l-3 3a5 5 0 007.07 7.07l1-1"/>
        </svg>
        <span>{copied ? "Copied" : "Copy link"}</span>
      </button>
    </div>
  );
}

/* Back-compat: expose old name */
const BlogPostPage = ArticlePage;

Object.assign(window, { BlogPage, BlogPostPage, ArticlePage });
