// FOOTPASS v2 · sous-pages 1/2 : socle (page, feuille, toggle, QR) + Pass ID, Coffre-fort, Autorisations
const { useState: useStateP } = React;

// ── Socle : page plein écran avec retour ──
function PgPage({ title, subtitle, onBack, action, tabbar, children }) {
  return (
    <div className={`pg ${tabbar ? 'with-tabbar' : ''}`} data-screen-label={title}>
      <FPStatusBar light />
      <div className="pg-head">
        <button className="pg-back" onClick={onBack} aria-label="Retour"><FPIcon.Back c="#EAEAEA" /></button>
        {subtitle
          ? <span className="pg-titlewrap"><span className="pg-title2">{TX(title)}</span><em className="pg-sub2">{subtitle}</em></span>
          : <span className="pg-title">{TX(title)}</span>}
        {action || null}
      </div>
      <div className="pg-scroll">{children}</div>
    </div>
  );
}

// ── Socle : feuille modale ──
function PgSheet({ onClose, title, children, inChat, centerTitle }) {
  return (
    <div className={`pg-sheetwrap ${inChat ? 'in-chat' : ''}`}>
      <div className="pg-scrim" onClick={onClose}></div>
      <div className="pg-sheet">
        <span className="pg-grab"></span>
        {title ? <div className={`pg-sheet-title${centerTitle ? ' center' : ''}`}>{TX(title)}</div> : null}
        {children}
      </div>
    </div>
  );
}

function PgToggle({ on, onChange }) {
  return <button className={`pg-toggle ${on ? 'on' : ''}`} role="switch" aria-checked={on} onClick={() => onChange(!on)}></button>;
}

// ── QR déterministe (motifs de repère + modules pseudo-aléatoires seedés) ──
function FpQR({ size = 132, seed = 24801196 }) {
  const n = 25, q = 1; // modules + zone calme
  const cell = size / (n + q * 2);
  let s = seed >>> 0;
  const rnd = () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
  const inFinder = (x, y) =>
    (x < 8 && y < 8) || (x >= n - 8 && y < 8) || (x < 8 && y >= n - 8);
  const cells = [];
  for (let y = 0; y < n; y++) {
    for (let x = 0; x < n; x++) {
      if (inFinder(x, y)) continue;
      const timing = (x === 6 || y === 6) ? (x + y) % 2 === 0 : rnd() < 0.46;
      if (timing) cells.push([x, y]);
    }
  }
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-label="QR du Pass ID">
      <rect width={size} height={size} fill="#FDFDFB"></rect>
      {[[0, 0], [n - 7, 0], [0, n - 7]].map(([fx, fy]) => (
        <g key={`f${fx}-${fy}`}>
          <rect x={(fx + q) * cell} y={(fy + q) * cell} width={cell * 7} height={cell * 7} fill="#0F0F0F"></rect>
          <rect x={(fx + 1 + q) * cell} y={(fy + 1 + q) * cell} width={cell * 5} height={cell * 5} fill="#FDFDFB"></rect>
          <rect x={(fx + 2 + q) * cell} y={(fy + 2 + q) * cell} width={cell * 3} height={cell * 3} fill="#0F0F0F"></rect>
        </g>
      ))}
      {cells.map(([x, y]) => (
        <rect key={`${x}.${y}`} x={(x + q) * cell} y={(y + q) * cell} width={cell * 0.92} height={cell * 0.92} fill="#0F0F0F"></rect>
      ))}
    </svg>
  );
}

// ═══════ MON PASS ID ═══════
function PassIdPage({ onBack, showToast }) {
  const me = FP_ME;
  // Structure (créée ou rejointe depuis l'Accueil) · s'affiche sur la carte et dans les détails
  const st = (window.fpGetStructure && window.fpGetStructure()) || null;
  const copy = (txt, msg) => {
    try { navigator.clipboard && navigator.clipboard.writeText(txt); } catch (e) { /* ignore */ }
    showToast(msg);
  };
  return (
    <PgPage title="Mon Pass ID" onBack={onBack}>
      <div className="pg-cardwrap">
        <ObPassCard name={me.name} role={me.role} org={st ? st.name : null} orgMissing="INDEPENDENT" clubLabel="Structure" photo={me.passPhoto || me.photo} verified gold shimmer />
      </div>
      <div className="pg-qrtile">
        <FpQR />
        <span className="pg-qrnum">{me.passNo}</span>
        <span className="pg-qrhint">{TX('Présentez ce code pour prouver votre identité.')}<br />{TX('Il se renouvelle toutes les 60 secondes.')}</span>
      </div>
      <div className="pg-actions">
        <button className="pg-btn primary" onClick={() => copy(me.passLink, TX('Lien copié · ') + me.passLink)}>{TX('Partager mon Pass')}</button>
        <button className="pg-btn" onClick={() => copy(me.passNo, TX('Numéro copié'))}>{TX('Copier le numéro')}</button>
      </div>
      <div className="hm-sechead"><span>{TX('Détails')}</span></div>
      <div className="pg-info">
        <div className="pg-inforow"><span>{TX('Statut')}</span><b className="ok"><FPIcon.Shield s={11} /> {TX('Vérifié')}</b></div>
        <div className="pg-inforow"><span>{TX('Titulaire')}</span><b>{window.fpUpperLast(me.name)}</b></div>
        <div className="pg-inforow"><span>{TX('Rôle certifié')}</span><b>{TX(me.role)}</b></div>
        <div className="pg-inforow"><span>{TX('Structure')}</span>{st
          ? <b>{st.name}</b>
          : <button className="pg-rowact warn" onClick={() => window.dispatchEvent(new CustomEvent('fp:growth', { detail: { kind: 'sheet', sheet: 'structure' } }))}>{TX('Ajouter · créer ou rejoindre')} ›</button>}</div>
        <div className="pg-inforow"><span>{TX('Émis le')}</span><b>{TX('13 juin 2026')}</b></div>
        <div className="pg-inforow"><span>{TX('Expire le')}</span><b>{TX('12 juin 2029')}</b></div>
        <div className="pg-inforow"><span>{TX('Formule')}</span><b>{TX("PassPRO · essai jusqu'au 23 juin")}</b></div>
        {st && st.kind !== 'joined' ? <div className="pg-inforow"><span>{TX('Formule structure')}</span><b>{TX('Palier')} {st.tier || 'Small'} · {TX('vérification en cours')}</b></div> : null}
      </div>
      <div className="hm-listfoot"><FPIcon.Shield s={10} /> {TX('Clés conservées sur cet appareil · jamais sur nos serveurs')}</div>
    </PgPage>
  );
}

// ═══════ COFFRE-FORT ═══════
// Intérieur = organisation « tableau de bord » (v2/coffre-v3.jsx) · l'arrivée (porte + plaque,
// Face ID auto) est TOUJOURS montrée à l'entrée du coffre, par-dessus l'intérieur.
function VaultPage({ onBack, showToast, dark }) {
  const [locked, setLocked] = useStateP(true);
  const relock = () => {
    try { localStorage.setItem('fp_coffre_unlock', '0'); } catch (e) { /* ignore */ }
    setLocked(true);
  };
  return (
    <React.Fragment>
    <CoffreV3 onBack={onBack} dark={dark} onLock={relock} />
    {locked && window.CoffreArrivee ? <window.CoffreArrivee onBack={onBack} onDone={() => setLocked(false)} /> : null}
    </React.Fragment>
  );
}

function DocSheet({ doc, onClose, showToast }) {
  return (
    <PgSheet onClose={onClose} title={doc.title}>
      <div className="pg-info">
        <div className="pg-inforow"><span>{TX('État')}</span><b>{TX(doc.meta)}</b></div>
        <div className="pg-inforow"><span>{TX('Taille')}</span><b>{doc.size}</b></div>
        <div className="pg-inforow"><span>{TX('Empreinte')}</span><b className="pg-mono">{doc.hash}</b></div>
        <div className="pg-inforow"><span>{TX('Chiffrement')}</span><b className="ok"><FPIcon.Shield s={11} /> AES-256 · E2EE</b></div>
      </div>
      <div className="pg-sheet-actions">
        <button className="pg-btn primary" onClick={() => { showToast(TX('Document déchiffré et ouvert')); onClose(); }}>{TX('Ouvrir le document')}</button>
        <button className="pg-btn" onClick={() => { showToast(TX('Lien sécurisé copié · expire dans 24 h')); onClose(); }}>{TX('Partager un lien sécurisé')}</button>
      </div>
    </PgSheet>
  );
}

// (Autorisations : la page vit dans mandats.jsx · doublon historique supprimé · audit P2-4)

Object.assign(window, { PgPage, PgSheet, PgToggle, FpQR, PassIdPage, VaultPage, DocSheet });
