/**
 * fluentx 个人中心脚本
 * 左侧菜单 + 两个页面：通用设置 / 订阅激活
 */

// 导入 i18n
import { initI18n, t, setLanguage, getCurrentLanguage, applyTranslations } from './i18n/index.js';

// 语言配置
const languages = [
  { code: 'en', flag: '🇺🇸', name: 'English', native: 'English' },
  { code: 'zh-CN', flag: '🇨🇳', name: 'Simplified Chinese', native: '简体中文' },
  { code: 'zh-TW', flag: '🇹🇼', name: 'Traditional Chinese', native: '繁體中文' },
  { code: 'ja', flag: '🇯🇵', name: 'Japanese', native: '日本語' },
  { code: 'ko', flag: '🇰🇷', name: 'Korean', native: '한국어' },
  { code: 'es', flag: '🇪🇸', name: 'Spanish', native: 'Español' },
  { code: 'fr', flag: '🇫🇷', name: 'French', native: 'Français' },
  { code: 'de', flag: '🇩🇪', name: 'German', native: 'Deutsch' },
  { code: 'pt', flag: '🇵🇹', name: 'Portuguese', native: 'Português' },
  { code: 'ru', flag: '🇷🇺', name: 'Russian', native: 'Русский' },
];

// 当前选择的语言
let currentLanguage = 'en';
let currentPage = 'general';

/**
 * 初始化
 */
async function init() {

  try {
    // 初始化 i18n
    currentLanguage = await initI18n();
    
    // 应用翻译到页面
    applyTranslations();
    
    // 渲染激活码帮助列表
    renderActivationHelpList();

    // 渲染语言网格
    renderLanguageGrid();

    // 加载功能设置
    await loadFeatureSettings();

    // 初始化认证管理器
    const isLoggedIn = await authManager.init();

    // 根据登录状态更新 UI
    updateUIBasedOnLoginStatus(isLoggedIn);

    // 绑定事件
    bindEvents();

    // 处理 URL hash 导航
    handleHashNavigation();
    window.addEventListener('hashchange', handleHashNavigation);

  } catch (error) {
    showToast(t('messages.error'), 'error');
  }
}

/**
 * 根据登录状态更新 UI
 */
async function updateUIBasedOnLoginStatus(isLoggedIn) {
  if (isLoggedIn) {
    try {
      // 强制从后端获取最新状态（包括过期检查）
      await authManager.verifyToken();
      showLoggedInState();
    } catch (error) {
      showLoggedOutState();
    }
  } else {
    showLoggedOutState();
  }
}

/**
 * 显示已登录状态
 */
function showLoggedInState() {
  // 通用设置页面
  document.getElementById('loginSection').style.display = 'none';
  document.getElementById('userInfoSection').style.display = 'block';
  
  // 侧边栏用户卡片
  document.getElementById('sidebarUserCard').style.display = 'flex';
  
  // 订阅页面
  document.getElementById('subscriptionLoginPrompt').style.display = 'none';
  document.getElementById('subscriptionContent').style.display = 'block';
  
  // 渲染用户信息
  renderUserInfo();
  
  // 渲染订阅状态
  renderSubscriptionStatus();
}

/**
 * 显示未登录状态
 */
function showLoggedOutState() {
  // 通用设置页面
  document.getElementById('loginSection').style.display = 'block';
  document.getElementById('userInfoSection').style.display = 'none';
  
  // 侧边栏用户卡片
  document.getElementById('sidebarUserCard').style.display = 'none';
  
  // 订阅页面
  document.getElementById('subscriptionLoginPrompt').style.display = 'block';
  document.getElementById('subscriptionContent').style.display = 'none';
}

/**
 * 渲染用户信息
 */
function renderUserInfo() {
  const user = authManager.getUser();
  if (!user) return;

  // 通用设置页面
  document.getElementById('userAvatar').src = user.picture || 'icons/touxiang.jpg';
  document.getElementById('userName').textContent = user.name || 'User';
  document.getElementById('userEmail').textContent = user.email || '';

  // 侧边栏
  document.getElementById('sidebarAvatar').src = user.picture || 'icons/touxiang.jpg';
  document.getElementById('sidebarUserName').textContent = user.name || 'User';
  document.getElementById('sidebarUserEmail').textContent = user.email || '';
}

/**
 * 渲染订阅状态
 */
function renderSubscriptionStatus() {
  const subscription = authManager.getSubscription();
  const statusCard = document.getElementById('subscriptionStatusCard');
  const activationCard = document.getElementById('activationCard');
  
  if (!subscription) {
    statusCard.innerHTML = `<p>${t('messages.loading')}</p>`;
    return;
  }

  const status = subscription.status;
  let html = '';
  let cardClass = 'subscription-status-card';

  if (status === 'inactive') {
    cardClass += ' status-inactive';
    html = `
      <div class="status-content">
        <div class="status-icon">⚠️</div>
        <h3 class="status-title">${t('subscription.status.inactive.title')}</h3>
        <p class="status-description">
          ${t('subscription.status.inactive.description')}
        </p>
      </div>
      <div class="qrcode-box">
        <img src="icons/qrcode.png" alt="微信二维码" class="qrcode-img">
        <p class="qrcode-text">扫描提需求</p>
      </div>
    `;
    activationCard.style.display = 'block';
  } else if (status === 'trial') {
    // 检查 expiresAt 是否有效
    if (!subscription.expiresAt) {
      // 回退到未激活状态
      cardClass += ' status-inactive';
      html = `
        <div class="status-content">
          <div class="status-icon">⚠️</div>
          <h3 class="status-title">${t('subscription.status.inactive.title')}</h3>
          <p class="status-description">
            ${t('subscription.status.inactive.description')}
          </p>
        </div>
        <div class="qrcode-box">
          <img src="icons/qrcode.png" alt="微信二维码" class="qrcode-img">
          <p class="qrcode-text">扫描提需求</p>
        </div>
      `;
      activationCard.style.display = 'block';
    } else {
      const expiresAt = new Date(subscription.expiresAt);
      const now = new Date();
      const daysLeft = Math.ceil((expiresAt - now) / (1000 * 60 * 60 * 24));
      
      cardClass += ' status-trial';
      html = `
        <div class="status-icon">🎁</div>
        <h3 class="status-title">${t('subscription.status.trial.title')}</h3>
        <p class="status-description">
          ${t('subscription.status.trial.description', { 
            days: daysLeft, 
            date: expiresAt.toLocaleDateString() 
          })}
        </p>
        <div class="website-link-container">
          <a href="https://mikeyang.cc" target="_blank" class="website-link">
            <svg class="website-link-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
              <polyline points="15 3 21 3 21 9"></polyline>
              <line x1="10" y1="14" x2="21" y2="3"></line>
            </svg>
            <span>${t('subscription.status.visitWebsite')}</span>
          </a>
        </div>
      `;
      activationCard.style.display = 'none';
    }
  } else if (status === 'active') {
    // 检查 expiresAt 是否有效
    if (!subscription.expiresAt) {
      // 显示激活状态但不显示日期
      cardClass += ' status-active';
      html = `
        <div class="status-icon">✅</div>
        <h3 class="status-title">${t('subscription.status.active.title')}</h3>
        <p class="status-description">
          Your subscription is active
        </p>
        <div class="website-link-container">
          <a href="https://mikeyang.cc" target="_blank" class="website-link">
            <svg class="website-link-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
              <polyline points="15 3 21 3 21 9"></polyline>
              <line x1="10" y1="14" x2="21" y2="3"></line>
            </svg>
            <span>${t('subscription.status.visitWebsite')}</span>
          </a>
        </div>
      `;
      activationCard.style.display = 'none';
    } else {
      const expiresAt = new Date(subscription.expiresAt);
      cardClass += ' status-active';
      html = `
        <div class="status-icon">✅</div>
        <h3 class="status-title">${t('subscription.status.active.title')}</h3>
        <p class="status-description">
          ${t('subscription.status.active.description', { 
            date: expiresAt.toLocaleDateString() 
          })}
        </p>
        <div class="website-link-container">
          <a href="https://mikeyang.cc" target="_blank" class="website-link">
            <svg class="website-link-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
              <polyline points="15 3 21 3 21 9"></polyline>
              <line x1="10" y1="14" x2="21" y2="3"></line>
            </svg>
            <span>${t('subscription.status.visitWebsite')}</span>
          </a>
        </div>
      `;
      activationCard.style.display = 'none';
    }
  } else if (status === 'expired') {
    cardClass += ' status-expired';
    const expiredType = subscription.plan === 'trial' 
      ? t('subscription.status.expired.typeTrial') 
      : t('subscription.status.expired.typeSubscription');
    html = `
      <div class="status-icon">❌</div>
      <h3 class="status-title">${t('subscription.status.expired.title')}</h3>
      <p class="status-description">
        ${t('subscription.status.expired.description', { type: expiredType })}
      </p>
    `;
    activationCard.style.display = 'block';
  } else if (status === 'cancelled') {
    cardClass += ' status-cancelled';
    html = `
      <div class="status-icon">⚠️</div>
      <h3 class="status-title">${t('subscription.status.expired.title')}</h3>
      <p class="status-description">
        ${t('subscription.status.expired.description', { 
          type: t('subscription.status.expired.typeSubscription') 
        })}
      </p>
    `;
    activationCard.style.display = 'block';
  } else {
    // 其他未知状态，默认显示未激活
    cardClass += ' status-inactive';
    html = `
      <div class="status-icon">⚠️</div>
      <h3 class="status-title">${t('subscription.status.inactive.title')}</h3>
      <p class="status-description">
        ${t('subscription.status.inactive.description')}
      </p>
    `;
    activationCard.style.display = 'block';
  }

  statusCard.className = cardClass;
  statusCard.innerHTML = html;
}

/**
 * 渲染激活码帮助列表
 */
function renderActivationHelpList() {
  const helpList = document.getElementById('activationHelpList');
  if (!helpList) return;
  
  const step1_part1 = t('subscription.activation.howToGet.step1_part1');
  const step1_part2 = t('subscription.activation.howToGet.step1_part2');
  const step2_part1 = t('subscription.activation.howToGet.step2_part1');
  const step3 = t('subscription.activation.howToGet.step3');
  const linkText = t('subscription.activation.howToGet.linkText');
  const replyText = t('subscription.activation.howToGet.replyText');
  
  helpList.innerHTML = `
    <li>
      ${step1_part1} 
      <a href="https://x.com/Mike_yanger" target="_blank" rel="noopener noreferrer">${linkText}</a> 
      ${step1_part2}
    </li>
    <li>
      ${step2_part1}
      <strong>${replyText}</strong>
    </li>
    <li>${step3}</li>
  `;
}

/**
 * 渲染语言网格
 */
function renderLanguageGrid() {
  const grid = document.getElementById('languageGrid');
  if (!grid) return;

  grid.innerHTML = '';
  
  languages.forEach(lang => {
    const card = document.createElement('div');
    card.className = 'language-card';
    card.innerHTML = `
      <div class="language-flag">${lang.flag}</div>
      <div class="language-name">${lang.native}</div>
    `;
    
    // 检查是否为当前选择
    if (currentLanguage === lang.code) {
      card.classList.add('selected');
    }
    
    // 点击事件
    card.addEventListener('click', () => handleLanguageSelect(lang.code));
    
    grid.appendChild(card);
  });
}

/**
 * 处理语言选择
 */
async function handleLanguageSelect(langCode) {
  try {
    currentLanguage = langCode;
    
    // 设置 i18n 语言
    setLanguage(langCode);
    
    // 应用翻译到页面
    applyTranslations();
    
    // 渲染激活码帮助列表
    renderActivationHelpList();
    
    // 更新所有网格的选中状态
    renderLanguageGrid();
    
    // 重新渲染订阅状态（使用新语言）
    renderSubscriptionStatus();
    
    // 显示成功消息
    showToast(t('messages.languageSaved'), 'success');
  } catch (error) {
    showToast(t('messages.error'), 'error');
  }
}

/**
 * 处理页面导航
 */
function handleHashNavigation() {
  const hash = window.location.hash.slice(1) || 'general';
  switchPage(hash);
}

/**
 * 切换页面
 */
function switchPage(pageName) {
  // 更新当前页面
  currentPage = pageName;
  
  // 隐藏所有页面
  document.querySelectorAll('.page-content').forEach(page => {
    page.classList.remove('active');
  });
  
  // 显示目标页面
  const targetPage = document.getElementById(`${pageName}Page`);
  if (targetPage) {
    targetPage.classList.add('active');
  }
  
  // 更新菜单激活状态
  document.querySelectorAll('.nav-item').forEach(item => {
    item.classList.remove('active');
  });
  const activeNav = document.querySelector(`.nav-item[data-page="${pageName}"]`);
  if (activeNav) {
    activeNav.classList.add('active');
  }
  
}

/**
 * 绑定事件
 */
function bindEvents() {
  // 菜单导航
  document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('click', (e) => {
      e.preventDefault();
      const pageName = item.getAttribute('data-page');
      window.location.hash = pageName;
    });
  });

  // Google 登录按钮
  const googleLoginBtn = document.getElementById('googleLoginBtn');
  if (googleLoginBtn) {
    googleLoginBtn.addEventListener('click', handleGoogleLogin);
  }

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

  // 推文翻译按钮开关
  const tweetTranslateToggle = document.getElementById('tweetTranslateButtonToggle');
  if (tweetTranslateToggle) {
    tweetTranslateToggle.addEventListener('change', handleTweetTranslateToggleChange);
  }

  // 激活按钮
  const activateBtn = document.getElementById('activateBtn');
  if (activateBtn) {
    activateBtn.addEventListener('click', handleActivate);
  }

  // 激活码输入框回车
  const activationInput = document.getElementById('activationCodeInput');
  if (activationInput) {
    activationInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        handleActivate();
      }
    });
  }

  // 前往通用设置按钮
  const goToGeneralBtn = document.getElementById('goToGeneralBtn');
  if (goToGeneralBtn) {
    goToGeneralBtn.addEventListener('click', () => {
      window.location.hash = 'general';
    });
  }
}

/**
 * 处理 Google 登录
 */
async function handleGoogleLogin() {
  const loginLoading = document.getElementById('loginLoading');
  const loginError = document.getElementById('loginError');
  const googleLoginBtn = document.getElementById('googleLoginBtn');

  try {
    googleLoginBtn.disabled = true;
    loginLoading.style.display = 'flex';
    loginError.style.display = 'none';


    await authManager.startGoogleLogin();

    showLoggedInState();
    showToast('Login successful!', 'success');
    
    // 自动跳转到订阅页面
    setTimeout(() => {
      window.location.hash = 'subscription';
    }, 1000);
    
  } catch (error) {
    loginError.textContent = error.message || 'Login failed. Please try again.';
    loginError.style.display = 'block';
    showToast('Login failed', 'error');
  } finally {
    googleLoginBtn.disabled = false;
    loginLoading.style.display = 'none';
  }
}

/**
 * 处理登出
 */
async function handleLogout() {
  if (confirm('Are you sure you want to logout?')) {
    await authManager.logout();
    showLoggedOutState();
    showToast('Logged out successfully', 'info');
    
    // 跳转到通用设置页面
    window.location.hash = 'general';
  }
}

/**
 * 处理激活
 */
async function handleActivate() {
  const input = document.getElementById('activationCodeInput');
  const activateBtn = document.getElementById('activateBtn');
  const message = document.getElementById('activationMessage');
  
  const code = input.value.trim().toUpperCase();
  
  if (!code) {
    message.textContent = 'Please enter an activation code';
    message.className = 'message-box error';
    message.style.display = 'block';
    return;
  }

  activateBtn.disabled = true;
  activateBtn.textContent = 'Activating...';
  message.style.display = 'none';

  try {
    await authManager.activateTrial(code);
    
    message.textContent = '✅ Trial activated successfully!';
    message.className = 'message-box success';
    message.style.display = 'block';
    
    showToast('Trial activated successfully!', 'success');
    
    // 强制从后端刷新最新状态
    await authManager.verifyToken();
    
    // 1.5秒后刷新订阅状态显示
    setTimeout(() => {
      renderSubscriptionStatus();
      input.value = '';
      message.style.display = 'none';
    }, 1500);
  } catch (error) {
    message.textContent = `❌ ${error.message}`;
    message.className = 'message-box error';
    message.style.display = 'block';
    
    showToast('Activation failed', 'error');
  } finally {
    activateBtn.disabled = false;
    activateBtn.textContent = 'Activate';
  }
}

/**
 * 加载功能设置
 */
async function loadFeatureSettings() {
  try {
    const settings = await chrome.storage.sync.get({ 
      tweetTranslateButtonEnabled: true // 默认开启
    });
    
    const toggle = document.getElementById('tweetTranslateButtonToggle');
    if (toggle) {
      toggle.checked = settings.tweetTranslateButtonEnabled;
    }
  } catch (error) {
    console.error('加载功能设置失败:', error);
  }
}

/**
 * 处理推文翻译按钮开关变化
 */
async function handleTweetTranslateToggleChange(e) {
  const enabled = e.target.checked;
  
  try {
    await chrome.storage.sync.set({ 
      tweetTranslateButtonEnabled: enabled 
    });
    
    showToast(
      enabled 
        ? t('settings.features.tweetTranslateButton.enabled') 
        : t('settings.features.tweetTranslateButton.disabled'),
      'success'
    );
  } catch (error) {
    console.error('保存功能设置失败:', error);
    showToast(t('messages.error'), 'error');
    // 恢复原状态
    e.target.checked = !enabled;
  }
}

/**
 * 显示全局消息提示
 */
function showToast(text, type = 'info') {
  const toast = document.getElementById('globalMessage');
  toast.textContent = text;
  toast.className = `toast-message ${type}`;
  toast.style.display = 'block';
  
  // 3秒后自动隐藏
  setTimeout(() => {
    toast.style.display = 'none';
  }, 3000);
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', init);
