"use client";

import { useEffect } from "react";

const UTM_KEYS = [
  "utm_source",
  "utm_medium",
  "utm_campaign",
  "utm_term",
  "utm_content",
  "utm_id",
  "gclid",
  "fbclid",
  "msclkid",
] as const;

type UtmKey = (typeof UTM_KEYS)[number];
type Attribution = Partial<Record<UtmKey, string>>;

// utm_source values that flag the traffic as a boost campaign (=> is_boost true).
// Côté plateforme externe : Advanced > utm_source = "boost-flow".
const FLAG_SOURCES = new Set(["boost-flow", "boost_flow", "boostflow"]);
const FLAG_EVENT_NAME = "campaign_boost_visit";

const ATTR_STORAGE_KEY = "op_attr";
const FLAG_EVENT_STORAGE_KEY = "op_boost_event_sent";

type OpFn = (...args: unknown[]) => void;

function readAttribution(): Attribution {
  try {
    const raw = sessionStorage.getItem(ATTR_STORAGE_KEY);
    return raw ? (JSON.parse(raw) as Attribution) : {};
  } catch {
    return {};
  }
}

function persistAttribution(value: Attribution) {
  try {
    sessionStorage.setItem(ATTR_STORAGE_KEY, JSON.stringify(value));
  } catch {
    // sessionStorage disabled
  }
}

function pollOp(callback: (op: OpFn) => void) {
  let attempts = 0;
  const maxAttempts = 40;
  const interval = window.setInterval(() => {
    attempts += 1;
    const op = (window as unknown as { op?: OpFn }).op;
    if (typeof op === "function") {
      callback(op);
      window.clearInterval(interval);
    } else if (attempts >= maxAttempts) {
      window.clearInterval(interval);
    }
  }, 250);
  return () => window.clearInterval(interval);
}

export function OpenPanelAttribution() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);

    const inbound: Attribution = {};
    for (const key of UTM_KEYS) {
      const value = params.get(key);
      if (value) inbound[key] = value;
    }

    const stored = readAttribution();
    const merged: Attribution = { ...stored, ...inbound };

    if (Object.keys(inbound).length > 0) {
      persistAttribution(merged);
    }

    if (Object.keys(merged).length === 0) return;

    const source = (merged.utm_source ?? "").toLowerCase();
    const isBoostSession = FLAG_SOURCES.has(source);

    const globalProps: Record<string, unknown> = { ...merged };
    if (isBoostSession) globalProps.is_boost = true;

    let flagEventAlreadySent = false;
    try {
      flagEventAlreadySent =
        sessionStorage.getItem(FLAG_EVENT_STORAGE_KEY) === "1";
    } catch {
      // sessionStorage disabled
    }

    const shouldFireFlagEvent =
      isBoostSession &&
      Object.keys(inbound).length > 0 &&
      !flagEventAlreadySent;

    return pollOp((op) => {
      op("setGlobalProperties", globalProps);

      if (shouldFireFlagEvent) {
        op("track", FLAG_EVENT_NAME, {
          utm_source: merged.utm_source,
          utm_medium: merged.utm_medium,
          utm_campaign: merged.utm_campaign,
          path: window.location.pathname,
          referrer: document.referrer || undefined,
        });
        try {
          sessionStorage.setItem(FLAG_EVENT_STORAGE_KEY, "1");
        } catch {
          // sessionStorage disabled
        }
      }
    });
  }, []);

  return null;
}
