// FOOTPASS Messenger v2 · Arrivée du coffre-fort (piste « plaque » validée au labo)
// Porte de chambre forte : la molette fait un tour complet, les pênes se rétractent,
// le monogramme FP s'enfonce · la porte ne pivote pas. Puis passage feutré vers le coffre.
// Plaque compacte gravée à l'identité (Pass = la clé) + accueil par prénom.
// Le Bonjour/Bonsoir suit l'heure LOCALE de l'appareil (fuseau horaire de la personne).
// Session : déverrouillé 25 min (localStorage fp_coffre_unlock) → ré-ouverture instantanée.
const { useState: useStateCV, useEffect: useEffectCV, useRef: useRefCV } = React;

window.fpCoffreUnlocked = function () {
  try { return Date.now() - (parseInt(localStorage.getItem('fp_coffre_unlock'), 10) || 0) < 25 * 60 * 1000; } catch (e) { return false; }
};

// Monogramme FOOTPASS (assets/logomark.svg, fond retiré)
const CavMark = ({ s = 44, c = 'rgba(174,178,186,0.9)' }) => (
  <svg width={s} height={s} viewBox="0 0 512 512" fill="none" aria-label="FOOTPASS">
    <g transform="translate(124.348,76.800) scale(0.477867)" fill={c}>
      <g transform="translate(0.000000,750.000000) scale(0.100000,-0.100000)">
        <path d="M625 6710 l600 -600 1502 0 1503 0 0 -1200 0 -1200 -1200 0 -1200 0 0 -1203 0 -1202 600 -600 600 -600 0 1202 0 1202 688 4 c602 3 696 5 757 20 240 58 417 152 579 308 176 168 281 347 344 584 l27 100 3 1293 3 1292 -601 0 -600 0 0 600 0 600 -2102 0 -2103 0 600 -600z"></path>
        <path d="M1059 5499 c-250 -36 -472 -146 -656 -322 -173 -166 -279 -347 -341 -582 l-26 -100 -3 -695 -4 -695 601 -600 600 -600 0 1203 0 1202 1200 0 1200 0 0 600 0 600 -1257 -1 c-692 -1 -1283 -5 -1314 -10z"></path>
      </g>
    </g>
  </svg>
);

// Guilloché · entrelacs fins, même langage que la carte Pass ID
const CavGuilloche = () => (
  <svg className="cav-guill" viewBox="0 0 326 206" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
    <g fill="none" stroke="currentColor" strokeWidth="0.5">
      {Array.from({ length: 22 }).map((_, i) => (
        <ellipse key={i} cx="163" cy="103" rx="150" ry="40" transform={`rotate(${(i * 180) / 22} 163 103)`}></ellipse>
      ))}
    </g>
  </svg>
);

const CavFaceId = ({ s = 19 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 8V6a3 3 0 013-3h2"></path>
    <path d="M16 3h2a3 3 0 013 3v2"></path>
    <path d="M21 16v2a3 3 0 01-3 3h-2"></path>
    <path d="M8 21H6a3 3 0 01-3-3v-2"></path>
    <path d="M8.5 9.3v1.2"></path>
    <path d="M15.5 9.3v1.2"></path>
    <path d="M12 9.3v3.4a1 1 0 01-1 1"></path>
    <path d="M8.8 16.1a4.6 4.6 0 006.4 0"></path>
  </svg>
);

// ── L'écran d'arrivée · rendu PAR-DESSUS le coffre ; s'estompe au passage ──
function CoffreArrivee({ onBack, onDone }) {
  const [phase, setPhase] = useStateCV('idle'); // idle → scan → act → enter
  const phaseRef = useRefCV('idle');
  const go = () => {
    if (phaseRef.current !== 'idle') return;
    phaseRef.current = 'scan';
    setPhase('scan');
    setTimeout(() => {
      phaseRef.current = 'act';
      setPhase('act');
      setTimeout(() => {
        phaseRef.current = 'enter';
        setPhase('enter');
        try { localStorage.setItem('fp_coffre_unlock', String(Date.now())); } catch (e) { /* ignore */ }
        setTimeout(() => { onDone && onDone(); }, 900);
      }, 950);
    }, 420);
  };
  // Face ID s'active automatiquement à l'arrivée (le bouton reste un déclencheur manuel immédiat)
  useEffectCV(() => {
    const t = setTimeout(go, 900);
    return () => clearTimeout(t);
  }, []);
  const me = window.FP_ME || {};
  const own = me.name || 'Alexandre Da Costa';
  const parts = own.trim().split(/\s+/).filter(Boolean);
  const disp = parts.length > 1 ? parts[0] + ' ' + parts.slice(1).join(' ').toLocaleUpperCase('fr') : own;
  const prenom = parts[0] || own;
  const h = new Date().getHours(); // heure locale de l'appareil · suit le fuseau horaire de la personne
  const salut = (h >= 6 && h < 18) ? TX('Bonjour') : TX('Bonsoir');
  const act = phase === 'act' || phase === 'enter';
  return (
    <div className={`cav ${act ? 'act' : ''} ${phase === 'enter' ? 'enter' : ''}`} data-screen-label="Arrivée coffre-fort">
      <FPStatusBar light />
      <div className="cav-head">
        <button className="pg-back" onClick={onBack} aria-label="Retour"><FPIcon.Back c="#EAEAEA" /></button>
        <span className="cav-brand"><b>FOOTPASS<sup>®</sup></b><em>{TX('Coffre-fort')}</em></span>
      </div>
      <div className="cav-mid">
        <div className="cav-hello">{salut}, {prenom}.</div>
        <div className="cav-doorwrap">
          <div className="cav-doorscene">
            <div className="cav-door">
              <div className="cav-doorring"></div>
              {Array.from({ length: 10 }, (_, i) => (
                <i key={i} className="cav-bolt" style={{ '--a': (i * 36) + 'deg', '--d': (i % 4) * 0.06 + 's' }}></i>
              ))}
              <div className="cav-ring"></div>
              <div className="cav-hub"><CavMark s={31} /></div>
            </div>
          </div>
          <span className="cav-bloom"></span>
        </div>
        <div className="cav-plate">
          <CavGuilloche />
          <span className="cav-sheen"></span>
          <span className="cav-sweep"></span>
          <i className="cav-frame"></i>
          <div className="cav-engraving">
            <div className="cav-k">{TX('Coffre-fort')}</div>
            <div className="cav-name">{disp}</div>
            <div className="cav-no">PASS N° {me.passNo || '2480 1196 0049'}</div>
          </div>
          <div className="cav-hallmark"><CavMark s={11} c="rgba(174,178,186,0.8)" /></div>
        </div>
        <p className="cav-sub">{TX('Ce qui est ici n’appartient qu’à vous.')}<b>{TX('Rien n’entre, rien ne sort, sans votre accord.')}</b></p>
      </div>
      <div className="cav-foot">
        <button className="cav-btn" disabled={phase !== 'idle'} onClick={go}>
          <CavFaceId s={19} /> {phase === 'idle' ? TX('Déverrouiller · Face ID') : phase === 'scan' ? TX('Reconnaissance…') : TX('Ouverture…')}
        </button>
      </div>
    </div>
  );
}

window.CoffreArrivee = CoffreArrivee;
