const LivePage = ({ setPage, setSelectedProduct, onAddToCart, lang, liveStreamSettings, products, productsReady }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const list = (Array.isArray(products) && products.length) ? products : (window.PRODUCTS || []);
  const activeProducts = list.filter(p => p.stock > 0);

  const [viewers, setViewers] = React.useState(80);
  const [live, setLive] = React.useState(liveStreamSettings);

  React.useEffect(() => {
    window.scrollTo(0,0);
    // Penonton REAL via heartbeat presence + baseline social proof.
    // Set VIEWER_BASE = 0 kalau mau angka MURNI real tanpa tambahan.
    const VIEWER_BASE = 80;
    let vid = sessionStorage.getItem("lpb_live_vid");
    if (!vid) { vid = Math.random().toString(36).slice(2) + Date.now().toString(36); sessionStorage.setItem("lpb_live_vid", vid); }
    const beat = async () => {
      try {
        const r = await fetch("api/live_presence.php", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ id: vid }) });
        const d = await r.json();
        if (d && typeof d.count === "number") setViewers(VIEWER_BASE + d.count);
      } catch (e) {}
    };
    beat();
    const interval = setInterval(beat, 10000);
    return () => clearInterval(interval);
  }, []);

  // Sinkron kalau prop berubah + AUTO-REFRESH setting live tiap 15 detik →
  // spotlight/pin ganti REAL-TIME di layar penonton tanpa mereka refresh.
  React.useEffect(() => { setLive(liveStreamSettings); }, [liveStreamSettings]);
  React.useEffect(() => {
    const iv = setInterval(async () => {
      try {
        const r = await fetch("api/settings.php");
        const d = await r.json();
        if (d && d.liveStream) setLive(d.liveStream);
      } catch (e) {}
    }, 15000);
    return () => clearInterval(iv);
  }, []);

  // Simpan kode voucher live → CheckoutPage auto-apply pas penonton checkout.
  React.useEffect(() => {
    const vc = ((live && live.voucherCode) || "").trim().toUpperCase();
    if (vc) { try { localStorage.setItem("lopobya_live_voucher", vc); } catch (e) {} }
  }, [live]);

  // Facebook: pakai SDK resmi (fb-video) — versi embed paling didukung FB,
  // peluang jalan di HP lebih besar drpd iframe polos. Load SDK sekali + parse ulang.
  React.useEffect(() => {
    if (!live || live.platform !== "facebook" || !live.facebookUrl) return;
    const parse = () => { try { if (window.FB && window.FB.XFBML) window.FB.XFBML.parse(); } catch (e) {} };
    if (window.FB) { parse(); return; }
    if (!document.getElementById("facebook-jssdk")) {
      const js = document.createElement("script");
      js.id = "facebook-jssdk";
      js.src = "https://connect.facebook.net/id_ID/sdk.js#xfbml=1&version=v19.0";
      js.async = true; js.defer = true; js.crossOrigin = "anonymous";
      js.onload = parse;
      document.body.appendChild(js);
    } else {
      const iv = setInterval(() => { if (window.FB) { parse(); clearInterval(iv); } }, 300);
      setTimeout(() => clearInterval(iv), 6000);
    }
  }, [live && live.platform, live && live.facebookUrl]);

  if (!live || !live.active) {
    return (
      <div style={{ minHeight:"60vh", display:"flex", alignItems:"center", justifyContent:"center", flexDirection:"column" }}>
        <h2 style={{ fontFamily:"'Fraunces',serif", fontSize:24, marginBottom:16 }}>{t("No active live stream.","Tidak ada siaran langsung saat ini.")}</h2>
        <button onClick={() => setPage("home")} style={{ padding:"12px 28px", background:"#111", color:"#fff", border:"none", borderRadius:30, cursor:"pointer", fontFamily:"'Inter',sans-serif", fontWeight:600 }}>
          {t("Back to Home","Kembali ke Beranda")}
        </button>
      </div>
    );
  }

  return (
    <div style={{ background: "#fbfbfd", minHeight: "100vh", paddingTop: 100, paddingBottom: 60 }}>
      <style>{`
        .lpb-float-heart {
          position: absolute; bottom: -30px; font-size: 20px; opacity: 0;
          animation: floatUp 3s infinite ease-in;
        }
        @keyframes floatUp {
          0% { transform: translateY(0) scale(0.5); opacity: 0; }
          20% { opacity: 1; transform: translateY(-30px) scale(1); }
          80% { opacity: 1; }
          100% { transform: translateY(-200px) scale(1.2); opacity: 0; }
        }
        .lpb-live-glow {
          box-shadow: 0 0 40px rgba(255, 0, 80, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.1);
        }
      `}</style>
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "0 24px", display: "flex", flexDirection: "column", gap: 40 }}>
        
        {/* Video Player */}
        <div>
          <div style={{ textAlign:"center", marginBottom:24 }}>
            <h1 style={{ fontFamily: "'Fraunces',serif", fontSize: "clamp(28px, 4vw, 42px)", color:"#1d1d1f", marginBottom:12 }}>
              {t("Watch Live & Shop","Tonton Live & Belanja")}
            </h1>
            <p style={{ fontFamily:"'Inter',sans-serif", fontSize:16, color:"#6e6e73" }}>
              {t("Checkout directly here to get our special live price.","Checkout langsung di website untuk mendapatkan harga spesial khusus penonton Live.")}
            </p>
          </div>
          <div className="lpb-live-glow" style={{ background: "#111", borderRadius: 24, overflow: "hidden", position: "relative", maxWidth: 440, margin:"0 auto" }}>
            
            {/* Live Badge Top Left */}
            <div style={{ position: "absolute", top: 16, left: 16, background: "#FF0050", color: "#fff", padding: "6px 14px", borderRadius: 20, fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", gap: 6, animation: "lpb-tiktok-blink 1s infinite alternate", zIndex:10 }}>
              <span style={{ width: 8, height: 8, background: "#fff", borderRadius: "50%", display: "inline-block" }}></span>
              LIVE SEKARANG
            </div>

            {/* Viewers Badge Top Right */}
            <div style={{ position: "absolute", top: 16, right: 16, background: "rgba(0,0,0,0.5)", backdropFilter: "blur(4px)", color: "#fff", padding: "6px 12px", borderRadius: 20, fontSize: 12, fontWeight: 600, display: "flex", alignItems: "center", gap: 6, zIndex:10, border: "1px solid rgba(255,255,255,0.1)", transition: "all 0.3s" }}>
              👁️ {viewers}
            </div>

            {/* Floating Likes (TikTok style) */}
            <div style={{ position: "absolute", bottom: 40, right: 20, width: 60, height: 200, zIndex: 10, pointerEvents: "none" }}>
              <div className="lpb-float-heart" style={{ animationDelay: "0s", left: 10 }}>❤️</div>
              <div className="lpb-float-heart" style={{ animationDelay: "0.8s", left: 30 }}>✨</div>
              <div className="lpb-float-heart" style={{ animationDelay: "1.5s", left: 20 }}>🔥</div>
              <div className="lpb-float-heart" style={{ animationDelay: "2.2s", left: 5 }}>👜</div>
              <div className="lpb-float-heart" style={{ animationDelay: "2.8s", left: 25 }}>❤️</div>
            </div>

            <div style={{ width: "100%", aspectRatio: "9/16", background: "#000" }}>
              {(!live.platform || live.platform === "youtube") ? (
                <iframe 
                  width="100%" height="100%" 
                  src={`https://www.youtube.com/embed/${live.youtubeId}?autoplay=1&mute=1`} 
                  title="Live Player"
                  frameBorder="0" allowFullScreen allow="autoplay"
                />
              ) : live.platform === "twitch" ? (
                <iframe 
                  width="100%" height="100%" 
                  src={`https://player.twitch.tv/?channel=${live.twitchChannel || ""}&parent=${window.location.hostname}&autoplay=true&muted=true`}
                  title="Live Player"
                  frameBorder="0" allowFullScreen
                />
              ) : (
                <div style={{ position:"relative", width:"100%", height:"100%", display:"flex", alignItems:"center", justifyContent:"center" }}>
                  <div id="fb-root"></div>
                  <div
                    className="fb-video"
                    data-href={live.facebookUrl || ""}
                    data-width="auto"
                    data-allowfullscreen="true"
                    data-autoplay="true"
                    data-show-captions="false"
                    style={{ width:"100%", maxWidth:"100%" }}
                  ></div>
                  {live.facebookUrl && (
                    <a
                      href={live.facebookUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        position:"absolute", left:"50%", bottom:16, transform:"translateX(-50%)",
                        background:"#1877f2", color:"#fff", padding:"11px 20px", borderRadius:26,
                        fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:700, textDecoration:"none",
                        display:"flex", alignItems:"center", gap:8, whiteSpace:"nowrap",
                        boxShadow:"0 6px 18px rgba(0,0,0,.4)", zIndex:5
                      }}
                    >
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M24 12.07C24 5.4 18.63 0 12 0S0 5.4 0 12.07C0 18.1 4.39 23.1 10.13 24v-8.44H7.08v-3.49h3.05V9.41c0-3.02 1.79-4.69 4.53-4.69 1.31 0 2.68.24 2.68.24v2.97h-1.51c-1.49 0-1.96.93-1.96 1.89v2.25h3.33l-.53 3.49h-2.8V24C19.61 23.1 24 18.1 24 12.07z"/></svg>
                      {t("Watch Live on Facebook", "Tonton Live di Facebook")}
                    </a>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Voucher khusus Live */}
        {(() => {
          const vcode = ((live && live.voucherCode) || "").trim().toUpperCase();
          if (!vcode) return null;
          return (
            <div style={{ maxWidth: 640, margin: "0 auto", width: "100%" }}>
              <div style={{ background: "linear-gradient(90deg,#FF0050,#ff5e8a)", color: "#fff", borderRadius: 16, padding: "14px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600 }}>🎁 {t("Live-only voucher", "Voucher khusus Live")}: <b style={{ fontSize: 17, letterSpacing: "0.03em" }}>{vcode}</b></div>
                <button onClick={() => { try { navigator.clipboard.writeText(vcode); } catch (e) {} }} style={{ background: "#fff", color: "#FF0050", border: "none", padding: "8px 16px", borderRadius: 20, fontWeight: 700, fontSize: 13, cursor: "pointer", whiteSpace: "nowrap" }}>{t("Copy", "Salin")}</button>
              </div>
            </div>
          );
        })()}

        {/* Produk Spotlight / Pinned (lagi dibahas host) */}
        {(() => {
          const pinned = live.pinnedProductId
            ? list.find(p => String(p.id) === String(live.pinnedProductId))
            : null;
          if (!pinned) return null;
          return (
            <div style={{ maxWidth: 640, margin: "0 auto", width: "100%" }}>
              <div style={{ background: "#fff", border: "2px solid #FF0050", borderRadius: 20, padding: 16, display: "flex", gap: 16, alignItems: "center", boxShadow: "0 8px 30px rgba(255,0,80,0.15)", position: "relative" }}>
                <div style={{ position: "absolute", top: -12, left: 20, background: "#FF0050", color: "#fff", fontSize: 11, fontWeight: 800, padding: "4px 12px", borderRadius: 20, letterSpacing: "0.05em" }}>📌 {t("NOW SHOWING", "LAGI DIBAHAS")}</div>
                <img src={pinned.images && pinned.images[0]} alt={pinned.name} style={{ width: 100, height: 130, objectFit: "cover", borderRadius: 12, flexShrink: 0, cursor: "pointer" }} onClick={() => { setSelectedProduct(pinned); setPage("product"); }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 16, fontWeight: 700, color: "#1d1d1f", marginBottom: 4 }}>{pinned.name}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
                    <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 20, fontWeight: 800, color: "#FF0050" }}>Rp {Number(pinned.price).toLocaleString("id-ID")}</span>
                    {pinned.original_price > pinned.price && <span style={{ fontSize: 13, color: "#aaa", textDecoration: "line-through" }}>Rp {Number(pinned.original_price).toLocaleString("id-ID")}</span>}
                    <span style={{ background: "#111", color: "#fff", fontSize: 10, fontWeight: 800, padding: "3px 8px", borderRadius: 12, letterSpacing: "0.03em" }}>⚡ {t("LIVE PRICE", "HARGA LIVE")}</span>
                  </div>
                  {pinned.stock > 0 && pinned.stock <= 15 && (
                    <div style={{ fontSize: 12, fontWeight: 700, color: "#FF0050", marginBottom: 10 }}>🔥 {t("Only " + pinned.stock + " left, hurry!", "Sisa " + pinned.stock + " lagi, buruan!")}</div>
                  )}
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={() => onAddToCart(pinned)} style={{ flex: 1, background: "#FF0050", color: "#fff", border: "none", padding: "12px", borderRadius: 30, fontWeight: 700, fontSize: 14, cursor: "pointer" }}>🛒 {t("Buy Now", "Beli Sekarang")}</button>
                    <button onClick={() => { setSelectedProduct(pinned); setPage("product"); }} style={{ background: "#f0f0f0", color: "#111", border: "none", padding: "12px 18px", borderRadius: 30, fontWeight: 600, fontSize: 14, cursor: "pointer" }}>{t("Details", "Detail")}</button>
                  </div>
                </div>
              </div>
            </div>
          );
        })()}

        {/* Catalog below live */}
        <div style={{ marginTop:20 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28 }}>
            <h2 style={{ fontFamily: "'Fraunces',serif", fontSize: "clamp(24px, 3vw, 32px)", color:"#1d1d1f" }}>
              {t("Live Collection","Koleksi Spesial Live")}
            </h2>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: 20 }}>
            {productsReady
              ? (() => {
                  // Kalau ada keranjang live → tampilkan produk yang udah dibahas (terkurasi).
                  // Kalau kosong → tampilkan semua produk ready.
                  const basketIds = Array.isArray(live.basketProductIds) ? live.basketProductIds : [];
                  const basketProducts = basketIds.map(id => list.find(p => String(p.id) === String(id))).filter(Boolean);
                  const collection = basketProducts.length ? basketProducts : activeProducts;
                  return collection.map(p => <ProductCard key={p.id} product={p} lang={lang} onView={(x)=>{setSelectedProduct(x);setPage("product");}} onAddToCart={onAddToCart} />);
                })()
              : [1,2,3,4].map(i => <div key={i}><div className="lpb-skeleton lpb-skel-card" style={{ borderRadius:22 }} /><div className="lpb-skeleton lpb-skel-line med" /><div className="lpb-skeleton lpb-skel-line short" /></div>)}
          </div>
        </div>

      </div>
    </div>
  );
};
Object.assign(window, { LivePage });
