// ZooFocus Background Service Worker
// Handles notifications only. Timer logic lives in popup.js and content.js.

// On install/update: ensure clean state (stop any stuck timers)
chrome.runtime.onInstalled.addListener(() => {
  // Clear any stale alarms from old versions
  chrome.alarms.clearAll();
  
  // Fix stuck state: if isRunning was true when extension updated, reset it
  chrome.storage.local.get(['zoofocusState'], (data) => {
    if (data.zoofocusState && data.zoofocusState.isRunning) {
      const fixed = { ...data.zoofocusState, isRunning: false };
      chrome.storage.local.set({ zoofocusState: fixed });
    }
  });
});

// Show notification
function showNotification(title, message) {
  chrome.notifications.create({
    type: 'basic',
    iconUrl: 'assets/icons/icon128.png',
    title: title,
    message: message,
    priority: 2
  });
}

// Listen for messages from popup and content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'SHOW_NOTIFICATION') {
    showNotification(message.title, message.message);
  }
});
