/**
 * Nexus Connect — Gmail Content Script
 * Floating CRM dashboard on mail.google.com.
 * Shows email campaign stats, contact lookup from threads, pipeline view.
 */

const PANEL_ID = "nexus-gmail-panel";
let panelLog = [];
let panelStatus = "Ready";
let panelMinimized = false;
let _contextDead = false;

// ── Context guard — stops everything when extension reloads ───────────

function isAlive() {
  try {
    return !_contextDead && !!chrome.runtime?.id;
  } catch {
    _contextDead = true;
    return false;
  }
}

function safeSendMessage(msg) {
  return new Promise((resolve) => {
    if (!isAlive()) return resolve({ error: "extension_disconnected" });
    try {
      chrome.runtime.sendMessage(msg, (res) => {
        if (chrome.runtime.lastError) {
          _contextDead = true;
          return resolve({ error: "extension_disconnected" });
        }
        resolve(res);
      });
    } catch {
      _contextDead = true;
      resolve({ error: "extension_disconnected" });
    }
  });
}

// ── State ─────────────────────────────────────────────────────────────

function savePanelState() {
  if (!isAlive()) return;
  try { chrome.storage.session.set({ _nxGmLog: panelLog.slice(0, 20), _nxGmStatus: panelStatus, _nxGmMin: panelMinimized }); } catch {}
}

async function loadPanelState() {
  if (!isAlive()) return;
  try {
    const d = await chrome.storage.session.get(["_nxGmLog", "_nxGmStatus", "_nxGmMin"]);
    if (d._nxGmLog) panelLog = d._nxGmLog;
    if (d._nxGmStatus) panelStatus = d._nxGmStatus;
    if (d._nxGmMin !== undefined) panelMinimized = d._nxGmMin;
  } catch {}
}

const LOG_ICONS = { "V": "\u2713", "X": "\u2717", "S": "\u25f7", "-": "\u2139", "!": "\u26a0" };

function addLog(icon, text, url = null) {
  const displayIcon = LOG_ICONS[icon] || icon;
  panelLog.unshift({ icon: displayIcon, text, url, time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) });
  if (panelLog.length > 50) panelLog.length = 50;
  updateLogUI();
  savePanelState();
}

let _showFullHistory = false;

function updateLogUI() {
  const el = document.getElementById(PANEL_ID)?.shadowRoot?.getElementById("nx-log");
  if (!el) return;
  const items = _showFullHistory ? panelLog : panelLog.slice(0, 6);
  if (items.length === 0) {
    el.innerHTML = '<div class="nx-empty">No activity yet</div>';
    return;
  }
  el.innerHTML = items.map((l) => {
    const textContent = l.url
      ? `<span class="nx-log-link" data-url="${escapeCardHtml(l.url)}">${escapeCardHtml(l.text)}</span>`
      : escapeCardHtml(l.text);
    return `<div class="nx-log-item${l.url ? ' clickable' : ''}"><span class="nx-log-icon">${l.icon}</span><span class="nx-log-text">${textContent}</span><span class="nx-log-time">${l.time}</span></div>`;
  }).join("")
    + (panelLog.length > 6 ? `<div class="nx-log-toggle" id="nx-log-toggle">${_showFullHistory ? "Show less" : `Show all (${panelLog.length})`}</div>` : '');

  el.querySelectorAll(".nx-log-link").forEach(link => {
    link.addEventListener("click", (e) => { e.stopPropagation(); window.open(link.dataset.url, "_blank"); });
  });
  const toggle = el.querySelector("#nx-log-toggle");
  if (toggle) toggle.addEventListener("click", () => { _showFullHistory = !_showFullHistory; updateLogUI(); });
}

function setStatus(text) {
  panelStatus = text;
  const el = document.getElementById(PANEL_ID)?.shadowRoot?.getElementById("nx-status");
  if (el) el.textContent = text;
  savePanelState();
}

// ── Panel injection ───────────────────────────────────────────────────

function injectPanel() {
  if (document.getElementById(PANEL_ID)) return;
  const host = document.createElement("div");
  host.id = PANEL_ID;
  host.style.cssText = "position:fixed;top:80px;right:16px;z-index:2147483647;";
  const shadow = host.attachShadow({ mode: "open" });
  shadow.innerHTML = buildPanelHTML();
  document.body.appendChild(host);
  setupPanelBehavior(host, shadow);
}

function buildPanelHTML() {
  return `
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    :host { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 13px; }
    .nx-panel { width: 300px; background: #fff; border: 1px solid #dadce0; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.12); overflow: hidden; color: #202124; }
    .nx-panel.minimized .nx-body { display: none; }
    .nx-panel.minimized { width: auto; border-radius: 10px; }
    .nx-header { display: flex; align-items: center; padding: 10px 14px; background: #f8f9fa; border-bottom: 1px solid #dadce0; cursor: move; -webkit-user-select: none; user-select: none; }
    .nx-logo { font-size: 14px; margin-right: 8px; color: #4ADE80; font-weight: 700; }
    .nx-title { font-size: 13px; font-weight: 600; color: #202124; flex: 1; }
    .nx-header-btn { background: none; border: none; color: #5f6368; cursor: pointer; font-size: 16px; padding: 2px 4px; }
    .nx-header-btn:hover { color: #202124; }
    .nx-body { padding: 12px; max-height: 450px; overflow-y: auto; }
    .nx-status { font-size: 11px; color: #4ADE80; padding: 4px 0 8px; }
    .nx-section-title { font-size: 10px; color: #5f6368; text-transform: uppercase; letter-spacing: 1px; margin: 10px 0 6px; padding-top: 8px; border-top: 1px solid #e8eaed; }
    .nx-section-title:first-child { border-top: none; margin-top: 0; padding-top: 0; }
    .nx-funnel { display: flex; gap: 4px; margin-bottom: 8px; }
    .nx-funnel-stage { flex: 1; text-align: center; padding: 6px 2px; border-radius: 6px; font-size: 10px; background: #f1f3f4; }
    .nx-funnel-stage .nx-count { font-size: 16px; font-weight: 700; display: block; color: #202124; }
    .nx-funnel-stage .nx-label { color: #5f6368; }
    .nx-contact-card { background: #f8f9fa; border: 1px solid #e8eaed; border-radius: 8px; padding: 10px; margin-bottom: 8px; }
    .nx-contact-name { font-weight: 600; color: #202124; margin-bottom: 2px; }
    .nx-contact-detail { font-size: 11px; color: #5f6368; margin-bottom: 2px; }
    .nx-stage-badge { display: inline-block; font-size: 10px; padding: 1px 6px; border-radius: 8px; font-weight: 500; }
    .nx-log { max-height: 200px; overflow-y: auto; }
    .nx-log-item { display: flex; align-items: center; padding: 3px 0; font-size: 11px; border-bottom: 1px solid #f1f3f4; }
    .nx-log-item.clickable { cursor: pointer; }
    .nx-log-item.clickable:hover { background: #f1f3f4; }
    .nx-log-icon { margin-right: 6px; font-size: 12px; }
    .nx-log-text { flex: 1; color: #5f6368; word-break: break-word; white-space: normal; line-height: 1.4; }
    .nx-log-link { color: #4ADE80; cursor: pointer; text-decoration: none; }
    .nx-log-link:hover { text-decoration: underline; }
    .nx-log-time { color: #9aa0a6; font-size: 10px; margin-left: 6px; }
    .nx-log-toggle { text-align: center; padding: 6px 0; font-size: 10px; color: #4ADE80; cursor: pointer; border-top: 1px solid #e8eaed; }
    .nx-log-toggle:hover { color: #1557b0; }
    .nx-empty { color: #9aa0a6; font-size: 11px; text-align: center; padding: 12px 0; }
    .nx-badge { display: inline-block; font-size: 10px; padding: 1px 6px; border-radius: 8px; margin-left: 6px; font-weight: 500; background: #e8f0fe; color: #4ADE80; }
    .nx-btn { display: block; width: 100%; padding: 8px; margin-top: 6px; background: #4ADE80; border: none; border-radius: 6px; color: #fff; font-size: 12px; font-weight: 500; cursor: pointer; }
    .nx-btn:hover { background: #1557b0; }
    .nx-btn.secondary { background: #f1f3f4; color: #202124; }
    .nx-btn.secondary:hover { background: #e8eaed; }
  </style>
  <div class="nx-panel" id="nx-root">
    <div class="nx-header" id="nx-drag">
      <span class="nx-logo">N</span>
      <span class="nx-title">Nexus</span>
      <span class="nx-badge" id="nx-conn-badge">connected</span>
      <button class="nx-header-btn" id="nx-minimize" title="Minimize">_</button>
      <button class="nx-header-btn" id="nx-close" title="Hide">x</button>
    </div>
    <div class="nx-body">
      <div id="nx-status" class="nx-status">Loading...</div>

      <div class="nx-section-title">Pipeline</div>
      <div class="nx-funnel" id="nx-funnel">
        <div class="nx-funnel-stage"><span class="nx-count">-</span><span class="nx-label">Cold</span></div>
        <div class="nx-funnel-stage"><span class="nx-count">-</span><span class="nx-label">Contact</span></div>
        <div class="nx-funnel-stage"><span class="nx-count">-</span><span class="nx-label">Reply</span></div>
        <div class="nx-funnel-stage"><span class="nx-count">-</span><span class="nx-label">Warm</span></div>
        <div class="nx-funnel-stage"><span class="nx-count">-</span><span class="nx-label">Hot</span></div>
      </div>

      <div class="nx-section-title">Current Contact</div>
      <div id="nx-contact-card">
        <div class="nx-empty">Open an email to see contact details</div>
      </div>

      <button class="nx-btn secondary" id="nx-refresh">Refresh Dashboard</button>

      <div class="nx-section-title">Activity</div>
      <div class="nx-log" id="nx-log"><div class="nx-empty">No activity yet</div></div>
    </div>
  </div>`;
}

function setupPanelBehavior(host, shadow) {
  const root = shadow.getElementById("nx-root");

  shadow.getElementById("nx-minimize").addEventListener("click", () => {
    panelMinimized = !panelMinimized;
    root.classList.toggle("minimized", panelMinimized);
    savePanelState();
  });

  shadow.getElementById("nx-close").addEventListener("click", () => { host.style.display = "none"; });

  // Drag
  let isDragging = false, dragX = 0, dragY = 0;
  shadow.getElementById("nx-drag").addEventListener("mousedown", (e) => {
    if (e.target.closest(".nx-header-btn")) return;
    isDragging = true;
    dragX = e.clientX - host.getBoundingClientRect().left;
    dragY = e.clientY - host.getBoundingClientRect().top;
    e.preventDefault();
  });
  document.addEventListener("mousemove", (e) => { if (!isDragging) return; host.style.left = (e.clientX - dragX) + "px"; host.style.top = (e.clientY - dragY) + "px"; host.style.right = "auto"; });
  document.addEventListener("mouseup", () => { isDragging = false; });

  shadow.getElementById("nx-refresh").addEventListener("click", () => loadDashboard(shadow));

  loadDashboard(shadow);
  loadPanelState().then(() => {
    updateLogUI();
    if (panelMinimized) root.classList.add("minimized");
  });

  // Connection badge
  if (isAlive()) {
    try {
      chrome.storage.local.get(["token"], ({ token }) => {
        if (chrome.runtime.lastError) return;
        const badge = shadow.getElementById("nx-conn-badge");
        if (badge && !token) { badge.textContent = "no token"; badge.style.background = "#fce8e6"; badge.style.color = "#d93025"; }
      });
    } catch {}
  }
}

async function loadDashboard(shadow) {
  if (!isAlive()) { setStatus("Extension disconnected"); return; }
  setStatus("Loading pipeline...");
  try {
    const data = await safeSendMessage({ action: "crm-dashboard" });
    if (data.error) { setStatus("Error: " + data.error); return; }

    const stages = data.funnelStages || {};
    const funnel = shadow.getElementById("nx-funnel");
    const stageMap = [
      { key: "cold", label: "Cold" },
      { key: "contacted", label: "Contact" },
      { key: "replied", label: "Reply" },
      { key: "warm", label: "Warm" },
      { key: "hot", label: "Hot" },
    ];
    funnel.innerHTML = stageMap.map(s =>
      `<div class="nx-funnel-stage"><span class="nx-count">${stages[s.key] || 0}</span><span class="nx-label">${s.label}</span></div>`
    ).join("");

    const total = data.totals?.contacts || 0;
    const campaigns = data.totals?.activeCampaigns || 0;
    setStatus(`${total} contacts | ${campaigns} active campaigns`);
    addLog("V", "Dashboard loaded");
  } catch {
    setStatus("Error loading dashboard");
  }
}

// ── Email thread detection ────────────────────────────────────────────

function detectEmailContact() {
  if (!isAlive()) return;
  try {
    const emailEls = document.querySelectorAll('span[email], [data-hovercard-id]');
    let email = null;
    for (const el of emailEls) {
      try {
        const e = el.getAttribute("email") || el.getAttribute("data-hovercard-id");
        if (e && e.includes("@")) { email = e; break; }
      } catch {}
    }
    if (!email) return;

    safeSendMessage({ action: "crm-lookup", platform: "email", identifier: email }).then(data => {
      if (data && !data.error) renderContactCard(data);
    });
  } catch {}
}

function renderContactCard(data) {
  try {
    const host = document.getElementById(PANEL_ID);
    if (!host) return;
    const card = host.shadowRoot?.getElementById("nx-contact-card");
    if (!card) return;

    const { contact, interactions, outreach, relationship } = data || {};
    if (!contact || !data.found) {
      card.innerHTML = `<div class="nx-contact-card"><div class="nx-contact-name">${escapeCardHtml(contact?.name || "Unknown")}</div><div class="nx-contact-detail">Not in CRM yet</div></div>`;
      return;
    }

    const stageColors = { cold: "#5f6368", contacted: "#f9ab00", replied: "#4ADE80", engaged: "#4ADE80", warm: "#e8710a", hot: "#d93025", customer: "#0d652d" };
    let html = `<div class="nx-contact-card">`;
    html += `<div class="nx-contact-name">${escapeCardHtml(contact.name)}</div>`;
    if (contact.company) html += `<div class="nx-contact-detail">${escapeCardHtml(contact.role || "")} @ ${escapeCardHtml(contact.company)}</div>`;
    html += `<div class="nx-contact-detail">Stage: <span class="nx-stage-badge" style="background:${stageColors[contact.stage] || "#5f6368"}22;color:${stageColors[contact.stage] || "#5f6368"}">${escapeCardHtml(contact.stage || "unknown")}</span></div>`;
    if (outreach) html += `<div class="nx-contact-detail">Outreach: LI:${escapeCardHtml(outreach.linkedin || "-")} | X:${escapeCardHtml(outreach.twitter || "-")} | Email:${escapeCardHtml(outreach.email || "-")}</div>`;
    if (relationship) html += `<div class="nx-contact-detail">${relationship.interactions || 0} interactions | Strength: ${Math.round((relationship.strength || 0) * 100)}%</div>`;
    if (interactions?.length > 0) {
      html += `<div class="nx-contact-detail" style="margin-top:4px;font-size:10px;color:#9aa0a6;">Last: ${escapeCardHtml(interactions[0].platform)}/${escapeCardHtml(interactions[0].type)} — ${new Date(interactions[0].date).toLocaleDateString()}</div>`;
    }
    html += `</div>`;
    card.innerHTML = html;
  } catch {}
}

function escapeCardHtml(str) {
  if (!str) return "";
  return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

// ── URL watcher (Gmail SPA) ──────────────────────────────────────────

let _lastUrl = window.location.href;
const _urlWatcher = setInterval(() => {
  if (!isAlive()) { clearInterval(_urlWatcher); return; }
  try {
    if (window.location.href !== _lastUrl) {
      _lastUrl = window.location.href;
      setTimeout(detectEmailContact, 1500);
    }
  } catch { clearInterval(_urlWatcher); }
}, 1500);

setTimeout(detectEmailContact, 3000);

// ── Message listener ─────────────────────────────────────────────────

if (isAlive()) {
  try {
    chrome.runtime.onMessage.addListener((msg) => {
      if (!isAlive()) return;
      try {
        if (msg?.nexusPanel) {
          if (msg.type === "status") setStatus(msg.data);
          if (msg.type === "log") addLog(msg.data.icon, msg.data.text, msg.data.url || null);
        }
      } catch {}
    });
  } catch {}
}

// ── Inject ───────────────────────────────────────────────────────────

if (document.body) injectPanel();
else document.addEventListener("DOMContentLoaded", injectPanel);
