// 当扩展安装或更新时触发
chrome.runtime.onInstalled.addListener((details) => {
  console.log("Extension installed or updated:", details.reason);

  if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
    chrome.tabs.create({ url: "chrome://newtab" });
    chrome.storage.local.set({ defaultBookmarkId: null });
    chrome.storage.sync.set({
      openInNewTab: false // 默认在当前标签页打开
    });
  }
});

let defaultBookmarkId = null;

chrome.storage.local.get(['defaultBookmarkId'], (result) => {
  if (result.defaultBookmarkId) {
    defaultBookmarkId = result.defaultBookmarkId;
  }
});

function containsPermission(permissions) {
  return new Promise((resolve) => {
    if (!chrome.permissions?.contains) {
      resolve(false);
      return;
    }
    chrome.permissions.contains({ permissions }, (result) => {
      resolve(Boolean(result) && !chrome.runtime.lastError);
    });
  });
}

async function ensureTabGroupsPermission() {
  // 后台无法可靠弹出权限对话框（需用户手势）；仅检查是否已授予
  return containsPermission(['tabGroups']);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Received message in background:', request);

  switch (request.action) {
    case 'fetchBookmarks':
      chrome.bookmarks.getTree(async (bookmarkTreeNodes) => {
        if (chrome.runtime.lastError) {
          sendResponse({ error: chrome.runtime.lastError.message });
        } else {
          try {
            const folders = await new Promise((resolve) => {
              chrome.bookmarks.getTree((tree) => {
                resolve(tree);
              });
            });

            const processedBookmarks = [];

            function processBookmarkNode(node) {
              if (node.url) {
                processedBookmarks.push(node);
              }
              if (node.children) {
                node.children.forEach(processBookmarkNode);
              }
            }

            folders.forEach(folder => {
              processBookmarkNode(folder);
            });

            sendResponse({
              bookmarks: bookmarkTreeNodes,
              processedBookmarks: processedBookmarks,
              success: true
            });
          } catch (error) {
            sendResponse({ error: error.message });
          }
        }
      });
      return true;

    case 'getDefaultBookmarkId':
      sendResponse({ defaultBookmarkId });
      break;

    case 'setDefaultBookmarkId':
      defaultBookmarkId = request.defaultBookmarkId;
      chrome.storage.local.set({ defaultBookmarkId: defaultBookmarkId }, function () {
        if (chrome.runtime.lastError) {
          sendResponse({ success: false, error: chrome.runtime.lastError.message });
        } else {
          sendResponse({ success: true });
        }
      });
      return true;

    case 'openMultipleTabsAndGroup':
      handleOpenMultipleTabsAndGroup(request, sendResponse);
      return true;

    case 'reloadExtension':
      chrome.runtime.reload();
      return true;

    case 'updateBookmarkDisplay':
      // 不再广播到所有标签页（避免 tabs 权限）；依赖各页自身的 storage/bookmarks 监听刷新
      chrome.storage.local.set({
        bookmarkDisplayRefresh: {
          folderId: request.folderId || null,
          at: Date.now()
        }
      }, () => {
        sendResponse({ success: !chrome.runtime.lastError });
      });
      return true;

    case 'getBookmarkFolder':
      chrome.bookmarks.get(request.folderId, (folder) => {
        if (chrome.runtime.lastError) {
          sendResponse({
            success: false,
            error: chrome.runtime.lastError.message
          });
          return;
        }

        // 如果是文件夹，获取其子项
        if (!folder[0].url) {
          chrome.bookmarks.getChildren(request.folderId, (children) => {
            if (chrome.runtime.lastError) {
              sendResponse({
                success: true,
                folder: folder[0],
                error: chrome.runtime.lastError.message
              });
            } else {
              sendResponse({
                success: true,
                folder: folder[0],
                children: children
              });
            }
          });
        } else {
          // 如果是书签，直接返回
          sendResponse({
            success: true,
            folder: folder[0]
          });
        }
      });
      return true;

    default:
      sendResponse({ success: false, error: 'Unknown action' });
      return false;
  }
});

function handleOpenMultipleTabsAndGroup(request, sendResponse) {
  const { urls, groupName } = request;
  const tabIds = [];

  const createTabPromises = urls.map(url => {
    return new Promise((resolve) => {
      chrome.tabs.create({ url: url, active: false }, function (tab) {
        if (!chrome.runtime.lastError && tab?.id != null) {
          tabIds.push(tab.id);
        }
        resolve();
      });
    });
  });

  Promise.all(createTabPromises).then(async () => {
    if (tabIds.length <= 1) {
      sendResponse({
        success: true,
        message: 'URL 数量不大于 1，直接打开标签页，不创建标签组'
      });
      return;
    }

    const canGroup = await ensureTabGroupsPermission();
    if (!canGroup || !chrome.tabs.group) {
      sendResponse({
        success: true,
        warning: '未授予标签组权限，已打开标签页但未分组'
      });
      return;
    }

    chrome.tabs.group({ tabIds: tabIds }, function (groupId) {
      if (chrome.runtime.lastError) {
        sendResponse({ success: true, warning: chrome.runtime.lastError.message });
        return;
      }
      if (chrome.tabGroups?.update) {
        chrome.tabGroups.update(groupId, {
          title: groupName,
          color: 'cyan'
        }, function () {
          if (chrome.runtime.lastError) {
            sendResponse({ success: true, warning: chrome.runtime.lastError.message });
          } else {
            sendResponse({ success: true });
          }
        });
      } else {
        sendResponse({ success: true, warning: 'tabGroups API 不可用，无法设置组名和颜色' });
      }
    });
  });
}

// 点击扩展图标时打开新标签页
chrome.action.onClicked.addListener(() => {
  chrome.tabs.create({ url: 'chrome://newtab' });
});

/**
 * Suppress HTTP Basic/Digest auth prompts while scanning bookmarks for 404s.
 * Without this, LAN panels like 1Panel show a login dialog during fetch.
 */
let clear404AuthListener = null;

function setClear404AuthSuppression(enabled) {
  const api = chrome.webRequest?.onAuthRequired;
  if (!api) {
    return { ok: false, error: 'webRequest_unavailable' };
  }

  if (!enabled) {
    if (clear404AuthListener) {
      try {
        api.removeListener(clear404AuthListener);
      } catch (error) {
        console.warn('Failed to remove auth suppression listener:', error);
      }
      clear404AuthListener = null;
    }
    return { ok: true, enabled: false };
  }

  if (clear404AuthListener) {
    return { ok: true, enabled: true };
  }

  clear404AuthListener = (details, callback) => {
    // Cancel the challenge so Chrome does not show a native login dialog.
    try {
      callback({ cancel: true });
    } catch (error) {
      console.warn('Failed to cancel auth challenge:', error);
    }
  };

  try {
    api.addListener(
      clear404AuthListener,
      { urls: ['http://*/*', 'https://*/*'] },
      ['asyncBlocking']
    );
    return { ok: true, enabled: true };
  } catch (error) {
    clear404AuthListener = null;
    console.warn('Failed to enable auth suppression:', error);
    return { ok: false, error: String(error?.message || error) };
  }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request?.action === 'clear404SetAuthSuppression') {
    sendResponse(setClear404AuthSuppression(Boolean(request.enabled)));
  }
});
