
import React, { useState, useEffect, useRef } from 'react';
import { User, StudentProfile, SavedRecord, Zodiac, Personality, Hobby } from '../../types';
import { api } from '../../services/api';
import { FileSpreadsheet, Loader2, Sparkles, Copy, Save, Trash2, Download, RefreshCw, PenTool, Edit, Box, ChevronLeft, Settings2, Check, X } from 'lucide-react';
import { Toast, ToastState } from '../Toast';
import { ConfirmModal } from '../ConfirmModal';

interface CommentGeneratorPanelProps {
    currentUser: User | null;
}

const ZODIACS: Zodiac[] = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
const PERSONALITIES: Personality[] = ['活泼', '内敛', '沉稳', '细心', '热心', '恒心', '爱心', '勇敢', '正义'];
const HOBBIES: Hobby[] = ['体育', '音乐', '舞蹈', '绘画', '书法', '手工', '其他'];

export const CommentGeneratorPanel: React.FC<CommentGeneratorPanelProps> = ({ currentUser }) => {
    // --- State ---
    const [viewMode, setViewMode] = useState<'GENERATOR' | 'MANAGER'>('GENERATOR');
    // Mobile View State: 'CONFIG' (Left) or 'RESULT' (Right)
    const [mobileTab, setMobileTab] = useState<'CONFIG' | 'RESULT'>('CONFIG');
    
    const [importedNames, setImportedNames] = useState<string[]>([]);
    const [savedRecords, setSavedRecords] = useState<SavedRecord[]>([]);
    
    // Form State
    const [profile, setProfile] = useState<StudentProfile>({
        name: '',
        classRole: 'NO',
        discipline: 'YES',
        academic: 'GOOD',
        personality: '活泼',
        hobby: '体育',
        labor: '热爱',
        zodiacYear: '龙',
        wordCount: 150
    });

    const [generatedComment, setGeneratedComment] = useState('');
    
    // Status State
    const [isImporting, setIsImporting] = useState(false);
    const [isGenerating, setIsGenerating] = useState(false);
    const [isExporting, setIsExporting] = useState(false);
    const [toast, setToast] = useState<ToastState>({ show: false, message: '', type: 'success' });
    const [confirmModal, setConfirmModal] = useState<{isOpen: boolean, title: string, message: string, onConfirm: () => void}>({ isOpen: false, title: '', message: '', onConfirm: () => {} });

    // Manager Edit State
    const [editingRecordId, setEditingRecordId] = useState<string | null>(null);
    const [editForm, setEditForm] = useState<SavedRecord | null>(null);

    // Refs
    const fileInputRef = useRef<HTMLInputElement>(null);
    const abortControllerRef = useRef<AbortController | null>(null);

    // Load saved records from localStorage
    useEffect(() => {
        try {
            const saved = localStorage.getItem(`comments_backup_${currentUser?._id}`);
            if (saved) setSavedRecords(JSON.parse(saved));
        } catch (e) {}
    }, [currentUser]);

    // Persist records
    useEffect(() => {
        if (currentUser?._id) {
            localStorage.setItem(`comments_backup_${currentUser._id}`, JSON.stringify(savedRecords));
        }
    }, [savedRecords, currentUser]);

    // Auto-load class students
    useEffect(() => {
        const fetchClassStudents = async () => {
            // If list is empty and user has a class, try to load from API
            if (importedNames.length === 0 && currentUser?.homeroomClass) {
                try {
                    const allStudents = await api.students.getAll();
                    const classStudents = allStudents
                        .filter((s: any) => s.className === currentUser.homeroomClass)
                        .map((s: any) => s.name);
                    
                    if (classStudents.length > 0) {
                        setImportedNames(classStudents);
                        setProfile(prev => ({ ...prev, name: classStudents[0] }));
                        setToast({ show: true, message: `已加载 ${currentUser.homeroomClass} 学生名单`, type: 'success' });
                    }
                } catch (e) {
                    console.error("Failed to load students", e);
                }
            }
        };
        fetchClassStudents();
    }, [currentUser]);

    // --- Excel Import Logic ---
    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        setIsImporting(true);
        
        let XLSX: any;
        try {
            // @ts-ignore
            XLSX = await import('xlsx');
        } catch (err) {
            setToast({ show: true, message: '无法加载Excel组件', type: 'error' });
            setIsImporting(false);
            return;
        }

        const reader = new FileReader();
        reader.onload = (evt) => {
            try {
                const data = evt.target?.result;
                const workbook = XLSX.read(data, { type: 'array' });
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];
                const jsonData: any[][] = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                // Smart Header Recognition
                let nameColIndex = -1;
                let headerRowIndex = 0;
                
                // Scan first 20 rows for "姓名" or "Name"
                for (let i = 0; i < Math.min(jsonData.length, 20); i++) {
                    const row = jsonData[i];
                    const idx = row.findIndex((cell: any) => typeof cell === 'string' && (cell.includes('姓名') || cell.toLowerCase() === 'name'));
                    if (idx !== -1) {
                        headerRowIndex = i;
                        nameColIndex = idx;
                        break;
                    }
                }

                // Fallback: Density Scan if no header found
                if (nameColIndex === -1) {
                    const colDensity: number[] = [];
                    const scanLimit = Math.min(jsonData.length, 50);
                    for (let i = 0; i < scanLimit; i++) {
                        const row = jsonData[i];
                        row.forEach((cell, idx) => {
                            if (typeof cell === 'string' && cell.length > 1 && cell.length < 5) {
                                colDensity[idx] = (colDensity[idx] || 0) + 1;
                            }
                        });
                    }
                    let maxDensity = 0;
                    colDensity.forEach((d, idx) => {
                        if (d > maxDensity) { maxDensity = d; nameColIndex = idx; }
                    });
                }

                if (nameColIndex === -1) {
                    setToast({ show: true, message: '无法识别“姓名”列，请检查文件', type: 'error' });
                    setIsImporting(false);
                    return;
                }

                // Extract Names
                const names: string[] = [];
                let emptyStreak = 0;
                
                // Async processing to prevent freeze
                const processRows = async () => {
                    for (let i = headerRowIndex + 1; i < jsonData.length; i++) {
                        if (emptyStreak > 50) break; // Safety break
                        const row = jsonData[i];
                        const val = row[nameColIndex];
                        if (val && typeof val === 'string' && val.trim()) {
                            names.push(val.trim());
                            emptyStreak = 0;
                        } else {
                            emptyStreak++;
                        }
                        
                        if (i % 100 === 0) await new Promise(r => setTimeout(r, 0));
                    }
                    
                    setImportedNames(names);
                    setToast({ show: true, message: `成功导入 ${names.length} 名学生`, type: 'success' });
                    if (names.length > 0) setProfile(p => ({ ...p, name: names[0] }));
                    setIsImporting(false);
                };
                processRows();

            } catch (err) {
                console.error(err);
                setToast({ show: true, message: '文件解析失败', type: 'error' });
                setIsImporting(false);
            }
        };
        reader.readAsArrayBuffer(file);
    };

    // --- AI Generation Logic ---
    const handleGenerate = async () => {
        if (!profile.name) return setToast({ show: true, message: '请输入或选择学生姓名', type: 'error' });
        
        // Mobile: Switch to result tab automatically when generating
        if (window.innerWidth < 768) {
            setMobileTab('RESULT');
        }

        setIsGenerating(true);
        setGeneratedComment('');
        abortControllerRef.current = new AbortController();

        const systemPrompt = `你是一位充满爱心、文笔优美的资深班主任。
你的任务是为学生生成一段期末评语。

### 核心规则 (必须严格遵守)
1.  **隐喻开头**：必须以“老师送你一只[形容词][生肖]……”开头。例如生肖是龙，可以说“老师送你一只腾飞的自信龙”或“老师送你一只威武的智慧龙”。形容词要结合学生的性格和表现。
2.  **内容覆盖**：必须自然地融合以下维度：纪律表现、学业质量、性格特点、兴趣爱好、劳动表现、以及班干部职责(如果是)。
3.  **语气风格**：温暖、真诚、富有文学性。多用排比、比喻。
4.  **缺点处理**：对于不足之处（如纪律差、学业不合格），必须委婉表达，用“希望你...”或“如果在...方面更进一步”的句式，体现教育的期待感。
5.  **格式要求**：纯文本输出，**不要**包含标题、Markdown符号或任何解释性文字。直接输出评语内容。字数控制在 ${profile.wordCount} 字左右。`;

        const userPrompt = `学生画像：
- 姓名：${profile.name}
- 生肖年份：${profile.zodiacYear}
- 班干部：${profile.classRole === 'YES' ? '是 (请肯定其服务精神)' : '否'}
- 纪律：${profile.discipline === 'YES' ? '优秀' : profile.discipline === 'AVERAGE' ? '一般' : '较差 (需委婉提醒)'}
- 学业：${profile.academic === 'EXCELLENT' ? '优秀' : profile.academic === 'GOOD' ? '良好' : profile.academic === 'PASS' ? '合格' : '需努力'}
- 性格：${profile.personality}
- 爱好：${profile.hobby}
- 劳动：${profile.labor === '热爱' ? '积极' : profile.labor === '一般' ? '一般' : '较少参与'}

请生成评语：`;

        try {
            const response = await fetch('/api/ai/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-user-username': currentUser?.username || '',
                    'x-user-role': currentUser?.role || '',
                    'x-school-id': currentUser?.schoolId || ''
                },
                body: JSON.stringify({
                    text: userPrompt,
                    overrideSystemPrompt: systemPrompt,
                    enableThinking: false, 
                    disableAudio: true
                }),
                signal: abortControllerRef.current.signal
            });

            if (!response.ok) throw new Error('Network error');
            const reader = response.body?.getReader();
            const decoder = new TextDecoder();
            let accumulated = '';
            let buffer = '';

            while (true) {
                const { done, value } = await reader!.read();
                if (done) break;
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n\n');
                buffer = lines.pop() || '';

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const data = JSON.parse(line.replace('data: ', ''));
                            if (data.type === 'text') {
                                accumulated += data.content;
                                setGeneratedComment(accumulated);
                            }
                        } catch (e) {}
                    }
                }
            }
        } catch (e: any) {
            if (e.name !== 'AbortError') setToast({ show: true, message: '生成失败', type: 'error' });
        } finally {
            setIsGenerating(false);
            abortControllerRef.current = null;
        }
    };

    const handleSave = () => {
        if (!generatedComment) return;
        const newRecord: SavedRecord = {
            id: Date.now().toString(),
            name: profile.name,
            comment: generatedComment,
            zodiac: profile.zodiacYear,
            timestamp: Date.now()
        };
        // Remove old record for same student if exists
        const filtered = savedRecords.filter(r => r.name !== profile.name);
        setSavedRecords([newRecord, ...filtered]);
        setToast({ show: true, message: '已保存到管理箱', type: 'success' });
        
        // Auto-advance logic
        if (importedNames.length > 0) {
            const idx = importedNames.indexOf(profile.name);
            if (idx !== -1 && idx < importedNames.length - 1) {
                setProfile(p => ({ ...p, name: importedNames[idx + 1] }));
                setGeneratedComment(''); // Clear for next
                
                // If mobile, ask if they want to go back to config to generate next
                if (window.innerWidth < 768) {
                    // Stay on result for a moment or give a toast hint
                    setToast({ show: true, message: `已保存。已切换到下一位：${importedNames[idx + 1]}`, type: 'success' });
                }
            }
        }
    };

    // --- Manager Logic ---
    const handleDeleteRecord = (id: string) => {
        setSavedRecords(prev => prev.filter(r => r.id !== id));
    };

    const handleBatchZodiac = (zodiac: Zodiac) => {
        setConfirmModal({
            isOpen: true,
            title: '批量修改生肖',
            message: `确定将管理箱中所有记录的生肖标记修改为“${zodiac}”吗？\n(注意：这不会修改评语文本内容，只修改分类标记)`,
            onConfirm: () => {
                setSavedRecords(prev => prev.map(r => ({ ...r, zodiac })));
                setToast({ show: true, message: '同步完成', type: 'success' });
            }
        });
    };

    const handleExportWord = async () => {
        if (savedRecords.length === 0) return setToast({ show: true, message: '没有可导出的记录', type: 'error' });
        
        setIsExporting(true);
        let docx: any;
        try {
            // @ts-ignore
            docx = await import('docx');
        } catch (e) {
            setToast({ show: true, message: '无法加载导出组件', type: 'error' });
            setIsExporting(false);
            return;
        }

        const { Document, Packer, Paragraph, TextRun, AlignmentType, HeadingLevel } = docx;

        const doc = new Document({
            sections: [{
                properties: {},
                children: [
                    new Paragraph({
                        text: "期末学生评语",
                        heading: HeadingLevel.HEADING_1,
                        alignment: AlignmentType.CENTER,
                        spacing: { after: 400 }
                    }),
                    ...savedRecords.flatMap(record => [
                        new Paragraph({
                            children: [
                                new TextRun({ text: record.name, bold: true, size: 28 }),
                                new TextRun({ text: "：" })
                            ],
                            spacing: { before: 200, after: 100 }
                        }),
                        new Paragraph({
                            text: record.comment,
                            alignment: AlignmentType.JUSTIFIED,
                            spacing: { after: 300 },
                            indent: { firstLine: 480 } // 2 chars indent roughly
                        })
                    ])
                ]
            }]
        });

        const blob = await Packer.toBlob(doc);
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `期末评语导出_${new Date().toLocaleDateString()}.docx`;
        a.click();
        window.URL.revokeObjectURL(url);
        setIsExporting(false);
        setToast({ show: true, message: '导出成功', type: 'success' });
    };

    const isStudentDone = (name: string) => savedRecords.some(r => r.name === name);

    return (
        <div className="h-full flex flex-col bg-amber-50/30 overflow-hidden relative">
            {toast.show && <Toast message={toast.message} type={toast.type} onClose={()=>setToast({...toast, show: false})}/>}
            <ConfirmModal isOpen={confirmModal.isOpen} title={confirmModal.title} message={confirmModal.message} onClose={()=>setConfirmModal({...confirmModal, isOpen: false})} onConfirm={confirmModal.onConfirm}/>

            {/* Top Bar */}
            <div className="bg-white border-b border-amber-100 px-4 md:px-6 py-3 flex justify-between items-center shrink-0 shadow-sm z-20">
                <div className="flex items-center gap-2 text-amber-700 font-bold text-lg truncate">
                    <PenTool className="fill-amber-500 text-amber-600 shrink-0" /> 
                    <span className="hidden md:inline">暖心评语助手</span>
                    <span className="md:hidden">评语助手</span>
                </div>
                <div className="flex bg-amber-100/50 p-1 rounded-lg">
                    <button onClick={()=>setViewMode('GENERATOR')} className={`px-3 md:px-4 py-1.5 text-xs md:text-sm font-bold rounded-md transition-all flex items-center gap-1 md:gap-2 ${viewMode==='GENERATOR' ? 'bg-white text-amber-600 shadow-sm' : 'text-amber-800/60'}`}>
                        <Sparkles size={14}/> 生成器
                    </button>
                    <button onClick={()=>setViewMode('MANAGER')} className={`px-3 md:px-4 py-1.5 text-xs md:text-sm font-bold rounded-md transition-all flex items-center gap-1 md:gap-2 ${viewMode==='MANAGER' ? 'bg-white text-amber-600 shadow-sm' : 'text-amber-800/60'}`}>
                        <Box size={14}/> 管理箱
                        {savedRecords.length > 0 && <span className="bg-red-500 text-white text-[10px] px-1.5 rounded-full ml-1">{savedRecords.length}</span>}
                    </button>
                </div>
            </div>

            {/* GENERATOR MODE */}
            {viewMode === 'GENERATOR' && (
                <div className="flex-1 overflow-hidden flex relative">
                    
                    {/* --- Left Panel: Controls --- */}
                    {/* Mobile: Shown only when mobileTab is CONFIG */}
                    {/* Desktop: Always shown, fixed width 450px */}
                    <div className={`
                        flex flex-col bg-white border-r border-amber-100 h-full transition-all duration-300 absolute md:relative z-10 w-full md:w-[450px] shrink-0
                        ${mobileTab === 'CONFIG' ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}
                    `}>
                        {/* 1. Header (Name Input) */}
                        <div className="p-4 border-b border-gray-100 bg-gray-50/50 shrink-0">
                            <label className="text-xs font-bold text-gray-500 uppercase block mb-2">当前学生</label>
                            <div className="flex gap-2">
                                {importedNames.length > 0 ? (
                                    <div className="relative flex-1">
                                        <select 
                                            className="w-full border border-amber-300 rounded-xl p-3 bg-white text-base font-bold text-gray-800 shadow-sm focus:ring-2 focus:ring-amber-400 outline-none appearance-none"
                                            value={profile.name}
                                            onChange={e => setProfile({...profile, name: e.target.value})}
                                        >
                                            {importedNames.map(name => (
                                                <option key={name} value={name}>
                                                    {isStudentDone(name) ? '✅' : '⬜'} {name}
                                                </option>
                                            ))}
                                        </select>
                                        <div className="absolute right-3 top-3.5 text-gray-400 pointer-events-none text-xs">▼</div>
                                    </div>
                                ) : (
                                    <input 
                                        className="flex-1 border border-gray-300 rounded-xl p-3 text-sm focus:ring-2 focus:ring-amber-400 outline-none shadow-sm"
                                        placeholder="输入姓名..."
                                        value={profile.name}
                                        onChange={e => setProfile({...profile, name: e.target.value})}
                                    />
                                )}
                                <button 
                                    onClick={() => fileInputRef.current?.click()} 
                                    className="px-3 bg-white text-green-600 rounded-xl border border-green-200 hover:bg-green-50 flex items-center justify-center shadow-sm shrink-0"
                                    title="Excel 导入 / 覆盖名单"
                                >
                                    <FileSpreadsheet size={20}/>
                                </button>
                                <input type="file" accept=".xlsx,.xls,.csv" ref={fileInputRef} className="hidden" onChange={handleFileUpload} />
                            </div>
                            {isImporting && <div className="text-xs text-gray-400 mt-2 flex items-center gap-1"><Loader2 size={10} className="animate-spin"/> 正在解析名单...</div>}
                        </div>

                        {/* 2. Scrollable Config Body */}
                        <div className="flex-1 overflow-y-auto p-4 custom-scrollbar space-y-5 pb-24 md:pb-6">
                            {/* Zodiac */}
                            <div>
                                <label className="text-xs font-bold text-gray-500 uppercase block mb-2">生肖年份 (隐喻主题)</label>
                                <div className="grid grid-cols-6 gap-2">
                                    {ZODIACS.map(z => (
                                        <button 
                                            key={z} 
                                            onClick={() => setProfile({...profile, zodiacYear: z})}
                                            className={`text-sm py-1.5 rounded-lg border transition-all ${profile.zodiacYear === z ? 'bg-red-50 text-red-600 border-red-300 font-bold shadow-sm' : 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50'}`}
                                        >
                                            {z}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">班干部</label>
                                    <select className="w-full text-sm border border-gray-300 rounded-lg p-2.5 bg-white" value={profile.classRole} onChange={e=>setProfile({...profile, classRole: e.target.value as any})}>
                                        <option value="NO">否</option>
                                        <option value="YES">是 (重点表扬)</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">纪律表现</label>
                                    <select className="w-full text-sm border border-gray-300 rounded-lg p-2.5 bg-white" value={profile.discipline} onChange={e=>setProfile({...profile, discipline: e.target.value as any})}>
                                        <option value="YES">遵守纪律</option>
                                        <option value="AVERAGE">一般</option>
                                        <option value="NO">较差 (需提醒)</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">学业质量</label>
                                    <select className="w-full text-sm border border-gray-300 rounded-lg p-2.5 bg-white" value={profile.academic} onChange={e=>setProfile({...profile, academic: e.target.value as any})}>
                                        <option value="EXCELLENT">优秀</option>
                                        <option value="GOOD">良好</option>
                                        <option value="PASS">合格</option>
                                        <option value="FAIL">需努力</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">劳动表现</label>
                                    <select className="w-full text-sm border border-gray-300 rounded-lg p-2.5 bg-white" value={profile.labor} onChange={e=>setProfile({...profile, labor: e.target.value as any})}>
                                        <option value="热爱">热爱劳动</option>
                                        <option value="一般">一般</option>
                                        <option value="较少参与">较少参与</option>
                                    </select>
                                </div>
                            </div>

                            {/* Personality */}
                            <div>
                                <label className="text-xs font-bold text-gray-500 uppercase block mb-2">性格特点</label>
                                <div className="grid grid-cols-3 gap-2">
                                    {PERSONALITIES.map(p => (
                                        <button 
                                            key={p} 
                                            onClick={() => setProfile({...profile, personality: p})}
                                            className={`text-xs py-1.5 rounded border transition-colors ${profile.personality === p ? 'bg-blue-50 text-blue-600 border-blue-300 font-bold' : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'}`}
                                        >
                                            {p}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Hobby & Length */}
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">兴趣爱好</label>
                                    <select className="w-full text-sm border border-gray-300 rounded-lg p-2.5 bg-white" value={profile.hobby} onChange={e=>setProfile({...profile, hobby: e.target.value as any})}>
                                        {HOBBIES.map(h => <option key={h} value={h}>{h}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase block mb-1">字数: {profile.wordCount}</label>
                                    <input type="range" min="50" max="300" step="10" className="w-full accent-amber-500 h-9" value={profile.wordCount} onChange={e=>setProfile({...profile, wordCount: Number(e.target.value)})}/>
                                </div>
                            </div>
                        </div>

                        {/* 3. Fixed Footer Button (Left Panel) */}
                        <div className="p-4 border-t border-gray-200 bg-white z-20 shrink-0">
                            <button 
                                onClick={handleGenerate} 
                                disabled={isGenerating || !profile.name}
                                className="w-full py-3 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl font-bold shadow-lg hover:shadow-orange-200 transition-all flex items-center justify-center gap-2 disabled:opacity-50 transform active:scale-95"
                            >
                                {isGenerating ? <Loader2 className="animate-spin" size={20}/> : <Sparkles size={20}/>}
                                {isGenerating ? 'AI 正在撰写...' : '立即生成评语'}
                            </button>
                        </div>
                    </div>

                    {/* --- Right Panel: Result Preview --- */}
                    {/* Mobile: Shown only when mobileTab is RESULT */}
                    {/* Desktop: Always shown, takes remaining space */}
                    <div className={`
                        flex-1 flex flex-col items-center justify-center bg-amber-50/50 relative overflow-hidden transition-all duration-300 absolute md:relative inset-0 md:inset-auto z-20
                        ${mobileTab === 'RESULT' ? 'translate-x-0' : 'translate-x-full md:translate-x-0'}
                        bg-white md:bg-amber-50/50
                    `}>
                        {/* Mobile Header for Result */}
                        <div className="md:hidden w-full p-4 border-b bg-white flex justify-between items-center shrink-0">
                            <button onClick={() => setMobileTab('CONFIG')} className="flex items-center text-gray-600 font-bold">
                                <ChevronLeft size={20}/> 返回配置
                            </button>
                            <span className="text-sm font-bold text-gray-800">生成结果</span>
                            <div className="w-6"></div> 
                        </div>

                        <div className="w-full h-full p-4 md:p-8 overflow-y-auto flex flex-col items-center">
                            {generatedComment ? (
                                <div className="w-full max-w-2xl bg-white rounded-2xl shadow-xl border border-amber-100 p-6 md:p-8 relative animate-in fade-in zoom-in-95 flex flex-col h-full md:h-auto">
                                    <div className="absolute -top-3 left-6 bg-amber-100 text-amber-800 px-4 py-1 rounded-full text-xs font-bold shadow-sm border border-amber-200 hidden md:block">
                                        {profile.name} 的专属评语
                                    </div>
                                    
                                    <div className="flex justify-between items-center mb-4 md:hidden">
                                        <span className="font-bold text-lg text-gray-800">{profile.name}</span>
                                        <span className="text-xs bg-amber-100 text-amber-800 px-2 py-1 rounded">{profile.zodiacYear}年主题</span>
                                    </div>

                                    <textarea 
                                        className="w-full flex-1 md:min-h-[250px] text-base md:text-lg leading-loose text-gray-700 outline-none resize-none bg-transparent font-medium border-none p-0"
                                        value={generatedComment}
                                        onChange={(e) => setGeneratedComment(e.target.value)}
                                    />
                                    
                                    <div className="flex flex-col md:flex-row justify-end gap-3 mt-6 pt-4 border-t border-gray-100 shrink-0">
                                        <button onClick={() => { navigator.clipboard.writeText(generatedComment); setToast({show:true, message:'已复制', type:'success'}); }} className="flex items-center justify-center gap-2 text-gray-600 hover:text-blue-600 px-4 py-2 rounded-lg bg-gray-50 hover:bg-blue-50 transition-colors font-bold border border-gray-200">
                                            <Copy size={18}/> 复制文本
                                        </button>
                                        <button onClick={handleSave} className="flex items-center justify-center gap-2 bg-amber-500 text-white px-6 py-3 md:py-2 rounded-lg font-bold hover:bg-amber-600 shadow-md transition-transform active:scale-95">
                                            <Save size={18}/> 保存到管理箱
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <div className="text-center text-amber-800/40 flex flex-col items-center justify-center h-full">
                                    <Settings2 size={64} className="mb-4 opacity-30"/>
                                    <p className="text-lg font-bold">准备就绪</p>
                                    <p className="text-sm mt-2 max-w-xs">在{window.innerWidth<768?'配置页':'左侧'}完善学生信息，AI 将为您生成暖心评语</p>
                                    <button onClick={() => setMobileTab('CONFIG')} className="mt-6 md:hidden px-6 py-2 bg-amber-100 text-amber-700 rounded-full font-bold text-sm">
                                        去配置
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* MANAGER MODE */}
            {viewMode === 'MANAGER' && (
                <div className="flex-1 overflow-hidden flex flex-col p-4 md:p-6 bg-gray-50">
                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-4 md:mb-6 gap-4">
                        <div className="flex gap-2 w-full md:w-auto">
                            <button onClick={handleExportWord} disabled={isExporting} className="flex-1 md:flex-none bg-blue-600 text-white px-4 py-2.5 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-blue-700 shadow-sm disabled:opacity-50 transition-colors text-sm">
                                {isExporting ? <Loader2 className="animate-spin" size={18}/> : <Download size={18}/>}
                                导出 Word
                            </button>
                            <div className="relative group flex-1 md:flex-none">
                                <button className="w-full bg-white text-gray-600 border border-gray-200 px-4 py-2.5 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-gray-50 shadow-sm text-sm">
                                    <RefreshCw size={16}/> 批量改年份
                                </button>
                                <div className="absolute top-full left-0 mt-2 w-32 bg-white border border-gray-200 rounded-lg shadow-xl hidden group-hover:block z-20 py-1">
                                    {ZODIACS.map(z => (
                                        <button key={z} onClick={() => handleBatchZodiac(z)} className="w-full text-left px-4 py-2 hover:bg-gray-50 text-sm text-gray-700">
                                            改为 {z}年
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>
                        <div className="text-xs text-gray-500 font-bold bg-white px-3 py-1 rounded-full border">
                            已保存 {savedRecords.length} 条
                        </div>
                    </div>

                    <div className="flex-1 overflow-y-auto custom-scrollbar pb-20">
                        {savedRecords.length === 0 ? (
                            <div className="h-full flex flex-col items-center justify-center text-gray-400 border-2 border-dashed border-gray-200 rounded-2xl bg-white/50">
                                <Box size={48} className="mb-4 opacity-50"/>
                                <p>管理箱是空的</p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6">
                                {savedRecords.map(record => (
                                    <div key={record.id} className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex flex-col hover:shadow-md transition-shadow group relative">
                                        <div className="flex justify-between items-center mb-3">
                                            <div className="font-bold text-lg text-gray-800 flex items-center gap-2">
                                                {record.name}
                                                <span className="text-xs bg-amber-50 text-amber-700 px-2 py-0.5 rounded border border-amber-100">{record.zodiac}年</span>
                                            </div>
                                            <div className="flex gap-1">
                                                <button 
                                                    onClick={() => { setEditingRecordId(record.id); setEditForm(record); }} 
                                                    className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                                                >
                                                    <Edit size={16}/>
                                                </button>
                                                <button 
                                                    onClick={() => handleDeleteRecord(record.id)} 
                                                    className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                                                >
                                                    <Trash2 size={16}/>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        {editingRecordId === record.id && editForm ? (
                                            <div className="flex-1 flex flex-col gap-2 z-10 bg-white absolute inset-2 p-2 shadow-lg border rounded-lg">
                                                <div className="flex justify-between items-center mb-1">
                                                    <span className="text-xs font-bold text-gray-500">编辑模式</span>
                                                    <button onClick={() => setEditingRecordId(null)} className="text-gray-400 hover:text-gray-600"><X size={16}/></button>
                                                </div>
                                                <input 
                                                    className="w-full border rounded p-1.5 text-sm font-bold bg-gray-50" 
                                                    value={editForm.name} 
                                                    onChange={e => setEditForm({...editForm, name: e.target.value})}
                                                />
                                                <textarea 
                                                    className="w-full border rounded p-2 text-sm resize-none flex-1 focus:ring-2 focus:ring-blue-500 outline-none" 
                                                    value={editForm.comment}
                                                    onChange={e => setEditForm({...editForm, comment: e.target.value})}
                                                />
                                                <button 
                                                    onClick={() => {
                                                        setSavedRecords(prev => prev.map(r => r.id === record.id ? editForm! : r));
                                                        setEditingRecordId(null);
                                                        setToast({ show: true, message: '修改已保存', type: 'success' });
                                                    }} 
                                                    className="w-full bg-blue-600 text-white px-3 py-2 rounded font-bold text-xs"
                                                >
                                                    保存修改
                                                </button>
                                            </div>
                                        ) : (
                                            <div className="flex-1 text-sm text-gray-600 leading-relaxed overflow-hidden text-ellipsis line-clamp-6 bg-gray-50 p-3 rounded-lg border border-gray-50/50">
                                                {record.comment}
                                            </div>
                                        )}
                                        
                                        <div className="mt-3 pt-3 border-t border-gray-100 flex justify-between items-center text-xs text-gray-400">
                                            <span>{new Date(record.timestamp).toLocaleDateString()}</span>
                                            <span className="font-mono bg-gray-100 px-1.5 rounded">{record.comment.length}字</span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};
