// # Source: https://github.com/huwangkeji/juejin_checkin/blob/main/juejin-extension/popup.js
// # Raw: https://raw.githubusercontent.com/huwangkeji/juejin_checkin/main/juejin-extension/popup.js
// # Repo: huwangkeji/juejin_checkin
// # Path: juejin-extension/popup.js
// # UploadedAt: 2026-05-19T14:34:11Z
// # SHA256: 0a4d49831a306fa984f62b0d1b3f26f7fc1274a625d08b5f4622ba94121b8469
// # Category: web版/抓包
// # Evidence: web/H5关键词 + cookie/token/header
// 

/**
 * 掘金参数提取器 - Popup脚本
 */

// 参数配置：key、显示名、青龙环境变量名
const PARAM_CONFIG = [
  { key: 'cookie', name: 'Cookie', env: 'JUEJIN_COOKIE', isLong: true },
  { key: 'aid', name: 'AID', env: 'JUEJIN_AID', isLong: false },
  { key: 'uuid', name: 'UUID', env: 'JUEJIN_UUID', isLong: true },
  { key: 'msToken', name: 'msToken', env: 'JUEJIN_MSTOKEN', isLong: true },
  { key: 'a_bogus', name: 'a_bogus', env: 'JUEJIN_A_BOGUS', isLong: true },
];

let currentData = null;

// 加载数据
async function loadData() {
  return new Promise((resolve) => {
    chrome.storage.local.get('juejinData', (result) => {
      resolve(result.juejinData || null);
    });
  });
}

// 渲染界面
async function render() {
  currentData = await loadData();

  const emptyState = document.getElementById('emptyState');
  const paramsList = document.getElementById('paramsList');
  const actionsBar = document.getElementById('actionsBar');
  const statusDot = document.getElementById('statusDot');
  const statusText = document.getElementById('statusText');
  const captureTime = document.getElementById('captureTime');

  if (!currentData || !currentData.cookie) {
    // 无数据
    emptyState.style.display = 'block';
    paramsList.style.display = 'none';
    actionsBar.style.display = 'none';
    statusDot.className = 'status-dot empty';
    statusText.textContent = '等待捕获...';
    captureTime.textContent = '';
    return;
  }

  // 有数据
  emptyState.style.display = 'none';
  paramsList.style.display = 'block';
  actionsBar.style.display = 'flex';
  statusDot.className = 'status-dot captured';
  statusText.textContent = '✅ 参数已捕获';
  captureTime.textContent = currentData.captureTime || '';

  // 渲染参数列表
  paramsList.innerHTML = PARAM_CONFIG.map((config) => {
    const value = currentData[config.key] || '';
    const isEmpty = !value;
    const displayValue = isEmpty ? '未捕获到' : value;
    const valueClass = isEmpty ? 'param-value empty' : 'param-value';

    return `
      <div class="param-item">
        <div class="param-header">
          <span class="param-name">${config.name}</span>
          <div style="display:flex;align-items:center;gap:6px;">
            <span class="param-env">${config.env}</span>
            <button class="copy-btn" data-key="${config.key}" title="复制${config.name}">复制</button>
          </div>
        </div>
        <div class="${valueClass}" title="${displayValue}">${displayValue}</div>
      </div>
    `;
  }).join('');

  // 绑定复制按钮
  paramsList.querySelectorAll('.copy-btn').forEach((btn) => {
    btn.addEventListener('click', () => {
      const key = btn.dataset.key;
      const value = currentData[key] || '';
      copyToClipboard(value, btn);
    });
  });
}

// 复制到剪贴板
function copyToClipboard(text, btn) {
  navigator.clipboard.writeText(text).then(() => {
    if (btn) {
      const original = btn.textContent;
      btn.textContent = '已复制 ✓';
      btn.classList.add('copied');
      setTimeout(() => {
        btn.textContent = original;
        btn.classList.remove('copied');
      }, 1500);
    }
  });
}

// 生成青龙面板环境变量格式
function generateQinglongFormat() {
  if (!currentData) return '';

  const lines = [];
  lines.push('# 掘金签到脚本 - 青龙面板环境变量');
  lines.push('# 复制以下内容到青龙面板 -> 环境变量');
  lines.push('');
  lines.push(`JUEJIN_COOKIE='${currentData.cookie || ''}'`);
  lines.push(`JUEJIN_AID='${currentData.aid || '2608'}'`);
  lines.push(`JUEJIN_UUID='${currentData.uuid || ''}'`);
  lines.push(`JUEJIN_MSTOKEN='${currentData.msToken || ''}'`);
  lines.push(`JUEJIN_A_BOGUS='${currentData.a_bogus || ''}'`);
  lines.push('');
  lines.push(`# 捕获时间: ${currentData.captureTime || '未知'}`);
  lines.push('# 参数有效期约30天，过期需重新获取');

  return lines.join('\n');
}

// 绑定事件
document.getElementById('copyAllBtn').addEventListener('click', () => {
  const text = generateQinglongFormat();
  copyToClipboard(text, document.getElementById('copyAllBtn'));
});

document.getElementById('goJuejinBtn').addEventListener('click', () => {
  chrome.tabs.create({ url: 'https://juejin.cn' });
});

document.getElementById('refreshBtn').addEventListener('click', () => {
  render();
});

// "从当前页面提取"按钮
document.getElementById('extractNowBtn').addEventListener('click', async () => {
  const btn = document.getElementById('extractNowBtn');
  const originalText = btn.textContent;
  btn.textContent = '⏳ 提取中...';
  btn.disabled = true;

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

    if (!tab || !tab.url || !tab.url.includes('juejin.cn')) {
      alert('请先在掘金网站 (juejin.cn) 页面点击此按钮');
      btn.textContent = originalText;
      btn.disabled = false;
      return;
    }

    // 在页面中执行提取脚本：主动发请求 -> 等待 hook 捕获 -> 读取 sessionStorage
    const results = await chrome.scripting.executeScript({
      target: { tabId: tab.id, allFrames: false },
      world: 'MAIN',
      func: () => {
        return new Promise((resolve) => {
          const data = {
            cookie: '',
            aid: '',
            uuid: '',
            msToken: '',
            a_bogus: '',
            spider: '',
            captureTime: new Date().toLocaleString('zh-CN'),
            captureUrl: location.href,
          };

          // 辅助：从 URL 提取参数
          function extractFromUrl(url) {
            try {
              const u = new URL(url);
              return {
                aid: u.searchParams.get('aid') || '',
                uuid: u.searchParams.get('uuid') || '',
                msToken: u.searchParams.get('msToken') || '',
                a_bogus: u.searchParams.get('a_bogus') || '',
                spider: u.searchParams.get('spider') || '',
              };
            } catch (e) { return null; }
          }

          // 1. 获取 cookie
          try { data.cookie = document.cookie; } catch (e) {}

          // 2. 扫描 performance entries
          try {
            const entries = performance.getEntriesByType('resource');
            for (const entry of entries) {
              if (entry.name && entry.name.includes('api.juejin.cn')) {
                const p = extractFromUrl(entry.name);
                if (p) {
                  if (p.aid) data.aid = p.aid;
                  if (p.uuid && p.uuid.length > 5) data.uuid = p.uuid;
                  if (p.msToken && p.msToken.length > 5) data.msToken = p.msToken;
                  if (p.a_bogus && p.a_bogus.length > 5) data.a_bogus = p.a_bogus;
                  if (p.spider) data.spider = p.spider;
                }
              }
            }
          } catch (e) {}

          // 3. 从 content script 的 sessionStorage 读取（如果 content.js 已捕获）
          try {
            const stored = JSON.parse(sessionStorage.getItem('__juejin_extractor_data__') || '{}');
            if (stored.cookie) data.cookie = stored.cookie;
            if (stored.aid) data.aid = stored.aid;
            if (stored.uuid) data.uuid = stored.uuid;
            if (stored.msToken) data.msToken = stored.msToken;
            if (stored.a_bogus) data.a_bogus = stored.a_bogus;
            if (stored.spider) data.spider = stored.spider;
          } catch (e) {}

          // 4. 主动触发一个请求来诱捕参数（content.js 的 MAIN world hook 会捕获）
          const needsTrigger = !data.uuid || !data.msToken || !data.a_bogus;
          if (needsTrigger) {
            try {
              fetch('https://api.juejin.cn/growth_api/v1/get_today_status?aid=2608', {
                credentials: 'include',
                headers: { 'Accept': 'application/json' },
              }).catch(() => {});
              fetch('https://api.juejin.cn/user_api/v1/user/get?aid=2608', {
                credentials: 'include',
                headers: { 'Accept': 'application/json' },
              }).catch(() => {});
            } catch (e) {}

            // 等待 hook 处理后再读取
            setTimeout(() => {
              try {
                const stored2 = JSON.parse(sessionStorage.getItem('__juejin_extractor_data__') || '{}');
                if (stored2.cookie) data.cookie = stored2.cookie;
                if (stored2.aid) data.aid = stored2.aid;
                if (stored2.uuid) data.uuid = stored2.uuid;
                if (stored2.msToken) data.msToken = stored2.msToken;
                if (stored2.a_bogus) data.a_bogus = stored2.a_bogus;
                if (stored2.spider) data.spider = stored2.spider;
              } catch (e) {}
              resolve(data);
            }, 800);
          } else {
            resolve(data);
          }
        });
      },
    });

    const extracted = results[0]?.result;
    if (extracted) {
      // 合并到已有数据
      chrome.storage.local.get('juejinData', (result) => {
        const existing = result.juejinData || {};
        const merged = {
          ...existing,
          ...Object.fromEntries(
            Object.entries(extracted).filter(([_, v]) => v && v !== '')
          ),
        };
        chrome.storage.local.set({ juejinData: merged }, () => {
          render();
          btn.textContent = '✅ 提取完成';
          setTimeout(() => {
            btn.textContent = originalText;
            btn.disabled = false;
          }, 1500);
        });
      });
    } else {
      alert('未能从当前页面提取到参数，请刷新页面后重试');
      btn.textContent = originalText;
      btn.disabled = false;
    }
  } catch (e) {
    console.error(e);
    alert('提取失败: ' + e.message);
    btn.textContent = originalText;
    btn.disabled = false;
  }
});

// 初始渲染
render();
