const FEATURE_STORAGE_KEY = 'shangxiaozhuPddToolFeatures';
const DEFAULT_FEATURES = { review: false, refundRate: false, feeDashboard: false, afterSales: true, tableExport: false, productPublish: false };
const FEATURES = [
  { id: 'review', icon: '评', title: '评价DSR提升', description: '筛选、导出、批量回复与差评举报', page: '/goods/evaluation/index', helpPage: 'modules/help/review.html' },
  { id: 'refundRate', icon: '退', title: '30 日金额退款率', description: '商品数据页显示退款金额与退款率', page: '/sycm/goods_effect', helpPage: 'modules/help/refund.html' },
  { id: 'feeDashboard', icon: '首', title: '首页经营卡片', description: '实时费比、成交花费、销量预测与退款率', page: '/home', helpPage: 'modules/help/fee-dashboard.html' },
  { id: 'afterSales', icon: '售', title: '售后率计算', description: '导入历史订单，按商家编码计算三项售后率', toolPage: 'modules/after-sales/dashboard.html', helpPage: 'modules/help/after-sales.html', alwaysEnabled: true },
  { id: 'tableExport', icon: '表', title: '表格导出', description: '商品数据与直通车列表一键导出 CSV', page: '/goods/promotion/list', helpPage: 'modules/help/table-export.html' },
  { id: 'productPublish', icon: '发', title: '商品发布', description: '图片、SKU、价格与商品编码辅助', page: '/goods/goods_add/', helpPage: 'modules/publish/help.html' }
];

const dom = {
  features: document.getElementById('features'),
  enabledCount: document.getElementById('enabledCount'),
  pageHint: document.getElementById('pageHint'),
  notice: document.getElementById('notice'),
  version: document.getElementById('version')
};

let settings = { ...DEFAULT_FEATURES };
let activeTab;

function setNotice(message = '', state = '') {
  dom.notice.textContent = message;
  dom.notice.dataset.state = state;
}

function showFeatureToast(featureId, message) {
  const row = dom.features.querySelector(`[data-feature="${featureId}"]`);
  if (!row) return;

  row.querySelector('.feature-toast')?.remove();
  const toast = document.createElement('div');
  toast.className = 'feature-toast';
  toast.setAttribute('role', 'status');
  toast.textContent = message;
  row.appendChild(toast);
  toast.addEventListener('animationend', () => toast.remove(), { once: true });
  window.setTimeout(() => toast.remove(), 2100);
}

function render() {
  dom.enabledCount.textContent = String(FEATURES.filter((feature) => feature.alwaysEnabled || settings[feature.id]).length);
  dom.features.replaceChildren(...FEATURES.map((feature) => {
    const row = document.createElement('article');
    row.className = 'feature';
    row.dataset.feature = feature.id;
    row.innerHTML = `
      <div class="icon" aria-hidden="true">${feature.icon}</div>
      <div class="copy"><div class="title-row"><strong>${feature.title}</strong><a class="help-link" href="${chrome.runtime.getURL(feature.helpPage)}" target="_blank" rel="noopener noreferrer" title="打开${feature.title}说明教程">说明教程</a></div><span>${feature.description}</span></div>
      <div class="actions">
        ${feature.toolPage ? `<button class="open-tool" type="button" data-open-feature="${feature.id}" aria-label="打开${feature.title}">打开工具</button>` : `<label class="switch" title="${settings[feature.id] ? '关闭' : '开启'}${feature.title}">
          <input type="checkbox" data-feature="${feature.id}" ${settings[feature.id] ? 'checked' : ''} aria-label="${feature.title}">
          <span class="track"></span><span class="thumb"></span>
        </label>`}
      </div>`;
    return row;
  }));
  dom.features.querySelectorAll('input[data-feature]').forEach((input) => input.addEventListener('change', (event) => {
    onToggle(event).catch((error) => {
      setNotice(error?.message || '设置失败，请重试。', 'error');
      init().catch(() => undefined);
    });
  }));
  dom.features.querySelectorAll('button[data-open-feature]').forEach((button) => button.addEventListener('click', (event) => {
    const feature = FEATURES.find((item) => item.id === event.currentTarget.dataset.openFeature);
    if (feature?.toolPage) chrome.tabs.create({ url: chrome.runtime.getURL(feature.toolPage) });
  }));
}

async function getActiveTab() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  return tab;
}

function updatePageHint() {
  try {
    const url = new URL(activeTab?.url || '');
    dom.pageHint.textContent = url.hostname === 'mms.pinduoduo.com' || url.hostname === 'yingxiao.pinduoduo.com' ? '当前为拼多多页面' : '请打开拼多多后台';
  } catch (_) {
    dom.pageHint.textContent = '请打开拼多多后台';
  }
}

async function onToggle(event) {
  const featureId = event.currentTarget.dataset.feature;
  const enabled = event.currentTarget.checked;

  settings = { ...settings, [featureId]: enabled };
  await chrome.storage.local.set({ [FEATURE_STORAGE_KEY]: settings });
  const syncResult = await chrome.runtime.sendMessage({ type: 'pdd-tools-sync-features' });
  if (!syncResult?.success) {
    throw new Error(syncResult?.error || '模块设置未能应用');
  }
  render();
  setNotice();
  showFeatureToast(featureId, `${enabled ? '已开启' : '已关闭'}，刷新相关页面后生效`);
}

async function init() {
  dom.version.textContent = `v${chrome.runtime.getManifest().version}`;
  const stored = await chrome.storage.local.get(FEATURE_STORAGE_KEY);
  settings = { ...DEFAULT_FEATURES, ...(stored[FEATURE_STORAGE_KEY] || {}), afterSales: true };
  activeTab = await getActiveTab();
  updatePageHint();
  render();
}

init().catch((error) => setNotice(error?.message || '初始化失败，请重新打开插件。', 'error'));
