<template>
  <aside class="sidebar left-sidebar" :style="panelStyle">
    <div class="sidebar-status">
      <div class="compact-status-card">
        <div class="status-line">
          <div class="status-brand">
            <span
              class="status-logo-image status-logo-inline"
              v-html="statusLogoSvg"
              aria-hidden="true"
            ></span>
            <div class="brand-text">
              <span class="brand-name">Astrion</span>
              <span class="agent-version" v-if="agentVersion">{{ agentVersion }}</span>
            </div>
          </div>
          <div class="status-indicators">
            <button
              type="button"
              class="mode-indicator"
              data-tutorial="run-mode-indicator"
              :class="modeIndicatorClass"
              :title="modeIndicatorTitle"
              @click="$emit('toggle-thinking-mode')"
            >
              <transition name="mode-icon" mode="out-in">
                <span
                  class="icon icon-sm"
                  :style="iconStyle(modeIndicatorIcon)"
                  :key="modeIndicatorIcon"
                  aria-hidden="true"
                ></span>
              </transition>
            </button>
            <span
              class="connection-dot"
              data-tutorial="connection-indicator"
              :class="{ active: isConnected }"
              :title="isConnected ? '已连接' : '未连接'"
            ></span>
          </div>
        </div>
      </div>
    </div>
    <div class="sidebar-panel-card-wrapper">
      <div class="sidebar-panel-card">
        <div class="sidebar-header">
          <div class="panel-menu-wrapper" ref="panelMenuWrapper">
            <button
              class="sidebar-view-toggle"
              data-tutorial="panel-menu-toggle"
              @click.stop="$emit('toggle-panel-menu')"
              title="切换侧边栏"
            >
              <span class="icon icon-md" :style="iconStyle('menu')" aria-hidden="true"></span>
            </button>
            <transition name="fade">
              <div class="panel-menu" data-tutorial="panel-menu" v-if="panelMenuOpen">
                <button
                  type="button"
                  :class="{ active: panelMode === 'files' }"
                  @click.stop="$emit('select-panel', 'files')"
                  :title="workspaceKind === 'project' ? '项目' : '项目文件'"
                >
                  <span class="icon icon-md" :style="iconStyle('folder')" aria-hidden="true"></span>
                </button>
                <button
                  type="button"
                  :class="{ active: panelMode === 'todo' }"
                  @click.stop="$emit('select-panel', 'todo')"
                  title="待办列表"
                >
                  <span
                    class="icon icon-md"
                    :style="iconStyle('stickyNote')"
                    aria-hidden="true"
                  ></span>
                </button>
                <button
                  type="button"
                  :class="{ active: panelMode === 'subAgents' }"
                  @click.stop="$emit('select-panel', 'subAgents')"
                  title="子智能体"
                >
                  <span class="icon icon-md" :style="iconStyle('bot')" aria-hidden="true"></span>
                </button>
                <button
                  type="button"
                  :class="{ active: panelMode === 'backgroundCommands' }"
                  @click.stop="$emit('select-panel', 'backgroundCommands')"
                  title="后台指令"
                >
                  <span
                    class="icon icon-md"
                    :style="iconStyle('terminal')"
                    aria-hidden="true"
                  ></span>
                </button>
                <button
                  v-if="panelMode === 'backgroundCommands' && runningBackgroundCommandCount > 0"
                  type="button"
                  class="background-stop-btn"
                  title="终止所有后台指令"
                  @click.stop="handleStopAllCommands"
                >
                  <span class="icon icon-sm" :style="iconStyle('stop')" aria-hidden="true"></span>
                  <span class="background-stop-label">停止</span>
                </button>
              </div>
            </transition>
          </div>
          <button
            class="sidebar-manage-btn"
            @click="$emit('open-file-manager')"
            :title="fileManagerDisabled ? '已被管理员禁用' : '打开桌面式文件管理器'"
          >
            管理
          </button>
          <h3>
              <span v-if="panelMode === 'files'" class="icon-label">
                <span class="icon icon-sm" :style="iconStyle('folder')" aria-hidden="true"></span>
              <span>{{ workspaceKind === 'project' ? '项目' : '项目文件' }}</span>
            </span>
            <span v-else-if="panelMode === 'todo'" class="icon-label">
              <span class="icon icon-sm" :style="iconStyle('stickyNote')" aria-hidden="true"></span>
              <span>待办列表</span>
            </span>
            <span v-else class="icon-label">
              <template v-if="panelMode === 'subAgents'">
                <span class="icon icon-sm" :style="iconStyle('bot')" aria-hidden="true"></span>
                <span>子智能体</span>
              </template>
              <template v-else>
                <span class="icon icon-sm" :style="iconStyle('terminal')" aria-hidden="true"></span>
                <span>后台指令</span>
              </template>
            </span>
          </h3>
        </div>
        <div class="sidebar-panel-content">
          <div v-if="panelMode === 'todo'" class="todo-panel">
            <div v-if="!todoList" class="todo-empty">暂无待办列表</div>
            <div v-else>
              <div
                class="todo-task"
                v-for="task in todoList.tasks || []"
                :key="task.index"
                :class="{ done: task.status === 'done' }"
              >
                <span class="todo-task-title">task{{ task.index }}：{{ task.title }}</span>
                <span class="todo-task-status icon-label">
                  <span
                    class="icon icon-sm"
                    :style="iconStyle(task.status === 'done' ? 'check' : 'checkbox')"
                    aria-hidden="true"
                  ></span>
                  <span>{{ task.status === 'done' ? '完成' : '未完成' }}</span>
                </span>
              </div>
              <div class="todo-instruction">{{ todoList.instruction }}</div>
            </div>
          </div>
          <div v-else-if="panelMode === 'subAgents'" class="sub-agent-panel">
            <div v-if="!subAgents.length" class="sub-agent-empty">暂无运行中的子智能体</div>
            <div v-else class="sub-agent-cards">
              <div
                class="sub-agent-card"
                v-for="agent in subAgents"
                :key="agent.task_id"
                @click="openSubAgent(agent)"
              >
                <div class="sub-agent-header">
                  <span class="sub-agent-summary-text">{{ agent.summary || agent.display_name || `#${agent.agent_id}` }}</span>
                  <span class="sub-agent-status" :class="agent.status">{{ agent.status }}</span>
                </div>
                <div class="sub-agent-meta">
                  <span class="sub-agent-name" v-if="agent.display_name">{{ agent.display_name }}</span>
                  <span class="sub-agent-tokens" v-if="agent.current_context_tokens">{{ formatTokens(agent.current_context_tokens) }}</span>
                </div>
                <div class="sub-agent-tool" v-if="agent.last_tool">当前：{{ agent.last_tool }}</div>
              </div>
            </div>
          </div>
          <div v-else-if="panelMode === 'backgroundCommands'" class="sub-agent-panel">
            <div v-if="!backgroundCommands.length" class="sub-agent-empty">暂无后台指令</div>
            <div v-else class="sub-agent-cards">
              <div
                class="sub-agent-card"
                v-for="command in backgroundCommands"
                :key="command.command_id"
                @click="openBackgroundCommand(command)"
              >
                <div class="sub-agent-header">
                  <span class="sub-agent-id">状态</span>
                  <span class="sub-agent-status" :class="command.status">{{
                    formatBackgroundCommandStatus(command.status)
                  }}</span>
                </div>
                <div class="sub-agent-summary background-command-summary">
                  {{ formatBackgroundCommandPreview(command.command) }}
                </div>
                <div class="sub-agent-tool">
                  {{ formatBackgroundCommandMeta(command) }}
                </div>
              </div>
            </div>
          </div>
          <div v-else class="file-tree" @contextmenu.prevent>
            <template v-if="fileTreeUnavailable">
              <div v-if="hostWorkspaceEnabled" class="host-workspace-section">
                <div class="host-workspace-header-box">
                  <button
                    type="button"
                    class="host-workspace-add-btn"
                    :disabled="hostWorkspaceSwitching"
                    @click="handleManageHostWorkspace"
                    :title="workspaceKind === 'project' ? '管理项目' : '管理工作区'"
                  >
                    <span class="icon icon-sm" :style="iconStyle('settings')" aria-hidden="true"></span>
                  </button>
                  <div class="host-workspace-title">
                    {{ workspaceKind === 'project' ? '管理项目' : '管理工作区' }}
                  </div>
                </div>
                <div class="host-workspace-list" v-if="hostWorkspaceOptions.length">
                  <button
                    v-for="item in hostWorkspaceOptions"
                    :key="item.workspace_id"
                    type="button"
                    class="host-workspace-card"
                    :class="{ active: item.workspace_id === hostWorkspaceId }"
                    :disabled="hostWorkspaceSwitching || item.workspace_id === hostWorkspaceId"
                    @click="handleHostWorkspaceClick(item.workspace_id)"
                  >
                    <div class="host-workspace-card-head">
                      <span class="host-workspace-label">{{ item.label }}</span>
                      <span class="host-workspace-badges">
                        <span
                          v-if="item.workspace_id === hostWorkspaceDefaultId"
                          class="host-workspace-badge default"
                        >
                          默认
                        </span>
                        <span
                          v-if="Number(item.running_task_count || 0) > 0"
                          class="host-workspace-badge running"
                        >
                          运行中
                        </span>
                      </span>
                    </div>
                    <div v-if="workspaceKind !== 'project'" class="host-workspace-path">
                      {{ item.path || (workspaceKind === 'project' ? '项目文件' : '（未配置路径）') }}
                    </div>
                  </button>
                </div>
                <div v-else class="file-tree-empty">
                  {{ workspaceKind === 'project' ? '暂无项目，点击齿轮管理' : '暂无工作区，点击齿轮管理' }}
                </div>
                <div class="host-workspace-hint" v-if="hostWorkspaceSwitching">
                  正在切换，请稍候…
                </div>
              </div>
              <div v-else class="file-tree-empty">{{ fileTreeMessage }}</div>
            </template>
            <template v-else>
              <div v-if="!fileTree.length" class="file-tree-empty">暂无文件</div>
              <FileNode
                v-for="node in fileTree"
                :key="node.path"
                :node="node"
                :level="0"
                :expanded-folders="expandedFolders"
                :icon-style="iconStyle"
              />
            </template>
          </div>
        </div>
      </div>
    </div>
  </aside>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { storeToRefs } from 'pinia';
import FileNode from '@/components/files/FileNode.vue';
import { useFileStore } from '@/stores/file';
import { useSubAgentStore } from '@/stores/subAgent';
import { useBackgroundCommandStore } from '@/stores/backgroundCommand';
import statusLogoSvgRaw from '../../../logo/logo.svg?raw';

defineOptions({ name: 'LeftPanel' });

const props = defineProps<{
  width: number;
  collapsed?: boolean;
  iconStyle: (key: string) => Record<string, string>;
  agentVersion: string | null;
  thinkingMode: boolean;
  isConnected: boolean;
  panelMenuOpen: boolean;
  panelMode: 'files' | 'todo' | 'subAgents' | 'backgroundCommands';
  runMode: 'fast' | 'thinking' | 'deep';
  fileManagerDisabled?: boolean;
  hostWorkspaceEnabled?: boolean;
  hostWorkspaces?: Array<{
    workspace_id: string;
    label: string;
    path?: string;
    is_current?: boolean;
    running_task_count?: number;
  }>;
  hostWorkspaceId?: string;
  hostWorkspaceDefaultId?: string;
  hostWorkspaceSwitching?: boolean;
  workspaceKind?: 'workspace' | 'project';
}>();

const emits = defineEmits<{
  (event: 'toggle-panel-menu'): void;
  (event: 'select-panel', mode: 'files' | 'todo' | 'subAgents' | 'backgroundCommands'): void;
  (event: 'open-file-manager'): void;
  (event: 'toggle-thinking-mode'): void;
  (event: 'switch-host-workspace', workspaceId: string): void;
  (event: 'create-host-workspace'): void;
  (event: 'manage-host-workspace'): void;
}>();

const panelMenuWrapper = ref<HTMLElement | null>(null);
const statusLogoSvg = statusLogoSvgRaw.replace(/fill="#000000"/g, 'fill="currentColor"');
const workspaceKind = computed(() => props.workspaceKind || 'workspace');
const panelStyle = computed(() => {
  const px = `${props.width}px`;
  const layoutWidth = props.collapsed ? '0px' : px;
  return {
    '--workspace-content-width': px,
    width: layoutWidth,
    minWidth: layoutWidth
  };
});

const resolveRunMode = () => {
  if (props.runMode === 'deep' || props.runMode === 'thinking' || props.runMode === 'fast') {
    return props.runMode;
  }
  return props.thinkingMode ? 'thinking' : 'fast';
};

const modeIndicatorClass = computed(() => {
  const mode = resolveRunMode();
  if (mode === 'deep') {
    return 'deep';
  }
  if (mode === 'thinking') {
    return 'thinking';
  }
  return 'fast';
});

const modeIndicatorIcon = computed(() => {
  const mode = resolveRunMode();
  if (mode === 'deep') {
    return 'brainCog';
  }
  if (mode === 'thinking') {
    return 'brain';
  }
  return 'zap';
});

const modeIndicatorTitle = computed(() => {
  const mode = resolveRunMode();
  if (mode === 'deep') {
    return '深度思考模式（点击切换）';
  }
  if (mode === 'thinking') {
    return '思考模式（点击切换）';
  }
  return '快速模式（点击切换）';
});
const fileStore = useFileStore();
const subAgentStore = useSubAgentStore();
const backgroundCommandStore = useBackgroundCommandStore();
const { fileTree, expandedFolders, todoList, fileTreeUnavailable, fileTreeMessage } =
  storeToRefs(fileStore);
const { subAgents } = storeToRefs(subAgentStore);
const { commands: backgroundCommands } = storeToRefs(backgroundCommandStore);

const hostWorkspaceOptions = computed(() => {
  const list = Array.isArray(props.hostWorkspaces) ? props.hostWorkspaces : [];
  return list.filter((item) => item && item.workspace_id);
});

const handleHostWorkspaceClick = (workspaceId: string) => {
  const targetId = String(workspaceId || '').trim();
  if (!targetId || targetId === props.hostWorkspaceId) {
    return;
  }
  if (props.hostWorkspaceSwitching) {
    return;
  }
  emits('switch-host-workspace', targetId);
};

const handleCreateHostWorkspace = () => {
  if (props.hostWorkspaceSwitching) {
    return;
  }
  emits('create-host-workspace');
};

const handleManageHostWorkspace = () => {
  if (props.hostWorkspaceSwitching) {
    return;
  }
  emits('manage-host-workspace');
};

const openSubAgent = (agent: any) => {
  subAgentStore.openSubAgent(agent);
};

const openBackgroundCommand = (command: any) => {
  backgroundCommandStore.openCommand(command);
};

const BG_COMMAND_TERMINAL = new Set(['completed', 'failed', 'timeout', 'cancelled']);
const runningBackgroundCommandCount = computed(() => {
  return (backgroundCommands.value || []).filter((c: any) => {
    const s = String(c?.status || '').toLowerCase();
    return !BG_COMMAND_TERMINAL.has(s);
  }).length;
});
const handleStopAllCommands = async () => {
  const result = await backgroundCommandStore.stopAllCommands();
  if (!result.success) {
    console.error('[LeftPanel] 批量停止后台指令失败:', result.error);
  }
};

const formatBackgroundCommandMeta = (command: any) => {
  const code = command?.return_code;
  if (code === null || code === undefined) {
    return '状态码：--';
  }
  return `状态码：${code}`;
};

const formatBackgroundCommandStatus = (status: any) => {
  const normalized = (status || 'running').toString().toLowerCase();
  return normalized;
};

const formatBackgroundCommandPreview = (rawCommand: any) => {
  const content = (rawCommand || '（空命令）').toString().replace(/\s+/g, ' ').trim();
  if (!content) {
    return '（空命令）';
  }
  return content;
};

const formatTokens = (tokens: number) => {
  if (!tokens || tokens <= 0) return '';
  if (tokens >= 1000) {
    return `${(tokens / 1000).toFixed(1)}k ctx`;
  }
  return `${tokens} ctx`;
};

defineExpose({
  panelMenuWrapper
});
</script>
