// Home_page_cp — homepage biến thể theo layout sàn TMĐT: hero 3 cột (rail + slider + cột phải),
// dải gợi ý, flashsale, các khối danh mục (banner dọc + tab + lưới 4x2), video, ưu đãi, tin tức.
// Header/footer dùng chung từ design system (xem Home_page_cp.html).
const { ProductCardCp: HomePageCpProductCard } = window.XedapVnDesignSystem_03b1c0;
const useHomecpMobile = () => window.useMq("(max-width: 767px)");
const useHomecpCompact = () => window.useMq("(max-width: 1024px)");

const HOMECP_MENU = [
  { label: "Xe đạp thể thao đường phố", icon: "ph-bicycle" },
  { label: "Xe đạp địa hình", icon: "ph-mountains" },
  { label: "Xe đạp đua", icon: "ph-flag-checkered" },
  { label: "Xe đạp gấp", icon: "ph-arrows-in" },
  { label: "Xe trợ lực điện", icon: "ph-lightning" },
  { label: "Xe đạp nữ", icon: "ph-heart" },
  { label: "Xe đạp trẻ em", icon: "ph-baby" },
  { label: "Khung sườn", icon: "ph-frame-corners" },
  { label: "Phụ kiện cho người đạp", icon: "ph-t-shirt" },
  { label: "Phụ kiện cho xe", icon: "ph-toolbox" },
  { label: "Phụ tùng thay thế", icon: "ph-gear-six" },
  { label: "Bảo trì – bảo dưỡng", icon: "ph-wrench" },
];

const HOMECP_MEGA_DEFAULT = {
  cols: [
    { title: "Theo dòng xe", items: ["Xe phổ thông", "Xe cao cấp", "Hàng nhập khẩu", "Xe trưng bày"] },
    { title: "Theo mức giá", items: ["Dưới 5 triệu", "5 – 10 triệu", "10 – 20 triệu", "20 – 40 triệu", "Trên 40 triệu"] },
  ],
  banner: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_tro_luc.png",
};
const HOMECP_MEGA = {
  "Xe đạp thể thao đường phố": { banner: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_do_thi_cate.png", cols: [
    { title: "Theo kiểu xe", items: ["Touring", "Hybrid / City", "Gravel", "Fixed gear", "Single speed"] },
    { title: "Theo cỡ bánh", items: ["700C", "27.5 inch", "26 inch", "24 inch"] },
  ] },
  "Xe đạp địa hình": { banner: "https://cdn.hstatic.net/files/200001086651/file/xe_dia_h_nh_cate.png", cols: [
    { title: "Theo hệ thống phuộc", items: ["Hardtail", "Full suspension", "Rigid"] },
    { title: "Theo cỡ bánh", items: ["29 inch", "27.5 inch", "26 inch", "24 inch"] },
  ] },
  "Xe đạp đua": { banner: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_duong_dai_cate.png", cols: [
    { title: "Theo chất liệu khung", items: ["Carbon", "Nhôm", "Thép Cr-Mo"] },
    { title: "Theo nhóm truyền động", items: ["Shimano 105", "Shimano Ultegra", "Shimano Tiagra", "SRAM Rival", "Campagnolo"] },
  ] },
  "Xe đạp gấp": { cols: [
    { title: "Theo cỡ bánh", items: ["14 inch", "16 inch", "20 inch", "22 inch"] },
    { title: "Theo nhu cầu", items: ["Đi làm nội đô", "Mang lên xe buýt", "Du lịch", "Gấp siêu nhẹ"] },
  ] },
  "Xe trợ lực điện": { cols: [
    { title: "Theo kiểu xe", items: ["E-city", "E-MTB", "E-folding", "E-cargo"] },
    { title: "Theo quãng đường", items: ["Dưới 40 km", "40 – 70 km", "70 – 100 km", "Trên 100 km"] },
  ] },
  "Xe đạp nữ": { cols: [
    { title: "Theo kiểu dáng", items: ["Xe mini", "City bike", "Xe cổ điển", "Có giỏ trước"] },
    { title: "Theo chiều cao", items: ["Dưới 1m50", "1m50 – 1m60", "1m60 – 1m70", "Trên 1m70"] },
  ] },
  "Xe đạp trẻ em": { cols: [
    { title: "Theo độ tuổi", items: ["2 – 4 tuổi", "4 – 6 tuổi", "6 – 9 tuổi", "9 – 12 tuổi"] },
    { title: "Theo cỡ bánh", items: ["12 inch", "14 inch", "16 inch", "18 inch", "20 inch"] },
  ] },
  "Khung sườn": { cols: [
    { title: "Theo chất liệu", items: ["Carbon", "Nhôm", "Thép Cr-Mo", "Titanium"] },
    { title: "Theo dòng xe", items: ["Khung MTB", "Khung Road", "Khung Gravel", "Khung Fixed gear"] },
  ] },
  "Phụ kiện cho người đạp": { cols: [
    { title: "Trang bị", items: ["Mũ bảo hiểm", "Găng tay", "Kính mắt", "Giày đạp xe"] },
    { title: "Quần áo", items: ["Áo đạp xe", "Quần đệm mông", "Áo gió", "Tất – khăn đa năng"] },
  ] },
  "Phụ kiện cho xe": { cols: [
    { title: "Tiện ích", items: ["Đèn xe", "Khoá chống trộm", "Bình nước & gá", "Baga – giỏ"] },
    { title: "Điện tử", items: ["Đồng hồ tốc độ", "Cảm biến nhịp", "Camera hành trình", "Chuông – còi"] },
  ] },
  "Phụ tùng thay thế": { cols: [
    { title: "Truyền động", items: ["Xích – líp", "Đùi đĩa", "Củ đề", "Bàn đạp"] },
    { title: "Bánh & phanh", items: ["Vành xe", "Lốp – săm", "Phanh đĩa", "Má phanh", "Moay-ơ"] },
  ] },
  "Bảo trì – bảo dưỡng": { cols: [
    { title: "Gói dịch vụ", items: ["Bảo dưỡng cơ bản", "Bảo dưỡng toàn diện", "Cân vành", "Ép bát"] },
    { title: "Vật tư", items: ["Dầu xích", "Dung dịch vệ sinh", "Dầu phanh", "Bộ dụng cụ"] },
  ] },
};

const HOMECP_IMG = {
  mtb: "https://cdn.hstatic.net/files/200001086651/file/xe_dia_h_nh_cate.png",
  city: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_do_thi_cate.png",
  ebike: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_tro_luc.png",
  road: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_duong_dai_cate.png",
};

function homecpMega(label) {
  const m = HOMECP_MEGA[label] || {};
  return { cols: m.cols || HOMECP_MEGA_DEFAULT.cols, banner: m.banner || HOMECP_MEGA_DEFAULT.banner, label };
}

function HomePageCpMegaPanel({ label, onNav, maxWidth }) {
  const data = homecpMega(label);
  const brands = (window.KitData.PARTNERS || []).slice(0, 12);
  return (
    <div style={{ position: "absolute", left: "100%", top: -1, bottom: -1, width: Math.max(420, maxWidth || 1000), boxSizing: "border-box", overflowY: "auto", background: "#fff", border: "1px solid var(--border)", padding: "22px 26px 24px", zIndex: 60 }}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(240px,1fr) minmax(200px,460px)", gap: 28, alignItems: "start" }}>
        <div>
          <div style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 7px*var(--ts))", lineHeight: 1.2, marginBottom: 16 }}>{label}</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2,minmax(0,1fr))", gap: "0 24px" }}>
            {data.cols.map((c) => (
              <div key={c.title} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div style={{ fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 700, color: "var(--foreground)" }}>{c.title}</div>
                {c.items.map((it) => (
                  <a key={it} className="homecp-mega-link" onClick={() => onNav && onNav(it)} style={{ fontSize: "calc(13px + 1px*var(--ts))", color: "var(--muted-foreground)", textDecoration: "none", cursor: "pointer" }}>{it}</a>
                ))}
              </div>
            ))}
          </div>
          <div style={{ borderTop: "1px solid var(--border)", marginTop: 18, paddingTop: 14 }}>
            <a className="homecp-seeall" onClick={() => onNav && onNav(label)} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 700, color: "var(--primary)", textDecoration: "none", cursor: "pointer" }}>Xem tất cả <i className="ph ph-caret-right" style={{ fontSize: 13 }} /></a>
          </div>
        </div>
        <a data-banner={"Banner mega menu — " + label} onClick={() => onNav && onNav(label)} style={{ display: "block", overflow: "hidden", background: "var(--muted)", cursor: "pointer" }}>
          <img src={data.banner} alt="" style={{ display: "block", width: "100%", aspectRatio: "16/9", height: "auto", maxHeight: 280, objectFit: "cover" }} />
        </a>
      </div>
      <div style={{ marginTop: 22 }}>
        <div style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 5px*var(--ts))", marginBottom: 12 }}>Thương hiệu</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 1, background: "var(--border)", border: "1px solid var(--border)" }}>
          {brands.map((b, i) => (
            <a key={i} onClick={() => onNav && onNav("brand")} style={{ background: "#fff", height: 74, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 14px", cursor: "pointer" }}>
              <img src={b} alt="" style={{ maxWidth: "100%", maxHeight: 46, objectFit: "contain" }} />
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

// Menu danh mục dùng chung: rail trang chủ + panel dropdown "Danh mục" trên header.
function HomePageCpMenu({ onNav, style, onBackdrop, fill }) {
  const [hover, setHover] = React.useState(null);
  const [avail, setAvail] = React.useState(1000);
  const navRef = React.useRef(null);
  const timer = React.useRef(null);
  const measure = () => {
    const n = navRef.current; if (!n) return;
    const page = document.getElementById("homecp-page");
    const right = page ? page.getBoundingClientRect().right - 24 : window.innerWidth - 24;
    setAvail(right - n.getBoundingClientRect().right);
  };
  React.useEffect(() => { measure(); window.addEventListener("resize", measure); return () => window.removeEventListener("resize", measure); }, []);
  const enter = (label) => { clearTimeout(timer.current); measure(); setHover(label); };
  const leave = () => { clearTimeout(timer.current); timer.current = setTimeout(() => setHover(null), 120); };
  return (
    <React.Fragment>
      {hover ? <div onMouseEnter={() => { leave(); onBackdrop && onBackdrop(); }} style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,.38)", zIndex: 1 }} /> : null}
      <nav ref={navRef} onMouseLeave={leave} style={{ position: "relative", zIndex: 2, display: "flex", flexDirection: "column", border: "1px solid var(--border)", background: "#fff", height: fill ? "100%" : "auto", boxSizing: "border-box", ...style }}>
        <a className="homecp-rail-item" href="find-your-bike.html" onMouseEnter={leave} style={{ display: "flex", alignItems: "center", gap: 10, padding: "0 14px", flex: fill ? "1 1 0" : "0 0 auto", minHeight: 39, borderBottom: "1px solid var(--border)", fontSize: "calc(13px + 0.5px*var(--ts))", fontWeight: 700, color: "var(--primary)", background: "#fff", opacity: hover ? .55 : 1, transition: "opacity .15s, background .15s", textDecoration: "none", cursor: "pointer" }}>
          <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>Gợi ý xe phù hợp với bạn</span>
          <i className="ph ph-caret-right" style={{ fontSize: 13, color: "var(--primary)" }} />
        </a>
        {HOMECP_MENU.map((m, mi) => (
          <a key={m.label} className="homecp-rail-item" onMouseEnter={() => enter(m.label)} onClick={() => onNav && onNav(m.label)} style={{ position: "relative", display: "flex", alignItems: "center", gap: 10, padding: "0 14px", flex: fill ? "1 1 0" : "0 0 auto", minHeight: 39, borderBottom: mi === HOMECP_MENU.length - 1 ? "none" : "1px solid var(--border)", fontSize: "calc(13px + 0.5px*var(--ts))", fontWeight: 700, color: hover === m.label ? "var(--primary)" : "var(--foreground)", background: hover === m.label ? "color-mix(in srgb,var(--primary) 7%,#fff)" : "#fff", opacity: hover && hover !== m.label ? .55 : 1, transition: "opacity .15s, background .15s, color .15s", textDecoration: "none", cursor: "pointer" }}>
            <i className={"ph " + m.icon} style={{ fontSize: "calc(13px + 3px*var(--ts))", color: "var(--primary)", flexShrink: 0 }} />
            <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.label}</span>
            <i className="ph ph-caret-right" style={{ fontSize: 12, color: hover === m.label ? "var(--primary)" : "var(--muted-foreground)" }} />
          </a>
        ))}
        {hover ? <HomePageCpMegaPanel label={hover} onNav={onNav} maxWidth={avail} /> : null}
      </nav>
    </React.Fragment>
  );
}

// Panel "Danh mục" của header: chính là menu trái, hiện đúng vị trí rail trên trang chủ (không cuộn trang).
function HomePageCpMenuFlyout({ onNav, onClose }) {
  const [box, setBox] = React.useState(null);
  React.useEffect(() => {
    const measure = () => {
      const el = document.getElementById("homecp-rail");
      if (el) { const r = el.getBoundingClientRect(); setBox({ left: r.left, width: r.width }); }
      else { const w = Math.min(1440, window.innerWidth); setBox({ left: (window.innerWidth - w) / 2 + 24, width: 268 }); }
    };
    measure();
    window.addEventListener("resize", measure);
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { window.removeEventListener("resize", measure); document.removeEventListener("keydown", onKey); };
  }, [onClose]);
  if (!box) return null;
  return (
    <React.Fragment>
      <div onClick={onClose} style={{ position: "fixed", inset: "106px 0 0", zIndex: 60, background: "rgba(255,255,255,.45)", backdropFilter: "blur(4px)", WebkitBackdropFilter: "blur(4px)", animation: "homecpFlyoutFade .18s var(--ease-out)" }} />
      <style>{`@keyframes homecpFlyoutFade{from{opacity:0}to{opacity:1}}`}</style>
      <div style={{ position: "fixed", top: 118, left: box.left, width: box.width, zIndex: 61, boxShadow: "0 22px 48px rgba(11,27,63,.24)" }}>
        <HomePageCpMenu onNav={onNav} fill style={{ height: 537 }} />
      </div>

    </React.Fragment>
  );
}

// (cũ) helper cuộn tới rail + làm nổi bật — giữ lại cho các trang khác nếu cần.
function homecpFocusRail() {
  window.scrollTo({ top: 0, behavior: "smooth" });
  const el = document.getElementById("homecp-rail");
  if (!el) return;
  el.classList.remove("homecp-rail-flash");
  void el.offsetWidth;
  el.classList.add("homecp-rail-flash");
  setTimeout(() => el.classList.remove("homecp-rail-flash"), 1400);
}

// Rail danh mục trên mobile: lưới icon + text, 4 cột × 2 hàng mỗi trang, vuốt ngang + dot.
function HomePageCpRailMobile({ onNav }) {
  const rail = React.useRef(null);
  const [p, setP] = React.useState(0);
  const items = [{ label: "Gợi ý xe phù hợp", icon: "ph-sparkle", href: "find-your-bike.html", accent: true }].concat(HOMECP_MENU);
  const pages = [];
  for (let i = 0; i < items.length; i += 8) pages.push(items.slice(i, i + 8));
  const onScroll = () => { const el = rail.current; if (!el) return; setP(Math.max(0, Math.min(pages.length - 1, Math.round(el.scrollLeft / (el.clientWidth || 1))))); };
  const go = (i) => { const el = rail.current; if (!el) return; el.scrollTo({ left: i * el.clientWidth, behavior: "smooth" }); setP(i); };
  const tile = (m, k) => (
    <a key={m.label} href={m.href} onClick={() => !m.href && onNav && onNav(m.label)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, minWidth: 0, padding: "2px 2px 4px", textDecoration: "none", cursor: "pointer" }}>
      <span data-banner={"Ảnh danh mục — " + m.label} title="Thả ảnh danh mục vào đây" style={{ width: 54, height: 54, display: "block", flexShrink: 0, border: "1px dashed color-mix(in srgb,var(--primary) 35%,#fff)", background: "repeating-linear-gradient(45deg,color-mix(in srgb,var(--primary) 9%,#fff) 0 6px,#fff 6px 12px)" }} />
      <span style={{ height: 41, fontSize: 11, lineHeight: 1.25, fontWeight: 600, textAlign: "center", color: m.accent ? "var(--primary)" : "var(--foreground)", display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{m.label}</span>
    </a>
  );
  return (
    <div style={{ padding: "12px 2px 8px", marginBottom: 10 }}>
      <div ref={rail} onScroll={onScroll} className="homecp-slot-rail" style={{ display: "flex", overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none" }}>
        {pages.map((pg, pi) => (
          <div key={pi} style={{ flex: "0 0 100%", scrollSnapAlign: "start", display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gridTemplateRows: "repeat(2,auto)", gap: "12px 4px", alignContent: "start", justifyItems: "center" }}>
            {pg.map(tile)}
          </div>
        ))}
      </div>
      {pages.length > 1 && (
        <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 10 }}>
          {pages.map((_, i) => (
            <button key={i} aria-label={"Trang " + (i + 1)} onClick={() => go(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 4, width: i === p ? 22 : 10, borderRadius: 999, background: i === p ? "var(--primary)" : "rgba(15,23,42,.18)", transition: "width .2s" }} />
          ))}
        </div>
      )}
    </div>
  );
}

function HomePageCpRail({ onNav }) {
  return (
    <aside id="homecp-rail" style={{ position: "relative", zIndex: 30, gridRow: "span 2" }}>
      <HomePageCpMenu onNav={onNav} fill />
    </aside>
  );
}

// ————— Hero: tab + slider giữa, cột phải (tài khoản + ưu đãi + banner), 3 banner dưới —————
const HOMECP_HERO_BANNERS = [
  "https://cdn.hstatic.net/files/200001188264/file/banner-home-1.jpg",
  "https://cdn.hstatic.net/files/200001188264/file/banner-home-2.jpg",
  "https://cdn.hstatic.net/files/200001188264/file/banner-home-3.jpg",
];
const HOMECP_HERO_SLIDES = [
  { tab: "MỪNG KHAI TRƯƠNG", tabSub: "Ưu đãi cực khủng", img: HOMECP_IMG.ebike, eyebrow: "XE TRỢ LỰC ĐIỆN", title: "Giảm đến 3 triệu", sub: "Tặng khoá chống trộm & mũ bảo hiểm", bg: "#142FF7" },
  { tab: "RAPTOR MTB 2026", tabSub: "Mở bán tặng quà", img: HOMECP_IMG.mtb, eyebrow: "MTB RAPTOR – JAVA", title: "Địa hình từ 4.99 triệu", sub: "Trả góp 0% – duyệt trong 5 phút", bg: "#0F172A" },
  { tab: "GIANT TCR SERIES", tabSub: "Siêu nhẹ, để bứt tốc", img: HOMECP_IMG.road, eyebrow: "ROAD GIANT TCR", title: "Ưu đãi hè 2026", sub: "Bảo dưỡng miễn phí trọn đời", bg: "#B91C1C" },
  { tab: "TOURING ĐI PHỐ", tabSub: "Tặng baga & giỏ xe", img: HOMECP_IMG.city, eyebrow: "TOURING – CITY BIKE", title: "Chỉ từ 3.9 triệu", sub: "Giao xe lắp sẵn trong 24 giờ", bg: "#0F172A" },
  { tab: "XE ĐẠP TRẺ EM", tabSub: "Tặng bộ bảo hộ", img: HOMECP_IMG.mtb, eyebrow: "BDD – BAMBI", title: "Chỉ từ 1.29 triệu", sub: "Tặng mũ, bọc gối và chuông xe", bg: "#B91C1C" },
  { tab: "XE GẤP & FIXED", tabSub: "Gọn cho đô thị", img: HOMECP_IMG.city, eyebrow: "XE GẤP – FIXED GEAR", title: "Giảm thêm 800K", sub: "Gấp trong 15 giây, mang lên xe buýt", bg: "#142FF7" },
  { tab: "PHỤ KIỆN CHÍNH HÃNG", tabSub: "Mua combo giảm 20%", img: HOMECP_IMG.road, eyebrow: "MŨ – ĐÈN – KHOÁ", title: "Combo giảm 20%", sub: "Hàng chính hãng, bảo hành 12 tháng", bg: "#0F172A" },
  { tab: "THU CŨ ĐỔI MỚI", tabSub: "Trợ giá đến 3 triệu", img: HOMECP_IMG.mtb, eyebrow: "THU CŨ LÊN ĐỜI", title: "Trợ giá đến 3 triệu", sub: "Định giá xe cũ miễn phí tại cửa hàng", bg: "#142FF7" },
  { tab: "BẢO DƯỠNG TRỌN GÓI", tabSub: "Giữ xe luôn như mới", img: HOMECP_IMG.ebike, eyebrow: "DỊCH VỤ KỸ THUẬT", title: "Gói năm giảm 1 triệu", sub: "Cân vành, chỉnh đề, vệ sinh truyền động", bg: "#B91C1C" },
].map((x, k) => ({ ...x, img: HOMECP_HERO_BANNERS[k % HOMECP_HERO_BANNERS.length] }));

const HOMECP_OFFER_LIST = [
  { group: "Ưu đãi cho giáo dục", items: [["ph-graduation-cap", "Đăng ký", "nhận ưu đãi"], ["ph-graduation-cap", "Deal hot", "học sinh sinh viên"], ["ph-graduation-cap", "Xe đạp", "ưu đãi khủng"]] },
  { group: "Thu cũ lên đời giá hời", items: [["ph-arrows-clockwise", "MTB trợ giá", "đến 2 triệu"], ["ph-arrows-clockwise", "Road trợ giá", "đến 3 triệu"]] },
  { group: "Khách hàng doanh nghiệp (B2B)", items: [["ph-briefcase", "Đăng ký", "X-Business"], ["ph-briefcase", "Chính sách", "ưu đãi"]] },
];

function HomePageCpHero({ onNav, mobile }) {
  const [i, setI] = React.useState(0);
  const n = HOMECP_HERO_SLIDES.length;
  React.useEffect(() => { const id = setInterval(() => setI((v) => (v + 1) % n), 5000); return () => clearInterval(id); }, [n]);
  const s = HOMECP_HERO_SLIDES[i];
  const tabsRef = React.useRef(null);
  React.useEffect(() => {
    const strip = tabsRef.current; if (!strip) return;
    const btn = strip.children[i]; if (!btn) return;
    const left = btn.offsetLeft, right = left + btn.offsetWidth;
    if (right > strip.scrollLeft + strip.clientWidth) strip.scrollLeft = right - strip.clientWidth;
    else if (left < strip.scrollLeft) strip.scrollLeft = left;
  }, [i]);
  const smalls = [
    { title: "Phụ kiện chính hãng", img: "https://cdn.hstatic.net/files/200001188264/file/banner-duoi-home-1.jpg" },
    { title: "Xe đạp trẻ em", img: "https://cdn.hstatic.net/files/200001188264/file/banner-duoi-home-2.jpg" },
    { title: "Bảo dưỡng trọn gói", img: "https://cdn.hstatic.net/files/200001188264/file/banner-duoi-home-3.jpg" },
    { title: "Hàng mới đổ bộ", img: "https://cdn.hstatic.net/files/200001188264/file/banner-duoi-home-2.jpg" },
  ];
  const [showPhone, setShowPhone] = React.useState(false);
  return (
    <React.Fragment>
      <div style={mobile
        ? { minWidth: 0, display: "flex", flexDirection: "column", background: "#fff", border: "1px solid var(--border)" }
        : { gridColumn: "2", gridRow: "1", minWidth: 0, display: "flex", flexDirection: "column", background: "#fff", border: "1px solid var(--border)" }}>
        {!mobile && (
        <div style={{ position: "relative", display: "flex", alignItems: "stretch", borderBottom: "1px solid var(--border)", background: "#F2F4F8" }}>
          <div ref={tabsRef} style={{ display: "flex", justifyContent: "center", flex: 1, minWidth: 0, overflowX: "auto", scrollbarWidth: "none", scrollBehavior: "smooth" }}>
            {HOMECP_HERO_SLIDES.map((x, k) => (
              <button key={x.tab} onClick={() => setI(k)} style={{ cursor: "pointer", border: "none", borderRight: k === n - 1 ? "none" : "1px solid var(--border)", background: k === i ? "#fff" : "transparent", padding: "8px 12px", textAlign: "center", flex: "0 0 20%", minWidth: 120, transition: "background .2s" }}>
                <span style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 12.5, textTransform: "uppercase", whiteSpace: "nowrap", color: k === i ? "var(--primary)" : "var(--muted-foreground)" }}>{x.tab}</span>
                <span style={{ display: "block", marginTop: 2, fontSize: 12, whiteSpace: "nowrap", color: k === i ? "var(--primary)" : "var(--muted-foreground)" }}>{x.tabSub}</span>
              </button>
            ))}
          </div>
          <button className="homecp-flash-arrow" aria-label="Tab tiếp theo" onClick={() => setI((v) => (v + 1) % n)} style={{ flexShrink: 0, width: 34, border: "none", borderLeft: "1px solid var(--border)", background: "#fff", color: "var(--foreground)", cursor: "pointer", fontSize: "calc(13px + 3px*var(--ts))", display: "flex", alignItems: "center", justifyContent: "center" }}><i className="ph ph-caret-right" /></button>
        </div>
        )}
        <a className="homecp-hero-stage" data-banner="Banner hero (slider chính)" data-banner-note="Ảnh demo đang objectFit: contain nên có thể chừa nền hai bên." onClick={() => onNav && onNav(s.tab)} style={{ position: "relative", display: "block", overflow: "hidden", background: s.bg, cursor: "pointer", flex: mobile ? "0 0 auto" : 1, minHeight: 0, aspectRatio: mobile ? "16/9" : "auto" }}>
          <img src={s.img} alt={s.tab} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", objectPosition: "center" }} />
          {[["left", "ph-caret-left", -1], ["right", "ph-caret-right", 1]].map(([side, icon, d]) => (
            <button key={side} className="homecp-hero-arrow" aria-label={d < 0 ? "Ảnh trước" : "Ảnh sau"} onClick={(e) => { e.preventDefault(); e.stopPropagation(); setI((v) => (v + d + n) % n); }} style={{ position: "absolute", top: "50%", [side]: 0, transform: "translateY(-50%)", width: 30, height: 62, borderRadius: side === "left" ? "0 999px 999px 0" : "999px 0 0 999px", border: 0, cursor: "pointer", background: "rgba(255,255,255,.88)", color: "#0F172A", fontSize: "calc(13px + 7px*var(--ts))", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3, boxShadow: "0 4px 14px rgba(11,27,63,.28)", opacity: 0, pointerEvents: "none", transition: "opacity .18s, background .16s" }}><i className={"ph " + icon} /></button>
          ))}
        </a>
        {mobile && (
          <div style={{ display: "flex", justifyContent: "center", gap: 6, padding: "10px 0" }}>
            {HOMECP_HERO_SLIDES.map((x, k) => (
              <button key={x.tab} aria-label={"Slide " + (k + 1)} onClick={() => setI(k)} style={{ width: k === i ? 18 : 7, height: 7, borderRadius: 999, border: "none", padding: 0, background: k === i ? "var(--primary)" : "rgba(15,23,42,.22)", cursor: "pointer", transition: "width .2s" }} />
            ))}
          </div>
        )}
      </div>

      {mobile
        ? <HomePageCpHeroSmallRail items={smalls} onNav={onNav} />
        : <div style={{ gridColumn: "2", gridRow: "2", display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", alignItems: "end", gap: 12 }}>
            {smalls.map((b) => (
              <a key={b.title} data-banner={"Banner nhỏ dưới hero — " + b.title} onClick={() => onNav && onNav(b.title)} style={{ display: "block", overflow: "hidden", cursor: "pointer", textDecoration: "none" }}>
                <img src={b.img} alt={b.title} loading="lazy" style={{ display: "block", width: "100%", height: "auto" }} />
              </a>
            ))}
          </div>}
    </React.Fragment>
  );
}

// Mobile: banner nhỏ dưới hero thành rail 1 hàng × 2 cột, swipe snap từng trang.
function HomePageCpHeroSmallRail({ items, onNav }) {
  const rail = React.useRef(null);
  const [p, setP] = React.useState(0);
  const pages = [];
  for (let i = 0; i < items.length; i += 2) pages.push(i);
  const onScroll = () => { const el = rail.current; if (!el) return; setP(Math.max(0, Math.min(pages.length - 1, Math.round(el.scrollLeft / (el.clientWidth || 1))))); };
  const go = (i) => { const el = rail.current; if (!el) return; el.scrollTo({ left: i * el.clientWidth, behavior: "smooth" }); setP(i); };
  return (
    <div style={{ marginTop: 10 }}>
      <div ref={rail} onScroll={onScroll} className="homecp-slot-rail" style={{ display: "flex", overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none" }}>
        {pages.map((start) => (
          <div key={start} style={{ flex: "0 0 100%", scrollSnapAlign: "start", display: "grid", gridTemplateColumns: "repeat(2,minmax(0,1fr))", alignItems: "end", gap: 8 }}>
            {items.slice(start, start + 2).map((b) => (
              <a key={b.title} data-banner={"Banner nhỏ dưới hero — " + b.title} onClick={() => onNav && onNav(b.title)} style={{ display: "block", overflow: "hidden", cursor: "pointer", textDecoration: "none" }}>
                <img src={b.img} alt={b.title} loading="lazy" style={{ display: "block", width: "100%", height: "auto" }} />
              </a>
            ))}
          </div>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 10 }}>
        {pages.map((_, i) => (
          <button key={i} aria-label={"Trang " + (i + 1)} onClick={() => go(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 6, width: i === p ? 20 : 6, borderRadius: 999, background: i === p ? "var(--primary)" : "rgba(15,23,42,.22)", transition: "width .2s" }} />
        ))}
      </div>
    </div>
  );
}

// ————— Card sản phẩm (ảnh thật, hover đổi màu) —————
function HomePageCpCard({ product, onAdd, onOpen, style }) {
  const [hover, setHover] = React.useState(false);
  const image = hover && product.img2 ? product.img2 : product.img;
  return (
    <div className="homecp-card" onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ display: "flex", minWidth: 0, ...style }}>
      <HomePageCpProductCard
        style={{ flex: 1, minWidth: 0 }}
        product={{
          ...product,
          image,
          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>
  );
}

// Dãy sản phẩm cuộn ngang trên mobile (thay cho lưới 5–6 cột).
const homecpRail = { display: "flex", gap: 8, overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none", paddingBottom: 6 };
const homecpRailItem = { flex: "0 0 calc((100% - 8px)/2)", scrollSnapAlign: "start" };

function homecpList(cat, brand) {
  const D = window.XedapApiData;
  const cats = cat == null ? null : [].concat(cat);
  let pool = cats ? D.PRODUCTS.filter((p) => cats.includes(p.category)) : D.PRODUCTS;
  if (brand && brand !== "Tất cả") pool = pool.filter((p) => p.brand === brand);
  return pool.length ? pool : (cats ? D.PRODUCTS.filter((p) => cats.includes(p.category)) : D.PRODUCTS);
}

// Trả tối đa n sản phẩm, không lặp lại khi kho ít hàng.
function homecpPool(cat, from = 0, brand) {
  const src = homecpList(cat, brand);
  const off = src.length ? from % src.length : 0;
  const rotated = src.slice(off).concat(src.slice(0, off));
  return (n) => rotated.slice(0, Math.min(n, rotated.length));
}

function homecpBrands(cat) {
  return [...new Set(homecpList(cat).map((p) => p.brand))].slice(0, 8);
}

// ————— Dải "Gợi ý cho bạn" —————
function HomePageCpSuggest({ onAdd, onOpen }) {
  const mobile = useHomecpMobile();
  const [page, setPage] = React.useState(0);
  const items = homecpPool(null, page * 5 + 2)(mobile ? 10 : 5);
  return (
    <section style={{ marginTop: 12, background: "color-mix(in srgb,var(--primary) 6%,#fff)", border: "2px solid var(--primary)", borderRadius: 16, padding: "0 0 14px" }}>
      <div style={{ display: "flex", justifyContent: "center" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, minHeight: 34, padding: mobile ? "0 18px" : "0 34px", background: "var(--primary)", color: "#fff", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 13.5 : 15, textTransform: "uppercase", letterSpacing: ".04em" }}><i className="ph-fill ph-sparkle" /> Gợi ý cho bạn</span>
      </div>
      <div style={{ position: "relative", padding: mobile ? "12px 10px 0" : "14px 12px 0" }}>
        <div className="homecp-slot-rail" style={mobile ? homecpRail : { display: "grid", gridTemplateColumns: "repeat(5,minmax(0,1fr))", gap: 10 }}>
          {items.map((p, i) => <HomePageCpCard key={"sg" + page + i} product={p} onAdd={onAdd} onOpen={onOpen} style={mobile ? homecpRailItem : null} />)}
        </div>
        {!mobile && (
        <button className="homecp-flash-arrow" aria-label="Sau" onClick={() => setPage((v) => (v + 1) % 4)} style={{ position: "absolute", top: "50%", right: 0, transform: "translateY(-50%)", width: 26, height: 64, border: "1px solid rgba(15,23,42,.14)", background: "rgba(255,255,255,.7)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3 }}><i className="ph ph-caret-right" /></button>
        )}
      </div>
    </section>
  );
}

// ————— Flashsale —————
const HOMECP_FLASH_TABS = [{ key: "deal", label: "Deal sốc hôm nay", activeImg: "https://cdn.hstatic.net/files/200001188264/file/deal_soc-12.png", mobileImg: "https://cdn2.cellphones.com.vn/x/media/wysiwyg/Web/landing-page/hang-moi-ve/hotDueHome-mb.png" }, { key: "hot", label: "Sản phẩm hot trend", activeImg: "https://cdn.hstatic.net/files/200001188264/file/deal_soc-13.png", mobileImg: "https://cdn2.cellphones.com.vn/x/media/wysiwyg/Web/landing-page/hang-moi-ve/hotTrendHome-mb.png" }, { key: "new", label: "Hàng mới về", activeImg: "https://cdn.hstatic.net/files/200001188264/file/deal_soc-14.png", mobileImg: "https://cdn2.cellphones.com.vn/x/media/wysiwyg/Web/landing-page/hang-moi-ve/newArrivalHome-mb.png" }];
const HOMECP_FLASH_CHIPS = [
  { label: "Tất cả", cat: null },
  { label: "Xe địa hình", cat: "Xe đạp địa hình" },
  { label: "Xe đường phố", cat: "Xe đạp thể thao đường phố" },
  { label: "Xe đua", cat: "Xe đạp đua" },
  { label: "Xe trẻ em", cat: "Xe đạp trẻ em" },
  { label: "Xe gấp & fixed", cat: ["Xe đạp gấp", "Xe đạp fixed gear"] },
];

function homecpFlashIcons(src) {
  const seen = new Map();
  src.forEach((p) => { if (!seen.has(p.brand)) seen.set(p.brand, p.img); });
  return [...seen].slice(0, 9).map(([label, img]) => ({ label, img }));
}

function HomePageCpFlash({ onAdd, onOpen }) {
  const D = window.XedapApiData;
  const mobile = useHomecpMobile();
  const [tab, setTab] = React.useState("deal");
  const [chip, setChip] = React.useState(0);
  const [brand, setBrand] = React.useState("Tất cả");
  const [page, setPage] = React.useState(0);
  const [left, setLeft] = React.useState(9 * 3600 + 9 * 60 + 48);
  React.useEffect(() => { const id = setInterval(() => setLeft((s) => (s <= 0 ? 12 * 3600 : s - 1)), 1000); return () => clearInterval(id); }, []);
  React.useEffect(() => { setPage(0); setBrand("Tất cả"); }, [tab, chip]);
  React.useEffect(() => setPage(0), [brand]);
  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 c = HOMECP_FLASH_CHIPS[chip];
  const cats = c.cat == null ? null : [].concat(c.cat);
  let base = cats ? D.PRODUCTS.filter((p) => cats.includes(p.category)) : D.PRODUCTS;
  if (tab === "new") base = [...base].reverse();
  if (tab === "hot") base = base.slice(0, Math.max(10, Math.ceil(base.length / 2)));
  const icons = homecpFlashIcons(base);
  const src = brand === "Tất cả" ? base : base.filter((p) => p.brand === brand);
  const pages = Math.max(1, Math.ceil(src.length / 5));
  const items = mobile ? src.slice(0, 10) : src.slice(page * 5, page * 5 + 5);
  const go = (d) => setPage((p) => (p + d + pages) % pages);
  const round = (side) => ({ position: "absolute", top: "50%", [side]: -6, transform: "translateY(-50%)", width: 30, height: 62, border: 0, borderRadius: side === "left" ? "0 999px 999px 0" : "999px 0 0 999px", cursor: "pointer", background: "rgba(255,255,255,.88)", color: "#0F172A", fontSize: "calc(13px + 7px*var(--ts))", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3, boxShadow: "0 4px 14px rgba(11,27,63,.28)" });
  return (
    <section style={{ marginTop: 24 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 8, alignItems: "end" }}>
        {HOMECP_FLASH_TABS.map((t) => {
          const on = t.key === tab;
          return (
            <button key={t.key} data-banner={"Ảnh tab flashsale — " + t.label} data-banner-height="74" data-banner-note="Ảnh chỉ hiện khi tab đang active (cao 74px); tab không active cao 66px." onClick={() => setTab(t.key)} style={{ cursor: "pointer", height: mobile ? (on ? 50 : 44) : (on ? 74 : 66), overflow: "hidden", padding: mobile ? "0 6px" : 0, display: "flex", alignItems: "center", justifyContent: "center", gap: mobile ? 4 : 10, borderRadius: mobile ? "10px 10px 0 0" : "16px 16px 0 0", border: "2px solid " + (on ? "var(--primary)" : "rgba(20,47,247,.16)"), borderBottom: on ? "2px solid #E4EBFF" : "2px solid rgba(20,47,247,.16)", marginBottom: on ? -2 : 0, background: on ? "#E4EBFF" : "#F7F9FF", color: "var(--primary)", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 11.5 : (on ? 24 : 22), lineHeight: 1.15, textTransform: "uppercase", letterSpacing: ".01em", position: "relative", zIndex: on ? 3 : 1, transition: "height .18s var(--ease-out), background .18s" }}>
              {on && (mobile ? t.mobileImg || t.activeImg : t.activeImg) ? (
                <img key={tab} src={mobile ? t.mobileImg || t.activeImg : t.activeImg} alt={t.label} style={{ width: "100%", height: "100%", objectFit: mobile ? "contain" : "cover", objectPosition: "center", display: "block", margin: mobile ? "0 -6px" : 0, animation: "homecpTabZoom .5s var(--ease-out) both" }} />
              ) : (
                <React.Fragment>
                  {t.key === "deal" && <i className="ph-fill ph-fire" style={{ fontSize: mobile ? 15 : 26, color: "#FF3B30" }} />}
                  {t.label}
                </React.Fragment>
              )}
            </button>
          );
        })}
      </div>
      <div style={{ position: "relative", zIndex: 2, border: "2px solid var(--primary)", borderRadius: "0 0 16px 16px", background: "#E4EBFF", padding: mobile ? "14px 10px 16px" : "18px 16px 20px" }}>
        <div className="homecp-slot-rail" style={{ display: "flex", flexWrap: mobile ? "nowrap" : "wrap", overflowX: mobile ? "auto" : "visible", justifyContent: mobile ? "flex-start" : "center", gap: 8, marginBottom: 12, scrollbarWidth: "none" }}>
          {HOMECP_FLASH_CHIPS.map((x, i) => (
            <button key={x.label} onClick={() => setChip(i)} style={{ cursor: "pointer", flex: "0 0 auto", height: 38, padding: mobile ? "0 14px" : "0 20px", borderRadius: 999, border: "1px solid " + (i === chip ? "var(--primary)" : "rgba(15,23,42,.14)"), background: i === chip ? "var(--primary)" : "#fff", color: i === chip ? "#fff" : "var(--foreground)", fontSize: mobile ? 13.5 : 14.5, fontWeight: 600, whiteSpace: "nowrap", boxShadow: i === chip ? "0 0 0 3px rgba(20,47,247,.10)" : "none", transition: "box-shadow .16s, border-color .16s, background .16s" }}>{x.label}</button>
          ))}
        </div>
        <div className="homecp-flash-icons" style={{ display: "flex", flexWrap: mobile ? "nowrap" : "wrap", overflowX: mobile ? "auto" : "visible", justifyContent: mobile ? "flex-start" : "center", gap: 8, padding: "2px 2px 10px", scrollbarWidth: "none" }}>
          {[{ label: "Tất cả", img: null }, ...icons].map((x) => {
            const on = x.label === brand;
            return (
              <button key={x.label} onClick={() => setBrand(x.label)} style={{ cursor: "pointer", flex: "0 0 auto", height: 38, display: "inline-flex", alignItems: "center", gap: 10, padding: mobile ? "0 14px" : "0 20px", borderRadius: 999, border: "1px solid " + (on ? "var(--primary)" : "rgba(15,23,42,.12)"), background: on ? "#E4EBFF" : "#fff", color: on ? "var(--primary)" : "var(--foreground)", fontSize: mobile ? 13.5 : 14.5, fontWeight: 600, whiteSpace: "nowrap", boxShadow: on ? "0 0 0 3px rgba(20,47,247,.10)" : "none" }}>
                {x.label}
              </button>
            );
          })}
        </div>
        <div style={{ position: "relative" }}>
          <div className="homecp-slot-rail" style={mobile ? homecpRail : { display: "grid", gridTemplateColumns: "repeat(5,minmax(0,1fr))", gap: 12 }}>
            {items.map((p, i) => <HomePageCpCard key={tab + chip + brand + page + i} product={p} onAdd={onAdd} onOpen={onOpen} style={mobile ? homecpRailItem : null} />)}
          </div>
          {pages > 1 && !mobile && (
            <React.Fragment>
              <button className="homecp-flash-arrow" aria-label="Trước" onClick={() => go(-1)} style={round("left")}><i className="ph ph-caret-left" /></button>
              <button className="homecp-flash-arrow" aria-label="Sau" onClick={() => go(1)} style={round("right")}><i className="ph ph-caret-right" /></button>
            </React.Fragment>
          )}
        </div>
      </div>
    </section>
  );
}

// ————— Khối danh mục lớn: banner dọc + tab + lưới 4x2 —————
const HOMECP_SECTIONS = [
  { key: "mtb", title: "Xe đạp trẻ em", banner: HOMECP_IMG.mtb, promo: ["MTB", "Giảm đến", "2 Triệu"], banner2: HOMECP_IMG.ebike, promo2: ["Phụ kiện MTB", "Đồng giá từ", "199K"], tabs: [
    { label: "Địa hình phổ thông", cat: "Xe đạp địa hình", from: 0 },
    { label: "Địa hình cao cấp", cat: "Xe đạp địa hình", from: 4 },
    { label: "Khung sườn MTB", cat: "Xe đạp địa hình", from: 8 },
  ] },
  { key: "city", title: "Xe đạp địa hình", banner: HOMECP_IMG.city, promo: ["Touring", "Chỉ từ", "3.9 Triệu"], banner2: HOMECP_IMG.mtb, promo2: ["City / Hybrid", "Ưu đãi đến", "1.5 Triệu"], tabs: [
    { label: "Touring", cat: "Xe đạp thể thao đường phố", from: 0 },
    { label: "City / Hybrid", cat: "Xe đạp thể thao đường phố", from: 4 },
    { label: "Fixed gear", cat: ["Xe đạp fixed gear", "Xe đạp thể thao đường phố"], from: 0 },
  ] },
  { key: "road", title: "Xe đạp touring", banner: HOMECP_IMG.road, promo: ["Road Bike", "Trả góp", "0%"], banner2: HOMECP_IMG.city, promo2: ["Gravel", "Giảm thêm", "10%"], tabs: [
    { label: "Road nhôm", cat: "Xe đạp đua", from: 0 },
    { label: "Road carbon", cat: "Xe đạp đua", from: 4 },
    { label: "Gravel", cat: "Xe đạp đua", from: 6 },
  ] },
  { key: "kids", title: "Xe đạp gấp", banner: HOMECP_IMG.ebike, promo: ["Trẻ em", "Chỉ từ", "1.29 Triệu"], banner2: HOMECP_IMG.road, promo2: ["Xe gấp", "Giảm đến", "800K"], tabs: [
    { label: "Xe trẻ em", cat: "Xe đạp trẻ em", from: 0 },
    { label: "Xe gấp & fixed gear", cat: ["Xe đạp gấp", "Xe đạp fixed gear"], from: 0 },
    { label: "Xe đạp nữ & mini", cat: ["Xe đạp trẻ em", "Xe đạp gấp", "Xe đạp fixed gear"], from: 3 },
  ] },
  { key: "ebike", title: "Xe đạp đua", banner: HOMECP_IMG.ebike, promo: ["E-Bike", "Trả góp", "0%"], banner2: HOMECP_IMG.city, promo2: ["Pin & sạc", "Giảm đến", "1 Triệu"], tabs: [
    { label: "Trợ lực đô thị", cat: "Xe đạp thể thao đường phố", from: 2 },
    { label: "Trợ lực địa hình", cat: "Xe đạp địa hình", from: 6 },
    { label: "Xe gấp trợ lực", cat: "Xe đạp gấp", from: 1 },
  ] },
  { key: "touring", title: "Phụ tùng", banner: HOMECP_IMG.road, promo: ["Touring", "Chỉ từ", "6.9 Triệu"], banner2: HOMECP_IMG.mtb, promo2: ["Gravel", "Ưu đãi đến", "2 Triệu"], tabs: [
    { label: "Touring đường dài", cat: "Xe đạp thể thao đường phố", from: 1 },
    { label: "Gravel", cat: "Xe đạp đua", from: 3 },
    { label: "Khung sườn & phụ tùng", cat: ["Xe đạp đua", "Xe đạp địa hình"], from: 5 },
  ] },
];

function HomePageCpSection({ section, onAdd, onOpen }) {
  const mobile = useHomecpMobile();
  const [tab, setTab] = React.useState(0);
  const [brand, setBrand] = React.useState("Tất cả");
  const t = section.tabs[tab];
  const brands = ["Tất cả", ...homecpBrands(t.cat)];
  const items = homecpPool(t.cat, t.from, brand)(4);
  return (
    <section style={{ marginTop: mobile ? 16 : 24, background: mobile ? "transparent" : "#fff", border: mobile ? "none" : "2px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: mobile ? "stretch" : "center", flexDirection: mobile ? "column" : "row", gap: mobile ? 0 : 18, flexWrap: "wrap", borderBottom: "1px solid var(--border)", padding: mobile ? 0 : "0 14px" }}>
        <h2 style={{ margin: 0, padding: mobile ? "12px 0 8px" : "14px 0", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 17 : 20, textTransform: "uppercase", color: "var(--primary)" }}>{section.title}</h2>
        <div className="homecp-slot-rail" style={{ display: "flex", gap: 4, minWidth: 0, maxWidth: "100%", width: mobile ? "100%" : "auto", marginLeft: mobile ? 0 : "auto", overflowX: mobile ? "auto" : "visible", scrollbarWidth: "none" }}>
          {section.tabs.map((x, i) => (
            <button key={x.label} onClick={() => { setTab(i); setBrand("Tất cả"); }} style={{ cursor: "pointer", flex: "0 0 auto", border: "none", background: "none", padding: mobile ? "6px 10px 8px" : "16px 14px 13px", borderBottom: "3px solid " + (i === tab ? "var(--primary)" : "transparent"), fontFamily: "var(--font-sans)", fontSize: mobile ? 12.5 : 14, fontWeight: 700, whiteSpace: "nowrap", textTransform: "uppercase", color: i === tab ? "var(--primary)" : "var(--muted-foreground)" }}>{x.label}</button>
          ))}
        </div>
        {!mobile && <a className="homecp-seeall" onClick={() => onOpen && onOpen(items[0])} style={{ fontSize: 13, fontWeight: 600, color: "var(--muted-foreground)", cursor: "pointer", whiteSpace: "nowrap" }}>Xem tất cả <i className="ph ph-caret-right" style={{ fontSize: 12 }} /></a>}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "minmax(0,1fr)" : "232px minmax(0,1fr)", alignItems: "stretch" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: mobile ? "12px 0 0" : 12, borderRight: mobile ? "none" : "1px solid var(--border)" }}>
          {[{ img: section.banner, promo: section.promo }].map((b, bi) => (
            <a key={bi} data-banner={"Banner dọc khối — " + section.title} data-banner-note="Có chữ promo đè lên: chừa vùng trống phía trên." onClick={() => onOpen && onOpen(items[bi] || items[0])} style={{ position: "relative", display: "block", overflow: "hidden", background: "#0F172A", cursor: "pointer", flex: 1, minHeight: mobile ? 132 : 168 }}>
              <img src={b.img} alt="" loading="lazy" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: .55 }} />
              <div style={{ position: "relative", padding: "18px 18px", display: "flex", flexDirection: "column", gap: 5, color: "#fff" }}>
                <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 7px*var(--ts))", textTransform: "uppercase", lineHeight: 1.05 }}>{b.promo[0]}</span>
                <span style={{ fontSize: 13, opacity: .9 }}>{b.promo[1]}</span>
                <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 13px*var(--ts))", color: "#FFD400", lineHeight: 1 }}>{b.promo[2]}</span>
                <span style={{ marginTop: 6, alignSelf: "flex-start", display: "inline-flex", alignItems: "center", height: 30, padding: "0 16px", borderRadius: 999, background: "#fff", color: "#111827", fontSize: 12.5, fontWeight: 700 }}>Mua ngay</span>
              </div>
            </a>
          ))}
        </div>
        <div style={{ minWidth: 0, padding: mobile ? "12px 0 0" : 12 }}>
          <div className="homecp-slot-rail" style={{ display: "flex", flexWrap: mobile ? "nowrap" : "wrap", overflowX: mobile ? "auto" : "visible", scrollbarWidth: "none", gap: 8, marginBottom: 12 }}>
            {brands.map((b) => (
              <button key={b} onClick={() => setBrand(b)} style={{ cursor: "pointer", flex: "0 0 auto", height: 30, padding: "0 12px", border: "1px solid " + (b === brand ? "var(--primary)" : "var(--border)"), background: b === brand ? "color-mix(in srgb,var(--primary) 8%,#fff)" : "#fff", color: b === brand ? "var(--primary)" : "var(--muted-foreground)", fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap" }}>{b}</button>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: mobile ? "repeat(2,minmax(0,1fr))" : "repeat(4,minmax(0,1fr))", gap: mobile ? 8 : 12 }}>
            {items.map((p, i) => <HomePageCpCard key={section.key + tab + brand + i} product={p} onAdd={onAdd} onOpen={onOpen} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

// ————— Dải phụ kiện nhỏ —————
const HOMECP_ACCESSORIES = [
  { label: "Mũ bảo hiểm", img: "https://api.xedap.vn/products/Ph%E1%BB%A5%20ki%E1%BB%87n/flexi-black.jpg" },
  { label: "Khoá chống trộm", img: "https://api.xedap.vn/wp-content/uploads/2020/07/520000040-850.jpg" },
  { label: "Đèn chiếu sáng", img: "https://api.xedap.vn/products/Ph%E1%BB%A5%20ki%E1%BB%87n/GI/gi-61.jpg" },
  { label: "Bơm & dụng cụ", img: "https://api.xedap.vn/wp-content/uploads/2024/09/B-4518-Black.jpg" },
  { label: "Săm lốp", img: "https://api.xedap.vn/wp-content/uploads/2022/01/maxxis-pace-850.jpg" },
  { label: "Yên & cọc yên", img: "https://api.xedap.vn/products/Ph%E1%BB%A5%20ki%E1%BB%87n/saddle-latte.jpg" },
  { label: "Ghi đông", img: "https://api.xedap.vn/wp-content/uploads/2024/04/170000269-275.jpg" },
  { label: "Bộ truyền động", img: "https://api.xedap.vn/products/SHIMANO/irdm-8200-gs.jpg" },
  { label: "Baga – giá đèo", img: "https://api.xedap.vn/products/Ph%E1%BB%A5%20ki%E1%BB%87n/PK%20RAPTOR/ra-76.jpg" },
  { label: "Quần áo đạp xe", img: "https://api.xedap.vn/products/SHIMANO/suki-green.jpeg" },
];

function HomePageCpAccessoryStrip({ onNav, slot }) {
  const mobile = useHomecpMobile();
  if (mobile) return (
    <section style={{ marginTop: 24 }}>
      <div data-banner={"Banner ngang mobile — vị trí " + (slot || 1)} data-banner-size="424×71" style={{ aspectRatio: "424/71", border: "1px dashed color-mix(in srgb,var(--primary) 40%,#fff)", background: "repeating-linear-gradient(45deg,color-mix(in srgb,var(--primary) 9%,#fff) 0 6px,#fff 6px 12px)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <span style={{ fontFamily: "var(--font-mono, ui-monospace, monospace)", fontSize: 11, fontWeight: 600, letterSpacing: ".02em", color: "var(--primary)", background: "#fff", padding: "3px 10px" }}>banner mobile — 424×71</span>
      </div>
    </section>
  );
  return (
    <section style={{ marginTop: 24 }}>
      <a data-banner={"Banner ngang full-width — vị trí " + (slot || 1)} onClick={() => onNav && onNav("Phụ kiện")} style={{ display: "block", cursor: "pointer", borderRadius: 16, overflow: "hidden" }}>
        <img src="https://cdn.hstatic.net/files/200001188264/file/banner_ngang.png" alt="Sắm thêm phụ kiện chất lượng" loading="lazy" style={{ width: "100%", height: "auto", display: "block" }} />
      </a>
    </section>
  );
}

// ————— Phụ kiện & bảo dưỡng: 3 banner + dải icon danh mục —————
const HOMECP_ACC_BANNERS = [
  { slot: "Banner_1", w: 456, h: 260, title: "Trang bị cho người đạp", cta: "Khám phá ngay" },
  { slot: "Banner_2", w: 456, h: 260, title: "Chăm sóc & bảo dưỡng", cta: "Khám phá ngay" },
  { slot: "Banner_3", w: 456, h: 260, title: "Phụ tùng thay thế", cta: "Khám phá ngay" },
];
const HOMECP_ACC_TILES = HOMECP_ACCESSORIES.concat([
  { label: "Mũ trẻ em", img: HOMECP_ACCESSORIES[0].img },
  { label: "Đồ bảo hộ", img: HOMECP_ACCESSORIES[9].img },
  { label: "Bình nước & gá", img: HOMECP_ACCESSORIES[3].img },
  { label: "Dầu xích & vệ sinh", img: HOMECP_ACCESSORIES[3].img },
  { label: "Bàn đạp", img: HOMECP_ACCESSORIES[7].img },
  { label: "Chuông & gương", img: HOMECP_ACCESSORIES[2].img },
]);
function HomePageCpDualPanels({ onNav }) {
  const mobile = useHomecpMobile();
  const strip = React.useRef(null);
  const bannerRail = React.useRef(null);
  const [bi, setBi] = React.useState(0);
  const slide = (d) => { const el = strip.current; if (el) el.scrollBy({ left: d * el.clientWidth * 0.8, behavior: "smooth" }); };
  const onBannerScroll = () => { const el = bannerRail.current; if (!el) return; const i = Math.round(el.scrollLeft / (el.clientWidth || 1)); setBi(Math.max(0, Math.min(HOMECP_ACC_BANNERS.length - 1, i))); };
  const goBanner = (i) => { const el = bannerRail.current; if (el) el.scrollTo({ left: i * el.clientWidth, behavior: "smooth" }); };
  const tilePages = Math.ceil(HOMECP_ACC_TILES.length / 3);
  const [tp, setTp] = React.useState(0);
  const tileStep = () => { const el = strip.current; if (!el) return 0; const t = el.children[0]; return t ? (t.offsetWidth + 12) * 3 : el.clientWidth; };
  const onTileScroll = () => { const el = strip.current; if (!el) return; if (el.scrollLeft + el.clientWidth >= el.scrollWidth - 2) { setTp(tilePages - 1); return; } const s = tileStep() || 1; const i = Math.round(el.scrollLeft / s); setTp(Math.max(0, Math.min(tilePages - 1, i))); };
  const goTiles = (i) => { const el = strip.current; if (!el) return; const max = el.scrollWidth - el.clientWidth; el.scrollTo({ left: Math.min(i * tileStep(), max), behavior: "smooth" }); setTp(Math.max(0, Math.min(tilePages - 1, i))); };
  React.useEffect(() => {
    if (!mobile) return;
    const t = setInterval(() => {
      const el = strip.current; if (!el) return;
      const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 2;
      setTp((p) => { const next = atEnd ? 0 : Math.min(p + 1, tilePages - 1); const max = el.scrollWidth - el.clientWidth; el.scrollTo({ left: Math.min(next * tileStep(), max), behavior: "smooth" }); return next; });
    }, 3200);
    return () => clearInterval(t);
  }, [mobile, tilePages]);
  const arrow = (side) => ({ position: "absolute", top: 52, [side]: -18, transform: "translateY(-50%)", width: 40, height: 40, borderRadius: 999, border: "1px solid rgba(15,23,42,.10)", background: "#fff", boxShadow: "0 6px 18px rgba(15,23,42,.12)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "calc(13px + 5px*var(--ts))", color: "var(--foreground)", zIndex: 2 });
  return (
    <div style={{ marginTop: 24 }}>
      <h2 style={{ margin: "0 0 14px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 19 : 22, letterSpacing: "-.01em", color: "var(--foreground)" }}>Phụ kiện & bảo dưỡng</h2>
      <div ref={bannerRail} onScroll={mobile ? onBannerScroll : undefined} className={mobile ? "homecp-slot-rail" : undefined} style={mobile ? { display: "flex", gap: 0, overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none" } : { display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 16 }}>
        {HOMECP_ACC_BANNERS.map((b) => (
          <a key={b.slot} onClick={() => onNav && onNav(b.title)} style={{ position: "relative", display: "flex", flexDirection: "column", cursor: "pointer", overflow: "hidden", aspectRatio: b.w + "/" + b.h, ...(mobile ? { flex: "0 0 100%", scrollSnapAlign: "start" } : null), background: "repeating-linear-gradient(135deg,#EDF1FA 0 10px,#E3E9F7 10px 20px)", border: "1px solid var(--border)", padding: 14 }}>
            <span style={{ alignSelf: "flex-start", display: "inline-flex", alignItems: "center", padding: "5px 10px", background: "rgba(255,255,255,.86)", fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: ".04em", color: "var(--muted-foreground)" }}>{b.slot} · {b.w}×{b.h}px</span>
            <div style={{ marginTop: "auto", padding: "0 10px 8px", display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 12 }}>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 20 : 24, lineHeight: 1.1, letterSpacing: "-.02em", color: "var(--foreground)" }}>{b.title}</span>
              <span style={{ display: "inline-flex", alignItems: "center", height: 42, padding: "0 22px", borderRadius: 999, background: "var(--primary)", color: "#fff", fontSize: "calc(13px + 2px*var(--ts))", fontWeight: 600 }}>{b.cta}</span>
            </div>
          </a>
        ))}
      </div>
      {mobile && (
        <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 10 }}>
          {HOMECP_ACC_BANNERS.map((b, i) => (
            <button key={b.slot} aria-label={"Banner " + (i + 1)} onClick={() => goBanner(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 6, width: i === bi ? 20 : 6, borderRadius: 999, background: i === bi ? "var(--primary)" : "rgba(15,23,42,.22)", transition: "width .2s" }} />
          ))}
        </div>
      )}
      <div style={{ position: "relative", marginTop: mobile ? 20 : 26 }}>
      {!mobile && <button aria-label="Trước" onClick={() => slide(-1)} style={arrow("left")}><i className="ph ph-caret-left" /></button>}
      {!mobile && <button aria-label="Sau" onClick={() => slide(1)} style={arrow("right")}><i className="ph ph-caret-right" /></button>}
      <div ref={strip} onScroll={mobile ? onTileScroll : undefined} className="homecp-slot-rail" style={{ display: "flex", gap: 12, overflowX: "auto", scrollbarWidth: "none", paddingBottom: 4, scrollSnapType: mobile ? "x mandatory" : "none" }}>
        {HOMECP_ACC_TILES.map((a, i) => (
          <a key={a.label + i} className="homecp-acc-tile" onClick={() => onNav && onNav(a.label)} style={{ flex: mobile ? "0 0 calc((100% - 24px)/3)" : "0 0 auto", width: mobile ? "auto" : 124, scrollSnapAlign: mobile && i % 3 === 0 ? "start" : "none", display: "flex", flexDirection: "column", alignItems: "center", gap: 10, cursor: "pointer" }}>
            <span style={{ width: "100%", maxWidth: 104, aspectRatio: "1/1", borderRadius: 999, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
              <img src={a.img} alt="" loading="lazy" style={{ width: "78%", height: "78%", objectFit: "contain" }} />
            </span>
            <span style={{ fontSize: 13, fontWeight: 600, textAlign: "center", lineHeight: 1.35, color: "var(--primary)" }}>{a.label}</span>
          </a>
        ))}
      </div>
      {mobile && (
        <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 12 }}>
          {Array.from({ length: tilePages }).map((_, i) => (
            <button key={i} aria-label={"Nhóm " + (i + 1)} onClick={() => goTiles(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 6, width: i === tp ? 20 : 6, borderRadius: 999, background: i === tp ? "var(--primary)" : "rgba(15,23,42,.22)", transition: "width .2s" }} />
          ))}
        </div>
      )}
      </div>
    </div>
  );
}

// ————— Hàng đã xem —————
function HomePageCpViewed({ onAdd, onOpen }) {
  const mobile = useHomecpMobile();
  const items = homecpPool(null, 9)(mobile ? 10 : 5);
  return (
    <section style={{ marginTop: mobile ? 16 : 24 }}>
      <h2 style={{ margin: "0 0 10px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 3px*var(--ts))", textTransform: "uppercase", letterSpacing: ".04em", color: "var(--muted-foreground)" }}>Sản phẩm bạn đã xem</h2>
      <div className="homecp-slot-rail" style={{ background: "#fff", border: mobile ? "none" : "1px solid var(--border)", padding: mobile ? 0 : 12, ...(mobile ? homecpRail : { display: "grid", gridTemplateColumns: "repeat(5,minmax(0,1fr))", gap: 12 }) }}>
        {items.map((p, i) => <HomePageCpCard key={"vw" + i} product={p} onAdd={onAdd} onOpen={onOpen} style={mobile ? homecpRailItem : null} />)}
      </div>
    </section>
  );
}

// ————— Video review —————
function HomePageCpVideos({ onOpen }) {
  const D = window.XedapApiData;
  const mobile = useHomecpMobile();
  const vids = [
    { title: "Đánh giá RAPTOR Mocha 2B sau 500 km", p: D.PRODUCTS[0], cover: "https://cdn.hstatic.net/files/200001188264/file/wqfgamat7efaqmfixly8dyhg4sslqaagkeisf_tplv-photomode-zoomcover_720_720.jpeg" },
    { title: "MTB dưới 6 triệu nên mua xe nào?", p: D.PRODUCTS[6], cover: "https://cdn.hstatic.net/files/200001188264/file/ekfbf6gci2uileaacngibu9exvoanhizbhys4_tplv-photomode-zoomcover_720_720.jpeg" },
    { title: "Road JAVA vs GIANT TCR – chọn sao?", p: D.PRODUCTS[12], cover: "https://cdn.hstatic.net/files/200001188264/file/yqwy5qhaaokolk8jkfl3eaqm8aewga6ekapdg_tplv-photomode-zoomcover_720_720.avif" },
    { title: "Chọn xe đạp cho bé 6–9 tuổi", p: D.PRODUCTS[18], cover: "https://cdn.hstatic.net/files/200001188264/file/kviblqubdvo7ub2eyfbg7qevanaafyfcacqa1_tplv-photomode-zoomcover_720_720.avif" },
  ];
  return (
    <section style={{ marginTop: 24 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 18, margin: "0 0 14px" }}>
        <h2 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 7px*var(--ts))", textTransform: "uppercase", letterSpacing: ".02em", color: "var(--foreground)" }}>Review sản phẩm</h2>
        <span style={{ width: 1, alignSelf: "stretch", background: "var(--border)" }} />
        <a onClick={() => onOpen && onOpen(vids[0].p)} style={{ display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer", textDecoration: "none", fontSize: "calc(13px + 1.5px*var(--ts))", fontWeight: 600, color: "#1a73e8" }}>Xem YouTube <i className="ph ph-caret-right" style={{ fontSize: "calc(13px + 1px*var(--ts))" }} /></a>
      </div>
      {mobile ? <HomePageCpVideoRail vids={vids} onOpen={onOpen} /> : (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 16 }}>
        {vids.map((v) => <HomePageCpVideoCard key={v.title} v={v} onOpen={onOpen} />)}
      </div>)}
    </section>
  );
}
// Mobile: review rail cuộn ngang, mỗi khung nhìn ~1,5 thẻ để thẻ rộng hơn, không mất chữ.
function HomePageCpVideoRail({ vids, onOpen }) {
  return (
    <div className="homecp-slot-rail" style={{ display: "flex", gap: 10, overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none", paddingBottom: 4 }}>
      {vids.map((v) => (
        <div key={v.title} style={{ flex: "0 0 calc((100% - 10px)/1.5)", scrollSnapAlign: "start", minWidth: 0 }}>
          <HomePageCpVideoCard v={v} onOpen={onOpen} />
        </div>
      ))}
    </div>
  );
}
function HomePageCpVideoCard({ v, onOpen }) {
  return (
          <article key={v.title} style={{ background: "#fff", border: "1px solid var(--border)", borderRadius: 10, overflow: "hidden", display: "flex", flexDirection: "column" }}>
            <a onClick={() => onOpen && onOpen(v.p)} style={{ position: "relative", display: "block", background: "#0F172A", cursor: "pointer" }}>
              <img src={v.cover || v.p.img2 || v.p.img} alt="" loading="lazy" style={{ display: "block", width: "100%", aspectRatio: "9/16", objectFit: "cover" }} />
              <span style={{ position: "absolute", inset: "0 0 auto 0", height: 92, background: "linear-gradient(180deg,rgba(0,0,0,.62),rgba(0,0,0,0))" }} />
              <span style={{ position: "absolute", top: 12, left: 12, right: 12, display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 34, height: 34, borderRadius: 999, background: "var(--primary)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 4px*var(--ts))" }}>X</span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 1.5px*var(--ts))", color: "#fff", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", textShadow: "0 1px 3px rgba(0,0,0,.5)" }}>{v.title}</span>
                  <span style={{ display: "block", fontSize: 12, color: "rgba(255,255,255,.85)" }}>Xedap.vn</span>
                </span>
              </span>
              <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <span style={{ width: 84, height: 84, display: "block" }}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" focusable="false" aria-hidden="true" style={{ pointerEvents: "none", display: "inherit", width: "100%", height: "100%" }}><path d="m19.45,3.88c1.12,1.82.48,4.15-1.42,5.22l-1.32.74.94.41c1.36.58,2.27,1.85,2.35,3.27.08,1.43-.68,2.77-1.97,3.49l-8,4.47c-1.91,1.06-4.35.46-5.48-1.35-1.12-1.82-.48-4.15,1.42-5.22l1.33-.74-.94-.41c-1.36-.58-2.27-1.85-2.35-3.27-.08-1.43.68-2.77,1.97-3.49l8-4.47c1.91-1.06,4.35-.46,5.48,1.35Z" fill="#f03"></path><path d="m10,15l5-3-5-3v6Z" fill="#fff"></path></svg>
                </span>
              </span>
            </a>
            <a onClick={() => onOpen && onOpen(v.p)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 12px 14px", cursor: "pointer", textDecoration: "none" }}>
              <img src={v.p.img} alt="" loading="lazy" style={{ width: 52, height: 52, objectFit: "contain", flexShrink: 0 }} />
              <span style={{ minWidth: 0 }}>
                <span style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "calc(13px + 0.5px*var(--ts))", lineHeight: 1.35, color: "var(--foreground)", overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{v.p.name}</span>
                <span style={{ display: "flex", alignItems: "baseline", flexWrap: "wrap", gap: "2px 8px", marginTop: 4 }}>
                  <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 2px*var(--ts))", color: "var(--primary)" }}>{v.p.price.toLocaleString("vi-VN")}đ</span>
                  {v.p.originalPrice && <span style={{ fontSize: 12.5, color: "var(--muted-foreground)", textDecoration: "line-through" }}>{v.p.originalPrice.toLocaleString("vi-VN")}đ</span>}
                </span>
              </span>
            </a>
          </article>
  );
}

// ————— Ưu đãi 2 cột + thương hiệu + dịch vụ —————
// Mobile: 4 banner ưu đãi thành rail 1 hàng × 2 cột, snap từng trang.
function HomePageCpOffersRail({ col }) {
  const rail = React.useRef(null);
  const [p, setP] = React.useState(0);
  const pages = [];
  for (let i = 0; i < col.items.length; i += 2) pages.push(i);
  const onScroll = () => { const el = rail.current; if (!el) return; setP(Math.max(0, Math.min(pages.length - 1, Math.round(el.scrollLeft / (el.clientWidth || 1))))); };
  const go = (i) => { const el = rail.current; if (!el) return; el.scrollTo({ left: i * el.clientWidth, behavior: "smooth" }); setP(i); };
  return (
    <div>
      <div ref={rail} onScroll={onScroll} className="homecp-slot-rail" style={{ display: "flex", overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none" }}>
        {pages.map((start) => (
          <div key={start} style={{ flex: "0 0 100%", scrollSnapAlign: "start", display: "grid", gridTemplateColumns: "repeat(2,minmax(0,1fr))", gap: 12 }}>
            {col.items.slice(start, start + 2).map((it, k) => {
              const i = start + k;
              return <HomePageCpOfferBanner key={i} col={col} i={i} onNav={col.onNav} />;
            })}
          </div>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 10 }}>
        {pages.map((_, i) => (
          <button key={i} aria-label={"Trang " + (i + 1)} onClick={() => go(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 6, width: i === p ? 20 : 6, borderRadius: 999, background: i === p ? "var(--primary)" : "rgba(15,23,42,.22)", transition: "width .2s" }} />
        ))}
      </div>
    </div>
  );
}

function HomePageCpOfferBanner({ col, i, onNav }) {
  return (
    <a data-banner={col.title + " — banner " + (i + 1)} data-banner-note="Khung tỉ lệ 600:200 (3:1), ảnh objectFit: cover." onClick={() => onNav && onNav(col.title)} style={{ display: "block", position: "relative", aspectRatio: "600/200", cursor: "pointer", overflow: "hidden", background: col.banners[i] ? "#F4F6FB" : "repeating-linear-gradient(135deg,#EDF1FA 0 10px,#E3E9F7 10px 20px)" }}>
      {col.banners[i]
        ? <img src={col.banners[i]} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        : <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--muted-foreground)" }}>banner {i + 1}</span>}
    </a>
  );
}

function HomePageCpOffers({ onNav }) {
  const mobile = useHomecpMobile();
  const cols = [
    { title: "Ưu đãi học sinh – sinh viên", items: [1, 2, 3, 4], banners: [null, null, null, null] },
    { title: "Ưu đãi thanh toán", items: [1, 2, 3, 4], banners: [null, null, null, null] },
  ];
  return (
    <div style={{ marginTop: mobile ? 16 : 24, display: "grid", gridTemplateColumns: mobile ? "minmax(0,1fr)" : "repeat(2,minmax(0,1fr))", gap: 16 }}>
      {cols.map((c) => (
        <section key={c.title}>
          <h2 style={{ margin: "0 0 10px", textAlign: "center", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 3px*var(--ts))", textTransform: "uppercase", letterSpacing: ".04em", color: "var(--muted-foreground)" }}>{c.title}</h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2,minmax(0,1fr))", gap: 12 }}>
            {c.items.map((it, i) => <HomePageCpOfferBanner key={i} col={c} i={i} onNav={onNav} />)}
          </div>
        </section>
      ))}
    </div>
  );
}

function HomePageCpBrandLogoSlider({ logos }) {
  const rail = React.useRef(null);
  const pages = [];
  for (let i = 0; i < logos.length; i += 4) pages.push(logos.slice(i, i + 4));
  const [p, setP] = React.useState(0);
  const onScroll = () => { const el = rail.current; if (!el) return; setP(Math.max(0, Math.min(pages.length - 1, Math.round(el.scrollLeft / (el.clientWidth || 1))))); };
  const go = (i) => { const el = rail.current; if (!el) return; el.scrollTo({ left: i * el.clientWidth, behavior: "smooth" }); setP(i); };
  return (
    <div style={{ marginTop: 12 }}>
      <div ref={rail} onScroll={onScroll} className="homecp-slot-rail" style={{ display: "flex", overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none", background: "#fff", border: "1px solid var(--border)" }}>
        {pages.map((pg, pi) => (
          <div key={pi} style={{ flex: "0 0 100%", scrollSnapAlign: "start", display: "grid", gridTemplateColumns: "repeat(2,1fr)" }}>
            {pg.map((b, i) => (
              <div key={i} style={{ height: 62, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 12px", borderRight: i % 2 === 0 ? "1px solid var(--border)" : "none", borderTop: i >= 2 ? "1px solid var(--border)" : "none" }}>
                <img src={b} alt="" loading="lazy" style={{ maxHeight: 32, maxWidth: "100%", objectFit: "contain" }} />
              </div>
            ))}
          </div>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 10 }}>
        {pages.map((_, i) => (
          <button key={i} aria-label={"Trang " + (i + 1)} onClick={() => go(i)} style={{ cursor: "pointer", border: "none", padding: 0, height: 6, width: i === p ? 20 : 6, borderRadius: 999, background: i === p ? "var(--primary)" : "rgba(15,23,42,.22)", transition: "width .2s" }} />
        ))}
      </div>
    </div>
  );
}

function HomePageCpBrandRow({ onNav }) {
  const mobile = useHomecpMobile();
  const P = window.KitData.PARTNERS || [];
  return (
    <section style={{ marginTop: mobile ? 16 : 24 }}>
      <h2 style={{ margin: "0 0 10px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 3px*var(--ts))", textTransform: "uppercase", letterSpacing: ".04em", color: "var(--muted-foreground)" }}>Chuyên trang thương hiệu</h2>
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "minmax(0,1fr)" : "repeat(3,minmax(0,1fr))", gap: mobile ? 10 : 16 }}>
        {[{ n: "RAPTOR", img: HOMECP_IMG.mtb, t: "Sale địa hình đến 25%" }, { n: "JAVA", img: HOMECP_IMG.road, t: "Road carbon chính hãng" }, { n: "GIANT", img: HOMECP_IMG.city, t: "Touring & city bike" }].map((b) => (
          <a key={b.n} data-banner={"Banner thương hiệu — " + b.n} data-banner-note="Ảnh nền mờ 50%, có chữ đè lên." onClick={() => onNav && onNav(b.n)} style={{ position: "relative", display: "block", overflow: "hidden", background: "#0F172A", cursor: "pointer", minHeight: 132 }}>
            <img src={b.img} alt="" loading="lazy" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: .5 }} />
            <div style={{ position: "relative", padding: "20px 22px", color: "#fff", display: "flex", flexDirection: "column", gap: 6 }}>
              <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 11px*var(--ts))", letterSpacing: ".02em" }}>{b.n}</span>
              <span style={{ fontSize: 13, opacity: .92 }}>{b.t}</span>
            </div>
          </a>
        ))}
      </div>
      {mobile ? <HomePageCpBrandLogoSlider logos={P.slice(0, 12)} /> : (
      <div style={{ marginTop: 12, background: "#fff", border: "1px solid var(--border)", display: "grid", gridTemplateColumns: "repeat(6,1fr)" }}>
        {P.slice(0, 12).map((b, i) => (
          <div key={i} style={{ height: 62, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 12px", borderRight: (i % 6 === 5 ? "none" : "1px solid var(--border)"), borderTop: i >= 6 ? "1px solid var(--border)" : "none" }}>
            <img src={b} alt="" loading="lazy" style={{ maxHeight: 32, maxWidth: "100%", objectFit: "contain" }} />
          </div>
        ))}
      </div>
      )}
    </section>
  );
}

function HomePageCpServiceBanner({ onNav }) {
  const mobile = useHomecpMobile();
  const stats = [["8%", "Chiết khấu cho khách hàng thân thiết"], ["1%", "Hoàn tiền mọi đơn trả góp"], ["24h", "Giao xe lắp sẵn nội thành"]];
  return (
    <section onClick={() => onNav && onNav("service")} style={{ marginTop: mobile ? 16 : 24, background: "#B91C1C", color: "#fff", display: "grid", gridTemplateColumns: mobile ? "minmax(0,1fr)" : "minmax(0,1.1fr) repeat(3,minmax(0,1fr))", alignItems: mobile ? "start" : "center", gap: mobile ? 14 : 24, padding: mobile ? "18px 16px" : "22px 26px", cursor: "pointer" }}>
      <div>
        <div style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 20 : 24, lineHeight: 1.05, textTransform: "uppercase" }}>Xe đạp doanh nghiệp</div>
        <div style={{ marginTop: 6, fontSize: "calc(13px + 0.5px*var(--ts))", opacity: .92 }}>Mua số lượng lớn cho công ty, trường học, khu nghỉ dưỡng</div>
      </div>
      {stats.map((s) => (
        <div key={s[0]} style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: mobile ? 28 : 34, color: "#FFD400", lineHeight: 1 }}>{s[0]}</span>
          <span style={{ fontSize: 13, lineHeight: 1.35, opacity: .95 }}>{s[1]}</span>
        </div>
      ))}
    </section>
  );
}

function HomePageCpNews() {
  const D = window.XedapApiData;
  const mobile = useHomecpMobile();
  const posts = [
    "Chọn cỡ khung xe đạp theo chiều cao: bảng tra nhanh",
    "5 lỗi thường gặp khi bảo dưỡng xích và cách xử lý",
    "Đạp xe 30 phút mỗi ngày thay đổi cơ thể ra sao",
    "Kinh nghiệm đạp xe đường dài Hà Nội – Ninh Bình",
    "Nên chọn phanh đĩa dầu hay phanh đĩa cơ?",
  ];
  return (
    <section style={{ marginTop: 24 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, margin: "0 0 10px" }}>
        <h2 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 3px*var(--ts))", textTransform: "uppercase", letterSpacing: ".04em", color: "var(--muted-foreground)" }}>Tin tức</h2>
        <a href="Blog.html" style={{ display: "inline-flex", alignItems: "center", gap: 4, flexShrink: 0, textDecoration: "none", fontSize: "calc(13px + 0.5px*var(--ts))", fontWeight: 600, color: "var(--primary)" }}>Xem tất cả <i className="ph ph-caret-right" style={{ fontSize: "calc(13px + 0.5px*var(--ts))" }} /></a>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "repeat(2,minmax(0,1fr))" : "repeat(5,minmax(0,1fr))", gap: mobile ? 10 : 16 }}>
        {(mobile ? posts.slice(0, 4) : posts).map((t, i) => (
          <a key={t} href="Blog.html" style={{ background: "#fff", border: "1px solid var(--border)", textDecoration: "none", color: "inherit", display: "flex", flexDirection: "column" }}>
            <img src={(D.PRODUCTS[i * 4] || D.PRODUCTS[0]).img} alt="" loading="lazy" style={{ display: "block", width: "100%", aspectRatio: "4/3", objectFit: "cover", background: "var(--muted)" }} />
            <p style={{ margin: 0, padding: "12px 14px 16px", fontSize: "calc(13px + 0.5px*var(--ts))", lineHeight: 1.4, fontWeight: 600, textWrap: "pretty" }}>{t}</p>
          </a>
        ))}
      </div>
    </section>
  );
}

// ————— Flash sale giờ vàng: ribbon đỏ + tab khung giờ + đếm ngược + hàng card có thanh "đã bán" —————
const HOMECP_SLOT_DATES = [{ key: "d1", label: "19/09" }, { key: "d2", label: "20/09" }];
const HOMECP_SLOT_TABS = [
  { key: "s1", date: "d1", time: "09-11h", label: "09-11h 19/09", state: "done" },
  { key: "s2", date: "d1", time: "14-16h", label: "14-16h 19/09", state: "live" },
  { key: "s3", date: "d1", time: "20-22h", label: "20-22h 19/09", state: "soon" },
  { key: "s4", date: "d2", time: "09-11h", label: "09-11h 20/09", state: "soon" },
  { key: "s5", date: "d2", time: "14-16h", label: "14-16h 20/09", state: "soon" },
  { key: "s6", date: "d2", time: "20-22h", label: "20-22h 20/09", state: "soon" },
];
const homecpSlotPrice = (n) => Number(n || 0).toLocaleString("vi-VN") + "đ";

function HomePageCpSlotCard({ product, sold, quota, onOpen, mobile }) {
  const pct = Math.min(100, Math.round((sold / quota) * 100));
  const off = product.originalPrice && product.originalPrice > product.price ? Math.round((1 - product.price / product.originalPrice) * 100) : 0;
  return (
    <a href={product.href || "#"} onClick={(e) => { e.preventDefault(); onOpen && onOpen(product); }} style={{ flex: mobile ? "0 0 calc((100% - 8px)/2)" : "0 0 214px", scrollSnapAlign: "start", display: "flex", flexDirection: "column", gap: 8, background: "#fff", borderRadius: 12, padding: 10, textDecoration: "none", color: "var(--foreground)", boxShadow: "0 2px 10px rgba(11,27,63,.18)" }}>
      <div style={{ position: "relative" }}>
        <img src={product.img} alt={product.name} loading="lazy" style={{ display: "block", width: "100%", aspectRatio: "1/1", objectFit: "contain", background: "#F7F9FF", borderRadius: 8 }} />
        {off ? <span style={{ position: "absolute", top: -2, left: -10, display: "inline-flex", alignItems: "center", gap: 4, whiteSpace: "nowrap", background: "var(--destructive)", color: "#fff", fontSize: 13, fontWeight: 500, lineHeight: 1, padding: "6px 10px", borderRadius: "0 14px 14px 0" }}>Giảm <b style={{ fontWeight: 800 }}>{off}%</b></span> : null}
      </div>
      <h3 style={{ margin: 0, fontSize: "calc(13px + 0.5px*var(--ts))", lineHeight: 1.35, fontWeight: 600, minHeight: 54, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden", textWrap: "pretty" }}>{product.name}</h3>
      <div style={{ marginTop: "auto", display: "flex", flexWrap: "wrap", alignItems: "flex-end", gap: 6 }}>
        <span style={{ color: "#E01B24", fontSize: "calc(13px + 2.5px*var(--ts))", fontWeight: 800 }}>{homecpSlotPrice(product.price)}</span>
        {product.originalPrice ? <del style={{ fontSize: 12.5, color: "var(--muted-foreground)" }}>{homecpSlotPrice(product.originalPrice)}</del> : null}
      </div>
      <div style={{ position: "relative", height: 16, borderRadius: 999, background: "#DCE3FF", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: "0 auto 0 0", width: pct + "%", background: "linear-gradient(90deg,#4C63FF,#142FF7)", borderRadius: 999, transition: "width .3s var(--ease-out)" }} />
        <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: pct > 55 ? "#fff" : "#0B1BA8" }}>Đã bán {sold}/{quota} suất</span>
      </div>
    </a>
  );
}

function HomePageCpFlashSlot({ onOpen }) {
  const D = window.XedapApiData;
  const mobile = useHomecpMobile();
  const [slot, setSlot] = React.useState("s2");
  const [date, setDate] = React.useState("d1");
  const [left, setLeft] = React.useState(1 * 3600 + 38 * 60 + 43);
  const railRef = React.useRef(null);
  React.useEffect(() => { const id = setInterval(() => setLeft((s) => (s <= 0 ? 2 * 3600 : s - 1)), 1000); return () => clearInterval(id); }, []);
  const pad = (n) => String(n).padStart(2, "0");
  const digits = ["00", pad(Math.floor(left / 3600)), pad(Math.floor((left % 3600) / 60)), pad(left % 60)];
  const idx = HOMECP_SLOT_TABS.findIndex((t) => t.key === slot);
  const slotState = (HOMECP_SLOT_TABS[idx] || {}).state;
  const items = homecpPool(null, idx * 6)(12);
  const scroll = (d) => railRef.current && railRef.current.scrollBy({ left: d * 226 * 3, behavior: "smooth" });
  const arrow = (side) => ({ position: "absolute", top: "50%", [side]: -6, transform: "translateY(-50%)", width: 30, height: 62, border: 0, cursor: "pointer", background: "rgba(255,255,255,.88)", color: "#0F172A", fontSize: "calc(13px + 7px*var(--ts))", display: "flex", alignItems: "center", justifyContent: "center", borderRadius: side === "left" ? "0 999px 999px 0" : "999px 0 0 999px", zIndex: 3, boxShadow: "0 4px 14px rgba(11,27,63,.28)" });
  return (
    <section style={{ marginTop: mobile ? 16 : 24, marginBottom: 12, position: "relative" }}>
      <div style={{ position: "relative", zIndex: 2, width: mobile ? "min(300px, 92%)" : "calc((100% - 60px) / 2)", height: mobile ? 44 : 54, margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "16px 16px 0 0", background: "linear-gradient(#1E3AF5,#4C63FF)", boxShadow: "inset 0 -5px 5px #0B1BA8, inset 0 1px 0 rgba(255,255,255,.35)" }}>
        <span style={{ fontFamily: "var(--font-heading)", fontWeight: 800, fontStyle: "italic", fontSize: mobile ? 16 : 22, textTransform: "uppercase", letterSpacing: ".02em", color: "#FFD84D" }}>Flash sale giờ vàng</span>
      </div>
      <div style={{ marginTop: -10, borderRadius: mobile ? 16 : 24, border: "1px solid #DCE3FF", background: "linear-gradient(#0F22C9 0%,#142FF7 55%,#142FF7 100%)", boxShadow: "inset 0 0 0 1px #FFFFFF, inset 0 0 0 3px #BFCCFF, inset 0 0 0 4px #5C74FF", padding: mobile ? "16px 6px 8px" : "18px 18px 8px" }}>
        {!mobile ? (
        <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 12, padding: "4px 8px 14px" }}>
          <div className="homecp-slot-rail" style={{ display: "flex", alignItems: "center", gap: 8, scrollbarWidth: "none", maxWidth: "100%" }}>
            {HOMECP_SLOT_TABS.filter((t) => t.date === "d1").map((t) => {
              const on = t.key === slot;
              return (
                <button key={t.key} onClick={() => setSlot(t.key)} disabled={t.state === "done"} style={{ cursor: t.state === "done" ? "not-allowed" : "pointer", flex: "0 0 auto", opacity: t.state === "done" ? 0.55 : 1, height: 36, padding: "0 18px", borderRadius: 999, border: "2px solid " + (on ? "#fff" : "rgba(255,255,255,.55)"), background: on ? "#fff" : "transparent", color: on ? "var(--primary)" : "#fff", fontSize: 14.5, fontWeight: 700, whiteSpace: "nowrap", transition: "background .18s, color .18s" }}>{t.time} hôm nay</button>
              );
            })}
          </div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ color: "#DCE3FF", fontSize: 14, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{slotState === "live" ? "Kết thúc sau" : "Bắt đầu sau"}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
              {digits.map((d, k) => (
                <React.Fragment key={k}>
                  {k > 0 && <span style={{ color: "#fff", fontSize: "calc(13px + 5px*var(--ts))", fontWeight: 800 }}>:</span>}
                  <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 34, height: 34, borderRadius: 6, background: "#fff", color: "#151515", fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 700 }}>{d}</span>
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
        ) : (
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: mobile ? 12 : 14, padding: mobile ? "4px 2px 14px" : "4px 8px 16px" }}>
          <div style={{ display: "flex", gap: 10 }}>
            {HOMECP_SLOT_DATES.map((d) => {
              const on = d.key === date;
              return (
                <button key={d.key} onClick={() => { setDate(d.key); const f = HOMECP_SLOT_TABS.find((t) => t.date === d.key && t.state !== "done") || HOMECP_SLOT_TABS.find((t) => t.date === d.key); setSlot(f.key); }} style={{ cursor: "pointer", height: mobile ? 32 : 36, padding: mobile ? "0 20px" : "0 26px", borderRadius: 999, border: "2px solid " + (on ? "#fff" : "rgba(255,255,255,.6)"), background: on ? "#fff" : "transparent", color: on ? "var(--primary)" : "#fff", fontFamily: "var(--font-heading)", fontSize: mobile ? 13.5 : 15, fontWeight: 800, letterSpacing: ".01em", transition: "background .18s, color .18s" }}>{d.label}</button>
              );
            })}
          </div>
          <div className="homecp-slot-rail" style={{ display: "flex", justifyContent: mobile ? "flex-start" : "center", gap: mobile ? 18 : 28, maxWidth: "100%", overflowX: mobile ? "auto" : "visible", scrollbarWidth: "none" }}>
            {HOMECP_SLOT_TABS.filter((t) => t.date === date).map((t) => {
              const on = t.key === slot;
              return (
                <button key={t.key} onClick={() => setSlot(t.key)} disabled={t.state === "done"} style={{ cursor: t.state === "done" ? "not-allowed" : "pointer", flex: "0 0 auto", opacity: t.state === "done" ? .5 : 1, padding: "0 2px 8px", border: "none", borderBottom: "3px solid " + (on ? "#FFD84D" : "rgba(255,255,255,.55)"), background: "transparent", color: "#fff", fontFamily: "var(--font-heading)", fontSize: mobile ? 13.5 : 16, fontWeight: on ? 800 : 600, whiteSpace: "nowrap", transition: "border-color .18s, font-weight .18s" }}>{t.time} {HOMECP_SLOT_DATES.find((d) => d.key === t.date).label}</button>
              );
            })}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: mobile ? 8 : 12 }}>
            <span style={{ color: "#fff", fontFamily: "var(--font-heading)", fontSize: mobile ? 13 : 16, fontWeight: 800, textTransform: "uppercase", letterSpacing: ".04em" }}>{slotState === "live" ? "Kết thúc sau" : "Bắt đầu sau"}</span>
            <div style={{ display: "flex", alignItems: "center", gap: mobile ? 4 : 6 }}>
              {digits.map((d, k) => (
                <React.Fragment key={k}>
                  {k > 0 && <span style={{ color: "#fff", fontSize: mobile ? 15 : 18, fontWeight: 800 }}>:</span>}
                  <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: mobile ? 32 : 38, height: mobile ? 32 : 38, borderRadius: 6, background: "#fff", color: "#151515", fontFamily: "var(--font-mono)", fontSize: mobile ? 15 : 18, fontWeight: 700 }}>{d}</span>
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
        )}
        <div style={{ position: "relative" }}>
          <div ref={railRef} className="homecp-slot-rail" style={{ display: "flex", gap: mobile ? 8 : 12, overflowX: "auto", scrollSnapType: "x mandatory", scrollbarWidth: "none", padding: mobile ? "2px 0 6px" : "2px 2px 6px" }}>
            {items.map((p, i) => <HomePageCpSlotCard key={slot + i} mobile={mobile} product={p} sold={[28, 6, 41, 12, 0, 33, 9, 47, 18, 3, 25, 11][i % 12]} quota={[35, 10, 50, 20, 10, 50, 15, 50, 35, 10, 50, 20][i % 12]} onOpen={onOpen} />)}
          </div>
          {!mobile && <button aria-label="Trước" onClick={() => scroll(-1)} style={arrow("left")}><i className="ph ph-caret-left" /></button>}
          {!mobile && <button aria-label="Sau" onClick={() => scroll(1)} style={arrow("right")}><i className="ph ph-caret-right" /></button>}
        </div>
        <p style={{ margin: 0, padding: "10px 8px 6px", textAlign: "center", color: "#DCE6FF", fontSize: mobile ? 11.5 : 13, fontWeight: 500 }}>Áp dụng khi thanh toán online thành công — mỗi số điện thoại mua tối đa 1 sản phẩm cùng loại — không áp dụng đồng thời khuyến mại khác.</p>
      </div>
    </section>
  );
}

function HomePageCpUsp() {
  const mobile = useHomecpMobile();
  return (
    <div data-banner="Dải USP dưới hero" style={{ marginTop: 12 }}>
      <img src={mobile ? "https://cdn2.cellphones.com.vn/insecure/rs:fill:800:150/q:100/plain/https://media-asset.cellphones.com.vn/dashboard-v1/manage-banner/SpecialBanner_Mobile_D3.gif" : "https://cdn2.cellphones.com.vn/insecure/rs:fill:1200:75/q:100/plain/https://media-asset.cellphones.com.vn/dashboard-v1/manage-banner/Special-banner-1-D3.gif"} alt="Trả chậm 0% · Miễn phí giao hàng · Bảo hành đến 5 năm · Miễn phí bảo dưỡng" loading="lazy" style={{ display: "block", width: "100%", height: "auto" }} />
    </div>
  );
}

function HomePageCpBackToTop() {
  const [show, setShow] = React.useState(false);
  const mobileFab = useHomecpMobile();
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 600);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <button aria-label="Lên đầu trang" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} style={{ position: "fixed", right: mobileFab ? 14 : 28, bottom: mobileFab ? 20 : 28, zIndex: 90, width: mobileFab ? 44 : 60, height: mobileFab ? 40 : 52, borderRadius: mobileFab ? 12 : 14, border: "1px solid var(--border)", cursor: "pointer", background: "#fff", color: "var(--primary)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: mobileFab ? 18 : "calc(13px + 9px*var(--ts))", 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>
  );
}

function HomePageCp({ onAdd, onOpen }) {
  const mobile = useHomecpMobile();
  const nav = () => onOpen && onOpen(window.XedapApiData.PRODUCTS[0]);
  return (
    <main style={{ paddingTop: mobile ? 56 : 106, background: "#F5F7FD", borderBottom: "1px solid var(--border)" }}>
      <style>{`@keyframes homecpRailFlash{0%,100%{box-shadow:0 0 0 0 rgba(20,47,247,0)}25%,75%{box-shadow:0 0 0 4px color-mix(in srgb,var(--primary) 30%,transparent)}}.homecp-rail-flash{animation:homecpRailFlash 1.2s var(--ease-out)}.homecp-rail-item:hover{background:color-mix(in srgb,var(--primary) 7%,#fff);color:var(--primary)!important}.homecp-seeall:hover{text-decoration:underline}.homecp-flash-arrow:hover{background:#fff!important;box-shadow:0 2px 10px rgba(11,27,63,.16)}.homecp-flash-icons::-webkit-scrollbar{display:none}.homecp-slot-rail::-webkit-scrollbar{display:none}.homecp-mega-link:hover{color:var(--primary)!important}.homecp-acc-tile:hover{border-color:var(--primary)!important}.homecp-hero-arrow:hover{background:rgba(255,255,255,.85)!important}.homecp-hero-stage:hover .homecp-hero-arrow{opacity:1!important;pointer-events:auto!important}.homecp-offer-link:hover{background:color-mix(in srgb,var(--primary) 6%,#fff)}@keyframes homecpTabZoom{from{transform:scale(1.12);opacity:.55}to{transform:scale(1);opacity:1}}`}</style>
      <div id="homecp-page" style={{ maxWidth: 1440, margin: "0 auto", padding: mobile ? "10px 12px 40px" : "12px 24px 56px" }}>
        {mobile ? (
          <HomePageCpHero onNav={nav} mobile />
        ) : (
        <div style={{ display: "grid", gridTemplateColumns: "268px minmax(0,1fr)", gridTemplateRows: "minmax(0,1fr) auto", height: 537, gap: 12, alignItems: "stretch" }}>
          <HomePageCpRail onNav={nav} />
          <HomePageCpHero onNav={nav} />
        </div>
        )}
        <HomePageCpUsp />
        {mobile && <HomePageCpRailMobile onNav={nav} />}
        <HomePageCpFlashSlot onOpen={onOpen} />
        <HomePageCpSuggest onAdd={onAdd} onOpen={onOpen} />
        <HomePageCpFlash onAdd={onAdd} onOpen={onOpen} />
        {HOMECP_SECTIONS.slice(0, 2).map((s) => <HomePageCpSection key={s.key} section={s} onAdd={onAdd} onOpen={onOpen} />)}
        <HomePageCpAccessoryStrip onNav={nav} slot={1} />
        {HOMECP_SECTIONS.slice(2, 4).map((s) => <HomePageCpSection key={s.key} section={s} onAdd={onAdd} onOpen={onOpen} />)}
        <HomePageCpAccessoryStrip onNav={nav} slot={2} />
        {HOMECP_SECTIONS.slice(4).map((s) => <HomePageCpSection key={s.key} section={s} onAdd={onAdd} onOpen={onOpen} />)}
        <HomePageCpDualPanels onNav={nav} />
        <HomePageCpViewed onAdd={onAdd} onOpen={onOpen} />
        <HomePageCpVideos onOpen={onOpen} />
        <HomePageCpOffers onNav={nav} />
        <HomePageCpBrandRow onNav={nav} />
        <HomePageCpServiceBanner onNav={nav} />
        <HomePageCpNews />
      </div>
      <HomePageCpBackToTop />
    </main>
  );
}

Object.assign(window, { HomePageCp, HomePageCpRailMobile, HomePageCpMenu, HomePageCpMenuFlyout, HomePageCpFlashSlot, homecpFocusRail, useHomecpMobile });
