/* GUIDKO App — shared Vehicles / B2B marketplace module (all roles) */

function VehiclesModule({ role, navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const V = store.state.vehicles;

  const [brandFilter, setBrandFilter] = React.useState([]);
  const [fuelFilter, setFuelFilter] = React.useState(null);
  const [gearFilter, setGearFilter] = React.useState(null);
  const [maxPrice, setMaxPrice] = React.useState(35000);
  const [verifiedOnly, setVerifiedOnly] = React.useState(false);
  const [favOnly, setFavOnly] = React.useState(false);
  const [sort, setSort] = React.useState("recent");
  const [detail, setDetail] = React.useState(null);
  const [listOpen, setListOpen] = React.useState(false);

  const allBrands = [...new Set(V.map(v => v.brand))];

  let list = V.filter(v =>
    (brandFilter.length === 0 || brandFilter.includes(v.brand)) &&
    (!fuelFilter || v.fuel === fuelFilter) &&
    (!gearFilter || v.gear === gearFilter) &&
    v.price <= maxPrice &&
    (!verifiedOnly || v.verified) &&
    (!favOnly || v.fav)
  );
  list = [...list].sort((a, b) =>
    sort === "recent" ? 0 : sort === "price-asc" ? a.price - b.price : sort === "price-desc" ? b.price - a.price : a.km - b.km
  );

  function toggleBrand(b) { setBrandFilter(f => f.includes(b) ? f.filter(x => x !== b) : [...f, b]); }
  function reset() { setBrandFilter([]); setFuelFilter(null); setGearFilter(null); setMaxPrice(35000); setVerifiedOnly(false); setFavOnly(false); }

  return (
    <>
      <Topbar
        subtitle={t("MARKETPLACE B2B · 2 481 ANNONCES ACTIVES", "B2B MARKETPLACE · 2,481 ACTIVE LISTINGS")}
        title={t("Marché véhicules", "Vehicle market")}
        actions={<Button kind="primary" onClick={() => setListOpen(true)}>+ {t("Publier une annonce", "List a vehicle")}</Button>}
      />
      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", flex: 1, overflow: "hidden" }}>
        {/* Filters */}
        <aside className="gk-scroll" style={{ padding: 22, borderRight: `1px solid ${C.softLine}`, overflowY: "auto", background: C.paper }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <Label>{t("FILTRES", "FILTERS")}</Label>
            <button onClick={reset} style={{ background: "none", border: "none", fontSize: 11, color: C.flame, cursor: "pointer" }}>{t("Réinit.", "Reset")}</button>
          </div>

          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>{t("Prix max", "Max price")}</div>
            <input type="range" min="8000" max="35000" step="500" value={maxPrice} onChange={e => setMaxPrice(+e.target.value)}
              style={{ width: "100%", accentColor: C.flame }}/>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.slate, marginTop: 4 }}>
              <span>8 000 €</span><span style={{ color: C.ink, fontWeight: 600 }}>≤ {maxPrice.toLocaleString("fr-FR")} €</span>
            </div>
          </div>

          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>{t("Marque", "Brand")}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {allBrands.map(b => {
                const on = brandFilter.includes(b);
                return (
                  <label key={b} onClick={() => toggleBrand(b)} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, cursor: "pointer" }}>
                    <span style={{ width: 16, height: 16, border: `1.5px solid ${on ? C.ink : C.softLine}`, borderRadius: 4, background: on ? C.ink : "#fff", display: "grid", placeItems: "center", color: "#fff", fontSize: 10 }}>{on ? "✓" : ""}</span>
                    <span style={{ flex: 1 }}>{b}</span>
                    <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, color: C.slate }}>{V.filter(v => v.brand === b).length}</span>
                  </label>
                );
              })}
            </div>
          </div>

          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>{t("Carburant", "Fuel")}</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {["Essence", "Diesel", "Hybride", "Élec."].map(f => {
                const on = fuelFilter === f;
                return <span key={f} onClick={() => setFuelFilter(on ? null : f)} style={{ padding: "6px 10px", borderRadius: 999, fontSize: 12, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}` }}>{f}</span>;
              })}
            </div>
          </div>

          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>{t("Boîte", "Gearbox")}</div>
            <div style={{ display: "flex", gap: 6 }}>
              {["Manuelle", "Auto"].map(g => {
                const on = gearFilter === g;
                return <span key={g} onClick={() => setGearFilter(on ? null : g)} style={{ flex: 1, textAlign: "center", padding: "8px 0", borderRadius: 8, fontSize: 12, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}` }}>{g}</span>;
              })}
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <label style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13, cursor: "pointer" }}>
              {t("Vendeurs vérifiés", "Verified sellers")}<Toggle on={verifiedOnly} onChange={setVerifiedOnly}/>
            </label>
            <label style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13, cursor: "pointer" }}>
              {t("Mes favoris", "My favorites")}<Toggle on={favOnly} onChange={setFavOnly}/>
            </label>
          </div>
        </aside>

        {/* Results */}
        <div className="gk-scroll" style={{ padding: 24, overflowY: "auto", background: C.paper }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <div><span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26 }}>{list.length}</span> <span style={{ fontSize: 14, color: C.slate }}>{t("véhicules", "vehicles")}</span></div>
            <Select value={sort} onChange={setSort} style={{ marginBottom: 0, width: 200 }}
              options={[
                { value: "recent", label: t("Trier · Plus récent", "Sort · Newest") },
                { value: "price-asc", label: t("Prix croissant", "Price ↑") },
                { value: "price-desc", label: t("Prix décroissant", "Price ↓") },
                { value: "km", label: t("Kilométrage", "Mileage") },
              ]}/>
          </div>

          {list.length === 0 ? (
            <div style={{ padding: 60, textAlign: "center", color: C.slate }}>
              <div style={{ fontSize: 36, marginBottom: 12 }}>⇄</div>
              {t("Aucun véhicule ne correspond. Élargis tes filtres.", "No vehicles match. Widen your filters.")}
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: 14 }}>
              {list.map((v, i) => (
                <Card key={v.id} hover onClick={() => setDetail(v)} style={{ padding: 0, overflow: "hidden", position: "relative" }}>
                  {v.badge === "boost" && <div style={{ position: "absolute", top: 10, left: 10, zIndex: 1 }}><Pill tone="flame">★ BOOST</Pill></div>}
                  {v.badge === "new" && <div style={{ position: "absolute", top: 10, left: 10, zIndex: 1 }}><Pill tone="signal">{t("NOUVEAU", "NEW")}</Pill></div>}
                  <div onClick={e => { e.stopPropagation(); store.toggleFav(v.id); }} style={{ position: "absolute", top: 10, right: 10, zIndex: 1, width: 30, height: 30, borderRadius: 999, background: "rgba(255,255,255,0.92)", display: "grid", placeItems: "center", fontSize: 14, cursor: "pointer", color: v.fav ? C.flame : C.slate }}>{v.fav ? "♥" : "♡"}</div>
                  <CarImg width="100%" height={140} label={v.brand}/>
                  <div style={{ padding: 15 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                      <div>
                        <Label style={{ fontSize: 9 }}>{v.brand}</Label>
                        <div style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>{v.model}</div>
                      </div>
                      <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 21, lineHeight: 1 }}>{v.price.toLocaleString("fr-FR")} €</div>
                    </div>
                    <div style={{ display: "flex", gap: 5, marginTop: 10, fontSize: 11, color: C.slate, fontFamily: "'Geist Mono', monospace", flexWrap: "wrap" }}>
                      <span>{v.year}</span><span>·</span><span>{(v.km/1000).toFixed(0)}k km</span><span>·</span><span>{v.fuel}</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 12, paddingTop: 12, borderTop: `1px solid ${C.softLine}` }}>
                      <Avatar name={v.seller} size={20} tone={i}/>
                      <span style={{ fontSize: 11, color: C.slate, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v.seller}</span>
                      {v.verified && <span style={{ color: C.signal, fontSize: 13 }}>✓</span>}
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Detail modal */}
      <Modal open={!!detail} onClose={() => setDetail(null)} title={detail ? `${detail.brand} ${detail.model}` : ""} width={520}>
        {detail && (
          <>
            <CarImg width="100%" height={200} label={detail.brand}/>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16 }}>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 40, lineHeight: 1 }}>{detail.price.toLocaleString("fr-FR")} €</div>
              <Button kind="light" size="sm" icon={detail.fav ? "♥" : "♡"} onClick={() => store.toggleFav(detail.id)}>{detail.fav ? t("Favori", "Saved") : t("Sauvegarder", "Save")}</Button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 16 }}>
              {[[t("Année","Year"), detail.year], [t("Kilométrage","Mileage"), detail.km.toLocaleString("fr-FR")+" km"], [t("Carburant","Fuel"), detail.fuel], [t("Boîte","Gearbox"), detail.gear], [t("Vendeur","Seller"), detail.seller], [t("Statut","Status"), detail.verified ? t("Vérifié ✓","Verified ✓") : t("Non vérifié","Unverified")]].map(([k, val]) => (
                <div key={k} style={{ padding: 12, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 9 }}>
                  <Label style={{ fontSize: 9 }}>{k}</Label>
                  <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{val}</div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
              <Button kind="flame" full onClick={() => { toast.push(t("Message envoyé au vendeur", "Message sent to seller"), "signal"); setDetail(null); }}>{t("Contacter le vendeur", "Contact seller")}</Button>
              <Button kind="light" onClick={() => { store.toggleFav(detail.id); }}>{detail.fav ? "♥" : "♡"}</Button>
            </div>
          </>
        )}
      </Modal>

      {/* List vehicle modal */}
      <ListVehicleModal open={listOpen} onClose={() => setListOpen(false)} onDone={(v) => { store.addVehicle(v); setListOpen(false); toast.push(t("Annonce publiée !", "Listing published!"), "signal"); }}/>
    </>
  );
}

function ListVehicleModal({ open, onClose, onDone }) {
  const { t } = useI18n();
  const [f, setF] = React.useState({ brand: "", model: "", year: "2022", km: "", price: "", fuel: "Essence", gear: "Manuelle", seller: "Auto-École Lubasa" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  const valid = f.brand && f.model && f.price;
  return (
    <Modal open={open} onClose={onClose} title={t("Publier une annonce", "List a vehicle")}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Input label={t("Marque","Brand")} value={f.brand} onChange={v => up("brand", v)} placeholder="Peugeot"/>
        <Input label={t("Modèle","Model")} value={f.model} onChange={v => up("model", v)} placeholder="208 GT"/>
        <Input label={t("Année","Year")} value={f.year} onChange={v => up("year", v)} type="number"/>
        <Input label="Km" value={f.km} onChange={v => up("km", v)} type="number" placeholder="38000"/>
        <Input label={t("Prix (€)","Price (€)")} value={f.price} onChange={v => up("price", v)} type="number" placeholder="12400"/>
        <Select label={t("Carburant","Fuel")} value={f.fuel} onChange={v => up("fuel", v)} options={["Essence","Diesel","Hybride","Élec."].map(x => ({ value: x, label: x }))}/>
        <Select label={t("Boîte","Gearbox")} value={f.gear} onChange={v => up("gear", v)} options={["Manuelle","Auto"].map(x => ({ value: x, label: x }))}/>
        <Input label={t("Vendeur","Seller")} value={f.seller} onChange={v => up("seller", v)}/>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button>
        <Button kind="flame" full onClick={() => onDone({ brand: f.brand, model: f.model, year: +f.year, km: +f.km || 0, price: +f.price || 0, fuel: f.fuel, gear: f.gear, seller: f.seller })} style={{ opacity: valid ? 1 : 0.5 }}>{t("Publier", "Publish")} →</Button>
      </div>
    </Modal>
  );
}

window.VehiclesModule = VehiclesModule;
