// Xedap.vn — Collection Category page (danh mục sản phẩm).
// Category banner strip → toolbar → filter rail + product grid → pagination
// → recently viewed → frequently bought together → related stories.
const { Badge, PriceTag, Rating, ColorSwatches, ProductCard } = window.XedapVnDesignSystem_03b1c0;

const BIKE = "https://api.xedap.vn/products/RAPTOR/rally-1-b-2026-metallicblack_2.jpg";

const CAT_BANNERS = [
  { eyebrow: "ĐỊA HÌNH", title: ["XE ĐẠP", "ĐỊA HÌNH"], bg: "#1f2430", img: "https://cdn.hstatic.net/files/200001086651/file/dia_hinh.png" },
  { eyebrow: "ĐƯỜNG PHỐ", title: ["XE THỂ THAO", "ĐƯỜNG PHỐ"], bg: "#f2551e", img: "https://cdn.hstatic.net/files/200001086651/file/the_thao.png" },
  { eyebrow: "GẤP GỌN", title: ["XE ĐẠP", "GẤP"], bg: "#22262f", img: "https://cdn.hstatic.net/files/200001086651/file/gap.png" },
  { eyebrow: "TỐC ĐỘ", title: ["XE ĐẠP", "ĐUA"], bg: "#2f5aa6", img: "https://cdn.hstatic.net/files/200001086651/file/dua.png" },
];

const FILTERS = [
  { title: "Danh mục", open: true, options: ["Xe địa hình", "Xe đường phố", "Xe gấp", "Xe đua"] },
  { title: "Thương hiệu", open: true, options: ["RAPTOR", "JAVA", "GIANT", "TrinX"] },
  ...["Ưu đãi", "Giới tính", "Kích cỡ", "Cỡ bánh", "Mục đích sử dụng", "Khoảng giá", "Giảm xóc", "Tính năng", "Loại phanh", "Trợ lực điện", "Màu sắc", "Chất liệu khung", "Đánh giá", "Kiểu ghi đông", "Số cấp tốc độ", "Dòng sản phẩm", "Bề rộng lốp", "Trọng lượng", "Hành trình phuộc"].map((title) => ({ title, options: [] })),
];

const SWATCHES = [
  ["#8a9099", "#7fb2e0", "#e7d9b8", "#e7e7e7", "#b91c1c", "#20242c"],
  ["#20242c", "#7fb2e0", "#e7d9b8", "#e7e7e7", "#b91c1c", "#8a9099"],
  ["#8a9099", "#e7d9b8", "#e7e7e7", "#b91c1c", "#20242c", "#7fb2e0"],
];

const mkProduct = (i) => ({
  slug: `mtb-collection-${i}`,
  brand: "RAPTOR",
  name: "Xe Đạp Địa Hình MTB RAPTOR Rally 1B – Bánh 24 Inches",
  price: 4999000,
  originalPrice: 5599000,
  colors: SWATCHES[i % SWATCHES.length],
  score: 4.9,
  count: 288,
  seed: `xedap-vn-mtb-collection-${i}`,
});

const GRID = Array.from({ length: 12 }, (_, i) => mkProduct(i));
const VIEWED = Array.from({ length: 3 }, (_, i) => mkProduct(100 + i));

const ADDONS = [
  { slug: "addon-lazer-tonic", brand: "LAZER", name: "Nón Bảo Hiểm Xe Đạp Thể Thao (52-56cm) LAZER Tonic Helmet", price: 2090000, image: "https://cdn.hstatic.net/files/200001086651/file/105.png", addon: true },
  { slug: "addon-monton-glove", brand: "Monton", name: "Bao Tay Ngắn Unisex – MONTON – Skull Monton SKMT", price: 299000, originalPrice: 330000, image: "https://cdn.hstatic.net/files/200001086651/file/106.png", addon: true },
  { slug: "addon-monton-jersey", brand: "Monton", name: "Áo Đạp Xe Ngắn Tay Nam – MONTON – Skull Monton", price: 749000, originalPrice: 1000000, image: "https://cdn.hstatic.net/files/200001086651/file/107.png", addon: true },
].map((p, i) => ({ colors: SWATCHES[i % SWATCHES.length], score: 4.9, count: 288, ...p }));

const STORIES = [
  { img: "https://cdn.hstatic.net/files/200001086651/file/cach_chon_xe_dap_di_lam_phu_hop_hang_ngay.png", date: "Apr 7, 2026", title: "Cách chọn xe đạp đi làm phù hợp hằng ngày" },
  { img: "https://cdn.hstatic.net/files/200001086651/file/ky_thuat_vao_cua_an_toan_khi_dap_xe_the_thao.png", date: "Sep 11, 2025", title: "Kỹ thuật vào cua an toàn khi đạp xe thể thao" },
  { img: "https://cdn.hstatic.net/files/200001086651/file/xe_dap_dua_la_gi__huong_dan_chon_xe_cho_nguoi_moi.png", date: "Jan 7, 2026", title: "Xe đạp đua là gì? Hướng dẫn chọn xe cho người mới" },
  { img: "https://cdn.hstatic.net/files/200001086651/file/kinh_nghiem_dap_xe_theo_nhom_an_toan_va_hieu_qua.png", date: "Jan 7, 2026", title: "Kinh nghiệm đạp xe theo nhóm an toàn và hiệu quả" },
];

const fmt = (n) => new Intl.NumberFormat("vi-VN").format(n) + "₫";

function CatBannerStrip({ active }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", borderBottom: "1px solid var(--border)" }}>
      {CAT_BANNERS.map((b, i) => {
        const isActive = i === 3;
        return (
          <a key={i} style={{ position: "relative", height: 96, overflow: "hidden", background: b.bg, cursor: "pointer", textDecoration: "none", display: "flex", alignItems: "center" }}>
            <img src={b.img} alt="" style={{ position: "absolute", right: 0, top: 0, height: "100%", width: "55%", objectFit: "cover", opacity: 0.55, maskImage: "linear-gradient(90deg,transparent,#000 60%)", WebkitMaskImage: "linear-gradient(90deg,transparent,#000 60%)" }} />
            <div style={{ position: "relative", padding: "0 20px", color: "#fff" }}>
              <span style={{ display: "block", fontSize: 10, fontWeight: 600, letterSpacing: ".14em", opacity: 0.85, marginBottom: 4 }}>{b.eyebrow}</span>
              {b.title.map((t, j) => (
                <span key={j} style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 20, lineHeight: 1.05, letterSpacing: "-0.01em" }}>{t}</span>
              ))}
            </div>
            {isActive && <span style={{ position: "absolute", left: 0, bottom: 0, height: 3, width: "100%", background: "var(--primary)" }} />}
          </a>
        );
      })}
    </div>
  );
}

function FilterAccordion({ f }) {
  const [open, setOpen] = React.useState(!!f.open);
  const [sel, setSel] = React.useState([]);
  const toggle = (o) => setSel((s) => s.includes(o) ? s.filter((x) => x !== o) : [...s, o]);
  return (
    <div style={{ borderBottom: "1px solid var(--border)" }}>
      <button onClick={() => setOpen((o) => !o)} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 0", background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--foreground)" }}>
        {f.title}
        <i className={`ph ${open ? "ph-caret-up" : "ph-caret-down"}`} style={{ fontSize: 14, color: "var(--muted-foreground)" }} />
      </button>
      {open && f.options.length > 0 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 10, paddingBottom: 16 }}>
          {f.options.map((o) => (
            <label key={o} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "rgba(51,51,51,.85)", cursor: "pointer" }}>
              <span style={{ display: "flex", alignItems: "center", justifyContent: "center", width: 18, height: 18, borderRadius: 5, border: `1.5px solid ${sel.includes(o) ? "var(--primary)" : "var(--input)"}`, background: sel.includes(o) ? "var(--primary)" : "#fff" }}>
                {sel.includes(o) && <i className="ph ph-check" style={{ fontSize: 12, color: "#fff" }} />}
              </span>
              <input type="checkbox" checked={sel.includes(o)} onChange={() => toggle(o)} style={{ display: "none" }} />
              {o}
            </label>
          ))}
        </div>
      )}
    </div>
  );
}

function StockToggle() {
  const [mode, setMode] = React.useState("pickup");
  const Opt = ({ id, title, sub, action }) => {
    const on = mode === id;
    return (
      <button onClick={() => setMode(id)} style={{ textAlign: "left", width: "100%", display: "flex", gap: 10, padding: 12, marginBottom: 8, background: on ? "var(--accent)" : "#fff", border: `1px solid ${on ? "var(--primary)" : "var(--border)"}`, borderRadius: "var(--radius-md)", cursor: "pointer" }}>
        <i className={`ph ${on ? "ph-check-circle" : "ph-circle"}`} style={{ fontSize: 18, color: on ? "var(--success)" : "var(--muted-foreground)", marginTop: 1 }} />
        <span style={{ display: "flex", flexDirection: "column", gap: 3 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--foreground)" }}>{title}</span>
          {sub && <span style={{ fontSize: 12, lineHeight: 1.4, color: "var(--muted-foreground)" }}>{sub}</span>}
          {action && <span style={{ fontSize: 12, fontWeight: 500, color: "var(--primary)" }}>{action}</span>}
        </span>
      </button>
    );
  };
  return (
    <div style={{ marginBottom: 16 }}>
      <Opt id="pickup" title="Nhận tại showroom (23)" sub="Có sẵn tại Q.5 · sẵn sàng trong 2 giờ" action="Đổi showroom" />
      <Opt id="ship" title="Giao tận nơi (23)" />
    </div>
  );
}

function ProductRefCard({ p, onAdd, onOpen }) {
  const image = p.image ? p.image : (p.addon ? "https://picsum.photos/seed/" + p.seed + "/600/400?grayscale" : BIKE);
  return <ProductCard product={{ ...p, image, code: "Thương hiệu: " + p.brand }} onAdd={onAdd} onClick={() => onOpen && onOpen(p)} />;
}

function Section({ title, children }) {
  return (
    <section style={{ maxWidth: 1440, margin: "0 auto", padding: "0 24px 8px" }}>
      <h2 style={{ margin: "48px 0 20px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 24, letterSpacing: "-0.01em" }}>{title}</h2>
      {children}
    </section>
  );
}

function CollectionCategory({ onAdd, onOpen }) {
  const [sort, setSort] = React.useState("Phù hợp nhất");
  const [chips, setChips] = React.useState(["Bánh 24 inch", "Nữ"]);
  const [page, setPage] = React.useState(1);
  const removeChip = (c) => setChips((s) => s.filter((x) => x !== c));

  return (
    <main>
      <CatBannerStrip />

      {/* Breadcrumb */}
      <div style={{ borderBottom: "1px solid var(--border)" }}>
        <nav style={{ maxWidth: 1440, margin: "0 auto", padding: "12px 24px", display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--muted-foreground)" }}>
          <a style={{ color: "var(--muted-foreground)", textDecoration: "none", cursor: "pointer" }}>Trang chủ</a>
          <i className="ph ph-caret-right" style={{ fontSize: 11 }} />
          <a style={{ color: "var(--muted-foreground)", textDecoration: "none", cursor: "pointer" }}>Xe đạp</a>
          <i className="ph ph-caret-right" style={{ fontSize: 11 }} />
          <span style={{ color: "var(--foreground)", fontWeight: 500 }}>Xe đạp địa hình</span>
        </nav>
      </div>

      {/* Toolbar */}
      <div style={{ borderBottom: "1px solid var(--border)" }}>
        <div style={{ maxWidth: 1440, margin: "0 auto", padding: "18px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
          <h1 style={{ margin: 0, fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 22, letterSpacing: "-0.01em" }}>
            XE ĐẠP ĐỊA HÌNH <span style={{ fontWeight: 400, fontSize: 15, color: "var(--muted-foreground)" }}>(53 sản phẩm)</span>
          </h1>
          <span style={{ fontSize: 13, color: "var(--muted-foreground)" }}>Hiển thị 1–12 / 53 sản phẩm</span>
        </div>
      </div>

      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "28px 24px 24px", display: "grid", gridTemplateColumns: "280px 1fr", gap: 40, alignItems: "start" }}>
        {/* Filter rail */}
        <aside style={{ position: "sticky", top: 80 }}>
          <h2 style={{ margin: "0 0 16px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 18 }}>Bộ lọc</h2>
          <div>{FILTERS.map((f) => <FilterAccordion key={f.title} f={f} />)}</div>
        </aside>

        {/* Grid column */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22, flexWrap: "wrap" }}>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, marginLeft: "auto", order: 2 }}>
              <span style={{ color: "var(--muted-foreground)" }}>Sắp xếp:</span>
              <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ height: 38, padding: "0 12px", borderRadius: "var(--radius-sm)", border: "1px solid var(--input)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 500, cursor: "pointer" }}>
                {["Phù hợp nhất", "Giá thấp → cao", "Giá cao → thấp", "Mới nhất", "Bán chạy"].map((s) => <option key={s}>{s}</option>)}
              </select>
            </label>
            {chips.map((c) => (
              <button key={c} onClick={() => removeChip(c)} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 30, padding: "0 12px", borderRadius: 5, border: "1px solid var(--border)", background: "var(--secondary)", fontSize: 13, color: "var(--foreground)", cursor: "pointer" }}>
                {c} <i className="ph ph-x" style={{ fontSize: 12 }} />
              </button>
            ))}
            {chips.length > 0 && (
              <button onClick={() => setChips([])} style={{ background: "none", border: "none", color: "var(--primary)", fontSize: 13, fontWeight: 500, cursor: "pointer" }}>Xóa tất cả</button>
            )}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 28 }}>
            {GRID.map((p) => <ProductRefCard key={p.slug} p={p} onAdd={onAdd} onOpen={onOpen} />)}
          </div>

          {/* Pagination */}
          <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 6, margin: "40px 0 8px" }}>
            {[1, 2, 3, 4, 5].map((n) => (
              <button key={n} onClick={() => setPage(n)} style={{ width: 44, height: 44, borderRadius: 5, border: "none", background: n === page ? "var(--foreground)" : "transparent", color: n === page ? "#fff" : "var(--foreground)", fontFamily: "var(--font-sans)", fontSize: 16, fontWeight: 500, cursor: "pointer" }}>{n}</button>
            ))}
            <button onClick={() => setPage((p) => Math.min(5, p + 1))} aria-label="Trang sau" style={{ width: 44, height: 44, borderRadius: 5, border: "none", background: "transparent", color: "var(--foreground)", cursor: "pointer" }}><i className="ph ph-caret-right" style={{ fontSize: 16 }} /></button>
          </div>
        </div>
      </div>

      {/* Recently viewed */}
      <Section title="Xe đạp bạn đã xem">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 28 }}>
          {VIEWED.map((p) => <ProductRefCard key={p.slug} p={p} onAdd={onAdd} onOpen={onOpen} />)}
        </div>
      </Section>

      {/* Frequently bought */}
      <Section title="Thường được mua cùng">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 28 }}>
          {ADDONS.map((p) => <ProductRefCard key={p.slug} p={p} onAdd={onAdd} onOpen={onOpen} />)}
        </div>
      </Section>

      {/* Related stories */}
      <section style={{ maxWidth: 1440, margin: "0 auto", padding: "0 24px 80px" }}>
        <h2 style={{ margin: "48px 0 20px", fontFamily: "var(--font-heading)", fontWeight: 800, fontSize: 28, letterSpacing: "-0.01em" }}>Bài viết liên quan</h2>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
          {STORIES.map((s, i) => (
            <a key={i} style={{ position: "relative", display: "block", aspectRatio: "3/4", borderRadius: "var(--radius)", overflow: "hidden", cursor: "pointer", textDecoration: "none" }}>
              <img src={s.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,transparent 40%,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.85, marginBottom: 6 }}>Cập nhật: {s.date}</span>
                <span style={{ display: "block", fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: 16, lineHeight: 1.25 }}>{s.title}</span>
              </div>
            </a>
          ))}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { CollectionCategory });
