/**
 * Material Content Component
 * Displays material items grid/list with canvas texture preview
 * Specific for Material tab (has canvas for texture preview, square thumbnails)
 */
Vue.component('material-content', {
  props: {
    // Navigation & state
    isOnline: Boolean,
    selectedType: String,

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

    // Items
    filteredItems: Array,
    selectedMaterials: Array,
    favorites: Array,

    // Canvas overlays for in-model textures
    overlayStyles: Array
  },

  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
    };
  },

  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);
  },

  watch: {
    'zoomPreview.show'(newVal) {
      if (newVal && this.selectedType === 'in-model' && this.zoomPreview.itemInfo) {
        this.$nextTick(() => {
          this.updateZoomCanvas();
        });
      }
    }
  },

  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);
    },

    handleToggleFavorite(itemInfo) {
      this.$emit('hide-context-menu');
      this.$emit('toggle-favorite', itemInfo);
    },

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

    handleQuickAction(action, itemInfo) {
      this.$emit('hide-context-menu');
      this.$emit('quick-action', { action, itemInfo });
    },

    handleSaveNewItemName(itemPath, itemName) {
      this.$emit('save-new-item-name', { itemPath, itemName });
    },

    cancelRenameItem(itemPath, itemName) {
      this.$emit('cancel-rename-item', { itemPath, itemName });
    },

    // 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;

        // For in-model, use 2x canvas size (256*2 = 512)
        if (this.selectedType === 'in-model') {
          const size = 256 * 1; // x1 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
        } else {
          // For local materials, use fixed size like in-model (x2)
          const size = 256 * 1;

          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'
      };
    },

    updateZoomCanvas() {
      const originalCanvas = document.getElementById('textureCanvas' + this.zoomPreview.index);
      const zoomCanvas = document.getElementById('zoomCanvas' + this.zoomPreview.index);

      if (originalCanvas && zoomCanvas) {
        // Use 2x canvas size (256*2 = 512)
        zoomCanvas.width = 256 * 1;
        zoomCanvas.height = 256 * 1;

        const ctx = zoomCanvas.getContext('2d');
        ctx.imageSmoothingEnabled = false; // Keep sharp pixels
        ctx.clearRect(0, 0, zoomCanvas.width, zoomCanvas.height);
        // Draw at 2x size
        ctx.drawImage(originalCanvas, 0, 0, zoomCanvas.width, zoomCanvas.height);
      }
    }
  },

  template: /*html*/ `
    <div class="item-cards-container">
      <!-- Items Grid/List -->
      <div
        v-show="!isOnline"
        class="item-cards bg-gray-light p-2"
        @contextmenu.stop.prevent="handleContentContextMenu($event)"
      >
        <div class="items-container" :style="currentStyle" v-if="filteredItems.length > 0">
          <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': selectedMaterials.includes(itemInfo.itemName) },
              { 'padding-right-25': viewMode === 'list' }
            ]"
            @click="handleItemClick($event, itemInfo, index)"
          >
            <div
              v-if="viewMode !== 'list' && itemInfo.itemType !== 'folder'"
              class="item-quick-actions item-quick-actions-three"
            >
              <button
                type="button"
                class="btn btn-sm item-quick-action-btn"
                :title="translated('replaceMaterial')"
                @click.stop="handleQuickAction('replace_material', itemInfo)"
              >
                {{ translated('replaceMaterial') }}
              </button>
              <button
                type="button"
                class="btn btn-sm item-quick-action-btn"
                title="替换柜体"
                @click.stop="handleQuickAction('replace_cabinet_layer', itemInfo)"
              >
                替换柜体
              </button>
              <button
                type="button"
                class="btn btn-sm item-quick-action-btn"
                title="替换门板"
                @click.stop="handleQuickAction('replace_door_panel_layer', itemInfo)"
              >
                替换门板
              </button>
            </div>

            <!-- Thumbnail (Canvas for in-model, Image for others) -->
            <div
              :class="[
                viewMode === 'list' ? 'square-image-list mr-2' : 'square-image',
                (viewMode === 'list' && itemInfo.itemType !== 'folder') ? 'square-material' : ''
              ]"
              @mousedown.left="showZoomPreview($event, itemInfo, index)"
              @mouseup="hideZoomPreview()"
              @mouseleave="hideZoomPreview()"
            >
              <div v-if="selectedType === 'in-model'">
                <canvas
                  class="canvas-image"
                  :id="'textureCanvas' + index"
                  :ref="'textureCanvas' + index"
                >
                </canvas>
                <div
                  class="overlay"
                  :style="overlayStyles[index]"
                >
                </div>
              </div>
              <img
                v-else
                :class="['material-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"
                :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 class="d-flex justify-content-center align-items-center item-empty" v-if="filteredItems.length === 0">
          <h2 class="text-tertiary text-center">
            {{ translated('noMaterialHere') }}
          </h2>
        </div>
      </div>

      <!-- Zoom Preview Popup -->
      <div
        v-if="zoomPreview.show"
        :class="['zoom-preview', { 'show': zoomPreview.show }]"
        :style="getZoomPreviewStyle()"
      >
        <div v-if="selectedType === 'in-model' && zoomPreview.itemInfo">
          <div class="zoom-preview-canvas-container">
            <canvas 
              class="zoom-canvas"
              :id="'zoomCanvas' + zoomPreview.index"
            >
            </canvas>
            <div 
              class="overlay"
              :style="overlayStyles[zoomPreview.index]"
            >
            </div>
          </div>
        </div>
        <img
          v-else-if="zoomPreview.itemInfo"
          :src="fileUrlFromPath(zoomPreview.itemInfo.thumbnailPath)"
          :alt="zoomPreview.itemInfo.itemName"
          :style="{ width: zoomPreview.width + 'px', height: zoomPreview.height + 'px', objectFit: 'contain' }"
        />
      </div>
    </div>
  `
});
