const ChangeEmailModal = ({ open, onClose, onSuccess, initialEmail }) => {
  const [pw, setPw] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (open) { setPw(''); setEmail(initialEmail || ''); setError(''); setSaving(false); }
  }, [open]);

  const submit = async (e) => {
    e?.preventDefault();
    setError('');
    if (pw.length < 6) { setError('Введите текущий пароль'); return; }
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      setError('Некорректный email'); return;
    }
    setSaving(true);
    try {
      await api.changeEmail(pw, email.trim());
      onSuccess?.();
      onClose?.();
    } catch (err) {
      setSaving(false);
      if (err.status === 401) setError('Пароль неверен');
      else setError('Ошибка: ' + (err.message || err.status));
    }
  };

  const clearEmail = async () => {
    setError('');
    if (pw.length < 6) { setError('Введите текущий пароль, чтобы удалить email'); return; }
    setSaving(true);
    try {
      await api.changeEmail(pw, '');
      onSuccess?.();
      onClose?.();
    } catch (err) {
      setSaving(false);
      if (err.status === 401) setError('Пароль неверен');
      else setError('Ошибка: ' + (err.message || err.status));
    }
  };

  return (
    <Modal open={open} onClose={onClose} width={460}>
      <form onSubmit={submit} 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 }}>Email для восстановления</h2>
        <p style={{ margin:'0 0 14px', color:'var(--fg-muted)', fontSize: 13, lineHeight: 1.5 }}>
          Нужен только для восстановления пароля. На него придёт письмо со ссылкой.
        </p>
        {error && <div style={{ padding: 10, borderRadius: 10, background:'#FBE1DA', color:'#9A3218', fontSize: 13, marginBottom: 12 }}>{error}</div>}
        <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          <div>
            <Label>Текущий пароль</Label>
            <Input leading={<IconLock size={16}/>} type="password" value={pw} onChange={e=> setPw(e.target.value)} autoComplete="current-password"/>
          </div>
          <div>
            <Label>Email</Label>
            <Input leading={<IconMail size={16}/>} type="email" placeholder="name@example.com" value={email} onChange={e=> setEmail(e.target.value)} autoComplete="email"/>
          </div>
        </div>
        <div style={{ display:'flex', gap: 8, marginTop: 20, flexWrap:'wrap' }}>
          <Button variant="ghost" type="button" onClick={onClose}>Отмена</Button>
          {initialEmail && (
            <Button variant="danger" type="button" onClick={clearEmail} disabled={saving}>Удалить</Button>
          )}
          <Button variant="primary" full type="submit" disabled={saving} leading={saving ? null : <IconCheck size={14}/>}>
            {saving ? 'Сохраняем…' : 'Сохранить'}
          </Button>
        </div>
      </form>
    </Modal>
  );
};

Object.assign(window, { ChangeEmailModal });
