// FOOTPASS v2 · Photos vérifiées — Pass ID + profil.
// Les deux photos peuvent différer, chacune est vérifiée (visage — ou logo pour une structure).
// Réutilisé par l'onboarding (ObStepPhoto, après la vérification d'identité) et les Réglages (FpPhotoSheet).
const { useState: useStatePP, useEffect: useEffectPP } = React;

const FPPH_DEFAULT = 'assets/alex-avatar.png';

// Photos persistées → rattachées à l'identité (avatar partout + carte Pass ID)
(function () {
  try {
    const me = window.FP_ME; if (!me) return;
    const p = localStorage.getItem('fp_me_photo'); if (p) me.photo = p;
    const pp = localStorage.getItem('fp_me_passphoto'); me.passPhoto = pp || me.passPhoto || me.photo;
  } catch (e) { /* ignore */ }
})();

window.fpSetPhotos = function (opt) {
  const me = window.FP_ME || (window.FP_ME = {});
  if (opt.photo) me.photo = opt.photo;
  if (opt.passPhoto) me.passPhoto = opt.passPhoto;
  try {
    if (opt.photo) localStorage.setItem('fp_me_photo', opt.photo);
    if (opt.passPhoto) localStorage.setItem('fp_me_passphoto', opt.passPhoto);
  } catch (e) { /* ignore */ }
  window.dispatchEvent(new CustomEvent('fp:me', { detail: { photo: me.photo, passPhoto: me.passPhoto } }));
};

const PPI = {
  Cam: ({ s = 22 }) => (<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 8.5A1.5 1.5 0 015.5 7h1.8l1-1.6A1 1 0 019.1 5h5.8a1 1 0 01.85.4L16.7 7h1.8A1.5 1.5 0 0120 8.5v9A1.5 1.5 0 0118.5 19h-13A1.5 1.5 0 014 17.5v-9z"></path><circle cx="12" cy="12.5" r="3.2"></circle></svg>),
  Check: ({ s = 12 }) => (<svg width={s} height={s} viewBox="0 0 14 14" fill="none"><path d="M2.5 7.5L5.5 10.5L11.5 3.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"></path></svg>),
  Shield: ({ s = 13 }) => (<svg width={s} height={s} viewBox="0 0 14 16" fill="none"><path d="M7 1l5 2v4.2C12 11 9.6 13.5 7 14.6 4.4 13.5 2 11 2 7.2V3l5-2z" stroke="currentColor" strokeWidth="1.4"></path></svg>),
  Lock: ({ s = 12 }) => (<svg width={s} height={s} viewBox="0 0 16 16" fill="none"><rect x="3" y="7" width="10" height="7" rx="2" stroke="currentColor" strokeWidth="1.5"></rect><path d="M5 7V5a3 3 0 016 0v2" stroke="currentColor" strokeWidth="1.5"></path></svg>),
};

// Un emplacement photo : vide → capture simulée (vérification) → vérifiée
function FpPhotoSlot({ label, hint, src, isLogo, onCapture, onClear }) {
  const [state, setState] = useStatePP(src ? 'done' : 'empty'); // empty | scan | done
  useEffectPP(() => { setState(src ? 'done' : 'empty'); }, [src]);
  const capture = () => {
    if (state === 'scan') return;
    setState('scan');
    setTimeout(() => { setState('done'); onCapture && onCapture(FPPH_DEFAULT); }, 1150);
  };
  return (
    <div className="fpph-slot">
      <button type="button" className={`fpph-disc ${isLogo ? 'logo' : ''} state-${state}`} onClick={capture} aria-label={TX(label)}>
        {state === 'done' && src ? <img src={src} alt="" /> : null}
        {state === 'scan' ? (<React.Fragment><span className="fpph-oval"></span><span className="fpph-sweep"></span></React.Fragment>) : null}
        {state === 'empty' ? <span className="fpph-add"><PPI.Cam s={22} /></span> : null}
        {state === 'done' ? <span className="fpph-ok"><PPI.Check s={11} /></span> : null}
      </button>
      <div className="fpph-meta">
        <b>{TX(label)}</b>
        <em className={state === 'done' ? 'ok' : ''}>{state === 'scan' ? TX(isLogo ? 'Vérification du logo…' : 'Vérification du visage…') : state === 'done' ? TX(isLogo ? 'Logo vérifié' : 'Visage vérifié') : TX(hint)}</em>
      </div>
      {state === 'done' ? <button type="button" className="fpph-link" onClick={() => { setState('empty'); onClear && onClear(); }}>{TX('Reprendre')}</button> : <span className="fpph-link ph">{TX('Appareil photo ou galerie')}</span>}
    </div>
  );
}

// Studio : les deux photos + règle de vérification
function FpPhotoStudio({ value, onChange, isStructure }) {
  const v = value || {};
  const set = (patch) => { if (onChange) onChange(patch); };
  return (
    <div className="fpph">
      <div className="fpph-slots">
        <FpPhotoSlot label={isStructure ? 'Logo du Pass ID' : 'Photo du Pass ID'} hint="Officielle · sur votre carte" isLogo={isStructure} src={v.pass} onCapture={(u) => set({ pass: u })} onClear={() => set({ pass: null })} />
        <FpPhotoSlot label="Photo de profil" hint="Visible dans vos échanges" isLogo={isStructure} src={v.profile} onCapture={(u) => set({ profile: u })} onClear={() => set({ profile: null })} />
      </div>
      {v.pass && !v.profile ? <button type="button" className="fpph-same" onClick={() => set({ profile: v.pass })}><PPI.Check s={11} /> {TX('Utiliser aussi comme photo de profil')}</button> : null}
      <div className="fpph-rule">
        <span className="fpph-rule-ic"><PPI.Shield s={13} /></span>
        <span>{TX('Les deux photos peuvent être différentes. Chacune doit montrer votre visage — ou le logo, pour une structure — et sera vérifiée.')}</span>
      </div>
    </div>
  );
}

// ── Onboarding · étape « Photos » (après la vérification d'identité) ──
function ObStepPhoto({ ctx }) {
  const [photos, setPhotos] = useStatePP({ pass: null, profile: null });
  const both = photos.pass && photos.profile;
  const confirm = () => {
    if (!both) return;
    if (window.fpSetPhotos) window.fpSetPhotos({ photo: photos.profile, passPhoto: photos.pass });
    ctx.set('photo', photos.profile); ctx.set('passPhoto', photos.pass);
    ctx.openPortal();
  };
  return (
    <div className="ob-step" data-screen-label="Onboarding · Photos du profil">
      <div className="ob-body">
        <div className="ob-kicker accent">PHOTOS · PASS ID</div>
        <h1 className="ob-h1">{TX('Ajoutez vos photos')}</h1>
        <p className="ob-sub">{TX('Votre identité est vérifiée. Ajoutez la ')}<strong>{TX('photo de votre Pass ID')}</strong>{TX(' et votre ')}<strong>{TX('photo de profil')}</strong>.</p>
        <FpPhotoStudio value={photos} onChange={(patch) => setPhotos((p) => ({ ...p, ...patch }))} />
      </div>
      <div className="ob-foot">
        <button className="ob-cta" disabled={!both} onClick={confirm}>{TX('Confirmer mes photos')}</button>
        <div className="ob-note"><PPI.Lock /> {TX('Vos photos sont vérifiées, puis rattachées à votre Pass ID.')}</div>
      </div>
    </div>
  );
}

// ── Réglages · feuille « Photo de profil » (réutilise le socle PgSheet quand disponible) ──
function FpPhotoSheet({ onClose, showToast }) {
  const me = window.FP_ME || {};
  const [photos, setPhotos] = useStatePP({ pass: me.passPhoto || me.photo || null, profile: me.photo || null });
  const both = photos.pass && photos.profile;
  const save = () => {
    if (window.fpSetPhotos) window.fpSetPhotos({ photo: photos.profile || me.photo, passPhoto: photos.pass || me.passPhoto });
    if (showToast) showToast(TX('Photos mises à jour · vérification en cours'));
    if (onClose) onClose();
  };
  const body = (
    <React.Fragment>
      <FpPhotoStudio value={photos} onChange={(patch) => setPhotos((p) => ({ ...p, ...patch }))} />
      <div className="fpph-actions">
        <button className="fpph-btn ghost" onClick={onClose}>{TX('Annuler')}</button>
        <button className="fpph-btn" disabled={!both} onClick={save}>{TX('Enregistrer')}</button>
      </div>
    </React.Fragment>
  );
  const Sheet = window.PgSheet;
  if (Sheet) return <Sheet onClose={onClose} title="Photo de profil" centerTitle>{body}</Sheet>;
  return (
    <div className="fpph-sheetwrap">
      <div className="fpph-scrim" onClick={onClose}></div>
      <div className="fpph-sheet"><span className="fpph-grab"></span><div className="fpph-sheet-title">{TX('Photo de profil')}</div>{body}</div>
    </div>
  );
}

Object.assign(window, { FpPhotoStudio, FpPhotoSlot, ObStepPhoto, FpPhotoSheet });
