// src/components/Auth/Auth.tsx
import {
  createContext,
  useContext,
  useEffect,
  useState,
  useCallback,
  useMemo as useMemo2
} from "react";
import { useLocation as useLocation2, Navigate } from "react-router-dom";

// src/components/Auth/useTokenInUrl.ts
import { useMemo } from "react";
import { useLocation } from "react-router-dom";
function useTokenInUrl() {
  const location = useLocation();
  const hasTokenInUrl = useMemo(() => {
    const searchParams = new URLSearchParams(location.search);
    const token = searchParams.get("token");
    const refreshToken = searchParams.get("refreshToken");
    const sessionId = searchParams.get("sessionId");
    return !!(token && refreshToken && sessionId);
  }, [location.search]);
  return { hasTokenInUrl };
}

// src/components/Auth/Auth.tsx
import { Fragment, jsx } from "react/jsx-runtime";
var AuthContext = createContext(void 0);
var AuthProvider = ({
  children,
  checkAuthFn,
  signOutFn,
  initialAuthState = {},
  getUserFn,
  getSessionFn,
  getTokensFn
}) => {
  const [authState, setAuthState] = useState({
    isAuthenticated: false,
    isLoading: true,
    ...initialAuthState
  });
  const checkAuth = useCallback(async () => {
    try {
      setAuthState((prev) => ({ ...prev, isLoading: true }));
      if (!checkAuthFn) {
        setAuthState((prev) => ({
          ...prev,
          isAuthenticated: false,
          isLoading: false
        }));
        return false;
      }
      const isAuth = await checkAuthFn();
      setAuthState((prev) => ({
        ...prev,
        isAuthenticated: isAuth,
        isLoading: false,
        user: getUserFn ? getUserFn() : prev.user,
        sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,
        tokens: getTokensFn ? getTokensFn() : prev.tokens
      }));
      return isAuth;
    } catch (error) {
      console.error("Erro ao verificar autentica\xE7\xE3o:", error);
      setAuthState((prev) => ({
        ...prev,
        isAuthenticated: false,
        isLoading: false
      }));
      return false;
    }
  }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);
  const signOut = useCallback(() => {
    if (signOutFn) {
      signOutFn();
    }
    setAuthState((prev) => ({
      ...prev,
      isAuthenticated: false,
      user: void 0,
      sessionInfo: void 0,
      tokens: void 0
    }));
  }, [signOutFn]);
  useEffect(() => {
    checkAuth();
  }, [checkAuth]);
  const contextValue = useMemo2(
    () => ({
      ...authState,
      checkAuth,
      signOut
    }),
    [authState, checkAuth, signOut]
  );
  return /* @__PURE__ */ jsx(AuthContext.Provider, { value: contextValue, children });
};
var useAuth = () => {
  const context = useContext(AuthContext);
  if (context === void 0) {
    throw new Error("useAuth deve ser usado dentro de um AuthProvider");
  }
  return context;
};
var ProtectedRoute = ({
  children,
  redirectTo = "/",
  loadingComponent,
  additionalCheck
}) => {
  const { isAuthenticated, isLoading, ...authState } = useAuth();
  const defaultLoadingComponent = /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ jsx("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
  if (isLoading) {
    return /* @__PURE__ */ jsx(Fragment, { children: loadingComponent || defaultLoadingComponent });
  }
  if (!isAuthenticated) {
    if (typeof window !== "undefined") {
      const rootDomain = getRootDomain();
      const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ":" + window.location.port : ""}`;
      if (rootDomain !== currentLocation) {
        window.location.href = rootDomain;
        return null;
      }
    }
    return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
  }
  if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
    return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
  }
  return /* @__PURE__ */ jsx(Fragment, { children });
};
var PublicRoute = ({
  children,
  redirectTo = "/painel",
  redirectIfAuthenticated = false,
  checkAuthBeforeRender = false,
  tokenValidationComponent
}) => {
  const { isAuthenticated, isLoading } = useAuth();
  const { hasTokenInUrl } = useTokenInUrl();
  if (hasTokenInUrl && tokenValidationComponent) {
    return /* @__PURE__ */ jsx(Fragment, { children: tokenValidationComponent });
  }
  if (checkAuthBeforeRender && isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ jsx("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
  }
  if (isAuthenticated && redirectIfAuthenticated) {
    return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
  }
  return /* @__PURE__ */ jsx(Fragment, { children });
};
var withAuth = (Component, options = {}) => {
  return (props) => /* @__PURE__ */ jsx(ProtectedRoute, { ...options, children: /* @__PURE__ */ jsx(Component, { ...props }) });
};
var useAuthGuard = (options = {}) => {
  const authState = useAuth();
  const { requireAuth = true, customCheck } = options;
  const canAccess = !authState.isLoading && (requireAuth ? authState.isAuthenticated && (!customCheck || customCheck(authState)) : !authState.isAuthenticated || !customCheck || customCheck(authState));
  return {
    canAccess,
    isLoading: authState.isLoading,
    authState
  };
};
var useRouteAuth = (fallbackPath = "/") => {
  const { isAuthenticated, isLoading } = useAuth();
  const location = useLocation2();
  const redirectToLogin = () => /* @__PURE__ */ jsx(Navigate, { to: fallbackPath, state: { from: location }, replace: true });
  return {
    isAuthenticated,
    isLoading,
    redirectToLogin
  };
};
var getRootDomain = () => {
  const { hostname, protocol, port } = window.location;
  const portStr = port ? ":" + port : "";
  if (hostname === "localhost") {
    return `${protocol}//${hostname}${portStr}`;
  }
  const isIPv4 = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname);
  const isIPv6 = hostname.includes(":");
  if (isIPv4 || isIPv6) {
    return `${protocol}//${hostname}${portStr}`;
  }
  const parts = hostname.split(".");
  const isHml = hostname.includes("hml");
  if (parts.length >= 3 && parts[parts.length - 2] === "com" && parts[parts.length - 1] === "br") {
    if (parts.length === 3) {
      return `${protocol}//${hostname}${portStr}`;
    }
    const base = parts.slice(-3).join(".");
    if (isHml) {
      return `${protocol}//hml.${base}${portStr}`;
    }
    return `${protocol}//${base}${portStr}`;
  }
  if (parts.length > 2) {
    const base = parts.slice(-2).join(".");
    if (isHml) {
      return `${protocol}//hml.${base}${portStr}`;
    }
    return `${protocol}//${base}${portStr}`;
  }
  return `${protocol}//${hostname}${portStr}`;
};
var Auth_default = {
  AuthProvider,
  ProtectedRoute,
  PublicRoute,
  withAuth,
  useAuth,
  useAuthGuard,
  useRouteAuth
};
export {
  AuthProvider,
  ProtectedRoute,
  PublicRoute,
  Auth_default as default,
  getRootDomain,
  useAuth,
  useAuthGuard,
  useRouteAuth,
  withAuth
};
//# sourceMappingURL=index.mjs.map