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);
  const [likes, setLikes] = React.useState(1240);   // hitungan like (social proof + interaktif)
  const [burst, setBurst] = React.useState(0);       // trigger burst hati pas di-tap
  const bumpLike = () => { setLikes(l => l + 1); setBurst(b => b + 1); };

  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>
    );
  }

  const vcode  = ((live && live.voucherCode) || "").trim().toUpperCase();
  const pinned = live.pinnedProductId ? list.find(p => String(p.id) === String(live.pinnedProductId)) : null;
  const scrollToCatalog = () => { try { document.getElementById("lpb-live-catalog").scrollIntoView({ behavior: "smooth", block: "start" }); } catch (e) {} };
  const shareLive = () => {
    const url = (typeof window !== "undefined" ? window.location.href : "https://lopobya.shop");
    if (navigator.share) { navigator.share({ title: "LOPOBYA LIVE 🔴", text: t("Watch LOPOBYA live & shop!","Lagi LIVE nih, tonton & belanja bareng!"), url }).catch(()=>{}); }
    else { try { navigator.clipboard.writeText(url); } catch (e) {} }
  };
  const railBtn = { background:"none", border:"none", cursor:"pointer", display:"flex", flexDirection:"column", alignItems:"center", gap:3, padding:0 };
  const railLbl = { color:"#fff", fontSize:10, fontWeight:700, textShadow:"0 1px 3px rgba(0,0,0,.6)" };

  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);
        }
        .lpb-live-dot { animation: lpb-blink 1s infinite alternate; }
        @keyframes lpb-blink { from { opacity: 1; } to { opacity: 0.25; } }
        .lpb-rail-btn:active { transform: scale(1.25); }
      `}</style>
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "0 24px", display: "flex", flexDirection: "column", gap: 40 }}>
        
        {/* ===== IMMERSIVE LIVE (TikTok-style) — video full + overlay ===== */}
        <div style={{ maxWidth: 460, margin: "0 auto", width: "100%" }}>
          <div className="lpb-live-glow" style={{ position: "relative", background: "#000", borderRadius: 24, overflow: "hidden", aspectRatio: "9/16" }}>

            {/* VIDEO (isi penuh frame) */}
            <div style={{ position: "absolute", inset: 0, background: "#000" }}>
              {(!live.platform || live.platform === "youtube") ? (
                <iframe width="100%" height="100%"
                  src={`https://www.youtube.com/embed/${live.youtubeId}?autoplay=1&mute=1&playsinline=1&rel=0`}
                  title="Live Player" frameBorder="0" allowFullScreen allow="autoplay"
                  style={{ width: "100%", height: "100%" }} />
              ) : 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 style={{ width: "100%", height: "100%" }} />
              ) : (
                <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: 90, transform: "translateX(-50%)", background: "#1877f2", color: "#fff", padding: "11px 20px", borderRadius: 26, fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 700, textDecoration: "none", whiteSpace: "nowrap", boxShadow: "0 6px 18px rgba(0,0,0,.4)", zIndex: 6 }}>
                      {t("Watch Live on Facebook", "Tonton Live di Facebook")}
                    </a>
                  )}
                </div>
              )}
            </div>

            {/* Gradient biar teks overlay kebaca (gak nangkep klik) */}
            <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 90, background: "linear-gradient(rgba(0,0,0,.5),transparent)", pointerEvents: "none", zIndex: 4 }} />
            <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 230, background: "linear-gradient(transparent,rgba(0,0,0,.72))", pointerEvents: "none", zIndex: 4 }} />

            {/* LIVE + host (kiri atas) */}
            <div style={{ position: "absolute", top: 14, left: 14, display: "flex", alignItems: "center", gap: 8, zIndex: 8 }}>
              <span style={{ background: "#FF0050", color: "#fff", padding: "5px 12px", borderRadius: 20, fontSize: 11, fontWeight: 800, display: "flex", alignItems: "center", gap: 6, letterSpacing: ".05em", boxShadow: "0 2px 10px rgba(255,0,80,.5)" }}>
                <span className="lpb-live-dot" style={{ width: 7, height: 7, background: "#fff", borderRadius: "50%" }}></span>LIVE
              </span>
              <span style={{ background: "rgba(0,0,0,.4)", backdropFilter: "blur(4px)", color: "#fff", padding: "4px 12px 4px 5px", borderRadius: 20, fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 22, height: 22, borderRadius: "50%", background: "linear-gradient(135deg,#FF0050,#ff8a5e)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 11 }}>🛍️</span>
                LOPOBYA
              </span>
            </div>

            {/* Viewers (kanan atas) */}
            <div style={{ position: "absolute", top: 14, right: 14, background: "rgba(0,0,0,.45)", backdropFilter: "blur(4px)", color: "#fff", padding: "5px 12px", borderRadius: 20, fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", gap: 6, zIndex: 8 }}>
              👁️ {Number(viewers).toLocaleString("id-ID")}
            </div>

            {/* Action rail kanan (like / belanja / bagikan) */}
            <div style={{ position: "absolute", right: 12, bottom: 160, display: "flex", flexDirection: "column", gap: 18, alignItems: "center", zIndex: 8 }}>
              <button className="lpb-rail-btn" onClick={bumpLike} style={railBtn}><span style={{ fontSize: 28 }}>❤️</span><span style={railLbl}>{likes > 999 ? (likes/1000).toFixed(1)+"rb" : likes}</span></button>
              <button className="lpb-rail-btn" onClick={scrollToCatalog} style={railBtn}><span style={{ fontSize: 25 }}>🛍️</span><span style={railLbl}>{t("Shop","Belanja")}</span></button>
              <button className="lpb-rail-btn" onClick={shareLive} style={railBtn}><span style={{ fontSize: 25 }}>🔗</span><span style={railLbl}>{t("Share","Bagikan")}</span></button>
            </div>

            {/* Hati melayang (re-trigger pas di-like) */}
            <div key={burst} style={{ position: "absolute", bottom: 160, right: 22, width: 60, height: 260, zIndex: 7, pointerEvents: "none" }}>
              {["❤️","✨","🔥","💖","👜"].map((h, i) => (
                <div key={i} className="lpb-float-heart" style={{ animationDelay: (i*0.6)+"s", left: (i*7)%28 }}>{h}</div>
              ))}
            </div>

            {/* Overlay bawah: voucher + kartu produk lagi dibahas */}
            <div style={{ position: "absolute", left: 12, right: 68, bottom: 14, display: "flex", flexDirection: "column", gap: 10, zIndex: 8 }}>
              {vcode && (
                <button onClick={() => { try { navigator.clipboard.writeText(vcode); } catch (e) {} }} style={{ alignSelf: "flex-start", background: "linear-gradient(90deg,#FF0050,#ff5e8a)", color: "#fff", border: "none", borderRadius: 20, padding: "7px 14px", fontSize: 12, fontWeight: 700, cursor: "pointer", boxShadow: "0 3px 12px rgba(255,0,80,.4)" }}>
                  🎁 {t("Voucher","Voucher")}: {vcode} · {t("Copy","Salin")}
                </button>
              )}
              {pinned && (
                <div style={{ background: "rgba(255,255,255,.96)", backdropFilter: "blur(6px)", borderRadius: 16, padding: 10, display: "flex", gap: 10, alignItems: "center", boxShadow: "0 6px 22px rgba(0,0,0,.35)" }}>
                  <div style={{ position: "relative", flexShrink: 0 }}>
                    <img src={pinned.images && pinned.images[0]} alt={pinned.name} onClick={() => { setSelectedProduct(pinned); setPage("product"); }} style={{ width: 52, height: 64, objectFit: "cover", borderRadius: 10, cursor: "pointer" }} />
                    <span style={{ position: "absolute", top: -7, left: -4, background: "#FF0050", color: "#fff", fontSize: 8, fontWeight: 800, padding: "2px 6px", borderRadius: 10, whiteSpace: "nowrap" }}>📌 {t("LIVE","DIBAHAS")}</span>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 700, color: "#111", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{pinned.name}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <span style={{ fontSize: 15, fontWeight: 800, color: "#FF0050" }}>Rp {Number(pinned.price).toLocaleString("id-ID")}</span>
                      {pinned.original_price > pinned.price && <span style={{ fontSize: 11, color: "#aaa", textDecoration: "line-through" }}>Rp {Number(pinned.original_price).toLocaleString("id-ID")}</span>}
                    </div>
                    {pinned.stock > 0 && pinned.stock <= 15 && <div style={{ fontSize: 10, fontWeight: 700, color: "#FF0050" }}>🔥 {t("Only "+pinned.stock+" left!","Sisa "+pinned.stock+"!")}</div>}
                  </div>
                  <button onClick={() => onAddToCart(pinned)} style={{ flexShrink: 0, background: "#FF0050", color: "#fff", border: "none", padding: "10px 16px", borderRadius: 24, fontWeight: 800, fontSize: 13, cursor: "pointer", whiteSpace: "nowrap" }}>🛒 {t("Buy","Beli")}</button>
                </div>
              )}
            </div>

          </div>

          <p style={{ textAlign: "center", fontFamily: "'Inter',sans-serif", fontSize: 13, color: "#6e6e73", marginTop: 14 }}>
            {t("Checkout here for the special live price 🔥","Checkout di sini buat harga spesial Live 🔥")}
          </p>
        </div>

        {/* Catalog below live */}
        <div id="lpb-live-catalog" style={{ marginTop:20, scrollMarginTop:90 }}>
          <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 });
