const HomePage = ({ setPage, setSelectedProduct, onAddToCart, lang, heroSettings, homeSettings, products, productsReady }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const ACCENT = "#a9744f";
  const list = (Array.isArray(products) && products.length) ? products : (window.PRODUCTS || []);

  // ── Settings + default ───────────────────────────────────
  const hero = heroSettings || {};
  const home = homeSettings || {};
  const fallbackImg = "uploads/product_images-1777527711871.png";

  const heroTitle    = hero.title    || "Bawa ceritamu ke mana saja.";
  const heroAccent   = hero.accent   || "ceritamu";
  const heroSubtitle = hero.subtitle || "Tas wanita premium yang dibuat dengan tangan di Indonesia — untuk mereka yang bergerak dengan niat dan gaya.";
  const heroBtn1     = hero.btnPrimary   || hero.btnText || "Belanja Sekarang";
  const heroBtn2     = hero.btnSecondary || "Lihat Koleksi";
  const heroImg      = hero.image    || fallbackImg;
  const heroPill     = hero.pillText || "Koleksi 2026 telah tiba";
  const heroStats    = Array.isArray(hero.stats) && hero.stats.length ? hero.stats : [
    { value:"4.9★", label:t("1,200+ reviews","1.200+ ulasan") },
    { value:"10K+", label:t("Customers","Pelanggan") },
    { value:"100%", label:t("Authentic","Bahan asli") },
  ];

  const showMarquee     = home.showMarquee     !== false;
  const showCategories  = home.showCategories  !== false;
  const showBestsellers = home.showBestsellers !== false;
  const showSpotlight   = home.spotlight ? home.spotlight.show !== false : true;
  const showTestimonials= home.showTestimonials!== false;
  const showNewsletter  = home.newsletter ? home.newsletter.show !== false : true;

  const marqueeItems = (Array.isArray(home.marquee) && home.marquee.length) ? home.marquee
    : [t("Free Shipping","Gratis Ongkir"), t("Authentic Materials","Bahan Asli"), t("Made in Indonesia","Buatan Indonesia"), t("Easy Returns","Mudah Dikembalikan"), t("7-Day Guarantee","Garansi 7 Hari")];

  const testimonials = (Array.isArray(home.testimonials) && home.testimonials.length) ? home.testimonials : [
    { name:"Saraswati A.", city:"Jakarta",  text:"Bahannya beneran premium, jahitannya rapi. Dipakai ke kantor maupun hangout sama-sama cocok. Worth it banget!" },
    { name:"Rina N.",      city:"Bandung",  text:"Packing aman, sampai cepat, dan tasnya lebih bagus dari foto. Udah beli 3 kali dan nggak pernah kecewa." },
    { name:"Dewi P.",      city:"Surabaya", text:"Suka banget sama desainnya yang simpel tapi elegan. CS-nya juga ramah dan fast respon. Recommended!" },
  ];

  const nl = home.newsletter || {};
  const nlTitle    = nl.title    || t("Be the first to know","Jadilah yang pertama tahu");
  const nlSubtitle = nl.subtitle || t("Sign up & get 10% off your first order.","Daftar newsletter & dapatkan diskon 10% untuk pembelian pertamamu.");

  // ── Derived product lists ────────────────────────────────
  const featured = (() => {
    const f = list.filter(p => p.badge === "NEW" || p.badge === "BEST SELLER").slice(0,4);
    return f.length ? f : list.slice(0,4);
  })();
  const bestsellers = list.slice(0,4);

  // Produk di kartu hero melayang — bisa dipilih admin (hero.featuredProductId), default produk unggulan pertama
  const heroCard = (() => {
    if (hero.featuredProductId) { const f = list.find(p => String(p.id) === String(hero.featuredProductId)); if (f) return f; }
    return featured[0] || null;
  })();

  const spotConf = home.spotlight || {};
  const spotlight = (() => {
    if (spotConf.productId) {
      const f = list.find(p => String(p.id) === String(spotConf.productId));
      if (f) return f;
    }
    return list.find(p => p.badge === "BEST SELLER") || list[0] || null;
  })();
  const spotImg = spotlight ? ((Array.isArray(spotlight.images) && spotlight.images[0]) || spotlight.image || fallbackImg) : fallbackImg;

  const categories = [
    { id:"tote", label:t("Tote Bag","Tote Bag") }, { id:"shoulder", label:t("Shoulder Bag","Shoulder Bag") },
    { id:"sling", label:t("Sling Bag","Sling Bag") }, { id:"handbag", label:t("Hand Bag","Hand Bag") },
    { id:"pouch", label:t("Pouch","Pouch") }, { id:"charm", label:t("Charm","Charm") },
  ].map(c => {
    const inCat = list.filter(p => p.category === c.id);
    const im = inCat[0] ? ((Array.isArray(inCat[0].images) && inCat[0].images[0]) || inCat[0].image) : null;
    return { ...c, count:inCat.length, img: im || fallbackImg };
  }).filter(c => c.count > 0).slice(0,5);

  // ── Reveal on scroll ─────────────────────────────────────
  React.useEffect(() => {
    const els = document.querySelectorAll(".lh-reveal:not(.in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold:0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [productsReady, list.length]);

  // ── Styles ───────────────────────────────────────────────
  const wrap = { maxWidth:1200, margin:"0 auto", padding:"0 24px" };
  const sec  = { padding:"140px 0 88px" };
  const secWrap = { maxWidth:1200, margin:"0 auto", padding:"140px 24px 88px" };
  const kicker = { fontFamily:"'Inter',sans-serif", fontSize:12, fontWeight:600, color:ACCENT, letterSpacing:"0.14em", textTransform:"uppercase", marginBottom:16 };
  const h2style = { fontFamily:"'Fraunces',serif", fontSize:"clamp(32px,4.3vw,54px)", fontWeight:400, letterSpacing:"-0.01em", lineHeight:1.05, color:"#1d1d1f", margin:0 };
  const viewAll = { fontFamily:"'Inter',sans-serif", fontSize:14, fontWeight:600, color:"#1d1d1f", cursor:"pointer", whiteSpace:"nowrap" };
  const btnPrimary = { fontFamily:"'Inter',sans-serif", fontSize:15, fontWeight:600, padding:"15px 30px", borderRadius:30, cursor:"pointer", border:"none", background:"#1d1d1f", color:"#fff", transition:"transform 0.2s, box-shadow 0.2s" };
  const btnGhost   = { fontFamily:"'Inter',sans-serif", fontSize:15, fontWeight:600, padding:"15px 30px", borderRadius:30, cursor:"pointer", background:"#fff", color:"#1d1d1f", border:"1px solid #ececf0" };

  const SectionHead = ({ k, title, withView }) => (
    <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom:38, gap:16 }}>
      <div><div style={kicker}>{k}</div><h2 style={h2style}>{title}</h2></div>
      {withView && <span style={viewAll} onClick={() => setPage("catalog")}>{t("View all","Lihat semua")} →</span>}
    </div>
  );

  const renderTitle = () => {
    if (heroAccent && heroTitle.includes(heroAccent)) {
      const i = heroTitle.indexOf(heroAccent);
      return (<>{heroTitle.slice(0,i)}<span style={{ fontStyle:"italic", color:ACCENT }}>{heroAccent}</span>{heroTitle.slice(i+heroAccent.length)}</>);
    }
    return heroTitle;
  };

  return (
    <div style={{ background:"#fff" }}>
      {/* ── HERO ── */}
      <header style={{ position:"relative", overflow:"hidden", padding:"92px 0 68px",
        background:"radial-gradient(1100px 540px at 78% -8%,#f3ebe3,transparent 60%),linear-gradient(180deg,#fbfbfd,#fff)" }}>
        <div className="lh-hero-grid" style={wrap}>
          <div>
            <span style={{ display:"inline-flex", gap:8, alignItems:"center", background:"#fff", border:"1px solid #ececf0", color:"#6e6e73", fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:500, padding:"7px 8px 7px 14px", borderRadius:30, marginBottom:30, boxShadow:"0 2px 10px rgba(0,0,0,0.04)" }}>
              <b style={{ background:ACCENT, color:"#fff", borderRadius:20, fontSize:11, fontWeight:600, padding:"3px 9px" }}>{t("New","Baru")}</b>{heroPill}
            </span>
            <h1 style={{ fontFamily:"'Fraunces',serif", fontSize:"clamp(54px,6.6vw,96px)", fontWeight:400, lineHeight:1.07, letterSpacing:"-0.015em", margin:"0 0 28px", color:"#1d1d1f" }}>
              {renderTitle()}
            </h1>
            <p style={{ fontFamily:"'Inter',sans-serif", fontSize:18, color:"#6e6e73", maxWidth:440, lineHeight:1.65, margin:"0 0 36px" }}>{heroSubtitle}</p>
            <div style={{ display:"flex", gap:12, flexWrap:"wrap", alignItems:"center" }}>
              <button style={btnPrimary} onClick={() => setPage("catalog")}
                onMouseEnter={e=>{e.currentTarget.style.transform="translateY(-2px)";e.currentTarget.style.boxShadow="0 18px 50px rgba(20,20,30,0.18)";}}
                onMouseLeave={e=>{e.currentTarget.style.transform="none";e.currentTarget.style.boxShadow="none";}}>{heroBtn1} →</button>
              <button style={btnGhost} onClick={() => setPage("catalog")}>{heroBtn2}</button>
            </div>
            <div style={{ display:"flex", gap:24, marginTop:34, flexWrap:"wrap" }}>
              {heroStats.map((s,i) => (
                <div key={i} style={{ display:"flex", flexDirection:"column" }}>
                  <b style={{ fontFamily:"'Inter',sans-serif", fontSize:22, fontWeight:700, color:"#1d1d1f" }}>{s.value}</b>
                  <span style={{ fontFamily:"'Inter',sans-serif", fontSize:12, color:"#6e6e73" }}>{s.label}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="lh-hero-visual" style={{ position:"relative" }}>
            <div style={{ aspectRatio:"4/5", borderRadius:28, overflow:"hidden", background:"#f5f5f7", boxShadow:"0 30px 80px rgba(20,20,30,0.16)" }}>
              <img src={heroImg} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
            </div>
            {heroCard && (
              <div className="lh-hide-mobile" onClick={() => { setSelectedProduct(heroCard); setPage("product"); }}
                style={{ position:"absolute", left:-18, bottom:54, display:"flex", alignItems:"center", gap:12, cursor:"pointer",
                  background:"rgba(255,255,255,0.85)", backdropFilter:"blur(12px)", border:"1px solid rgba(255,255,255,0.6)", borderRadius:16, boxShadow:"0 18px 50px rgba(20,20,30,0.10)", padding:"12px 16px" }}>
                <div style={{ width:42, height:42, borderRadius:12, overflow:"hidden", flexShrink:0 }}>
                  <img src={(Array.isArray(heroCard.images)&&heroCard.images[0])||heroCard.image} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
                </div>
                <div>
                  <div style={{ fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:600 }}>{heroCard.name}</div>
                  <div style={{ fontFamily:"'Inter',sans-serif", fontSize:12, color:"#6e6e73" }}>{formatPrice(heroCard.price)}</div>
                </div>
              </div>
            )}
            <div className="lh-hide-mobile" style={{ position:"absolute", right:-14, top:42, display:"flex", alignItems:"center", gap:9,
              background:"rgba(255,255,255,0.85)", backdropFilter:"blur(12px)", border:"1px solid rgba(255,255,255,0.6)", borderRadius:16, boxShadow:"0 18px 50px rgba(20,20,30,0.10)", padding:"12px 16px" }}>
              <span style={{ color:"#f5a623", fontSize:13 }}>★★★★★</span>
              <b style={{ fontFamily:"'Inter',sans-serif", fontSize:14 }}>4.9</b>
              <span style={{ fontFamily:"'Inter',sans-serif", fontSize:11, color:"#6e6e73" }}>/ 5.0</span>
            </div>
          </div>
        </div>
      </header>

      {/* ── MARQUEE ── */}
      {showMarquee && (
        <div style={{ borderTop:"1px solid #ececf0", borderBottom:"1px solid #ececf0", overflow:"hidden", whiteSpace:"nowrap", padding:"16px 0", background:"#fafafb" }}>
          <div className="lh-marquee-track">
            {[...marqueeItems, ...marqueeItems].map((m,i) => (
              <span key={i} style={{ margin:"0 30px", fontFamily:"'Inter',sans-serif", fontSize:14, color:"#6e6e73", fontWeight:500 }}>✦ <b style={{ color:"#1d1d1f" }}>{m}</b></span>
            ))}
          </div>
        </div>
      )}

      {/* ── NEW ARRIVALS ── */}
      <section className="lh-sec lh-reveal" style={secWrap}>
        <SectionHead k={t("COLLECTION","KOLEKSI")} title={t("New Arrivals","Produk Terbaru")} withView />
        <div className="lh-grid4">
          {productsReady
            ? featured.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>
      </section>

      {/* ── SPOTLIGHT ── */}
      {showSpotlight && spotlight && (
        <section className="lh-sec lh-reveal" style={secWrap}>
          <div className="lh-spot" style={{ background:"#1d1d1f", color:"#fff", borderRadius:28, overflow:"hidden" }}>
            <div style={{ minHeight:440, overflow:"hidden" }}>
              <img src={spotImg} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
            </div>
            <div style={{ padding:"60px 56px", display:"flex", flexDirection:"column", justifyContent:"center" }}>
              <div style={{ fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:600, color:"#f0c89a", marginBottom:14 }}>{spotConf.eyebrow || t("★ FEATURED","★ PRODUK UNGGULAN")}</div>
              <h2 style={{ fontFamily:"'Fraunces',serif", fontSize:"clamp(32px,3.8vw,50px)", fontWeight:400, letterSpacing:"-0.01em", lineHeight:1.1, marginBottom:16 }}>{spotlight.name}</h2>
              <p style={{ color:"#a1a1a6", fontFamily:"'Inter',sans-serif", fontSize:16, lineHeight:1.6, marginBottom:24, maxWidth:380 }}>{spotConf.blurb || spotlight.description || t("A timeless piece, crafted to last.","Pilihan abadi yang dibuat untuk menemani setiap langkahmu.")}</p>
              <div style={{ fontFamily:"'Inter',sans-serif", fontSize:24, fontWeight:700, marginBottom:26 }}>{formatPrice(spotlight.price)}</div>
              <button style={{ ...btnPrimary, background:"#fff", color:"#1d1d1f", alignSelf:"flex-start" }}
                onClick={() => { setSelectedProduct(spotlight); setPage("product"); }}>{t("View Detail","Lihat Detail")} →</button>
            </div>
          </div>
        </section>
      )}

      {/* ── CATEGORIES ── */}
      {showCategories && categories.length > 0 && (
        <section className="lh-sec lh-reveal" style={secWrap}>
          <SectionHead k={t("EXPLORE","JELAJAHI")} title={t("Shop by Category","Belanja per Kategori")} />
          <div className="lh-cat-mosaic">
            {categories.map((c,i) => (
              <div key={c.id} onClick={() => setPage("catalog")}
                style={{ borderRadius:22, overflow:"hidden", position:"relative", cursor:"pointer", minHeight:160 }}
                onMouseEnter={e=>{const im=e.currentTarget.querySelector("img"); if(im) im.style.transform="scale(1.06)";}}
                onMouseLeave={e=>{const im=e.currentTarget.querySelector("img"); if(im) im.style.transform="none";}}>
                <img src={c.img} alt={c.label} style={{ width:"100%", height:"100%", objectFit:"cover", transition:"transform 0.6s ease" }} />
                <div style={{ position:"absolute", inset:0, background:"linear-gradient(180deg,transparent 45%,rgba(0,0,0,0.6))", display:"flex", flexDirection:"column", justifyContent:"flex-end", padding:22, color:"#fff" }}>
                  <b style={{ fontFamily:"'Inter',sans-serif", fontSize:20, fontWeight:600 }}>{c.label}</b>
                  <span style={{ fontFamily:"'Inter',sans-serif", fontSize:13, opacity:0.85 }}>{c.count} {t("items","produk")}</span>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ── BEST SELLERS ── */}
      {showBestsellers && (
        <section className="lh-sec lh-reveal" style={secWrap}>
          <SectionHead k={t("TOP PICKS","PILIHAN TERBAIK")} title={t("Best Sellers","Terlaris")} withView />
          <div className="lh-grid4">
            {productsReady
              ? bestsellers.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>
        </section>
      )}

      {/* ── TESTIMONIALS ── */}
      {showTestimonials && (
        <section className="lh-sec lh-reveal" style={{ ...sec, background:"#fafafb" }}>
          <div style={wrap}>
            <div style={{ textAlign:"center", marginBottom:44 }}>
              <div style={{ ...kicker, marginBottom:8 }}>{t("CUSTOMER REVIEWS","ULASAN PELANGGAN")}</div>
              <h2 style={h2style}>{t("Loved by 10,000+ women","Dicintai 10.000+ wanita")}</h2>
            </div>
            <div className="lh-rgrid">
              {testimonials.map((r,i) => (
                <div key={i} style={{ background:"#fff", border:"1px solid #ececf0", borderRadius:22, padding:28 }}>
                  <div style={{ color:"#f5a623", fontSize:14, marginBottom:14 }}>★★★★★</div>
                  <p style={{ fontFamily:"'Inter',sans-serif", fontSize:15, lineHeight:1.6, color:"#3a3a3c", marginBottom:20 }}>"{r.text}"</p>
                  <div style={{ display:"flex", alignItems:"center", gap:12 }}>
                    <div style={{ width:42, height:42, borderRadius:"50%", background:"#f3ebe3", color:ACCENT, display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontFamily:"'Inter',sans-serif" }}>
                      {(r.name||"?").split(" ").map(w=>w[0]).slice(0,2).join("")}
                    </div>
                    <div>
                      <b style={{ fontFamily:"'Inter',sans-serif", fontSize:14, display:"block" }}>{r.name}</b>
                      <span style={{ fontFamily:"'Inter',sans-serif", fontSize:12, color:"#6e6e73" }}>{r.city}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── NEWSLETTER ── */}
      {showNewsletter && (
        <div className="lh-reveal" style={{ position:"relative", overflow:"hidden", borderRadius:28, textAlign:"center", padding:"80px 24px", margin:"0 24px",
          background:"linear-gradient(135deg,#201d1b,#14110f)", color:"#fff" }}>
          <div style={{ position:"absolute", width:420, height:420, borderRadius:"50%", background:"radial-gradient(circle,rgba(169,116,79,0.45),transparent 65%)", top:-180, right:-120 }} />
          <h2 style={{ position:"relative", fontFamily:"'Fraunces',serif", fontSize:"clamp(30px,4.2vw,50px)", fontWeight:400, letterSpacing:"-0.01em", maxWidth:"18ch", margin:"0 auto 14px", lineHeight:1.14 }}>{nlTitle}</h2>
          <p style={{ position:"relative", color:"#a1a1a6", fontFamily:"'Inter',sans-serif", fontSize:17, marginBottom:30 }}>{nlSubtitle}</p>
          <form onSubmit={(e)=>{e.preventDefault(); alert(t("Thank you for subscribing!","Terima kasih sudah mendaftar!"));}}
            style={{ position:"relative", display:"flex", gap:10, maxWidth:440, margin:"0 auto" }}>
            <input type="email" required placeholder={t("Your email address","Alamat email kamu")}
              style={{ flex:1, background:"rgba(255,255,255,0.1)", border:"1px solid rgba(255,255,255,0.2)", borderRadius:30, padding:"15px 22px", color:"#fff", fontSize:15, fontFamily:"'Inter',sans-serif", outline:"none" }} />
            <button type="submit" style={{ ...btnPrimary, background:"#fff", color:"#1d1d1f" }}>{t("Subscribe","Daftar")}</button>
          </form>
        </div>
      )}

      {/* ── FOOTER ── */}
      <footer style={{ padding:"60px 24px 36px", background:"#f5f5f7", marginTop:84 }}>
        <div className="lh-fgrid" style={{ maxWidth:1200, margin:"0 auto", paddingBottom:36, borderBottom:"1px solid #ececf0" }}>
          <div>
            <img src="uploads/logo-1777527805215.jpg" alt="LOPOBYA" style={{ height:34, marginBottom:14 }} />
            <p style={{ fontFamily:"'Inter',sans-serif", fontSize:14, color:"#6e6e73", lineHeight:1.6, maxWidth:240 }}>{t("Premium women's bags made in Indonesia, for the modern woman.","Tas wanita premium buatan Indonesia, untuk wanita modern yang bergerak dengan gaya.")}</p>
          </div>
          {[
            { title:t("Shop","Belanja"), links:[t("All Products","Semua Produk"),"Tote Bag","Shoulder Bag","Sling Bag","Pouch & Charm"] },
            { title:t("Info","Info"), links:[t("About Us","Tentang Kami"),t("Contact","Kontak"),t("Track Order","Lacak Pesanan"),t("Terms","Syarat & Ketentuan"),t("Privacy","Privasi")] },
            { title:t("Help","Bantuan"), links:[t("How to Shop","Cara Belanja"),t("Shipping","Pengiriman"),t("Returns","Pengembalian"),"FAQ"] },
          ].map((col,i) => (
            <div key={i}>
              <h4 style={{ fontFamily:"'Inter',sans-serif", fontSize:13, fontWeight:600, marginBottom:14, color:"#1d1d1f" }}>{col.title}</h4>
              {col.links.map((l,j) => (
                <span key={j} onClick={() => setPage(i===1 && j===0 ? "about" : i===1 && j===1 ? "contact" : "catalog")}
                  style={{ display:"block", fontFamily:"'Inter',sans-serif", fontSize:14, color:"#6e6e73", marginBottom:10, cursor:"pointer" }}
                  onMouseEnter={e=>e.target.style.color="#1d1d1f"} onMouseLeave={e=>e.target.style.color="#6e6e73"}>{l}</span>
              ))}
            </div>
          ))}
        </div>
        <div style={{ maxWidth:1200, margin:"22px auto 0", display:"flex", justifyContent:"space-between", flexWrap:"wrap", gap:8, fontFamily:"'Inter',sans-serif", fontSize:13, color:"#6e6e73" }}>
          <span>© 2026 LOPOBYA. {t("All rights reserved.","Hak cipta dilindungi.")}</span>
          <span>{t("Made with ♥ in Indonesia","Dibuat dengan ♥ di Indonesia")}</span>
        </div>
      </footer>
    </div>
  );
};
Object.assign(window, { HomePage });
