const STORAGE_KEY = 'actuate_attribution';
const isBrowser = typeof window !== 'undefined';
const MOBILE_PATTERN = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i;
const TABLET_PATTERN = /iPad|Android(?!.*Mobile)|Tablet/i;
export function getDeviceType() {
    if (!isBrowser)
        return 'desktop';
    const ua = navigator.userAgent;
    if (TABLET_PATTERN.test(ua))
        return 'tablet';
    if (MOBILE_PATTERN.test(ua))
        return 'mobile';
    return 'desktop';
}
const CLICK_ID_PARAMS = ['gclid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id'];
export function parseUtmParams(url) {
    if (!isBrowser && !url)
        return {};
    let params;
    try {
        const raw = url ?? (isBrowser ? window.location.href : '');
        params = new URL(raw, 'https://placeholder.local').searchParams;
    }
    catch {
        return {};
    }
    const result = {};
    const source = params.get('utm_source');
    if (source)
        result.source = source;
    const medium = params.get('utm_medium');
    if (medium)
        result.medium = medium;
    const campaign = params.get('utm_campaign');
    if (campaign)
        result.campaign = campaign;
    const term = params.get('utm_term');
    if (term)
        result.term = term;
    const content = params.get('utm_content');
    if (content)
        result.content = content;
    const clickIds = {};
    for (const key of CLICK_ID_PARAMS) {
        const val = params.get(key);
        if (val)
            clickIds[key] = val;
    }
    if (Object.keys(clickIds).length > 0) {
        result.clickIds = {
            gclid: clickIds.gclid ?? '',
            fbclid: clickIds.fbclid ?? '',
            msclkid: clickIds.msclkid ?? '',
            ttclid: clickIds.ttclid ?? '',
            li_fat_id: clickIds.li_fat_id ?? '',
        };
    }
    return result;
}
const SEARCH_ENGINES = {
    'google.': 'google',
    'bing.': 'bing',
    'yahoo.': 'yahoo',
    'duckduckgo.': 'duckduckgo',
    'baidu.': 'baidu',
    'yandex.': 'yandex',
};
const SOCIAL_NETWORKS = {
    'facebook.': 'facebook',
    'fb.': 'facebook',
    'instagram.': 'instagram',
    'twitter.': 'twitter',
    'x.com': 'twitter',
    't.co': 'twitter',
    'linkedin.': 'linkedin',
    'tiktok.': 'tiktok',
    'pinterest.': 'pinterest',
    'reddit.': 'reddit',
    'youtube.': 'youtube',
};
function domainMatches(hostname, patterns) {
    const lower = hostname.toLowerCase();
    for (const [pattern, name] of Object.entries(patterns)) {
        if (lower.includes(pattern))
            return name;
    }
    return undefined;
}
function isSearchEngine(hostname) {
    return domainMatches(hostname, SEARCH_ENGINES) !== undefined;
}
export function inferSource(referrer, utmSource) {
    if (utmSource)
        return utmSource;
    if (!referrer)
        return 'direct';
    try {
        const { hostname } = new URL(referrer);
        return domainMatches(hostname, { ...SEARCH_ENGINES, ...SOCIAL_NETWORKS }) ?? hostname;
    }
    catch {
        return 'direct';
    }
}
export function inferMedium(utmMedium, clickIds) {
    if (utmMedium)
        return utmMedium;
    if (clickIds) {
        const hasClickId = Object.values(clickIds).some((v) => v !== '');
        if (hasClickId)
            return 'cpc';
    }
    if (isBrowser && document.referrer) {
        try {
            const { hostname } = new URL(document.referrer);
            if (isSearchEngine(hostname))
                return 'organic';
            if (domainMatches(hostname, SOCIAL_NETWORKS))
                return 'social';
            return 'referral';
        }
        catch {
            return '(none)';
        }
    }
    return '(none)';
}
function createEmptyAttribution() {
    return {
        source: 'direct',
        medium: '(none)',
        campaign: '',
        term: '',
        content: '',
        landingPage: '',
        referrer: '',
        deviceType: 'desktop',
        clickIds: { gclid: '', fbclid: '', msclkid: '', ttclid: '', li_fat_id: '' },
        sessionStart: new Date().toISOString(),
        pageViews: 1,
    };
}
export function captureAttribution() {
    if (!isBrowser)
        return createEmptyAttribution();
    const existing = getStoredAttribution();
    const utmData = parseUtmParams();
    const clickIds = utmData.clickIds ??
        existing?.clickIds ?? {
        gclid: '',
        fbclid: '',
        msclkid: '',
        ttclid: '',
        li_fat_id: '',
    };
    const referrer = document.referrer || existing?.referrer || '';
    const data = {
        source: inferSource(referrer, utmData.source),
        medium: inferMedium(utmData.medium, clickIds),
        campaign: utmData.campaign ?? existing?.campaign ?? '',
        term: utmData.term ?? existing?.term ?? '',
        content: utmData.content ?? existing?.content ?? '',
        landingPage: existing?.landingPage ?? window.location.href,
        referrer,
        deviceType: getDeviceType(),
        clickIds,
        sessionStart: existing?.sessionStart ?? new Date().toISOString(),
        pageViews: (existing?.pageViews ?? 0) + 1,
    };
    storeAttribution(data);
    return data;
}
export function storeAttribution(data) {
    if (!isBrowser)
        return;
    try {
        sessionStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    }
    catch {
        // sessionStorage unavailable (private mode, full storage, etc.)
    }
}
export function getStoredAttribution() {
    if (!isBrowser)
        return null;
    try {
        const raw = sessionStorage.getItem(STORAGE_KEY);
        if (!raw)
            return null;
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
export function trackPageView() {
    if (!isBrowser)
        return;
    const data = getStoredAttribution();
    if (data) {
        data.pageViews++;
        storeAttribution(data);
    }
    else {
        captureAttribution();
    }
}
export function getAttributionForSubmission() {
    if (!isBrowser)
        return createEmptyAttribution();
    let data = getStoredAttribution();
    if (!data) {
        data = captureAttribution();
    }
    else {
        data.pageViews++;
        storeAttribution(data);
    }
    return data;
}
//# sourceMappingURL=attribution.js.map