"use client";

import { useEffect } from "react";

/**
 * Beacon component that POSTs a view event for the given slug exactly once
 * after the page becomes visible. Rendered on the server inside the article
 * page; runs only in the browser.
 */
export function ViewBeacon({ slug }: { slug: string }) {
  useEffect(() => {
    if (typeof navigator === "undefined") return;
    // Avoid double-counting in dev React strict mode by storing a sessionStorage
    // marker per slug-loadtime.
    const key = `viewed:${slug}`;
    if (sessionStorage.getItem(key)) return;
    sessionStorage.setItem(key, String(Date.now()));

    const send = () => {
      const data = JSON.stringify({ slug });
      if (navigator.sendBeacon) {
        const blob = new Blob([data], { type: "application/json" });
        navigator.sendBeacon("/api/track/view", blob);
      } else {
        fetch("/api/track/view", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: data,
          keepalive: true,
        }).catch(() => {});
      }
    };

    if (document.visibilityState === "visible") send();
    else {
      const onVis = () => {
        if (document.visibilityState === "visible") {
          send();
          document.removeEventListener("visibilitychange", onVis);
        }
      };
      document.addEventListener("visibilitychange", onVis);
      return () => document.removeEventListener("visibilitychange", onVis);
    }
  }, [slug]);

  return null;
}
