'use client';

import { useState, useRef, useEffect, FormEvent, Suspense } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { getToken, apiFetch } from '@/lib/auth';
import { DEFAULT_MODEL } from '@/lib/models';
import { ModelSelector } from '@/components/ui/model-selector';
import { useT } from '@/i18n';
import { CodeBlock } from '@/components/ui/code-block';
import LearningPath, { LEARNING_STAGES } from '@/components/sandbox/learning-path';
import { API_BASE } from '@/lib/config';
import { toast } from 'sonner';

interface Message {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

interface SessionItem {
  id: number;
  conversationId: string;
  model: string;
  title: string;
  createdAt: string;
  tokens: number;
}

interface GuideTask {
  taskKey: string;
  hint: string;
  actionLabel?: string;
}

const STAGE_GUIDES: Record<string, GuideTask[]> = {
  'welcome': [
    { taskKey: 'taskSendMsg', hint: '在下方输入框中输入任意问题（如"什么是 AI？"），然后按回车或点击发送按钮', actionLabel: '已发送第一条消息' },
    { taskKey: 'taskTryStarter', hint: '点击下方任意 Starter 气泡（如"帮我写一封邮件"），快速开始一次对话', actionLabel: '已尝试 Starter' },
    { taskKey: 'taskReadReply', hint: '阅读 AI 回复的内容和格式，观察它如何组织语言、分段和排版', actionLabel: '已理解回复特点' },
  ],
  'scene': [
    { taskKey: 'taskSwitchCoding', hint: '点击右侧场景下拉菜单 👉，选择「编程助手」，体验编程场景的专属提示', actionLabel: '已切换到编程' },
    { taskKey: 'taskSwitchWriting', hint: '再次打开场景菜单，选择「写作助手」，试问"帮我润色这段文字"', actionLabel: '已切换到写作' },
    { taskKey: 'taskSwitchStudy', hint: '切换到「学习辅导」场景，提问"请解释一下什么是机器学习"', actionLabel: '已切换到学习' },
  ],
  'params': [
    { taskKey: 'taskHighTemp', hint: '点击右上角的 ⚙ 高级参数按钮，将 Temperature 滑动到 0.9，然后发送一个问题', actionLabel: '已调高 Temperature' },
    { taskKey: 'taskLowTemp', hint: '将 Temperature 滑动到 0.1，发送同样的问题，观察两次回复的差异', actionLabel: '已调低 Temperature' },
    { taskKey: 'taskCompareTemp', hint: '对比高低 Temperature 的回复：高值更富创意多样，低值更保守聚焦', actionLabel: '已理解区别' },
  ],
  'models': [
    { taskKey: 'taskSwitchModel', hint: '在顶部的模型选择器中切换到 DeepSeek V4 Flash 模型', actionLabel: '已切换模型' },
    { taskKey: 'taskCompareModel', hint: '向两个模型问同样的问题，观察他们在回复风格、详细程度上的差异', actionLabel: '已对比模型' },
  ],
  'prompts': [
    { taskKey: 'taskRolePrompt', hint: '输入一条包含角色设定的提示词，例如："你是一名资深编辑，请帮我审稿这篇文字，指出改进方向"', actionLabel: '已使用角色提示' },
    { taskKey: 'taskStructured', hint: '尝试使用结构化提示：分步骤说明任务，例如："第一步：概括要点；第二步：分析优缺点；第三步：给出改进建议"', actionLabel: '已完成结构化提示' },
  ],
  'master': [
    { taskKey: 'taskTryStarter', hint: '选择一个 Starter 问题开始你的综合实战练习', actionLabel: '已选择问题' },
    { taskKey: 'taskCodeExec', hint: '当 AI 生成代码后，点击消息下方的「在代码沙盒中运行」按钮，打开代码沙箱执行代码', actionLabel: '已运行代码' },
    { taskKey: 'taskCommunity', hint: '点击「分享到社区」按钮，将你的对话分享到宇之然社区', actionLabel: '已分享到社区' },
  ],
};

function extractCodeBlocks(content: string): string[] {
  const blocks: string[] = [];
  const regex = /```(?:\w+)?\n([\s\S]*?)```/g;
  let match;
  while ((match = regex.exec(content)) !== null) {
    const code = match[1].trim();
    if (code.length > 0) blocks.push(code);
  }
  return blocks;
}

export default function SandboxPageWrapper() {
  return (
    <Suspense fallback={
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="h-8 w-48 bg-muted rounded-lg animate-pulse mb-4" />
        <div className="h-[65vh] bg-muted rounded-2xl animate-pulse" />
      </div>
    }>
      <SandboxPage />
    </Suspense>
  );
}

function SandboxPage() {
  const searchParams = useSearchParams();
  const t = useT();
  const [messages, setMessages] = useState<Message[]>([
    { role: 'assistant', content: '你好！我是宇之然 AI 助手。你可以问我任何问题，我会尽力帮你解答。\n\n试试问我关于 AI、编程、写作、办公效率等方面的问题！' },
  ]);
  const [input, setInput] = useState('');
  const [model, setModel] = useState(DEFAULT_MODEL);
  const [scene, setScene] = useState('');
  const [SCENES, setSCENES] = useState<{ id: string; name: string; icon: string; systemPrompt: string; starters: string[] }[]>([]);
  const [skillsLoading, setSkillsLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [showParams, setShowParams] = useState(false);
  const [temperature, setTemperature] = useState(0.7);
  const [topP, setTopP] = useState(1);
  const [maxTokens, setMaxTokens] = useState(2000);
  const [quota, setQuota] = useState<{ used: number; dailyLimit: number; dailyRemaining: number; extra: number; totalRemaining: number; remaining: number } | null>(null);
  const [sessions, setSessions] = useState<SessionItem[]>([]);
  const [sessionsLoading, setSessionsLoading] = useState(false);
  const [sessionsOpen, setSessionsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [conversationId, setConversationId] = useState(() => crypto.randomUUID());
  const [sessionFeedback, setSessionFeedback] = useState<Record<number, string | null>>({});
  const [currentSessionId, setCurrentSessionId] = useState<number | null>(null);
  const [renamingId, setRenamingId] = useState<number | null>(null);
  const [renameValue, setRenameValue] = useState('');
  const [uploadedImages, setUploadedImages] = useState<string[]>([]);
  const [uploading, setUploading] = useState(false);
  const [mode, setMode] = useState<'free' | 'learn'>('learn');
  const [guidedStageId, setGuidedStageId] = useState<string | null>(null);
  const [guidedTaskIdx, setGuidedTaskIdx] = useState(0);
  const [guidedDone, setGuidedDone] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  const isStreamingRef = useRef(false);
  const { isLoggedIn } = useAuth();

  useEffect(() => {
    const tk = getToken();
    if (tk) {
      fetch(`${API_BASE}/sandbox/quota`, {
        headers: { Authorization: `Bearer ${tk}` },
      }).then(r => r.json()).then(data => {
        if (data.remaining !== undefined) setQuota(data);
      }).catch(() => {});
      loadSessions(tk);
    }
  }, [isLoggedIn]);

  useEffect(() => {
    const DEFAULT_SCENES = [
      { id: 'general-chat', name: '通用对话', icon: '💬', systemPrompt: '你是一个智能 AI 助手', starters: ['什么是 AI？', '帮我写一封邮件', '解释一下量子计算', '推荐一本好书'] },
      { id: 'coding', name: '编程助手', icon: '💻', systemPrompt: '你是一个编程专家，擅长解答编程问题和编写代码', starters: ['用 Python 写一个斐波那契数列', '解释 RESTful API 设计原则', '帮我调试这段代码', '什么是闭包？'] },
      { id: 'writing', name: '写作助手', icon: '✍️', systemPrompt: '你是一个专业的写作助手，擅长润色和创作各类文本', starters: ['帮我润色这段文字', '写一篇产品介绍', '如何写好工作总结？', '帮我拟一份会议邀请'] },
      { id: 'study', name: '学习辅导', icon: '📚', systemPrompt: '你是一个耐心的学习辅导员，善于解释复杂概念', starters: ['什么是机器学习？', '解释 HTTP 与 HTTPS 的区别', '帮我理解微积分', '英语单词记忆技巧'] },
      { id: 'tutor', name: '编程导师', icon: '🧑‍🏫', systemPrompt: '你是一位编程导师，采用苏格拉底式教学法。核心理念是「不直接给答案，引导对方自己找到答案」。当学习者提出编程问题时：1) 先通过提问理解他们的水平和困惑点；2) 给出思路提示而非完整代码；3) 如果对方卡住了，逐步增加提示的明确度；4) 只有在对方已经尝试并仍然困惑时，才给出带解释的参考代码。目标是培养独立思考和问题解决能力。', starters: ['我想学编程，从哪开始？', '变量和常量有什么区别？', '这段代码为啥报错？帮我看下', 'for 循环和 while 循环有什么区别？'] },
    ];

    fetch(`${API_BASE}/skills`)
      .then(r => r.json())
      .then(data => {
        const scenes = (data.items || []).map((s: any) => ({ id: s.id, name: s.name, icon: s.icon, systemPrompt: s.systemPrompt, starters: s.starters }));
        const all = scenes.length > 0 ? scenes : DEFAULT_SCENES;
        setSCENES(all);
        const skillParam = searchParams.get('skill');
        const initialScene = all.find((s: any) => s.id === skillParam) ? skillParam : (all[0]?.id || '');
        setScene(initialScene);
      })
      .catch(() => {
        setSCENES(DEFAULT_SCENES);
        setScene(DEFAULT_SCENES[0].id);
      })
      .finally(() => setSkillsLoading(false));
  }, []);

  useEffect(() => {
    if (messages.some(m => m.role === 'user') && messagesContainerRef.current) {
      messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
    }
  }, [messages]);

  function loadSessions(tk?: string) {
    const token = tk || getToken();
    if (!token) return;
    setSessionsLoading(true);
    const params = searchQuery ? `?search=${encodeURIComponent(searchQuery)}` : '';
    fetch(`${API_BASE}/sandbox/sessions${params}`, {
      headers: { Authorization: `Bearer ${token}` },
    }).then(r => r.json()).then(data => {
      if (data.items) setSessions(data.items);
    }).catch(() => {}).finally(() => setSessionsLoading(false));
  }

  function handleSceneChange(sceneId: string) {
    setScene(sceneId);
    const s = SCENES.find(x => x.id === sceneId);
    setMessages([
      { role: 'assistant', content: `欢迎来到 **${s?.name || sceneId}** 模式！试试下面的问题，或者直接输入你的问题吧。` },
    ]);
  }

  function handleStartStage(stage: typeof LEARNING_STAGES[0]) {
    const s = SCENES.find(x => x.id === stage.sceneId);
    const stageName = t.sandbox[stage.descKey as keyof typeof t.sandbox] as string;
    const stageDesc = t.sandbox[stage.descDescKey as keyof typeof t.sandbox] as string;
    if (s) {
      setScene(stage.sceneId);
      setModel(stage.model);
      setTemperature(stage.temperature);
      setTopP(1);
      setMaxTokens(2000);
      setConversationId(crypto.randomUUID());
      setCurrentSessionId(null);
      setMessages([
        { role: 'assistant', content: `📚 **${stageName}**\n\n${stageDesc}\n\n开始练习吧！按照左侧引导逐步完成本阶段任务。` },
      ]);
    }
    setMode('free');
    setGuidedStageId(stage.id);
    setGuidedTaskIdx(0);
    setGuidedDone(false);
    if (stage.id === 'params') setShowParams(true);
  }

  function handleCompleteTask() {
    const guide = guidedStageId ? STAGE_GUIDES[guidedStageId] : null;
    if (!guide) return;
    if (guidedTaskIdx < guide.length - 1) {
      setGuidedTaskIdx(guidedTaskIdx + 1);
    } else {
      setGuidedDone(true);
      try {
        const raw = localStorage.getItem('sandbox_learning_progress');
        const progress = raw ? JSON.parse(raw) : { done: [] };
        if (!progress.done.includes(guidedStageId)) {
          progress.done.push(guidedStageId);
          for (const task of guide) {
            if (!progress.done.includes(task.taskKey)) progress.done.push(task.taskKey);
          }
          localStorage.setItem('sandbox_learning_progress', JSON.stringify(progress));
        }
      } catch {}
    }
  }

  function handleNextStage() {
    if (!guidedStageId) return;
    const idx = LEARNING_STAGES.findIndex(s => s.id === guidedStageId);
    if (idx >= 0 && idx < LEARNING_STAGES.length - 1) {
      handleStartStage(LEARNING_STAGES[idx + 1]);
    } else {
      setGuidedStageId(null);
      setGuidedTaskIdx(0);
      setGuidedDone(false);
    }
  }

  function handleExitGuide() {
    setGuidedStageId(null);
    setGuidedTaskIdx(0);
    setGuidedDone(false);
  }

  async function handleSend(e: FormEvent) {
    e.preventDefault();
    const text = input.trim();
    if (!text || sending) return;

    const userMsg: Message = { role: 'user', content: text };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setSending(true);

    try {
      const tk = getToken();
      if (tk) {
        const curScene = SCENES.find(s => s.id === scene) || SCENES[0];
        const systemPrompt = curScene?.systemPrompt || '你是一个智能 AI 助手';
        const apiMessages = [
          { role: 'system', content: systemPrompt },
          ...messages,
          userMsg,
        ].map(m => ({ role: m.role, content: m.content }));

        const res = await fetch(`${API_BASE}/sandbox/chat`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${tk}`,
          },
          body: JSON.stringify({ conversationId, model, messages: apiMessages, temperature, top_p: topP, max_tokens: maxTokens, stream: true, ...(uploadedImages.length > 0 ? { images: uploadedImages } : {}) }),
        });

        if ((res.headers.get('content-type') || '').includes('text/event-stream')) {
          isStreamingRef.current = true;
          setMessages(prev => [...prev, { role: 'assistant', content: '' }]);

          const reader = res.body!.getReader();
          const decoder = new TextDecoder();
          let buf = '';

          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            buf += decoder.decode(value, { stream: true });
            const lines = buf.split('\n');
            buf = lines.pop() || '';
            for (const line of lines) {
              if (!line.startsWith('data: ')) continue;
              try {
                const d = JSON.parse(line.slice(6));
                if (d.type === 'text') {
                  setMessages(prev => {
                    const msgs = [...prev];
                    if (msgs.length > 0) {
                      const last = msgs[msgs.length - 1];
                      if (last.role === 'assistant') {
                        msgs[msgs.length - 1] = { ...last, content: last.content + d.content };
                      }
                    }
                    return msgs;
                  });
                } else if (d.type === 'done') {
                  if (d.sessionId) setCurrentSessionId(d.sessionId);
                  if (d.conversationId) setConversationId(d.conversationId);
                } else if (d.type === 'error') {
                  throw new Error(d.message);
                }
              } catch {}
            }
          }
        } else {
          const data = await res.json();
          if (!res.ok) throw new Error(data.message || '请求失败');
          if (data.conversationId) setConversationId(data.conversationId);
          if (data.sessionId) setCurrentSessionId(data.sessionId);
          setMessages(prev => [...prev, { role: 'assistant', content: data.reply }]);
        }

        if (quota) setQuota({ ...quota, used: quota.used + 1, remaining: quota.remaining - 1 });
        setUploadedImages([]);
        loadSessions(tk);
      } else {
        await new Promise(r => setTimeout(r, 300));
        setMessages(prev => [...prev, { role: 'assistant', content: '📝 注册登录后可体验完整 AI 对话功能。\n\n点击右上角「登录」或「注册」即可开始使用。' }]);
      }
    } catch (e: any) {
      const errMsg = e.message.includes('今日沙箱使用次数已用完')
        ? '今日沙箱使用次数已用完。' + (isLoggedIn ? '' : ' 登录后可获得更多使用次数。')
        : e.message.includes('未登录') || e.message.includes('Unauthorized')
        ? '登录已过期，请重新登录后再试。'
        : `出错啦：${e.message}`;

      if (isStreamingRef.current) {
        setMessages(prev => {
          const msgs = [...prev];
          const last = msgs[msgs.length - 1];
          if (last?.role === 'assistant' && last.content === '') {
            msgs[msgs.length - 1] = { role: 'assistant', content: errMsg };
            return msgs;
          }
          return [...prev, { role: 'assistant', content: errMsg }];
        });
      } else {
        setMessages(prev => [...prev, { role: 'assistant', content: errMsg }]);
      }
    } finally {
      isStreamingRef.current = false;
      setSending(false);
    }
  }

  async function loadSession(sessionId: number) {
    const tk = getToken();
    if (!tk) return;
    try {
      const res = await fetch(`${API_BASE}/sandbox/sessions/${sessionId}`, {
        headers: { Authorization: `Bearer ${tk}` },
      });
      const data = await res.json();
      if (data.messages) {
        setMessages(data.messages.filter((m: any) => m.role !== 'system'));
        setModel(data.model);
        setConversationId(data.conversationId);
        setCurrentSessionId(data.id);
        setSessionFeedback(prev => ({ ...prev, [data.id]: data.feedback || null }));
      }
    } catch {}
  }

  async function deleteSession(sessionId: number) {
    const tk = getToken();
    if (!tk) return;
    try {
      await fetch(`${API_BASE}/sandbox/sessions/${sessionId}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${tk}` },
      });
      setSessions(prev => prev.filter(s => s.id !== sessionId));
    } catch {}
  }

  async function renameSession(sessionId: number, title: string) {
    const tk = getToken();
    if (!tk || !title.trim()) return;
    try {
      await fetch(`${API_BASE}/sandbox/sessions/${sessionId}/rename`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
        body: JSON.stringify({ title: title.trim() }),
      });
      setSessions(prev => prev.map(s => s.id === sessionId ? { ...s, title: title.trim() } : s));
      setRenamingId(null);
    } catch {}
  }

  function newChat() {
    setConversationId(crypto.randomUUID());
    setCurrentSessionId(null);
    const s = SCENES.find(x => x.id === scene);
    setMessages([
      { role: 'assistant', content: `欢迎来到 **${s?.name || scene}** 模式！试试下面的问题，或者直接输入你的问题吧。` },
    ]);
  }

  async function handleFeedback(sessionId: number, value: 'LIKE' | 'DISLIKE') {
    const tk = getToken();
    if (!tk) return;
    const newVal = sessionFeedback[sessionId] === value ? null : value;
    setSessionFeedback(prev => ({ ...prev, [sessionId]: newVal }));
    try {
      await fetch(`${API_BASE}/sandbox/sessions/${sessionId}/feedback`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
        body: JSON.stringify({ feedback: newVal }),
      });
    } catch {}
  }

  function formatTime(dateStr: string) {
    const d = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - d.getTime();
    if (diff < 60000) return t.sandbox.justNow;
    if (diff < 3600000) return t.sandbox.minutesAgo.replace('{n}', String(Math.floor(diff / 60000)));
    if (diff < 86400000) return t.sandbox.hoursAgo.replace('{n}', String(Math.floor(diff / 3600000)));
    return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  }

  async function shareSessionLink() {
    if (!getToken() || !currentSessionId) { toast.error('请先登录'); return; }
    try {
      const tk = getToken();
      const res = await fetch(`${API_BASE}/sandbox/sessions/${currentSessionId}/share`, {
        method: 'POST', headers: { Authorization: `Bearer ${tk}` },
      });
      const data = await res.json();
      if (data.shareUrl) {
        await navigator.clipboard.writeText(data.shareUrl);
        toast.success(t.sandbox.linkCopied);
      }
    } catch { toast.error('生成分享链接失败'); }
  }

  function shareToCommunity(content: string, title?: string) {
    if (!getToken()) { toast.error('请先登录'); return; }
    apiFetch('/community/posts', {
      method: 'POST',
      body: JSON.stringify({
        title: title || `AI对话分享 - ${new Date().toLocaleDateString()}`,
        content: `【AI沙箱对话分享】\n\n${content}\n\n---\n来自宇之然AI沙箱`,
        tags: '沙箱分享,AI对话',
      }),
    }).then(() => toast.success(t.sandbox.shareSuccess)).catch(() => toast.error(t.sandbox.shareFailed));
  }

  const currentScene = SCENES.find(s => s.id === scene) || SCENES[0] || null;

  if (skillsLoading) return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="animate-pulse space-y-4">
        <div className="h-8 w-48 bg-muted rounded-lg" />
        <div className="h-[65vh] bg-muted rounded-2xl" />
      </div>
    </div>
  );
  const isNewChat = messages.length <= 1 && messages[0]?.role === 'assistant';

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex items-center justify-between mb-4 gap-3">
        <div className="flex items-center gap-3 min-w-0 flex-shrink overflow-hidden">
          <button onClick={() => setSessionsOpen(!sessionsOpen)}
            className="lg:hidden p-2 text-muted-foreground hover:text-foreground rounded-lg hover:bg-accent flex-shrink-0">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>
          <div className="truncate">
            <h1 className="text-2xl font-bold text-foreground truncate">{t.sandbox.title}</h1>
            <p className="text-sm text-muted-foreground mt-0.5 truncate">{t.sandbox.subtitle}</p>
          </div>
        </div>
        <div className="flex items-center gap-2 sm:gap-3 flex-shrink-0">
          <button onClick={() => setShowParams(!showParams)}
            className={`px-2.5 py-1.5 rounded-xl text-xs font-medium border transition-colors ${
              showParams ? 'bg-brand-600 text-white border-brand-600' : 'bg-card text-muted-foreground border-border hover:text-foreground'
            }`}>
            ⚙ {t.sandbox.advancedParams}
          </button>
          <ModelSelector value={model} onChange={setModel} className="w-40 sm:w-48" />
          {!isLoggedIn && (
            <Link href="/auth"
              className="px-4 py-1.5 text-sm font-medium text-brand-600 border border-brand-200 rounded-lg hover:bg-brand-50">
              {t.sandbox.loginForMore}
            </Link>
          )}
        </div>
      </div>

      <div className="flex gap-4">
        {isLoggedIn && (
          <>
            <div className={`${sessionsOpen ? 'fixed inset-0 z-40 bg-black/50 lg:static lg:bg-transparent' : 'hidden'} lg:block lg:w-72 shrink-0`}>
              <div className={`${sessionsOpen ? 'fixed left-0 top-0 bottom-0 w-80 z-50' : ''} lg:static lg:w-72 bg-card border border-border rounded-2xl overflow-hidden flex flex-col`} style={{ maxHeight: '75vh' }}>
                <div className="p-3 border-b border-border flex items-center justify-between">
                  <span className="text-sm font-medium text-foreground">{t.sandbox.history}</span>
                  <button onClick={newChat}
                    className="text-xs px-3 py-1 bg-brand-600 text-white rounded-lg hover:bg-brand-700">
                    {t.sandbox.newChat}
                  </button>
                </div>
                <div className="p-2 border-b border-border">
                  <input type="text" value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
                    placeholder={t.sandbox.searchHistory} onKeyDown={e => { if (e.key === 'Enter') loadSessions(); }}
                    className="w-full px-3 py-1.5 bg-background border border-border rounded-lg text-xs focus:outline-none focus:border-brand-400" />
                </div>
                <div className="flex-1 overflow-y-auto">
                  {sessionsLoading ? (
                    <div className="p-4 space-y-3">
                      {[1,2,3].map(i => (
                        <div key={i} className="h-12 bg-muted rounded-lg animate-pulse" />
                      ))}
                    </div>
                  ) : sessions.length === 0 ? (
                    <div className="p-4 text-center text-xs text-muted-foreground">{t.sandbox.noHistory}</div>
                  ) : sessions.map(s => (
                      <div key={s.id} onClick={() => { if (renamingId !== s.id) { loadSession(s.id); setSessionsOpen(false); } }}
                        className="group px-3 py-2.5 hover:bg-accent cursor-pointer border-b border-border/50"
                        onDoubleClick={() => { setRenamingId(s.id); setRenameValue(s.title); }}>
                        {renamingId === s.id ? (
                          <input type="text" value={renameValue} onChange={e => setRenameValue(e.target.value)}
                            autoFocus onClick={e => e.stopPropagation()}
                            onBlur={() => renameSession(s.id, renameValue)}
                            onKeyDown={e => { if (e.key === 'Enter') { e.stopPropagation(); renameSession(s.id, renameValue); } if (e.key === 'Escape') setRenamingId(null); }}
                            className="w-full px-1 py-0.5 text-xs font-medium bg-background border border-border rounded focus:outline-none" />
                        ) : (
                          <div className="text-xs font-medium text-foreground truncate">{s.title}</div>
                        )}
                      <div className="flex items-center justify-between mt-1">
                        <span className="text-[10px] text-muted-foreground">{formatTime(s.createdAt)} · {s.model}</span>
                        <button onClick={e => { e.stopPropagation(); deleteSession(s.id); }}
                          className="opacity-0 group-hover:opacity-100 text-[10px] text-red-500 hover:text-red-700">
                          {t.common.delete}
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              {sessionsOpen && (
                <div className="fixed inset-0 z-40 lg:hidden" onClick={() => setSessionsOpen(false)} />
              )}
            </div>
          </>
        )}

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-4">
            <button onClick={() => setMode('learn')}
              className={`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${
                mode === 'learn' ? 'bg-brand-600 text-white border-brand-600' : 'bg-card text-muted-foreground border-border hover:text-foreground'
              }`}>
              📚 {t.sandbox.learnMode}
            </button>
            <button onClick={() => setMode('free')}
              className={`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${
                mode === 'free' ? 'bg-brand-600 text-white border-brand-600' : 'bg-card text-muted-foreground border-border hover:text-foreground'
              }`}>
              🎯 {t.sandbox.freeMode}
            </button>
            {mode === 'free' && SCENES.length > 0 && (
              <select value={scene} onChange={e => handleSceneChange(e.target.value)}
                className="ml-2 px-2 py-1.5 text-xs bg-card border border-border rounded-lg text-foreground focus:outline-none focus:border-brand-400">
                {SCENES.map(s => (
                  <option key={s.id} value={s.id}>{s.icon} {s.name}</option>
                ))}
              </select>
            )}
          </div>

          {showParams && (
            <div className="bg-card border border-border rounded-2xl p-4 mb-4">
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="text-xs text-muted-foreground block mb-1">{t.sandbox.temperature} ({temperature})</label>
                  <input type="range" min="0" max="2" step="0.1" value={temperature}
                    onChange={e => setTemperature(parseFloat(e.target.value))}
                    className="w-full accent-brand-600" />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground block mb-1">{t.sandbox.topP} ({topP})</label>
                  <input type="range" min="0" max="1" step="0.05" value={topP}
                    onChange={e => setTopP(parseFloat(e.target.value))}
                    className="w-full accent-brand-600" />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground block mb-1">{t.sandbox.maxTokens} ({maxTokens})</label>
                  <input type="range" min="256" max="4096" step="256" value={maxTokens}
                    onChange={e => setMaxTokens(parseInt(e.target.value))}
                    className="w-full accent-brand-600" />
                </div>
              </div>
            </div>
          )}

          {guidedStageId && mode === 'free' && (() => {
            const guide = STAGE_GUIDES[guidedStageId];
            const stage = LEARNING_STAGES.find(s => s.id === guidedStageId);
            const stageNum = LEARNING_STAGES.findIndex(s => s.id === guidedStageId) + 1;
            const task = guide?.[guidedTaskIdx];
            const isLast = guidedTaskIdx >= guide.length - 1;
            const progressPct = ((guidedDone ? guide.length : guidedTaskIdx) / guide.length) * 100;
            return (
            <div className="bg-brand-600/5 border border-brand-200 dark:border-brand-800 rounded-2xl p-4 mb-4">
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-bold text-brand-600 uppercase tracking-wider">{stageNum} / {LEARNING_STAGES.length}</span>
                    <span className="text-sm font-semibold text-foreground">{t.sandbox[stage?.descKey as keyof typeof t.sandbox] as string}</span>
                  </div>
                  <div className="w-full bg-muted rounded-full h-1 mb-3">
                    <div className="bg-brand-600 h-1 rounded-full transition-all" style={{ width: `${progressPct}%` }} />
                  </div>
                  {guidedDone ? (
                    <div className="flex items-center gap-2">
                      <span className="text-lg">🎉</span>
                      <div>
                        <p className="text-sm font-semibold text-foreground">{t.sandbox.stageDone}！本阶段全部完成</p>
                        <p className="text-xs text-muted-foreground">你已经掌握了这一阶段的核心技能，继续前进吧！</p>
                      </div>
                    </div>
                  ) : task ? (
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <span className="w-5 h-5 rounded-full bg-brand-600 text-white flex items-center justify-center text-[10px] font-bold shrink-0">{guidedTaskIdx + 1}</span>
                        <span className="text-xs font-medium text-foreground">{t.sandbox[task.taskKey as keyof typeof t.sandbox] as string}</span>
                      </div>
                      <p className="text-xs text-muted-foreground ml-7 mb-2">{task.hint}</p>
                    </div>
                  ) : null}
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  {!guidedDone ? (
                    <button onClick={handleCompleteTask}
                      className="px-4 py-2 text-sm font-medium bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-colors">
                      {isLast ? '✅ 全部完成！' : '✅ 完成，下一步'}
                    </button>
                  ) : (
                    <button onClick={handleNextStage}
                      className="px-4 py-2 text-sm font-medium bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-colors">
                      {stageNum < LEARNING_STAGES.length ? '➡️ 下一阶段' : '🎊 完成全部！'}
                    </button>
                  )}
                  <button onClick={handleExitGuide} className="px-3 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors">退出引导</button>
                </div>
              </div>
            </div>
            );
          })()}

          {mode === 'learn' && (
            <div className="bg-card rounded-2xl border border-border shadow-sm p-4 sm:p-6 overflow-y-auto" style={{ maxHeight: '75vh' }}>
              <div className="flex items-center gap-2 mb-4">
                <h2 className="text-lg font-semibold text-foreground">{t.sandbox.learnPath}</h2>
              </div>
              <LearningPath onStartStage={handleStartStage} />
            </div>
          )}

          {mode === 'free' && (<>
            <div ref={messagesContainerRef} className="flex-1 overflow-y-auto p-4 space-y-4">
              {isNewChat && (
                <div className="flex flex-wrap gap-2 mb-4">
                  {currentScene?.starters?.map((q, i) => (
                    <button key={i} onClick={() => setInput(q)}
                      className="px-3 py-1.5 text-xs bg-muted text-muted-foreground rounded-full border border-border hover:bg-accent hover:text-foreground transition-colors">
                      {q}
                    </button>
                  ))}
                </div>
              )}
              {messages.map((msg, i) => {
                if (msg.role === 'system') return null;
                const isLastAssistant = msg.role === 'assistant' && i === messages.length - 1;
                return (
                  <div key={i}>
                    <div className={`flex items-start gap-3 ${msg.role === 'user' ? 'justify-end' : ''}`}>
                      {msg.role === 'assistant' && (
                        <div className="w-8 h-8 bg-brand-600 rounded-xl flex items-center justify-center text-white text-sm font-bold shrink-0">Y</div>
                      )}
                      <div className={`max-w-[75%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap ${msg.role === 'user' ? 'bg-brand-600 text-white rounded-tr-none' : 'bg-muted text-foreground rounded-tl-none'}`}>
                        {(() => {
                          const parts = msg.content.split(/(```(?:\w+)?\n[\s\S]*?```)/g)
                          return parts.map((part, pi) => {
                            const match = part.match(/^```(\w*)\n([\s\S]*)```$/)
                            if (match) {
                              const [, lang, code] = match
                              return <CodeBlock key={pi} code={code.trim()} language={lang || undefined} />
                            }
                            if (pi > 0 && parts[pi-1].startsWith('```')) return null
                            return <span key={pi} className="whitespace-pre-wrap">{part}</span>
                          })
                        })()}
                      </div>
                      {msg.role === 'user' && (
                        <div className="w-8 h-8 bg-muted-foreground/20 rounded-xl flex items-center justify-center text-xs font-bold shrink-0">我</div>
                      )}
                    </div>
                    {msg.role === 'assistant' && currentSessionId && isLastAssistant && (
                      <div className="flex items-center gap-2 mt-1 ml-11">
                        <button onClick={() => handleFeedback(currentSessionId, 'LIKE')}
                          className={`text-xs px-2 py-1 rounded-full border transition-colors ${sessionFeedback[currentSessionId] === 'LIKE' ? 'bg-green-500/10 text-green-600 border-green-300' : 'text-muted-foreground border-border hover:border-green-300 hover:text-green-600'}`}>
                          {t.sandbox.helpful}
                        </button>
                        <button onClick={() => handleFeedback(currentSessionId, 'DISLIKE')}
                          className={`text-xs px-2 py-1 rounded-full border transition-colors ${sessionFeedback[currentSessionId] === 'DISLIKE' ? 'bg-red-500/10 text-red-600 border-red-300' : 'text-muted-foreground border-border hover:border-red-300 hover:text-red-600'}`}>
                          {t.sandbox.notHelpful}
                        </button>
                      </div>
                    )}
                    {msg.role === 'assistant' && extractCodeBlocks(msg.content).length > 0 && (
                      <div className="flex flex-wrap gap-2 mt-2 ml-11">
                        {extractCodeBlocks(msg.content).map((code, ci) => (
                          <button key={ci} onClick={() => window.open(`/sandbox/code?code=${btoa(code)}`, '_blank')}
                            className="text-xs px-2.5 py-1 rounded-full border border-border text-brand-600 hover:bg-accent transition-colors">
                            {t.sandbox.runInCodeSandbox}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
              {sending && (
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 bg-brand-600 rounded-xl flex items-center justify-center text-white text-sm font-bold shrink-0">Y</div>
                  <div className="bg-muted rounded-2xl rounded-tl-none px-4 py-2.5">
                    <span className="inline-flex gap-1">
                      <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" />
                      <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                      <span className="w-2 h-2 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                    </span>
                  </div>
                </div>
              )}
              {!sending && messages.length > 2 && (
                <div className="flex justify-end gap-2">
                  <button onClick={shareSessionLink}
                    className="text-xs text-brand-600 hover:underline">
                    {t.sandbox.copyShareLink}
                  </button>
                  <button onClick={() => {
                    const lastAssistantMsg = [...messages].reverse().find(m => m.role === 'assistant');
                    if (lastAssistantMsg) shareToCommunity(lastAssistantMsg.content);
                  }} className="text-xs text-brand-600 hover:underline">
                    {t.sandbox.shareToCommunity}
                  </button>
                </div>
              )}
              <div ref={messagesEndRef} />
            </div>

              <div className="border-t border-border p-4">
                {quota && quota.totalRemaining <= 0 ? (
                  <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-3 mb-3">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-sm font-medium text-amber-800 dark:text-amber-300">{t.sandbox.quotaExhausted}</div>
                        <div className="text-xs text-amber-600 dark:text-amber-400 mt-0.5">{t.sandbox.quotaExhaustedHint}</div>
                      </div>
                      <Link href="/donate"
                        className="px-3 py-1.5 text-xs font-medium bg-rose-600 text-white rounded-lg hover:bg-rose-700 shrink-0">
                        {t.donate.toDonate}
                      </Link>
                    </div>
                  </div>
                ) : quota && (
                  <div className="text-xs text-muted-foreground mb-2 flex items-center gap-3">
                    <span>{t.sandbox.dailyQuota.replace('{used}', String(quota.used)).replace('{remaining}', String(quota.dailyRemaining))}</span>
                    {quota.extra > 0 && <span className="text-brand-600">{t.packages.extraQuota.replace('{n}', String(quota.extra))}</span>}
                  </div>
                )}
              {uploadedImages.length > 0 && (
                <div className="flex gap-2 mb-2 flex-wrap">
                  {uploadedImages.map((img, i) => (
                    <div key={i} className="relative group">
                      <img src={img} alt="" className="w-16 h-16 object-cover rounded-lg border border-border" />
                      <button onClick={() => setUploadedImages(prev => prev.filter((_, j) => j !== i))}
                        className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">×</button>
                    </div>
                  ))}
                </div>
              )}
              <form onSubmit={handleSend} className="flex gap-2">
                <input ref={fileInputRef} type="file" accept="image/*" className="hidden"
                  onChange={async e => {
                    const file = e.target.files?.[0]
                    if (!file) return
                    setUploading(true)
                    const formData = new FormData()
                    formData.append('file', file)
                    try {
                      const tk = getToken()
                      const res = await fetch(`${API_BASE}/upload`, {
                        method: 'POST',
                        headers: tk ? { Authorization: `Bearer ${tk}` } : {},
                        body: formData,
                      })
                      const data = await res.json()
                      if (data.url) setUploadedImages(prev => [...prev, data.url])
                    } catch {}
                    setUploading(false)
                  }} />
                <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploading || !isLoggedIn}
                  className="px-2.5 py-2.5 text-muted-foreground hover:text-foreground border border-input rounded-xl hover:bg-accent disabled:opacity-50">
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                </button>
                <input type="text" value={input} onChange={e => setInput(e.target.value)}
                  placeholder={t.sandbox.placeholder} disabled={sending}
                  className="flex-1 px-4 py-2.5 bg-background border border-input rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50" />
                <button type="submit" disabled={sending || (!input.trim() && uploadedImages.length === 0)}
                  className="px-5 py-2.5 bg-brand-600 text-white text-sm font-medium rounded-xl hover:bg-brand-700 disabled:opacity-50">
                  {sending ? t.sandbox.sending : t.sandbox.send}
                </button>
              </form>
            </div>

          </>)}
          <div className="mt-4 text-center text-xs text-muted-foreground">
            {t.sandbox.aiReplyDisclaimer}{!isLoggedIn && ` ${t.sandbox.loginForMoreQuota}`}
          </div>
        </div>
      </div>
    </div>
  );
}
