/* 运营后台：仅显示已连接服务器的功能。 */
const AdminUI = {
  page: { minHeight:'100vh', background:'#f5f9f8', color:'#16302f', fontFamily:'system-ui,sans-serif', padding:'28px' },
  box: { background:'#fff', border:'1px solid #d6e5e2', borderRadius:8, padding:20, marginBottom:16 },
  input: { width:'100%', boxSizing:'border-box', padding:'10px', margin:'5px 0 12px', border:'1px solid #b8d1cd', borderRadius:4, fontSize:14 },
  button: { background:'#12545a', color:'white', padding:'9px 14px', border:0, borderRadius:4, cursor:'pointer', margin:'3px' },
};
async function adminRequest(url, options = {}) {
  const config = { credentials:'same-origin', ...options, headers:{...(options.headers || {})} };
  if (options.body && !(options.body instanceof FormData)) { config.headers['Content-Type']='application/json'; config.body=JSON.stringify(options.body); }
  const r=await fetch('/api/admin'+url, config);
  let data={}; try { data=await r.json(); } catch (_) {}
  if (!r.ok) throw new Error((data.error && data.error.message) || ('请求失败（'+r.status+'）'));
  return data;
}
function Admin() {
  const [user,setUser]=React.useState(null), [loading,setLoading]=React.useState(true), [error,setError]=React.useState('');
  const [email,setEmail]=React.useState(''), [password,setPassword]=React.useState(''), [section,setSection]=React.useState('dashboard');
  const [message,setMessage]=React.useState('');
  React.useEffect(()=>{ adminRequest('/me').then(x=>setUser(x.user)).catch(()=>{}).finally(()=>setLoading(false)); },[]);
  const login=async e=>{e.preventDefault();setError('');try{const r=await adminRequest('/login',{method:'POST',body:{email,password}});setUser(r.user);setPassword('');}catch(err){setError(err.message);}};
  const logout=async()=>{await adminRequest('/logout',{method:'POST'});setUser(null);setSection('dashboard');};
  if (loading) return <main style={AdminUI.page}>正在检查登录状态…</main>;
  if (!user) return <main style={AdminUI.page}><form onSubmit={login} style={{...AdminUI.box,maxWidth:440,margin:'9vh auto'}}><h1>运营后台登录</h1><p>使用网站管理员账号登录。</p><label>邮箱<input style={AdminUI.input} type="email" autoComplete="username" required value={email} onChange={e=>setEmail(e.target.value)} /></label><label>密码<input style={AdminUI.input} type="password" autoComplete="current-password" required value={password} onChange={e=>setPassword(e.target.value)} /></label>{error && <p role="alert" style={{color:'#a32d2d'}}>{error}</p>}<button style={AdminUI.button}>登录</button></form></main>;
  const menus=[['dashboard','概览'],['posts','文章'],['events','活动'],['bookings','预约'],['enrollments','报名'],['images','站点图片'],['password','修改密码']];
  return <main style={AdminUI.page}><header style={{display:'flex',alignItems:'center',flexWrap:'wrap',gap:8,marginBottom:18}}><h1 style={{fontSize:22,marginRight:'auto'}}>量子催眠中国 · 运营后台</h1><span>{user.email}</span><button style={AdminUI.button} onClick={logout}>退出登录</button><button style={AdminUI.button} onClick={()=>window.__go('home')}>返回网站</button></header><nav style={{display:'flex',flexWrap:'wrap',gap:4,marginBottom:18}}>{menus.map(([id,label])=><button key={id} style={{...AdminUI.button,background:section===id?'#12545a':'#658d89'}} onClick={()=>{setSection(id);setMessage('');}}>{label}</button>)}</nav>{message && <p role="status">{message}</p>}{section==='dashboard' && <AdminDashboard/>}{section==='posts' && <AdminPosts notify={setMessage}/>} {section==='events' && <AdminEvents notify={setMessage}/>} {section==='bookings' && <AdminBookings notify={setMessage}/>} {section==='enrollments' && <AdminEnrollments/>}{section==='images' && <AdminImages notify={setMessage}/>} {section==='password' && <AdminPassword onChanged={()=>{setUser(null);setMessage('');setError('密码已修改，请使用新密码登录。');}}/>}</main>;
}
function AdminLoad({url, children}) {
  const [data,setData]=React.useState(null),[error,setError]=React.useState(''),[version,setVersion]=React.useState(0);
  React.useEffect(()=>{let alive=true;setError('');setData(null);adminRequest(url).then(x=>alive&&setData(x)).catch(e=>alive&&setError(e.message));return()=>{alive=false};},[url,version]);
  if(error)return <div role="alert" style={AdminUI.box}>读取失败：{error} <button style={AdminUI.button} onClick={()=>setVersion(x=>x+1)}>重试</button></div>;
  if(!data)return <div style={AdminUI.box}>加载中…</div>;
  return children(data,()=>setVersion(x=>x+1));
}
function AdminDashboard(){return <AdminLoad url="/dashboard">{d=><div style={AdminUI.box}><h2>网站概览</h2><p>已发布文章：{d.content.posts}　草稿：{d.content.drafts}</p><p>即将举办活动：{d.content.eventsUpcoming}　往期活动：{d.content.eventsPast}</p><p>新预约：{d.bookings.new}　待支付报名：{d.enrollments.pending}</p><p>以下栏目连接当前网站的数据；公众号自动同步等未完成的功能没有开放。</p></div>}</AdminLoad>}
function AdminPassword({onChanged}) {const [current,setCurrent]=React.useState(''),[next,setNext]=React.useState(''),[again,setAgain]=React.useState(''),[err,setErr]=React.useState('');const submit=async e=>{e.preventDefault();if(next!==again){setErr('两次输入的新密码不一致');return;}try{await adminRequest('/password',{method:'POST',body:{currentPassword:current,newPassword:next}});onChanged();}catch(e){setErr(e.message)}};return <form style={{...AdminUI.box,maxWidth:520}} onSubmit={submit}><h2>修改密码</h2><label>当前密码<input style={AdminUI.input} type="password" required autoComplete="current-password" value={current} onChange={e=>setCurrent(e.target.value)}/></label><label>新密码（至少 12 个字符）<input style={AdminUI.input} type="password" minLength="12" required autoComplete="new-password" value={next} onChange={e=>setNext(e.target.value)}/></label><label>再次输入新密码<input style={AdminUI.input} type="password" minLength="12" required autoComplete="new-password" value={again} onChange={e=>setAgain(e.target.value)}/></label>{err&&<p role="alert">{err}</p>}<button style={AdminUI.button}>保存新密码</button></form>}
function AdminPosts({notify}) {const [edit,setEdit]=React.useState(null),[error,setError]=React.useState('');const open=async id=>{try{setEdit(id?await adminRequest('/posts/'+encodeURIComponent(id)):{title:'',excerpt:'',category:'其它',cover:'',status:'draft',body:[]});}catch(e){setError(e.message)}};return <AdminLoad url="/posts?pageSize=200">{(d,reload)=><div style={AdminUI.box}><h2>文章</h2>{error&&<p role="alert">{error}</p>}<button style={AdminUI.button} onClick={()=>open(null)}>新建文章</button>{edit&&<AdminPostEditor item={edit} cancel={()=>setEdit(null)} save={async b=>{try{await adminRequest(edit.id?'/posts/'+encodeURIComponent(edit.id):'/posts',{method:edit.id?'PATCH':'POST',body:b});setEdit(null);notify('文章已保存');reload();}catch(e){setError(e.message)}}}/>}<div>{d.items.map(p=><div key={p.id} style={{padding:'12px 0',borderBottom:'1px solid #e1eeeb'}}><b>{p.title}</b>　{p.status==='published'?'已发布':'草稿'}　<button style={AdminUI.button} onClick={()=>open(p.id)}>编辑</button></div>)}</div></div>}</AdminLoad>}
function AdminPostEditor({item,save,cancel}) {const [v,setV]=React.useState(item);React.useEffect(()=>setV(item),[item]);const set=(k,x)=>setV(o=>({...o,[k]:x}));return <form style={{...AdminUI.box,background:'#f5f9f8'}} onSubmit={e=>{e.preventDefault();save({title:v.title,excerpt:v.excerpt,category:v.category,cover:v.cover,status:v.status,body:v.body})}}><h3>{item.id?'编辑文章':'新建文章'}</h3>{[['title','标题'],['excerpt','摘要'],['category','分类'],['cover','封面图片地址']].map(([k,label])=><label key={k}>{label}<input required={k==='title'} style={AdminUI.input} value={v[k]||''} onChange={e=>set(k,e.target.value)}/></label>)}<div>正文{(v.body||[]).map((block,i)=><div key={i} style={{borderBottom:'1px solid #d6e5e2',padding:'8px 0'}}><label>段落类型 <select value={block[0]} onChange={e=>set('body',v.body.map((b,n)=>n===i?[e.target.value,b[1]]:b))}><option value="p">正文</option><option value="h2">小标题</option><option value="q">引用</option></select></label><textarea style={{...AdminUI.input,minHeight:70}} value={block[1]||''} onChange={e=>set('body',v.body.map((b,n)=>n===i?[b[0],e.target.value]:b))}/><button type="button" style={AdminUI.button} onClick={()=>set('body',v.body.filter((_,n)=>n!==i))}>移除此段</button></div>)}<button type="button" style={AdminUI.button} onClick={()=>set('body',[...(v.body||[]),['p','']])}>添加段落</button></div><label>状态 <select value={v.status||'draft'} onChange={e=>set('status',e.target.value)}><option value="draft">草稿</option><option value="published">发布</option></select></label><div><button style={AdminUI.button}>保存</button><button type="button" style={AdminUI.button} onClick={cancel}>取消</button></div></form>}
function AdminEvents({notify}) {const [edit,setEdit]=React.useState(null),[error,setError]=React.useState('');return <AdminLoad url="/events">{(d,reload)=><div style={AdminUI.box}><h2>活动</h2>{error&&<p role="alert">{error}</p>}<button style={AdminUI.button} onClick={()=>setEdit({title:'',city:'',venue:'',start_date:'',end_date:'',state:'upcoming'})}>新建活动</button>{edit&&<AdminEventEditor item={edit} cancel={()=>setEdit(null)} save={async b=>{try{await adminRequest(edit.id?'/events/'+encodeURIComponent(edit.id):'/events',{method:edit.id?'PATCH':'POST',body:b});setEdit(null);notify('活动已保存');reload();}catch(e){setError(e.message)}}}/>} {d.items.map(x=><div key={x.id} style={{padding:'12px 0',borderBottom:'1px solid #e1eeeb'}}><b>{x.title}</b>　{x.city}　{x.start_date}　{x.state==='past'?'往期':'即将举行'} <button style={AdminUI.button} onClick={()=>setEdit(x)}>编辑</button></div>)}</div>}</AdminLoad>}
function AdminEventEditor({item,save,cancel}) {const [v,setV]=React.useState(item);React.useEffect(()=>setV(item),[item]);const set=(k,x)=>setV(o=>({...o,[k]:x}));return <form style={{...AdminUI.box,background:'#f5f9f8'}} onSubmit={e=>{e.preventDefault();const changes={title:v.title,city:v.city,venue:v.venue,start:v.start_date||null,end:v.end_date||null,state:v.state};if ((v.start_date||'')!==(item.start_date||'') || (v.end_date||'')!==(item.end_date||'')) changes.dateText=[v.start_date,v.end_date].filter(Boolean).join(' 至 ');save(changes)}}><h3>{item.id?'编辑活动':'新建活动'}</h3>{[['title','标题','text'],['city','城市','text'],['venue','地点','text'],['start_date','开始日期','date'],['end_date','结束日期','date']].map(([k,label,type])=><label key={k}>{label}<input style={AdminUI.input} required={k==='title'} type={type} value={v[k]||''} onChange={e=>set(k,e.target.value)}/></label>)}<label>状态 <select value={v.state} onChange={e=>set('state',e.target.value)}><option value="upcoming">即将举行</option><option value="past">往期</option></select></label><div><button style={AdminUI.button}>保存</button><button type="button" style={AdminUI.button} onClick={cancel}>取消</button></div></form>}
function AdminBookings({notify}){const [error,setError]=React.useState('');return <AdminLoad url="/bookings?pageSize=200">{(d,reload)=><div style={AdminUI.box}><h2>预约</h2>{error&&<p role="alert">{error}</p>}{d.items.length===0?<p>暂无预约。</p>:d.items.map(x=><div key={x.id} style={{padding:'12px 0',borderBottom:'1px solid #e1eeeb'}}><b>{x.name}</b>　{x.city}　{x.phone}　{x.wechat}<p>{x.message}</p><label>处理状态 <select value={x.status} onChange={async e=>{try{await adminRequest('/bookings/'+x.id,{method:'PATCH',body:{status:e.target.value}});notify('预约状态已更新');reload()}catch(err){setError(err.message)}}}><option value="new">新预约</option><option value="contacted">已联系</option><option value="scheduled">已安排</option><option value="closed">已关闭</option></select></label></div>)}</div>}</AdminLoad>}
function AdminEnrollments(){return <AdminLoad url="/enrollments">{d=><div style={AdminUI.box}><h2>报名</h2>{d.items.length===0?<p>暂无报名记录。</p>:d.items.map(x=><p key={x.id}>{x.name}　{x.course_title}　{x.phone}　{x.payment}</p>)}</div>}</AdminLoad>}
function AdminImages({notify}){return <div style={AdminUI.box}><AdmMedia flash={notify}/></div>}
Object.assign(window,{Admin});
