"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import {
  persistReferralVisitor,
  readReferralAttribution,
  referralAttributionFromLocation,
} from "@/lib/referral-attribution";

export default function ReferralTracker() {
  const pathname = usePathname();

  useEffect(() => {
    const attribution =
      readReferralAttribution() || referralAttributionFromLocation();
    if (!attribution?.utm_source) return;

    persistReferralVisitor(attribution);

    const sessionKey = `skylight_referral_logged:${attribution.utm_source.toLowerCase()}`;
    try {
      if (window.sessionStorage.getItem(sessionKey)) return;
      window.sessionStorage.setItem(sessionKey, "pending");
    } catch {
      // Continue without session de-duplication if storage is unavailable.
    }

    const logVisit = async () => {
      try {
        const response = await fetch("/api/referral-visit", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            ...attribution,
            landing_path: `${window.location.pathname}${window.location.search}`,
            referrer_url: document.referrer || null,
          }),
          keepalive: true,
        });

        if (!response.ok) {
          throw new Error(`Referral visit returned ${response.status}`);
        }

        try {
          window.sessionStorage.setItem(sessionKey, "logged");
        } catch {
          // The visit was still saved successfully.
        }
      } catch (error) {
        console.warn("[referral] visit tracking failed", error);
        try {
          window.sessionStorage.removeItem(sessionKey);
        } catch {
          // Nothing else to do.
        }
      }
    };

    void logVisit();
  }, [pathname]);

  return null;
}
