// content/injector.js — mejoras visuales y automatización en Skool
(function () {
  'use strict';
  if (window.__SKOOP_INJECTOR__) return;
  window.__SKOOP_INJECTOR__ = true;

  // ── APLICAR CONFIGURACIÓN GUARDADA ───────────────────────

  async function loadAndApply() {
    const r = await chrome.storage.local.get('skoop_settings').catch(() => ({}));
    const s = r.skoop_settings || {};
    applyBlurMode(!!s.blurMode);
    applyDarkMode(!!s.darkMode);
  }

  // Reaccionar a cambios desde el popup sin necesidad de recargar
  chrome.storage.onChanged.addListener((changes) => {
    if (changes.skoop_settings) {
      const s = changes.skoop_settings.newValue || {};
      if (s.blurMode !== undefined) applyBlurMode(s.blurMode);
      if (s.darkMode !== undefined) applyDarkMode(s.darkMode);
    }
  });

  // ── BLUR MODE ────────────────────────────────────────────
  // Oculta avatares y nombres con blur — útil para capturas de pantalla
  function applyBlurMode(enabled) {
    const id = 'skoop-blur-style';
    if (enabled) {
      if (document.getElementById(id)) return;
      const s = document.createElement('style');
      s.id = id;
      s.textContent = `
        img[class*="avatar" i], img[class*="photo" i], img[class*="profile" i],
        [class*="avatar" i]:not(input):not(button) img,
        [class*="memberName" i], [class*="member-name" i], [class*="userName" i],
        [class*="fullName" i], [class*="displayName" i] {
          filter: blur(7px) !important;
          transition: filter 0.2s;
          user-select: none;
        }
        img[class*="avatar" i]:hover, [class*="memberName" i]:hover,
        [class*="userName" i]:hover, [class*="fullName" i]:hover {
          filter: blur(0px) !important;
        }
      `;
      document.head.appendChild(s);
    } else {
      document.getElementById(id)?.remove();
    }
  }

  // ── DARK MODE ────────────────────────────────────────────
  // Invierte colores de la página para un modo oscuro rápido
  function applyDarkMode(enabled) {
    const id = 'skoop-dark-style';
    if (enabled) {
      if (document.getElementById(id)) return;
      const s = document.createElement('style');
      s.id = id;
      s.textContent = `
        html { filter: invert(1) hue-rotate(180deg) !important; }
        img, video, canvas, iframe,
        [class*="avatar" i] img, [class*="photo" i] img {
          filter: invert(1) hue-rotate(180deg) !important;
        }
      `;
      document.head.appendChild(s);
    } else {
      document.getElementById(id)?.remove();
    }
  }

  // ── PLANTILLAS: SLASH COMMAND EN EL COMPOSITOR ───────────
  // Cuando el usuario escribe "/" en el campo de post de Skool,
  // muestra un picker de plantillas guardadas.
  let _templatePicker = null;

  async function setupTemplatePicker() {
    document.addEventListener('keydown', async (e) => {
      if (e.key !== '/' || e.target.tagName === 'INPUT') return;

      const isComposer = e.target.isContentEditable ||
        e.target.closest('[class*="editor" i], [class*="composer" i], [class*="post" i]');
      if (!isComposer) return;

      const r = await chrome.storage.local.get('skoop_templates').catch(() => ({}));
      const templates = r.skoop_templates || [];
      if (templates.length === 0) return;

      showTemplatePicker(e.target, templates);
    });
  }

  function showTemplatePicker(target, templates) {
    closePicker();
    const rect = target.getBoundingClientRect();
    const div = document.createElement('div');
    div.id = 'skoop-template-picker';
    div.style.cssText = `
      position: fixed;
      left: ${rect.left}px;
      top: ${rect.bottom + 4}px;
      z-index: 99999;
      background: #1a1d27;
      border: 1px solid #2d3148;
      border-radius: 8px;
      padding: 6px;
      min-width: 260px;
      max-width: 320px;
      box-shadow: 0 8px 32px rgba(0,0,0,0.5);
      font-family: -apple-system, sans-serif;
      font-size: 12px;
      color: #e2e8f0;
    `;
    div.innerHTML = `
      <div style="padding:4px 8px;font-size:10px;color:#5a647a;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">
        Plantillas Skoop (Esc para cerrar)
      </div>
      ${templates.map(t => `
        <div class="skoop-tpl-item" data-body="${escAttr(t.body)}"
          style="padding:8px 10px;border-radius:5px;cursor:pointer;border:1px solid transparent;margin-bottom:2px">
          <div style="font-weight:600;color:#e2e8f0">${esc(t.name)}</div>
          <div style="color:#8892a4;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
            ${esc(t.body.slice(0, 60))}${t.body.length > 60 ? '…' : ''}
          </div>
        </div>
      `).join('')}
    `;
    document.body.appendChild(div);
    _templatePicker = div;

    div.querySelectorAll('.skoop-tpl-item').forEach(item => {
      item.addEventListener('mouseenter', () => {
        item.style.background = '#232636';
        item.style.borderColor = '#2d3148';
      });
      item.addEventListener('mouseleave', () => {
        item.style.background = 'transparent';
        item.style.borderColor = 'transparent';
      });
      item.addEventListener('click', () => {
        const body = item.dataset.body;
        if (target.isContentEditable) {
          document.execCommand('insertText', false, body);
        } else {
          const start = target.selectionStart;
          const val = target.value;
          target.value = val.slice(0, start) + body + val.slice(target.selectionEnd);
          target.selectionStart = target.selectionEnd = start + body.length;
        }
        closePicker();
      });
    });

    document.addEventListener('keydown', onPickerKeydown);
    setTimeout(() => document.addEventListener('click', closePicker), 100);
  }

  function onPickerKeydown(e) {
    if (e.key === 'Escape') closePicker();
  }

  function closePicker() {
    _templatePicker?.remove();
    _templatePicker = null;
    document.removeEventListener('keydown', onPickerKeydown);
    document.removeEventListener('click', closePicker);
  }

  function esc(str) {
    return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
  function escAttr(str) {
    return String(str || '').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  }

  // ── NOTIFICACIÓN DE NUEVOS MIEMBROS ──────────────────────
  // El service worker ya maneja esto vía alarmas, aquí solo procesamos
  // el banner visual dentro de Skool (opcional, no intrusivo).

  // ── INIT ─────────────────────────────────────────────────

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      loadAndApply();
      setupTemplatePicker();
    });
  } else {
    loadAndApply();
    setupTemplatePicker();
  }

  // ── ESCÁNER DE MIEMBROS ───────────────────────────────────

  function _startScanner() {
    if (!window.__SkoopScanner || window.__SkoopScanner.isScanRunning()) return;
    const slug = location.pathname.split('/').filter(Boolean)[0];
    window.__SkoopScanner.startScan(
      ({ scanned }) => {
        chrome.runtime.sendMessage({ type: 'SCAN_PROGRESS', scanned, slug }).catch(() => {});
      },
      ({ total }) => {
        chrome.runtime.sendMessage({ type: 'SCAN_COMPLETE', total, slug }).catch(() => {});
      }
    );
  }

  // ── ESCÁNER DE FEED / ACTIVIDAD (Fase 3) ──────────────────
  function _startFeedScanner() {
    if (!window.__SkoopScanner || window.__SkoopScanner.isScanRunning()) return;
    const slug = location.pathname.split('/').filter(Boolean)[0];
    window.__SkoopScanner.startFeedScan(
      ({ scanned }) => {
        chrome.runtime.sendMessage({ type: 'FEED_SCAN_PROGRESS', scanned, slug }).catch(() => {});
      },
      ({ total }) => {
        chrome.runtime.sendMessage({ type: 'FEED_SCAN_COMPLETE', total, slug }).catch(() => {});
      }
    );
  }

  // Recibir START_SCAN / START_FEED_SCAN desde el popup (via SW)
  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg.type !== 'START_SCAN' && msg.type !== 'START_FEED_SCAN') return;
    if (!window.__SkoopScanner) { sendResponse({ ok: false, error: 'scanner not loaded' }); return true; }
    if (window.__SkoopScanner.isScanRunning()) { sendResponse({ ok: false, error: 'already running' }); return true; }
    // El scanner pagina la API por fetch: basta con estar en una comunidad (slug válido).
    const slug = location.pathname.split('/').filter(Boolean)[0];
    if (!slug || ['login', 'signup', 'api', '_next'].includes(slug)) {
      sendResponse({ ok: false, error: 'no community' });
      return true;
    }
    if (msg.type === 'START_FEED_SCAN') _startFeedScanner();
    else _startScanner();
    sendResponse({ ok: true });
    return true;
  });

  // Auto-start si esta tab fue abierta por Skoop para escanear (cualquier página de la comunidad)
  chrome.storage.local.get(['skoop_auto_scan_slug', 'skoop_auto_feed_scan_slug']).then((stored) => {
    const slug = location.pathname.split('/').filter(Boolean)[0];
    if (stored.skoop_auto_feed_scan_slug && stored.skoop_auto_feed_scan_slug === slug) {
      setTimeout(_startFeedScanner, 1500);
    } else if (stored.skoop_auto_scan_slug && stored.skoop_auto_scan_slug === slug) {
      setTimeout(_startScanner, 1500);
    }
  }).catch(() => {});

})();
