<template>
  <AdminLayout :currentPage="currentView" @navigate="onNavigate">
    <keep-alive :include="keepAliveViews">
      <component :is="currentComponent" :key="viewKey" v-bind="viewProps" @navigate="onNavigate" />
    </keep-alive>
  </AdminLayout>
</template>

<script>
import AdminLayout from '../../components/AdminLayout.vue'
import DashboardView from '../../views/DashboardView.vue'
import DeviceListView from '../../views/DeviceListView.vue'
import DeviceDetailView from '../../views/DeviceDetailView.vue'
import UserListView from '../../views/UserListView.vue'
import UserDetailView from '../../views/UserDetailView.vue'
import SubscriptionView from '../../views/SubscriptionView.vue'
import RecordView from '../../views/RecordView.vue'
import LogView from '../../views/LogView.vue'
import SettingsView from '../../views/SettingsView.vue'

var VIEW_MAP = {
  dashboard: DashboardView,
  device: DeviceListView,
  'device-detail': DeviceDetailView,
  user: UserListView,
  'user-detail': UserDetailView,
  subscription: SubscriptionView,
  record: RecordView,
  log: LogView,
  settings: SettingsView
}

// List views that should be kept alive (preserve state when navigating to detail and back)
var KEEP_ALIVE_VIEWS = ['DeviceListView', 'UserListView', 'SubscriptionView', 'RecordView', 'LogView']

export default {
  components: {
    AdminLayout,
    DashboardView,
    DeviceListView,
    DeviceDetailView,
    UserListView,
    UserDetailView,
    SubscriptionView,
    RecordView,
    LogView,
    SettingsView
  },
  data() {
    return {
      currentView: 'dashboard',
      viewProps: {},
      keepAliveViews: KEEP_ALIVE_VIEWS
    }
  },
  computed: {
    currentComponent() {
      return VIEW_MAP[this.currentView] || DashboardView
    },
    viewKey() {
      // Detail views get a unique key so they always re-mount with fresh data
      if (this.currentView === 'device-detail') {
        return 'device-detail-' + (this.viewProps.device_id || '')
      }
      if (this.currentView === 'user-detail') {
        return 'user-detail-' + (this.viewProps.user_id || '')
      }
      return this.currentView
    }
  },
  methods: {
    onNavigate(view, props) {
      this.currentView = view
      this.viewProps = props || {}
    }
  }
}
</script>
