import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const TRACK_API = "http://openplate.my.id/api/visitor/track.php";

const getVisitorId = () => {
  let visitorId = localStorage.getItem("visitor_id");

  if (!visitorId) {
    if (window.crypto?.randomUUID) {
      visitorId = window.crypto.randomUUID();
    } else {
      visitorId = `visitor-${Date.now()}-${Math.random().toString(16).slice(2)}`;
    }

    localStorage.setItem("visitor_id", visitorId);
  }

  return visitorId;
};

const getRole = () => {
  const savedRole = localStorage.getItem("role") || "publik";

  // Masyarakat tidak perlu login, jadi statistiknya dihitung sebagai publik.
  if (savedRole === "masyarakat") return "publik";

  return savedRole;
};

export default function VisitorTracker() {
  const location = useLocation();

  useEffect(() => {
    const visitorId = getVisitorId();

    fetch(TRACK_API, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        visitor_id: visitorId,
        role: getRole(),
        page_url: `${location.pathname}${location.search}`,
      }),
    }).catch((err) => {
      console.warn("Gagal mencatat visitor:", err);
    });
  }, [location.pathname, location.search]);

  return null;
}
