
// Capture Lovable Bearer token from outgoing api.lovable.dev requests
try {
  chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
      try {
        const headers = details.requestHeaders || [];
        const authHeader = headers.find(h => h.name && h.name.toLowerCase() === "authorization");
        if (!authHeader || !authHeader.value || !authHeader.value.startsWith("Bearer ")) return;
        chrome.storage.local.set({
          lovableBearerToken: authHeader.value,
          lovableBearerTokenCapturedAt: Date.now()
        });
      } catch(e) {}
    },
    { urls: ["https://api.lovable.dev/*"] },
    ["requestHeaders", "extraHeaders"]
  );
} catch(e) {
  console.warn("[Background] webRequest listener failed:", e && e.message);
}

// Default settings on install
try {
  chrome.runtime.onInstalled.addListener(() => {
    try {
      chrome.storage.local.get(['soundNotificationsEnabled'], (r) => {
        if (!r || typeof r.soundNotificationsEnabled === 'undefined') {
          chrome.storage.local.set({ soundNotificationsEnabled: true });
        }
      });
    } catch(_){}
  });
} catch(_){}


// The extension UI now lives as an overlay injected into lovable.dev by
// the content script. The chrome.sidePanel API is kept only as a fallback
// for users that explicitly open it; the icon click toggles the overlay.

async function openLovableTabAndToggle() {
  try {
    const tabs = await chrome.tabs.query({ url: ["https://lovable.dev/*", "https://*.lovable.dev/*"] });
    let target = tabs && tabs[0];
    if (!target) {
      target = await chrome.tabs.create({ url: "https://lovable.dev/" });
      return; // content script will mount overlay on load (default expanded)
    }
    try { await chrome.tabs.update(target.id, { active: true }); } catch (_) {}
    try { await chrome.windows.update(target.windowId, { focused: true }); } catch (_) {}
    chrome.tabs.sendMessage(target.id, { type: "TS_TOGGLE_OVERLAY" }, () => void chrome.runtime.lastError);
  } catch (err) {
    console.error("[Background] toggle overlay error:", err);
  }
}

chrome.action.onClicked.addListener(async (tab) => {
  if (tab && tab.url && /^https:\/\/([^/]+\.)?lovable\.dev\//.test(tab.url)) {
    chrome.tabs.sendMessage(tab.id, { type: "TS_TOGGLE_OVERLAY" }, () => void chrome.runtime.lastError);
    return;
  }
  await openLovableTabAndToggle();
});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {

  if (msg && msg.action === "lovableSync") {
    const updates = {};
    if (msg.token) updates.lovable_token = msg.token;
    if (msg.projectId) updates.lovable_projectId = msg.projectId;
    if (Object.keys(updates).length) {
      chrome.storage.local.set(updates, () => {
      });
    }
  }


  if (msg && msg.action === "openSidePanel") {
    // This can only work if triggered from a user gesture context
    if (sender.tab && sender.tab.id) {
      chrome.sidePanel.open({ tabId: sender.tab.id }).then(() => {
        sendResponse({ ok: true });
      }).catch((err) => {
        console.warn("[Background] openSidePanel deferred:", err.message);
        sendResponse({ ok: false, error: err.message });
      });
    } else {
      sendResponse({ ok: false, error: "No tab context" });
    }
    return true;
  }



  if (msg && msg.action === "lovableApiFetch") {
    (async () => {
      try {
        let tab = null;
        const activeTabs = await chrome.tabs.query({ active: true, currentWindow: true });
        if (activeTabs && activeTabs[0] && /^https:\/\/([^/]+\.)?lovable\.dev\//.test(activeTabs[0].url || '')) {
          tab = activeTabs[0];
        } else {
          const lovableTabs = await chrome.tabs.query({ url: ["https://lovable.dev/*", "https://*.lovable.dev/*"] });
          tab = (lovableTabs && lovableTabs[0]) || null;
        }
        if (!tab || !tab.id) {
          sendResponse({ ok: false, status: 0, data: { error: "Abra uma aba do Lovable antes de enviar." } });
          return;
        }
        const results = await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: 'MAIN',
          func: async (url, options) => {
            try {
              const r = await fetch(url, options);
              const text = await r.text();
              let data;
              try { data = JSON.parse(text); } catch (e) { data = { raw: text }; }
              return { ok: r.ok, status: r.status, data };
            } catch (err) {
              return { ok: false, status: 0, data: { error: (err && err.message) || 'fetch failed in page' } };
            }
          },
          args: [msg.url, {
            method: msg.method || 'POST',
            headers: msg.headers || {},
            body: msg.body || null,
            credentials: 'include',
          }],
        });
        const value = (results && results[0] && results[0].result) || { ok: false, status: 0, data: { error: 'sem resposta da página Lovable' } };
        sendResponse(value);
      } catch (err) {
        console.error("[Background] lovableApiFetch error:", err);
        sendResponse({ ok: false, status: 0, data: { error: err.message || "Falha no executeScript." } });
      }
    })();
    return true;
  }

  if (msg && msg.action === "proxyFetch") {
    (async () => {
      try {
        var opts = {
          method: msg.method || "POST",
          headers: msg.headers || {},
        };
        if (msg.body) opts.body = msg.body;
        var resp = await fetch(msg.url, opts);
        var text = await resp.text();
        var data;
        try { data = JSON.parse(text); } catch(e) { data = { raw: text }; }
        sendResponse({ ok: resp.ok, status: resp.status, data: data });
      } catch(err) {
        console.error("[Background] proxyFetch error:", err);
        sendResponse({ ok: false, status: 0, data: { error: err.message || "Fetch failed in background" } });
      }
    })();
    return true;
  }

  // --- READ_COOKIES: read HttpOnly cookies for JWT token ---
  if (msg && msg.action === "readCookies") {
    var cookieNames = [
      "lovable-session-id.id",
      "lovable-session-id.custom",
      "lovable-session-id.refresh",
      "lovable-session-id.sig"
    ];
    var foundTokens = [];
    var checkedCount = 0;
    cookieNames.forEach(function(name) {
      chrome.cookies.get({ url: "https://lovable.dev", name: name }, function(cookie) {
        checkedCount++;
        if (cookie && cookie.value) {
          var parts = cookie.value.split(".");
          if (parts.length === 3 && cookie.value.indexOf("eyJ") === 0) {
            foundTokens.push({
              token: cookie.value,
              cookieName: name,
              httpOnly: cookie.httpOnly
            });
          }
        }
        if (checkedCount === cookieNames.length) {
          sendResponse({ success: foundTokens.length > 0, tokens: foundTokens });
        }
      });
    });
    return true;
  }

  // --- DOWNLOAD_PROJECT: fetch project source code from Lovable API ---
  if (msg && msg.action === "downloadProject") {
    (async function() {
      try {
        var apiUrl = "https://lovable-api.com/projects/" + msg.projectId + "/source-code";
        var resp = await fetch(apiUrl, {
          method: "GET",
          headers: {
            "Authorization": "Bearer " + msg.token,
            "Accept": "application/json"
          }
        });
        if (!resp.ok) {
          sendResponse({ success: false, error: "API retornou " + resp.status });
          return;
        }
        var data = await resp.json();
        sendResponse({ success: true, files: data.files || [] });
      } catch(err) {
        sendResponse({ success: false, error: err.message || "Download falhou" });
      }
    })();
    return true;
  }

});
