check if the useEffect is really necessary and edit for best practice "// Login.tsx
import "./Login.css";
import Cookies from "universal-cookie";
import PasswordInput from "../../components/passwordInput/PasswordInput";
import { motion } from "framer-motion";
import MobileAppSoon from "@/components/Icons/MobileAppSoon";
import { useDispatch, useSelector } from "react-redux";
import { useFormik } from "formik";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { login as loginAction } from "@/redux/authSlice";
import * as yup from "yup";
import { RootState } from "@/redux/store";
import GoBack from "@/components/Icons/GoBack";
import "lazysizes";
import "lazysizes/plugins/attrchange/ls.attrchange";
import { loginUser } from "@/lib/api";
import { loadSessionFromCookie } from "@/helper";
import { setUserSelection } from "@/redux/userTypeSlice";

const validationSchema = yup.object({
  email: yup
    .string()
    .email("Invalid email format")
    .required("Email is required"),
  password: yup.string().required("Password is required"),
});

export default function Login() {
  /** ─── short-circuit if a session already exists ─────────────────────── **/
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const isLogged = useSelector((s: RootState) => s.auth.isLoggedIn);

  const userSelection = useSelector(
    (state: RootState) => state.user.userSelection,
  );

  // console.log("userSelection: ", userSelection);

  useEffect(() => {
    console.log("STARTING RE-LOGIN");
    console.log("isLoggedIn: ", isLogged);
    if (isLogged) {
      navigate(`${userSelection === "CHARITY" ? "/dashboard-charity?section=home" : "/dashboard-donor?section=home"}`, { replace: true });
      return;
    }
    console.log("RE-LOGIN FROM isLoggedIn");
    const session = loadSessionFromCookie();
    if (session) {
      console.log("this is the problem");
      dispatch(loginAction(session));
      // navigate("/dashboard-charity", { replace: true });
    }
    console.log("COMPLETED RE-LOGIN");
  }, [dispatch, isLogged, navigate, userSelection]);
  /** ───────────────────────────────────────────────────────────────────── **/

  /* ---------- original login form logic ---------- */
  const cloud_route = import.meta.env.VITE_CLOUDINARY_ROUTE;
  const cookies = new Cookies();
  const [loginError, setLoginError] = useState("");
  const [rememberUser, setRememberUser] = useState(false);
  const { darkMode } = useSelector((state: RootState) => state.darkMode);

  const getHomeHref = () => {
    // 1) First check that we’re in “production” mode
    // 2) Then check that the current origin is exactly the app’s production origin
    if (
      process.env.NODE_ENV === "production" &&
      window.location.origin === "https://app.philanthrify.co.uk"
    ) {
      return "https://philanthrify.co.uk/home";
    }
    // Otherwise, just stay on “/”
    navigate(-1);
    //return "/";
  };

  const formik = useFormik({
    initialValues: { email: "", password: "" },
    validationSchema,
    onSubmit: async (values) => {
      try {
        const response = await loginUser(values);

        dispatch(
          loginAction({
            userId: response.id,
            token: response.token,
            firstname: response.firstname,
            lastname: response.lastname,
            email: response.email,
            bio: response.bio,
            introduction: response.introduction,
            avatarid: response.avatarid,
            charities: response.charities,
            projects: response.projects,
            userType: response.usertype,
            roles: response.roles,
          }),
        );

        // cookie: share across both hosts
        const exp = new Date(
          Date.now() + (rememberUser ? 14 : 1) * 60 * 60 * 1000,
        );
        cookies.set("jwt_authorisation", response.token, {
          expires: exp,
          path: "/",
          domain: ".philanthrify.co.uk",
          secure: process.env.NODE_ENV === "production",
          sameSite: "lax",
        });

        let destination = "";

        // Use Redux action instead of directly setting localStorage
        if (response.usertype === "DONOR & CHARITY") {
          destination = "/dashboard-charity?section=home";
          dispatch(setUserSelection("CHARITY")); // This will update both Redux and localStorage
        } else if (response.usertype === "DONOR") {
          destination = "/dashboard-donor?section=home";
          dispatch(setUserSelection("DONOR")); // This will update both Redux and localStorage
        } else if (response.usertype === "CHARITY") {
          destination = "/dashboard-charity?section=home";
          dispatch(setUserSelection("CHARITY"));
        } else {
          dispatch(setUserSelection(null)); // Clear selection for other user types
        }

        navigate(destination, { replace: true });
      } catch (err: any) {
        setLoginError(
          "There was an error during login: " + err?.response?.data?.message,
        );
      }
    },
  });

  return (
    <section className="grid h-screen w-full xl:grid-cols-2">
      <div className="relative flex h-full w-full bg-[#e0dfdf] dark:bg-[#15161D]">
        <div className="absolute left-5 top-5 z-50">
          <GoBack
            width={20}
            height={20}
            color={darkMode ? "white" : "#4E5051"}
            onClick={() => getHomeHref()}
          />
        </div>
        <motion.div
          initial={{ opacity: 0, x: -180 }}
          animate={{ opacity: 1, x: 0 }}
          className="login flex w-full items-center justify-center px-2 text-black/90 sm:px-4 dark:text-white"
        >
          <div className="w-full rounded-xl bg-[#f2f3f4] p-5 shadow-xl sm:w-96 dark:bg-[#181b24]">
            <div className="text-center">
              <h1 className="text-2xl">Sign in</h1>
              <h4 className="text-greyLight">Welcome back to Philanthrify!</h4>
            </div>
            <form onSubmit={formik.handleSubmit} className="login-form">
              <h5 className="text-sm">Email</h5>
              <input
                id="email"
                name="email"
                type="email"
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                value={formik.values.email}
                placeholder="Enter your email"
                className="w-full rounded-lg p-3 shadow-sm transition duration-200 placeholder:text-gray-400 focus:border-[#09864A] focus:outline-none focus:ring-2 focus:ring-[#09864A] dark:bg-[#333746] dark:placeholder:text-gray-500 dark:hover:dark:bg-[#1f2330b5]"
              />
              {formik.touched.email && formik.errors.email && (
                <div className="error-message text-sm" style={{ color: "red" }}>
                  {formik.errors.email}
                </div>
              )}
              <h5 className="text-sm" style={{ marginTop: "16px" }}>
                Password
              </h5>
              <PasswordInput
                value={formik.values.password}
                onChange={formik.handleChange}
              />
              {formik.touched.password && formik.errors.password && (
                <div className="error-message text-sm" style={{ color: "red" }}>
                  {formik.errors.password}
                </div>
              )}
              <div
                className="options-box"
                style={{ justifyContent: "space-between" }}
              >
                <div className="remember-me">
                  <div
                    title=""
                    className="toggle-button"
                    onClick={() => {
                      setRememberUser(!rememberUser);
                    }}
                    style={{ backgroundColor: rememberUser ? "#13d276" : "" }}
                  />
                  <h6
                    onClick={() => {
                      setRememberUser(!rememberUser);
                    }}
                    style={{ color: "#a4a6ad", fontWeight: "normal" }}
                  >
                    Remember me?
                  </h6>
                </div>
                <h6
                  className="cursor-pointer hover:opacity-90"
                  onClick={() => {
                    navigate("/forgot-password");
                  }}
                >
                  Forgot password
                </h6>
              </div>
              <button type="submit" className="login-button mt-4">
                Sign in
              </button>
              {loginError && <h6 style={{ color: "red" }}>{loginError}</h6>}
            </form>
            <div
              className="options-box"
              style={{ justifyContent: "center", marginBottom: "-24px" }}
            >
              <h5
                className="text-greyLight"
                onClick={() => {
                  navigate("/register");
                }}
              >
                Don't have an account?
              </h5>
              <h6
                className="cursor-pointer"
                onClick={() => {
                  navigate("/register");
                }}
                style={{ marginLeft: "12px" }}
              >
                Register
              </h6>
            </div>

            <div className="mt-10 flex h-28 justify-center">
              <MobileAppSoon
                width={250}
                height={112}
                color={darkMode ? "#828388" : "#000000"}
              />
            </div>
          </div>
        </motion.div>
      </div>

      <div className="hidden h-full w-full xl:block">
        <img
          className="lazyload h-full w-full object-cover"
          data-src={`${cloud_route}/v1733135080/site_images/general/make-a-change_mzwhqa.jpg?c_scale&,f_auto,q_auto`}
          data-srcset={`
            ${cloud_route}/v1733135080/site_images/general/make-a-change_mzwhqa.jpg?f_auto,q_auto,c_scale,w_800 800w,
            ${cloud_route}/v1733135080/site_images/general/make-a-change_mzwhqa.jpg?f_auto,q_auto,c_scale,w_1200 1200w,
            ${cloud_route}/v1733135080/site_images/general/make-a-change_mzwhqa.jpg?f_auto,q_auto,c_scale,w_1600 1600w
          `}
          sizes="(max-width: 1200px) 800px, (max-width: 1600px) 1200px, 1600px"
          alt="make a change"
        />
      </div>
    </section>
  );
}
"