/* GUIDKO Confiance — KYC unique (vérifié une fois, valable partout) + avis croisés.
   Le statut de vérification suit l'identité dans tous les services.
   Persisté en localStorage (guidko_kyc). Role-aware. */

const KYC_STEPS = [
  { k: "identity", fr: "Identité", en: "Identity", g: "🪪", desc: { fr: "Pièce d'identité ou passeport.", en: "ID card or passport." } },
  { k: "licence",  fr: "Permis de conduire", en: "Driving licence", g: "🚗", desc: { fr: "Permis valide selon ton/tes véhicules.", en: "Valid licence for your vehicle(s)." } },
  { k: "insurance",fr: "Assurance", en: "Insurance", g: "🛡", desc: { fr: "Attestation d'assurance à jour.", en: "Up-to-date insurance certificate." } },
  { k: "address",  fr: "Justificatif de domicile", en: "Proof of address", g: "🏠", desc: { fr: "Facture de moins de 3 mois.", en: "Bill less than 3 months old." } },
];

function loadKyc() { try { return JSON.parse(localStorage.getItem("guidko_kyc") || "{}"); } catch (e) { return {}; } }
function saveKyc(s) { try { localStorage.setItem("guidko_kyc", JSON.stringify(s)); } catch (e) {} }

const REVIEWS_RECEIVED = [
  { from: "Léa Mercier", ctx: "École · Élève", stars: 5, txt: "Moniteur très pédagogue, je me suis sentie en confiance dès le premier cours.", g: "★", color: "#FF5A1F" },
  { from: "Sophie Berger", ctx: "Covoit · Passagère", stars: 5, txt: "Trajet ponctuel et agréable, conduite très sûre. Je recommande !", g: "⇅", color: "#0FB76B" },
  { from: "Chez Mama", ctx: "Livraison · Restaurant", stars: 4, txt: "Livreur rapide et soigneux. Toujours à l'heure.", g: "📦", color: "#FF5A1F" },
  { from: "AutoPlus 93", ctx: "Marché · Vendeur", stars: 5, txt: "Acheteur sérieux, transaction fluide via l'escrow GUIDKO.", g: "⇄", color: "#A78BFA" },
];

function TrustPage({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const toast = useToast();
  const [state, setState] = React.useState(loadKyc());

  const done = (k) => !!state[k];
  const doneCount = KYC_STEPS.filter(s => done(s.k)).length;
  const pct = Math.round((doneCount / KYC_STEPS.length) * 100);
  const verified = doneCount === KYC_STEPS.length;

  function verify(k) {
    const next = { ...state, [k]: true };
    setState(next); saveKyc(next);
    toast.push(t("Document vérifié par Lia ✓", "Document verified by Lia ✓"), "signal");
  }
  function reset() { setState({}); saveKyc({}); toast.push(t("Vérification réinitialisée", "Verification reset")); }

  const avg = (REVIEWS_RECEIVED.reduce((s, r) => s + r.stars, 0) / REVIEWS_RECEIVED.length).toFixed(1);

  return (
    <>
      <Topbar subtitle={t("CONFIANCE & SÉCURITÉ", "TRUST & SAFETY")} title={t("Mon identité vérifiée", "My verified identity")} search={false}
        actions={<Button kind="ghost" size="sm" onClick={reset}>{t("Réinitialiser", "Reset")}</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 14, marginBottom: 16 }}>
          {/* Badge */}
          <Card dark style={{ padding: 28, position: "relative", overflow: "hidden" }}>
            <Label color="#7A82A8">{t("STATUT GUIDKO", "GUIDKO STATUS")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 16, margin: "16px 0 10px" }}>
              <div style={{ width: 66, height: 66, borderRadius: 18, background: verified ? C.signal : "#1F2542", display: "grid", placeItems: "center", fontSize: 30, flexShrink: 0 }}>{verified ? "✓" : "◐"}</div>
              <div>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 34, lineHeight: 1 }}>{verified ? t("Vérifié", "Verified") : t("En cours", "In progress")}</div>
                <div style={{ fontSize: 13, color: "#9098B5", marginTop: 4 }}>{doneCount}/{KYC_STEPS.length} {t("documents validés", "documents validated")}</div>
              </div>
            </div>
            <div style={{ height: 8, borderRadius: 4, background: "#1F2542", overflow: "hidden", marginTop: 10 }}>
              <div style={{ height: "100%", width: pct + "%", background: verified ? C.signal : C.flame, borderRadius: 4, transition: "width .4s" }}/>
            </div>
            <div style={{ marginTop: 16, padding: 13, background: "#1F2542", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, color: "#C9CEE3", lineHeight: 1.5 }}>
              ✦ {t("Vérifie une seule fois. Ton badge te suit dans l'école, le covoiturage, la livraison et le marché auto.", "Verify once. Your badge follows you across school, carpool, delivery and the auto market.")}
            </div>
          </Card>

          {/* Rating */}
          <Card style={{ padding: 28 }}>
            <Label style={{ marginBottom: 14 }}>{t("RÉPUTATION CROISÉE", "CROSS REPUTATION")}</Label>
            <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 60, lineHeight: 1 }}>{avg}</div>
              <div>
                <div style={{ color: C.flame, fontSize: 18, letterSpacing: 2 }}>{"★".repeat(Math.round(avg))}<span style={{ color: C.softLine }}>{"★".repeat(5 - Math.round(avg))}</span></div>
                <div style={{ fontSize: 13, color: C.slate, marginTop: 4 }}>{REVIEWS_RECEIVED.length} {t("avis · tous services", "reviews · all services")}</div>
              </div>
            </div>
            <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 7 }}>
              {[["École", 5, "#FF5A1F"], ["Covoiturage", 5, "#0FB76B"], ["Livraison", 4, "#3B6FF8"], ["Marché Auto", 5, "#A78BFA"]].map(([n, s, c]) => (
                <div key={n} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12.5 }}>
                  <span style={{ width: 90, color: C.slate }}>{n}</span>
                  <div style={{ flex: 1, height: 6, borderRadius: 3, background: C.cream, overflow: "hidden" }}><div style={{ height: "100%", width: (s / 5 * 100) + "%", background: c, borderRadius: 3 }}/></div>
                  <span className="mono" style={{ width: 28, textAlign: "right" }}>{s}.0</span>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* KYC checklist */}
        <Card style={{ padding: 0, overflow: "hidden", marginBottom: 16 }}>
          <div style={{ padding: "15px 20px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Label>{t("VÉRIFICATION KYC — UNE FOIS POUR TOUTES", "KYC VERIFICATION — ONCE FOR ALL")}</Label>
            {verified && <Pill tone="signal">{t("Complet ✓", "Complete ✓")}</Pill>}
          </div>
          {KYC_STEPS.map((s, i) => (
            <div key={s.k} style={{ display: "flex", gap: 14, padding: "15px 20px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}`, alignItems: "center" }}>
              <div style={{ width: 42, height: 42, borderRadius: 11, background: done(s.k) ? "#EAF7F0" : C.cream, display: "grid", placeItems: "center", fontSize: 19, flexShrink: 0 }}>{done(s.k) ? "✓" : s.g}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{s[lang] || s.fr}</div>
                <div style={{ fontSize: 12.5, color: C.slate, marginTop: 2 }}>{s.desc[lang] || s.desc.fr}</div>
              </div>
              {done(s.k)
                ? <Pill tone="signal">{t("Vérifié", "Verified")}</Pill>
                : <Button size="sm" kind="primary" onClick={() => verify(s.k)}>{t("Téléverser", "Upload")}</Button>}
            </div>
          ))}
        </Card>

        {/* Reviews */}
        <Label style={{ marginBottom: 12 }}>{t("AVIS REÇUS — TOUS SERVICES CONFONDUS", "REVIEWS RECEIVED — ACROSS ALL SERVICES")}</Label>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {REVIEWS_RECEIVED.map((r, i) => (
            <Card key={i} style={{ padding: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 10 }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: r.color + "22", color: r.color, display: "grid", placeItems: "center", fontSize: 15 }}>{r.g}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{r.from}</div>
                  <div style={{ fontSize: 11, color: C.slate }}>{r.ctx}</div>
                </div>
                <span style={{ color: C.flame, fontSize: 13 }}>{"★".repeat(r.stars)}<span style={{ color: C.softLine }}>{"★".repeat(5 - r.stars)}</span></span>
              </div>
              <p style={{ fontSize: 13, color: C.ink, lineHeight: 1.5 }}>{r.txt}</p>
            </Card>
          ))}
        </div>

        <div style={{ marginTop: 16, padding: 14, background: "#FFF1EB", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, lineHeight: 1.5 }}>
          🛡 {t("Chaque trajet, cours et livraison est couvert par l'assurance GUIDKO une fois ton identité vérifiée. Les avis sont croisés : tu notes, tu es noté.", "Every ride, lesson and delivery is covered by GUIDKO insurance once your identity is verified. Reviews are mutual: you rate, you're rated.")}
        </div>
      </PageBody>
    </>
  );
}

window.TrustPage = TrustPage;
