// Nouveau virement — miroir mobile du parcours web (CompteProView) :
// 1 bénéficiaire → 2 montant & exécution → 3 récapitulatif → 4 confirmation
// forte (OTP, façon DSP2) → en file. Mêmes données (ui_kits/shared/virements.js),
// mêmes règles (plafond, solde, frais instantané). Rien n'est émis (démo).
// window.OryzeApp.VirementScreen
(function () {
  const { Amount, Button, StatusBadge, Avatar, Input, SegmentedControl, OtpInput, StatusTimeline, IconButton, Tag } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;

  const lbl = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };
  const errS = { fontSize: 12.5, color: "var(--fin-negative)", fontWeight: 600 };
  const sunken = { display: "flex", flexDirection: "column", gap: 7, padding: "12px 13px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" };

  function VirementScreen({ go }) {
    const V = window.OryzeVirements;
    const [step, setStep] = React.useState(1); // 1..4 | 5 = en file
    const [mode, setMode] = React.useState("saved");
    const [benef, setBenef] = React.useState(V.beneficiaires[0].value);
    const [newName, setNewName] = React.useState("");
    const [newIban, setNewIban] = React.useState("");
    const [amount, setAmount] = React.useState("250");
    const [label, setLabel] = React.useState("");
    const [speed, setSpeed] = React.useState("standard");
    const [error, setError] = React.useState(null);

    const saved = V.beneficiaires.find((x) => x.value === benef);
    const ibanOk = /^FR\d{2}[\d ]{23,}$/i.test(newIban.trim().replace(/\s+/g, " "));
    const target = mode === "saved"
      ? { name: saved.label, iban: saved.iban }
      : { name: newName.trim(), iban: newIban.trim().toUpperCase() };
    const val = parseFloat(String(amount).replace(",", ".")) || 0;
    const fee = speed === "instant" ? V.instantFee : 0;
    const total = val + fee;

    function next() {
      setError(null);
      if (step === 1) {
        if (mode === "new" && !target.name) { setError("Renseignez le nom du bénéficiaire."); return; }
        if (mode === "new" && !ibanOk) { setError("IBAN invalide — format attendu : FR76 suivi de 23 chiffres."); return; }
        setStep(2);
      } else if (step === 2) {
        if (!(val > 0)) { setError("Saisissez un montant valide."); return; }
        if (total > V.plafond) { setError("Au-dessus du plafond de 5 000 € / jour."); return; }
        if (total > V.solde) { setError("Solde insuffisant pour couvrir ce virement."); return; }
        setStep(3);
      } else if (step === 3) {
        setStep(4);
      }
    }

    function confirm() {
      V.historique.unshift({
        ref: "VIR-2026-0049", label: target.name + (label ? " — " + label : ""),
        benef: target.name, iban: target.iban.slice(0, 14) + " ···",
        date: "15/04/2026", amount: -val, status: "pending",
        note: speed === "instant" ? "instantané · en file" : "en file d'attente",
        steps: [
          { label: "Ordre créé", date: "15/04", state: "done" },
          { label: "En file d'attente", date: "15/04", state: "current" },
          { label: "Exécution", date: speed === "instant" ? "< 10 s" : "sous 1 j ouvré", state: "future" },
        ],
      });
      setStep(5);
    }

    const row = (k, v, strong) => (
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
        <span style={{ fontSize: 12.5, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{k}</span>
        <span style={{ fontSize: strong ? 13.5 : 12.5, fontWeight: strong ? 700 : 600, textAlign: "right", minWidth: 0 }}>{v}</span>
      </div>
    );

    if (step === 5) {
      return (
        <div style={{ padding: "14px 16px 26px", display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, padding: "18px 0 4px", textAlign: "center" }}>
            <StatusBadge status="pending" />
            <div style={{ fontWeight: 700, fontSize: 19, letterSpacing: "-0.02em" }}>Virement en file d'attente</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>VIR-2026-0049</div>
          </div>
          <div style={sunken}>
            {row("Bénéficiaire", target.name)}
            {row("Montant", <Amount value={-val} size="sm" />)}
            {row("Exécution", speed === "instant" ? "instantané · < 10 s" : "sous 1 j ouvré")}
          </div>
          <StatusTimeline steps={V.historique[0].steps} />
          <div style={{ fontSize: 11.5, color: "var(--text-subtle)", textAlign: "center" }}>Mode démo — aucun ordre réel n'est émis.</div>
          <Button size="md" variant="secondary" onClick={() => go && go("dashboard")} style={{ alignSelf: "center" }}>Terminé</Button>
        </div>
      );
    }

    const titles = { 1: "Bénéficiaire", 2: "Montant & exécution", 3: "Récapitulatif", 4: "Confirmation" };

    return (
      <div style={{ padding: "14px 16px 26px", display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <IconButton size="sm" variant="ghost" label="Retour" icon={<Ic.chevronLeft size={20} />}
            onClick={() => (step > 1 ? (setError(null), setStep(step - 1)) : go && go("dashboard"))} />
          <div style={{ fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em", flex: 1 }}>Nouveau virement</div>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)", flex: "none" }}>{step}/4</span>
        </div>
        <div style={{ ...lbl }}>{titles[step]} — mode démo, rien n'est émis</div>

        {step === 1 && (
          <React.Fragment>
            <SegmentedControl value={mode} onChange={setMode} options={[{ value: "saved", label: "Enregistré" }, { value: "new", label: "Nouveau" }]} />
            {mode === "saved" ? (
              <div style={{ border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--surface-card)" }}>
                {V.beneficiaires.map((b, i) => (
                  <div key={b.value} onClick={() => setBenef(b.value)}
                    style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", borderBottom: i === V.beneficiaires.length - 1 ? "none" : "1px solid var(--line-divider)", cursor: "pointer", background: benef === b.value ? "var(--surface-sunken)" : "transparent" }}>
                    <Avatar initials={b.init} tone={b.tone} size={32} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{b.label}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)", marginTop: 1 }}>{b.iban.slice(0, 14)} ····</div>
                    </div>
                    <span style={{ width: 16, height: 16, borderRadius: "50%", border: "1.5px solid var(--line-keyline)", background: benef === b.value ? "var(--oryze-majorelle)" : "transparent", boxShadow: benef === b.value ? "inset 0 0 0 3px var(--surface-card)" : "none", flex: "none" }}></span>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <Input label="Nom du bénéficiaire" value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Ex. Print Pro" />
                <Input label="IBAN" value={newIban} onChange={(e) => setNewIban(e.target.value)} mono placeholder="FR76 …" />
                <div style={{ fontSize: 11.5, color: "var(--text-subtle)" }}>Le BIC est détecté automatiquement. IBAN fictifs uniquement — démo.</div>
              </div>
            )}
          </React.Fragment>
        )}

        {step === 2 && (
          <React.Fragment>
            <Input label="Montant" value={amount} onChange={(e) => setAmount(e.target.value)} mono suffix="€" />
            <Input label="Libellé (optionnel)" value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Ex. loyer avril" />
            <div>
              <div style={{ ...lbl, marginBottom: 7 }}>Vitesse</div>
              <SegmentedControl value={speed} onChange={setSpeed} options={[{ value: "standard", label: "Standard · gratuit" }, { value: "instant", label: "Instantané · 0,80 €" }]} />
              <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 5 }}>
                {speed === "instant" ? "Arrive en moins de 10 secondes, 7 j/7 — frais de 0,80 €." : "Arrive sous 1 jour ouvré — sans frais."}
              </div>
            </div>
            <div style={sunken}>
              {row("Solde disponible", <Amount value={V.solde} size="sm" />)}
              {row("Plafond restant / jour", <Amount value={V.plafond} size="sm" />)}
            </div>
          </React.Fragment>
        )}

        {step === 3 && (
          <div style={sunken}>
            {row("Bénéficiaire", target.name)}
            {row("IBAN", <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{target.iban.slice(0, 19)} ···</span>)}
            {label ? row("Libellé", label) : null}
            <div style={{ height: 1, background: "var(--line-divider)", margin: "2px 0" }} />
            {row("Montant", <Amount value={val} size="sm" />)}
            {row("Frais", fee ? <Amount value={fee} size="sm" /> : "Gratuit")}
            {row("Total débité", <Amount value={total} size="md" />, true)}
            <div style={{ height: 1, background: "var(--line-divider)", margin: "2px 0" }} />
            {row("Solde après", <Amount value={V.solde - total} size="sm" tone="muted" />)}
          </div>
        )}

        {step === 4 && (
          <React.Fragment>
            <div style={{ fontSize: 13, color: "var(--text-body)", lineHeight: 1.55 }}>
              Confirmation forte : saisissez le code envoyé au <span style={{ fontFamily: "var(--font-mono)" }}>{window.OryzeCarte ? window.OryzeCarte.pinContact : "+33 6 •• •• 42 10"}</span> pour signer l'ordre de <Amount value={total} size="sm" />.
            </div>
            <div style={{ display: "flex", justifyContent: "center", padding: "6px 0" }}>
              <OtpInput length={6} autoFocus onComplete={confirm} />
            </div>
            <div style={{ fontSize: 11.5, color: "var(--text-subtle)", textAlign: "center" }}>Mode démo — n'importe quel code fonctionne.</div>
          </React.Fragment>
        )}

        {error && <div style={errS}>{error}</div>}

        {step < 4 && (
          <Button size="md" iconLeft={step === 3 ? <Ic.send size={15} /> : null} onClick={next}>
            {step === 3 ? "Confirmer et signer" : "Continuer"}
          </Button>
        )}
      </div>
    );
  }

  window.OryzeApp = window.OryzeApp || {};
  window.OryzeApp.VirementScreen = VirementScreen;
})();
