<template>
  <div class="app">
    <TopBar :products="products" :active-sku="activeSku" @select="selectProduct" />
    <div class="app-body">
      <Sidebar :active-sku="activeSku" :active-view="activeView" />
      <div class="main">
        <ProductHeader v-if="activeProduct" :product="activeProduct" />
        <div class="content">
          <router-view :key="activeSku" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import TopBar from './components/layout/TopBar.vue'
import Sidebar from './components/layout/Sidebar.vue'
import ProductHeader from './components/layout/ProductHeader.vue'
const route = useRoute()
const router = useRouter()
const products = ref([])
const activeSku = ref(null)
const activeProduct = computed(() => products.value.find(p => p.sku === activeSku.value) || null)
const activeView = computed(() => route.path.split('/').pop() || '')
onMounted(async () => {
  try {
    const res = await fetch('/api/products')
    products.value = await res.json()
    const first = products.value.find(p => p.hasIntelligence) || products.value[0]
    if (first && !activeSku.value) selectProduct(first.sku)
  } catch (e) {
    console.error('Failed to load products', e)
  }
})
watch(() => route.params.sku, sku => { if (sku) activeSku.value = sku })
function selectProduct(sku) {
  activeSku.value = sku
  const view = activeView.value && activeView.value !== 'catalog' ? activeView.value : 'research-profile'
  router.push(`/product/${sku}/${view}`)
}
</script>
<style>
.app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background: var(--bg);
}
.app-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.content {
  flex: 1;
  overflow-y: auto;
  background: var(--bg);
}
</style>
