// Product detail page — with consumption calculator, add-to-quote, share

function ProductPage({ slug }) {
  useLang();
  const product = PRODUCTS.find(p => p.slug === slug);
  const [area, setArea] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  const [lb, setLb] = React.useState(null);
  const quote = useQuote();

  // Decap can save list-of-image items either as bare strings or
  // as { url: "..." } objects; normalise to strings here.
  const gallery = React.useMemo(
    () => (product?.gallery || [])
      .map(g => typeof g === "string" ? g : g?.url || "")
      .filter(Boolean),
    [product?.gallery]
  );

  React.useEffect(() => { setLb(null); }, [slug]);
  React.useEffect(() => {
    if (lb === null) return;
    const onKey = (e) => {
      if (e.key === "Escape") setLb(null);
      if (e.key === "ArrowLeft") setLb(i => i === null ? null : (i - 1 + gallery.length) % gallery.length);
      if (e.key === "ArrowRight") setLb(i => i === null ? null : (i + 1) % gallery.length);
    };
    window.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [lb, gallery.length]);

  if (!product) {
    return (
      <main className="page-404">
        <h1>{t("notFound.product.title")}</h1>
        <Link to="/catalog" className="btn btn-primary">{t("notFound.product.back")}</Link>
      </main>
    );
  }

  const idx = PRODUCTS.findIndex(p => p.slug === slug);
  const next = PRODUCTS[(idx + 1) % PRODUCTS.length];
  const prev = PRODUCTS[(idx - 1 + PRODUCTS.length) % PRODUCTS.length];

  // Related: same effect primary tag, fallback to category
  const primary = (product.effect || "").split("·")[0].trim().toLowerCase();
  const related = PRODUCTS.filter(p => p.slug !== product.slug && (p.effect || "").toLowerCase().includes(primary)).slice(0, 3);
  const relatedFallback = related.length > 0 ? related :
    PRODUCTS.filter(p => p.category === product.category && p.slug !== product.slug).slice(0, 3);

  const calc = calcConsumption(product, Number(area));
  const cRange = parseConsumption(product.consumption);
  const inQuote = quote.has(product.slug);

  const specs = [
    { label: t("product.specs.binder"), value: product.binder },
    { label: t("product.specs.consumption"), value: product.consumption },
    { label: t("product.specs.drying"), value: product.drying },
    { label: t("product.specs.layers"), value: product.layers },
    { label: t("product.specs.tools"), value: product.tools },
    { label: t("product.specs.application"), value: product.category === "both" ? t("product.application.both") : product.category === "interior" ? t("product.application.interior") : t("product.application.exterior") },
  ];

  const safety = [
    { icon: "🍃", title: t("product.safety.eco.title"), desc: t("product.safety.eco.desc") },
    { icon: "🔥", title: t("product.safety.fire.title"), desc: t("product.safety.fire.desc") },
    { icon: "❄", title: t("product.safety.temp.title"), desc: t("product.safety.temp.desc") },
    { icon: "💧", title: t("product.safety.moisture.title"), desc: t("product.safety.moisture.desc") }
  ];

  const addToQuote = () => {
    quote.toggle(product.slug, Number(area) || 0);
  };

  const shareLink = async () => {
    const url = `${location.origin}${location.pathname}#/product/${product.slug}`;
    try {
      if (navigator.share) {
        await navigator.share({ title: `${product.name} — Artifex De Color`, url });
      } else {
        await navigator.clipboard.writeText(url);
        setCopied(true);
        setTimeout(() => setCopied(false), 1800);
      }
    } catch {
      // user cancelled or permission denied; ignore
    }
  };

  return (
    <main className="product">
      <div className="product-breadcrumbs">
        <Link to="/">{t("product.crumbs.home")}</Link> / <Link to="/catalog">{t("product.crumbs.catalog")}</Link> / <span>{product.name}</span>
      </div>

      <section className="product-hero">
        <div className="product-info">
          <div className="eyebrow">{product.effect}</div>
          <h1 className="product-title">{product.name}</h1>
          <p className="product-tagline">{product.tagline}</p>
          <p className="product-desc">{product.desc}</p>
          <div className="product-story">
            <div className="story-mark">❝</div>
            <p>{product.story}</p>
          </div>

          {/* Consumption calculator */}
          {cRange && (
            <div className="product-calc">
              <div className="product-calc-head">
                <div className="eyebrow">{t("product.calc.eyebrow")}</div>
                <span className="product-calc-rate">{cRange.min}–{cRange.max} {cRange.unit}/m²</span>
              </div>
              <div className="product-calc-row">
                <label>
                  <span>{t("product.calc.area")}</span>
                  <div className="product-calc-input">
                    <input
                      type="number"
                      min="0"
                      step="0.5"
                      value={area}
                      onChange={e => setArea(e.target.value)}
                      placeholder="0"
                    />
                    <span>m²</span>
                  </div>
                </label>
                <div className="product-calc-result">
                  {calc ? (
                    <>
                      <div className="product-calc-result-label">{t("product.calc.resultLabel")}</div>
                      <div className="product-calc-result-value">{calc.minText} – {calc.maxText}</div>
                      <div className="product-calc-result-hint">{t("product.calc.resultHint")}</div>
                    </>
                  ) : (
                    <div className="product-calc-result-empty">{t("product.calc.empty")}</div>
                  )}
                </div>
              </div>
            </div>
          )}

          <div className="product-ctas">
            <button className={`btn btn-primary ${inQuote ? "btn-in-quote" : ""}`} onClick={addToQuote}>
              {inQuote ? t("product.cta.inQuote") : t("product.cta.add")}
            </button>
            <Link to="/contacts" className="btn btn-ghost">{t("product.cta.contact")}</Link>
            <button className="btn-icon" onClick={shareLink} aria-label={t("product.cta.shareAria")}>
              {copied ? t("product.cta.copied") : t("product.cta.share")}
            </button>
          </div>
        </div>
        <div className="product-visual">
          <div className="pv-main">
            {product.cover ? (
              <img
                className="pv-cover"
                src={product.cover}
                alt={product.name}
                loading="eager"
                onError={e => { e.currentTarget.style.display = "none"; }}
              />
            ) : (
              <Swatch product={product}/>
            )}
          </div>
        </div>
      </section>

      <section className="product-specs">
        <div className="eyebrow">{t("product.specs.eyebrow")}</div>
        <div className="specs-grid">
          {specs.map(s => (
            <div key={s.label} className="spec">
              <div className="spec-label">{s.label}</div>
              <div className="spec-value">{s.value}</div>
            </div>
          ))}
        </div>
      </section>

      <section className="product-safety">
        <div className="eyebrow">{t("product.safety.eyebrow")}</div>
        <div className="safety-grid">
          {safety.map(s => (
            <div key={s.title} className="safety-card">
              <div className="safety-icon">{s.icon}</div>
              <h4>{s.title}</h4>
              <p>{s.desc}</p>
            </div>
          ))}
        </div>
      </section>

      {gallery.length > 0 && (
        <section className="product-gallery">
          <div className="product-gallery-head">
            <div className="eyebrow">{t("product.gallery.eyebrow")}</div>
            <h2 className="section-title">{t("product.gallery.title")}</h2>
          </div>
          <div className="product-gallery-grid">
            {gallery.map((src, i) => (
              <button
                key={src + i}
                type="button"
                className="product-gallery-tile"
                onClick={() => setLb(i)}
                aria-label={`${t("product.gallery.open")} ${i + 1}/${gallery.length}`}>
                <img src={src} alt="" loading="lazy"
                  onError={e => { e.currentTarget.parentElement.style.display = "none"; }}/>
                <span className="product-gallery-zoom" aria-hidden="true">⤢</span>
              </button>
            ))}
          </div>
        </section>
      )}

      {lb !== null && gallery[lb] && (
        <div className="product-lightbox" onClick={() => setLb(null)} role="dialog" aria-modal="true">
          <button type="button" className="plb-close" onClick={() => setLb(null)} aria-label={t("product.gallery.close")}>×</button>
          {gallery.length > 1 && (
            <button type="button" className="plb-nav plb-prev"
              onClick={e => { e.stopPropagation(); setLb(i => (i - 1 + gallery.length) % gallery.length); }}
              aria-label={t("product.gallery.prev")}>‹</button>
          )}
          <img
            className="plb-img"
            src={gallery[lb]}
            alt=""
            onClick={e => e.stopPropagation()}
          />
          {gallery.length > 1 && (
            <button type="button" className="plb-nav plb-next"
              onClick={e => { e.stopPropagation(); setLb(i => (i + 1) % gallery.length); }}
              aria-label={t("product.gallery.next")}>›</button>
          )}
          <div className="plb-counter" onClick={e => e.stopPropagation()}>
            {lb + 1} / {gallery.length}
          </div>
        </div>
      )}

      <section className="product-nav">
        <Link to={`/product/${prev.slug}`} className="pnav-card pnav-prev">
          <div className="pnav-label">{t("product.nav.prev")}</div>
          <div className="pnav-name">{prev.name}</div>
          <div className="pnav-effect">{prev.effect}</div>
        </Link>
        <Link to={`/product/${next.slug}`} className="pnav-card pnav-next">
          <div className="pnav-label">{t("product.nav.next")}</div>
          <div className="pnav-name">{next.name}</div>
          <div className="pnav-effect">{next.effect}</div>
        </Link>
      </section>

      {relatedFallback.length > 0 && (
        <section className="section">
          <div className="section-head">
            <h2 className="section-title">{t("product.related")}</h2>
            <Link to="/catalog" className="link-arrow">{t("home.fullCatalog")}</Link>
          </div>
          <div className="products-row">
            {relatedFallback.map(p => (
              <Link key={p.slug} to={`/product/${p.slug}`} className="product-small">
                <div className="ps-swatch"><ProductCoverOrSwatch product={p}/></div>
                <div className="ps-name">{p.name}</div>
                <div className="ps-effect">{p.effect}</div>
              </Link>
            ))}
          </div>
        </section>
      )}
    </main>
  );
}

window.ProductPage = ProductPage;
