<script>
import { defineComponent } from 'vue';
import logobeginPCpld from '@/assets/logobeginPCpld.png';
import logobeginPC from '@/assets/logobeginPC.mp4';
import intopagedir from '@/assets/intopagedir.svg';

const mobileFrames = import.meta.glob('@/assets/openvideo/*.jpg', { eager: true, as: 'url' });
const tabletFrames = import.meta.glob('@/assets/openvideopad/*.jpg', { eager: true, as: 'url' });

export default defineComponent({
  name: "HeaderVideo",
  props: {
    alt: { type: String, default: '' },
    fps: { type: Number, default: 15 },
    autoplay: { type: Boolean, default: true },
    loop: { type: Boolean, default: false },
    framesCount: { type: Number, default: 82 }, // Max frame index, so 83 frames total (0-82)
    basePath: { type: String, default: '/openvideo/' },
    // New prop: Percentage of frames to load before starting playback (0.0 to 1.0)
    playbackStartThreshold: { type: Number, default: 0.3 }
  },
  data() {
    return {
      currentFrame: 0,
      timer: null,
      isLoading: true, // True while loading initial frames needed for playback
      loadingProgress: 0, // Progress for loading initial frames (0-100%)
      preloadedImages: [], // Array to store preloaded Image objects
      logobeginPCpld: logobeginPCpld,
      logobeginPC: logobeginPC,
      intopagedir: intopagedir
    };
  },
  computed: {
    frames() {
      const arr = [];
      if (this.$isMobile.phone) {
        for (let i = 0; i <= this.framesCount; i++) {
          const name = String(i).padStart(2, '0') + '.jpg';
          const path = `/src/assets/openvideo/${name}`;
          if (mobileFrames[path]) {
            arr.push(mobileFrames[path]);
          }
        }
      } else if (this.$isMobile.tablet) {
        const tabletFramesCount = 90;
        for (let i = 0; i <= tabletFramesCount; i++) {
          const name = String(i).padStart(2, '0') + '.jpg';
          const path = `/src/assets/openvideopad/${name}`;
          if (tabletFrames[path]) {
            arr.push(tabletFrames[path]);
          }
        }
      }
      return arr;
    },
    // Number of frames that need to be loaded before playback can start
    framesNeededForPlayback() {
      if (this.frames.length === 0) return 0;
      const calculatedFrames = Math.ceil(this.frames.length * this.playbackStartThreshold);
      return Math.max(1, calculatedFrames);
    },
    currentFrameSrc() {
      if (this.preloadedImages[this.currentFrame] && this.preloadedImages[this.currentFrame].src) {
        return this.preloadedImages[this.currentFrame].src;
      }
      return '';
    }
  },
  methods: {
    handleVideoEnded() { // For the <video> element, not the frame animation
      window.location.href = "/Homepage";
    },

    initializeAndPreload() {
      this.isLoading = true;
      this.loadingProgress = 0;
      this.preloadedImages = new Array(this.frames.length).fill(null);

      const framesToLoadInitially = this.framesNeededForPlayback;

      if (framesToLoadInitially === 0) {
        console.warn("framesNeededForPlayback is 0. Starting playback immediately and loading all frames in background.");
        this.isLoading = false;
        if (this.autoplay) {
          this.start();
        }
        this.preloadRemainingFrames(0); // Load all frames
        return;
      }

      let initialLoadedCount = 0;
      const initialLoadPromises = [];

      for (let i = 0; i < framesToLoadInitially; i++) {
        // Ensure we don't try to load beyond available frames if threshold is 1.0 and framesNeededForPlayback equals frames.length
        if (i >= this.frames.length) break;

        const src = this.frames[i];
        initialLoadPromises.push(
            new Promise((resolve) => { // No reject, always resolve to allow progress
              const img = new Image();
              img.onload = () => {
                this.preloadedImages[i] = img;
                initialLoadedCount++;
                this.loadingProgress = Math.floor(initialLoadedCount / framesToLoadInitially * 100);
                resolve(img);
              };
              img.onerror = (e) => {
                console.error(`Error loading initial frame ${src}:`, e);
                initialLoadedCount++; // Still count as processed for progress bar
                this.loadingProgress = Math.floor(initialLoadedCount / framesToLoadInitially * 100);
                resolve(null); // Resolve with null, preloadedImages[i] will remain null
              };
              img.src = src;
            })
        );
      }

      Promise.all(initialLoadPromises)
          .then(() => {
            console.log("Initial frames loaded, starting playback.");
            this.isLoading = false;
            if (this.autoplay) {
              this.start();
            }
            // Start preloading the rest of the frames
            if (framesToLoadInitially < this.frames.length) {
              this.preloadRemainingFrames(framesToLoadInitially);
            } else {
              console.log("All frames were loaded in the initial batch.");
            }
          })
      // .catch is not strictly needed here because individual promises always resolve
      // If it were to catch, it would imply a fundamental issue with Promise.all itself
      ;
    },

    preloadRemainingFrames(startIndex) {
      if (startIndex >= this.frames.length) {
        // This case should be handled by the caller, but good to have a guard
        console.log("No remaining frames to preload or startIndex is out of bounds.");
        return;
      }

      console.log(`Preloading remaining ${this.frames.length - startIndex} frames from index ${startIndex}...`);
      for (let i = startIndex; i < this.frames.length; i++) {
        const src = this.frames[i];
        // Skip if already loaded (e.g. if an error occurred and this is retried, or some other logic)
        if (this.preloadedImages[i]) continue;

        const img = new Image();
        img.onload = () => {
          this.preloadedImages[i] = img;
        };
        img.onerror = (e) => {
          console.error(`Error loading remaining frame ${src}:`, e);
          // preloadedImages[i] will remain null for this frame
        };
        img.src = src;
      }
    },

    start() {
      if (this.timer || this.frames.length === 0) return;

      // Ensure playback doesn't start if it's still in the initial loading phase
      if (this.isLoading) {
        console.warn("Attempted to start playback while still in initial loading phase.");
        return;
      }

      let curfps=this.fps;
      if(this.$isMobile.tablet){
        curfps=15;
      }
      const interval = 1000 / curfps;
      this.timer = setInterval(() => {
        const nextFrame = this.currentFrame + 1;

        if (nextFrame < this.frames.length) {
          this.currentFrame = nextFrame;
        } else {
          // Reached the end
          if (!this.loop) {
            this.stop();
            setTimeout(() => {
              window.location.href = "/Homepage";
            }, 100);
          } else {
            this.currentFrame = 0; // Loop back
          }
        }
      }, interval);
    },

    stop() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  },
  mounted() {
    if (this.$isMobile.phone || this.$isMobile.tablet) { // 修改此处，增加平板的判断
      this.initializeAndPreload();
    } else {
      // 桌面设备使用 <video> 标签
      const videos = document.querySelectorAll('.startvideo');
      if (videos.length > 0) {
        videos.forEach(video => {
          video.addEventListener('ended', this.handleVideoEnded);
        });
      } else {
        console.warn("No video elements found for desktop.");
      }
    }
  },
  beforeUnmount() {
    this.stop();
  },
  watch: {
    autoplay(val, oldVal) {
      if (val === oldVal) return; // No change

      if (this.$isMobile.phone) { // Only apply to frame animation
        if (val && !this.timer && !this.isLoading) {
          // If autoplay turned on, not already playing, and not in initial load
          this.start();
        } else if (!val && this.timer) {
          // If autoplay turned off and currently playing
          this.stop();
        }
      }
    },
    // Optional: If framesCount or basePath could change dynamically and require reloading
  }
});
</script>

<template>
  <div id="beginroot" class="pageroot">
    <div id="videodiv">
      <!-- Loading progress for initial frames on mobile -->
      <div v-if="($isMobile.phone||$isMobile.tablet) && isLoading" class="loading-container">
        <div class="progress-container">
          <div class="progress-bar" :style="{width: loadingProgress + '%'}"></div>
        </div>
        <div class="loading-text">加载中 {{ loadingProgress }}%</div>
      </div>

      <!-- Frame animation player for mobile, shown after initial load -->
      <img
          v-if="($isMobile.phone||$isMobile.tablet) && !isLoading"
          :src="currentFrameSrc"
          id="beginwep"
          :alt="alt"
          class="simple-frame-player"
      />
      <video v-if="(!$isMobile.phone&&!$isMobile.tablet)" :poster="logobeginPCpld"
             id="pcstart" muted autoplay
             playsinline webkit-playsinline
             class="startvideo"
             x5-video-player-type="h5-page">
        <source :src="logobeginPC" type="video/mp4"></source>
      </video>
    </div>
    <div id="beginbottom" v-if="false">
      <a href="/Homepage">
        <div class="normalcontentdiv" id="intovideoreq">
        <span class="normalcontenttitle" id="intoa">
          <u>进入kdesign.top</u>
          <img :src="intopagedir" id="intopagesvg"/>
        </span>
        </div>
      </a>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import "src/publicstyle.scss"; // Assuming this path is correct relative to your project structure
.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 80%;
  z-index: 10;
}
.progress-container {
  background-color: rgba(255, 255, 255, 0.2);
  height: 8px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-bar {
  height: 100%;
  background-color: white;
  transition: width 0.3s ease; /* Smooth progress bar transition */
}

.loading-text {
  color: white;
  font-size: 14px;
  @include media-breakpoint-up(md){
    margin-top: 10px;
  }
}
#beginroot{
  height: 100%;
  display: flex;
  flex-direction: column;
}
#wepstart{ // This style block seems to target an element not in the provided template.
  // If #beginwep is sometimes referred to as #wepstart, it's covered by #beginwep styles.
  @include media-breakpoint-between(xs, md) {
    visibility: visible;
    height: 100%!important;
  }
  @include media-breakpoint-up(md) {
    visibility: collapse;
    height: 0!important;
  }
}
#pcstart{
  @include media-breakpoint-between(xs, md) {
    visibility: collapse; // Hidden on smaller screens where frame animation or tablet video is used
  }
  @include media-breakpoint-up(md) {
    visibility: visible; // Visible on larger screens
  }
}
#beginbottom {
  flex-shrink: 0;
  a {
    text-decoration: none;
    width: 100%;

    .normalcontenttitle {
      transition: color 0.3s ease;
      color: white;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    #intoa{
      @include media-breakpoint-between(xs, md) {
        font-size: 24px;
      }
      @include media-breakpoint-up(md) {
        font-size: 35px;
        line-height: 48px;
      }
    }

    &:hover {
      .normalcontenttitle {
        color: #DAA520 !important;
      }
    }
  }
}
#videodiv{
  width: 100%;
  flex:1;
  min-height: 0;
  background-color: black;
  overflow: hidden;
  position: relative; /* Added for absolute positioning of loading-container */
}
.startvideo{ // Styles for <video> elements
  width: 100%;
  height: 100%;
  object-fit: cover;
}
#beginwep{ // Styles for the <img> frame player
  width: 100%;
  height: 100%;
  object-fit: cover;
}

#intopagesvg{
  height: 1em; // Adjusted for better alignment with text
  width: auto;
  margin-left: 0.5em;
}
#intovideoreq{
  margin-top: 2px;
  padding-bottom: 2px;
  transition: background 0.5s, color 0.5s;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-left: 0!important;
  margin-bottom: 10px;
}
#intovideoreq .normalcontenttitle {
  width: auto !important;
  text-align: center !important;
}
</style>
