// ZooFocus Floating Timer - Content Script
// Injects draggable timer overlay on every webpage

(function() {
  'use strict';
  
  // Prevent multiple injections
  if (window.zoofocusInjected) {
    console.log('ZooFocus already injected');
    return;
  }
  window.zoofocusInjected = true;
  
  // Constants
  const WORK_DURATION = 25 * 60;
  const BREAK_DURATION = 5 * 60;
  const SESSIONS_PER_LEVEL = 5;
  
  // Get extension URL for assets
  const getAssetURL = (path) => {
    try {
      return chrome.runtime.getURL(path);
    } catch (error) {
      console.log('Extension context invalidated, using fallback');
      return '';
    }
  };
  
  // State
  let state = {
    timeRemaining: WORK_DURATION,
    isRunning: false,
    isWorkSession: true,
    level: 1,
    sessionsCompleted: 0,
    totalSessions: 0,
    isCelebrating: false,
    lastMilestone: 0,
    isMinimized: false,
    isHidden: false,
    position: { x: null, y: null }
  };
  
  let timerInterval = null;
  let savingState = false; // flag to prevent storage change feedback loop
  
  // DOM Elements (will be created)
  let overlay, widget, widgetMini, timerDisplay, bearImg, progressBar, levelProgressBar;
  let startBtn, pauseBtn, resetBtn, skipBtn, levelNumber, sessionsProgress;
  let sessionLabel, miniTimer;
  
  // 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."
  ];
  
  // Create overlay HTML
  function createOverlay() {
    const overlayHTML = `
      <div id="zoofocus-overlay">
        <div id="zoofocus-widget">
          <div class="zoofocus-handle">
            <img src="${getAssetURL('assets/icons/icon48.png')}" class="zoofocus-logo" alt="ZooFocus">
            <span>ZooFocus</span>
            <button class="zoofocus-minimize" title="Minimize">−</button>
            <button class="zoofocus-close" title="Close">×</button>
          </div>
          
          <div class="zoofocus-session-label" id="zoofocus-session-label">Work Session</div>
          
          <div class="zoofocus-timer" id="zoofocus-timer">25:00</div>
          
          <div class="zoofocus-progress-container">
            <div class="zoofocus-progress-bar" id="zoofocus-progress-bar"></div>
          </div>
          
          <div class="zoofocus-animation">
            <img src="${getAssetURL('assets/animations/bear_idle.gif')}" id="zoofocus-bear" alt="Bear">
          </div>
          
          <div class="zoofocus-controls">
            <button class="zoofocus-btn-start" id="zoofocus-start">Start</button>
            <button class="zoofocus-btn-pause" id="zoofocus-pause" disabled>Pause</button>
            <button class="zoofocus-btn-reset" id="zoofocus-reset">Reset</button>
            <button class="zoofocus-btn-skip" id="zoofocus-skip">Skip</button>
          </div>
          
          <div class="zoofocus-level">
            <div class="zoofocus-level-number" id="zoofocus-level-number">Level 1</div>
            <div class="zoofocus-sessions" id="zoofocus-sessions">0/5 sessions</div>
            <div class="zoofocus-level-progress">
              <div class="zoofocus-level-progress-fill" id="zoofocus-level-progress"></div>
            </div>
          </div>
        </div>
        
        <div id="zoofocus-widget-mini" class="zoofocus-hidden">
          <img src="${getAssetURL('assets/icons/icon48.png')}" class="zoofocus-mini-icon" alt="ZooFocus">
          <span class="zoofocus-mini-timer" id="zoofocus-mini-timer">25:00</span>
          <button class="zoofocus-expand" title="Expand">+</button>
        </div>
      </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', overlayHTML);
    
    // Get DOM references
    overlay = document.getElementById('zoofocus-overlay');
    widget = document.getElementById('zoofocus-widget');
    widgetMini = document.getElementById('zoofocus-widget-mini');
    timerDisplay = document.getElementById('zoofocus-timer');
    bearImg = document.getElementById('zoofocus-bear');
    progressBar = document.getElementById('zoofocus-progress-bar');
    levelProgressBar = document.getElementById('zoofocus-level-progress');
    sessionLabel = document.getElementById('zoofocus-session-label');
    miniTimer = document.getElementById('zoofocus-mini-timer');
    
    startBtn = document.getElementById('zoofocus-start');
    pauseBtn = document.getElementById('zoofocus-pause');
    resetBtn = document.getElementById('zoofocus-reset');
    skipBtn = document.getElementById('zoofocus-skip');
    levelNumber = document.getElementById('zoofocus-level-number');
    sessionsProgress = document.getElementById('zoofocus-sessions');
    
    // Setup event listeners
    setupEventListeners();
    
    // Make draggable
    makeDraggable(widget);
    
    // Load saved state
    loadState();
  }
  
  // Setup event listeners
  function setupEventListeners() {
    if (!startBtn || !pauseBtn || !resetBtn || !skipBtn) return;
    
    startBtn.addEventListener('click', () => startTimer());
    pauseBtn.addEventListener('click', () => pauseTimer());
    resetBtn.addEventListener('click', () => resetTimer());
    skipBtn.addEventListener('click', () => skipSession());
    
    const minimizeBtn = document.querySelector('.zoofocus-minimize');
    const closeBtn = document.querySelector('.zoofocus-close');
    const expandBtn = document.querySelector('.zoofocus-expand');
    
    if (minimizeBtn) minimizeBtn.addEventListener('click', minimizeWidget);
    if (closeBtn) closeBtn.addEventListener('click', closeWidget);
    if (expandBtn) expandBtn.addEventListener('click', expandWidget);
    if (widgetMini) widgetMini.addEventListener('click', expandWidget);
  }
  
  // Draggable functionality
  function makeDraggable(element) {
    let isDragging = false;
    let currentX, currentY, initialX, initialY;
    const handle = element.querySelector('.zoofocus-handle');
    
    handle.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', dragEnd);
    
    function dragStart(e) {
      if (e.target.tagName === 'BUTTON' || e.target.tagName === 'IMG') return;
      
      isDragging = true;
      initialX = e.clientX - (state.position.x || element.offsetLeft);
      initialY = e.clientY - (state.position.y || element.offsetTop);
      handle.style.cursor = 'grabbing';
    }
    
    function drag(e) {
      if (!isDragging) return;
      
      e.preventDefault();
      currentX = e.clientX - initialX;
      currentY = e.clientY - initialY;
      
      element.style.left = currentX + 'px';
      element.style.top = currentY + 'px';
      element.style.right = 'auto';
    }
    
    function dragEnd() {
      if (isDragging) {
        state.position = { x: currentX, y: currentY };
        saveState();
      }
      isDragging = false;
      handle.style.cursor = 'move';
    }
  }
  
  // Minimize widget
  function minimizeWidget() {
    state.isMinimized = true;
    widget.classList.add('zoofocus-hidden');
    widgetMini.classList.remove('zoofocus-hidden');
    saveState();
  }
  
  // Expand widget
  function expandWidget() {
    state.isMinimized = false;
    widget.classList.remove('zoofocus-hidden');
    widgetMini.classList.add('zoofocus-hidden');
    saveState();
  }
  
  // Close widget — fully removes overlay so it can be re-injected
  function closeWidget() {
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    state.isRunning = false;
    state.isHidden = false;
    state.isMinimized = false;
    saveState();
    
    if (overlay) {
      overlay.remove();
    }
    window.zoofocusInjected = false;
  }
  
  // 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() {
    const timeStr = formatTime(state.timeRemaining);
    timerDisplay.textContent = timeStr;
    miniTimer.textContent = timeStr;
    sessionLabel.textContent = state.isWorkSession ? 'Work Session' : 'Break Time';
    
    // Update progress bar
    if (state.isWorkSession && progressBar) {
      const progressPercent = ((WORK_DURATION - state.timeRemaining) / WORK_DURATION) * 100;
      progressBar.style.width = `${progressPercent}%`;
    } else if (progressBar) {
      progressBar.style.width = '0%';
    }
    
    // Update button states
    if (startBtn && pauseBtn) {
      startBtn.disabled = state.isRunning;
      pauseBtn.disabled = !state.isRunning;
    }
    
    // Pulsing effect in last minute
    if (state.timeRemaining <= 60 && state.isRunning) {
      timerDisplay.classList.add('pulsing');
    } else {
      timerDisplay.classList.remove('pulsing');
    }
  }
  
  // Update level display
  function updateLevelDisplay() {
    levelNumber.textContent = `Level ${state.level}`;
    const sessionsInLevel = state.sessionsCompleted % SESSIONS_PER_LEVEL;
    sessionsProgress.textContent = `${sessionsInLevel}/${SESSIONS_PER_LEVEL} sessions`;
    
    const progressPercent = (sessionsInLevel / SESSIONS_PER_LEVEL) * 100;
    levelProgressBar.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'
    };
    
    if (!bearImg) return;
    
    const animPath = animations[animState] || animations.idle;
    const fullURL = getAssetURL(animPath) + '?t=' + Date.now();
    
    // Force reload by clearing src first
    bearImg.src = '';
    
    setTimeout(() => {
      bearImg.src = fullURL;
    }, 10);
    
    // Update CSS class
    bearImg.classList.remove('working');
    if (animState === 'working') {
      bearImg.classList.add('working');
    }
  }
  
  // Show toast
  function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'zoofocus-toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => toast.classList.add('show'), 100);
    
    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 300);
    }, 2500);
  }
  
  // Show full-screen celebration
  function showCelebration(title, message) {
    try {
      const celebrationOverlay = document.createElement('div');
      celebrationOverlay.className = 'zoofocus-celebration-overlay';
      
      const bearURL = getAssetURL('assets/animations/bear_celebrating.gif');
      if (!bearURL) {
            return;
      }
      
      celebrationOverlay.innerHTML = `
        <div class="zoofocus-celebration-content">
          <img src="${bearURL}?t=${Date.now()}" 
               class="zoofocus-celebration-bear" 
               alt="Celebrating Bear">
          <div class="zoofocus-celebration-text">${title}</div>
          <div class="zoofocus-celebration-message">${message}</div>
        </div>
      `;
    
      document.body.appendChild(celebrationOverlay);
      
      // Add confetti
      createConfetti(celebrationOverlay);
      
      // Show overlay
      setTimeout(() => celebrationOverlay.classList.add('show'), 100);
      
      // Hide and remove after 1.5 seconds (more subtle)
      setTimeout(() => {
        celebrationOverlay.classList.remove('show');
        setTimeout(() => celebrationOverlay.remove(), 200);
      }, 1500);
    } catch (error) {
      console.log('Error showing celebration:', error.message);
    }
  }
  
  // Create confetti effect
  function createConfetti(container) {
    const colors = ['#FFD700', '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8'];
    const confettiCount = 20; // Reduced for subtlety
    
    for (let i = 0; i < confettiCount; i++) {
      const confetti = document.createElement('div');
      confetti.className = 'zoofocus-confetti';
      confetti.style.left = Math.random() * 100 + 'vw';
      confetti.style.background = colors[Math.floor(Math.random() * colors.length)];
      confetti.style.animationDelay = Math.random() * 0.5 + 's';
      confetti.style.animationDuration = (Math.random() * 2 + 2) + 's';
      container.appendChild(confetti);
    }
  }
  
  // Get random message
  function getRandomMessage(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  
  // Check milestone
  function checkMilestone() {
    if (!state.isWorkSession) return;
    if (state.isCelebrating) return;
    
    const timeElapsed = WORK_DURATION - state.timeRemaining;
    const minutesCompleted = Math.floor(timeElapsed / 60);
    
    const milestones = [1, 5, 10, 15, 20];
    
    if (milestones.includes(minutesCompleted) && minutesCompleted > state.lastMilestone) {
      state.lastMilestone = minutesCompleted;
      celebrateMilestone(minutesCompleted);
    }
  }
  
  // Celebrate milestone
  function celebrateMilestone(minutes) {
    state.isCelebrating = true;
    
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    
    setAnimation('celebrating');
    
    if (progressBar) {
      progressBar.classList.add('milestone-hit');
      setTimeout(() => progressBar.classList.remove('milestone-hit'), 500);
    }
    
    const celebrations = {
      1: {
        title: '🎉 1 Minute Focused!',
        message: 'Great start! Keep the momentum going!'
      },
      5: {
        title: '💪 5 Minutes Down!',
        message: 'You\'re doing amazing! Stay focused!'
      },
      10: {
        title: '🔥 Halfway There!',
        message: '10 minutes of pure focus! You\'re unstoppable!'
      },
      15: {
        title: '⭐ 15 Minutes!',
        message: 'You\'re crushing it! Keep going strong!'
      },
      20: {
        title: '🚀 20 Minutes!',
        message: 'Almost done! You\'re a focus champion!'
      }
    };
    
    const celebration = celebrations[minutes];
    if (celebration) {
      showCelebration(celebration.title, celebration.message);
    }
    
    setTimeout(() => {
      setAnimation('working');
      state.isCelebrating = false;
      
      timerInterval = setInterval(() => {
        state.timeRemaining--;
        updateDisplay();
        saveState();
        
        if (state.timeRemaining % 60 === 0) {
          checkMilestone();
        }
        
        if (state.timeRemaining <= 0) {
          completeSession();
        }
      }, 1000);
    }, 1500); // Reduced pause time for subtlety
  }
  
  // Start the interval (shared helper)
  function startInterval() {
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    
    timerInterval = setInterval(() => {
      state.timeRemaining--;
      updateDisplay();
      saveState();
      
      if (state.isWorkSession) checkMilestone();
      
      if (state.timeRemaining <= 0) {
        completeSession();
      }
    }, 1000);
  }
  
  // Start timer
  function startTimer() {
    if (state.isRunning) return;
    
    state.isRunning = true;
    state.isCelebrating = false;
    if (state.isWorkSession) state.lastMilestone = 0;
    
    if (startBtn) startBtn.disabled = true;
    if (pauseBtn) pauseBtn.disabled = false;
    
    setAnimation(state.isWorkSession ? 'working' : 'idle');
    startInterval();
    saveState();
  }
  
  // Pause timer
  function pauseTimer() {
    if (!state.isRunning) return;
    
    state.isRunning = false;
    state.isCelebrating = false;
    
    if (startBtn) startBtn.disabled = false;
    if (pauseBtn) pauseBtn.disabled = true;
    
    setAnimation('idle');
    
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    
    saveState();
  }
  
  // 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;
    
    if (startBtn) startBtn.disabled = false;
    if (pauseBtn) pauseBtn.disabled = true;
    updateDisplay();
    updateLevelDisplay();
    setAnimation('idle');
    
    saveState();
  }
  
  // Skip session — toggles between work and break
  function skipSession() {
    pauseTimer();
    
    setAnimation('sad');
    showToast(state.isWorkSession ? 'Skipping to break 😢' : 'Skipping to work 💪');
    
    setTimeout(() => {
      state.isWorkSession = !state.isWorkSession;
      state.timeRemaining = state.isWorkSession ? WORK_DURATION : BREAK_DURATION;
      state.lastMilestone = 0;
      state.isCelebrating = false;
      
      updateDisplay();
      updateLevelDisplay();
      setAnimation('idle');
      saveState();
    }, 2000);
  }
  
  // Complete session
  function completeSession() {
    // Stop the timer
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    state.isRunning = false;
    
    if (state.isWorkSession) {
      // Work session completed
      state.sessionsCompleted++;
      state.totalSessions++;
      
      const sessionsInLevel = state.sessionsCompleted % SESSIONS_PER_LEVEL;
      const isLevelUp = sessionsInLevel === 0;
      
      if (isLevelUp) {
        state.level++;
        setAnimation('levelup');
        showToast(`🎊 Level ${state.level} Unlocked!`);
      } else {
        setAnimation('celebrating');
        showToast('Session complete! 🎯');
      }
      
      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 (error) {}
      
      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;
        if (startBtn) startBtn.disabled = false;
        if (pauseBtn) pauseBtn.disabled = true;
        updateDisplay();
        updateLevelDisplay();
        setAnimation('idle');
        saveState();
      }, delay);
      
    } else {
      // Break completed — go back to work
      setAnimation('celebrating');
      showToast('Break over! Let\'s focus! 💪');
      
      try {
        chrome.runtime.sendMessage({
          type: 'SHOW_NOTIFICATION',
          title: 'Break Over! 💪',
          message: 'Ready to focus again?'
        });
      } catch (error) {}
      
      saveState();
      
      setTimeout(() => {
        state.isWorkSession = true;
        state.timeRemaining = WORK_DURATION;
        state.lastMilestone = 0;
        state.isCelebrating = false;
        if (startBtn) startBtn.disabled = false;
        if (pauseBtn) pauseBtn.disabled = true;
        updateDisplay();
        updateLevelDisplay();
        setAnimation('idle');
        saveState();
      }, 3000);
    }
  }
  
  // Save state
  function saveState() {
    try {
      savingState = true;
      chrome.storage.local.set({ zoofocusState: state }, () => {
        // Reset flag after write completes
        setTimeout(() => { savingState = false; }, 50);
      });
    } catch (error) {
      savingState = false;
    }
  }
  
  // Load state
  function loadState() {
    try {
      chrome.storage.local.get(['zoofocusState'], (data) => {
      if (data.zoofocusState) {
        // Restore timer-related state but always show widget on fresh injection
        const saved = data.zoofocusState;
        state.timeRemaining = saved.timeRemaining || WORK_DURATION;
        state.isWorkSession = saved.isWorkSession !== undefined ? saved.isWorkSession : true;
        state.level = saved.level || 1;
        state.sessionsCompleted = saved.sessionsCompleted || 0;
        state.totalSessions = saved.totalSessions || 0;
        state.lastMilestone = saved.lastMilestone || 0;
        
        // Always show widget on injection — don't restore hidden/minimized
        state.isHidden = false;
        state.isMinimized = false;
        state.isRunning = false;
        state.isCelebrating = false;
        
        // Restore position
        if (saved.position && saved.position.x !== null && saved.position.y !== null) {
          state.position = saved.position;
          widget.style.left = state.position.x + 'px';
          widget.style.top = state.position.y + 'px';
          widget.style.right = 'auto';
        }
        
        updateDisplay();
        updateLevelDisplay();
        setAnimation('idle');
        
        if (startBtn) startBtn.disabled = false;
        if (pauseBtn) pauseBtn.disabled = true;
      }
    });
    } catch (error) {
      console.log('Could not load state (extension context may be invalid)');
    }
  }
  
  // Listen for messages from popup and background
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'TIMER_UPDATE') {
      state = { ...state, ...message.state };
      updateDisplay();
      updateLevelDisplay();
      return false;
    }
    
    if (message.type === 'CHECK_INJECTION') {
      sendResponse({ isInjected: true });
      return false;
    }
    
    // Popup commands — content script is the single timer owner
    if (message.type === 'CMD_START') {
      if (!state.isRunning) {
        startTimer();
      }
      return false;
    }
    
    if (message.type === 'CMD_PAUSE') {
      pauseTimer();
      return false;
    }
    
    if (message.type === 'CMD_RESET') {
      resetTimer();
      return false;
    }
    
    if (message.type === 'CMD_SKIP') {
      skipSession();
      return false;
    }
    
    if (message.type === 'SYNC_STATE') {
      // Full state sync from popup
      if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
      }
      
      state = { ...state, ...message.state };
      state.isRunning = false;
      state.isHidden = false;
      state.isMinimized = false;
      state.isCelebrating = false;
      
      // Ensure widget is visible
      if (widget) widget.classList.remove('zoofocus-hidden');
      if (widgetMini) widgetMini.classList.add('zoofocus-hidden');
      
      if (startBtn) startBtn.disabled = false;
      if (pauseBtn) pauseBtn.disabled = true;
      updateDisplay();
      updateLevelDisplay();
      setAnimation('idle');
      saveState();
      return false;
    }
    
    if (message.type === 'REMOVE_OVERLAY') {
      if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
      }
      if (overlay) {
        overlay.remove();
        window.zoofocusInjected = false;
      }
      sendResponse({ removed: true });
      return false;
    }
  });
  
  // Listen for storage changes — only react if WE didn't write it (popup wrote it)
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local' && changes.zoofocusState && !savingState) {
      const newState = changes.zoofocusState.newValue;
      if (newState && !state.isCelebrating) {
        state = { ...state, ...newState };
        updateDisplay();
        updateLevelDisplay();
      }
    }
  });
  
  // Initialize
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createOverlay);
  } else {
    createOverlay();
  }
})();
