// Página /blog/<slug>/ — composante générique d'article
// Charge /blog/<slug>/article.md via fetch, le parse avec marked et le rend.
// Génère une TOC à partir des H2. Expose window.BlogArticle.

const slugify = (text) => text
  .toLowerCase()
  .normalize('NFD').replace(/[̀-ͯ]/g, '')
  .replace(/[^a-z0-9\s-]/g, '')
  .trim()
  .replace(/\s+/g, '-');

const BlogArticleHero = ({ article }) => {
  const heroCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const heroCountry = (heroCtx && heroCtx.country) || 'co';
  return (
  <section style={{ paddingTop: 120, paddingBottom: 32, position: 'relative', overflow: 'hidden' }}>
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -260, left: '20%', width: 500, height: 500, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.14) 0%, transparent 70%)', filter: 'blur(40px)' }} />
      <div style={{ position: 'absolute', top: -200, right: '15%', width: 460, height: 460, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.14) 0%, transparent 70%)', filter: 'blur(40px)' }} />
    </div>
    <div className="container" style={{ position: 'relative' }}>
      <div className="reveal in" style={{ marginBottom: 28, textAlign: 'center' }}>
        <a href={`/${heroCountry}/blog/`} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 13, color: 'var(--fg-muted)',
          fontFamily: 'Geist Mono, monospace',
          textTransform: 'uppercase', letterSpacing: '0.08em',
        }}>
          <span>←</span><span>Blog</span>
        </a>
      </div>
      <div style={{ textAlign: 'center', maxWidth: 820, margin: '0 auto' }}>
        <div className="reveal in reveal-delay-1" style={{
          display: 'flex', justifyContent: 'center', gap: 12,
          marginBottom: 22, flexWrap: 'wrap',
          fontFamily: 'Geist Mono, monospace',
          fontSize: 12, color: 'var(--fg-muted)',
          textTransform: 'uppercase', letterSpacing: '0.1em',
        }}>
          <span>{article.categoryLabel}</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--fg-faint)', alignSelf: 'center' }} />
          <span>{article.dateLabel}</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--fg-faint)', alignSelf: 'center' }} />
          <span>{article.readTime}</span>
        </div>
        <h1 className="h1 reveal in reveal-delay-2" style={{
          marginBottom: 24,
          textWrap: 'balance',
          fontSize: 'clamp(32px, 4.6vw, 54px)',
        }}>
          {article.title}
        </h1>
        <div className="reveal in reveal-delay-3" style={{
          fontSize: 14, color: 'var(--fg-muted)',
        }}>
          Por{' '}
          {article.authorUrl ? (
            <a
              href={article.authorUrl}
              target="_blank"
              rel="noopener noreferrer author"
              style={{
                color: 'var(--fg-soft)',
                fontWeight: 500,
                textDecoration: 'underline',
                textDecorationColor: 'rgba(198,156,255,0.55)',
                textUnderlineOffset: 3,
              }}
            >
              {article.author}
            </a>
          ) : (
            <span style={{ color: 'var(--fg-soft)', fontWeight: 500 }}>{article.author}</span>
          )}
        </div>
        {article.authorBio && (
          <div className="reveal in reveal-delay-3" style={{
            marginTop: 6,
            fontSize: 13.5, color: 'var(--fg-muted)',
            lineHeight: 1.55,
            maxWidth: 520, margin: '6px auto 0',
            fontStyle: 'normal',
          }}>
            {article.authorBio}
          </div>
        )}
        {article.updatedDateLabel && article.updatedDateLabel !== article.dateLabel && (
          <div className="reveal in reveal-delay-3" style={{
            marginTop: 12,
            fontSize: 12, color: 'var(--fg-muted)',
            fontFamily: 'Geist Mono, monospace',
            letterSpacing: '0.04em',
          }}>
            Última actualización: {article.updatedDateLabel}
          </div>
        )}
      </div>
    </div>
  </section>
  );
};

const BlogArticleCover = ({ article }) => (
  <section style={{ paddingTop: 16, paddingBottom: 32 }}>
    <div className="container">
      <div className="reveal" style={{
        maxWidth: 960, margin: '0 auto',
        borderRadius: 18, overflow: 'hidden',
        boxShadow: '0 24px 60px -20px rgba(15,23,42,0.18), 0 1px 2px rgba(0,0,0,0.04)',
      }}>
        <BlogCover
          eyebrow={article.coverEyebrow}
          title={article.title}
          variant={article.coverVariant}
          size="lg"
        />
      </div>
    </div>
  </section>
);

const BlogToc = ({ items }) => {
  if (!items.length) return null;
  return (
    <aside className="cb-blog-toc" aria-label="Tabla de contenidos">
      <div className="mono" style={{
        fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em',
        color: 'var(--fg-muted)', marginBottom: 14,
      }}>
        En este artículo
      </div>
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map(it => (
          <a key={it.id} href={`#${it.id}`} style={{
            fontSize: 13.5, color: 'var(--fg-soft)',
            lineHeight: 1.45, padding: '4px 0',
            transition: 'color 0.2s ease',
          }} className="cb-blog-toc-link">
            {it.text}
          </a>
        ))}
      </nav>
    </aside>
  );
};

const BlogInlineCta = () => {
  const ctaCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const ctaCountry = (ctaCtx && ctaCtx.country) || 'co';
  return (
  <div className="reveal cb-blog-inline-cta" style={{
    margin: '48px 0',
    padding: '32px 36px',
    borderRadius: 16,
    background: 'linear-gradient(135deg, rgba(84,181,227,0.08) 0%, rgba(198,156,255,0.08) 100%)',
    border: '1px solid rgba(198,156,255,0.30)',
    display: 'flex', flexDirection: 'column', gap: 14,
    alignItems: 'flex-start',
  }}>
    <div className="mono" style={{
      fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em',
      color: 'var(--fg-muted)',
    }}>
      Empieza con CloserBroker
    </div>
    <div style={{
      fontSize: 20, fontWeight: 500, lineHeight: 1.3,
      letterSpacing: '-0.015em',
    }}>
      Estructura tu agencia con un{' '}
      <span className="serif" style={{ fontStyle: 'italic' }}>CRM diseñado para LATAM.</span>
    </div>
    <div style={{ fontSize: 15, color: 'var(--fg-soft)', lineHeight: 1.55 }}>
      Pipeline visual, automatizaciones, bolsa inmobiliaria, portal Ogarom y más — todo desde el mismo lugar, sin sorpresas en la factura.
    </div>
    <a href={`/${ctaCountry}/precios/`} className="btn btn-grad" style={{ marginTop: 4 }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        Ver precios
        <Icon name="arrow" size={14} />
      </span>
    </a>
  </div>
  );
};

const BlogRelated = ({ articles }) => {
  const relCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const relCountry = (relCtx && relCtx.country) || 'co';
  if (!articles.length) return null;
  return (
    <section style={{ paddingTop: 56, paddingBottom: 96, borderTop: '1px solid var(--border-soft)' }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 40px' }}>
          <div className="eyebrow" style={{ marginBottom: 18 }}>
            <span className="eyebrow-dot" />Sigue leyendo
          </div>
          <h2 className="h2" style={{ fontSize: 'clamp(26px, 3.2vw, 36px)', textWrap: 'balance' }}>
            Otros artículos que{' '}
            <span className="serif" style={{ fontStyle: 'italic' }}>te pueden interesar.</span>
          </h2>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
          gap: 28,
          maxWidth: 960, margin: '0 auto',
        }}>
          {articles.map(a => (
            <a
              key={a.slug}
              href={`/${relCountry}/blog/${a.slug}/`}
              className="reveal cb-blog-card"
              style={{
                display: 'flex', flexDirection: 'column',
                background: '#fff',
                border: '1px solid var(--border)',
                borderRadius: 16, overflow: 'hidden',
                textDecoration: 'none', color: 'inherit',
                transition: 'border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease',
              }}
            >
              <BlogCover eyebrow={a.coverEyebrow} title={a.title} variant={a.coverVariant} />
              <div style={{ padding: '22px 24px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div className="mono" style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  fontSize: 11, color: 'var(--fg-muted)',
                  textTransform: 'uppercase', letterSpacing: '0.1em',
                }}>
                  <span>{a.categoryLabel}</span>
                  <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--fg-faint)' }} />
                  <span>{a.dateLabel}</span>
                </div>
                <h3 style={{
                  fontSize: 19, fontWeight: 500,
                  letterSpacing: '-0.015em', lineHeight: 1.25,
                  textWrap: 'balance',
                }}>
                  {a.title}
                </h3>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

const BlogArticle = ({ slug }) => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  // Pour la lookup individuelle on utilise la liste COMPLETE (incluant articles programmés)
  // pour que l'URL directe d'un article futur reste accessible (preview, partage, Google).
  const articlesAll = (typeof getAllBlogArticles === 'function') ? getAllBlogArticles(country)
    : ((typeof getBlogArticles === 'function') ? getBlogArticles(country) : BLOG_ARTICLES);
  const article = articlesAll.find(a => a.slug === slug);
  const [html, setHtml] = React.useState('');
  const [error, setError] = React.useState(null);
  const [toc, setToc] = React.useState([]);
  const proseRef = React.useRef(null);

  React.useEffect(() => {
    if (!article) return;
    if (!window.marked) {
      setError('marked-not-loaded');
      return;
    }
    fetch(`/${country}/blog/${slug}/article.md`, { cache: 'no-cache' })
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.text();
      })
      .then(md => {
        const parsed = window.marked.parse(md);
        setHtml(parsed);
      })
      .catch(e => setError(String(e)));
  }, [slug, country]);

  React.useEffect(() => {
    if (!html || !proseRef.current) return;
    const h2s = proseRef.current.querySelectorAll('h2');
    const items = [];
    h2s.forEach((h, i) => {
      const text = h.textContent || '';
      const baseId = slugify(text) || `section-${i}`;
      h.id = baseId;
      items.push({ id: baseId, text });
    });
    setToc(items);

    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.1, rootMargin: '0px 0px -10% 0px' });
    proseRef.current.querySelectorAll('.reveal, h2, h3, p, ul, ol, blockquote').forEach(el => {
      el.classList.add('reveal');
      obs.observe(el);
    });
    return () => obs.disconnect();
  }, [html]);

  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.1, rootMargin: '0px 0px -10% 0px' });
    document.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  if (!article) {
    return (
      <>
        <Nav />
        <main style={{ padding: '160px 0 120px', textAlign: 'center' }}>
          <div className="container">
            <h1 className="h2">Artículo no encontrado</h1>
            <p style={{ marginTop: 16, color: 'var(--fg-muted)' }}>
              <a href={`/${country}/blog/`} style={{ color: 'inherit', textDecoration: 'underline' }}>Volver al blog</a>
            </p>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  // Pour les "related articles" on utilise la liste FILTREE (seuls les articles déjà publiés
  // doivent apparaître en suggestion).
  const articlesPublished = (typeof getBlogArticles === 'function') ? getBlogArticles(country) : BLOG_ARTICLES;
  const related = articlesPublished.filter(a => a.slug !== slug).slice(0, 2);

  return (
    <>
      <Nav />
      <main>
        <BlogArticleHero article={article} />
        <BlogArticleCover article={article} />

        <section style={{ paddingTop: 32, paddingBottom: 64 }}>
          <div className="container">
            <div className="cb-blog-layout" style={{
              maxWidth: 1080, margin: '0 auto',
              display: 'grid',
              gridTemplateColumns: '220px minmax(0, 1fr)',
              gap: 64,
              alignItems: 'flex-start',
            }}>
              <div className="cb-blog-toc-wrap">
                <BlogToc items={toc} />
              </div>
              <div>
                {error && (
                  <div style={{
                    padding: '20px 24px',
                    border: '1px solid var(--border)',
                    borderRadius: 12,
                    color: 'var(--fg-muted)',
                    fontSize: 14,
                  }}>
                    No se pudo cargar el artículo ({error}).
                  </div>
                )}
                <div
                  ref={proseRef}
                  className="cb-prose"
                  dangerouslySetInnerHTML={{ __html: html }}
                />
                <BlogInlineCta />
              </div>
            </div>
          </div>
        </section>

        <BlogRelated articles={related} />
      </main>
      <Footer />
      <WhatsAppButton />

      <style>{`
        .cb-blog-toc-wrap { position: sticky; top: 96px; align-self: start; }
        .cb-blog-toc-link:hover { color: var(--fg) !important; }

        .cb-prose {
          max-width: 720px;
          font-size: 17px;
          line-height: 1.75;
          color: var(--fg);
        }
        .cb-prose > * + * { margin-top: 1.4em; }
        .cb-prose p { color: var(--fg-soft); text-wrap: pretty; }
        .cb-prose h2 {
          font-size: clamp(24px, 2.6vw, 30px);
          font-weight: 500;
          letter-spacing: -0.018em;
          line-height: 1.22;
          margin-top: 2.2em;
          margin-bottom: 0.6em;
          color: var(--fg);
          scroll-margin-top: 96px;
        }
        .cb-prose h3 {
          font-size: 21px;
          font-weight: 500;
          letter-spacing: -0.012em;
          line-height: 1.3;
          margin-top: 1.8em;
          margin-bottom: 0.5em;
          color: var(--fg);
        }
        .cb-prose ul, .cb-prose ol { padding-left: 22px; color: var(--fg-soft); }
        .cb-prose li { margin: 0.4em 0; }
        .cb-prose li::marker { color: var(--fg-faint); }
        .cb-prose strong { color: var(--fg); font-weight: 600; }
        .cb-prose em { font-style: italic; }
        .cb-prose a {
          color: var(--fg);
          text-decoration: underline;
          text-decoration-color: rgba(198,156,255,0.55);
          text-underline-offset: 3px;
          transition: text-decoration-color 0.2s ease;
        }
        .cb-prose a:hover { text-decoration-color: var(--purple); }
        .cb-prose blockquote {
          margin: 1.8em 0;
          padding: 18px 22px;
          border: 1px solid rgba(198,156,255,0.30);
          background: linear-gradient(135deg, rgba(84,181,227,0.06) 0%, rgba(198,156,255,0.06) 100%);
          border-radius: 14px;
          color: var(--fg-soft);
          font-style: normal;
          font-size: 16.5px;
          line-height: 1.6;
        }
        .cb-prose blockquote p { margin: 0; }
        .cb-prose blockquote p + p { margin-top: 0.5em; }
        .cb-prose blockquote strong { color: var(--fg); }
        .cb-prose blockquote a {
          text-decoration-color: var(--purple);
          font-weight: 500;
        }
        .cb-prose img {
          display: block;
          width: 100%;
          max-width: 100%;
          height: auto;
          margin: 2em 0;
          border-radius: 14px;
          box-shadow: 0 8px 28px -12px rgba(15,23,42,0.18), 0 1px 2px rgba(0,0,0,0.04);
        }
        .cb-prose figure { margin: 2em 0; }
        .cb-prose figure img { margin: 0; }
        .cb-prose figcaption {
          font-size: 13px;
          color: var(--fg-muted);
          text-align: center;
          margin-top: 10px;
          line-height: 1.5;
        }
        .cb-prose code {
          background: var(--bg-muted);
          padding: 2px 6px;
          border-radius: 6px;
          font-size: 0.92em;
          font-family: 'Geist Mono', monospace;
        }
        .cb-prose pre {
          background: var(--bg-muted);
          padding: 18px 22px;
          border-radius: 12px;
          overflow-x: auto;
          font-size: 14px;
          line-height: 1.6;
        }
        .cb-prose pre code { background: none; padding: 0; }
        .cb-prose hr { border: none; border-top: 1px solid var(--border); margin: 2.4em 0; }

        .cb-prose table {
          width: 100%;
          margin: 2em 0;
          border-collapse: collapse;
          font-size: 15px;
          line-height: 1.5;
          overflow-x: auto;
          display: block;
        }
        @media (min-width: 760px) {
          .cb-prose table { display: table; }
        }
        .cb-prose thead {
          background: var(--bg-soft);
          border-bottom: 2px solid var(--fg);
        }
        .cb-prose th {
          text-align: left;
          padding: 12px 14px;
          font-weight: 500;
          color: var(--fg);
          letter-spacing: -0.01em;
        }
        .cb-prose td {
          padding: 14px;
          border-bottom: 1px solid var(--border-soft);
          color: var(--fg-soft);
          vertical-align: top;
        }
        .cb-prose tbody tr:last-child td { border-bottom: none; }
        .cb-prose tbody tr:hover { background: var(--bg-soft); }

        .cb-prose .reveal { opacity: 0; transform: translateY(12px); transition: opacity 0.6s ease, transform 0.6s ease; }
        .cb-prose .reveal.in { opacity: 1; transform: translateY(0); }

        @media (max-width: 880px) {
          .cb-blog-layout { grid-template-columns: 1fr !important; gap: 0 !important; }
          .cb-blog-toc-wrap { display: none; }
          .cb-prose { max-width: 100%; }
        }
        @media (max-width: 760px) {
          .cb-prose { font-size: 16px; line-height: 1.7; }
          .cb-prose blockquote { font-size: 16.5px; padding: 4px 0 4px 18px; margin: 1.4em 0; }
          .cb-prose pre { padding: 14px 16px; font-size: 13px; }
          .cb-blog-inline-cta {
            margin: 36px 0 !important;
            padding: 24px 22px !important;
            gap: 12px !important;
          }
          .cb-blog-inline-cta > div:nth-child(2) {
            font-size: 18px !important;
          }
        }
      `}</style>
    </>
  );
};

window.BlogArticle = BlogArticle;
