// Furnishfy — Product detail page
function Product({ go, productId, lang }) {
  const { PRODUCTS, CATEGORIES } = window.FURN;
  const p = PRODUCTS.find((x) => x.id === productId) || PRODUCTS[0];
  const [active, setActive] = useState(0);
  useReveal();
  useEffect(() => { setActive(0); window.scrollTo(0, 0); }, [productId]);

  const cat = CATEGORIES.find((c) => c.id === p.cat) || { en: "Collection", ar: "مجموعة" };
  const related = PRODUCTS.filter((x) => x.cat === p.cat && x.id !== p.id).slice(0, 4);
  const fill = related.length < 4 ? PRODUCTS.filter((x) => x.id !== p.id && !related.includes(x)).slice(0, 4 - related.length) : [];
  const relatedAll = [...related, ...fill];

  // Build gallery from real images first, fallback to hue placeholders
  const realImgs = (p.images && p.images.length > 0)
    ? p.images
    : (p.thumbnail && !p.thumbnail.includes('no-product') ? [{ url: p.thumbnail }] : []);
  const hueGallery = [p.hue, (p.hue + 20) % 360, (p.hue + 340) % 360, (p.hue + 40) % 360];
  const hasRealImgs = realImgs.length > 0;

  const specs = [
    { label: lang === "ar" ? "الخامة" : "Material", value: lang === "ar" ? (p.material?.ar || "") : (p.material?.en || "") },
    { label: lang === "ar" ? "اللون" : "Finish", value: lang === "ar" ? (p.color?.ar || "") : (p.color?.en || "") },
    { label: lang === "ar" ? "مدة التوصيل" : "Lead time", value: lang === "ar" ? "6–8 أسابيع" : "6–8 weeks" },
    { label: lang === "ar" ? "المنشأ" : "Origin", value: lang === "ar" ? "صنع يدويًا عند الطلب" : "Handmade to order" },
  ];

  const name = lang === "ar" ? p.ar : p.en;
  const description = lang === "ar" ? (p.descAr || p.descEn) : (p.descEn || p.descAr);

  return (
    <main className="page-fade" style={{ paddingTop: 92 }}>
      {/* breadcrumb */}
      <div className="wrap" style={{ padding: "30px 40px 0", display: "flex", gap: 10, alignItems: "center", color: "var(--faint)", fontSize: 12.5, letterSpacing: ".08em" }}>
        <span onClick={() => go("home")} style={{ cursor: "pointer" }} className="bc">{lang === "ar" ? "الرئيسية" : "Home"}</span>
        <span>/</span>
        <span onClick={() => go("shop", null, p.cat)} style={{ cursor: "pointer" }} className="bc">{lang === "ar" ? cat.ar : cat.en}</span>
        <span>/</span>
        <span style={{ color: "var(--muted)" }}>{name}</span>
      </div>

      <section className="wrap pdp-grid" style={{ padding: "30px 40px 90px", display: "grid", gridTemplateColumns: "1.15fr 1fr", gap: 64, alignItems: "start" }}>
        {/* gallery */}
        <div style={{ position: "sticky", top: 100 }} className="pdp-gallery">
          {/* Main image */}
          {hasRealImgs
            ? <img
              src={realImgs[active]?.url || realImgs[0]?.url}
              alt={name}
              style={{ width: "100%", height: "100%", aspectRatio: "1/1", objectFit: "cover", borderRadius: var_radius2(), border: "1px solid var(--line)", display: "block" }}
            />
            : <Placeholder hue={hueGallery[active]} name={name} label={p.cat} style={{ aspectRatio: "1/1", borderRadius: var_radius2(), border: "1px solid var(--line)" }} />
          }
          {/* Thumbnails */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginTop: 12 }}>
            {hasRealImgs
              ? realImgs.slice(0, 4).map((img, i) => (
                <button key={i} onClick={() => setActive(i)} style={{ border: active === i ? "1px solid var(--gold)" : "1px solid var(--line)", padding: 0, background: "none", cursor: "pointer", borderRadius: 3, overflow: "hidden" }}>
                  <img src={img.url} alt={"" + (i + 1)} style={{ width: "100%", aspectRatio: "1/1", objectFit: "cover", display: "block" }} />
                </button>
              ))
              : hueGallery.map((h, i) => (
                <button key={i} onClick={() => setActive(i)} style={{ border: active === i ? "1px solid var(--gold)" : "1px solid var(--line)", padding: 0, background: "none", cursor: "pointer", borderRadius: 3, overflow: "hidden" }}>
                  <Placeholder hue={h} label="" style={{ aspectRatio: "1/1" }} />
                </button>
              ))
            }
          </div>
        </div>

        {/* info */}
        <div>
          {p.badge && <div className="eyebrow" style={{ marginBottom: 12 }}>{lang === "ar" ? (p.badge.ar || p.badge.en) : p.badge.en}</div>}
          <h1 style={{ fontSize: "clamp(34px,4.5vw,56px)", lineHeight: 1.02 }}>{name}</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 18 }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 30, color: "var(--gold)" }}>{money(p.price)}</span>
            {p.old && <span style={{ color: "var(--faint)", fontSize: 17, textDecoration: "line-through" }}>{money(p.old)}</span>}
            <span style={{ display: "flex", alignItems: "center", gap: 8, marginInlineStart: "auto" }}><Stars n={5} size={14} /> <span style={{ color: "var(--faint)", fontSize: 12.5 }}>(48)</span></span>
          </div>

          <div style={{ color: "var(--muted)", fontSize: 16, lineHeight: 1.85, marginTop: 26 }} dangerouslySetInnerHTML={{ __html: description }} />

          {/* specs */}
          <div style={{ marginTop: 30, borderTop: "1px solid var(--line)" }}>
            {specs.map((s, i) => {
              if (!s.value) return null;
              return (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "14px 0", borderBottom: "1px solid var(--line)" }}>
                  <span style={{ color: "var(--faint)", fontSize: 13, letterSpacing: ".06em", textTransform: "uppercase" }}>{s.label}</span>
                  <span style={{ fontSize: 14.5, color: "var(--ink)" }}>{s.value}</span>
                </div>
              );
            })}
          </div>

          {/* inquiry button */}
          <div style={{ display: "flex", gap: 14, marginTop: 32, alignItems: "stretch" }}>
            <button onClick={() => go("contact")} className="btn btn--solid" style={{ flex: 1, display: "inline-flex", justifyContent: "center", alignItems: "center" }}>
              <span>{lang === "ar" ? "استفسر عن هذه القطعة" : "Inquire about this piece"}</span>
            </button>
          </div>

          {/* assurances */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 30 }}>
            {[
              ["truck", lang === "ar" ? "شحن وتركيب مجاني خلال 4 أسابيع" : "Free white-glove delivery within 4 weeks"],
              ["shield", lang === "ar" ? "ضمان هيكلي لمدة 10 سنوات" : "Backed by a 10-year structural guarantee"],
              ["leaf", lang === "ar" ? "أخشاب من غابات مدارة بمسؤولية" : "Timber from responsibly managed forests"]
            ].map((a, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--muted)", fontSize: 13.5 }}>
                <Icon name={a[0]} size={20} style={{ color: "var(--gold)", flexShrink: 0 }} stroke={1.2} /> {a[1]}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* related */}
      <section className="wrap" style={{ padding: "20px 40px 110px", borderTop: "1px solid var(--line)" }}>
        <h2 style={{ fontSize: "clamp(28px,3.5vw,44px)", margin: "56px 0 36px" }}>{lang === "ar" ? "قد يعجبك أيضاً" : "You may also like"}</h2>
        <div className="grid-4">
          {relatedAll.map((rp, i) => <ProductCard key={rp.id} p={rp} go={go} index={i} />)}
        </div>
      </section>

      <style>{`
        .bc { transition: color .25s; }
        .bc:hover { color: var(--gold); }
        @media (max-width: 860px){
          .pdp-grid { grid-template-columns: 1fr !important; gap: 36px !important; }
          .pdp-gallery { position: static !important; }
        }
      `}</style>
    </main>
  );
}
function var_radius2() { return getComputedStyle(document.documentElement).getPropertyValue("--radius") || "4px"; }
Object.assign(window, { Product });
