import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import "../scss/pages.scss";

const SUPEROAUTH_URL = import.meta.env.VITE_SUPEROAUTH_URL;

export default function Login() {
  const { user } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (user) navigate("/", { replace: true });
  }, [user, navigate]);

  const handleLogin = () => {
    const callbackUrl = `${window.location.origin}/callback`;
    window.location.href = `${SUPEROAUTH_URL}/api/v1/oauth/discord?redirectUrl=${encodeURIComponent(callbackUrl)}&tenantId=clickerz`;
  };

  return (
    <section>
      <div className="containererror">
        <h1>Connexion</h1>
        <p className="message">Connecte-toi pour sauvegarder ta progression.</p>
        <button className="btn-return" onClick={handleLogin} type="button">
          Se connecter avec SuperOAuth
        </button>
      </div>
    </section>
  );
}
