// background.js

// Function to block specific requests
function blockRequest(details) {
    // Check if the request URL matches the file you want to block
    if (details.url.includes("title_manager.js")) {
        console.log("Blocking request for:", details.url);
        return { cancel: true }; // Cancel the request
    }
}

// Check if the browser is Firefox or Chrome
const isFirefox = typeof browser !== "undefined";
// background.js

// Handle all miip:// requests
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        console.log("[DEBUG] Intercepted URL:", details.url);
        
        if (details.url.startsWith('miip://')) {
            const redirectUrl = chrome.runtime.getURL("images/mii.bmp");
            console.log("[DEBUG] Redirecting to:", redirectUrl);
            return { redirectUrl: redirectUrl };
        }
        return {};
    },
    { urls: ["<all_urls>"] },
    ["blocking"]
);

let logs = [];

chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    const url = new URL(details.url);
    
    if (url.pathname === '/_extension_storage') {
      const params = new URLSearchParams(url.search);
      
      // GET Requests
      if (params.has('get')) {
        const key = params.get('get');
        console.log("Get key: " + key)
        return new Promise(resolve => {
          chrome.storage.local.get(key, result => {
            if (key === 'logs') {
              resolve({
                redirectUrl: `data:application/json,${JSON.stringify({
                  value: logs
                })}`
              });
            } else {
              resolve({
                redirectUrl: `data:application/json,${JSON.stringify({
                  value: result[key]
                })}`
              });
            }
          });
        });
      }
      
      // SET Requests
      if (params.has('set_key')) {
        const key = params.get('set_key');
        const value = params.get('set_value');
        console.log("Set key: " + key + " with value: " + value)
        if (key === 'slogs') {
          console.log("Set key: logs with value: " + value)
          logs.push(`[SET] ${new Date().toISOString()}: ${value}`);
          chrome.storage.local.set({ logs });
        } else {
          chrome.storage.local.set({ [key]: value });
        }
        return { cancel: true };
      }
      
      // CLEAR Logs
      if (params.has('clogs')) {
        console.log("Clear Logs")
        logs = [];
        chrome.storage.local.set({ logs: [] });
        return { cancel: true };
      }
      if (params.has('set_key') && params.get('set_key') === 'spts') {
        const pointsToAdd = parseInt(params.get('set_value')) || 0;
        
        chrome.storage.local.get(['pts'], (result) => {
            const currentPoints = parseInt(result.pts) || 0;
            const newTotal = currentPoints + pointsToAdd;
            
            // Update both in-memory and storage
            logs.push(`[POINTS] Added ${pointsToAdd} points (Total: ${newTotal})`);
            chrome.storage.local.set({ 
                pts: newTotal,
                logs 
            });
        });
        
        return { cancel: true };
      }
      if (params.has('cpts')) {
        console.log("Clear Points")
        chrome.storage.local.set({ pts: 0 });
        return { cancel: true };
      }
    }
  },
  { urls: ["*://*/_extension_storage*"] },
  ["blocking"]
);