// WapiBot CRM - Notificaciones WAPlus PRO (Producción)
// Consulta dinámica a /api/notifications/get.php?service=...
(function(){
  const STATE_KEY = "wapibot_notifications_seen_v2";

  function sendMessage(payload){
    return new Promise((resolve) => {
      try { chrome.runtime.sendMessage(payload, (res) => resolve(res || {})); }
      catch(e){ resolve({ success:false, error:String(e) }); }
    });
  }

  function normalizeServiceFolder(service){
    service = (service || "api/services").toString().trim().replace(/^\/+|\/+$/g, "");
    return service || "api/services";
  }

  function getStoredLoginContext(){
    return new Promise((resolve) => {
      try {
        chrome.storage.local.get(["wapibot_login_context", "user", "auth_user", "session_user", "current_user"], (s) => {
          const pick = (obj) => {
            if (!obj || typeof obj !== "object") return {};
            const u = obj.user && typeof obj.user === "object" ? obj.user : obj;
            return {
              reseller_id: u.reseller_id || u.resellerId || u.owner_id || u.ownerId || u.admin_id || u.adminId || u.user_id || u.userId || "",
              client_id: u.client_id || u.clientId || u.id || "",
              license_key: u.license_key || u.licenseKey || u.access_token_plugin || u.token || "",
              client_type: u.client_type || u.clientType || u.plan_type || u.planType || ""
            };
          };
          const candidates = [pick(s.wapibot_login_context), pick(s.user), pick(s.auth_user), pick(s.session_user), pick(s.current_user)];
          resolve(candidates.find(c => c.reseller_id || c.client_id || c.license_key || c.client_type) || {});
        });
      } catch(e) { resolve({}); }
    });
  }

  async function getConfig(){
    const res = await sendMessage({ type: "get_wapibot_config" });
    const links = res && res.links ? res.links : {};
    const loginCtx = await getStoredLoginContext();
    return {
      backend_plugin: (links.backend_plugin || "https://super.socioscrm.site/").replace(/\/+$/, "/"),
      service_folder: normalizeServiceFolder(links.service_folder || "api/services"),
      owner_id: links.owner_id || links.notification_owner_id || "",
      notification_owner_id: links.notification_owner_id || links.owner_id || "",
      reseller_id: loginCtx.reseller_id || links.reseller_id || "",
      client_id: loginCtx.client_id || links.client_id || links.user_id || "",
      license_key: loginCtx.license_key || links.license_key || "",
      client_type: loginCtx.client_type || links.client_type || ""
    };
  }

  function getSeen(){
    try { return JSON.parse(localStorage.getItem(STATE_KEY) || "[]"); }
    catch(e){ return []; }
  }

  function setSeen(arr){
    try { localStorage.setItem(STATE_KEY, JSON.stringify(arr.slice(-150))); } catch(e){}
  }

  function notifId(n){
    return String(n.id || `${n.titulo || ""}|${n.mensaje || ""}|${n.fecha_inicio || ""}|${n.fecha_fin || ""}`);
  }

  function isInDate(n){
    const now = new Date();
    const today = new Date();
    today.setHours(0,0,0,0);
    if (n.fecha_inicio && new Date(n.fecha_inicio + "T00:00:00") > today) return false;
    if (n.fecha_fin && new Date(n.fecha_fin + "T23:59:59") < now) return false;
    return true;
  }

  function colorByTipo(tipo, customColor){
    if (customColor) return customColor;
    tipo = String(tipo || "").toLowerCase();
    if (tipo === "alerta" || tipo === "alert") return "#ff3b30";
    if (tipo === "update" || tipo === "actualizacion" || tipo === "actualización") return "#00d4ff";
    if (tipo === "promo" || tipo === "promotion" || tipo === "promocion" || tipo === "promoción") return "#ffcc00";
    return "#00ff66";
  }

  function escapeHtml(value){
    return String(value || "").replace(/[&<>'"]/g, (c) => ({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"}[c]));
  }

  async function track(config, n, accion, boton){
    try {
      await fetch(`${config.backend_plugin}api/notifications/track.php`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: n.id || "",
          titulo: n.titulo || "",
          accion: accion,
          boton: boton || "",
          service: config.service_folder,
          owner_id: config.owner_id || "",
          ts: Date.now()
        })
      });
    } catch(e) {}
  }

  function buildGetUrl(config){
    const params = new URLSearchParams();
    params.set("service", config.service_folder || "api/services");
    if (config.owner_id) params.set("owner_id", config.owner_id);
    if (config.notification_owner_id) params.set("notification_owner_id", config.notification_owner_id);
    if (config.reseller_id) params.set("reseller_id", config.reseller_id);
    if (config.client_id) params.set("client_id", config.client_id);
    if (config.license_key) params.set("license_key", config.license_key);
    if (config.client_type) params.set("client_type", config.client_type);
    params.set("_", String(Date.now()));
    return `${config.backend_plugin}api/notifications/get.php?${params.toString()}`;
  }

  function mostrarNotificacionWAPlus(n, config){
    const id = notifId(n);
    if (document.querySelector(`[data-wapibot-notif="${CSS.escape(id)}"]`)) return;

    const wrap = document.createElement("div");
    wrap.setAttribute("data-wapibot-notif", id);
    wrap.style.cssText = `
      position: fixed;
      right: 22px;
      bottom: 22px;
      z-index: 2147483647;
      width: min(340px, calc(100vw - 34px));
      background: #101418;
      color: #fff;
      border-radius: 16px;
      padding: 16px;
      box-shadow: 0 20px 70px rgba(0,0,0,.45);
      border: 1px solid rgba(255,255,255,.11);
      border-left: 5px solid ${colorByTipo(n.tipo, n.color)};
      font-family: Arial, Helvetica, sans-serif;
      animation: wapibotNotifyIn .28s ease both;
    `;

    if (!document.getElementById("wapibot-notify-style")) {
      const st = document.createElement("style");
      st.id = "wapibot-notify-style";
      st.textContent = `
        @keyframes wapibotNotifyIn{from{opacity:0;transform:translateY(18px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}
        .wapibot-notify-btn{border:none;border-radius:9px;padding:8px 11px;background:#00ff66;color:#07110a;font-weight:700;cursor:pointer;font-size:12px}
        .wapibot-notify-btn.secondary{background:rgba(255,255,255,.12);color:#fff}
      `;
      document.head.appendChild(st);
    }

    const botones = Array.isArray(n.botones) ? n.botones : [];
    const botonesHtml = botones.length
      ? `<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px;">${botones.map((b,i)=>`<button class="wapibot-notify-btn ${b.accion === 'cerrar' ? 'secondary' : ''}" data-i="${i}">${escapeHtml(b.texto || 'Ver')}</button>`).join("")}</div>`
      : "";

    wrap.innerHTML = `
      <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;">
        <div style="font-weight:800;font-size:15px;line-height:1.25;">${escapeHtml(n.titulo || 'Notificación')}</div>
        <button data-close="1" style="background:transparent;border:none;color:#9ca3af;cursor:pointer;font-size:18px;line-height:1;">×</button>
      </div>
      <div style="margin-top:8px;color:#d1d5db;font-size:13px;line-height:1.45;">${escapeHtml(n.mensaje || '')}</div>
      ${botonesHtml}
    `;

    document.body.appendChild(wrap);
    track(config, n, "view");

    wrap.querySelector('[data-close="1"]').onclick = async () => {
      await track(config, n, "close");
      wrap.remove();
    };

    wrap.querySelectorAll('button[data-i]').forEach(btn => {
      btn.onclick = async () => {
        const b = botones[parseInt(btn.dataset.i, 10)] || {};
        await track(config, n, "click", b.texto || 'boton');
        if ((b.accion || 'link') === 'cerrar') wrap.remove();
        else if (b.url) window.open(b.url, '_blank');
      };
    });

    const duration = parseInt(n.duracion || 9000, 10);
    if (duration > 0) setTimeout(() => { try { wrap.remove(); } catch(e){} }, duration);
  }

  async function cargarNotificaciones(){
    try {
      const config = await getConfig();
      const res = await fetch(buildGetUrl(config), { cache: 'no-store' });
      const data = await res.json();
      if (!Array.isArray(data) || !data.length) return;

      const seen = getSeen();
      const nextSeen = [...seen];

      data.forEach(n => {
        if (!n || !isInDate(n)) return;
        const id = notifId(n);
        if (n.mostrar_una_vez === true && seen.includes(id)) return;
        mostrarNotificacionWAPlus(n, config);
        if (!nextSeen.includes(id)) nextSeen.push(id);
      });

      setSeen(nextSeen);
    } catch(e) {
      console.log('WapiBot notificaciones error:', e);
    }
  }

  function esperarWhatsApp(){
    let tries = 0;
    const timer = setInterval(() => {
      tries++;
      if (document.querySelector('#app') || tries > 20) {
        clearInterval(timer);
        setTimeout(cargarNotificaciones, 2500);
      }
    }, 1000);
  }

  esperarWhatsApp();
  window.WAPIBOT_cargarNotificaciones = cargarNotificaciones;
})();
