<template>
  <div class="h-screen w-screen bg-slate-950 text-slate-200 overflow-hidden flex flex-col font-sans">
    
    <!-- Top Navigation Bar -->
    <header class="bg-slate-900 border-b border-slate-800 px-6 py-4 flex justify-between items-center shadow-md z-10 shrink-0">
      <div class="flex items-center space-x-4">
        <h1 class="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-400 to-cyan-400 tracking-tight">
          {{ appTitle }} <span class="text-xs font-mono font-normal ml-2 text-slate-500 bg-slate-800 px-2 py-1 rounded">Web</span>
        </h1>
        
        <!-- Connection Status Indicator -->
        <span 
          class="flex items-center text-xs font-medium px-2.5 py-1 rounded-full border"
          :class="isConnected ? 'bg-emerald-900/30 text-emerald-400 border-emerald-800/50' : 'bg-rose-900/30 text-rose-400 border-rose-800/50'"
        >
          <span class="w-2 h-2 rounded-full mr-2" :class="isConnected ? 'bg-emerald-400 animate-pulse' : 'bg-rose-500'"></span>
          {{ isConnected ? 'Connected to Backend Engine' : 'Disconnected - Retrying...' }}
        </span>
      </div>
      
      <!-- Controls and Connect Button -->
      <div class="flex items-center space-x-3">
        <!-- View Switcher -->
        <div class="flex bg-slate-800 rounded-lg p-1 mr-4">
          <button 
            @click="activeView = 'dashboard'"
            class="px-3 py-1 text-xs font-bold rounded-md transition-all"
            :class="activeView === 'dashboard' ? 'bg-indigo-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'"
          >
            Dashboard
          </button>
          <button 
            @click="activeView = 'chipInfo'"
            class="px-3 py-1 text-xs font-bold rounded-md transition-all"
            :class="activeView === 'chipInfo' ? 'bg-indigo-600 text-white shadow-lg' : 'text-slate-400 hover:text-slate-200'"
          >
            Chip Info
          </button>
        </div>
      
        <!-- Streaming & Clear Controls -->
        <div v-show="isDeviceConnected && activeView === 'dashboard'" class="flex items-center space-x-2 mr-4 border-r border-slate-700 pr-4">
            <button 
              @click="toggleStream"
              class="px-3 py-1.5 text-xs font-semibold rounded shadow-sm transition-all border text-slate-200"
              :class="isStreaming ? 'bg-amber-600/20 border-amber-600/50 hover:bg-amber-600/40 text-amber-500' : 'bg-emerald-600/20 border-emerald-600/50 hover:bg-emerald-600/40 text-emerald-400'"
            >
              {{ isStreaming ? 'Pause Stream' : 'Resume Stream' }}
            </button>
            <button 
              @click="clearData"
              class="px-3 py-1.5 text-xs font-semibold rounded shadow-sm transition-all border border-slate-600 bg-slate-800 hover:bg-slate-700 text-slate-300"
            >
              Clear
            </button>
         </div>
      
         <select @focus="refreshPorts" v-model="selectedPort" class="bg-slate-800 border border-slate-700 text-sm rounded-md px-3 py-1.5 focus:border-indigo-500 min-w-[140px]">
           <option v-for="port in availablePorts" :key="port" :value="port">{{ port }}</option>
           <option value="SIMULATOR">-- Simulator (Mock) --</option>
         </select>
         <select v-model="selectedBaud" class="bg-slate-800 border border-slate-700 text-sm rounded-md px-3 py-1.5 focus:border-indigo-500 w-[110px]">
           <option v-for="baud in [115200, 921600, 1152000, 2000000]" :key="baud" :value="baud">{{ baud }}</option>
         </select>
         <button 
           @click="toggleConnection" 
           class="px-4 py-1.5 text-sm font-semibold rounded-md shadow-sm transition-all text-white"
           :class="isDeviceConnected ? 'bg-rose-600 hover:bg-rose-500 shadow-rose-900/50' : 'bg-indigo-600 hover:bg-indigo-500 shadow-indigo-900/50'"
           :disabled="!isConnected || isFirmwareOperationActive"
         >
            {{ isDeviceConnected ? 'Disconnect' : 'Connect' }}
         </button>
      </div>
    </header>

    <!-- Main Workspace (Grid Layout) -->
    <main class="flex-1 overflow-hidden p-4">
      <div v-if="activeView === 'dashboard'" class="h-full grid grid-cols-12 grid-rows-6 gap-4">
         <!-- Left Sidebar: Controls -->
         <aside class="col-span-3 row-span-6">
            <DynamicControlPanel v-if="profileConfig" />
            <div v-else class="h-full flex items-center justify-center bg-slate-900 rounded-lg shadow border border-slate-800 text-slate-500 text-center p-6">
               <span class="animate-pulse">Waiting for Profile Sync or Connection...</span>
            </div>
         </aside>
         <!-- Top Right: Live Plotting Area -->
         <section class="col-span-9 row-span-4">
            <PlotArea />
         </section>
         <!-- Bottom Right: Log Console -->
         <section class="col-span-9 row-span-2">
            <DataLogConsole />
         </section>
      </div>
      
      <div v-else-if="activeView === 'chipInfo'" class="h-full">
         <ChipInfoTab />
      </div>
    </main>

  </div>
</template>

<script setup>
import { onMounted, ref, provide, computed } from 'vue';
import { connectBackend, isConnected, profileConfig, sendCommand, isDeviceConnected, isStreaming, availablePorts, isFirmwareOperationActive } from './services/backend';
import DynamicControlPanel from './components/DynamicControlPanel.vue';
import PlotArea from './components/PlotArea.vue';
import DataLogConsole from './components/DataLogConsole.vue';
import ChipInfoTab from './components/ChipInfoTab.vue';

const appTitle = computed(() => profileConfig.value?.name || profileConfig.value?.meta?.name || 'ESP Viewer');
const activeView = ref('dashboard');
const selectedPort = ref('');
const selectedBaud = ref(2000000);

// Global Clear trigger
const clearTrigger = ref(0);
provide('clearTrigger', clearTrigger);

function clearData() {
    clearTrigger.value += 1;
}

function refreshPorts() {
    sendCommand('LIST_PORTS');
}

function toggleStream() {
    if (isStreaming.value) {
        sendCommand('STOP_STREAM');
    } else {
        clearData(); // Auto-clear old plots on a fresh stream
        sendCommand('START_STREAM');
    }
}

onMounted(() => {
    // Initiate WebSocket connection on app startup
    connectBackend();
});

function toggleConnection() {
    if (isDeviceConnected.value) {
        sendCommand('DISCONNECT');
    } else {
        clearData(); // Prevent stale data from squishing plots layout
        let port = selectedPort.value;
        if (port === 'SIMULATOR') {
            // Handle simulator mode by requesting a mock type if defined in profile
            const mockType = profileConfig.value?.meta?.mock_type || 'default';
            port = `mock://${mockType}`;
        }
        sendCommand('CONNECT', port ? { port: port, baud: selectedBaud.value } : { baud: selectedBaud.value });
    }
}
</script>

<style>
/* Global resets inside the main app layout are handled by Tailwind base */
</style>
