/* WeChat identity is established exclusively by the server callback. */
const AuthCtx = React.createContext(null);
function useAuth() { return React.useContext(AuthCtx); }
async function readerRequest(url, options) {
  const r=await fetch(url,options);const data=await r.json();
  if(!r.ok)throw new Error(data.error?.message||'请求失败，请重试。');return data;
}
function AuthProvider({children}) {
  const [user,setUser]=React.useState(null),[gate,setGate]=React.useState(null),[profile,setProfile]=React.useState(false);
  const userRef=React.useRef(null);
  const accept=React.useCallback(u=>{userRef.current=u;setUser(u);},[]);
  React.useEffect(()=>{let live=true;readerRequest('/api/auth/me').then(u=>{if(live)accept(u.authed?u:null);}).catch(()=>{});return()=>{live=false;};},[accept]);
  const requireAuth=React.useCallback((reason,onDone)=>{
    if(userRef.current){onDone&&onDone();return true;}setGate({reason,onDone});return false;
  },[]);
  const logout=async()=>{await readerRequest('/api/auth/logout',{method:'POST'});accept(null);setProfile(false);};
  return <AuthCtx.Provider value={{user,setUser:accept,requireAuth,logout,openProfile:()=>requireAuth('profile',()=>setProfile(true))}}>
    {children}
    {gate&&<WechatLogin reason={gate.reason} onClose={()=>setGate(null)} onSuccess={u=>{accept(u);const cb=gate.onDone;setGate(null);cb&&cb();}}/>}
    {profile&&<ReaderProfile onClose={()=>setProfile(false)} />}
  </AuthCtx.Provider>;
}
const REASON_COPY={favorite:['登录后保存收藏','收藏保存在官网账号中，换设备登录后也能查看。'],enroll:['微信登录','登录后提交的报名会关联到你的官网账号。'],profile:['微信登录','查看官网收藏和登录后提交的报名记录。']};
function WechatLogin({reason='profile',onClose,onSuccess}) {
  const [challenge,setChallenge]=React.useState(null),[state,setState]=React.useState('loading'),[error,setError]=React.useState(''),[copied,setCopied]=React.useState(false),[retry,setRetry]=React.useState(0);
  const copy=REASON_COPY[reason]||REASON_COPY.profile;
  React.useEffect(()=>{
    let active=true,timer;const controller=new AbortController();setState('loading');setError('');setCopied(false);setChallenge(null);
    async function start(){try{
      const c=await readerRequest('/api/auth/qr',{method:'POST',signal:controller.signal});if(!active)return;setChallenge(c);setState('waiting');
      const deadline=Date.now()+c.expiresIn*1000;
      async function poll(){if(!active)return;if(Date.now()>=deadline){setState('expired');return;}
        try{const result=await readerRequest('/api/auth/poll?ticket='+encodeURIComponent(c.ticket),{headers:{'x-login-token':c.pollToken},signal:controller.signal});
          if(!active)return;if(result.state==='ok'){onSuccess(result.user);return;}if(result.state==='expired'){setState('expired');return;}setError('');
        }catch(e){if(!active)return;setError(e.message);}
        if(active)timer=setTimeout(poll,2500);
      }timer=setTimeout(poll,1800);
    }catch(e){if(active){setState('error');setError(e.message);}}}
    start();return()=>{active=false;controller.abort();clearTimeout(timer);};
  },[retry]);
  async function copyCommand(){try{await navigator.clipboard.writeText(challenge.command);setCopied(true);}catch{setError('请手动选择并复制上面的登录口令。');}}
  return <div className="wechat-login-layer"><Modal onClose={onClose} max={460}>
    <div className="modal-hd"><div><h3 style={{fontSize:26}}>{copy[0]}</h3><p style={{marginTop:10,color:'var(--txt-2)',fontSize:14}}>{copy[1]}</p></div><button className="x-btn" onClick={onClose} aria-label="关闭">{Ico.close()}</button></div>
    <div className="modal-bd">
      {state==='loading'&&<p role="status">正在创建安全登录请求…</p>}
      {challenge&&state==='waiting'&&<>
        <div className="qr-frame">{challenge.qrUrl?<img src={challenge.qrUrl} alt="微信登录二维码" style={{width:'100%',display:'block'}}/>:<QrCanvas ticket="FOLLOW01"/>}</div>
        {challenge.mode==='message'?<div style={{marginTop:20}}>
          <p style={{lineHeight:1.8}}>关注「量子催眠中国」后，在公众号对话中发送以下完整口令，再回到本页。</p>
          <div style={{padding:16,background:'var(--cloud-2)',borderRadius:6,margin:'14px 0',display:'flex',gap:12,alignItems:'center',flexWrap:'wrap'}}><strong style={{fontFamily:'var(--f-mono)',fontSize:20,userSelect:'all'}}>{challenge.command}</strong><button className="btn btn-ghost btn-sm" onClick={copyCommand}>{copied?'已复制':'复制口令'}</button></div>
          <p style={{fontSize:12,color:'var(--txt-2)'}}>口令 5 分钟内有效，只用于当前浏览器登录。请勿发送给其他人。</p>
        </div>:<p style={{marginTop:20,lineHeight:1.8}}>使用微信扫描上方二维码，在微信确认后返回本页；账号验证成功后自动登录。</p>}
        {challenge.notice&&<p style={{marginTop:12,fontSize:13}}>{challenge.notice}</p>}
        <p role="status" style={{marginTop:18,color:'var(--teal-700)'}}>等待公众号确认…</p>
      </>}
      {state==='expired'&&<p role="status">登录请求已过期，请重新获取。</p>}
      {error&&<p role="alert" style={{color:'#a03729',margin:'12px 0',lineHeight:1.7}}>{error}</p>}
      {state!=='loading'&&<button className="btn btn-ghost btn-sm" style={{marginTop:18}} onClick={()=>setRetry(n=>n+1)}>重新获取登录请求</button>}
    </div>
  </Modal></div>;
}
function ReaderProfile({onClose}) {
  const {logout}=useAuth();const [data,setData]=React.useState(null),[error,setError]=React.useState('');
  React.useEffect(()=>{let live=true;Promise.all([readerRequest('/api/reader/favorites'),readerRequest('/api/reader/enrollments')]).then(([f,e])=>{if(live)setData({favorites:f.items,enrollments:e.items});}).catch(e=>{if(live)setError(e.message);});return()=>{live=false;};},[]);
  const status={pending:'资格待审核',confirmed:'报名已确认',cancelled:'已取消',expired:'已过期',refunded:'已退款'};
  return <Modal onClose={onClose} max={640}><div className="modal-hd"><h3 style={{fontSize:26}}>我的记录</h3><button className="x-btn" onClick={onClose} aria-label="关闭">{Ico.close()}</button></div><div className="modal-bd">
    {error&&<p role="alert">{error}</p>}{!data&&!error&&<p>正在读取…</p>}{data&&<>
      <h4>文章收藏</h4>{!data.favorites.length?<p style={{margin:'12px 0 24px'}}>暂无收藏，可在文章页点击收藏。</p>:data.favorites.map(p=><button className="btn btn-quiet" style={{display:'block',textAlign:'left',margin:'8px 0'}} key={p.id} onClick={()=>{onClose();window.__go('post',p.id);}}>{p.title}</button>)}
      <h4 style={{marginTop:24}}>报名记录</h4><p style={{fontSize:12,color:'var(--txt-2)',margin:'8px 0'}}>显示登录后提交的报名。此前的报名请使用报名编号查询。</p>
      {!data.enrollments.length?<p>暂无关联的报名记录。</p>:data.enrollments.map(e=><div key={e.orderNo} style={{padding:'14px 0',borderBottom:'1px solid var(--line)'}}><strong>{e.title}</strong><p>{status[e.status]||e.status}</p><small style={{overflowWrap:'anywhere'}}>{e.orderNo}</small></div>)}
    </>}
    <button className="btn btn-ghost btn-sm" style={{marginTop:24}} onClick={()=>logout().catch(e=>setError(e.message))}>退出微信登录</button>
  </div></Modal>;
}

/* 页脚 / 文末的关注引导条 */
function FollowStrip({ compact }) {
  const { user, requireAuth } = useAuth();
  return (
    <>
      <div className="dark noise" style={{ borderRadius: compact ? 'var(--radius)' : 0, padding: compact ? '26px 24px' : 'clamp(30px,4vw,54px) clamp(24px,4vw,52px)' }}>
        <div style={{ display: 'flex', gap: 28, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <div style={{ maxWidth: 560 }}>
            <Eyebrow>{user ? '微信账号已登录' : '量子催眠中国公众号'}</Eyebrow>
            <h3 style={{ marginTop: 14, fontSize: compact ? 19 : 'clamp(21px,2.2vw,28px)', lineHeight: 1.36 }}>
              {user ? '收藏和报名，随时回来查看' : '关注公众号，新文章不必再来找'}
            </h3>
            <p style={{ marginTop: 10, fontSize: 13.5, color: 'var(--on-dark-2)', fontWeight: 300, lineHeight: 1.7 }}>
              {user ? '收藏与登录后提交的报名可在个人记录中查看。' : '关注公众号阅读新文章；登录官网后可保存收藏和查看报名。'}
            </p>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 74, height: 74, background: '#fff', borderRadius: 3, padding: 5, flex: 'none' }}>
              <QrCanvas ticket="FOLLOW01" />
            </div>
            {!user && <Btn kind="gold" size="sm" onClick={() => requireAuth('profile')}>微信登录</Btn>}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window,{AuthCtx,AuthProvider,useAuth,WechatLogin,FollowStrip});
