/* ───────────────────────────────────────────────────────────
   IbanWallet.jsx — écrans wallet « ID Wallet » du parcours IBAN
   Acte 1 (émission OpenID4VCI) : offre d'attestation → ajout au portefeuille
   Acte 2 (présentation OpenID4VP) : consentement combiné PID + IBAN
   Rendu DANS un <IOSDevice> fourni par IbanApp.
   ─────────────────────────────────────────────────────────── */

const { Ic: IWIc, IDPhoto: IWPhoto, RFLockup: IWRF, PidCertBand: IWCertBand, IIc: IW2, ibanAttestation: IWiban,
        TEL_IDENTITY_CLAIMS: IWtel, TEL_OFFER: IWoffer } = window;

const IW_TOP = 58, IW_BOT = 30;

// — boutons (mêmes codes couleur que WalletApp) —
function IWBtn({ children, onClick, tone = 'blue', disabled }) {
  const [h, setH] = React.useState(false);
  const bg = tone === 'blue'
    ? (disabled ? '#aab0bb' : (h ? 'var(--rf-blue-700)' : 'var(--rf-blue)'))
    : (h ? '#f0f0f8' : '#eeeeee');
  const col = tone === 'blue' ? '#fff' : 'var(--rf-blue)';
  return (
    <button onClick={onClick} disabled={disabled}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ width: '100%', padding: '15px 18px', border: 'none', borderRadius: 10,
        fontSize: 16, fontWeight: 700, color: col, background: bg,
        cursor: disabled ? 'not-allowed' : 'pointer', transition: 'background .16s' }}>
      {children}
    </button>
  );
}
function IWBtnText({ children, onClick }) {
  return (
    <button onClick={onClick} style={{ width: '100%', padding: '13px', border: 'none', background: 'none',
      fontSize: 15, fontWeight: 600, color: 'var(--rf-grey)', cursor: 'pointer',
      textDecoration: 'underline', textUnderlineOffset: 3 }}>{children}</button>
  );
}
function IWHeader({ sub }) {
  return (
    <div style={{ padding: `${IW_TOP}px 20px 14px`, borderBottom: '1px solid var(--rf-line)' }}>
      <IWRF scale={1.15} />
      {sub && <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', marginTop: 12 }}>{sub}</div>}
    </div>
  );
}

// — petite vignette « attestation IBAN » réutilisée partout —
function IbanChip({ small }) {
  const s = small ? 0.86 : 1;
  return (
    <div style={{ width: 44 * s, height: 44 * s, borderRadius: 11 * s, flexShrink: 0,
      background: 'linear-gradient(150deg,#1657c8,#0f3f95)', display: 'flex',
      alignItems: 'center', justifyContent: 'center' }}>
      <IWIc.bank s={22 * s} c="#fff" />
    </div>
  );
}

/* ─────────── ACCUEIL WALLET (avec documents) ─────────── */
function IWHome({ profile, hasIban, incoming, onScan }) {
  const iban = IWiban(profile);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <IWHeader sub="Votre identité et vos attestations" />
      <div className="thin-scroll" style={{ flex: 1, overflow: 'auto', padding: '18px 20px' }}>
        {/* carte identité */}
        <div style={{ borderRadius: 16, overflow: 'hidden', border: '1px solid var(--rf-line)',
          boxShadow: '0 10px 30px -18px rgba(0,0,20,.4)' }}>
          <div style={{ background: 'var(--rf-blue)', padding: '12px 16px', display: 'flex',
            alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ color: '#fff', fontSize: 12.5, fontWeight: 700, letterSpacing: '.04em' }}>IDENTITÉ · PID</span>
            <span style={{ color: '#fff', opacity: .85 }}><IWIc.shield s={16} c="#fff" /></span>
          </div>
          <div style={{ padding: 16, display: 'flex', gap: 14, alignItems: 'center', background: '#fff' }}>
            <IWPhoto hue={profile.hue} size={54} radius={9} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16.5, fontWeight: 800, color: 'var(--rf-ink)' }}>{profile.prenom} {profile.nom}</div>
              <div style={{ fontSize: 12, color: 'var(--rf-grey)', marginTop: 2 }}>Né(e) le {profile.dateNaissance}</div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 7,
                fontSize: 11, fontWeight: 700, color: 'var(--rf-ok)' }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--rf-ok)' }} /> Active et certifiée
              </div>
            </div>
          </div>
          <IWCertBand />
        </div>

        {/* documents / attestations */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '20px 2px 10px' }}>
          <span style={{ fontSize: 13, fontWeight: 800, color: 'var(--rf-ink)', letterSpacing: '.01em' }}>Mes attestations</span>
          <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--rf-grey)' }}>{hasIban ? '1' : '0'}</span>
        </div>

        {hasIban ? (
          <div className="rise" style={{ borderRadius: 14, border: '1px solid var(--rf-line)', overflow: 'hidden' }}>
            <div style={{ padding: 14, display: 'flex', gap: 13, alignItems: 'center' }}>
              <IbanChip />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--rf-ink)' }}>{iban.shortLabel}</div>
                <div style={{ fontSize: 12, color: 'var(--rf-grey)', marginTop: 1 }}>{iban.banque} · valable {iban.valable}</div>
              </div>
              <span style={{ color: 'var(--rf-ok)' }}><IWIc.check s={17} c="var(--rf-ok)" /></span>
            </div>
            <div style={{ padding: '10px 14px', borderTop: '1px solid var(--rf-line)', background: 'var(--rf-bg)',
              fontSize: 12, fontFamily: 'monospace', color: 'var(--rf-ink)', letterSpacing: '.02em' }}>
              {iban.iban}
            </div>
          </div>
        ) : (
          <div style={{ borderRadius: 14, border: '1px dashed var(--rf-line)', padding: '20px 16px',
            textAlign: 'center', color: 'var(--rf-grey)', fontSize: 12.5, lineHeight: 1.5,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <IW2.wallet s={24} c="#b9bcc8" />
            Aucune attestation pour l'instant.<br />Ajoutez-en une depuis un service partenaire.
          </div>
        )}
      </div>

      {/* bouton scanner */}
      <div style={{ padding: `14px 20px ${IW_BOT}px`, borderTop: '1px solid var(--rf-line)', background: '#fff' }}>
        {incoming && (
          <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', textAlign: 'center', marginBottom: 10 }}>
            ↙ Une demande vient d'arriver d'un service partenaire
          </div>
        )}
        <IWBtn onClick={onScan}>Scanner un QR code</IWBtn>
      </div>
    </div>
  );
}

/* ─────────── ACTE 1 · OFFRE D'ATTESTATION (OpenID4VCI) ─────────── */
function IWOffer({ profile, onAdd, onRefuse }) {
  const iban = IWiban(profile);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <div style={{ padding: `${IW_TOP}px 20px 0` }}><IWRF scale={0.92} /></div>
      <div className="thin-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px 20px 8px' }}>
        <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase',
          color: 'var(--rf-blue)' }}>Nouvelle attestation</div>
        <h3 style={{ fontSize: 19, fontWeight: 800, color: 'var(--rf-ink)', margin: '6px 0 14px', lineHeight: 1.25 }}>
          Ajouter cette attestation à votre portefeuille ?
        </h3>

        {/* émetteur */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12,
          background: 'var(--rf-bg)', border: '1px solid var(--rf-line)', marginBottom: 14 }}>
          <IbanChip small />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 800, color: 'var(--rf-ink)' }}>{iban.issuer}</div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11,
              fontWeight: 700, color: 'var(--rf-ok)' }}>
              <IWIc.check s={12} c="var(--rf-ok)" /> Émetteur vérifié
            </div>
          </div>
        </div>

        {/* aperçu de l'attestation */}
        <div style={{ borderRadius: 14, overflow: 'hidden', border: '1px solid var(--rf-line)' }}>
          <div style={{ background: 'linear-gradient(150deg,#1657c8,#0f3f95)', padding: '14px 16px' }}>
            <div style={{ color: 'rgba(255,255,255,.8)', fontSize: 11, fontWeight: 700, letterSpacing: '.05em' }}>
              ATTESTATION DE COMPTE BANCAIRE
            </div>
            <div style={{ color: '#fff', fontSize: 17, fontWeight: 800, marginTop: 4, fontFamily: 'monospace',
              letterSpacing: '.02em' }}>{iban.iban}</div>
          </div>
          <div style={{ background: '#fff' }}>
            {[['Titulaire', iban.titulaire], ['BIC', iban.bic], ['Banque', iban.banque], ['Format', iban.format]]
              .map(([k, v], i, a) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '11px 14px',
                borderBottom: i === a.length - 1 ? 'none' : '1px solid var(--rf-line)' }}>
                <span style={{ fontSize: 12.5, color: 'var(--rf-grey)' }}>{k}</span>
                <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--rf-ink)', textAlign: 'right' }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ fontSize: 11.5, color: 'var(--rf-grey)', marginTop: 12, lineHeight: 1.5, display: 'flex', gap: 8 }}>
          <IWIc.lock s={24} c="var(--rf-grey)" />
          L'attestation sera stockée chiffrée sur votre téléphone. Vous resterez seul(e) à décider à qui la présenter.
        </div>
      </div>
      <div style={{ padding: `12px 20px ${IW_BOT}px`, borderTop: '1px solid var(--rf-line)', display: 'flex',
        flexDirection: 'column', gap: 4 }}>
        <IWBtn onClick={onAdd}>Ajouter à mon portefeuille</IWBtn>
        <IWBtnText onClick={onRefuse}>Refuser</IWBtnText>
      </div>
    </div>
  );
}

/* ─────────── ACTE 2 · CONSENTEMENT COMBINÉ (OpenID4VP) ─────────── */
function IWConsent2({ profile, onAllow, onRefuse }) {
  const iban = IWiban(profile);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <div style={{ padding: `${IW_TOP}px 20px 0` }}><IWRF scale={0.92} /></div>
      <div className="thin-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px 20px 8px' }}>
        <h3 style={{ fontSize: 19, fontWeight: 800, color: 'var(--rf-ink)', margin: '8px 0 4px', lineHeight: 1.25 }}>
          Partager mes données ?
        </h3>
        {/* verifier télécom */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12,
          background: 'var(--rf-bg)', border: '1px solid var(--rf-line)', margin: '12px 0 16px' }}>
          <div style={{ width: 38, height: 38, borderRadius: 9, background: 'var(--tel-primary)', flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IW2.signal s={20} c="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800, color: 'var(--rf-ink)' }}>{IWoffer.brand}</div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5,
              fontWeight: 700, color: 'var(--rf-ok)' }}>
              <IWIc.check s={13} c="var(--rf-ok)" /> Destinataire vérifié
            </div>
          </div>
        </div>
        <div style={{ fontSize: 13, color: 'var(--rf-grey)', marginBottom: 4, lineHeight: 1.45 }}>
          souhaite vérifier votre IBAN et votre identité pour&nbsp;:
          <strong style={{ color: 'var(--rf-ink)' }}> la souscription d'une ligne mobile</strong>.
        </div>

        {/* source 1 : attestation IBAN (QEAA) — mise en avant : c'est l'objet de la demande */}
        <Caption2 icon={<IW2.doc s={13} c="var(--rf-blue)" />}>Votre IBAN · Attestation Banque Démo</Caption2>
        <div style={{ borderRadius: 12, border: '1px solid var(--rf-line)', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
            <IbanChip small />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--rf-ink)' }}>IBAN — Compte courant</div>
              <div style={{ fontSize: 12, fontFamily: 'monospace', color: 'var(--rf-grey)', whiteSpace: 'nowrap',
                overflow: 'hidden', textOverflow: 'ellipsis' }}>{iban.iban}</div>
            </div>
            <span style={{ color: 'var(--rf-ok)' }}><IWIc.check s={15} c="var(--rf-ok)" /></span>
          </div>
        </div>

        {/* source 2 : identité (PID) */}
        <Caption2 icon={<IWIc.shield s={13} c="var(--rf-blue)" />}>Votre identité · Carte d'identité</Caption2>
        <div style={{ borderRadius: 12, border: '1px solid var(--rf-line)', overflow: 'hidden' }}>
          {IWtel.map((c, i) => (
            <div key={c.key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px',
              borderBottom: i === IWtel.length - 1 ? 'none' : '1px solid var(--rf-line)' }}>
              {c.isPhoto
                ? <IWPhoto hue={profile.hue} size={32} radius={6} />
                : <div style={{ width: 24, height: 24, borderRadius: 7, background: 'var(--rf-bg)', flexShrink: 0 }} />}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--rf-ink)' }}>{c.label}</div>
                <div style={{ fontSize: 12, color: 'var(--rf-grey)', whiteSpace: 'nowrap', overflow: 'hidden',
                  textOverflow: 'ellipsis' }}>{c.isPhoto ? 'Portrait certifié' : profile[c.key]}</div>
              </div>
              <span style={{ color: 'var(--rf-ok)' }}><IWIc.check s={15} c="var(--rf-ok)" /></span>
            </div>
          ))}
        </div>

        <div style={{ fontSize: 11.5, color: 'var(--rf-grey)', marginTop: 12, lineHeight: 1.5, display: 'flex', gap: 8 }}>
          <IWIc.lock s={26} c="var(--rf-grey)" />
          {IWoffer.brand} reçoit uniquement ces données signées. Votre code personnel n'est jamais transmis.
        </div>
      </div>
      <div style={{ padding: `12px 20px ${IW_BOT}px`, borderTop: '1px solid var(--rf-line)', display: 'flex',
        flexDirection: 'column', gap: 4 }}>
        <IWBtn onClick={onAllow}>Autoriser le partage</IWBtn>
        <IWBtnText onClick={onRefuse}>Refuser</IWBtnText>
      </div>
    </div>
  );
}
function Caption2({ icon, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, margin: '16px 0 6px' }}>
      {icon}
      <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.03em', textTransform: 'uppercase',
        color: 'var(--rf-grey)' }}>{children}</span>
    </div>
  );
}

/* ─────────── PAVÉ CODE PERSONNEL (réutilisé Actes 1 & 2) ─────────── */
function IWAuth({ title, onDone }) {
  const [code, setCode] = React.useState('');
  const LEN = 6;
  const press = (d) => {
    if (code.length >= LEN) return;
    const nc = code + d; setCode(nc);
    if (nc.length === LEN) setTimeout(onDone, 380);
  };
  const del = () => setCode(c => c.slice(0, -1));
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff',
      padding: `${IW_TOP}px 24px ${IW_BOT}px`, textAlign: 'center' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: 54, height: 54, borderRadius: 14, background: 'var(--rf-bg)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
          <IWIc.lock s={26} c="var(--rf-blue)" />
        </div>
        <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--rf-ink)', marginBottom: 6 }}>Confirmez votre identité</div>
        <div style={{ fontSize: 13.5, color: 'var(--rf-grey)', maxWidth: 250, lineHeight: 1.45 }}>{title}</div>
        <div style={{ display: 'flex', gap: 12, marginTop: 26 }}>
          {Array.from({ length: LEN }).map((_, i) => (
            <span key={i} style={{ width: 13, height: 13, borderRadius: '50%',
              background: i < code.length ? 'var(--rf-blue)' : 'transparent',
              border: `2px solid ${i < code.length ? 'var(--rf-blue)' : '#c7cad6'}`, transition: 'all .12s' }} />
          ))}
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, maxWidth: 280, margin: '0 auto', width: '100%' }}>
        {['1','2','3','4','5','6','7','8','9'].map(d => <IWKey key={d} d={d} onPress={press} />)}
        <span />
        <IWKey d="0" onPress={press} />
        <button onClick={del} style={{ border: 'none', background: 'none', cursor: 'pointer',
          fontSize: 15, fontWeight: 700, color: 'var(--rf-grey)' }}>Effacer</button>
      </div>
    </div>
  );
}
function IWKey({ d, onPress }) {
  const [a, setA] = React.useState(false);
  return (
    <button onMouseDown={() => setA(true)} onMouseUp={() => setA(false)} onMouseLeave={() => setA(false)}
      onClick={() => onPress(d)}
      style={{ height: 58, borderRadius: 14, border: 'none', cursor: 'pointer',
        fontSize: 26, fontWeight: 600, color: 'var(--rf-ink)',
        background: a ? '#e7e9f3' : 'var(--rf-bg)', transition: 'background .08s' }}>{d}</button>
  );
}

/* ─────────── ÉTATS GÉNÉRIQUES (spinner / succès) ─────────── */
function IWWorking({ title, sub }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', background: '#fff', padding: 30 }}>
      <div style={{ position: 'relative', width: 64, height: 64, marginBottom: 22 }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '4px solid var(--rf-line)' }} />
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '4px solid var(--rf-blue)',
          borderTopColor: 'transparent', animation: 'spin .8s linear infinite' }} />
      </div>
      <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--rf-ink)' }}>{title}</div>
      <div style={{ fontSize: 13, color: 'var(--rf-grey)', marginTop: 4, textAlign: 'center' }}>{sub}</div>
    </div>
  );
}
function IWDone({ title, children }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', background: '#fff', padding: 30, textAlign: 'center' }}>
      <div style={{ position: 'relative', marginBottom: 24 }}>
        <span style={{ position: 'absolute', inset: -10, borderRadius: '50%', border: '2px solid var(--rf-ok)',
          animation: 'ring 1.4s ease-out infinite' }} />
        <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'var(--rf-ok)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'pop .5s ease-out both' }}>
          <IWIc.check s={40} c="#fff" />
        </div>
      </div>
      <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--rf-ink)' }}>{title}</div>
      <div style={{ fontSize: 14, color: 'var(--rf-grey)', marginTop: 8, maxWidth: 250, lineHeight: 1.5 }}>{children}</div>
    </div>
  );
}

Object.assign(window, { IWHome, IWOffer, IWConsent2, IWAuth, IWWorking, IWDone, IbanChip });
