import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { setLocation } from "../slice/IpAddressSlice";

const IP_API_URL = process.env.NEXT_PUBLIC_IP_ADDRESS_API!;
const Location = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchLocation = async () => {
      try {
        const res = await fetch(IP_API_URL);

        // Check if response is not JSON
        const contentType = res.headers.get("content-type");
        if (!contentType || !contentType.includes("application/json")) {
          const text = await res.text(); // Get raw response text
          throw new Error(
            `Invalid response (not JSON): ${text.substring(0, 100)}`
          );
        }
        const data = await res.json();
        dispatch(
          setLocation({
            messageData: "Location fetched successfully",
            locationData: `${data.country}`,
            latitudeData: data.loc.split(",")[0],
            longitudeData: data.loc.split(",")[1],
          })
        );
      } catch {
        return null;
        // console.error("Failed to fetch location:", error);
      }
    };

    fetchLocation();
  }, [dispatch]);

  return <h2></h2>;
};

export default Location;
