/* ============ 63MOBIL — car detail page ============ */

function Detail({ carId }) {
  const car = window.CARS.find((c) => c.id === carId) || window.CARS[0];
  const [active, setActive] = React.useState(0);
  const hasPrice = window.hasPrice(car);
  const [dpPct, setDpPct] = React.useState(hasPrice && car.dp ? Math.round(car.dp / car.price * 100 / 5) * 5 : 20);
  const [tenor, setTenor] = React.useState(4);
  React.useEffect(() => { window.scrollTo(0, 0); }, [carId]);
  React.useEffect(() => {
    setActive(0);
    setDpPct(hasPrice && car.dp ? Math.round(car.dp / car.price * 100 / 5) * 5 : 20);
  }, [carId, hasPrice, car.dp, car.price]);

  const gallery = car.images && car.images.length ? car.images : [{ label: "Tampak depan", src: "" }];
  const sold = car.status === "sold";

  const rate = 0.055;
  const dp = hasPrice ? Math.round(car.price * dpPct / 100) : 0;
  const pokok = hasPrice ? car.price - dp : 0;
  const angsuran = hasPrice ? Math.round((pokok + pokok * rate * tenor) / (tenor * 12)) : 0;

  const specs = [
    ["calendar", "Tahun", car.year],
    ["gauge", "Kilometer", window.kmText(car)],
    ["gear", "Transmisi", car.transmission === "AT" ? "Matic (AT)" : "Manual (MT)"],
    ["fuel", "Bahan bakar", car.fuel],
    ["seat", "Kapasitas", car.seats + " penumpang"],
    ["tag", "Tipe bodi", car.body],
    ["sparkle", "Warna", car.color],
    ["shield", "Status surat", "Lengkap"],
  ];

  const waMsg = window.waLink(`Halo 63 Mobil, saya minat unit ini:\n${car.brand} ${car.model} ${car.variant} ${car.year}\nHarga: ${window.priceText(car)}\nMasih ready? Boleh info lebih lanjut & jadwal lihat unit.`);

  const related = window.CARS.filter((c) => c.id !== car.id && (c.body === car.body || c.brand === car.brand) && c.status !== "sold").slice(0, 3);

  return (
    <div style={{ background: "var(--bg)" }}>
      {/* breadcrumb */}
      <div className="wrap" style={{ paddingTop: 22 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--muted)", fontWeight: 600 }}>
          <button onClick={() => window.__nav("home")} style={{ color: "var(--muted)" }}>Beranda</button>
          <Icon name="chevron" size={13} />
          <button onClick={() => window.__nav("catalog")} style={{ color: "var(--muted)" }}>Stok Mobil</button>
          <Icon name="chevron" size={13} />
          <span style={{ color: "var(--ink)" }}>{car.brand} {car.model}</span>
        </div>
      </div>

      <div className="wrap" style={{ paddingTop: 22, paddingBottom: 70 }}>
        <div className="detail-grid" style={{ display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 38, alignItems: "start" }}>
          {/* gallery */}
          <div>
            <div style={{ position: "relative" }}>
              <Photo src={gallery[active]?.src} label={(gallery[active]?.label || "Foto unit") + " — " + car.brand + " " + car.model} tinted={car.hot} ratio="4 / 3" radius="var(--r-lg)" style={{ boxShadow: "var(--shadow-md)" }}>
                <div style={{ position: "absolute", top: 14, left: 14, display: "flex", gap: 8 }}>
                  <StatusBadge status={car.status} />
                  {car.hot && !sold && <span className="badge badge-hot"><Icon name="sparkle" size={12} /> Best deal</span>}
                </div>
                {active === 0 && car.video && (
                  <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
                    <span style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--red)", color: "#fff", display: "grid", placeItems: "center", boxShadow: "var(--shadow-red)" }}><Icon name="play" size={30} /></span>
                  </div>
                )}
              </Photo>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10, marginTop: 12 }}>
              {gallery.map((g, i) => (
                <button key={i} onClick={() => setActive(i)} style={{ position: "relative", borderRadius: 11, overflow: "hidden", border: active === i ? "2.5px solid var(--red)" : "2.5px solid transparent", padding: 0 }}>
                  <Photo src={g.src} label="" tinted={i === 0 && car.video} ratio="1 / 1" radius="0" />
                  {i === 0 && car.video && <span style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(22,19,17,.22)", color: "#fff" }}><Icon name="play" size={20} /></span>}
                </button>
              ))}
            </div>

            {/* description + checklist */}
            <div style={{ marginTop: 34 }}>
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24 }}>Tentang unit ini</h2>
              <p style={{ color: "var(--ink-2)", fontSize: 16.5, lineHeight: 1.7, marginTop: 12 }}>{car.blurb}</p>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 18 }}>
                {car.tags.map((t) => (
                  <span key={t} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "var(--green-tint)", color: "var(--green)", padding: "8px 13px", borderRadius: 999, fontWeight: 700, fontSize: 13.5 }}>
                    <Icon name="check" size={15} /> {t}
                  </span>
                ))}
              </div>
            </div>

            {/* specs */}
            <div style={{ marginTop: 34 }}>
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24 }}>Spesifikasi</h2>
              <div className="spec-grid" style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 12, marginTop: 16 }}>
                {specs.map(([ic, l, v]) => (
                  <div key={l} style={{ display: "flex", alignItems: "center", gap: 13, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 13, padding: "14px 16px" }}>
                    <span style={{ width: 40, height: 40, borderRadius: 10, background: "#fff", color: "var(--red)", display: "grid", placeItems: "center", flex: "none", border: "1px solid var(--line)" }}><Icon name={ic} size={20} /></span>
                    <div>
                      <div style={{ fontSize: 12.5, color: "var(--muted)", fontWeight: 600 }}>{l}</div>
                      <div style={{ fontWeight: 800, fontSize: 15.5 }}>{v}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* sticky buy panel */}
          <div className="detail-side" style={{ position: "sticky", top: 86, display: "flex", flexDirection: "column", gap: 18 }}>
            <div className="card" style={{ padding: 26, boxShadow: "var(--shadow-md)" }}>
              <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: "var(--muted)" }}>{car.body} · {car.transmission} · {car.fuel}</span>
              </div>
              <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 28, letterSpacing: "-0.02em", lineHeight: 1.1 }}>
                {car.brand} {car.model} {car.variant}
              </h1>
              <div style={{ fontSize: 15, color: "var(--muted)", fontWeight: 600, marginTop: 4 }}>{car.year} · {car.color}</div>

              <div className="detail-price-block" style={{ marginTop: 20, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
                <div style={{ fontSize: 13, color: "var(--muted)", fontWeight: 600 }}>Harga {sold ? "(terjual)" : "cash"}</div>
                <div className="detail-price" style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 38, letterSpacing: "-0.03em", color: sold ? "var(--muted)" : "var(--ink)" }}>{window.priceText(car)}</div>
                <div className="detail-finance-grid" style={{ display: "flex", gap: 10, marginTop: 14 }}>
                  <div style={{ flex: 1, background: "var(--surface)", borderRadius: 11, padding: "12px 14px" }}>
                    <div style={{ fontSize: 12, color: "var(--muted)", fontWeight: 600 }}>DP mulai</div>
                    <div style={{ fontWeight: 800, fontSize: 17 }}>{window.dpText(car)}</div>
                  </div>
                  <div style={{ flex: 1, background: "var(--red-tint)", borderRadius: 11, padding: "12px 14px" }}>
                    <div style={{ fontSize: 12, color: "var(--red)", fontWeight: 700 }}>Cicilan mulai</div>
                    <div style={{ fontWeight: 800, fontSize: 17, color: "var(--red)" }}>{window.monthlyText(car)}</div>
                  </div>
                </div>
              </div>

              {/* mini simulator */}
              {!sold && hasPrice && (
                <div style={{ marginTop: 20, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 9 }}>
                    <span style={{ fontWeight: 700, fontSize: 13.5 }}>Simulasi DP</span>
                    <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, color: "var(--red)", fontSize: 14 }}>{dpPct}% · {window.rupiah(dp)}</span>
                  </div>
                  <input type="range" min="15" max="60" step="5" value={dpPct} onChange={(e) => setDpPct(+e.target.value)} style={{ width: "100%", accentColor: "var(--red)" }} />
                  <div style={{ display: "flex", gap: 7, marginTop: 12 }}>
                    {[3, 4, 5].map((t) => (
                      <button key={t} onClick={() => setTenor(t)} style={{ flex: 1, padding: "9px 0", borderRadius: 9, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13.5, background: tenor === t ? "var(--ink)" : "#fff", color: tenor === t ? "#fff" : "var(--ink)", border: "1.5px solid " + (tenor === t ? "var(--ink)" : "var(--line-2)") }}>{t} thn</button>
                    ))}
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 14, background: "var(--ink)", color: "#fff", padding: "14px 16px", borderRadius: 12 }}>
                    <span style={{ fontSize: 13, opacity: .85 }}>Estimasi angsuran</span>
                    <span style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22 }}>{window.rupiah(angsuran)}<span style={{ fontSize: 12, opacity: .8 }}>/bln</span></span>
                  </div>
                </div>
              )}

              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 20 }}>
                <a className="btn btn-wa btn-block btn-lg" href={waMsg} target="_blank" rel="noreferrer"><Icon name="whatsapp" size={20} /> {sold ? "Cari unit serupa" : "Chat & Tanya Unit Ini"}</a>
                <button className="btn btn-ghost btn-block" onClick={() => window.__goSection("kontak", "catalog-then")}><Icon name="calendar" size={18} /> Booking Test Drive</button>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "center", marginTop: 14, color: "var(--muted)", fontSize: 13 }}>
                <Icon name="pin" size={15} /> Lokasi unit: Showroom Medan
              </div>
            </div>

            <div className="card" style={{ padding: "18px 20px", display: "flex", gap: 13, alignItems: "center", background: "var(--surface)" }}>
              <span style={{ width: 42, height: 42, borderRadius: 11, background: "var(--red)", color: "#fff", display: "grid", placeItems: "center", flex: "none" }}><Icon name="shield" size={22} /></span>
              <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
                <strong>Aman & terjamin.</strong> Surat lengkap, bisa cek fisik & bawa ke bengkel langganan sebelum deal.
              </div>
            </div>
          </div>
        </div>

        {/* related */}
        {related.length > 0 && (
          <div style={{ marginTop: 64 }}>
            <SectionHead eyebrow="Rekomendasi" title="Unit serupa yang mungkin kamu suka" action={<button className="btn btn-ghost" onClick={() => window.__nav("catalog")}>Semua stok <Icon name="arrowRight" size={17} /></button>} />
            <div className="cars-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 22 }}>
              {related.map((c) => <CarCard key={c.id} car={c} />)}
            </div>
          </div>
        )}
      </div>

      {/* mobile sticky buy bar */}
      {!sold && (
        <div className="detail-mobile-bar" style={{ display: "none", position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 70, background: "#fff", borderTop: "1px solid var(--line)", padding: "12px 16px", boxShadow: "0 -8px 24px rgba(22,19,17,.08)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11.5, color: "var(--muted)", fontWeight: 600 }}>Cicilan mulai</div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 19, color: "var(--red)" }}>{window.monthlyText(car)}</div>
            </div>
            <a className="btn btn-wa" style={{ flex: 1.3 }} href={waMsg} target="_blank" rel="noreferrer"><Icon name="whatsapp" size={18} /> Chat Unit</a>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Detail });
