/**
 * Model Content Component
 * Displays model items grid/list with breadcrumb navigation
 * Specific for Model tab (has breadcrumb, dynamic/live icons, etc.)
 */
Vue.component('model-content', {
  props: {
    // Navigation & state
    isOnline: Boolean,
    selectedType: String,
    showAllModels: Boolean,
    activeModelPath: Array,

    // View mode
    viewMode: String,
    currentStyle: Object,
    folderEmpty: Boolean,
    showDetails: Boolean,
    sidebarOpen: Boolean,
    isSmallWindow: Boolean,
    isMediumWindow: Boolean,

    // Items
    filteredItems: Array,
    selectedModels: Array,
    favorites: Array,

    // Icons
    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, // Flag to prevent click after preview
      tooltip: {
        show: false,
        x: 0,
        y: 0,
        description: ''
      },
      tooltipTimeout: null
    };
  },

  mounted() {
    // Listen for focus input event from parent
    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() {
    // Clean up event listener
    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);
    },

    // Events
    handleContentContextMenu(event) {
      this.$emit('content-context-menu', event);
    },

    handleItemContextMenu(event, itemInfo) {
      this.$emit('item-context-menu', { event, itemInfo });
    },

    handleItemClick(event, itemInfo, index) {
      // Prevent click if preview was shown
      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);
    },

    // Zoom Preview Methods
    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;

        // Calculate position (to the right of thumbnail by default)
        let x = rect.right + 15;
        let y = rect.top - 10;

        const size = 256; // Preview size

        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: x,
          y: y,
          width: size,
          height: size,
          itemInfo: itemInfo,
          index: index
        };
        this.previewWasShown = true; // Mark that preview was shown
      }, 200); // Show after 200ms hold
    },

    hideZoomPreview() {
      clearTimeout(this.hoverTimeout);
      this.zoomPreview.show = false;
    },

    getZoomPreviewStyle() {
      return {
        left: this.zoomPreview.x + 'px',
        top: this.zoomPreview.y + 'px'
      };
    },

    // Tooltip Methods (for hover)
    showTooltip(event, itemInfo) {
      // Only show tooltip for in-model items with description
      if (this.selectedType !== 'in-model' || !itemInfo.itemDescription || itemInfo.itemType === 'folder') {
        return;
      }

      clearTimeout(this.tooltipTimeout);
      this.tooltipTimeout = setTimeout(() => {
        const rect = event.target.closest('.item-card, .item-card-list').getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        const padding = 10;

        // Position tooltip near the cursor
        let x = event.clientX + 15;
        let y = event.clientY + 15;

        // Estimate tooltip width (will be adjusted by CSS max-width)
        const estimatedWidth = 250;
        const estimatedHeight = 60;

        // Adjust if tooltip goes off screen
        if (x + estimatedWidth > viewportWidth - padding) {
          x = event.clientX - estimatedWidth - 15;
        }
        if (x < padding) x = padding;
        if (y + estimatedHeight > viewportHeight - padding) {
          y = event.clientY - estimatedHeight - 15;
        }
        if (y < padding) y = padding;

        this.tooltip = {
          show: true,
          x: x,
          y: y,
          description: itemInfo.itemDescription
        };
      }, 300); // Show after 300ms hover
    },

    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">
      <!-- Breadcrumb Navigation -->
      <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>

      <!-- Items Grid/List -->
      <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="quickActionShortLabel('replace_selected')"
                @click.stop="handleQuickAction('replace_selected', itemInfo)"
              >
                {{ quickActionShortLabel('replace_selected') }}
              </button>
              <button
                type="button"
                class="btn btn-sm item-quick-action-btn"
                :title="translated('replaceAllInstances')"
                @click.stop="handleQuickAction('replace_instances', itemInfo)"
              >
                {{ quickActionShortLabel('replace_instances') }}
              </button>
              <button
                type="button"
                class="btn btn-sm item-quick-action-btn"
                :title="quickActionShortLabel('replace_match')"
                @click.stop="handleQuickAction('replace_match', itemInfo)"
              >
                {{ quickActionShortLabel('replace_match') }}
              </button>
            </div>

            <!-- Thumbnail -->
            <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>

            <!-- Item Info -->
            <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>

        <!-- Empty State：无文件时显示（文件夹在二级目录列显示） -->
        <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>

      <!-- Zoom Preview Popup -->
      <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>

      <!-- Tooltip for item description -->
      <div
        v-if="tooltip.show && tooltip.description"
        class="item-tooltip"
        :style="getTooltipStyle()"
      >
        {{ tooltip.description }}
      </div>
    </div>
  `
});
