const FeedPage = ({ setPage, setSelectedProduct, onAddToCart, lang, feedSettings, products }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const feed = Array.isArray(feedSettings) ? feedSettings : [];
  const [isMuted, setIsMuted] = React.useState(true);
  const [activeIndex, setActiveIndex] = React.useState(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (activeIndex !== null && containerRef.current) {
      const slideHeight = containerRef.current.clientHeight;
      containerRef.current.scrollTop = activeIndex * slideHeight;
    }
  }, [activeIndex]);

  React.useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        const vid = entry.target;
        if(entry.isIntersecting) {
          vid.play().catch(e => console.log("Autoplay prevented:", e));
        } else {
          vid.pause();
        }
      });
    }, { threshold: 0.6 });

    const videos = document.querySelectorAll(".lpb-feed-video");
    videos.forEach(v => observer.observe(v));

    // Hide default header/footer when in Feed Page
    const header = document.querySelector(".lpb-header");
    const footer = document.querySelector(".lpb-footer");
    const wa = document.querySelector(".lpb-wa-float");
    if(header) header.style.display = "none";
    if(footer) footer.style.display = "none";
    if(wa) wa.style.display = "none";
    return () => {
      videos.forEach(v => observer.unobserve(v));
      if(header) header.style.display = "";
      if(footer) footer.style.display = "";
      if(wa) wa.style.display = "";
    };
  }, [feed, activeIndex]);

  const handleProductClick = (productId) => {
    const p = products.find(x => x.id === productId);
    if(p) {
      setSelectedProduct(p);
      setPage("product");
    }
  };

  if (feed.length === 0) {
    return (
      <div style={{ height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", flexDirection:"column", background:"#000", color:"#fff", position:"fixed", top:0, left:0, width:"100%", zIndex:9999 }}>
        <h2 style={{ fontFamily: "'Inter', sans-serif", fontWeight: 500, fontSize: 18, marginBottom: 16 }}>{t("No videos available.","Belum ada video.")}</h2>
        <button onClick={() => setPage("home")} style={{ background: "#FF0050", color: "#fff", border: "none", padding: "12px 24px", borderRadius: 24, fontWeight: 600, cursor: "pointer" }}>
          {t("Back to Home","Kembali ke Beranda")}
        </button>
      </div>
    );
  }

  if (activeIndex === null) {
    return (
      <div style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100%", height: "100%", background: "#0f0f0f", overflowY: "auto", zIndex: 9999, fontFamily:"'Inter',sans-serif", color: "#fff" }}>
        
        {/* Header */}
        <div style={{ display:"flex", alignItems:"center", justifyContent:"center", padding:"16px", borderBottom:"1px solid #222", position:"sticky", top:0, background:"rgba(15,15,15,0.85)", backdropFilter:"blur(12px)", zIndex:10 }}>
          <button onClick={() => setPage("home")} style={{ position:"absolute", left:16, background:"none", border:"none", fontSize:24, cursor:"pointer", color:"#fff" }}>&#8592;</button>
          <span style={{ fontSize:16, fontWeight:600 }}>{t("Lopobya Video", "Lopobya Video")}</span>
        </div>

        <div style={{ maxWidth: 800, margin: "0 auto", paddingBottom: 40, width: "100%" }}>
          {/* Profile Section */}
          <div style={{ display:"flex", flexDirection:"column", alignItems:"center", padding:"24px 16px" }}>
            <img src="uploads/logo-1777527805215.jpg" alt="Lopobya" style={{ width: 96, height: 96, borderRadius: "50%", objectFit:"cover", border:"2px solid #333", marginBottom: 12, background:"#fff" }} />
            <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 4px" }}>@lopobya.official</h2>
            <p style={{ fontSize: 14, color: "#aaa", margin: "0 0 16px" }}>Premium Women's Bags 👜</p>
            <div style={{ display:"flex", gap: 32, marginBottom: 16 }}>
              <div style={{ textAlign:"center" }}><b style={{ display:"block", fontSize:18 }}>{feed.length}</b><span style={{ fontSize:12, color:"#888" }}>Videos</span></div>
              <div style={{ textAlign:"center" }}><b style={{ display:"block", fontSize:18 }}>12.4K</b><span style={{ fontSize:12, color:"#888" }}>Followers</span></div>
              <div style={{ textAlign:"center" }}><b style={{ display:"block", fontSize:18 }}>102K</b><span style={{ fontSize:12, color:"#888" }}>Likes</span></div>
            </div>
          </div>
          
          {/* Grid Container */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:2, padding:2 }}>
            {feed.map((f, i) => (
              <div key={i} onClick={() => setActiveIndex(i)} style={{ aspectRatio:"9/16", background:"#222", position:"relative", cursor:"pointer", overflow:"hidden", transition:"transform 0.2s" }} onMouseEnter={e=>e.currentTarget.style.opacity=0.9} onMouseLeave={e=>e.currentTarget.style.opacity=1}>
                <video src={`${f.videoUrl}#t=0.1`} playsInline muted preload="metadata" style={{ width:"100%", height:"100%", objectFit:"cover", opacity:0.85 }} />
                <div style={{ position:"absolute", bottom:8, left:8, color:"#fff", fontSize:12, fontWeight:600, display:"flex", alignItems:"center", gap:4, textShadow:"0 1px 3px rgba(0,0,0,0.8)" }}>
                  <span style={{ display:"inline-block", width:0, height:0, borderTop:"4px solid transparent", borderBottom:"4px solid transparent", borderLeft:"6px solid #fff" }}></span>
                  {Math.floor(Math.random() * 900 + 100)}K
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="lpb-feed-container" ref={containerRef} style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, width: "100%", height: "100%", background: "#000", overflowY: "scroll", scrollSnapType: "y mandatory", zIndex: 9999 }}>
      <style>{`
        .lpb-feed-container::-webkit-scrollbar { display: none; }
        .lpb-feed-slide { height: 100vh; height: 100dvh; width: 100%; scroll-snap-align: start; position: relative; display: flex; justify-content: center; background: #000; }
        .lpb-feed-player-wrapper { width: 100%; max-width: 440px; height: 100%; position: relative; background: #111; overflow: hidden; }
        .lpb-feed-video { width: 100%; height: 100%; object-fit: cover; }
        .lpb-feed-overlay { position: absolute; bottom: 0; left: 0; right: 0; padding: 24px 16px; background: linear-gradient(to top, rgba(0,0,0,0.8) 0%, transparent 100%); display:flex; flex-direction:column; gap:16; z-index: 2; }
        .lpb-feed-title { color: #fff; font-family: 'Inter', sans-serif; font-size: 15px; font-weight: 500; line-height: 1.4; text-shadow: 0 1px 3px rgba(0,0,0,0.5); }
        
        @media (max-width: 900px) {
          .lpb-feed-player-wrapper { max-width: 100%; }
          .lpb-feed-buttons-wrapper { max-width: 100% !important; }
        }
        
        .lpb-feed-product { background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.2); border-radius: 12px; padding: 12px; display: flex; gap: 12px; align-items: center; cursor: pointer; transition: transform 0.2s; }
        .lpb-feed-product:hover { transform: scale(1.02); }
        .lpb-feed-product img { width: 56px; height: 56px; object-fit: cover; border-radius: 8px; }
        .lpb-feed-product-info { flex: 1; }
        .lpb-feed-product-name { color: #fff; font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 600; margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; }
        .lpb-feed-product-price { color: #FF0050; font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 700; }
        
      `}</style>

      {feed.map((f, i) => {
        const prod = products.find(x => String(x.id) === String(f.productId));
        return (
          <div key={i} className="lpb-feed-slide">
            <div className="lpb-feed-player-wrapper">
              <video 
                className="lpb-feed-video" 
                src={f.videoUrl} 
                autoPlay={i === 0}
                muted={isMuted} 
                loop 
                playsInline 
                onClick={(e) => { e.target.paused ? e.target.play() : e.target.pause(); }}
              />
              
              <div className="lpb-feed-overlay">
                {f.title && <div className="lpb-feed-title">{f.title}</div>}
                
                {prod && (
                  <div className="lpb-feed-product" onClick={() => handleProductClick(prod.id)}>
                    <img src={prod.images[0]} alt={prod.name} />
                    <div className="lpb-feed-product-info">
                      <div className="lpb-feed-product-name">{prod.name}</div>
                      <div className="lpb-feed-product-price">Rp {prod.price.toLocaleString("id-ID")}</div>
                    </div>
                    <button onClick={(e) => { e.stopPropagation(); onAddToCart(prod); }} style={{ background: "#FF0050", color: "#fff", border: "none", padding: "8px 16px", borderRadius: 20, fontSize: 13, fontWeight: 600, cursor: "pointer" }}>
                      {t("Buy","Beli")}
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        );
      })}

      <div style={{ position:"fixed", top:0, left:0, right:0, bottom:0, pointerEvents:"none", display:"flex", justifyContent:"center", zIndex: 100 }}>
        <div className="lpb-feed-buttons-wrapper" style={{ width: "100%", maxWidth: 440, position: "relative" }}>
          
          <button className="lpb-feed-back" onClick={() => setActiveIndex(null)} style={{
            position: "absolute", top: 24, left: 16, width: 40, height: 40, borderRadius: "50%", 
            background: "rgba(0,0,0,0.4)", backdropFilter: "blur(4px)", border: "none", 
            display: "flex", alignItems: "center", justifyContent: "center", 
            cursor: "pointer", color: "#fff", fontSize: 24, pointerEvents:"auto"
          }}>
            &#8592; {/* Left arrow icon */}
          </button>

          <button onClick={() => setIsMuted(!isMuted)} style={{
            position: "absolute", top: 24, right: 16, width: 40, height: 40, borderRadius: "50%", 
            background: "rgba(0,0,0,0.4)", backdropFilter: "blur(4px)", border: "none", 
            display: "flex", alignItems: "center", justifyContent: "center", 
            cursor: "pointer", color: "#fff", fontSize: 20, pointerEvents:"auto"
          }}>
            {isMuted ? "🔇" : "🔊"}
          </button>

        </div>
      </div>

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