// 创建 WebSocket 连接
const socket = new WebSocket('ws://localhost:9000/socket'); // 后端WebSocket服务器的地址

socket.onopen = () => {
    console.log('WebSocket 连接已建立');
};

socket.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === 'urlResult') {
        displayUrlResult(data.result);
    } else if (data.type === 'imageResult') {
        displayImageResult(data.result);
    } else if (data.type === 'textResult') {
        displayTextResult(data.result);
    }
};

socket.onerror = (error) => {
    console.error('WebSocket 错误:', error);
};

socket.onclose = () => {
    console.log('WebSocket 连接关闭');
};

// 钓鱼网站检测
function checkPhishingWebsite() {
    const url = document.getElementById('urlInput').value;
    if (url) {
        socket.send(JSON.stringify({ type: 'checkPhishing', url }));
    } else {
        alert("请输入网址");
    }
}

// 聊天图片检测
function checkChatImage() {
    const imageInput = document.getElementById('imageInput');
    if (imageInput.files.length > 0) {
        const file = imageInput.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
            console.info(reader.result)
            console.info(reader.result.length)
            console.info(e.target.result.length)
            socket.send(JSON.stringify({ type: 'checkImage', imageData: reader.result }));
        };
        reader.readAsDataURL(file);
    } else {
        alert("请上传图片进行检测");
    }
}

// 话术检测
function checkScript() {
    const text = document.getElementById('textInput').value;
    if (text) {
        socket.send(JSON.stringify({ type: 'checkScript', text }));
    } else {
        alert("请输入文本进行检测");
    }
}

// 显示检测结果（适配语言切换）
function displayUrlResult(result) {
    const resultDiv = document.getElementById('urlResult');
    const language = localStorage.getItem('language') || 'zh-CN';
    const translations = {
        'zh-CN': {
            warning: '警告！这是一个钓鱼网站。',
            safe: '这个网站看起来安全。',
        },
        'en-US': {
            warning: 'Warning! This is a phishing website.',
            safe: 'This website looks safe.',
        },
    };

    if (result>=50) {
        resultDiv.textContent = translations[language].warning;
        resultDiv.classList.remove('success');
        resultDiv.classList.add('error');
    } else {
        resultDiv.textContent = translations[language].safe;
        resultDiv.classList.remove('error');
        resultDiv.classList.add('success');
    }
}

function displayImageResult(result) {
    const resultDiv = document.getElementById('imageResult');
    const language = localStorage.getItem('language') || 'zh-CN';
    const translations = {
        'zh-CN': {
            warning: '警告！图片检测到可疑内容。',
            safe: '图片通过检测。',
        },
        'en-US': {
            warning: 'Warning! Suspicious content detected in the image.',
            safe: 'The image passed the check.',
        },
    };

    if (result.isSuspicious) {
        resultDiv.textContent = translations[language].warning;
        resultDiv.classList.remove('success');
        resultDiv.classList.add('error');
    } else {
        resultDiv.textContent = translations[language].safe;
        resultDiv.classList.remove('error');
        resultDiv.classList.add('success');
    }
}

function displayTextResult(result) {
    const resultDiv = document.getElementById('textResult');
    const language = localStorage.getItem('language') || 'zh-CN';
    const translations = {
        'zh-CN': {
            warning: '警告！检测到可疑话术。',
            safe: '文本通过检测。',
        },
        'en-US': {
            warning: 'Warning! Suspicious script detected.',
            safe: 'The text passed the check.',
        },
    };

    if (result.isSuspicious) {
        resultDiv.textContent = translations[language].warning;
        resultDiv.classList.remove('success');
        resultDiv.classList.add('error');
    } else {
        resultDiv.textContent = translations[language].safe;
        resultDiv.classList.remove('error');
        resultDiv.classList.add('success');
    }
}

// 语言切换
function switchLanguage(language) {
    const translations = {
        'zh-CN': {
            title: 'AntiScamAI',
            phishingLabel: '钓鱼网站检测',
            phishingPlaceholder: '输入网址进行检测',
            phishingButton: '检测网址',
            imageLabel: '聊天图片检测',
            imageButton: '检测图片',
            textLabel: '话术检测',
            textPlaceholder: '输入文本进行检测',
            textButton: '检测话术',
            darkModeButton: '切换深色模式',
            urlWarning: '警告！这是一个钓鱼网站。',
            urlSafe: '这个网站看起来安全。',
            imageWarning: '警告！图片检测到可疑内容。',
            imageSafe: '图片通过检测。',
            textWarning: '警告！检测到可疑话术。',
            textSafe: '文本通过检测。',
        },
        'en-US': {
            title: 'AntiScamAI',
            phishingLabel: 'Phishing Website Detection',
            phishingPlaceholder: 'Enter URL to check',
            phishingButton: 'Check URL',
            imageLabel: 'Chat Image Detection',
            imageButton: 'Check Image',
            textLabel: 'Script Detection',
            textPlaceholder: 'Enter text to check',
            textButton: 'Check Script',
            darkModeButton: 'Toggle Dark Mode',
            urlWarning: 'Warning! This is a phishing website.',
            urlSafe: 'This website looks safe.',
            imageWarning: 'Warning! Suspicious content detected in the image.',
            imageSafe: 'The image passed the check.',
            textWarning: 'Warning! Suspicious script detected.',
            textSafe: 'The text passed the check.',
        },
    };

    const translation = translations[language];
    document.querySelector('h1').textContent = translation.title;
    document.querySelectorAll('h2')[0].textContent = translation.phishingLabel;
    document.querySelector('#urlInput').placeholder = translation.phishingPlaceholder;
    document.querySelectorAll('button')[2].textContent = translation.phishingButton;
    document.querySelectorAll('h2')[1].textContent = translation.imageLabel;
    document.querySelectorAll('button')[3].textContent = translation.imageButton;
    document.querySelectorAll('h2')[2].textContent = translation.textLabel;
    document.querySelector('#textInput').placeholder = translation.textPlaceholder;
    document.querySelectorAll('button')[4].textContent = translation.textButton;
    document.querySelector('.theme-switcher button').textContent = translation.darkModeButton;

    // 更新结果文本
    const urlResult = document.getElementById('urlResult');
    if (urlResult.textContent.includes('警告')) {
        urlResult.textContent = translation.urlWarning;
    } else if (urlResult.textContent.includes('安全')) {
        urlResult.textContent = translation.urlSafe;
    }

    const imageResult = document.getElementById('imageResult');
    if (imageResult.textContent.includes('警告')) {
        imageResult.textContent = translation.imageWarning;
    } else if (imageResult.textContent.includes('通过')) {
        imageResult.textContent = translation.imageSafe;
    }

    const textResult = document.getElementById('textResult');
    if (textResult.textContent.includes('警告')) {
        textResult.textContent = translation.textWarning;
    } else if (textResult.textContent.includes('通过')) {
        textResult.textContent = translation.textSafe;
    }
}

// 页面加载时初始化语言
window.onload = () => {
    const savedLanguage = localStorage.getItem('language') || 'zh-CN';
    switchLanguage(savedLanguage);
};

// 深色模式切换
function toggleDarkMode() {
    document.body.classList.toggle('dark-theme');
    const isDarkMode = document.body.classList.contains('dark-theme');
    localStorage.setItem('darkMode', isDarkMode);
}

// 页面加载时初始化深色模式
window.onload = () => {
    const isDarkMode = localStorage.getItem('darkMode') === 'true';
    if (isDarkMode) document.body.classList.add('dark-theme');
};