const ProductCard = ({ product, onView, onAddToCart, lang }) => {
  const [hovered, setHovered] = React.useState(false);
  const [wish,    setWish]    = React.useState(false);
  const [rating,  setRating]  = React.useState(product.rating > 0 ? { avg: product.rating, total: product.ratingCount || 0 } : null);
  const ACCENT = "#a9744f";

  React.useEffect(() => {
    if (product.rating > 0) return; // pakai rating manual dari admin
    fetch("api/reviews.php?product_id=" + product.id)
      .then(r=>r.json())
      .then(d=>{ if(d.total>0) setRating({avg:d.avg_rating, total:d.total}); })
      .catch(()=>{});
  }, [product.id]);

  const t = (en, id) => lang === "id" ? id : en;

  // peta nama warna → hex untuk swatch
  const COLORMAP = {
    black:"#1d1d1f", hitam:"#1d1d1f", ivory:"#efece4", putih:"#f4f1ea", white:"#f4f1ea",
    cream:"#ece3d2", caramel:"#c9a37a", brown:"#8a5a37", coklat:"#8a5a37", stone:"#b9b2a6",
    blush:"#e7b9b0", pink:"#e7b9b0", grey:"#b8b8bd", gray:"#b8b8bd", abu:"#b8b8bd",
    silver:"#cfcfcf", gold:"#d4af37", "rose gold":"#dca08a", navy:"#2a3550", blue:"#2a4d8f",
    sand:"#e3d9c8", tan:"#c9a37a", beige:"#e8e0d4", green:"#4a6b4a", red:"#b4452f", maroon:"#7a2e3a"
  };
  const colorNames = Array.isArray(product.colors) ? product.colors.slice(0,5) : [];
  const hexOf = (c) => (product.colorHex && product.colorHex[c]) || COLORMAP[String(c).toLowerCase().trim()] || "#d9d4cb";
  const [selColor, setSelColor] = React.useState(null);  // jangan paksa pilih warna — cover = foto utama produk

  const hasDisc = product.originalPrice && Number(product.originalPrice) > Number(product.price);
  const discPct = hasDisc ? Math.round((1 - Number(product.price)/Number(product.originalPrice)) * 100) : 0;
  const _matchVar = (Array.isArray(product.variants) && selColor)
    ? product.variants.find(v => v.image && String(v.name).toLowerCase().trim() === String(selColor).toLowerCase().trim())
    : null;
  const img = (product.colorImages && selColor && product.colorImages[selColor])
    || (_matchVar && _matchVar.image)
    || (Array.isArray(product.images) && product.images.length > 0 ? product.images[0] : product.image);

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        background:"#fff", border:"1px solid #ececf0", borderRadius:22, overflow:"hidden",
        cursor:"pointer", transition:"transform 0.35s ease, box-shadow 0.35s ease",
        transform: hovered ? "translateY(-6px)" : "none",
        boxShadow: hovered ? "0 18px 50px rgba(20,20,30,0.10)" : "none",
        display:"flex", flexDirection:"column"
      }}
    >
      {/* Image */}
      <div onClick={() => onView(product)} className="lh-card-img"
        style={{ position:"relative", overflow:"hidden", aspectRatio:"1/1", background:"#f5f5f7" }}>
        <img src={img} alt={product.name}
          style={{ width:"100%", height:"100%", objectFit:"cover", transition:"transform 0.6s ease", transform: hovered ? "scale(1.06)" : "scale(1)" }} />

        {/* Badge */}
        {product.isPreorder ? (
          <span style={{ position:"absolute", top:12, left:12, background:"#f59e0b", color:"#fff", fontFamily:"'Inter',sans-serif", fontSize:11, fontWeight:600, padding:"5px 11px", borderRadius:20, boxShadow:"0 2px 8px rgba(0,0,0,0.1)" }}>
            ⏳ PO {product.preorderDays || 14}h
          </span>
        ) : hasDisc ? (
          <span style={{ position:"absolute", top:12, left:12, background:ACCENT, color:"#fff", fontFamily:"'Inter',sans-serif", fontSize:11, fontWeight:600, padding:"5px 11px", borderRadius:20, boxShadow:"0 2px 8px rgba(0,0,0,0.1)" }}>
            −{discPct}%
          </span>
        ) : product.badge ? (
          <span style={{ position:"absolute", top:12, left:12, background:"#fff", color:"#1d1d1f", fontFamily:"'Inter',sans-serif", fontSize:11, fontWeight:600, padding:"5px 11px", borderRadius:20, boxShadow:"0 2px 8px rgba(0,0,0,0.1)" }}>
            {product.badge}
          </span>
        ) : null}

        {/* Wishlist */}
        <button
          onClick={(e) => { e.stopPropagation(); setWish(w=>!w); }}
          aria-label="Wishlist"
          style={{
            position:"absolute", top:10, right:10, width:34, height:34, borderRadius:"50%",
            background:"rgba(255,255,255,0.9)", backdropFilter:"blur(6px)", border:"none", cursor:"pointer",
            display:"flex", alignItems:"center", justifyContent:"center", fontSize:15,
            color: wish ? ACCENT : "#6e6e73",
            opacity: hovered || wish ? 1 : 0, transform: hovered || wish ? "none" : "translateY(-6px)",
            transition:"opacity 0.25s, transform 0.25s, color 0.2s"
          }}>{wish ? "♥" : "♡"}</button>

        {/* Quick add */}
        {(() => {
          const hasVar    = Array.isArray(product.variants) && product.variants.length > 0;
          const hasColor  = Array.isArray(product.colors)   && product.colors.length   > 0;
          const needsPick = hasVar || hasColor;   // wajib pilih dulu di halaman produk
          return (
        <button
          onClick={(e) => {
            e.stopPropagation();
            // Produk dgn varian/warna: arahkan ke halaman produk biar pilih dulu (keranjang harus tau opsinya)
            if (needsPick) { onView(product); return; }
            onAddToCart(product);
          }}
          style={{
            position:"absolute", left:12, right:12, bottom:12,
            background:"#1d1d1f", color:"#fff", border:"none", borderRadius:30, cursor:"pointer",
            fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:600, padding:"11px",
            opacity: hovered ? 1 : 0, transform: hovered ? "none" : "translateY(12px)",
            transition:"opacity 0.3s, transform 0.3s"
          }}>{hasVar
              ? t("Choose Variant","Pilih Varian")
              : hasColor
                ? t("Choose Color","Pilih Warna")
                : "+ " + t("Add to Cart","Tambah ke Keranjang")}</button>
          );
        })()}
      </div>

      {/* Info */}
      <div onClick={() => onView(product)} style={{ padding:"15px 17px 18px", flex:1, display:"flex", flexDirection:"column" }}>
        {colorNames.length > 0 && (
          <div style={{ display:"flex", alignItems:"center", gap:7, marginBottom:9 }}>
            {colorNames.map((c,i)=>{
              const active = selColor === c;
              return (
                <button key={i} title={c} aria-label={c}
                  onClick={(e)=>{ e.stopPropagation(); setSelColor(c); }}
                  style={{ width:15, height:15, borderRadius:"50%", background:hexOf(c), cursor:"pointer", padding:0,
                    border:"1px solid rgba(0,0,0,0.12)",
                    outline: active ? "1.5px solid #1d1d1f" : "none", outlineOffset:2,
                    transition:"outline 0.15s" }} />
              );
            })}
            {selColor && <span style={{ fontFamily:"'Inter',sans-serif", fontSize:11, color:"#6e6e73", marginLeft:2 }}>{selColor}</span>}
          </div>
        )}
        <p style={{ fontFamily:"'Inter',sans-serif", fontSize:12, color:"#6e6e73", margin:"0 0 3px" }}>{product.categoryLabel}</p>
        <h3 style={{ fontFamily:"'Inter',sans-serif", fontSize:16, fontWeight:600, color:"#1d1d1f", margin:"0 0 7px", lineHeight:1.25, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{product.name}</h3>
        {rating && (
          <div style={{ fontSize:11, color:"#f5a623", marginBottom:9 }}>
            {"★".repeat(Math.round(rating.avg))}{"☆".repeat(5-Math.round(rating.avg))}
            {rating.total>0 && <span style={{ color:"#6e6e73", marginLeft:5 }}>({rating.total})</span>}
          </div>
        )}
        <div style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", marginTop:"auto" }}>
          <span style={{ fontFamily:"'Inter',sans-serif", fontSize:16, color:"#1d1d1f", fontWeight:700 }}>{(Array.isArray(product.variants) && product.variants.length) ? (t("From ","Mulai ") ) : ""}{formatPrice(product.price)}</span>
          {hasDisc && (
            <span style={{ fontFamily:"'Inter',sans-serif", fontSize:13, color:"#a1a1a6", textDecoration:"line-through" }}>{formatPrice(product.originalPrice)}</span>
          )}
        </div>
        {/* Urgensi stok asli — cuma tampil kalau stok beneran tinggal sedikit */}
        {Number(product.stock) > 0 && Number(product.stock) <= 8 && (
          <p style={{ fontFamily:"'Inter',sans-serif", fontSize:11.5, color:"#b4452f", fontWeight:600, margin:"7px 0 0" }}>
            🔥 {t(`Only ${product.stock} left`, `Sisa ${product.stock} stok`)}
          </p>
        )}
      </div>
    </div>
  );
};
Object.assign(window, { ProductCard });
