// 動畫
AOS.init({
  once: true
});

// SweetAlert 彈窗簡化函式
function showAlert(title, callback) {
  Swal.fire({
    title: title,
    confirmButtonText: '確認',
    confirmButtonColor: "#293591",
    timer: 2000,
    timerProgressBar: true,
    customClass: {
      title: 'lightbox-title',
      closeButton: 'lightbox-close',
      container: 'lightbox-alert',
      actions: 'alert-btn-wrap',
      confirmButton: "alert-btn alert-btn-filled alert-btn-rounded",
    },
    willClose: () => {
      if (typeof callback === 'function') callback();
    }
  });
}

// 全域阻擋 SweetAlert 內的 Tab 鍵切換
document.addEventListener('keydown', function (e) {
  if (e.key === 'Tab' && document.body.classList.contains('swal2-shown')) {
    e.preventDefault();
  }
});

// 首頁進站警語
document.addEventListener("DOMContentLoaded", function () {
  const isHome = document.body.classList.contains("page-air-quality");
  if (!isHome) return;

  const disclaimerKey = 'airQualityDisclaimerSeen';
  if (localStorage.getItem(disclaimerKey)) return;

  Swal.fire({
    width: '800px',
    title: '環境部官方授權網站聲明',
    html: '您即將進入的網站是由環境部委託鴻廣傳播專業有限公司建置與維護之官方專區。<br>本網站旨在提供全民空品通識課之相關資訊與服務，請安心瀏覽。<br>',
    confirmButtonText: '我已了解，進入網站',
    confirmButtonColor: "#293591",
    timer: 15000,
    timerProgressBar: true,
    allowOutsideClick: false,
    focusConfirm: false,
    allowEnterKey: false,
    allowEscapeKey: false,
    customClass: {
      title: 'lightbox-title',
      confirmButton: 'alert-btn alert-btn-filled alert-btn-rounded alert-btn-wide',
    },
  }).then(() => {
    localStorage.setItem(disclaimerKey, '1');
  });
});

// 登出檢查
if (window.location.search.includes('logout=true')) {
  showAlert('登出成功', () => {
    window.location.href = '/';
  });
}

// 網址有token檢查
if (window.location.search.includes('token')) {
  const urlParams = new URLSearchParams(window.location.search);
  const tokenFromUrl = urlParams.get('token');
  const resetTokenInput = document.getElementById("reset-token");
  if (resetTokenInput) {
    resetTokenInput.value = tokenFromUrl;
  }
  openModal('resetPassword');
}

// header 控制
window.addEventListener("scroll", function scrollFunction() {
  // let totop = document.querySelector('.top');
  const header = document.querySelector("header");
  const socialToolbar = document.querySelector(".social-toolbar");
  let scrollTop = document.documentElement.scrollTop;
  const scrollY = window.scrollY || window.pageYOffset;
  const triggerHeight = 200;

  if (scrollY > triggerHeight) {
    header.classList.add("scroll-down");
    socialToolbar.classList.add("scroll-down");
  } else {
    header.classList.remove("scroll-down");
    socialToolbar.classList.remove("scroll-down");
  }

}, false);

// 桌機固定 header 高度補償
document.addEventListener("DOMContentLoaded", function () {
  const header = document.querySelector(".site-header");
  if (!header) return;

  const mqDesktop = window.matchMedia("(min-width: 992px)");

  const applyHeaderOffset = () => {
    if (mqDesktop.matches) {
      const h = header.offsetHeight;
      document.documentElement.style.setProperty('--header-height', `${h}px`);
      document.body.classList.add('has-fixed-header');
      header.style.backgroundColor = '#fff9f0';
    } else {
      document.documentElement.style.removeProperty('--header-height');
      document.body.classList.remove('has-fixed-header');
      header.style.backgroundColor = '';
    }
  };

  applyHeaderOffset();
  window.addEventListener("resize", applyHeaderOffset);
});

// 回到頂端
document.addEventListener("DOMContentLoaded", function () {
  const goTopBtn = document.querySelector(".go-top");

  if (goTopBtn) {
    goTopBtn.addEventListener("click", function (e) {
      e.preventDefault();
      window.scrollTo({
        top: 0,
        behavior: "smooth"
      });
    });
  }
});

// 首頁 swiper

const swiper = new Swiper('.hero-section_swiper', {
  // Optional parameters
  loop: true,

  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
  },
});

const courseSwiper = new Swiper('.course_swiper', {
  enabled: false,
  slidesPerView: 4,
  spaceBetween: 25,
  pagination: {
    el: '.swiper-pagination',
  },
  breakpoints: {
    992: {
      // 768 以上才啟用 Swiper
      enabled: true,
    }
  }
});

// mobile menu toggle

function menuBtnFunction(menuBtn, type) {
  if (type == 'menu') {
    menuBtn.classList.toggle("active");
    document.querySelector('body').classList.toggle("freeze");
    document.querySelector('.mobile-menu').classList.toggle("expand");
  } else {
    menuBtn.classList.toggle("active");
  }
}

/* =========================================================
    Modal 開啟 / 關閉
 ========================================================= */

const openBtns = document.querySelectorAll("[data-modal]");

function openModal(id) {
  // console.log(id)
  const modal = document.getElementById(id);
  if (!modal) return;

  modal.classList.add("active");
  document.body.classList.add("freeze");

  const mask = modal.querySelector(".modal-mask");
  const closeBtn = modal.querySelector(".btn-close");

  mask?.addEventListener("click", () => closeModal(id));
  closeBtn?.addEventListener("click", () => closeModal(id));

  // 如果是重設密碼 modal，檢查 URL 參數中的 token
  if (id === 'resetPassword') {
    const urlParams = new URLSearchParams(window.location.search);
    const tokenFromUrl = urlParams.get('token');
    const resetTokenInput = document.getElementById("reset-token");

    if (tokenFromUrl && resetTokenInput) {
      resetTokenInput.value = tokenFromUrl;
      // 清除 URL 中的 token 參數（可選，保持 URL 乾淨）
      // window.history.replaceState({}, document.title, window.location.pathname);
    }
  }
}

function closeModal(id) {
  const modal = document.getElementById(id);
  if (!modal) return;

  modal.classList.remove("active");
  document.body.classList.remove("freeze");

  // 如果是重設密碼 modal，清空 token
  if (id === 'resetPassword') {
    const resetTokenInput = document.getElementById("reset-token");
    if (resetTokenInput) {
      resetTokenInput.value = '';
    }
    // 清空表單
    const resetForm = document.querySelector(".reset-password-form");
    if (resetForm) {
      resetForm.reset();
    }
    // 重新導向到首頁
    window.location.href = '/';
  }
}

openBtns.forEach(btn => {
  btn.addEventListener("click", (e) => {
    e.preventDefault();
    const id = btn.dataset.modal;
    openModal(id);
  });
});

// 手機版本登入／註冊切換
const panerBtns = document.querySelectorAll("[data-panelname]");
panerBtns.forEach(btn => {
  btn.addEventListener("click", (e) => {
    e.preventDefault();
    const panel = btn.dataset.panelname;
    if (panel == 'signin') {
      document.querySelector("[data-modal-panel='signin']").classList.remove('hide')
      document.querySelector("[data-modal-panel='signup']").classList.remove('show')
      // console.log('2')
    }
    if (panel == 'signup') {
      document.querySelector("[data-modal-panel='signin']").classList.add('hide')
      document.querySelector("[data-modal-panel='signup']").classList.add('show')
      // console.log('3')

    }
  });
});


//  忘記密碼
const forgotTrigger = document.querySelector('#signup .modal-action a.text-button[href="#"]');
const forgotModal = document.getElementById('forgotPassword');
const signupModal = document.getElementById('signup');

if (forgotTrigger && forgotModal) {
  forgotTrigger.addEventListener('click', function (e) {
    e.preventDefault();

    // 1. 先關掉原本的登入 / 註冊彈窗
    if (typeof closeModal === 'function') {
      closeModal('signup');              // 若你有共用 closeModal，就用它
    } else if (signupModal) {
      signupModal.classList.remove('active');
      // body.no-scroll 先不要動，待會會再打開忘記密碼，保持鎖卷軸
    }

    // 2. 再開啟忘記密碼彈窗
    if (typeof openModal === 'function') {
      openModal('forgotPassword');
      generateForgotCaptcha();
    } else {
      forgotModal.classList.add('active');
      document.body.classList.add('no-scroll');
    }
  });
}

// 忘記密碼用的驗證碼（隨機算式 + 隨機底色 / 字色）
function generateForgotCaptcha() {
  const box = document.getElementById("forgetCaptcha");
  if (!box) return;

  // 隨機產生兩個 1~9 的數字
  const a = Math.floor(Math.random() * 20) + 1;
  const b = Math.floor(Math.random() * 20) + 1;

  // 算式顯示文字，例如「3 + 2」
  const text = `${a} + ${b}`;

  // 深色底色（hsl 形式）
  const hue = Math.floor(Math.random() * 360);
  const bgColor = `hsl(${hue}, 20%, 25%)`;

  // 亮色文字（跟背景有對比）
  const textColor = `hsl(${(hue + 180) % 360}, 80%, 85%)`;

  box.textContent = text;
  box.style.backgroundColor = bgColor;
  box.style.color = textColor;

  // 如果你之後要驗證，可以把答案存到 data 屬性
  box.dataset.answer = (a + b).toString();

  // 存到 captchaAnswer
  const captchaAnswer = document.getElementById("captchaAnswer");
  if (captchaAnswer) {
    captchaAnswer.value = (a + b).toString();
  }
}

const refreshBtn = document.querySelector("#forgotPassword .refresh-btn");
if (refreshBtn) {
  refreshBtn.addEventListener("click", function () {
    generateForgotCaptcha();
  });
}

/* =========================================================
   忘記密碼表單驗證
========================================================= */

const forgotPasswordForm = document.querySelector(".forgot-password-form");

if (forgotPasswordForm) {
  forgotPasswordForm.addEventListener("submit", function (e) {
    e.preventDefault();

    const email = document.getElementById("forget-email");
    const captchaCode = document.getElementById("forget-code");
    const captchaAnswer = document.getElementById("captchaAnswer");

    let isValid = true;

    clearError(email);
    clearError(captchaCode);

    // email 驗證
    if (!email.value.trim()) {
      showError(email, "請輸入電子信箱");
      isValid = false;
    } else if (!/\S+@\S+\.\S+/.test(email.value)) {
      showError(email, "電子信箱格式不正確");
      isValid = false;
    }

    // 驗證碼驗證
    if (!captchaCode.value.trim()) {
      showError(captchaCode, "請輸入驗證碼");
      isValid = false;
    } else if (captchaCode.value.trim() !== captchaAnswer.value) {
      showError(captchaCode, "驗證碼不正確");
      isValid = false;
    }

    if (isValid) {
      // 取得提交按鈕並更新狀態
      const submitBtn = forgotPasswordForm.querySelector('button[type="submit"]');
      const originalText = submitBtn ? submitBtn.textContent : '';

      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.classList.add('loading');
        submitBtn.style.pointerEvents = 'none';
        submitBtn.style.cursor = 'not-allowed';
        submitBtn.textContent = '重設密碼連結發送中';
      }

      // API 呼叫
      const formData = new FormData(forgotPasswordForm);

      fetch('./_data/member_ForgetPassword.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          // 恢復按鈕狀態
          if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.classList.remove('loading');
            submitBtn.style.pointerEvents = '';
            submitBtn.style.cursor = '';
            submitBtn.textContent = originalText;
          }

          if (data.ErrorCode === 0) {
            // 清空忘記密碼表單
            forgotPasswordForm.reset();
            generateForgotCaptcha();
            closeModal('forgotPassword');
            showAlert(data.msg, () => {
              window.location.href = '/';
            });
          } else {
            showAlert(data.msg);
          }
        })
        .catch(err => {
          // 恢復按鈕狀態
          if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.classList.remove('loading');
            submitBtn.style.pointerEvents = '';
            submitBtn.style.cursor = '';
            submitBtn.textContent = originalText;
          }
          // console.error(err);
          showAlert('系統錯誤，請稍後再試');
        });
    }
  });
}

/* =========================================================
   Utils：建立錯誤訊息
========================================================= */

function showError(inputEl, message) {
  clearError(inputEl);

  const errorEl = document.createElement("div");
  errorEl.className = "error-msg";
  errorEl.textContent = message;
  inputEl.classList.add("is-error");

  inputEl.parentElement.appendChild(errorEl);
}

function clearError(inputEl) {
  inputEl.classList.remove("is-error");
  const existing = inputEl.parentElement.querySelector(".error-msg");
  if (existing) existing.remove();
}



/* =========================================================
   登入表單驗證
========================================================= */

const loginForm = document.querySelector(".login-form");
if (loginForm) {
  loginForm.addEventListener("submit", function (e) {
    e.preventDefault();

    const email = document.getElementById("login-email");
    const pwd = document.getElementById("login-password");

    let isValid = true;

    clearError(email);
    clearError(pwd);

    if (!email.value.trim()) {
      showError(email, "請輸入電子信箱");
      isValid = false;
    } else if (!/\S+@\S+\.\S+/.test(email.value)) {
      showError(email, "電子信箱格式不正確");
      isValid = false;
    }

    if (!pwd.value.trim()) {
      showError(pwd, "請輸入密碼");
      isValid = false;
    }

    if (isValid) {
      // API 呼叫
      const formData = new FormData(loginForm);

      fetch('./_data/member _Login.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          if (data.ErrorCode === 0) {
            // 清空表單
            loginForm.reset();
            // 先關閉 modal
            closeModal('signup');
            // 顯示成功訊息
            showAlert(data.msg, () => {
              if (data.rego === 'reload') {
                window.location.reload();
              }
            });
          } else {
            showAlert(data.msg);
          }
        })
        .catch(err => {
          console.error(err);
          showAlert('系統錯誤，請稍後再試');
        });
    }
  });
}





/* =========================================================
   註冊表單驗證
========================================================= */

const registerForm = document.querySelector(".register-form");

if (registerForm) {
  registerForm.addEventListener("submit", function (e) {
    e.preventDefault();
    // console.log('ssss')

    const email = document.getElementById("reg-email");
    const pwd = document.getElementById("reg-password");
    const name = document.getElementById("reg-name");
    const gender = document.getElementById("reg-gender");
    const age = document.getElementById("reg-age");
    const nationalId = document.getElementById("reg-id");
    const phone = document.getElementById("reg-phone");
    const passcheck = document.getElementById("reg-password-confirm");

    let isValid = true;

    [email, pwd, name, gender, age, nationalId, phone, passcheck].forEach(clearError);

    // email
    if (!email.value.trim()) {
      showError(email, "請輸入電子信箱");
      isValid = false;
    } else if (!/\S+@\S+\.\S+/.test(email.value)) {
      showError(email, "電子信箱格式不正確");
      isValid = false;
    }

    // password
    if (!pwd.value.trim()) {
      showError(pwd, "請輸入密碼");
      isValid = false;
    }

    // passcheck
    if (!passcheck.value.trim()) {
      showError(passcheck, "請輸入確認密碼");
      isValid = false;
    }

    if (pwd.value != passcheck.value) {
      showError(passcheck, "密碼不一致");
      isValid = false;
    }

    if (pwd.value.length < 8 || !/[a-zA-Z]/.test(pwd.value) || !/[0-9]/.test(pwd.value)) {
      showAlert('密碼長度必須大於8位數且包含英文和數字');
      isValid = false;
    }

    // name
    if (!name.value.trim()) {
      showError(name, "請輸入姓名");
      isValid = false;
    }

    // gender
    if (!gender.value) {
      showError(gender, "請選擇性別");
      isValid = false;
    }

    // age
    const ageValue = parseInt(age.value, 10);
    if (!age.value.trim()) {
      showError(age, "請輸入年齡");
      isValid = false;
    } else if (isNaN(ageValue) || ageValue < 1 || ageValue > 120) {
      showError(age, "年齡需介於 1~120");
      isValid = false;
    }

    // national ID：第一個字母 + 9 位數字
    if (!nationalId.value.trim()) {
      showError(nationalId, "請輸入身分證字號");
      isValid = false;
    } else {
      const normalizedId = nationalId.value.trim().toUpperCase();
      nationalId.value = normalizedId;
      if (!/^[A-Z][0-9]{9}$/.test(normalizedId)) {
        showError(nationalId, "身分證字號格式不正確，需英文字母+9位數字");
        isValid = false;
      }
    }

    // phone（簡單版，只檢查 10 碼手機）
    if (!phone.value.trim()) {
      showError(phone, "請輸入手機");
      isValid = false;
    } else if (!/^09\d{8}$/.test(phone.value)) {
      showError(phone, "手機格式不正確");
      isValid = false;
    }

    if (isValid) {
      // API 呼叫
      const formData = new FormData(registerForm);

      fetch('./_data/member_Register.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          if (data.ErrorCode === 0) {
            // 清空表單
            registerForm.reset();
            // 先關閉 modal
            closeModal('signup');
            // 顯示成功訊息
            showAlert(data.msg, () => {
              if (data.rego === 'reload') {
                window.location.reload();
              }
            });
          } else {
            showAlert(data.msg);
          }
        })
        .catch(err => {
          // console.error(err);
          showAlert('系統錯誤，請稍後再試');
        });
    }
  });
}


/* =========================================================
   重設密碼表單驗證
========================================================= */

const resetPasswordForm = document.querySelector(".reset-password-form");

if (resetPasswordForm) {
  resetPasswordForm.addEventListener("submit", function (e) {
    e.preventDefault();

    const newPassword = document.getElementById("reset-password");
    const confirmPassword = document.getElementById("reset-password-confirm");
    const resetToken = document.getElementById("reset-token");

    let isValid = true;

    clearError(newPassword);
    clearError(confirmPassword);

    // 新密碼驗證
    if (!newPassword.value.trim()) {
      showError(newPassword, "請輸入新密碼");
      isValid = false;
    } else if (newPassword.value.length < 8 || !/[a-zA-Z]/.test(newPassword.value) || !/[0-9]/.test(newPassword.value)) {
      showError(newPassword, "密碼長度必須大於8位數且包含英文和數字");
      isValid = false;
    }

    // 確認密碼驗證
    if (!confirmPassword.value.trim()) {
      showError(confirmPassword, "請輸入確認密碼");
      isValid = false;
    } else if (newPassword.value !== confirmPassword.value) {
      showError(confirmPassword, "密碼不一致");
      isValid = false;
    }

    // 檢查是否有 token（從 hidden input 或 URL 參數取得）
    if (!resetToken.value) {
      const urlParams = new URLSearchParams(window.location.search);
      const tokenFromUrl = urlParams.get('token');

      if (tokenFromUrl) {
        resetToken.value = tokenFromUrl;
      } else {
        // 如果沒有 token，提示用戶重新申請
        showAlert('缺少重設密碼驗證碼，請重新申請');
        isValid = false;
      }
    }

    if (isValid) {
      // API 呼叫
      const formData = new FormData();
      formData.append('reset_token', resetToken.value);
      formData.append('reset_new_password', newPassword.value);
      formData.append('reset_confirm_password', confirmPassword.value);

      fetch('./_data/member_ResetPassword.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          if (data.ErrorCode === 0) {
            showAlert(data.msg, () => {
              window.location.href = '/';
            });
          } else {
            if (data.ErrorCode === 99) {
              showAlert(data.msg, () => {
                window.location.href = '/';
              });
            } else {
              showAlert(data.msg);
            }
          }
        })
        .catch(err => {
          // console.error(err);
          showAlert('系統錯誤，請稍後再試');
        });
    }
  });
}

/* =========================================================
   知識挑戰頁
========================================================= */

let quizPage = document.querySelector('.challenge-page');
if (quizPage) {


  // 1. 修改圖片路徑設定：將正確與錯誤的熊改成「陣列 (Array)」格式
  const IMG_SRC = {
    // 正確白熊：放入兩款圖片路徑
    bear_white: [
      './src/quiz/correct01.png',
      './src/quiz/correct02.png'
    ],
    // 錯誤黑熊：放入兩款圖片路徑
    bear_black: [
      './src/quiz/wrong01.png',
      './src/quiz/wrong02.png'
    ],
  };

  const quizData = [
    {
      q: "依據《空氣污染防制法》規定，某事業單位為規避高額防制成本，故意將連續排放監測數據偽造不實以規避管制。此行為最根本違反了企業的哪一項核心責任？",
      options: [
        "僅違反勞工權益保障",
        "屬於正常的產業機密保護",
        "違反環境保護義務，同時背離「誠實申報、不欺瞞主管機關」之企業誠信原則", // 正確
        "只要空氣品質未明顯惡化，就不構成違法"
      ],
      ans: 2
    }
  ];

  // 自動生成 49 題假資料
  for (let i = 1; i < 50; i++) { // 這裡我改回 50 讓邏輯完整
    quizData.push({
      q: `[測試題目 ${i + 1}] 這裡會顯示第 ${i + 1} 題的題目內容。題目可能會很長，測試一下換行效果。`,
      options: [`測試選項 ${i + 1}A`, `測試選項 ${i + 1}B (正確)`, `測試選項 ${i + 1}C`, `測試選項 ${i + 1}D`],
      ans: 1
    });
  }

  let currentIdx = 0;
  let score = 0;
  let isLocked = false;

  function initQuiz() {
    renderQuestion();
  }

  function renderQuestion() {
    isLocked = false;
    const data = quizData[currentIdx];

    // 更新 UI
    document.getElementById('current-step').innerText = (currentIdx + 1).toString().padStart(2, '0');
    document.getElementById('question-text').innerText = data.q;

    // 渲染選項文字
    const list = document.getElementById('options-text-list');
    list.innerHTML = data.options.map((opt, i) => `<li> ${opt}</li>`).join('');
    // list.innerHTML = data.options.map((opt, i) => `<li>(${i + 1}) ${opt}</li>`).join('');

    // 渲染按鈕
    const btns = document.getElementById('btns-container');
    btns.innerHTML = '';
    data.options.forEach((_, i) => {
      const btn = document.createElement('button');
      btn.className = 'option-btn';
      btn.innerText = i + 1;
      btn.onclick = () => handleSelect(i, data.ans, btn);
      btns.appendChild(btn);
    });

    // 隱藏熊
    document.getElementById('bear-display').classList.remove('active');
  }

  // 2. 修改答題邏輯：加入隨機選取功能
  function handleSelect(idx, correctAns, btnEl) {
    if (isLocked) return;
    isLocked = true;

    const isCorrect = idx === correctAns;
    const bearImg = document.getElementById('bear-display');

    if (isCorrect) {
      score++;
      btnEl.classList.add('correct');

      // 隨機邏輯：Math.random() 會產生 0~1 之間的數，乘上長度(2)再無條件捨去，會得到 0 或 1
      const randomIdx = Math.floor(Math.random() * IMG_SRC.bear_white.length);
      bearImg.src = IMG_SRC.bear_white[randomIdx]; // 隨機顯示其中一款白熊

    } else {
      btnEl.classList.add('wrong');

      // 隨機邏輯同上
      const randomIdx = Math.floor(Math.random() * IMG_SRC.bear_black.length);
      bearImg.src = IMG_SRC.bear_black[randomIdx]; // 隨機顯示其中一款黑熊
    }

    bearImg.classList.add('active');

    // 模擬儲存
    console.log(`Progress saved: ${score}/${currentIdx + 1}`);

    // 延遲下一題
    setTimeout(() => {
      currentIdx++;
      if (currentIdx < quizData.length) {
        renderQuestion();
      } else {
        showResult();
      }
    }, 1500);
  }

  function showResult() {
    const successDiv = document.getElementById('result-success');
    const failDiv = document.getElementById('result-fail');

    const isPass = score >= 35; // 通過門檻

    // 先將兩個都隱藏 (Reset)
    successDiv.style.display = 'none';
    failDiv.style.display = 'none';

    // 根據結果顯示對應的 Div
    if (isPass) {
      successDiv.style.display = 'block';
    } else {
      failDiv.style.display = 'block';
    }

    // 顯示遮罩
    openModal('quizResult');
  }
  // 啟動
  initQuiz();
}
/* =========================================================
   課程總覽隨機排序
========================================================= */

document.addEventListener("DOMContentLoaded", function () {
  const wrap = document.querySelector('.courses-wrap');
  console.log('?')
  if (wrap) {
    // 1. 取得所有的 row
    const rows = Array.from(wrap.querySelectorAll('.courses-row'));

    // 2. 取得所有的卡片 (跨 row 全部抓出來)
    const allCards = Array.from(wrap.querySelectorAll('.course-card'));

    // 3. 記錄每一列原本有幾張卡片
    // 例如: [4, 3, 4] 代表第一列要放4張，第二列3張...
    const rowCapacities = rows.map(row => row.children.length);

    // 4. 洗牌演算法 (Fisher-Yates Shuffle)
    for (let i = allCards.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [allCards[i], allCards[j]] = [allCards[j], allCards[i]];
    }

    // 5. 依照原本的容量，把卡片填回去
    let cardIndex = 0;

    rows.forEach((row, rowIndex) => {
      // 清空該列目前的內容 (雖然後面 append 會自動移動，但清空較保險)
      // row.innerHTML = ''; 

      // 這一列原本有幾張？
      const capacity = rowCapacities[rowIndex];

      // 從洗好的牌堆中，拿取對應數量的卡片放進去
      for (let i = 0; i < capacity; i++) {
        if (allCards[cardIndex]) {
          row.appendChild(allCards[cardIndex]);
          cardIndex++;
        }
      }
    });

    // 6. 排完後，顯示畫面
    setTimeout(() => {
      wrap.classList.add('show');
    }, 100);
  }
});


/* =========================================================
   課程總覽隨機排序
========================================================= */
let videoWrap = document.querySelector('#my-vimeo-video');

if (videoWrap) {
  // 設定參數
  var options = {
    id: 183120214,      // 你的影片 ID
    width: 800,         // 影片寬度 (也會自適應容器)
    loop: false,        // 是否循環播放
    autoplay: false,    // 是否自動播放 (注意：瀏覽器通常需要靜音才能自動播放)
    muted: false,       // 是否靜音
    controls: true      // 是否顯示控制列
  };

  // 初始化播放器
  // 參數 1: 對應 HTML 的 ID ('my-vimeo-video')
  // 參數 2: 上面的 options 設定
  var player = new Vimeo.Player('my-vimeo-video', options);

  // --- 以下是 API 事件監聽範例 (選用) ---

  // 監聽：當影片準備好時
  player.on('loaded', function () {
    console.log('影片已載入完成');
  });

  // 監聽：當按下播放時
  player.on('play', function () {
    console.log('影片開始播放');
  });

  // 監聽：當影片結束時
  player.on('ended', function () {
    console.log('影片播放結束');
    alert('影片看完了！');
  });

  // 也可以透過程式碼控制 (例如 5秒後自動暫停)
  /*
  setTimeout(function() {
      player.pause().then(function() {
          console.log('已自動暫停');
      });
  }, 5000);
  */


  // 課程章節開關
  const toggles = document.querySelectorAll(".menu-toggle-button");

  toggles.forEach(toggle => {
    toggle.addEventListener("click", function (e) {
      e.preventDefault(); // 防止 button 預設行為

      // 找到按鈕所在的父層 li
      const parentItem = this.closest(".course-menu-item");

      // 切換 active class
      parentItem.classList.toggle("active");
    });
  });

}
//課程選單開關
let toggleCourseMenu = function () {
  const courseMenu = document.getElementById("courseMenu");

  courseMenu.classList.toggle("collapsed");
}



let searchHours = document.querySelector('.learning-content');

if (searchHours) {
  // 課程章節開關
  const toggles = document.querySelectorAll(".menu-toggle-button");

  toggles.forEach(toggle => {
    toggle.addEventListener("click", function (e) {
      e.preventDefault(); // 防止 button 預設行為

      // 找到按鈕所在的父層 li
      const parentItem = this.closest(".course-menu-item");

      // 切換 active class
      parentItem.classList.toggle("active");
    });
  });
}






