// Enkel modal där en inloggad användare kan byta sitt eget lösenord.
function ChangePassword({ open, onClose }) {
  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [error, setError] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [visa, setVisa] = React.useState(false);

  React.useEffect(() => {
    if (open) { setCurrentPassword(''); setNewPassword(''); setConfirm(''); setError(''); setDone(false); }
  }, [open]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (newPassword.length < 8) return setError('Nytt lösenord måste vara minst 8 tecken.');
    if (newPassword !== confirm) return setError('Lösenorden matchar inte.');
    setBusy(true);
    try {
      await api('/api/me/password', { method: 'POST', body: JSON.stringify({ currentPassword, newPassword }) });
      setDone(true);
    } catch (e) { setError(e.message || 'Kunde inte byta lösenord.'); }
    finally { setBusy(false); }
  };

  const fieldStyle = {
    display:'block', width:'100%', marginTop:4, fontSize:13, padding:'8px 10px',
    border:'1px solid var(--border-strong)', borderRadius:4, boxSizing:'border-box', fontFamily:'var(--font-sans)',
  };

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(0,54,95,.32)', zIndex:60,
      display:'flex', alignItems:'center', justifyContent:'center', padding:32,
    }}>
      <div role="dialog" aria-modal="true" aria-label="Byt lösenord" onClick={e => e.stopPropagation()} style={{
        width:'min(360px, 100%)', background:'#fff', borderRadius:8,
        boxShadow:'0 16px 48px rgba(0,54,95,.18)', padding:24, fontFamily:'var(--font-sans)',
      }}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
          <h2 style={{margin:0, fontFamily:'var(--font-serif)', fontWeight:500, fontSize:20, color:'var(--ulab-navy)'}}>Byt lösenord</h2>
          <button onClick={onClose} style={{background:'transparent', border:'none', cursor:'pointer', color:'var(--ulab-navy)'}}><Icon name="close" size={20}/></button>
        </div>
        {done ? (
          <div>
            <p style={{fontSize:13, color:'var(--ulab-navy)', lineHeight:1.6}}>Lösenordet är bytt. Nästa gång du loggar in använder du det nya — och har webbläsaren sparat det gamla, säg ja när den frågar om att uppdatera det.</p>
            <button onClick={onClose} style={{
              background:'var(--ulab-navy)', color:'#fff', border:'none', padding:'8px 14px',
              borderRadius:4, fontSize:13, fontWeight:600, cursor:'pointer',
            }}>Stäng</button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <label style={{display:'block', marginBottom:10, fontSize:12, fontWeight:600, color:'var(--ulab-navy)'}}>Nuvarande lösenord
              <input required type={visa ? 'text' : 'password'} autoComplete="current-password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} style={fieldStyle} />
            </label>
            <label style={{display:'block', marginBottom:10, fontSize:12, fontWeight:600, color:'var(--ulab-navy)'}}>Nytt lösenord
              <input required type={visa ? 'text' : 'password'} autoComplete="new-password" minLength={8} value={newPassword} onChange={e => setNewPassword(e.target.value)} style={fieldStyle} />
            </label>
            <label style={{display:'block', marginBottom:14, fontSize:12, fontWeight:600, color:'var(--ulab-navy)'}}>Upprepa nytt lösenord
              <input required type={visa ? 'text' : 'password'} autoComplete="new-password" minLength={8} value={confirm} onChange={e => setConfirm(e.target.value)} style={fieldStyle} />
            </label>
            <label style={{display:'inline-flex', alignItems:'center', gap:6, fontSize:12, color:'var(--fg-muted)', marginBottom:14, cursor:'pointer'}}>
              <input type="checkbox" checked={visa} onChange={e => setVisa(e.target.checked)} /> Visa lösenorden
            </label>
            {error && <div role="alert" style={{background:'#fdf0ee', border:'1px solid #eab5ac', color:'#8a3b30', borderRadius:4, padding:'9px 12px', fontSize:12.5, marginBottom:12}}>{error}</div>}
            <button type="submit" disabled={busy} style={{
              width:'100%', background:'var(--ulab-navy)', color:'#fff', border:'none',
              padding:'9px 14px', borderRadius:4, fontSize:13, fontWeight:600, cursor:'pointer',
            }}>{busy ? 'Sparar…' : 'Byt lösenord'}</button>
          </form>
        )}
      </div>
    </div>
  );
}
window.ChangePassword = ChangePassword;
