// RegistrationForm.jsx
function RegistrationForm() {
  const [form, setForm] = React.useState({
    name: "",
    email: "",
    role: "",
    license: "",
    specialization: "",
    password: "",
    wallet: "",
    emailCode: ""
  });

  const [errors, setErrors] = React.useState({});
  const [passwordStrength, setPasswordStrength] = React.useState("");
  const [generatedCode, setGeneratedCode] = React.useState("");
  const [emailVerified, setEmailVerified] = React.useState(false);
  const [timer, setTimer] = React.useState(0);
  const domainSuggestions = ["gmail.com","yandex.ru","mail.ru","outlook.com","med.clinic","hospital.org","doctor.edu","health.center"];
  const [suggestions, setSuggestions] = React.useState([]);

  React.useEffect(() => {
    if (timer <= 0) return;
    const t = setTimeout(() => setTimer((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [timer]);

  const update = (field, value) => {
    setForm((p) => ({ ...p, [field]: value }));
    validateField(field, value);
    if (field === "password") evaluatePasswordStrength(value, setPasswordStrength);
    if (field === "email") updateEmailSuggestions(value);
  };

  const updateEmailSuggestions = (value) => {
    if (!value.includes("@")) { setSuggestions([]); return; }
    const [local, domainPart] = value.split("@");
    if (!domainPart) { setSuggestions(domainSuggestions); return; }
    setSuggestions(domainSuggestions.filter((d) => d.startsWith(domainPart)));
  };

  const validateField = (field, value) => {
    let msg = "";
    const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    if (field === "email") {
      if (!value) msg = "Введите email";
      else if (!emailRegex.test(value)) msg = "Некорректный формат email";
    }
    if (field === "password") {
      if (value.length < 8) msg = "Минимум 8 символов";
      else if (!/[0-9]/.test(value)) msg = "Пароль должен содержать цифру";
      else if (!/[A-Za-z]/.test(value)) msg = "Пароль должен содержать букву";
    }
    if (field === "role" && !value) msg = "Выберите статус";
    if (field === "license" && form.role === "doctor") {
      const licenseRegex = /^[A-Za-z0-9]{6,}$/;
      if (!licenseRegex.test(value)) msg = "Минимум 6 символов, только буквы и цифры";
    }
    setErrors((prev) => ({ ...prev, [field]: msg }));
  };

  const evaluatePasswordStrength = (password, setter) => {
    let score = 0;
    if (password.length >= 8) score++;
    if (/[A-Z]/.test(password)) score++;
    if (/[0-9]/.test(password)) score++;
    if (/[^A-Za-z0-9]/.test(password)) score++;
    if (score <= 1) setter("weak");
    else if (score <= 3) setter("medium");
    else setter("strong");
  };

  const sendEmailCode = () => {
    if (errors.email || !form.email) return;
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    setGeneratedCode(code);
    setTimer(60);
    console.log("Код подтверждения email:", code);
    alert("Код отправлен на email (в демо выводится в консоль)");
  };

  const verifyEmailCode = () => {
    if (form.emailCode === generatedCode && generatedCode) {
      setEmailVerified(true);
      alert("Email подтверждён");
    } else {
      alert("Неверный код");
    }
  };

  const isFormValid = () => {
    const licenseValid = form.role !== "doctor" || (form.license && !errors.license);
    return form.name && form.email && form.password && form.role && licenseValid && emailVerified && !errors.email && !errors.password && !errors.role;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!isFormValid()) return;
    const profile = {
      name: form.name,
      email: form.email,
      role: form.role,
      license: form.license,
      specialization: form.specialization,
      wallet: form.wallet,
      // В демо сохраняем пароль в профиле (не делайте так в продакшене)
      password: form.password
    };
  try {
  localStorage.setItem("mta_profile", JSON.stringify(profile));
  // уведомляем приложение в той же вкладке
  window.dispatchEvent(new Event('mta_profile_updated'));
  // затем переходим в кабинет
  window.location.hash = "#/dashboard";
} catch (e) {
  console.error("Не удалось сохранить профиль:", e);
  alert("Ошибка при сохранении профиля. Попробуйте ещё раз.");
}
  };

  return (
    <div className="registration-container" style={{ maxWidth: 720, margin: '24px auto' }}>
      <h1 className="registration-title">Регистрация</h1>
      <form className="registration-form" onSubmit={handleSubmit}>
        <div className="field">
          <input className="registration-input" placeholder="Email" type="email" value={form.email} onChange={(e) => update("email", e.target.value)} />
          {errors.email && <p className="error-text">{errors.email}</p>}
          {suggestions.length > 0 && (
            <div className="email-suggestions">
              {suggestions.map((d) => (
                <div key={d} className="suggestion-item" onClick={() => { update("email", form.email.split("@")[0] + "@" + d); setSuggestions([]); }}>
                  {form.email.split("@")[0] + "@" + d}
                </div>
              ))}
            </div>
          )}
        </div>

        <button type="button" className="registration-button" disabled={!!errors.email || !form.email || timer > 0} onClick={sendEmailCode}>
          {timer > 0 ? `Отправить снова через ${timer}с` : "Отправить код"}
        </button>

        <div className="field">
          <input className="registration-input" placeholder="Код подтверждения" value={form.emailCode} onChange={(e) => update("emailCode", e.target.value)} />
        </div>

        <button type="button" className="registration-button" style={{ background: emailVerified ? "#16a34a" : "#334155" }} onClick={verifyEmailCode}>
          {emailVerified ? "Email подтверждён" : "Подтвердить email"}
        </button>

        <div className="field">
          <input className="registration-input" placeholder="Ваше имя" value={form.name} onChange={(e) => update("name", e.target.value)} />
        </div>

        <div className="field">
          <select className="registration-input" value={form.role} onChange={(e) => update("role", e.target.value)}>
            <option value="">Выберите статус</option>
            <option value="student">Студент</option>
            <option value="doctor">Врач</option>
            <option value="other">Другое</option>
          </select>
          {errors.role && <p className="error-text">{errors.role}</p>}
        </div>

        {form.role === "doctor" && (
          <div className="field">
            <input className="registration-input" placeholder="Номер медицинской лицензии" value={form.license} onChange={(e) => update("license", e.target.value)} />
            {errors.license && <p className="error-text">{errors.license}</p>}
          </div>
        )}

        <div className="field">
          <input className="registration-input" placeholder="Специализация" value={form.specialization} onChange={(e) => update("specialization", e.target.value)} />
        </div>

        <div className="field">
          <input className="registration-input" placeholder="Пароль" type="password" value={form.password} onChange={(e) => update("password", e.target.value)} />
          {form.password && <div className={`password-strength ${passwordStrength}`}>{passwordStrength === "weak" ? "Слабый пароль" : passwordStrength === "medium" ? "Средний пароль" : "Сильный пароль"}</div>}
          {errors.password && <p className="error-text">{errors.password}</p>}
        </div>

        <div className="field">
          <input className="registration-input" placeholder="Адрес криптокошелька (опционально)" value={form.wallet} onChange={(e) => update("wallet", e.target.value)} />
        </div>

        <button className="registration-button" type="submit" disabled={!isFormValid()}>Зарегистрироваться</button>
      </form>
    </div>
  );
}
