// content/base.js
console.log("✅ Puente base.js cargado en admin/localhost:", location.href);

async function findAndSyncFirebaseUid() {
  try {
    // 1. Direct local/session storage o autopost_perfil_activo
    const perfilStr = localStorage.getItem("autopost_perfil_activo");
    if (perfilStr) {
      try {
        const perfil = JSON.parse(perfilStr);
        if (perfil && (perfil.usuarioID || perfil.usuario_firebase_id)) {
          const uid = perfil.usuarioID || perfil.usuario_firebase_id;
          chrome.runtime.sendMessage({ type: "SET_USER_ID", uid: uid });
          return uid;
        }
      } catch(e) {}
    }

    let uid = localStorage.getItem("usuario_firebase_id") || localStorage.getItem("uid");
    if (uid) {
      chrome.runtime.sendMessage({ type: "SET_USER_ID", uid: uid });
      return uid;
    }

    // 2. Scan localStorage
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      try {
        const v = localStorage.getItem(k);
        if (v && (v.includes("usuarioID") || v.includes("uid"))) {
          const obj = JSON.parse(v);
          const found = obj.usuarioID || obj.uid || (obj.user && obj.user.uid) || (obj.value && obj.value.uid);
          if (found) {
            chrome.runtime.sendMessage({ type: "SET_USER_ID", uid: found });
            return found;
          }
        }
      } catch(e) {}
    }

    // 3. Scan IndexedDB (firebaseLocalStorageDb)
    try {
      const req = indexedDB.open("firebaseLocalStorageDb");
      req.onsuccess = function() {
        const db = req.result;
        if (db && db.objectStoreNames.contains("firebaseLocalStorage")) {
          const tx = db.transaction("firebaseLocalStorage", "readonly");
          const store = tx.objectStore("firebaseLocalStorage");
          const getAll = store.getAll();
          getAll.onsuccess = function() {
            for (const item of getAll.result || []) {
              if (item && item.value && item.value.uid) {
                chrome.runtime.sendMessage({ type: "SET_USER_ID", uid: item.value.uid });
              }
            }
          };
        }
      };
    } catch(e) {}

  } catch(e) {}
}

findAndSyncFirebaseUid();
setInterval(findAndSyncFirebaseUid, 5000);

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log("📨 base.js recibió desde background:", request.type);

  // Enviamos TODO el objeto a Angular, sin importar el tipo
  window.postMessage({
    from: 'AUTOPOST_EXTENSION',
    ...request 
  }, "*");
  
  if (sendResponse) sendResponse({ok: true});
});

// 📌 Escuchar mensajes desde Angular hacia la extensión (Puente Universal postMessage)
window.addEventListener("message", (event) => {
  if (event.data && typeof event.data === "object") {
    if (event.data.from === "AUTOPOST_ANGULAR" || event.data.type === "START_PUBLISH" || event.data.type === "SCHEDULE_CAMPAIGN" || event.data.type === "CANCEL_CAMPAIGN" || event.data.type === "SET_USER_ID") {
      console.log("📨 [base.js] Reenviando mensaje a background:", event.data.type || event.data);
      try {
        chrome.runtime.sendMessage(event.data, (response) => {
          if (chrome.runtime.lastError) {
            // Ignorar errores silenciosos de canal no abierto
          }
        });
      } catch (e) {
        console.error("Error al reenviar a background:", e);
      }
    }
  }
});