/* ============ 63MOBIL — catalog page ============ */

function priceBucket(price) {
  if (!Number.isFinite(price) || price <= 0) return "Tanya harga";
  if (price < 150000000) return "< 150 jt";
  if (price < 200000000) return "150–200 jt";
  if (price < 250000000) return "200–250 jt";
  return "> 250 jt";
}

function Catalog() {
  const preset = window.__catalogPreset || {};
  const [brand, setBrand] = React.useState(preset.brand && preset.brand !== "Semua" ? preset.brand : "Semua");
  const [body, setBody] = React.useState(preset.body && preset.body !== "Semua" ? preset.body : "Semua");
  const [budget, setBudget] = React.useState(preset.budget && preset.budget !== "Semua harga" ? preset.budget : "Semua");
  const [trans, setTrans] = React.useState("Semua");
  const [q, setQ] = React.useState("");
  const [sort, setSort] = React.useState("relevan");
  const [showFilter, setShowFilter] = React.useState(false);
  React.useEffect(() => { window.__catalogPreset = null; }, []);

  let list = window.CARS.filter((c) => {
    if (brand !== "Semua" && c.brand !== brand) return false;
    if (body !== "Semua" && c.body !== body) return false;
    if (trans !== "Semua" && c.transmission !== trans) return false;
    if (budget !== "Semua" && priceBucket(c.price) !== budget) return false;
    if (q && !(`${c.brand} ${c.model} ${c.variant}`.toLowerCase().includes(q.toLowerCase()))) return false;
    return true;
  });
  list = [...list].sort((a, b) => {
    if (sort === "murah") return (a.price || Number.MAX_SAFE_INTEGER) - (b.price || Number.MAX_SAFE_INTEGER);
    if (sort === "mahal") return (b.price || 0) - (a.price || 0);
    if (sort === "baru") return b.year - a.year;
    // relevan: ready first, then hot
    const s = (c) => (c.status === "ready" ? 0 : c.status === "booked" ? 1 : 2);
    return s(a) - s(b) || (b.hot - a.hot);
  });

  const reset = () => { setBrand("Semua"); setBody("Semua"); setBudget("Semua"); setTrans("Semua"); setQ(""); };
  const activeCount = [brand, body, budget, trans].filter((x) => x !== "Semua").length + (q ? 1 : 0);

  const FilterContent = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>Merek</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {window.BRANDS.map((b) => <button key={b} className={"pill-tab" + (brand === b ? " active" : "")} onClick={() => setBrand(b)}>{b}</button>)}
        </div>
      </div>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>Tipe bodi</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {window.BODIES.map((b) => <button key={b} className={"pill-tab" + (body === b ? " active" : "")} onClick={() => setBody(b)}>{b}</button>)}
        </div>
      </div>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>Budget</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {["Semua","< 150 jt","150–200 jt","200–250 jt","> 250 jt","Tanya harga"].map((b) => <button key={b} className={"pill-tab" + (budget === b ? " active" : "")} onClick={() => setBudget(b)}>{b}</button>)}
        </div>
      </div>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>Transmisi</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {["Semua","AT","MT"].map((b) => <button key={b} className={"pill-tab" + (trans === b ? " active" : "")} onClick={() => setTrans(b)}>{b === "AT" ? "Matic (AT)" : b === "MT" ? "Manual (MT)" : "Semua"}</button>)}
        </div>
      </div>
      {activeCount > 0 && <button className="btn btn-ghost btn-sm" onClick={reset} style={{ alignSelf: "flex-start" }}><Icon name="close" size={15} /> Reset filter</button>}
    </div>
  );

  return (
    <div style={{ background: "var(--surface)", minHeight: "100vh" }}>
      {/* page head */}
      <div style={{ background: "var(--ink)", color: "#fff", paddingTop: 40, paddingBottom: 40 }}>
        <div className="wrap">
          <button onClick={() => window.__nav("home")} style={{ color: "rgba(255,255,255,.7)", fontSize: 14, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 16 }}>
            <Icon name="chevron" size={15} style={{ transform: "rotate(180deg)" }} /> Beranda
          </button>
          <h1 style={{ fontSize: "clamp(30px,4.4vw,46px)", fontWeight: 900, letterSpacing: "-0.03em" }}>Stok Mobil Bekas Medan</h1>
          <p style={{ color: "rgba(255,255,255,.7)", fontSize: 16, marginTop: 10 }}>Semua unit terawat & surat lengkap. Klik unit untuk foto, video & spesifikasi.</p>
          <div style={{ position: "relative", marginTop: 22, maxWidth: 460 }}>
            <span style={{ position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: "var(--muted)" }}><Icon name="search" size={19} /></span>
            <input className="input" style={{ paddingLeft: 46, height: 50 }} placeholder="Cari merek atau model… (cth. Avanza)" value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
        </div>
      </div>

      <div className="wrap" style={{ padding: "30px 24px 80px" }}>
        <div className="catalog-grid" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 30, alignItems: "start" }}>
          {/* sidebar */}
          <aside className="catalog-side card" style={{ padding: 24, position: "sticky", top: 86 }}>
            <FilterContent />
          </aside>

          {/* results */}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, gap: 12, flexWrap: "wrap" }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--ink-2)" }}><strong style={{ fontFamily: "var(--font-display)", fontSize: 20 }}>{list.length}</strong> unit ditemukan</div>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <button className="btn btn-ghost btn-sm catalog-filter-btn" style={{ display: "none" }} onClick={() => setShowFilter(true)}>
                  <Icon name="filter" size={16} /> Filter {activeCount > 0 && <span style={{ background: "var(--red)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px" }}>{activeCount}</span>}
                </button>
                <select className="select" style={{ width: "auto", padding: "10px 36px 10px 14px" }} value={sort} onChange={(e) => setSort(e.target.value)}>
                  <option value="relevan">Paling relevan</option>
                  <option value="murah">Harga termurah</option>
                  <option value="mahal">Harga tertinggi</option>
                  <option value="baru">Tahun terbaru</option>
                </select>
              </div>
            </div>

            {list.length === 0 ? (
              <div className="card" style={{ padding: "60px 30px", textAlign: "center" }}>
                <span style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--surface-2)", color: "var(--muted)", display: "grid", placeItems: "center", margin: "0 auto" }}><Icon name="search" size={30} /></span>
                <h3 style={{ fontSize: 22, fontWeight: 800, marginTop: 18 }}>Belum ada unit yang cocok</h3>
                <p style={{ color: "var(--muted)", marginTop: 8 }}>Coba ubah filter, atau chat kami — sering ada unit baru yang belum tayang.</p>
                <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 20 }}>
                  <button className="btn btn-ghost" onClick={reset}>Reset filter</button>
                  <a className="btn btn-wa" href={window.waLink("Halo 63 Mobil, saya cari unit tertentu nih, ada rekomendasi?")} target="_blank" rel="noreferrer"><Icon name="whatsapp" size={17} /> Tanya stok</a>
                </div>
              </div>
            ) : (
              <div className="cars-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 22 }}>
                {list.map((c) => <CarCard key={c.id} car={c} />)}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* mobile filter drawer */}
      {showFilter && (
        <div style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(22,19,17,.5)" }} onClick={() => setShowFilter(false)}>
          <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, background: "#fff", borderRadius: "22px 22px 0 0", padding: "22px 22px 30px", maxHeight: "86vh", overflowY: "auto" }} onClick={(e) => e.stopPropagation()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
              <h3 style={{ fontSize: 21, fontWeight: 800 }}>Filter</h3>
              <button onClick={() => setShowFilter(false)} style={{ color: "var(--ink)" }}><Icon name="close" size={24} /></button>
            </div>
            <FilterContent />
            <button className="btn btn-red btn-block btn-lg" style={{ marginTop: 24 }} onClick={() => setShowFilter(false)}>Lihat {list.length} unit</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Catalog });
