<template>
  <div class="app">
    <SidebarRail
      :nav-items="filteredNavItems"
      :active-view="activeView"
      :company-name="companyProfile.name"
      :current-user="currentUser"
      @navigate="handleNavigate"
      @open-chat="handleOpenChat"
      @logout="handleLogout"
    />

    <main
      class="main"
      :class="{
        'chat-main': activeView === 'chat',
        'overview-main': activeView === 'overview',
        'workbench-main': activeView === 'workbench',
        'requests-main': activeView === 'requests',
        'approval-main': activeView === 'approval',
        'policies-main': activeView === 'policies',
        'audit-main': activeView === 'audit',
        'audit-detail-main': activeView === 'audit' && auditDetailOpen,
        'employees-main': activeView === 'employees',
        'settings-main': activeView === 'settings'
      }"
    >
      <TopBar
        v-if="activeView !== 'settings' && !(activeView === 'audit' && auditDetailOpen)"
        :current-view="topBarView"
        :search="search"
        :active-view="activeView"
        :ranges="ranges"
        :active-range="activeRange"
        :employee-summary="employeeSummary"
        :knowledge-summary="knowledgeSummary"
        :request-summary="requestSummary"
        :custom-range="customRange"
        @update:search="search = $event"
        @update:active-range="activeRange = $event"
        @update:custom-range="customRange = $event"
        @batch-approve="toast('已批量通过 23 条审批任务。')"
        @open-chat="handleOpenChat"
        @new-application="openTravelCreate"
      />

      <FilterBar
        v-if="activeView !== 'chat' && activeView !== 'overview' && activeView !== 'workbench' && activeView !== 'requests' && activeView !== 'approval' && activeView !== 'policies' && activeView !== 'audit' && activeView !== 'employees' && activeView !== 'settings'"
        :compact="activeView === 'overview'"
        :filters="filters"
        :ranges="ranges"
        :active-range="activeRange"
        @update:active-range="activeRange = $event"
      />

      <section
        class="workarea"
        :class="{
          'chat-workarea': activeView === 'chat',
          'requests-workarea': activeView === 'requests',
          'approval-workarea': activeView === 'approval',
          'policies-workarea': activeView === 'policies',
          'audit-workarea': activeView === 'audit',
          'employees-workarea': activeView === 'employees',
          'settings-workarea': activeView === 'settings'
        }"
      >
        <OverviewView
          v-if="activeView === 'overview'"
          :filtered-requests="filteredRequests"
          @ask="handleOpenChat"
          @approve="handleApprove"
          @reject="handleReject"
        />

        <PersonalWorkbenchView
          v-else-if="activeView === 'workbench'"
          @open-assistant="openSmartEntry"
        />

        <ChatView
          v-else-if="activeView === 'chat'"
          :documents="filteredDocuments"
          :doc-search="docSearch"
          :messages="messages"
          :uploaded-files="uploadedFiles"
          :active-case="activeCase"
          :quick-prompts="travelPrompts"
          :draft="draft"
          :sending="sending"
          :message-list="messageList"
          @send="sendMessage"
          @upload="handleUpload"
          @draft="draft = $event"
          @select-case="handleOpenChat"
          @approve-case="toast(`${activeCase?.id || '当前单据'} 已标记为通过。`)"
          @reject-case="toast(`${activeCase?.id || '当前单据'} 已标记为驳回。`)"
        />

        <TravelRequestDetailView
          v-else-if="activeView === 'requests' && detailMode && selectedRequest"
          :request="selectedRequest"
          @back-to-requests="closeRequestDetail"
          @open-assistant="openSmartEntry"
          @request-updated="handleRequestUpdated"
          @request-deleted="handleRequestDeleted"
        />

        <RequestsView
          v-else-if="activeView === 'requests'"
          :filtered-requests="filteredRequests"
          :has-data="requests.length > 0"
          :loading="requestsLoading"
          :error="requestsError"
          @ask="openRequestDetail"
          @approve="handleApprove"
          @reject="handleReject"
          @reload="reloadRequests"
          @create-request="openTravelCreate"
        />

        <ApprovalCenterView v-else-if="activeView === 'approval'" />
        <PoliciesView v-else-if="activeView === 'policies'" @summary-change="knowledgeSummary = $event" />
        <AuditView v-else-if="activeView === 'audit'" @detail-open-change="auditDetailOpen = $event" />
        <EmployeeManagementView v-else-if="activeView === 'employees'" @overview-change="employeeSummary = $event" />
        <SettingsView v-else />
      </section>
    </main>

    <TravelReimbursementCreateView
      v-if="smartEntryOpen"
      :key="smartEntrySessionId"
      :initial-prompt="smartEntryContext.prompt"
      :initial-files="smartEntryContext.files"
      :initial-conversation="smartEntryContext.conversation"
      :entry-source="smartEntryContext.source"
      :request-context="smartEntryContext.request"
      @close="closeSmartEntry"
      @draft-saved="handleDraftSaved"
    />
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

import SidebarRail from '../components/layout/SidebarRail.vue'
import TopBar from '../components/layout/TopBar.vue'
import FilterBar from '../components/layout/FilterBar.vue'
import OverviewView from './OverviewView.vue'
import PersonalWorkbenchView from './PersonalWorkbenchView.vue'
import ChatView from './ChatView.vue'
import TravelReimbursementCreateView from './TravelReimbursementCreateView.vue'
import TravelRequestDetailView from './TravelRequestDetailView.vue'
import RequestsView from './RequestsView.vue'
import ApprovalCenterView from './ApprovalCenterView.vue'
import PoliciesView from './PoliciesView.vue'
import AuditView from './AuditView.vue'
import EmployeeManagementView from './EmployeeManagementView.vue'
import SettingsView from './SettingsView.vue'

import { useAppShell } from '../composables/useAppShell.js'
import { useSystemState } from '../composables/useSystemState.js'
import { filterNavItemsByAccess } from '../utils/accessControl.js'

const employeeSummary = ref(null)
const knowledgeSummary = ref(null)
const auditDetailOpen = ref(false)

const {
  activeCase,
  activeRange,
  activeView,
  closeRequestDetail,
  closeSmartEntry,
  customRange,
  detailMode,
  docSearch,
  draft,
  filteredDocuments,
  filteredRequests,
  filters,
  handleApprove,
  handleDraftSaved,
  handleNavigate,
  handleOpenChat,
  handleReject,
  handleRequestDeleted,
  handleRequestUpdated,
  handleUpload,
  messageList,
  messages,
  navItems,
  openRequestDetail,
  openSmartEntry,
  openTravelCreate,
  ranges,
  requestSummary,
  requestsError,
  requestsLoading,
  reloadRequests,
  requests,
  search,
  selectedRequest,
  sendMessage,
  sending,
  smartEntryContext,
  smartEntryOpen,
  smartEntrySessionId,
  toast,
  topBarView,
  travelPrompts,
  uploadedFiles
} = useAppShell()

const { companyProfile, currentUser, logout } = useSystemState()
const filteredNavItems = computed(() => filterNavItemsByAccess(navItems, currentUser.value))

function handleLogout() {
  logout('manual')
}
</script>
