 (function () {
  const STORAGE_KEY = 'codayun_sidebar_ai_settings_v2';

  const BUILTIN_PROVIDERS = [
    {
      id: 'doubao',
      name: '豆包',
      url: 'https://www.doubao.com/chat'
    },
    {
      id: 'yuanbao',
      name: '腾讯元宝',
      url: 'https://yuanbao.tencent.com/chat/naQivTmsDa?yb_channel=3002&yb_dl=js&yb_ad_type=201&bd_vid=6583835034614972176'
    }
  ];

  function loadState() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return {};
      return JSON.parse(raw) || {};
    } catch (e) {
      console.warn('加载侧边栏配置失败：', e);
      return {};
    }
  }

  function saveState(state) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(state || {}));
    } catch (e) {
      console.warn('保存侧边栏配置失败：', e);
    }
  }

  function normalizeUrl(url) {
    const trimmed = (url || '').trim();
    if (!trimmed) return '';
    if (/^https?:\/\//i.test(trimmed)) return trimmed;
    return 'https://' + trimmed;
  }

  function findProviderById(id, customProviders) {
    const allCustom = customProviders || [];
    const builtin = BUILTIN_PROVIDERS.find(p => p.id === id);
    if (builtin) return builtin;
    return allCustom.find(p => p.id === id) || null;
  }

  function renderSelect(selectEl, state) {
    const customProviders = state.customProviders || [];
    selectEl.innerHTML = '';

    const builtinGroup = document.createElement('optgroup');
    builtinGroup.label = '内置';
    BUILTIN_PROVIDERS.forEach(p => {
      const opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = p.name;
      builtinGroup.appendChild(opt);
    });
    selectEl.appendChild(builtinGroup);

    if (customProviders.length > 0) {
      const customGroup = document.createElement('optgroup');
      customGroup.label = '自定义';
      customProviders.forEach(p => {
        const opt = document.createElement('option');
        opt.value = p.id;
        opt.textContent = p.name;
        customGroup.appendChild(opt);
      });
      selectEl.appendChild(customGroup);
    }

    const selectedId = state.selectedId || BUILTIN_PROVIDERS[0].id;
    selectEl.value = selectedId;
  }

  function init() {
    const providerSelect = document.getElementById('providerSelect');
    const customNameInput = document.getElementById('customName');
    const customUrlInput = document.getElementById('customUrl');
    const saveCustomBtn = document.getElementById('saveCustomBtn');
    const deleteCustomBtn = document.getElementById('deleteCustomBtn');
    const iframe = document.getElementById('aiFrame');

    if (!providerSelect || !customNameInput || !customUrlInput || !saveCustomBtn || !deleteCustomBtn || !iframe) {
      console.warn('侧边栏元素未找到，初始化失败。');
      return;
    }

    const state = loadState();
    state.customProviders = state.customProviders || [];
    state.selectedId = state.selectedId || BUILTIN_PROVIDERS[0].id;

    renderSelect(providerSelect, state);

    function updateDeleteButtonState() {
      const currentId = providerSelect.value;
      const isBuiltin = !!BUILTIN_PROVIDERS.find(p => p.id === currentId);
      deleteCustomBtn.disabled = isBuiltin;
      deleteCustomBtn.style.opacity = isBuiltin ? 0.5 : 1;
    }

    function applyById(id) {
      const provider = findProviderById(id, state.customProviders);
      if (!provider) return;
      iframe.src = normalizeUrl(provider.url) || 'about:blank';
      state.selectedId = id;
      saveState(state);
      updateDeleteButtonState();
    }

    providerSelect.addEventListener('change', function () {
      applyById(this.value);
    });

    saveCustomBtn.addEventListener('click', function () {
      const name = (customNameInput.value || '').trim();
      const urlRaw = customUrlInput.value;
      const url = normalizeUrl(urlRaw);

      if (!name) {
        alert('请填写名称，例如：团队 AI 或某模型名称');
        return;
      }
      if (!url) {
        alert('请填写有效的链接地址');
        return;
      }

      const id = 'custom_' + Date.now();
      const provider = { id, name, url };
      state.customProviders.push(provider);
      state.selectedId = id;
      saveState(state);

      customNameInput.value = '';
      customUrlInput.value = '';

      renderSelect(providerSelect, state);
      applyById(id);
    });

    deleteCustomBtn.addEventListener('click', function () {
      const currentId = providerSelect.value;
      const isBuiltin = !!BUILTIN_PROVIDERS.find(p => p.id === currentId);
      if (isBuiltin) {
        return;
      }

      const target = state.customProviders.find(p => p.id === currentId);
      if (!target) return;

      if (!confirm(`确定要删除「${target.name}」吗？`)) {
        return;
      }

      state.customProviders = state.customProviders.filter(p => p.id !== currentId);

      if (!findProviderById(state.selectedId, state.customProviders)) {
        state.selectedId = BUILTIN_PROVIDERS[0].id;
      }

      saveState(state);
      renderSelect(providerSelect, state);
      applyById(state.selectedId);
    });

    // 首次加载时应用一次
    applyById(state.selectedId);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

