/**
 * Track360 affiliate cookie writer (client-side).
 *
 * Why this runs in the browser instead of PHP:
 * Our pages sit behind Cloudflare / Varnish, and cached responses
 * have their Set-Cookie headers stripped. So we write the cookies
 * from JS after the page loads — that layer doesn't touch them.
 *
 * Drop this in functions.php or a mu-plugin.
 */
add_action('wp_head', 'wp_t360_client_side_cookie_script', 1);
function wp_t360_client_side_cookie_script() {
    ?>
    <script>
    (function () {
        try {
            // Pull the two params we care about off the current URL.
            var qs = new URLSearchParams(window.location.search);
            var tracking = qs.get('t360_tracking');
            var ref      = qs.get('ref');

            // Nothing to do on most page loads — bail early.
            if (!tracking && !ref) return;

            var host = window.location.hostname;

            // Hosts where we must NOT set a parent-domain cookie:
            //   - IPs and localhost (no concept of a parent)
            //   - public-suffix hosts like *.vercel.app, where a
            //     cookie on ".vercel.app" would be rejected by the
            //     browser (and would leak to every other tenant if
            //     it weren't).
            var isIp = /^\d+\.\d+\.\d+\.\d+$/.test(host);

            var publicSuffixHosts = [
                'wpdns.site',
                'wpengine.com',
                'flywheelsites.com',
                'kinsta.cloud',
                'vercel.app',
                'netlify.app',
                'pages.dev',
                'herokuapp.com',
                'ngrok.io',
                'ngrok-free.app'
            ];

            // ccTLDs where the "real" registrable domain is 3 parts,
            // not 2 (example.co.uk, not co.uk).
            var multiPartTlds = [
                'co.uk', 'org.uk', 'me.uk', 'net.uk', 'gov.uk', 'ac.uk',
                'co.il', 'org.il', 'net.il', 'gov.il', 'ac.il',
                'com.au', 'org.au', 'net.au', 'gov.au', 'edu.au',
                'com.br', 'org.br', 'net.br', 'gov.br',
                'co.jp', 'or.jp', 'ne.jp', 'go.jp', 'ac.jp',
                'co.in', 'org.in', 'net.in', 'gov.in',
                'co.nz', 'org.nz', 'net.nz', 'govt.nz',
                'co.za', 'org.za', 'net.za', 'gov.za',
                'com.ar', 'com.pl', 'com.sg', 'com.mx'
            ];

            // Figure out the domain attribute. Default to host-only
            // (empty string) and only promote to a parent-domain
            // cookie when it's safe.
            var domainAttr = '';

            if (host && host !== 'localhost' && !isIp) {
                var onPublicSuffix = publicSuffixHosts.some(function (s) {
                    return host === s || host.endsWith('.' + s);
                });

                if (!onPublicSuffix) {
                    var parts = host.split('.');

                    // Only bother computing a parent when we actually
                    // have a subdomain to strip.
                    if (parts.length > 2) {
                        var lastTwo = parts.slice(-2).join('.');
                        var registrable;

                        if (multiPartTlds.indexOf(lastTwo) !== -1 && parts.length >= 3) {
                            // e.g. foo.example.co.uk -> example.co.uk
                            registrable = parts.slice(-3).join('.');
                        } else {
                            // e.g. www.example.com -> example.com
                            registrable = parts.slice(-2).join('.');
                        }

                        domainAttr = '; domain=.' + registrable;
                    }
                    // parts.length <= 2 means we're already on the
                    // apex (example.com) — leave it host-only.
                }
            }

            // 90 days. Long enough to outlive most attribution windows.
            var ninetyDays = 60 * 60 * 24 * 90;
            var secure = window.location.protocol === 'https:' ? '; secure' : '';

            var attrs = '; path=/'
                      + '; max-age=' + ninetyDays
                      + domainAttr
                      + '; SameSite=Lax'
                      + secure;

            function setCookie(name, value) {
                document.cookie = name + '=' + encodeURIComponent(value) + attrs;
            }

            // Note: the URL param is `ref` but we store it as `t360_ref`
            // to keep our cookie namespace consistent.
            if (tracking) setCookie('t360_tracking', tracking);
            if (ref)      setCookie('t360_ref', ref);
        } catch (e) {
            // Tracking must never break a page render. Stay quiet.
        }
    })();
    </script>
    <?php
}