/* GUIDKO Messagerie unifiée — un seul fil par relation, tous services.
   Acheteur↔vendeur (Marché), passager↔conducteur (Covoit), client↔livreur (Livraison),
   élève↔moniteur (École). Modérable par l'Admin. Role-aware. */

const MSG_THREADS = {
  gerant: [
    { id: "t1", who: "Léa Mercier", ctx: "École · Forfait B", g: "★", color: "#FF5A1F", unread: 2, last: "Merci, je confirme le créneau de jeudi !", time: "10:24", msgs: [
      { me: false, txt: "Bonjour, est-ce qu'il reste de la place jeudi après-midi ?", t: "09:58" },
      { me: true,  txt: "Oui, 14h ou 16h avec Marc. Je vous réserve lequel ?", t: "10:05" },
      { me: false, txt: "16h c'est parfait.", t: "10:20" },
      { me: false, txt: "Merci, je confirme le créneau de jeudi !", t: "10:24" },
    ]},
    { id: "t2", who: "AutoPlus 93", ctx: "Marché · Clio IV double-cmd", g: "⇄", color: "#A78BFA", unread: 0, last: "Le véhicule est dispo à la location dès lundi.", time: "Hier", msgs: [
      { me: true, txt: "Bonjour, la Clio double-commande est toujours disponible à la location ?", t: "Hier 16:01" },
      { me: false, txt: "Le véhicule est dispo à la location dès lundi.", t: "Hier 16:40" },
    ]},
    { id: "t3", who: "Marc Lefèvre", ctx: "Équipe · Moniteur", g: "♛", color: "#0B0F1F", unread: 0, last: "Planning de la semaine validé 👍", time: "Lun", msgs: [
      { me: false, txt: "Planning de la semaine validé 👍", t: "Lun 08:30" },
    ]},
    { id: "t4", who: "Rafael Souza", ctx: "Équipe · Brésil 🇧🇷", g: "🌍", color: "#0FB76B", unread: 2, last: "Bom dia! A agenda de São Paulo está cheia esta semana.", time: "08:12", team: true, msgs: [
      { me: false, lang: "pt", orig: "Bom dia chefe! Como vão as inscrições em Paris?", tr: { fr: "Bonjour patron ! Comment vont les inscriptions à Paris ?", en: "Good morning boss! How are the Paris enrollments going?" }, t: "08:05" },
      { me: true, txt: "Très bien Rafael, +12 cette semaine. Et São Paulo ?", t: "08:08" },
      { me: false, lang: "pt", orig: "Bom dia! A agenda de São Paulo está cheia esta semana. Precisamos de mais dois instrutores.", tr: { fr: "Bonjour ! L'agenda de São Paulo est plein cette semaine. Il nous faut deux moniteurs de plus.", en: "Morning! The São Paulo schedule is full this week. We need two more instructors." }, t: "08:12" },
    ]},
  ],
  moniteur: [
    { id: "t1", who: "Léa Mercier", ctx: "École · Élève B", g: "★", color: "#FF5A1F", unread: 1, last: "À jeudi 16h alors, merci Marc !", time: "10:25", msgs: [
      { me: false, txt: "Bonjour Marc, on travaille les créneaux jeudi ?", t: "10:10" },
      { me: true,  txt: "Oui, on attaque les créneaux et la marche arrière. À 16h.", t: "10:18" },
      { me: false, txt: "À jeudi 16h alors, merci Marc !", t: "10:25" },
    ]},
    { id: "t2", who: "Tom Vasseur", ctx: "Covoit · Paris → Créteil", g: "⇅", color: "#0FB76B", unread: 0, last: "Je vous attends devant la gare à 18h.", time: "Hier", msgs: [
      { me: false, txt: "Bonjour, vous partez bien vers Créteil ce soir ?", t: "Hier 17:20" },
      { me: true,  txt: "Oui ! Je vous attends devant la gare à 18h.", t: "Hier 17:25" },
    ]},
  ],
  eleve: [
    { id: "t1", who: "Marc Lefèvre", ctx: "École · Mon moniteur", g: "♛", color: "#0B0F1F", unread: 1, last: "On attaque les créneaux et la marche arrière. À 16h.", time: "10:18", msgs: [
      { me: true,  txt: "Bonjour Marc, on travaille les créneaux jeudi ?", t: "10:10" },
      { me: false, txt: "Oui, on attaque les créneaux et la marche arrière. À 16h.", t: "10:18" },
    ]},
    { id: "t2", who: "Auto-École Lubasa", ctx: "Accueil · Inscription", g: "◎", color: "#3B6FF8", unread: 0, last: "Votre dossier est complet, bienvenue !", time: "12/03", msgs: [
      { me: false, txt: "Votre dossier est complet, bienvenue !", t: "12/03" },
    ]},
  ],
  covoit: [
    { id: "t1", who: "Sophie Berger", ctx: "Covoit · Passagère Lyon", g: "⇅", color: "#0FB76B", unread: 3, last: "Super, je réserve 1 place. À demain 7h !", time: "18:42", msgs: [
      { me: false, txt: "Bonjour, il reste des places pour Lyon demain ?", t: "18:30" },
      { me: true,  txt: "Oui, 2 places à 29€. Départ 7h porte d'Italie.", t: "18:35" },
      { me: false, txt: "Parfait pour moi.", t: "18:40" },
      { me: false, txt: "Super, je réserve 1 place. À demain 7h !", t: "18:42" },
    ]},
    { id: "t2", who: "PiècesAuto94", ctx: "Marché · Plaquettes", g: "⇄", color: "#A78BFA", unread: 0, last: "En stock, je vous les mets de côté.", time: "Hier", msgs: [
      { me: false, txt: "En stock, je vous les mets de côté.", t: "Hier" },
    ]},
  ],
  livraison: [
    { id: "t1", who: "Chez Mama", ctx: "Livraison · Restaurant", g: "📦", color: "#FF5A1F", unread: 1, last: "Commande prête, tu peux passer 👍", time: "12:14", msgs: [
      { me: false, txt: "Salut, la commande #2841 est bientôt prête ?", t: "12:08" },
      { me: true,  txt: "J'arrive dans 4 min.", t: "12:10" },
      { me: false, txt: "Commande prête, tu peux passer 👍", t: "12:14" },
    ]},
    { id: "t2", who: "Lucas (client)", ctx: "Livraison · Commande #2841", g: "🛍️", color: "#3B6FF8", unread: 0, last: "Merci, c'était rapide !", time: "12:31", msgs: [
      { me: false, txt: "Bonjour, vous êtes loin ?", t: "12:25" },
      { me: true,  txt: "Je suis en bas dans 2 min, code 1234A.", t: "12:28" },
      { me: false, txt: "Merci, c'était rapide !", t: "12:31" },
    ]},
  ],
};

function MessagingPage({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const vp = (window.useViewport ? window.useViewport() : "desktop");
  const mobile = vp === "mobile";
  const threads = MSG_THREADS[role] || MSG_THREADS.eleve;
  const [activeId, setActiveId] = React.useState(mobile ? null : threads[0]?.id);
  const [drafts, setDrafts] = React.useState({});
  const [sent, setSent] = React.useState({});
  const [transOn, setTransOn] = React.useState(true);
  const active = threads.find(x => x.id === activeId);
  const langName = (code) => (window.GKlocale ? window.GKlocale(code).native : code);

  // Rendu d'un message (gère la traduction instantanée des messages en langue étrangère)
  function renderBody(m) {
    if (m.lang && m.tr) {
      if (m.lang === lang) return m.orig; // même langue → pas de traduction
      const display = transOn ? (m.tr[lang] || m.tr.en || m.orig) : m.orig;
      return (
        <>
          <div>{display}</div>
          {transOn && (
            <div style={{ fontSize: 10.5, marginTop: 6, opacity: 0.7, display: "flex", alignItems: "center", gap: 5, fontStyle: "italic" }}>
              <span>🌐</span> {t("Traduit du", "Translated from")} {langName(m.lang)}
            </div>
          )}
        </>
      );
    }
    return m.txt;
  }

  const allMsgs = (th) => [...th.msgs, ...((sent[th.id] || []).map(txt => ({ me: true, txt, t: t("À l'instant", "Just now") })))];

  function send() {
    if (!active || !(drafts[active.id] || "").trim()) return;
    setSent(s => ({ ...s, [active.id]: [...(s[active.id] || []), drafts[active.id].trim()] }));
    setDrafts(d => ({ ...d, [active.id]: "" }));
  }

  const ThreadList = (
    <div style={{ width: mobile ? "100%" : 320, borderRight: mobile ? "none" : `1px solid ${C.softLine}`, display: "flex", flexDirection: "column", flexShrink: 0, background: "#fff", overflow: "hidden" }}>
      <div style={{ padding: "14px 18px", borderBottom: `1px solid ${C.softLine}` }}>
        <Label>{t("CONVERSATIONS — TOUS SERVICES", "CONVERSATIONS — ALL SERVICES")}</Label>
      </div>
      <div className="gk-scroll" style={{ overflowY: "auto", flex: 1 }}>
        {threads.map(th => {
          const on = th.id === activeId;
          return (
            <div key={th.id} onClick={() => setActiveId(th.id)} style={{ display: "flex", gap: 12, padding: "13px 18px", cursor: "pointer", borderBottom: `1px solid ${C.softLine}`, background: on ? C.cream : "transparent", alignItems: "center" }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: th.color === "#0B0F1F" ? C.ink : th.color + "22", color: th.color === "#0B0F1F" ? C.flame : th.color, display: "grid", placeItems: "center", fontSize: 17, flexShrink: 0 }}>{th.g}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontSize: 14, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{th.who}</span>
                  <span style={{ fontSize: 11, color: C.slate, flexShrink: 0, marginLeft: 6 }}>{th.time}</span>
                </div>
                <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, color: th.color === "#0B0F1F" ? C.slate : th.color, letterSpacing: "0.04em", margin: "2px 0 3px" }}>{th.ctx}</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 12.5, color: C.slate, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{th.last}</span>
                  {th.unread > 0 && !sent[th.id] && <span style={{ background: C.flame, color: "#fff", fontSize: 10, fontWeight: 700, minWidth: 18, height: 18, borderRadius: 999, display: "grid", placeItems: "center", padding: "0 5px", flexShrink: 0 }}>{th.unread}</span>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );

  const Conversation = active ? (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", background: C.paper }}>
      <div style={{ padding: "12px 20px", borderBottom: `1px solid ${C.softLine}`, display: "flex", alignItems: "center", gap: 12, background: "#fff", flexShrink: 0 }}>
        {mobile && <button onClick={() => setActiveId(null)} style={{ background: "none", border: "none", fontSize: 18, color: C.slate }}>←</button>}
        <div style={{ width: 38, height: 38, borderRadius: 10, background: active.color === "#0B0F1F" ? C.ink : active.color + "22", color: active.color === "#0B0F1F" ? C.flame : active.color, display: "grid", placeItems: "center", fontSize: 16 }}>{active.g}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600 }}>{active.who}</div>
          <div style={{ fontSize: 11.5, color: C.slate }}>{active.ctx}</div>
        </div>
        {active.team && (
          <div onClick={() => setTransOn(o => !o)} title={t("Traduction instantanée", "Instant translation")} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 11px", borderRadius: 999, cursor: "pointer", background: transOn ? "#EAF7F0" : "#fff", border: `1px solid ${transOn ? C.signal : C.softLine}`, fontSize: 11.5, fontWeight: 600, color: transOn ? "#0a7d4a" : C.slate }}>
            🌐 {t("Traduction", "Translation")} {transOn ? "ON" : "OFF"}
          </div>
        )}
        <span title={t("Conversation protégée GUIDKO", "GUIDKO-protected conversation")} style={{ fontSize: 11, color: C.signal, display: "inline-flex", alignItems: "center", gap: 5 }}>🔒 {t("Protégé", "Protected")}</span>
      </div>
      <div className="gk-scroll" style={{ flex: 1, overflowY: "auto", padding: 22, display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{ textAlign: "center", fontSize: 11, color: C.slate, padding: "4px 0 8px" }}>{t("Restez sur GUIDKO : paiement, litiges et avis sont protégés.", "Stay on GUIDKO: payment, disputes and reviews are protected.")}</div>
        {active.team && (
          <div style={{ textAlign: "center", fontSize: 11, color: "#0a7d4a", padding: "2px 0", display: "flex", justifyContent: "center", alignItems: "center", gap: 6 }}>🌍 {t("Équipe internationale — chacun écrit dans sa langue, Lia traduit en temps réel.", "International team — everyone writes in their language, Lia translates in real time.")}</div>
        )}
        {allMsgs(active).map((m, i) => (
          <div key={i} style={{ alignSelf: m.me ? "flex-end" : "flex-start", maxWidth: "72%" }}>
            <div style={{ padding: "10px 14px", borderRadius: m.me ? "14px 14px 4px 14px" : "14px 14px 14px 4px", background: m.me ? C.ink : "#fff", color: m.me ? "#fff" : C.ink, fontSize: 14, lineHeight: 1.45, border: m.me ? "none" : `1px solid ${C.softLine}` }}>{renderBody(m)}</div>
            <div style={{ fontSize: 10, color: C.slate, marginTop: 4, textAlign: m.me ? "right" : "left" }}>{m.t}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: 14, borderTop: `1px solid ${C.softLine}`, display: "flex", gap: 10, background: "#fff", flexShrink: 0 }}>
        <input value={drafts[active.id] || ""} onChange={e => setDrafts(d => ({ ...d, [active.id]: e.target.value }))} onKeyDown={e => e.key === "Enter" && send()} placeholder={t("Écrire un message…", "Write a message…")} style={{ flex: 1, padding: "12px 16px", borderRadius: 10, border: `1px solid ${C.softLine}`, fontSize: 14, fontFamily: "inherit", outline: "none" }}/>
        <Button kind="primary" onClick={send}>{t("Envoyer", "Send")}</Button>
      </div>
    </div>
  ) : (
    <div style={{ flex: 1, display: "grid", placeItems: "center", color: C.slate, background: C.paper }}>
      <div style={{ textAlign: "center" }}><div style={{ fontSize: 40, marginBottom: 10 }}>✉</div>{t("Choisis une conversation", "Pick a conversation")}</div>
    </div>
  );

  return (
    <>
      <Topbar subtitle={t("MESSAGERIE", "MESSAGING")} title={t("Messages", "Messages")} search={false}/>
      <div style={{ flex: 1, display: "flex", overflow: "hidden" }}>
        {mobile ? (active ? Conversation : ThreadList) : (<>{ThreadList}{Conversation}</>)}
      </div>
    </>
  );
}

window.MessagingPage = MessagingPage;
