// ZooFocus Popup Script
// Handles both popup mode and floating mode injection
// When content script is injected, popup sends COMMANDS and reads state from storage.
// When NOT injected, popup runs its own timer interval.

const WORK_DURATION = 25 * 60;
const BREAK_DURATION = 5 * 60;
const SESSIONS_PER_LEVEL = 5;

// State
let state = {
  timeRemaining: WORK_DURATION,
  isRunning: false,
  isWorkSession: true,
  level: 1,
  sessionsCompleted: 0,
  totalSessions: 0,
  isCelebrating: false,
  lastMilestone: 0,
  currentMode: 'popup',
  isInjected: false
};

let timerInterval = null;
let contentIsInjected = false; // tracks if content script is active on current tab

// DOM Elements
const popupModeBtn = document.getElementById('popupModeBtn');
const floatingModeBtn = document.getElementById('floatingModeBtn');
const popupMode = document.getElementById('popupMode');
const floatingMode = document.getElementById('floatingMode');
const injectBtn = document.getElementById('injectBtn');
const removeBtn = document.getElementById('removeBtn');
const statusIndicator = document.getElementById('statusIndicator');
const statusText = document.getElementById('statusText');

const timerDisplay = document.getElementById('timerDisplay');
const bearAnimation = document.getElementById('bearAnimation');
const sessionLabel = document.getElementById('sessionLabel');
const progressBar = document.getElementById('progressBar');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
const skipBtn = document.getElementById('skipBtn');
const levelNumber = document.getElementById('levelNumber');
const sessionsProgress = document.getElementById('sessionsProgress');
const levelProgressFill = document.getElementById('levelProgressFill');

// Motivational messages
const LEVEL_UP_MESSAGES = [
  "You're on fire! Keep the momentum going!",
  "Incredible focus! You're building great habits!",
  "Level up! Your productivity is soaring!",
  "Amazing work! You're becoming a focus master!",
  "Unstoppable! Your dedication is inspiring!"
];

const WORK_COMPLETE_MESSAGES = [
  "Excellent work! Time to recharge.",
  "Great job! You've earned this break.",
  "Well done! Take a moment to relax.",
  "Fantastic focus! Enjoy your break."
];

// Initialize
function init() {
  loadState();
  setupEventListeners();
  updateDisplay();
  updateLevelDisplay();
  checkInjectionStatus();
  
  // Listen for storage changes — this is how we stay in sync with the content script
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local' && changes.zoofocusState) {
      const newState = changes.zoofocusState.newValue;
      if (newState) {
        state = { ...state, ...newState };
        updateDisplay();
        updateLevelDisplay();
        updateButtonStates();
        setAnimation(state.isRunning ? (state.isWorkSession ? 'working' : 'idle') : 'idle');
        
        // Only manage popup interval if content script is NOT injected
        if (!contentIsInjected) {
          if (state.isRunning && !timerInterval) {
            startPopupTimer();
          } else if (!state.isRunning && timerInterval) {
            clearInterval(timerInterval);
            timerInterval = null;
          }
        }
      }
    }
  });
}

// Update button enabled/disabled states
function updateButtonStates() {
  if (startBtn) startBtn.disabled = state.isRunning;
  if (pauseBtn) pauseBtn.disabled = !state.isRunning;
}

// Setup event listeners
function setupEventListeners() {
  if (!startBtn || !pauseBtn || !resetBtn || !skipBtn) return;
  
  popupModeBtn.addEventListener('click', () => switchMode('popup'));
  floatingModeBtn.addEventListener('click', () => switchMode('floating'));
  
  startBtn.addEventListener('click', () => startTimer());
  pauseBtn.addEventListener('click', () => pauseTimer());
  resetBtn.addEventListener('click', () => resetTimer());
  skipBtn.addEventListener('click', () => skipSession());
  
  injectBtn.addEventListener('click', injectToPage);
  removeBtn.addEventListener('click', removeFromPage);
}

// Switch between popup and floating mode
function switchMode(mode) {
  state.currentMode = mode;
  
  if (mode === 'popup') {
    popupModeBtn.classList.add('active');
    floatingModeBtn.classList.remove('active');
    popupMode.style.display = 'block';
    floatingMode.style.display = 'none';
  } else {
    popupModeBtn.classList.remove('active');
    floatingModeBtn.classList.add('active');
    popupMode.style.display = 'none';
    floatingMode.style.display = 'block';
    checkInjectionStatus();
  }
  
  saveState();
}

// Check if timer is injected on current page
async function checkInjectionStatus() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    chrome.tabs.sendMessage(tab.id, { type: 'CHECK_INJECTION' }).then((response) => {
      updateInjectionStatus(response && response.isInjected);
    }).catch(() => {
      updateInjectionStatus(false);
    });
  } catch (error) {
    updateInjectionStatus(false);
  }
}

// Update injection status UI
function updateInjectionStatus(isInjected) {
  contentIsInjected = isInjected;
  state.isInjected = isInjected;
  
  if (isInjected) {
    statusIndicator.classList.add('active');
    statusText.textContent = 'Timer is active on this page';
    injectBtn.style.display = 'none';
    removeBtn.style.display = 'block';
    
    // Content script owns the timer — kill popup interval
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
  } else {
    statusIndicator.classList.remove('active');
    statusText.textContent = 'Not injected';
    injectBtn.style.display = 'block';
    removeBtn.style.display = 'none';
  }
}

// Inject timer to current page
async function injectToPage() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // Inject CSS first
    await chrome.scripting.insertCSS({
      target: { tabId: tab.id },
      files: ['overlay.css']
    });
    
    // Then inject JS
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ['content.js']
    });
    
    // Kill popup's own timer — content script will own it now
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    
    // Sync current state to injected timer
    setTimeout(() => {
      const syncState = { ...state, isCelebrating: false, lastMilestone: 0 };
      
      chrome.tabs.sendMessage(tab.id, {
        type: 'SYNC_STATE',
        state: syncState
      }).catch(() => {});
    }, 500);
    
    updateInjectionStatus(true);
  } catch (error) {
    alert('Could not inject timer. Try refreshing the page.');
  }
}

// Remove timer from current page
async function removeFromPage() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    chrome.tabs.sendMessage(tab.id, { type: 'REMOVE_OVERLAY' }).then(() => {
      updateInjectionStatus(false);
    }).catch(() => {
      updateInjectionStatus(false);
    });
  } catch (error) {
    // ignore
  }
}

// Format time
function formatTime(seconds) {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// Update display
function updateDisplay() {
  timerDisplay.textContent = formatTime(state.timeRemaining);
  sessionLabel.textContent = state.isWorkSession ? 'Work Session' : 'Break Time';
  
  // Update progress bar
  if (state.isWorkSession) {
    const progressPercent = ((WORK_DURATION - state.timeRemaining) / WORK_DURATION) * 100;
    progressBar.style.width = `${progressPercent}%`;
  } else {
    progressBar.style.width = '0%';
  }
  
  // Pulsing effect
  if (state.timeRemaining <= 60 && state.isRunning) {
    timerDisplay.classList.add('pulsing');
  } else {
    timerDisplay.classList.remove('pulsing');
  }
}

// Update level display
function updateLevelDisplay() {
  levelNumber.textContent = state.level;
  const sessionsInLevel = state.sessionsCompleted % SESSIONS_PER_LEVEL;
  sessionsProgress.textContent = `${sessionsInLevel}/${SESSIONS_PER_LEVEL} sessions`;
  
  const progressPercent = (sessionsInLevel / SESSIONS_PER_LEVEL) * 100;
  levelProgressFill.style.width = `${progressPercent}%`;
}

// Set animation
function setAnimation(animState) {
  const animations = {
    idle: 'assets/animations/bear_idle.gif',
    working: 'assets/animations/bear_working.gif',
    celebrating: 'assets/animations/bear_celebrating.gif',
    levelup: 'assets/animations/bear_levelup.gif',
    sad: 'assets/animations/bear_sad.gif'
  };
  
  bearAnimation.src = animations[animState] + '?t=' + Date.now();
}

// Get random message
function getRandomMessage(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

// Start popup timer (internal) — only used when content script is NOT injected
function startPopupTimer() {
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  
  timerInterval = setInterval(() => {
    state.timeRemaining--;
    updateDisplay();
    saveState();
    
    if (state.timeRemaining <= 0) {
      completeSession();
    }
  }, 1000);
}

// Send a command to the content script
async function sendCommand(command, extraState) {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.tabs.sendMessage(tab.id, {
      type: command,
      state: extraState || state
    }).catch(() => {});
  } catch (e) {}
}

// Start timer
function startTimer() {
  if (state.isRunning) return;
  
  state.isRunning = true;
  state.isCelebrating = false;
  if (state.isWorkSession) state.lastMilestone = 0;
  
  updateButtonStates();
  setAnimation(state.isWorkSession ? 'working' : 'idle');
  saveState();
  
  if (contentIsInjected) {
    sendCommand('CMD_START');
  } else {
    startPopupTimer();
  }
}

// Pause timer
function pauseTimer() {
  if (!state.isRunning) return;
  
  state.isRunning = false;
  
  updateButtonStates();
  setAnimation('idle');
  
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  
  saveState();
  
  if (contentIsInjected) {
    sendCommand('CMD_PAUSE');
  }
}

// Reset timer — always goes back to work session
function resetTimer() {
  state.isRunning = false;
  state.isCelebrating = false;
  state.lastMilestone = 0;
  state.isWorkSession = true;
  
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  
  state.timeRemaining = WORK_DURATION;
  
  updateButtonStates();
  updateDisplay();
  updateLevelDisplay();
  setAnimation('idle');
  saveState();
  
  if (contentIsInjected) {
    sendCommand('CMD_RESET');
  }
}

// Skip session — toggles between work and break
function skipSession() {
  pauseTimer();
  setAnimation('sad');
  
  if (contentIsInjected) {
    sendCommand('CMD_SKIP');
  }
  
  setTimeout(() => {
    state.isWorkSession = !state.isWorkSession;
    state.timeRemaining = state.isWorkSession ? WORK_DURATION : BREAK_DURATION;
    state.lastMilestone = 0;
    state.isCelebrating = false;
    
    updateDisplay();
    updateLevelDisplay();
    setAnimation('idle');
    saveState();
    
    if (contentIsInjected) {
      sendCommand('SYNC_STATE');
    }
  }, 2000);
}

// Complete session
function completeSession() {
  // Stop timer
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  state.isRunning = false;
  updateButtonStates();
  
  if (state.isWorkSession) {
    state.sessionsCompleted++;
    state.totalSessions++;
    
    const sessionsInLevel = state.sessionsCompleted % SESSIONS_PER_LEVEL;
    const isLevelUp = sessionsInLevel === 0;
    
    if (isLevelUp) {
      state.level++;
      setAnimation('levelup');
    } else {
      setAnimation('celebrating');
    }
    
    try {
      chrome.runtime.sendMessage({
        type: 'SHOW_NOTIFICATION',
        title: isLevelUp ? `Level ${state.level} Achieved! 🎉` : 'Work Session Complete! 🎯',
        message: isLevelUp ? getRandomMessage(LEVEL_UP_MESSAGES) : getRandomMessage(WORK_COMPLETE_MESSAGES)
      });
    } catch (e) {}
    
    updateLevelDisplay();
    saveState();
    
    // Transition to break after celebration
    const delay = isLevelUp ? 5000 : 3000;
    setTimeout(() => {
      state.isWorkSession = false;
      state.timeRemaining = BREAK_DURATION;
      state.lastMilestone = 0;
      state.isCelebrating = false;
      updateDisplay();
      updateLevelDisplay();
      setAnimation('idle');
      saveState();
      if (contentIsInjected) sendCommand('SYNC_STATE');
    }, delay);
    
  } else {
    // Break completed — go back to work
    setAnimation('celebrating');
    
    try {
      chrome.runtime.sendMessage({
        type: 'SHOW_NOTIFICATION',
        title: 'Break Over! 💪',
        message: 'Ready to focus again?'
      });
    } catch (e) {}
    
    saveState();
    
    setTimeout(() => {
      state.isWorkSession = true;
      state.timeRemaining = WORK_DURATION;
      state.lastMilestone = 0;
      state.isCelebrating = false;
      updateDisplay();
      updateLevelDisplay();
      setAnimation('idle');
      saveState();
      if (contentIsInjected) sendCommand('SYNC_STATE');
    }, 3000);
  }
}

// Save state
function saveState() {
  chrome.storage.local.set({ zoofocusState: state });
}

// Load state
function loadState() {
  chrome.storage.local.get(['zoofocusState'], (data) => {
    if (data.zoofocusState) {
      state = { ...state, ...data.zoofocusState };
      
      updateDisplay();
      updateLevelDisplay();
      updateButtonStates();
      setAnimation(state.isRunning ? (state.isWorkSession ? 'working' : 'idle') : 'idle');
      
      // Only start popup timer if running AND content script is not injected
      // checkInjectionStatus will be called after this and will kill the interval if needed
      if (state.isRunning) {
        startPopupTimer();
      }
      
      if (state.currentMode === 'floating') {
        switchMode('floating');
      }
    }
  });
}

// Initialize on load
init();
