/* ───────────────────────────────────────────────────────────
   WalletApp.jsx — Portefeuille « ID Wallet » (mobile)
   Wallet neutre, conforme eIDAS 2.0 ; carte PID validée ANSSI (émetteur : République française).
   Écrans : idle · scan · consent · auth · sharing · success
   Rendu DANS un <IOSDevice> fourni par App.
   ─────────────────────────────────────────────────────────── */

const { Ic: WIc, IDPhoto: WIDPhoto, RFLockup: WRF, PidCertBand: WCertBand } = window;

const PAD_TOP = 58, PAD_BOT = 30;

// — boutons —
function WBtn({ 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 WBtnText({ 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>
  );
}

// — en-tête ID Wallet —
function WHeader({ sub }) {
  return (
    <div style={{ padding: `${PAD_TOP}px 20px 14px`, borderBottom: '1px solid var(--rf-line)' }}>
      <WRF scale={1.15} />
      {sub && <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', marginTop: 12 }}>{sub}</div>}
    </div>
  );
}

// — ACCUEIL (idle) —
function WIdle({ profile, onScan }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <WHeader sub="Votre identité, sécurisée sur votre téléphone" />
      <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 }}><WIc.shield s={16} c="#fff" /></span>
          </div>
          <div style={{ padding: 16, display: 'flex', gap: 14, alignItems: 'center', background: '#fff' }}>
            <WIDPhoto hue={profile.hue} size={58} radius={9} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--rf-ink)' }}>{profile.prenom} {profile.nom}</div>
              <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', marginTop: 2 }}>Né(e) le {profile.dateNaissance}</div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 8,
                fontSize: 11.5, 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>
          <WCertBand />
        </div>

        {/* tuiles */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 }}>
          {[['Justifier mon identité', WIc.shield], ['Mes documents', WIc.lock],
            ['Historique', WIc.refresh], ['Réglages', WIc.key]].map(([t, I], i) => (
            <div key={i} style={{ padding: '16px 14px', borderRadius: 13, background: 'var(--rf-bg)',
              border: '1px solid var(--rf-line)' }}>
              <I s={20} c="var(--rf-blue)" />
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--rf-ink)', marginTop: 10 }}>{t}</div>
            </div>
          ))}
        </div>
      </div>
      {/* bouton scanner */}
      <div style={{ padding: `14px 20px ${PAD_BOT}px`, borderTop: '1px solid var(--rf-line)', background: '#fff' }}>
        <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', textAlign: 'center', marginBottom: 10 }}>
          ↙ Une demande d'identification vient d'arriver
        </div>
        <WBtn onClick={onScan}>Scanner un QR code</WBtn>
      </div>
    </div>
  );
}

// — SCANNER (fond sombre, statut blanc) —
function WScan() {
  return (
    <div style={{ height: '100%', background: '#0c0e14', position: 'relative', overflow: 'hidden' }}>
      {/* faux flux caméra */}
      <div style={{ position: 'absolute', inset: 0,
        background: 'radial-gradient(120% 80% at 50% 30%, #20242f 0%, #0c0e14 70%)' }} />
      <div style={{ position: 'absolute', top: PAD_TOP + 6, left: 0, right: 0, textAlign: 'center',
        color: '#fff', fontSize: 16, fontWeight: 700 }}>Scanner</div>
      <div style={{ position: 'absolute', top: PAD_TOP + 34, left: 0, right: 0, textAlign: 'center',
        color: 'rgba(255,255,255,.7)', fontSize: 13 }}>Placez le QR code dans le cadre</div>

      {/* cadre */}
      <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        width: 220, height: 220, borderRadius: 24 }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: 24,
          boxShadow: '0 0 0 2000px rgba(8,10,18,.55)' }} />
        {/* coins bleu france */}
        {[['top','left'],['top','right'],['bottom','left'],['bottom','right']].map(([v, hz], i) => (
          <div key={i} style={{ position: 'absolute', [v]: -2, [hz]: -2, width: 34, height: 34,
            borderTop: v === 'top' ? '4px solid var(--rf-scan)' : 'none',
            borderBottom: v === 'bottom' ? '4px solid var(--rf-scan)' : 'none',
            borderLeft: hz === 'left' ? '4px solid var(--rf-scan)' : 'none',
            borderRight: hz === 'right' ? '4px solid var(--rf-scan)' : 'none',
            borderRadius: v === 'top' && hz === 'left' ? '12px 0 0 0'
              : v === 'top' ? '0 12px 0 0' : hz === 'left' ? '0 0 0 12px' : '0 0 12px 0' }} />
        ))}
        {/* ligne de scan */}
        <div style={{ position: 'absolute', left: 10, right: 10, height: 2, borderRadius: 2,
          background: 'linear-gradient(90deg, transparent, var(--rf-scan), transparent)',
          boxShadow: '0 0 12px var(--rf-scan)', animation: 'scanline 1.4s ease-in-out infinite alternate' }} />
      </div>
      <div style={{ position: 'absolute', bottom: PAD_BOT + 10, left: 0, right: 0, textAlign: 'center',
        color: 'rgba(255,255,255,.55)', fontSize: 12.5 }}>
        Détection en cours…
      </div>
    </div>
  );
}

// — CONSENTEMENT —
function WConsent({ profile, claims, sharedKeys, toggleClaim, onAllow, onRefuse }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <div style={{ padding: `${PAD_TOP}px 20px 0` }}>
        <WRF scale={0.92} />
      </div>
      <div className="thin-scroll" style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', 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 */}
        <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(--rf-blue)', flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <WIc.bank s={20} c="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800, color: 'var(--rf-ink)' }}>Banque Démo</div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5,
              fontWeight: 700, color: 'var(--rf-ok)' }}>
              <WIc.check s={13} c="var(--rf-ok)" /> Destinataire vérifié
            </div>
          </div>
        </div>
        <div style={{ fontSize: 13, color: 'var(--rf-grey)', marginBottom: 6, lineHeight: 1.45 }}>
          souhaite accéder aux données suivantes pour&nbsp;:
          <strong style={{ color: 'var(--rf-ink)' }}> l'ouverture d'un compte bancaire</strong>.
        </div>

        {/* claims — les attributs optionnels (à votre choix) sont remontés en tête
            pour que la possibilité de partager ou non soit visible sans défiler */}
        {(() => {
          const optional = claims.filter(c => !c.required);
          const required = claims.filter(c => c.required);
          const Row = (c, i, last) => {
            const on = c.required || sharedKeys.includes(c.key);
            const val = c.isPhoto ? null : profile[c.key];
            return (
              <div key={c.key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
                borderBottom: last ? 'none' : '1px solid var(--rf-line)',
                opacity: on ? 1 : .5 }}>
                {c.isPhoto
                  ? <WIDPhoto hue={profile.hue} size={34} radius={6} />
                  : <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--rf-bg)', flexShrink: 0 }} />}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--rf-ink)' }}>{c.label}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', whiteSpace: 'nowrap', overflow: 'hidden',
                    textOverflow: 'ellipsis' }}>{c.isPhoto ? 'Portrait certifié' : String(val).replace('\n', ' · ')}</div>
                </div>
                {c.required
                  ? <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--rf-grey)',
                      background: 'var(--rf-bg)', padding: '3px 7px', borderRadius: 6 }}>Requis</span>
                  : <Toggle on={on} onClick={() => toggleClaim(c.key)} />}
              </div>
            );
          };
          const Caption = (txt) => (
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase',
              color: 'var(--rf-grey)', margin: '14px 0 6px' }}>{txt}</div>
          );
          return (
            <React.Fragment>
              {optional.length > 0 && (
                <React.Fragment>
                  {Caption('Vous choisissez de partager')}
                  <div style={{ borderRadius: 12, border: '1px solid var(--rf-line)', overflow: 'hidden' }}>
                    {optional.map((c, i) => Row(c, i, i === optional.length - 1))}
                  </div>
                </React.Fragment>
              )}
              {Caption('Toujours partagé')}
              <div style={{ borderRadius: 12, border: '1px solid var(--rf-line)', overflow: 'hidden' }}>
                {required.map((c, i) => Row(c, i, i === required.length - 1))}
              </div>
            </React.Fragment>
          );
        })()}
        <div style={{ fontSize: 11.5, color: 'var(--rf-grey)', marginTop: 12, lineHeight: 1.5, display: 'flex', gap: 8 }}>
          <WIc.lock s={26} c="var(--rf-grey)" />
          Vous ne partagez que les données cochées. Banque Démo ne reçoit pas votre code personnel et ne peut pas accéder à votre téléphone.
        </div>
      </div>
      {/* actions */}
      <div style={{ padding: `12px 20px ${PAD_BOT}px`, borderTop: '1px solid var(--rf-line)', display: 'flex',
        flexDirection: 'column', gap: 4 }}>
        <WBtn onClick={onAllow}>Autoriser le partage</WBtn>
        <WBtnText onClick={onRefuse}>Refuser</WBtnText>
      </div>
    </div>
  );
}
function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} style={{ width: 42, height: 25, borderRadius: 999, border: 'none', padding: 2,
      cursor: 'pointer', background: on ? 'var(--rf-ok)' : '#cdd0da', transition: 'background .18s', flexShrink: 0 }}>
      <span style={{ display: 'block', width: 21, height: 21, borderRadius: '50%', background: '#fff',
        transform: on ? 'translateX(17px)' : 'translateX(0)', transition: 'transform .18s',
        boxShadow: '0 1px 3px rgba(0,0,0,.3)' }} />
    </button>
  );
}

// — CODE PERSONNEL —
function WAuth({ 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: `${PAD_TOP}px 24px ${PAD_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 }}>
          <WIc.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: 240, lineHeight: 1.45 }}>
          Saisissez votre code personnel ID Wallet pour signer le partage.
        </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>
      {/* pavé numérique */}
      <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 => <Key key={d} d={d} onPress={press} />)}
        <span />
        <Key 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 Key({ 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>
  );
}

// — PARTAGE EN COURS —
function WSharing() {
  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)' }}>Partage en cours…</div>
      <div style={{ fontSize: 13, color: 'var(--rf-grey)', marginTop: 4 }}>Signature et envoi sécurisé</div>
    </div>
  );
}

// — SUCCÈS —
function WSuccess() {
  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' }}>
          <WIc.check s={40} c="#fff" />
        </div>
      </div>
      <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--rf-ink)' }}>Partage réussi</div>
      <div style={{ fontSize: 14, color: 'var(--rf-grey)', marginTop: 8, maxWidth: 240, lineHeight: 1.5 }}>
        Vos données ont été transmises à <strong style={{ color: 'var(--rf-ink)' }}>Banque Démo</strong>.
        Reprenez sur votre ordinateur.
      </div>
    </div>
  );
}

// — OUVERTURE (deep link same-device) —
function WLaunch() {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', background: '#fff', padding: 30, textAlign: 'center' }}>
      <div style={{ marginBottom: 22 }}><WRF scale={1.5} /></div>
      <div style={{ position: 'relative', width: 52, height: 52, marginBottom: 18 }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '3px solid var(--rf-line)' }} />
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '3px solid var(--rf-blue)',
          borderTopColor: 'transparent', animation: 'spin .8s linear infinite' }} />
      </div>
      <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--rf-ink)' }}>Ouverture d'ID Wallet…</div>
      <div style={{ fontSize: 12.5, color: 'var(--rf-grey)', marginTop: 6, fontFamily: 'monospace' }}>openid4vp://</div>
    </div>
  );
}

function WalletApp(props) {
  const s = props.walletStage;
  if (s === 'launch')  return <WLaunch />;
  if (s === 'scan')    return <WScan />;
  if (s === 'consent') return <WConsent {...props} />;
  if (s === 'auth')    return <WAuth onDone={props.onAuthDone} />;
  if (s === 'sharing') return <WSharing />;
  if (s === 'success') return <WSuccess />;
  return <WIdle profile={props.profile} onScan={props.onScan} />;
}

Object.assign(window, { WalletApp });
