const BlogList = ({ lang = 'en', onNavigate, blogs }) => {
  const [query, setQuery] = React.useState('');

  // DB data takes priority; fallback to static mock when DB returns nothing
  const posts = (blogs && blogs.length > 0) ? blogs : (window.BLOG_POSTS || []);

  // Latest featured post; fallback to first post if none are featured
  const featured = React.useMemo(() => {
    const featuredPosts = posts.filter(p => p.featured);
    if (featuredPosts.length === 0) return posts[0] || null;
    return featuredPosts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))[0];
  }, []);

  const filtered = React.useMemo(() => {
    if (!query) return posts;
    const q = query.toLowerCase();
    return posts.filter(p =>
      i18(p.title, lang).toLowerCase().includes(q) ||
      i18(p.excerpt, lang).toLowerCase().includes(q)
    );
  }, [query, lang]);

  const grid = query ? filtered : filtered.filter(p => p.id !== (featured && featured.id));

  const LOCALE_MAP = { fr: 'fr-FR', dar: 'ar-MA', ar: 'ar-SA', en: 'en-US' };
  const fmt = (iso) => new Date(iso).toLocaleDateString(
    LOCALE_MAP[lang] || 'en-US',
    { year: 'numeric', month: 'short', day: 'numeric' }
  );

  return (
    <div className="ag-bl">

      {/* Hero */}
      <section className="ag-bl__hero ag-section">
        <p className="ag-eyebrow-pill">{t('blog.eyebrow', lang)}</p>
        <h1 className="ag-bl__hero-title">{t('blog.heroTitle', lang)}</h1>
        <p className="ag-bl__hero-sub">{t('blog.heroSub', lang)}</p>
      </section>

      {/* Search */}
      <div className="ag-bl__search-wrap">
        <div className="ag-bl__search-inner">
          <svg className="ag-bl__search-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
          <input
            className="ag-bl__search"
            type="text"
            placeholder={t('blog.searchPh', lang)}
            value={query}
            onChange={e => setQuery(e.target.value)}
            aria-label="Search articles"
          />
          {query && (
            <button className="ag-bl__search-clear" onClick={() => setQuery('')} aria-label="Clear search">×</button>
          )}
        </div>
        {query && (
          <p className="ag-bl__search-count">
            {filtered.length === 0 ? 'No results' : `${filtered.length} article${filtered.length !== 1 ? 's' : ''} found`}
          </p>
        )}
      </div>

      {/* Featured */}
      {!query && featured && (
        <section className="ag-bl__featured ag-section">
          <div
            className="ag-bl__feat-card"
            onClick={() => onNavigate(`/blog/${featured.slug}`)}
            role="button"
            tabIndex={0}
            onKeyPress={e => e.key === 'Enter' && onNavigate(`/blog/${featured.slug}`)}
          >
            <div className="ag-bl__feat-img">
              <img
                src={featured.cover_url || featured.cover}
                alt={i18(featured.title, lang)}
                onError={e => { e.target.src = 'assets/hero-bg.jpg'; }}
              />
            </div>
            <div className="ag-bl__feat-body">
              <div className="ag-bl__feat-labels">
                <span className="ag-bl__cat">{featured.category}</span>
                <span className="ag-bl__featured-badge">{t('blog.featured', lang)}</span>
              </div>
              <h2 className="ag-bl__feat-title">{i18(featured.title, lang)}</h2>
              <p className="ag-bl__feat-excerpt">{i18(featured.excerpt, lang)}</p>
              <div className="ag-bl__meta">
                <span>{fmt(featured.created_at)}</span>
                <span className="ag-bl__dot">·</span>
                <span>{featured.reading_time} {t('blog.readTime', lang)}</span>
              </div>
              <button className="ag-btn ag-btn--dark ag-bl__feat-btn">{t('blog.readArticle', lang)}</button>
            </div>
          </div>
        </section>
      )}

      {/* Grid */}
      <section className="ag-bl__grid-section ag-section">
        {posts.length === 0 ? (
          <p className="ag-bl__empty">No articles yet. Check back soon.</p>
        ) : grid.length === 0 && query ? (
          <p className="ag-bl__empty">No articles match "{query}"</p>
        ) : (
          <div className="ag-bl__grid">
            {grid.map(post => (
              <article
                key={post.id}
                className="ag-bl__card"
                onClick={() => onNavigate(`/blog/${post.slug}`)}
                role="button"
                tabIndex={0}
                onKeyPress={e => e.key === 'Enter' && onNavigate(`/blog/${post.slug}`)}
              >
                <div className="ag-bl__card-img">
                  <img
                    src={post.cover_url || post.cover}
                    alt={i18(post.title, lang)}
                    onError={e => { e.target.src = 'assets/hero-bg.jpg'; }}
                  />
                </div>
                <div className="ag-bl__card-body">
                  <span className="ag-bl__cat">{post.category}</span>
                  <h3 className="ag-bl__card-title">{i18(post.title, lang)}</h3>
                  <p className="ag-bl__card-excerpt">{i18(post.excerpt, lang)}</p>
                  <div className="ag-bl__meta">
                    <span>{fmt(post.created_at)}</span>
                    <span className="ag-bl__dot">·</span>
                    <span>{post.reading_time} {t('blog.readTime', lang)}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        )}
      </section>

    </div>
  );
};

window.BlogList = BlogList;
