<script setup>
  import { ref, provide, onMounted } from 'vue'
  import { useLayout } from './composables/useLayout'
  import { useToast } from 'primevue/usetoast'
  const toast = useToast()

  const { primaryColors, surfaces, primary, surface, isDarkMode, updateColors, toggleDarkMode } =
    useLayout()
  import MQTTService from './services/mqtt.js'

  import AppTopbar from './components/AppTopbar.vue'
  import AppFooter from './components/AppFooter.vue'
  import DevicesWidget from './components/dashboard/DevicesWidget.vue'
  import PropertiesWidget from './components/dashboard/PropertiesWidget.vue'
  import CommandsWidget from './components/dashboard/CommandsWidget.vue'

  const mqtt = ref(null)
  const loggedIn = ref(false)
  const selectedDevice = ref(null)

  function handleLogin({ username, password }) {
    // Create the shared MQTT client
    mqtt.value = new MQTTService('wss://dmc.jonotargett.com:443/mqtt', username, password)
    loggedIn.value = true
  }

  onMounted(() => {
    if(isDarkMode !== false) toggleDarkMode()
  })

  provide('mqtt', mqtt)
</script>

<template>
  <Toast position="bottom-right" />

  <div id="app">
    <SplashPage v-if="!loggedIn" @login="handleLogin" />
    <div v-else class="layout-container">
      <AppTopbar />
      <div class="layout-grid">
        <DevicesWidget @select="selectedDevice = $event" />
        <div v-if="selectedDevice" class="layout-grid-row">
          <PropertiesWidget
            v-if="selectedDevice"
            :key="'props-' + selectedDevice"
            :device-id="selectedDevice"
          />
          <CommandsWidget
            v-if="selectedDevice"
            :key="'cmds-' + selectedDevice"
            :device-id="selectedDevice"
          />
        </div>
      </div>
      <AppFooter />
    </div>
  </div>
</template>
