/* GUIDKO Discover — PAGE CENTRALE.
   Fonctionne comme un LIVRE : on atterrit, on comprend, on entre.
   Sections narratives progressives : Qui sommes-nous → Ton entrée → Ce qui se passe → Explorer.
   Pub = première ouverture / post-inscription. Non-pub = onglet dans chaque compte. */

const DISCOVER_FAMILIES = [
  { fr: "Apprendre & Travailler", en: "Learn & Work", keys: ["eleve", "pro", "emploi", "formation", "prevention"] },
  { fr: "Acheter, Vendre, Entretenir", en: "Buy, Sell, Maintain", keys: ["auto", "entretien", "carrosserie", "demarches", "recyclage", "financement", "equipement"] },
  { fr: "Se déplacer", en: "Get around", keys: ["covoit", "vtc", "autopartage", "mobilitedouce", "adapte", "train", "bus", "bateau", "aerien", "transit"] },
  { fr: "Transporter & Livrer", en: "Transport & Deliver", keys: ["livraison", "fret", "convoyage", "sanitaire", "flotte"] },
  { fr: "Énergie, Route & Loisirs", en: "Energy, Road & Leisure", keys: ["energie", "recharge", "parking", "peage", "lavage", "depannage", "controle", "loisirs", "engins", "evenement", "tourisme", "voiturier", "connect", "verte"] },
  { fr: "Socle & Confiance", en: "Core & Trust", keys: ["wallet", "assurance", "pass", "data", "gps"] },
];

// Portes principales (section 2 du livre)
const MAIN_DOORS = [
  { k: "pro",       ic: "b2b",     color: "#0B0F1F", fr: "Espace Pro", en: "Pro", d: { fr: "Gérant · Moniteur · Accueil", en: "Manager · Instructor · Reception" } },
  { k: "eleve",     ic: "eleve",   color: "#FF5A1F", fr: "Espace Élève", en: "Student", d: { fr: "Apprendre à conduire", en: "Learn to drive" } },
  { k: "auto",      ic: "auto",    color: "#A78BFA", fr: "Marché Mobilité", en: "Mobility Market", d: { fr: "Acheter · vendre · louer", en: "Buy · sell · rent" } },
  { k: "covoit",    ic: "covoit",  color: "#0FB76B", fr: "Covoiturage", en: "Carpool", d: { fr: "Partager la route", en: "Share the road" } },
  { k: "livraison", ic: "b2b",     color: "#3B6FF8", fr: "Livraison", en: "Delivery", d: { fr: "Commander ou livrer", en: "Order or deliver" } },
  { k: "gps",       ic: "bolt",    color: "#FF5A1F", fr: "GUIDAROUTE", en: "GUIDAROUTE", d: { fr: "Le code, vivant", en: "The code, alive" } },
];

// Posts du fil (section 3 du livre)
const FEED_POSTS = [
  { who: "Marc Lefèvre", role: { fr: "Moniteur · Lubasa", en: "Instructor · Lubasa" }, tone: 0, time: "12 min",
    text: { fr: "Encore une réussite au permis B aujourd'hui ! Bravo Léa — 3 mois de travail. Le covoiturage pour venir aux leçons, ça a tout changé.", en: "Another B-licence pass today! Well done Léa — 3 months of work. Carpooling to lessons changed everything." },
    react: 48, comments: 7, tag: { k: "eleve", fr: "École", en: "School" }, tagColor: "#FF5A1F" },
  { who: "GUIDKO", role: { fr: "Officiel", en: "Official" }, tone: 2, time: "1 h", official: true,
    text: { fr: "🚆 Nouveau : le rail rejoint le pont. Train + dernier km en covoiturage, payé en une fois.", en: "🚆 New: rail joins the bridge. Train + last-mile carpool, paid once." },
    react: 213, comments: 24, tag: { k: "train", fr: "Train", en: "Rail" }, tagColor: "#3B6FF8", pinned: true },
  { who: "Sofia Nkamba", role: { fr: "Vend sa Clio IV", en: "Selling her Clio IV" }, tone: 1, time: "2 h",
    text: { fr: "Je vends ma Clio IV (2019, 68 000 km). CT OK, paiement escrow GUIDKO. 8 900 €. Visites ce week-end.", en: "Selling my Clio IV (2019, 68k km). MOT OK, GUIDKO escrow. €8,900. Viewings this weekend." },
    react: 31, comments: 12, tag: { k: "auto", fr: "Marché", en: "Market" }, tagColor: "#A78BFA", price: 8900 },
  { who: "Yanis Traoré", role: { fr: "Covoitureur & livreur", en: "Driver & courier" }, tone: 4, time: "4 h",
    text: { fr: "Paris → Lyon vendredi 18h, 3 places. Je complète avec des livraisons sur la route. Qui embarque ?", en: "Paris → Lyon Fri 6pm, 3 seats. Topping up with deliveries en route. Who's in?" },
    react: 19, comments: 5, tag: { k: "covoit", fr: "Covoit", en: "Carpool" }, tagColor: "#0FB76B" },
];

// Live deals (section 3 inline)
const LIVE_DEALS = [
  { fr: "Peugeot 208 · 42k km", en: "Peugeot 208 · 42k km", sub: { fr: "Vérifiée · Escrow", en: "Verified · Escrow" }, price: 12400, interested: 7, k: "auto" },
  { fr: "Paris → Lyon · 2 places", en: "Paris → Lyon · 2 seats", sub: { fr: "Ven 18h · 29 €/place", en: "Fri 6pm · €29/seat" }, price: 29, interested: 4, k: "covoit" },
  { fr: "Mission urgente · 12e", en: "Urgent mission · 12e", sub: { fr: "Vélo/Scooter · 1.4 km", en: "Bike/Scooter · 1.4 km" }, price: 7.2, interested: null, k: "livraison" },
];

function discoverMeta(key) {
  const C = GK.colors;
  const SVC = { assurance: ["shield", C.signal], energie: ["bolt", C.signal], parking: ["location", C.sky], entretien: ["auto", "#A78BFA"], flotte: ["b2b", C.slate], wallet: ["finance", C.flame], auto: ["auto", "#A78BFA"], covoit: ["covoit", C.signal], livraison: ["b2b", C.flame], eleve: ["eleve", C.flame], pro: ["b2b", C.ink], gps: ["bolt", C.flame] };
  if (SVC[key]) return { ic: SVC[key][0], color: SVC[key][1] };
  const bd = window.BRANCH_DATA && window.BRANCH_DATA[key];
  if (bd) return { ic: bd.icon || "region", color: bd.accent || C.slate };
  return { ic: "region", color: C.slate };
}
function discoverLabel(key, lang) {
  const bd = window.BRANCH_DATA && window.BRANCH_DATA[key];
  if (bd) return bd[lang] || bd.fr;
  const map = { eleve: { fr: "Espace Élève", en: "Student" }, pro: { fr: "Espace Pro", en: "Pro" }, auto: { fr: "Marché Mobilité", en: "Mobility Market" }, covoit: { fr: "Covoiturage", en: "Carpool" }, livraison: { fr: "Livraison", en: "Delivery" }, wallet: { fr: "Wallet", en: "Wallet" }, assurance: { fr: "Assurance", en: "Insurance" }, energie: { fr: "Énergie", en: "Energy" }, parking: { fr: "Stationnement", en: "Parking" }, entretien: { fr: "Entretien", en: "Service" }, flotte: { fr: "Flotte B2B", en: "B2B Fleet" }, gps: { fr: "GUIDAROUTE", en: "GUIDAROUTE" }, pass: { fr: "Pass Mobilité", en: "Mobility Pass" } };
  return (map[key] && (map[key][lang] || map[key].fr)) || key;
}
function discoverRoute(key) {
  const direct = { eleve: "eleve/overview", pro: "moniteur/overview", auto: "auto/market", covoit: "covoit/overview", livraison: "livraison/overview", gps: "gps/drive", wallet: "eleve/wallet", assurance: "assurance/overview" };
  return direct[key] || `${key}/overview`;
}

// ──────────────────────────────────────────────
// Sous-domaines par porte principale (hover dropdown)
const DOOR_SUBS = {
  pro:       [{ fr: "Espace Gérant", en: "Manager", k: "gerant" }, { fr: "Espace Accueil", en: "Reception", k: "accueil" }, { fr: "Espace Moniteur", en: "Instructor", k: "moniteur" }],
  eleve:     [{ fr: "Ma progression", en: "My progress", k: "overview" }, { fr: "Réserver une leçon", en: "Book a lesson", k: "book" }, { fr: "Code de la route", en: "Road code", k: "code" }],
  auto:      [{ fr: "Acheter un véhicule", en: "Buy a vehicle", k: "market" }, { fr: "Vendre le mien", en: "Sell mine", k: "sell" }, { fr: "Louer", en: "Rent", k: "rent" }, { fr: "Pièces détachées", en: "Spare parts", k: "parts" }, { fr: "Bateaux & Engins", en: "Boats & Machinery", k: "market" }],
  covoit:    [{ fr: "Chercher un trajet", en: "Find a ride", k: "search" }, { fr: "Proposer un trajet", en: "Offer a ride", k: "driver" }, { fr: "Trajets récurrents", en: "Recurring rides", k: "driver" }],
  livraison: [{ fr: "Commander un repas", en: "Order food", k: "client" }, { fr: "Livrer (missions)", en: "Deliver", k: "livreur" }, { fr: "Logistique B2B", en: "B2B logistics", k: "b2b" }],
  gps:       [{ fr: "Navigation", en: "Navigation", k: "drive" }, { fr: "Carte ressources", en: "Resource map", k: "map" }, { fr: "Code en continu", en: "Continuous code", k: "learn" }],
};

// ===== Filtre Lancement V1 (window.GK_LAUNCH) — ouverture progressive =====
if (window.GK_LAUNCH) {
  const gkAll = window.GK_LAUNCH.all || [];
  const gkCut = (arr, keyFn) => { for (let i = arr.length - 1; i >= 0; i--) if (!gkAll.includes(keyFn(arr[i]))) arr.splice(i, 1); };
  gkCut(MAIN_DOORS, d => d.k);
  DISCOVER_FAMILIES.forEach(f => { f.keys = f.keys.filter(k => gkAll.includes(k)); });
  for (let i = DISCOVER_FAMILIES.length - 1; i >= 0; i--) if (DISCOVER_FAMILIES[i].keys.length === 0) DISCOVER_FAMILIES.splice(i, 1);
  if (typeof FEED_POSTS !== "undefined") gkCut(FEED_POSTS, p => (p.tag && p.tag.k) || "eleve");
}

const GK_NB = (window.GK_LAUNCH && window.GK_LAUNCH.count) || 46;

function DiscoverPage({ role, navigate, pub }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const [likes, setLikes] = React.useState({});
  const [exploreOpen, setExploreOpen] = React.useState(false);
  const [hoveredDoor, setHoveredDoor] = React.useState(null);
  const store = (window.useStore ? window.useStore() : { state: {} });
  const me = store.state && store.state.user;
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const greeting = !pub && me ? t(`Salut ${me.name ? me.name.split(" ")[0] : ""}`, `Hi ${me.name ? me.name.split(" ")[0] : ""}`) : null;

  function go(key) {
    if (pub) {
      // Mémorise l'intention → LoginScreen ouvrira directement sur ce service
      try { localStorage.setItem("guidko_intent", key); } catch (e) {}
      navigate("/login");
    } else {
      navigate("/" + discoverRoute(key));
    }
  }

  const dark = pub;
  const bg     = dark ? C.ink        : C.paper;
  const card   = dark ? "#10172E"    : "#fff";
  const cardBd = dark ? "#1F2542"    : C.softLine;
  const txt    = dark ? "#fff"       : C.ink;
  const muted  = dark ? "#9098B5"    : C.slate;
  const sec    = dark ? "#0B0F1F"    : C.cream;

  const content = (
    <div className="gk-scroll" style={{ overflowY: "auto", flex: 1, background: bg, color: txt, fontFamily: "'Geist', sans-serif", WebkitFontSmoothing: "antialiased" }}>

      {/* ── SECTION 1 : LE MANIFESTE (comprendre d'un coup d'œil) ── */}
      <div style={{ padding: "40px 5vw 32px", maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.22em", color: C.flame, marginBottom: 10 }}>GUIDKO · {t("L'OS DE LA MOBILITÉ", "THE MOBILITY OS")}</div>
        <h1 style={{ fontFamily: "'Instrument Serif', serif", fontSize: "clamp(36px,6vw,68px)", fontWeight: 400, lineHeight: 0.96, letterSpacing: "-0.025em", margin: "0 0 18px" }}>
          {greeting ? <>{greeting},<br/><span style={{ fontStyle: "italic", color: C.flame }}>{t("que veux-tu faire ?", "what will you do?")}</span></> : <>{t("Un noyau.", "One core.")}<br/><span style={{ fontStyle: "italic", color: C.flame }}>{t(GK_NB + " services reliés.", GK_NB + " connected services.")}</span></>}
        </h1>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 12 }}>
          {[
            { g: "●", c: C.flame,  fr: "Former, gérer, accueillir", en: "Train, manage, welcome" },
            { g: "●", c: C.signal, fr: "Acheter, vendre, louer, livrer", en: "Buy, sell, rent, deliver" },
            window.GK_LAUNCH
              ? { g: "●", c: C.sky, fr: "Du permis au revenu", en: "From license to income" }
              : { g: "●", c: C.sky, fr: "Route, rail, eau, ciel", en: "Road, rail, sea, sky" },
          ].map((p, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "13px 15px", borderRadius: 12, background: card, border: `1px solid ${cardBd}` }}>
              <span style={{ color: p.c, fontSize: 9, flexShrink: 0 }}>●</span>
              <span style={{ fontSize: 14, fontWeight: 500 }}>{p[lang] || p.fr}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ── SECTION 2 : TON ENTRÉE (les portes principales) ── */}
      <div style={{ padding: "0 5vw 36px", maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
          <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.18em", color: muted }}>{t("TROUVE TON ENTRÉE", "FIND YOUR DOOR")}</div>
          <div style={{ flex: 1, height: 1, background: cardBd }}/>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(175px, 1fr))", gap: 11 }}>
          {MAIN_DOORS.map(d => {
            const subs = DOOR_SUBS[d.k] || [];
            const hov = hoveredDoor === d.k;
            return (
            <div key={d.k} style={{ position: "relative" }}
              onMouseEnter={() => setHoveredDoor(d.k)}
              onMouseLeave={() => setHoveredDoor(null)}>
              <div onClick={() => go(d.k)} style={{ padding: 18, borderRadius: 14, border: `1.5px solid ${hov ? d.color : cardBd}`, background: hov ? (dark ? "#1A2142" : C.cream) : card, cursor: "pointer", transition: "all .15s", height: "100%" }}>
                <div style={{ width: 42, height: 42, borderRadius: 11, background: d.color === C.ink ? (dark ? C.flame : C.ink) : d.color + "22", color: d.color === C.ink ? (dark ? C.ink : "#fff") : d.color, display: "grid", placeItems: "center", marginBottom: 12 }}>
                  {window.GKIcon && window.hasGKIcon(d.ic) ? <GKIcon name={d.ic} size={20}/> : "◆"}
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4, color: txt }}>{d[lang] || d.fr}</div>
                <div style={{ fontSize: 12, color: muted, lineHeight: 1.45 }}>{d.d[lang] || d.d.fr}</div>
                <div style={{ marginTop: 12, fontSize: 12, fontWeight: 600, color: d.color === C.ink ? C.flame : d.color, display: "flex", alignItems: "center", gap: 5 }}>
                  {pub ? t("Entrer", "Enter") : t("Ouvrir", "Open")} <span style={{ fontSize: 9, transition: "transform .15s", transform: hov && subs.length ? "rotate(90deg)" : "none" }}>▶</span>
                </div>
              </div>
              {hov && subs.length > 0 && (
                <div style={{ position: "absolute", top: "100%", left: 0, zIndex: 600, marginTop: 6, background: dark ? "#10172E" : "#fff", border: `1px solid ${dark ? "#2A3250" : C.softLine}`, borderRadius: 11, boxShadow: "0 14px 40px rgba(8,11,24,0.24)", minWidth: 220, overflow: "hidden" }}>
                  {subs.map((s, si) => {
                    const base = d.k === "pro" ? s.k : d.k === "eleve" ? "eleve" : d.k;
                    return (
                      <div key={si} onClick={(e) => { e.stopPropagation(); if (pub) { try { localStorage.setItem("guidko_intent", d.k); } catch (ex) {} navigate("/login"); } else { navigate(`/${base}/${s.k}`); } setHoveredDoor(null); }}
                        style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", cursor: "pointer", fontSize: 13.5, color: dark ? "#E6E9F5" : C.ink, borderTop: si === 0 ? "none" : `1px solid ${dark ? "#1F2949" : C.softLine}`, transition: "background .1s" }}
                        onMouseEnter={e => e.currentTarget.style.background = dark ? "#1F2949" : C.cream}
                        onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                        <span style={{ color: C.flame, fontSize: 11 }}>→</span>
                        <span>{s[lang] || s.fr}</span>
                      </div>
                    );
                  })}
                  <div onClick={() => go(d.k)} style={{ padding: "10px 14px", borderTop: `1px solid ${dark ? "#1F2949" : C.softLine}`, fontSize: 12.5, fontWeight: 600, color: d.color === C.ink ? C.flame : d.color, cursor: "pointer" }}>{t("Voir tout →", "See all →")}</div>
                </div>
              )}
            </div>
          );})}
          {/* Porte "Explorer les 46" */}
          <div onClick={() => setExploreOpen(o => !o)} style={{ padding: 18, borderRadius: 14, border: `2px dashed ${cardBd}`, background: "transparent", cursor: "pointer", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", gap: 8, minHeight: 140 }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: C.flame + "22", color: C.flame, display: "grid", placeItems: "center" }}>{window.GKIcon && window.hasGKIcon("region") ? <GKIcon name="region" size={19}/> : "+"}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: muted, textAlign: "center" }}>{t("Explorer les " + GK_NB + " services", "Explore all " + GK_NB)}</div>
            <div style={{ fontSize: 11, color: C.flame, fontWeight: 600 }}>{exploreOpen ? "▲" : "▼"}</div>
          </div>
        </div>

        {/* Explorateur dépliable (les 46 services) */}
        {exploreOpen && (
          <div style={{ marginTop: 16, padding: 18, borderRadius: 14, border: `1px solid ${cardBd}`, background: card }}>
            {DISCOVER_FAMILIES.map((fam, fi) => (
              <div key={fi} style={{ marginBottom: 20 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                  <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.14em", color: muted, fontWeight: 600 }}>{(fam[lang] || fam.fr).toUpperCase()}</span>
                  <div style={{ flex: 1, height: 1, background: cardBd }}/>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
                  {fam.keys.map(k => {
                    const m = discoverMeta(k);
                    return (
                      <span key={k} onClick={() => go(k)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 12px", borderRadius: 999, border: `1px solid ${cardBd}`, background: sec, cursor: "pointer", fontSize: 12.5, fontWeight: 500, color: txt, transition: "border-color .12s" }}
                        onMouseEnter={e => e.currentTarget.style.borderColor = m.color} onMouseLeave={e => e.currentTarget.style.borderColor = cardBd}>
                        <span style={{ color: m.color }}>{window.GKIcon && window.hasGKIcon(m.ic) ? <GKIcon name={m.ic} size={13}/> : "◆"}</span>
                        {discoverLabel(k, lang)}
                      </span>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── SECTION 3 : CE QUI SE PASSE (fil social + offres en vie) ── */}
      <div style={{ padding: "0 5vw 40px", maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
          <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.18em", color: muted }}>{t("CE QUI SE PASSE", "WHAT'S HAPPENING")}</div>
          <div style={{ flex: 1, height: 1, background: cardBd }}/>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 14, alignItems: "start" }} className="discover-layout">
          {/* Feed */}
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {/* Composer */}
            <div style={{ background: card, border: `1px solid ${cardBd}`, borderRadius: 13, padding: "11px 14px", display: "flex", gap: 10, alignItems: "center" }}>
              {window.Avatar ? <Avatar name="?" size={34} tone={3}/> : <div style={{ width: 34, height: 34, borderRadius: 999, background: C.flame + "55" }}/>}
              <div onClick={() => pub ? navigate("/login") : null} style={{ flex: 1, padding: "9px 13px", borderRadius: 999, background: sec, color: muted, fontSize: 13, cursor: pub ? "pointer" : "text" }}>{t("Partage avec la communauté…", "Share with the community…")}</div>
              <button onClick={() => pub ? navigate("/login") : null} style={{ padding: "8px 13px", borderRadius: 999, border: "none", background: C.flame, color: "#fff", fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{t("Publier", "Post")}</button>
            </div>

            {/* EN VIE */}
            <div style={{ background: card, border: `2px solid ${C.flame}`, borderRadius: 13, padding: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 11, fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.14em", color: C.flame }}>
                <span style={{ width: 7, height: 7, borderRadius: 999, background: C.flame, animation: "gkBlink 1s infinite" }}/>
                {t("EN VIE — OFFRES DU MOMENT", "LIVE — CURRENT DEALS")}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                {LIVE_DEALS.map((d, i) => {
                  const m = discoverMeta(d.k);
                  return (
                    <div key={i} onClick={() => go(d.k)} style={{ display: "flex", alignItems: "center", gap: 11, padding: 11, borderRadius: 10, background: sec, cursor: "pointer" }}>
                      <div style={{ width: 36, height: 36, borderRadius: 9, background: m.color + "22", color: m.color, display: "grid", placeItems: "center", flexShrink: 0 }}>{window.GKIcon && window.hasGKIcon(m.ic) ? <GKIcon name={m.ic} size={17}/> : "◆"}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: txt, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d[lang] || d.fr}</div>
                        <div style={{ fontSize: 11.5, color: muted }}>{d.sub[lang] || d.sub.fr}{d.interested ? ` · ${d.interested} ${t("intéressés","interested")}` : ""}</div>
                      </div>
                      <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 20, flexShrink: 0 }}>{money(d.price)}</span>
                    </div>
                  );
                })}
              </div>
              <style>{`@keyframes gkBlink{0%,100%{opacity:1}50%{opacity:.3}}`}</style>
            </div>

            {/* Posts */}
            {FEED_POSTS.map((p, i) => (
              <div key={i} style={{ background: card, border: `1px solid ${p.pinned ? C.flame : cardBd}`, borderRadius: 13, padding: 15 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                  {window.Avatar ? <Avatar name={p.who} size={38} tone={p.tone}/> : <div style={{ width: 38, height: 38, borderRadius: 999, background: C.flame + "55" }}/>}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 600, color: txt }}>{p.who}</span>
                      {p.official && <span style={{ fontSize: 9.5, padding: "1px 7px", borderRadius: 999, background: C.flame, color: "#fff", fontWeight: 700 }}>✓ GUIDKO</span>}
                    </div>
                    <div style={{ fontSize: 11.5, color: muted }}>{p.role[lang] || p.role.fr} · {p.time}</div>
                  </div>
                  <span style={{ fontSize: 11, color: p.tagColor, fontWeight: 600, padding: "3px 8px", borderRadius: 999, border: `1px solid ${p.tagColor}44`, cursor: "pointer" }} onClick={() => go(p.tag.k)}>{p.tag[lang] || p.tag.fr}</span>
                </div>
                <p style={{ fontSize: 13.5, lineHeight: 1.55, color: txt, marginBottom: 11 }}>{p.text[lang] || p.text.fr}</p>
                {p.price && (
                  <div onClick={() => go(p.tag.k)} style={{ display: "flex", alignItems: "center", gap: 11, padding: 10, borderRadius: 10, background: sec, marginBottom: 11, cursor: "pointer" }}>
                    <div style={{ width: 36, height: 36, borderRadius: 9, background: "#A78BFA22", color: "#A78BFA", display: "grid", placeItems: "center" }}>{window.GKIcon && window.hasGKIcon("auto") ? <GKIcon name="auto" size={17}/> : "🚗"}</div>
                    <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600, color: txt }}>{t("Annonce vérifiée · escrow GUIDKO", "Verified listing · GUIDKO escrow")}</div></div>
                    <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 20 }}>{money(p.price)}</span>
                  </div>
                )}
                <div style={{ display: "flex", alignItems: "center", gap: 18, paddingTop: 10, borderTop: `1px solid ${cardBd}`, fontSize: 12.5, color: muted }}>
                  <button onClick={() => setLikes(s => ({ ...s, [i]: !s[i] }))} style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "none", border: "none", color: likes[i] ? C.flame : muted, cursor: "pointer", fontSize: 12.5, fontWeight: 600, fontFamily: "inherit" }}>♥ {p.react + (likes[i] ? 1 : 0)}</button>
                  <span>💬 {p.comments}</span>
                  <span>↗ {t("Partager", "Share")}</span>
                </div>
              </div>
            ))}
          </div>

          {/* Rail droit */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {/* Stats écosystème */}
            <div style={{ background: card, border: `1px solid ${cardBd}`, borderRadius: 13, padding: 15 }}>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.14em", color: muted, marginBottom: 12 }}>{t("AUJOURD'HUI", "TODAY")}</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[[t("TRAJETS", "RIDES"), "2 841", C.signal], [t("ANNONCES", "LISTINGS"), "1 284", "#A78BFA"], [t("MISSIONS", "MISSIONS"), "187", C.flame], [t("CO2 ÉCONOMISÉ", "CO2 SAVED"), "3.2 t", "#0FB76B"]].map(([l, v, c]) => (
                  <div key={l} style={{ padding: "10px 8px", borderRadius: 10, background: sec, textAlign: "center" }}>
                    <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, color: c }}>{v}</div>
                    <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 7.5, color: muted, marginTop: 3, letterSpacing: "0.1em" }}>{l}</div>
                  </div>
                ))}
              </div>
            </div>
            {/* Parrainage */}
            <div style={{ background: card, border: `1px solid ${cardBd}`, borderRadius: 13, padding: 15 }}>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, letterSpacing: "0.14em", color: muted, marginBottom: 10 }}>{t("PARRAINAGE", "REFERRAL")}</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: txt, marginBottom: 5 }}>{t("Parraine, gagne 15 €", "Refer a friend, get €15")}</div>
              <div style={{ fontSize: 12.5, color: muted, lineHeight: 1.5, marginBottom: 12 }}>{t("Ton filleul reçoit 10 €. Sur tous les services.", "Your friend gets €10. Across all services.")}</div>
              <button onClick={() => pub ? navigate("/login") : null} style={{ width: "100%", padding: "9px", borderRadius: 9, border: "none", background: C.flame, color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{t("Mon code de parrainage", "My referral code")}</button>
            </div>
            {/* Connexion si pub */}
            {pub && (
              <div style={{ background: C.flame, borderRadius: 13, padding: 18, color: "#fff", textAlign: "center" }}>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, lineHeight: 1.1, marginBottom: 10 }}>{t("Prêt à entrer ?", "Ready to enter?")}</div>
                <button onClick={() => navigate("/login")} style={{ width: "100%", padding: "10px", borderRadius: 9, border: "none", background: "#fff", color: C.flame, fontSize: 14, fontWeight: 700, cursor: "pointer", fontFamily: "inherit" }}>{t("Se connecter / S'inscrire", "Sign in / Sign up")}</button>
              </div>
            )}
          </div>
        </div>
      </div>
      <style>{`@media(max-width:860px){.discover-layout{grid-template-columns:1fr!important;}}`}</style>
    </div>
  );

  if (pub) {
    return (
      <div style={{ height: "100vh", display: "flex", flexDirection: "column", background: bg, color: txt, fontFamily: "'Geist', sans-serif" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 5vw", borderBottom: `1px solid ${cardBd}`, flexShrink: 0, background: "rgba(11,15,31,0.9)", backdropFilter: "blur(10px)" }}>
          {window.GuidkoLogo ? <GuidkoLogo color="#fff"/> : <span style={{ fontWeight: 800 }}>GUIDKO</span>}
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            {window.LangSelector && <LangSelector dark compact/>}
            <button onClick={() => navigate("/login")} style={{ padding: "8px 16px", borderRadius: 999, border: "none", background: C.flame, color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{t("Se connecter", "Sign in")}</button>
          </div>
        </div>
        {content}
      </div>
    );
  }

  return (
    <>
      <Topbar subtitle={t("DISCOVER", "DISCOVER")} title={t("Bienvenue dans GUIDKO", "Welcome to GUIDKO")} search={false}/>
      {content}
    </>
  );
}

window.DiscoverPage = DiscoverPage;
