// 我的界面逻辑

(function() {
  let currentUsername = null;
  let currentUserInfo = null;

  function init() {
    bindEvents();
    // 延迟加载，确保DOM完全渲染
    setTimeout(() => {
      loadUserInfo();
      loadPoints();
      loadAIHistory();
      loadPurchaseHistory();
    }, 200);
  }

  function bindEvents() {
    // 返回按钮
    const backBtn = document.getElementById('backBtn');
    if (backBtn) {
      backBtn.addEventListener('click', () => {
        // 如果在 iframe 中，通过 postMessage 通知父窗口切换页面
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'navigation',
            page: 'store'
          }, '*');
        } else {
          // 独立页面，直接跳转到主页面
          window.location.href = '../../index.html';
        }
      });
    }

    // 头像上传功能已移除

    // 充值按钮
    const rechargeBtn = document.getElementById('rechargeBtn');
    if (rechargeBtn) {
      rechargeBtn.addEventListener('click', () => {
        // 打开充值界面（通过postMessage通知父窗口，如果是独立页面则直接打开）
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'open-recharge-view'
          }, '*');
        } else {
          // 独立页面，需要创建充值iframe
          openRechargeView();
        }
      });
    }

    // 退出登录按钮
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', handleLogout);
    }

    // 监听消息
    window.addEventListener('message', (event) => {
      if (event.data && event.data.type === 'recharge-success') {
        loadPoints(); // 刷新点数
        closeRechargeView(); // 关闭充值界面
      } else if (event.data && event.data.type === 'close-recharge-view') {
        closeRechargeView();
      } else if (event.data && event.data.type === 'open-recharge-view') {
        // 如果充值iframe发送消息，也打开充值界面
        openRechargeView();
      } else if (event.data && event.data.type === 'refresh-points') {
        // 刷新点数（购买成功后触发）
        loadPoints();
        loadPurchaseHistory(); // 同时刷新购买记录
      } else if (event.data && event.data.type === 'refresh-ai-history') {
        // 刷新AI历史（生图请求成功后触发）
        loadAIHistory();
      }
    });
  }

  // 打开充值界面
  function openRechargeView() {
    const rechargeFrame = document.getElementById('rechargeViewFrame');
    if (rechargeFrame) {
      rechargeFrame.style.display = 'block';
      rechargeFrame.style.pointerEvents = 'auto';
      rechargeFrame.style.visibility = 'visible';
      
      // 发送消息给充值iframe
      const sendRechargeData = () => {
        if (rechargeFrame.contentWindow) {
          rechargeFrame.contentWindow.postMessage({
            type: 'open-recharge-view'
          }, '*');
        } else {
          setTimeout(sendRechargeData, 100);
        }
      };
      
      sendRechargeData();
      
      const handleLoad = () => {
        setTimeout(() => {
          sendRechargeData();
        }, 50);
      };
      
      if (rechargeFrame.contentDocument && rechargeFrame.contentDocument.readyState === 'complete') {
        handleLoad();
      } else {
        rechargeFrame.addEventListener('load', handleLoad, { once: true });
      }
    }
  }

  // 关闭充值界面
  function closeRechargeView() {
    const rechargeFrame = document.getElementById('rechargeViewFrame');
    if (rechargeFrame) {
      rechargeFrame.style.display = 'none';
      rechargeFrame.style.pointerEvents = 'none';
      rechargeFrame.style.visibility = 'hidden';
    }
  }

  // 加载用户信息
  async function loadUserInfo() {
    const username = getCurrentUsername();
    if (!username) {
      // 未登录，跳转到登录页
      window.location.href = '../../index.html';
      return;
    }

    currentUsername = username;

    // 先从localStorage读取用户信息作为备用
    try {
      const loginDataStr = localStorage.getItem('loginData');
      if (loginDataStr) {
        const loginData = JSON.parse(loginDataStr);
        if (loginData.user) {
          // 先显示localStorage中的用户信息
          displayUserInfo(loginData.user);
        }
      }
    } catch (error) {
      console.error('[Profile] 从localStorage读取用户信息失败:', error);
    }

    // 然后从API获取最新信息
    try {
      const response = await fetch(`/api/user/info?username=${encodeURIComponent(username)}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const result = await response.json();
      
      if (result.success && result.user) {
        currentUserInfo = result.user;
        displayUserInfo(result.user);
      } else {
        console.error('[Profile] API返回数据格式错误:', result);
      }
    } catch (error) {
      console.error('[Profile] 加载用户信息失败:', error);
      // 如果API调用失败，至少显示localStorage中的信息
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error('加载用户信息失败，显示缓存信息', 2000);
      }
    }
  }

  // 手机号脱敏处理
  function maskPhone(phone) {
    if (!phone || phone.length < 7) {
      return phone;
    }
    // 保留前3位和后4位，中间用*代替
    const start = phone.substring(0, 3);
    const end = phone.substring(phone.length - 4);
    const middle = '*'.repeat(phone.length - 7);
    return start + middle + end;
  }

  // 显示用户信息
  function displayUserInfo(user) {
    if (!user) {
      console.error('[Profile] 用户信息为空');
      return;
    }

    // 使用函数来确保元素存在
    const setUserInfo = () => {
      const avatarImage = document.getElementById('avatarImage');
      const usernameInput = document.getElementById('usernameInput');
      const phoneInput = document.getElementById('phoneInput');

      if (avatarImage) {
        let avatarUrl = user.avatar;
        if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('data:')) {
          avatarUrl = 'http://localhost:3000' + (avatarUrl.startsWith('/') ? avatarUrl : '/' + avatarUrl);
        }
        avatarImage.src = avatarUrl || '../../static/default-avatar.png';
        avatarImage.onerror = function() {
          this.src = '../../static/default-avatar.png';
        };
      }

      if (usernameInput) {
        usernameInput.value = user.username || '';
      }

      if (phoneInput) {
        const phone = user.phone || '';
        phoneInput.value = maskPhone(phone);
      }
    };

    // 如果元素还没准备好，等待一下再试
    if (!document.getElementById('usernameInput') || !document.getElementById('phoneInput')) {
      setTimeout(setUserInfo, 100);
    } else {
      setUserInfo();
    }
  }

  // 加载点数
  async function loadPoints() {
    const username = getCurrentUsername();
    if (!username) return;

    try {
      const response = await fetch(`/api/user/points?username=${encodeURIComponent(username)}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const result = await response.json();
      
      if (result.success) {
        const pointsValue = document.getElementById('pointsValue');
        if (pointsValue) {
          const points = parseFloat(result.points || 0);
          pointsValue.textContent = points.toFixed(2);
        }
      }
    } catch (error) {
      console.error('[Profile] 加载点数失败:', error);
    }
  }

  // 处理退出登录
  function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
      // 清除localStorage
      localStorage.removeItem('loginData');
      
      // 通知父窗口（如果是在iframe中）
      if (window.parent && window.parent !== window) {
        window.parent.postMessage({
          type: 'logout'
        }, '*');
      }
      
      // 跳转到登录页
      window.location.href = '../../index.html';
    }
  }


  // 加载AI生图历史
  async function loadAIHistory() {
    const username = getCurrentUsername();
    if (!username) return;

    const historyLoading = document.getElementById('historyLoading');
    const historyEmpty = document.getElementById('historyEmpty');
    const historyGrid = document.getElementById('historyGrid');

    if (historyLoading) {
      historyLoading.style.display = 'block';
    }
    if (historyEmpty) {
      historyEmpty.style.display = 'none';
    }
    if (historyGrid) {
      historyGrid.innerHTML = '';
    }

    try {
      const response = await fetch(`/api/ai/history?username=${encodeURIComponent(username)}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const result = await response.json();
      
      if (historyLoading) {
        historyLoading.style.display = 'none';
      }

      if (result.success && result.history && result.history.length > 0) {
        if (historyGrid) {
          result.history.forEach(item => {
            const historyItem = createHistoryItem(item);
            historyGrid.appendChild(historyItem);
          });
        }
      } else {
        if (historyEmpty) {
          historyEmpty.style.display = 'block';
        }
      }
      
      // 如果有正在处理的任务，定期刷新
      if (result.success && result.history) {
        const hasProcessing = result.history.some(item => item.status === 'rendering' || item.status === 'queued');
        if (hasProcessing) {
          setTimeout(loadAIHistory, 3000); // 3秒后刷新
        }
      }
    } catch (error) {
      console.error('[Profile] 加载AI历史失败:', error);
      if (historyLoading) {
        historyLoading.style.display = 'none';
      }
      if (historyEmpty) {
        historyEmpty.style.display = 'block';
      }
    }
  }

  // 创建历史记录项
  function createHistoryItem(item) {
    const div = document.createElement('div');
    div.className = 'history-item';
    div.dataset.taskId = item.id;
    
    // 格式化时间
    const formatTime = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      const now = new Date();
      const diff = now - date;
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);
      
      if (minutes < 1) return '刚刚';
      if (minutes < 60) return `${minutes}分钟前`;
      if (hours < 24) return `${hours}小时前`;
      if (days < 7) return `${days}天前`;
      
      return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    };
    
    const timeText = formatTime(item.createdAt);
    
    // 预览图URL（模糊显示）
    const previewUrl = item.previewUrl || '';
    
    if (item.status === 'rendering' || item.status === 'queued') {
      div.classList.add(item.status);
      const statusText = item.status === 'rendering' ? '正在生成' : '等待中';
      div.innerHTML = `
        ${previewUrl ? `<img class="history-item-preview" src="${previewUrl}" alt="预览图" onerror="this.style.display='none'">` : ''}
        <div class="history-item-loading-overlay">
          <div class="loading-spinner-container">
            <div class="loading-spinner"></div>
          </div>
          <div class="loading-status-text">${statusText}</div>
        </div>
        <div class="history-item-time">${timeText}</div>
      `;
    } else if (item.status === 'completed' && item.imageUrl) {
      div.innerHTML = `
        <img class="history-item-image" src="${item.imageUrl}" alt="AI生成图" onerror="this.src='../../static/default-avatar.png'">
        <div class="history-item-overlay">
          <div class="history-item-actions">
            <button class="history-action-btn preview-btn" title="预览">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
              <span>预览</span>
            </button>
            <button class="history-action-btn download-btn" title="下载">
              <svg width="22" height="22" viewBox="0 0 16 16" fill="none">
                <path d="M8 11V3M8 11L5 8M8 11L11 8M3 13H13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span>下载</span>
            </button>
          </div>
        </div>
        <div class="history-item-time">${timeText}</div>
      `;
      
      // 点击预览按钮
      const previewBtn = div.querySelector('.preview-btn');
      if (previewBtn) {
        previewBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          showImagePreviewModal(item.imageUrl, item.id || 'ai-image');
        });
      }
      
      // 点击下载按钮 - 直接下载PNG
      const downloadBtn = div.querySelector('.download-btn');
      if (downloadBtn) {
        downloadBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          downloadImage(item.imageUrl, item.id || 'ai-image');
        });
      }
    } else if (item.status === 'failed') {
      div.classList.add('failed');
      
      // 如果已经重试过，显示"已重试"标记
      const retryButtonHtml = item.retried 
        ? `<div class="retried-badge">已重试</div>`
        : `<button class="retry-btn" data-task-id="${item.id}">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M2 8C2 4.686 4.686 2 8 2C10.5 2 12.5 3.5 13.5 5.5M14 8C14 11.314 11.314 14 8 14C5.5 14 3.5 12.5 2.5 10.5M14 2V6H10M2 14V10H6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            重新生图
          </button>`;
      
      div.innerHTML = `
        ${previewUrl ? `<img class="history-item-preview failed-preview" src="${previewUrl}" alt="预览图" onerror="this.style.display='none'">` : ''}
        <div class="failed-content">
          <div class="failed-icon">❌</div>
          <div class="failed-text">生成失败</div>
          ${retryButtonHtml}
        </div>
        <div class="history-item-time">${timeText}</div>
      `;
      
      // 绑定重试按钮事件
      const retryBtn = div.querySelector('.retry-btn');
      if (retryBtn) {
        retryBtn.addEventListener('click', async (e) => {
          e.stopPropagation();
          await retryAIGeneration(item.id);
        });
      }
    }
    
    return div;
  }

  // 重新生图（免费）
  async function retryAIGeneration(taskId) {
    const username = getCurrentUsername();
    if (!username) {
      alert('请先登录');
      return;
    }
    
    try {
      const response = await fetch('/api/ai/retry', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          taskId: taskId,
          username: username
        })
      });
      
      const result = await response.json();
      
      if (result.success) {
        // 刷新历史列表
        loadAIHistory();
      } else {
        alert('重试失败: ' + (result.error || '未知错误'));
      }
    } catch (error) {
      console.error('[Profile] 重试失败:', error);
      alert('重试失败: ' + error.message);
    }
  }

  // 下载图片（直接下载PNG）
  function downloadImage(url, filename) {
    const a = document.createElement('a');
    a.href = url;
    a.download = `${filename}.png`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  // 显示图片预览弹窗
  function showImagePreviewModal(imageUrl, filename) {
    const modal = document.createElement('div');
    modal.className = 'image-preview-modal';
    modal.innerHTML = `
      <div class="image-preview-backdrop"></div>
      <div class="image-preview-content">
        <img src="${imageUrl}" alt="预览图">
        <button class="image-preview-close">×</button>
        <button class="image-preview-download-btn" title="下载">
          <svg width="24" height="24" viewBox="0 0 16 16" fill="none">
            <path d="M8 11V3M8 11L5 8M8 11L11 8M3 13H13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>
    `;
    
    document.body.appendChild(modal);
    
    requestAnimationFrame(() => {
      modal.classList.add('show');
    });
    
    const closeModal = () => {
      modal.classList.remove('show');
      setTimeout(() => {
        if (modal.parentNode) modal.parentNode.removeChild(modal);
      }, 300);
    };
    
    modal.querySelector('.image-preview-backdrop').onclick = closeModal;
    modal.querySelector('.image-preview-close').onclick = closeModal;
    modal.querySelector('.image-preview-download-btn').onclick = (e) => {
      e.stopPropagation();
      downloadImage(imageUrl, filename);
    };
    
    document.addEventListener('keydown', function escHandler(e) {
      if (e.key === 'Escape') {
        closeModal();
        document.removeEventListener('keydown', escHandler);
      }
    });
  }

  // 加载购买记录
  async function loadPurchaseHistory() {
    const username = getCurrentUsername();
    if (!username) return;

    const purchaseLoading = document.getElementById('purchaseLoading');
    const purchaseEmpty = document.getElementById('purchaseEmpty');
    const purchaseGrid = document.getElementById('purchaseGrid');

    if (purchaseLoading) {
      purchaseLoading.style.display = 'block';
    }
    if (purchaseEmpty) {
      purchaseEmpty.style.display = 'none';
    }
    if (purchaseGrid) {
      purchaseGrid.innerHTML = '';
    }

    try {
      const response = await fetch(`/api/pay/purchase-history?username=${encodeURIComponent(username)}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const result = await response.json();
      
      if (purchaseLoading) {
        purchaseLoading.style.display = 'none';
      }

      if (result.success && result.history && result.history.length > 0) {
        if (purchaseGrid) {
          result.history.forEach(item => {
            const purchaseItem = createPurchaseItem(item);
            purchaseGrid.appendChild(purchaseItem);
          });
        }
      } else {
        if (purchaseEmpty) {
          purchaseEmpty.style.display = 'block';
        }
      }
    } catch (error) {
      console.error('[Profile] 加载购买记录失败:', error);
      if (purchaseLoading) {
        purchaseLoading.style.display = 'none';
      }
      if (purchaseEmpty) {
        purchaseEmpty.style.display = 'block';
      }
    }
  }

  // 创建购买记录项
  function createPurchaseItem(item) {
    const div = document.createElement('div');
    div.className = 'purchase-item';
    
    if (item.deleted) {
      div.classList.add('deleted');
    }
    
    const previewHtml = item.previewUrl 
      ? `<img class="purchase-item-image" src="${item.previewUrl}" alt="${item.name}" onerror="this.src='../../static/default-avatar.png'">`
      : `<div class="purchase-item-placeholder">
           <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
             <path d="M14 2H6C5.46957 2 4.96086 2.21071 4.58579 2.58579C4.21071 2.96086 4 3.46957 4 4V20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V8L14 2Z"/>
           </svg>
         </div>`;
    
    const deletedBadge = item.deleted ? '<div class="purchase-item-deleted-badge">已删除</div>' : '';
    const priceText = item.points > 0 ? `<div class="purchase-item-price">${item.points} Ani币</div>` : '';
    
    // 格式化时间（购买记录暂时没有时间，可以添加）
    const formatTime = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      const now = new Date();
      const diff = now - date;
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);
      
      if (minutes < 1) return '刚刚';
      if (minutes < 60) return `${minutes}分钟前`;
      if (hours < 24) return `${hours}小时前`;
      if (days < 7) return `${days}天前`;
      
      return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    };
    
    const timeText = item.purchasedAt ? formatTime(item.purchasedAt) : '';
    
    div.innerHTML = `
      ${previewHtml}
      <div class="purchase-item-info">
        <div class="purchase-item-name">${item.name}</div>
        <div class="purchase-item-category">${item.category}</div>
        ${priceText}
      </div>
      <div class="purchase-item-overlay">
        <button class="purchase-item-add-btn" data-path="${item.path}" data-category="${item.category}" data-name="${item.name}">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M8 3V13M3 8H13" stroke-linecap="round"/>
          </svg>
          添加
        </button>
      </div>
      ${timeText ? `<div class="purchase-item-time">${timeText}</div>` : ''}
      ${deletedBadge}
    `;
    
    // 绑定添加按钮事件
    const addBtn = div.querySelector('.purchase-item-add-btn');
    if (addBtn) {
      addBtn.addEventListener('click', async (e) => {
        e.stopPropagation();
        const resourcePath = addBtn.dataset.path;
        const categoryDir = addBtn.dataset.category;
        const itemName = addBtn.dataset.name;
        
        await handleAddToDisk(resourcePath, categoryDir, itemName, addBtn);
      });
    }
    
    return div;
  }

  // 处理添加到网盘
  async function handleAddToDisk(resourcePath, categoryDir, itemName, buttonEl) {
    const username = getCurrentUsername();
    if (!username) {
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error('请先登录', 2000);
      }
      return;
    }

    // 禁用按钮
    if (buttonEl) {
      buttonEl.disabled = true;
      buttonEl.textContent = '添加中...';
    }

    try {
      const response = await fetch('/api/pay/purchase', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username,
          resourcePath: resourcePath,
          categoryDir: categoryDir,
          itemName: itemName,
          points: 0 // 已购买，不需要扣除点数
        })
      });

      const result = await response.json();
      
      if (result.success) {
        if (window.parent && window.parent.HintView) {
          window.parent.HintView.success('添加成功！文件已添加到网盘', 2000);
        }
        
        // 通知父窗口刷新网盘
        if (window.parent && window.parent.postMessage) {
          window.parent.postMessage({ type: 'refresh-disk' }, '*');
        }
      } else {
        throw new Error(result.message || '添加失败');
      }
    } catch (error) {
      console.error('[Profile] 添加到网盘失败:', error);
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error(error.message || '添加失败，请稍后重试', 2000);
      }
    } finally {
      // 恢复按钮状态
      if (buttonEl) {
        buttonEl.disabled = false;
        buttonEl.innerHTML = `
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M8 3V13M3 8H13" stroke-linecap="round"/>
          </svg>
          添加
        `;
      }
    }
  }

  // 获取当前登录用户名
  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('[Profile] 获取用户名失败:', error);
      return null;
    }
  }

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

