const { useState } = React;
const API_BASE_URL = window.location.protocol === "file:" || ["localhost", "127.0.0.1"].includes(window.location.hostname)
  ? "http://127.0.0.1:3001"
  : "";

function ResetPasswordApp() {
  const params = new URLSearchParams(window.location.search);
  const token = params.get("token") || "";
  const isRequestMode = !token;
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [resetDone, setResetDone] = useState(false);

  async function submitRequest(e) {
    e.preventDefault();
    setMessage("");
    setError("");
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/auth/forgot-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({ identifier }),
      });
      const data = await response.json().catch(() => ({}));
      setMessage(data.message || "Se os dados estiverem corretos, enviaremos um e-mail com instrucoes.");
    } catch (_) {
      setMessage("Se os dados estiverem corretos, enviaremos um e-mail com instrucoes.");
    } finally {
      setLoading(false);
    }
  }

  async function submitReset(e) {
    e.preventDefault();
    setMessage("");
    setError("");
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/auth/reset-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({ token, password, confirmPassword }),
      });
      const data = await response.json().catch(() => ({}));
      if (!response.ok || !data.ok) {
        setError(data.message || "Token invalido ou expirado.");
        return;
      }
      setMessage(data.message || "Senha alterada com sucesso.");
      setResetDone(true);
      setPassword("");
      setConfirmPassword("");
    } catch (_) {
      setError("Erro temporario. Tente novamente em instantes.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="app">
      <header className="header">
        <a href="index.html" className="brand">
          <BrandMark/>
          <div>
            <div className="brand-name">Pummel Tale</div>
            <span className="brand-tag">Season III - Awaken</span>
          </div>
        </a>
      </header>

      <main className="register-wrap auth-page-wrap">
        <form className="form-card auth-token-card" onSubmit={isRequestMode ? submitRequest : submitReset}>
          <div className="fc-corner tl"></div>
          <div className="fc-corner tr"></div>
          <div className="fc-corner bl"></div>
          <div className="fc-corner br"></div>

          <div className="form-eyebrow">// seguranca da conta</div>
          <h2>{isRequestMode ? "Esqueci minha senha" : "Redefinir senha"}</h2>
          <p className="login-sub">
            {isRequestMode ? "Informe seu usuario ou e-mail para receber instrucoes." : "Crie uma nova senha para sua conta."}
          </p>

          {isRequestMode ? (
            <div className="field-group">
              <div className="field-label"><span>E-mail ou usuario</span><span className="req">*</span></div>
              <div className="field-input-wrap">
                <input className="field-input" value={identifier} onChange={(e) => setIdentifier(e.target.value)} autoComplete="username" />
              </div>
            </div>
          ) : (
            <React.Fragment>
              <div className="password-hint">
                Use no minimo 8 caracteres, com pelo menos 1 letra e 1 numero. A confirmacao deve ser igual.
              </div>
              <div className="field-group">
                <div className="field-label"><span>Nova senha</span><span className="req">*</span></div>
                <div className="field-input-wrap">
                  <input className="field-input" type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" />
                </div>
              </div>
              <div className="field-group">
                <div className="field-label"><span>Confirmar nova senha</span><span className="req">*</span></div>
                <div className="field-input-wrap">
                  <input className="field-input" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} autoComplete="new-password" />
                </div>
              </div>
            </React.Fragment>
          )}

          {message && <div className="field-msg valid"><Icons.Verified/><span>{message}</span></div>}
          {error && <div className="field-msg error"><Icons.Alert/><span>{error}</span></div>}

          {resetDone ? (
            <div className="success-actions">
              <button
                className="btn btn-primary"
                type="button"
                onClick={() => window.dispatchEvent(new Event("open-login"))}
              >
                <span className="glint"></span>
                Entrar
              </button>
              <a className="btn btn-ghost" href="index.html">Inicio</a>
            </div>
          ) : (
            <div className="success-actions">
              <button className="btn btn-primary" type="submit" disabled={loading}>
                <span className="glint"></span>
                {loading ? "Enviando..." : (isRequestMode ? "Enviar instrucoes" : "Salvar nova senha")}
              </button>
              <a className="btn btn-ghost" href="index.html">Voltar</a>
            </div>
          )}
        </form>
      </main>
      {window.LoginModal && <window.LoginModal/>}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ResetPasswordApp/>);
