const FaceRegisterModal = ({ open, onClose, onRegistered }) => {
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  if (!open) return null;

  const onComplete = async (descriptor) => {
    setSaving(true);
    try {
      await api.face.register(descriptor);
      onRegistered?.();
      onClose?.();
    } catch (e) {
      if (e.status === 409) setError('Это лицо уже зарегистрировано у другого члена семьи.');
      else setError('Не удалось сохранить: ' + (e.message || e.status));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} width={520}>
      <div style={{ padding: 24 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 4 }}>
          <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', textTransform:'uppercase' }}>БЕЗОПАСНОСТЬ</div>
          <button type="button" onClick={onClose} style={{ background:'none', border:'none', color:'var(--fg-subtle)', cursor:'pointer' }}><IconClose size={18}/></button>
        </div>
        <h2 style={{ margin:'4px 0 6px', fontSize: 22, fontWeight: 600 }}>Настроить Face ID</h2>
        <p style={{ margin:'0 0 14px', color:'var(--fg-muted)', fontSize: 14, lineHeight: 1.5 }}>
          Медленно проведите взглядом по кругу — заполните все сектора. Нужно ~10 секунд.
        </p>
        {error && (
          <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13, marginBottom: 12 }}>{error}</div>
        )}
        <FaceScanCamera
          onComplete={onComplete}
          onCancel={onClose}
          onError={(msg)=> setError(msg)}
        />
        {saving && (
          <div style={{ marginTop: 12, fontSize: 13, color:'var(--fg-muted)', textAlign:'center' }}>Сохранение…</div>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { FaceRegisterModal });
