const ChangePasswordModal = ({ open, onClose, onSuccess }) => {
  const [cur, setCur] = React.useState('');
  const [next, setNext] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (open) { setCur(''); setNext(''); setConfirm(''); setError(''); setSaving(false); }
  }, [open]);

  const submit = async (e) => {
    e?.preventDefault();
    setError('');
    if (cur.length < 6) { setError('Введите текущий пароль'); return; }
    if (next.length < 6) { setError('Новый пароль: минимум 6 символов'); return; }
    if (next !== confirm) { setError('Пароли не совпадают'); return; }
    setSaving(true);
    try {
      await api.changePassword(cur, next);
      onSuccess?.();
      onClose?.();
    } catch (err) {
      setSaving(false);
      if (err.status === 401) setError('Текущий пароль неверен');
      else setError('Ошибка: ' + (err.message || err.status));
    }
  };

  return (
    <Modal open={open} onClose={onClose} width={440}>
      <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 16px', fontSize: 22, fontWeight: 600 }}>Сменить пароль</h2>
        {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={cur} onChange={e=> setCur(e.target.value)} autoComplete="current-password"/>
          </div>
          <div>
            <Label>Новый пароль (мин. 6 символов)</Label>
            <Input leading={<IconLock size={16}/>} type="password" value={next} onChange={e=> setNext(e.target.value)} autoComplete="new-password"/>
          </div>
          <div>
            <Label>Повторите новый пароль</Label>
            <Input leading={<IconLock size={16}/>} type="password" value={confirm} onChange={e=> setConfirm(e.target.value)} autoComplete="new-password"/>
          </div>
        </div>
        <div style={{ display:'flex', gap: 8, marginTop: 20 }}>
          <Button variant="ghost" full type="button" onClick={onClose}>Отмена</Button>
          <Button variant="primary" full type="submit" disabled={saving} leading={saving ? null : <IconCheck size={14}/>}>
            {saving ? 'Сохраняем…' : 'Сохранить'}
          </Button>
        </div>
      </form>
    </Modal>
  );
};

Object.assign(window, { ChangePasswordModal });
