/* GUIDKO App — "Marché Mobilité" : achat · vente · location de TOUTE la mobilité.
   Voitures, motos, vélos, trottinettes, bateaux, engins, pièces — C2C · B2C · B2B.
   Onglets : Acheter (C2C+B2B) · Louer (5 modes) · Pièces · Vendre.
   Réutilisé embarqué (rôles école) ET en surface conso autonome (role "auto"). */

const RENT_MODES = {
  short:      { fr: "Courte durée", en: "Short term", c: "#3B6FF8" },
  long:       { fr: "Longue durée", en: "Long term", c: "#A78BFA" },
  instructor: { fr: "Moniteurs indés", en: "Indie instructors", c: "#FF5A1F" },
  school:     { fr: "Auto-écoles", en: "Driving schools", c: "#0FB76B" },
  p2p:        { fr: "Entre particuliers", en: "Peer to peer", c: "#6B7280" },
};

function AutoModule({ role, navigate, consumer = false }) {
  const C = GK.colors;
  const { t, lang, setLang } = useI18n();
  const store = useStore();
  const [tab, setTab] = React.useState("buy");

  const tabs = [
    { k: "buy", fr: "Acheter", en: "Buy", g: "◈" },
    { k: "rent", fr: "Louer", en: "Rent", g: "⏱" },
    { k: "parts", fr: "Pièces", en: "Parts", g: "⚙" },
    { k: "sell", fr: "Vendre", en: "Sell", g: "✎" },
    { k: "trace", fr: "Transactions", en: "Transactions", g: "◉" },
  ];

  const body = (
    <PageBody>
      {tab === "buy" && <BuyTab/>}
      {tab === "rent" && <RentTab role={role}/>}
      {tab === "parts" && <PartsTab/>}
      {tab === "sell" && <SellTab onPublished={() => setTab("trace")}/>}
      {tab === "trace" && <TraceTab/>}
    </PageBody>
  );

  const tabBar = (
    <div style={{ display: "flex", gap: 4, padding: "0 28px", borderBottom: `1px solid ${C.softLine}`, background: C.paper, flexShrink: 0 }}>
      {tabs.map(tb => {
        const on = tb.k === tab;
        return (
          <button key={tb.k} onClick={() => setTab(tb.k)} style={{
            padding: "14px 18px", border: "none", background: "transparent", cursor: "pointer",
            fontSize: 14, fontWeight: on ? 600 : 500, color: on ? C.ink : C.slate,
            borderBottom: `2px solid ${on ? C.flame : "transparent"}`, marginBottom: -1,
            display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "'Geist', sans-serif",
          }}>
            <span style={{ color: on ? C.flame : C.slate }}>{tb.g}</span>{tb[lang]}
          </button>
        );
      })}
    </div>
  );

  if (consumer) {
    // standalone consumer surface — own top bar (no school sidebar)
    return (
      <div style={{ height: "100vh", display: "flex", flexDirection: "column", background: C.paper, color: C.ink, fontFamily: "'Geist', sans-serif", overflow: "hidden" }}>
        <header style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 28px", borderBottom: `1px solid ${C.softLine}`, background: C.paper, flexShrink: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 28 }}>
            <div style={{ cursor: "pointer" }} onClick={() => navigate("/login")}><GuidkoLogo/></div>
            <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, letterSpacing: "0.14em", color: C.flame, paddingLeft: 18, borderLeft: `1px solid ${C.softLine}` }}>MARCHÉ MOBILITÉ</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <LangSelector/>
            <Button kind="ghost" size="sm" onClick={() => navigate("/login")}>{t("Mon compte", "Account")}</Button>
          </div>
        </header>
        <div style={{ padding: "20px 28px 0", background: C.paper, flexShrink: 0 }}>
          <Label color={C.flame} style={{ fontSize: 10 }}>{t("ACHÈTE · LOUE · VENDS · TROUVE DES PIÈCES","BUY · RENT · SELL · FIND PARTS")}</Label>
          <h1 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 40, fontWeight: 400, margin: "4px 0 14px", letterSpacing: "-0.02em" }}>{t("Toute la mobilité, un seul endroit.","All mobility, one place.")}</h1>
        </div>
        {tabBar}
        {body}
        <LiaAssistant role="auto"/>
      </div>
    );
  }

  // embedded in a school role (AppShell provides sidebar)
  return (
    <>
      <Topbar
        subtitle={t("MARCHÉ MOBILITÉ · ACHAT · LOCATION · PIÈCES","MOBILITY MARKET · BUY · RENT · PARTS")}
        title={t("Marché Mobilité","Mobility Market")}
        actions={<Button kind="primary" onClick={() => setTab("sell")}>+ {t("Publier","List")}</Button>}/>
      {tabBar}
      {body}
    </>
  );
}

// ---------- BUY ----------
function BuyTab() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [remoteVehicles, setRemoteVehicles] = React.useState([]);
  const [sellerType, setSellerType] = React.useState("all");
  const [cat, setCat] = React.useState("all");
  const [maxPrice, setMaxPrice] = React.useState(40000);
  const [detail, setDetail] = React.useState(null);
  const allVehicles = [...remoteVehicles, ...store.state.vehicles];
  let list = allVehicles.filter(v => (sellerType === "all" || v.sellerType === sellerType) && (cat === "all" || (v.cat || "auto") === cat) && v.price <= maxPrice);

  React.useEffect(() => {
    let dead = false;
    (async () => {
      try {
        if (!(window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.list === "function")) return;
        const res = await window.GuidkoAPI.marketplace.list({ category: "auto" });
        if (dead) return;
        const mapped = ((res && res.items) || []).map((item, idx) => {
          const bits = String(item.title || "").split(" ");
          const brand = bits[0] || "Véhicule";
          const model = bits.slice(1).join(" ") || "GUIDKO";
          return {
            id: `mk-auto-${item.id || idx}`,
            brand,
            model,
            year: new Date().getFullYear(),
            km: 0,
            price: Number(item.price || 0),
            fuel: "—",
            gear: "—",
            seller: "GUIDKO Marketplace",
            sellerType: "pro",
            verified: true,
            cat: "auto",
            remote: true,
          };
        });
        setRemoteVehicles(mapped);
      } catch (e) {}
    })();
    return () => { dead = true; };
  }, []);

  return (
    <>
      <CatChips cat={cat} setCat={setCat}/>
      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 18, flexWrap: "wrap" }}>
        <Segmented value={sellerType} onChange={setSellerType} options={[
          { value: "all", label: t("Tous","All") }, { value: "particulier", label: t("Particuliers","Private") }, { value: "pro", label: t("Professionnels","Pros") },
        ]}/>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 14px", background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 9 }}>
          <span style={{ fontSize: 12, color: C.slate }}>{t("Prix max","Max")}</span>
          <input type="range" min="5000" max="40000" step="500" value={maxPrice} onChange={e => setMaxPrice(+e.target.value)} style={{ accentColor: C.flame, width: 120 }}/>
          <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 12, fontWeight: 600, minWidth: 66 }}>≤ {(maxPrice/1000).toFixed(0)}k €</span>
        </div>
        <span style={{ marginLeft: "auto", fontFamily: "'Geist Mono', monospace", fontSize: 12, color: C.slate }}>{list.length} {t("véhicules","vehicles")}</span>
      </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" }}>
            <div style={{ position: "absolute", top: 10, left: 10, zIndex: 1, display: "flex", gap: 6 }}>
              {v.badge === "boost" && <Pill tone="flame">★ BOOST</Pill>}
              {v.badge === "new" && <Pill tone="signal">{t("NOUVEAU","NEW")}</Pill>}
              <Pill tone={v.sellerType === "pro" ? "sky" : "neutral"}>{v.sellerType === "pro" ? "Pro" : t("Particulier","Private")}</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" }}><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>

      <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>
            <Pill tone={detail.sellerType === "pro" ? "sky" : "neutral"}>{detail.sellerType === "pro" ? t("Vendeur pro","Pro seller") : t("Particulier","Private")}</Pill>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 16 }}>
            {[[t("Année","Year"), detail.year], ["Km", detail.km.toLocaleString("fr-FR")], [t("Carburant","Fuel"), detail.fuel], [t("Boîte","Gearbox"), detail.gear], [t("Vendeur","Seller"), detail.seller], [t("Vérifié","Verified"), detail.verified ? "✓" : "—"]].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"), "signal"); setDetail(null); }}>{t("Contacter le vendeur","Contact seller")}</Button>
            <Button kind="light" onClick={() => store.toggleFav(detail.id)}>{detail.fav ? "♥" : "♡"}</Button>
          </div>
        </>)}
      </Modal>
    </>
  );
}

// ---------- RENT ----------
function RentTab({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [remoteRentals, setRemoteRentals] = React.useState([]);
  const [mode, setMode] = React.useState("all");
  const [cat, setCat] = React.useState("all");
  const [detail, setDetail] = React.useState(null);
  const allRentals = [...remoteRentals, ...store.state.rentals];
  let list = allRentals.filter(r => (mode === "all" || r.mode === mode) && (cat === "all" || (r.cat || "auto") === cat));

  React.useEffect(() => {
    let dead = false;
    (async () => {
      try {
        if (!(window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.list === "function")) return;
        const res = await window.GuidkoAPI.marketplace.list({ category: "rental" });
        if (dead) return;
        const mapped = ((res && res.items) || []).map((item, idx) => {
          const bits = String(item.title || "").split(" ");
          return {
            id: `mk-rental-${item.id || idx}`,
            brand: bits[0] || "Location",
            model: bits.slice(1).join(" ") || "GUIDKO",
            year: new Date().getFullYear(),
            city: "France",
            mode: "p2p",
            doublePedal: false,
            pricePerDay: Number(item.price || 0),
            pricePerMonth: Number(item.price || 0) * 20,
            seller: "GUIDKO Marketplace",
            sellerType: "pro",
            verified: true,
            cat: "auto",
            remote: true,
          };
        });
        setRemoteRentals(mapped);
      } catch (e) {}
    })();
    return () => { dead = true; };
  }, []);

  return (
    <>
      {/* Mode explainer banner */}
      <Card dark style={{ padding: 18, marginBottom: 16, display: "flex", gap: 18, alignItems: "center" }}>
        <div style={{ fontSize: 26 }}>⏱</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600 }}>{t("La location, repensée pour la mobilité.","Rental, reimagined for mobility.")}</div>
          <div style={{ fontSize: 12.5, color: "#C9CEE3", marginTop: 3, lineHeight: 1.4 }}>
            {t("Moniteurs indépendants : louez une voiture double-commande à la journée. Auto-écoles sans flotte : louez auprès de particuliers ou de pros. Et la location classique entre particuliers.","Indie instructors: rent a dual-control car by the day. Schools with no fleet: rent from individuals or pros. Plus classic peer-to-peer rental.")}
          </div>
        </div>
      </Card>

      <CatChips cat={cat} setCat={setCat}/>
      <div style={{ display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap", alignItems: "center" }}>
        <span onClick={() => setMode("all")} style={chip(mode === "all", C)}>{t("Tous","All")}</span>
        {Object.entries(RENT_MODES).map(([k, m]) => (
          <span key={k} onClick={() => setMode(k)} style={chip(mode === k, C, m.c)}><span style={{ width: 8, height: 8, background: m.c, borderRadius: 999, display: "inline-block", marginRight: 6 }}/>{m[lang]}</span>
        ))}
        <span style={{ marginLeft: "auto", fontFamily: "'Geist Mono', monospace", fontSize: 12, color: C.slate }}>{list.length} {t("offres","offers")}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
        {list.map((r, i) => {
          const m = RENT_MODES[r.mode];
          return (
            <Card key={r.id} hover onClick={() => setDetail(r)} style={{ padding: 0, overflow: "hidden", position: "relative" }}>
              <div style={{ position: "absolute", top: 10, left: 10, zIndex: 1, display: "flex", gap: 6 }}>
                <span style={{ padding: "4px 10px", borderRadius: 999, fontSize: 11, fontWeight: 600, background: m.c, color: "#fff" }}>{m[lang]}</span>
                {r.doublePedal && <Pill tone="flame">⊕ {t("Double-commande","Dual-control")}</Pill>}
              </div>
              <div onClick={e => { e.stopPropagation(); store.toggleRentalFav(r.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: r.fav ? C.flame : C.slate }}>{r.fav ? "♥" : "♡"}</div>
              <CarImg width="100%" height={130} label={r.brand} tone="ink"/>
              <div style={{ padding: 15 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{r.brand} {r.model}</div>
                <div style={{ fontSize: 11, color: C.slate, fontFamily: "'Geist Mono', monospace", marginTop: 3 }}>{r.year} · {r.city}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 12 }}>
                  <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, lineHeight: 1 }}>{r.pricePerDay} €</span>
                  <span style={{ fontSize: 12, color: C.slate }}>/ {t("jour","day")}</span>
                  <span style={{ marginLeft: "auto", fontSize: 12, color: C.slate, fontFamily: "'Geist Mono', monospace" }}>{r.pricePerMonth} €/mois</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 12, paddingTop: 12, borderTop: `1px solid ${C.softLine}` }}>
                  <Avatar name={r.seller} size={20} tone={i}/><span style={{ fontSize: 11, color: C.slate, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.seller}</span>{r.verified && <span style={{ color: C.signal, fontSize: 13 }}>✓</span>}
                </div>
              </div>
            </Card>
          );
        })}
      </div>

      <Modal open={!!detail} onClose={() => setDetail(null)} title={detail ? `${detail.brand} ${detail.model}` : ""} width={500}>
        {detail && (<>
          <CarImg width="100%" height={180} label={detail.brand} tone="ink"/>
          <div style={{ display: "flex", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
            <span style={{ padding: "4px 10px", borderRadius: 999, fontSize: 11, fontWeight: 600, background: RENT_MODES[detail.mode].c, color: "#fff" }}>{RENT_MODES[detail.mode][lang]}</span>
            {detail.doublePedal && <Pill tone="flame">⊕ {t("Double-commande","Dual-control")}</Pill>}
            {detail.verified && <Pill tone="signal">{t("Vérifié","Verified")} ✓</Pill>}
          </div>
          <div style={{ display: "flex", gap: 16, marginTop: 16 }}>
            <div style={{ flex: 1, padding: 14, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 9 }}><Label style={{ fontSize: 9 }}>{t("À LA JOURNÉE","PER DAY")}</Label><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, marginTop: 2 }}>{detail.pricePerDay} €</div></div>
            <div style={{ flex: 1, padding: 14, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 9 }}><Label style={{ fontSize: 9 }}>{t("AU MOIS","PER MONTH")}</Label><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, marginTop: 2 }}>{detail.pricePerMonth} €</div></div>
          </div>
          <div style={{ fontSize: 13, color: C.slate, marginTop: 14, lineHeight: 1.5 }}>{t("Loueur","Lessor")} : <strong style={{ color: C.ink }}>{detail.seller}</strong> · {detail.city}</div>
          <Button kind="flame" full style={{ marginTop: 18 }} onClick={() => { toast.push(t("Demande de location envoyée !","Rental request sent!"), "signal"); setDetail(null); }}>{t("Demander à louer","Request to rent")} →</Button>
        </>)}
      </Modal>
    </>
  );
}

function chip(on, C, color) {
  return { padding: "8px 14px", borderRadius: 999, fontSize: 13, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}`, fontWeight: on ? 600 : 500, display: "inline-flex", alignItems: "center" };
}

const VEHICLE_CATS = [
  { k: "all", fr: "Tous", en: "All", g: "◈" },
  { k: "auto", fr: "Voiture", en: "Car", g: "🚗" },
  { k: "moto", fr: "Moto / Scooter", en: "Moto / Scooter", g: "🏍️" },
  { k: "velo", fr: "Vélo / Trottinette", en: "Bike / Scooter", g: "🚲" },
  { k: "util", fr: "Utilitaire", en: "Van", g: "🚐" },
  { k: "pl", fr: "Poids lourd", en: "Truck", g: "🚚" },
  { k: "nautique", fr: "Bateau / Nautique", en: "Boat", g: "⚓" },
  { k: "engin", fr: "Engin / BTP", en: "Machinery", g: "◮" },,
  { k: "bateau", fr: "Bateau", en: "Boat", g: "🛥️" },
];

function CatChips({ cat, setCat }) {
  const C = GK.colors;
  const { lang } = useI18n();
  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
      {VEHICLE_CATS.map(c => {
        const on = cat === c.k;
        return (
          <span key={c.k} onClick={() => setCat(c.k)} style={{ padding: "9px 15px", borderRadius: 11, fontSize: 13.5, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}`, fontWeight: on ? 600 : 500, display: "inline-flex", alignItems: "center", gap: 7 }}>
            <span style={{ fontSize: 15 }}>{c.g}</span>{c[lang]}
          </span>
        );
      })}
    </div>
  );
}

// ---------- PARTS ----------
function PartsTab() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [remoteParts, setRemoteParts] = React.useState([]);
  const [cat, setCat] = React.useState("all");
  const [cond, setCond] = React.useState("all");
  const cats = ["Moteur", "Freinage", "Pneus", "Carrosserie", "Électronique", "Auto-école"];
  const allParts = [...remoteParts, ...store.state.parts];
  let list = allParts.filter(p => (cat === "all" || p.category === cat) && (cond === "all" || p.condition === cond));

  React.useEffect(() => {
    let dead = false;
    (async () => {
      try {
        if (!(window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.list === "function")) return;
        const res = await window.GuidkoAPI.marketplace.list({ category: "part" });
        if (dead) return;
        const mapped = ((res && res.items) || []).map((item, idx) => ({
          id: `mk-part-${item.id || idx}`,
          name: item.title || "Pièce",
          category: "Auto-école",
          condition: "occasion",
          compatible: "Toutes mobilités",
          price: Number(item.price || 0),
          seller: "GUIDKO Marketplace",
          sellerType: "pro",
          fav: false,
          remote: true,
        }));
        setRemoteParts(mapped);
      } catch (e) {}
    })();
    return () => { dead = true; };
  }, []);

  return (
    <>
      <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap", alignItems: "center" }}>
        <span onClick={() => setCat("all")} style={chip(cat === "all", C)}>{t("Toutes catégories","All categories")}</span>
        {cats.map(c => <span key={c} onClick={() => setCat(c)} style={chip(cat === c, C)}>{c}</span>)}
        <div style={{ marginLeft: "auto" }}><Segmented value={cond} onChange={setCond} options={[{value:"all",label:t("Tous","All")},{value:"neuf",label:t("Neuf","New")},{value:"occasion",label:t("Occasion","Used")}]}/></div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
        {list.map((p, i) => (
          <Card key={p.id} style={{ padding: 16, display: "flex", gap: 14 }}>
            <div style={{ width: 70, height: 70, borderRadius: 9, background: "#EDE6D6", display: "grid", placeItems: "center", fontSize: 24, flexShrink: 0 }}>⚙</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.25 }}>{p.name}</div>
                <div onClick={() => store.togglePartFav(p.id)} style={{ cursor: "pointer", color: p.fav ? C.flame : C.slate }}>{p.fav ? "♥" : "♡"}</div>
              </div>
              <div style={{ fontSize: 11, color: C.slate, marginTop: 3 }}>{p.compatible}</div>
              <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
                <Pill tone="neutral">{p.category}</Pill>
                <Pill tone={p.condition === "neuf" ? "signal" : "sky"}>{p.condition === "neuf" ? t("Neuf","New") : t("Occasion","Used")}</Pill>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
                <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 24, whiteSpace: "nowrap" }}>{p.price} €</span>
                <Button size="sm" kind="primary" onClick={() => toast.push(t("Pièce ajoutée au panier","Part added to cart"), "signal")}>{t("Acheter","Buy")}</Button>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

// ---------- SELL (publish hub) ----------
function SellTab({ onPublished }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [open, setOpen] = React.useState(null); // "vehicle" | "rental" | "part"

  const options = [
    { k: "vehicle", g: "◈", fr: "Vendre un moyen de mobilité", en: "Sell a mobility item", d: t("Voiture, moto, vélo, bateau, engin — particulier ou pro.","Car, moto, bike, boat, machinery — private or pro.") },
    { k: "rental", g: "⏱", fr: "Mettre en location", en: "List for rent", d: t("Loue ton véhicule : moniteurs, auto-écoles, particuliers.","Rent out your vehicle: instructors, schools, peers.") },
    { k: "part", g: "⚙", fr: "Vendre une pièce", en: "Sell a part", d: t("Pièces neuves ou d'occasion, toute mobilité.","New or used parts, all mobility.") },,
  ];

  return (
    <>
      <div style={{ maxWidth: 760 }}>
        <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32, fontWeight: 400, margin: "0 0 6px", letterSpacing: "-0.02em" }}>{t("Que veux-tu publier ?","What do you want to list?")}</h2>
        <p style={{ fontSize: 14, color: C.slate, margin: "0 0 24px" }}>{t("Publication gratuite. Boost optionnel pour plus de visibilité.","Free listing. Optional boost for more reach.")}</p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
          {options.map(o => (
            <Card key={o.k} hover onClick={() => setOpen(o.k)} style={{ padding: 22 }}>
              <div style={{ width: 48, height: 48, borderRadius: 11, background: C.ink, color: C.flame, display: "grid", placeItems: "center", fontSize: 22, marginBottom: 16 }}>{o.g}</div>
              <div style={{ fontSize: 16, fontWeight: 600 }}>{o[GK_lang()]}</div>
              <div style={{ fontSize: 13, color: C.slate, marginTop: 6, lineHeight: 1.45 }}>{o.d}</div>
              <div style={{ marginTop: 16, color: C.flame, fontSize: 13, fontWeight: 600 }}>{t("Commencer","Start")} →</div>
            </Card>
          ))}
        </div>
      </div>

      <SellVehicleForm open={open === "vehicle"} onClose={() => setOpen(null)} onDone={async (v) => {
        try {
          if (window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.create === "function") {
            await window.GuidkoAPI.marketplace.create({
              title: `${v.brand} ${v.model}`,
              description: `${v.year} · ${v.km} km · ${v.fuel} · ${v.gear}`,
              category: "auto",
              price: v.price,
            });
          }
        } catch (e) {}
        store.addVehicle({ ...v, sellerType: v.sellerType || "particulier" });
        setOpen(null);
        toast.push(t("Véhicule publié !","Vehicle listed!"), "signal");
        onPublished && onPublished();
      }}/>
      <SellRentalForm open={open === "rental"} onClose={() => setOpen(null)} onDone={async (r) => {
        try {
          if (window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.create === "function") {
            await window.GuidkoAPI.marketplace.create({
              title: `${r.brand} ${r.model} · ${t("Location","Rental")}`,
              description: `${r.city} · ${r.pricePerDay}€/jour · ${r.pricePerMonth}€/mois`,
              category: "rental",
              price: r.pricePerDay || r.pricePerMonth || 0,
            });
          }
        } catch (e) {}
        store.addRental(r);
        setOpen(null);
        toast.push(t("Location publiée !","Rental listed!"), "signal");
      }}/>
      <SellPartForm open={open === "part"} onClose={() => setOpen(null)} onDone={async (p) => {
        try {
          if (window.GuidkoAPI && window.GuidkoAPI.marketplace && typeof window.GuidkoAPI.marketplace.create === "function") {
            await window.GuidkoAPI.marketplace.create({
              title: p.name,
              description: `${p.category} · ${p.condition} · ${p.compatible}`,
              category: "part",
              price: p.price,
            });
          }
        } catch (e) {}
        store.addPart(p);
        setOpen(null);
        toast.push(t("Pièce publiée !","Part listed!"), "signal");
      }}/>
    </>
  );
}

function SellVehicleForm({ open, onClose, onDone }) {
  const { t, lang } = useI18n();
  const [f, setF] = React.useState({ brand: "", model: "", year: "2022", km: "", price: "", fuel: "Essence", gear: "Manuelle", sellerType: "particulier", seller: "Moi (particulier)", saleMode: "direct" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  return (
    <Modal open={open} onClose={onClose} title={t("Vendre un véhicule","Sell 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"/>
        <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"/>
        <Select label={t("Carburant","Fuel")} value={f.fuel} onChange={v => up("fuel", v)} options={["Essence","Diesel","Hybride","Élec."].map(x => ({ value: x, label: x }))}/>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Select label={t("Tu es","You are")} value={f.sellerType} onChange={v => up("sellerType", v)} options={[{value:"particulier",label:t("Particulier","Private")},{value:"pro",label:t("Professionnel","Pro")}]}/>
        <Select label={t("Mode de vente","Sale mode")} value={f.saleMode} onChange={v => up("saleMode", v)} options={Object.entries(SALE_MODES).map(([k, m]) => ({ value: k, label: m[lang] || m.fr }))}/>
      </div>
      <div style={{ padding: 11, background: "#FBF8EE", borderRadius: 9, fontSize: 12, color: GK.colors.slate, lineHeight: 1.45, marginTop: 4 }}>{SALE_MODES[f.saleMode] && (SALE_MODES[f.saleMode].d[lang] || SALE_MODES[f.saleMode].d.fr)}</div>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}><Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button><Button kind="flame" full onClick={() => f.brand && f.model && 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, sellerType: f.sellerType, saleMode: f.saleMode })}>{t("Publier","Publish")} →</Button></div>
    </Modal>
  );
}

// Modes & circuits de vente du Marché — adaptés à toute la plateforme.
// B2C (pro→particulier), B2B (pro↔pro), B2D (pro→casse/recycleur),
// C2C (particulier↔particulier), C2B (reprise), enchère, lot flotte.
const SALE_MODES = {
  direct:  { fr: "Vente directe", en: "Direct sale", circ: "C2C·B2C", d: { fr: "Prix fixe, paiement sécurisé par escrow Wallet, remise confirmée.", en: "Fixed price, Wallet-escrow secured, confirmed handover." } },
  offre:   { fr: "Offres / négociation", en: "Offers / haggle", circ: "C2C·B2C", d: { fr: "Reçois des offres, accepte la meilleure. Historique tracé.", en: "Receive offers, accept the best. Tracked history." } },
  enchere: { fr: "Enchère", en: "Auction", circ: "C2C·B2B", d: { fr: "Mise montante sur durée limitée. Idéal véhicules rares ou flotte.", en: "Rising bids over a set time. Ideal for rare cars or fleet." } },
  reprise: { fr: "Reprise / C2B", en: "Trade-in / C2B", circ: "C2B", d: { fr: "Rachat immédiat par un pro partenaire, estimation Lia.", en: "Instant buy-back by a partner pro, Lia estimate." } },
  b2b:     { fr: "Lot B2B", en: "B2B batch", circ: "B2B", d: { fr: "Vente en lot entre pros (flottes, concessions, loueurs).", en: "Batch sale between pros (fleets, dealers, renters)." } },
  b2d:     { fr: "Cession casse / B2D", en: "Scrap cession / B2D", circ: "B2D", d: { fr: "Véhicule hors d'usage cédé à un recycleur agréé (branche Recyclage).", en: "End-of-life vehicle ceded to an approved recycler (Recycling branch)." } },
  abo:     { fr: "Abonnement / LLD", en: "Subscription / lease", circ: "B2C·B2B", d: { fr: "Mise à disposition longue durée, mensualité via Wallet (branche Financement).", en: "Long-term lease, monthly via Wallet (Financing branch)." } },
};

// ---------- TRACE : traçabilité des transactions ----------
function TraceTab() {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const [sel, setSel] = React.useState("tx1");
  const txs = [
    { id: "tx1", item: "Peugeot 208 · 2021", mode: "direct", amount: 12400, buyer: "L. Girard", seller: "Auto-École Lubasa", status: "escrow", date: "14/06",
      steps: [[t("Annonce publiée","Listed"),"done"],[t("Acheteur trouvé","Buyer matched"),"done"],[t("Paiement bloqué (escrow)","Payment held (escrow)"),"done"],[t("Contrat signé","Contract signed"),"done"],[t("Remise du véhicule","Handover"),"current"],[t("Fonds libérés","Funds released"),"todo"]] },
    { id: "tx2", item: "Clio IV double-cmd · location", mode: "abo", amount: 55, buyer: "M. Lefèvre", seller: "AutoPlus 93", status: "done", date: "12/06",
      steps: [[t("Annonce publiée","Listed"),"done"],[t("Offre acceptée","Offer accepted"),"done"],[t("Caution bloquée","Deposit held"),"done"],[t("Location en cours","Rental active"),"done"],[t("Restitution + caution rendue","Return + deposit back"),"done"]] },
    { id: "tx3", item: "Lot 4 scooters · flotte", mode: "b2b", amount: 8600, buyer: "LogiPro", seller: "GUIDKO Flotte", status: "enchere", date: "16/06",
      steps: [[t("Lot publié","Batch listed"),"done"],[t("Enchère ouverte","Auction open"),"current"],[t("Meilleure offre","Best bid"),"todo"],[t("Clôture & escrow","Close & escrow"),"todo"]] },
    { id: "tx4", item: "Renault Scénic HS · cession", mode: "b2d", amount: 480, buyer: "Recyclage GUIDKO", seller: "K. Diallo", status: "done", date: "10/06",
      steps: [[t("Diagnostic VHU","End-of-life check"),"done"],[t("Centre agréé assigné","Approved center"),"done"],[t("Enlèvement","Pickup"),"done"],[t("Certificat de destruction","Destruction cert."),"done"],[t("Prime versée (Wallet)","Bonus paid (Wallet)"),"done"]] },
  ];
  const active = txs.find(x => x.id === sel) || txs[0];
  const stCol = { escrow: "sky", done: "signal", enchere: "flame" };
  const stLbl = { escrow: t("Escrow en cours","In escrow"), done: t("Terminée","Completed"), enchere: t("Enchère active","Live auction") };

  return (
    <div style={{ maxWidth: 980 }}>
      <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32, fontWeight: 400, margin: "0 0 6px", letterSpacing: "-0.02em" }}>{t("Traçabilité des transactions","Transaction traceability")}</h2>
      <p style={{ fontSize: 14, color: C.slate, margin: "0 0 18px", maxWidth: 640, lineHeight: 1.55 }}>{t("Le Marché n'est pas qu'un connecteur : chaque vente — B2C, B2B, C2C, C2B, B2D, enchère, LLD — est tracée de bout en bout. Aucune information ne s'échappe.","The Market isn't just a connector: every sale — B2C, B2B, C2C, C2B, B2D, auction, lease — is tracked end-to-end. Nothing escapes.")}</p>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 18 }}>
        {Object.values(SALE_MODES).map((m, i) => <span key={i} style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.08em", padding: "4px 9px", borderRadius: 999, background: C.cream, color: C.slate }}>{(m[lang] || m.fr)} · {m.circ}</span>)}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 16 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {txs.map(tx => (
            <Card key={tx.id} hover onClick={() => setSel(tx.id)} style={{ padding: 15, border: tx.id === sel ? `2px solid ${C.flame}` : `1px solid ${C.softLine}` }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{tx.item}</div>
                <Pill tone={stCol[tx.status]}>{stLbl[tx.status]}</Pill>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 12, color: C.slate }}>
                <span>{SALE_MODES[tx.mode] ? (SALE_MODES[tx.mode][lang] || SALE_MODES[tx.mode].fr) : tx.mode} · {tx.date}</span>
                <span style={{ fontFamily: "'Geist Mono', monospace", color: C.ink, fontWeight: 600 }}>{money(tx.amount)}</span>
              </div>
            </Card>
          ))}
        </div>
        <Card style={{ padding: 24 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 }}>
            <div>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.12em", color: C.flame }}>{active.id.toUpperCase()} · {(SALE_MODES[active.mode] && (SALE_MODES[active.mode][lang]||SALE_MODES[active.mode].fr)) || active.mode}</div>
              <div style={{ fontSize: 20, fontWeight: 700, marginTop: 4 }}>{active.item}</div>
            </div>
            <div style={{ textAlign: "right" }}><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, lineHeight: 1 }}>{money(active.amount)}</div></div>
          </div>
          <div style={{ display: "flex", gap: 18, padding: "14px 0", borderTop: `1px solid ${C.softLine}`, borderBottom: `1px solid ${C.softLine}`, margin: "12px 0 18px", fontSize: 13 }}>
            <div><div style={{ fontSize: 11, color: C.slate }}>{t("Vendeur","Seller")}</div><div style={{ fontWeight: 600 }}>{active.seller}</div></div>
            <div><div style={{ fontSize: 11, color: C.slate }}>{t("Acheteur","Buyer")}</div><div style={{ fontWeight: 600 }}>{active.buyer}</div></div>
          </div>
          <Label style={{ marginBottom: 12 }}>{t("PISTE D'AUDIT","AUDIT TRAIL")}</Label>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {active.steps.map(([lbl, st], i) => (
              <div key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start", paddingBottom: i < active.steps.length-1 ? 14 : 0 }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", alignSelf: "stretch" }}>
                  <div style={{ width: 18, height: 18, borderRadius: 999, background: st==="done"?C.signal:st==="current"?C.flame:"#fff", border: st==="todo"?`2px solid ${C.softLine}`:"none", display: "grid", placeItems: "center", color: "#fff", fontSize: 10, flexShrink: 0 }}>{st==="done"?"✓":""}</div>
                  {i < active.steps.length-1 && <div style={{ width: 2, flex: 1, minHeight: 16, background: st==="done"?C.signal:C.softLine }}/>}
                </div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: st==="current"?600:500, color: st==="todo"?C.slate:C.ink }}>{lbl}</div>
                  {st==="current" && <div style={{ fontSize: 11.5, color: C.flame, marginTop: 2 }}>{t("En cours","In progress")}</div>}
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 18, padding: 12, background: "#FBF8EE", borderRadius: 9, fontSize: 12, color: C.slate, lineHeight: 1.45 }}>{t("Tracé, horodaté et arbitrable par l'Admin GUIDKO. Litige possible à chaque étape, fonds protégés.","Tracked, timestamped and arbitrable by GUIDKO Admin. Dispute at any step, funds protected.")}</div>
        </Card>
      </div>
    </div>
  );
}

function SellRentalForm({ open, onClose, onDone }) {
  const { t, lang } = useI18n();
  const [f, setF] = React.useState({ brand: "", model: "", year: "2022", pricePerDay: "", pricePerMonth: "", mode: "p2p", doublePedal: false, city: "", seller: "Moi (particulier)", sellerType: "particulier" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  return (
    <Modal open={open} onClose={onClose} title={t("Mettre en location","List for rent")}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Input label={t("Marque","Brand")} value={f.brand} onChange={v => up("brand", v)}/>
        <Input label={t("Modèle","Model")} value={f.model} onChange={v => up("model", v)}/>
        <Input label={t("Prix / jour (€)","Price / day (€)")} value={f.pricePerDay} onChange={v => up("pricePerDay", v)} type="number"/>
        <Input label={t("Prix / mois (€)","Price / month (€)")} value={f.pricePerMonth} onChange={v => up("pricePerMonth", v)} type="number"/>
        <Input label={t("Ville","City")} value={f.city} onChange={v => up("city", v)}/>
        <Select label={t("Mode","Mode")} value={f.mode} onChange={v => up("mode", v)} options={Object.entries(RENT_MODES).map(([k, m]) => ({ value: k, label: m[lang] }))}/>
      </div>
      <label style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 14, padding: "6px 0" }}>{t("Voiture double-commande (auto-école)","Dual-control car (driving school)")}<Toggle on={f.doublePedal} onChange={v => up("doublePedal", v)}/></label>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}><Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button><Button kind="flame" full onClick={() => f.brand && f.model && onDone({ brand: f.brand, model: f.model, year: +f.year, pricePerDay: +f.pricePerDay || 0, pricePerMonth: +f.pricePerMonth || 0, mode: f.mode, doublePedal: f.doublePedal, city: f.city, seller: f.seller, sellerType: f.sellerType })}>{t("Publier","Publish")} →</Button></div>
    </Modal>
  );
}

function SellPartForm({ open, onClose, onDone }) {
  const { t } = useI18n();
  const [f, setF] = React.useState({ name: "", category: "Moteur", condition: "occasion", price: "", compatible: "", seller: "Moi (particulier)", sellerType: "particulier" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  return (
    <Modal open={open} onClose={onClose} title={t("Vendre une pièce","Sell a part")}>
      <Input label={t("Désignation","Name")} value={f.name} onChange={v => up("name", v)} placeholder={t("Plaquettes de frein…","Brake pads…")}/>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Select label={t("Catégorie","Category")} value={f.category} onChange={v => up("category", v)} options={["Moteur","Freinage","Pneus","Carrosserie","Électronique","Auto-école"].map(x => ({ value: x, label: x }))}/>
        <Select label={t("État","Condition")} value={f.condition} onChange={v => up("condition", v)} options={[{value:"neuf",label:t("Neuf","New")},{value:"occasion",label:t("Occasion","Used")}]}/>
        <Input label={t("Prix (€)","Price (€)")} value={f.price} onChange={v => up("price", v)} type="number"/>
        <Input label={t("Compatible avec","Fits")} value={f.compatible} onChange={v => up("compatible", v)} placeholder="Clio IV"/>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}><Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button><Button kind="flame" full onClick={() => f.name && f.price && onDone({ name: f.name, category: f.category, condition: f.condition, price: +f.price, compatible: f.compatible || "—", seller: f.seller, sellerType: f.sellerType })}>{t("Publier","Publish")} →</Button></div>
    </Modal>
  );
}

window.AutoModule = AutoModule;
Object.assign(window, { RENT_MODES });
