// src/pages/HistoryPage.jsx
function HistoryPage() {
  const { lang, t, stories, storiesLoading, storiesError, storiesSource } = useApp();
  const [currentPage, setCurrentPage] = React.useState(1);
  const PER_PAGE = 12;
  const th = t.historyPage;

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

  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" />

        <h1 className="text-2xl sm:text-[48px] font-bold mb-10" style={{ color: 'var(--text)' }}>
          {t.stories.h2}
        </h1>

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

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

        {!storiesLoading && storiesError && (
          <p className="text-[15px]" style={{ color: 'var(--accent)' }}>{th.error}</p>
        )}

        {!storiesLoading && !storiesError && stories.length === 0 && (
          <p className="text-[15px]" style={{ color: 'var(--text-muted)' }}>{th.empty}</p>
        )}

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

        {!storiesLoading && 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' }}
            >
              {th.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' }}
            >
              {th.next}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
