// src/pages/NewsPage.jsx
function NewsPage() {
  const { lang, t, news, newsLoading, newsError, newsSource } = useApp();
  const [activeTag, setActiveTag] = React.useState('all');
  const [currentPage, setCurrentPage] = React.useState(1);
  const [indicator, setIndicator] = React.useState({ left: 0, width: 0, ready: false });
  const tabsRef = React.useRef(null);
  const btnRefs = React.useRef({});
  const PER_PAGE = 12;

  const tabs = FILTER_TABS_I18N[lang];

  const filtered = activeTag === 'all'
    ? news
    : news.filter(n => n.tag === activeTag);

  const totalPages = Math.ceil(filtered.length / PER_PAGE);
  const paged = filtered.slice((currentPage - 1) * PER_PAGE, currentPage * PER_PAGE);

  const updateIndicator = React.useCallback(() => {
    const list = tabsRef.current;
    const btn = btnRefs.current[activeTag];
    if (!list || !btn) return;
    setIndicator({
      left: btn.offsetLeft,
      width: btn.offsetWidth,
      ready: true,
    });
  }, [activeTag]);

  React.useEffect(() => {
    updateIndicator();
    window.addEventListener('resize', updateIndicator);
    return () => window.removeEventListener('resize', updateIndicator);
  }, [updateIndicator, tabs, lang]);

  function handleTag(key) {
    setActiveTag(key);
    setCurrentPage(1);
  }

  function getPageNumbers() {
    if (totalPages <= 7) {
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }
    const pages = new Set([1, totalPages, currentPage, currentPage - 1, currentPage + 1]);
    return [...pages].filter(p => p >= 1 && p <= totalPages).sort((a, b) => a - b);
  }

  const pageNumbers = getPageNumbers();

  return (
    <div className="pt-24 pb-16">
      <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
        <div className="h-10"></div>

        <div className="w-full overflow-x-auto no-scrollbar mb-8">
          <div
            ref={tabsRef}
            className="news-tags relative inline-flex items-center p-1 rounded-lg min-w-full sm:min-w-0"
            style={{ border: '1px solid var(--border-card)' }}
          >
            <span
              className="news-tags-indicator"
              aria-hidden="true"
              style={{
                width: indicator.width,
                transform: `translateX(${indicator.left}px)`,
                opacity: indicator.ready ? 1 : 0,
              }}
            />
            {tabs.map(tab => (
              <button
                key={tab.key}
                ref={el => { btnRefs.current[tab.key] = el; }}
                type="button"
                onClick={() => handleTag(tab.key)}
                className="news-tags-btn relative z-[1] px-4 py-1.5 rounded-md text-sm cursor-pointer whitespace-nowrap flex-1 sm:flex-initial text-center"
                style={{
                  color: activeTag === tab.key ? 'var(--text)' : 'var(--filter-txt)',
                }}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {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>
        )}

        {newsLoading && (
          <p className="text-[15px]" style={{ color: 'var(--text-muted)' }}>{t.newsPage.loading}</p>
        )}

        {!newsLoading && newsError && (
          <p className="text-[15px]" style={{ color: 'var(--accent)' }}>{t.newsPage.error}</p>
        )}

        {!newsLoading && !newsError && filtered.length === 0 && (
          <p className="text-[15px]" style={{ color: 'var(--text-muted)' }}>{t.newsPage.empty}</p>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {!newsLoading && paged.map(item => <NewsCard key={item.id} item={item} />)}
        </div>

        {!newsLoading && totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 mt-10 flex-wrap">
            <button
              className="pagination-btn"
              onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              style={{ width: 'auto', padding: '0 14px' }}
            >
              {t.newsPage.prev}
            </button>

            {pageNumbers.map((p, i) => {
              const prev = pageNumbers[i - 1];
              const showEllipsis = prev != null && p - prev > 1;
              return (
                <React.Fragment key={p}>
                  {showEllipsis && (
                    <span style={{ color: 'var(--text-muted)', fontSize: 14, padding: '0 4px' }}>...</span>
                  )}
                  <button
                    className={`pagination-btn ${currentPage === p ? 'active' : ''}`}
                    onClick={() => setCurrentPage(p)}
                  >
                    {p}
                  </button>
                </React.Fragment>
              );
            })}

            <button
              className="pagination-btn"
              onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              style={{ width: 'auto', padding: '0 14px' }}
            >
              {t.newsPage.next}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
