import { useRouteLoaderData } from "@remix-run/react";
import { loader as rootLoader } from "../root";

/**
 * Custom hook to access all data from the root loader
 * @returns all data from the root loader including user, lang, theme, etc.
 */
export function useRootData() {
  const rootData = useRouteLoaderData<typeof rootLoader>("root");
  return {
    user: rootData?.user,
    lang: rootData?.lang,
    theme: rootData?.theme,
  };
}

// Hook to get auth token from root data
export const useAuthToken = () => {
  const rootData = useRootData();
  // Check for valid token and remove extra quotes
  const token = rootData?.user?.access_token;
  if (!token) return undefined;

  // Remove extra quotes that might be surrounding the token
  return token.replace(/^["'](.*)["']$/, "$1");
};
