import { unref } from "vue";

export type UtmPayload = Record<string, unknown> | null;

export function useUtmPayload() {
  const utm = useNuxtUTM();

  function getUTMPayload(): UtmPayload {
    try {
      const data = unref(utm);
      const plain = JSON.parse(JSON.stringify(data));
      if (Array.isArray(plain)) {
        // Most UTM composables keep an array of visits; send the latest/first
        return plain[0] ?? null;
      }
      return plain;
    } catch (e) {
      console.warn("Failed to serialize UTM data", e);
      return null;
    }
  }

  return { utm, getUTMPayload };
}
