// ui_kits/website/ArchivePage.jsx
//
// Full-archive index of every blog post on the site. Linked from the
// "Ver todas las historias / View all stories" button at the bottom of
// the homepage BlogGrid, and (eventually) from the sitemap / footer.
//
// Why this exists as its own page:
//   • SEO — gives crawlers a single, link-rich index of all articles
//   • Discoverability — readers can scan the whole catalogue, not just
//     the curated homepage selection
//   • Filtering + sorting that doesn't fit on the homepage
//
// Visual vocabulary matches SectionPage: cream hero strip, breadcrumb,
// big serif title, italic deck, library grid of BlogCards.

const archiveStyles = {
  page: { background: '#fff' },

  // ---- Hero ----------------------------------------------------------
  hero: {
    position: 'relative',
    padding: '64px 0 56px',
    background: 'var(--brand-cream)',
    borderBottom: '1px solid var(--color-divider)',
    overflow: 'hidden',
  },
  heroInner: {
    maxWidth: 1200, margin: '0 auto', padding: '0 32px',
    position: 'relative', zIndex: 2,
  },
  breadcrumb: {
    display: 'flex', alignItems: 'center', gap: 8,
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
    marginBottom: 22,
  },
  breadcrumbLink: {
    color: 'inherit', textDecoration: 'none', cursor: 'pointer',
    background: 'none', border: 'none', padding: 0,
    fontFamily: 'inherit', fontSize: 'inherit', fontWeight: 'inherit',
    letterSpacing: 'inherit', textTransform: 'inherit',
    transition: 'color 200ms var(--ease-out)',
  },
  breadcrumbSep: { opacity: 0.4 },
  eyebrow: {
    fontFamily: 'var(--font-sans)', fontWeight: 700,
    fontSize: 12, letterSpacing: '0.22em', textTransform: 'uppercase',
    marginBottom: 12, color: 'var(--brand-leaf)',
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 72, lineHeight: 1, letterSpacing: '-0.02em',
    margin: 0, color: 'var(--color-fg-strong)',
    textWrap: 'balance',
  },
  deck: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 400,
    fontSize: 22, lineHeight: 1.45,
    maxWidth: '52ch', marginTop: 22,
    color: 'var(--color-fg)',
    textWrap: 'pretty',
  },
  countLine: {
    display: 'flex', alignItems: 'center', gap: 14,
    marginTop: 28,
    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
    letterSpacing: '0.06em', color: 'var(--color-fg-muted)',
  },
  countNum: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 28, letterSpacing: '-0.01em',
    color: 'var(--color-fg-strong)',
    lineHeight: 1,
  },
  countRule: { flex: 1, height: 1, background: 'var(--color-divider)' },

  // Decorative leaf watermark
  watermark: {
    position: 'absolute',
    right: -40, top: '50%', transform: 'translateY(-50%)',
    pointerEvents: 'none', zIndex: 1, opacity: 0.5,
  },

  // ---- Controls bar (filter + sort) ----------------------------------
  controls: {
    position: 'sticky', top: 0, zIndex: 10,
    background: 'rgba(255,255,255,0.92)',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    borderBottom: '1px solid var(--color-divider)',
  },
  controlsInner: {
    maxWidth: 1200, margin: '0 auto', padding: '14px 32px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    gap: 24, flexWrap: 'wrap',
  },
  filters: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' },
  chip: {
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
    letterSpacing: '0.1em', textTransform: 'uppercase',
    padding: '8px 14px', borderRadius: 9999,
    background: 'transparent', color: '#525150',
    border: '1px solid var(--color-divider)',
    cursor: 'pointer', transition: 'all 200ms var(--ease-out)',
  },
  chipActive: {
    background: 'var(--brand-leaf)', color: '#fff',
    borderColor: 'var(--brand-leaf)',
  },
  sort: {
    display: 'flex', alignItems: 'center', gap: 10,
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
    letterSpacing: '0.06em', color: 'var(--color-fg-muted)',
  },
  sortSelect: {
    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
    color: '#151414', cursor: 'pointer',
    padding: '6px 28px 6px 10px', borderRadius: 8,
    border: '1px solid var(--color-divider)',
    background: '#fff',
    appearance: 'none', WebkitAppearance: 'none',
    backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\' viewBox=\'0 0 10 6\'><path fill=\'none\' stroke=\'%23525150\' stroke-width=\'1.5\' d=\'M1 1l4 4 4-4\'/></svg>")',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'right 10px center',
  },

  // ---- Library grid --------------------------------------------------
  library: {
    maxWidth: 1200, margin: '0 auto', padding: '56px 32px 80px',
  },
  grid: {
    display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28,
  },
  empty: {
    padding: '64px 32px', textAlign: 'center',
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontSize: 20, color: 'var(--color-fg-muted)',
  },
};

// Parse a localized date string from a resolved post object back to a
// Date so we can sort newest/oldest. The raw post objects carry
// `{ es, en }` strings like "23 mayo, 2026" / "May 23, 2026". We hand
// the English version to Date.parse since it's the most reliable.
const ES_MONTHS = {
  enero: 0, febrero: 1, marzo: 2, abril: 3, mayo: 4, junio: 5,
  julio: 6, agosto: 7, septiembre: 8, octubre: 9, noviembre: 10, diciembre: 11,
};
function parsePostDate(rawPost) {
  if (!rawPost) return 0;
  // Prefer English string — easiest to parse.
  const en = rawPost.date && rawPost.date.en;
  if (en) {
    const t = Date.parse(en);
    if (!isNaN(t)) return t;
  }
  // Fall back to Spanish — "23 mayo, 2026"
  const es = rawPost.date && rawPost.date.es;
  if (es) {
    const m = es.match(/(\d{1,2})\s+([a-záéíóúñ]+)[,\s]+(\d{4})/i);
    if (m) {
      const day = parseInt(m[1], 10);
      const monKey = m[2].toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
      const mon = ES_MONTHS[monKey];
      const yr = parseInt(m[3], 10);
      if (mon != null) return new Date(yr, mon, day).getTime();
    }
  }
  // Last resort: id (newer ids tend to be newer posts in this dataset)
  return rawPost.id || 0;
}

function ArchivePage() {
  const lang = React.useContext(LangContext);
  const tr = useT();
  const isMobile = useIsMobile();

  // Re-render when blog-feed.js swaps in real posts
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const handler = () => force();
    window.addEventListener('blog-feed-updated', handler);
    return () => window.removeEventListener('blog-feed-updated', handler);
  }, []);

  // SEO — CollectionPage listing every article.
  React.useEffect(() => {
    updateSeo({
      title: t('archive.title', lang),
      description: t('archive.deck', lang),
      canonical: SEO.url(buildPath({ view: 'archive' })),
      ogType: 'website',
      ogImage: SEO.url('/og-image.jpg'),
      lang,
      jsonLd: {
        '@context': 'https://schema.org',
        '@type': 'CollectionPage',
        name: t('archive.title', lang) + ' — Top Natural Tips',
        description: t('archive.deck', lang),
        url: SEO.url(buildPath({ view: 'archive' })),
        isPartOf: { '@type': 'WebSite', name: 'Top Natural Tips', url: SEO.ORIGIN + '/' },
        publisher: SEO.org(),
      },
    });
  }, [lang]);

  const [filter, setFilter] = React.useState('All');
  const [sort, setSort]     = React.useState('newest'); // 'newest' | 'oldest'

  const filters = ['All', 'Health', 'Beauty', 'Nutrition', 'Exercise'];
  const chipLabel = (f) => f === 'All' ? tr('blog.filter.all') : tr('cat.' + f);

  const raw = window.SAMPLE_POSTS || [];

  // Filter, then sort, then resolve to flat strings.
  const sortedRaw = React.useMemo(() => {
    let arr = filter === 'All' ? [...raw] : raw.filter(p => p.category === filter);
    arr.sort((a, b) => {
      const da = parsePostDate(a);
      const db = parsePostDate(b);
      return sort === 'newest' ? db - da : da - db;
    });
    return arr;
  }, [raw, filter, sort]);

  const resolved = sortedRaw.map(p => (window.resolvePost ? window.resolvePost(p, lang) : p));

  return (
    <main style={archiveStyles.page}>
      {/* Hero */}
      <header style={{ ...archiveStyles.hero, ...(isMobile ? { padding: '40px 0 36px' } : {}) }}>
        <div style={{ ...archiveStyles.heroInner, ...(isMobile ? { padding: '0 20px' } : {}) }}>
          <nav style={archiveStyles.breadcrumb} aria-label="Breadcrumb">
            <a
              href={hrefFor({ view: 'home' })}
              style={archiveStyles.breadcrumbLink}
              onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--brand-leaf)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = 'inherit'; }}>
              {tr('section.back')}
            </a>
            <span style={archiveStyles.breadcrumbSep}>/</span>
            <span>{tr('archive.crumb')}</span>
          </nav>

          <div style={archiveStyles.eyebrow}>{tr('archive.eyebrow')}</div>
          <h1 style={{ ...archiveStyles.title, ...(isMobile ? { fontSize: 33 } : {}) }}>{tr('archive.title')}</h1>
          <p style={archiveStyles.deck}>{tr('archive.deck')}</p>

          <div style={archiveStyles.countLine}>
            <span style={archiveStyles.countNum}>{String(raw.length).padStart(2, '0')}</span>
            <span>{tr('archive.countLabel')}</span>
            <span style={archiveStyles.countRule}/>
          </div>
        </div>

        {/* Decorative leaf */}
        {window.LeafMark && (
          <div style={archiveStyles.watermark}>
            <LeafMark size={360} color="var(--brand-leaf)" opacity={0.08}/>
          </div>
        )}
      </header>

      {/* Sticky controls */}
      <div style={archiveStyles.controls}>
        <div style={{ ...archiveStyles.controlsInner, ...(isMobile ? { gap: 12, flexWrap: 'wrap', padding: '14px 20px' } : {}) }}>
          <div style={archiveStyles.filters}>
            {filters.map(f => (
              <button key={f}
                style={{ ...archiveStyles.chip, ...(filter === f ? archiveStyles.chipActive : {}) }}
                onClick={() => setFilter(f)}>{chipLabel(f)}</button>
            ))}
          </div>
          <label style={archiveStyles.sort}>
            <span>{tr('archive.sort.label')}</span>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              style={archiveStyles.sortSelect}>
              <option value="newest">{tr('archive.sort.newest')}</option>
              <option value="oldest">{tr('archive.sort.oldest')}</option>
            </select>
          </label>
        </div>
      </div>

      {/* Library grid */}
      <section style={{ ...archiveStyles.library, ...(isMobile ? { padding: '40px 20px 64px' } : {}) }}>
        {resolved.length === 0 ? (
          <div style={archiveStyles.empty}>{tr('archive.empty')}</div>
        ) : (
          <div style={{ ...archiveStyles.grid, ...(isMobile ? { gridTemplateColumns: '1fr' } : {}) }}>
            {resolved.map(p => (
              <BlogCard key={p.id || p.slug} post={p}/>
            ))}
          </div>
        )}
      </section>
    </main>
  );
}

window.ArchivePage = ArchivePage;
