import Cookies from 'js-cookie';
import { getEnvRootDomain } from './domains.js';
const UTM_PARAM_NAMES = [
    'utm_source',
    'utm_medium',
    'utm_campaign',
    'utm_term',
    'utm_content'
];
export function getUTMParams() {
    const fromSearch = getUTMParamsFromSearch();
    if (fromSearch) {
        setUTMParamsInCookies(fromSearch);
        return fromSearch;
    }
    const fromCookies = getUTMParamsFromCookies();
    return fromCookies;
}
export function copyUTMParamsFromSearchToCookies() {
    const fromSearch = getUTMParamsFromSearch();
    if (fromSearch) {
        setUTMParamsInCookies(fromSearch);
    }
}
function setUTMParamsInCookies(utmParams) {
    for (const paramName of UTM_PARAM_NAMES) {
        const paramValue = utmParams[paramName];
        if (paramValue) {
            Cookies.set(paramName, paramValue, {
                domain: getEnvRootDomain(window.location.href),
                expires: 9999,
                path: '/'
            });
        }
        else {
            Cookies.remove(paramName, {
                domain: getEnvRootDomain(window.location.href),
                path: '/'
            });
        }
    }
}
function getUTMParamsFromCookies() {
    const result = {};
    for (const paramName of UTM_PARAM_NAMES) {
        const paramValue = Cookies.get(paramName);
        if (paramValue) {
            result[paramName] = paramValue;
        }
    }
    if (Object.keys(result).length) {
        return result;
    }
    else {
        return null;
    }
}
function getUTMParamsFromSearch() {
    const searchParams = new URLSearchParams(window.location.search);
    const result = {};
    for (const paramName of UTM_PARAM_NAMES) {
        const paramValue = searchParams.get(paramName);
        if (paramValue) {
            result[paramName] = paramValue;
        }
    }
    if (Object.keys(result).length) {
        return result;
    }
    else {
        return null;
    }
}
