/* GUIDKO Services — branches additionnelles, chacune avec sa porte d'entrée.
   Énergie/Recharge · Stationnement · Pièces & Entretien · Flotte B2B.
   Pages partagées (role-aware), reliées Wallet/Marché/GPS. Langage premium GUIDKO. */

function SvcHero({ icon, color, kicker, title, sub }) {
  const C = GK.colors;
  return (
    <Card dark style={{ padding: 26, marginBottom: 16, position: "relative", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        <div style={{ width: 58, height: 58, borderRadius: 15, background: color, display: "grid", placeItems: "center", color: "#fff", flexShrink: 0 }}>{window.GKIcon && window.hasGKIcon && window.hasGKIcon(icon) ? <GKIcon name={icon} size={27}/> : "◆"}</div>
        <div>
          <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.16em", color: "#7A82A8" }}>{kicker}</div>
          <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, lineHeight: 1.05, marginTop: 4 }}>{title}</div>
          <div style={{ fontSize: 13, color: "#9098B5", marginTop: 6, maxWidth: 460, lineHeight: 1.5 }}>{sub}</div>
        </div>
      </div>
    </Card>
  );
}

// ============ ÉNERGIE / RECHARGE ============
function EnergiePage({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const stations = [
    { id: "e1", name: "TotalEnergies · Bd Voltaire", type: "fuel", dist: "0.4 km", price: { fr: "Gazole 1,72 €/L", en: "Diesel €1.72/L" }, slots: null, g: "fuel" },
    { id: "e2", name: "Ionity · A6 Aire de Lyon", type: "ev", dist: "2.1 km", price: { fr: "0,59 €/kWh · 350 kW", en: "€0.59/kWh · 350 kW" }, slots: "4/8", g: "bolt" },
    { id: "e3", name: "GUIDKO Recharge · 12e", type: "ev", dist: "0.9 km", price: { fr: "0,42 €/kWh · 150 kW", en: "€0.42/kWh · 150 kW" }, slots: "6/6", g: "bolt", partner: true },
    { id: "e4", name: "Station Avia · Nation", type: "fuel", dist: "1.3 km", price: { fr: "SP95 1,89 €/L", en: "SP95 €1.89/L" }, slots: null, g: "fuel" },
  ];
  const [filter, setFilter] = React.useState("all");
  const list = stations.filter(s => filter === "all" || s.type === filter);
  return (
    <>
      <Topbar subtitle={t("ÉNERGIE & RECHARGE", "ENERGY & CHARGING")} title={t("Faire le plein, recharger", "Refuel, recharge")} search={false}
        actions={<Button kind="primary" onClick={() => navigate && navigate(`/${role}/wallet`)}>{t("Payer via Wallet", "Pay via Wallet")}</Button>}/>
      <PageBody>
        <SvcHero icon="bolt" color="#0FB76B" kicker="GUIDKO ENERGIE" title={t("Le réseau, près de toi", "The network, near you")} sub={t("Carburant et bornes de recharge géolocalisés, prix en direct, réservation et paiement par Wallet. Relié à la carte GUIDAROUTE.", "Geolocated fuel & charging, live prices, booking and Wallet payment. Linked to the GUIDAROUTE map.")}/>
        <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
          {[["all", t("Tout", "All")], ["ev", t("Recharge élec.", "EV charging")], ["fuel", t("Carburant", "Fuel")]].map(([k, l]) => (
            <span key={k} onClick={() => setFilter(k)} style={{ padding: "8px 14px", borderRadius: 999, cursor: "pointer", fontSize: 13, fontWeight: filter === k ? 600 : 500, background: filter === k ? C.ink : "#fff", color: filter === k ? "#fff" : C.ink, border: `1px solid ${filter === k ? C.ink : C.softLine}` }}>{l}</span>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
          {list.map(s => (
            <Card key={s.id} hover style={{ padding: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: s.type === "ev" ? "#EAF7F0" : "#FFF1EB", color: s.type === "ev" ? "#0a7d4a" : C.flame, display: "grid", placeItems: "center" }}>{window.GKIcon && window.hasGKIcon(s.g) ? <GKIcon name={s.g} size={19}/> : (s.type === "ev" ? "⚡" : "⛽")}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: C.slate }}>{s.dist}{s.partner ? " · " + t("Partenaire", "Partner") : ""}</div>
                </div>
              </div>
              <div style={{ fontSize: 13, color: C.ink, fontWeight: 500 }}>{s.price[GK_lang ? GK_lang() : "fr"] || s.price.fr}</div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12 }}>
                {s.slots ? <Pill tone="signal">{s.slots} {t("bornes libres", "free")}</Pill> : <span style={{ fontSize: 11.5, color: C.slate }}>{t("Station-service", "Fuel station")}</span>}
                <Button size="sm" kind="ghost" onClick={() => toast.push(t("Itinéraire lancé (GUIDAROUTE)", "Route started (GUIDAROUTE)"), "signal")}>{t("Itinéraire", "Route")} →</Button>
              </div>
            </Card>
          ))}
        </div>
      </PageBody>
    </>
  );
}

// ============ STATIONNEMENT ============
function ParkingPage({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const [booked, setBooked] = React.useState(null);
  const spots = [
    { id: "p1", name: "Parking Nation", dist: "0.3 km", price: 2.4, free: 12, secure: true },
    { id: "p2", name: "Place résident · 11e", dist: "0.6 km", price: 1.8, free: 3, secure: false },
    { id: "p3", name: "Indigo · Gare de Lyon", dist: "1.1 km", price: 3.2, free: 28, secure: true },
    { id: "p4", name: "Box privé (particulier)", dist: "0.8 km", price: 4.0, free: 1, secure: true, p2p: true },
  ];
  return (
    <>
      <Topbar subtitle={t("STATIONNEMENT", "PARKING")} title={t("Se garer, sans tourner", "Park without circling")} search={false}/>
      <PageBody>
        <SvcHero icon="location" color="#3B6FF8" kicker="GUIDKO PARKING" title={t("Une place qui t'attend", "A spot waiting for you")} sub={t("Réserve une place à l'avance, sécurisée ou entre particuliers. Paiement Wallet, guidage GUIDAROUTE jusqu'à la place.", "Book ahead, secure or peer-to-peer. Wallet payment, GUIDAROUTE guidance to the spot.")}/>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
          {spots.map(s => (
            <Card key={s.id} hover style={{ padding: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: "#EAF0FE", color: "#2456c8", display: "grid", placeItems: "center" }}>{window.GKIcon && window.hasGKIcon("location") ? <GKIcon name="location" size={19}/> : "🅿"}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: C.slate }}>{s.dist}{s.p2p ? " · " + t("Particulier", "Private") : ""}</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
                <Pill tone="signal">{s.free} {t("libres", "free")}</Pill>
                {s.secure && <Pill tone="neutral">🔒 {t("Sécurisé", "Secure")}</Pill>}
              </div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22 }}>{money(s.price)}<span style={{ fontSize: 12, color: C.slate }}>/h</span></span>
                <Button size="sm" kind={booked === s.id ? "light" : "primary"} onClick={() => { setBooked(s.id); toast.push(t("Place réservée — payée via Wallet.", "Spot booked — paid via Wallet."), "signal"); }}>{booked === s.id ? t("Réservée ✓", "Booked ✓") : t("Réserver", "Book")}</Button>
              </div>
            </Card>
          ))}
        </div>
      </PageBody>
    </>
  );
}

// ============ PIÈCES & ENTRETIEN ============
function EntretienPage({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const garages = [
    { id: "g1", name: "Garage Central · 11e", note: 4.8, svc: { fr: "Révision, freins, pneus", en: "Service, brakes, tyres" }, from: 89 },
    { id: "g2", name: "Speedy · Nation", note: 4.5, svc: { fr: "Vidange, contrôle technique", en: "Oil change, MOT" }, from: 49 },
    { id: "g3", name: "GUIDKO Entretien · Mobile", note: 5.0, svc: { fr: "Mécanicien à domicile", en: "Mechanic at home" }, from: 69, partner: true },
  ];
  const parts = [
    { id: "pt1", name: { fr: "Plaquettes de frein", en: "Brake pads" }, price: 48 },
    { id: "pt2", name: { fr: "Filtre à huile", en: "Oil filter" }, price: 14 },
    { id: "pt3", name: { fr: "Balais d'essuie-glace", en: "Wiper blades" }, price: 22 },
  ];
  return (
    <>
      <Topbar subtitle={t("PIÈCES & ENTRETIEN", "PARTS & SERVICE")} title={t("Entretenir son véhicule", "Maintain your vehicle")} search={false}/>
      <PageBody>
        <SvcHero icon="auto" color="#A78BFA" kicker="GUIDKO ENTRETIEN" title={t("Garages & pièces, au juste prix", "Garages & parts, fair price")} sub={t("Réserve un créneau garage ou un mécanicien à domicile, commande tes pièces. Devis estimés par Lia, paiement Wallet, escrow sur les pièces.", "Book a garage slot or a home mechanic, order parts. Lia-estimated quotes, Wallet payment, escrow on parts.")}/>
        <Label style={{ marginBottom: 12 }}>{t("GARAGES & MÉCANICIENS", "GARAGES & MECHANICS")}</Label>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12, marginBottom: 24 }}>
          {garages.map(g => (
            <Card key={g.id} hover style={{ padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{g.name}</div>
                <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 12, color: "#0a7d4a" }}>★ {g.note}</span>
              </div>
              <div style={{ fontSize: 12.5, color: C.slate, marginTop: 4 }}>{g.svc[GK_lang ? GK_lang() : "fr"] || g.svc.fr}{g.partner ? " · " + t("Partenaire", "Partner") : ""}</div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 14 }}>
                <span style={{ fontSize: 13, color: C.slate }}>{t("Dès", "From")} <strong style={{ color: C.ink }}>{money(g.from)}</strong></span>
                <Button size="sm" kind="primary" onClick={() => toast.push(t("Créneau demandé — confirmation par message.", "Slot requested — confirmation by message."), "signal")}>{t("Réserver", "Book")}</Button>
              </div>
            </Card>
          ))}
        </div>
        <Label style={{ marginBottom: 12 }}>{t("PIÈCES DÉTACHÉES", "SPARE PARTS")}</Label>
        <Card style={{ padding: 0, overflow: "hidden" }}>
          {parts.map((p, i) => (
            <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 18px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
              <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{p.name[GK_lang ? GK_lang() : "fr"] || p.name.fr}</div>
              <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 13, fontWeight: 600 }}>{money(p.price)}</span>
              <Button size="sm" kind="ghost" onClick={() => { toast.push(t("Ajouté au panier (escrow).", "Added to cart (escrow)."), "signal"); navigate && navigate(`/${role}/vehicles`); }}>{t("+ Commander", "+ Order")}</Button>
            </div>
          ))}
        </Card>
      </PageBody>
    </>
  );
}

// ============ FLOTTE B2B / ENTREPRISES ============
function FlottePage({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const fleet = [
    { id: "f1", veh: { fr: "Camionnettes", en: "Vans" }, count: 6, active: 4, status: "ok" },
    { id: "f2", veh: { fr: "Voitures double-commande", en: "Dual-control cars" }, count: 8, active: 7, status: "ok" },
    { id: "f3", veh: { fr: "Scooters livraison", en: "Delivery scooters" }, count: 12, active: 9, status: "warn" },
    { id: "f4", veh: { fr: "Poids lourds", en: "Trucks" }, count: 2, active: 2, status: "ok" },
  ];
  const stats = [
    [t("VÉHICULES", "VEHICLES"), "28", "trendup"],
    [t("EN SERVICE", "IN SERVICE"), "22", "check"],
    [t("ENTRETIENS DUS", "SERVICE DUE"), "3", "alert"],
    [t("COÛT / MOIS", "COST / MO"), money(4280), "finance"],
  ];
  return (
    <>
      <Topbar subtitle={t("FLOTTE B2B · ENTREPRISES", "B2B FLEET · BUSINESS")} title={t("Gérer mon parc", "Manage my fleet")} search={false}
        actions={<Button kind="primary" onClick={() => toast.push(t("Véhicule ajouté au parc.", "Vehicle added to fleet."), "signal")}>+ {t("Ajouter un véhicule", "Add vehicle")}</Button>}/>
      <PageBody>
        <SvcHero icon="b2b" color="#6B7280" kicker="GUIDKO FLOTTE" title={t("Tout ton parc, un tableau", "Your whole fleet, one board")} sub={t("Suivi des véhicules, entretien, affectation aux moniteurs/livreurs, location croisée sur le Marché. Relié à l'Assurance Pro et au Wallet.", "Track vehicles, service, assign to instructors/couriers, cross-rent on the Market. Linked to Pro Insurance and Wallet.")}/>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
          {stats.map(([l, v, ic]) => (
            <Card key={l} style={{ padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <Label style={{ marginBottom: 8 }}>{l}</Label>
                <span style={{ color: C.slate }}>{window.GKIcon && window.hasGKIcon(ic) ? <GKIcon name={ic} size={16}/> : ""}</span>
              </div>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32, lineHeight: 1 }}>{v}</div>
            </Card>
          ))}
        </div>
        <Card style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "14px 18px", borderBottom: `1px solid ${C.softLine}` }}><Label>{t("PARC PAR CATÉGORIE", "FLEET BY CATEGORY")}</Label></div>
          {fleet.map((f, i) => (
            <div key={f.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{f.veh[GK_lang ? GK_lang() : "fr"] || f.veh.fr}</div>
                <div style={{ fontSize: 12, color: C.slate }}>{f.active}/{f.count} {t("en service", "in service")}</div>
              </div>
              <div style={{ width: 120, height: 6, borderRadius: 3, background: C.cream, overflow: "hidden" }}><div style={{ height: "100%", width: `${f.active / f.count * 100}%`, background: f.status === "warn" ? C.flame : C.signal, borderRadius: 3 }}/></div>
              {f.status === "warn" ? <Pill tone="flame">{t("Entretien dû", "Service due")}</Pill> : <Pill tone="signal">OK</Pill>}
            </div>
          ))}
        </Card>
        <div style={{ marginTop: 14, padding: 14, background: "#FBF8EE", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, lineHeight: 1.5 }}>
          {t("Un véhicule libre ? Lia le propose automatiquement à la location ou au covoiturage sur le Marché — pour que rien ne dorme au parking.", "A free vehicle? Lia auto-lists it for rental or carpool on the Market — so nothing sits idle.")}
        </div>
      </PageBody>
    </>
  );
}

window.EnergiePage = EnergiePage;
window.ParkingPage = ParkingPage;
window.EntretienPage = EntretienPage;
window.FlottePage = FlottePage;
