const ProductPage = ({ product, setPage, onAddToCart, lang }) => {
  const [selectedColor, setSelectedColor] = React.useState(product?.colors?.[0] || null);
  const [mainImg, setMainImg] = React.useState(null);
  const [selectedSize, setSelectedSize] = React.useState(product?.sizes?.[0] || null);
  const [variantName, setVariantName] = React.useState(product?.variants?.[0]?.name || null);
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);
  const [reviews,     setReviews]     = React.useState([]);
  const [reviewStats, setReviewStats] = React.useState({ total:0, avg:0 });
  const [canReview,   setCanReview]   = React.useState(false);
  const [alreadyReviewed, setAlreadyReviewed] = React.useState(false);
  const [myRating,    setMyRating]    = React.useState(5);
  const [myReview,    setMyReview]    = React.useState("");
  const [submitting,  setSubmitting]  = React.useState(false);
  const [reviewMsg,   setReviewMsg]   = React.useState("");
  const t = (en, id) => lang === "id" ? id : en;

  React.useEffect(() => {
    setSelectedColor(null);          // jangan paksa pilih warna saat load
    setSelectedSize(product?.sizes?.[0] || null);
    const _vs = Array.isArray(product?.variants) ? product.variants : [];
    // Default varian = yang termurah biar harga awal = "mulai dari"; cover foto TIDAK ikut warna
    let _cheap = null;
    _vs.forEach(v => { if (!_cheap || (v.price || 0) < (_cheap.price || 0)) _cheap = v; });
    setVariantName(_cheap ? _cheap.name : null);
    // Cover awal = foto utama produk (pilihan admin), BUKAN foto warna. Ganti hanya saat user klik warna.
    setMainImg(
      (product?.images && product.images[0]) ||
      product?.image ||
      (_cheap && _cheap.image) || null
    );
    setQty(1); setAdded(false);
    window.scrollTo({ top: 0, behavior: "smooth" });
    if (product?.id && typeof fbq === 'function') {
      fbq('track', 'ViewContent', {
        content_ids:      [String(product.id)],
        content_name:     product.name,
        content_category: product.category || '',
        content_type:     'product',
        value:            product.price,
        currency:         'IDR'
      });
    }
    // Load reviews
    if (product?.id) {
      fetch("api/reviews.php?product_id=" + product.id, { credentials:"include" })
        .then(r => r.json())
        .then(d => {
          setReviews(d.reviews || []);
          setReviewStats({ total: d.total || 0, avg: d.avg_rating || 0 });
          setCanReview(d.can_review || false);
          setAlreadyReviewed(d.already_reviewed || false);
        }).catch(() => {});
      setMyRating(5); setMyReview(""); setReviewMsg("");
    }
  }, [product]);

  const submitReview = async () => {
    if (myReview.length < 10) { setReviewMsg("❌ Ulasan minimal 10 karakter"); return; }
    setSubmitting(true);
    try {
      const res  = await fetch("api/reviews.php", { method:"POST", credentials:"include", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ product_id: product.id, rating: myRating, review: myReview }) });
      const data = await res.json();
      if (data.success) {
        setReviewMsg("✓ Ulasan berhasil dikirim!");
        setCanReview(false); setAlreadyReviewed(true);
        // Reload reviews
        fetch("api/reviews.php?product_id=" + product.id, { credentials:"include" })
          .then(r => r.json()).then(d => { setReviews(d.reviews||[]); setReviewStats({ total:d.total||0, avg:d.avg_rating||0 }); });
      } else { setReviewMsg("❌ " + (data.error||"Gagal mengirim")); }
    } catch { setReviewMsg("❌ Gagal terhubung"); }
    finally { setSubmitting(false); }
  };

  const StarRating = ({ value, onChange, size=20 }) => (
    <div style={{ display:"flex", gap:4 }}>
      {[1,2,3,4,5].map(n => (
        <span key={n} onClick={() => onChange && onChange(n)}
          style={{ fontSize:size, cursor:onChange?"pointer":"default", color: n<=value ? "#f59e0b" : "#ddd", transition:"color 0.1s" }}>★</span>
      ))}
    </div>
  );

  if (!product) return null;

  // Varian harga: tiap varian punya harga & stok sendiri
  const variants    = Array.isArray(product.variants) ? product.variants : [];
  const hasVariants = variants.length > 0;
  const curVariant  = hasVariants ? (variants.find(v => v.name === variantName) || variants[0]) : null;
  const curPrice    = curVariant ? curVariant.price : product.price;
  const curStock    = curVariant ? curVariant.stock : product.stock;
  // Kalau tiap varian punya Warna bernama sama → pemilihan cukup lewat swatch Warna,
  // sembunyikan baris Varian biar gak dobel (warna jadi "wajah", varian kasih harga/stok).
  const _colorsLower   = Array.isArray(product.colors) ? product.colors.map(c => String(c).toLowerCase().trim()) : [];
  const variantsCovered = hasVariants && variants.every(v => _colorsLower.includes(String(v.name).toLowerCase().trim()));

  // Produk berwarna WAJIB pilih warna dulu (biar keranjang selalu tau warnanya)
  const needColor = Array.isArray(product.colors) && product.colors.length > 0;
  const mustPick  = needColor && !selectedColor;

  const handleAdd = () => {
    if (mustPick) { alert(t("Please choose a color first 🙏", "Pilih warna dulu ya 🙏")); return; }
    if (curStock <= 0) return;
    onAddToCart({
      ...product,
      price: curPrice,
      stock: curStock,
      selectedColor, selectedSize,
      selectedVariant: curVariant ? curVariant.name : null,
    }, qty);
    setAdded(true);
    setTimeout(() => setAdded(false), 2000);
  };

  const related = PRODUCTS.filter(p => p.category === product.category && p.id !== product.id).slice(0, 4);

  return (
    <div style={{ paddingTop: 72, minHeight: "100vh", background: "#f9f8f6" }}>
      {/* Breadcrumb */}
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "24px 32px 0" }}>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          {[
            { label: t("Home", "Beranda"), page: "home" },
            { label: t("Products", "Produk"), page: "catalog" },
            { label: product.name, page: null }
          ].map((crumb, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span style={{ color: "#ccc", fontSize: 11 }}>/</span>}
              <span
                onClick={() => crumb.page && setPage(crumb.page)}
                style={{
                  fontFamily: "'DM Sans', sans-serif", fontSize: 11,
                  letterSpacing: "0.08em", color: crumb.page ? "#888" : "#111",
                  cursor: crumb.page ? "pointer" : "default",
                  textDecoration: crumb.page ? "underline" : "none",
                  textUnderlineOffset: 3
                }}
              >{crumb.label}</span>
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Main content */}
      <div className="lpb-product-wrap" style={{ maxWidth: 1200, margin: "0 auto", padding: "48px 32px" }}>
        <div className="lpb-product-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "start" }}>
          {/* Image Gallery */}
          <div className="lpb-product-gallery" style={{ position: "sticky", top: 100 }}>
            {(() => {
              const baseImgs = (product.images && product.images.length > 0) ? product.images : (product.image ? [product.image] : []);
              const ci = product.colorImages || {};
              const extra = [];
              Object.keys(ci).forEach(k => { const u = ci[k]; if (u && !baseImgs.includes(u) && !extra.includes(u)) extra.push(u); });
              variants.forEach(v => {
                if (!v.image) return;
                // skip kalau varian ini sudah punya Foto per Warna bernama sama (hindari foto dobel)
                const ck = Object.keys(ci).find(k => String(k).toLowerCase().trim() === String(v.name).toLowerCase().trim());
                if (ck && ci[ck]) return;
                if (!baseImgs.includes(v.image) && !extra.includes(v.image)) extra.push(v.image);
              });
              const imgs = [...baseImgs, ...extra];
              const cur  = mainImg || imgs[0];
              return (
                <>
                  {/* Main image */}
                  <div style={{ background: "#f0efed", aspectRatio: "1/1", overflow: "hidden", borderRadius: 12, marginBottom: 10 }}>
                    <img src={cur} alt={product.name}
                      style={{ width: "100%", height: "100%", objectFit: "cover", transition: "opacity 0.2s" }} />
                  </div>
                  {/* Thumbnails */}
                  {imgs.length > 1 && (
                    <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                      {imgs.map((img, i) => (
                        <div key={i} onClick={() => setMainImg(img)}
                          style={{ width: 64, height: 64, borderRadius: 8, overflow: "hidden", cursor: "pointer",
                            border: cur===img ? "2px solid #111" : "2px solid transparent",
                            opacity: cur===img ? 1 : 0.6, transition: "all 0.2s" }}>
                          <img src={img} alt={`foto ${i+1}`} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                        </div>
                      ))}
                    </div>
                  )}
                  {product.badge && (
                    <span style={{ display: "inline-block", marginTop: 12, background: "#111", color: "#f9f8f6",
                      fontFamily: "'DM Sans', sans-serif", fontSize: 9, letterSpacing: "0.15em", padding: "3px 10px" }}>
                      {product.badge}
                    </span>
                  )}
                </>
              );
            })()}
          </div>

          {/* Info */}
          <div>
            <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#999", margin: "0 0 12px" }}>
              {product.categoryLabel}
            </p>
            <h1 style={{ fontFamily: "'Cormorant Garant', serif", fontSize: "clamp(32px, 4vw, 52px)", fontWeight: 400, color: "#111", margin: "0 0 20px", lineHeight: 1.1 }}>
              {product.name}
            </h1>

            {/* Price */}
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 32 }}>
              <span style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 22, fontWeight: 500, color: "#111" }}>
                {formatPrice(curPrice)}
              </span>
              {product.originalPrice && (
                <span style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 16, color: "#bbb", textDecoration: "line-through" }}>
                  {formatPrice(product.originalPrice)}
                </span>
              )}
              {product.originalPrice && (
                <span style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 10, letterSpacing: "0.1em", background: "#111", color: "#f9f8f6", padding: "3px 8px" }}>
                  SALE
                </span>
              )}
            </div>

            {/* Trust badges — selalu tampil (social proof / kepercayaan toko baru) */}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 32 }}>
              {[
                t("Handmade", "Buatan Tangan"),
                product.isPreorder ? t("Pre-Order", "Pre-Order") : t("Ready Stock", "Ready Stock"),
                t("Ships from Bogor", "Dikirim dari Bogor"),
                t("COD available", "Bisa COD"),
              ].map((b, i) => (
                <span key={i} style={{
                  display: "inline-flex", alignItems: "center", gap: 5,
                  fontFamily: "'DM Sans', sans-serif", fontSize: 11, color: "#5a5a5a",
                  background: "#f0efed", border: "1px solid #e8e6e2", borderRadius: 999,
                  padding: "5px 12px", letterSpacing: "0.02em"
                }}>
                  <span style={{ color: "#4a9d6f", fontWeight: 700 }}>✓</span>{b}
                </span>
              ))}
            </div>

            {/* Varian Harga — disembunyikan kalau tiap varian sudah diwakili swatch Warna */}
            {hasVariants && !variantsCovered && (
              <div style={{ marginBottom: 28 }}>
                <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "#666", marginBottom: 12 }}>
                  {t("Variant", "Varian")}: <strong style={{ color: "#111", fontWeight: 500 }}>{curVariant ? curVariant.name : ""}</strong>
                </p>
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  {variants.map(v => {
                    const active = curVariant && curVariant.name === v.name;
                    const out    = (v.stock || 0) <= 0;
                    return (
                      <button
                        key={v.name}
                        onClick={() => { if (out) return; setVariantName(v.name); if (v.image) setMainImg(v.image); }}
                        disabled={out}
                        style={{
                          background: active ? "#111" : "none",
                          border: active ? "2px solid #111" : "1px solid #ddd",
                          cursor: out ? "not-allowed" : "pointer",
                          fontFamily: "'DM Sans', sans-serif",
                          textAlign: "left", padding: "8px 16px",
                          opacity: out ? 0.45 : 1,
                          transition: "all 0.15s",
                        }}
                      >
                        <span style={{ display: "block", fontSize: 12, fontWeight: 600, color: active ? "#f9f8f6" : "#111" }}>
                          {v.name}{out ? t(" (Sold out)", " (Habis)") : ""}
                        </span>
                        <span style={{ display: "block", fontSize: 11, color: active ? "#dcd2c0" : "#888", marginTop: 2 }}>
                          {formatPrice(v.price)}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* PO Notice */}
            {product.isPreorder && (
              <div style={{
                background: "#fffbeb",
                border: "1px solid #fde68a",
                borderLeft: "3px solid #f59e0b",
                padding: "14px 16px",
                marginBottom: 24,
                borderRadius: 4
              }}>
                <p style={{
                  fontFamily: "'DM Sans', sans-serif", fontSize: 11,
                  letterSpacing: "0.14em", textTransform: "uppercase",
                  fontWeight: 700, color: "#92400e", margin: "0 0 6px",
                  display: "flex", alignItems: "center", gap: 6
                }}>
                  ⏳ Pre-Order — {product.preorderDays || 14} Hari
                </p>
                <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 12, color: "#92400e", margin: 0, lineHeight: 1.6 }}>
                  {t(
                    `This product is made-to-order. It will be processed and shipped approximately ${product.preorderDays || 14} days after payment.`,
                    `Produk ini dibuat berdasarkan pesanan. Akan diproses & dikirim ±${product.preorderDays || 14} hari setelah pembayaran lunas.`
                  )}
                </p>
              </div>
            )}

            <div style={{ width: 40, height: 1, background: "#e8e6e2", marginBottom: 32 }} />

            {/* Rating */}
            {reviewStats.total > 0 && (
              <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:20, marginTop:-16 }}>
                <div style={{ display:"flex", gap:2 }}>
                  {[1,2,3,4,5].map(n => (
                    <span key={n} style={{ fontSize:15, color: n<=Math.round(reviewStats.avg)?"#f59e0b":"#ddd" }}>★</span>
                  ))}
                </div>
                <span style={{ fontSize:13, fontWeight:600, color:"#111" }}>{reviewStats.avg}</span>
                <span style={{ fontSize:12, color:"#aaa" }}>({reviewStats.total} ulasan)</span>
              </div>
            )}

            {/* Color */}
            {product.colors && (
              <div style={{ marginBottom: 28 }}>
                <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "#666", marginBottom: 12 }}>
                  {t("Color", "Warna")}: <strong style={{ color: "#111", fontWeight: 500 }}>{selectedColor || t("— Choose", "— Pilih")}</strong>
                </p>
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  {product.colors.map(c => {
                    const mvc = variants.find(v => String(v.name).toLowerCase().trim() === String(c).toLowerCase().trim());
                    const cOut = mvc ? (mvc.stock || 0) <= 0 : false;
                    const active = selectedColor === c;
                    return (
                    <button
                      key={c}
                      disabled={cOut}
                      onClick={() => {
                        if (cOut) return;
                        setSelectedColor(c);
                        // Kalau ada varian dgn nama sama → pilih juga (harga/stok ikut)
                        if (mvc) setVariantName(mvc.name);
                        // Foto: dari "Foto per Warna" ATAU foto varian yang namanya sama
                        const u = (product.colorImages||{})[c] || (mvc && mvc.image) || null;
                        if (u) setMainImg(u);
                      }}
                      style={{
                        background: "none",
                        border: active ? "2px solid #111" : "1px solid #ddd",
                        cursor: cOut ? "not-allowed" : "pointer",
                        fontFamily: "'DM Sans', sans-serif",
                        textAlign: "left",
                        opacity: cOut ? 0.45 : 1,
                        color: active ? "#111" : "#666",
                        padding: mvc ? "8px 16px" : "6px 16px",
                        transition: "all 0.15s"
                      }}
                    >
                      <span style={{ display: "block", fontSize: 11, letterSpacing: "0.08em", fontWeight: mvc ? 600 : 400 }}>
                        {c}{cOut ? t(" (Sold out)", " (Habis)") : ""}
                      </span>
                      {mvc && (
                        <span style={{ display: "block", fontSize: 10, color: active ? "#a9744f" : "#999", marginTop: 2 }}>
                          {formatPrice(mvc.price)}
                        </span>
                      )}
                    </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Size */}
            {product.sizes && (
              <div style={{ marginBottom: 28 }}>
                <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "#666", marginBottom: 12 }}>
                  {t("Size", "Ukuran")}: <strong style={{ color: "#111", fontWeight: 500 }}>{selectedSize}</strong>
                </p>
                <div style={{ display: "flex", gap: 10 }}>
                  {product.sizes.map(s => (
                    <button
                      key={s}
                      onClick={() => setSelectedSize(s)}
                      style={{
                        background: selectedSize === s ? "#111" : "none",
                        border: selectedSize === s ? "2px solid #111" : "1px solid #ddd",
                        cursor: "pointer",
                        fontFamily: "'DM Sans', sans-serif",
                        fontSize: 11, letterSpacing: "0.08em",
                        color: selectedSize === s ? "#f9f8f6" : "#666",
                        padding: "6px 20px",
                        transition: "all 0.15s"
                      }}
                    >{s}</button>
                  ))}
                </div>
              </div>
            )}

            {/* Qty */}
            <div style={{ marginBottom: 32 }}>
              <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "#666", marginBottom: 12 }}>
                {t("Quantity", "Jumlah")}
              </p>
              <div style={{ display: "flex", alignItems: "center", border: "1px solid #e8e6e2", width: "fit-content" }}>
                <button
                  onClick={() => setQty(q => Math.max(1, q - 1))}
                  style={{ background: "none", border: "none", cursor: "pointer", padding: "10px 18px", fontSize: 16, color: "#111" }}
                >−</button>
                <span style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 14, color: "#111", padding: "10px 4px", minWidth: 28, textAlign: "center" }}>
                  {qty}
                </span>
                <button
                  onClick={() => setQty(q => Math.min(curStock || 1, q + 1))}
                  style={{ background: "none", border: "none", cursor: "pointer", padding: "10px 18px", fontSize: 16, color: "#111" }}
                >+</button>
              </div>
            </div>

            {/* Urgensi stok asli — cuma tampil kalau stok beneran tinggal sedikit */}
            {curStock > 0 && curStock <= 8 && (
              <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 13, color: "#b4452f", fontWeight: 600, margin: "0 0 14px", display: "flex", alignItems: "center", gap: 6 }}>
                🔥 {t(`Only ${curStock} left — order soon`, `Sisa ${curStock} stok — buruan sebelum kehabisan`)}
              </p>
            )}

            {/* Add to cart — inline */}
            <button
              onClick={handleAdd}
              disabled={curStock <= 0 || mustPick}
              className="lpb-add-cart-btn"
              style={{
                width: "100%", padding: "18px",
                background: (curStock <= 0 || mustPick) ? "#bbb" : (added ? "#555" : "#111"),
                border: "none", cursor: (curStock <= 0 || mustPick) ? "not-allowed" : "pointer",
                fontFamily: "'DM Sans', sans-serif",
                fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
                color: "#f9f8f6", fontWeight: 600,
                transition: "background 0.2s",
                marginBottom: 12
              }}
            >
              {curStock <= 0
                ? t("Sold Out", "Stok Habis")
                : mustPick
                  ? t("Choose a Color First", "Pilih Warna Dulu")
                  : added
                    ? t("✓ Added!", "✓ Ditambahkan!")
                    : product.isPreorder
                      ? t("Pre-Order Now", "Pesan Pre-Order")
                      : t("Add to Cart", "Tambah ke Keranjang")
              }
            </button>
            <button
              onClick={() => {
                const wa = (typeof window !== "undefined" && window.LOPOBYA_WA) || "6289512645973";
                const opts = [selectedColor, selectedSize, (curVariant && curVariant.name)].filter(Boolean).join(" / ");
                const msg = t(
                  `Hi LOPOBYA, I'm interested in *${product.name}*${opts ? " (" + opts + ")" : ""} — ${formatPrice(curPrice)}. Is it available?`,
                  `Halo LOPOBYA, saya tertarik dengan *${product.name}*${opts ? " (" + opts + ")" : ""} — ${formatPrice(curPrice)}. Apakah ready?`
                );
                if (typeof fbq === "function") fbq("track", "Contact");
                window.open(`https://wa.me/${wa}?text=${encodeURIComponent(msg)}`, "_blank", "noopener,noreferrer");
              }}
              style={{
                width: "100%", padding: "16px",
                display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                background: "none", border: "1px solid #25d366", cursor: "pointer",
                fontFamily: "'DM Sans', sans-serif",
                fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
                color: "#1a8a45", transition: "all 0.2s"
              }}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="#25d366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a12.8 12.8 0 00-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884"/></svg>
              {t("Order via WhatsApp", "Pesan via WhatsApp")}
            </button>

            {/* Sticky bottom CTA — mobile only */}
            <div className="lpb-sticky-cta">
              <div style={{ flex:1, display:"flex", flexDirection:"column", justifyContent:"center" }}>
                <p style={{ fontSize:9, color:"#888", letterSpacing:"0.1em", textTransform:"uppercase", marginBottom:2 }}>
                  {product.name}
                </p>
                <p style={{ fontFamily:"'Cormorant Garant',serif", fontSize:18, color:"#111", fontWeight:500 }}>
                  {formatPrice(curPrice)}
                </p>
              </div>
              <button
                onClick={handleAdd}
                style={{
                  flexShrink:0, padding:"14px 22px",
                  background: mustPick ? "#bbb" : (added ? "#555" : "#111"),
                  border:"none", cursor: mustPick ? "not-allowed" : "pointer",
                  fontFamily:"'DM Sans',sans-serif",
                  fontSize:11, letterSpacing:"0.14em", textTransform:"uppercase",
                  color:"#f9f8f6", fontWeight:600, borderRadius:2
                }}>
                {mustPick
                  ? t("Pick","Pilih")
                  : added
                    ? t("✓","✓")
                    : product.isPreorder
                      ? t("Pre-Order","Pre-Order")
                      : t("Add","Tambah")
                }
              </button>
            </div>

            <div style={{ width: "100%", height: 1, background: "#e8e6e2", margin: "36px 0" }} />

            {/* Description */}
            <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 14, color: "#555", lineHeight: 1.8, marginBottom: 24 }}>
              {product.description}
            </p>

            {/* Details */}
            <div>
              <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#999", marginBottom: 16, fontWeight: 600 }}>
                {t("Details", "Detail")}
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
                {product.details.map((d, i) => (
                  <li key={i} style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 13, color: "#666", paddingLeft: 16, position: "relative" }}>
                    <span style={{ position: "absolute", left: 0, color: "#ccc" }}>—</span>
                    {d}
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>

        {/* Related products */}
        {related.length > 0 && (
          <div style={{ marginTop: 96 }}>
            <div style={{ width: "100%", height: 1, background: "#e8e6e2", marginBottom: 56 }} />
            <h2 style={{ fontFamily: "'Cormorant Garant', serif", fontSize: 36, fontWeight: 400, color: "#111", marginBottom: 40 }}>
              {t("You May Also Like", "Mungkin Kamu Suka")}
            </h2>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 32 }}>
              {related.map(p => (
                <ProductCard key={p.id} product={p} lang={lang}
                  onView={(prod) => { window.scrollTo({ top: 0, behavior: "smooth" }); setTimeout(() => { setSelectedProduct(prod); }, 100); }}
                  onAddToCart={onAddToCart}
                />
              ))}
            </div>
          </div>
        )}
      </div>
      {/* Reviews Section */}
      <div style={{ maxWidth:1200, margin:"48px auto 0", padding:"0 32px 64px" }}>
        <div style={{ borderTop:"1px solid #e8e6e2", paddingTop:48 }}>

          {/* Header */}
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom:32 }}>
            <div>
              <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:28, fontWeight:400, color:"#111" }}>
                Ulasan Pembeli
              </h2>
              {reviewStats.total > 0 && (
                <div style={{ display:"flex", alignItems:"center", gap:10, marginTop:8 }}>
                  <StarRating value={Math.round(reviewStats.avg)} size={18} />
                  <span style={{ fontFamily:"'Cormorant Garant',serif", fontSize:22, color:"#111" }}>{reviewStats.avg}</span>
                  <span style={{ fontSize:13, color:"#aaa" }}>dari {reviewStats.total} ulasan</span>
                </div>
              )}
            </div>
          </div>

          {/* Form ulasan */}
          {canReview && (
            <div style={{ background:"#f9f8f6", border:"1px solid #e8e6e2", borderRadius:4, padding:"24px 28px", marginBottom:32 }}>
              <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:16 }}>
                Tulis Ulasanmu
              </p>
              <div style={{ marginBottom:16 }}>
                <p style={{ fontSize:12, color:"#888", marginBottom:8 }}>Rating</p>
                <StarRating value={myRating} onChange={setMyRating} size={28} />
              </div>
              <textarea
                value={myReview}
                onChange={e => setMyReview(e.target.value)}
                placeholder="Bagikan pengalamanmu dengan produk ini... (min. 10 karakter)"
                style={{ width:"100%", padding:"12px 14px", border:"1px solid #e0deda", background:"#fff", fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#111", outline:"none", borderRadius:2, resize:"vertical", minHeight:100 }}
              />
              {reviewMsg && (
                <p style={{ fontSize:12, marginTop:8, color: reviewMsg.startsWith("✓") ? "#22c55e" : "#e55" }}>{reviewMsg}</p>
              )}
              <button onClick={submitReview} disabled={submitting}
                style={{ marginTop:12, background:"#111", color:"#f9f8f6", border:"none", cursor:"pointer", fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.1em", textTransform:"uppercase", fontWeight:600, padding:"11px 28px", borderRadius:2, opacity:submitting?0.6:1 }}>
                {submitting ? "Mengirim..." : "Kirim Ulasan"}
              </button>
            </div>
          )}

          {alreadyReviewed && (
            <div style={{ background:"#f0fdf4", border:"1px solid #86efac", borderRadius:4, padding:"14px 18px", marginBottom:24, fontSize:13, color:"#15803d" }}>
              ✓ Kamu sudah mengulas produk ini
            </div>
          )}

          {/* Daftar ulasan */}
          {reviews.length === 0 ? (
            <div style={{ textAlign:"center", padding:"40px 0", color:"#bbb" }}>
              <p style={{ fontSize:32, marginBottom:8 }}>💬</p>
              <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:14 }}>Belum ada ulasan</p>
              <p style={{ fontSize:12, color:"#ccc", marginTop:4 }}>Jadilah yang pertama mengulas produk ini</p>
            </div>
          ) : (
            <div style={{ display:"flex", flexDirection:"column", gap:20 }}>
              {reviews.map((r, i) => (
                <div key={r.id || i} style={{ paddingBottom:20, borderBottom: i < reviews.length-1 ? "1px solid #f0efed" : "none" }}>
                  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:8 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:12 }}>
                      <div style={{ width:36, height:36, borderRadius:"50%", background:"#111", color:"#f9f8f6", display:"flex", alignItems:"center", justifyContent:"center", fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:600, flexShrink:0 }}>
                        {r.user_name?.charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:600, color:"#111" }}>{r.user_name}</p>
                        <StarRating value={r.rating} size={12} />
                      </div>
                    </div>
                    <p style={{ fontSize:11, color:"#bbb" }}>
                      {new Date(r.created_at).toLocaleDateString("id-ID", { day:"numeric", month:"long", year:"numeric" })}
                    </p>
                  </div>
                  <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#555", lineHeight:1.7, marginLeft:48 }}>{r.review}</p>
                  {Array.isArray(r.photos) && r.photos.length > 0 && (
                    <div style={{ display:"flex", gap:8, flexWrap:"wrap", marginLeft:48, marginTop:10 }}>
                      {r.photos.map((u, j) => (
                        <a key={j} href={u} target="_blank" rel="noopener noreferrer"
                          style={{ display:"block", width:84, height:84, borderRadius:8, overflow:"hidden", border:"1px solid #eee" }}>
                          <img src={u} alt={"foto ulasan "+(j+1)} style={{ width:"100%", height:"100%", objectFit:"cover" }} />
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

    </div>
  );
};

Object.assign(window, { ProductPage });
