// Service Worker - Hookd Extension

const STORAGE_KEY = 'hookd_items';
const SETTINGS_KEY = 'hookd_settings';
const LISTS_KEY = 'hookd_lists';

const defaultSettings = {
  categories: ['AI', 'News', 'Ideas', 'Memes', 'Other'],
  userHandle: 'HaithamEKhalifa',
  relayEnabled: true
};

const defaultLists = [
  { id: 'dev', name: 'Dev Friends', emoji: '👨‍💻', contacts: [] },
  { id: 'memes', name: 'Meme Buddies', emoji: '😂', contacts: [] },
  { id: 'business', name: 'Business', emoji: '💼', contacts: [] },
  { id: 'family', name: 'Family', emoji: '👨‍👩‍👧', contacts: [] }
];

// Initialize
chrome.runtime.onInstalled.addListener(() => {
  console.log('Hookd installed');
  chrome.storage.local.set({
    [STORAGE_KEY]: [],
    [SETTINGS_KEY]: defaultSettings,
    [LISTS_KEY]: defaultLists
  });
});

// Handle messages
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Get items
  if (message.type === 'GET_ITEMS') {
    chrome.storage.local.get([STORAGE_KEY], (r) => sendResponse(r[STORAGE_KEY] || []));
    return true;
  }
  
  // Get lists
  if (message.type === 'GET_LISTS') {
    chrome.storage.local.get([LISTS_KEY], (r) => sendResponse(r[LISTS_KEY] || defaultLists));
    return true;
  }
  
  // Add contact to list
  if (message.type === 'ADD_CONTACT') {
    chrome.storage.local.get([LISTS_KEY], (r) => {
      const lists = r[LISTS_KEY] || defaultLists;
      const list = lists.find(l => l.id === message.listId);
      if (list && !list.contacts.find(c => c.username === message.contact.username)) {
        list.contacts.push(message.contact);
        chrome.storage.local.set({ [LISTS_KEY]: lists });
      }
      sendResponse({ success: true });
    });
    return true;
  }
  
  // Remove contact from list
  if (message.type === 'REMOVE_CONTACT') {
    chrome.storage.local.get([LISTS_KEY], (r) => {
      const lists = r[LISTS_KEY] || defaultLists;
      const list = lists.find(l => l.id === message.listId);
      if (list) {
        list.contacts = list.contacts.filter(c => c.username !== message.username);
        chrome.storage.local.set({ [LISTS_KEY]: lists });
      }
      sendResponse({ success: true });
    });
    return true;
  }
  
  // Create new list
  if (message.type === 'CREATE_LIST') {
    chrome.storage.local.get([LISTS_KEY], (r) => {
      const lists = r[LISTS_KEY] || defaultLists;
      lists.push({
        id: Date.now().toString(),
        name: message.name,
        emoji: message.emoji || '📌',
        contacts: []
      });
      chrome.storage.local.set({ [LISTS_KEY]: lists });
      sendResponse({ success: true });
    });
    return true;
  }
  
  // Delete list
  if (message.type === 'DELETE_LIST') {
    chrome.storage.local.get([LISTS_KEY], (r) => {
      let lists = r[LISTS_KEY] || defaultLists;
      lists = lists.filter(l => l.id !== message.listId);
      chrome.storage.local.set({ [LISTS_KEY]: lists });
      sendResponse({ success: true });
    });
    return true;
  }
  
  // Share item to list
  if (message.type === 'SHARE_TO_LIST') {
    chrome.storage.local.get([STORAGE_KEY], (r) => {
      const items = r[STORAGE_KEY] || [];
      // Mark item as shared
      const item = items.find(i => i.id === message.itemId);
      if (item) {
        item.sharedTo = item.sharedTo || [];
        item.sharedTo.push(message.listId);
        chrome.storage.local.set({ [STORAGE_KEY]: items });
      }
      sendResponse({ success: true });
    });
    return true;
  }
  
  // Save item
  if (message.type === 'SAVE_ITEM') {
    chrome.storage.local.get([STORAGE_KEY], (r) => {
      const items = r[STORAGE_KEY] || [];
      const newItem = {
        id: Date.now(),
        ...message.data,
        type: message.data.source || 'dm',
        saved: false,
        aiProcessed: false,
        sharedTo: [],
        time: new Date().toISOString()
      };
      items.unshift(newItem);
      chrome.storage.local.set({ [STORAGE_KEY]: items });
      sendResponse({ success: true, item: newItem });
    });
    return true;
  }
  
  // Delete items
  if (message.type === 'DELETE_ITEMS') {
    chrome.storage.local.get([STORAGE_KEY], (r) => {
      const items = r[STORAGE_KEY] || [];
      const remaining = items.filter(i => !message.ids.includes(i.id));
      chrome.storage.local.set({ [STORAGE_KEY]: remaining });
      sendResponse({ success: true, deleted: message.ids.length });
    });
    return true;
  }
  
  // Update item
  if (message.type === 'UPDATE_ITEM') {
    chrome.storage.local.get([STORAGE_KEY], (r) => {
      const items = r[STORAGE_KEY] || [];
      const idx = items.findIndex(i => i.id === message.data.id);
      if (idx !== -1) {
        items[idx] = { ...items[idx], ...message.data };
        chrome.storage.local.set({ [STORAGE_KEY]: items });
      }
      sendResponse({ success: true });
    });
    return true;
  }
});
