/* AI 历史通鉴 — 人物对话 / 时间脉络 双模式 */
const { useState, useRef, useEffect } = React;
const Icon = window.LCYIcon;
const { Page, Intro, Field, Seg, GenBtn, ResultCard, BusyCard, Rich, flash } = window;

const FIGURES = ["李白", "苏轼", "诸葛亮", "秦始皇", "拿破仑", "爱因斯坦"];

function HistoryApp() {
  const [mode, setMode] = useState("chat");
  const [figure, setFigure] = useState("");
  const [msgs, setMsgs] = useState([]);
  const [val, setVal] = useState("");
  const [topic, setTopic] = useState("");
  const [timeline, setTimeline] = useState("");
  const [busy, setBusy] = useState(false);
  const endRef = useRef(null);
  useEffect(()=>{ if(endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; });

  const startFigure = (f) => { setFigure(f); setMsgs([{ who:"ai", text:`我便是${f}。你想与我聊些什么？` }]); };

  const send = async () => {
    if (!val.trim() || !figure) return;
    const q = val.trim(); setVal("");
    setMsgs(m=>[...m, {who:"me",text:q}, {who:"ai",text:"",loading:true}]);
    try {
      const ctx = msgs.filter(m=>!m.loading).map(m=>(m.who==="me"?"用户：":figure+"：")+m.text).join("\n");
      const out = await window.aiComplete(`你正在扮演历史人物「${figure}」与用户对话。请以${figure}的身份、口吻、价值观和时代背景作答，可适当引用其生平与作品，语言生动有代入感但通俗易懂。不要跳出角色。\n\n${ctx?"之前的对话：\n"+ctx+"\n\n":""}用户：${q}\n\n${figure}：`);
      setMsgs(m=>m.map((x,i)=>i===m.length-1?{who:"ai",text:out}:x));
    } catch (e) { flash(window.failMsg(e)); setMsgs(m=>m.filter(x=>!x.loading)); }
  };

  const genTimeline = async () => {
    if (!topic.trim()) { flash("输入一个历史事件或时期"); return; }
    setBusy(true); setTimeline("");
    try {
      setTimeline(await window.aiComplete(`你是历史老师。请为"${topic.trim()}"梳理一条清晰的时间脉络：按时间顺序列出关键节点（标注年份/时间），每个节点简述发生了什么及其意义，最后用一段话点出整体的因果逻辑。中文：`));
    } catch (e) { flash(window.failMsg(e)); } finally { setBusy(false); }
  };

  return (
    <Page icon="landmark" name="历史通鉴" sub="AI HISTORY">
      <Intro eyebrow="AI 历史老师" title="让历史活起来" sub="与历史人物隔空对话，或把任意事件梳理成清晰的时间脉络。" />
      <div className="card">
        <Field icon="compass" label="模式" style={{marginBottom: mode==="chat"&&figure?16:0}}>
          <Seg options={[{id:"chat",label:"与人物对话"},{id:"timeline",label:"时间脉络"}]} value={mode} onChange={setMode} />
        </Field>

        {mode==="chat" ? <React.Fragment>
          <Field icon="users" label="选择对话人物"><Seg options={FIGURES} value={figure} onChange={startFigure} /></Field>
          {figure && <div className="field">
            <div ref={endRef} style={{maxHeight:300,overflowY:"auto",display:"flex",flexDirection:"column",gap:10,padding:"4px 0 12px"}}>
              {msgs.map((m,i)=>(
                <div key={i} style={{alignSelf:m.who==="me"?"flex-end":"flex-start",maxWidth:"86%"}}>
                  <div style={{padding:"10px 14px",borderRadius:14,fontSize:14.5,lineHeight:1.7,background:m.who==="me"?"var(--grad-soft)":"var(--surface)",border:"1px solid var(--border)",borderTopRightRadius:m.who==="me"?4:14,borderTopLeftRadius:m.who==="ai"?4:14}}>
                    {m.loading ? <span className="busy-row" style={{padding:0}}><span className="spinner"></span>{figure}正在思索…</span> : m.text}
                  </div>
                </div>
              ))}
            </div>
            <div style={{display:"flex",gap:9}}>
              <input className="in" placeholder={`问问${figure}…`} value={val} onChange={e=>setVal(e.target.value)} onKeyDown={e=>e.key==="Enter"&&send()} style={{flex:1}} />
              <button className="btn btn-primary" onClick={send}><Icon name="arrow-up" /></button>
            </div>
          </div>}
        </React.Fragment> : <React.Fragment>
          <Field icon="milestone" label="历史事件 / 时期">
            <textarea className="in" placeholder="例：第一次世界大战 / 唐朝由盛转衰 / 工业革命" value={topic} onChange={e=>setTopic(e.target.value)} />
          </Field>
          <GenBtn onClick={genTimeline} busy={busy} label="生成时间脉络" busyLabel="梳理中…" />
        </React.Fragment>}
      </div>

      {mode==="timeline" && busy && <BusyCard label="AI 正在梳理脉络…" />}
      {mode==="timeline" && timeline && <ResultCard icon="git-commit-horizontal" title="时间脉络" copy={timeline}><Rich>{timeline}</Rich></ResultCard>}
    </Page>
  );
}
ReactDOM.createRoot(document.getElementById("root")).render(<HistoryApp />);
