// Trình gợi ý xe ("Find your bike") — quiz 3 bước trên MỘT trang duy nhất:
// chọn xong một câu → câu đó thu gọn thành dòng tóm tắt, câu kế tiếp trượt mượt xuống ngay bên dưới.
// Không reload, không đổi URL. Yếu tố Chiều cao/Size nằm ngoài phễu, là filter tuỳ chọn ở phần kết quả.
const { Button, ProductCardCp: BikeFinderProductCard } = window.XedapVnDesignSystem_03b1c0;

const bikeFinderStyles = {
  shell: { background: "#fff", paddingBottom: 8 },
  wrap: { width: "100%", maxWidth: 1200, margin: "0 auto", padding: "0 24px" },
  h1: { font: "700 40px/1.15 var(--font-sans)", letterSpacing: "-0.02em", margin: 0, color: "var(--foreground)" },
  h2: { font: "700 28px/1.25 var(--font-sans)", letterSpacing: "-0.02em", margin: 0, color: "var(--foreground)" },
  lead: { font: "400 18px/1.55 var(--font-sans)", color: "var(--muted-foreground)", margin: 0, maxWidth: 620, textWrap: "pretty" },
  eyebrow: { font: "600 12px/1 var(--font-sans)", letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted-foreground)" },
  grid: { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(210px, 1fr))", gap: 14 },
  card: { border: "1px solid var(--border)", borderRadius: 18, background: "#fff", overflow: "hidden", transition: "box-shadow .25s ease, border-color .25s ease" },
};

// Trọng số theo dòng xe cho từng mục đích / cung đường.
const BF_CATS = { mtb: "Xe đạp địa hình", road: "Xe đạp đua", city: "Xe đạp thể thao đường phố", fold: "Xe đạp gấp" };

const BF_PURPOSE = [
  { id: "commute", label: "Đi làm – Đi học", note: "Mỗi ngày, đường quen", icon: "briefcase", boost: { city: 3, fold: 3, road: 1, mtb: 0 } },
  { id: "fitness", label: "Tập thể dục", note: "Rèn thể lực đều đặn", icon: "heartbeat", boost: { road: 3, city: 2, mtb: 1, fold: 0 } },
  { id: "stroll", label: "Dạo phố", note: "Đi gần, nhẹ nhàng", icon: "storefront", boost: { city: 3, fold: 2, mtb: 1, road: 0 } },
  { id: "travel", label: "Đi phượt", note: "Tour dài, mang hành lý", icon: "backpack", boost: { road: 2, city: 3, mtb: 2, fold: 0 } },
  { id: "race", label: "Đua xe", note: "Tốc độ, thi đấu", icon: "trophy", boost: { road: 4, city: 1, mtb: 1, fold: 0 } },
];

const BF_TERRAIN = [
  { id: "street", label: "Đường phố, đường bằng phẳng", icon: "buildings", boost: { city: 3, fold: 3, road: 1, mtb: 0 } },
  { id: "long", label: "Đường trường, đường ngoại ô", icon: "road-horizon", boost: { road: 3, city: 2, mtb: 0, fold: 0 } },
  { id: "trail", label: "Đường gồ ghề, địa hình", icon: "mountains", boost: { mtb: 4, city: 1, road: 0, fold: 0 } },
  { id: "gravel", label: "Đường sỏi đá nhỏ (gravel)", icon: "path", boost: { road: 2, mtb: 3, city: 1, fold: 0 } },
  { id: "mixed", label: "Đường hỗn hợp", icon: "shuffle", boost: { city: 2, mtb: 2, road: 2, fold: 1 } },
];

const BF_BUDGET = [
  { id: "b1", label: "Dưới 5 triệu", min: 0, max: 5000000, icon: "wallet" },
  { id: "b2", label: "5 – 10 triệu", min: 5000000, max: 10000000, icon: "wallet" },
  { id: "b3", label: "10 – 20 triệu", min: 10000000, max: 20000000, icon: "wallet" },
  { id: "b4", label: "Trên 20 triệu", min: 20000000, max: Infinity, icon: "wallet" },
];

const BF_HEIGHTS = [
  { id: "h1", label: "Dưới 1m55", size: "S (48–50)" },
  { id: "h2", label: "1m55 – 1m65", size: "M (52)" },
  { id: "h3", label: "1m66 – 1m75", size: "L (54–56)" },
  { id: "h4", label: "Trên 1m75", size: "XL (58)" },
];

const BF_STEPS = [
  { key: "purpose", n: 1, title: "Mục đích đạp xe chính của bạn là gì?", short: "Mục đích đạp xe", options: BF_PURPOSE },
  { key: "terrain", n: 2, title: "Bạn thường đạp trên cung đường nào?", short: "Cung đường", options: BF_TERRAIN },
  { key: "budget", n: 3, title: "Ngân sách mua xe của bạn trong khoảng bao nhiêu?", short: "Tầm giá", options: BF_BUDGET, hint: "Chúng tôi vẫn hiển thị mẫu lệch nhẹ nếu đó là lựa chọn tốt hơn." },
];

// Cuộn mượt tới một element mà không dùng scrollIntoView.
const bfScrollTo = (el, offset = 96) => {
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.pageYOffset - offset;
  window.scrollTo({ top: Math.max(0, y), behavior: "smooth" });
};

function BikeFinderOption({ selected, onClick, label, note, icon }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ textAlign: "left", cursor: "pointer", background: selected ? "var(--accent)" : "#fff", padding: "16px 16px",
        border: "1px solid " + (selected ? "var(--primary)" : hover ? "var(--xd-gray-300)" : "var(--border)"),
        boxShadow: selected ? "0 0 0 2px color-mix(in srgb, var(--primary) 28%, transparent)" : hover ? "0 6px 18px rgba(17,24,39,.07)" : "none",
        borderRadius: 14, transition: "all .18s ease", display: "flex", alignItems: "center", gap: 12, minHeight: 76 }}>
      <span style={{ width: 44, height: 44, flex: "0 0 auto", borderRadius: 12, background: selected ? "#fff" : "var(--secondary)", display: "grid", placeItems: "center" }}>
        <i className={"ph ph-" + icon} style={{ fontSize: "calc(13px + 11px*var(--ts))", color: selected ? "var(--primary)" : "var(--foreground)" }}></i>
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: "block", font: "600 15px/1.35 var(--font-sans)", color: "var(--foreground)" }}>{label}</span>
        {note && <span style={{ display: "block", marginTop: 3, font: "400 13px/1.35 var(--font-sans)", color: "var(--muted-foreground)" }}>{note}</span>}
      </span>
      <span style={{ width: 20, height: 20, borderRadius: 999, flex: "0 0 auto", border: "1.5px solid " + (selected ? "var(--primary)" : "var(--input)"), background: selected ? "var(--primary)" : "#fff", display: "grid", placeItems: "center" }}>
        {selected && <i className="ph-fill ph-check" style={{ fontSize: 12, color: "#fff" }}></i>}
      </span>
    </button>
  );
}

// Một câu hỏi: mở (grid lựa chọn), đã trả lời (thu gọn thành dòng tóm tắt), hoặc chờ (mờ).
function BikeFinderQuestion({ step, state, value, onPick, onEdit, innerRef }) {
  const open = state === "open";
  const done = state === "done";
  const chosen = step.options.find((o) => o.id === value);
  return (
    <div ref={innerRef} style={{ ...bikeFinderStyles.card, opacity: state === "locked" ? .45 : 1,
      borderColor: open ? "var(--xd-gray-300)" : "var(--border)",
      boxShadow: open ? "0 10px 30px rgba(17,24,39,.07)" : "none" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: open ? "22px 24px 4px" : "18px 24px" }}>
        <span style={{ width: 28, height: 28, flex: "0 0 auto", borderRadius: 999, display: "grid", placeItems: "center",
          background: done ? "var(--primary)" : open ? "var(--foreground)" : "var(--secondary)",
          color: done || open ? "#fff" : "var(--muted-foreground)", font: "600 13px/1 var(--font-sans)" }}>
          {done ? <i className="ph-fill ph-check" style={{ fontSize: "calc(13px + 1px*var(--ts))" }}></i> : step.n}
        </span>
        <span style={{ flex: 1, minWidth: 0 }}>
          {done ? (
            <span style={{ display: "flex", flexWrap: "wrap", alignItems: "baseline", gap: "2px 10px" }}>
              <span style={{ font: "400 14px/1.4 var(--font-sans)", color: "var(--muted-foreground)" }}>{step.short}:</span>
              <span style={{ font: "600 16px/1.4 var(--font-sans)", color: "var(--foreground)" }}>{chosen ? chosen.label : "—"}</span>
            </span>
          ) : (
            <span style={{ display: "block", font: open ? "700 22px/1.3 var(--font-sans)" : "500 17px/1.4 var(--font-sans)", letterSpacing: open ? "-0.01em" : 0, color: open ? "var(--foreground)" : "var(--muted-foreground)" }}>{step.title}</span>
          )}
        </span>
        {done && (
          <button onClick={onEdit} style={{ cursor: "pointer", flex: "0 0 auto", background: "none", border: "1px solid var(--border)", borderRadius: 999, padding: "7px 14px", font: "500 13px/1 var(--font-sans)", color: "var(--foreground)" }}>Đổi</button>
        )}
      </div>
      <div style={{ display: "grid", gridTemplateRows: open ? "1fr" : "0fr", transition: "grid-template-rows .45s cubic-bezier(.4,0,.2,1)" }}>
        <div style={{ overflow: "hidden", minHeight: 0 }}>
          <div style={{ padding: "14px 24px 24px", opacity: open ? 1 : 0, transform: open ? "translateY(0)" : "translateY(-8px)", transition: "opacity .3s ease .06s, transform .35s cubic-bezier(.4,0,.2,1)" }}>
            {step.hint && <p style={{ ...bikeFinderStyles.lead, fontSize: "calc(13px + 2px*var(--ts))", margin: "0 0 16px" }}>{step.hint}</p>}
            <div style={bikeFinderStyles.grid}>
              {step.options.map((o) => (
                <BikeFinderOption key={o.id} icon={o.icon} label={o.label} note={o.note} selected={value === o.id} onClick={() => onPick(step.key, o.id)} />
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Card sản phẩm dùng chung style với homepage_cp (ProductCardCp + hover đổi ảnh).
function BikeFinderCard({ product, onAdd, onOpen }) {
  const [hover, setHover] = React.useState(false);
  const image = (hover && product.img2) || product.image || product.img;
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ display: "flex", minWidth: 0 }}>
      <BikeFinderProductCard
        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ờ",
        }}
        onAdd={onAdd}
        onClick={() => onOpen && onOpen(product)}
      />
    </div>
  );
}

function BikeFinderProgress({ answered }) {
  return (
    <div style={{ position: "sticky", top: 64, zIndex: 5, background: "#fff", borderBottom: "1px solid var(--border)" }}>
      <div style={{ ...bikeFinderStyles.wrap, display: "flex", alignItems: "center", gap: 16, padding: "12px 24px" }}>
        <span style={{ font: "600 13px/1 var(--font-sans)", color: "var(--foreground)", flex: "0 0 auto" }}>{Math.min(answered + 1, 3)}/3 câu</span>
        <div style={{ flex: 1, display: "flex", gap: 6 }}>
          {[0, 1, 2].map((i) => (
            <span key={i} style={{ flex: 1, height: 4, borderRadius: 999, background: i < answered ? "var(--primary)" : "var(--border)", transition: "background .3s ease" }}></span>
          ))}
        </div>
        <span style={{ font: "400 13px/1 var(--font-sans)", color: "var(--muted-foreground)", flex: "0 0 auto" }}>{answered === 3 ? "Đã có kết quả" : "Khoảng 30 giây"}</span>
      </div>
    </div>
  );
}

function BikeFinderResults({ answers, height, onHeight, onAdd, onOpen, onBrowseAll, onRestart, innerRef }) {
  const products = (window.KitData && window.KitData.PRODUCTS) || [];
  const purpose = BF_PURPOSE.find((p) => p.id === answers.purpose);
  const terrain = BF_TERRAIN.find((t) => t.id === answers.terrain);
  const budget = BF_BUDGET.find((b) => b.id === answers.budget) || BF_BUDGET[3];
  const heightOpt = BF_HEIGHTS.find((h) => h.id === height);

  const scored = products.map((p) => {
    let s = 0;
    for (const src of [purpose, terrain]) {
      if (!src) continue;
      for (const [cid, w] of Object.entries(src.boost)) if (p.category === BF_CATS[cid]) s += w;
    }
    if (p.price >= budget.min && p.price <= budget.max) s += 5;
    else s -= Math.min(4, Math.abs(p.price - (p.price > budget.max ? budget.max : budget.min)) / 4000000);
    s += (p.rating - 4.4) * 2;
    return { p, s };
  }).sort((a, b) => b.s - a.s);

  const top = scored.slice(0, 3).map((x) => x.p);
  const outOfBudget = top.some((p) => p.price < budget.min || p.price > budget.max);
  const tags = [purpose && purpose.label, terrain && terrain.label, budget.label, heightOpt && heightOpt.label].filter(Boolean);

  return (
    <section ref={innerRef} style={{ ...bikeFinderStyles.wrap, padding: "48px 24px 88px" }}>
      <span style={bikeFinderStyles.eyebrow}>Kết quả gợi ý</span>
      <h2 style={{ ...bikeFinderStyles.h2, marginTop: 10 }}>3 mẫu xe khớp nhất với bạn</h2>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 18 }}>
        {tags.map((t) => (
          <span key={t} style={{ font: "500 13px/1 var(--font-sans)", color: "var(--accent-foreground)", background: "var(--accent)", borderRadius: 999, padding: "9px 14px", whiteSpace: "nowrap", flex: "0 0 auto" }}>{t}</span>
        ))}
        <button onClick={onRestart} style={{ cursor: "pointer", font: "500 13px/1 var(--font-sans)", color: "var(--muted-foreground)", background: "none", border: "1px solid var(--border)", borderRadius: 999, padding: "9px 14px", whiteSpace: "nowrap", flex: "0 0 auto" }}>Làm lại từ đầu</button>
      </div>

      {/* Chiều cao / size — filter tuỳ chọn, nằm ngoài phễu 3 bước */}
      <div style={{ marginTop: 24, border: "1px solid var(--border)", borderRadius: 16, padding: "18px 20px", display: "flex", flexWrap: "wrap", alignItems: "center", gap: "14px 20px" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 10, font: "600 15px/1.3 var(--font-sans)", color: "var(--foreground)" }}>
          <i className="ph ph-ruler" style={{ fontSize: "calc(13px + 7px*var(--ts))", color: "var(--primary)" }}></i>Chiều cao của bạn
          <span style={{ font: "400 13px/1.3 var(--font-sans)", color: "var(--muted-foreground)" }}>(không bắt buộc)</span>
        </span>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {BF_HEIGHTS.map((h) => {
            const on = height === h.id;
            return (
              <button key={h.id} onClick={() => onHeight(on ? null : h.id)}
                style={{ cursor: "pointer", font: "500 13px/1 var(--font-sans)", padding: "10px 14px", borderRadius: 999, whiteSpace: "nowrap",
                  border: "1px solid " + (on ? "var(--primary)" : "var(--border)"), background: on ? "var(--accent)" : "#fff",
                  color: on ? "var(--accent-foreground)" : "var(--foreground)" }}>{h.label}</button>
            );
          })}
        </div>
        {heightOpt && (
          <span style={{ font: "400 14px/1.4 var(--font-sans)", color: "var(--muted-foreground)" }}>
            Size khung gợi ý: <strong style={{ color: "var(--foreground)", fontWeight: 600 }}>{heightOpt.size}</strong> · xem hướng dẫn chọn size ở trang sản phẩm
          </span>
        )}
      </div>

      {outOfBudget && (
        <div style={{ display: "flex", gap: 8, alignItems: "flex-start", font: "400 14px/1.5 var(--font-sans)", color: "var(--muted-foreground)", marginTop: 16 }}>
          <i className="ph ph-info" style={{ fontSize: "calc(13px + 4px*var(--ts))", color: "var(--primary)", flex: "0 0 auto", marginTop: 1 }}></i>
          <span>Một số mẫu lệch khỏi mức {budget.label.toLowerCase()} nhưng khớp hơn với cách bạn đạp.</span>
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 20, marginTop: 26 }}>
        {top.map((p) => <BikeFinderCard key={p.slug} product={p} onAdd={onAdd} onOpen={onOpen} />)}
      </div>

      <div style={{ background: "var(--secondary)", borderRadius: 16, padding: "28px 32px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap", marginTop: 36 }}>
        <div>
          <div style={{ font: "600 18px/1.3 var(--font-sans)", color: "var(--foreground)" }}>Vẫn muốn xem thêm?</div>
          <div style={{ font: "400 15px/1.4 var(--font-sans)", color: "var(--muted-foreground)", marginTop: 4 }}>Xem toàn bộ danh mục hoặc nhờ tư vấn viên chọn giúp bạn.</div>
        </div>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <Button variant="outline" size="lg" onClick={onBrowseAll}>Xem tất cả xe</Button>
          <Button size="lg" onClick={onBrowseAll}>Liên hệ tư vấn viên</Button>
        </div>
      </div>
    </section>
  );
}

function BikeFinder({ onAdd, onOpen, onBrowseAll }) {
  const [answers, setAnswers] = React.useState({});
  const [height, setHeight] = React.useState(null);
  const [editing, setEditing] = React.useState(null); // key câu đang mở lại để sửa
  const refs = React.useRef({});

  const answeredCount = BF_STEPS.filter((s) => answers[s.key]).length;
  const firstUnanswered = BF_STEPS.find((s) => !answers[s.key]);
  const activeKey = editing || (firstUnanswered && firstUnanswered.key) || null;

  const stateOf = (s) => (s.key === activeKey ? "open" : answers[s.key] ? "done" : "locked");

  const pick = (key, value) => {
    const next = { ...answers, [key]: value };
    setAnswers(next);
    setEditing(null);
    const following = BF_STEPS.find((s) => !next[s.key]);
    const targetKey = following ? following.key : "results";
    setTimeout(() => bfScrollTo(refs.current[targetKey], following ? 120 : 96), 260);
  };

  const restart = () => {
    setAnswers({}); setHeight(null); setEditing(null);
    setTimeout(() => bfScrollTo(refs.current.purpose, 120), 60);
  };

  return (
    <div style={bikeFinderStyles.shell}>
      <BikeFinderProgress answered={answeredCount} />
      <section style={{ ...bikeFinderStyles.wrap, padding: "44px 24px 8px" }}>
        <span style={bikeFinderStyles.eyebrow}>Trình gợi ý xe</span>
        <h1 style={{ ...bikeFinderStyles.h1, marginTop: 10 }}>Tìm chiếc xe dành cho bạn</h1>
        <p style={{ ...bikeFinderStyles.lead, marginTop: 14 }}>Trả lời 3 câu hỏi ngắn về cách bạn muốn đạp. Kết quả hiện ngay bên dưới, không cần chuyển trang.</p>
      </section>

      <div style={{ ...bikeFinderStyles.wrap, padding: "28px 24px 0", display: "flex", flexDirection: "column", gap: 14 }}>
        {BF_STEPS.map((s) => (
          <BikeFinderQuestion key={s.key} step={s} state={stateOf(s)} value={answers[s.key]}
            innerRef={(el) => { refs.current[s.key] = el; }}
            onPick={pick} onEdit={() => { setEditing(s.key); setTimeout(() => bfScrollTo(refs.current[s.key], 120), 60); }} />
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateRows: answeredCount === 3 ? "1fr" : "0fr", transition: "grid-template-rows .5s cubic-bezier(.4,0,.2,1)" }}>
        <div style={{ overflow: "hidden", minHeight: 0 }}>
          <div style={{ opacity: answeredCount === 3 ? 1 : 0, transition: "opacity .35s ease .1s" }}>
            {answeredCount === 3 && (
              <BikeFinderResults answers={answers} height={height} onHeight={setHeight}
                innerRef={(el) => { refs.current.results = el; }}
                onAdd={onAdd} onOpen={onOpen} onBrowseAll={onBrowseAll} onRestart={restart} />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BikeFinder });
