/**
 * Handle Content Component
 * Displays handle items grid/list - same structure as model tab
 */
Vue.component('handle-content', {
  props: {
    isOnline: Boolean,
    selectedType: String,
    showAllModels: Boolean,
    activeModelPath: Array,
    viewMode: String,
    currentStyle: Object,
    folderEmpty: Boolean,
    showDetails: Boolean,
    sidebarOpen: Boolean,
    isSmallWindow: Boolean,
    isMediumWindow: Boolean,
    filteredItems: Array,
    selectedModels: Array,
    favorites: Array,
    dynamicIconPath: String,
    liveIconPath: String
  },

  data() {
    return {
      zoomPreview: { show: false, x: 0, y: 0, width: 0, height: 0, itemInfo: null, index: -1 },
      hoverTimeout: null,
      previewWasShown: false,
      tooltip: { show: false, x: 0, y: 0, description: '' },
      tooltipTimeout: null
    };
  },

  mounted() {
    this.$root.$on('focus-item-input', (itemName) => {
      this.$nextTick(() => {
        const input = this.$refs['inputRef_' + itemName];
        if (input && input.length > 0) {
          input[0].focus();
          input[0].select();
        }
      });
    });
  },

  beforeDestroy() {
    this.$root.$off('focus-item-input');
    clearTimeout(this.hoverTimeout);
    clearTimeout(this.tooltipTimeout);
  },

  computed: {
    shouldShowShowAllCheckbox() {
      return this.selectedType === 'in-model';
    }
  },

  methods: {
    fileUrlFromPath(path) {
      return window.fileUrlFromPath ? window.fileUrlFromPath(path) : ('file:///' + (path || '').replace(/\\/g, '/'));
    },
    translated(key) {
      return this.$root.translated(key);
    },
    handleContentContextMenu(event) {
      this.$emit('content-context-menu', event);
    },
    handleItemContextMenu(event, itemInfo) {
      this.$emit('item-context-menu', { event, itemInfo });
    },
    handleItemClick(event, itemInfo, index) {
      if (this.previewWasShown) {
        this.previewWasShown = false;
        return;
      }
      this.$emit('item-click', itemInfo);
    },
    isLastItem(index) {
      return index === this.activeModelPath.length - 1;
    },
    handleToggleFavorite(itemInfo) {
      this.$emit('hide-context-menu');
      this.$emit('toggle-favorite', itemInfo);
    },
    toggleShowAllModels() {
      this.$emit('toggle-show-all-models');
    },
    handleQuickAction(action, itemInfo) {
      this.$emit('hide-context-menu');
      this.$emit('quick-action', { action, itemInfo });
    },
    quickActionShortLabel(action) {
      const labelMap = {
        insert_origin: '插入',
        replace_selected: '替换所选',
        replace_instances: '拉手替换',
        replace_match: '替换匹配'
      };
      return labelMap[action] || action;
    },
    handleInputClick() {
      this.$emit('hide-context-menu');
    },
    handleSaveNewItemName(itemPath, itemName) {
      this.$emit('save-new-item-name', { itemPath, itemName });
    },
    cancelRenameItem(itemPath, itemName) {
      this.$emit('cancel-rename-item', { itemPath, itemName });
    },
    handleGoToRoot() {
      this.$emit('go-to-root');
    },
    handleGoToParent(index) {
      this.$emit('go-to-parent', index);
    },
    showZoomPreview(event, itemInfo, index) {
      if (itemInfo.itemType === 'folder') return;
      clearTimeout(this.hoverTimeout);
      this.hoverTimeout = setTimeout(() => {
        const rect = event.target.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        const padding = 20;
        let x = rect.right + 15;
        let y = rect.top - 10;
        const size = 256;
        if (x + size > viewportWidth - padding) x = rect.left - size - 10;
        if (x < padding) x = padding;
        if (y + size > viewportHeight - padding) y = viewportHeight - size - padding;
        if (y < padding) y = padding;
        this.zoomPreview = { show: true, x, y, width: size, height: size, itemInfo, index };
        this.previewWasShown = true;
      }, 200);
    },
    hideZoomPreview() {
      clearTimeout(this.hoverTimeout);
      this.zoomPreview.show = false;
    },
    getZoomPreviewStyle() {
      return { left: this.zoomPreview.x + 'px', top: this.zoomPreview.y + 'px' };
    },
    showTooltip(event, itemInfo) {
      if (this.selectedType !== 'in-model' || !itemInfo.itemDescription || itemInfo.itemType === 'folder') return;
      clearTimeout(this.tooltipTimeout);
      this.tooltipTimeout = setTimeout(() => {
        const padding = 10;
        let x = event.clientX + 15;
        let y = event.clientY + 15;
        const estimatedWidth = 250;
        const estimatedHeight = 60;
        if (x + estimatedWidth > window.innerWidth - padding) x = event.clientX - estimatedWidth - 15;
        if (x < padding) x = padding;
        if (y + estimatedHeight > window.innerHeight - padding) y = event.clientY - estimatedHeight - 15;
        if (y < padding) y = padding;
        this.tooltip = { show: true, x, y, description: itemInfo.itemDescription };
      }, 300);
    },
    hideTooltip() {
      clearTimeout(this.tooltipTimeout);
      this.tooltip.show = false;
    },
    getTooltipStyle() {
      return { left: this.tooltip.x + 'px', top: this.tooltip.y + 'px' };
    }
  },

  template: /*html*/ `
    <div class="item-cards-container">
      <nav
        v-if="selectedType === 'in-model' && !(sidebarOpen && isMediumWindow)"
        aria-label="breadcrumb"
        class="d-flex bg-selected px-2 pt-0 pb-1"
        id="breadcrumb"
      >
        <div
          v-show="shouldShowShowAllCheckbox"
          class="custom-control custom-checkbox mt-1"
          id="showAllModels"
        >
          <input type="checkbox" class="custom-control-input" id="breadcrumbCheckbox" :checked="showAllModels" @change="toggleShowAllModels" />
          <label class="custom-control-label" for="breadcrumbCheckbox" data-toggle="tooltip" :title="translated('showAllModels')"></label>
        </div>
        <ol v-show="!showAllModels" class="breadcrumb bg-selected mb-0 p-0">
          <li class="breadcrumb-item mt-1">
            <span class="custom-breadcrumb bg-white text-dark" href="#" @click.prevent="handleGoToRoot">{{ translated('inModel') }}</span>
          </li>
          <li v-for="(folder, index) in activeModelPath" :key="index" class="breadcrumb-item mt-1" :class="{'active': isLastItem(index)}">
            <span v-if="!isLastItem(index)" href="#" class="custom-breadcrumb bg-white text-dark" @click.prevent="handleGoToParent(index)">{{ folder }}</span>
            <span class="custom-breadcrumb-active" v-else>{{ folder }}</span>
          </li>
        </ol>
      </nav>
      <div v-show="!isOnline" class="item-cards bg-gray-light p-2" @contextmenu.stop.prevent="handleContentContextMenu($event)">
        <div v-if="filteredItems.length > 0" class="items-container" :style="currentStyle">
          <div
            v-for="(itemInfo, index) in filteredItems"
            v-show="!itemInfo.isDelete"
            :key="index"
            @contextmenu.stop.prevent="handleItemContextMenu($event, itemInfo)"
            :class="[
              'bg-white',
              viewMode === 'list' ? 'item-card-list p-1' : 'item-card p-2',
              { 'item-card-details': showDetails && viewMode !== 'list' },
              { 'selected-item': selectedModels.includes(itemInfo.itemName) },
              { 'padding-right-25': viewMode === 'list' }
            ]"
            @click="handleItemClick($event, itemInfo, index)"
            @mouseleave="hideTooltip()"
          >
            <div
              v-if="viewMode !== 'list' && itemInfo.itemType !== 'folder' && !itemInfo.isItemEditing"
              class="item-quick-actions item-quick-actions-four"
            >
              <button type="button" class="btn btn-sm item-quick-action-btn" :title="translated('insertOrigin')" @click.stop="handleQuickAction('insert_origin', itemInfo)">
                {{ quickActionShortLabel('insert_origin') }}
              </button>
              <button type="button" class="btn btn-sm item-quick-action-btn" title="拉手替换" @click.stop="handleQuickAction('replace_instances', itemInfo)">
                {{ quickActionShortLabel('replace_instances') }}
              </button>
            </div>
            <div
              :class="viewMode === 'list' ? 'thumbnail-container-list mr-2' : 'thumbnail-container'"
              @mousedown.left="showZoomPreview($event, itemInfo, index)"
              @mouseup="hideZoomPreview()"
              @mouseleave="hideZoomPreview()"
              @mouseenter="showTooltip($event, itemInfo)"
              @mousemove="showTooltip($event, itemInfo)"
            >
              <div v-show="viewMode !== 'list' && (itemInfo.itemType === 'dynamic' || itemInfo.itemType === 'live')" class="type-icon" :title="itemInfo.itemType === 'dynamic' ? 'dynamicComponent' : 'liveComponent'">
                <img :src="itemInfo.itemType === 'dynamic' ? dynamicIconPath : liveIconPath" />
              </div>
              <img :class="['model-image', { 'scale-image': itemInfo.itemType === 'folder' && !showDetails }]" :src="fileUrlFromPath(itemInfo.thumbnailPath)" :alt="itemInfo.itemName" />
            </div>
            <div
              v-if="!(viewMode === 'list' && sidebarOpen && isSmallWindow)"
              :class="[viewMode === 'list' ? 'item-info-list' : ((!showDetails && itemInfo.itemType === 'folder') ? 'folder-info' : 'flex-column item-info'), { 'item-info-details': showDetails && viewMode !== 'list' }]"
            >
              <!-- 先显示文件大小 -->
              <div v-show="showDetails || viewMode === 'list'" type="text" :class="['text-tertiary', (viewMode === 'list' ? 'item-size-list ml-auto' : (showDetails ? 'item-size item-size-details' : 'item-size pb-2'))]">
                {{ itemInfo.itemSize }}
              </div>

              <!-- 再显示名称（重命名输入框 / 普通名称） -->
              <input
                v-show="itemInfo.isItemEditing"
                :value="itemInfo.newName"
                @input="itemInfo.newName = $event.target.value"
                @click.stop="handleInputClick"
                @keydown.enter.stop="handleSaveNewItemName(itemInfo.itemPath, itemInfo.itemName)"
                @keydown.esc.stop="cancelRenameItem(itemInfo.itemPath, itemInfo.itemName)"
                @blur="handleSaveNewItemName(itemInfo.itemPath, itemInfo.itemName)"
                type="text"
                :name="itemInfo.itemName"
                :class="['custom-form-control', viewMode !== 'list' ? 'text-center mt-2' : 'mr-3']"
                :ref="'inputRef_' + itemInfo.itemName"
              />
              <div v-show="((showDetails || itemInfo.itemType === 'folder') || viewMode === 'list') && !itemInfo.isItemEditing" :class="viewMode === 'list' ? 'item-name-list' : 'text-center item-name mt-2'">
                {{ itemInfo.itemName.replace('.png', '') }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="filteredItems.length === 0" class="d-flex justify-content-center align-items-center item-empty">
          <h2 class="text-tertiary text-center">{{ translated('noModelHere') }}</h2>
        </div>
      </div>
      <div v-if="zoomPreview.show && zoomPreview.itemInfo" :class="['zoom-preview', { 'show': zoomPreview.show }]" :style="getZoomPreviewStyle()">
        <img :src="fileUrlFromPath(zoomPreview.itemInfo.thumbnailPath)" :alt="zoomPreview.itemInfo.itemName" :style="{ width: zoomPreview.width + 'px', height: zoomPreview.height + 'px', objectFit: 'contain' }" />
      </div>
      <div v-if="tooltip.show && tooltip.description" class="item-tooltip" :style="getTooltipStyle()">{{ tooltip.description }}</div>
    </div>
  `
});
