'use client' import { useState, useMemo, useCallback } from 'react' import { ProtectedRoute } from '@/components/ProtectedRoute' import { Navigation } from '@/components/Navigation' import { ClickableTextV2 } from '@/components/ClickableTextV2' import { flashcardsService } from '@/lib/services/flashcards' import Link from 'next/link' // 常數定義 const CEFR_LEVELS = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'] as const const MAX_MANUAL_INPUT_LENGTH = 300 // 工具函數 const getLevelIndex = (level: string): number => { return CEFR_LEVELS.indexOf(level as typeof CEFR_LEVELS[number]) } const getTargetLearningRange = (userLevel: string): string => { const ranges: Record = { 'A1': 'A2-B1', 'A2': 'B1-B2', 'B1': 'B2-C1', 'B2': 'C1-C2', 'C1': 'C2', 'C2': 'C2' } return ranges[userLevel] || 'B1-B2' } interface GrammarCorrection { hasErrors: boolean; originalText: string; correctedText: string; corrections: Array<{ error: string; correction: string; type: string; explanation: string; }>; } interface PhrasePopup { phrase: string; analysis: any; position: { x: number; y: number }; } function GenerateContent() { const [textInput, setTextInput] = useState('') const [isAnalyzing, setIsAnalyzing] = useState(false) const [showAnalysisView, setShowAnalysisView] = useState(false) const [sentenceAnalysis, setSentenceAnalysis] = useState | null>(null) const [sentenceMeaning, setSentenceMeaning] = useState('') const [grammarCorrection, setGrammarCorrection] = useState(null) const [finalText, setFinalText] = useState('') const [phrasePopup, setPhrasePopup] = useState(null) // 處理句子分析 - 使用假資料測試 const handleAnalyzeSentence = async () => { console.log('🚀 handleAnalyzeSentence 被調用 (假資料模式)') setIsAnalyzing(true) try { // 模擬API延遲 await new Promise(resolve => setTimeout(resolve, 1000)) // 使用有語法錯誤的測試句子 const testSentence = "She just join the team, so let's cut her some slack until she get used to the workflow." // 假資料:完整詞彙分析結果 (包含句子中的所有詞彙) const mockAnalysis = { "she": { word: "she", translation: "她", definition: "female person pronoun", partOfSpeech: "pronoun", pronunciation: "/ʃiː/", difficultyLevel: "A1", isPhrase: false, synonyms: ["her"], example: "She is a teacher.", exampleTranslation: "她是一名老師。" }, "just": { word: "just", translation: "剛剛;僅僅", definition: "recently; only", partOfSpeech: "adverb", pronunciation: "/dʒʌst/", difficultyLevel: "A2", isPhrase: false, synonyms: ["recently", "only", "merely"], example: "I just arrived.", exampleTranslation: "我剛到。" }, "join": { word: "join", translation: "加入", definition: "to become a member of", partOfSpeech: "verb", pronunciation: "/dʒɔɪn/", difficultyLevel: "B1", isPhrase: false, synonyms: ["enter", "become part of"], example: "I want to join the team.", exampleTranslation: "我想加入團隊。" }, "the": { word: "the", translation: "定冠詞", definition: "definite article", partOfSpeech: "article", pronunciation: "/ðə/", difficultyLevel: "A1", isPhrase: false, synonyms: [], example: "The cat is sleeping.", exampleTranslation: "貓在睡覺。" }, "team": { word: "team", translation: "團隊", definition: "a group of people working together", partOfSpeech: "noun", pronunciation: "/tiːm/", difficultyLevel: "A2", isPhrase: false, synonyms: ["group", "crew"], example: "Our team works well together.", exampleTranslation: "我們的團隊合作得很好。" }, "so": { word: "so", translation: "所以;如此", definition: "therefore; to such a degree", partOfSpeech: "adverb", pronunciation: "/soʊ/", difficultyLevel: "A1", isPhrase: false, synonyms: ["therefore", "thus"], example: "It was raining, so I stayed home.", exampleTranslation: "下雨了,所以我待在家裡。" }, "let's": { word: "let's", translation: "讓我們", definition: "let us (contraction)", partOfSpeech: "contraction", pronunciation: "/lets/", difficultyLevel: "A1", isPhrase: false, synonyms: ["let us"], example: "Let's go to the park.", exampleTranslation: "我們去公園吧。" }, "cut": { word: "cut", translation: "切;削減", definition: "to use a knife or other sharp tool to divide something", partOfSpeech: "verb", pronunciation: "/kʌt/", difficultyLevel: "A2", isPhrase: false, synonyms: ["slice", "chop", "reduce"], example: "Please cut the apple.", exampleTranslation: "請切蘋果。" }, "her": { word: "her", translation: "她的;她", definition: "belonging to or associated with a female", partOfSpeech: "pronoun", pronunciation: "/hər/", difficultyLevel: "A1", isPhrase: false, synonyms: ["hers"], example: "This is her book.", exampleTranslation: "這是她的書。" }, "some": { word: "some", translation: "一些", definition: "an unspecified amount or number of", partOfSpeech: "determiner", pronunciation: "/sʌm/", difficultyLevel: "A1", isPhrase: false, synonyms: ["several", "a few"], example: "I need some help.", exampleTranslation: "我需要一些幫助。" }, "slack": { word: "slack", translation: "寬鬆;懈怠", definition: "looseness; lack of tension", partOfSpeech: "noun", pronunciation: "/slæk/", difficultyLevel: "B1", isPhrase: false, synonyms: ["looseness", "leeway"], example: "There's too much slack in this rope.", exampleTranslation: "這條繩子太鬆了。" }, "until": { word: "until", translation: "直到", definition: "up to a particular time", partOfSpeech: "preposition", pronunciation: "/ʌnˈtɪl/", difficultyLevel: "A2", isPhrase: false, synonyms: ["till", "up to"], example: "Wait until tomorrow.", exampleTranslation: "等到明天。" }, "get": { word: "get", translation: "變得;獲得", definition: "to become or obtain", partOfSpeech: "verb", pronunciation: "/ɡet/", difficultyLevel: "A1", isPhrase: false, synonyms: ["become", "obtain"], example: "I get tired easily.", exampleTranslation: "我很容易累。" }, "used": { word: "used", translation: "習慣的", definition: "familiar with something (used to)", partOfSpeech: "adjective", pronunciation: "/juːzd/", difficultyLevel: "A2", isPhrase: false, synonyms: ["accustomed", "familiar"], example: "I'm not used to this weather.", exampleTranslation: "我不習慣這種天氣。" }, "to": { word: "to", translation: "到;向", definition: "preposition expressing direction", partOfSpeech: "preposition", pronunciation: "/tu/", difficultyLevel: "A1", isPhrase: false, synonyms: [], example: "I'm going to school.", exampleTranslation: "我要去學校。" }, "workflow": { word: "workflow", translation: "工作流程", definition: "the sequence of processes through which work passes", partOfSpeech: "noun", pronunciation: "/ˈwɜːrkfloʊ/", difficultyLevel: "B2", isPhrase: false, synonyms: ["process", "procedure", "system"], example: "We need to improve our workflow.", exampleTranslation: "我們需要改善工作流程。" }, "joined": { word: "joined", translation: "加入", definition: "became a member of (past tense of join)", partOfSpeech: "verb", pronunciation: "/dʒɔɪnd/", difficultyLevel: "B1", isPhrase: false, synonyms: ["entered", "became part of"], example: "He joined the company last year.", exampleTranslation: "他去年加入了這家公司。" }, "gets": { word: "gets", translation: "變得;獲得", definition: "becomes or obtains (third person singular)", partOfSpeech: "verb", pronunciation: "/ɡets/", difficultyLevel: "A1", isPhrase: false, synonyms: ["becomes", "obtains"], example: "It gets cold at night.", exampleTranslation: "晚上會變冷。" }, "cut someone some slack": { word: "cut someone some slack", translation: "對某人寬容一點", definition: "to be more lenient or forgiving with someone", partOfSpeech: "idiom", pronunciation: "/kʌt ˈsʌmwʌn sʌm slæk/", difficultyLevel: "B2", isPhrase: true, synonyms: ["be lenient", "be forgiving", "give leeway"], example: "Cut him some slack, he's new here.", exampleTranslation: "對他寬容一點,他是新來的。" }, } // 設定結果 - 包含語法錯誤情境 setFinalText("She just joined the team, so let's cut her some slack until she gets used to the workflow.") // 修正後的句子 setSentenceAnalysis(mockAnalysis) setSentenceMeaning("她剛加入團隊,所以讓我們對她寬容一點,直到她習慣工作流程。") setGrammarCorrection({ hasErrors: true, originalText: testSentence, // 有錯誤的原始句子 correctedText: "She just joined the team, so let's cut her some slack until she gets used to the workflow.", corrections: [ { error: "join", correction: "joined", type: "時態錯誤", explanation: "第三人稱單數過去式應使用 'joined'" }, { error: "get", correction: "gets", type: "時態錯誤", explanation: "第三人稱單數現在式應使用 'gets'" } ] }) setShowAnalysisView(true) console.log('✅ 假資料設定完成') } catch (error) { console.error('Error in sentence analysis:', error) setGrammarCorrection({ hasErrors: true, originalText: textInput, correctedText: textInput, corrections: [] }) setSentenceMeaning('分析過程中發生錯誤,請稍後再試。') setFinalText(textInput) setShowAnalysisView(true) } finally { setIsAnalyzing(false) } } const handleAcceptCorrection = useCallback(() => { if (grammarCorrection?.correctedText) { setFinalText(grammarCorrection.correctedText) console.log('✅ 已採用修正版本,後續學習將基於正確的句子進行!') } }, [grammarCorrection?.correctedText]) const handleRejectCorrection = useCallback(() => { setFinalText(grammarCorrection?.originalText || textInput) console.log('📝 已保持原始版本,將基於您的原始輸入進行學習。') }, [grammarCorrection?.originalText, textInput]) // 詞彙統計計算 - 移到組件頂層避免Hooks順序問題 const vocabularyStats = useMemo(() => { if (!sentenceAnalysis) return null const userLevel = localStorage.getItem('userEnglishLevel') || 'A2' let simpleCount = 0 let moderateCount = 0 let difficultCount = 0 let phraseCount = 0 Object.entries(sentenceAnalysis).forEach(([, wordData]: [string, any]) => { const isPhrase = wordData?.isPhrase || wordData?.IsPhrase const difficultyLevel = wordData?.difficultyLevel || 'A1' if (isPhrase) { phraseCount++ } else { const userIndex = getLevelIndex(userLevel) const wordIndex = getLevelIndex(difficultyLevel) if (userIndex > wordIndex) { simpleCount++ } else if (userIndex === wordIndex) { moderateCount++ } else { difficultCount++ } } }) return { simpleCount, moderateCount, difficultCount, phraseCount } }, [sentenceAnalysis]) // 保存單個詞彙 const handleSaveWord = useCallback(async (word: string, analysis: any) => { try { const cardData = { word: word, translation: analysis.translation || analysis.Translation || '', definition: analysis.definition || analysis.Definition || '', pronunciation: analysis.pronunciation || analysis.Pronunciation || `/${word}/`, partOfSpeech: analysis.partOfSpeech || analysis.PartOfSpeech || 'unknown', example: `Example sentence with ${word}.` // 提供預設例句 } const response = await flashcardsService.createFlashcard(cardData) if (response.success) { console.log(`✅ 已將「${word}」保存到詞卡!`) return { success: true } } else { throw new Error(response.error || '保存失敗') } } catch (error) { console.error('Save word error:', error) return { success: false, error: error instanceof Error ? error.message : '保存失敗' } } }, []) return (
{!showAnalysisView ? (

AI 智能生成詞卡

{/* Content Input */}

輸入英文文本