// articles.jsx — Index page for DIB Articles.
// Search, category filter, sort, and magazine layout.
// Depends on: tweaks-panel.jsx, articles-atoms.jsx, articles-data.js, i18n.js
const { useState, useEffect, useMemo } = React;

const LANGS = [
  { value: 'en', label: 'English',  flag: '🇬🇧' },
  { value: 'de', label: 'Deutsch',  flag: '🇩🇪' },
  { value: 'ro', label: 'Română',   flag: '🇷🇴' },
  { value: 'fr', label: 'Français', flag: '🇫🇷' },
  { value: 'it', label: 'Italiano', flag: '🇮🇹' },
  { value: 'es', label: 'Español',  flag: '🇪🇸' },
];

const TWEAK_DEFAULTS = {
  accent: 'cyan', customColor: '#22e3ff', glowIntensity: 35,
  typeface: 'sora', motion: 'medium', theme: 'dark', language: 'en',
};

/** ISO 639-1 → BCP-47 locale for Intl.DateTimeFormat */
const LANG_LOCALE = { en: 'en-US', de: 'de-DE', ro: 'ro-RO', fr: 'fr-FR', it: 'it-IT', es: 'es-ES' };

/** Return translated { title, excerpt } for an article, falling back to EN fields. */
function artT(a, lang) {
  const tr = a.translations?.[lang];
  return {
    title:   tr?.title   ?? a.title,
    excerpt: tr?.excerpt ?? a.excerpt,
  };
}

/** Format an ISO date string using the locale matching the current language. */
function fmtDate(iso, lang) {
  try {
    return new Date(iso).toLocaleDateString(LANG_LOCALE[lang] || 'en-US',
      { month: 'short', day: 'numeric', year: 'numeric' });
  } catch (_) {
    return iso;
  }
}

/* ─── Article Card ──────────────────────────────────────────────────── */
function ArticleCard({ a, idx, lang, t }) {
  const { title, excerpt } = artT(a, lang);
  const cat      = window.BLOG_CATEGORIES.find(c => c.id === a.category);
  const author   = window.BLOG_AUTHORS[a.author];
  const catLabel = t.categories?.[a.category] || cat?.label || '';
  return (
    <a href={`Article.html?id=${a.id}`}
       className={`b-card reveal delay-${Math.min(idx % 6 + 1, 6)}`}>
      <div className="b-card__visual">
        <Placeholder caption={a.figureCap || title} label={catLabel.toUpperCase()} aspect="16 / 10" />
      </div>
      <div className="b-card__meta">
        <span className="tag">{catLabel}</span>
        <span className="dot" />
        <span>{fmtDate(a.date, lang)}</span>
        <span className="dot" />
        <span>{a.readMin} {t.min}</span>
      </div>
      <h3>{title}</h3>
      <p className="b-card__excerpt">{excerpt}</p>
      <div className="b-card__byline">
        <Avatar author={a.author} size={28} />
        <strong>{author.name}</strong>
      </div>
    </a>
  );
}

/* ─── Layout A: Featured + Grid ─────────────────────────────────────── */
function LayoutFeatured({ articles, lang, t }) {
  if (articles.length === 0) return null;
  const featured     = articles.find(a => a.featured) || articles[0];
  const rest         = articles.filter(a => a.id !== featured.id);
  const { title, excerpt } = artT(featured, lang);
  const cat          = window.BLOG_CATEGORIES.find(c => c.id === featured.category);
  const author       = window.BLOG_AUTHORS[featured.author];
  const catLabel     = t.categories?.[featured.category] || cat?.label || '';
  return (
    <div>
      <a href={`Article.html?id=${featured.id}`} className="b-featured reveal">
        <div className="b-featured__visual">
          <Placeholder caption={featured.figureCap} label={t.featured} aspect="auto" />
        </div>
        <div className="b-featured__body">
          <div className="b-featured__meta">
            <span className="tag">{catLabel}</span>
            <span>·</span>
            <span>{fmtDate(featured.date, lang)}</span>
            <span>·</span>
            <span>{featured.readMin} {t.min_read}</span>
          </div>
          <h2>{title}</h2>
          <p className="b-featured__excerpt">{excerpt}</p>
          <div className="b-featured__byline">
            <Avatar author={featured.author} size={32} />
            <span>{t.by} <strong>{author.name}</strong> · {author.role}</span>
          </div>
          <span className="b-featured__cta">{t.read_more} <Arrow /></span>
        </div>
      </a>
      <div className="b-grid">
        {rest.map((a, i) => <ArticleCard key={a.id} a={a} idx={i} lang={lang} t={t} />)}
      </div>
    </div>
  );
}

/* ─── Layout B: Uniform Grid ────────────────────────────────────────── */
function LayoutUniform({ articles, lang, t }) {
  return (
    <div className="b-uniform">
      {articles.map((a, i) => <ArticleCard key={a.id} a={a} idx={i} lang={lang} t={t} />)}
    </div>
  );
}

/* ─── Layout C: Editorial List ──────────────────────────────────────── */
function LayoutList({ articles, lang, t }) {
  return (
    <div className="b-list">
      {articles.map((a, i) => {
        const { title, excerpt } = artT(a, lang);
        const cat      = window.BLOG_CATEGORIES.find(c => c.id === a.category);
        const author   = window.BLOG_AUTHORS[a.author];
        const catLabel = t.categories?.[a.category] || cat?.label || '';
        return (
          <a href={`Article.html?id=${a.id}`} key={a.id}
             className={`b-list__row reveal delay-${Math.min(i % 6 + 1, 6)}`}>
            <span className="idx">{String(i + 1).padStart(2, '0')}</span>
            <div>
              <h3>{title}</h3>
              <p>{excerpt}</p>
            </div>
            <div className="meta">
              <strong>{catLabel}</strong>
              <span>{fmtDate(a.date, lang)}</span>
              <span>{author.name}</span>
            </div>
            <span className="dur">{a.readMin} {t.min.toUpperCase()}</span>
          </a>
        );
      })}
    </div>
  );
}

/* ─── Layout D: Magazine (hero + 2-up + grid) ───────────────────────── */
function LayoutMagazine({ articles, lang, t }) {
  if (articles.length === 0) return null;
  const featured     = articles.find(a => a.featured) || articles[0];
  const rest         = articles.filter(a => a.id !== featured.id);
  const twoUp        = rest.slice(0, 2);
  const grid         = rest.slice(2);
  const { title, excerpt } = artT(featured, lang);
  const cat          = window.BLOG_CATEGORIES.find(c => c.id === featured.category);
  const author       = window.BLOG_AUTHORS[featured.author];
  const catLabel     = t.categories?.[featured.category] || cat?.label || '';
  return (
    <div className="b-magazine">
      <a href={`Article.html?id=${featured.id}`} className="b-mag-hero reveal">
        <div className="b-mag-hero__visual">
          <Placeholder caption={featured.figureCap} label={t.featured} aspect="auto" />
        </div>
        <div className="b-mag-hero__body">
          <div className="b-featured__meta">
            <span className="tag">{catLabel}</span>
            <span>·</span>
            <span>{fmtDate(featured.date, lang)}</span>
            <span>·</span>
            <span>{featured.readMin} {t.min}</span>
            <span>·</span>
            <span>{t.by} {author.name}</span>
          </div>
          <h2>{title}</h2>
          <p>{excerpt}</p>
        </div>
      </a>
      <div className="b-mag-twoup">
        {twoUp.map((a, i) => <ArticleCard key={a.id} a={a} idx={i} lang={lang} t={t} />)}
      </div>
      <div className="b-grid">
        {grid.map((a, i) => <ArticleCard key={a.id} a={a} idx={i} lang={lang} t={t} />)}
      </div>
    </div>
  );
}

/* ─── Toolbar ──────────────────────────────────────────────────────── */
function Toolbar({ query, setQuery, category, setCategory, sort, setSort, articles, t }) {
  const counts = useMemo(() => {
    const c = { all: articles.length };
    window.BLOG_CATEGORIES.forEach(cat => {
      if (cat.id !== 'all') c[cat.id] = articles.filter(a => a.category === cat.id).length;
    });
    return c;
  }, [articles]);

  return (
    <div className="b-toolbar">
      <div className="b-toolbar__row">
        <div className="b-search">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
            <circle cx="7" cy="7" r="4.5" stroke="currentColor" strokeWidth="1.4" />
            <path d="M10.5 10.5L14 14" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
          </svg>
          <input
            type="search"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder={t.search_placeholder}
            aria-label={t.search_placeholder}
          />
          {!query && <kbd>⌘ K</kbd>}
        </div>

        <div className="b-pills" role="group" aria-label="Filter by category">
          {window.BLOG_CATEGORIES.map(c => (
            <button key={c.id}
                    className={`b-pill ${category === c.id ? 'on' : ''}`}
                    onClick={() => setCategory(c.id)}>
              {t.categories?.[c.id] || c.label}
              <span className="b-pill__count">{counts[c.id] || 0}</span>
            </button>
          ))}
        </div>

        <div className="b-sort">
          <span>{t.sort}</span>
          <div className="b-sort__btns">
            <button className={`b-sort__btn ${sort === 'newest' ? 'on' : ''}`}
                    onClick={() => setSort('newest')}>{t.newest}</button>
            <button className={`b-sort__btn ${sort === 'popular' ? 'on' : ''}`}
                    onClick={() => setSort('popular')}>{t.popular}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─── Main Page ────────────────────────────────────────────────────── */
function BlogIndex() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [query,    setQuery]   = useState('');
  const [category, setCat]    = useState('all');
  const [sort,     setSort]   = useState('newest');

  useEffect(() => { window.applyBlogTweaks(tweaks); }, [tweaks]);

  // Cmd/Ctrl+K → focus search
  useEffect(() => {
    const onKey = e => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        document.querySelector('.b-search input')?.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const lang = tweaks.language || 'en';

  // Filter + sort — uses artT for translated search
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    let xs = window.BLOG_ARTICLES.filter(a => {
      if (category !== 'all' && a.category !== category) return false;
      if (!q) return true;
      const { title, excerpt } = artT(a, lang);
      const author = window.BLOG_AUTHORS[a.author]?.name?.toLowerCase() || '';
      return title.toLowerCase().includes(q)
          || excerpt.toLowerCase().includes(q)
          || author.includes(q)
          || (a.tags || []).some(tag => tag.toLowerCase().includes(q));
    });
    if (sort === 'newest') xs.sort((x, y) => y.date.localeCompare(x.date));
    else                   xs.sort((x, y) => (y.popularity || 0) - (x.popularity || 0));
    return xs;
  }, [query, category, sort, lang]);

  useReveal([filtered, lang]);

  const t = window.I18N[lang]?.articles_ui || window.I18N.en.articles_ui;

  return (
    <>
      <BlogNav pageLabel={t.nav_articles} tweaks={tweaks} setTweak={setTweak}
               presets={window.BLOG_ACCENT_PRESETS} langs={LANGS} />

      {/* Hero */}
      <header className="b-hero" id="main-content">
        <div style={{ position: 'absolute', inset: 0, opacity: 0.5, pointerEvents: 'none' }}>
          <MiniLattice opacity={1} />
        </div>
        <div className="b-hero__inner">
          <div className="b-hero__top">
            <span>Digital Immersive Box · {t.nav_articles}</span>
            <span>
              {t.entries_count.replace('{count}', window.BLOG_ARTICLES.length)}
              {' · '}
              {t.updated} {fmtDate(window.BLOG_ARTICLES[0]?.date, lang)}
            </span>
          </div>
          <h1 className="reveal" dangerouslySetInnerHTML={{ __html: t.hero_h1 }} />
          <p className="b-hero__sub reveal delay-1">{t.hero_sub}</p>
        </div>
      </header>

      {/* Toolbar */}
      <Toolbar query={query} setQuery={setQuery}
               category={category} setCategory={setCat}
               sort={sort} setSort={setSort}
               articles={window.BLOG_ARTICLES} t={t} />

      {/* Content */}
      <main className="b-content">
        <div className="b-content__inner">
          {filtered.length === 0 ? (
            <div className="b-empty">
              <h3>{t.no_match_title}</h3>
              <p>{t.no_match_desc}</p>
            </div>
          ) : (
            <LayoutMagazine articles={filtered} lang={lang} t={t} />
          )}
        </div>
      </main>

      <footer className="b-footer">
        <span>{t.footer_copy}</span>
        <a href="index.html">← digitalimmersivebox.com</a>
      </footer>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<BlogIndex />);
