(function() {
    'use strict';
    const TRACK = '/api/hub/track.php';
    function track(event, meta) {
        fetch(TRACK, {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({event, meta: meta||{}}),
            keepalive: true
        }).catch(()=>{});
    }
    track('hub.visit', {referrer: document.referrer, page: location.pathname});
    const obs = new IntersectionObserver((entries) => {
        entries.forEach(e => {
            if (e.isIntersecting) { track('service.view', {service: e.target.dataset.service}); obs.unobserve(e.target); }
        });
    }, {threshold: 0.5});
    document.querySelectorAll('[data-service]').forEach(c => obs.observe(c));
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('[data-cta]');
        if (btn) track('cta.click', {cta: btn.dataset.cta, service: btn.dataset.service||null, label: btn.textContent.trim().slice(0,50)});
    });
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('[data-provider-join]');
        if (btn) track('provider.join', {specialty: btn.dataset.specialty||null});
    });
})();
