// 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, ProductCardCp } = 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 === "video") 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 === "placeholder" ? (
        <div key={"ph" + i} style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(135deg,#14171f 0 22px,#191d27 22px 44px)" }}>
          <span style={{ position: "absolute", right: 24, bottom: 76, whiteSpace: "nowrap", fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: ".08em", textTransform: "uppercase", color: "rgba(255,255,255,.45)", border: "1px dashed rgba(255,255,255,.28)", borderRadius: 4, padding: "10px 18px" }}>Banner {String(i + 1).padStart(2, "0")} — chờ bổ sung ảnh/video</span>
        </div>
      ) : 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(calc(13px + 43px*var(--ts)), 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: "calc(13px + 5px*var(--ts))", 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: "calc(13px + 7px*var(--ts))", 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: "calc(13px + 7px*var(--ts))", cursor: "pointer", backdropFilter: "blur(2px)", transition: "background var(--dur) var(--ease-out)",
});

/* ---------- Category tiles (ô đầu ghim, phần còn lại trượt) ---------- */
function renderCategoryTile(t, IMG, onPick, basis) {
  return (
    <div style={{ flex: `0 0 ${basis}`, 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: "calc(13px + 11px*var(--ts))", lineHeight: 1.05, color: t.fg, textTransform: "uppercase", marginTop: 4 }}>{t.title}</div>
      </div>
      <a onClick={(e) => { e.preventDefault(); if (t.finder) { window.location.href = "./find-your-bike.html"; return; } 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: "calc(13px + 2px*var(--ts))", flexShrink: 0 }}><i className={t.finder ? "ph ph-magnifying-glass" : "ph ph-plus"} /></span>
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: t.fg }}>{t.finder ? "Tìm xe phù hợp" : "Khám phá"}</span>
      </a>
    </div>
  );
}

/* ---------- Category tiles (auto-scroll carousel) ---------- */
function CategoryTiles({ onPick }) {
  const { TILES, IMG } = window.KitData;
  const trackRef = React.useRef(null);
  const [trackW, setTrackW] = React.useState(1200);
  React.useEffect(() => {
    const el = trackRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(([e]) => setTrackW(e.contentRect.width));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  const VISIBLE = Math.max(1, Math.min(4, Math.floor(trackW / 250) || 1));
  // Ô đầu tiên được ghim cố định; chỉ các ô còn lại trượt.
  const pinned = TILES[0];
  const sliding = TILES.slice(1);
  const slideVisible = Math.max(1, VISIBLE - 1);
  const maxIndex = Math.max(0, sliding.length - slideVisible);
  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 ref={null} style={{ display: "flex" }}>
        <div style={{ flex: `0 0 ${100 / VISIBLE}%`, minWidth: 0 }}>{renderCategoryTile(pinned, IMG, onPick, "100%")}</div>
        <div style={{ flex: 1, minWidth: 0, overflow: "hidden" }}>
        <div style={{ display: "flex", transform: `translateX(-${index * (100 / slideVisible)}%)`, transition: "transform .6s cubic-bezier(.4,0,.2,1)" }}>
          {sliding.map((t) => (
            <div key={t.title} style={{ flex: `0 0 ${100 / slideVisible}%`, 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: "calc(13px + 11px*var(--ts))", lineHeight: 1.05, color: t.fg, textTransform: "uppercase", marginTop: 4 }}>{t.title}</div>
              </div>
              <a onClick={(e) => { e.preventDefault(); if (t.finder) { window.location.href = "./find-your-bike.html"; return; } 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: "calc(13px + 2px*var(--ts))", flexShrink: 0 }}><i className={t.finder ? "ph ph-magnifying-glass" : "ph ph-plus"} /></span>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: t.fg }}>{t.finder ? "Tìm xe phù hợp" : "Khám phá"}</span>
              </a>
            </div>
          ))}
        </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];
  const scrollRef = React.useRef(null);
  const pausedRef = React.useRef(false);
  const dragRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    let raf;
    const step = () => {
      if (!pausedRef.current && !dragRef.current) {
        el.scrollLeft += 0.5;
        const half = el.scrollWidth / 2;
        if (el.scrollLeft >= half) el.scrollLeft -= half;
      }
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, []);

  const onPointerDown = (e) => {
    const el = scrollRef.current;
    dragRef.current = { x: e.clientX, left: el.scrollLeft, moved: false };
    el.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    const el = scrollRef.current;
    const dx = e.clientX - d.x;
    if (Math.abs(dx) > 3) d.moved = true;
    let next = d.left - dx;
    const half = el.scrollWidth / 2;
    if (next < 0) next += half; else if (next >= half) next -= half;
    el.scrollLeft = next;
  };
  const endDrag = (e) => {
    const el = scrollRef.current;
    if (dragRef.current) { try { el.releasePointerCapture(e.pointerId); } catch (_) {} }
    dragRef.current = null;
  };

  return (
    <section id="home-brandwall" style={{ background: "#fff", borderBottom: "1px solid var(--border)", overflow: "hidden" }}>
      <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
          ref={scrollRef}
          onMouseEnter={() => { pausedRef.current = true; }}
          onMouseLeave={() => { pausedRef.current = false; }}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={endDrag}
          onPointerCancel={endDrag}
          style={{ display: "flex", alignItems: "center", gap: 56, overflowX: "auto", scrollbarWidth: "none", cursor: "grab", touchAction: "pan-y", userSelect: "none" }}
        >
          {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" draggable={false} style={{ height: "100%", width: "auto", objectFit: "contain", pointerEvents: "none" }} />
            </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: "calc(13px + 13px*var(--ts))", 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: "calc(13px + 17px*var(--ts))", 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://cdn.hstatic.net/files/200001086651/file/48_6df1156ec5cc4486842d1af6715028f2.png", seed: "xedap-vn-exclusive-1" },
    { tag: "Xedap.vn", img: "https://cdn.hstatic.net/files/200001086651/file/49.png", 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: "color-mix(in srgb, var(--primary) 78%, #000)", 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(0,0,0,.55) 0%, rgba(0,0,0,.2) 50%, transparent 100%)" }} />
            <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 14, maxWidth: 300 }}>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontStyle: "italic", fontSize: "calc(13px + 21px*var(--ts))", 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: "calc(13px + 21px*var(--ts))", letterSpacing: "-0.01em", color: "var(--foreground)" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 14 }}><svg viewBox="0 0 512 512" aria-label="TikTok" role="img" style={{ width: "1em", height: "1em", display: "block", fill: "currentColor" }}><path d="M412.19,118.66a109.27,109.27,0,0,1-9.45-5.5,132.87,132.87,0,0,1-24.27-20.62c-18.1-20.71-24.86-41.72-27.35-56.43h.1C349.14,23.9,350,16,350.13,16H267.69V334.78c0,4.28,0,8.51-.18,12.69,0,.52-.05,1-.08,1.56,0,.23,0,.47-.05.71,0,.06,0,.12,0,.18a70,70,0,0,1-35.22,55.56,68.8,68.8,0,0,1-34.11,9c-38.41,0-69.54-31.32-69.54-70s31.13-70,69.54-70a68.9,68.9,0,0,1,21.41,3.39l.1-83.94a153.14,153.14,0,0,0-118,34.52,161.79,161.79,0,0,0-35.3,43.53c-3.48,6-16.61,30.11-18.2,69.24-1,22.21,5.67,45.22,8.85,54.73v.2c2,5.6,9.75,24.71,22.38,40.82A167.53,167.53,0,0,0,115,470.66v-.2l.2.2C155.11,497.78,199.36,496,199.36,496c7.66-.31,33.32,0,62.46-13.81,32.32-15.31,50.72-38.12,50.72-38.12a158.46,158.46,0,0,0,27.64-45.93c7.46-19.61,9.95-43.13,9.95-52.53V176.49c1,.6,14.32,9.41,14.32,9.41s19.19,12.3,49.13,20.31c21.48,5.7,50.42,6.9,50.42,6.9V131.27C453.86,132.37,433.27,129.17,412.19,118.66Z"/></svg>Cập nhật thêm từ Xedap.vn</span></h2>
        {/* profile row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 16, marginBottom: 28 }}>
          <img src="https://cdn.hstatic.net/files/200001188264/file/guideline_xedapvn-11__1_.png" alt="Xedapvn" style={{ width: 56, height: 56, borderRadius: "var(--radius-pill)", objectFit: "cover", flexShrink: 0 }} />
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 5px*var(--ts))", 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: "calc(13px + 1px*var(--ts))", 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: "calc(13px + 2px*var(--ts))", color: "var(--foreground)" }}>{it.lines[0]}</p>
              <p style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 2px*var(--ts))", color: "var(--foreground)" }}>{it.lines[1]}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------- Closing showroom CTA (giống trang blog) ---------- */
function HomeStoreCTA() {
  return (
    <section style={{ margin: "8px 0 0" }}>
      <div style={{ position: "relative", height: 340, overflow: "hidden", background: "#0b0d12" }}>
        <img src="https://cdn.hstatic.net/files/200001086651/file/xedap_-_hinh_demo_ui_ux__2_.png" 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(11,13,18,.15),rgba(11,13,18,.72))" }} />
        <div style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", alignItems: "flex-end", justifyContent: "center", textAlign: "right", padding: "0 56px" }}>
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".16em", color: "rgba(255,255,255,.85)", marginBottom: 10 }}>HỆ THỐNG SHOWROOM</span>
          <h2 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 21px*var(--ts))", lineHeight: 1.05, color: "#fff", maxWidth: 420 }}>Ghé thăm Xedap.vn Store</h2>
          <p style={{ margin: "14px 0 0", maxWidth: 380, fontSize: "calc(13px + 2px*var(--ts))", lineHeight: 1.6, color: "rgba(255,255,255,.8)" }}>32 showroom trên toàn quốc — trải nghiệm, chạy thử và nhận tư vấn trực tiếp từ chuyên gia.</p>
          <div style={{ marginTop: 22 }}><a href="./cua-hang.html"><Button>Xem cửa hàng</Button></a></div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Scroll-to-top arrow (xuất hiện khi cuộn quá 1/3 trang) ---------- */
function ScrollTopButton() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => {
      const bw = document.getElementById("home-brandwall");
      setShow(bw ? bw.getBoundingClientRect().bottom < 0 : false);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, []);
  return (
    <button
      aria-label="Lên đầu trang"
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
      style={{
        position: "fixed", right: 28, bottom: 28, zIndex: 90,
        width: 60, height: 52, borderRadius: 14, border: "1.5px solid rgba(255,255,255,.55)", cursor: "pointer",
        background: "rgba(11,13,18,.22)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "calc(13px + 9px*var(--ts))",
        backdropFilter: "blur(4px)", WebkitBackdropFilter: "blur(4px)",
        opacity: show ? 1 : 0, transform: show ? "translateY(0)" : "translateY(16px)", pointerEvents: show ? "auto" : "none",
        transition: "opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out)",
      }}
    >
      <i className="ph ph-arrow-up" />
    </button>
  );
}

/* ---------- Flash sale (tab đỏ + đếm ngược + carousel) ---------- */
const FLASH_TABS = [
  { key: "flash", label: "SẢN PHẨM HOT TREND" },
  { key: "new", label: "HÀNG MỚI VỀ" },
];
const FLASH_SLOTS = [
  { label: "Đang diễn ra", time: "09:00 - 23:59" },
  { label: "Ngày mai", time: "00:00 - 23:59" },
];

function FlashCard({ product, sold, quota, onOpen, onAdd }) {
  const { IMG } = window.KitData;
  return (
    <div className="xdp-flash-card" style={{ display: "flex", flexDirection: "column", height: "100%", boxSizing: "border-box", background: "#fff", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
      <style>{`.xdp-flash-card > div > *{border:none!important;border-radius:0!important;box-shadow:none!important}`}</style>
      <div style={{ flex: 1, display: "flex" }}>
        <ProductCardCp style={{ flex: 1, width: "100%", minWidth: 0 }} product={{ ...product, image: product.img || IMG(product.seed, 480, 360), status: product.status || "Hàng mới về", notes: product.notes || [product.gift, "Trả góp 0% - 0đ phụ phí - 0đ trả trước - kỳ hạn đến 12 tháng"].filter(Boolean), delivery: product.delivery ?? "2 Giờ" }} onClick={() => onOpen && onOpen(product)} />
      </div>
    </div>
  );
}

function HomeFlashSale({ onOpen, onAdd, perView, noBorder, rows, onSeeAll }) {
  const ROWS = Math.max(1, rows || 1);
  const { PRODUCTS } = window.KitData;
  const [tab, setTab] = React.useState("flash");
  const [slotIdx, setSlotIdx] = React.useState(0);
  const [page, setPage] = React.useState(0);
  const [left, setLeft] = React.useState(9 * 3600 + 13 * 60 + 20);
  React.useEffect(() => {
    const id = setInterval(() => setLeft((s) => (s <= 0 ? 12 * 3600 : s - 1)), 1000);
    return () => clearInterval(id);
  }, []);
  React.useEffect(() => setPage(0), [tab, slotIdx]);
  const [shown, setShown] = React.useState(0);
  const pad = (n) => String(n).padStart(2, "0");
  const digits = [pad(Math.floor(left / 3600)), pad(Math.floor((left % 3600) / 60)), pad(left % 60)];
  const POOL_SIZE = ROWS > 1 ? 20 : 10;
  const pool = tab === "flash" ? PRODUCTS.slice(0, POOL_SIZE) : [...PRODUCTS].slice(-POOL_SIZE).reverse();
  const items = pool.map((p, i) => ({ p, sold: [0, 3, 7, 12, 5, 9, 2, 14, 6, 1][i % 10], quota: [10, 20, 50, 30, 20, 10, 20, 100, 20, 10][i % 10] }));
  const trackRef = React.useRef(null);
  const [trackW, setTrackW] = React.useState(1200);
  React.useEffect(() => {
    const el = trackRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(([e]) => setTrackW(e.contentRect.width));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  const VISIBLE = perView ? Math.max(1, Math.min(perView, items.length)) : Math.max(1, Math.min(4, Math.floor(trackW / 250) || 1));
  const PER_PAGE = VISIBLE * ROWS;
  const pages = Math.max(1, Math.ceil(items.length / PER_PAGE));
  const go = (d) => setPage((p) => (p + d + pages) % pages);
  React.useEffect(() => setShown(PER_PAGE), [tab, slotIdx, PER_PAGE]);
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "24px 12px 40px", position: "relative" }}>
        {/* gray stage */}
        <div style={{ margin: "34px 0 0", border: noBorder ? "none" : "5px solid var(--primary)", borderRadius: 22, background: "#cfcfcf", padding: "12px" }}>
          {/* blue header bar, overlapping the stage */}
          <div style={{ position: "relative", margin: "-56px 0 22px", minHeight: 96, borderRadius: 12, background: "var(--primary)", display: "flex", alignItems: "center", flexWrap: "wrap", rowGap: 12, columnGap: "clamp(16px,2vw,28px)", padding: "14px clamp(16px,2.2vw,34px)", boxSizing: "border-box", zIndex: 2 }}>
            <span style={{ position: "relative", paddingRight: "0.18em", display: "inline-flex", alignItems: "center", flexShrink: 0, fontFamily: "var(--font-heading)", fontWeight: 900, fontStyle: "italic", fontSize: "clamp(calc(13px + 13px*var(--ts)),2.6vw,38px)", letterSpacing: "-0.01em", color: "transparent", backgroundImage: "linear-gradient(100deg,#ffd400 0%,#ffd400 42%,#fffceb 50%,#ffd400 58%,#ffd400 100%)", backgroundSize: "260% 100%", WebkitBackgroundClip: "text", backgroundClip: "text", animation: "fsShine 2.6s cubic-bezier(.4,0,.2,1) infinite" }}>
              F<i className="ph-fill ph-lightning" style={{ fontSize: "1.05em", margin: "0 -2px", color: "#ffd400" }} />ASHSALE
            </span>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", minWidth: 0 }}>
              {FLASH_TABS.map((t) => {
                const on = t.key === tab;
                return (
                  <button key={t.key} onClick={() => setTab(t.key)} style={{ cursor: "pointer", whiteSpace: "nowrap", borderRadius: "var(--radius-pill)", border: "2px solid #fff", padding: "11px clamp(14px,1.6vw,28px)", fontFamily: "var(--font-sans)", fontSize: "clamp(13px,1.2vw,17px)", fontWeight: 800, textTransform: "uppercase", letterSpacing: ".01em", background: on ? "#fff" : "transparent", color: on ? "var(--primary)" : "#fff", transition: "background .2s, color .2s" }}>{t.label}</button>
                );
              })}
            </div>
            <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: "clamp(16px,2.4vw,34px)", flexWrap: "wrap", minWidth: 0 }}>
              <div style={{ textAlign: "center", color: "#fff" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em", opacity: .95 }}>Kết thúc trong</div>
                <div style={{ marginTop: 6, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "var(--font-mono)", fontSize: "clamp(calc(13px + 3px*var(--ts)),1.5vw,20px)", fontWeight: 700 }}>
                  {digits.map((d, k) => (
                    <React.Fragment key={k}>
                      {k > 0 && <span style={{ opacity: .8 }}>:</span>}
                      <span>{d}</span>
                    </React.Fragment>
                  ))}
                </div>
              </div>
              {FLASH_SLOTS.map((s, i) => (
                <button key={s.label} onClick={() => setSlotIdx(i)} style={{ cursor: "pointer", border: "none", background: "none", padding: 0, textAlign: "center", color: "#fff", opacity: i === slotIdx ? 1 : .72 }}>
                  <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600 }}>{s.label}</div>
                  <div style={{ marginTop: 6, fontFamily: "var(--font-mono)", fontSize: "clamp(13px,1.25vw,17px)", fontWeight: 700, whiteSpace: "nowrap" }}>{s.time}</div>
                  <div style={{ marginTop: 6, height: 3, borderRadius: 2, background: i === slotIdx ? "#fff" : "transparent" }} />
                </button>
              ))}
            </div>
          </div>
          {/* carousel */}
          <div ref={trackRef} style={{ position: "relative", overflow: "hidden", borderRadius: 8 }}>
            {ROWS > 1 ? (
              <div style={{ display: "grid", gridTemplateColumns: `repeat(${VISIBLE},minmax(0,1fr))`, gap: 12 }}>
                {items.slice(0, shown).map((it, i) => (
                  <div key={tab + page + i} style={{ minWidth: 0 }}>
                    <FlashCard product={it.p} sold={it.sold} quota={it.quota} onOpen={onOpen} onAdd={onAdd} />
                  </div>
                ))}
              </div>
            ) : (
            <div style={{ display: "flex", transition: "transform .5s cubic-bezier(.4,0,.2,1)", transform: `translateX(-${page * 100}%)` }}>
              {items.map((it) => (
                <div key={it.p.slug} style={{ flex: `0 0 ${100 / VISIBLE}%`, minWidth: 0, boxSizing: "border-box", padding: "0 6px" }}>
                  <FlashCard product={it.p} sold={it.sold} quota={it.quota} onOpen={onOpen} onAdd={onAdd} />
                </div>
              ))}
            </div>
            )}
            {ROWS === 1 && pages > 1 && (
              <React.Fragment>
                <button aria-label="Trước" onClick={() => go(-1)} style={flashArrow("left")}><i className="ph ph-caret-left" /></button>
                <button aria-label="Sau" onClick={() => go(1)} style={flashArrow("right")}><i className="ph ph-caret-right" /></button>
              </React.Fragment>
            )}
          </div>
          {((ROWS > 1 && shown < items.length) || onSeeAll) && (
            <div style={{ display: "flex", justifyContent: "center", marginTop: 14 }}>
              <button onClick={() => (onSeeAll ? onSeeAll() : setShown((n) => n + PER_PAGE))} style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 40, padding: "0 26px", borderRadius: "var(--radius-md)", border: "1px solid var(--border)", background: "#fff", color: "var(--foreground)", fontFamily: "var(--font-sans)", fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 700, cursor: "pointer" }}>Xem thêm sản phẩm <i className="ph ph-caret-right" style={{ fontSize: 13 }} /></button>
            </div>
          )}
          <p style={{ margin: "16px 0 4px", textAlign: "center", fontFamily: "var(--font-sans)", fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 500, color: "#3f3f46" }}>Chỉ áp dụng thanh toán online thành công — Mỗi SĐT chỉ được mua 1 sản phẩm cùng loại · Không áp dụng cùng ưu đãi khác</p>
        </div>
      </div>
    </section>
  );
}
const flashArrow = (side) => ({
  position: "absolute", top: "50%", [side]: 0, transform: "translateY(-50%)",
  width: 30, height: 30, border: "none", cursor: "pointer", borderRadius: "50%",
  background: "rgba(255,255,255,.95)", color: "#27272a", fontSize: "calc(13px + 5px*var(--ts))",
  boxShadow: "0 2px 8px rgba(0,0,0,.18)",
  display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3,
});

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

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