// LoginForm.jsx
function LoginForm() {
  const [values, setValues] = React.useState({ email: "", password: "", remember: false });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    try {
      const session = sessionStorage.getItem("mta_session") || localStorage.getItem("mta_session_persistent");
      if (session) window.location.hash = "#/dashboard";
    } catch {}
  }, []);

  const validate = () => {
    const e = {};
    const emailRe = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    if (!values.email) e.email = "Введите email";
    else if (!emailRe.test(values.email)) e.email = "Некорректный email";
    if (!values.password) e.password = "Введите пароль";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleChange = (field) => (ev) => {
    const val = field === "remember" ? ev.target.checked : ev.target.value;
    setValues((p) => ({ ...p, [field]: val }));
    setErrors((p) => ({ ...p, [field]: "" }));
  };

  const handleSubmit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setLoading(true);
    setTimeout(() => {
      try {
        const raw = localStorage.getItem("mta_profile");
        if (!raw) { setErrors({ email: "Профиль не найден. Зарегистрируйтесь." }); return; }
        let profile;
        try { profile = JSON.parse(raw); } catch { setErrors({ email: "Ошибка данных профиля." }); return; }
        if (!profile.password) { setErrors({ password: "У пользователя нет сохранённого пароля." }); return; }
        if (profile.email.toLowerCase() !== values.email.toLowerCase()) { setErrors({ email: "Email не совпадает." }); return; }
        if (profile.password !== values.password) { setErrors({ password: "Неверный пароль." }); return; }

        const session = { email: profile.email, name: profile.name || "", loggedAt: new Date().toISOString() };
        if (values.remember) localStorage.setItem("mta_session_persistent", JSON.stringify(session));
        sessionStorage.setItem("mta_session", JSON.stringify(session));
        window.location.hash = "#/dashboard";
      } finally {
        setLoading(false);
      }
    }, 300);
  };

  const handleForgot = () => {
    window.location.hash = '#/register';
    alert('Откройте форму восстановления на странице регистрации.');
  };

  return (
    <div style={{ maxWidth: 520, margin: '24px auto', color: '#e6eef8' }}>
      <h2 style={{ marginBottom: 8 }}>Вход</h2>
      <p style={{ marginTop: 0, color: '#9fb0c8' }}>Используйте email и пароль, указанные при регистрации</p>

      <form onSubmit={handleSubmit} style={{ marginTop: 12 }}>
        <div className="field">
          <input className="registration-input" placeholder="Email" type="email" value={values.email} onChange={handleChange("email")} autoComplete="username" />
          {errors.email && <p className="error-text">{errors.email}</p>}
        </div>

        <div className="field">
          <input className="registration-input" placeholder="Пароль" type="password" value={values.password} onChange={handleChange("password")} autoComplete="current-password" />
          {errors.password && <p className="error-text">{errors.password}</p>}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#cfe7ff', fontSize: 14 }}>
            <input type="checkbox" checked={values.remember} onChange={handleChange("remember")} />
            Запомнить меня
          </label>

          <button
            type="button"
            className="registration-button"
            style={{ background: "transparent", border: "none", color: "#7dd3fc" }}
            onClick={() => (window.location.hash = "#/reset")}
            > Забыли пароль?
          </button>
        </div>

        <div style={{ marginTop: 12 }}>
          <button className="registration-button" type="submit" disabled={loading} style={{ width: '100%' }}>
            {loading ? 'Входим...' : 'Войти'}
          </button>
        </div>
      </form>
    </div>
  );
}
