// 充值界面逻辑

(function() {
  let overlay = null;
  let container = null;
  let closeBtn = null;
  let packages = null;
  let rechargeInfo = null;
  let selectedPointsEl = null;
  let selectedPriceEl = null;
  
  let currentPackage = null;
  let currentUsername = null;

  function init() {
    overlay = document.getElementById('rechargeOverlay');
    container = document.getElementById('rechargeContainer');
    closeBtn = document.getElementById('rechargeClose');
    packages = document.querySelectorAll('.recharge-package');
    rechargeInfo = document.getElementById('rechargeInfo');
    selectedPointsEl = document.getElementById('selectedPoints');
    selectedPriceEl = document.getElementById('selectedPrice');

    if (!overlay || !container) {
      console.error('[RechargeView] 充值界面元素未找到');
      return;
    }

    bindEvents();
  }

  function bindEvents() {
    // 关闭按钮 - 只关闭界面，不触发充值
    if (closeBtn) {
      closeBtn.addEventListener('click', () => {
        hide();
        // 通知父窗口关闭充值界面
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'close-recharge-view'
          }, '*');
        }
      });
    }

    // 点击遮罩层关闭 - 只关闭界面，不触发充值
    if (overlay) {
      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
          hide();
          // 通知父窗口关闭充值界面
          if (window.parent && window.parent !== window) {
            window.parent.postMessage({
              type: 'close-recharge-view'
            }, '*');
          }
        }
      });
    }

    // ESC 键关闭 - 只关闭界面，不触发充值
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && overlay && overlay.classList.contains('show')) {
        hide();
        // 通知父窗口关闭充值界面
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'close-recharge-view'
          }, '*');
        }
      }
    });

    // 测试购买按钮
    const testBuyBtn = document.getElementById('testBuyBtn');
    if (testBuyBtn) {
      testBuyBtn.addEventListener('click', handleRechargeSuccess);
    }

    // 套餐选择
    if (packages) {
      packages.forEach(pkg => {
        pkg.addEventListener('click', () => {
          selectPackage(pkg);
        });
      });
    }

    // 监听来自父窗口的消息
    window.addEventListener('message', (event) => {
      if (event.data && event.data.type === 'open-recharge-view') {
        show(event.data.needPoints, event.data.currentPoints);
      }
    });
  }

  function selectPackage(pkg) {
    // 移除所有选中状态
    packages.forEach(p => p.classList.remove('selected'));
    
    // 添加选中状态
    pkg.classList.add('selected');
    currentPackage = {
      points: parseInt(pkg.dataset.points),
      price: parseFloat(pkg.dataset.price),
      package: pkg.dataset.package
    };

    // 显示充值信息
    if (rechargeInfo) {
      rechargeInfo.style.display = 'block';
    }
    
    if (selectedPointsEl) {
      selectedPointsEl.textContent = currentPackage.points + ' Ani币';
    }
    
    if (selectedPriceEl) {
      selectedPriceEl.textContent = '¥' + currentPackage.price;
    }
  }

  function show(needPoints, currentPoints) {
    if (!overlay) {
      init();
    }

    currentUsername = getCurrentUsername();
    if (!currentUsername) {
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error('请先登录', 2000);
      }
      return;
    }

    // 重置状态
    if (packages) {
      packages.forEach(p => p.classList.remove('selected'));
    }
    if (rechargeInfo) {
      rechargeInfo.style.display = 'none';
    }
    currentPackage = null;

    // 显示充值界面
    overlay.classList.add('show');
    overlay.style.pointerEvents = 'auto';
    
    // 默认选中第一个套餐
    if (packages && packages.length > 0) {
      selectPackage(packages[0]);
    }
  }

  function hide() {
    if (overlay) {
      overlay.classList.remove('show');
      overlay.style.pointerEvents = 'none';
    }
    currentPackage = null;
    currentUsername = null;
  }

  async function handleRechargeSuccess() {
    if (!currentPackage || !currentUsername) {
      hide();
      return;
    }

    try {
      // 调用充值API
      const response = await fetch('/api/recharge', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: currentUsername,
          points: currentPackage.points,
          price: currentPackage.price,
          package: currentPackage.package
        })
      });

      const result = await response.json();

      if (result.success) {
        // 充值成功，通知父窗口
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'recharge-success',
            points: currentPackage.points
          }, '*');
        }

        // 显示成功提示
        if (window.parent && window.parent.HintView) {
          window.parent.HintView.success(`充值成功！获得 ${currentPackage.points} Ani币`, 3000);
        }

        hide();
      } else {
        // 充值失败
        if (window.parent && window.parent.HintView) {
          window.parent.HintView.error(result.message || '充值失败', 3000);
        }
        hide();
      }
    } catch (error) {
      console.error('[RechargeView] 充值处理失败:', error);
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error('充值失败，请稍后重试', 3000);
      }
      hide();
    }
  }

  // 获取当前登录用户名
  function getCurrentUsername() {
    try {
      const loginDataStr = localStorage.getItem('loginData');
      if (!loginDataStr) {
        return null;
      }
      
      const loginData = JSON.parse(loginDataStr);
      const now = Date.now();
      
      // 检查是否过期
      if (now >= loginData.expireTime) {
        localStorage.removeItem('loginData');
        return null;
      }
      
      return loginData.user ? loginData.user.username : null;
    } catch (error) {
      console.error('[RechargeView] 获取用户名失败:', error);
      return null;
    }
  }

  // 初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

