// Xedap.vn homepage — reference layout: hero carousel, category tiles, brand wall,
// four category product sections (rich cards), dual promo banners, closing hero.
const { Button, Badge, PriceTag, Rating, ColorSwatches, IconButton, ProductCard } = window.XedapVnDesignSystem_03b1c0;

/* ---------- Hero carousel ---------- */
function Hero({ onExplore }) {
  const { HERO_SLIDES } = window.KitData;
  const [i, setI] = React.useState(0);
  const [muted, setMuted] = React.useState(true);
  const vidRef = React.useRef(null);
  const slides = HERO_SLIDES;
  const s = slides[i];
  const go = (d) => setI((p) => (p + d + slides.length) % slides.length);
  React.useEffect(() => { if (vidRef.current) vidRef.current.muted = muted; }, [muted, i]);
  React.useEffect(() => {
    if (s.type !== "image") return;
    const t = setTimeout(() => go(1), 6000);
    return () => clearTimeout(t);
  }, [i]);
  return (
    <section style={{ position: "relative", width: "100%", height: "82vh", overflow: "hidden", background: "#0b0d12" }}>
      {s.type === "video" ? (
        <video ref={vidRef} key={s.src} src={s.src} autoPlay muted playsInline onEnded={() => go(1)} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.85 }} />
      ) : (
        <img key={s.src} src={s.src} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.85 }} />
      )}
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(9,11,16,.82) 0%, rgba(9,11,16,.45) 42%, rgba(9,11,16,0) 70%)" }} />
      <div style={{ position: "relative", width: "100%", margin: "0 auto", height: "100%", padding: "0 72px", boxSizing: "border-box", display: "flex", flexDirection: "column", justifyContent: "center", gap: "clamp(20px, 2.4vh, 32px)" }}>
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "rgba(255,255,255,.75)" }}>{s.eyebrow}</span>
        <h1 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "clamp(56px, 7vw, 88px)", lineHeight: 0.98, letterSpacing: "-0.02em", color: "#fff", textTransform: "uppercase" }}>
          {s.title.map((t, k) => <span key={k} style={{ display: "block" }}>{t}</span>)}
        </h1>
        <p style={{ margin: 0, maxWidth: 460, fontSize: 18, lineHeight: 1.6, color: "rgba(255,255,255,.8)" }}>{s.body}</p>
        <div style={{ paddingTop: 8 }}><Button size="lg" onClick={onExplore}>Mua ngay</Button></div>
      </div>
      <button aria-label="Trước" onClick={() => go(-1)} style={arrowStyle("left")}><i className="ph ph-arrow-left" /></button>
      <button aria-label="Sau" onClick={() => go(1)} style={arrowStyle("right")}><i className="ph ph-arrow-right" /></button>
      {s.type === "video" && (
        <button aria-label={muted ? "Bật âm thanh" : "Tắt âm thanh"} onClick={() => setMuted((m) => !m)} style={{ position: "absolute", right: 24, bottom: 24, width: 44, height: 44, borderRadius: "var(--radius-pill)", border: "1.5px solid rgba(255,255,255,.5)", background: "rgba(255,255,255,.06)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, cursor: "pointer", backdropFilter: "blur(2px)", zIndex: 6 }}>
          <i className={muted ? "ph ph-speaker-slash" : "ph ph-speaker-high"} />
        </button>
      )}
      <div style={{ position: "absolute", bottom: 24, left: 0, right: 0, display: "flex", justifyContent: "center", gap: 20 }}>
        {slides.map((_, k) => (
          <button key={k} onClick={() => setI(k)} style={{ background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: k === i ? "#fff" : "rgba(255,255,255,.45)", borderBottom: k === i ? "2px solid var(--primary)" : "2px solid transparent", padding: "0 2px 4px" }}>
            {String(k + 1).padStart(2, "0")}
          </button>
        ))}
      </div>
    </section>
  );
}
const arrowStyle = (side) => ({
  position: "absolute", top: "50%", [side]: 24, transform: "translateY(-50%)",
  width: 56, height: 42, borderRadius: 5, border: "1.5px solid rgba(255,255,255,.5)",
  background: "rgba(255,255,255,.06)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
  fontSize: 20, cursor: "pointer", backdropFilter: "blur(2px)", transition: "background var(--dur) var(--ease-out)",
});

/* ---------- Category tiles (auto-scroll carousel) ---------- */
function CategoryTiles({ onPick }) {
  const { TILES, IMG } = window.KitData;
  const VISIBLE = 4;
  const maxIndex = Math.max(0, TILES.length - VISIBLE);
  const [index, setIndex] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setIndex((i) => (i >= maxIndex ? 0 : i + 1)), 2800);
    return () => clearInterval(id);
  }, [paused, maxIndex]);

  return (
    <section style={{ background: "#fff", position: "relative" }} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", transform: `translateX(-${index * (100 / VISIBLE)}%)`, transition: "transform .6s cubic-bezier(.4,0,.2,1)" }}>
          {TILES.map((t) => (
            <div key={t.title} style={{ flex: `0 0 ${100 / VISIBLE}%`, boxSizing: "border-box", position: "relative", aspectRatio: "1/1", overflow: "hidden", background: t.bg, display: "flex", flexDirection: "column", justifyContent: "space-between", padding: 24 }}>
              <img src={t.img || IMG(t.seed, 640, 640)} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
              <div style={{ position: "absolute", inset: 0, background: t.bg === "#f4f4f5" ? "linear-gradient(180deg, rgba(255,255,255,.55) 0%, rgba(255,255,255,0) 45%)" : "linear-gradient(180deg, rgba(0,0,0,.45) 0%, rgba(0,0,0,.1) 45%, rgba(0,0,0,.35) 100%)" }} />
              <div style={{ position: "relative" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: t.fg, opacity: 0.7 }}>{t.eyebrow}</div>
                <div style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 24, lineHeight: 1.05, color: t.fg, textTransform: "uppercase", marginTop: 4 }}>{t.title}</div>
              </div>
              <a onClick={(e) => { e.preventDefault(); onPick && onPick(); }} style={{ position: "relative", display: "inline-flex", alignItems: "center", gap: 10, cursor: "pointer", textDecoration: "none" }}>
                <span style={{ width: 30, height: 30, borderRadius: "var(--radius-pill)", background: "var(--primary)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 15, flexShrink: 0 }}><i className="ph ph-plus" /></span>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: t.fg }}>Khám phá</span>
              </a>
            </div>
          ))}
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "center", gap: 8, padding: "16px 0" }}>
        {Array.from({ length: maxIndex + 1 }).map((_, i) => (
          <button key={i} onClick={() => setIndex(i)} aria-label={`Nhóm ${i + 1}`} style={{ width: i === index ? 24 : 8, height: 8, borderRadius: "var(--radius-pill)", border: "none", cursor: "pointer", background: i === index ? "var(--primary)" : "var(--border)", transition: "width .3s, background .3s", padding: 0 }} />
        ))}
      </div>
    </section>
  );
}

/* ---------- Brand wall ---------- */
function BrandWall() {
  const { PARTNERS } = window.KitData;
  const loop = [...PARTNERS, ...PARTNERS];
  return (
    <section style={{ background: "#fff", borderBottom: "1px solid var(--border)", overflow: "hidden" }}>
      <style>{`@keyframes brandwall-scroll{from{transform:translateX(0)}to{transform:translateX(-50%)}}.brandwall-track:hover{animation-play-state:paused}`}</style>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "36px 0", position: "relative", maskImage: "linear-gradient(90deg,transparent,#000 6%,#000 94%,transparent)", WebkitMaskImage: "linear-gradient(90deg,transparent,#000 6%,#000 94%,transparent)" }}>
        <div className="brandwall-track" style={{ display: "flex", width: "max-content", alignItems: "center", gap: 56, animation: "brandwall-scroll 40s linear infinite" }}>
          {loop.map((b, i) => (
            <div key={i} style={{ height: 56, flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <img src={b} alt={`Partner ${(i % PARTNERS.length) + 1}`} loading="lazy" style={{ height: "100%", width: "auto", objectFit: "contain" }} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Rich product card ---------- */
function SectionCard({ product, onAdd, onOpen }) {
  const { IMG } = window.KitData;
  const p = product;
  return <ProductCard product={{ ...p, image: p.img || IMG(p.seed, 480, 360) }} onAdd={onAdd} onClick={() => onOpen && onOpen(p)} />;
}

/* ---------- Category section: promo panel + 3 cards ---------- */
function CategorySection({ section, onAdd, onOpen, onCategory, onBrand }) {
  const { IMG } = window.KitData;
  const pr = section.promo;
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "24px 12px 8px" }}>
        <h2 style={{ margin: "0 0 20px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 26, letterSpacing: "-0.01em", color: "var(--foreground)" }}>{section.title}</h2>
        <div style={{ display: "grid", gridTemplateColumns: "280px repeat(3,1fr)", gap: 20 }}>
          <div style={{ position: "relative", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "#111827", minHeight: 380, display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: 24 }}>
            <img src={pr.img || IMG(pr.seed, 560, 760)} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.7 }} />
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(17,24,39,.15) 0%, rgba(17,24,39,.85) 100%)" }} />
            <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 14 }}>
              <span style={{ fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "rgba(255,255,255,.7)" }}>{pr.eyebrow}</span>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 30, lineHeight: 1.02, color: "#fff", textTransform: "uppercase" }}>{pr.title}</span>
              <div><Button variant="secondary" onClick={onBrand || onCategory}>{pr.cta}</Button></div>
            </div>
          </div>
          {section.products.map((p) => <SectionCard key={p.slug} product={p} onAdd={onAdd} onOpen={onOpen} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- Exclusive promo banners ---------- */
function ExclusiveBanners({ onExplore }) {
  const { IMG } = window.KitData;
  const banners = [
    { tag: "Xedap.vn", img: "https://api.xedap.vn/Loc%20SEO/Banner/banner-java-2026.webp", seed: "xedap-vn-exclusive-1" },
    { tag: "Xedap.vn", img: "https://api.xedap.vn/Loc%20SEO/Banner/banner-xe-dap-dia-hinh.webp", seed: "xedap-vn-exclusive-2" },
  ];
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "48px 12px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
        {banners.map((b, k) => (
          <div key={k} style={{ position: "relative", height: 260, borderRadius: "var(--radius-lg)", overflow: "hidden", background: "#0b0d12", display: "flex", flexDirection: "column", justifyContent: "center", padding: 40 }}>
            <img src={b.img || IMG(b.seed, 900, 520)} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(11,13,18,.75) 0%, rgba(11,13,18,.25) 50%, rgba(11,13,18,0) 100%)" }} />
            <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 14, maxWidth: 300 }}>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontStyle: "italic", fontSize: 15, color: "var(--primary)" }}>{b.tag}</span>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontStyle: "italic", fontSize: 34, lineHeight: 1, color: "#fff", textTransform: "uppercase" }}>Xe cao cấp<br />đã có mặt</span>
              <div><Button onClick={onExplore}>Mua ngay</Button></div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Social feed: Cập nhật thêm từ Xedap.vn ---------- */
function SocialFeed() {
  const posts = [
    { id: "raptor-hunter-4", img: "https://cdn.hstatic.net/files/200001086651/file/tiktok_thumb__2_.png" },
    { id: "can-thi-kinh", img: "https://cdn.hstatic.net/files/200001086651/file/tiktok_thumb__1_.png" },
    { id: "trong-kinh", img: "https://cdn.hstatic.net/files/200001086651/file/tiktok_thumb__4_.png" },
    { id: "chi-nhanh", img: "https://cdn.hstatic.net/files/200001086651/file/tiktok_thumb__5_.png" },
    { id: "giant-rincon-2", img: "https://cdn.hstatic.net/files/200001086651/file/tiktok_thumb__3_.png" },
  ];
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "24px 12px 48px" }}>
        <h2 style={{ margin: "0 0 28px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 34, letterSpacing: "-0.01em", color: "var(--foreground)" }}>Cập nhật thêm từ Xedap.vn</h2>
        {/* profile row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 16, marginBottom: 28 }}>
          <span style={{ width: 56, height: 56, borderRadius: "var(--radius-pill)", background: "var(--primary)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 30, flexShrink: 0 }}><i className="ph-fill ph-person-simple-bike" /></span>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 18, color: "var(--foreground)" }}>Xedapvn</span>
            <span style={{ fontSize: 13, color: "var(--muted-foreground)" }}>xedap.vn.official</span>
            <span style={{ fontSize: 13, color: "var(--muted-foreground)" }}>37,7K follower · 246,2K lượt thích</span>
          </div>
          <a href="https://www.tiktok.com/@xedap.vn.official" target="_blank" rel="noopener" style={{ marginLeft: 12, background: "#fe2c55", color: "#fff", textDecoration: "none", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 700, padding: "11px 26px", borderRadius: "var(--radius-pill)" }}>Follow</a>
        </div>
        {/* thumbnails */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 16 }}>
          {posts.map((p) => (
            <div key={p.id} style={{ position: "relative", aspectRatio: "9/13", borderRadius: 5, overflow: "hidden", background: "#e4e4e7" }}>
              <img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function PromoRow() {
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "28px 12px", display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 24 }}>
        {[
          { img: "https://cdn.hstatic.net/files/200001188264/file/logo_brand_xedap-21.svg", lines: ["Trả chậm 0%", "trả trước 0đ"] },
          { img: "https://cdn.hstatic.net/files/200001188264/file/logo_brand_xedap-22.svg", lines: ["Miễn phí", "giao hàng"] },
          { img: "https://cdn.hstatic.net/files/200001188264/file/logo_brand_xedap-19.svg", lines: ["Bảo hành", "đến 5 năm"] },
          { img: "https://cdn.hstatic.net/files/200001188264/file/logo_brand_xedap-20.svg", lines: ["Miễn phí", "bảo dưỡng"] },
        ].map((it, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 14 }}>
            <span style={{ flexShrink: 0, width: 44, height: 44, display: "grid", placeItems: "center" }}>
              <img src={it.img} alt="" style={{ width: 44, height: 44, objectFit: "contain" }} />
            </span>
            <div style={{ width: 132 }}>
              <p style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 15, color: "var(--foreground)" }}>{it.lines[0]}</p>
              <p style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 15, color: "var(--foreground)" }}>{it.lines[1]}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function HomePage({ onAdd, onOpen, onCategory, onBrand, onCollection }) {
  const { SECTIONS } = window.KitData;
  return (
    <main>
      <Hero onExplore={onCategory} />
      <CategoryTiles onPick={onCollection || onCategory} />
      <BrandWall />
      <PromoRow />
      {SECTIONS.map((s) => <CategorySection key={s.title} section={s} onAdd={onAdd} onOpen={onOpen} onCategory={onCategory} onBrand={onBrand} />)}
      <ExclusiveBanners onExplore={onCategory} />
      <SocialFeed />
      <Hero onExplore={onCategory} />
    </main>
  );
}

Object.assign(window, { HomePage });
