// src/pages/HomePage.jsx
function HomePage() {
  const { lang, t, navigate, setSection, scrollToSection, news, newsLoading, newsSource, stories, storiesLoading, storiesSource } = useApp();
  const th  = t.hero;
  const ts  = t.stories;
  const tp  = t.problems;
  const td  = t.demands;
  const tn  = t.latestNews;
  const tsu = t.supporters;

  // ── Scroll spy: стабильная подсветка пункта навигации ───
  React.useEffect(() => {
    const ORDER = ['hero', 'stories', 'problems', 'demands', 'latest-news', 'supporters'];
    const ratios = {};

    function pickActive() {
      if (window.__navScrollLock) return;
      let bestId = 'hero';
      let bestRatio = -1;
      for (const id of ORDER) {
        const r = ratios[id] || 0;
        if (r > bestRatio) {
          bestRatio = r;
          bestId = id;
        }
      }
      // Если почти ничего не видно — берём секцию у верхней границы
      if (bestRatio < 0.05) {
        const marker = 120;
        let current = 'hero';
        for (const id of ORDER) {
          const el = document.getElementById(id);
          if (!el) continue;
          if (el.getBoundingClientRect().top <= marker) current = id;
        }
        bestId = current;
      }
      setSection(prev => (prev === bestId ? prev : bestId));
    }

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          ratios[entry.target.id] = entry.isIntersecting ? entry.intersectionRatio : 0;
        });
        pickActive();
      },
      {
        root: null,
        // Учитываем фиксированный хедер
        rootMargin: '-96px 0px -45% 0px',
        threshold: [0, 0.1, 0.25, 0.4, 0.55, 0.7, 1],
      }
    );

    ORDER.forEach(id => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

    pickActive();
    return () => observer.disconnect();
  }, [setSection]);

  return (
    <div>

      {/* ── Hero ─────────────────────────────────── */}
      <section id="hero" className="min-h-screen flex flex-col justify-center pt-24 pb-24 sm:pb-28">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6 w-full">

          <h1
            className="hero-h1 font-bold leading-tight mb-5"
            style={{ color: 'var(--text)', maxWidth: 1100 }}
          >
            {th.h1a ? <>{th.h1a}{' '}</> : null}
            <span style={{ color: 'var(--accent)' }}>{th.h1b}</span>
            {th.h1c}
          </h1>

          <p
            className="text-[16px] sm:text-[18px] leading-[1.65] mb-10"
            style={{ color: 'var(--text-muted)', maxWidth: 720 }}
          >
            {th.body}
          </p>

          <button type="button" className="btn-outline" onClick={() => scrollToSection('problems')}>
            {th.more}
          </button>
        </div>
      </section>

      {/* ── Stories ──────────────────────────────── */}
      <section id="stories" className="section-block sec-border">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
          <h2 className="text-2xl sm:text-[48px] font-bold mb-10" style={{ color: 'var(--text)' }}>{ts.h2}</h2>
          {storiesSource === 'fallback' && (
            <p className="text-[13px] mb-4 px-3 py-2 rounded" style={{ color: 'var(--accent)', background: 'rgba(229,57,53,0.1)', border: '1px solid var(--accent)' }}>
              {lang === 'ru'
                ? 'Показаны демо-истории — Strapi недоступен. Запустите cms: npm run develop'
                : 'Showing demo stories — Strapi is unavailable. Start cms: npm run develop'}
            </p>
          )}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {storiesLoading
              ? <p className="text-[15px] col-span-full" style={{ color: 'var(--text-muted)' }}>{t.historyPage.loading}</p>
              : stories.slice(0, 4).map(item => <StoryCard key={item.id} item={item} />)}
          </div>
          <div className="mt-6 text-center">
            <button className="btn-outline text-sm" onClick={() => navigate('history')}>{ts.showMore}</button>
          </div>
        </div>
      </section>

      {/* ── Problems ─────────────────────────────── */}
      <section id="problems" className="section-block sec-border">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
          <h2 className="text-2xl sm:text-[48px] font-bold mb-10" style={{ color: 'var(--text)' }}>{tp.h2}</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {PROBLEMS.map(p => (
              <div key={p.num} className="card-base" style={{ padding: 24 }}>
                <h3 className="font-semibold text-[16px] mb-2" style={{ color: 'var(--text)' }}>{p.title[lang]}</h3>
                <p className="text-[15px] leading-relaxed" style={{ color: 'var(--text-muted)' }}>{p.text[lang]}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── Demands ──────────────────────────────── */}
      <section id="demands" className="section-block sec-border">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
          <h2 className="text-2xl sm:text-[48px] font-bold mb-6" style={{ color: 'var(--text)' }}>{td.h2}</h2>
          <p
            className="text-[15px] leading-relaxed mb-10"
            style={{ color: 'var(--text-muted)', maxWidth: 720 }}
          >
            {td.body}
          </p>
          <div className="max-w-4xl">
            {DEMANDS.map(d => (
              <div key={d.num} className="flex gap-[40%] mb-8 pb-8" style={{ borderBottom: '1px solid var(--border-card)' }}>
                <span className="font-bold text-lg flex-shrink-0 w-6" style={{ color: 'var(--text)' }}>{d.num}</span>
                <div>
                  <h3 className="font-semibold mb-1" style={{ color: 'var(--text)' }}>{d.title[lang]}</h3>
                  <p className="text-[15px] leading-relaxed" style={{ color: 'var(--text-muted)' }}>{d.text[lang]}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── Latest News ──────────────────────────── */}
      <section id="latest-news" className="section-block sec-border">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
          <h2 className="text-2xl sm:text-[48px] font-bold mb-6" style={{ color: 'var(--text)' }}>{tn.h2}</h2>
          <p className="text-[15px] mb-10 max-w-xl" style={{ color: 'var(--text-muted)' }}>{tn.sub}</p>
          {newsSource === 'fallback' && (
            <p className="text-[13px] mb-4 px-3 py-2 rounded" style={{ color: 'var(--accent)', background: 'rgba(229,57,53,0.1)', border: '1px solid var(--accent)' }}>
              {lang === 'ru'
                ? 'Показаны демо-новости — Strapi недоступен. Запустите cms: npm run develop'
                : 'Showing demo news — Strapi is unavailable. Start cms: npm run develop'}
            </p>
          )}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {newsLoading
              ? <p className="text-[15px] col-span-full" style={{ color: 'var(--text-muted)' }}>{t.newsPage.loading}</p>
              : news.slice(0, 4).map(item => <NewsCard key={item.id} item={item} />)
            }
          </div>
          <div className="mt-8 text-center">
            <button className="btn-outline" onClick={() => navigate('news')}>{tn.allNews}</button>
          </div>
        </div>
      </section>

      {/* ── Supporters ───────────────────────────── */}
      <section id="supporters" className="section-block sec-border">
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
          <h2 className="text-2xl sm:text-[48px] font-bold mb-10" style={{ color: 'var(--text)' }}>{tsu.h2}</h2>
          <div className="supporters-grid">
            {SUPPORTERS.map((s, i) => {
              if (s.placeholder) {
                return (
                  <div key={i} className="supporter-cell supporter-cell--placeholder">
                    <span className="supporter-placeholder-text">{tsu.placeholder}</span>
                  </div>
                );
              }
              const logo = (
                <img src={s.logo} alt={s.name} className="supporter-logo" />
              );
              if (s.url) {
                return (
                  <a
                    key={i}
                    href={s.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="supporter-cell"
                  >
                    {logo}
                  </a>
                );
              }
              return (
                <div key={i} className="supporter-cell">
                  {logo}
                </div>
              );
            })}
          </div>
        </div>
      </section>

    </div>
  );
}
