<template>
  <div class="agent-layout">
    <!-- AI Agent 独立对话布局：/agent/chat 与 /agent/preview -->
    <template v-if="isChatLayout">
      <TopNav />
      <div class="agent-layout__chat-body">
        <ChatSidebar
          :conversations="chatStore.conversations"
          :current-id="chatStore.currentConversationId"
          @create="chatStore.createConversation"
          @select="chatStore.selectConversation"
          @delete="chatStore.deleteConversation"
        />
        <div class="agent-layout__chat-main">
          <router-view />
        </div>
        <RightPanel />
      </div>
    </template>

    <!-- 传统工作台布局：代码、监控等 -->
    <template v-else>
      <TitleBar />
      <TopNav :icon-nav-collapsed="iconNavCollapsed" @toggle-icon-nav="iconNavCollapsed = !iconNavCollapsed" />
      <div class="agent-layout__body">
        <IconNav
          :collapsed="iconNavCollapsed"
          @navigate="handleIconNav"
        />
        <SplitPane
          direction="horizontal"
          :default-ratio="0.55"
          storage-key="agent-h-split"
        >
          <template #first>
            <router-view />
          </template>
          <template #second>
            <SplitPane
              direction="vertical"
              :default-ratio="0.6"
              storage-key="agent-right-v-split"
            >
              <template #first>
                <QuadrantPanel
                  ref="trPanel"
                  :tabs="topRightTabs"
                  default-tab="code"
                  storage-key="quadrant-tr-tab"
                >
                  <template #code>
                    <div class="agent-layout__placeholder">
                      <FileTextOutlined style="font-size: 32px; color: var(--text-placeholder)" />
                      <p>代码预览</p>
                    </div>
                  </template>
                  <template #workflow>
                    <WorkflowView />
                  </template>
                  <template #knowledge>
                    <KnowledgeBaseView />
                  </template>
                </QuadrantPanel>
              </template>
              <template #second>
                <QuadrantPanel
                  ref="brPanel"
                  :tabs="bottomRightTabs"
                  default-tab="monitor"
                  storage-key="quadrant-br-tab"
                >
                  <template #monitor>
                    <EvolutionView />
                  </template>
                  <template #skills>
                    <SkillsView />
                  </template>
                  <template #calendar>
                    <CalendarTab />
                  </template>
                  <template #settings>
                    <SettingsView />
                  </template>
                </QuadrantPanel>
              </template>
            </SplitPane>
          </template>
        </SplitPane>
      </div>
    </template>

    <div class="agent-layout__small-screen">
      <DesktopOutlined style="font-size: 48px; color: var(--text-placeholder)" />
      <h2>请使用更大的屏幕</h2>
      <p>Fischer AgentKit 布局需要至少 1024px 宽度的屏幕才能正常使用。</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineAsyncComponent, computed, type Component } from 'vue'
import { useRoute } from 'vue-router'
import {
  FileTextOutlined,
  ApartmentOutlined,
  BookOutlined,
  DashboardOutlined,
  AppstoreOutlined,
  SettingOutlined,
  DesktopOutlined,
  CalendarOutlined,
} from '@ant-design/icons-vue'
import { useChatStore } from '@/stores/chat'
import TopNav from './TopNav.vue'
import TitleBar from './TitleBar.vue'
import SplitPane from './SplitPane.vue'
import QuadrantPanel from './QuadrantPanel.vue'
import IconNav from './IconNav.vue'
import RightPanel from './RightPanel.vue'
import ChatSidebar from '@/components/chat/ChatSidebar.vue'
import type { QuadrantTab } from './QuadrantPanel.vue'

// Lazy-load views to avoid bundling all into initial chunk
const WorkflowView = defineAsyncComponent(() => import('@/views/WorkflowView.vue'))
const KnowledgeBaseView = defineAsyncComponent(() => import('@/views/KnowledgeBaseView.vue'))
const EvolutionView = defineAsyncComponent(() => import('@/views/EvolutionView.vue'))
const SkillsView = defineAsyncComponent(() => import('@/views/SkillsView.vue'))
const SettingsView = defineAsyncComponent(() => import('@/views/SettingsView.vue'))
const CalendarTab = defineAsyncComponent(() => import('./tabs/CalendarTab.vue'))

const route = useRoute()
const chatStore = useChatStore()

const isChatLayout = computed(() => {
  return route.name === 'agent-chat' || route.name === 'agent-preview'
})

// IconNav state
const iconNavCollapsed = ref(localStorage.getItem('icon-nav-collapsed') === 'true')
watch(iconNavCollapsed, (val) => {
  localStorage.setItem('icon-nav-collapsed', String(val))
})

function handleIconNav(panel: string, tab?: string) {
  if (panel === 'chat') return // ChatView is always visible
  const panelRef = panel === 'tr' ? trPanel : brPanel
  if (tab && panelRef.value) {
    panelRef.value.setActiveTab(tab)
  }
}

const topRightTabs: QuadrantTab[] = [
  { key: 'code', label: '代码', icon: FileTextOutlined as Component },
  { key: 'workflow', label: '工作流', icon: ApartmentOutlined as Component },
  { key: 'knowledge', label: '知识库', icon: BookOutlined as Component },
]

const bottomRightTabs: QuadrantTab[] = [
  { key: 'monitor', label: '监控', icon: DashboardOutlined as Component },
  { key: 'skills', label: '技能', icon: AppstoreOutlined as Component },
  { key: 'calendar', label: '日历', icon: CalendarOutlined as Component },
  { key: 'settings', label: '设置', icon: SettingOutlined as Component },
]

// Quadrant refs for route-driven tab switching
const trPanel = ref<InstanceType<typeof QuadrantPanel> | null>(null)
const brPanel = ref<InstanceType<typeof QuadrantPanel> | null>(null)

// Watch route changes to sync quadrant tabs with URL
watch(() => route.meta, (meta) => {
  const panel = meta.panel as string | undefined
  const tab = meta.tab as string | undefined
  if (panel && tab) {
    const panelMap: Record<string, typeof trPanel> = {
      tr: trPanel,
      br: brPanel,
    }
    const panelRef = panelMap[panel]
    if (panelRef?.value) {
      panelRef.value.setActiveTab(tab)
    }
  }
}, { immediate: true })
</script>

<style scoped>
.agent-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: var(--bg-tertiary);
}

.agent-layout__body {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 0;
  gap: 0;
}

.agent-layout__chat-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  background: var(--bg-primary);
}

.agent-layout__chat-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--bg-primary);
}

.agent-layout__placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: var(--space-3);
  color: var(--text-placeholder);
  font-size: var(--font-sm);
}
</style>
