"use client";

import { useEffect } from "react";

export function PageLoadTracker({ locale }) {
  useEffect(() => {
    const payload = {
      path: window.location.pathname,
      locale,
      referrer: document.referrer || null,
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight,
        devicePixelRatio: window.devicePixelRatio || 1,
      },
      metadata: {
        language: navigator.language || null,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null,
      },
    };
    const body = JSON.stringify(payload);

    if (navigator.sendBeacon) {
      const blob = new Blob([body], { type: "application/json" });
      navigator.sendBeacon("/track/page-load", blob);
      return;
    }

    fetch("/track/page-load", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body,
      keepalive: true,
    }).catch(() => {});
  }, [locale]);

  return null;
}
