/* =========================================================
   InternalLinks.jsx — Sprint 4: internal linking
   - POST_LINKS[slug]    = { posts: [slug,…], products: [slug,…] }
   - PRODUCT_LINKS[slug] = { posts: [slug,…] }
   Loaded AFTER Blog.jsx / BlogPosts2.jsx / BlogPosts3.jsx so
   BLOG_POSTS is populated. Overwrites BlogPostPage's "Keep reading"
   section with a curated version and exposes a FurtherReading
   component used by ProductDetailPage.
   ========================================================= */

const POST_LINKS = {

  /* ── Methodology / foundational ── */
  'how-to-read-a-peptide-coa': {
    posts:    ['hplc-purity-explained', 'peptide-coa-red-flags', 'how-to-vet-peptide-supplier'],
    products: ['bpc-157', 'semaglutide', 'tirzepatide'],
  },
  'hplc-purity-explained': {
    posts:    ['how-to-read-a-peptide-coa', 'peptide-coa-red-flags', 'peptide-storage-guide'],
    products: ['semaglutide', 'bpc-157', 'tb-500'],
  },
  'peptide-storage-guide': {
    posts:    ['how-to-read-a-peptide-coa', 'hplc-purity-explained', 'research-use-only-meaning'],
    products: ['bpc-157', 'cjc-1295-dac', 'ipamorelin'],
  },

  /* ── Product deep-dives ── */
  'bpc-157-research-review': {
    posts:    ['bpc-157-vs-tb-500', 'peptide-storage-guide', 'how-to-read-a-peptide-coa'],
    products: ['bpc-157', 'tb-500', 'bpc-tb-combo'],
  },
  'tirzepatide-research-review': {
    posts:    ['semaglutide-vs-tirzepatide', 'hplc-purity-explained', 'how-to-read-a-peptide-coa'],
    products: ['tirzepatide', 'semaglutide', 'retatrutide'],
  },
  'ghk-cu-research-review': {
    posts:    ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'research-use-only-meaning'],
    products: ['ghk-cu', 'bpc-157', 'tb-500'],
  },

  /* ── Comparisons ── */
  'bpc-157-vs-tb-500': {
    posts:    ['bpc-157-research-review', 'peptide-storage-guide', 'how-to-read-a-peptide-coa'],
    products: ['bpc-157', 'tb-500', 'bpc-tb-combo'],
  },
  'semaglutide-vs-tirzepatide': {
    posts:    ['tirzepatide-research-review', 'how-to-read-a-peptide-coa', 'hplc-purity-explained'],
    products: ['semaglutide', 'tirzepatide', 'retatrutide'],
  },

  /* ── Buyer education ── */
  'how-to-vet-peptide-supplier': {
    posts:    ['peptide-coa-red-flags', 'how-to-read-a-peptide-coa', 'research-use-only-meaning'],
    products: ['bpc-157', 'semaglutide', 'cjc-1295-dac'],
  },
  'research-use-only-meaning': {
    posts:    ['how-to-vet-peptide-supplier', 'peptide-coa-red-flags', 'how-to-read-a-peptide-coa'],
    products: ['semaglutide', 'bpc-157', 'ghk-cu'],
  },
  'peptide-coa-red-flags': {
    posts:    ['how-to-read-a-peptide-coa', 'how-to-vet-peptide-supplier', 'hplc-purity-explained'],
    products: ['bpc-157', 'semaglutide', 'tirzepatide'],
  },
};

/* Per-product → relevant posts. Any product not listed falls back
   to the three foundational methodology pieces. */
const PRODUCT_LINKS = {
  'bpc-157':       { posts: ['bpc-157-research-review', 'bpc-157-vs-tb-500', 'peptide-storage-guide'] },
  'tb-500':        { posts: ['bpc-157-vs-tb-500', 'bpc-157-research-review', 'peptide-storage-guide'] },
  'bpc-tb-combo':  { posts: ['bpc-157-vs-tb-500', 'bpc-157-research-review', 'how-to-read-a-peptide-coa'] },
  'semaglutide':   { posts: ['semaglutide-vs-tirzepatide', 'tirzepatide-research-review', 'hplc-purity-explained'] },
  'tirzepatide':   { posts: ['tirzepatide-research-review', 'semaglutide-vs-tirzepatide', 'how-to-read-a-peptide-coa'] },
  'retatrutide':   { posts: ['tirzepatide-research-review', 'semaglutide-vs-tirzepatide', 'how-to-read-a-peptide-coa'] },
  'ghk-cu':        { posts: ['ghk-cu-research-review', 'peptide-storage-guide', 'how-to-read-a-peptide-coa'] },
  'cjc-1295-dac':  { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'how-to-vet-peptide-supplier'] },
  'ipamorelin':    { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'how-to-vet-peptide-supplier'] },
  'sermorelin':    { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'how-to-vet-peptide-supplier'] },
  'tesamorelin':   { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'how-to-vet-peptide-supplier'] },
  'pt-141':        { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'research-use-only-meaning'] },
  'nad-plus':      { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'research-use-only-meaning'] },
  'mots-c':        { posts: ['peptide-storage-guide', 'how-to-read-a-peptide-coa', 'research-use-only-meaning'] },
};

const FALLBACK_POSTS = ['how-to-read-a-peptide-coa', 'hplc-purity-explained', 'peptide-storage-guide'];

/* ---------- Helpers ---------- */
function findPost(slug) {
  return (window.BLOG_POSTS || []).find(p => p.slug === slug);
}
function findProduct(slug) {
  return (window.PRODUCTS || []).find(p => p.slug === slug);
}

/* ---------- FurtherReading (used on PDPs) ---------- */
function FurtherReading({ productSlug, go }) {
  const links = (PRODUCT_LINKS[productSlug] && PRODUCT_LINKS[productSlug].posts) || FALLBACK_POSTS;
  const posts = links.map(findPost).filter(Boolean);
  if (!posts.length) return null;

  return (
    <section style={{ padding: '56px 0 72px', background: 'var(--clarion-frost)', borderTop: '1px solid var(--border)' }}>
      <div className="container">
        <div className="eyebrow" style={{ marginBottom: 14 }}>FURTHER READING</div>
        <h2 style={{ fontSize: 28, fontWeight: 800, color: 'var(--fg-brand)', letterSpacing: '-0.01em', margin: '0 0 28px', maxWidth: 640 }}>
          Methodology and context for this compound.
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
          {posts.map(r => (
            <a
              key={r.slug}
              href={'/blog/' + r.slug}
              onClick={e => { e.preventDefault(); go && go('blog', r.slug); }}
              style={{ background: '#fff', border: '1px solid var(--border-strong)', borderRadius: 12, padding: 22, cursor: 'pointer', textDecoration: 'none', color: 'inherit', display: 'block', transition: 'box-shadow .15s, transform .15s' }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-md)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}
            >
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', color: 'var(--fg-accent)', fontWeight: 700, marginBottom: 10 }}>
                {r.category.toUpperCase()} · {r.readingMin} MIN
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--fg-brand)', marginBottom: 8, letterSpacing: '-0.01em', lineHeight: 1.25 }}>
                {r.title}
              </div>
              <div style={{ fontSize: 13, color: 'var(--fg1)', lineHeight: 1.55 }}>
                {r.excerpt.slice(0, 120)}…
              </div>
              <div style={{ marginTop: 14, fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, letterSpacing: '.12em', color: 'var(--clarion-teal)' }}>
                READ →
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Curated "Keep reading" for blog posts ---------- */
function CuratedKeepReading({ postSlug, go }) {
  const links = POST_LINKS[postSlug] || {};
  const postSlugs = links.posts || [];
  const productSlugs = links.products || [];

  const posts = postSlugs.map(findPost).filter(Boolean);
  const products = productSlugs.map(findProduct).filter(Boolean);

  if (!posts.length && !products.length) return null;

  return (
    <section style={{ background: 'var(--clarion-frost)', padding: '56px 0 72px' }}>
      <div className="container-narrow">

        {posts.length > 0 && (
          <>
            <div className="eyebrow" style={{ marginBottom: 18 }}>KEEP READING</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 44 }}>
              {posts.map(r => (
                <a
                  key={r.slug}
                  href={'/blog/' + r.slug}
                  onClick={e => { e.preventDefault(); go && go('blog', r.slug); }}
                  style={{ background: '#fff', border: '1px solid var(--border-strong)', borderRadius: 12, padding: 20, cursor: 'pointer', textDecoration: 'none', color: 'inherit', display: 'block', transition: 'box-shadow .15s, transform .15s' }}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-md)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}
                >
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', color: 'var(--fg-accent)', marginBottom: 10, fontWeight: 700 }}>
                    {r.category.toUpperCase()} · {r.readingMin} MIN
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--fg-brand)', marginBottom: 8, letterSpacing: '-0.01em', lineHeight: 1.25 }}>
                    {r.title}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--fg1)', lineHeight: 1.55 }}>
                    {r.excerpt.slice(0, 110)}…
                  </div>
                </a>
              ))}
            </div>
          </>
        )}

        {products.length > 0 && (
          <>
            <div className="eyebrow" style={{ marginBottom: 14 }}>COMPOUNDS REFERENCED</div>
            <p style={{ fontSize: 13, color: 'var(--fg2)', margin: '0 0 20px', lineHeight: 1.55 }}>
              The research compounds discussed in this article — each released under the standard Clarion analytical panel with per-lot COA.
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {products.map(pr => (
                <a
                  key={pr.slug}
                  href={'/product/' + pr.slug}
                  onClick={e => { e.preventDefault(); go && go('product', pr.slug); }}
                  style={{ background: '#fff', border: '1px solid var(--border-strong)', borderRadius: 10, padding: '16px 18px', cursor: 'pointer', textDecoration: 'none', color: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, transition: 'background .15s, border-color .15s' }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--clarion-surface)'; e.currentTarget.style.borderColor = 'var(--clarion-teal)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = '#fff'; e.currentTarget.style.borderColor = 'var(--border-strong)'; }}
                >
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 700, letterSpacing: '.14em', color: 'var(--fg-accent)' }}>
                      {pr.sku}
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--fg-brand)', letterSpacing: '-0.01em', marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {pr.code}
                    </div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg2)', letterSpacing: '.08em', marginTop: 3 }}>
                      {pr.weight} · {pr.purity}
                    </div>
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700, letterSpacing: '.12em', color: 'var(--clarion-teal)', flexShrink: 0 }}>
                    VIEW →
                  </div>
                </a>
              ))}
            </div>
          </>
        )}

      </div>
    </section>
  );
}

Object.assign(window, { POST_LINKS, PRODUCT_LINKS, FurtherReading, CuratedKeepReading });

/* ---------- Patch BlogPostPage to use the curated module ---------- */
(function patchBlogPostPage() {
  if (typeof window.BlogPostPage !== 'function') return;
  const Original = window.BlogPostPage;

  function PatchedBlogPostPage(props) {
    const { slug, go } = props;
    const post = (window.BLOG_POSTS || []).find(p => p.slug === slug) || (window.BLOG_POSTS || [])[0];
    const Body = window.BLOG_BODIES && window.BLOG_BODIES[post && post.slug];

    React.useEffect(() => { window.__go = go; }, [go]);

    if (!post || !Body) {
      // Safety net — if anything is missing, fall back to the original component.
      return React.createElement(Original, props);
    }

    return (
      <>
        <section style={{ padding: '32px 0 0' }}>
          <div className="container-narrow">
            <button className="btn-link" onClick={() => go('blog')}>← Field notes</button>
          </div>
        </section>

        <article>
          <header style={{ padding: '32px 0 24px' }}>
            <div className="container-narrow">
              <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 18, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', color: 'var(--fg2)' }}>
                <span style={{ color: 'var(--fg-accent)', fontWeight: 700 }}>{post.category.toUpperCase()}</span>
                <span>·</span>
                <span>{post.dateLabel.toUpperCase()}</span>
                <span>·</span>
                <span>{post.readingMin} MIN READ</span>
              </div>
              <h1 style={{ fontSize: 44, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 18px', lineHeight: 1.1 }}>{post.title}</h1>
              <p style={{ fontSize: 18, lineHeight: 1.6, color: 'var(--fg1)', fontFamily: 'var(--font-serif)', fontStyle: 'italic', margin: 0, maxWidth: 640 }}>{post.excerpt}</p>
            </div>
          </header>

          <section style={{ padding: '0 0 64px' }}>
            <div className="container-narrow">
              <Body />
            </div>
          </section>
        </article>

        <CuratedKeepReading postSlug={post.slug} go={go} />
      </>
    );
  }

  window.BlogPostPage = PatchedBlogPostPage;
})();

/* ---------- Patch ProductDetailPage to append FurtherReading ---------- */
(function patchProductDetailPage() {
  if (typeof window.ProductDetailPage !== 'function') return;
  const Original = window.ProductDetailPage;

  function PatchedProductDetailPage(props) {
    return (
      <>
        <Original {...props} />
        <FurtherReading productSlug={props.slug} go={props.go} />
      </>
    );
  }

  window.ProductDetailPage = PatchedProductDetailPage;
})();
