'use client' import { useState, useEffect } from 'react' import { ClickableTextV2 } from '@/components/ClickableTextV2' import { GrammarCorrectionPanel } from '@/components/GrammarCorrectionPanel' export default function DemoV3Page() { const [mode, setMode] = useState<'manual' | 'screenshot'>('manual') const [textInput, setTextInput] = useState('') const [isAnalyzing, setIsAnalyzing] = useState(false) const [showAnalysisView, setShowAnalysisView] = useState(false) const [sentenceAnalysis, setSentenceAnalysis] = useState(null) const [sentenceMeaning, setSentenceMeaning] = useState('') const [grammarCorrection, setGrammarCorrection] = useState(null) const [finalText, setFinalText] = useState('') // 最終用於分析的文本 const [usageCount, setUsageCount] = useState(0) const [isPremium] = useState(false) const [apiConnected, setApiConnected] = useState(false) // 模擬正確句子的分析資料 const mockCorrectSentenceAnalysis = { meaning: "他在我們的會議中提出了這件事,但沒有人同意。這句話表達了在會議中有人提出某個議題或想法,但得不到其他與會者的認同。", grammarCorrection: { hasErrors: false, originalText: "He brought this thing up during our meeting and no one agreed.", correctedText: null, corrections: [], confidenceScore: 0.98 }, highValueWords: ["brought", "up", "meeting", "agreed"], words: { "brought": { word: "brought", translation: "帶來、提出", definition: "Past tense of bring; to take or carry something to a place", partOfSpeech: "verb", pronunciation: "/brɔːt/", synonyms: ["carried", "took", "delivered"], antonyms: ["removed", "took away"], isPhrase: true, isHighValue: true, learningPriority: "high", phraseInfo: { phrase: "bring up", meaning: "提出(話題)、養育", warning: "在這個句子中,\"brought up\" 是一個片語,意思是\"提出話題\",而不是單純的\"帶來\"", colorCode: "#F59E0B" }, difficultyLevel: "B1" }, "meeting": { word: "meeting", translation: "會議", definition: "An organized gathering of people for discussion", partOfSpeech: "noun", pronunciation: "/ˈmiːtɪŋ/", synonyms: ["conference", "assembly", "gathering"], antonyms: [], isPhrase: false, isHighValue: true, learningPriority: "high", difficultyLevel: "B2" }, "thing": { word: "thing", translation: "事情、東西", definition: "An object, fact, or situation", partOfSpeech: "noun", pronunciation: "/θɪŋ/", synonyms: ["object", "matter", "item"], antonyms: [], isPhrase: false, isHighValue: false, learningPriority: "low", difficultyLevel: "A1", costIncurred: 1 } } } // 模擬有語法錯誤的句子分析資料 const mockErrorSentenceAnalysis = { meaning: "我昨天去學校遇見了我的朋友們。這句話描述了過去發生的事情,表達了去學校並遇到朋友的經歷。", grammarCorrection: { hasErrors: true, originalText: "I go to school yesterday and meet my friends.", correctedText: "I went to school yesterday and met my friends.", corrections: [ { position: { start: 2, end: 4 }, errorType: "tense_mismatch", original: "go", corrected: "went", reason: "過去式時態修正:句子中有 'yesterday',應使用過去式", severity: "high" }, { position: { start: 29, end: 33 }, errorType: "tense_mismatch", original: "meet", corrected: "met", reason: "過去式時態修正:與 'went' 保持時態一致", severity: "high" } ], confidenceScore: 0.95 }, highValueWords: ["went", "yesterday", "met", "friends"], words: { "went": { word: "went", translation: "去、前往", definition: "Past tense of go; to move or travel to a place", partOfSpeech: "verb", pronunciation: "/went/", synonyms: ["traveled", "moved", "proceeded"], antonyms: ["stayed", "remained"], isPhrase: false, isHighValue: true, learningPriority: "high", difficultyLevel: "A2" }, "yesterday": { word: "yesterday", translation: "昨天", definition: "The day before today", partOfSpeech: "adverb", pronunciation: "/ˈjestədeɪ/", synonyms: ["the day before"], antonyms: ["tomorrow", "today"], isPhrase: false, isHighValue: true, learningPriority: "medium", difficultyLevel: "A1" }, "met": { word: "met", translation: "遇見、認識", definition: "Past tense of meet; to encounter or come together with", partOfSpeech: "verb", pronunciation: "/met/", synonyms: ["encountered", "saw", "found"], antonyms: ["avoided", "missed"], isPhrase: false, isHighValue: true, learningPriority: "high", difficultyLevel: "A2" }, "friends": { word: "friends", translation: "朋友們", definition: "People you like and know well", partOfSpeech: "noun", pronunciation: "/frends/", synonyms: ["companions", "buddies", "pals"], antonyms: ["enemies", "strangers"], isPhrase: false, isHighValue: true, learningPriority: "medium", difficultyLevel: "A1" }, "school": { word: "school", translation: "學校", definition: "A place where children go to learn", partOfSpeech: "noun", pronunciation: "/skuːl/", synonyms: ["educational institution"], antonyms: [], isPhrase: false, isHighValue: false, learningPriority: "low", difficultyLevel: "A1", costIncurred: 1 } } } // 處理句子分析 - 使用真實API const handleAnalyzeSentence = async () => { if (!textInput.trim()) return if (!isPremium && usageCount >= 5) { alert('❌ 免費用戶 3 小時內只能分析 5 次句子,請稍後再試或升級到付費版本') return } setIsAnalyzing(true) try { console.log('🚀 開始API調用') console.log('📝 輸入文本:', textInput) console.log('🌐 API URL:', 'http://localhost:5000/api/ai/analyze-sentence') // 調用真實的後端API const response = await fetch('http://localhost:5000/api/ai/analyze-sentence', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ inputText: textInput, analysisMode: 'full', forceRefresh: true // 暫時強制刷新,避免舊快取問題 }) }) console.log('📡 API響應狀態:', response.status, response.statusText) console.log('📦 響應頭:', [...response.headers.entries()]) if (!response.ok) { const errorText = await response.text() console.log('❌ 錯誤響應內容:', errorText) throw new Error(`API 錯誤: ${response.status} ${response.statusText} - ${errorText}`) } const result = await response.json() console.log('✅ API響應數據:', result) if (result.success) { console.log('💫 開始更新前端狀態') // 確保數據結構完整 const wordAnalysis = result.data.wordAnalysis || {} const sentenceMeaning = result.data.sentenceMeaning || {} const grammarCorrection = result.data.grammarCorrection || { hasErrors: false } const finalText = result.data.finalAnalysisText || textInput console.log('📊 詞彙分析詞數:', Object.keys(wordAnalysis).length) console.log('🎯 高價值詞彙:', result.data.highValueWords) console.log('📝 翻譯內容:', sentenceMeaning.translation) // 批次更新狀態,避免競態條件 setSentenceAnalysis(wordAnalysis) setSentenceMeaning((sentenceMeaning.translation || '翻譯處理中...') + ' ' + (sentenceMeaning.explanation || '解釋處理中...')) setGrammarCorrection(grammarCorrection) setFinalText(finalText) // 延遲顯示分析視圖,確保狀態更新完成 setTimeout(() => { setShowAnalysisView(true) console.log('✅ 分析視圖已顯示') }, 100) setUsageCount(prev => prev + 1) console.log('🎉 狀態更新完成') } else { throw new Error(result.error || '分析失敗') } } catch (error) { console.error('❌ API錯誤詳情:', error) // 不要自動回退到模擬資料,讓用戶知道真實錯誤 alert(`🔌 無法連接到後端API:\n\n${error instanceof Error ? error.message : '未知錯誤'}\n\n請檢查:\n1. 後端服務是否運行在 localhost:5000\n2. CORS 設定是否正確\n3. 網路連接是否正常`) // 重置分析狀態 setShowAnalysisView(false) } finally { setIsAnalyzing(false) } } const handleAcceptCorrection = () => { if (grammarCorrection?.correctedText) { setFinalText(grammarCorrection.correctedText) // 這裡可以重新分析修正後的句子 alert('✅ 已採用修正版本,後續學習將基於正確的句子進行!') } } const handleRejectCorrection = () => { setFinalText(grammarCorrection?.originalText || textInput) alert('📝 已保持原始版本,將基於您的原始輸入進行學習。') } // 檢查API連接狀態 useEffect(() => { const checkApiConnection = async () => { try { const response = await fetch('http://localhost:5000/api/ai/test/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ inputText: 'test', extractionType: 'vocabulary', cardCount: 1 }) }) setApiConnected(response.ok) } catch (error) { setApiConnected(false) } } checkApiConnection() }, []) return (
{/* Navigation */}
{!showAnalysisView ? (

AI 智能語法修正 + 高價值標記系統

{/* API 連接狀態 */}
{apiConnected ? '✅' : '❌'} 後端 API 連接狀態: {apiConnected ? '已連接' : '未連接'}
{!apiConnected && (

請確認後端服務正在 http://localhost:5000 運行

)}
{/* 功能說明 */}

🔧 語法修正 + 高價值標記特色

智能錯誤檢測 - 9種語法錯誤類型
🔧 自動修正建議 - 詳細修正說明
高價值標記 - 基於修正後句子
💰 成本優化 - 語法修正不額外收費
{/* Content Input */}

輸入英文文本 (更新:300字限制)