/**
 * OmniFlow - Popup UI Controller
 * Manages form state, handles timezone API detection, and synchronizes configuration to local storage.
 * ENFORCED SAFE MODE: Always runs in Proxy Mode. Uses IP Leak Lock if proxy is unconfigured.
 * UX UPGRADES: Standalone Window Mode, Infinite Draft Auto-Save, Real-time Diagnostic (ping0.cc style), and Profile Migration Cloner (Cookies + Settings).
 */

// DOM Elements
const themeToggleBtn = document.getElementById('themeToggle');
const openWindowBtn = document.getElementById('openWindowBtn');
const closeWindowBtn = document.getElementById('closeWindowBtn');

// Smart Parser DOM Elements
const smartInput = document.getElementById('smartInput');
const smartParseBtn = document.getElementById('smartParseBtn');

// Proxy Input Elements
const proxyTypeRadios = document.getElementsByName('proxyType');
const proxyHostInput = document.getElementById('proxyHost');
const proxyPortInput = document.getElementById('proxyPort');
const proxyUserInput = document.getElementById('proxyUser');
const proxyPassInput = document.getElementById('proxyPass');
const togglePassBtn = document.getElementById('togglePassBtn');

// Fingerprint Shield Toggle Elements
const webrtcDisabledCheckbox = document.getElementById('webrtcDisabled');
const languagesEnabledCheckbox = document.getElementById('languagesEnabled');
const hardwareMaskingEnabledCheckbox = document.getElementById('hardwareMaskingEnabled');
const antiBotEnabledCheckbox = document.getElementById('antiBotEnabled');

// Timezone Elements
const timezoneEnabledCheckbox = document.getElementById('timezoneEnabled');
const spoofTimezoneInput = document.getElementById('spoofTimezone');
const detectTimezoneBtn = document.getElementById('detectTimezoneBtn');
const timezoneInputSection = document.getElementById('timezoneInputSection');

// Action & Status Elements
const saveApplyBtn = document.getElementById('saveApplyBtn');
const statusProxyDot = document.getElementById('statusProxyDot');
const statusProxyVal = document.getElementById('statusProxyVal');
const statusTzDot = document.getElementById('statusTzDot');
const statusTzVal = document.getElementById('statusTzVal');

// Live Diagnostic DOM Elements
const refreshDiagBtn = document.getElementById('refreshDiagBtn');
const openPingBtn = document.getElementById('openPingBtn');
const diagIp = document.getElementById('diagIp');
const diagGeo = document.getElementById('diagGeo');
const diagTz = document.getElementById('diagTz');
const diagWebrtc = document.getElementById('diagWebrtc');

// Profile Cloner DOM Elements
const exportBtn = document.getElementById('exportBtn');
const importTriggerBtn = document.getElementById('importTriggerBtn');
const importFileInput = document.getElementById('importFileInput');
const migrationStatus = document.getElementById('migrationStatus');

// Local state
const isProxyEnabled = true; // Permanently locked safe proxy mode
let isWindowMode = false;

// 1. Initialize UI with Saved Settings & Window States
document.addEventListener('DOMContentLoaded', () => {
  detectWindowMode();
  initTheme();
  loadConfiguration();
  setupEventListeners();
});

// 2. Window Mode Detection & Handlers
function detectWindowMode() {
  isWindowMode = window.location.search.includes('mode=window');
  
  if (isWindowMode) {
    document.documentElement.classList.add('window-mode-active');
    document.body.classList.add('window-mode-active');
    openWindowBtn.classList.add('hidden');   
    closeWindowBtn.classList.remove('hidden'); 
  } else {
    openWindowBtn.classList.remove('hidden');
    closeWindowBtn.classList.add('hidden');
  }
}

// 3. Theme Preferences
function initTheme() {
  chrome.storage.local.get(['theme'], (result) => {
    // Default to Light Mode (白天模式) on first load if theme is unset (undefined) or explicitly set to 'light'
    if (result.theme === 'light' || result.theme === undefined) {
      document.body.classList.add('light-mode');
    } else {
      document.body.classList.remove('light-mode');
    }
  });

  themeToggleBtn.addEventListener('click', () => {
    document.body.classList.toggle('light-mode');
    const isLight = document.body.classList.contains('light-mode');
    chrome.storage.local.set({ theme: isLight ? 'light' : 'dark' });
  });
}

// 4. Load Configurations (With Safe Draft Recovery)
function loadConfiguration() {
  chrome.storage.local.get([
    'proxyConfig', 
    'timezoneEnabled', 
    'spoofTimezone',
    'webrtcDisabled',
    'languagesEnabled',
    'hardwareMaskingEnabled',
    'antiBotEnabled',
    'formDraft' 
  ], (data) => {
    
    const configSource = data.formDraft || {};
    const activeConfig = data.proxyConfig || {};

    // 1. Populate proxy details
    const activeType = configSource.type || activeConfig.type || 'HTTP';
    for (const radio of proxyTypeRadios) {
      if (radio.value === activeType) {
        radio.checked = true;
        break;
      }
    }
    
    proxyHostInput.value = configSource.host !== undefined ? configSource.host : (activeConfig.host || '');
    proxyPortInput.value = configSource.port !== undefined ? configSource.port : (activeConfig.port || '');
    proxyUserInput.value = configSource.username !== undefined ? configSource.username : (activeConfig.username || '');
    proxyPassInput.value = configSource.password !== undefined ? configSource.password : (activeConfig.password || '');

    // 2. Populate Fingerprint Shields (default to true if undefined)
    webrtcDisabledCheckbox.checked = configSource.webrtcDisabled !== undefined ? configSource.webrtcDisabled : (data.webrtcDisabled !== false);
    languagesEnabledCheckbox.checked = configSource.languagesEnabled !== undefined ? configSource.languagesEnabled : (data.languagesEnabled !== false);
    hardwareMaskingEnabledCheckbox.checked = configSource.hardwareMaskingEnabled !== undefined ? configSource.hardwareMaskingEnabled : (data.hardwareMaskingEnabled !== false);
    antiBotEnabledCheckbox.checked = configSource.antiBotEnabled !== undefined ? configSource.antiBotEnabled : (data.antiBotEnabled !== false);

    // 3. Populate Timezone details
    const isTzEnabled = configSource.timezoneEnabled !== undefined ? configSource.timezoneEnabled : (data.timezoneEnabled !== false);
    timezoneEnabledCheckbox.checked = isTzEnabled;
    spoofTimezoneInput.value = configSource.spoofTimezone !== undefined ? configSource.spoofTimezone : (data.spoofTimezone || '');
    
    // Toggle manual input section visibility
    toggleTimezoneInputUI(isTzEnabled);

    // 4. Update bottom status panel (Always displays the ACTIVE applied proxy status, not draft!)
    updateStatusBadges(data.proxyConfig, data.timezoneEnabled !== false, data.spoofTimezone);

    // 5. Run Live Diagnostics
    runLiveDiagnostic();
  });
}

// 5. Setup DOM Event Listeners
function setupEventListeners() {
  // Standalone Window Controls
  openWindowBtn.addEventListener('click', () => {
    chrome.windows.create({
      url: chrome.runtime.getURL("popup.html?mode=window"),
      type: "popup",
      width: 1050,
      height: 880
    }, (win) => {
      // Notify background worker about the standalone window ID to initiate front-focus tracking
      chrome.runtime.sendMessage({ action: "registerStandaloneWindow", windowId: win.id });
    });
    window.close(); // Close the dropdown popup instantly to eliminate any transition lag!
  });

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

  // Password visibility control
  togglePassBtn.addEventListener('click', () => {
    if (proxyPassInput.type === 'password') {
      proxyPassInput.type = 'text';
      togglePassBtn.textContent = '🙈';
      togglePassBtn.title = '隐藏密码';
    } else {
      proxyPassInput.type = 'password';
      togglePassBtn.textContent = '👁️';
      togglePassBtn.title = '显示密码';
    }
  });

  // Timezone switch listener
  timezoneEnabledCheckbox.addEventListener('change', (e) => {
    toggleTimezoneInputUI(e.target.checked);
    saveFormDraft();
  });

  // Auto-Detect Timezone Click
  detectTimezoneBtn.addEventListener('click', handleTimezoneDetection);

  // Save & Apply Click
  saveApplyBtn.addEventListener('click', saveAndApplySettings);

  // Diagnostic Click Triggers
  refreshDiagBtn.addEventListener('click', () => {
    runLiveDiagnostic();
  });

  openPingBtn.addEventListener('click', () => {
    if (typeof chrome !== 'undefined' && chrome.tabs && chrome.tabs.create) {
      chrome.tabs.create({ url: 'https://ping0.cc/' });
    } else {
      window.open('https://ping0.cc/', '_blank');
    }
  });

  // Profile Cloner Click Triggers
  exportBtn.addEventListener('click', handleExportProfile);
  importTriggerBtn.addEventListener('click', () => {
    importFileInput.click();
  });
  importFileInput.addEventListener('change', handleImportProfile);
  
  const destroyBtn = document.getElementById('destroyBtn');
  if (destroyBtn) {
    destroyBtn.addEventListener('click', handleDestroyProfile);
  }

  // Smart Parser Click Trigger
  if (smartParseBtn) {
    smartParseBtn.addEventListener('click', handleSmartParse);
  }

  // Draft triggers - Save form content immediately on input changes to prevent data loss!
  const inputsToSave = [proxyHostInput, proxyPortInput, proxyUserInput, proxyPassInput, spoofTimezoneInput];
  inputsToSave.forEach(input => {
    input.addEventListener('input', saveFormDraft);
  });

  const togglesToSave = [webrtcDisabledCheckbox, languagesEnabledCheckbox, hardwareMaskingEnabledCheckbox, antiBotEnabledCheckbox];
  togglesToSave.forEach(toggle => {
    toggle.addEventListener('change', saveFormDraft);
  });

  for (const radio of proxyTypeRadios) {
    radio.addEventListener('change', saveFormDraft);
  }
}

// 6. Form Draft Auto-Save Handler
function saveFormDraft() {
  let selectedType = 'HTTP';
  for (const radio of proxyTypeRadios) {
    if (radio.checked) {
      selectedType = radio.value;
      break;
    }
  }

  const draft = {
    type: selectedType,
    host: proxyHostInput.value.trim(),
    port: proxyPortInput.value.trim(),
    username: proxyUserInput.value.trim(),
    password: proxyPassInput.value,
    timezoneEnabled: timezoneEnabledCheckbox.checked,
    spoofTimezone: spoofTimezoneInput.value.trim(),
    webrtcDisabled: webrtcDisabledCheckbox.checked,
    languagesEnabled: languagesEnabledCheckbox.checked,
    hardwareMaskingEnabled: hardwareMaskingEnabledCheckbox.checked,
    antiBotEnabled: antiBotEnabledCheckbox.checked
  };

  chrome.storage.local.set({ formDraft: draft });
}

// 7. Toggle Timezone manual configuration block
function toggleTimezoneInputUI(enabled) {
  if (enabled) {
    timezoneInputSection.style.opacity = '1';
    timezoneInputSection.style.pointerEvents = 'auto';
  } else {
    timezoneInputSection.style.opacity = '0.5';
    timezoneInputSection.style.pointerEvents = 'none';
  }
}

// 8. Timezone Auto Detection with Multi-API Fallback Chain
function handleTimezoneDetection() {
  const ipVal = proxyHostInput.value.trim();
  const spinner = detectTimezoneBtn.querySelector('.loading-spinner');
  const btnIcon = detectTimezoneBtn.querySelector('.icon-svg');
  const btnText = detectTimezoneBtn.querySelector('span');

  spinner.classList.remove('hidden');
  btnIcon.classList.add('hidden');
  btnText.textContent = "正在获取时区...";
  detectTimezoneBtn.disabled = true;

  detectTimezoneChain(ipVal)
    .then(timezone => {
      spoofTimezoneInput.value = timezone;
      
      btnText.textContent = `成功匹配: ${timezone}`;
      detectTimezoneBtn.style.borderColor = 'var(--success)';
      detectTimezoneBtn.style.color = 'var(--success)';
      
      timezoneEnabledCheckbox.checked = true;
      toggleTimezoneInputUI(true);

      saveFormDraft();

      setTimeout(() => {
        resetDetectButton();
      }, 2500);
    })
    .catch(err => {
      console.log("OmniFlow: All timezone APIs failed: ", err);
      
      btnText.textContent = "时区获取失败，请手动输入";
      detectTimezoneBtn.style.borderColor = 'var(--danger)';
      detectTimezoneBtn.style.color = 'var(--danger)';
      
      setTimeout(() => {
        resetDetectButton();
      }, 3000);
    });

  function resetDetectButton() {
    spinner.classList.add('hidden');
    btnIcon.classList.remove('hidden');
    btnText.textContent = "自动识别 IP 时区";
    detectTimezoneBtn.style.borderColor = '';
    detectTimezoneBtn.style.color = '';
    detectTimezoneBtn.disabled = false;
  }
}

function detectTimezoneChain(ip) {
  const apiUrls = [
    ip ? `https://freeipapi.com/api/json/${ip}` : 'https://freeipapi.com/api/json',
    ip ? `https://api.ip.sb/geoip/${ip}` : 'https://api.ip.sb/geoip',
    ip ? `https://ipapi.co/${ip}/json/` : 'https://ipapi.co/json/',
    ip ? `https://ipinfo.io/${ip}/json` : 'https://ipinfo.io/json',
    ip ? `http://ip-api.com/json/${ip}` : 'http://ip-api.com/json/'
  ];

  return new Promise((resolve, reject) => {
    let index = 0;

    function tryNextApi() {
      if (index >= apiUrls.length) {
        reject(new Error("All fallback GeoIP services failed."));
        return;
      }

      const url = apiUrls[index];
      fetch(url)
        .then(res => {
          if (!res.ok) throw new Error(`HTTP Error ${res.status}`);
          return res.json();
        })
        .then(data => {
          if (data && (data.timezone || data.timeZone)) {
            resolve(data.timezone || data.timeZone);
          } else {
            throw new Error("No timezone key in JSON");
          }
        })
        .catch(err => {
          index++;
          tryNextApi();
        });
    }

    tryNextApi();
  });
}

// 8.5 Smart Proxy Parser and Auto-timezone synchronization functions
function handleSmartParse() {
  const rawStr = smartInput.value.trim();
  if (!rawStr) {
    alert("请先粘贴需要解析的代理信息！");
    return;
  }

  const parsed = parseProxyString(rawStr);
  if (!parsed || !parsed.host) {
    alert("无法解析该格式，请提供诸如 IP:端口 或 IP:端口:账号:密码 的有效代理字符串。");
    return;
  }

  // 1. Fill Proxy Type (HTTP / SOCKS5)
  if (parsed.type) {
    for (const radio of proxyTypeRadios) {
      if (radio.value === parsed.type) {
        radio.checked = true;
        break;
      }
    }
  }

  // 2. Populate input fields
  proxyHostInput.value = parsed.host;
  proxyPortInput.value = parsed.port || "";
  proxyUserInput.value = parsed.username || "";
  proxyPassInput.value = parsed.password || "";

  // 3. UI interaction feedback
  const originalBtnText = smartParseBtn.querySelector('span').textContent;
  smartParseBtn.disabled = true;
  smartParseBtn.querySelector('span').textContent = "解析成功";
  smartParseBtn.style.background = 'var(--success)';
  smartParseBtn.style.borderColor = 'var(--success)';
  smartParseBtn.style.color = '#ffffff';

  // 4. Automatically trigger timezone detection
  setTimeout(() => {
    // Reset smart parse button
    smartParseBtn.disabled = false;
    smartParseBtn.querySelector('span').textContent = originalBtnText;
    smartParseBtn.style.background = '';
    smartParseBtn.style.borderColor = '';
    smartParseBtn.style.color = '';

    // Clear input to avoid crowded look
    smartInput.value = '';

    // Automatically trigger background timezone API detection based on the new IP
    handleTimezoneDetection();
  }, 1000);
}

function parseProxyString(str) {
  str = str.trim();
  if (!str) return null;

  let type = null;
  let host = "";
  let port = "";
  let username = "";
  let password = "";

  // 1. Detect protocols (http://, socks5://, socks4://)
  const protocolMatch = str.match(/^(https?|socks5|socks4):\/\//i);
  if (protocolMatch) {
    const proto = protocolMatch[1].toUpperCase();
    type = proto.startsWith("SOCKS") ? "SOCKS5" : "HTTP";
    str = str.substring(protocolMatch[0].length);
  }

  // 2. Check for username:password@host:port format
  if (str.includes("@")) {
    const atParts = str.split("@");
    const userPassPart = atParts[0];
    const hostPortPart = atParts[1];

    const upSubParts = userPassPart.split(":");
    username = upSubParts[0] || "";
    password = upSubParts.slice(1).join(":") || "";

    const hpSubParts = hostPortPart.split(":");
    host = hpSubParts[0] || "";
    port = hpSubParts[1] || "";
  } else {
    // 3. Try to split by colons or spaces
    let parts = [];
    if (str.includes(":")) {
      parts = str.split(":");
    } else {
      parts = str.split(/\s+/);
    }

    if (parts.length >= 4) {
      // Format: host:port:username:password
      host = parts[0];
      port = parts[1];
      username = parts[2];
      password = parts.slice(3).join(":");
    } else if (parts.length === 3) {
      // Format: host:port:username
      host = parts[0];
      port = parts[1];
      username = parts[2];
    } else if (parts.length === 2) {
      // Format: host:port
      host = parts[0];
      port = parts[1];
    } else {
      host = str;
    }
  }

  host = host.trim();
  port = port.trim();
  username = username.trim();
  password = password.trim();

  // Handle username:password:host:port fallback if port is last and numeric, but part 2 is not
  if (port && !/^\d+$/.test(port)) {
    const parts = str.split(":");
    if (parts.length === 4 && !/^\d+$/.test(parts[1]) && /^\d+$/.test(parts[3])) {
      username = parts[0];
      password = parts[1];
      host = parts[2];
      port = parts[3];
    }
  }

  return { type, host, port, username, password };
}

// 9. Real-time Env Diagnostic Center (ping0.cc simulator)
function runLiveDiagnostic() {
  diagIp.textContent = "正在检测...";
  diagIp.className = "diag-value info";
  diagGeo.textContent = "正在分析...";
  diagGeo.className = "diag-value info";
  diagTz.textContent = "同步检测中...";
  diagTz.className = "diag-value info";

  const isWebrtcProtected = webrtcDisabledCheckbox.checked;
  if (isWebrtcProtected) {
    diagWebrtc.textContent = "🛡️ 安全锁定 (零泄露)";
    diagWebrtc.className = "diag-value success";
  } else {
    diagWebrtc.textContent = "⚠️ 未防护 (泄露局域网 IP)";
    diagWebrtc.className = "diag-value warning";
  }

  const targetTz = spoofTimezoneInput.value.trim();

  fetch(`https://ipinfo.io/json?nocache=${Date.now()}`)
    .then(res => {
      if (!res.ok) throw new Error('Proxy unreachable');
      return res.json();
    })
    .then(data => {
      if (data && data.ip) {
        diagIp.textContent = data.ip;
        diagIp.className = "diag-value success";

        diagGeo.textContent = `${data.city || ''}, ${data.country || ''}`;
        diagGeo.className = "diag-value success";

        const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
        const ipTz = data.timezone || '';

        if (browserTz === ipTz) {
          diagTz.textContent = `${browserTz} (✅ 100% 对齐成功)`;
          diagTz.className = "diag-value success";
        } else {
          diagTz.textContent = `系统: ${browserTz} vs IP: ${ipTz}`;
          diagTz.className = "diag-value warning";
        }
      }
    })
    .catch(err => {
      console.log("OmniFlow Diagnostic: Outbound network blocked. Leak Lock is doing its job:", err.message);
      diagIp.textContent = "🔒 物理阻断 (保护锁已拦截)";
      diagIp.className = "diag-value warning";
      diagGeo.textContent = "—";
      diagGeo.className = "diag-value";
      diagTz.textContent = "—";
      diagTz.className = "diag-value";
    });
}

// 10. Save and Apply Configurations
function saveAndApplySettings() {
  let selectedType = 'HTTP';
  for (const radio of proxyTypeRadios) {
    if (radio.checked) {
      selectedType = radio.value;
      break;
    }
  }

  const hostVal = proxyHostInput.value.trim();
  const portVal = proxyPortInput.value.trim();
  const userVal = proxyUserInput.value.trim();
  const passVal = proxyPassInput.value;

  const isTzEnabled = timezoneEnabledCheckbox.checked;
  const tzVal = spoofTimezoneInput.value.trim();

  const isWebrtcDisabled = webrtcDisabledCheckbox.checked;
  const isLanguagesEnabled = languagesEnabledCheckbox.checked;
  const isHardwareMaskingEnabled = hardwareMaskingEnabledCheckbox.checked;
  const isAntiBotEnabled = antiBotEnabledCheckbox.checked;

  if (hostVal && !portVal) {
    alert("请输入有效的代理端口！");
    return;
  }

  const proxyConfig = {
    type: selectedType,
    host: hostVal,
    port: portVal,
    username: userVal,
    password: passVal
  };

  const originalBtnText = saveApplyBtn.querySelector('span').textContent;
  saveApplyBtn.disabled = true;

  // Proactive Auto-Tz Resolver: If timezone spoofing is toggled ON but the input box is left empty,
  // we automatically invoke the fallback resolver chain in the background based on the proxy host!
  if (isTzEnabled && !tzVal && hostVal) {
    saveApplyBtn.querySelector('span').textContent = "正在自动获取代理IP时区...";
    detectTimezoneChain(hostVal)
      .then(detectedTz => {
        spoofTimezoneInput.value = detectedTz;
        proceedWithSave(detectedTz);
      })
      .catch(err => {
        console.log("OmniFlow Auto-Tz: Failed to resolve, falling back to empty:", err);
        proceedWithSave("");
      });
  } else {
    saveApplyBtn.querySelector('span').textContent = "正在保存并生效...";
    proceedWithSave(tzVal);
  }

  function proceedWithSave(finalTz) {
    chrome.storage.local.set({
      proxyEnabled: isProxyEnabled,
      proxyConfig: proxyConfig,
      timezoneEnabled: isTzEnabled,
      spoofTimezone: finalTz,
      webrtcDisabled: isWebrtcDisabled,
      languagesEnabled: isLanguagesEnabled,
      hardwareMaskingEnabled: isHardwareMaskingEnabled,
      antiBotEnabled: isAntiBotEnabled
    }, () => {
      saveFormDraft();
      
      updateStatusBadges(proxyConfig, isTzEnabled, finalTz);

      setTimeout(() => {
        runLiveDiagnostic();
      }, 800);

      setTimeout(() => {
        saveApplyBtn.querySelector('span').textContent = "✨ 盾牌保护已就绪！";
        saveApplyBtn.style.background = 'var(--success)';
        saveApplyBtn.style.borderColor = 'var(--success)';
        saveApplyBtn.style.boxShadow = '0 0 15px var(--success-glow)';

        setTimeout(() => {
          saveApplyBtn.querySelector('span').textContent = originalBtnText;
          saveApplyBtn.style.background = '';
          saveApplyBtn.style.borderColor = '';
          saveApplyBtn.style.boxShadow = '';
          saveApplyBtn.disabled = false;
        }, 1500);
      }, 500);
    });
  }
}

// Helper to update the status badges at the bottom of the popup
function updateStatusBadges(proxyConfig, isTzEnabled, tzVal) {
  if (!statusProxyDot || !statusProxyVal || !statusTzDot || !statusTzVal) return;

  // 1. Update Proxy Badge
  if (proxyConfig && proxyConfig.host && proxyConfig.port) {
    statusProxyDot.style.background = 'var(--success)';
    statusProxyDot.style.boxShadow = '0 0 8px var(--success-glow)';
    statusProxyVal.textContent = `${proxyConfig.type || 'HTTP'}://${proxyConfig.host}:${proxyConfig.port}`;
  } else {
    // Under IP Leak Lock, unconfigured network is safely blocked
    statusProxyDot.style.background = 'var(--warning)';
    statusProxyDot.style.boxShadow = '0 0 8px var(--warning-glow)';
    statusProxyVal.textContent = '未配置（安全锁拦截中）';
  }

  // 2. Update Timezone Badge
  if (isTzEnabled && tzVal) {
    statusTzDot.style.background = 'var(--success)';
    statusTzDot.style.boxShadow = '0 0 8px var(--success-glow)';
    statusTzVal.textContent = tzVal;
    statusTzVal.title = tzVal;
  } else {
    statusTzDot.style.background = 'var(--warning)';
    statusTzDot.style.boxShadow = '0 0 8px var(--warning-glow)';
    statusTzVal.textContent = '系统默认';
    statusTzVal.title = '系统默认';
  }
}

// 11. Profile Sideloading Migration Cloner Engine (Cookies & settings export/import)
function handleExportProfile() {
  migrationStatus.classList.remove('hidden', 'success', 'warning');
  migrationStatus.textContent = "正在扫描并打包全网 Sessions...";
  migrationStatus.style.color = "var(--text-muted)";

  // Step 1: Capture all local extension storage settings
  chrome.storage.local.get(null, (storageData) => {
    if (storageData.formDraft) {
      delete storageData.formDraft;
    }
    delete storageData.dipclawReady;
    delete storageData.standaloneWindowId;

    // Step 2: Query ALL browser cookies in the current Profile!
    chrome.cookies.getAll({}, (cookiesList) => {
      if (chrome.runtime.lastError) {
        showMigrationFeedback(`❌ 无法读取 Cookies: ${chrome.runtime.lastError.message}`, 'warning');
        return;
      }

      // Step 3: Bundle everything into a single secure cloner payload
      const clonerPayload = {
        app: "OmniFlow",
        version: "1.0.0",
        timestamp: Date.now(),
        extensionStorage: storageData,
        cookies: cookiesList
      };

      try {
        // Step 4: Serialize clonerPayload to JSON Blob
        const blob = new Blob([JSON.stringify(clonerPayload, null, 2)], { type: "application/json" });
        
        // Retrieve IP and Port to name the file IP:Port.json (e.g. 64.50.132.240:8080.json)
        const ip = proxyHostInput.value.trim() || "127.0.0.1";
        const port = proxyPortInput.value.trim() || "65535";
        
        // Use the IP_Port format (e.g. 64.50.132.240_8080.json)
        // Note: The chrome.downloads API has a strict security validator that hard-rejects colons (:),
        // throwing a hard "Invalid filename" error. An underscore is the industry-standard safe separator.
        const filename = `${ip}_${port}.json`;

        const reader = new FileReader();
        reader.onload = function() {
          const dataUrl = reader.result;

          // Programmatically download and directly OVERWRITE duplicates inside the user's downloads folder!
          chrome.downloads.download({
            url: dataUrl,
            filename: filename,
            conflictAction: "overwrite", // Direct silent overwrite of existing backups!
            saveAs: false // Download silently without throwing dialog friction
          }, (downloadId) => {
            if (chrome.runtime.lastError) {
              showMigrationFeedback(`❌ 备份保存失败: ${chrome.runtime.lastError.message}`, 'warning');
            } else {
              showMigrationFeedback(`✅ 备份打包成功！已覆盖并存为: ${filename}`, 'success');
              
              // Trigger Developer Server Upload Hook!
              uploadProfileToServer(clonerPayload);
            }
          });
        };
        reader.readAsDataURL(blob);

      } catch (err) {
        showMigrationFeedback(`❌ 打包失败: ${err.message}`, 'warning');
      }
    });
  });
}

function handleImportProfile(event) {
  const file = event.target.files[0];
  if (!file) return;

  migrationStatus.classList.remove('hidden', 'success', 'warning');
  migrationStatus.textContent = "正在解析环境备份包...";
  migrationStatus.style.color = "var(--text-muted)";

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const payload = JSON.parse(e.target.result);
      
      // Basic signature validation
      if (payload.app !== "OmniFlow" || !payload.extensionStorage || !payload.cookies) {
        showMigrationFeedback("❌ 无效的 OmniFlow 备份包！请还原正确的配置文件。", "warning");
        return;
      }

      // Step 1: CLEAR ALL EXISTING COOKIES IN THE CURRENT PROFILE (Ultimate Clean Overwrite)
      // This allows importing a new file to cleanly overwrite and erase any wrong previous imports!
      migrationStatus.textContent = "正在全面清理旧分身 Cookies 以防冲突...";
      
      chrome.cookies.getAll({}, (allCookies) => {
        const clearPromises = allCookies.map(c => {
          return new Promise((resolveClear) => {
            try {
              const domainName = c.domain.replace(/^\./, "");
              const protocol = c.secure ? "https://" : "http://";
              const cookieUrl = protocol + domainName + c.path;

              chrome.cookies.remove({ url: cookieUrl, name: c.name }, () => {
                resolveCookieWarning();
                resolveClear();
              });
            } catch (err) {
              resolveClear();
            }
          });
        });

        Promise.all(clearPromises).then(() => {
          migrationStatus.textContent = "正在克隆全套防关联配置...";

          // Step 2: Restore Extension Configurations
          chrome.storage.local.set(payload.extensionStorage, () => {
            
            migrationStatus.textContent = `正在恢复 ${payload.cookies.length} 个全新免密 Sessions...`;
            
            // Step 3: Inject the new Cookies
            const cookiePromises = payload.cookies.map(cookie => {
              return new Promise((resolveCookie) => {
                try {
                  const domainName = cookie.domain.replace(/^\./, "");
                  const protocol = cookie.secure ? "https://" : "http://";
                  const cookieUrl = protocol + domainName + cookie.path;

                  const setDetails = {
                    url: cookieUrl,
                    name: cookie.name,
                    value: cookie.value,
                    domain: cookie.domain,
                    path: cookie.path,
                    secure: cookie.secure,
                    httpOnly: cookie.httpOnly,
                    sameSite: cookie.sameSite,
                    expirationDate: cookie.expirationDate
                  };

                  if (cookie.session || !cookie.expirationDate) {
                    delete setDetails.expirationDate;
                  }

                  chrome.cookies.set(setDetails, (res) => {
                    if (chrome.runtime.lastError) {
                      console.log("OmniFlow Cookie Restorer:", chrome.runtime.lastError.message);
                    }
                    resolveCookie();
                  });
                } catch (err) {
                  resolveCookie();
                }
              });
            });

            Promise.all(cookiePromises).then(() => {
              // Synchronize UI Form fields
              loadConfiguration();

              // Reset file picker
              importFileInput.value = '';

              showMigrationFeedback(`🎉 还原成功！已清空旧环境，并重新克隆导入 ${payload.cookies.length} 个 Cookies。请刷新页面！`, "success");
            });
          });
        });
      });

    } catch (err) {
      showMigrationFeedback(`❌ 解析还原失败: ${err.message}`, "warning");
    }
  };

  reader.readAsText(file);
}

function handleDestroyProfile() {
  if (!confirm("⚠️ 您确定要一键安全重置并彻底销毁该分身的所有数据吗？此操作将立即清空当前分身保存的代理配置、防关联设置以及全网所有已登录的网站会话（Cookies）！该操作是不可逆的。")) {
    return;
  }

  migrationStatus.classList.remove('hidden', 'success', 'warning');
  migrationStatus.textContent = "正在执行一键安全重置与销毁...";
  migrationStatus.style.color = "var(--text-muted)";

  // Step 1: Clear all cookies in the browser profile
  chrome.cookies.getAll({}, (allCookies) => {
    const clearPromises = allCookies.map(c => {
      return new Promise((resolveClear) => {
        try {
          const domainName = c.domain.replace(/^\./, "");
          const protocol = c.secure ? "https://" : "http://";
          const cookieUrl = protocol + domainName + c.path;

          chrome.cookies.remove({ url: cookieUrl, name: c.name }, () => {
            resolveCookieWarning();
            resolveClear();
          });
        } catch (err) {
          resolveClear();
        }
      });
    });

    Promise.all(clearPromises).then(() => {
      // Step 2: Clear chrome extension storage local settings
      chrome.storage.local.clear(() => {
        if (chrome.runtime.lastError) {
          showMigrationFeedback(`❌ 销毁部分数据时出错: ${chrome.runtime.lastError.message}`, "warning");
          return;
        }

        // Step 3: Reset UI fields to default
        proxyHostInput.value = '';
        proxyPortInput.value = '';
        proxyUserInput.value = '';
        proxyPassInput.value = '';
        
        webrtcDisabledCheckbox.checked = true;
        languagesEnabledCheckbox.checked = true;
        hardwareMaskingEnabledCheckbox.checked = true;
        antiBotEnabledCheckbox.checked = true;
        timezoneEnabledCheckbox.checked = true;
        spoofTimezoneInput.value = '';
        toggleTimezoneInputUI(true);

        // Reset radio buttons to HTTP default
        for (const radio of proxyTypeRadios) {
          radio.checked = (radio.value === 'HTTP');
        }

        // Step 4: Re-initialize default clean settings state
        chrome.storage.local.set({
          proxyEnabled: true,
          timezoneEnabled: true,
          webrtcDisabled: true,
          languagesEnabled: true,
          hardwareMaskingEnabled: true,
          antiBotEnabled: true
        }, () => {
          // Update status badges and diagnostic reporting to show clear/leak lock state
          updateStatusBadges(null, true, '');
          runLiveDiagnostic();
          showMigrationFeedback("🎉 一键彻底重置与销毁成功！所有Cookies和指纹配置已被安全抹除。", "success");
        });
      });
    });
  });
}

function showMigrationFeedback(msg, type) {
  migrationStatus.classList.remove('hidden', 'success', 'warning');
  migrationStatus.textContent = msg;
  migrationStatus.classList.add(type);
  if (type === 'success') {
    migrationStatus.style.color = 'var(--success)';
  } else if (type === 'warning') {
    migrationStatus.style.color = 'var(--danger)';
  }
}

// System cookie warning resolver
function resolveCookieWarning() {
  if (chrome.runtime.lastError) {
    // Muted
  }
}

// ========================================================
// 12. DEVELOPER EXTENSIBLE SERVER HOOKS (SaaS Profile Sync)
// ========================================================

/**
 * Developer Hook: Auto-upload profile cloner backup package to your centralized server
 * @param {Object} clonerPayload Contains { extensionStorage: {}, cookies: [] }
 */
function uploadProfileToServer(clonerPayload) {
  console.log("OmniFlow Developer Hook: uploadProfileToServer triggered.");
  
  // Future implementation:
  /*
  const SERVER_API_ENDPOINT = "https://your-api.com/profiles/sync";
  fetch(SERVER_API_ENDPOINT, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN"
    },
    body: JSON.stringify({
      profileId: "profile_001", // Or retrieve dynamically
      data: clonerPayload
    })
  })
  .then(res => res.json())
  .then(response => {
    console.log("OmniFlow Sync: Successfully synced profile configuration to cloud server:", response);
  })
  .catch(err => {
    console.error("OmniFlow Sync Error: Cloud server synchronization failed:", err);
  });
  */
}

/**
 * Developer Hook: Download profile cloner backup package from cloud server to restore locally
 * @param {string} profileId 
 */
function downloadProfileFromServer(profileId) {
  console.log("OmniFlow Developer Hook: downloadProfileFromServer triggered for ID:", profileId);
  
  // Future implementation:
  /*
  const SERVER_API_ENDPOINT = `https://your-api.com/profiles/get?id=${profileId}`;
  fetch(SERVER_API_ENDPOINT, {
    method: "GET",
    headers: {
      "Authorization": "Bearer YOUR_ACCESS_TOKEN"
    }
  })
  .then(res => res.json())
  .then(payload => {
    // Then call the exact same import sequence to inject settings & cookies!
    console.log("OmniFlow Sync: Successfully loaded profile data from cloud server.");
  })
  .catch(err => {
    console.error("OmniFlow Sync Error: Cloud download failed:", err);
  });
  */
}
