/* GUIDKO Monde — Région & conformité (légal par pays) + Parrainage/fidélité.
   RegionPage : règles permis, taxes, devise, conformité par pays.
   ReferralPage : parrainage multi-services + paliers de fidélité. */

const COUNTRY_RULES = [
  { k: "fr", flag: "🇫🇷", name: "France", cur: "EUR", drive: "Droite", age: "17 ans (conduite acc.)", licences: "AM·A1·A2·A·B·BE·C·D", vat: "20%", notes: { fr: "Permis à points (12). Visite médicale poids lourd. RGPD strict.", en: "Points licence (12). Medical for trucks. Strict GDPR." } },
  { k: "br", flag: "🇧🇷", name: "Brasil", cur: "BRL", drive: "Direita", age: "18 anos", licences: "A·B·C·D·E", vat: "ICMS ~17%", notes: { fr: "CNH obligatoire. Examen théorique + pratique. Auto-écoles agréées DETRAN.", en: "CNH required. Theory + practical. DETRAN-licensed schools." } },
  { k: "ma", flag: "🇲🇦", name: "المغرب · Maroc", cur: "MAD", drive: "Droite", age: "18 ans", licences: "AM·A1·A·B·C·D·EC", vat: "20%", notes: { fr: "Permis à points (30). Examens NARSA. Bilingue AR/FR.", en: "Points licence (30). NARSA exams. Bilingual AR/FR." } },
  { k: "gb", flag: "🇬🇧", name: "United Kingdom", cur: "GBP", drive: "Left", age: "17", licences: "AM·A1·A2·A·B·C·D", vat: "20%", notes: { fr: "Conduite à gauche. Theory + hazard perception + practical. DVLA.", en: "Drives on left. Theory + hazard perception + practical. DVLA." } },
  { k: "de", flag: "🇩🇪", name: "Deutschland", cur: "EUR", drive: "Rechts", age: "17 (begleitet)", licences: "AM·A1·A2·A·B·C·D", vat: "19%", notes: { fr: "Formation premiers secours obligatoire. Führerschein. TÜV.", en: "Mandatory first-aid course. Führerschein. TÜV inspection." } },
  { k: "tr", flag: "🇹🇷", name: "Türkiye", cur: "TRY", drive: "Sağ", age: "18", licences: "M·A1·A2·A·B·C·D", vat: "KDV 20%", notes: { fr: "MEB sürücü kursu. Examen écrit + pratique.", en: "MEB driving course. Written + practical exam." } },
];

function RegionPage({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const curLoc = window.GKlocale ? window.GKlocale(window.__guidkoLang || "fr") : { cur: "EUR" };
  const [sel, setSel] = React.useState(COUNTRY_RULES.find(c => c.cur === curLoc.cur)?.k || "fr");
  const c = COUNTRY_RULES.find(x => x.k === sel) || COUNTRY_RULES[0];
  const money = (v) => window.GKmoney ? window.GKmoney(v, { cur: c.cur }) : v + " €";

  return (
    <>
      <Topbar subtitle={t("MONDE · CONFORMITÉ","WORLD · COMPLIANCE")} title={t("Région & conformité","Region & compliance")} search={false}/>
      <PageBody>
        <p style={{ fontSize: 14, color: C.slate, maxWidth: 680, lineHeight: 1.55, margin: "0 0 18px" }}>
          {t("GUIDKO s'adapte au pays : langue, devise, permis, taxes et règles locales. Tes opérateurs à l'étranger travaillent dans leur cadre légal — automatiquement.","GUIDKO adapts to each country: language, currency, licences, taxes and local rules. Your operators abroad work within their legal frame — automatically.")}
        </p>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 18 }}>
          {COUNTRY_RULES.map(x => {
            const on = x.k === sel;
            return <span key={x.k} onClick={() => setSel(x.k)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 14px", borderRadius: 999, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}`, fontSize: 13, fontWeight: on ? 600 : 500 }}>{x.flag} {x.name}</span>;
          })}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14 }}>
          <Card style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "20px 24px", borderBottom: `1px solid ${C.softLine}`, display: "flex", alignItems: "center", gap: 14 }}>
              <span style={{ fontSize: 34 }}>{c.flag}</span>
              <div><div style={{ fontSize: 20, fontWeight: 700 }}>{c.name}</div><div style={{ fontSize: 12.5, color: C.slate }}>{t("Cadre réglementaire local","Local regulatory frame")}</div></div>
            </div>
            {[
              [t("Devise","Currency"), `${c.cur} · ${money(100)} ${t("pour 100 €","for €100")}`],
              [t("Sens de conduite","Driving side"), c.drive],
              [t("Âge minimum","Minimum age"), c.age],
              [t("Permis proposés","Licences offered"), c.licences],
              [t("TVA / taxe","VAT / tax"), c.vat],
            ].map(([k, v], i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "13px 24px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}`, fontSize: 13.5 }}>
                <span style={{ color: C.slate }}>{k}</span>
                <span style={{ fontWeight: 600, textAlign: "right" }}>{v}</span>
              </div>
            ))}
          </Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <Card dark style={{ padding: 22 }}>
              <Label color="#7A82A8" style={{ marginBottom: 10 }}>{t("RÈGLES LOCALES","LOCAL RULES")}</Label>
              <p style={{ fontSize: 14, lineHeight: 1.6, color: "#E6E9F5" }}>{c.notes[lang] || c.notes.fr}</p>
            </Card>
            <Card style={{ padding: 18, background: "#FBF8EE", display: "flex", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 20 }}>✦</span>
              <div style={{ flex: 1, fontSize: 12.5, color: C.slate, lineHeight: 1.45 }}>{t("Lia met à jour les règles à chaque évolution légale et alerte tes équipes locales.","Lia updates rules on every legal change and alerts your local teams.")}</div>
            </Card>
            <Card style={{ padding: 18, display: "flex", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 20 }}>🔏</span>
              <div style={{ flex: 1, fontSize: 12.5, color: C.slate, lineHeight: 1.45 }}>{t("Contrats générés conformes au droit du pays sélectionné.","Contracts generated compliant with the selected country's law.")}</div>
            </Card>
          </div>
        </div>
      </PageBody>
    </>
  );
}

// ============ PARRAINAGE & FIDÉLITÉ ============
const LOYALTY_TIERS = [
  { k: "bronze", fr: "Bronze", en: "Bronze", g: "🥉", min: 0, perk: { fr: "5% de réduction services", en: "5% off services" }, color: "#C08552" },
  { k: "silver", fr: "Argent", en: "Silver", g: "🥈", min: 3, perk: { fr: "Commission covoit −2%, missions prioritaires", en: "−2% carpool fee, priority missions" }, color: "#9CA3AF" },
  { k: "gold",   fr: "Or",     en: "Gold",   g: "🥇", min: 8, perk: { fr: "GUIDAROUTE offert, support prioritaire", en: "Free GUIDAROUTE, priority support" }, color: "#E0A106" },
  { k: "platine",fr: "Platine",en: "Platinum",g: "💎", min: 20, perk: { fr: "0% commission 1 mois, assurance premium", en: "0% fee for 1 month, premium insurance" }, color: "#5EC2D6" },
];

function ReferralPage({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const toast = useToast();
  const [invited, setInvited] = React.useState(5);
  const code = "GUIDKO-" + (role || "X").slice(0, 3).toUpperCase() + "-2026";
  const tierIdx = LOYALTY_TIERS.reduce((acc, tr, i) => invited >= tr.min ? i : acc, 0);
  const tier = LOYALTY_TIERS[tierIdx];
  const next = LOYALTY_TIERS[tierIdx + 1];
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";

  return (
    <>
      <Topbar subtitle={t("PARRAINAGE & FIDÉLITÉ","REFERRAL & LOYALTY")} title={t("Invite, gagne, monte en grade","Invite, earn, level up")} search={false}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
          {/* Referral */}
          <Card dark style={{ padding: 26 }}>
            <Label color="#7A82A8">{t("TON CODE DE PARRAINAGE","YOUR REFERRAL CODE")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "12px 0 14px" }}>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 22, fontWeight: 600, letterSpacing: "0.04em", flex: 1 }}>{code}</div>
              <Button kind="flame" size="sm" onClick={() => toast.push(t("Code copié !","Code copied!"), "signal")}>{t("Copier","Copy")}</Button>
            </div>
            <p style={{ fontSize: 13, color: "#9098B5", lineHeight: 1.5 }}>{t("Chaque filleul actif te rapporte","Each active referral earns you")} <strong style={{ color: "#fff" }}>{money(15)}</strong> {t("et lui offre","and gives them")} <strong style={{ color: "#fff" }}>{money(10)}</strong>. {t("Valable sur tous les services.","Valid across all services.")}</p>
            <div style={{ display: "flex", gap: 16, marginTop: 18 }}>
              <div><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32 }}>{invited}</div><Label color="#7A82A8" style={{ fontSize: 8 }}>{t("FILLEULS","REFERRALS")}</Label></div>
              <div><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32 }}>{money(invited * 15)}</div><Label color="#7A82A8" style={{ fontSize: 8 }}>{t("GAGNÉS","EARNED")}</Label></div>
            </div>
            <Button kind="light" full style={{ marginTop: 18 }} onClick={() => { setInvited(n => n + 1); toast.push(t("Invitation envoyée !","Invite sent!"), "signal"); }}>+ {t("Inviter un ami","Invite a friend")}</Button>
          </Card>

          {/* Current tier */}
          <Card style={{ padding: 26 }}>
            <Label style={{ marginBottom: 10 }}>{t("TON NIVEAU FIDÉLITÉ","YOUR LOYALTY TIER")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
              <div style={{ width: 58, height: 58, borderRadius: 16, background: tier.color + "22", display: "grid", placeItems: "center", fontSize: 28 }}>{tier.g}</div>
              <div><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, lineHeight: 1 }}>{tier[lang] || tier.fr}</div><div style={{ fontSize: 12.5, color: C.slate, marginTop: 3 }}>{tier.perk[lang] || tier.perk.fr}</div></div>
            </div>
            {next ? (
              <>
                <div style={{ height: 8, borderRadius: 4, background: C.cream, overflow: "hidden" }}><div style={{ height: "100%", width: `${Math.min((invited - tier.min) / (next.min - tier.min) * 100, 100)}%`, background: tier.color, borderRadius: 4 }}/></div>
                <div style={{ fontSize: 12.5, color: C.slate, marginTop: 8 }}>{next.min - invited > 0 ? `${next.min - invited} ${t("filleuls pour","more for")} ${next[lang] || next.fr} ${next.g}` : t("Niveau suivant débloqué !","Next tier unlocked!")}</div>
              </>
            ) : <Pill tone="signal">{t("Niveau maximum atteint 💎","Top tier reached 💎")}</Pill>}
          </Card>
        </div>

        {/* Tiers */}
        <Label style={{ marginBottom: 12 }}>{t("PALIERS DE FIDÉLITÉ — TOUS SERVICES","LOYALTY TIERS — ALL SERVICES")}</Label>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
          {LOYALTY_TIERS.map((tr, i) => (
            <Card key={tr.k} style={{ padding: 18, border: i === tierIdx ? `2px solid ${tr.color}` : `1px solid ${C.softLine}` }}>
              <div style={{ fontSize: 26, marginBottom: 8 }}>{tr.g}</div>
              <div style={{ fontSize: 15, fontWeight: 700 }}>{tr[lang] || tr.fr}</div>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10.5, color: C.slate, margin: "4px 0 10px" }}>{tr.min}+ {t("filleuls","referrals")}</div>
              <div style={{ fontSize: 12.5, color: C.ink, lineHeight: 1.45 }}>{tr.perk[lang] || tr.perk.fr}</div>
              {i === tierIdx && <div style={{ marginTop: 10 }}><Pill tone="signal">{t("Actuel","Current")}</Pill></div>}
            </Card>
          ))}
        </div>
      </PageBody>
    </>
  );
}

window.RegionPage = RegionPage;
window.ReferralPage = ReferralPage;
