// BlogIndex — Liste des articles du blog Vestora
// Route : #/blog
// Affiche les cards titre + extrait + date pour chaque article Markdown

(function () {
  const { useState: useBIS, useEffect: useBIE } = 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 BlogCard({ article, onClick }) {
    const { meta, slug } = article;
    const tags = Array.isArray(meta.tags) ? meta.tags : [];

    return (
      <article
        className="blog-card"
        onClick={onClick}
        style={{ cursor: 'pointer' }}
        role="button"
        tabIndex={0}
        onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') onClick(); }}
        aria-label={`Lire : ${meta.title}`}
      >
        <div className="blog-card-body">
          <div className="blog-card-meta">
            <time dateTime={meta.date}>{formatDate(meta.date)}</time>
            {tags.length > 0 && (
              <span className="blog-card-tags">
                {tags.slice(0, 3).map((tag, i) => (
                  <span key={i} className="blog-tag">{tag}</span>
                ))}
              </span>
            )}
          </div>
          <h2 className="blog-card-title">{meta.title}</h2>
          <p className="blog-card-excerpt">{meta.excerpt}</p>
          <span className="blog-card-cta">Lire l'article →</span>
        </div>
      </article>
    );
  }

  function BlogIndex({ lang, onBack, onArticle }) {
    const [articles, setArticles] = useBIS(null);
    const [error, setError] = useBIS(null);

    useBIE(() => {
      window.scrollTo(0, 0);
      if (!window.vestora || !window.vestora.blog) {
        setError('Module blog non chargé.');
        return;
      }
      window.vestora.blog.loadArticles()
        .then(data => setArticles(data))
        .catch(e => setError(e.message));
    }, []);

    // SEO — meta dynamique
    useBIE(() => {
      document.title = 'Blog — Vestora | Investissement immobilier Québec';
      let metaDesc = document.querySelector('meta[name="description"]');
      if (metaDesc) {
        metaDesc.setAttribute('content',
          'Articles et analyses sur l\'investissement immobilier au Québec : cap rate, DSCR, marchés locatifs et stratégies pour investisseurs.'
        );
      }
      return () => {
        document.title = 'Vestora — Estimation d\'investissement immobilier';
        if (metaDesc) {
          metaDesc.setAttribute('content',
            'Vestora analyse les biens à revenus du Québec et estime leur potentiel d\'investissement : cap rate, DSCR, cash-flow, score sur 100.'
          );
        }
      };
    }, []);

    return (
      <div className="blog-page">
        {/* Header */}
        <div className="blog-page-header">
          <button className="btn btn-ghost" onClick={onBack}>← Retour</button>
          <div className="blog-page-hero">
            <h1 className="blog-page-title">
              <span className="blog-page-title-accent">Blog</span> Vestora
            </h1>
            <p className="blog-page-subtitle">
              Analyses, guides et données sur l'investissement immobilier au Québec
            </p>
          </div>
        </div>

        {/* Contenu */}
        <div className="blog-page-content">
          {error && (
            <div className="blog-empty">
              <p>Impossible de charger les articles : {error}</p>
            </div>
          )}

          {!error && articles === null && (
            <div className="blog-list">
              {[1, 2, 3].map(i => (
                <div key={i} className="blog-card blog-card-skeleton">
                  <div className="blog-card-body">
                    <div className="skeleton-line" style={{ width: '30%', height: 14, marginBottom: 12 }} />
                    <div className="skeleton-line" style={{ width: '80%', height: 22, marginBottom: 10 }} />
                    <div className="skeleton-line" style={{ width: '95%', height: 14, marginBottom: 6 }} />
                    <div className="skeleton-line" style={{ width: '70%', height: 14 }} />
                  </div>
                </div>
              ))}
            </div>
          )}

          {!error && articles && articles.length === 0 && (
            <div className="blog-empty">
              <p>Aucun article disponible pour l'instant.</p>
            </div>
          )}

          {!error && articles && articles.length > 0 && (
            <div className="blog-list">
              {articles.map(article => (
                <BlogCard
                  key={article.slug}
                  article={article}
                  onClick={() => onArticle(article.slug)}
                />
              ))}
            </div>
          )}
        </div>

        {/* Footer simple */}
        <div className="blog-page-footer">
          <button className="btn btn-ghost" onClick={onBack}>← Retour à Vestora</button>
        </div>
      </div>
    );
  }

  window.BlogIndex = BlogIndex;
})();
