const APT_URL = 'http://127.0.0.1:18247/cookie';
const APT_TOKEN = 'apt-local-bridge-token';

const tabInfo = document.getElementById('tabInfo');
const sendBtn = document.getElementById('sendBtn');
const statusMsg = document.getElementById('statusMsg');

let detectedOrigin = null;

function showStatus(message, type) {
  statusMsg.textContent = message;
  statusMsg.className = 'status-msg ' + type;
}

// Check the active tab on popup open
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  if (!tabs || tabs.length === 0) {
    tabInfo.textContent = 'No active tab found.';
    tabInfo.className = 'tab-info not-detected';
    return;
  }

  const tab = tabs[0];
  let url;
  try {
    url = new URL(tab.url);
  } catch {
    tabInfo.textContent = 'Cannot read this tab URL.';
    tabInfo.className = 'tab-info not-detected';
    return;
  }

  const hostname = url.hostname;
  const isAlta = hostname.endsWith('.avasecurity.com') || hostname.endsWith('.avigilon.com');

  if (!isAlta) {
    tabInfo.textContent = 'This tab is not an Alta deployment.';
    tabInfo.className = 'tab-info not-detected';
    return;
  }

  detectedOrigin = url.origin;
  tabInfo.textContent = 'Detected: ' + hostname;
  tabInfo.className = 'tab-info detected';
  sendBtn.disabled = false;
});

// Send cookie on button click
sendBtn.addEventListener('click', async () => {
  if (!detectedOrigin) return;

  sendBtn.disabled = true;
  showStatus('Retrieving cookie...', 'info');

  try {
    const cookie = await chrome.cookies.get({ url: detectedOrigin, name: 'va' });

    if (!cookie || !cookie.value) {
      showStatus('No "va" session cookie found. Are you logged in?', 'error');
      sendBtn.disabled = false;
      return;
    }

    if (cookie.expirationDate && cookie.expirationDate < Date.now() / 1000) {
      showStatus('Session cookie has expired. Please log in again.', 'error');
      sendBtn.disabled = false;
      return;
    }

    showStatus('Sending to Alta Proxy Tool...', 'info');

    const response = await fetch(APT_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-APT-Token': APT_TOKEN
      },
      body: JSON.stringify({
        deploymentUrl: detectedOrigin,
        cookieValue: cookie.value
      })
    });

    const data = await response.json();

    if (data.success) {
      showStatus('Cookie sent successfully!', 'success');
    } else {
      showStatus('Error: ' + (data.message || 'Unknown error'), 'error');
      sendBtn.disabled = false;
    }
  } catch (err) {
    if (err.message && err.message.includes('Failed to fetch')) {
      showStatus('Alta Proxy Tool is not running.', 'error');
    } else {
      showStatus('Error: ' + err.message, 'error');
    }
    sendBtn.disabled = false;
  }
});
