/* Category landing pages: summary, product grid, selection guide, look comparison, spec table, FAQ */

function uniq(arr) { return arr.filter((v, i) => arr.indexOf(v) === i); }
function sortSizes(a) { return a.slice().sort((x, y) => parseFloat(x) - parseFloat(y) || x.localeCompare(y)); }

function CategoryTabs({ current }) {
  const { t, route } = useApp();
  const S = window.SEO_CONTENT[route.lang];
  return (
    <nav className="cat-tabs" aria-label={t("cats.eyebrow")}>
      <a href={hrefFor(route.lang, "products")} aria-current={!current ? "page" : undefined}>{t("cg.all")}</a>
      {window.CATEGORIES.map(c => (
        <a key={c.id} href={hrefFor(route.lang, "category", c.id)} aria-current={current === c.id ? "page" : undefined}>{S.cats[c.id].h1}</a>
      ))}
    </nav>
  );
}

function CategoryPage() {
  const { t, route } = useApp();
  const id = route.slug;
  const S = window.SEO_CONTENT[route.lang];
  const C = S.cats[id];
  const cat = window.CATEGORIES.find(c => c.id === id);
  const items = window.PRODUCTS.filter(p => p.cat === id);
  const looks = uniq(items.map(p => p.look));
  const sizes = sortSizes(uniq(items.map(p => p.size)));
  const surfaces = uniq(items.map(p => p.surface));
  const usages = uniq(items.flatMap(p => p.usage));
  const matchCount = f => items.filter(p => Object.keys(f).every(k => k === "usage" ? p.usage.includes(f[k]) : p[k] === f[k])).length;

  return (
    <>
      <header className="cg-hero">
        <div className="wrap cg-hero-in">
          <div>
            <Crumbs />
            <h1 className="h-display" style={{ fontSize: "clamp(40px,5vw,72px)" }}>{C.h1}</h1>
            <p className="lead" style={{ marginTop: 20 }}>{C.intro}</p>
            <div className="btn-row" style={{ marginTop: 28 }}>
              <a className="btn btn-primary" href="#cg-grid" onClick={e => { e.preventDefault(); const el = document.getElementById("cg-grid"); el && window.scrollTo({ top: el.getBoundingClientRect().top + scrollY - 90, behavior: "smooth" }); }}>{t("cg.grid")} ({items.length})</a>
              <a className="btn btn-ghost" href={hrefFor(route.lang, "quote")}>{t("hero.cta2")}</a>
            </div>
          </div>
          <figure className="cg-hero-img"><img src={cat.img} alt="" /><span className="caption">{t("hero.caption")}</span></figure>
        </div>
      </header>

      {/* Quick, machine-readable summary */}
      <section className="wrap cg-sum" aria-labelledby="cg-sum-h">
        <h2 id="cg-sum-h" className="eyebrow">{t("cg.summary")}</h2>
        <dl>
          <div><dt>{t("cg.s.count")}</dt><dd>{items.length}</dd></div>
          <div><dt>{t("cg.s.looks")}</dt><dd>{looks.map(l => t("v." + l)).join(", ")}</dd></div>
          <div><dt>{t("cg.s.sizes")}</dt><dd>{sizes.join(" · ")}</dd></div>
          <div><dt>{t("cg.s.surfaces")}</dt><dd>{surfaces.map(s => t("v." + s)).join(", ")}</dd></div>
          <div><dt>{t("cg.s.usage")}</dt><dd>{usages.map(u => t("v." + u)).join(", ")}</dd></div>
        </dl>
      </section>

      <section id="cg-grid" className="wrap" style={{ paddingTop: 48, paddingBottom: 88 }} aria-labelledby="cg-grid-h">
        <div className="sec-head" style={{ marginBottom: 24 }}>
          <h2 id="cg-grid-h" className="h-2">{t("cg.grid")}</h2>
          <a className="link" href={hrefFor(route.lang, "products", null, "category=" + id)}>{Ico.filter()} {t("cg.inCatalog")}</a>
        </div>
        <CategoryTabs current={id} />
        <div className="grid" style={{ marginTop: 28 }}>{items.map(p => <ProductCard key={p.id} p={p} />)}</div>
        <p className="ref-note">{t("cg.demo")}</p>
      </section>

      {/* Selection guide */}
      <section className="sec sec-stone" aria-labelledby="cg-guide-h">
        <div className="wrap">
          <div className="sec-head">
            <div><p className="eyebrow">{C.h1}</p><h2 id="cg-guide-h" className="h-1" style={{ marginTop: 16 }}>{t("cg.guide")}</h2></div>
            <p className="muted" style={{ maxWidth: 46 + "ch" }}>{t("cg.guide.sub")}</p>
          </div>
          <ol className="guide">
            {C.guide.map((g, i) => {
              const k = Object.keys(g.f)[0];
              const qk = k === "look" ? "look" : k;
              return (
                <li key={i} className="guide-item">
                  <span className="step-n">0{i + 1}</span>
                  <h3>{g.t}</h3>
                  <p>{g.d}</p>
                  <a className="link" href={hrefFor(route.lang, "products", null, `category=${id}&${qk}=${g.f[k]}`)}>
                    {t("cg.guide.see")} ({matchCount(g.f)}) {Ico.arrow(14)}
                  </a>
                </li>
              );
            })}
          </ol>
        </div>
      </section>

      {/* Look comparison */}
      <section className="sec" aria-labelledby="cg-cmp-h">
        <div className="wrap">
          <div className="sec-head">
            <div><h2 id="cg-cmp-h" className="h-1">{t("cg.cmp")}</h2><p className="muted" style={{ marginTop: 12 }}>{t("cg.cmp.sub")}</p></div>
          </div>
          <div className="tbl-wrap" role="region" aria-label={t("cg.cmp")} tabIndex={0}>
            <table className="tbl tbl-cmp">
              <thead>
                <tr><th scope="col"><span className="sr-only">—</span></th>{looks.map(l => {
                  const ex = items.find(p => p.look === l);
                  return <th key={l} scope="col"><img src={ex.img[0]} alt="" /><span>{t("v." + l)}</span></th>;
                })}</tr>
              </thead>
              <tbody>
                <tr><th scope="row">{t("cg.row.char")}</th>{looks.map(l => <td key={l}>{S.look[l]}</td>)}</tr>
                <tr><th scope="row">{t("cg.row.usage")}</th>{looks.map(l => <td key={l}>{uniq(items.filter(p => p.look === l).flatMap(p => p.usage)).map(u => t("v." + u)).join(", ")}</td>)}</tr>
                <tr><th scope="row">{t("cg.row.sizes")}</th>{looks.map(l => <td key={l}>{sortSizes(uniq(items.filter(p => p.look === l).map(p => p.size))).join(" · ")}</td>)}</tr>
                <tr><th scope="row">{t("cg.row.surfaces")}</th>{looks.map(l => <td key={l}>{uniq(items.filter(p => p.look === l).map(p => p.surface)).map(s => t("v." + s)).join(", ")}</td>)}</tr>
                <tr><th scope="row">{t("cg.row.types")}</th>{looks.map(l => <td key={l}>{uniq(items.filter(p => p.look === l && p.type).map(p => p.type)).map(x => t("pt." + x)).join(", ")}</td>)}</tr>
                <tr><th scope="row">{t("cg.row.products")}</th>{looks.map(l => <td key={l}>{items.filter(p => p.look === l).map((p, i, a) => <React.Fragment key={p.id}><a href={hrefFor(route.lang, "product", p.id)}>{p.name}</a>{i < a.length - 1 ? ", " : ""}</React.Fragment>)}</td>)}</tr>
              </tbody>
            </table>
          </div>
          <p className="tbl-hint">{t("cg.hint")} →</p>

          {/* Full spec table */}
          <h2 className="h-2" style={{ marginTop: 72 }}>{t("cg.table")}</h2>
          <p className="muted" style={{ margin: "10px 0 22px" }}>{t("cg.table.sub")}</p>
          <div className="tbl-wrap" role="region" aria-label={t("cg.table")} tabIndex={0}>
            <table className="tbl tbl-spec">
              <thead><tr>
                <th scope="col">{t("pdq.product")}</th><th scope="col">{t("d.code")}</th><th scope="col">{t("d.size")}</th>
                <th scope="col">{t("d.type")}</th><th scope="col">{t("d.look")}</th><th scope="col">{t("d.surface")}</th>
                <th scope="col">{t("d.color")}</th><th scope="col">{t("d.usage")}</th><th scope="col">{t("d.badges")}</th>
              </tr></thead>
              <tbody>
                {items.map(p => (
                  <tr key={p.id}>
                    <th scope="row"><a href={hrefFor(route.lang, "product", p.id)} className="tbl-prod"><img src={p.img[0]} alt="" />{p.name}</a></th>
                    <td className="mono">{p.code}</td><td>{p.size} cm</td><td>{p.type ? t("pt." + p.type) : "—"}</td>
                    <td>{t("v." + p.look)}</td><td>{t("v." + p.surface)}</td>
                    <td><span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}><span className="sw" style={{ background: SWATCH[p.color] }} />{t("v." + p.color)}</span></td>
                    <td>{p.usage.map(u => t("v." + u)).join(", ")}</td>
                    <td>{p.badges && p.badges.length ? p.badges.map(b => t("b." + b)).join(", ") : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="ref-note">{t("cg.demo")} {t("d.unverified")}</p>
        </div>
      </section>

      {/* FAQ */}
      <section className="sec sec-stone" aria-labelledby="cg-faq-h">
        <div className="wrap faq">
          <div>
            <p className="eyebrow">{t("faq.eyebrow")}</p>
            <h2 id="cg-faq-h" className="h-1" style={{ marginTop: 16 }}>{t("cg.faq", { cat: C.h1 })}</h2>
          </div>
          <FaqList items={faqsFor(route)} />
        </div>
      </section>

      {/* Other categories */}
      <section className="sec-tight" aria-labelledby="cg-oth-h">
        <div className="wrap">
          <h2 id="cg-oth-h" className="h-3" style={{ marginBottom: 18 }}>{t("cg.other")}</h2>
          <div className="cg-others">
            {window.CATEGORIES.filter(c => c.id !== id).map(c => (
              <a key={c.id} className="mini cg-mini" href={hrefFor(route.lang, "category", c.id)}>
                <img src={c.img} alt="" loading="lazy" />
                <span><b>{S.cats[c.id].h1}</b><span>{t("cat." + c.id + ".d")}</span></span>
              </a>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

/* Product detail additions: comparison table with similar products + product FAQ */
function ProductCompare({ p, similar }) {
  const { t, route } = useApp();
  const cols = [p, ...similar.slice(0, 3)];
  const rows = [
    ["d.size", x => x.size + " cm"],
    ["d.type", x => (x.type ? t("pt." + x.type) : "—")],
    ["d.look", x => t("v." + x.look)],
    ["d.surface", x => t("v." + x.surface)],
    ["d.color", x => t("v." + x.color)],
    ["d.usage", x => x.usage.map(u => t("v." + u)).join(", ")],
    ["d.badges", x => (x.badges && x.badges.length ? x.badges.map(b => t("b." + b)).join(", ") : "—")]
  ];
  return (
    <section className="sec-tight" aria-labelledby="pd-cmp-h">
      <div className="wrap">
        <h2 id="pd-cmp-h" className="h-2">{t("pdq.cmp")}</h2>
        <p className="muted" style={{ margin: "10px 0 24px" }}>{t("pdq.cmp.sub")}</p>
        <div className="tbl-wrap" role="region" aria-label={t("pdq.cmp")} tabIndex={0}>
          <table className="tbl tbl-cmp tbl-pd">
            <thead>
              <tr>
                <th scope="col"><span className="sr-only">—</span></th>
                {cols.map((x, i) => (
                  <th key={x.id} scope="col" className={i === 0 ? "is-this" : ""}>
                    <img src={x.img[0]} alt="" />
                    {i === 0 ? <span className="this-lbl">{t("pdq.this")}</span> : null}
                    {i === 0 ? <span>{x.name}</span> : <a href={hrefFor(route.lang, "product", x.id)}>{x.name}</a>}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map(([k, fn]) => {
                const vals = cols.map(fn);
                return (
                  <tr key={k}>
                    <th scope="row">{t(k)}</th>
                    {vals.map((v, i) => <td key={i} className={(i === 0 ? "is-this " : "") + (i > 0 && v === vals[0] ? "same" : "")}>{v}</td>)}
                  </tr>
                );
              })}
              <tr>
                <th scope="row"><span className="sr-only">{t("card.add")}</span></th>
                {cols.map((x, i) => <td key={x.id} className={i === 0 ? "is-this" : ""}><AddButton product={x} className="btn-sm" /></td>)}
              </tr>
            </tbody>
          </table>
        </div>
        <p className="tbl-hint">{t("cg.hint")} →</p>
      </div>
    </section>
  );
}

function ProductFaq({ p }) {
  const { t, route } = useApp();
  return (
    <section className="sec-tight" aria-labelledby="pd-faq-h" style={{ borderTop: "1px solid var(--line-soft)" }}>
      <div className="wrap faq">
        <div>
          <p className="eyebrow">{t("faq.eyebrow")}</p>
          <h2 id="pd-faq-h" className="h-2" style={{ marginTop: 16 }}>{t("pdq.faq", { name: p.name })}</h2>
          <p className="muted" style={{ marginTop: 16 }}>
            <a href={hrefFor(route.lang, "category", p.cat)}>{window.SEO_CONTENT[route.lang].cats[p.cat].h1}</a> — {t("cg.guide")}
          </p>
        </div>
        <FaqList items={faqsFor(route)} />
      </div>
    </section>
  );
}

Object.assign(window, { CategoryPage, CategoryTabs, ProductCompare, ProductFaq });
