Vue.component('online-container', {
  props: {
    type: {
      type: String,
      required: true,
      validator: (value) => ['model', 'material'].includes(value)
    },
    isOnline: {
      type: Boolean,
      required: true
    },
    defaultSource: {
      type: Array,
      default: () => []
    },
    onlineSources: {
      type: Array,
      default: () => []
    },
    currentUrl: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      iframeLoading: true,
      iframeError: false
    };
  },

  computed: {
    sortableId() {
      const idMap = { model: 'sortableOnlineModel', material: 'sortableOnlineMaterial', door: 'sortableOnlineDoor', handle: 'sortableOnlineHandle' };
      return idMap[this.type] || 'sortableOnlineModel';
    },
    iframeId() {
      return this.type === 'model' ? 'iframeModel' : 'iframeMaterial';
    }
  },

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

    handleBrowseUrl(url) {
      // Kiểm tra URL hợp lệ trước khi tải
      if (this.isValidUrl(url)) {
        this.$emit('browse-url', url);
      } else {
        console.warn('Invalid URL detected:', url);
        // Có thể thêm thông báo lỗi cho user
      }
    },

    handleShowOnlineContextMenu(event, source) {
      this.$emit('show-online-context-menu', { event, source });
    },

    handleSaveOnlineSourceName(url, oldName) {
      this.$emit('save-online-source-name', { url, oldName });
    },

    handleOpenAddSource() {
      this.$emit('open-add-source');
    },

    isValidUrl(url) {
      if (!url || typeof url !== 'string') return false;
      
      try {
        const urlObj = new URL(url);
        // Chỉ cho phép HTTP và HTTPS
        return urlObj.protocol === 'http:' || urlObj.protocol === 'https:';
      } catch (e) {
        return false;
      }
    },

    handleIframeError() {
      console.warn('Iframe failed to load:', this.currentUrl);
      this.iframeError = true;
      this.iframeLoading = false;
    },

    handleIframeLoad() {
      this.iframeLoading = false;
      this.iframeError = false;
    },

    resetIframeState() {
      this.iframeLoading = true;
      this.iframeError = false;
    },

    focusInput(sourceName) {
      this.$nextTick(() => {
        const input = this.$refs['inputRef_' + sourceName];
        if (input && input[0]) {
          input[0].focus();
          input[0].select();
        } else if (input && input.focus) {
          input.focus();
          input.select();
        }
      });
    }
  },

  watch: {
    currentUrl() {
      this.resetIframeState();
    },
    
    onlineSources: {
      handler() {
        this.$nextTick(() => {
          const editingSource = this.onlineSources.find(s => s.isOnlineEditing);
          if (editingSource) {
            setTimeout(() => {
              const input = this.$refs['inputRef_' + editingSource[1]];
              if (input && input[0]) {
                input[0].focus();
                input[0].select();
              } else if (input && input.focus) {
                input.focus();
                input.select();
              }
            }, 50);
          }
        });
      },
      deep: true,
      immediate: false
    }
  },

  template: /*html*/ `
    <div v-show="isOnline" class="online-container flex-grow-1">
      <!-- Online Panel -->
      <div class="d-flex control-panel border-bottom p-2">
        <button
          v-if="defaultSource.length > 0"
          :class="['btn mr-1', currentUrl === defaultSource[0] ? 'btn-dark' : 'btn-outline-dark' ]"
          @click="handleBrowseUrl(defaultSource[0])"
        >
          {{ defaultSource[1] }}
        </button>

        <div :id="sortableId">
          <div v-for="(source, index) in onlineSources" :key="index" class="d-inline-block mr-1">
            <input
              v-if="source.isOnlineEditing"
              v-model="source.newName"
              type="text"
              class="custom-form-control text-center"
              @keydown.enter="handleSaveOnlineSourceName(source[0], source[1])"
              @blur="handleSaveOnlineSourceName(source[0], source[1])"
              :ref="'inputRef_' + source[1]"
            />

            <button
              v-else
              :class="['btn', source.isOnlineEditing ? 'p-0' : '', currentUrl === source[0] ? 'btn-dark' : 'btn-outline-dark' ]"
              :data-url="source[0]"
              @contextmenu.stop.prevent="handleShowOnlineContextMenu($event, source)"
              @click="handleBrowseUrl(source[0])"
            >
              <span>{{ source[1] }}</span>
            </button>
          </div>
        </div>

        <button
          type="button"
          class="btn btn-text-dark btn-icon-only"
          data-toggle="tooltip"
          :title="translated('addSource')"
          @click="handleOpenAddSource()"
        >
          <i class="modus-icons">add</i>
        </button>
      </div>

      <!-- Online Content -->
      <div
        v-if="isOnline"
        class="embed-responsive embed-responsive-16by9 position-relative"
        :id="iframeId"
        style="overflow: hidden;"
      >
        <!-- Loading Indicator -->
        <div
          v-if="iframeLoading && isValidUrl(currentUrl)" 
          class="position-absolute w-100 h-100 d-flex align-items-center justify-content-center bg-white"
          style="top: 0; left: 0; z-index: 5;"
        >
          <div class="text-center">
            <div class="spinner-border text-primary" role="status">
              <span class="sr-only">Loading...</span>
            </div>
            <p class="mt-2 text-muted">{{ translated('loading') || 'Loading...' }}</p>
          </div>
        </div>

        <!-- Iframe with protection -->
        <iframe
          v-if="isValidUrl(currentUrl)"
          class="embed-responsive-item"
          :src="currentUrl"
          loading="lazy"
          sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-presentation allow-popups-to-escape-sandbox"
          referrerpolicy="no-referrer"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          style="border: none; pointer-events: auto;"
          @load="handleIframeLoad"
          @error="handleIframeError"
        ></iframe>
      </div>
    </div>
  `
});

