/**
 * Nexus Connect — Telegram Content Script
 * Floating panel on web.telegram.org.
 * All actions route through the bot API — no DOM automation.
 */

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

// ── State persistence ─────────────────────────────────────────────────

function savePanelState() {
  try { chrome.storage.session.set({ _nxTgLog: panelLog.slice(0, 50), _nxTgStatus: panelStatus, _nxTgMin: panelMinimized }); } catch {}
}

async function loadPanelState() {
  try {
    const d = await chrome.storage.session.get(["_nxTgLog", "_nxTgStatus", "_nxTgMin"]);
    if (d._nxTgLog) panelLog = d._nxTgLog;
    if (d._nxTgStatus) panelStatus = d._nxTgStatus;
    if (d._nxTgMin !== undefined) panelMinimized = d._nxTgMin;
  } 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, 8);
  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="${l.url}">${l.text}</span>` : 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 > 8 ? `<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();
}

// ── API helpers ───────────────────────────────────────────────────────

function telegramApi(action, params = {}) {
  return new Promise((resolve, reject) => {
    const attempt = (retryLeft) => {
      chrome.runtime.sendMessage({ action, params }, (res) => {
        const err = chrome.runtime.lastError;
        if (err && retryLeft > 0 && (err.message.includes("context invalidated") || err.message.includes("establish connection"))) {
          setTimeout(() => attempt(retryLeft - 1), 1000);
          return;
        }
        if (err) return reject(new Error(err.message));
        if (res?.error) return reject(new Error(res.error));
        resolve(res);
      });
    };
    attempt(2);
  });
}

function crmSync(data) {
  try { chrome.runtime.sendMessage({ action: "crm-sync", ...data }); } catch {}
}

// Keepalive
let _keepaliveInterval = null;
function startKeepalive() {
  if (_keepaliveInterval) return;
  _keepaliveInterval = setInterval(() => {
    try { chrome.runtime.sendMessage({ action: "keepalive" }).catch(() => {}); }
    catch { clearInterval(_keepaliveInterval); _keepaliveInterval = null; }
  }, 25000);
}

// ── Humanization ──────────────────────────────────────────────────────
// humanDelay lives in content-common.js, prepended to this content_scripts
// entry in manifest.json (shared MV3 isolated world).

// ── Action configs ────────────────────────────────────────────────────

const ACTION_CONFIGS = {
  "group-scraper": {
    title: "Group Scraper",
    html: `
      <label class="nx-label">Group link or @username</label>
      <input class="nx-input" id="cfg-group" type="text" placeholder="https://t.me/cryptogroup or @groupname">
      <p class="nx-hint">Scrapes group members and auto-syncs them to the CRM as contacts. Members become available for cross-platform campaigns.</p>`,
    async start(shadow) {
      const groupLink = shadow.getElementById("cfg-group").value.trim();
      if (!groupLink) { setStatus("Enter a group link"); return; }

      setStatus("Scraping group...");
      addLog("S", `Scraping: ${groupLink}`);
      try {
        const result = await telegramApi("telegram-scrape", { groupLink, filters: [] });
        if (result.members) {
          addLog("V", `Scraped ${result.members} members from ${result.groupName || groupLink}`);
          setStatus(`Done! ${result.members} members scraped`);
        } else {
          addLog("V", `Scrape initiated: ${result.message || "processing..."}`);
          setStatus("Scrape initiated — check Telegram bot for results");
        }
      } catch (err) {
        addLog("X", err.message);
        setStatus("Error: " + err.message);
      }
    },
  },
  "group-analytics": {
    title: "Group Analytics",
    html: `<p class="nx-hint">Shows all scraped groups with member counts and active talker data.</p>`,
    async start() {
      setStatus("Loading groups...");
      try {
        const result = await telegramApi("telegram-groups", {});
        const groups = result.groups || [];
        if (groups.length === 0) {
          addLog("-", "No groups scraped yet. Use Group Scraper first.");
          setStatus("No groups found");
          return;
        }
        for (const g of groups) {
          const link = g.source_link || (g.chat_id ? `Chat: ${g.chat_id}` : null);
          addLog("V", `${g.title || "Group"}: ${g.member_count || "?"} members (scraped ${g.scraped_at ? new Date(g.scraped_at).toLocaleDateString() : "?"})`, link);
        }
        setStatus(`${groups.length} groups loaded`);
      } catch (err) {
        addLog("X", err.message);
        setStatus("Error: " + err.message);
      }
    },
  },
  "bulk-dm": {
    title: "Bulk DM",
    html: `
      <label class="nx-label">Message</label>
      <textarea class="nx-input nx-textarea" id="cfg-message" rows="3" placeholder="Hi! I noticed you're in the crypto space..."></textarea>
      <label class="nx-label">Recipients (one @username per line)</label>
      <textarea class="nx-input nx-textarea" id="cfg-recipients" rows="3" placeholder="@user1\n@user2\n@user3"></textarea>
      <p class="nx-hint">Sends DMs via the Telegram account pool with automatic rotation and rate limiting.</p>`,
    async start(shadow) {
      const message = shadow.getElementById("cfg-message").value.trim();
      const recipients = shadow.getElementById("cfg-recipients").value.split("\n").map(s => s.trim().replace(/^@/, "")).filter(Boolean);
      if (!message) { setStatus("Enter a message"); return; }
      if (recipients.length === 0) { setStatus("Enter at least one recipient"); return; }

      addLog("S", `Sending DM to ${recipients.length} recipients`);
      let sent = 0, failed = 0;

      for (const username of recipients) {
        setStatus(`(${sent + 1}/${recipients.length}) DMing @${username}...`);
        try {
          await telegramApi("telegram-dm", { recipientUsername: username, message });
          sent++;
          addLog("V", `DM sent: @${username}`);
          crmSync({ platform: "telegram", identifier: username, action: "dm_sent", source: "bulk_dm" });
        } catch (err) {
          failed++;
          addLog("X", `@${username}: ${err.message}`);
        }
        await humanDelay(5000); // 5s+ between DMs
      }

      setStatus(`Done! Sent: ${sent}${failed ? `, Failed: ${failed}` : ""}`);
      addLog("V", `Bulk DM complete: ${sent}/${recipients.length}`);
    },
  },
  "account-pool": {
    title: "Account Pool",
    html: `<p class="nx-hint">Shows Telegram account health, daily actions, and cooldown status.</p>`,
    async start() {
      setStatus("Loading accounts...");
      try {
        const result = await telegramApi("telegram-accounts", {});
        const accounts = result.accounts || [];
        if (accounts.length === 0) {
          addLog("-", "No Telegram accounts configured");
          setStatus("No accounts found");
          return;
        }
        for (const a of accounts) {
          const icon = a.health >= 70 ? "V" : a.health >= 40 ? "-" : "X";
          addLog(icon, `${a.phone || a.username || "Account"}: health ${a.health || "?"}, ${a.actionsToday || 0} actions today${a.cooldownUntil ? ` (cooldown until ${new Date(a.cooldownUntil).toLocaleTimeString()})` : ""}`);
        }
        setStatus(`${accounts.length} accounts loaded`);
      } catch (err) {
        addLog("X", err.message);
        setStatus("Error: " + err.message);
      }
    },
  },
  "crm-dashboard": {
    title: "Open CRM Dashboard",
    html: `<p class="nx-hint">View the full CRM dashboard in a new tab — pipeline funnel, top leads, account health, and Telegram stats live here.</p>
      <p class="nx-hint" style="opacity:0.7;">Press <b>Start</b> below to open it.</p>`,
    async start() {
      try {
        const url = chrome.runtime.getURL("dashboard.html#crm");
        window.open(url, "_blank", "noopener");
        setStatus("Opening dashboard…");
        addLog("V", "Opened CRM dashboard in new tab");
      } catch (err) {
        addLog("X", err.message);
        setStatus("Error: " + err.message);
      }
    },
  },
};

const MENU_ITEMS = [
  // ── Intelligence ──
  { id: "group-scraper", icon: "S", label: "Group Scraper" },
  { id: "group-analytics", icon: "G", label: "Group Analytics" },
  // ── Engage ──
  { id: "bulk-dm", icon: "B", label: "Bulk DM" },
  // ── Manage ──
  { id: "account-pool", icon: "P", label: "Account Pool" },
  { id: "crm-dashboard", icon: "D", label: "Dashboard" },
];

// ── Panel UI ──────────────────────────────────────────────────────────

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);
  startKeepalive();
}

function buildPanelHTML() {
  const menuHTML = MENU_ITEMS.map(m =>
    `<div class="nx-menu-item" data-action="${m.id}"><span class="nx-menu-icon">${m.icon}</span><span class="nx-menu-label">${m.label}</span><span class="nx-menu-arrow">&rsaquo;</span></div>`
  ).join("");

  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: #0f0f11; border: 1px solid #2a2a38; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.5); overflow: hidden; color: #e0e0e8; }
    .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: #0a1628; border-bottom: 1px solid #1a2a44; cursor: move; -webkit-user-select: none; user-select: none; }
    .nx-logo { font-size: 16px; margin-right: 8px; color: #4ADE80; font-weight: 700; }
    .nx-title { font-size: 13px; font-weight: 600; color: #fff; flex: 1; }
    .nx-header-btn { background: none; border: none; color: #666; cursor: pointer; font-size: 16px; padding: 2px 4px; }
    .nx-header-btn:hover { color: #ccc; }
    .nx-body { padding: 0; max-height: 480px; overflow-y: auto; }
    .nx-status { font-size: 11px; color: #4ADE80; padding: 8px 12px 4px; }
    .nx-menu-item { display: flex; align-items: center; padding: 9px 12px; cursor: pointer; border-bottom: 1px solid #0d0d10; transition: background 0.12s; }
    .nx-menu-item:hover { background: #1a1a22; }
    .nx-menu-icon { width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; background: #0a1628; border-radius: 4px; font-size: 11px; font-weight: 700; color: #4ADE80; margin-right: 10px; }
    .nx-menu-label { flex: 1; font-size: 12px; color: #e0e0e8; }
    .nx-menu-arrow { color: #444; font-size: 16px; }
    .nx-config-page { padding: 12px; }
    .nx-back-row { display: flex; align-items: center; padding: 0 0 8px; margin-bottom: 8px; border-bottom: 1px solid #1a1a22; }
    .nx-back-btn { background: none; border: none; color: #4ADE80; cursor: pointer; font-size: 13px; padding: 2px 8px 2px 0; }
    .nx-config-title { font-size: 13px; font-weight: 600; color: #fff; flex: 1; }
    .nx-label { display: block; font-size: 11px; color: #888; margin: 8px 0 4px; }
    .nx-label:first-child { margin-top: 0; }
    .nx-hint { font-size: 11px; color: #555; margin-top: 6px; line-height: 1.4; }
    .nx-input { width: 100%; background: #1a1a22; border: 1px solid #2a2a38; border-radius: 6px; color: #e0e0e8; padding: 7px 10px; font-size: 12px; outline: none; }
    .nx-input:focus { border-color: #4ADE80; }
    .nx-textarea { resize: vertical; min-height: 36px; font-family: inherit; }
    .nx-start-btn { display: block; width: 100%; padding: 10px; margin-top: 12px; background: #4ADE80; border: none; border-radius: 20px; color: #fff; font-size: 13px; font-weight: 600; cursor: pointer; }
    .nx-start-btn:hover { background: #006699; }
    .nx-start-btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .nx-log-section { padding: 0 12px 8px; }
    .nx-section-title { font-size: 10px; color: #555; text-transform: uppercase; letter-spacing: 1px; margin: 0; padding: 8px 12px 4px; }
    .nx-log { max-height: 240px; overflow-y: auto; }
    .nx-log-item { display: flex; align-items: center; padding: 3px 0; font-size: 11px; border-bottom: 1px solid #0d0d10; }
    .nx-log-item.clickable { cursor: pointer; }
    .nx-log-item.clickable:hover { background: #1a1a22; }
    .nx-log-icon { margin-right: 6px; font-size: 12px; flex-shrink: 0; }
    .nx-log-text { flex: 1; color: #ccc; word-break: break-word; white-space: normal; line-height: 1.4; }
    .nx-log-link { color: #4ADE80; cursor: pointer; }
    .nx-log-link:hover { text-decoration: underline; }
    .nx-log-time { color: #555; font-size: 10px; margin-left: 6px; flex-shrink: 0; }
    .nx-log-toggle { text-align: center; padding: 6px 0; font-size: 10px; color: #4ADE80; cursor: pointer; border-top: 1px solid #1a1a22; }
    .nx-empty { color: #444; 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; }
    .nx-badge.on { background: #1a3a1a; color: #4ade80; }
    .nx-badge.off { background: #3a1a1a; color: #f87171; }
  </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 on" 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">Ready</div>
      <div id="nx-menu">${menuHTML}</div>
      <div id="nx-config" style="display:none">
        <div class="nx-config-page">
          <div class="nx-back-row">
            <button class="nx-back-btn" id="nx-back">&lsaquo; Back</button>
            <span class="nx-config-title" id="nx-config-title"></span>
          </div>
          <div id="nx-config-form"></div>
          <button class="nx-start-btn" id="nx-start">Start</button>
        </div>
      </div>
      <div class="nx-log-section">
        <div class="nx-section-title" style="border-top:none;padding-left:0;">Activity Log</div>
        <div class="nx-log" id="nx-log"><div class="nx-empty">No activity yet</div></div>
      </div>
    </div>
  </div>`;
}

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

  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; });

  // Menu navigation
  function showMenu() {
    shadow.getElementById("nx-menu").style.display = "block";
    shadow.getElementById("nx-config").style.display = "none";
    currentAction = null;
  }

  function showConfig(actionId) {
    const config = ACTION_CONFIGS[actionId];
    if (!config) return;
    currentAction = actionId;
    shadow.getElementById("nx-menu").style.display = "none";
    shadow.getElementById("nx-config").style.display = "block";
    shadow.getElementById("nx-config-title").textContent = config.title;
    shadow.getElementById("nx-config-form").innerHTML = config.html;
    if (config.init) config.init(shadow);
  }

  shadow.querySelectorAll(".nx-menu-item").forEach(item => {
    item.addEventListener("click", () => showConfig(item.dataset.action));
  });

  shadow.getElementById("nx-back").addEventListener("click", showMenu);

  shadow.getElementById("nx-start").addEventListener("click", async () => {
    if (!currentAction) return;
    const config = ACTION_CONFIGS[currentAction];
    if (!config) return;
    const btn = shadow.getElementById("nx-start");
    btn.disabled = true; btn.textContent = "Running...";
    try { await config.start(shadow); } catch (err) { setStatus("Error: " + err.message); addLog("X", err.message); }
    btn.disabled = false; btn.textContent = "Start";
  });

  // Restore state
  loadPanelState().then(() => {
    updateLogUI();
    const statusEl = shadow.getElementById("nx-status");
    if (statusEl && panelStatus) statusEl.textContent = panelStatus;
    if (panelMinimized) root.classList.add("minimized");
  });

  // Connection badge
  chrome.storage.local.get(["token"], ({ token }) => {
    const badge = shadow.getElementById("nx-conn-badge");
    badge.textContent = token ? "connected" : "no token";
    badge.className = token ? "nx-badge on" : "nx-badge off";
  });
}

// Message listener for panel notifications
chrome.runtime.onMessage.addListener((msg) => {
  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);
  }
});

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

console.log("[Nexus Connect] Telegram content script active");
