// Connect the 熊猫 AI listing page with the extension background worker.
(function() {
    'use strict';
    if (window.__QYDZ_AI_LISTING_BRIDGE__) return;
    window.__QYDZ_AI_LISTING_BRIDGE__ = true;

    function post(action, response) {
        window.postMessage({
            source: 'qydz-ai-listing-extension',
            action: action,
            response: response || { success: false }
        }, '*');
    }

    window.addEventListener('message', function(event) {
        if (event.source !== window) return;
        var message = event.data || {};

        if (message.source === 'qydz-ai-listing-page' && message.action === 'detectBridge') {
            post('bridgeReady', { success: true, version: chrome.runtime.getManifest().version });
            return;
        }

        if (message.source === 'qydz-ai-listing-page' && message.action === 'collectDraft') {
            chrome.runtime.sendMessage({
                action: 'openAiDraftScrape',
                draft_id: message.draft_id,
                url: message.url,
                token: message.token
            }, function(response) {
                if (chrome.runtime.lastError) response = { success: false, message: chrome.runtime.lastError.message };
                post('collectDraftStarted', response);
            });
            return;
        }

        if (message.source === 'qydz-ai-listing-page' && message.action === 'ozonVisualCategorySearch') {
            chrome.runtime.sendMessage({
                action: 'openOzonVisualCategorySearch',
                draft_id: message.draft_id,
                image_url: message.image_url,
                token: message.token
            }, function(response) {
                if (chrome.runtime.lastError) response = { success: false, message: chrome.runtime.lastError.message };
                if (response && response.success === false) post('ozonVisualCategoryComplete', response);
            });
            return;
        }

        // Compatibility with the previous AI collection page.
        if (message.source === 'qydz-ai-shop-page' && message.action === 'openFailedLinks') {
            chrome.runtime.sendMessage({ action: 'openAiScrapeTabs', urls: Array.isArray(message.links) ? message.links : [] }, function(response) {
                if (chrome.runtime.lastError) response = { success: false, message: chrome.runtime.lastError.message };
                window.postMessage({ source: 'qydz-ai-shop-extension', action: 'openFailedLinksResult', response: response || { success: false } }, '*');
            });
            return;
        }

        if (message.source === 'qydz-ai-shop-page' && message.action === 'syncCachedProducts') {
            chrome.runtime.sendMessage({ action: 'syncCachedScrapeData' }, function(response) {
                if (chrome.runtime.lastError) response = { success: false, message: chrome.runtime.lastError.message };
                window.postMessage({ source: 'qydz-ai-shop-extension', action: 'syncCachedProductsResult', response: response || { success: false } }, '*');
            });
        }
    });

    chrome.runtime.onMessage.addListener(function(message) {
        if (message && message.action === 'aiDraftCollectionComplete') {
            post('collectDraftComplete', message.response || { success: false });
        }
        if (message && message.action === 'ozonVisualCategoryComplete') {
            post('ozonVisualCategoryComplete', message.response || { success: false });
        }
    });

    post('bridgeReady', { success: true, version: chrome.runtime.getManifest().version });
})();
