// Xedap.vn — Blog landing page.
// Blocks: search → hero → featured stories (image/video toggle) → assembly-clip
// videos → category carousels (Kỷ lục / Câu chuyện / Cẩm nang) → owner stories
// → store suggestion → product suggestions (bestsellers).
const { Badge, PriceTag, Rating, Button, ProductCardCp: BlogProductCard } = window.XedapVnDesignSystem_03b1c0;

const PIC = (seed, w = 800, h = 600) => `https://picsum.photos/seed/${encodeURIComponent(seed)}/${w}/${h}`;
const fmt = (n) => new Intl.NumberFormat("vi-VN").format(n) + "đ";
const YT = (id) => `https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;
const YT_THUMB = (id) => `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;

const MAX = 1280;

// ── Shared bits ──────────────────────────────────────────────────────────
function SectionHead({ title, sort, onSort, size = 30, kicker }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 20, flexWrap: "wrap" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <h2 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: size, letterSpacing: "-0.01em", lineHeight: 1.05 }}>{title}</h2>
      </div>
    </div>
  );
}

// Horizontal scroller with arrows + progress track.
function Carousel({ children, gap = 20 }) {
  const ref = React.useRef(null);
  const [prog, setProg] = React.useState(0);
  const [thumb, setThumb] = React.useState(0.4);
  const recalc = React.useCallback(() => {
    const el = ref.current; if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    setProg(max > 0 ? el.scrollLeft / max : 0);
    setThumb(el.scrollWidth > 0 ? Math.max(0.12, el.clientWidth / el.scrollWidth) : 1);
  }, []);
  React.useEffect(() => { recalc(); const el = ref.current; if (!el) return; el.addEventListener("scroll", recalc, { passive: true }); window.addEventListener("resize", recalc); return () => { el.removeEventListener("scroll", recalc); window.removeEventListener("resize", recalc); }; }, [recalc]);
  const nudge = (dir) => { const el = ref.current; if (!el) return; el.scrollBy({ left: dir * el.clientWidth * 0.82, behavior: "smooth" }); };
  const atEnd = prog >= 0.9;
  return (
    <div>
      <div ref={ref} style={{ display: "flex", gap, overflowX: "auto", scrollBehavior: "smooth", paddingBottom: 4, scrollbarWidth: "none", msOverflowStyle: "none" }} className="xd-noscrollbar">{children}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 20 }}>
        <button onClick={() => nudge(-1)} aria-label="Trước" style={blogArrowStyle}><i className="ph ph-arrow-left" style={{ fontSize: "calc(13px + 3px*var(--ts))" }} /></button>
        <button onClick={() => nudge(1)} aria-label="Sau" style={blogArrowStyle}><i className="ph ph-arrow-right" style={{ fontSize: "calc(13px + 3px*var(--ts))" }} /></button>
        <div style={{ position: "relative", flex: 1, height: 3, background: "var(--border)", borderRadius: 5 }}>
          <div style={{ position: "absolute", top: 0, height: "100%", borderRadius: 5, background: "var(--foreground)", width: `${thumb * 100}%`, left: `${prog * (1 - thumb) * 100}%`, transition: "left .1s linear" }} />
        </div>
        <i className="ph ph-arrow-right" aria-hidden="true" style={{ flex: "0 0 auto", fontSize: "calc(13px + 9px*var(--ts))", fontWeight: 700, color: "var(--primary)", opacity: atEnd ? 1 : 0, transform: atEnd ? "translateX(0)" : "translateX(-10px)", transition: "opacity .3s var(--ease-out), transform .3s var(--ease-out)", animation: atEnd ? "xdNudge 1s ease-in-out infinite" : "none" }} />
        <a style={{ flex: "0 0 auto", display: "inline-flex", alignItems: "center", gap: 8, padding: "9px 18px", fontSize: 13, fontWeight: 700, letterSpacing: ".01em", color: "#fff", background: "var(--primary)", borderRadius: 5, textDecoration: "none", cursor: "pointer", whiteSpace: "nowrap", boxShadow: atEnd ? "0 0 0 4px color-mix(in srgb, var(--primary) 22%, transparent)" : "none", transition: "box-shadow .3s var(--ease-out)" }}>Xem tất cả</a>
      </div>
    </div>
  );
}
const blogArrowStyle = { width: 40, height: 40, flex: "0 0 40px", borderRadius: 5, border: "1px solid var(--border)", background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--foreground)" };

// Click-to-play video poster → YouTube iframe.
// Only one poster plays at a time: playing one broadcasts its id; the rest reset.
let VP_SEQ = 0;
function VideoPoster({ seed, videoId, radius = "var(--radius-md)", overlay }) {
  const idRef = React.useRef(++VP_SEQ);
  const [play, setPlay] = React.useState(false);
  React.useEffect(() => {
    const onPlay = (e) => { if (e.detail !== idRef.current) setPlay(false); };
    window.addEventListener("xd-video-play", onPlay);
    return () => window.removeEventListener("xd-video-play", onPlay);
  }, []);
  const start = () => { window.dispatchEvent(new CustomEvent("xd-video-play", { detail: idRef.current })); setPlay(true); };
  return (
    <div style={{ position: "relative", width: "100%", height: "100%", borderRadius: radius, overflow: "hidden", background: "#0b0d12" }}>
      {play ? (
        <React.Fragment>
          <iframe src={YT(videoId)} title="video" referrerPolicy="strict-origin-when-cross-origin" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }} />
          <button onClick={() => setPlay(false)} aria-label="Đóng video" style={{ position: "absolute", right: 10, top: 10, zIndex: 2, width: 34, height: 34, borderRadius: 5, border: "none", background: "rgba(0,0,0,.6)", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><i className="ph ph-x" style={{ fontSize: "calc(13px + 3px*var(--ts))" }} /></button>
        </React.Fragment>
      ) : (
        <button onClick={start} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0, padding: 0, cursor: "pointer", background: "none" }}>
          <img src={YT_THUMB(videoId)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          <span style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,rgba(0,0,0,.05),rgba(0,0,0,.35))" }} />
          <span style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)", width: 62, height: 62, borderRadius: 5, background: "rgba(255,255,255,.92)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 30px rgba(0,0,0,.35)" }}>
            <i className="ph-fill ph-play" style={{ fontSize: "calc(13px + 11px*var(--ts))", color: "var(--primary)", marginLeft: 3 }} />
          </span>
          {overlay}
        </button>
      )}
    </div>
  );
}

// ── Data ───────────────────────────────────────────────────────────────
const FEATURED = [
  { kicker: "SỰ KIỆN", type: "video", seed: "xd-blog-tdf", videoId: "_tCVXFytsFY", title: "Dòng xe hybrid đỉnh cao: Giant Roam 4, bánh 700C - 2025", meta: "Khám phá mẫu hybrid đa năng cho cả phố thị lẫn đường trường — vận hành êm, bền bỉ và linh hoạt trên mọi cung đường.", cta: "Đọc bài viết" },
  { kicker: "CÔNG NGHỆ", type: "video", seed: "xd-blog-gline", videoId: "IPfR-l6CABU", title: "Tinh tế & nữ tính cùng Momentum iNeed Latte 2026", meta: "Mẫu xe đô thị dành riêng cho phái đẹp — thiết kế thanh lịch, trang bị tiện dụng cho hành trình mỗi ngày.", cta: "Tìm hiểu thêm" },
];

const CLIPS = [
  { seed: "xd-clip-fold", videoId: "4fqlRpuF8vk", title: "Cách điều chỉnh chiều cao yên xe đạp", tag: "SETUP" },
  { seed: "xd-clip-brake", videoId: "5rZH7Vcmx3I", title: "Lắp ráp Java Neo 9S và Neo 9SE dễ dàng", tag: "LẮP RÁP" },
  { seed: "xd-clip-chain", videoId: "eJuznRrlveI", title: "Hướng dẫn lắp ráp Giant Rincon 2", tag: "LẮP RÁP" },
  { seed: "xd-clip-fit", videoId: "84lL3eL7_tM", title: "Quy trình sửa chữa & vệ sinh đùm líp", tag: "BẢO DƯỠNG" },
];

const ICONIC = [
  { seed: "xd-ic-1", img: "https://cdn.hstatic.net/files/200001086651/file/108.png", title: "Vô địch giải đua địa hình toàn quốc 2025", meta: "Đội Xedap.vn Racing giành ngôi đầu trên chiếc RAPTOR Rally sau vòng đua nghẹt thở." },
  { seed: "xd-ic-2", img: "https://cdn.hstatic.net/files/200001086651/file/109.png", title: "Kỷ lục leo đèo Hải Vân bằng xe trợ lực", meta: "Chinh phục 21km đèo chỉ trong 58 phút — cột mốc mới cho dòng e-bike." },
  { seed: "xd-ic-3", img: "https://cdn.hstatic.net/files/200001086651/file/110.png", title: "Chặng touring xuyên Việt 1.700km", meta: "Hành trình Bắc–Nam trên chiếc JAVA Touring, không một lần hỏng hóc." },
  { seed: "xd-ic-4", img: "https://cdn.hstatic.net/files/200001086651/file/111.png", title: "Giải phong trào lớn nhất miền Nam", meta: "3.200 tay đua góp mặt, Xedap.vn tài trợ toàn bộ kỹ thuật hậu cần." },
  { seed: "xd-ic-5", img: "https://cdn.hstatic.net/files/200001086651/file/112.png", title: "Về nhất giải xe gấp châu Á", meta: "Mẫu NEO-406 lập thành tích ấn tượng ở đường đua thành phố." },
];

const STORIES = [
  { seed: "xd-st-1", date: "12 Th7, 2026", title: "Vì sao dân văn phòng đang chuyển sang xe gấp", img: "https://cdn.hstatic.net/files/200001086651/file/logo.png" },
  { seed: "xd-st-2", date: "05 Th7, 2026", title: "So sánh phanh đĩa dầu và phanh cơ: nên chọn gì?", img: "https://cdn.hstatic.net/files/200001086651/file/60.png" },
  { seed: "xd-st-3", date: "28 Th6, 2026", title: "Bốn cung đường đạp xe đẹp nhất quanh Sài Gòn", img: "https://cdn.hstatic.net/files/200001086651/file/61.png" },
  { seed: "xd-st-4", date: "19 Th6, 2026", title: "Xe trợ lực điện: giải mã những lầm tưởng phổ biến", img: "https://cdn.hstatic.net/files/200001086651/file/62.png" },
  { seed: "xd-st-5", date: "10 Th6, 2026", title: "Cách bảo quản pin e-bike bền gấp đôi tuổi thọ", img: "https://cdn.hstatic.net/files/200001086651/file/63.png" },
];

const GUIDES = [
  { seed: "xd-gd-1", date: "17 Th7, 2026", title: "Cách chọn xe touring: cẩm nang mua hàng đầy đủ", img: "https://cdn.hstatic.net/files/200001086651/file/64.png" },
  { seed: "xd-gd-2", date: "11 Th7, 2026", title: "Chọn xe đi làm hoàn hảo cho người mới bắt đầu", img: "https://cdn.hstatic.net/files/200001086651/file/65.png" },
  { seed: "xd-gd-3", date: "02 Th7, 2026", title: "Xe trợ lực điện tốt nhất: hướng dẫn toàn tập", img: "https://cdn.hstatic.net/files/200001086651/file/67.png" },
  { seed: "xd-gd-4", date: "24 Th6, 2026", title: "Chọn xe địa hình đúng nhu cầu và ngân sách", img: "https://cdn.hstatic.net/files/200001086651/file/66.png" },
  { seed: "xd-gd-5", date: "15 Th6, 2026", title: "Cỡ khung & size xe: chọn sao cho vừa vặn", img: "https://cdn.hstatic.net/files/200001086651/file/68.png" },
];

const MAINTENANCE = [
  { seed: "xd-mt-1", date: "12 Th7, 2026", title: "Bảo dưỡng bộ truyền động: làm sạch và tra dầu đúng cách", img: "https://cdn.hstatic.net/files/200001086651/file/64.png" },
  { seed: "xd-mt-2", date: "05 Th7, 2026", title: "Căn chỉnh phanh đĩa: hết kêu, hết bó", img: "https://cdn.hstatic.net/files/200001086651/file/65.png" },
  { seed: "xd-mt-3", date: "28 Th6, 2026", title: "Kiểm tra áp suất lốp theo từng loại địa hình", img: "https://cdn.hstatic.net/files/200001086651/file/66.png" },
  { seed: "xd-mt-4", date: "20 Th6, 2026", title: "Thay dây và vỏ dây đề: hướng dẫn từng bước", img: "https://cdn.hstatic.net/files/200001086651/file/67.png" },
  { seed: "xd-mt-5", date: "11 Th6, 2026", title: "Lịch bảo dưỡng xe đạp theo quãng đường", img: "https://cdn.hstatic.net/files/200001086651/file/68.png" },
];

const GEAR = [
  { seed: "xd-gr-1", date: "10 Th7, 2026", title: "Chọn mũ bảo hiểm: tiêu chuẩn an toàn và độ thoáng", img: "https://cdn.hstatic.net/files/200001086651/file/65.png" },
  { seed: "xd-gr-2", date: "03 Th7, 2026", title: "Đèn xe đạp cho người đi làm buổi tối", img: "https://cdn.hstatic.net/files/200001086651/file/67.png" },
  { seed: "xd-gr-3", date: "25 Th6, 2026", title: "Giá đèo và túi treo: mang hành lý gọn gàng", img: "https://cdn.hstatic.net/files/200001086651/file/64.png" },
  { seed: "xd-gr-4", date: "16 Th6, 2026", title: "Đồng hồ tốc độ và cảm biến: nên bắt đầu từ đâu", img: "https://cdn.hstatic.net/files/200001086651/file/68.png" },
  { seed: "xd-gr-5", date: "07 Th6, 2026", title: "Quần áo đạp xe cho khí hậu nhiệt đới", img: "https://cdn.hstatic.net/files/200001086651/file/66.png" },
];

const OWNER = [
  { seed: "xd-ow-1", date: "Cửa hàng Q.5", title: "Ngày hội đạp xe cộng đồng tại showroom Nguyễn Văn Cừ", img: "https://cdn.hstatic.net/files/200001086651/file/xedap_-_hinh_demo_ui_ux__1_.png" },
  { seed: "xd-ow-2", date: "Sự kiện", title: "Workshop bảo dưỡng miễn phí cuối tuần", img: "https://cdn.hstatic.net/files/200001086651/file/72.png" },
  { seed: "xd-ow-3", date: "Câu chuyện", title: "Anh Minh và hành trình 10.000km cùng chiếc JAVA", img: "https://cdn.hstatic.net/files/200001086651/file/75.png" },
  { seed: "xd-ow-4", date: "Cửa hàng Đà Nẵng", title: "Khai trương showroom thứ 32 trên toàn quốc", img: "https://cdn.hstatic.net/files/200001086651/file/73.png" },
  { seed: "xd-ow-5", date: "Sự kiện", title: "Đêm ra mắt bộ sưu tập xe đua carbon 2026", img: "https://cdn.hstatic.net/files/200001086651/file/76.png" },
];

// ── Blocks ─────────────────────────────────────────────────────────────
function SearchBar() {
  const [v, setV] = React.useState("");
  const [focus, setFocus] = React.useState(false);
  return (
    <div style={{ borderBottom: "1px solid var(--border)", background: "#fff" }}>
      <div style={{ maxWidth: MAX, margin: "0 auto", padding: "18px 24px" }}>
        <form onSubmit={(e) => e.preventDefault()} style={{ display: "flex", alignItems: "center", gap: 8, height: 52, padding: "0 8px 0 18px", background: "#fff", border: `1.5px solid ${focus ? "var(--primary)" : "var(--input)"}`, borderRadius: "var(--radius-pill)", boxShadow: focus ? "0 0 0 4px var(--ring)" : "none", transition: "border-color .18s, box-shadow .18s" }}>
          <i className="ph ph-magnifying-glass" style={{ fontSize: "calc(13px + 7px*var(--ts))", color: "var(--muted-foreground)" }} />
          <input value={v} onChange={(e) => setV(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} placeholder="Bạn tìm gì? Tìm sản phẩm hoặc bài viết…" style={{ flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "calc(13px + 2px*var(--ts))", color: "var(--foreground)" }} />
          <Button size="sm" type="submit" style={{ borderRadius: "var(--radius-pill)", height: 38, padding: "0 22px", boxShadow: "none" }}>Tìm</Button>
        </form>
      </div>
    </div>
  );
}

const BLOG_HERO_SLIDES = [
  { type: "content" },
  { type: "banner", label: "Banner 2" },
  { type: "banner", label: "Banner 3" },
  { type: "banner", label: "Banner 4" },
  { type: "banner", label: "Banner 5" },
];

function BlogHero() {
  const [i, setI] = React.useState(0);
  const [hover, setHover] = React.useState(false);
  const n = BLOG_HERO_SLIDES.length;
  React.useEffect(() => {
    const t = setInterval(() => setI((v) => (v + 1) % n), 6000);
    return () => clearInterval(t);
  }, [n]);
  const arrowStyle = (side) => ({ position: "absolute", top: "50%", [side]: 16, transform: "translateY(-50%)", width: 44, height: 44, borderRadius: "50%", border: "none", background: "rgba(11,13,18,.45)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", opacity: hover ? 1 : 0, transition: "opacity .2s, background .2s", zIndex: 2 });
  return (
    <section style={{ position: "relative", maxWidth: MAX, margin: "24px auto 0", padding: "0 24px" }}>
      <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ position: "relative", height: 540, borderRadius: "var(--radius-lg)", overflow: "hidden", background: "#0b0d12", boxShadow: "0 24px 60px rgba(11,13,18,.28)" }}>
        <button aria-label="Slide trước" onClick={() => setI((v) => (v - 1 + n) % n)} onMouseEnter={(e) => e.currentTarget.style.background = "rgba(11,13,18,.7)"} onMouseLeave={(e) => e.currentTarget.style.background = "rgba(11,13,18,.45)"} style={arrowStyle("left")}>
          <i className="ph ph-caret-left" style={{ fontSize: "calc(13px + 7px*var(--ts))" }} />
        </button>
        <button aria-label="Slide sau" onClick={() => setI((v) => (v + 1) % n)} onMouseEnter={(e) => e.currentTarget.style.background = "rgba(11,13,18,.7)"} onMouseLeave={(e) => e.currentTarget.style.background = "rgba(11,13,18,.45)"} style={arrowStyle("right")}>
          <i className="ph ph-caret-right" style={{ fontSize: "calc(13px + 7px*var(--ts))" }} />
        </button>
        {BLOG_HERO_SLIDES.map((s, idx) => (
          <div key={idx} style={{ position: "absolute", inset: 0, opacity: idx === i ? 1 : 0, transition: "opacity .5s ease", pointerEvents: idx === i ? "auto" : "none" }}>
            {s.type === "content" ? (
              <React.Fragment>
                <img src="https://cdn.hstatic.net/files/200001086651/file/cover_blog.png" alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 1, transform: idx === i ? "scale(1.06)" : "scale(1)", transition: "transform 7s ease-out" }} />
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg,rgba(9,11,15,.92),rgba(9,11,15,.72) 42%,rgba(9,11,15,.25) 72%,rgba(9,11,15,.35))" }} />
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(0deg,rgba(9,11,15,.75),transparent 46%)" }} />
                <div style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 clamp(28px,5vw,72px)" }}>
                  <h1 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 55px*var(--ts))", lineHeight: .98, letterSpacing: "-0.03em", color: "#fff", maxWidth: 760, textShadow: "0 4px 28px rgba(0,0,0,.45)" }}>Câu chuyện<br />trên từng cung đường</h1>
                  <p style={{ margin: "22px 0 0", maxWidth: 520, fontSize: "calc(13px + 5px*var(--ts))", lineHeight: 1.6, color: "rgba(255,255,255,.9)" }}>Kinh nghiệm, cẩm nang, sự kiện và những hành trình truyền cảm hứng từ cộng đồng đạp xe Việt Nam.</p>
                </div>
              </React.Fragment>
            ) : (
              <div style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(135deg,#1a1d24,#1a1d24 14px,#22262f 14px,#22262f 28px)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <div style={{ position: "absolute", inset: 0, background: "rgba(11,13,18,.6)" }} />
                <span style={{ position: "relative", fontFamily: "var(--font-mono, monospace)", fontSize: "calc(13px + 1px*var(--ts))", letterSpacing: ".08em", color: "rgba(255,255,255,.8)" }}>{s.label}</span>
              </div>
            )}
          </div>
        ))}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 20, display: "flex", justifyContent: "center", gap: 8 }}>
          {BLOG_HERO_SLIDES.map((_, idx) => (
            <button key={idx} onClick={() => setI(idx)} aria-label={`Slide ${idx + 1}`} style={{ width: idx === i ? 22 : 8, height: 8, borderRadius: "var(--radius-pill)", border: "none", background: idx === i ? "#fff" : "rgba(255,255,255,.45)", cursor: "pointer", transition: "width .25s, background .25s" }} />
          ))}
        </div>
      </div>
    </section>
  );
}

function FeaturedRow({ item, i }) {
  const flip = i % 2 === 1;
  const media = (
    <div style={{ aspectRatio: "3/2", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
      {item.type === "video"
        ? <VideoPoster seed={item.seed} videoId={item.videoId} radius="var(--radius-lg)" />
        : <img src={PIC(item.seed, 900, 600)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
    </div>
  );
  const text = (
    <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", padding: flip ? "0 0 0 8px" : "0 8px 0 0" }}>
      <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", color: "var(--primary)", marginBottom: 12 }}>{item.kicker}</span>
      <h3 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 17px*var(--ts))", lineHeight: 1.12, letterSpacing: "-0.01em" }}>{item.title}</h3>
      <p style={{ margin: "14px 0 0", fontSize: "calc(13px + 2.5px*var(--ts))", lineHeight: 1.65, color: "rgba(51,51,51,.72)", maxWidth: 460 }}>{item.meta}</p>
      <div style={{ marginTop: 24 }}>
        <Button onClick={() => openArticle(item)} style={{ boxShadow: "none" }}>{item.cta}</Button>
      </div>
    </div>
  );
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "stretch" }}>
      {flip ? <React.Fragment>{text}{media}</React.Fragment> : <React.Fragment>{media}{text}</React.Fragment>}
    </div>
  );
}

function Featured() {
  return (
    <section style={{ maxWidth: MAX, margin: "0 auto", padding: "56px 24px 0" }}>
      <SectionHead title="Bài viết nổi bật" kicker="ĐỀ XUẤT" />
      <div style={{ display: "flex", flexDirection: "column", gap: 48 }}>
        {FEATURED.map((f, i) => <FeaturedRow key={i} item={f} i={i} />)}
      </div>
    </section>
  );
}

function Clips() {
  return (
    <section style={{ background: "#0b0d12", marginTop: 44 }}>
      <div style={{ maxWidth: MAX, margin: "0 auto", padding: "48px 24px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "300px 1fr", gap: 48, alignItems: "start" }}>
          <div>
            <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", color: "var(--xd-blue-2)" }}>VIDEO HƯỚNG DẪN</span>
            <h2 style={{ margin: "12px 0 0", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 17px*var(--ts))", lineHeight: 1.1, color: "#fff" }}>Hướng dẫn lắp ráp & bảo dưỡng</h2>
            <p style={{ margin: "16px 0 0", fontSize: "calc(13px + 1.5px*var(--ts))", lineHeight: 1.65, color: "rgba(255,255,255,.6)" }}>Các clip ngắn giúp bạn tự lắp ráp, tinh chỉnh và chăm sóc chiếc xe của mình ngay tại nhà.</p>
            <a style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", marginTop: 22, fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 600, color: "#fff", textDecoration: "none", cursor: "pointer", padding: "11px 24px", border: "1px solid rgba(255,255,255,.7)", borderRadius: "var(--radius-pill)" }}>Xem tất cả clip</a>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
            {CLIPS.map((c, i) => (
              <div key={i} style={{ display: "flex", flexDirection: "column" }}>
                <div style={{ aspectRatio: "1/1" }}>
                  <VideoPoster seed={c.seed} videoId={c.videoId} overlay={<span style={{ position: "absolute", left: 10, top: 10, fontSize: 10, fontWeight: 700, letterSpacing: ".1em", color: "#fff", background: "rgba(0,0,0,.5)", padding: "4px 8px", borderRadius: 5 }}>{c.tag}</span>} />
                </div>
                <h4 style={{ margin: "12px 0 0", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "calc(13px + 1px*var(--ts))", lineHeight: 1.35, color: "#fff" }}>{c.title}</h4>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// Navigate to the standalone blog-detail page (passes the article slug via hash).
const openArticle = (item) => { const slug = (item && (item.slug || item.seed)) || ""; window.location.href = "BlogDetail.html" + (slug ? "#" + encodeURIComponent(slug) : ""); };

// Editorial card: title + meta BELOW landscape thumbnail.
function BelowCard({ item, w = 300 }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a onClick={() => openArticle(item)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ flex: `0 0 ${w}px`, width: w, display: "block", textDecoration: "none", cursor: "pointer" }}>
      <div style={{ aspectRatio: "4/3", borderRadius: "var(--radius-md)", overflow: "hidden", background: "var(--secondary)" }}>
        <img src={item.img || PIC(item.seed, 600, 450)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", transition: "transform .5s var(--ease-out)", transform: hover ? "scale(1.04)" : "none" }} />
      </div>
      <h3 style={{ margin: "14px 0 0", fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "calc(13px + 3px*var(--ts))", lineHeight: 1.28, color: "var(--foreground)" }}>{item.title}</h3>
      <p style={{ margin: "8px 0 0", fontSize: "calc(13px + 0.5px*var(--ts))", lineHeight: 1.55, color: "rgba(51,51,51,.62)" }}>{item.meta}</p>
    </a>
  );
}

// Overlay card: date + title over darkened landscape thumbnail.
function OverlayCard({ item, w = 300, aspect = "4/3" }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a onClick={() => openArticle(item)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ flex: `0 0 ${w}px`, width: w, position: "relative", display: "block", aspectRatio: aspect, borderRadius: "var(--radius-md)", overflow: "hidden", textDecoration: "none", cursor: "pointer" }}>
      <img src={item.img || PIC(item.seed, 640, 480)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", transition: "transform .5s var(--ease-out)", transform: hover ? "scale(1.05)" : "none" }} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,transparent 35%,rgba(0,0,0,.82))" }} />
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: 18, color: "#fff" }}>
        <span style={{ display: "block", fontSize: 11, opacity: 0.82, marginBottom: 7 }}>{item.date}</span>
        <span style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "calc(13px + 3px*var(--ts))", lineHeight: 1.25 }}>{item.title}</span>
      </div>
    </a>
  );
}

function CategoryRow({ title, kicker, data, render }) {
  const [sort, setSort] = React.useState("desc");
  const list = sort === "asc" ? [...data].slice().reverse() : data;
  return (
    <section style={{ maxWidth: MAX, margin: "0 auto", padding: "0 24px" }}>
      <SectionHead title={title} kicker={kicker} size={24} sort={sort} onSort={setSort} />
      <Carousel>{list.map((it, i) => render(it, i))}</Carousel>
    </section>
  );
}

function Categories() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 52, padding: "56px 0 0" }}>
      <CategoryRow title="Sự kiện" kicker="SỰ KIỆN" data={ICONIC} render={(it, i) => <BelowCard key={i} item={it} />} />
      <CategoryRow title="Công nghệ" kicker="CÔNG NGHỆ" data={STORIES} render={(it, i) => <OverlayCard key={i} item={it} />} />
      <CategoryRow title="Khuyến mãi" kicker="KHUYẾN MÃI" data={GUIDES} render={(it, i) => <OverlayCard key={i} item={it} />} />
      <CategoryRow title="Hướng dẫn" kicker="HƯỚNG DẪN" data={MAINTENANCE} render={(it, i) => <OverlayCard key={i} item={it} />} />
      <CategoryRow title="Truyền cảm hứng" kicker="CẢM HỨNG" data={GEAR} render={(it, i) => <OverlayCard key={i} item={it} />} />
    </div>
  );
}

function OwnerStories() {
  const [sort, setSort] = React.useState("desc");
  const list = sort === "asc" ? [...OWNER].slice().reverse() : OWNER;
  return (
    <div style={{ marginTop: 56 }}>
      <section style={{ position: "relative", width: "100%", height: 420, overflow: "hidden", background: "#0b0d12" }}>
        <img src="https://cdn.hstatic.net/files/200001086651/file/cong_dong_va_su_kien.png" alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.75 }} />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(270deg,rgba(11,13,18,.72),rgba(11,13,18,.15) 60%,transparent)" }} />
        <div style={{ position: "relative", maxWidth: MAX, height: "100%", margin: "0 auto", padding: "0 24px", display: "flex", flexDirection: "column", alignItems: "flex-end", justifyContent: "center", textAlign: "right" }}>
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".16em", color: "rgba(255,255,255,.85)", marginBottom: 12 }}>CỘNG ĐỒNG & SỰ KIỆN</span>
          <h2 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: "calc(13px + 27px*var(--ts))", lineHeight: 1.05, color: "#fff", maxWidth: 480 }}>Câu chuyện chủ xe & sự kiện</h2>
          <p style={{ margin: "16px 0 0", maxWidth: 420, fontSize: "calc(13px + 2px*var(--ts))", lineHeight: 1.6, color: "rgba(255,255,255,.78)" }}>Từ những buổi off-ride cuối tuần đến các sự kiện ra mắt — nơi cộng đồng Xedap.vn gặp gỡ và chia sẻ.</p>
          <div style={{ marginTop: 24 }}><Button variant="outline" style={{ background: "transparent", color: "#fff", borderColor: "rgba(255,255,255,.6)" }}>Khám phá</Button></div>
        </div>
      </section>
      <section style={{ maxWidth: MAX, margin: "0 auto", padding: "56px 24px 0" }}>
        <SectionHead title="Bài viết cửa hàng & sự kiện" size={24} sort={sort} onSort={setSort} />
        <Carousel>{list.map((it, i) => <OverlayCard key={i} item={it} />)}</Carousel>
      </section>
    </div>
  );
}

function StoreCTA() {
  return (
    <section style={{ maxWidth: MAX, margin: "56px auto 0", padding: "0 24px" }}>
      <div style={{ position: "relative", height: 340, borderRadius: "var(--radius-lg)", 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 }}><Button>Xem cửa hàng</Button></div>
        </div>
      </div>
    </section>
  );
}

// Ảnh + giá sản phẩm lấy từ api.xedap.vn — ưu tiên các mẫu đang giảm sâu.
function blogApiDeals(n) {
  const api = window.XedapApiData;
  const pool = (api && api.PRODUCTS) || (window.KitData && window.KitData.PRODUCTS) || [];
  return pool.slice().sort((a, b) => (a.discount || 0) - (b.discount || 0)).slice(0, n);
}

function ProductSuggest({ onAdd }) {
  const products = blogApiDeals(10);
  return (
    <section style={{ maxWidth: MAX, margin: "56px auto 72px", padding: "0 24px" }}>
      <SectionHead title="Xe đạp đang có deal tốt" kicker="BÁN CHẠY" />
      <Carousel>
        {products.map((p, i) => <ProductSuggestCard key={p.slug || i} p={p} onAdd={onAdd} />)}
      </Carousel>
    </section>
  );
}

// Card sản phẩm dùng chung style với homepage_cp (ProductCardCp + hover đổi ảnh).
function ProductSuggestCard({ p, onAdd }) {
  const [hover, setHover] = React.useState(false);
  const open = () => { if (p.href) window.open(p.href, "_blank", "noopener"); };
  const image = hover && p.img2 ? p.img2 : p.img;
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ flex: "0 0 268px", width: 268, display: "flex" }}>
      <BlogProductCard
        style={{ flex: 1, minWidth: 0, cursor: p.href ? "pointer" : "default" }}
        product={{
          ...p,
          image,
          status: p.status || "Hàng mới về",
          notes: p.notes || [p.gift, "Trả góp 0% - 0đ phụ phí - 0đ trả trước - kỳ hạn đến 12 tháng"].filter(Boolean),
          delivery: p.delivery ?? "2 Giờ",
        }}
        onClick={open}
      />
    </div>
  );
}

function Blog({ onAdd }) {
  return (
    <main>
      <SearchBar />
      <BlogHero />
      <Featured />
      <Categories />
      <OwnerStories />
      <StoreCTA />
      <ProductSuggest onAdd={onAdd} />
    </main>
  );
}

Object.assign(window, { Blog });
