/* === Shared helpers for family pages === */

function FamilyHero({ family, navigate }) {
  return (
    <section className="fam-hero">
      <div className="container">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24, flexWrap: "wrap", gap: 12 }}>
          <Breadcrumb trail={[
          { label: "Sistema", route: "home" },
          { label: family.label }]
          } navigate={navigate} />
          <PageTag pages={`P. ${family.pages}`} label={`${family.num} · ${family.label}`} />
        </div>
        <div className="grid-2-narrative">
          <div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 18, marginBottom: 18 }}>
              <div style={{ fontSize: 88, fontWeight: 700, letterSpacing: "-0.03em", color: "var(--c-navy)", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{family.num}</div>
              <Eyebrow>Famiglia</Eyebrow>
            </div>
            <h1 className="h-display" style={{ fontSize: "clamp(40px, 6vw, 88px)" }}>{family.title.pre} <span className="text-accent">{family.title.accent}</span></h1>
            <HRule lg />
            <p className="lead lg" style={{ maxWidth: "52ch" }}>{family.lead}</p>
            {family.body && <p className="body" style={{ marginTop: 22 }}>{family.body}</p>}
            <div style={{ marginTop: 32 }}>
              <InfoPillRow items={family.pills} />
            </div>
            <div className="row mt-5">
              <a className="btn primary" href="https://conrad.com" target="_blank" rel="noreferrer">
                Acquista su Conrad <img src="assets/icons/external.svg" alt="" />
              </a>
              <a className="btn outline" href="https://wa.me/393668248457" target="_blank" rel="noreferrer">
                <img src="assets/icons/whatsapp.svg" alt="" /> Quotazione volumi
              </a>
            </div>
          </div>
          <div>
            <div style={{ aspectRatio: "1", background: "var(--c-tile)", overflow: "hidden", borderRadius: 8, position: "relative" }}>
              <img src={`assets/${family.img}`} alt="" style={{ width: "100%", height: "100%", objectFit: "contain", padding: 40 }} />
            </div>
            {family.gallery &&
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${family.gallery.length}, 1fr)`, gap: 8, marginTop: 8 }}>
                {family.gallery.map((g, i) =>
              <div key={i} style={{ aspectRatio: 1, background: "var(--c-tile)", overflow: "hidden", borderRadius: 6 }}>
                    <img src={`assets/${g}`} alt="" style={{ width: "100%", height: "100%", objectFit: "contain", padding: 14 }} />
                  </div>
              )}
              </div>
            }
          </div>
        </div>
      </div>
    </section>);

}

/* === DataTable: generic listino renderer === */
function DataTable({ title, eyebrow, subtitle, columns, rows, footer, highlightSku }) {
  return (
    <div style={{ marginBottom: 36 }}>
      {(title || eyebrow) &&
      <div style={{ marginBottom: 18 }}>
          {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
          {title && <h3 style={{ fontSize: 22, fontWeight: 700, marginTop: 6, letterSpacing: "-0.01em" }}>{title}</h3>}
          {subtitle && <p style={{ fontSize: 13, color: "var(--c-mute)", marginTop: 6 }}>{subtitle}</p>}
        </div>
      }
      <div className="spec-table-wrap">
        <table className="spec-table">
          <thead>
            <tr>{columns.map((c, i) => <th key={i} style={{ textAlign: c.right ? "right" : "left" }}>{c.label}</th>)}</tr>
          </thead>
          <tbody>
            {rows.map((row, ri) =>
            <tr key={ri} data-sku={row.sku} className={highlightSku && row.sku === highlightSku ? "row-highlight" : ""}>
                {columns.map((c, ci) => {
                const v = c.get ? c.get(row) : row[c.key];
                return <td key={ci} className={c.cls || ""} style={{ textAlign: c.right ? "right" : "left" }}>{v || <span style={{ color: "var(--c-mute)" }}>—</span>}</td>;
              })}
              </tr>
            )}
          </tbody>
        </table>
      </div>
      {footer && <p style={{ marginTop: 14, fontSize: 12, color: "var(--c-mute)" }}>{footer}</p>}
    </div>);

}

/* === GroupedTable: rows grouped by a key === */
function GroupedTable({ title, eyebrow, subtitle, columns, groups, footer, highlightSku }) {
  return (
    <div style={{ marginBottom: 36 }}>
      {(title || eyebrow) &&
      <div style={{ marginBottom: 18 }}>
          {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
          {title && <h3 style={{ fontSize: 22, fontWeight: 700, marginTop: 6, letterSpacing: "-0.01em" }}>{title}</h3>}
          {subtitle && <p style={{ fontSize: 13, color: "var(--c-mute)", marginTop: 6 }}>{subtitle}</p>}
        </div>
      }
      <div className="spec-table-wrap">
        <table className="spec-table">
          <thead>
            <tr>{columns.map((c, i) => <th key={i} style={{ textAlign: c.right ? "right" : "left" }}>{c.label}</th>)}</tr>
          </thead>
          <tbody>
            {groups.map((g, gi) =>
            <React.Fragment key={gi}>
                <tr className="section-row">
                  <td colSpan={columns.length}>{g.label}</td>
                </tr>
                {g.rows.map((row, ri) =>
              <tr key={ri} data-sku={row.sku} className={highlightSku && row.sku === highlightSku ? "row-highlight" : ""}>
                    {columns.map((c, ci) => {
                  const v = c.get ? c.get(row) : row[c.key];
                  return <td key={ci} className={c.cls || ""} style={{ textAlign: c.right ? "right" : "left" }}>{v || <span style={{ color: "var(--c-mute)" }}>—</span>}</td>;
                })}
                  </tr>
              )}
              </React.Fragment>
            )}
          </tbody>
        </table>
      </div>
      {footer && <p style={{ marginTop: 14, fontSize: 12, color: "var(--c-mute)" }}>{footer}</p>}
    </div>);

}

const DISCLAIMER = "Attenzione: non originale Cembre/Brady/Murrplastik, compatibile con i loro sistemi (rif. C. Cass. Pen. Sez. V 5957/2012).";

function FamilyCallout({ navigate }) {
  return (
    <section className="section tile">
      <div className="container">
        <div className="grid-2-narrative">
          <div>
            <Eyebrow>Acquista — <span className="accent">su Conrad</span></Eyebrow>
            <h2 className="h1" style={{ marginTop: 14 }}>Stesse quantità, <span className="text-light">stessi codici.</span></h2>
            <HRule />
            <p className="lead">Tutti i prodotti a listino sono disponibili sullo shop Conrad con le stesse confezioni e quantità che vedi in tabella. Fatturazione UE, spedizione 24/48h. Per accordi commerciali e quotazioni dedicate, contattaci direttamente.</p>
            <div className="row mt-5">
              <a className="btn primary" href="https://conrad.com" target="_blank" rel="noreferrer">Vai allo shop Conrad <img src="assets/icons/external.svg" alt="" /></a>
              <a className="btn outline" href="https://wa.me/393668248457" target="_blank" rel="noreferrer"><img src="assets/icons/whatsapp.svg" alt="" /> WhatsApp</a>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            <img src="assets/factory/fab_11.jpeg" alt="" style={{ aspectRatio: 1, objectFit: "cover", borderRadius: 6 }} />
            <img src="assets/factory/fab_07.JPG" alt="" style={{ aspectRatio: 1, objectFit: "cover", borderRadius: 6 }} />
          </div>
        </div>
      </div>
    </section>);

}

/* Filter helper for products data */
function getProducts(predicate) {
  const all = window.PRODUCTS_DATA || [];
  return all.filter(predicate);
}

/* Scroll to highlighted SKU and apply flash animation */
function useHighlightScroll(highlightSku) {
  React.useEffect(() => {
    if (!highlightSku) return;
    let cancelled = false;
    const attempt = (tries = 0) => {
      if (cancelled) return;
      const el = document.querySelector(`tr[data-sku="${highlightSku}"]`);
      if (el) {
        const top = el.getBoundingClientRect().top + window.scrollY - 200;
        window.scrollTo({ top, behavior: 'smooth' });
      } else if (tries < 20) {
        setTimeout(() => attempt(tries + 1), 100);
      }
    };
    setTimeout(() => attempt(), 250);
    return () => {cancelled = true;};
  }, [highlightSku]);
}

Object.assign(window, { FamilyHero, DataTable, GroupedTable, FamilyCallout, getProducts, DISCLAIMER, useHighlightScroll });