/* GUIDKO Livraison — écosystème livraison complet.
   Catégories : Repas · Colis · Logistique B2B · Médical · Déménagement · Vert.
   Tous véhicules : vélo, trottinette, scooter, moto, voiture, cargo, camionnette, PL.
   Espaces : Client (commander/suivre) · Livreur (missions, GUIDAROUTE, gains) · B2B Logistique. */

const DELIVERY_CATS = [
  { k: "repas",     fr: "Repas & Courses",     en: "Food & Groceries",   g: "🍔", color: "#FF5A1F" },
  { k: "colis",     fr: "Colis particuliers",  en: "Personal parcels",   g: "📦", color: "#3B6FF8" },
  { k: "b2b",       fr: "Logistique B2B",      en: "B2B Logistics",      g: "🏭", color: "#6B7280" },
  { k: "medical",   fr: "Médical / Pharmacie", en: "Medical / Pharmacy", g: "💊", color: "#0FB76B" },
  { k: "moving",    fr: "Déménagement léger",  en: "Light moving",       g: "🛋", color: "#A78BFA" },
  { k: "vert",      fr: "Livraison verte",     en: "Green delivery",     g: "🌿", color: "#0FB76B" },
];

const RESTO_DATA = [
  { id: "rd1", name: "Chez Mama",           cat: "repas",   note: 4.8, time: "25-35 min", delivery: 2.5,  promo: true,  g: "🍲" },
  { id: "rd2", name: "Sushi Naka",          cat: "repas",   note: 4.6, time: "20-30 min", delivery: 1.9,  promo: false, g: "🍱" },
  { id: "rd3", name: "Pizza Roma",          cat: "repas",   note: 4.4, time: "30-40 min", delivery: 2.0,  promo: false, g: "🍕" },
  { id: "rd4", name: "Le Burger",           cat: "repas",   note: 4.5, time: "20-25 min", delivery: 0,    promo: true,  g: "🍔" },
  { id: "rd5", name: "Thaï Garden",         cat: "repas",   note: 4.7, time: "25-35 min", delivery: 2.2,  promo: false, g: "🍜" },
  { id: "rd6", name: "Carrefour Express",   cat: "colis",   note: 4.6, time: "45-60 min", delivery: 3.5,  promo: false, g: "🛒" },
  { id: "rd7", name: "Pharmacie Centrale",  cat: "medical", note: 5.0, time: "15-20 min", delivery: 4.0,  promo: false, g: "💊" },
  { id: "rd8", name: "Entrepôt LogiPro",    cat: "b2b",     note: 4.5, time: "2-4 h",     delivery: 12.0, promo: false, g: "🏭" },
  { id: "rd9", name: "Marché Bio du 11e",   cat: "vert",    note: 4.9, time: "30-45 min", delivery: 0,    promo: false, g: "🌿" },
];

const DELIVERY_VEHICLES = [
  { k: "velo",       fr: "Vélo",          en: "Bike",       g: "🚲", licence: null,    cats: ["repas","colis","vert"],                 desc: { fr: "Aucun permis. Livraisons courtes, écolo.",       en: "No license. Short, eco deliveries." },      earn: "8-14 €/h" },
  { k: "trottinette",fr: "Trottinette",   en: "E-Scooter",  g: "🛴", licence: null,    cats: ["repas","colis"],                        desc: { fr: "Sans permis. Rapide en ville.",                  en: "No license. Fast in the city." },           earn: "10-15 €/h" },
  { k: "scooter",    fr: "Scooter",       en: "Moped",      g: "🛵", licence: "A1/AM", cats: ["repas","colis","medical"],              desc: { fr: "Permis AM/A1. Rayon élargi.",                    en: "AM/A1 license. Wider range." },             earn: "12-17 €/h" },
  { k: "moto",       fr: "Moto",          en: "Motorcycle", g: "🏍️", licence: "A2/A",  cats: ["repas","colis","medical"],              desc: { fr: "Permis A2/A. Longues distances.",                en: "A2/A license. Long distances." },           earn: "14-20 €/h" },
  { k: "voiture",    fr: "Voiture",       en: "Car",        g: "🚗", licence: "B",     cats: ["repas","colis","b2b","moving","medical"],desc: { fr: "Permis B. Colis volumineux, mauvais temps.",     en: "B license. Bulky, bad weather." },          earn: "11-16 €/h" },
  { k: "cargo",      fr: "Vélo-cargo",    en: "Cargo bike", g: "📦", licence: null,    cats: ["repas","colis","vert","b2b"],           desc: { fr: "Sans permis. Grosses commandes groupées.",       en: "No license. Large grouped orders." },       earn: "12-18 €/h" },
  { k: "camionnette",fr: "Camionnette",   en: "Van",        g: "🚐", licence: "B/C1",  cats: ["b2b","moving","colis"],                 desc: { fr: "Permis B ou C1. Palettes, meubles, stocks.",     en: "B or C1 license. Pallets, furniture." },   earn: "18-28 €/h" },
  { k: "pl",         fr: "Poids lourd",   en: "Truck",      g: "🚚", licence: "C",     cats: ["b2b"],                                  desc: { fr: "Permis C. Logistique grande distance, entrepôts.",en: "C license. Long-haul logistics." },         earn: "22-35 €/h" },
];

const MISSIONS = [
  { id: "mi1", cat: "repas",   from: "Chez Mama · 12e",          to: "18 rue Voltaire, 11e",     dist: "1.4 km", pay: 7.20,  vehicles: ["velo","trottinette","scooter"], urgent: true,  boost: false },
  { id: "mi2", cat: "repas",   from: "Pizza Roma · 9e",          to: "42 av. République, 10e",   dist: "2.1 km", pay: 8.50,  vehicles: ["trottinette","scooter","moto"],  urgent: false, boost: true  },
  { id: "mi3", cat: "colis",   from: "Carrefour Express · 15e",  to: "7 rue du Commerce, 15e",   dist: "0.8 km", pay: 6.00,  vehicles: ["velo","cargo","voiture"],        urgent: false, boost: false },
  { id: "mi4", cat: "b2b",     from: "Entrepôt LogiPro, Roissy", to: "ZI Le Bourget, 93",        dist: "18 km",  pay: 42.00, vehicles: ["camionnette","pl"],              urgent: false, boost: false },
  { id: "mi5", cat: "medical", from: "Pharmacie Centrale · 4e",  to: "Hôpital Saint-Antoine, 12e",dist:"3.2 km", pay: 14.00, vehicles: ["scooter","moto","voiture"],      urgent: true,  boost: false },
  { id: "mi6", cat: "moving",  from: "Entrepôt IKEA, 95",        to: "Vincennes, 94",            dist: "22 km",  pay: 58.00, vehicles: ["camionnette"],                   urgent: false, boost: false },
  { id: "mi7", cat: "vert",    from: "Marché Bio · 11e",         to: "6 passage Thiéré, 11e",    dist: "0.6 km", pay: 5.50,  vehicles: ["velo","cargo"],                  urgent: false, boost: false },
  { id: "mi8", cat: "b2b",     from: "Hub Amazon, Gennevilliers", to: "Multi-adresses · 92",     dist: "Tour",   pay: 94.00, vehicles: ["camionnette","voiture"],         urgent: false, boost: true  },
];

// ============ APP SHELL ============
function LivraisonApp({ section, navigate }) {
  switch (section) {
    case "overview": return <LivraisonLanding navigate={navigate}/>;
    case "client":   return <LivraisonClient navigate={navigate}/>;
    case "livreur":  return <LivraisonDriver navigate={navigate}/>;
    case "b2b":      return <LivraisonB2B navigate={navigate}/>;
    case "track":    return <LivraisonTrack/>;
    case "drive":    return <LivraisonDriveMode navigate={navigate}/>;
    default:         return <LivraisonLanding navigate={navigate}/>;
  }
}

// ============ LANDING split Client / Livreur ============
function LivraisonLanding({ navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();

  return (
    <div style={{ height: "100vh", fontFamily: "'Geist', sans-serif", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {/* Header */}
      <header style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 32px", background: C.ink, color: "#fff", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <GuidkoMark size={24} color="#fff" accent={C.flame}/>
          <span style={{ fontWeight: 800, letterSpacing: "0.04em" }}>GUIDKO</span>
          <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, color: C.flame, letterSpacing: "0.18em", paddingLeft: 10, borderLeft: "1px solid #1F2542" }}>LIVRAISON</span>
        </div>
        <Button kind="light" size="sm" onClick={() => navigate("/login")}>{t("Toutes les apps","All apps")} ↗</Button>
      </header>

      {/* Catégories bar */}
      <div style={{ background: C.paper, padding: "10px 32px", borderBottom: `1px solid ${C.softLine}`, display: "flex", gap: 8, overflowX: "auto", flexShrink: 0 }}>
        {DELIVERY_CATS.map(c => (
          <span key={c.k} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 14px", borderRadius: 999, border: `1px solid ${C.softLine}`, background: "#fff", fontSize: 13, whiteSpace: "nowrap", cursor: "pointer", fontWeight: 500 }}>
            {c.g} {c[GK_lang()] || c.fr}
          </span>
        ))}
      </div>

      {/* Split card */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 1fr", overflow: "hidden" }}>
        {/* Client */}
        <div onClick={() => { store.login({ name: "Lucas Client", email: "", tone: 3, role: "livraison", livrSide: "client" }); navigate("/livraison/client"); }}
          style={{ background: C.paper, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", padding: "52px 52px", cursor: "pointer", borderRight: `1px solid ${C.softLine}`, transition: "background .15s" }}
          onMouseEnter={e => e.currentTarget.style.background = C.cream}
          onMouseLeave={e => e.currentTarget.style.background = C.paper}>
          <div style={{ fontSize: 68, marginBottom: 20 }}>🛍️</div>
          <Pill tone="sky" style={{ marginBottom: 16 }}>CLIENT</Pill>
          <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 48, fontWeight: 400, lineHeight: 0.95, letterSpacing: "-0.025em", margin: "0 0 16px" }}>{t("Je commande.", "I order.")}</h2>
          <p style={{ fontSize: 15, color: C.slate, lineHeight: 1.55, maxWidth: 340, margin: "0 0 28px" }}>{t("Repas, pharmacie, courses, colis. Livré à ta porte en quelques minutes.", "Food, pharmacy, groceries, packages. Delivered to your door in minutes.")}</p>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "13px 22px", background: C.ink, color: "#fff", borderRadius: 10, fontSize: 15, fontWeight: 600 }}>
            {t("Commander →", "Order →")}
          </div>
        </div>

        {/* Livreur */}
        <div onClick={() => { store.login({ name: "Yanis Livreur", email: "", tone: 2, role: "livraison", livrSide: "livreur" }); navigate("/livraison/livreur"); }}
          style={{ background: C.ink, color: "#fff", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", padding: "52px 52px", cursor: "pointer", transition: "background .15s" }}
          onMouseEnter={e => e.currentTarget.style.background = "#10172E"}
          onMouseLeave={e => e.currentTarget.style.background = C.ink}>
          <div style={{ fontSize: 68, marginBottom: 20 }}>🚴</div>
          <span style={{ display: "inline-flex", padding: "5px 12px", borderRadius: 999, background: `${C.flame}22`, color: C.flame, fontSize: 12, fontWeight: 600, fontFamily: "'Geist Mono', monospace", letterSpacing: "0.14em", marginBottom: 16 }}>LIVREUR</span>
          <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 48, fontWeight: 400, lineHeight: 0.95, letterSpacing: "-0.025em", margin: "0 0 16px" }}>{t("Je livre & je gagne.", "I deliver & earn.")}</h2>
          <p style={{ fontSize: 15, color: "#C9CEE3", lineHeight: 1.55, maxWidth: 340, margin: "0 0 16px" }}>{t("Vélo, scooter, voiture, camionnette, PL. Repas, colis, logistique B2B, médical.", "Bike, scooter, car, van, truck. Food, parcels, B2B logistics, medical.")}</p>
          <div style={{ marginBottom: 28, padding: 14, background: "#1F2542", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 13, color: "#C9CEE3", lineHeight: 1.45, maxWidth: 340 }}>
            🛰 {t("GUIDAROUTE inclus à chaque mission — code de la route vivant, au service du livreur.", "GUIDAROUTE included on every mission — live road code, at the courier's service.")}
          </div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "13px 22px", background: C.flame, color: "#fff", borderRadius: 10, fontSize: 15, fontWeight: 600 }}>
            {t("Devenir livreur →", "Become courier →")}
          </div>
        </div>
      </div>

      {/* B2B banner */}
      <div onClick={() => { store.login({ name: "LogiPro Manager", email: "", tone: 0, role: "livraison", livrSide: "livreur" }); navigate("/livraison/b2b"); }}
        style={{ background: "#1A1F33", color: "#fff", padding: "16px 52px", display: "flex", alignItems: "center", gap: 20, cursor: "pointer", flexShrink: 0 }}
        onMouseEnter={e => e.currentTarget.style.background = "#222944"}
        onMouseLeave={e => e.currentTarget.style.background = "#1A1F33"}>
        <span style={{ fontSize: 28 }}>🏭</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600 }}>{t("Logistique B2B — Entrepôts & Flottes","B2B Logistics — Warehouses & Fleets")}</div>
          <div style={{ fontSize: 12.5, color: "#9098B5", marginTop: 2 }}>{t("Gérez vos flux, planifiez vos livraisons, camionnettes et PL. Pour professionnels et entrepôts.","Manage your flows, schedule deliveries, vans and trucks. For businesses and warehouses.")}</div>
        </div>
        <span style={{ color: "#9098B5", fontSize: 18 }}>→</span>
      </div>
    </div>
  );
}

// ============ CLIENT — Commander ============
function LivraisonClient({ navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const [cat, setCat] = React.useState("repas");
  const [cart, setCart] = React.useState([]);
  const [ordered, setOrdered] = React.useState(false);
  const list = RESTO_DATA.filter(r => r.cat === cat);

  if (ordered) {
    return (
      <>
        <Topbar subtitle={t("COMMANDE EN COURS","ORDER IN PROGRESS")} title={t("En route !","On the way!")} search={false}/>
        <PageBody>
          <Card dark style={{ padding: 36, textAlign: "center", maxWidth: 540, margin: "0 auto" }}>
            <div style={{ fontSize: 64, marginBottom: 16 }}>🛵</div>
            <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 52, lineHeight: 1 }}>25 min</div>
            <div style={{ fontSize: 14, color: "#C9CEE3", marginTop: 8, marginBottom: 22 }}>{t("Ton livreur utilise le GUIDAROUTE.","Your courier uses GUIDAROUTE.")}</div>
            {[t("Commande préparée","Order prepared"), t("Livreur en chemin","Courier en route"), t("Livré","Delivered")].map((s, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "#1F2542", borderRadius: 9, marginBottom: 8, textAlign: "left" }}>
                <span style={{ width: 22, height: 22, borderRadius: 11, background: i <= 1 ? C.signal : "#3A4068", display: "grid", placeItems: "center", fontSize: 11, color: "#fff", flexShrink: 0 }}>{i <= 1 ? "✓" : i+1}</span>
                <span style={{ flex: 1, fontSize: 14 }}>{s}</span>
                {i === 1 && <Pill tone="flame">{t("En cours","Live")}</Pill>}
              </div>
            ))}
            <Button kind="light" full style={{ marginTop: 18 }} onClick={() => setOrdered(false)}>{t("Nouvelle commande","New order")}</Button>
          </Card>
          <Card style={{ padding: 16, marginTop: 14, maxWidth: 540, margin: "14px auto 0", display: "flex", gap: 12, alignItems: "center", background: "#FBF8EE" }}>
            <span style={{ fontSize: 18 }}>🚴</span>
            <div style={{ flex: 1, fontSize: 13, color: C.slate }}>{t("Et si tu livrais aussi ? Rejoins GUIDKO Livraison.","What if you delivered too? Join GUIDKO.")}</div>
            <Button size="sm" kind="ink" onClick={() => navigate("/livraison/livreur")}>{t("Livrer","Deliver")} →</Button>
          </Card>
        </PageBody>
      </>
    );
  }

  return (
    <>
      <Topbar subtitle={t("COMMANDER","ORDER")} title={t("Que veux-tu recevoir ?","What do you want delivered?")} search={false}
        actions={cart.length > 0 && <Button kind="flame" onClick={async () => {
          try {
            if (window.GuidkoAPI && window.GuidkoAPI.delivery && typeof window.GuidkoAPI.delivery.create === "function") {
              const first = cart[0];
              await window.GuidkoAPI.delivery.create({
                recipientId: "guidko-client",
                pickupAddress: first ? first.name : "Restaurant",
                dropoffAddress: "Adresse client",
                item: first ? `${first.name} x${cart.length}` : "Commande",
                weight: Math.max(1, cart.length),
                price: cart.reduce((sum, x) => sum + (x.delivery || 0) + 9, 0),
              });
            }
          } catch (e) {}
          setOrdered(true);
          setCart([]);
          toast.push(t("Commande passée !","Order placed!"), "signal");
        }}>🛒 {t("Commander","Order")} ({cart.length})</Button>}/>
      <PageBody>
        {/* Cat tabs */}
        <div style={{ display: "flex", gap: 8, marginBottom: 18, overflowX: "auto", paddingBottom: 4 }}>
          {DELIVERY_CATS.map(c => {
            const on = cat === c.k;
            return <span key={c.k} onClick={() => setCat(c.k)} style={{ display: "inline-flex", alignItems: "center", gap: 6, 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, whiteSpace: "nowrap" }}><span>{c.g}</span>{c[GK_lang()] || c.fr}</span>;
          })}
        </div>

        {list.length === 0 ? (
          <div style={{ padding: 50, textAlign: "center", color: C.slate }}>
            <div style={{ fontSize: 36, marginBottom: 12 }}>{DELIVERY_CATS.find(c => c.k === cat)?.g}</div>
            <div>{t("Bientôt disponible dans cette catégorie.","Coming soon in this category.")}</div>
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
            {list.map(r => (
              <Card key={r.id} hover style={{ padding: 0, overflow: "hidden" }}>
                <div style={{ height: 110, background: "#EDE6D6", display: "grid", placeItems: "center", fontSize: 40, position: "relative" }}>
                  {r.g}
                  {r.promo && <div style={{ position: "absolute", top: 8, left: 8 }}><Pill tone="flame">PROMO</Pill></div>}
                </div>
                <div style={{ padding: 16 }}>
                  <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 600 }}>{r.name}</div>
                      <div style={{ fontSize: 12, color: C.slate, marginTop: 2 }}>⏱ {r.time}</div>
                    </div>
                    <span style={{ fontSize: 12, color: C.signal, fontFamily: "'Geist Mono', monospace" }}>★ {r.note}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
                    <span style={{ fontSize: 12, color: r.delivery === 0 ? C.signal : C.slate }}>{r.delivery === 0 ? t("Livraison gratuite","Free delivery") : r.delivery.toFixed(2) + " €"}</span>
                    <Button kind="primary" size="sm" onClick={() => { setCart(c => [...c, r]); toast.push(t("Ajouté !","Added!"), "signal"); }}>{t("+ Ajouter","+ Add")}</Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </PageBody>
    </>
  );
}

// ============ LIVREUR — Tableau de missions ============
function LivraisonDriver({ navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const toast = useToast();
  const [vehicle, setVehicle] = React.useState(null);
  const [catFilter, setCatFilter] = React.useState("all");
  const [accepted, setAccepted] = React.useState([]);

  if (!vehicle) {
    return (
      <>
        <Topbar subtitle={t("DEVENIR LIVREUR","BECOME A COURIER")} title={t("Choisis ton véhicule","Pick your vehicle")} search={false}/>
        <PageBody>
          <p style={{ fontSize: 14, color: C.slate, margin: "0 0 18px", maxWidth: 680, lineHeight: 1.55 }}>
            {t("Ton véhicule détermine tes missions et ton taux horaire. Certains nécessitent un permis — GUIDKO te connecte à une auto-école partenaire.", "Your vehicle determines your missions and hourly rate. Some require a license — GUIDKO connects you with a partner school.")}
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
            {DELIVERY_VEHICLES.map(v => (
              <Card key={v.k} hover onClick={() => setVehicle(v)} style={{ padding: 22 }}>
                <div style={{ fontSize: 38, marginBottom: 14 }}>{v.g}</div>
                <div style={{ fontSize: 17, fontWeight: 600 }}>{v[lang] || v.fr}</div>
                <div style={{ fontSize: 13, color: C.slate, marginTop: 6, lineHeight: 1.45 }}>{v.desc[lang] || v.desc.fr}</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
                  <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, color: C.signal }}>{v.earn}</span>
                  {v.licence ? <Pill tone="flame">🪪 {v.licence}</Pill> : <Pill tone="signal">{t("Sans permis","No license")}</Pill>}
                </div>
                <div style={{ marginTop: 10, display: "flex", gap: 5, flexWrap: "wrap" }}>
                  {v.cats.map(c => { const cat = DELIVERY_CATS.find(d => d.k === c); return cat ? <span key={c} style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "#F0EBDC", color: C.slate }}>{cat.g} {cat.fr}</span> : null; })}
                </div>
              </Card>
            ))}
          </div>
          <Card style={{ padding: 22, marginTop: 18, display: "flex", gap: 16, alignItems: "center", background: "#FBF8EE", maxWidth: 640 }}>
            <div style={{ fontSize: 30 }}>🎓</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>{t("Tu n'as pas encore le permis ?","Don't have a license yet?")}</div>
              <div style={{ fontSize: 13, color: C.slate, marginTop: 4, lineHeight: 1.5 }}>{t("GUIDKO te connecte à une auto-école partenaire pour les permis A, A2, B, C1, C.","GUIDKO connects you with a partner driving school for A, A2, B, C1, C licenses.")}</div>
            </div>
            <Button kind="primary" onClick={() => navigate("/eleve/overview")}>{t("Trouver une auto-école","Find a school")} →</Button>
          </Card>
        </PageBody>
      </>
    );
  }

  // Missions board
  const myMissions = MISSIONS.filter(m => (catFilter === "all" || m.cat === catFilter) && m.vehicles.includes(vehicle.k));

  return (
    <>
      <Topbar subtitle={t("TABLEAU DE MISSIONS","MISSION BOARD")} title={vehicle.g + " " + (vehicle[lang] || vehicle.fr)} search={false}
        actions={<><Button kind="ghost" size="sm" onClick={() => setVehicle(null)}>{t("Changer de véhicule","Change vehicle")}</Button><Button kind="flame" onClick={() => navigate("/livraison/drive")}>🛰 GUIDAROUTE</Button></>}/>
      <PageBody>
        {/* KPIs */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
          <KPI label={t("MISSIONS DISPO","AVAIL. MISSIONS")} value={myMissions.length} icon="📋"/>
          <KPI label={t("ACCEPTÉES","ACCEPTED")} value={accepted.length} deltaTone="signal"/>
          <KPI label={t("GAINS POTENTIELS","POTENTIAL EARN")} value={myMissions.reduce((s,m)=>s+m.pay,0).toFixed(2)+" €"} icon="€"/>
          <KPI label={t("TAUX HORAIRE","HOURLY RATE")} value={vehicle.earn} deltaTone="signal"/>
        </div>

        {/* Cat filter */}
        <div style={{ display: "flex", gap: 7, marginBottom: 16, flexWrap: "wrap" }}>
          <span onClick={() => setCatFilter("all")} style={{ padding: "7px 14px", borderRadius: 999, fontSize: 13, cursor: "pointer", background: catFilter === "all" ? C.ink : "#fff", color: catFilter === "all" ? "#fff" : C.ink, border: `1px solid ${catFilter === "all" ? C.ink : C.softLine}`, fontWeight: catFilter === "all" ? 600 : 500 }}>{t("Toutes","All")}</span>
          {DELIVERY_CATS.filter(c => myMissions.some(m => m.cat === c.k)).map(c => (
            <span key={c.k} onClick={() => setCatFilter(c.k)} style={{ display: "inline-flex", gap: 6, alignItems: "center", padding: "7px 14px", borderRadius: 999, fontSize: 13, cursor: "pointer", background: catFilter === c.k ? c.color : "#fff", color: catFilter === c.k ? "#fff" : C.ink, border: `1px solid ${catFilter === c.k ? c.color : C.softLine}`, fontWeight: catFilter === c.k ? 600 : 500 }}>{c.g} {c[lang] || c.fr}</span>
          ))}
        </div>

        {/* Mission cards */}
        {myMissions.length === 0 ? (
          <div style={{ padding: 40, textAlign: "center", color: C.slate }}>{t("Aucune mission disponible pour ce véhicule et ce filtre.","No missions for this vehicle and filter.")}</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {myMissions.map(m => {
              const cat = DELIVERY_CATS.find(c => c.k === m.cat);
              const done = accepted.includes(m.id);
              return (
                <Card key={m.id} style={{ padding: 18, display: "flex", alignItems: "center", gap: 16, opacity: done ? 0.5 : 1, borderLeft: m.urgent ? `3px solid ${C.flame}` : "1px solid transparent" }}>
                  <div style={{ width: 46, height: 46, borderRadius: 11, background: cat ? cat.color + "22" : "#F0EBDC", display: "grid", placeItems: "center", fontSize: 22, flexShrink: 0 }}>{cat?.g || "📦"}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{m.from}</div>
                      <span style={{ color: C.slate }}>→</span>
                      <div style={{ fontSize: 14, color: C.slate, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.to}</div>
                    </div>
                    <div style={{ display: "flex", gap: 8, marginTop: 6, flexWrap: "wrap" }}>
                      <Pill tone="neutral">{m.dist}</Pill>
                      {m.urgent && <Pill tone="flame">{t("Urgent","Urgent")} ⚡</Pill>}
                      {m.boost && <Pill tone="signal">+Boost</Pill>}
                      {cat && <span style={{ fontSize: 11, color: cat.color }}>{cat.fr}</span>}
                    </div>
                  </div>
                  <div style={{ textAlign: "right", flexShrink: 0 }}>
                    <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, lineHeight: 1 }}>{m.pay.toFixed(2)} €</div>
                    <Button kind={done ? "light" : "flame"} size="sm" style={{ marginTop: 8 }}
                      onClick={async () => {
                        if (done) return;
                        try {
                          if (window.GuidkoAPI && window.GuidkoAPI.delivery && typeof window.GuidkoAPI.delivery.create === "function" && typeof window.GuidkoAPI.delivery.accept === "function") {
                            const created = await window.GuidkoAPI.delivery.create({
                              recipientId: "guidko-recipient",
                              pickupAddress: m.from,
                              dropoffAddress: m.to,
                              item: cat ? cat.fr : "Mission",
                              weight: 1,
                              price: m.pay,
                            });
                            if (created && created.id) {
                              await window.GuidkoAPI.delivery.accept(created.id);
                            }
                          }
                        } catch (e) {}
                        setAccepted(a => [...a, m.id]);
                        toast.push(t("Mission acceptée ! GUIDAROUTE prêt.","Mission accepted! GUIDAROUTE ready."), "signal");
                      }}>
                      {done ? t("Acceptée ✓","Accepted ✓") : t("Accepter","Accept")}
                    </Button>
                  </div>
                </Card>
              );
            })}
          </div>
        )}

        {/* Cross-service */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 18 }}>
          <Card style={{ padding: 16, background: "#FBF8EE", display: "flex", gap: 12, alignItems: "center" }}>
            <span style={{ fontSize: 18 }}>⇅</span>
            <div style={{ flex: 1, fontSize: 13, color: C.slate }}>{t("Aussi covoitureur ? Complète tes revenus avec GUIDKO Covoiturage.","Also a driver? Top up income with GUIDKO Carpool.")}</div>
            <Button size="sm" kind="ink" onClick={() => navigate("/covoit/driver")}>{t("Covoit →","Carpool →")}</Button>
          </Card>
          <Card dark style={{ padding: 16, display: "flex", gap: 12, alignItems: "center" }}>
            <span style={{ fontSize: 18 }}>🏭</span>
            <div style={{ flex: 1, fontSize: 13, color: "#C9CEE3" }}>{t("Accès Logistique B2B : entrepôts, palettes, flottes.","B2B Logistics: warehouses, pallets, fleets.")}</div>
            <Button size="sm" kind="light" onClick={() => navigate("/livraison/b2b")}>{t("B2B →","B2B →")}</Button>
          </Card>
        </div>
      </PageBody>
    </>
  );
}

// ============ B2B LOGISTIQUE ============
function LivraisonB2B({ navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();

  const contracts = [
    { id: "c1", client: "Amazon Hub",         type: t("Tournée multi-stops","Multi-stop tour"), freq: t("Quotidien","Daily"),   vehicle: "🚐", pay: "94 €/tournée",  status: "actif" },
    { id: "c2", client: "LogiPro Roissy",      type: t("Livraison entrepôt","Warehouse delivery"), freq: t("3×/semaine","3×/week"),vehicle: "🚚", pay: "42 €/trajet",   status: "actif" },
    { id: "c3", client: "IKEA Logistique",     type: t("Déménagement léger","Light moving"),  freq: t("Variable","Variable"), vehicle: "🚐", pay: "58-120 €",      status: "nouveau" },
    { id: "c4", client: "Pharmacies Réunies",  type: t("Livraison médicale","Medical delivery"), freq: t("Quotidien","Daily"),   vehicle: "🛵", pay: "14 €/livraison", status: "actif" },
  ];

  const stats = [
    [t("CLIENTS B2B","B2B CLIENTS"), "12",    "+3"],
    [t("LIVREURS DÉDIÉS","DEDICATED COURIERS"), "34", "+6"],
    [t("LIVRAISONS / JOUR","DELIVERIES / DAY"), "187","▲"],
    [t("CA MENSUEL","MONTHLY REV."), "8 240 €","+18%"],
  ];

  return (
    <>
      <Topbar subtitle={t("LOGISTIQUE B2B · ENTREPÔTS & FLOTTES","B2B LOGISTICS · WAREHOUSES & FLEETS")} title={t("Tableau de bord B2B","B2B Dashboard")} search={false}
        actions={<Button kind="primary">+ {t("Nouveau contrat","New contract")}</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
          {stats.map(([l, v, d]) => <KPI key={l} label={l} value={v} delta={d} deltaTone="signal"/>)}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14 }}>
          {/* Contracts */}
          <Card style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <Label>{t("CONTRATS EN COURS","ACTIVE CONTRACTS")}</Label>
              <Pill tone="signal">{contracts.filter(c=>c.status==="actif").length} {t("actifs","active")}</Pill>
            </div>
            {contracts.map((c, i) => (
              <div key={c.id} style={{ display: "flex", gap: 14, padding: "14px 20px", borderTop: i===0?"none":`1px solid ${C.softLine}`, alignItems: "center" }}>
                <div style={{ fontSize: 28 }}>{c.vehicle}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{c.client}</div>
                  <div style={{ fontSize: 12, color: C.slate }}>{c.type} · {c.freq}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 13, fontWeight: 600 }}>{c.pay}</div>
                  <Pill tone={c.status === "actif" ? "signal" : "flame"}>{c.status === "actif" ? t("Actif","Active") : t("Nouveau","New")}</Pill>
                </div>
              </div>
            ))}
          </Card>

          {/* Vehicles needed */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <Card dark style={{ padding: 22 }}>
              <Label color="#7A82A8" style={{ marginBottom: 12 }}>{t("FLOTTE REQUISE","FLEET NEEDED")}</Label>
              {[["🚚", t("Poids lourds","Trucks"), 4], ["🚐", t("Camionnettes","Vans"), 12], ["🛵", t("Scooters","Scooters"), 8], ["🚲", t("Vélos-cargo","Cargo bikes"), 6]].map(([g, n, v]) => (
                <div key={n} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderTop: `1px solid #1F2949`, fontSize: 13 }}>
                  <span style={{ display: "inline-flex", gap: 8 }}>{g} {n}</span>
                  <span style={{ fontFamily: "'Geist Mono', monospace", fontWeight: 600 }}>{v}</span>
                </div>
              ))}
              <Button kind="flame" full style={{ marginTop: 14 }} onClick={() => toast.push(t("Recrutement livreurs lancé !","Courier recruitment started!"), "signal")}>{t("Recruter des livreurs","Recruit couriers")}</Button>
            </Card>
            <Card style={{ padding: 18, display: "flex", gap: 12, alignItems: "center", background: "#FBF8EE" }}>
              <span style={{ fontSize: 20 }}>🎓</span>
              <div style={{ flex: 1, fontSize: 13, color: C.slate, lineHeight: 1.45 }}>{t("Besoin de chauffeurs permis C ? GUIDKO les forme en partenariat avec des auto-écoles.","Need C-license drivers? GUIDKO trains them via partner schools.")}</div>
              <Button size="sm" kind="ink" onClick={() => navigate("/gerant/overview")}>{t("Partenaires","Partners")}</Button>
            </Card>
          </div>
        </div>
      </PageBody>
    </>
  );
}

// ============ GUIDAROUTE MODE LIVRAISON ============
const DELIVERY_STEPS = [
  { instr: { fr: "Récupérer chez Chez Mama · 12e", en: "Pick up at Chez Mama · 12e" }, lia: { fr: "Arrêt temporaire : 3 min max sans bloquer la circulation. Hazards si nécessaire.", en: "Temporary stop: 3 min max without blocking traffic. Hazards if needed." }, icon: "📦", tone: "sky" },
  { instr: { fr: "Tourner à gauche Bd Voltaire", en: "Turn left on Bd Voltaire" }, lia: { fr: "Clignotant 30 m avant. Vérifier rétroviseur et angle mort.", en: "Signal 30m ahead. Check mirror and blind spot." }, icon: "↰", tone: "flame" },
  { instr: { fr: "Zone 30 — ralentis", en: "Zone 30 — slow down" }, lia: { fr: "30 km/h max. Piétons et cyclistes prioritaires. Port du casque obligatoire.", en: "30 km/h max. Pedestrians and cyclists have priority. Helmet required." }, icon: "⚠", tone: "danger" },
  { instr: { fr: "Déposer au 18 rue Voltaire", en: "Drop off at 18 rue Voltaire" }, lia: { fr: "Code interphone : 1234A. Notifie le client via l'app.", en: "Intercom: 1234A. Notify the customer via the app." }, icon: "🏠", tone: "signal" },
];

function LivraisonDriveMode({ navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const [on, setOn] = React.useState(false);
  const [i, setI] = React.useState(0);
  const [voice, setVoice] = React.useState(true);
  const step = DELIVERY_STEPS[i];
  const toneColor = { sky: C.sky, flame: C.flame, danger: "#E11D48", signal: C.signal };

  React.useEffect(() => { if (!on) return; const id = setInterval(() => setI(x => (x+1)%DELIVERY_STEPS.length), 4000); return () => clearInterval(id); }, [on]);
  React.useEffect(() => {
    if (!on || !voice) return;
    try { const u = new SpeechSynthesisUtterance(step.lia[lang]); u.lang = lang==="fr"?"fr-FR":"en-US"; u.rate=1.02; window.speechSynthesis.cancel(); window.speechSynthesis.speak(u); } catch(e){}
  }, [i, on, voice]);

  return (
    <>
      <Topbar subtitle={t("GUIDAROUTE · LIVRAISON","GUIDAROUTE · DELIVERY")} title={t("Mode livraison","Delivery mode")} search={false}
        actions={<div style={{ display: "flex", alignItems: "center", gap: 8 }}><Toggle on={voice} onChange={setVoice}/><span style={{ fontSize: 13, color: C.slate }}>{t("Voix","Voice")}</span></div>}/>
      <PageBody style={{ padding: 0 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", height: "100%" }}>
          <div style={{ position: "relative", background: "#0A0E1B", overflow: "hidden" }}>
            <svg width="100%" height="100%" style={{ position: "absolute", inset: 0 }}>
              <defs><pattern id="dlg" width="44" height="44" patternUnits="userSpaceOnUse"><path d="M44 0 L0 0 0 44" fill="none" stroke="#ffffff08" strokeWidth="1"/></pattern></defs>
              <rect width="100%" height="100%" fill="url(#dlg)"/>
              <path d="M 80 600 Q 160 480 180 380 Q 200 280 300 200" stroke="#1F2949" strokeWidth="28" fill="none" strokeLinecap="round"/>
              <path d="M 80 600 Q 160 480 180 380 Q 200 280 300 200" stroke={toneColor[step.tone]} strokeWidth="4" fill="none" strokeDasharray="4 12" strokeLinecap="round" opacity="0.9"/>
              <circle cx="80" cy="600" r="8" fill={C.signal}/>
              <circle cx="300" cy="200" r="10" fill={C.flame}/>
            </svg>
            <div style={{ position: "absolute", top: 18, left: 18, right: 18, background: "rgba(11,15,31,0.88)", border: "1px solid #1F2949", borderRadius: 14, padding: "14px 18px", color: "#fff", display: "flex", gap: 14, backdropFilter: "blur(6px)" }}>
              <div style={{ width: 46, height: 46, borderRadius: 11, background: toneColor[step.tone], display: "grid", placeItems: "center", fontSize: 22, flexShrink: 0 }}>{step.icon}</div>
              <div><div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, color: "#7A82A8", letterSpacing: "0.14em" }}>{t("PROCHAINE ÉTAPE","NEXT STEP")}</div><div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>{step.instr[lang]}</div></div>
            </div>
            {!on && <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(6,9,26,0.6)" }}>
              <Button kind="flame" size="lg" onClick={() => setOn(true)}>▶ {t("Démarrer","Start")}</Button>
            </div>}
          </div>
          <div style={{ background: C.paper, padding: 24, display: "flex", flexDirection: "column", gap: 14, borderLeft: `1px solid ${C.softLine}` }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ width: 30, height: 30, borderRadius: 9, background: C.ink, color: C.flame, display: "grid", placeItems: "center", fontSize: 13 }}>✦</span>
              <div><div style={{ fontWeight: 600 }}>Lia</div><div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, color: on ? C.signal : C.slate, letterSpacing: "0.14em" }}>● {on ? t("EN DIRECT","LIVE") : t("EN PAUSE","PAUSED")}</div></div>
            </div>
            <Card style={{ padding: 18, borderLeft: `3px solid ${toneColor[step.tone]}`, flex: 1 }}>
              <Label style={{ marginBottom: 8 }}>{t("CODE EN DIRECT","LIVE CODE")}</Label>
              <div style={{ fontSize: 17, lineHeight: 1.45, fontWeight: 500 }}>{on ? step.lia[lang] : t("Lance la livraison pour activer le code de la route en direct.","Start delivery to activate live road code.")}</div>
            </Card>
            <div style={{ display: "flex", gap: 4 }}>
              {DELIVERY_STEPS.map((_, k) => <span key={k} style={{ flex: 1, height: 4, borderRadius: 2, background: k === i && on ? C.flame : "#E0DAC8" }}/>)}
            </div>
            <div style={{ padding: 14, background: "#FFF1EB", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, lineHeight: 1.5 }}>
              💡 {t("Lia guide le livreur — elle ne prend pas le guidon.","Lia guides the courier — it doesn't take the wheel.")}
            </div>
            {on && <Button kind="light" full onClick={() => { setOn(false); try { window.speechSynthesis.cancel(); } catch(e){} }}>■ {t("Arrêter","Stop")}</Button>}
            <Button kind="ghost" size="sm" full onClick={() => navigate("/livraison/livreur")}>{t("← Retour missions","← Back to missions")}</Button>
          </div>
        </div>
      </PageBody>
    </>
  );
}

function LivraisonTrack() {
  const C = GK.colors;
  const { t } = useI18n();
  return (
    <>
      <Topbar subtitle={t("SUIVI","TRACKING")} title={t("En route !","On its way!")} search={false}/>
      <PageBody>
        <Card dark style={{ padding: 36, textAlign: "center", maxWidth: 420, margin: "0 auto" }}>
          <div style={{ fontSize: 56 }}>🛵</div>
          <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 52, lineHeight: 1, margin: "16px 0 8px" }}>18 min</div>
          <div style={{ fontSize: 14, color: "#C9CEE3" }}>{t("GUIDAROUTE actif.","GUIDAROUTE active.")}</div>
        </Card>
      </PageBody>
    </>
  );
}

window.LivraisonApp = LivraisonApp;
