(function () {
    const NAMESPACE_KEY = '__OFFICELESS_WEB_EXTENDER__';
    const extensionNamespace = window[NAMESPACE_KEY] || {};
    window[NAMESPACE_KEY] = extensionNamespace;

    // Activity logging toggle — sync from content script via CustomEvent
    document.addEventListener('Officeless_LoggingToggle', (e) => {
        window.__OWE_ACTIVITY_LOGGING__ = !!e.detail?.enabled;
        console.log('[OWE] Activity logging toggle:', window.__OWE_ACTIVITY_LOGGING__);
    });

    // Store captured data
    let capturedWorkflowList = null;
    let capturedCompanyId = null;

    console.log('[OWE] Officeless Web Extender: Interceptors (Fetch & XHR) Initialized.');

    function handleWorkflowData(data, url) {
        console.log('[OWE] handleWorkflowData called', { 
            url, 
            hasData: !!data, 
            hasDataData: !!(data && data.data),
            dataType: data ? (Array.isArray(data.data) ? 'array' : typeof data.data) : 'null'
        });

        // Check if this is a list response (GET /automations) or single workflow response
        if (!data || !data.data) {
            console.log('[OWE] handleWorkflowData - no data or data.data, returning early');
            return;
        }

        const isListEndpoint = url && url.match(/\/automations[?#]|\/automations$/);
        const isSingleWorkflow = url && url.match(/\/automations\/[^/]+[?#]|\/automations\/[^/]+$/);
        
        console.log('[OWE] handleWorkflowData pattern match', {
            url,
            isListEndpoint: !!isListEndpoint,
            isSingleWorkflow: !!isSingleWorkflow,
            isDataArray: Array.isArray(data.data),
            dataId: !Array.isArray(data.data) && data.data.id ? data.data.id : 'N/A'
        });
        
        if (isListEndpoint && Array.isArray(data.data)) {
            // This is a workflow list - parse and categorize
            console.log('[OWE] BRANCH: List endpoint matched - processing', data.data.length, 'workflows');
            
            const workflows = data.data.map(workflow => {
                const name = workflow.name || '';
                const parts = name.split('_');
                const layer = parts[0] || 'Unknown';
                const entity = parts[1] || 'Unknown';
                
                return {
                    id: workflow.id,
                    name: name,
                    layer: layer,
                    entity: entity,
                    updated_at: workflow.updated_at
                };
            });

            const maxUpdatedAt = workflows.reduce((max, wf) => wf.updated_at > max ? wf.updated_at : max, 0);

            // Categorize by Entity -> Layer
            const categorized = {};
            workflows.forEach(wf => {
                if (!categorized[wf.entity]) {
                    categorized[wf.entity] = {};
                }
                if (!categorized[wf.entity][wf.layer]) {
                    categorized[wf.entity][wf.layer] = [];
                }
                categorized[wf.entity][wf.layer].push(wf);
            });

            capturedWorkflowList = {
                workflows: workflows,
                categorized: categorized,
                timestamp: Date.now(),
                maxUpdatedAt: maxUpdatedAt
            };

            console.log('[OWE] Dispatching Officeless_WorkflowList event');
            document.dispatchEvent(new CustomEvent('Officeless_WorkflowList', {
                detail: capturedWorkflowList,
                bubbles: true
            }));

            // Also check if list response contains trigger info for the specific workflow
            // This is needed for the execute button to work
            const currentWorkflowId = window.location.href.match(/\/workflows\/([^/]+)/)?.[1];
            if (currentWorkflowId) {
                const currentWorkflowData = data.data.find(w => w.id === currentWorkflowId);
                if (currentWorkflowData && currentWorkflowData.trigger) {
                    console.log('[OWE] Found trigger info in list response for current workflow');
                    const trigger = currentWorkflowData.trigger;
                    let endpointUrl = '';
                    let method = '';
                    let type = '';

                    if (trigger.api_v2 && trigger.api_v2.url) {
                        endpointUrl = trigger.api_v2.url;
                        method = trigger.api_v2.method;
                        type = 'api';
                    } else if (trigger.webhook_v2 && trigger.webhook_v2.url) {
                        endpointUrl = trigger.webhook_v2.url;
                        method = trigger.webhook_v2.method;
                        type = 'webhook';
                    } else if (trigger.type === 'function') {
                        type = 'function';
                    } else if (trigger.type === 'job' || trigger.type === 'dedicated_job') {
                        type = 'job';
                    }

                    // Always dispatch to update capturedWorkflow.type
                    console.log('[OWE] Dispatching Officeless_WorkflowData from list response with:', { url: endpointUrl, method, type });
                    document.dispatchEvent(new CustomEvent('Officeless_WorkflowData', {
                        detail: { url: endpointUrl, method: method, type: type },
                        bubbles: true
                    }));
                }
            }
        } else if (isSingleWorkflow && !Array.isArray(data.data)) {
            // This is a single workflow response - capture full workflow JSON
            console.log('[OWE] BRANCH: Single workflow matched - processing workflow', data.data.id);
            
            const workflowData = data.data;
            const trigger = workflowData.trigger;
            
            console.log('[OWE] Single workflow data:', {
                id: workflowData.id,
                name: workflowData.name,
                hasTrigger: !!trigger,
                triggerType: trigger ? (trigger.api_v2 ? 'api_v2' : (trigger.webhook_v2 ? 'webhook_v2' : 'other')) : 'none',
                triggerKeys: trigger ? Object.keys(trigger) : []
            });
            
            // Extract trigger info for backwards compatibility
            if (trigger) {
                let endpointUrl = '';
                let method = '';
                let type = '';

                if (trigger.api_v2 && trigger.api_v2.url) {
                    endpointUrl = trigger.api_v2.url;
                    method = trigger.api_v2.method;
                    type = 'api';
                    console.log('[OWE] Found api_v2 trigger:', { endpointUrl, method });
                } else if (trigger.webhook_v2 && trigger.webhook_v2.url) {
                    endpointUrl = trigger.webhook_v2.url;
                    method = trigger.webhook_v2.method;
                    type = 'webhook';
                    console.log('[OWE] Found webhook_v2 trigger:', { endpointUrl, method });
                } else if (trigger.type === 'function') {
                    type = 'function';
                    console.log('[OWE] Found function trigger:', { functionName: trigger.function?.name });
                } else if (trigger.type === 'job') {
                    type = 'job';
                    console.log('[OWE] Found job trigger:', { jobName: trigger.job?.name });
                } else {
                    console.log('[OWE] Trigger found but no api_v2/webhook_v2 URL. Trigger keys:', Object.keys(trigger));
                }

                // Always dispatch Officeless_WorkflowData to update capturedWorkflow.type
                // For function/job types, url and method will be empty but type will be set
                console.log('[OWE] Dispatching Officeless_WorkflowData event with:', { url: endpointUrl, method, type });
                document.dispatchEvent(new CustomEvent('Officeless_WorkflowData', {
                    detail: { url: endpointUrl, method: method, type: type },
                    bubbles: true
                }));
            } else {
                console.log('[OWE] No trigger property on workflow data');
            }
            
            // Dispatch full workflow JSON
            console.log('[OWE] Dispatching Officeless_WorkflowJson event');
            document.dispatchEvent(new CustomEvent('Officeless_WorkflowJson', {
                detail: { id: workflowData.id, data: workflowData },
                bubbles: true
            }));
        } else if (Array.isArray(data.data) && data.data.length > 0 && data.data[0].trigger) {
            // Fallback: Handle array response with trigger info (legacy format)
            console.log('[OWE] BRANCH: Legacy array format matched');
            const trigger = data.data[0].trigger;
            if (trigger) {
                let endpointUrl = '';
                let method = '';
                let type = '';

                if (trigger.api_v2 && trigger.api_v2.url) {
                    endpointUrl = trigger.api_v2.url;
                    method = trigger.api_v2.method;
                    type = 'api';
                } else if (trigger.webhook_v2 && trigger.webhook_v2.url) {
                    endpointUrl = trigger.webhook_v2.url;
                    method = trigger.webhook_v2.method;
                    type = 'webhook';
                }

                if (endpointUrl) {
                    console.log('[OWE] Legacy format - Dispatching Officeless_WorkflowData with:', { url: endpointUrl, method, type });
                    document.dispatchEvent(new CustomEvent('Officeless_WorkflowData', {
                        detail: { url: endpointUrl, method: method, type: type },
                        bubbles: true
                    }));
                }
            }
        } else {
            console.log('[OWE] BRANCH: No conditions matched for handleWorkflowData');
            console.log('[OWE] Data structure:', {
                isArray: Array.isArray(data.data),
                dataLength: Array.isArray(data.data) ? data.data.length : 'N/A',
                firstItemHasTrigger: Array.isArray(data.data) && data.data.length > 0 ? !!(data.data[0].trigger) : 'N/A'
            });
        }
    }

    function handleCompanyData(data) {
        if (data && data.data && data.data.id) {
            capturedCompanyId = data.data.id;
            console.log('[OWE] Captured Company ID:', capturedCompanyId);
            document.dispatchEvent(new CustomEvent('Officeless_CompanyId', {
                detail: { id: capturedCompanyId },
                bubbles: true
            }));
        }
    }

    // -- FETCH INTERCEPTOR --
    const originalFetch = window.fetch;
    window.fetch = async function (...args) {
        const response = await originalFetch.apply(this, args);
        const url = typeof args[0] === 'string' ? args[0] : args[0].url;
        const method = (args[1]?.method || 'GET').toUpperCase();
        
        // Log ALL fetch requests for debugging
        if (url.includes('officeless') || url.includes('mekari') || url.includes('automation')) {
            console.log('[OWE] FETCH intercepted:', { method, url });
        }

        // Clone the response because reading the body consumes the stream
        const clone = response.clone();

        try {
            if (url.includes('https://officeless-gateway.mekari.com/v1/nocode-workflow-setup-service/studio/automations')) {
                console.log('[OWE] Fetch automations URL detected:', {
                    url,
                    isNavigating: !!window.__OWE_NAVIGATING__,
                    hasPageParam: url.includes('page='),
                    flagValue: window.__OWE_NAVIGATING__
                });
                
                // Check if navigating - if so and has page param, return empty to prevent load
                if (window.__OWE_NAVIGATING__ && url.includes('page=')) {
                    console.log('[OWE] Prevented workflow list fetch during navigation');
                    return new Response(JSON.stringify({ data: [], message: 'Navigating' }), {
                        status: 200,
                        statusText: 'OK',
                        headers: { 'Content-Type': 'application/json' }
                    });
                }
                console.log('[OWE] MATCH: automations URL detected:', url);
                clone.json().then(data => {
                    handleWorkflowData(data, url);
                }).catch(err => console.error('[OWE] Fetch parse error (automations):', err));
            }

            if (url.includes('https://officeless-gateway.mekari.com/v1/company/studio/detail')) {
                console.log('[OWE] MATCH: company detail URL detected');
                clone.json().then(handleCompanyData).catch(err => console.error('[OWE] Fetch parse error (company):', err));
            }

            // Mutation interception for non-GET /automations requests
            if (window.__OWE_ACTIVITY_LOGGING__ && method !== 'GET' && url.includes('studio/automations')) {
                let requestBody = null;
                try { if (args[1]?.body) { requestBody = typeof args[1].body === 'string' ? JSON.parse(args[1].body) : args[1].body; } } catch (e) {}

                const mutationClone = response.clone();
                mutationClone.json().then(responseData => {
                    document.dispatchEvent(new CustomEvent('Officeless_WorkflowMutation', {
                        detail: { method, url, requestBody, responseBody: responseData }, bubbles: true
                    }));
                }).catch(() => {
                    document.dispatchEvent(new CustomEvent('Officeless_WorkflowMutation', {
                        detail: { method, url, requestBody, responseBody: null }, bubbles: true
                    }));
                });
            }
        } catch (e) {
            console.error('[OWE] Fetch Interceptor Error:', e);
        }

        return response;
    };

    // -- XHR INTERCEPTOR --
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;
    const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

    XMLHttpRequest.prototype.open = function (method, url, ...args) {
        this._interceptedUrl = url;
        this._interceptedMethod = method;
        return originalXHROpen.apply(this, [method, url, ...args]);
    };

    XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
        return originalXHRSetRequestHeader.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function (...args) {
        this.addEventListener('load', function () {
            try {
                const url = this._interceptedUrl || '';
                const method = (this._interceptedMethod || 'GET').toUpperCase();
                
                // Log ALL XHR requests for debugging
                if (url.includes('officeless') || url.includes('mekari') || url.includes('automation')) {
                    console.log('[OWE] XHR intercepted:', { method, url, status: this.status });
                }
                
                if (url.includes('https://officeless-gateway.mekari.com/v1/nocode-workflow-setup-service/studio/automations')) {
                    console.log('[OWE] XHR automations URL detected:', {
                        url,
                        isNavigating: !!window.__OWE_NAVIGATING__,
                        hasPageParam: url.includes('page='),
                        flagValue: window.__OWE_NAVIGATING__
                    });
                    
                    // Check if navigating - if so and has page param, abort to prevent load
                    if (window.__OWE_NAVIGATING__ && url.includes('page=')) {
                        console.log('[OWE] XHR Prevented workflow list fetch during navigation');
                        this.abort();
                        return;
                    }
                    console.log('[OWE] XHR MATCH: automations URL detected:', url);
                    if (this.responseText) {
                        try {
                            const parsed = JSON.parse(this.responseText);
                            console.log('[OWE] XHR automations response structure:', {
                                hasData: !!parsed.data,
                                isArray: Array.isArray(parsed.data),
                                dataLength: Array.isArray(parsed.data) ? parsed.data.length : 'N/A',
                                firstItemKeys: Array.isArray(parsed.data) && parsed.data.length > 0 ? Object.keys(parsed.data[0]) : 'N/A',
                                firstItemHasTrigger: Array.isArray(parsed.data) && parsed.data.length > 0 ? !!parsed.data[0].trigger : 'N/A',
                                responseKeys: Object.keys(parsed)
                            });
                            handleWorkflowData(parsed, url);
                        } catch (e) {
                            console.error('[OWE] XHR parse error:', e);
                        }
                    }
                }
                if (url.includes('https://officeless-gateway.mekari.com/v1/company/studio/detail')) {
                    console.log('[OWE] XHR MATCH: company detail URL detected');
                    if (this.responseText) {
                        handleCompanyData(JSON.parse(this.responseText));
                    }
                }

                // Mutation interception for non-GET /automations requests
                if (window.__OWE_ACTIVITY_LOGGING__ && method !== 'GET' && url.includes('studio/automations')) {
                    let requestBody = null;
                    try { if (args[0]) { requestBody = typeof args[0] === 'string' ? JSON.parse(args[0]) : args[0]; } } catch (e) {}

                    try {
                        const responseData = JSON.parse(this.responseText);
                        document.dispatchEvent(new CustomEvent('Officeless_WorkflowMutation', {
                            detail: { method, url, requestBody, responseBody: responseData }, bubbles: true
                        }));
                    } catch (e) {
                        document.dispatchEvent(new CustomEvent('Officeless_WorkflowMutation', {
                            detail: { method, url, requestBody, responseBody: null }, bubbles: true
                        }));
                    }
                }
            } catch (err) {
                console.error('[OWE] XHR Interceptor Error:', err);
            }
        });
        return originalXHRSend.apply(this, args);
    };

    const vueRouterObserver = new MutationObserver(() => {
        const appElement = document.querySelector('#app');

        if (appElement) {
            const vueApp = appElement?.__vue_app__; // Vue 3
            const router = vueApp?.config.globalProperties.$router;
            if (router) {
                console.log('[OWE] Vue Router found:', {
                    hasReplace: typeof router.replace === 'function',
                    hasPush: typeof router.push === 'function',
                    currentRoute: router.currentRoute?.value?.path
                });
                
                if (extensionNamespace.vueRouter !== router) {
                    extensionNamespace.vueRouter = router;
                    vueRouterObserver.disconnect();
                }
            } else {
                console.log('[OWE] Vue Router not found yet, continuing to observe...');
            }
        }
    });

    vueRouterObserver.observe(document.documentElement, {
        childList: true,
        subtree: true
    });

    // Native Navigation API (modern SPA navigation)
    window.navigation.addEventListener('navigate', (event) => {
        console.log('[OWE] Navigation API navigate:', {
            destination: event.destination?.url,
            navigationType: event.navigationType,
            canIntercept: event.canIntercept,
            hashChanged: event.hashChange,
            userInitiated: event.userInitiated
        });
    });
    
    window.navigation.addEventListener('navigatesuccess', (event) => {
        console.log('[OWE] Navigation API navigatesuccess:', event);
    });
    
    window.navigation.addEventListener('navigateerror', (event) => {
        console.error('[OWE] Navigation API navigateerror:', event);
    });

    // Popstate events (browser back/forward)
    window.addEventListener('popstate', (event) => {
        console.log('[OWE] Popstate event:', {
            state: event.state,
            currentURL: window.location.href
        });
    });

    // Wrap history methods to debug all navigation attempts
    const originalPushState = window.history.pushState;
    const originalReplaceState = window.history.replaceState;

    window.history.pushState = function(...args) {
        console.log('[OWE] History.pushState:', { 
            state: args[0], 
            title: args[1], 
            url: args[2],
            stack: new Error().stack
        });
        return originalPushState.apply(this, args);
    };

    window.history.replaceState = function(...args) {
        console.log('[OWE] History.replaceState:', { 
            state: args[0], 
            title: args[1], 
            url: args[2],
            stack: new Error().stack
        });
        return originalReplaceState.apply(this, args);
    };

    // Intercept router navigation
    const originalRouterPush = null; // Will be set when router is found
    const originalRouterReplace = null;

    // -- TOKEN FROM LOCALSTORAGE FALLBACK --
    function getTokenFromLocalStorage() {
        try {
            const raw = localStorage.getItem('token');
            if (!raw) return null;
            const parsed = JSON.parse(raw);
            return parsed?.value || null;
        } catch (err) {
            console.error('[OWE] Failed to read token from localStorage:', err);
            return null;
        }
    }

// Listen for token request from content script
    document.addEventListener('Officeless_RequestToken', () => {
        console.log('[OWE] Received Officeless_RequestToken event');
        const token = getTokenFromLocalStorage();
        if (token) {
            document.dispatchEvent(new CustomEvent('Officeless_AuthToken', {
                detail: { token },
                bubbles: true
            }));
        }
    });
})();
