// 知识卡片保存对话框

const DEFAULT_HOST_PORT = '127.0.0.1:38221';
const API_PATH_CARD_DECKS = '/api/v2/card-decks';
const API_PATH_CREATE_DECK = '/api/v2/card-decks';
const API_PATH_CREATE_FOLDER = '/api/v2/card-folders';
const API_PATH_CREATE_CARD = '/api/v2/cards';

const contentInput = document.getElementById('contentInput');
const deckSelect = document.getElementById('deckSelect');
const folderSelect = document.getElementById('folderSelect');
const saveBtn = document.getElementById('saveBtn');
const cancelBtn = document.getElementById('cancelBtn');
const createDeckBtn = document.getElementById('createDeckBtn');
const createFolderBtn = document.getElementById('createFolderBtn');
const statusEl = document.getElementById('status');
const createDeckModal = document.getElementById('createDeckModal');
const createFolderModal = document.getElementById('createFolderModal');
const newDeckTitle = document.getElementById('newDeckTitle');
const newFolderTitle = document.getElementById('newFolderTitle');
const confirmDeckBtn = document.getElementById('confirmDeckBtn');
const cancelDeckBtn = document.getElementById('cancelDeckBtn');
const confirmFolderBtn = document.getElementById('confirmFolderBtn');
const cancelFolderBtn = document.getElementById('cancelFolderBtn');
const configGroup = document.getElementById('configGroup');
const configSelect = document.getElementById('configSelect');
const saveConfigBtn = document.getElementById('saveConfigBtn');
const deleteConfigBtn = document.getElementById('deleteConfigBtn');
const openSettingBtn = document.getElementById('openSettingBtn');

let cardDecks = [];
let currentDeckId = null;
let savedConfigs = [];
let preferredDeckId = '';
let preferredFolderId = '';

function setStatus(message, type = '') {
  statusEl.textContent = message || '';
  statusEl.className = 'status';
  if (type) {
    statusEl.classList.add(type);
  }
}

function loadHostPort() {
  return new Promise(resolve => {
    if (!chrome.storage || !chrome.storage.sync) {
      resolve(DEFAULT_HOST_PORT);
      return;
    }
    // 优先从新配置读取，兼容旧配置
    chrome.storage.sync.get(['wisemindConfig', 'wisemindHostPort'], result => {
      const config = result.wisemindConfig || {};
      resolve(config.apiEndpoint || result.wisemindHostPort || DEFAULT_HOST_PORT);
    });
  });
}

function buildEndpoint(hostPort, path) {
  if (!hostPort) return null;
  let raw = hostPort.trim();
  if (!raw) return null;

  if (!raw.startsWith('http://') && !raw.startsWith('https://')) {
    raw = `http://${raw}`;
  }

  try {
    const url = new URL(raw);
    const port = url.port || (raw.startsWith('https://') ? '443' : '80');
    const hostPortStr = `${url.hostname}:${port}`;
    return `http://${hostPortStr}${path}`;
  } catch {
    return null;
  }
}

async function loadCardDecks() {
  try {
    const hostPort = await loadHostPort();
    const endpoint = buildEndpoint(hostPort, API_PATH_CARD_DECKS);

    if (!endpoint) {
      setStatus('✗ API 端点配置错误', 'error');
      return;
    }

    setStatus('正在加载卡片集...', 'info');
    const res = await fetch(endpoint, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!res.ok) {
      throw new Error(`HTTP ${res.status}`);
    }

    const result = await res.json();
    if (result.ok && result.data) {
      cardDecks = result.data.sort((a, b) => Number(b.id) - Number(a.id));
      updateDeckSelect();
      setStatus('');
    } else {
      throw new Error(result.error || '加载失败');
    }
  } catch (err) {
    const errorMsg = err?.message || String(err);
    setStatus(`✗ 加载卡片集失败: ${errorMsg}`, 'error');
    cardDecks = [];
    updateDeckSelect();
  }
}

function updateDeckSelect() {
  if (!deckSelect) return;

  deckSelect.innerHTML = '<option value="">请选择卡片集</option>';
  cardDecks.forEach(deck => {
    const option = document.createElement('option');
    option.value = deck.id;
    option.textContent = deck.title;
    deckSelect.appendChild(option);
  });
}

function updateFolderSelect(deckId) {
  if (!folderSelect) return;

  folderSelect.innerHTML = '<option value="">请选择卡片目录</option>';

  if (!deckId) {
    folderSelect.innerHTML = '<option value="">请先选择卡片集</option>';
    return;
  }

  const deck = cardDecks.find(d => d.id === Number(deckId));
  if (deck && deck.folders) {
    deck.folders
      .slice()
      .sort((a, b) => Number(b.id) - Number(a.id))
      .forEach(folder => {
      const option = document.createElement('option');
      option.value = folder.id;
      option.textContent = folder.title;
      folderSelect.appendChild(option);
    });
  }
}

async function createCardDeck(title) {
  try {
    const hostPort = await loadHostPort();
    const endpoint = buildEndpoint(hostPort, API_PATH_CREATE_DECK);

    if (!endpoint) {
      setStatus('✗ API 端点配置错误', 'error');
      return null;
    }

    const res = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ title }),
    });

    if (!res.ok) {
      const text = await res.text().catch(() => '');
      throw new Error(text || `HTTP ${res.status}`);
    }

    const result = await res.json();
    if (result.ok && result.id) {
      setStatus('✓ 卡片集创建成功', 'success');
      await loadCardDecks();
      if (deckSelect) {
        deckSelect.value = result.id;
        currentDeckId = result.id;
        updateFolderSelect(result.id);
      }
      return result.id;
    } else {
      throw new Error(result.error || '创建失败');
    }
  } catch (err) {
    const errorMsg = err?.message || String(err);
    setStatus(`✗ 创建卡片集失败: ${errorMsg}`, 'error');
    return null;
  }
}

async function createCardFolder(deckId, title) {
  try {
    const hostPort = await loadHostPort();
    const endpoint = buildEndpoint(hostPort, API_PATH_CREATE_FOLDER);

    if (!endpoint) {
      setStatus('✗ API 端点配置错误', 'error');
      return null;
    }

    const res = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ deckId, title }),
    });

    if (!res.ok) {
      const text = await res.text().catch(() => '');
      throw new Error(text || `HTTP ${res.status}`);
    }

    const result = await res.json();
    if (result.ok && result.id) {
      setStatus('✓ 卡片目录创建成功', 'success');
      await loadCardDecks();
      if (folderSelect) {
        folderSelect.value = result.id;
      }
      return result.id;
    } else {
      throw new Error(result.error || '创建失败');
    }
  } catch (err) {
    const errorMsg = err?.message || String(err);
    setStatus(`✗ 创建卡片目录失败: ${errorMsg}`, 'error');
    return null;
  }
}

async function saveCard() {
  setStatus('');

  if (!contentInput || !deckSelect || !folderSelect) {
    setStatus('✗ 页面元素未找到', 'error');
    return;
  }

  const content = contentInput.value.trim();
  const deckId = Number(deckSelect.value);
  const folderId = Number(folderSelect.value);

  if (!content) {
    setStatus('✗ 内容不能为空', 'error');
    return;
  }

  if (!deckId) {
    setStatus('✗ 请选择卡片集', 'error');
    return;
  }

  if (!folderId) {
    setStatus('✗ 请选择卡片目录', 'error');
    return;
  }

  const hostPort = await loadHostPort();
  const endpoint = buildEndpoint(hostPort, API_PATH_CREATE_CARD);

  if (!endpoint) {
    setStatus('✗ API 端点配置错误', 'error');
    return;
  }

  // 加载配置获取默认背景色
  const config = await loadDefaultConfig();
  const backgroundColor = config.cardBackgroundColor || 'yellow';

  // 默认样式
  const defaultStyle = {
    backgroundColor: backgroundColor,
    font: 'sans',
    fontSize: 16,
    width: 260,
    height: 260,
    x: 100,
    y: 100,
    zIndex: 0,
    lastUpdated: Date.now(),
  };

  const payload = {
    deckId,
    folderId,
    content,
    style: defaultStyle,
  };

  try {
    setStatus('正在保存...', 'info');
    const res = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });

    if (!res.ok) {
      const text = await res.text().catch(() => '');
      throw new Error(text || `HTTP ${res.status}`);
    }

    await res.json();
    setStatus('✓ 已成功保存', 'success');
    setTimeout(() => {
      window.close();
    }, 1000);
  } catch (err) {
    const errorMsg = err?.message || String(err);
    setStatus(`✗ 保存失败: ${errorMsg}`, 'error');
  }
}

// 保存配置相关函数
function loadSavedConfigs() {
  return new Promise(resolve => {
    if (!chrome.storage || !chrome.storage.sync) {
      resolve([]);
      return;
    }
    chrome.storage.sync.get(['cardSaveConfigs'], result => {
      savedConfigs = result.cardSaveConfigs || [];
      resolve(savedConfigs);
    });
  });
}

function saveConfigs() {
  if (!chrome.storage || !chrome.storage.sync) return;
  chrome.storage.sync.set({ cardSaveConfigs: savedConfigs });
}

function saveCurrentConfig() {
  const deckId = Number(deckSelect?.value);
  const folderId = Number(folderSelect?.value);
  const deckTitle = deckSelect?.selectedOptions[0]?.text || '';
  const folderTitle = folderSelect?.selectedOptions[0]?.text || '';

  if (!deckId || !folderId) {
    setStatus('✗ 请先选择卡片集和卡片目录', 'error');
    return;
  }

  const configName = prompt('请输入配置名称：', `${deckTitle} - ${folderTitle}`);
  if (!configName || !configName.trim()) {
    return;
  }

  const config = {
    id: Date.now().toString(),
    name: configName.trim(),
    deckId,
    folderId,
    deckTitle,
    folderTitle,
  };

  // 检查是否已存在同名配置
  const existingIndex = savedConfigs.findIndex(c => c.name === config.name);
  if (existingIndex >= 0) {
    if (confirm(`配置 "${config.name}" 已存在，是否覆盖？`)) {
      savedConfigs[existingIndex] = config;
    } else {
      return;
    }
  } else {
    savedConfigs.push(config);
  }

  saveConfigs();
  updateConfigSelect();
  setStatus('✓ 配置已保存', 'success');
  setTimeout(() => setStatus(''), 2000);
}

function deleteCurrentConfig() {
  const configId = configSelect?.value;
  if (!configId) {
    setStatus('✗ 请先选择要删除的配置', 'error');
    return;
  }

  const config = savedConfigs.find(c => c.id === configId);
  if (!config) {
    return;
  }

  if (confirm(`确定要删除配置 "${config.name}" 吗？`)) {
    savedConfigs = savedConfigs.filter(c => c.id !== configId);
    saveConfigs();
    updateConfigSelect();
    setStatus('✓ 配置已删除', 'success');
    setTimeout(() => setStatus(''), 2000);
  }
}

function applyConfig(configId) {
  const config = savedConfigs.find(c => c.id === configId);
  if (!config) {
    return;
  }

  // 设置卡片集
  if (deckSelect) {
    deckSelect.value = config.deckId;
    currentDeckId = config.deckId;
    updateFolderSelect(config.deckId);
    
    // 等待文件夹列表更新后再设置文件夹
    setTimeout(() => {
      if (folderSelect) {
        folderSelect.value = config.folderId;
      }
    }, 100);
  }

  setStatus(`✓ 已应用配置: ${config.name}`, 'success');
  setTimeout(() => setStatus(''), 2000);
}

function updateConfigSelect() {
  if (!configSelect) return;

  configSelect.innerHTML = '<option value="">选择保存的配置</option>';
  savedConfigs.forEach(config => {
    const option = document.createElement('option');
    option.value = config.id;
    option.textContent = `${config.name} (${config.deckTitle} - ${config.folderTitle})`;
    configSelect.appendChild(option);
  });

  // 如果有保存的配置，显示配置组
  if (configGroup) {
    configGroup.style.display = savedConfigs.length > 0 ? 'block' : 'none';
  }
}

// 加载默认配置
async function loadDefaultConfig() {
  return new Promise(resolve => {
    if (!chrome.storage || !chrome.storage.sync) {
      resolve({});
      return;
    }
    chrome.storage.sync.get(['wisemindConfig'], result => {
      resolve(result.wisemindConfig || {});
    });
  });
}

// 应用默认配置
async function applyDefaultConfig() {
  const config = await loadDefaultConfig();
  
  // 应用默认卡片集和目录
  if (config.defaultCardDeckId && deckSelect) {
    const defaultDeckId = String(config.defaultCardDeckId);
    // 等待卡片集列表加载完成后再设置
    setTimeout(() => {
      if (deckSelect.querySelector(`option[value="${defaultDeckId}"]`)) {
        deckSelect.value = defaultDeckId;
        currentDeckId = Number(defaultDeckId);
        updateFolderSelect(currentDeckId);
        
        // 等待文件夹列表更新后再设置默认文件夹
        setTimeout(() => {
          if (config.defaultCardFolderId && folderSelect) {
            const defaultFolderId = String(config.defaultCardFolderId);
            if (folderSelect.querySelector(`option[value="${defaultFolderId}"]`)) {
              folderSelect.value = defaultFolderId;
            }
          }
        }, 300);
      }
    }, 100);
  }
}

// 从 URL 参数获取选中的文本（只使用纯文本）
async function init() {
  const urlParams = new URLSearchParams(window.location.search);
  const payloadId = urlParams.get('payloadId');
  let selectedText = '';
  if (payloadId && chrome.storage && chrome.storage.local) {
    selectedText = await new Promise(resolve => {
      chrome.storage.local.get([`wisemindTemp:${payloadId}`], result => {
        const payload = result[`wisemindTemp:${payloadId}`] || {};
        preferredDeckId = payload.preferredDeckId || '';
        preferredFolderId = payload.preferredFolderId || '';
        resolve(payload.text || '');
      });
    });
    chrome.storage.local.remove([`wisemindTemp:${payloadId}`]);
  } else {
    selectedText = urlParams.get('text') || '';
  }

  if (contentInput) {
    // 只使用纯文本，不使用 HTML
    contentInput.value = selectedText;
  }

  await loadCardDecks();
  await loadSavedConfigs();
  updateConfigSelect();
  await applyDefaultConfig();
  if (preferredDeckId && deckSelect) {
    const deckId = String(preferredDeckId);
    if (deckSelect.querySelector(`option[value="${deckId}"]`)) {
      deckSelect.value = deckId;
      currentDeckId = Number(deckId);
      updateFolderSelect(currentDeckId);
      setTimeout(() => {
        if (preferredFolderId && folderSelect) {
          const folderId = String(preferredFolderId);
          if (folderSelect.querySelector(`option[value="${folderId}"]`)) {
            folderSelect.value = folderId;
          }
        }
      }, 100);
    }
  }
}

deckSelect?.addEventListener('change', () => {
  currentDeckId = Number(deckSelect.value);
  updateFolderSelect(currentDeckId);
});

saveBtn?.addEventListener('click', async () => {
  try {
    await saveCard();
  } catch (err) {
    console.error('Save card error:', err);
    setStatus(`✗ 保存失败: ${err?.message || err}`, 'error');
  }
});

cancelBtn?.addEventListener('click', () => {
  window.close();
});

createDeckBtn?.addEventListener('click', () => {
  if (createDeckModal && newDeckTitle) {
    createDeckModal.classList.add('active');
    newDeckTitle.value = '';
    newDeckTitle.focus();
  }
});

createFolderBtn?.addEventListener('click', () => {
  if (!currentDeckId) {
    setStatus('✗ 请先选择卡片集', 'error');
    return;
  }
  if (createFolderModal && newFolderTitle) {
    createFolderModal.classList.add('active');
    newFolderTitle.value = '';
    newFolderTitle.focus();
  }
});

confirmDeckBtn?.addEventListener('click', async () => {
  if (newDeckTitle) {
    const title = newDeckTitle.value.trim();
    if (!title) {
      setStatus('✗ 请输入卡片集标题', 'error');
      return;
    }
    await createCardDeck(title);
    if (createDeckModal) {
      createDeckModal.classList.remove('active');
    }
  }
});

cancelDeckBtn?.addEventListener('click', () => {
  if (createDeckModal) {
    createDeckModal.classList.remove('active');
  }
});

confirmFolderBtn?.addEventListener('click', async () => {
  if (newFolderTitle && currentDeckId) {
    const title = newFolderTitle.value.trim();
    if (!title) {
      setStatus('✗ 请输入卡片目录标题', 'error');
      return;
    }
    await createCardFolder(currentDeckId, title);
    if (createFolderModal) {
      createFolderModal.classList.remove('active');
    }
  }
});

cancelFolderBtn?.addEventListener('click', () => {
  if (createFolderModal) {
    createFolderModal.classList.remove('active');
  }
});

createDeckModal?.addEventListener('click', e => {
  if (e.target === createDeckModal) {
    createDeckModal.classList.remove('active');
  }
});

createFolderModal?.addEventListener('click', e => {
  if (e.target === createFolderModal) {
    createFolderModal.classList.remove('active');
  }
});

configSelect?.addEventListener('change', () => {
  const configId = configSelect.value;
  if (configId) {
    applyConfig(configId);
  }
});

saveConfigBtn?.addEventListener('click', () => {
  saveCurrentConfig();
});

deleteConfigBtn?.addEventListener('click', () => {
  deleteCurrentConfig();
});

openSettingBtn?.addEventListener('click', () => {
  chrome.runtime.openOptionsPage();
});

init();
