// Dashboard — Virements : solde + IBAN (MOCK), KPIs, liste filtrable avec
// machine à états visible (pending → executed | failed), détail avec cycle de
// vie, bénéficiaires, virements programmés, émission (démo — rien n'est émis).
// window.OryzeDash.CompteProView (onglet "Virements")
(function () {
  const { Card, Amount, Tag, Button, StatusBadge, Select, Input, Dialog, Avatar, Tabs, StatTile, StatusTimeline, IconButton, SegmentedControl, ProgressSteps, OtpInput, EmptyState } = 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 BENEFICIAIRES = window.OryzeVirements.beneficiaires;

  const HISTORIQUE = window.OryzeVirements.historique;

  const PROGRAMMES = [
    { label: "SCI Part-Dieu — loyer", cadence: "Mensuel · le 5", amount: -720 },
    { label: "URSSAF — cotisations", cadence: "Mensuel · le 5", amount: -1140 },
  ];

  function CompteProView({ demoState = "normal" }) {
    const [transfers, setTransfers] = React.useState(HISTORIQUE);
    const [modal, setModal] = React.useState(null); // {type:'new', benef?} | {type:'detail', v}
    const [tab, setTab] = React.useState("all");

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    const { ErrorState, SkelTiles, SkelListCard, SkelBlockCard } = window.OryzeShared;
    if (demoState === "empty") {
      return (
        <React.Fragment>
          <EmptyState framed title="Aucun virement pour l'instant"
            description="Émettez votre premier virement : il apparaîtra ici avec son cycle de vie visible — de l'ordre authentifié à l'exécution."
            action={<Button size="sm" iconLeft={<Ic.send size={15} />} onClick={() => setModal({ type: "new" })}>Nouveau virement</Button>} />
          <NewTransferDialog open={modal && modal.type === "new"} initialBenef={null} onClose={() => setModal(null)} onDone={() => setModal(null)} />
        </React.Fragment>
      );
    }
    if (demoState === "loading") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }}>
            <SkelBlockCard height={96} />
            <SkelBlockCard height={96} />
          </div>
          <SkelTiles n={3} />
          <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
            <SkelListCard rows={5} avatar={false} />
            <SkelListCard rows={3} />
          </div>
        </div>
      );
    }
    if (demoState === "error") {
      return <ErrorState what="Impossible de charger vos virements" endpoint="GET /virements · 503 · réf. e2a8-…" />;
    }

    const pending = transfers.filter((t) => t.status === "pending");
    const failed = transfers.filter((t) => t.status === "failed");
    const executedApril = transfers.filter((t) => t.status === "executed" && t.date.includes("/04/"));
    const outApril = executedApril.reduce((a, t) => a + t.amount, 0);
    const list = transfers.filter((t) => (tab === "all" ? true : t.status === tab));

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Compte hero + statut */}
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, alignItems: "stretch" }}>
          <Card variant="hero" padding="22px" style={{ minWidth: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
              <div style={{ minWidth: 0 }}>
                <div style={lbl}>Solde disponible · Atelier Lefèvre</div>
                <div style={{ marginTop: 8 }}><Amount value={8920} size="xl" /></div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-body)" }}>FR76 3000 4028 3798 7654 3210 943</span>
                  <Tag tone="butter" mono>IBAN MOCK</Tag>
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 4 }}>BIC BNPAFRPPXXX · Titulaire Marie Lefèvre</div>
              </div>
              <Button size="sm" iconLeft={<Ic.send size={15} />} onClick={() => setModal({ type: "new" })} style={{ flex: "none" }}>Nouveau virement</Button>
            </div>
          </Card>

          <Card variant="flat" padding="20px" style={{ minWidth: 0 }}>
            <div style={{ ...lbl, marginBottom: 12 }}>Statut du compte</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13.5 }}>Identité (KYC)</span><Tag tone="paid" dot>Vérifiée</Tag>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13.5 }}>Virements SEPA</span><Tag tone="mint" dot>Activés</Tag>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13.5 }}>Plafond / jour</span><Amount value={5000} size="sm" />
              </div>
            </div>
            <div style={{ marginTop: 14, paddingTop: 11, borderTop: "1px solid var(--line-divider)", fontSize: 11.5, color: "var(--text-subtle)" }}>
              Mode démo : compte fictif, aucun ordre réel n'est émis.
            </div>
          </Card>
        </div>

        {/* KPIs du mois */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
          <StatTile label="Sortant exécuté · avril" value={<Amount value={outApril} size="lg" />} hint={executedApril.length + " virements"} />
          <StatTile label="En attente" value={<Amount value={pending.reduce((a, t) => a + t.amount, 0)} size="lg" />} accent="var(--oryze-butter)" hint={pending.length + " ordre programmé le 05/05"} />
          <StatTile label="Rejetés · 30 j" value={<span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 26 }}>{failed.length}</span>} accent="var(--oryze-coral)" hint="IBAN invalide — aucun débit" />
        </div>

        {/* Liste + colonne droite */}
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
          <Card variant="flat" padding="0" style={{ minWidth: 0 }}>
            <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "6px 12px", padding: "12px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
              <div style={{ fontWeight: 700, fontSize: 15, minWidth: 0 }}>Virements</div>
              <Tabs value={tab} onChange={setTab} tabs={[
                { value: "all", label: "Tous" },
                { value: "pending", label: "En attente", count: pending.length },
                { value: "executed", label: "Exécutés" },
                { value: "failed", label: "Rejetés", count: failed.length }]} />
            </div>
            {list.map((v) => (
              <TransferRow key={v.ref} v={v} onOpen={() => setModal({ type: "detail", v })} />
            ))}
            {list.length === 0 && (
              <div style={{ padding: "36px", textAlign: "center", color: "var(--text-muted)", fontSize: 13.5 }}>Aucun virement dans cet état.</div>
            )}
          </Card>

          <div style={{ display: "flex", flexDirection: "column", gap: 16, minWidth: 0 }}>
            <Card variant="flat" padding="0" style={{ minWidth: 0 }}>
              <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "6px 12px", padding: "14px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
                <div style={{ fontWeight: 700, fontSize: 15, minWidth: 0 }}>Bénéficiaires</div>
                <Button size="sm" variant="ghost" iconLeft={<Ic.plus size={14} />}>Ajouter</Button>
              </div>
              {BENEFICIAIRES.map((b, i) => (
                <div key={b.value} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 18px", borderBottom: i < BENEFICIAIRES.length - 1 ? "1px solid var(--line-divider)" : "none" }}>
                  <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>
                  <IconButton size="sm" variant="ghost" label={"Virer à " + b.label} icon={<Ic.send size={15} />} onClick={() => setModal({ type: "new", benef: b.value })} />
                </div>
              ))}
            </Card>

            <Card variant="flat" padding="0" style={{ minWidth: 0 }}>
              <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "6px 12px", padding: "14px 18px", borderBottom: "1.5px solid var(--line-keyline)" }}>
                <div style={{ fontWeight: 700, fontSize: 15, minWidth: 0 }}>Programmés</div>
                <span style={lbl}>Récurrents</span>
              </div>
              {PROGRAMMES.map((p, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 18px", borderBottom: i < PROGRAMMES.length - 1 ? "1px solid var(--line-divider)" : "none" }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.label}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-subtle)", marginTop: 1 }}>{p.cadence}</div>
                  </div>
                  <Amount value={p.amount} size="sm" />
                </div>
              ))}
            </Card>
          </div>
        </div>

        <NewTransferDialog open={modal && modal.type === "new"} initialBenef={modal && modal.benef} onClose={() => setModal(null)}
          onDone={(t) => { setTransfers((ts) => [t, ...ts]); setModal(null); setTab("all"); }} />
        <TransferDetailDialog modal={modal} onClose={() => setModal(null)} />
      </div>
    );
  }

  function TransferRow({ v, onOpen }) {
    const [h, setH] = React.useState(false);
    return (
      <div onClick={onOpen} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--line-divider)", cursor: "pointer", background: h ? "var(--surface-page)" : "transparent", transition: "background var(--dur-fast) var(--ease-out)" }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v.label}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: v.status === "failed" ? "var(--fin-negative)" : "var(--text-subtle)", marginTop: 2 }}>
            {v.ref} · {v.date}{v.note ? " · " + v.note : ""}
          </div>
        </div>
        <Amount value={v.amount} size="sm" />
        <StatusBadge size="sm" status={v.status} />
        <Ic.chevronRight size={16} style={{ color: "var(--text-subtle)", flex: "none" }} />
      </div>
    );
  }

  // Détail — cycle de vie complet de l'ordre
  function TransferDetailDialog({ modal, onClose }) {
    const open = modal && modal.type === "detail";
    const v = open ? modal.v : null;
    return (
      <Dialog open={!!open} onClose={onClose} width={480} title={v ? v.label : ""} subtitle={v ? v.ref + " · " + v.date : ""}>
        {v && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
              <Amount value={v.amount} size="xl" />
              <StatusBadge status={v.status} />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 20px", padding: "13px 14px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" }}>
              <div><div style={lbl}>Bénéficiaire</div><div style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{v.benef}</div></div>
              <div><div style={lbl}>IBAN</div><div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, marginTop: 3 }}>{v.iban}</div></div>
            </div>
            <div>
              <div style={{ ...lbl, marginBottom: 10 }}>Cycle de vie</div>
              <StatusTimeline steps={v.steps} />
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              {v.status === "pending" && <Button variant="ghost" size="sm">Annuler l'ordre</Button>}
              {v.status === "failed" && <Button variant="secondary" size="sm" iconLeft={<Ic.send size={14} />}>Corriger l'IBAN et réémettre</Button>}
              {v.status === "executed" && <Button variant="ghost" size="sm" iconLeft={<Ic.download size={14} />}>Justificatif (PDF)</Button>}
            </div>
          </div>
        )}
      </Dialog>
    );
  }

  // Nouveau virement — parcours complet façon SEPA réel, 4 étapes :
  // 1 bénéficiaire (enregistré ou nouveau + validation IBAN) → 2 montant
  // (standard/instantané, exécution auj./programmée, plafond & solde) →
  // 3 récapitulatif (frais, total, solde après) → 4 confirmation forte (OTP,
  // façon DSP2) → en file (pending). Démo : aucun ordre réel n'est émis.
  const SOLDE = window.OryzeVirements.solde;
  const PLAFOND = window.OryzeVirements.plafond;

  function NewTransferDialog({ open, initialBenef, onClose, onDone }) {
    const [step, setStep] = React.useState(1);
    // Étape 1 — bénéficiaire
    const [mode, setMode] = React.useState("saved"); // saved | new
    const [benef, setBenef] = React.useState("urssaf");
    const [newName, setNewName] = React.useState("");
    const [newIban, setNewIban] = React.useState("");
    // Étape 2 — montant & exécution
    const [amount, setAmount] = React.useState("250");
    const [label, setLabel] = React.useState("");
    const [speed, setSpeed] = React.useState("standard"); // standard | instant
    const [when, setWhen] = React.useState("now"); // now | scheduled
    const [schedDate, setSchedDate] = React.useState("05/05/2026");
    // Étape 4 — confirmation forte
    const [otp, setOtp] = React.useState("");
    const [phase, setPhase] = React.useState("edit"); // edit | sending | queued
    const [error, setError] = React.useState(null);

    React.useEffect(() => {
      if (open) {
        setStep(1); setPhase("edit"); setError(null); setOtp("");
        setMode("saved"); setBenef(initialBenef || "urssaf");
        setNewName(""); setNewIban(""); setLabel("");
        setSpeed("standard"); setWhen("now");
      }
    }, [open, initialBenef]);

    const saved = 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, bic: "BNPAFRPPXXX" }
      : { name: newName.trim(), iban: newIban.trim().toUpperCase(), bic: ibanOk ? "BNPAFRPPXXX (détecté)" : "—" };

    const val = parseFloat(String(amount).replace(",", ".")) || 0;
    const fee = speed === "instant" ? window.OryzeVirements.instantFee : 0;
    const total = val + fee;
    const execDate = when === "now" ? (speed === "instant" ? "aujourd'hui · < 10 s" : "aujourd'hui · exécuté sous 1 j ouvré") : schedDate;

    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 > PLAFOND) { setError("Au-dessus du plafond de 5 000 € / jour."); return; }
        if (total > SOLDE) { setError("Solde insuffisant pour couvrir ce virement."); return; }
        if (when === "scheduled" && !/^\d{2}\/\d{2}\/\d{4}$/.test(schedDate)) { setError("Date attendue au format JJ/MM/AAAA."); return; }
        setStep(3);
      } else if (step === 3) {
        setStep(4);
      }
    }

    function confirmOtp(code) {
      if (code.length < 6) return;
      setPhase("sending");
      setTimeout(() => {
        setPhase("queued");
        setTimeout(() => onDone({
          ref: "VIR-2026-0049",
          label: target.name + (label ? " — " + label : ""),
          benef: target.name, iban: target.iban.slice(0, 14) + " ···",
          date: when === "now" ? "15/04/2026" : schedDate, amount: -val, status: "pending",
          note: speed === "instant" ? "instantané · en file" : when === "scheduled" ? "exécution programmée" : "en file d'attente",
          steps: [
            { label: "Ordre créé · authentifié", date: "auj.", state: "done" },
            { label: "En file d'attente", date: "auj.", state: "current" },
            { label: "Exécution", date: when === "now" ? "auj." : schedDate.slice(0, 5), state: "future" },
          ],
        }), 1600);
      }, 1100);
    }

    const stepTitles = { 1: "Bénéficiaire", 2: "Montant & exécution", 3: "Récapitulatif", 4: "Confirmation" };
    const recapRow = (k, v, strong) => (
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
        <span style={{ fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{k}</span>
        <span style={{ fontSize: 13, fontWeight: strong ? 700 : 500, textAlign: "right", minWidth: 0 }}>{v}</span>
      </div>
    );

    return (
      <Dialog open={!!open} onClose={onClose} width={520} title="Nouveau virement"
        subtitle={phase === "queued" ? "Mode démo — aucun ordre réel n'est émis" : "Étape " + step + "/4 · " + stepTitles[step] + " — mode démo, rien n'est émis"}>
        {open && (phase === "queued" ? (
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "22px 0 14px", textAlign: "center" }}>
            <StatusBadge status="pending" />
            <div style={{ fontWeight: 700, fontSize: 18, 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 style={{ width: "100%", maxWidth: 340, display: "flex", flexDirection: "column", gap: 7, padding: "13px 14px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)", textAlign: "left" }}>
              {recapRow("Bénéficiaire", target.name)}
              {recapRow("Montant", <Amount value={-val} size="sm" />)}
              {recapRow("Exécution", execDate)}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-subtle)", maxWidth: 320, lineHeight: 1.5 }}>
              Il passera à « Exécuté » ou « Rejeté » après traitement. Vous serez notifiée.
            </div>
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <ProgressSteps total={4} current={step} />

            {step === 1 && (
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <SegmentedControl value={mode} onChange={setMode} options={[{ value: "saved", label: "Enregistré" }, { value: "new", label: "Nouveau bénéficiaire" }]} />
                {mode === "saved" ? (
                  <div>
                    <Select label="Bénéficiaire" value={benef} onChange={(e) => setBenef(e.target.value)} options={BENEFICIAIRES} />
                    <div style={{ display: "flex", flexWrap: "wrap", gap: "3px 16px", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-subtle)" }}>
                      <span>{saved.iban}</span><span>BIC BNPAFRPPXXX</span>
                    </div>
                  </div>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                    <Input label="Nom du bénéficiaire" value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Ex. Imprimerie Chartier" />
                    <div>
                      <Input label="IBAN" value={newIban} onChange={(e) => setNewIban(e.target.value)} placeholder="FR76 …" mono error={newIban && !ibanOk ? " " : undefined} />
                      <div style={{ fontSize: 11.5, marginTop: 5, color: ibanOk ? "var(--fin-positive-text)" : "var(--text-subtle)" }}>
                        {ibanOk ? "IBAN valide · BIC détecté : BNPAFRPPXXX" : "Format : FR76 + 23 chiffres — vérification automatique"}
                      </div>
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--text-subtle)", lineHeight: 1.5, padding: "9px 12px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" }}>
                      Premier virement vers ce bénéficiaire : une confirmation forte vous sera demandée à l'étape 4.
                    </div>
                  </div>
                )}
              </div>
            )}

            {step === 2 && (
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <div style={{ display: "grid", gridTemplateColumns: "150px 1fr", gap: 14 }}>
                  <Input label="Montant" value={amount} onChange={(e) => setAmount(e.target.value)} mono suffix="€" />
                  <Input label="Motif / référence" value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Cotisations T2 2026" />
                </div>
                <div>
                  <div style={{ ...lbl, marginBottom: 7 }}>Type de virement</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>
                  <div style={{ ...lbl, marginBottom: 7 }}>Exécution</div>
                  <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
                    <SegmentedControl value={when} onChange={setWhen} options={[{ value: "now", label: "Aujourd'hui" }, { value: "scheduled", label: "Programmé" }]} />
                    {when === "scheduled" && <Input value={schedDate} onChange={(e) => setSchedDate(e.target.value)} mono style={{ width: 130 }} aria-label="Date d'exécution" />}
                  </div>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: "3px 18px", fontSize: 11.5, color: "var(--text-subtle)", paddingTop: 2 }}>
                  <span>Solde disponible : <strong style={{ fontFamily: "var(--font-mono)", color: "var(--text-body)" }}>8 920,00 €</strong></span>
                  <span>Plafond restant aujourd'hui : <strong style={{ fontFamily: "var(--font-mono)", color: "var(--text-body)" }}>5 000,00 €</strong></span>
                </div>
              </div>
            )}

            {step === 3 && (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "14px 16px", background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", borderRadius: "var(--radius-md)" }}>
                  {recapRow("Bénéficiaire", target.name, true)}
                  {recapRow("IBAN", <span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{target.iban}</span>)}
                  {recapRow("BIC", <span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{target.bic}</span>)}
                  {label ? recapRow("Motif", label) : null}
                  <div style={{ height: 1, background: "var(--line-divider)", margin: "2px 0" }} />
                  {recapRow("Montant", <Amount value={val} size="sm" />)}
                  {recapRow("Frais", fee ? <Amount value={fee} size="sm" /> : "Gratuit")}
                  {recapRow("Total débité", <Amount value={total} size="md" />, true)}
                  <div style={{ height: 1, background: "var(--line-divider)", margin: "2px 0" }} />
                  {recapRow("Exécution", execDate)}
                  {recapRow("Solde après virement", <Amount value={SOLDE - total} size="sm" tone={SOLDE - total < 2000 ? "negative" : "default"} />)}
                </div>
                {SOLDE - total < 2000 && (
                  <div style={{ fontSize: 12, color: "var(--oryze-butter-ink)", background: "var(--oryze-butter)", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", padding: "8px 12px", fontWeight: 600 }}>
                    Ce virement fera passer votre solde sous votre seuil de sécurité (2 000 €).
                  </div>
                )}
                <div style={{ fontSize: 11.5, color: "var(--text-subtle)", lineHeight: 1.5 }}>
                  En confirmant, vous autorisez cet ordre de virement SEPA. Une authentification forte est requise à l'étape suivante.
                </div>
              </div>
            )}

            {step === 4 && (
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, padding: "6px 0", textAlign: "center" }}>
                <div style={{ fontSize: 13.5, color: "var(--text-body)", lineHeight: 1.5, maxWidth: 330 }}>
                  Confirmez avec le code à 6 chiffres envoyé au <strong style={{ fontFamily: "var(--font-mono)" }}>06 12 •• •• 43</strong>
                </div>
                <OtpInput length={6} value={otp} onChange={setOtp} onComplete={confirmOtp} />
                {phase === "sending" ? (
                  <Button size="sm" variant="secondary" loading>Vérification…</Button>
                ) : (
                  <Button size="sm" variant="ghost">Renvoyer le code</Button>
                )}
                <div style={{ fontSize: 11, color: "var(--text-subtle)" }}>Démo : saisissez 6 chiffres, n'importe lesquels.</div>
              </div>
            )}

            {error && <div style={{ fontSize: 12.5, color: "var(--fin-negative)", fontWeight: 600 }}>{error}</div>}

            {step < 4 && (
              <div style={{ display: "flex", gap: 10, justifyContent: "space-between", paddingTop: 2 }}>
                {step > 1
                  ? <Button variant="ghost" size="md" onClick={() => { setError(null); setStep(step - 1); }}>Retour</Button>
                  : <Button variant="ghost" size="md" onClick={onClose}>Annuler</Button>}
                <Button size="md" iconLeft={step === 3 ? <Ic.check size={15} /> : undefined} onClick={next}>
                  {step === 3 ? "Confirmer le virement" : "Continuer"}
                </Button>
              </div>
            )}
            {step === 4 && (
              <div style={{ display: "flex", justifyContent: "flex-start" }}>
                <Button variant="ghost" size="sm" onClick={() => { setOtp(""); setStep(3); }}>Retour au récapitulatif</Button>
              </div>
            )}
          </div>
        ))}
      </Dialog>
    );
  }

  window.OryzeDash = window.OryzeDash || {};
  window.OryzeDash.CompteProView = CompteProView;
})();
