const STORAGE_KEY = 'kai-dial-data';

(async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  document.getElementById('title').value = tab.title;
  document.getElementById('url').value = tab.url;
  
  chrome.storage.sync.get(STORAGE_KEY, ({ [STORAGE_KEY]: data }) => {
    const d = data || { groups: [{id:'work',name:'Работа'}], bookmarks: [] };
    const select = document.getElementById('group');
    for (const g of d.groups) {
      const opt = document.createElement('option');
      opt.value = g.id;
      opt.textContent = g.name;
      select.appendChild(opt);
    }
    
    document.getElementById('form').onsubmit = (e) => {
      e.preventDefault();
      d.bookmarks.push({
        id: Date.now() + '',
        title: document.getElementById('title').value,
        url: document.getElementById('url').value,
        group: document.getElementById('group').value,
      });
      chrome.storage.sync.set({ [STORAGE_KEY]: d }, () => window.close());
    };
  });
})();
