const FEATURE_STORAGE_KEY = 'shangxiaozhuPddToolFeatures';

const DEFAULT_FEATURES = Object.freeze({
  review: false,
  refundRate: false,
  feeDashboard: false,
  afterSales: true,
  tableExport: false,
  productPublish: false
});

const SCRIPT_IDS = ['sxz-pdd-review', 'sxz-pdd-refund-bridge', 'sxz-pdd-refund-ui', 'sxz-pdd-fee-dashboard', 'sxz-pdd-table-export', 'sxz-pdd-product-publish'];
let registrationQueue = Promise.resolve();

async function readFeatures() {
  const stored = await chrome.storage.local.get(FEATURE_STORAGE_KEY);
  return { ...DEFAULT_FEATURES, ...(stored[FEATURE_STORAGE_KEY] || {}) };
}

async function registerEnabledScripts() {
  const features = await readFeatures();
  const registered = await chrome.scripting.getRegisteredContentScripts({ ids: SCRIPT_IDS });
  const registeredIds = registered.map((script) => script.id);
  if (registeredIds.length) {
    await chrome.scripting.unregisterContentScripts({ ids: registeredIds });
  }

  const scripts = [];
  if (features.review) {
    scripts.push({
      id: 'sxz-pdd-review',
      matches: ['https://mms.pinduoduo.com/goods/evaluation/index*'],
      js: ['modules/review/pdd_review_helper.js'],
      runAt: 'document_idle'
    });
  }
  if (features.refundRate) {
    scripts.push({
      id: 'sxz-pdd-refund-bridge',
      matches: ['https://mms.pinduoduo.com/sycm/goods_effect*'],
      js: ['modules/refund/refund_rate_page_bridge.js'],
      runAt: 'document_start',
      world: 'MAIN'
    });
    scripts.push({
      id: 'sxz-pdd-refund-ui',
      matches: ['https://mms.pinduoduo.com/sycm/goods_effect*'],
      js: ['modules/refund/refund_rate_content.js'],
      runAt: 'document_start'
    });
  }
  if (features.feeDashboard) {
    scripts.push({
      id: 'sxz-pdd-fee-dashboard',
      matches: [
        'https://mms.pinduoduo.com/*',
        'https://yingxiao.pinduoduo.com/*'
      ],
      js: [
        'modules/fee-dashboard/history-data.js',
        'modules/fee-dashboard/content.js'
      ],
      css: ['modules/fee-dashboard/styles.css'],
      runAt: 'document_idle'
    });
  }
  if (features.tableExport) {
    scripts.push({
      id: 'sxz-pdd-table-export',
      matches: [
        'https://yingxiao.pinduoduo.com/goods/promotion/list*',
        'https://mms.pinduoduo.com/sycm/goods_effect*'
      ],
      js: ['modules/table-export/content.js'],
      runAt: 'document_start'
    });
  }
  if (features.productPublish) {
    scripts.push({
      id: 'sxz-pdd-product-publish',
      matches: [
        'https://mms.pinduoduo.com/*goods_add*',
        'https://mms.pinduoduo.com/goods/goods_list*'
      ],
      js: ['modules/publish/content.js'],
      runAt: 'document_idle'
    });
  }

  if (scripts.length) {
    await chrome.scripting.registerContentScripts(scripts);
  }
  return features;
}

function syncRegisteredScripts() {
  registrationQueue = registrationQueue
    .catch(() => undefined)
    .then(() => registerEnabledScripts());
  return registrationQueue;
}

chrome.runtime.onInstalled.addListener(async () => {
  const stored = await chrome.storage.local.get(FEATURE_STORAGE_KEY);
  if (!stored[FEATURE_STORAGE_KEY]) {
    await chrome.storage.local.set({ [FEATURE_STORAGE_KEY]: DEFAULT_FEATURES });
  }
  await syncRegisteredScripts();
});

chrome.runtime.onStartup.addListener(() => {
  syncRegisteredScripts().catch((error) => console.error('[商小助拼多多工具合集] 注册脚本失败', error));
});

chrome.storage.onChanged.addListener((changes, areaName) => {
  if (areaName === 'local' && changes[FEATURE_STORAGE_KEY]) {
    syncRegisteredScripts().catch((error) => console.error('[商小助拼多多工具合集] 更新模块失败', error));
  }
});

function attachDebugger(target) {
  return new Promise((resolve, reject) => {
    chrome.debugger.attach(target, '1.3', () => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }
      resolve();
    });
  });
}

function detachDebugger(target) {
  return new Promise((resolve) => chrome.debugger.detach(target, resolve));
}

function sendDebuggerCommand(target, method, params) {
  return new Promise((resolve, reject) => {
    chrome.debugger.sendCommand(target, method, params, (result) => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }
      resolve(result);
    });
  });
}

async function dispatchNativeClick(tabId, x, y) {
  const target = { tabId };
  let attached = false;
  try {
    await attachDebugger(target);
    attached = true;
    await sendDebuggerCommand(target, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none', buttons: 0, clickCount: 0 });
    await sendDebuggerCommand(target, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 });
    await sendDebuggerCommand(target, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 });
    return { success: true };
  } catch (error) {
    return { success: false, error: error?.message || 'native click failed' };
  } finally {
    if (attached) {
      await detachDebugger(target).catch(() => undefined);
    }
  }
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message?.type === 'pdd-tools-sync-features') {
    syncRegisteredScripts().then(
      (features) => sendResponse({ success: true, features }),
      (error) => sendResponse({ success: false, error: error?.message || '注册模块失败' })
    );
    return true;
  }
  if (message?.type !== 'pdd-native-click') return false;
  const tabId = sender.tab?.id;
  if (!Number.isInteger(tabId)) {
    sendResponse({ success: false, error: 'missing tab id' });
    return undefined;
  }
  dispatchNativeClick(tabId, Number(message.x), Number(message.y)).then(sendResponse);
  return true;
});
