<template>
  <div :class="[theme, 'min-h-screen flex flex-col no-select']">
    <!-- Optional: Update Notification UI -->
    <div v-if="showUpdateBar" class="bg-blue-600 text-white p-3 text-center text-sm shadow-md">
      A new version is available!
      <button @click="refreshApp" class="ml-4 font-semibold underline hover:text-blue-200">REFRESH</button>
      <button @click="showUpdateBar = false" class="ml-4 font-semibold absolute right-3 top-1/2 transform -translate-y-1/2 p-1">✕</button>
    </div>

    <!-- Optional: Install Button (place somewhere appropriate, e.g., header or settings) -->
    <!-- Example: Adding to App.vue for demo, ideally place in SetupView or a menu -->
    <button v-if="showInstallButton" @click="promptInstall" class="fixed bottom-4 right-4 bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded shadow-lg z-50">
      Install App
    </button>

    <router-view class="flex-grow" />
  </div>
</template>

<script setup>
import { computed, onMounted, watch, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { AudioService } from './services/AudioService';
import { MqttService } from './services/MqttService';

const store = useStore();
const router = useRouter();
const theme = computed(() => store.getters.theme);

const handleMqttMessage = (char) => { // This is the general command handler
  console.log(`App.vue: Processing MQTT char (as command): '${char}'`);
  const currentRouteName = router.currentRoute.value.name;

  // Global MQTT Stop/Pause All
  if (char === store.getters.globalMqttStopPause && store.getters.globalMqttStopPause) {
    if (currentRouteName === 'Game') {
      store.dispatch('globalStopPauseAll');
      console.log("MQTT Command: Global Stop/Pause All triggered");
    }
    return;
  }

  // Global MQTT Run All Timers
  if (char === store.getters.globalMqttRunAll && store.getters.globalMqttRunAll) {
    if (currentRouteName === 'Game' && store.getters.gameMode === 'normal') {
      store.dispatch('switchToAllTimersMode');
      console.log("MQTT Command: Global Run All Timers triggered");
    }
    return;
  }

  // Global MQTT Pass Turn
  if (char === store.getters.globalMqttPassTurn && store.getters.globalMqttPassTurn) {
    if (currentRouteName === 'Game' && store.getters.gameMode === 'normal') {
      // Similar logic to player-specific pass turn, but not tied to current player's MQTT char
      const currentPlayer = store.getters.currentPlayer;
      if (currentPlayer && !currentPlayer.isSkipped) { // Ensure there's a current player to pass from
          AudioService.cancelPassTurnSound(); 
          const wasRunning = currentPlayer.isTimerRunning;
          store.dispatch('passTurn').then(() => {
            const newCurrentPlayer = store.getters.currentPlayer;
            if (wasRunning && newCurrentPlayer && newCurrentPlayer.isTimerRunning) {
               AudioService.playPassTurnAlert(); 
            }
          });
          console.log("MQTT Command: Global Pass Turn triggered");
      }
    }
    return;
  }
  
  // Player specific MQTT Pass Turn / My Pause
  if (currentRouteName === 'Game') {
    const gameModeInStore = store.getters.gameMode;
    const currentPlayerInStore = store.getters.currentPlayer;

    if (gameModeInStore === 'normal' && currentPlayerInStore && char === currentPlayerInStore.mqttChar) {
      const wasRunning = currentPlayerInStore.isTimerRunning;
          store.dispatch('passTurn').then(() => {
            const newCurrentPlayer = store.getters.currentPlayer;
            if (wasRunning && newCurrentPlayer && newCurrentPlayer.isTimerRunning) {
               AudioService.playPassTurnAlert(); 
            }
          });
      console.log(`MQTT Command: Player ${currentPlayerInStore.name} Pass Turn triggered`);
    return;
  }
  
    if (gameModeInStore === 'allTimers') {
      // Find player by mqttChar. Ensure players array exists.
      const playerToToggle = store.state.players?.find(p => p.mqttChar === char && !p.isSkipped);
      if (playerToToggle) {
        const playerIndex = store.state.players.indexOf(playerToToggle);
        store.dispatch('togglePlayerTimerAllTimersMode', playerIndex);
        console.log(`MQTT Command: Player ${playerToToggle.name} Timer Toggle triggered`);
      }
    }
  }
};

// --- PWA Install Prompt Logic ---
const deferredPrompt = ref(null);
const showInstallButton = ref(false);

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt.value = e;
  // Update UI to notify the user they can add to home screen
  showInstallButton.value = true;
  console.log('`beforeinstallprompt` event was fired.');
});

const promptInstall = async () => {
  if (!deferredPrompt.value) {
    alert('Install prompt not available.');
    return;
  }
  showInstallButton.value = false; // Hide the button once prompt is shown
  // Show the prompt
  deferredPrompt.value.prompt();
  // Wait for the user to respond to the prompt
  const { outcome } = await deferredPrompt.value.userChoice;
  console.log(`User response to the install prompt: ${outcome}`);
  // We've used the prompt, and can't use it again, throw it away
  deferredPrompt.value = null;
};

window.addEventListener('appinstalled', () => {
  // Hide the install button if the app is installed
  showInstallButton.value = false;
  deferredPrompt.value = null;
  console.log('Nexus Timer was installed.');
  // Optionally: Send analytics event
});
// --- End PWA Install Prompt Logic ---

// --- PWA Update Logic ---
const showUpdateBar = ref(false);
let newWorker;

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.ready.then(registration => {
    if (registration.waiting) {
      console.log("SW Update: Found waiting worker on load");
      newWorker = registration.waiting;
      showUpdateBar.value = true;
      return;
    }
    registration.addEventListener('updatefound', () => {
      console.log("SW Update: New worker found, installing...");
      newWorker = registration.installing;
      newWorker.addEventListener('statechange', () => {
        if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
           console.log("SW Update: New worker installed and ready");
           showUpdateBar.value = true; // Show refresh bar
        }
      });
    });
  });

  // Detect controller change and refresh the page.
  // Can happen if skipWaiting() is used and the page wasn't manually refreshed.
  let refreshing;
  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (refreshing) return;
    console.log("SW Update: Controller changed, refreshing page.");
    refreshing = true;
    window.location.reload();
  });
}

const refreshApp = () => {
  showUpdateBar.value = false;
  if (newWorker) {
    console.log("SW Update: Sending skipWaiting message");
    newWorker.postMessage({ action: 'skipWaiting' });
    // Page should reload via 'controllerchange' listener above
  } else {
     console.warn("SW Update: Refresh called but no new worker found.");
     window.location.reload(); // Fallback reload
  }
};
// --- End PWA Update Logic ---


onMounted(() => {
  store.dispatch('loadState').then(() => {
    // Sync with OS theme preference on initial load if no theme is saved yet
    // Note: Store initializer already loads saved theme if it exists.
    // This logic should perhaps check if the loaded theme matches OS pref
    // or only apply OS pref if no theme was loaded from storage.
    // Simplified: Apply loaded theme regardless for now.
    applyTheme();

    // Example: Sync with OS theme only if no theme saved (requires store modification)
    // syncWithOsThemeIfNeeded();

  // Auto-connect MQTT only if URL is stored AND user desires connection
  const storedBrokerUrl = store.getters.mqttBrokerUrl;
    const connectDesired = store.getters.mqttConnectDesired; // Get the flag

    if (storedBrokerUrl && 
        connectDesired && // Check the flag
        MqttService.connectionStatus.value !== 'connected' && 
        MqttService.connectionStatus.value !== 'connecting') {
      console.log("App.vue: Auto-connecting to stored MQTT broker (user desired):", storedBrokerUrl);
      MqttService.connect(storedBrokerUrl);
    } else if (storedBrokerUrl && !connectDesired) {
      console.log("App.vue: MQTT Broker URL is stored, but user previously disconnected. Not auto-connecting.");
    }
  }).catch(error => {
    console.error("App.vue: Error during store.dispatch('loadState'):", error);
  });

  document.addEventListener('keydown', handleGlobalKeyDown);
  MqttService.setGeneralMessageHandler(handleMqttMessage); // Set handler regardless of initial connection

  const resumeAudio = () => { AudioService.resumeContext(); /* ... remove listeners ... */ };
  document.body.addEventListener('click', resumeAudio, { once: true });
  document.body.addEventListener('touchstart', resumeAudio, { once: true });
  MqttService.setGeneralMessageHandler(handleMqttMessage);
});

watch(theme, () => {
  applyTheme();
});

watch(() => store.state.isMuted, (newMutedState) => {
  AudioService.setMuted(newMutedState);
});


const applyTheme = () => {
  if (store.getters.theme === 'dark') {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
};

// Optional: Function to sync with OS theme
// const syncWithOsThemeIfNeeded = () => {
//   // Requires modification to store state/initializer to know if theme was explicitly set/saved
//   const themeWasLoaded = store.getters.theme !== initialState.theme; // Example check needed
//   if (!themeWasLoaded && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
//      console.log("Syncing with OS dark theme preference.");
//      store.dispatch('toggleTheme'); // Assumes toggle sets it correctly
//   }
// }

// handleGlobalKeyDown (remains the same as previous version)
const handleGlobalKeyDown = (event) => {
  const targetElement = event.target;
  if (targetElement.tagName === 'INPUT' || 
      targetElement.tagName === 'TEXTAREA' || 
      targetElement.isContentEditable) {
    return;
  }

  const keyPressed = event.key.toLowerCase();
  const currentRouteName = router.currentRoute.value.name;

  if (keyPressed === store.getters.globalHotkeyStopPause && store.getters.globalHotkeyStopPause) {
    event.preventDefault();
    if (currentRouteName === 'Game') {
        store.dispatch('globalStopPauseAll');
    }
    return;
  }

  if (keyPressed === store.getters.globalHotkeyRunAll && store.getters.globalHotkeyRunAll) {
    event.preventDefault();
    if (currentRouteName === 'Game' && store.getters.gameMode === 'normal') {
        store.dispatch('switchToAllTimersMode');
    }
    return;
  }

  if (keyPressed === store.getters.globalHotkeyPassTurn && store.getters.globalHotkeyPassTurn) {
    event.preventDefault();
    if (currentRouteName === 'Game' && store.getters.gameMode === 'normal') {
      const currentPlayer = store.getters.currentPlayer;
       if (currentPlayer && !currentPlayer.isSkipped) {
          AudioService.cancelPassTurnSound(); 
          const wasRunning = currentPlayer.isTimerRunning;
          store.dispatch('passTurn').then(() => {
            const newCurrentPlayer = store.getters.currentPlayer;
            if (wasRunning && newCurrentPlayer && newCurrentPlayer.isTimerRunning) {
               AudioService.playPassTurnAlert(); 
            }
          });
          console.log("Hotkey: Global Pass Turn triggered");
      }
    }
    return;
  }

  if (currentRouteName === 'Game') {
      const currentPlayerInStore = store.getters.currentPlayer;
      const gameModeInStore = store.getters.gameMode;

      if (gameModeInStore === 'normal' && currentPlayerInStore && keyPressed === currentPlayerInStore.hotkey) {
        event.preventDefault();
        const wasRunning = currentPlayerInStore.isTimerRunning;
        store.dispatch('passTurn').then(() => {
            const newCurrentPlayer = store.getters.currentPlayer;
            if (wasRunning && newCurrentPlayer && newCurrentPlayer.isTimerRunning) {
                AudioService.playPassTurnAlert();
            }
        });
      } else if (gameModeInStore === 'allTimers') {
        const playerToToggle = store.state.players.find(p => p.hotkey === keyPressed && !p.isSkipped);
        if (playerToToggle) {
          event.preventDefault();
          const playerIndex = store.state.players.indexOf(playerToToggle);
          store.dispatch('togglePlayerTimerAllTimersMode', playerIndex);
        }
      }
  }
};
</script>

<style>
html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
  overscroll-behavior: none;
}
</style>