/*
// 功能：首页脚本文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。
*/

// 默认头像和缩略图路径常量由PHP通过全局变量提供
// 确保PHP在页面加载时定义了全局变量 DEFAULT_AVATAR_PATH 和 DEFAULT_THUMBNAIL_PATH
// 如果全局变量未定义，提供一个默认值作为后备方案
if (typeof window.DEFAULT_AVATAR_PATH === 'undefined') {
  window.DEFAULT_AVATAR_PATH = '/assets/images/avatar.png';
}

if (typeof window.DEFAULT_THUMBNAIL_PATH === 'undefined') {
  window.DEFAULT_THUMBNAIL_PATH = '/assets/images/moren.jpg';
}

function checkLoginStatus() {
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.has('login_success')) {
    document.body.classList.add('logged-in');
    localStorage.setItem('qkcms_logged_in', 'true');
    return true;
  }

  if (localStorage.getItem('qkcms_logged_in') === 'true') {
    return true;
  }

  return false;
}


function addSidebarPostButton(userActions) {
  if (!userActions || userActions.querySelector('.sidebar-post-btn')) {
    return userActions?.querySelector('.sidebar-post-btn');
  }

  const template = document.getElementById('user-actions-template');
  if (!template) return null;
  const postBtn = template.querySelector('.sidebar-post-btn').cloneNode(true);
  userActions.appendChild(postBtn);
  return postBtn;
}


function updateSidebarButtons(isLoggedIn) {
  const userActions = cacheElement('.user-actions', 'userActions');
  if (!userActions) return;

  if (!DOM_ELEMENTS.sidebarPostBtn) {
    DOM_ELEMENTS.sidebarPostBtn = userActions.querySelector('.sidebar-post-btn') ||
      addSidebarPostButton(userActions);
  }
  let postBtn = DOM_ELEMENTS.sidebarPostBtn;

  if (!DOM_ELEMENTS.sidebarLoginBtn) {
    DOM_ELEMENTS.sidebarLoginBtn = userActions.querySelector('a[href="/admin/login.php"].btn-primary');
  }
  if (!DOM_ELEMENTS.sidebarRegisterBtn) {
    DOM_ELEMENTS.sidebarRegisterBtn = userActions.querySelector('a[href="/admin/login.php?register=1"].btn-outline');
  }
  const sidebarLoginBtn = DOM_ELEMENTS.sidebarLoginBtn;
  const sidebarRegisterBtn = DOM_ELEMENTS.sidebarRegisterBtn;

  if (isLoggedIn) {
    userActions.classList.add('is-logged');
    userActions.classList.remove('is-guest');
    if (sidebarLoginBtn) sidebarLoginBtn.style.display = 'none';
    if (sidebarRegisterBtn) sidebarRegisterBtn.style.display = 'none';
    if (postBtn) postBtn.style.display = 'inline-flex';
  } else {
    userActions.classList.add('is-guest');
    userActions.classList.remove('is-logged');
    if (sidebarLoginBtn) sidebarLoginBtn.style.display = 'inline-flex';
    if (sidebarRegisterBtn) sidebarRegisterBtn.style.display = 'inline-flex';
    if (postBtn) postBtn.style.display = 'none';
  }
}


function updateNavbarLoginStatus(isLoggedIn) {
  const navUserAvatar = document.getElementById('userAvatar');
  const loginRegisterButtons = document.querySelector('.login-register-buttons');
  const htmlRoot = document.documentElement;
  const normalizeAvatarUrl = (url) => {
    try {
      return new URL(url || '', window.location.origin).href;
    } catch (e) {
      return String(url || '');
    }
  };

  if (isLoggedIn) {
    htmlRoot.classList.add('qk-prelogged');
    document.body.classList.add('logged-in');
    if (navUserAvatar) {
      navUserAvatar.classList.add('has-user');
      const avatarImg = navUserAvatar.querySelector('img');
      const storedAvatar = localStorage.getItem('qkcms_user_avatar');
      if (avatarImg && storedAvatar) {
        const currentSrc = normalizeAvatarUrl(avatarImg.getAttribute('src'));
        const targetSrc = normalizeAvatarUrl(storedAvatar);
        if (!currentSrc || currentSrc !== targetSrc) {
          avatarImg.src = storedAvatar;
        }
      }
    }
    if (loginRegisterButtons) {
      loginRegisterButtons.classList.add('hidden');
    }
  } else {
    htmlRoot.classList.remove('qk-prelogged');
    document.body.classList.remove('logged-in');
    if (navUserAvatar) {
      navUserAvatar.classList.remove('has-user');
    }
    if (loginRegisterButtons) {
      loginRegisterButtons.classList.remove('hidden');
    }
  }
}

// 在DOM加载完成后立即执行登录状态检查，避免闪烁
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', function () {
    const isLoggedIn = checkLoginStatus();
    updateNavbarLoginStatus(isLoggedIn);
  });
} else {
  // DOM已经加载完成，立即执行
  const isLoggedIn = checkLoginStatus();
  updateNavbarLoginStatus(isLoggedIn);
}


function forceFullUIReset() {
  updateSidebarButtons(false);
  updateNavbarLoginStatus(false);

  const userRoleElement = document.querySelector('.user-role');
  // 获取当前登录用户的名称元素
  const userNameElement = document.querySelector('.user-name, .comment-user-name');
  // 获取所有可能的用户头像元素，只包括当前登录用户的头像，不影响评论列表
  const userAvatarElements = document.querySelectorAll('.user-avatar, .user-profile img, .qk-dropdown-avatar-img, .comment-user-avatar');

  if (userNameElement && !userNameElement.hasAttribute('data-synced')) {
    userNameElement.textContent = '未登录';
  }

  if (userRoleElement) {
    userRoleElement.innerHTML = '<span class="user-level"></span>欢迎你，请先登录';
  }

  // 重置所有找到的头像元素
  userAvatarElements.forEach(userAvatarElement => {
    try {
      userAvatarElement.onerror = null;
      userAvatarElement.onerror = function (e) {
        if (e && e.preventDefault) {
          e.preventDefault();
        }
        this.src = window.DEFAULT_AVATAR_PATH;
      };

      if (!userAvatarElement.src || userAvatarElement.src.indexOf('avatar.png') === -1) {
        userAvatarElement.src = window.DEFAULT_AVATAR_PATH;
      }
    } catch (e) {
      console.error('设置用户头像样式时出错:', e);
      userAvatarElement.src = window.DEFAULT_AVATAR_PATH;
    }
  });
}

const LOGIN_KEYS = ['qkcms_logged_in', 'qkcms_user_nickname', 'qkcms_user_id', 'qkcms_user_token'];


function checkLoginStatusAndUpdate() {
  const actualStatus = checkLoginStatus();
  if (actualStatus) {
    updateSidebarButtons(true);
    updateNavbarLoginStatus(true);
    return true;
  }

  const hasCompleteLoginData = localStorage.getItem('qkcms_logged_in') === 'true' &&
    localStorage.getItem('qkcms_user_nickname');

  if (!hasCompleteLoginData) {
    LOGIN_KEYS.forEach(key => localStorage.removeItem(key));
    document.body.classList.remove('logged-in');
    sessionStorage.removeItem('qkcms_logged_in');

    forceFullUIReset();
    localStorage.setItem('qkcms_logged_in', 'false');
    localStorage.removeItem('qkcms_logged_in');

    return false;
  }

  updateSidebarButtons(actualStatus);
  updateNavbarLoginStatus(actualStatus);

  return actualStatus;
}


function initNavbarUserMenu() {
  const userAvatar = document.getElementById('userAvatar');
  const userDropdownMenu = document.getElementById('userDropdownMenu');
  const logoutBtn = document.querySelector('.user-logout');

  if (!userAvatar || !userDropdownMenu) return;

  // 使用 onclick 确保唯一性，并防止事件冒泡导致的意外触发
  userAvatar.onclick = function (event) {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }
    userDropdownMenu.classList.toggle('show');
  };

  document.addEventListener('click', function (event) {
    if (userAvatar && !userAvatar.contains(event.target) && 
        userDropdownMenu && !userDropdownMenu.contains(event.target)) {
      userDropdownMenu.classList.remove('show');
    }
  });

  // 为下拉菜单中的链接添加点击事件处理，确保点击链接时不会隐藏下拉菜单
  const dropdownLinks = userDropdownMenu.querySelectorAll('a');
  dropdownLinks.forEach(link => {
    link.addEventListener('click', function (event) {
      // 阻止事件冒泡到document，避免触发隐藏下拉菜单的逻辑
      event.stopPropagation();
      // 链接会正常跳转，不需要额外处理
    });
  });

  // 为退出登录按钮添加点击事件处理，确保它能正常点击
  const logoutButton = userDropdownMenu.querySelector('.user-logout');
  if (logoutButton) {
    logoutButton.addEventListener('click', function (event) {
      // 阻止事件冒泡到document，避免触发隐藏下拉菜单的逻辑
      event.stopPropagation();
      // 退出登录按钮有自己的onclick处理，不需要额外处理
    });
  }

  if (logoutBtn) {
    logoutBtn.onclick = function (event) {
      if (event) event.preventDefault();
      userDropdownMenu.classList.remove('show');
      if (window.handleLogout) {
        window.handleLogout();
      }
    };
  }
}


function init() {
  const userActions = document.querySelector('.user-actions');
  if (userActions) {
    addSidebarPostButton(userActions);
  }

  initNavbarUserMenu();

  const isLoggedIn = checkLoginStatus();
  updateSidebarButtons(isLoggedIn);
  updateNavbarLoginStatus(isLoggedIn);
}

window.forceUpdateUI = function () {
  const isLoggedIn = checkLoginStatus();
  updateSidebarButtons(isLoggedIn);
  updateNavbarLoginStatus(isLoggedIn);
};

// 移除冗余的 storage 监听器，统一由 common.php 中的 LoginSync 处理信号
// 以避免多页面同步时产生 UI 冲突或自动弹出菜单
/*
window.addEventListener('storage', function (e) {
  if (e.key === 'qkcms_logged_in') {
    const newLoggedInState = e.newValue === 'true';

    if (newLoggedInState) {
      document.body.classList.add('logged-in');
    } else {
      document.body.classList.remove('logged-in');
    }

    updateSidebarButtons(newLoggedInState);
    updateNavbarLoginStatus(newLoggedInState);
  }
});
*/

const DOM_ELEMENTS = {
};

function cacheElement(selector, key) {
  if (!DOM_ELEMENTS[key]) {
    DOM_ELEMENTS[key] = document.querySelector(selector);
  }
  return DOM_ELEMENTS[key];
}

// 登录状态检查函数，避免频繁重置头像
function checkAndUpdateUIIfNeeded() {
  try {
    const actualStatus = checkLoginStatus();
    if (actualStatus) return;

    const hasCompleteLoginData = localStorage.getItem('qkcms_logged_in') === 'true' &&
      localStorage.getItem('qkcms_user_nickname');

    const userActions = cacheElement('.user-actions', 'userActions');
    if (!DOM_ELEMENTS.sidebarPostBtn && userActions) {
      DOM_ELEMENTS.sidebarPostBtn = userActions.querySelector('.sidebar-post-btn');
    }

    const isUIInLoggedInState = DOM_ELEMENTS.sidebarPostBtn &&
      DOM_ELEMENTS.sidebarPostBtn.style.display !== 'none';

    // 只在确实需要重置时才调用forceFullUIReset，避免频繁重置导致头像闪烁
    if (!hasCompleteLoginData && isUIInLoggedInState) {
      forceFullUIReset();
      if (window.forceUpdateUI) forceUpdateUI();
    }
  } catch (error) {
    console.error('UI检查更新出错:', error);
  }
}

// 设置定时器，降低检查频率并移除随机检查逻辑，避免头像频繁闪烁
setInterval(checkAndUpdateUIIfNeeded, 30000); // 改为30秒检查一次

// 保留页面可见性和焦点事件处理，但添加防抖逻辑
let lastUpdateTime = 0;
const MIN_UPDATE_INTERVAL = 5000; // 最小更新间隔5秒

function debouncedCheckLogin() {
  const now = Date.now();
  if (now - lastUpdateTime > MIN_UPDATE_INTERVAL) {
    lastUpdateTime = now;
    checkLoginStatusAndUpdate();
  }
}

// 替换原来的visibilitychange和focus事件监听器
document.addEventListener('visibilitychange', function () {
  if (!document.hidden) {
    debouncedCheckLogin();
  }
});

window.addEventListener('focus', debouncedCheckLogin);



function initPageLoader() {
  const progressBar = document.getElementById('page-loader-progress');
  if (!progressBar) return;

  let progress = 0;

  const getProgressIncrement = () => {
    if (progress < 20) return 0.3 + Math.random() * 0.7;
    if (progress < 70) return 0.8 + Math.random() * 1.2;
    return 0.4 + Math.random() * 0.6;
  };

  const updateProgress = function () {
    const increment = getProgressIncrement();
    progress = Math.min(progress + increment, 90);
    progressBar.style.width = progress + '%';

    if (progress < 90) requestAnimationFrame(updateProgress);
  };

  window.addEventListener('load', function () {
    const finishProgress = function () {
      const finalIncrement = 1 + Math.random() * 1;
      progress += finalIncrement;

      if (progress >= 100) {
        progress = 100;
        progressBar.style.width = '100%';

        setTimeout(() => {
          progressBar.style.opacity = '0';
          setTimeout(() => {
            progressBar.style.display = 'none';
          }, 500);
        }, 300);
      } else {
        progressBar.style.width = progress + '%';
        requestAnimationFrame(finishProgress);
      }
    };

    requestAnimationFrame(finishProgress);
  });

  requestAnimationFrame(updateProgress);
}


function initScrollEffects() {
  const header = document.querySelector('.header');
  // 始终显示导航栏阴影
  header.style.boxShadow = 'var(--shadow-md)';

  const fadeElements = document.querySelectorAll('.fade-in');
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
        observer.unobserve(entry.target);
      }
    });
  }, {
    threshold: 0.1
  });

  fadeElements.forEach(element => observer.observe(element));
}


const HOME_TOPICS_TAB_REQUESTS = {};
const HOME_TOPICS_TAB_CACHE_TTL = 60000;

function getHomeTopicsCacheKey(requestUrl) {
  return 'qkcms_home_topics_cache:' + requestUrl;
}

function readHomeTopicsCache(requestUrl) {
  try {
    const raw = localStorage.getItem(getHomeTopicsCacheKey(requestUrl));
    if (!raw) return null;
    const cached = JSON.parse(raw);
    if (!cached || typeof cached.html !== 'string' || !cached.savedAt) return null;
    if (Date.now() - Number(cached.savedAt) > HOME_TOPICS_TAB_CACHE_TTL) {
      localStorage.removeItem(getHomeTopicsCacheKey(requestUrl));
      return null;
    }
    return cached.html;
  } catch (error) {
    return null;
  }
}

function writeHomeTopicsCache(requestUrl, html) {
  try {
    localStorage.setItem(getHomeTopicsCacheKey(requestUrl), JSON.stringify({
      html,
      savedAt: Date.now()
    }));
  } catch (error) {
  }
}

function markLoadedTabContent(content) {
  if (!content) return;
  const fadeItems = content.querySelectorAll('.fade-in');
  fadeItems.forEach(item => item.classList.add('visible'));
}

function loadTabContentIfNeeded(content) {
  if (!content || content.dataset.loaded === 'true') {
    return Promise.resolve();
  }

  const requestUrl = content.dataset.homeTopicsUrl;
  if (!requestUrl) {
    content.dataset.loaded = 'true';
    return Promise.resolve();
  }

  if (HOME_TOPICS_TAB_REQUESTS[requestUrl]) {
    return HOME_TOPICS_TAB_REQUESTS[requestUrl];
  }

  const cachedHtml = readHomeTopicsCache(requestUrl);
  if (cachedHtml) {
    content.innerHTML = cachedHtml;
    content.dataset.loaded = 'true';
    markLoadedTabContent(content);
    return Promise.resolve();
  }

  content.innerHTML = '<div class="topic-item"><div class="topic-content"><p>加载中...</p></div></div>';

  HOME_TOPICS_TAB_REQUESTS[requestUrl] = fetch(requestUrl, {
    credentials: 'same-origin',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
    .then(response => response.json())
    .then(json => {
      if (json && json.success && typeof json.html === 'string') {
        content.innerHTML = json.html;
        content.dataset.loaded = 'true';
        writeHomeTopicsCache(requestUrl, json.html);
        markLoadedTabContent(content);
        return;
      }
      throw new Error('load failed');
    })
    .catch(() => {
      content.innerHTML = '<div class="topic-item"><div class="topic-content"><p>加载失败，请稍后重试</p></div></div>';
    })
    .finally(() => {
      delete HOME_TOPICS_TAB_REQUESTS[requestUrl];
    });

  return HOME_TOPICS_TAB_REQUESTS[requestUrl];
}

function initTabSwitching() {
  const filterBtns = document.querySelectorAll('.filter-btn');
  const tabContents = document.querySelectorAll('.tab-content');

  tabContents.forEach(content => {
    if (!content.classList.contains('active')) {
      content.style.display = 'none';
    }
  });

  filterBtns.forEach(btn => {
    btn.addEventListener('click', function () {
      const tabId = this.getAttribute('data-tab');

      // 获取当前按钮所属的topics-header
      const topicsHeader = this.closest('.topics-header');
      // 获取当前header对应的title
      const topicsTitle = topicsHeader ? topicsHeader.querySelector('.topics-title') : null;

      // 判断是评论区域还是话题区域
      const isCommentPage = window.location.pathname.includes('/post.php') ||
        (topicsTitle && topicsTitle.textContent.includes('评论'));

      // 判断是否为用户中心页面
      const isUserCenterPage = window.location.pathname.includes('Member') ||
        document.querySelector('.user-stats') !== null;

      // 保存原始标题，用于提取用户名
      const originalTitle = topicsTitle ? topicsTitle.textContent : '';

      // 获取用户昵称，优先从页面元素获取
      let userName = '';
      if (isUserCenterPage) {
        // 直接从页面顶部的用户信息区域获取用户名
        const userHeaderName = document.querySelector('.user-details .user-name');
        if (userHeaderName) {
          userName = userHeaderName.textContent.trim();
        }
        // 如果当前显示的是"我的文章"，则不需要用户名前缀
        else if (originalTitle.includes('我的文章')) {
          userName = '';
        }
        // 从原始标题中提取用户名
        else {
          const match = originalTitle.match(/^(\S+)的文章$/);
          if (match) {
            userName = match[0]; // 保留完整的"用户名的文章"格式
          }
        }
      }

      // 更新按钮状态
      filterBtns.forEach(b => {
        // 只移除同一header下的按钮active状态
        if (b.closest('.topics-header') === topicsHeader) {
          b.classList.remove('active');
        }
      });
      this.classList.add('active');

      // 更新标题文本（支持首页话题和评论区域）
      if (topicsTitle) {
        let titlePrefix = '';

        if (isCommentPage) {
          // 评论区域标题 - 保留数字部分
          if (tabId === 'comment') {
            titlePrefix = '最早评论';
          } else if (tabId === 'hot') {
            titlePrefix = '热门评论';
          } else {
            titlePrefix = '最新评论';
          }

          // 保留评论数量，只替换前缀
          const match = originalTitle.match(/（\d+）/);
          if (match) {
            topicsTitle.textContent = titlePrefix + match[0];
          } else {
            topicsTitle.textContent = titlePrefix + '（0）';
          }
        } else {
          // 话题区域标题 - 只显示纯文本，不包含数字

          // 基于data-tab属性直接判断按钮类型
          let actionText = '';
          if (tabId === 'hot') {
            actionText = '推荐文章';
          } else if (tabId === 'comment') {
            actionText = '热门文章';
          } else if (tabId === 'latest') {
            actionText = '最新文章';
          } else {
            actionText = '最新文章';
          }

          // 检测是否为TAG页面
          const isTagPage = window.location.pathname.includes('tag') ||
            (topicsTitle && topicsTitle.textContent.includes('TAG'));

          // 设置标题前缀
          if (isTagPage) {
            // TAG页面标题
            if (tabId === 'hot') {
              titlePrefix = '推荐TAG';
            } else if (tabId === 'comment') {
              titlePrefix = '热门TAG';
            } else {
              titlePrefix = '最新TAG';
            }
          } else if (isUserCenterPage) {
            // 用户中心页面标题 - 显示格式：用户名+的+按钮文本
            if (originalTitle.includes('我的文章')) {
              // 如果是"我的文章"，则显示"我的+按钮文本"
              titlePrefix = '我的' + actionText;
            } else {
              // 否则显示"用户名的+按钮文本"
              // 从页面元素直接获取用户名
              const userHeaderName = document.querySelector('.user-details .user-name');
              let userPart = '';
              if (userHeaderName) {
                userPart = userHeaderName.textContent.trim();
              }

              // 如果获取到用户名，格式为：用户名的+按钮文本
              if (userPart) {
                titlePrefix = userPart + '的' + actionText;
              } else {
                // 如果没有获取到用户名，保持原始标题
                titlePrefix = originalTitle;
              }
            }
          } else {
            // 固定标题为“全站头条”，不随筛选变化
            titlePrefix = '全站头条';
          }

          // 只设置纯文本标题，不添加数字
          topicsTitle.textContent = titlePrefix;
        }
      }

      // 更新内容显示，只操作同一header下的内容
      let relatedTabContents;
      if (topicsHeader) {
        // 获取当前header的父级section，用于找到所有相关内容
        const parentSection = topicsHeader.closest('section');
        if (parentSection) {
          // 检查是否为TAG页面
          const isTagPage = window.location.pathname.includes('tag') ||
            parentSection.classList.contains('categories-section');

          if (isTagPage) {
            // TAG页面，内容区域直接在section下
            relatedTabContents = parentSection.querySelectorAll('.tab-content');
          } else {
            // 普通页面，内容区域是topicsHeader的下一个兄弟元素
            const currentContentContainer = topicsHeader.nextElementSibling;
            relatedTabContents = currentContentContainer ? currentContentContainer.querySelectorAll('.tab-content') : [];
          }
        } else {
          // 没有section时，使用原有逻辑
          const currentContentContainer = topicsHeader.nextElementSibling;
          relatedTabContents = currentContentContainer ? currentContentContainer.querySelectorAll('.tab-content') : [];
        }
      } else {
        relatedTabContents = [];
      }

      // 执行内容切换
      let activeContent = null;
      relatedTabContents.forEach(content => {
        if (content.id === tabId) {
          activeContent = content;
          content.style.display = 'block';
          content.style.opacity = '0';
          setTimeout(() => {
            content.style.transition = 'opacity 0.3s ease';
            content.style.opacity = '1';
          }, 10);
        } else {
          content.style.display = 'none';
        }
      });

      if (activeContent) {
        loadTabContentIfNeeded(activeContent);
      }
    });
  });
}


function initTopicHoverEffects() {
  // 移除所有topic-item的hover效果JavaScript实现
  // 改为完全使用CSS实现，避免冲突导致的抖动
}



function initMobileMenu() {
  const mobileMenuBtn = document.querySelector('.mobile-menu-btn');
  const navLinks = document.querySelector('.nav-links');

  if (!mobileMenuBtn || !navLinks) return;

  mobileMenuBtn.addEventListener('click', function () {
    navLinks.classList.toggle('show');

    const icon = mobileMenuBtn.querySelector('svg');
    if (icon) {
      icon.innerHTML = navLinks.classList.contains('show')
        ? '<line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line>'
        : '<line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line>';
    }
  });

  document.addEventListener('click', function (event) {
    if (!mobileMenuBtn.contains(event.target) && !navLinks.contains(event.target)) {
      navLinks.classList.remove('show');
      const icon = mobileMenuBtn.querySelector('svg');
      if (icon) {
        icon.innerHTML = '<line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line>';
      }
    }
  });
}



function initTrendingRankStyles() {
  const rankElements = document.querySelectorAll('.trending-rank');

  rankElements.forEach(element => {
    const rankNumber = parseInt(element.textContent.trim());

    element.classList.remove('warm', 'rank-1-2', 'rank-3-4', 'rank-5-6');

    if (rankNumber === 1 || rankNumber === 2) {
      element.classList.add('rank-1-2');
    } else if (rankNumber === 3 || rankNumber === 4) {
      element.classList.add('rank-3-4');
    } else if (rankNumber === 5 || rankNumber === 6) {
      element.classList.add('rank-5-6');
    }
  });
}


function createParticles() {
  const particles = document.querySelector('.particles');
  if (!particles) return;

  const particleCount = 50;
  particles.innerHTML = '';

  for (let i = 0; i < particleCount; i++) {
    const particle = document.createElement('div');

    const size = Math.random() * 4 + 1;
    const x = Math.random() * 100;
    const y = Math.random() * 100;

    particle.style.position = 'absolute';
    particle.style.left = `${x}%`;
    particle.style.top = `${y}%`;
    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;
    particle.style.borderRadius = '50%';

    const opacity = Math.random() * 0.5 + 0.2;
    particle.style.backgroundColor = `rgba(255, 255, 255, ${opacity})`;
    particle.style.boxShadow = `0 0 ${Math.random() * 10 + 5}px rgba(255, 255, 255, ${opacity * 0.5})`;

    const delay = Math.random() * 5;
    const duration = 5 + Math.random() * 10;
    particle.style.animation = `particleFloat ${duration}s ease-in-out infinite`;
    particle.style.animationDelay = `${delay}s`;

    particles.appendChild(particle);
  }
}




function initRandomTagColors() {
  try {
    const tags = document.querySelectorAll('.tags-cloud .tag');
    if (!tags || tags.length === 0) return;

    const predefinedColors = [
      { r: 231, g: 76, b: 60 }, { r: 192, g: 57, b: 43 }, { r: 200, g: 50, b: 50 }, { r: 150, g: 0, b: 0 }, { r: 180, g: 0, b: 0 },
      { r: 46, g: 204, b: 113 }, { r: 39, g: 174, b: 96 }, { r: 0, g: 100, b: 0 }, { r: 26, g: 188, b: 156 }, { r: 22, g: 160, b: 133 },
      { r: 52, g: 152, b: 219 }, { r: 41, g: 128, b: 185 }, { r: 0, g: 100, b: 200 }, { r: 0, g: 80, b: 150 }, { r: 0, g: 150, b: 130 },
      { r: 155, g: 89, b: 182 }, { r: 142, g: 68, b: 173 }, { r: 100, g: 40, b: 180 }, { r: 120, g: 0, b: 120 }, { r: 165, g: 0, b: 165 },
      { r: 230, g: 126, b: 34 }, { r: 211, g: 84, b: 0 }, { r: 192, g: 100, b: 0 }, { r: 140, g: 60, b: 0 }, { r: 165, g: 42, b: 42 },
      { r: 127, g: 140, b: 141 }, { r: 52, g: 73, b: 94 }, { r: 44, g: 62, b: 80 }, { r: 70, g: 130, b: 180 }, { r: 72, g: 61, b: 139 }];

    const storageKey = 'qkcms_tags_cloud_color_map_v1';
    let colorMap = {};
    try {
      const cached = localStorage.getItem(storageKey);
      colorMap = cached ? JSON.parse(cached) : {};
      if (!colorMap || typeof colorMap !== 'object') colorMap = {};
    } catch (e) {
      colorMap = {};
    }

    let usedColorIndices = Object.values(colorMap)
      .map(v => parseInt(v, 10))
      .filter(v => Number.isInteger(v) && v >= 0 && v < predefinedColors.length);

    let availableColorIndices = Array.from({ length: predefinedColors.length }, (_, i) => i);
    availableColorIndices = availableColorIndices.filter(i => usedColorIndices.indexOf(i) === -1);

    function getUniqueColor() {
      if (availableColorIndices.length > 0) {
        const randomPos = Math.floor(Math.random() * availableColorIndices.length);
        const selectedIndex = availableColorIndices[randomPos];
        availableColorIndices.splice(randomPos, 1);
        usedColorIndices.push(selectedIndex);
        return predefinedColors[selectedIndex];
      } else {
        usedColorIndices = [];
        availableColorIndices = Array.from({ length: predefinedColors.length }, (_, i) => i);
        return getUniqueColor();
      }
    }

    function hsvToRgb(h, s, v) {
      let r, g, b;
      const i = Math.floor(h * 6);
      const f = h * 6 - i;
      const p = v * (1 - s);
      const q = v * (1 - f * s);
      const t = v * (1 - (1 - f) * s);

      switch (i % 6) {
        case 0: r = v; g = t; b = p; break;
        case 1: r = q; g = v; b = p; break;
        case 2: r = p; g = v; b = t; break;
        case 3: r = p; g = q; b = v; break;
        case 4: r = t; g = p; b = v; break;
        case 5: r = v; g = p; b = q; break;
      }

      return {
        r: Math.floor(r * 255),
        g: Math.floor(g * 255),
        b: Math.floor(b * 255)
      };
    }

    tags.forEach((tag) => {
      const tagKey = (tag.getAttribute('href') || '') + '|' + (tag.textContent || '').trim();
      let colorIndex = parseInt(colorMap[tagKey], 10);
      if (!Number.isInteger(colorIndex) || colorIndex < 0 || colorIndex >= predefinedColors.length) {
        const color = getUniqueColor();
        colorIndex = predefinedColors.findIndex(c => c.r === color.r && c.g === color.g && c.b === color.b);
        if (colorIndex < 0) colorIndex = 0;
        colorMap[tagKey] = colorIndex;
      }
      const color = predefinedColors[colorIndex];
      const rgbStr = 'rgb(' + color.r + ', ' + color.g + ', ' + color.b + ')';

      tag.style.color = rgbStr;
      tag.style.backgroundColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.2)';
      tag.style.transition = 'background-color 0.3s ease';
      tag.style.cssText += 'color: ' + rgbStr + ' !important; background-color: rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.2) !important;';

      tag.onmouseenter = function () {
        this.style.backgroundColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.39)';
        this.style.cssText += 'background-color: rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.39) !important;';
      };

      tag.onmouseleave = function () {
        this.style.backgroundColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.2)';
        this.style.cssText += 'background-color: rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', 0.2) !important;';
      };
    });

    try {
      localStorage.setItem(storageKey, JSON.stringify(colorMap));
    } catch (e) {
    }
  } catch (error) {
    console.error('热门标签颜色初始化失败:', error);
  }
}

// 定义s函数用于立即执行
function s(fn) {
  fn();
}

// 使用立即执行函数，在脚本加载时就添加CSS样式以隐藏关键词容器
(function () {
  // 立即添加预隐藏样式，确保在DOM开始渲染前就生效
  if (!document.getElementById('keyword-preload-styles')) {
    const style = document.createElement('style');
    style.id = 'keyword-preload-styles';
    style.textContent = `
      #keywords-container, .tags-wrapper:not(.category-keywords) {
        visibility: hidden;
      }
    `;
    // 立即添加到head标签，确保在DOM渲染前生效
    (document.head || document.documentElement).appendChild(style);
  }
})();

// 处理关键词容器中的关键词（按逗号分割）
function processKeywords() {
  const keywordsContainer = document.getElementById('keywords-container');
  if (keywordsContainer) {
    try {
      // 获取原始文本内容
      const originalKeywords = keywordsContainer.innerText;
      // 按逗号分割关键词
      const keywordArray = originalKeywords.split(',');
      let keywordsHTML = '';

      // 判断是否为移动端
      const isMobile = window.innerWidth <= 768;
      // 电脑端最多显示6个，手机端最多显示4个
      const maxKeywords = isMobile ? 4 : 6;

      // 生成带样式的关键词标签，限制显示数量
      for (let i = 0; i < keywordArray.length && i < maxKeywords; i++) {
        const trimmedKeyword = keywordArray[i].trim();
        if (trimmedKeyword) { // 确保不为空
          keywordsHTML += '<span class="keyword-tag" style="display: inline-block; padding: 4px 10px; background: #f0f2f5; color: #666; border-radius: 15px; font-size: 12px; margin-right: 8px; margin-bottom: 8px;">' + trimmedKeyword + '</span>';
        }
      }

      // 更新HTML内容
      keywordsContainer.innerHTML = keywordsHTML;
    } catch (error) {
      console.error('处理关键词时出错:', error);
    } finally {
      // 无论处理成功与否，都显示容器
      keywordsContainer.style.visibility = 'visible';
    }
  }
}

// 处理.tags-wrapper中的关键词
function processTagsWrapper() {
  const tagsWrappers = document.querySelectorAll('.tags-wrapper');

  tagsWrappers.forEach(wrapper => {
    try {
      var isPostKeywordsBlock = wrapper.classList.contains('category-keywords') && (
        !!document.querySelector('.category-header-section') ||
        /post(_id\d+)?\.html$/i.test(window.location.pathname) ||
        /\/templates\/post\.php$/i.test(window.location.pathname)
      );
      if (isPostKeywordsBlock) {
        wrapper.style.visibility = 'visible';
        return;
      }
      const link = wrapper.querySelector('a');
      if (link) {
        const originalHref = link.getAttribute('href');
        const keywords = link.textContent;
        const keywordArray = keywords.split(',').map(k => k.trim());
        wrapper.innerHTML = '';

        // 判断是否为移动端
        const isMobile = window.innerWidth <= 768;

        // 为不同页面的关键词容器设置不同的显示数量
        let maxKeywords = 3; // 电脑端列表页面默认显示3个关键词

        // 分类列表右上角的关键词：手机端改成显示1个
        if (!wrapper.classList.contains('category-keywords') && isMobile) {
          maxKeywords = 1; // 手机端列表页面显示1个关键词
        } else if (!wrapper.classList.contains('category-keywords') && !isMobile) {
          maxKeywords = 3; // 电脑端列表页面最多显示3个关键词
        }

        // 分类页面的关键词：电脑端最多显示5个，手机端最多显示4个
        if (wrapper.classList.contains('category-keywords')) {
          maxKeywords = isMobile ? 4 : 6; // 手机端最多显示4个，电脑端最多显示5个
        }

        const displayKeywords = keywordArray.slice(0, maxKeywords);

        displayKeywords.forEach((keyword, index) => {
          const tagSpan = document.createElement('span');
          // 为分类页面使用不同的类名，避免与列表页关键词样式冲突
          if (wrapper.classList.contains('category-keywords')) {
            tagSpan.classList.add('category-tag');
          } else {
            tagSpan.classList.add('custom-tag1');
          }

          const newLink = document.createElement('a');
          // 动态生成/tag_关键词.html格式的链接
          newLink.href = '/tag.html?tag=' + encodeURIComponent(keyword);
          newLink.textContent = keyword;
          tagSpan.appendChild(newLink);

          wrapper.appendChild(tagSpan);

          if (index < displayKeywords.length - 1) {
            const space = document.createTextNode(' ');
            wrapper.appendChild(space);
          }
        });
      }
    } catch (error) {
      console.error('处理tags-wrapper时出错:', error);
    } finally {
      // 无论处理成功与否，都显示容器
      wrapper.style.visibility = 'visible';
    }
  });
}

// 页面加载完成后处理关键词
document.addEventListener('DOMContentLoaded', function () {
  // 调用其他初始化函数
  if (typeof init === 'function') init();
  if (typeof initPageLoader === 'function') initPageLoader();
  if (typeof initScrollEffects === 'function') initScrollEffects();
  if (typeof initTabSwitching === 'function') initTabSwitching();
  if (typeof initTopicHoverEffects === 'function') initTopicHoverEffects();
  if (typeof initMobileMenu === 'function') initMobileMenu();
  if (typeof initTrendingRankStyles === 'function') initTrendingRankStyles();
  if (typeof createParticles === 'function') createParticles();
  if (typeof initRandomTagColors === 'function') initRandomTagColors();
  if (typeof initFriendlinkCarousel === 'function') initFriendlinkCarousel();

  // 立即处理关键词，不再额外延迟
  processKeywords();
  processTagsWrapper();

  // 初始化用户头像 - 确保所有头像元素都有默认头像
  initializeUserAvatars();
});

// 初始化用户头像函数 - 确保所有场景下都能显示默认头像
function initializeUserAvatars() {
  try {
    // 获取所有可能的用户头像元素
    const avatarElements = document.querySelectorAll('.user-avatar, .user-profile img, #userAvatar img, .user-profile-avatar img, .topic-avatar, .comment-avatar, .reply-avatar');

    // 如果没有找到头像元素，直接返回
    if (avatarElements.length === 0) {
      return;
    }

    const isLoggedIn = localStorage.getItem('qkcms_logged_in') === 'true';
    const storedAvatar = localStorage.getItem('qkcms_user_avatar');

    avatarElements.forEach(avatar => {
      try {
        avatar.onerror = null;
        avatar.onerror = function () {
          this.src = window.DEFAULT_AVATAR_PATH;
        };

        // 识别所有与用户相关的头像：包含 userAvatar 的容器、含有 avatar 类名的图片、或者在下拉菜单里的图片
        if (avatar.closest('#userAvatar') || 
            avatar.classList.contains('user-avatar') || 
            avatar.classList.contains('comment-user-avatar') ||
            avatar.closest('.user-profile-avatar') ||
            avatar.closest('.user-dropdown-menu')) {
          
          // 如果已登录，优先从本地存储同步
          if (isLoggedIn && storedAvatar) {
            // 只有当头像确实不同时才更新，避免重复设置导致闪烁
            const currentSrc = avatar.getAttribute('src');
            if (!currentSrc || currentSrc !== storedAvatar) {
              avatar.src = storedAvatar;
            }
            return;
          }

          // 未登录或无存储时设置默认头像
          if (avatar.closest('#userAvatar')) {
            return;
          }
          if (!avatar.src || avatar.src === '' || avatar.src === 'about:blank' || avatar.src.indexOf('avatar.png') === -1) {
            avatar.src = window.DEFAULT_AVATAR_PATH;
          }
        }
      } catch (err) {
        console.error('初始化单个头像时出错:', err);
      }
    });
  } catch (err) {
    console.error('初始化用户头像时出错:', err);
  }
}

// 简化window.onload事件，只执行必要的操作
window.onload = function () {
  // 如果需要在完全加载后重新执行随机标签颜色设置
  if (typeof initRandomTagColors === 'function') initRandomTagColors();
};




// 搜索框功能实现
document.addEventListener('DOMContentLoaded', function () {
  const searchInput = document.getElementById('search-input');
  const searchButton = document.getElementById('search-button');
  const originalPlaceholder = '请输入搜索关键词，请勿输入违禁内容';

  // 搜索处理逻辑，保存搜索词并跳转
  const handleSearch = () => {
    const searchWord = searchInput.value.trim();
    if (!searchWord) {
      searchInput.placeholder = '搜索词不可为空';
      return;
    }

    // 发送搜索词到后端保存
    fetch('', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        action: 'save_search',
        search_word: searchWord
      })
    })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          // 跳转到搜索结果页
          window.location.href = `/search.html?keyword=${encodeURIComponent(searchWord)}`;
        } else {
          // 保存失败，将错误信息显示在搜索框placeholder中，不跳转
          searchInput.placeholder = data.message;
          searchInput.value = ''; // 清空搜索框
        }
      })
      .catch(error => {
        console.error('保存搜索词失败:', error);
        // 保存失败，将错误信息显示在搜索框placeholder中，不跳转
        searchInput.placeholder = '保存搜索词失败，请稍后重试';
        searchInput.value = ''; // 清空搜索框
      });
  };

  const restorePlaceholder = () => {
    searchInput.placeholder = originalPlaceholder;
  };

  searchButton.addEventListener('click', handleSearch);
  searchInput.addEventListener('keypress', (e) => e.key === 'Enter' && handleSearch());
  searchInput.addEventListener('input', restorePlaceholder);
});

// 页面加载完成后初始化所有功能
document.addEventListener('DOMContentLoaded', function () {
  // 初始化标签切换功能
  initTabSwitching();

  // 初始化主题悬停效果
  initTopicHoverEffects();
});








// 回到顶部功能实现
document.addEventListener('DOMContentLoaded', function () {
  const backToTopButton = document.getElementById('back-to-top');

  // 检查按钮是否存在
  if (!backToTopButton) {
    console.warn('回到顶部按钮元素未找到');
    return;
  }

  // 监听滚动事件，控制按钮显示/隐藏
  window.addEventListener('scroll', () => {
    if (window.pageYOffset > 300) {
      backToTopButton.classList.add('visible');
    } else {
      backToTopButton.classList.remove('visible');
    }
  });

  // 点击按钮回到顶部
  backToTopButton.addEventListener('click', () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });
});

/**
 * 初始化友情链接轮播功能
 * 实现一行2个，每次显示6个链接（3行2列）
 */
function initFriendlinkCarousel() {
  // 等待DOM完全加载
  if (document.readyState !== 'complete') {
    window.addEventListener('load', initFriendlinkCarousel);
    return;
  }

  const carousel = document.querySelector('.friendlink-carousel');
  if (!carousel) return;

  const container = carousel.querySelector('.friendlink-container');
  if (!container) return;

  const items = Array.from(container.querySelectorAll('.friendlink-item'));
  

  // 设置一行显示2个，每次显示6个链接（3行2列）
  const itemsPerPage = 6;
  const itemsPerRow = 2; // 每行显示2个
  const rowsPerPage = Math.ceil(itemsPerPage / itemsPerRow);
  const totalItems = items.length;
  let currentPage = 0;

  // 恢复flex布局
  container.style.display = 'flex';
  container.style.flexWrap = 'wrap';
  container.style.gap = '10px'; // 保持gap为10px
  container.style.width = 'auto'; // 自动宽度以适应内容
  container.style.maxWidth = '240px'; // 2个110px + 10px gap

  // 恢复flex布局下的项目样式，使用CSS中设置的110px宽度
  items.forEach(item => {
    item.style.width = ''; // 使用CSS中设置的固定宽度110px
    item.style.margin = '0';
    item.style.float = 'none';
    item.style.display = 'none'; // 先隐藏所有链接
  });

  // 如果链接数量不足6个，显示所有链接
  if (totalItems <= itemsPerPage) {
    items.forEach(item => {
      item.style.display = 'block';
    });
    return;
  }

  // 强制设置容器高度，确保能完整显示3行（6个链接）
  const containerHeight = 150; // 直接设置足够的高度
  carousel.style.height = containerHeight + 'px';
  carousel.style.maxHeight = containerHeight + 'px';
  carousel.style.overflow = 'hidden';
  carousel.style.display = 'block';

  // 初始化显示第一页
  showPage(0);

  // 自动轮播
  setInterval(() => {
    currentPage = (currentPage + 1) % Math.ceil(totalItems / itemsPerPage);
    showPage(currentPage);
  }, 5000);

  /**
   * 显示指定页面的链接
   * @param {number} pageIndex - 页面索引
   */
  function showPage(pageIndex) {
    const startIndex = pageIndex * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, totalItems);

    

    // 隐藏所有链接
    items.forEach((item, index) => {
      if (index >= startIndex && index < endIndex) {
        item.style.display = 'block';
      } else {
        item.style.display = 'none';
      }
    });

    // 更新轮播指示器（如果需要）
    updateIndicators(pageIndex);
  }

  /**
   * 更新轮播指示器
   * @param {number} activeIndex - 当前公告速速页面索引
   */
  function updateIndicators(activeIndex) {
    // 这里可以添加指示器逻辑，暂时省略
  }
}

window.openVideoModal = function () {
  var modal = document.getElementById('videoModalOverlay');
  var video = document.getElementById('demoVideo');
  if (!modal || !video) return;
  modal.classList.add('active');
  try { video.play(); } catch (e) { }
};

window.closeVideoModal = function () {
  var modal = document.getElementById('videoModalOverlay');
  var video = document.getElementById('demoVideo');
  if (!modal || !video) return;
  modal.classList.remove('active');
  try { video.pause(); } catch (e) { }
};

document.addEventListener('DOMContentLoaded', function () {
  function updateOverlay() {
    var overlay = document.querySelector('.banner-color-overlay');
    if (!overlay) return;
    var primary = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim().toLowerCase();
    if (primary === '#10b981' || primary === '#07c160' || primary === '#3a8769') {
      overlay.style.display = 'none';
    } else {
      overlay.style.display = 'block';
    }
  }

  updateOverlay();

  try {
    var observer = new MutationObserver(updateOverlay);
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['style', 'class'] });
    if (document.body) observer.observe(document.body, { attributes: true, attributeFilter: ['style', 'class'] });
  } catch (e) { }

  var v = document.querySelector('.banner-video-bg');
  if (!v) return;
  var t = setTimeout(function () {
    if (!v.dataset.loaded) v.style.display = 'none';
  }, 8000);
  v.addEventListener('canplaythrough', function () { v.dataset.loaded = 'true'; clearTimeout(t); });
  v.addEventListener('error', function () { v.style.display = 'none'; clearTimeout(t); });
});
