// BlogArticle — Rendu d'un article Markdown individuel
// Route : #/blog/:slug
// SEO : <title>, <meta description>, JSON-LD Article

(function () {
  const { useState: useBAS, useEffect: useBAE } = React;

  function formatDate(dateStr) {
    if (!dateStr) return '';
    try {
      return new Date(dateStr).toLocaleDateString('fr-CA', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      });
    } catch {
      return dateStr;
    }
  }

  function BlogArticle({ slug, lang, onBack, onBlog }) {
    const [article, setArticle] = useBAS(null);
    const [error, setError] = useBAS(null);
    const [loading, setLoading] = useBAS(true);

    useBAE(() => {
      window.scrollTo(0, 0);
      setLoading(true);
      setError(null);

      if (!window.vestora || !window.vestora.blog) {
        setError('Module blog non chargé.');
        setLoading(false);
        return;
      }

      window.vestora.blog.loadArticle(slug)
        .then(data => {
          setArticle(data);
          setLoading(false);
        })
        .catch(e => {
          setError(`Article introuvable (${e.message})`);
          setLoading(false);
        });
    }, [slug]);

    // SEO — <title>, <meta description>, JSON-LD
    useBAE(() => {
      if (!article) return;
      const { meta } = article;

      // Title
      const prevTitle = document.title;
      document.title = `${meta.title} — Vestora`;

      // Meta description
      let metaDesc = document.querySelector('meta[name="description"]');
      const prevDesc = metaDesc ? metaDesc.getAttribute('content') : '';
      if (metaDesc && meta.excerpt) {
        metaDesc.setAttribute('content', meta.excerpt);
      }

      // JSON-LD Article
      const jsonLd = document.createElement('script');
      jsonLd.type = 'application/ld+json';
      jsonLd.id = 'blog-article-jsonld';
      const tags = Array.isArray(meta.tags) ? meta.tags : [];
      jsonLd.textContent = JSON.stringify({
        '@context': 'https://schema.org',
        '@type': 'Article',
        'headline': meta.title,
        'description': meta.excerpt || '',
        'datePublished': meta.date || '',
        'dateModified': meta.date || '',
        'author': {
          '@type': 'Organization',
          'name': 'Vestora',
          'url': 'https://vestora.ca',
        },
        'publisher': {
          '@type': 'Organization',
          'name': 'Vestora',
          'url': 'https://vestora.ca',
        },
        'keywords': tags.join(', '),
        'inLanguage': 'fr-CA',
        'url': `https://vestora.ca/#/blog/${meta.slug || slug}`,
      });
      document.head.appendChild(jsonLd);

      return () => {
        document.title = prevTitle;
        if (metaDesc) metaDesc.setAttribute('content', prevDesc);
        const existing = document.getElementById('blog-article-jsonld');
        if (existing) existing.remove();
      };
    }, [article]);

    // ---- Skeleton ----
    if (loading) {
      return (
        <div className="blog-article-page">
          <div className="blog-article-header">
            <button className="btn btn-ghost" onClick={onBack}>← Retour</button>
          </div>
          <div className="blog-article-content">
            <div className="skeleton-line" style={{ width: '20%', height: 14, marginBottom: 20 }} />
            <div className="skeleton-line" style={{ width: '85%', height: 32, marginBottom: 16 }} />
            <div className="skeleton-line" style={{ width: '60%', height: 32, marginBottom: 32 }} />
            {[95, 88, 92, 78, 90, 70, 85].map((w, i) => (
              <div key={i} className="skeleton-line" style={{ width: `${w}%`, height: 14, marginBottom: 10 }} />
            ))}
          </div>
        </div>
      );
    }

    // ---- Erreur ----
    if (error) {
      return (
        <div className="blog-article-page">
          <div className="blog-article-header">
            <button className="btn btn-ghost" onClick={onBack}>← Retour</button>
          </div>
          <div className="blog-article-content">
            <div className="blog-empty">
              <p>{error}</p>
              <button className="btn btn-ghost" onClick={onBlog} style={{ marginTop: 16 }}>
                Voir tous les articles
              </button>
            </div>
          </div>
        </div>
      );
    }

    if (!article) return null;

    const { meta, html } = article;
    const tags = Array.isArray(meta.tags) ? meta.tags : [];

    // Sanitiser le HTML via DOMPurify si disponible
    const safeHtml = typeof DOMPurify !== 'undefined'
      ? DOMPurify.sanitize(html, { USE_PROFILES: { html: true } })
      : html;

    return (
      <div className="blog-article-page">
        {/* Header nav */}
        <div className="blog-article-header">
          <button className="btn btn-ghost" onClick={onBlog}>← Blog</button>
        </div>

        {/* Article */}
        <article className="blog-article-content">
          {/* Meta : date + tags */}
          <div className="blog-article-meta">
            <time dateTime={meta.date}>{formatDate(meta.date)}</time>
            {tags.length > 0 && (
              <span className="blog-card-tags">
                {tags.map((tag, i) => (
                  <span key={i} className="blog-tag">{tag}</span>
                ))}
              </span>
            )}
          </div>

          {/* Corps Markdown rendu */}
          <div
            className="blog-article-body"
            dangerouslySetInnerHTML={{ __html: safeHtml }}
          />
        </article>

        {/* CTA bas de page */}
        <div className="blog-article-footer">
          <div className="blog-article-cta">
            <p>Analysez ces marchés en temps réel avec Vestora</p>
            <button
              className="btn"
              style={{
                background: 'var(--accent, oklch(0.36 0.07 155))',
                color: '#fff',
                border: 'none',
                padding: '10px 22px',
                borderRadius: 8,
                fontWeight: 600,
                cursor: 'pointer',
                fontFamily: 'inherit',
                fontSize: 14,
              }}
              onClick={onBack}
            >
              Explorer les plex →
            </button>
          </div>
          <div className="blog-article-nav">
            <button className="btn btn-ghost" onClick={onBlog}>← Tous les articles</button>
          </div>
        </div>
      </div>
    );
  }

  window.BlogArticle = BlogArticle;
})();
