Vue.component('side-bar', {
  props: {
    type: {
      type: String,
      required: true,
      // 支持五个页面：模型 / 材料 / 门型 / 拉手 / 构件
      validator: (value) => ['model', 'material', 'door', 'handle', 'component'].includes(value)
    },
    // 保留 isOnline 以兼容旧调用，但不再在模板中展示切换按钮
    isOnline: {
      type: Boolean,
      required: true
    },
    selectedType: {
      type: String,
      default: null
    },
    folders: {
      type: Array,
      default: () => []
    },
    sortOrderFolders: {
      type: Number,
      default: 1
    },
    recentFolderPath: {
      type: String,
      default: null
    },
    selectedFolderPath: {
      type: String,
      default: null
    },
    /** 左侧点击锁定的一级根；与 selected 一并参与高亮判定（优先 selected） */
    treeRootPath: {
      type: String,
      default: ''
    }
  },

  computed: {
    inModelIcon() {
      return this.type === 'model' ? 'cube' : 'palette';
    },
    folderElementId() {
      const idMap = {
        model: 'modelFolders',
        material: 'materialFolders',
        door: 'doorFolders',
        handle: 'handleFolders',
        component: 'componentFolders'
      };
      return idMap[this.type] || 'modelFolders';
    },
    sortableListId() {
      const idMap = {
        model: 'sortableLocalModel',
        material: 'sortableLocalMaterial',
        door: 'sortableLocalDoor',
        handle: 'sortableLocalHandle',
        component: 'sortableLocalComponent'
      };
      return idMap[this.type] || 'sortableLocalModel';
    },
    inModelCountId() {
      const idMap = {
        model: 'modelInModel',
        material: 'materialInModel',
        door: 'doorInModel',
        handle: 'handleInModel',
        component: 'componentInModel'
      };
      return idMap[this.type] || 'modelInModel';
    },
    favoritesCountId() {
      const idMap = {
        model: 'allModelFavorites',
        material: 'allMaterialFavorites',
        door: 'allDoorFavorites',
        handle: 'allHandleFavorites',
        component: 'allComponentFavorites'
      };
      return idMap[this.type] || 'allModelFavorites';
    },
    recentCountId() {
      const idMap = {
        model: 'allModelRecent',
        material: 'allMaterialRecent',
        door: 'allDoorRecent',
        handle: 'allHandleRecent',
        component: 'allComponentRecent'
      };
      return idMap[this.type] || 'allModelRecent';
    },
    // Create a unique key based on folder paths order to force re-render when order changes
    foldersKey() {
      return this.folders.map(f => f.folderPath).join('|');
    }
  },

  mounted() {
    // Listen for focus input event from parent
    this.$root.$on('focus-folder-input', (folderPath) => {
      this.$nextTick(() => {
        // Find the index of the folder by folderPath
        const folderIndex = this.folders.findIndex(f => f.folderPath === folderPath);
        if (folderIndex !== -1) {
          const input = this.$refs['inputRef_' + folderIndex];
          if (input && input.length > 0) {
            input[0].focus();
            input[0].select();
          }
        }
      });
    });
  },

  beforeDestroy() {
    // Clean up event listener
    this.$root.$off('focus-folder-input');
  },

  methods: {
    translated(key) {
      return this.$root.translated(key);
    },

    normPath(p) {
      return (p || '').toString().replace(/\\/g, '/').replace(/\/+$/, '');
    },

    // 一级目录高亮：只跟随「一条」当前路径，避免 Ruby restore recent 与 JS 默认 browse 首库时
    // selectedFolderPath 与 recentFolderPath 指向不同根目录导致两个一级项同时 active。
    // 优先级：当前浏览路径 > 左侧树根 > 持久化的 recent。
    canonicalContextPath() {
      const s = this.normPath(this.selectedFolderPath);
      if (s) return s;
      const tr = this.normPath(this.treeRootPath);
      if (tr) return tr;
      return this.normPath(this.recentFolderPath);
    },

    // 一级目录是否应视为“选中”：上下文路径等于该根或在其子树内（路径段边界，避免 C:/a 匹配 C:/ab）
    isActiveFolder(folderPath) {
      const base = this.normPath(folderPath);
      const ctx = this.canonicalContextPath();
      if (!base || !ctx) return false;
      return ctx === base || ctx.startsWith(base + '/');
    },

    handleFolderContextMenu(event, folderInfo) {
      this.$emit('folder-context-menu', {
        event,
        folderPath: folderInfo.folderPath,
        folderName: folderInfo.customFolderName
      });
    },

    handleSeparatorContextMenu(event) {
      this.$emit('separator-context-menu', event);
    },

    handleInputClick() {
      this.$emit('hide-context-menu');
    },

    handleFolderEnter(folderInfo) {
      this.$emit('folder-enter', {
        folderPath: folderInfo.folderPath,
        folderName: folderInfo.customFolderName
      });
    },

    handleFolderBlur(folderInfo) {
      this.$emit('folder-blur', {
        folderPath: folderInfo.folderPath,
        folderName: folderInfo.customFolderName
      });
    },

    handleFolderEsc(folderInfo) {
      this.$emit('folder-esc', {
        folderPath: folderInfo.folderPath,
        folderName: folderInfo.customFolderName
      });
    }
  },

  template: /*html*/ `
    <div class="sidebar">
      <!-- Static Sidebar：本地/在线按钮已移除，默认始终使用本地功能，保留顶部间距 -->
      <div class="static-container p-2"></div>

      <!-- Add Collection：紧凑排列，避免撑大侧栏最小宽度 -->
      <div class="d-flex sidebar-actions-row mb-1">
        <button
          class="btn btn-icon-only btn-text-dark"
          data-toggle="tooltip"
          :title="translated('addCollection')"
          @click="$emit('add-collection')"
        >
          <i class="modus-icons">folder_new</i>
        </button>
      </div>

      <!-- Scroll Sidebar -->
      <div class="scroll-container pb-2 border-top px-2" :id="folderElementId">
        <ul class="list-group list-group-borderless mt-1" :id="sortableListId" :key="foldersKey">
          <li
            v-if="folderInfo.folderPath !== '|-----|'"
            v-for="(folderInfo, index) in folders"
            :key="folderInfo.folderPath"
            :data-folder-path="folderInfo.folderPath"
            class="list-group-item d-flex mt-1 px-2"
            :class="{ 'active': isActiveFolder(folderInfo.folderPath) }"
            @contextmenu.stop.prevent="handleFolderContextMenu($event, folderInfo)"
            @click="!folderInfo.isFolderEditing && $emit('browse-folder', folderInfo.folderPath, false)">

            <input
              v-if="folderInfo.isFolderEditing"
              v-model="folderInfo.newName"
              class="custom-form-control mr-2"
              type="text"
              @keydown.enter.stop="handleFolderEnter(folderInfo)"
              @keydown.esc.stop="handleFolderEsc(folderInfo)"
              @blur="handleFolderBlur(folderInfo)"
              @click.stop="handleInputClick"
              :ref="'inputRef_' + index"
            />

            <span v-else class="folder-name cursor-default">{{ folderInfo.customFolderName }}</span>

            <span class="text-primary ml-auto pl-2">
              {{ folderInfo.folderItems }}
            </span>
          </li>

          <!-- Separator Element -->
          <li
            v-else data-folder-path="|-----|"
            class="li-separator"
            @contextmenu.stop.prevent="handleSeparatorContextMenu($event)"
          >
            <div class="dropdown-divider custom-dropdown-divider"></div>
            <span class="folder-name"></span>
          </li>
        </ul>
      </div>
    </div>
  `,
});

