import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { getSession } from "./Services/others";

const useVisitLogger = (pricingData) => {
  const location = useLocation();
  const UserId = getSession("UserId");
  const AppId = getSession("AppId");

  useEffect(() => {
    const stored = JSON.parse(localStorage.getItem("visitLogFormat") || "null");

    const newVisit = {
      VisitTime: new Date().toISOString(),
      Location: location?.pathname
    };

    let updatedLog;

    if (stored) {
      const oldVisits = Array.isArray(stored.LocationVistDtl) ? stored.LocationVistDtl : [];

      updatedLog = {
        ...stored,
        PricingId: pricingData?.PricingId || stored.PricingId || null,
        LocationVistDtl: [...oldVisits, newVisit]
      };
    } else {
      updatedLog = {
        UserId,
        AppId,
        PricingId: pricingData?.PricingId || null,
        LocationVistDtl: [newVisit]
      };
    }

    localStorage.setItem("visitLogFormat", JSON.stringify(updatedLog));
  }, [location, pricingData]);
};

export default useVisitLogger;
