/* GUIDKO Wallet — portefeuille unique cross-services.
   Un seul solde par identité : cours, covoiturage, livraisons, marché auto.
   Escrow : fonds bloqués jusqu'à remise du véhicule (Marché Auto). */

const WALLET_DATA = {
  gerant:   { balance: 12480.50, pending: 8900, txs: [
    { d: "Auj.",  label: "Forfait B — Léa Mercier", app: "École", amt: +210 },
    { d: "Auj.",  label: "Vente Peugeot 208 (escrow en cours)", app: "Marché", amt: +8900, escrow: true },
    { d: "Hier",  label: "Loyer simulateur conduite", app: "École", amt: -340 },
    { d: "21/03", label: "Commission GUIDKO (2%)", app: "Marché", amt: -178 },
    { d: "20/03", label: "Location Clio double-cmd × 3j", app: "Marché", amt: +165 },
  ]},
  moniteur: { balance: 3214.80, pending: 0, txs: [
    { d: "Auj.",  label: "Cours B-route — Tom Vasseur", app: "École", amt: +42 },
    { d: "Auj.",  label: "Covoiturage Paris → Créteil × 2 places", app: "Covoit", amt: +16 },
    { d: "Hier",  label: "Livraison Chez Mama (2 missions)", app: "Livraison", amt: +14.70 },
    { d: "21/03", label: "Cours manœuvres — Léa Mercier", app: "École", amt: +42 },
    { d: "20/03", label: "Retrait vers compte bancaire", app: "Wallet", amt: -2800 },
  ]},
  eleve:    { balance: 145.00, pending: 0, txs: [
    { d: "Auj.",  label: "Heure de conduite supplémentaire", app: "École", amt: -48 },
    { d: "Hier",  label: "Covoiturage retour — Marc L.", app: "Covoit", amt: -8 },
    { d: "15/03", label: "Mensualité forfait B (3/10)", app: "École", amt: -210 },
    { d: "12/03", label: "Recharge wallet (CB)", app: "Wallet", amt: +300 },
  ]},
  covoit:   { balance: 486.20, pending: 0, txs: [
    { d: "Auj.",  label: "Trajet Paris → Lyon × 3 places", app: "Covoit", amt: +87 },
    { d: "Hier",  label: "Trajet Paris → Orléans × 2 places", app: "Covoit", amt: +38 },
    { d: "19/03", label: "Livraison colis (mission B2B)", app: "Livraison", amt: +42 },
    { d: "18/03", label: "Retrait vers compte bancaire", app: "Wallet", amt: -350 },
  ]},
  livraison:{ balance: 264.30, pending: 0, txs: [
    { d: "Auj.",  label: "7 livraisons repas", app: "Livraison", amt: +64 },
    { d: "Hier",  label: "Tournée B2B Gennevilliers", app: "Livraison", amt: +94 },
    { d: "20/03", label: "Boost week-end (+15%)", app: "Livraison", amt: +21.30 },
    { d: "19/03", label: "Retrait vers compte bancaire", app: "Wallet", amt: -180 },
  ]},
};

function WalletPage({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const data = WALLET_DATA[role] || WALLET_DATA.eleve;
  const [liveWallet, setLiveWallet] = React.useState(null);
  const [liveTransactions, setLiveTransactions] = React.useState([]);
  const [walletBusy, setWalletBusy] = React.useState(false);
  const [stepup, setStepup] = React.useState(false);
  const hasLiveData = !!liveWallet;
  const pendingAmount = hasLiveData ? 0 : data.pending;
  const currentBalance = hasLiveData ? Number(liveWallet.balance || 0) : data.balance;
  const txList = hasLiveData
    ? liveTransactions.map(tx => ({
        d: tx.createdAt ? new Date(tx.createdAt).toLocaleDateString("fr-FR") : "—",
        label: tx.type === "deposit"
          ? t("Recharge wallet","Wallet top-up")
          : tx.type === "withdrawal"
            ? t("Retrait vers banque","Bank withdrawal")
            : t("Transaction","Transaction"),
        app: "Wallet",
        amt: tx.toUserId ? Number(tx.amount || 0) : -Number(tx.amount || 0),
        escrow: false,
      }))
    : data.txs;
  const money = (v) => (window.GKmoney ? window.GKmoney(v) : v.toLocaleString("fr-FR", { minimumFractionDigits: 2 }) + " €");
  const appColor = { "École": C.sky, "Covoit": C.signal, "Livraison": C.flame, "Marché": "#A78BFA", "Wallet": C.slate };

  React.useEffect(() => {
    let dead = false;
    (async () => {
      if (!(window.GuidkoAPI && window.GuidkoAPI.wallet)) return;
      setWalletBusy(true);
      try {
        const [walletRes, txRes] = await Promise.all([
          window.GuidkoAPI.wallet.get(),
          window.GuidkoAPI.wallet.getTransactions(),
        ]);
        if (dead) return;
        setLiveWallet(walletRes || null);
        setLiveTransactions((txRes && txRes.transactions) || []);
      } catch (e) {
      } finally {
        if (!dead) setWalletBusy(false);
      }
    })();
    return () => { dead = true; };
  }, []);

  return (
    <>
      {typeof StepUp !== "undefined" && <StepUp open={stepup} reason={t("Retrait vers ton compte bancaire","Withdrawal to your bank account")} amount={currentBalance.toLocaleString("fr-FR",{minimumFractionDigits:2}) + " €"} onCancel={() => setStepup(false)} onConfirm={async () => {
        setStepup(false);
        try {
          if (window.GuidkoAPI && window.GuidkoAPI.wallet && typeof window.GuidkoAPI.wallet.withdraw === "function") {
            const amount = currentBalance > 0 ? currentBalance : 0;
            if (amount > 0) {
              const res = await window.GuidkoAPI.wallet.withdraw({ amount });
              if (res && res.wallet) setLiveWallet(res.wallet);
              if (res && res.transaction) setLiveTransactions(ts => [res.transaction, ...ts]);
            }
          }
        } catch (e) {}
        toast.push(t("Virement confirmé — sous 1 jour ouvré.","Withdrawal confirmed — within 1 business day."), "signal");
      }}/>}
      <Topbar subtitle={t("WALLET GUIDKO","GUIDKO WALLET")} title={t("Mon portefeuille","My wallet")} search={false}
        actions={<Button kind="primary" onClick={() => setStepup(true)} disabled={walletBusy || currentBalance <= 0}>{t("Retirer vers ma banque","Withdraw to bank")} →</Button>}/>
      <PageBody>
        <div style={{ marginBottom: 14, display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: C.slate }}>
          💱 {t("Devise active","Active currency")} : <strong style={{ color: C.ink }}>{window.GKcurrency ? window.GKcurrency() : "EUR"}</strong> <span style={{ color: C.slate }}>· {t("suit ta langue — change-la en haut","follows your language — change it top-right")}</span>
        </div>
        {/* Balance hero */}
        <div style={{ display: "grid", gridTemplateColumns: data.pending ? "1.4fr 1fr" : "1fr", gap: 14, marginBottom: 16 }}>
          <Card dark style={{ padding: 28, position: "relative", overflow: "hidden" }}>
            <svg style={{ position: "absolute", right: -30, top: -30, opacity: 0.07 }} width="200" height="200" viewBox="0 0 48 48" fill="none">
              <path d="M4 38 L4 22 A12 12 0 0 1 16 10 L24 10" stroke="#fff" strokeWidth="1.2" fill="none"/>
              <path d="M44 38 L44 22 A12 12 0 0 0 32 10 L24 10" stroke="#fff" strokeWidth="1.2" fill="none"/>
            </svg>
            <Label color="#7A82A8">{t("SOLDE DISPONIBLE","AVAILABLE BALANCE")}</Label>
            <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 60, lineHeight: 1, margin: "10px 0 6px" }}>
              {money(currentBalance)}
            </div>
            <div style={{ fontSize: 13, color: "#9098B5" }}>{t("Un seul solde, converti dans ta devise. Tous tes services GUIDKO.","One balance, in your currency. All your GUIDKO services.")}</div>
          </Card>
          {pendingAmount > 0 && (
            <Card style={{ padding: 24, borderLeft: `3px solid ${C.sky}` }}>
              <Label style={{ marginBottom: 8 }}>🔒 {t("EN ESCROW","IN ESCROW")}</Label>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 36, lineHeight: 1 }}>{money(pendingAmount)}</div>
              <div style={{ fontSize: 12.5, color: C.slate, marginTop: 8, lineHeight: 1.5 }}>{t("Vente Peugeot 208 — les fonds seront libérés à la remise du véhicule, après confirmation de l'acheteur.","Peugeot 208 sale — funds release at vehicle handover, after buyer confirmation.")}</div>
            </Card>
          )}
        </div>

        {/* Transactions */}
        <Card style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "14px 20px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Label>{t("MOUVEMENTS — TOUS SERVICES","ACTIVITY — ALL SERVICES")}</Label>
            <div style={{ display: "flex", gap: 6 }}>
              {Object.entries(appColor).slice(0, 4).map(([k, c]) => <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, color: C.slate }}><span style={{ width: 7, height: 7, borderRadius: 999, background: c }}/>{k}</span>)}
            </div>
          </div>
          {txList.map((tx, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 20px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
              <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.slate, width: 38, flexShrink: 0 }}>{tx.d}</span>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: appColor[tx.app] || C.slate, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{tx.label}</div>
                <div style={{ fontSize: 11, color: C.slate }}>{tx.app}{tx.escrow ? " · 🔒 escrow" : ""}</div>
              </div>
              <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 14, fontWeight: 600, color: tx.amt > 0 ? C.signal : C.ink }}>{tx.amt > 0 ? "+" : "−"}{money(Math.abs(tx.amt))}</span>
            </div>
          ))}
        </Card>

        <div style={{ marginTop: 14, padding: 14, background: "#FFF1EB", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, lineHeight: 1.5 }}>
          ✦ {t("Tes gains covoiturage, livraison et cours arrivent au même endroit. L'escrow Marché Auto protège acheteur et vendeur jusqu'à la remise.","Your carpool, delivery and lesson earnings land in one place. Auto Market escrow protects buyer and seller until handover.")}
        </div>
      </PageBody>
    </>
  );
}

window.WalletPage = WalletPage;
