const fieldStore = new Map();

function originKey(tabId) {
  return `tab_${tabId}`;
}

function resolveOrigin(sender, payloadOrigin) {
  if (sender.tab && sender.tab.url) {
    try {
      return `web:${new URL(sender.tab.url).origin}`;
    } catch (e) {}
  }
  return payloadOrigin;
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.type) {
    case 'dudou.autofill.getProfile': {
      const origin = resolveOrigin(sender, message.payload?.origin);
      const profiles = {};

      chrome.storage.local.get(['autofill_profiles'], (result) => {
        const stored = result.autofill_profiles || {};
        const profile = stored[origin] || null;

        const keys = Object.keys(stored);
        keys.forEach(key => {
          if (key === origin || key.startsWith(origin)) {
            profiles[key] = stored[key];
          }
        });

        sendResponse({profile, profiles});
      });
      return true;
    }

    case 'dudou.autofill.saveProfile': {
      const payload = message.payload || {};
      const origin = resolveOrigin(sender, payload.origin);
      const data = payload.data;
      if (!origin || !data) {
        sendResponse({ok: false});
        return;
      }

      chrome.storage.local.get(['autofill_profiles'], (result) => {
        const stored = result.autofill_profiles || {};
        stored[origin] = data;
        chrome.storage.local.set({autofill_profiles: stored}, () => {
          sendResponse({ok: true});
        });
      });
      return true;
    }

    case 'dudou.autofill.storeFields': {
      if (sender.tab) {
        const key = originKey(sender.tab.id);
        fieldStore.set(key, message.payload.fields || []);
      }
      sendResponse({ok: true});
      break;
    }

    case 'dudou.autofill.getStoredFields': {
      const tabId = message.payload?.tabId;
      const key = originKey(tabId || (sender.tab?.id));
      const fields = fieldStore.get(key) || [];
      sendResponse({fields});
      break;
    }

    case 'dudou.autofill.fill':
    case 'dudou.autofill.requestFill':
    case 'dudou.autofill.showSuggestions': {
      const tabId = sender.tab ? sender.tab.id : null;
      if (tabId) {
        chrome.tabs.sendMessage(tabId, message, (response) => {
          sendResponse(response || {error: 'no response from content script'});
        });
      } else {
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
          if (tabs.length === 0) {
            sendResponse({error: 'no active tab'});
            return;
          }
          chrome.tabs.sendMessage(tabs[0].id, message, (response) => {
            sendResponse(response || {error: 'no response from content script'});
          });
        });
      }
      return true;
    }

    case 'dudou.autofill.getLearning': {
      const {origin: payloadOrigin, fieldSignature} = message.payload || {};
      const origin = resolveOrigin(sender, payloadOrigin);
      if (!origin || !fieldSignature) { sendResponse({}); return; }
      chrome.storage.local.get(['autofill_learning'], (result) => {
        const store = result.autofill_learning || {};
        sendResponse({learned: store[origin + '|' + fieldSignature] || null});
      });
      return true;
    }

    case 'dudou.autofill.saveLearning': {
      const {origin: payloadOrigin, fieldSignature, fieldType, confidence} = message.payload || {};
      const origin = resolveOrigin(sender, payloadOrigin);
      if (!origin || !fieldSignature || !fieldType) { sendResponse({ok: false}); return; }
      chrome.storage.local.get(['autofill_learning'], (result) => {
        const store = result.autofill_learning || {};
        store[origin + '|' + fieldSignature] = {fieldType, confidence: confidence || 0.95, updatedAt: Date.now()};
        chrome.storage.local.set({autofill_learning: store}, () => sendResponse({ok: true}));
      });
      return true;
    }

    case 'dudou.autofill.checkProfile': {
      const origin = resolveOrigin(sender, message.payload?.origin);
      chrome.storage.local.get(['autofill_profiles'], (result) => {
        const stored = result.autofill_profiles || {};
        sendResponse({exists: !!stored[origin], profile: stored[origin] || null});
      });
      return true;
    }

    case 'dudou.autofill.classify': {
      if (sender.tab) {
        const key = originKey(sender.tab.id);
        fieldStore.set(key, message.payload.fields || []);
      }
      sendResponse({ok: true, stored: true});
      break;
    }
  }
});

chrome.runtime.onConnect.addListener((port) => {
  if (port.name === 'dudou-autofill') {
    port.onMessage.addListener((message) => {
      if (message.type === 'getFields') {
        const fields = fieldStore.get(originKey(message.tabId)) || [];
        port.postMessage({type: 'fields', tabId: message.tabId, fields});
      }
    });
  }
});

chrome.tabs.onRemoved.addListener((tabId) => {
  fieldStore.delete(originKey(tabId));
});
