/**
 * Local Panel Component
 * Control panel for local container (search, filters, view options)
 * Shared between Model and Material tabs
 */
Vue.component('local-panel', {
  props: {
    type: {
      type: String,
      required: true,
      validator: function(value) {
        return ['model', 'material', 'door', 'handle', 'component'].indexOf(value) !== -1;
      }
    },
    // Navigation
    sidebarOpen: Boolean,
    isSmallWindow: Boolean,
    selectedType: String,
    isDrive: Boolean,
    activeModel: Boolean,
    showShowEditMaterial: Boolean,

    // Show All (Model only)
    showAllModels: Boolean,

    // View controls
    isMediumWindow: Boolean,
    viewMode: String,
    showDetails: Boolean,
    currentView: Object,
    selectedSort: String,
    activeFolderPath: {
      type: String,
      default: ''
    },

    // 当前选中目录路径（上一级按钮旁显示）
    selectedFolderPath: {
      type: String,
      default: ''
    },
    // 左侧文件目录列表当前选中的根目录（路径只显示此目录以下的相对部分）
    treeRootPath: {
      type: String,
      default: ''
    }
  },

  computed: {
    controlPanelId() {
      const suffixMap = {
        model: 'Model',
        material: 'Material',
        door: 'Door',
        handle: 'Handle',
        component: 'Component'
      };
      return `controlPanel${suffixMap[this.type] || 'Panel'}`;
    },

    detailSwitchId() {
      const suffixMap = {
        model: 'Model',
        material: 'Material',
        door: 'Door',
        handle: 'Handle',
        component: 'Component'
      };
      return `detailSwitch${suffixMap[this.type] || 'Panel'}`;
    },

    isParentDisabled() {
      const isActive = this.type === 'model' && this.activeModel;
      return (this.isDrive && this.selectedType !== 'in-model') ||
             (isActive && this.selectedType === 'in-model') ||
             this.selectedType === 'favorites' ||
             this.selectedType === 'recent';
    },

    shouldShowUpButton() {
      return !(this.sidebarOpen && this.isSmallWindow) && !this.showShowEditMaterial;
    },

    sortOptions() {
      return [
        { value: 'nameA', text: 'nameA' },
        { value: 'nameZ', text: 'nameZ' },
        { value: 'sizeMin', text: 'sizeMin' },
        { value: 'sizeMax', text: 'sizeMax' }
      ];
    },

    shouldShowAddSelectedButton() {
      return !(this.sidebarOpen && this.isMediumWindow) &&
             this.selectedType !== 'in-model' &&
             this.selectedType !== 'favorites' &&
             this.selectedType !== 'recent';
    },

    /** 路径拆成面包屑：从一级目录到当前目录都显示，二三级选中时显示 一级/二级/三级 */
    pathBreadcrumbs() {
      const selected = (this.selectedFolderPath || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
      const root = (this.treeRootPath || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
      if (!selected) return [];
      if (!root) return [];
      const rootNorm = root.toLowerCase ? root.toLowerCase() : root;
      const selectedNorm = selected.toLowerCase ? selected.toLowerCase() : selected;
      if (!selectedNorm.startsWith(rootNorm)) return [];
      if (selectedNorm === rootNorm) return [];
      const rel = selected.slice(root.length).replace(/^\/+/, '');
      if (!rel) return [];
      const parts = rel.split('/').filter(Boolean);
      const rootName = root.split('/').pop() || root;
      const list = [{ label: rootName, path: root }];
      let acc = root;
      for (let i = 0; i < parts.length; i++) {
        acc = acc + '/' + parts[i];
        list.push({ label: parts[i], path: acc });
      }
      return list;
    },
    _pathBreadcrumbsFromFull(p) {
      if (!p) return [];
      const parts = p.split('/').filter(Boolean);
      const list = [];
      const hasLeadingSlash = (this.selectedFolderPath || '').replace(/\\/g, '/').startsWith('/');
      let acc = '';
      for (let i = 0; i < parts.length; i++) {
        acc = i === 0 ? (hasLeadingSlash ? '/' + parts[0] : parts[0]) : acc + '/' + parts[i];
        list.push({ label: parts[i], path: acc });
      }
      return list;
    }
  },


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

    handleEditMaterial() {
      this.$emit('handle-edit-material');
    },

    handleParentClick() {
      this.$emit('handle-parent-click');
    },

    handleDetailsChange(event) {
      const newValue = event.target.checked;
      this.$emit('details-change', newValue);
    },

    handleChangeView() {
      this.$emit('change-view');
    },

    handleUpdateThumbnails() {
      this.$emit('update-thumbnails');
    },

    handleSortBy(sortType) {
      this.$emit('sort-by', sortType);
    },

    handleAddSelected() {
      this.$emit('add-selected');
    },

    handlePathSegmentClick(path) {
      this.$emit('browse-folder-path', path);
    }
  },

  template: /*html*/ `
    <div class="d-flex control-panel border-bottom p-2" :id="controlPanelId">
      <!-- Edit Material Button -->
      <button
        v-if="type === 'material' && showShowEditMaterial"
        type="button"
        class="btn btn-icon-only btn-text-dark mr-1"
        data-toggle="tooltip"
        :title="translated('editMaterial')"
        @click="handleEditMaterial"
      >
        <i class="modus-icons">paint_bucket</i>
      </button>

      <!-- Up One Level Button + 当前路径 -->
      <button
        v-if="shouldShowUpButton"
        type="button"
        class="go-parent btn btn-icon-only btn-text-dark mr-1"
        :disabled="isParentDisabled"
        data-toggle="tooltip"
        :title="translated('upOneLevel')"
        @click="handleParentClick"
      >
        <i class="modus-icons">sort_arrow_up</i>
      </button>
      <span
        v-if="shouldShowUpButton && selectedFolderPath"
        class="current-folder-path text-tertiary ml-1"
        :title="selectedFolderPath"
      >
        <template v-for="(seg, idx) in pathBreadcrumbs">
          <span v-if="idx > 0" :key="'sep-' + idx" class="path-sep">/</span>
          <span
            :key="idx"
            class="path-segment"
            :class="{ 'path-segment-current': idx === pathBreadcrumbs.length - 1 }"
            :title="seg.path"
            @click="handlePathSegmentClick(seg.path)"
          >{{ seg.label }}</span>
        </template>
      </span>

      <!-- Update In Model Button -->
      <button
        v-show="selectedType === 'in-model' && !(sidebarOpen && isMediumWindow)"
        class="btn btn-icon-only btn-outline-tertiary text-dark ml-1"
        type="button"
        id="updateThumbnailsButton"
        data-toggle="tooltip"
        :title="translated('updateThumbnails')"
        @click="handleUpdateThumbnails"
      >
        <i class="modus-icons">image_scene</i>
      </button>

      <!-- Control Panel Buttons -->
      <div
        v-if="!(sidebarOpen && isMediumWindow)"
        class="control-panel-buttons d-flex ml-auto"
      >
        <button
          v-if="shouldShowAddSelectedButton"
          type="button"
          class="btn btn-icon-only btn-text-dark ml-1"
          data-toggle="tooltip"
          :title="translated('addObjectFolder')"
          @click="handleAddSelected"
        >
          <i class="modus-icons">add_bold</i>
        </button>

        <!-- 缩略图大小切换按钮（只在两种缩略图模式间切换） -->
        <button
          class="btn btn-icon-only btn-text-dark ml-1"
          type="button"
          data-toggle="tooltip"
          :title="translated(currentView.title)"
          @click="handleChangeView"
        >
          <i class="modus-icons">{{ currentView.icon }}</i>
        </button>

        <!-- Filter Dropdown -->
        <div class="dropdown">
          <button
            class="btn btn-icon-only btn-text-dark ml-1"
            type="button"
            data-toggle="dropdown"
            :title="translated('sortedBy')"
          >
            <i class="modus-icons">filter</i>
          </button>

          <div class="dropdown-menu dropdown-menu-right custom-menu">
            <h5 class="px-3 py-2">{{ translated('sortedBy') }}</h5>
            <div class="dropdown-divider"></div>
            <ul class="form-group list-group list-group-borderless px-2">
              <li
                v-for="option in sortOptions"
                :key="option.value"
                class="list-group-item list-item-right-control custom-list-group-item"
                @click="handleSortBy(option.value)"
              >
                {{ translated(option.text) }}
                <i v-if="selectedSort === option.value" class="modus-icons">check</i>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  `
});
