<template>
  <div class="app" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
    <div class="app-sidebar">
      <SidebarRail
        :nav-items="filteredNavItems"
        :active-view="activeView"
        :company-name="companyProfile.name"
        :company-logo="companyProfile.logo"
        :current-user="currentUser"
        :collapsed="sidebarCollapsed"
        @navigate="handleNavigate"
        @open-chat="openSmartEntry"
        @logout="handleLogout"
        @toggle-collapse="toggleSidebarCollapsed"
      />
    </div>

    <main
      class="main"
      :class="{
        'overview-main': activeView === 'overview',
        'workbench-main': activeView === 'workbench',
        'documents-main': activeView === 'documents',
        'requests-main': activeView === 'requests',
        'approval-main': activeView === 'approval',
        'archive-main': activeView === 'archive',
        'policies-main': activeView === 'policies',
        'audit-main': activeView === 'audit',
        'audit-detail-main': activeView === 'audit' && auditDetailOpen,
        'logs-main': activeView === 'logs',
        '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"
        :logs-summary="logsSummary"
        :request-summary="requestSummary"
        :document-summary="documentSummary"
        :workbench-summary="workbenchSummary"
        :detail-mode="detailMode"
        :log-detail-mode="logDetailMode"
        :detail-alerts="detailAlerts"
        :custom-range="customRange"
        @update:search="search = $event"
        @update:active-range="activeRange = $event"
        @update:custom-range="customRange = $event"
        @batch-approve="toast('已批量通过 23 条审批任务。')"
        @new-application="openExpenseApplicationCreate"
      />

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

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

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

        <TravelRequestDetailView
          v-else-if="['requests', 'documents'].includes(activeView) && detailMode && selectedRequest"
          :request="selectedRequest"
          :back-label="activeView === 'documents' ? '返回单据中心' : '返回报销列表'"
          @back-to-requests="closeRequestDetail"
          @open-assistant="openSmartEntry"
          @request-updated="handleRequestUpdated"
          @request-deleted="handleRequestDeleted"
        />

        <DocumentsCenterView
          v-else-if="activeView === 'documents'"
          :filtered-requests="filteredRequests"
          :has-data="requests.length > 0"
          :loading="requestsLoading"
          :error="requestsError"
          @open-document="openRequestDetail"
          @create-request="openTravelCreate"
          @create-application="openExpenseApplicationCreate"
          @reload="reloadRequests"
          @summary-change="documentSummary = $event"
        />

        <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'" />
        <ArchiveCenterView v-else-if="activeView === 'archive'" />
        <PoliciesView v-else-if="activeView === 'policies'" @summary-change="knowledgeSummary = $event" />
        <AuditView v-else-if="activeView === 'audit'" @detail-open-change="auditDetailOpen = $event" />
        <LogDetailView v-else-if="activeView === 'logs' && logDetailMode" />
        <LogsView v-else-if="activeView === 'logs'" @summary-change="logsSummary = $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"
      :invalidated-draft-claim-id="smartEntryInvalidatedDraftClaimId"
      @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 TravelReimbursementCreateView from './TravelReimbursementCreateView.vue'
import TravelRequestDetailView from './TravelRequestDetailView.vue'
import DocumentsCenterView from './DocumentsCenterView.vue'
import RequestsView from './RequestsView.vue'
import ApprovalCenterView from './ApprovalCenterView.vue'
import ArchiveCenterView from './ArchiveCenterView.vue'
import PoliciesView from './PoliciesView.vue'
import AuditView from './AuditView.vue'
import LogsView from './LogsView.vue'
import LogDetailView from './LogDetailView.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 logsSummary = ref(null)
const documentSummary = ref(null)
const auditDetailOpen = ref(false)
const sidebarCollapsed = ref(true)

function toggleSidebarCollapsed() {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const {
  activeRange,
  activeView,
  closeRequestDetail,
  closeSmartEntry,
  customRange,
  detailAlerts,
  detailMode,
  logDetailMode,
  filteredRequests,
  filters,
  handleApprove,
  handleDraftSaved,
  handleNavigate,
  handleReject,
  handleRequestDeleted,
  handleRequestUpdated,
  navItems,
  openExpenseApplicationCreate,
  openRequestDetail,
  openSmartEntry,
  openTravelCreate,
  ranges,
  requestSummary,
  workbenchSummary,
  requestsError,
  requestsLoading,
  reloadRequests,
  requests,
  search,
  selectedRequest,
  smartEntryContext,
  smartEntryInvalidatedDraftClaimId,
  smartEntryOpen,
  smartEntrySessionId,
  toast,
  topBarView
} = useAppShell()

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

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