(function () {
    'use strict';

    if (typeof window === 'undefined' || typeof document === 'undefined') {
        return;
    }

    if (window.__nlReferralCaptureInit) {
        return;
    }
    window.__nlReferralCaptureInit = true;

    var STORAGE_KEY = 'nl_referral_ref';
    var COOKIE_NAME = 'nl_referral_ref';
    var COOKIE_MAX_AGE = 7776000;

    function normalizeHash(value) {
        if (!value) {
            return '';
        }
        var hash = String(value).trim().toLowerCase();
        return /^[a-f0-9]{32}$/.test(hash) ? hash : '';
    }

    function setCookie(name, value, maxAge) {
        try {
            document.cookie = name + '=' + encodeURIComponent(value)
                + '; path=/; max-age=' + maxAge + '; SameSite=Lax';
        } catch (e) {}
    }

    function persistRef(hash) {
        if (!hash) {
            return;
        }
        try {
            localStorage.setItem(STORAGE_KEY, hash);
        } catch (e) {}
        setCookie(COOKIE_NAME, hash, COOKIE_MAX_AGE);
    }

    function captureFromUrl() {
        try {
            var search = window.location.search;
            if (!search || search.indexOf('ref=') === -1) {
                return;
            }
            var refParam = '';
            if (typeof URLSearchParams !== 'undefined') {
                refParam = new URLSearchParams(search).get('ref');
            } else {
                var m = search.match(/[?&]ref=([^&]+)/);
                refParam = m ? decodeURIComponent(m[1].replace(/\+/g, ' ')) : '';
            }
            var hash = normalizeHash(refParam);
            if (hash) {
                persistRef(hash);
            }
        } catch (e) {}
    }

    function readStoredRef() {
        var hash = '';
        try {
            hash = normalizeHash(localStorage.getItem(STORAGE_KEY));
        } catch (e) {}
        if (hash) {
            return hash;
        }
        try {
            var match = document.cookie.match(new RegExp('(?:^|;\\s*)' + COOKIE_NAME + '=([^;]+)'));
            if (match) {
                hash = normalizeHash(decodeURIComponent(match[1]));
            }
        } catch (e2) {}
        return hash;
    }

    function bindReferralAfterSignup() {
        var hash = readStoredRef();
        if (!hash) {
            return Promise.resolve();
        }

        var body = 'ref_hash=' + encodeURIComponent(hash);
        return fetch('/api/referralprogram/bind.json', {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body,
        }).then(function (res) {
            return res.text().then(function (text) {
                var data = null;
                try {
                    data = text ? JSON.parse(text) : null;
                } catch (parseErr) {
                    data = null;
                }
                return { status: res.status, data: data };
            });
        }).then(function (result) {
            var data = result.data;
            if (!data || data.success !== true) {
                var err = (data && data.error) ? data.error : ('http_' + result.status);
                if (typeof console !== 'undefined' && console.warn) {
                    console.warn('[nl-referral] bind failed:', err);
                }
                return { ok: false, error: err };
            }
            return { ok: true, applied: !!data.applied };
        }).catch(function () {
            if (typeof console !== 'undefined' && console.warn) {
                console.warn('[nl-referral] bind failed: network');
            }
            return { ok: false, error: 'network' };
        });
    }

    try {
        captureFromUrl();
    } catch (e) {}

    window.__nlReferralBind = bindReferralAfterSignup;
})();
""