// 接管手机端底部音乐按钮
function modify_m_bottom_music_button_link() {
  const music = document.querySelector('a[href*="#m_bottom_music_button"]');
  if (!music) return;
  music.addEventListener('click', function (event) {
    event.preventDefault();
    if (!box_up) mu_box_show();
    else mu_box_hide(0);
  });
}

// 登录逻辑
let csrfToken = '';
let publicKey = '';
let loginTimer = null;
let countdownSeconds = 3;
let closeLoading = null;
const login_modal = document.getElementById('customLoginModal');
const login_closeBtn = document.getElementById('closeLoginModal');
const login_loginBtn = document.getElementById('customLoginBtn');

// 获取令牌及公钥
async function fetchCSRFToken() {
  login_modal.classList.add('show');
  login_loginBtn.disabled = true;
  login_loginBtn.textContent = '加载中...';
  closeLoading = cocoMessage.loading('正在加载署名信息...');

  try {
    const response = await fetch('/login', { credentials: 'include' });
    if (response.url.includes('/uc')) {
      return 'logged';
    }
    const htmlText = await response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlText, 'text/html');
    // 获取 CSRF Token
    const csrfInput = doc.querySelector('input[name="_csrf"]');
    if (!csrfInput || !csrfInput.value) {
      throw new Error('页面未找到 CSRF 令牌');
    }
    csrfToken = csrfInput.value;
    // 获取 PublicKey
    const publicKeyMatch = htmlText.match(/const publicKey = "([^"]+)";/);
    if (!publicKeyMatch || !publicKeyMatch[1]) {
      throw new Error('页面未找到 PublicKey');
    }
    publicKey = publicKeyMatch[1].replace(/\\\//g, '/');
    return 'ok';
  } catch (err) {
    closeLoading?.()
    cocoMessage.error('署名信息加载失败，请刷新');
    if (loginTimer) { clearInterval(loginTimer) }
    login_loginBtn.textContent = '错误！请刷新';
    login_loginBtn.disabled = true;
    return 'error';
  }
}

// 打开弹窗逻辑
async function open_login_box() {
  if (loginTimer) { clearInterval(loginTimer) }
  countdownSeconds = 3;
  const success = await fetchCSRFToken();
  if (success === 'logged') {
    closeLoading?.()
    cocoMessage.success('您已署名成功，请刷新');
    login_modal.classList.remove('show');
  } else if (success === 'ok') {
    loginTimer = setInterval(() => {
      if (countdownSeconds > 0) {
        login_loginBtn.textContent = '请稍等...' + countdownSeconds;
      } else {
        clearInterval(loginTimer);
        closeLoading?.()
        cocoMessage.success('署名信息加载完成');
        login_loginBtn.textContent = '署 名';
        login_loginBtn.disabled = false;
      }
      countdownSeconds--;
    }, 1000);
  } else {
    closeLoading?.()
    cocoMessage.error('服务器错误，请刷新');
    login_modal.classList.remove('show');
  }
}

// 关闭弹窗
login_closeBtn.addEventListener('click', () => {
  closeLoading?.()
  login_modal.classList.remove('show');
  if (loginTimer) { clearInterval(loginTimer) }
});

// 加密逻辑
function encryptPassword(password) {
  try {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(password);
  } catch (e) {
    return null;
  }
}

// 提交登录
login_loginBtn.addEventListener('click', async () => {
  let islogin = false;
  const username = document.getElementById('customUsername').value.trim();
  const password = document.getElementById('customPassword').value.trim();
  if (!username || !password) {
    cocoMessage.warning('请先填写信息');
    return;
  }
  const encryptedPwd = encryptPassword(password);
  login_loginBtn.disabled = true;
  login_closeBtn.disabled = true;
  login_loginBtn.textContent = '验证中...';
  closeLoading = cocoMessage.loading('正在验证信息...');
  try {
    countdownSeconds = 3
    const response = await fetch('/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      credentials: 'include',
      body: new URLSearchParams({
        _csrf: csrfToken,
        username: username,
        password: encryptedPwd,
        'remember-me': 'true'
      })
    });
    // 核心细节：判断最终落点 URL
    const finalUrl = response.url;
    if (loginTimer) {
      clearInterval(loginTimer);
    }
    if (finalUrl.includes('/uc')) {
      islogin = true;
      closeLoading?.()
      cocoMessage.success('署名成功，正在跳转...');
      login_loginBtn.textContent = '跳转中...';
      const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
      $.cookie('load_type', 'login', { path: '/' });
      window.location.reload();
    } else if (finalUrl.includes('error=invalid-credential')) {
      closeLoading?.()
      cocoMessage.warning('署名人与心上锁不匹配');
    } else {
      closeLoading?.()
      cocoMessage.error('速度过快，请稍后重试');
    }
  } catch (err) {
    closeLoading?.()
    cocoMessage.error('服务器连接失败');
  } finally {
    if (!islogin) {
      fetchCSRFToken();
      login_closeBtn.disabled = false;
      loginTimer = setInterval(() => {
        if (countdownSeconds > 0) {
          login_loginBtn.textContent = '请稍等...' + countdownSeconds;
        } else {
          clearInterval(loginTimer);
          closeLoading?.()
          cocoMessage.success('请重新尝试署名');
          login_loginBtn.textContent = '署 名';
          login_loginBtn.disabled = false;
        }
        countdownSeconds--;
      }, 1000);
    }
  }
});

// 回车登录
document.addEventListener("keydown", function (e) {
  if (e.key === "Enter") {
    const modal = document.getElementById("customLoginModal");
    if (modal.classList.contains("show")) {
      document.getElementById("customLoginBtn").click();
    }
  }
});


// 退出登录
async function customLogout() {
  $('.pixar-notice-btn-confirm, .pixar-notice-btn-close').prop('disabled', true);
  let closeLoading = cocoMessage.loading('退出登录中...');
  try {
    const getResponse = await fetch('/logout', { credentials: 'include' });
    const htmlText = await getResponse.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlText, 'text/html');
    const logoutCsrfToken = doc.querySelector('input[name="_csrf"]')?.value;
    if (!logoutCsrfToken) {
      cocoMessage.error('页面未找到 CSRF 令牌');
      $('.pixar-notice-btn-confirm, .pixar-notice-btn-close').prop('disabled', false);
      closeLoading();
      return;
    }
    const postResponse = await fetch('/logout', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      credentials: 'include',
      body: new URLSearchParams({
        '_csrf': logoutCsrfToken
      })
    });
    if (postResponse.ok) {
      closeLoading();
      cocoMessage.success('您已成功退出登录');
      const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
      $.cookie('load_type', 'logout', { path: '/' });
      window.location.reload();
    } else {
      closeLoading();
      $('.pixar-notice-btn-confirm, .pixar-notice-btn-close').prop('disabled', false);
      throw new Error('退出请求被拒绝');
    }
  } catch (err) {
    closeLoading();
    $('.pixar-notice-btn-confirm, .pixar-notice-btn-close').prop('disabled', false);
    console.error('Logout Error:', err);
    cocoMessage.error('退出失败，请手动刷新页面');
  }
}

function open_logout_box() {
  const wrapper = document.getElementById("pixarNoticeWrapper");
  wrapper.style.display = "flex";
}

function hidePixarCard() {
  const wrapper = document.getElementById("pixarNoticeWrapper");
  wrapper.style.display = "none";
}

function confirmPixarAction() {
  customLogout();
}

function initDoubanDetailLinks() {
  document.querySelectorAll('.douban_page:not(.douban_detail_page) .douban_card_item').forEach(function (card) {
    var link = card.querySelector('.douban_detail_link');
    var title = card.querySelector('.douban_title_text');
    var content = card.querySelector('.douban_content_main');

    if (!link || !title || !content) {
      return;
    }

    var titleOverflow = title.scrollWidth > title.clientWidth;
    var contentOverflow = content.scrollHeight > content.clientHeight + 1;
    link.classList.toggle('is-visible', titleOverflow || contentOverflow);
  });
}

document.addEventListener('pjax:complete', initDoubanDetailLinks);
document.addEventListener('DOMContentLoaded', initDoubanDetailLinks);
window.addEventListener('resize', initDoubanDetailLinks);

// 打开确认模态框
function openModal(title, msg, type) {
  var modal = $('#momentsDeleteModal');
  var card = modal.find('.moments-card-widget');
  modal.find('.moments-title-text').text(title);
  modal.find('.moments-message-text').text(msg);
  card.removeClass('theme-red theme-yellow theme-green').addClass('theme-' + type);
  $('.moments-btn-cancel, .moments-btn-confirm').prop('disabled', false);
  $('body').off('click', '#momentsCancelBtn');
  $('body').off('click', '#momentsConfirmBtn');
  modal.fadeIn(200);
}

// 主题通用交互初始化
modify_m_bottom_music_button_link();
