(function () {
    const TARGETS = ['/summary', 'open-deals-summary', '/timeline', '/garage', 'conversation-preview'];

    // Helper to send to Content Script
    function notifyExtension(type, payload, url) {
        window.postMessage({
            source: 'VYO_PAGE_INTERCEPTOR',
            type: type,
            payload: payload,
            url: url
        }, '*');
    }

    // --- XHR Interceptor ---
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url) {
        this._vyo_url = url;
        this._vyo_method = method;
        return originalOpen.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function (body) {
        const self = this;

        // Log Request Start
        notifyExtension('XHR', {
            method: self._vyo_method,
            url: self._vyo_url,
            body: body,
            stage: 'start'
        }, self._vyo_url);

        this.addEventListener('load', function () {
            // Log Response
            let responseData = null;
            try {
                if (self.responseType === 'json') responseData = self.response;
                else if (self.responseText) responseData = JSON.parse(self.responseText);
            } catch (e) { /* ignore */ }

            notifyExtension('XHR', {
                method: self._vyo_method,
                url: self._vyo_url,
                status: self.status,
                stage: 'end',
                response: responseData
            }, self._vyo_url);

            // LEGACY DATA RESTORATION
            const isTarget = TARGETS.some(t => self._vyo_url.includes(t));
            if (isTarget && responseData) {
                notifyExtension('CRM_DATA', responseData, self._vyo_url);
            }
        });

        return originalSend.apply(this, arguments);
    };

    // --- Fetch Interceptor ---
    const originalFetch = window.fetch;
    window.fetch = async function (...args) {
        const [resource, config] = args;
        const url = (typeof resource === 'string') ? resource : resource.url;
        const method = config?.method || 'GET';

        // Log Request Start
        notifyExtension('FETCH', {
            method: method,
            url: url,
            body: config?.body,
            stage: 'start'
        }, url);

        try {
            const response = await originalFetch(...args);

            // Log Response Metadata (clone if we want body, but body reading consumes stream)
            // For Recorder, status is enough usually, but if we want data we clone.
            // Let's safe clone.
            try {
                const clone = response.clone();
                // Only parse JSON if content type matches? 
                // Or just fire 'end' event.
                notifyExtension('FETCH', {
                    method: method,
                    url: url,
                    status: response.status,
                    stage: 'end'
                }, url);

                // LEGACY DATA RESTORATION: Parse body for known targets
                const isTarget = TARGETS.some(t => url.includes(t));
                if (isTarget) {
                    const clone = response.clone();
                    clone.json().then(data => {
                        notifyExtension('CRM_DATA', data, url);
                    }).catch(() => { });
                }

            } catch (e) { }

            return response;
        } catch (e) {
            notifyExtension('FETCH', {
                method: method,
                url: url,
                error: e.message,
                stage: 'error'
            }, url);
            throw e;
        }
    };
})();
