/* ============================================================
   GlowMerald — Homepage
   Banner carousel + credibility & curiosity sections
   ============================================================ */
const { useState:useStateH, useEffect, useRef:useRefH } = React;

/* ---- HERO: image-only banner carousel (smooth, seamless loop) ---- */
const BANNERS = [
  { img:'assets/banner-serum.png', to:'serum', pad:'50%',    alt:'GlowMerald 6in1 Phyto Complex Serum — Six Actives, One Serum' },
  { img:'assets/banner-mask.png',  to:'mask',  pad:'56.25%', alt:'GlowMerald Luminous Skin Indulgence Hydrogel Mask' },
];

function Hero(){
  const { navigate } = useApp();
  const [i,setI] = useStateH(0);
  const [paused,setPaused] = useStateH(false);
  const n = BANNERS.length;
  const go = (idx)=> setI((idx+n)%n);
  useEffect(()=>{
    if(paused) return;
    const t = setInterval(()=> setI(p=>(p+1)%n), 5200);
    return ()=> clearInterval(t);
  },[n,paused]);
  const active = BANNERS[i];
  return (
    <section className="hero-banner">
      <div className="hb-frame" style={{ paddingBottom:active.pad }}
           onMouseEnter={()=>setPaused(true)} onMouseLeave={()=>setPaused(false)}>
        {BANNERS.map((b,idx)=>(
          <a key={idx} className={'hb-slide'+(idx===i?' active':'')}
             onClick={()=>navigate('product',b.to)} role="link" aria-label={b.alt}>
            <img src={b.img} alt={b.alt} draggable="false"/>
          </a>
        ))}
        <button className="hb-arrow left" onClick={(e)=>{e.stopPropagation(); go(i-1);}} aria-label="Sebelumnya"><Icon name="chevron" size={20} style={{ transform:'rotate(180deg)' }}/></button>
        <button className="hb-arrow right" onClick={(e)=>{e.stopPropagation(); go(i+1);}} aria-label="Berikutnya"><Icon name="chevron" size={20}/></button>
        <div className="hb-dots">
          {BANNERS.map((_,idx)=>(
            <button key={idx} className={'hb-dot'+(idx===i?' active':'')} onClick={(e)=>{e.stopPropagation(); go(idx);}} aria-label={'Banner '+(idx+1)}></button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- TRUST MARQUEE (seamless infinite loop) ---- */
const TRUST_ITEMS = [
  ['shield','Terdaftar BPOM'],
  ['leaf','Cruelty-Free'],
  ['spark','Tanpa Paraben & Sulfat'],
  ['gem','Made in Indonesia'],
  ['check','Formula Bersih'],
];
function TrustMarquee(){
  const row = (
    <div className="marquee-row" aria-hidden="false">
      {TRUST_ITEMS.map(([ic,t],i)=>(
        <span key={i} className="marquee-item"><Icon name={ic} size={16}/> {t}<span className="marquee-sep">✦</span></span>
      ))}
    </div>
  );
  return (
    <div className="trust-marquee">
      <div className="marquee-track">{row}{row}</div>
    </div>
  );
}

/* ---- PRODUCT VIDEO SHOWCASE (tabs · video left · explanation right) ---- */
function ProductShowcase(){
  const { navigate, addToCart, toast } = useApp();
  const tabs = [
    { item:findItem('serum'), tab:'6-in-1 Serum', cap:'Beauty shot · 6-in-1 Phyto Complex Serum' },
    { item:findItem('mask'),  tab:'Hydrogel Mask', cap:'Beauty shot · Luminous Hydrogel Mask' },
  ];
  const [active,setActive] = useStateH(0);
  const { item, cap } = tabs[active];
  const switchTab=(i)=>{ setActive(i); };
  // p.showcaseVideo can be added later (real beauty-shot video); falls back to placeholder
  const videoSrc = item.showcaseVideo;
  return (
    <section className="section showcase-band">
      <div className="container">
        <SectionHead eyebrow="Lihat Lebih Dekat" title="Kenali setiap detailnya"
          sub="Tonton bagaimana setiap produk bekerja, lalu temukan mana yang paling sesuai untuk kulitmu."/>
        <div className="showcase-tabs">
          {tabs.map((t,i)=>(
            <button key={i} className={'sc-tab'+(i===active?' active':'')} onClick={()=>switchTab(i)}>{t.tab}</button>
          ))}
        </div>
        <div className="showcase-grid">
          <div className="sc-video">
            {videoSrc ? (
              <video key={item.id} src={videoSrc} controls playsInline poster={item.poster} style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }}></video>
            ) : (
              <button className="sc-video-ph" onClick={()=>toast('Video beauty shot segera hadir','play')} aria-label="Putar video">
                <span className="sc-play"><Icon name="play" size={28} fill/></span>
                <span className="sc-cap">Video Segera Hadir<small>{cap}</small></span>
              </button>
            )}
          </div>
          <div className="sc-info">
            <span className="sc-type">{item.type}</span>
            <h3 className="sc-name">{item.name}</h3>
            <p className="ital sc-tagline">{item.tagline}</p>
            <p className="muted sc-desc">{item.desc}</p>
            <ul className="sc-benefits">
              {item.benefits.map((b,i)=>(
                <li key={i}><span className="sc-bic"><Icon name="check" size={12} stroke={2.4}/></span>{b}</li>
              ))}
            </ul>
            <a className="link-gold sc-link" onClick={()=>navigate('product',item.id)}>Pelajari Selengkapnya <Icon name="arrow" size={15}/></a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- ABOUT BAND (intrigue: brand origin) ---- */
function AboutBand(){
  const { navigate } = useApp();
  return (
    <section className="section about-band-wrap">
      <div className="container about-band">
        <div className="about-img">
          <EditorialPH label="Still life · Serum & Emerald" tone="cream" style={{ position:'absolute', inset:0 }}/>
          <span className="about-stamp">Est. 2026<br/><span className="ital">Jakarta</span></span>
        </div>
        <div className="about-copy">
          <div className="eyebrow">Brand Baru · Cerita Kami</div>
          <h2>Lahir dari <span className="ital">Emerald.</span></h2>
          <p className="muted" style={{ fontWeight:300, fontSize:'1.02rem', maxWidth:460 }}>
            Namanya berasal dari <span className="ital">Glow</span> dan <span className="ital">Emerald</span> — batu permata hijau yang melambangkan ketenangan, kemurnian, dan keseimbangan. Sebuah filosofi yang kami tuangkan ke dalam setiap formula.
          </p>
          <p className="muted" style={{ fontWeight:300, maxWidth:460 }}>
            Kami percaya setiap orang berhak bersinar dengan caranya sendiri. Inilah awal dari sebuah ritual yang baru.
          </p>
          <button className="btn-pill" onClick={()=>navigate('about')}>Selengkapnya <Icon name="arrow" size={15}/></button>
        </div>
      </div>
    </section>
  );
}

/* ---- FEATURED COLLECTION ---- */
function FeaturedCard({ item }){
  const { navigate, addToCart } = useApp();
  const [added,setAdded] = useStateH(false);
  const add=(e)=>{ e.stopPropagation(); addToCart(item.id); setAdded(true); setTimeout(()=>setAdded(false),1200); };
  return (
    <div className="fcard">
      <div className="fcard-media" onClick={()=>navigate('product',item.id)}>
        {item.bestSeller && <span className="badge-best">Best Seller</span>}
        <ProductVisual kind={item.visual}/>
      </div>
      <div className="fcard-body">
        <div className="fcard-name" onClick={()=>navigate('product',item.id)}>{item.name}</div>
        <div className="fcard-sub">{item.tagline || item.sub}</div>
        <div className="fcard-foot">
          <span className="fcard-price">{formatRp(item.price)}</span>
          <button className={'add-round'+(added?' added':'')} onClick={add} aria-label="Tambah ke keranjang">
            <Icon name={added?'check':'plus'} size={17}/>
          </button>
        </div>
      </div>
    </div>
  );
}
function Featured(){
  const { navigate } = useApp();
  const items=[findItem('serum'), findItem('mask'), findItem('starter-duo'), findItem('double-glow')];
  return (
    <section className="section" style={{ paddingTop:72 }}>
      <div className="container">
        <div className="feat-head">
          <div><div className="eyebrow" style={{ margin:0 }}>Signature Collection</div><h2 style={{ marginTop:8 }}>Koleksi pilihan kami</h2></div>
          <a className="link-gold" onClick={()=>navigate('shop')}>Lihat Semua Produk <Icon name="arrow" size={15}/></a>
        </div>
        <div className="feat-grid">{items.map(p=><FeaturedCard key={p.id} item={p}/>)}</div>
      </div>
    </section>
  );
}

/* ---- INGREDIENT SPOTLIGHT (curiosity + credibility) ---- */
function IngredientSpotlight(){
  const { navigate } = useApp();
  const six = PRODUCTS[0].ingredients;
  return (
    <section className="section ingredient-band">
      <div className="container">
        <div className="ing-spot-head">
          <div className="eyebrow on-dark">6 Kekuatan Aktif Pilihan</div>
          <h2 style={{ color:'var(--on-dark)' }}>Apa yang membuatnya <span className="ital c-gold">bekerja.</span></h2>
          <p className="hero-sub" style={{ fontWeight:300, maxWidth:520, margin:'14px auto 0' }}>
            Phyto Complex Technology memadukan enam bahan aktif yang bekerja sinergis dalam satu tetes. Inilah rahasia di balik glow yang terjaga.
          </p>
        </div>
        <div className="ing-spot-grid">
          {six.map((name,i)=>(
            <div key={name} className="ing-spot-card">
              <span className="ing-spot-num">{String(i+1).padStart(2,'0')}</span>
              <div className="ing-spot-name">{name}</div>
              <p className="ing-spot-desc">{INGREDIENTS[name]}</p>
            </div>
          ))}
        </div>
        <div className="center" style={{ marginTop:40 }}>
          <button className="btn-pill gold" onClick={()=>navigate('product','serum')}>Jelajahi Serum <Icon name="arrow" size={15}/></button>
        </div>
      </div>
    </section>
  );
}

/* ---- SHOPPING CONFIDENCE (slim strip, distinct from pillar grid) ---- */
function CredNumbers(){
  const items=[
    { ic:'truck',  t:'Pengiriman ke Seluruh Indonesia' },
    { ic:'gem',    t:'Pembayaran Aman & Fleksibel' },
    { ic:'shield', t:'Produk Resmi Terdaftar BPOM' },
    { ic:'check',  t:'Kemasan Aman Terlindungi' },
  ];
  return (
    <section className="section" style={{ paddingTop:8, paddingBottom:8 }}>
      <div className="container">
        <div className="confidence-strip">
          {items.map((it,i)=>(
            <div key={i} className="conf-item">
              <span className="conf-ic"><Icon name={it.ic} size={20} stroke={1.5}/></span>
              <span className="conf-t">{it.t}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- ROUTINE BAND ---- */
function RoutineBand(){
  const { navigate } = useApp();
  const checks=['Dipersonalisasi untuk kebutuhan kulitmu','Diformulasikan dengan bahan aktif pilihan','Mendukung kulit sehat dari dalam'];
  return (
    <section className="section">
      <div className="container">
        <div className="routine-band">
          <div className="deco-circle" style={{ width:240, height:240, top:-80, left:-60, opacity:.14 }}></div>
          <div className="routine-copy">
            <h2 style={{ color:'var(--on-dark)' }}>Bangun ritual<br/>kulitmu yang ideal.</h2>
            <p className="hero-sub" style={{ fontWeight:300, maxWidth:380, marginTop:14 }}>Temukan rangkaian yang sesuai dengan kebutuhan kulitmu — sederhana, cerdas, dan terasa premium.</p>
            <ul className="routine-checks">
              {checks.map((c,i)=>(<li key={i}><span className="rc-ic"><Icon name="check" size={13} stroke={2.2}/></span>{c}</li>))}
            </ul>
            <button className="btn-pill gold" onClick={()=>navigate('shop')}>Mulai Belanja <Icon name="arrow" size={15}/></button>
          </div>
          <div className="routine-visual">
            <EditorialPH label="Product trio · Emerald" tone="emerald" style={{ position:'absolute', inset:0 }}/>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- SOCIAL PROOF ---- */
function SocialProof(){
  return (
    <section className="section" style={{ background:'var(--cream-deep)' }}>
      <div className="container">
        <SectionHead eyebrow="Dipercaya Pelanggan" title="Cerita kulit yang bersinar" sub="Pengalaman nyata dari ritual harian mereka."/>
        <div className="testi-grid">
          {TESTIMONIALS.map((t,i)=>(
            <div key={i} className="testi-card">
              <Stars value={t.rating}/>
              <p className="ital" style={{ fontSize:'1.02rem', color:'var(--ink)', margin:'14px 0 18px', lineHeight:1.5 }}>“{t.quote}”</p>
              <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                <Avatar name={t.name} size={42}/>
                <div><div style={{ fontWeight:500, fontSize:'.9rem' }}>{t.name}</div><div className="muted" style={{ fontSize:'.74rem' }}>{t.city} · {t.concern}</div></div>
              </div>
            </div>
          ))}
        </div>
        <div className="hr-gold" style={{ margin:'56px auto', maxWidth:120 }}></div>
        <h3 className="center serif" style={{ fontSize:'1.6rem', marginBottom:8 }}>Before &amp; After</h3>
        <p className="center muted" style={{ marginBottom:34, fontWeight:300 }}>Hasil bertahap dengan pemakaian rutin.</p>
        <div className="ba-grid">
          {BEFORE_AFTER.map((ba,i)=>(
            <div key={i} className="ba-card">
              <div className="ba-images">{ba.stages.map((s,j)=><div key={j} className="ba-frame"><EditorialPH label={s} tone="cream" style={{ aspectRatio:'3/4' }}/></div>)}</div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:14 }}>
                <span style={{ fontWeight:500, fontSize:'.9rem' }}>{ba.name}</span><span className="chip ghost-gold">{ba.concern}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- INSIGHT TEASER ---- */
function InsightTeaser(){
  const { navigate } = useApp();
  return (
    <section className="section">
      <div className="container">
        <div className="feat-head">
          <div><div className="eyebrow">Beauty Insight</div><h2 style={{ marginTop:6 }}>Pengetahuan sebelum perawatan</h2></div>
          <a className="link-gold" onClick={()=>navigate('insight')}>Lihat Semua <Icon name="arrow" size={15}/></a>
        </div>
        <div className="grid grid-3">{ARTICLES.slice(0,3).map(a=><ArticleCard key={a.id} article={a}/>)}</div>
      </div>
    </section>
  );
}

/* ---- NEWSLETTER / BE THE FIRST (intrigue) ---- */
function Newsletter(){
  const { toast } = useApp();
  const [email,setEmail] = useStateH('');
  const [done,setDone] = useStateH(false);
  const submit=(e)=>{ e.preventDefault(); if(!email.trim()||!email.includes('@')){ toast('Masukkan email yang valid'); return; } setDone(true); toast('Terima kasih — kamu termasuk yang pertama','spark'); };
  return (
    <section className="section">
      <div className="container">
        <div className="news-band">
          <div className="deco-circle" style={{ width:280, height:280, bottom:-120, right:-80, opacity:.16 }}></div>
          <div className="news-inner">
            <span className="pill-eyebrow gold-pill">Akses Awal</span>
            <h2>Jadilah yang pertama.</h2>
            <p className="muted" style={{ fontWeight:300, maxWidth:480, margin:'12px auto 26px' }}>
              Sebagai brand baru, kami menyiapkan sesuatu yang istimewa. Daftar untuk penawaran perdana, peluncuran produk, dan rahasia ritual sebelum siapa pun.
            </p>
            {done ? (
              <div className="news-done"><Icon name="check" size={18}/> Kamu sudah terdaftar. Sampai jumpa di inbox.</div>
            ) : (
              <form className="news-form" onSubmit={submit}>
                <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="Alamat email kamu"/>
                <button type="submit" className="btn btn-gold">Daftar</button>
              </form>
            )}
            <p className="muted" style={{ fontSize:'.72rem', marginTop:14, marginBottom:0 }}>Tanpa spam. Berhenti kapan saja.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- UGC ---- */
function UGCStrip(){
  return (
    <section style={{ paddingBottom:80 }}>
      <div className="container"><p className="center eyebrow" style={{ marginBottom:24 }}>#GlowMerald · @glowmeraldofficial</p></div>
      <div className="ugc-strip">
        {UGC.map((u,i)=>(<div key={i} className="ugc-tile"><Placeholder label="UGC" style={{ position:'absolute', inset:0 }}/><span className="ugc-user"><Icon name="ig" size={13}/> {u}</span></div>))}
      </div>
    </section>
  );
}

function HomePage(){
  return (
    <div>
      <Hero/>
      <TrustMarquee/>
      <Featured/>
      <ProductShowcase/>
      <AboutBand/>
      <RoutineBand/>
      <SocialProof/>
      <InsightTeaser/>
      <CredNumbers/>
    </div>
  );
}

Object.assign(window, { HomePage, Hero });
