const ChangeChildPasswordModal = ({ open, onClose, onSuccess, child }) => {
  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) { setNext(''); setConfirm(''); setError(''); setSaving(false); }
  }, [open]);

  const submit = async (e) => {
    e?.preventDefault();
    setError('');
    if (next.length < 2) { setError('Пароль: минимум 2 символа'); return; }
    if (next !== confirm) { setError('Пароли не совпадают'); return; }
    setSaving(true);
    try {
      await api.changeChildPassword(child.id, next);
      onSuccess?.();
      onClose?.();
    } catch (err) {
      setSaving(false);
      if (err.status === 403) setError('Только родители могут менять пароль ребёнка');
      else if (err.status === 404) setError('Ребёнок не найден в этой семье');
      else setError('Ошибка: ' + (err.message || err.status));
    }
  };

  if (!open || !child) return null;

  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 6px', fontSize: 22, fontWeight: 600 }}>Пароль для {child.name}</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={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, { ChangeChildPasswordModal });
