// UI Utilities module for Overleaf Chrome Extension
// 通用UI函数：错误提示、成功提示、页面切换等

// 错误消息自动隐藏定时器
let errorHideTimer = null;

// AI 模型错误的建议提示
const AI_MODEL_ERROR_HINT = '\n建议：尝试更高级的模型或更高的思考程度，初级模型+低思考可能无法正确返回所需格式。';

// Show error message
function showError(message) {
    const errorEl = document.getElementById('error-message');
    errorEl.textContent = message;
    errorEl.classList.remove('hidden');
    errorEl.classList.add('animate-slideIn');
    document.getElementById('success-message').classList.add('hidden');

    // 清除之前的定时器
    if (errorHideTimer) {
        clearTimeout(errorHideTimer);
    }

    // 15秒后自动隐藏
    errorHideTimer = setTimeout(() => {
        errorEl.classList.add('hidden');
        errorHideTimer = null;
    }, 15000);
}

// Show AI model related error with hint to try higher model/thinking level
function showAIModelError(message) {
    showError(message + AI_MODEL_ERROR_HINT);
}

// Clear error message
function clearError() {
    const errorEl = document.getElementById('error-message');
    errorEl.classList.add('hidden');

    // 清除定时器
    if (errorHideTimer) {
        clearTimeout(errorHideTimer);
        errorHideTimer = null;
    }
}

// Show success message
function showSuccess(message, isLoading = false) {
    const successEl = document.getElementById('success-message');

    if (isLoading) {
        successEl.innerHTML = `<svg class="inline w-4 h-4 mr-2 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>${message}`;
        successEl.className = 'px-4 py-3 bg-blue-50 border-b border-blue-100 text-blue-700 text-sm animate-slideIn';
    } else {
        successEl.textContent = message;
        successEl.className = 'px-4 py-3 bg-green-50 border-b border-green-100 text-green-700 text-sm animate-slideIn';
    }

    successEl.classList.remove('hidden');
    document.getElementById('error-message').classList.add('hidden');

    // Only auto-hide if not loading
    if (!isLoading) {
        setTimeout(() => {
            successEl.classList.add('hidden');
        }, 3000);
    }
}

// Page navigation
function showPage(pageId) {
    // Hide all pages
    document.querySelectorAll('.page').forEach(page => {
        page.classList.remove('active');
    });
    // Show target page
    document.getElementById(pageId).classList.add('active');
    currentPageId = pageId; // 跟踪当前页面
}

function goToHomePage() {
    showPage('home-page');
}

// Update last update time display
function updateLastUpdateTime(timestamp) {
    const element = document.getElementById('last-update');
    if (!element) return;

    if (!timestamp) {
        element.textContent = '--';
        return;
    }

    const date = new Date(timestamp);
    element.textContent = date.toLocaleTimeString();
}

// Update VIP status display
function updateVipDisplay(vipStatus) {
    const vipStatusEl = document.getElementById('user-vip-status');
    const vipExpireEl = document.getElementById('vip-expire-time');

    if (!vipStatusEl) return;

    if (vipStatus.isVip) {
        vipStatusEl.textContent = `VIP${vipStatus.vipLevel}`;
        vipStatusEl.className = 'vip-status active';
        if (vipExpireEl) {
            const remainingDays = authService.calculateRemainingDays(vipStatus.expireAt);
            vipExpireEl.textContent = `剩余 ${remainingDays} 天`;
            vipExpireEl.style.display = 'block';
        }
    } else {
        vipStatusEl.textContent = '普通用户';
        vipStatusEl.className = 'vip-status';
        if (vipExpireEl) {
            vipExpireEl.style.display = 'none';
        }
    }
}

// Translation buttons update (selected text display)
function updateTranslationButtons() {
    const selectedTextDisplay = document.getElementById('selected-text-display');

    if (selectedText && selectedText.trim()) {
        selectedTextDisplay.textContent = selectedText.length > 50 ?
            selectedText.substring(0, 47) + '...' : selectedText;
        selectedTextDisplay.classList.remove('italic');
    } else {
        selectedTextDisplay.textContent = '无';
        selectedTextDisplay.classList.add('italic');
    }
}

// Update connection status display (in header)
function updateConnectionStatus(isConnected) {
    const statusDot = document.getElementById('status-dot');
    const statusText = document.getElementById('status-text');

    if (!statusDot || !statusText) return;

    if (isConnected) {
        statusDot.className = 'w-2 h-2 rounded-full bg-green-500';
        statusText.textContent = '已连接';
        statusText.className = 'text-xs text-green-600';
    } else {
        statusDot.className = 'w-2 h-2 rounded-full bg-red-500';
        statusText.textContent = '未连接';
        statusText.className = 'text-xs text-slate-500';
    }
}
