function VisitorTracker() {
  React.useEffect(() => {
    let cancelled = false;

    const getSessionId = () => {
      const key = "discover_visitor_session_id";
      let id = sessionStorage.getItem(key);
      if (!id) {
        id = (window.crypto && crypto.randomUUID)
          ? crypto.randomUUID()
          : "sess_" + Date.now() + "_" + Math.random().toString(16).slice(2);
        sessionStorage.setItem(key, id);
      }
      return id;
    };

    const getIp = async () => {
      try {
        const resp = await fetch("https://api.ipify.org?format=json", { cache: "no-store" });
        if (!resp.ok) return null;
        const data = await resp.json();
        return data.ip || null;
      } catch (_) {
        return null;
      }
    };

    const track = async () => {
      if (!window.DiscoverSupabase || typeof window.DiscoverSupabase.insertVisitorEvent !== "function") {
        return;
      }

      const payload = {
        session_id: getSessionId(),
        page_path: window.location.pathname + window.location.hash,
        page_url: window.location.href,
        referrer: document.referrer || null,
        user_agent: navigator.userAgent,
        language: navigator.language || null,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null,
        screen_width: window.screen.width,
        screen_height: window.screen.height,
        ip_address: await getIp(),
      };

      if (cancelled) return;
      await window.DiscoverSupabase.insertVisitorEvent(payload);
    };

    track();

    return () => {
      cancelled = true;
    };
  }, []);

  return null;
}

window.VisitorTracker = VisitorTracker;
