// Category page.
//   #/c/<slug>                 → category landing (subcategory tiles + first page of products)
//   #/c/<slug>/<sub-slug>      → filtered to that subcategory
//   #/c/<unknown>              → EmptyState card (legacy non-enriched categories)
//
// All-product pagination: PAGE_SIZE per page with "load more" button.

(function () {
  const PAGE_SIZE = 24;

  window.CategoryPage = function CategoryPage({ slug }) {
    // Slug can be "category" or "category/subcategory"
    const parts = (slug || '').split('/').filter(Boolean);
    const catSlug = parts[0];
    const subSlug = parts[1] || null;

    const cat = window.NAJMAT_DATA.categories.find(c => c.slug === catSlug);
    const [shown, setShown] = React.useState(PAGE_SIZE);

    // Reset pagination on slug change
    React.useEffect(() => { setShown(PAGE_SIZE); }, [slug]);

    if (!cat) {
      return (
        <section className="page-pad">
          <div className="rail" style={{ textAlign: 'center', padding: 'var(--s-80) 0' }}>
            <h1 style={{ fontSize: 'var(--fs-30)', marginBottom: 'var(--s-12)' }}>Category not found.</h1>
            <p style={{ color: 'var(--warm-ink)' }}><a href="#/" style={{ color: 'var(--orange)', borderBottom: '1px solid currentColor' }}>← back to all categories</a></p>
          </div>
        </section>
      );
    }

    const allProducts = window.NAJMAT_DATA.products.filter(p => p.category === cat.slug);
    const filtered = subSlug
      ? allProducts.filter(p => p.subcategory === subSlug)
      : allProducts;
    const visible = filtered.slice(0, shown);
    const subcat = subSlug && cat.subcategories
      ? cat.subcategories.find(s => s.slug === subSlug)
      : null;

    return (
      <>
        <section className="cat-title">
          <div className="rail cat-title-inner">
            <nav className="cat-breadcrumb" aria-label="Breadcrumb">
              <a href="#/">home</a> <span>›</span>
              {subcat ? (
                <>
                  <a href={`#/c/${cat.slug}`}>{cat.name}</a> <span>›</span> <span>{subcat.name}</span>
                </>
              ) : (
                <span>{cat.name}</span>
              )}
            </nav>
            <h1 className="cat-title-h">
              {subcat ? subcat.name : cat.name}
              <span className="cat-title-count tnum"> · {filtered.length.toLocaleString()} products</span>
            </h1>
            <div className="cat-title-meta label-mono">
              {subcat
                ? <>{cat.name} · subcategory</>
                : <>category {cat.n} of {window.NAJMAT_DATA.categoryCount}</>}
            </div>
          </div>
        </section>

        {!cat.enriched ? (
          <section className="cat-empty" aria-label={`${cat.name} cataloguing notice`}>
            <div className="rail">
              <window.EmptyState categoryName={cat.name} />
            </div>
          </section>
        ) : (
          <>
            {/* Subcategory tiles — show only on category landing, not on sub pages */}
            {!subSlug && cat.subcategories && cat.subcategories.length > 1 && (
              <section className="subcat-strip" aria-label={`${cat.name} subcategories`}>
                <div className="rail">
                  <div className="label-mono subcat-strip-h">Browse by type</div>
                  <ul className="subcat-grid" role="list">
                    {cat.subcategories.map(s => {
                      const subCount = allProducts.filter(p => p.subcategory === s.slug).length;
                      return (
                        <li key={s.slug} className="subcat-tile-li">
                          <a className="subcat-tile" href={`#/c/${cat.slug}/${s.slug}`}>
                            <span className="subcat-tile-name">{s.name}</span>
                            <span className="subcat-tile-count tnum">{subCount.toLocaleString()}</span>
                          </a>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </section>
            )}

            <section className="cat-list" aria-label={`${cat.name} listing`}>
              <div className="rail">
                <div className="product-grid">
                  {visible.map(p => (
                    <window.ProductCard key={p.sku} product={p} />
                  ))}
                </div>
                {filtered.length > shown && (
                  <div className="cat-load-more">
                    <button
                      type="button"
                      className="cat-load-more-btn"
                      onClick={() => setShown(s => Math.min(s + PAGE_SIZE, filtered.length))}
                    >
                      Show more
                      <span className="label-mono cat-load-more-meta">
                        ({(filtered.length - shown).toLocaleString()} remaining)
                      </span>
                    </button>
                  </div>
                )}
              </div>
            </section>
          </>
        )}
      </>
    );
  };
})();
