main = function () {
	//private menbers
	let pcWidth = 1440; // pc預設寬度
	let mbWidth = 992;  // ㄖㄩ預設寬度
	let defaultFz = 16; // 預設 wrapper字體大小
	let windowWidth;
	let headerH;
	let swiper_video;
	let swiper_history;
	let activeTimelineTl; // 歷史軌跡動態timeline
	let currentHistoryIdx = 0;  // 歷史軌跡第幾個idx
	let historySlideTl // 歷史軌跡倒數計時器
	let imgUrls = [];
	const section = $(".section"); // 取得所有section
	let currentId = null; // foces的區塊ID


	// 每個播放器的配置信息
	var playerConfigs = [
		{
			containerId: "player_expert",
			videoId: "dYBnqdUu6xo",
			category: "expert",
		},
		{
			containerId: "player_understand_1",
			videoId: "dYBnqdUu6xo",
			category: "understand",
			
		},
		{
			containerId: "player_understand_2",
			videoId: "cmgHpZ0Ahs8",
			category: "understand",
			
		},
		{
			containerId: "player_understand_3",
			videoId: "hbfEBBz69eo",
			category: "understand",
			
		},
		{
			containerId: "player_understand_4",
			videoId: "s77XkuPn7YM",
			category: "understand",
			
		},
		{
			containerId: "player_understand_5",
			videoId: "Kti8pWSXXd4",
			category: "understand",
			
		},
		{
			containerId: "player_understand_6",
			videoId: "hbfEBBz69eo",
			category: "understand",
			
		},
	];

	// 創建播放器對象數組
	var players = [];

	//private methods
	function init() {
		console.log("main is loaded.");

		$(window).resize(function () {
			resizeWindow();
		});

		// if ($(window).width() > 992) {
		// 	// smooth scroll
		// 	lenisHandler();
		// }

		// $("#showModal").modal('show');

		loadImagesAndPerformAction(imgUrls, startHandler);

		scrollToSection();

		// 點擊漢堡
		$(".header__hamburger").on("click", function () {
			if(!$(this).hasClass("active")) {
				$(this).addClass("active");
				$(".header__nav").addClass("active");
				openMenu();
			}else {
				$(this).removeClass("active");
				$(".header__nav").removeClass("active");
				closeMenu();
			}		
		});

		// 點擊 專家影片 關閉此功能
		// $(".expert__video .video__overlay").on("click", function () {
		// 	let targetIdx = $(this).data("videoIdx");
		// 	let videoBox = $(this).parents(".video");
		// 	if (!videoBox.hasClass("active")) {
		// 		videoBox.addClass("active");
		// 		playVideo(targetIdx);
		// 	} else {
		// 		videoBox.removeClass("active");
		// 		pauseVideo(targetIdx);
		// 	}
		// });

		// 點擊 歷史軌跡 年份
		$(".history .history__timeline__year").on("click", function () {
			currentHistoryIdx = $(this).data("yearidx");
			autoPlayHistory(currentHistoryIdx);
		});

		$(".modal-test .modal__game__btns__btn").click(function(){
			console.log("modal__game__item click")
			let num = $(this).parents(".modal__game__item").data("num");
			modalGameItemAni(num)
			$(this).parents(".modal__game__item").addClass("active");
			$(this).parent(".modal__game__btns").hide();
		});

		$("#testModal").on('hidden.bs.modal', event => {
			$("#testModal .modal__game__item").removeClass("active");
			$("#testModal .modal__game__btns").css("display", "flex")
			$("#testModal .modal__game__ans").hide();
		})

		// 測試用
		// gsap.to(".game__item-start", { duration: 0.5, autoAlpha: 0 });
		// gsap.to(".game__item-main", { duration: 0.5, autoAlpha: 0 });
		// gsap.to(".game__item-result", { duration: 0.3, autoAlpha: 1, delay: 0.3 });
		// totalScore = 16;
		// gameResultCal()
	}

	function modalGameItemAni(num) {
		$(".modal-test .modal__game__item:nth-child("+num+") .modal__game__ans").css("display", "flex");
	}

	// 初始元素動態
	function elementReset() {
		// gsap.set(".qa__item", { y: 50, autoAlpha: 0 });
	}

	// 開始程序
	function startHandler() {
		// 調整頁面font-size
		windowWidth = $(window).width();
		if (windowWidth > 992) {
			let pcScale = windowWidth / pcWidth;
			$(".wrapper").css("font-size", defaultFz * pcScale + "px");

			setTimeout(() => {
				headerH = $(".header").outerHeight();
				console.log("headerH: " + headerH);
				$(".wrapper").css("padding-top", headerH);
			}, 800);
		} else {
			let mbScale = windowWidth / mbWidth;
			$(".wrapper").css("font-size", defaultFz * mbScale + "px");
			setTimeout(() => {
				headerH = $(".header").outerHeight();
				initMenu();;
			}, 800);
		}

		elementReset();

		understandVideoHandler();
		swiperHandler_history();

		setTimeout(() => {
			gsap.to(".wrapper", { duration: 0.3, autoAlpha: 1 });

			if(!isMobile) {
				$(".qa__box__scroll").niceScroll({
					cursorcolor: "#2ba4da", // 滾動條的顏色
					cursorwidth: "0.6em", // 滾動條寬度
					cursorborder: "1px solid #fff", // 滾動條邊框
					cursorborderradius: "5px", // 滾動條圓角
					touchbehavior: false, // 是否啟用拖曳行為
					autohidemode: false, // 不隱藏卷軸
					background: "", // 軌道背景色
					cursorminheight: 32, // 滾動條最小高度
					railpadding: { top: 0, right: 0, left: 0, bottom: 0 }, // 軌道內間距
					railalign: "center", // 對其垂直軌道
					railvalign: "center", // 對其水平軌道
					cursordragontouch: false, // 使用觸屏模式來實現拖曳
					grabcursorenabled: false,
				});
			}else {
				$(".qa__box__scroll").niceScroll({
					cursorcolor: "#2ba4da", // 滾動條的顏色
					cursorwidth: "0.7em", // 滾動條寬度
					cursorborder: "1px solid #fff", // 滾動條邊框
					cursorborderradius: "5px", // 滾動條圓角
					touchbehavior: false, // 是否啟用拖曳行為
					autohidemode: false, // 不隱藏卷軸
					background: "", // 軌道背景色
					cursorminheight: 32, // 滾動條最小高度
					railpadding: { top: 0, right: 0, left: 0, bottom: 0 }, // 軌道內間距
					railalign: "center", // 對其垂直軌道
					railvalign: "center", // 對其水平軌道
					cursordragontouch: false, // 使用觸屏模式來實現拖曳
					grabcursorenabled: false,
				});
			}

			detectScrollSection();

			$(window).scroll(function(){
				detectScrollSection();
			})

			setTimeout(()=>{
				// 測試
				// swiper_history.slideNext();
				// swiper_history.slideTo(4, 1000)


			}, 1000);
	

			// // 開頭動態
			// startAni();

			// // 元素動態
			// elementAni();
		}, 1000);
	}

	// 桌機調整視窗大小
	function resizeWindow() {
		let currWindowWidth = $(window).width();
		if (currWindowWidth !== windowWidth) {
			if (currWindowWidth > 992) {
				let pcScale = currWindowWidth / pcWidth;
				let currFz = defaultFz * pcScale;
				$(".wrapper").css("font-size", currFz + "px");

				headerH = $(".header").outerHeight();
				$(".wrapper").css("padding-top", headerH);
			} else {
				let mbScale = currWindowWidth / mbWidth;
				let currFz = defaultFz * mbScale;
				$(".wrapper").css("font-size", currFz + "px");

				headerH = $(".header").outerHeight();
				$(".wrapper").css("padding-top", headerH);
			}
		}
	}

	// 宣導影片程序 MB
	async function understandVideoHandler() {
		await buildUnderstandVideo();
		await initIframeApi();
		// // 影片 swiper 程序
		await swiperHandler_video();
	}

	// 初始menu
	function initMenu() {
		let menuListH = $(".header__nav").outerHeight();
		console.log("menuListH: "+menuListH)
		gsap.set(".header__nav", { top: -menuListH });
	}

	// 打開menu
	function openMenu() {
		let headerH = $(".header").outerHeight();
		gsap.to(".header__nav", { duration: 0.3, top: headerH });
	}

	// 關閉menu
	function closeMenu() {
		let menuListH = $(".header__nav").outerHeight();
		gsap.to(".header__nav", { duration: 0.3, top: -menuListH });
	}

	// smoothWheel
	function lenisHandler() {
		const lenis = new Lenis({
			duration: 0.3,
			smoothWheel: true,
		});

		lenis.on("scroll", (e) => {
			// console.log(e)
			ScrollTrigger.update();
		});

		function raf(time) {
			lenis.raf(time);
			requestAnimationFrame(raf);
		}

		requestAnimationFrame(raf);
	}

	// ====================  影片相關  ====================

	function initIframeApi () {
		return new Promise(resolve => {
			var script = document.createElement('script');
			script.src = 'https://www.youtube.com/iframe_api';
			script.onload = onLibraryLoaded;
			document.head.appendChild(script);
			resolve("initIframeApi complete");
		});
	}

	// 談談mRNA 影片DOM
	function buildUnderstandVideo() {
		return new Promise((resolve) => {
			console.log("buildUnderstandVideo")
			$(`.understand__swiper .swiper-wrapper`).html("");
			playerConfigs.forEach((videoData, idx) => {
				if(videoData.category == "understand") {
					$(`.understand__swiper .swiper-wrapper`)
					.append(`
						<div class="swiper-slide">
							<div class="video understand__video ${videoData.category}__video-${idx}">
								<div class="video__overlay">
									<div class="video__frame"></div>
									<div class="video__icon">
										<img src="./images/video-icon.png" alt="">
										<p>影片播放</p>
									</div>
								</div>
								<div class="video__player">
									<div class="video__yt" id="player_${videoData.category}_${idx}">
									</div>
								</div>
							</div>
						</div>
					`);
				}
			});
			resolve("buildPropagandaVideo complete");
		});
	}

	// 談談mRNA 影片程序
	function swiperHandler_video() {
		return new Promise((resolve) => {
			swiper_video = new Swiper(".understand__swiper", {
				// Optional parameters
				allowTouchMove: false,
				slidesPerView: 1,
				centeredSlides: false,
				pagination: {
					el: ".understand__swiper .swiper-pagination",
					clickable: true,
				},
				// spaceBetween: "5%",

				// Navigation arrows
				navigation: {
					nextEl: ".understand__swiper .swiper-button-next",
					prevEl: ".understand__swiper .swiper-button-prev",
				},
				breakpoints: {
					992: {
						// spaceBetween: 100,
					}
				},
				on: {
					init: function (swiper) {
						resolve("swiper_video init");
					},
					slideChangeTransitionEnd: function () {
						pauseAllVideos();
					},
				},
			});
		});
	}

	function onLibraryLoaded() {
		setTimeout(()=>{
			onYouTubeIframeAPIReady();
		}, 1000);
	}

	function onYouTubeIframeAPIReady() {
		// 循環創建播放器
		for (var i = 0; i < playerConfigs.length; i++) {
			var config = playerConfigs[i];
			players[i] = new YT.Player(config.containerId, {
				videoId: config.videoId,
				loop: 1,
				rel: 0,
				events: {
					'onReady': onPlayerReady,
					'onStateChange': onPlayerStateChange,
				},
			});
		}
	}

	function onPlayerReady(event) {
		// 處理播放器準備好後的事件
		// event.target.mute(); // 靜音播放器
		// event.target.playVideo(); // 播放影片
	}

	function onPlayerStateChange(event) {
		console.log(event.target.o.id)
		if (event.data == YT.PlayerState.PLAYING) {
			$(`#${event.target.o.id}`).parents(".video").find(".video__overlay").hide();
		}
	}

	// 控制單個播放器播放
	function playVideo(playerIndex) {
		players[playerIndex].playVideo();
	}

	// 控制單個播放器暫停
	function pauseVideo(playerIndex) {
		players[playerIndex].pauseVideo();
	}

	// 控制單個播放器停止
	function stopVideo(playerIndex) {
		players[playerIndex].stopVideo();
	}

	// 控制所有播放器播放
	function playAllVideos() {
		for (var i = 0; i < players.length; i++) {
			players[i].playVideo();
		}
	}

	// 控制所有播放器暫停
	function pauseAllVideos() {
		for (var i = 0; i < players.length; i++) {
			players[i].pauseVideo();
		}
	}

	// 控制所有播放器停止
	function stopAllVideos() {
		for (var i = 0; i < players.length; i++) {
			players[i].stopVideo();
		}
	}

	// ====================  時間軸相關  ====================

	// 踏上mRNA歷史軌跡 影片程序
	function swiperHandler_history() {
		return new Promise((resolve) => {
			resolve("swiper_history init");
			swiper_history = new Swiper(".history__swiper", {
				// Optional parameters
				autoplay: {
					delay: 10000,
					disableOnInteraction: false,
				},
				slidesPerView: 2,
				centeredSlides: true,
				allowTouchMove: true,
				

				// Navigation arrows
				navigation: {
					nextEl: ".history__swiper .swiper-button-next",
					prevEl: ".history__swiper .swiper-button-prev",
				},
				on: {
					init: function (swiper) {
						
						resetTimelineAni();
						currentHistoryIdx = 0;
						setTimeout(()=>{
							autoPlayHistory(currentHistoryIdx);
						},1000);
					},
					transitionStart: function(swiper) {
						// console.log("transitionStart");
						resetTimelineAni();
					},
					slideChangeTransitionStart: function(swiper){
						// console.log("slideChangeTransitionStart");
						timelineAni();
					},
				},
				breakpoints: { 
					992: {
						autoplay: false,
						centeredSlides: false,
						spaceBetween: 0,
						speed: 500,
						loop: false,
						slidesPerView: "auto",
						allowTouchMove: false,
						watchSlidesProgress: true,
						virtualTranslate: true,
						watchSlidesVisibility: true,
					}
				},

			});
			// 解決 slidesPerView: "auto" 無法準確抓到最後一個的問題
			swiper_history.snapGrid = swiper_history.slidesGrid.slice(0);
			swiper_history.slideTo(0, 0)
		});
	}

	function autoPlayHistory(idx) {
		swiper_history.slideTo(idx, 0)
		if(!isMobile) {
			if(historySlideTl) {
				clearInterval(historySlideTl);
			}
			historySlideTl = setInterval(()=>{
				if(idx < ($(".history .swiper-slide").length-1)) {
					idx+=1;
					swiper_history.slideTo(idx, 0);
				}
				else {
					idx = 0
					swiper_history.slideTo(idx, 0);
				}
				// console.log("idx: "+idx)
			}, 10000);

		}
	}

	function resetTimelineAni() {
		if($(window).width() > 992) {
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__item", { top:"4.8em", width: "13.5em" })
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__year", { top: "-2.5em", left: "-3.3em", width: "7em" })
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__year h3", { fontSize: "1.7em" }, 0)
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__branchline", { autoAlpha: 0, height: 0 }, 0)
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__desc", { autoAlpha: 0, y: "1em" }, 0)
		}else {
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__item", { top:"8.09em", width: "16em" })
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__year", { top: "-4em", left: "-3.8em", width: "9em" })
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__year h3", { fontSize: "2.1em" }, 0)
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__branchline", { autoAlpha: 0, height: 0 }, 0)
			gsap.set(".swiper-slide:not(.swiper-slide-active) .history__timeline__desc", { autoAlpha: 0, y: "1em" }, 0)
		}

	}

	function timelineAni() {
		if(activeTimelineTl) {
			activeTimelineTl.kill();
			animation = null;
		}
		if($(window).width() > 992) {
			activeTimelineTl = gsap.timeline();
			activeTimelineTl.to(".swiper-slide-active .history__timeline__item", { duration: 0.3, width: "22em" })
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year", { duration: 0.3, left: "1.1em", width: "9.5em" }, 0)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__item", { duration: 0.3, top:0 })
			activeTimelineTl.to(".swiper-slide-active .history__timeline__branchline", { duration: 0.5, height: "7.5em", autoAlpha: 1 }, 0.3)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year", { duration: 0.3, top: "-1.5em" }, 0.3)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year h3", { duration: 0.3, fontSize: "2.4em" }, "-=0.4")
			activeTimelineTl.to(".swiper-slide-active .history__timeline__desc", { duration: 0.3, autoAlpha: 1, y: 0 }, "-=0.1")
		}else {
			activeTimelineTl = gsap.timeline();
			activeTimelineTl.to(".swiper-slide-active .history__timeline__item", { duration: 0.3, width: "31em" })
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year", { duration: 0.3, left: "2em", width: "13.5em" }, 0)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__item", { duration: 0.3, top:0 })
			activeTimelineTl.to(".swiper-slide-active .history__timeline__branchline", { duration: 0.5, height: "11.5em", autoAlpha: 1 }, 0.3)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year", { duration: 0.3, top: "-1.8em" }, 0.3)
			activeTimelineTl.to(".swiper-slide-active .history__timeline__year h3", { duration: 0.3, fontSize: "3.4em" }, "-=0.4")
			activeTimelineTl.to(".swiper-slide-active .history__timeline__desc", { duration: 0.3, autoAlpha: 1, y: 0 }, "-=0.1")
		}
		
	}

	// ====================  滑動動態  ====================

	function startAni() {
		// gsap.to(".kv__pic", { duration: 0.5, scale:1 });
		gsap.to(".kv__copywriting", {
			duration: 0.5,
			x: 0,
			autoAlpha: 1,
			delay: 0.3,
		});
	}

	function elementAni() {
		gsap.registerPlugin(ScrollTrigger);

		ScrollTrigger.defaults({
			toggleActions: "restart pause resume pause",
			scroller: "body",
		});

		function qaItemAni($el) {
			gsap.to($el, {
				scrollTrigger: {
					trigger: $el,
					start: "top bottom-=20%", // when the top of the trigger hits the top of the viewport
					end: "+=" + $($el).height() / 2, // end after scrolling 500px beyond the start
					scrub: 1, // smooth scrubbing, takes 1 second to "catch up" to the scrollbar
					// markers: true
				},
				duration: 1,
				y: 0,
				autoAlpha: 1,
			});
		}

		qaItemAni(".qa__item-keypoints");
		qaItemAni(".qa__item-group");
		qaItemAni(".qa__item-positive");
		qaItemAni(".qa__item-child");

		gsap.to(".brandvideo .mainvideo__video__frame", {
			scrollTrigger: {
				trigger: ".mainvideo .bg",
				start: "top center",
				end: "+=" + $(".mainvideo__video__frame").height(),
				scrub: 1,
			},
			duration: 1,
			scale: 1,
			autoAlpha: 1,
		});

		gsap.to(".propagandavideo-pc", {
			scrollTrigger: {
				trigger: ".propagandavideo-pc",
				start: "top center",
				end: "+=" + $(".propagandavideo-pc").height() / 3,
				scrub: 1,
			},
			duration: 0.5,
			autoAlpha: 1,
			y: 0,
		});

		gsap.to(".process__pic", {
			scrollTrigger: {
				trigger: ".process .bg",
				start: "top center",
				end: "+=" + $(".process__pic").height(),
				scrub: 1,
			},
			duration: 0.5,
			autoAlpha: 1,
		});

		gsap.to(".game__head", {
			scrollTrigger: {
				trigger: ".game",
				start: "top center",
				end: "+=" + $(".game__head").height(),
				scrub: 1,
			},
			duration: 0.3,
			scale: 1,
			autoAlpha: 1,
			y: 0,
		});

		gsap.to(".game__place", {
			scrollTrigger: {
				trigger: ".game",
				start: "top center",
				end: "+=" + $(".game__head").height(),
				scrub: 1,
			},
			duration: 0.3,
			scale: 1,
			autoAlpha: 1,
			y: 0,
			delay: 0.2,
		});
	}

	function scrollToSection() {
		$(".header__nav__item").on("click", function (e) {
			e.preventDefault();
			let anchor  =  $(this).data("anchor");

			let target = "#" + anchor;
			console.log("target: " + target);

			$(".header__nav__item").removeClass("active");
			$(".header__nav__item-"+anchor).addClass("active");

			$("html, body").animate({
				scrollTop: $(target).offset().top - $(".header").outerHeight() - 50,
			});

			if (windowWidth < 992) {
				closeMenu();
			}
		});
	}

	// 偵測滾動到哪一個section
	function detectScrollSection() {

			const scrollPosition = !isMobile ? $(window).scrollTop() + headerH : $(window).scrollTop();
			const windowH = $(window).height();
			const bodyH = $("body").height();
			let tempId = null;
			let isBlankSpace = true;

			// console.log("windowH: "+windowH);
			// console.log("bodyH: "+bodyH);
			// console.log("scrollPosition: "+scrollPosition);
			// console.log("headerH: "+headerH);

		if(scrollPosition < (bodyH - windowH)) {
			section.each(function(idx, section) {
				const sectionTop = $(section).offset().top;
				const sectionBottom = sectionTop + $(section).height();
				const sectionH = $(section).outerHeight();
				let tempBlankSpace = (windowH - sectionH) / 2
				if(tempBlankSpace < 0 && !isMobile) {
					isBlankSpace = false
				}

				if(isMobile) {
					isBlankSpace = false
				}

				let blankSpace = isBlankSpace ? tempBlankSpace : headerH;
				// console.log("tempBlankSpace: "+tempBlankSpace)
				// console.log("isBlankSpace: "+isBlankSpace)
				// console.log("blankSpace: "+blankSpace)

				
				if(scrollPosition >= (sectionTop - blankSpace) && scrollPosition < (sectionBottom - blankSpace))  {
					// console.log("blankSpace: "+blankSpace)
					tempId = section.id;
					if(tempId === "history") {
						tempId = "understand";
					}
					if(currentId !== tempId) {
						currentId = tempId;
						console.log("focus: "+currentId);
						$(".header__nav__item").removeClass("active");
						$(".header__nav__item-"+currentId).addClass("active");
					}
				}
				

			});

		}else {
			tempId = "moreref";
			if(currentId !== tempId) {
				currentId = tempId;
				console.log("focus: "+currentId);
				$(".header__nav__item").removeClass("active");
				$(".header__nav__item-"+currentId).addClass("active");
			}
		}

		
	}

	{
		$(document).ready(function () {
			init();
		});
	}

	//public
	return {
	};
};

var main = new main();
