// State
var items = [];
var lists = [
  { id: '1', name: 'Dev Friends', contacts: [] },
  { id: '2', name: 'Meme Buddies', contacts: [] },
  { id: '3', name: 'Business', contacts: [] }
];

// Load data
function loadData() {
  chrome.storage.local.get(['hookd_items', 'hookd_lists'], function(result) {
    items = result.hookd_items || [];
    lists = result.hookd_lists || [
      { id: '1', name: 'Dev Friends', contacts: [] },
      { id: '2', name: 'Meme Buddies', contacts: [] },
      { id: '3', name: 'Business', contacts: [] }
    ];
    renderAll();
  });
}

// Save items
function saveItems() {
  chrome.storage.local.set({ hookd_items: items });
}

// Render all
function renderAll() {
  renderInbox();
  renderLists();
  loadHandle();
}

// Tab switching
function switchTab(tabId) {
  var contents = document.querySelectorAll('.tab-content');
  for (var i = 0; i < contents.length; i++) {
    contents[i].classList.remove('active');
  }
  var tabs = document.querySelectorAll('.tab');
  for (var i = 0; i < tabs.length; i++) {
    tabs[i].classList.remove('active');
  }
  document.getElementById(tabId).classList.add('active');
  document.getElementById('tab-' + tabId).classList.add('active');
}

// Render inbox
function renderInbox() {
  document.getElementById('inbox-count').textContent = '(' + items.length + ')';
  var list = document.getElementById('inbox-list');
  var empty = document.getElementById('inbox-empty');
  
  if (items.length === 0) {
    list.innerHTML = '';
    empty.style.display = 'block';
  } else {
    empty.style.display = 'none';
    var html = '';
    for (var i = 0; i < items.length; i++) {
      html += '<div class="box" style="position:relative;">' +
        '<div style="font-size:10px;color:#64748b;margin-bottom:4px;">@' + (items[i].author || 'unknown') + '</div>' +
        '<div style="font-size:12px;">' + ((items[i].content || 'No content').substring(0, 60)) + '</div>' +
        '<button class="delete-btn" data-index="' + i + '">x</button>' +
      '</div>';
    }
    list.innerHTML = html;
    
    // Add delete handlers
    var deleteBtns = list.querySelectorAll('.delete-btn');
    for (var i = 0; i < deleteBtns.length; i++) {
      deleteBtns[i].addEventListener('click', function() {
        var idx = parseInt(this.getAttribute('data-index'));
        items.splice(idx, 1);
        saveItems();
        renderInbox();
      });
    }
  }
}

// Test add item
function testAddItem() {
  items.unshift({
    id: Date.now(),
    author: 'TestUser',
    content: 'Test item saved!',
    time: new Date().toISOString()
  });
  saveItems();
  renderInbox();
}

// Render lists
function renderLists() {
  var container = document.getElementById('lists-container');
  var html = '';
  for (var i = 0; i < lists.length; i++) {
    html += '<div class="box-list">' +
      '<span>' + lists[i].name + ' (' + lists[i].contacts.length + ')</span>' +
      '<button class="delete-btn" data-list-index="' + i + '">x</button>' +
    '</div>';
  }
  container.innerHTML = html;
  
  // Add delete handlers
  var deleteBtns = container.querySelectorAll('.delete-btn');
  for (var i = 0; i < deleteBtns.length; i++) {
    deleteBtns[i].addEventListener('click', function() {
      var idx = parseInt(this.getAttribute('data-list-index'));
      lists.splice(idx, 1);
      chrome.storage.local.set({ hookd_lists: lists });
      renderLists();
    });
  }
}

// Create list
function createList() {
  var input = document.getElementById('new-list-name');
  var name = input.value.trim();
  if (!name) return;
  
  lists.push({
    id: String(Date.now()),
    name: name,
    contacts: []
  });
  chrome.storage.local.set({ hookd_lists: lists });
  input.value = '';
  renderLists();
}

// Load handle
function loadHandle() {
  chrome.storage.local.get(['hookd_handle'], function(result) {
    if (result.hookd_handle) {
      document.getElementById('setting-handle').value = result.hookd_handle;
    }
  });
}

// Save handle
function saveHandle() {
  var handle = document.getElementById('setting-handle').value.trim();
  if (!handle) return;
  chrome.storage.local.set({ hookd_handle: handle });
  alert('Saved: ' + handle);
}

// Clear all
function clearAll() {
  if (!confirm('Delete ALL data?')) return;
  items = [];
  lists = [
    { id: '1', name: 'Dev Friends', contacts: [] },
    { id: '2', name: 'Meme Buddies', contacts: [] },
    { id: '3', name: 'Business', contacts: [] }
  ];
  chrome.storage.local.set({ hookd_items: [], hookd_lists: lists });
  renderAll();
  alert('All data cleared');
}

// Setup
document.addEventListener('DOMContentLoaded', function() {
  // Tab clicks
  document.getElementById('tab-inbox').addEventListener('click', function() { switchTab('inbox'); });
  document.getElementById('tab-lists').addEventListener('click', function() { switchTab('lists'); });
  document.getElementById('tab-settings').addEventListener('click', function() { switchTab('settings'); });
  
  // Buttons
  document.getElementById('btn-test-add').addEventListener('click', testAddItem);
  document.getElementById('btn-create-list').addEventListener('click', createList);
  document.getElementById('btn-save-handle').addEventListener('click', saveHandle);
  document.getElementById('btn-clear-all').addEventListener('click', clearAll);
  
  // Load data
  loadData();
});
