@markus-global/cli 0.7.10 → 0.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -655,7 +655,7 @@ l0,-`+(r+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
655
655
 
656
656
  `)}),lt.toolCalls?.length)for(let Mn=0;Mn<lt.toolCalls.length;Mn++){const pr=lt.toolCalls[Mn];xn.push({type:"tool",key:`${pr.tool}_${Mn}`,tool:pr.tool,status:pr.status==="error"?"error":"done",args:pr.arguments,result:pr.result,durationMs:pr.durationMs})}xn.length>0&&(xn.push({type:"text",content:We}),Rn.segments=xn)}let Wt;if(Le.startsWith("notes:"))Wt=`dm:${Le.slice(6)}`;else if(Le.startsWith("dm:")){const xn=Le.slice(3).split(":");Wt=`dm:${xn.find(pr=>pr!==(t?.id??""))??xn[0]??""}`}else Wt=`ch:${Le}`;wn(Wt,xn=>[...xn,Rn]),Wt===nt.current&&!sa.current&&(Dt.current+=1,hr(Dt.current),ot(!0)),xt==="agent"&&Wt===`ch:${fe}`&&Vt(xn=>{const Mn=xn.filter(pr=>pr.id!==Lt);return Mn.length===0&&mn.current&&(clearTimeout(mn.current),mn.current=null),Mn})}),[r,wn,t?.id,fe]),x.useEffect(()=>r?void 0:pn.on("chat:agent_no_response",Se=>{const he=Se.payload,Le=he.channel??"",xt=he.agentId??"";Le&&xt&&`ch:${fe}`==`ch:${Le}`&&Vt(We=>{const Lt=We.filter(Bt=>Bt.id!==xt);return Lt.length===0&&mn.current&&(clearTimeout(mn.current),mn.current=null),Lt})}),[r,fe]),x.useEffect(()=>r?void 0:pn.on("chat:proactive_message",Se=>{const he=Se.payload,Le=he.targetUserId;if(Le&&Le!==t?.id)return;const xt=he.agentId??"",We=he.agentName??a("page.fallbackAgent"),Lt=he.message??"";he.sessionId;const Bt=he.metadata??{};if(!xt||!Lt||Lt==="[cancelled]"||Lt==="[Stream cancelled]")return;const lt=!!Bt.activityLog||Lt.startsWith("[ACTIVITY:"),{cleaned:jt,priority:nn}=GS(Lt),Rn=!!Bt.notifyUser||jt!==Lt,Wt={id:`proactive_${Date.now()}`,sender:"agent",text:jt,time:new Date().toLocaleTimeString(),agentName:We,agentId:xt,...Rn?{isNotification:!0,notifyPriority:Bt.priority??nn}:{},...lt?{isActivityLog:!0,activityType:Bt.activityType,outcome:Bt.outcome,mailboxItemId:Bt.mailboxItemId,taskId:Bt.taskId,requirementId:Bt.requirementId}:{},...!lt&&Bt.taskId?{taskId:Bt.taskId}:{},...!lt&&Bt.requirementId?{requirementId:Bt.requirementId}:{}},xn=Cs("direct",xt,"","");wn(xn,Mn=>[...Mn,Wt])}),[r,wn,a]),cs.find(re=>re.id===ti),x.useEffect(()=>{Oa(null)},[be]);const oe=re=>BW(re),Ee=()=>{Ur.current?.abort(),Ur.current=null;const re=nt.current;gt.current.delete(re),Je.current.delete(re),In(!1),Ot([]),te==="direct"&&be&&le.agents.cancelProcessing(be).catch(()=>{})},et=async(re,Se)=>{const he=(re??Ve).trim();if(!he&&Fn.length===0||te==="direct"&&!be)return;if(sa.current=!0,ie.current=!1,sn){Ur.current?.abort(),Ur.current=null,te==="direct"&&be&&le.agents.cancelProcessing(be).catch(()=>{});const lt=nt.current;gt.current.delete(lt),Je.current.delete(lt),wn(lt,jt=>{const nn=[...jt];for(let Rn=nn.length-1;Rn>=0;Rn--)if(nn[Rn].sender==="agent"&&!nn[Rn].isStopped&&!nn[Rn].isError){const Wt=nn[Rn];if(!(Wt.text?.trim()||(Wt.segments??[]).some(Mn=>Mn.type==="text"&&(Mn.content||Mn.thinking)||Mn.type==="tool")))nn.splice(Rn,1);else{const Mn=(Wt.segments??[]).map(pr=>pr.type==="tool"&&pr.status==="running"?{...pr,status:"stopped"}:pr);nn[Rn]={...Wt,isStopped:!0,segments:Mn}}break}return nn}),In(!1),Ot([]),await new Promise(jt=>setTimeout(jt,50))}const Le=Fn.length>0?Fn.map(lt=>lt.dataUrl):void 0,xt=Fn.length>0?Fn.map(lt=>lt.name):void 0,We=Cs(te,be,fe,Ne),Lt=un;re||Rt(""),mr([]),Is(!1),yn(null);const Bt=te==="dm";if(gt.current.add(We),Je.current.set(We,[]),nt.current===We&&!Bt&&(In(!0),Ot([])),te==="dm"){const lt=Wn(t?.id??"",Ne),jt=`opt_${Date.now()}`,nn={id:jt,sender:"user",text:he,time:new Date().toLocaleTimeString()};Lt&&(nn.replyToId=Lt.id,nn.replyToSender=Lt.sender,nn.replyToText=Lt.text),wn(We,Rn=>[...Rn,nn]);try{const Rn=await le.channels.sendMessage(lt,{text:he,senderName:t?.name??a("page.fallbackYou"),senderId:t?.id,mentions:[],orgId:"default",humanOnly:!0});Rn.userMessage&&ze(Rn.userMessage.id),wn(We,Wt=>{const xn=Wt.filter(pr=>pr.id!==jt),Mn=[];return Rn.userMessage&&Mn.push(Yl(Rn.userMessage,t?.id)),Mn.length>0?[...xn,...Mn]:Wt})}catch(Rn){wn(We,Wt=>[...Wt,{id:`err_${Date.now()}`,sender:"agent",text:a("page.errorWithMessage",{message:String(Rn)}),time:new Date().toLocaleTimeString(),agentName:a("page.systemName"),isError:!0}])}gt.current.delete(We),nt.current===We&&In(!1)}else if(te==="channel"){const lt=`opt_${Date.now()}`,jt={id:lt,sender:"user",text:he,time:new Date().toLocaleTimeString()};Lt&&(jt.replyToId=Lt.id,jt.replyToSender=Lt.sender,jt.replyToText=Lt.text),wn(We,Wt=>[...Wt,jt]);const nn=oe(he),Rn=Mt.find(Wt=>Wt.channelKey===fe);if(fe.startsWith("group:")){const Wt=[];if(Rn?.members){for(const xn of Rn.members)if(xn.type==="agent"){const Mn=u.find(pr=>pr.id===xn.id);Mn&&Wt.push({id:Mn.id,name:Mn.name,avatarUrl:Mn.avatarUrl})}}Wt.length>0&&(mn.current&&clearTimeout(mn.current),Vt(Wt),mn.current=setTimeout(()=>Vt([]),12e4))}try{const Wt=await le.channels.sendMessage(fe,{text:he,senderName:t?.name??a("page.fallbackYou"),mentions:nn,senderId:t?.id,orgId:"default",replyToId:Lt?.id});Wt.userMessage&&ze(Wt.userMessage.id),Wt.agentMessage&&ze(Wt.agentMessage.id),wn(We,xn=>{const Mn=xn.filter(Qs=>Qs.id!==lt),pr=[];return Wt.userMessage&&pr.push(Yl(Wt.userMessage,t?.id)),Wt.agentMessage&&pr.push(Yl(Wt.agentMessage,t?.id)),pr.length>0?[...Mn,...pr]:xn})}catch(Wt){const xn=Vk(Wt,a)||a("page.errorWithMessage",{message:String(Wt)});wn(We,Mn=>[...Mn,{id:`err_${Date.now()}`,sender:"agent",text:xn,time:new Date().toLocaleTimeString(),agentName:a("page.systemName"),isError:!0}]),mn.current&&(clearTimeout(mn.current),mn.current=null),Vt([])}gt.current.delete(We),nt.current===We&&In(!1)}else{const lt=`a_${Date.now()}`;if(Se?.isResume){const Pt=new Date().toISOString();wn(We,Yt=>[...Yt,{id:lt,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:Pt,segments:[]}])}else{const Pt=new Date().toISOString(),Yt={id:`u_${Date.now()}`,sender:"user",text:he,time:new Date().toLocaleTimeString()};Le?.length&&(Yt.images=Le),Lt&&(Yt.replyToId=Lt.id,Yt.replyToSender=Lt.sender,Yt.replyToText=Lt.text),wn(We,$t=>[...$t,Yt,{id:lt,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:Pt,segments:[]}])}let jt=!1;const nn=Pt=>{_e.current=Date.now(),Os(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(za=>za.id===lt);if(Ct<0)return Yt;const _t=$t[Ct].segments??[],Kt=_t[_t.length-1],Qt=Kt?.type==="text"?Kt.thinking??"":"";let vn="",qn="",Gn=Pt;for(;Gn.length>0;)if(jt){const za=Gn.indexOf("</think>");za>=0?(vn+=Gn.slice(0,za),Gn=Gn.slice(za+8),jt=!1):(vn+=Gn,Gn="")}else{const za=Gn.indexOf("<think>");za>=0?(qn+=Gn.slice(0,za),Gn=Gn.slice(za+7),jt=!0):(qn+=Gn,Gn="")}const yi=Qt+vn||void 0,ia=Kt?.type==="text"?[..._t.slice(0,-1),{type:"text",content:Kt.content+qn,thinking:yi,createdAt:Kt.createdAt}]:[..._t,{type:"text",content:qn,thinking:yi,createdAt:new Date().toISOString()}];return $t[Ct]={...$t[Ct],text:$t[Ct].text+qn,segments:ia},$t})},Rn=Pt=>{if(_e.current=Date.now(),Pt.type==="session_start"&&Pt.sessionId){nt.current===We&&(qt(Pt.sessionId),br(Yt=>Yt.map($t=>$t.id===ir?{...$t,id:Pt.sessionId}:$t)));return}wn(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(Kt=>Kt.id===lt);if(Ct<0)return Yt;const _t=[...$t[Ct].committedSegments??[]];return Pt.type==="thinking_commit"?_t.push({type:"text",content:"",thinking:Pt.content,createdAt:Pt.createdAt}):_t.push({type:"text",content:Pt.content,createdAt:Pt.createdAt}),$t[Ct]={...$t[Ct],committedSegments:_t},$t})},Wt=Pt=>{_e.current=Date.now(),Pt.phase!=="heartbeat"&&((Pt.phase==="start"||Pt.phase==="end")&&Hs(We,{...Pt,phase:Pt.phase,ts:Date.now()}),Pt.phase==="start"?wn(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(Gn=>Gn.id===lt);if(Ct<0)return Yt;const _t=[...$t[Ct].segments??[]];let Kt=!1;if(Pt.arguments)for(let Gn=_t.length-1;Gn>=0;Gn--){const yi=_t[Gn];if(yi.type==="tool"&&yi.tool===Pt.tool&&yi.status==="running"){_t[Gn]={...yi,args:Pt.arguments},Kt=!0;break}}const Qt=`${Pt.tool}_${Date.now()}`,vn=new Date().toISOString();Kt||_t.push({type:"tool",key:Qt,tool:Pt.tool,status:"running",args:Pt.arguments,createdAt:vn});const qn=[...$t[Ct].committedSegments??[]];return Pt.arguments!==void 0&&qn.push({type:"tool",key:Qt,tool:Pt.tool,status:"running",args:Pt.arguments,createdAt:vn}),$t[Ct]={...$t[Ct],segments:_t,committedSegments:qn},$t}):Pt.phase==="output"?wn(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(Kt=>Kt.id===lt);if(Ct<0)return Yt;const _t=[...$t[Ct].segments??[]];for(let Kt=_t.length-1;Kt>=0;Kt--){const Qt=_t[Kt];if(Qt.type==="tool"&&Qt.tool===Pt.tool&&Qt.status==="running"){_t[Kt]={...Qt,liveOutput:(Qt.liveOutput??"")+(Pt.output??"")};break}}return $t[Ct]={...$t[Ct],segments:_t},$t}):Pt.phase==="subagent_progress"&&Pt.subagentEvent?wn(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(Kt=>Kt.id===lt);if(Ct<0)return Yt;const _t=[...$t[Ct].segments??[]];for(let Kt=_t.length-1;Kt>=0;Kt--){const Qt=_t[Kt];if(Qt.type==="tool"&&(Qt.tool==="spawn_subagent"||Qt.tool==="spawn_subagents")&&Qt.status==="running"){_t[Kt]={...Qt,subagentLogs:[...Qt.subagentLogs??[],Pt.subagentEvent]};break}}return $t[Ct]={...$t[Ct],segments:_t},$t}):wn(We,Yt=>{const $t=[...Yt],Ct=$t.findIndex(vn=>vn.id===lt);if(Ct<0)return Yt;const _t=new Date().toISOString(),Kt=[...$t[Ct].segments??[]];for(let vn=Kt.length-1;vn>=0;vn--){const qn=Kt[vn];if(qn.type==="tool"&&qn.tool===Pt.tool&&qn.status==="running"){Kt[vn]={...qn,status:Pt.success===!1?"error":"done",args:Pt.arguments,result:Pt.result,error:Pt.error,durationMs:Pt.durationMs,liveOutput:void 0,createdAt:_t};break}}const Qt=[...$t[Ct].committedSegments??[]];for(let vn=Qt.length-1;vn>=0;vn--){const qn=Qt[vn];if(qn.type==="tool"&&qn.tool===Pt.tool&&qn.status==="running"){Qt[vn]={...qn,status:Pt.success===!1?"error":"done",args:Pt.arguments,result:Pt.result,error:Pt.error,durationMs:Pt.durationMs,liveOutput:void 0,createdAt:_t};break}}return $t[Ct]={...$t[Ct],segments:Kt,committedSegments:Qt},$t}))},xn=new AbortController;Ur.current=xn;try{_e.current=Date.now();const Pt=It===ir?null:It,Yt=await le.agents.messageStream(be,he,nn,Wt,xn.signal,Le,Pt,Se?.isRetry,Se?.isResume,Rn,xt);nt.current===We&&(Yt.merged&&wn(We,$t=>$t.filter(Ct=>Ct.id!==lt)),!Yt.merged&&Yt.segments?.length&&wn(We,$t=>{const Ct=[...$t],_t=Ct.findIndex(vn=>vn.id===lt);if(_t<0)return $t;const Kt=Yt.segments.map((vn,qn)=>vn.type==="tool"?{type:"tool",key:`${vn.tool}_${qn}`,tool:vn.tool,status:vn.status,args:vn.arguments,result:vn.result,error:vn.error,durationMs:vn.durationMs,createdAt:vn.createdAt}:{type:"text",content:vn.content,thinking:vn.thinking,createdAt:vn.createdAt});let Qt=Yt.content||Ct[_t].text;return Qt||(Qt=Kt.filter(vn=>vn.type==="text").map(vn=>vn.content).join("")),Ct[_t]={...Ct[_t],text:Qt,segments:Kt,committedSegments:Kt},Ct}),!Yt.merged&&!Yt.segments?.length&&wn(We,$t=>{const Ct=[...$t],_t=Ct.findIndex(Gn=>Gn.id===lt);if(_t<0)return $t;const Kt=Ct[_t],Qt=Kt.committedSegments??[],qn=Qt.filter(Gn=>Gn.type==="text"&&!!Gn.content).map(Gn=>Gn.content).join("")||Yt.content||Kt.text;return(Qt.length>0||qn)&&(Ct[_t]={...Kt,text:qn,segments:Qt.length>0?Qt:Kt.segments}),Ct}),Yt.sessionId&&(qt(Yt.sessionId),br($t=>$t.map(Ct=>Ct.id===ir?{...Ct,id:Yt.sessionId}:Ct))),ms(be).then($t=>{if(nt.current===We&&(At($t),Yt.sessionId)){const Ct=$t.find(_t=>_t.id===Yt.sessionId);Ct&&br(_t=>_t.some(Qt=>Qt.id===Ct.id)?_t.map(Qt=>Qt.id===Ct.id?Ct:Qt):[Ct,..._t.filter(Qt=>Qt.id!==ir)])}}))}catch(Pt){const Yt=Pt?.sessionId;Yt&&te==="direct"&&nt.current===We&&(qt(Yt),br(Ct=>Ct.map(_t=>_t.id===ir?{..._t,id:Yt}:_t)),ms(be).then(Ct=>{if(nt.current!==We)return;At(Ct);const _t=Ct.find(Kt=>Kt.id===Yt);_t&&br(Kt=>Kt.some(vn=>vn.id===_t.id)?Kt.map(vn=>vn.id===_t.id?_t:vn):[_t,...Kt])}));const $t=Vk(Pt,a);$t?wn(We,Ct=>{const _t=[...Ct],Kt=_t.findIndex(Qt=>Qt.id===lt);if(Kt>=0){const Qt=_t[Kt].segments??[];_t[Kt]={..._t[Kt],text:$t,isError:!0,segments:[...Qt,{type:"text",content:$t}]}}return _t}):wn(We,Ct=>{const _t=[...Ct],Kt=_t.findIndex(Qt=>Qt.id===lt);if(Kt>=0){const Qt=_t[Kt];if(!(Qt.text||Qt.segments&&Qt.segments.length>0&&Qt.segments.some(qn=>qn.type==="text"&&(qn.content||qn.thinking)||qn.type==="tool")))return Ct.filter(qn=>qn.id!==lt);_t[Kt]={...Qt,isStopped:!0}}return _t})}wn(We,Pt=>{const Yt=[...Pt],$t=Yt.findIndex(Ct=>Ct.id===lt);if($t>=0){const Ct=(Yt[$t].segments??[]).map(_t=>_t.type==="tool"&&_t.status==="running"?{..._t,status:"stopped"}:_t);Yt[$t]={...Yt[$t],segments:Ct}}return Yt}),xn.signal.aborted&&wn(We,Pt=>{const Yt=[...Pt],$t=Yt.findIndex(Ct=>Ct.id===lt);if($t>=0){const Ct=Yt[$t];if(!(Ct.text||Ct.segments&&Ct.segments.length>0&&Ct.segments.some(Kt=>Kt.type==="text"&&(Kt.content||Kt.thinking)||Kt.type==="tool")))return Pt.filter(Kt=>Kt.id!==lt);Yt[$t]={...Ct,isStopped:!0}}return Yt});const pr=(Fe.current.get(We)??[]).find(Pt=>Pt.id===lt),Qs=It&&It!==ir?It:null,jc=pr?.text||pr?.segments?.some(Pt=>Pt.type==="text"&&Pt.content||Pt.type==="tool");pr&&!jc&&te==="direct"&&Qs&&!xn.signal.aborted&&await(async(Yt,$t)=>{for(let Ct=0;Ct<Yt;Ct++){await new Promise(_t=>setTimeout(_t,$t));try{const Kt=(await le.sessions.getMessages(Qs,2)).messages.find(Qt=>Qt.role==="assistant");if(Kt?.content){const Qt=Fx(Kt);wn(We,vn=>{const qn=[...vn],Gn=qn.findIndex(yi=>yi.id===lt);return Gn>=0&&(qn[Gn]={...qn[Gn],text:Qt.text,segments:Qt.segments}),qn});return}}catch{}}})(5,3e3),(Ur.current===xn||Ur.current===null)&&(Ur.current=null,gt.current.delete(We),Je.current.delete(We),nt.current===We&&(In(!1),Ot([])))}};ri.current=et;const[hn,Cn]=x.useState(null),[,zs]=x.useState(new Set),no=x.useMemo(()=>{for(let re=Et.length-1;re>=0;re--)if(Et[re]?.sender==="agent"&&!Et[re]?.isActivityLog)return Et[re].id;return null},[Et]),_0=x.useCallback(re=>{const Se=re.segments?re.segments.filter(he=>he.type==="text").map(he=>he.content).join(`
657
657
  `):re.text;navigator.clipboard.writeText(Se),Cn(re.id),setTimeout(()=>Cn(he=>he===re.id?null:he),2e3)},[]),z0=x.useCallback(re=>{const Se=nt.current,he=Fe.current.get(Se)??Et,Le=he.findIndex(lt=>lt.id===re.id);if(Le<0)return;let xt=null;for(let lt=Le-1;lt>=0;lt--)if(he[lt]?.sender==="user"){xt=he[lt];break}const We=xt?.text??"";if(!We)return;if(Le<he.length-1){const lt=he.length-1-Le;if(!window.confirm(lt===1?a("page.retryConfirmSingular"):a("page.retryConfirmPlural",{count:lt})))return}const Bt=xt&&Le>0&&he[Le-1]?.id===xt.id;wn(Se,lt=>{const jt=lt.findIndex(nn=>nn.id===(Bt?xt.id:re.id));return jt>=0?lt.slice(0,jt):lt}),et(We,{isRetry:!0})},[Et,wn,a]),$0=x.useCallback(re=>{const Se=nt.current;(Fe.current.get(Se)??Et).findIndex(xt=>xt.id===re.id)<0||(wn(Se,xt=>{const We=[...xt],Lt=We.findIndex(jt=>jt.id===re.id);if(Lt<0)return xt;const Bt=We[Lt],lt=[...Bt.segments??[]];for(;lt.length>0;){const jt=lt[lt.length-1];if(jt.type==="tool"&&(jt.status==="stopped"||jt.status==="running"))lt.pop();else if(jt.type==="text"&&!jt.content)lt.pop();else break}return We[Lt]={...Bt,segments:lt,isStopped:!1,isError:!1},We}),et("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0}))},[Et,wn]),$o=x.useCallback(re=>{const Se=re.sender==="user"?t?.name??a("page.fallbackYou"):re.agentName??a("page.fallbackAgent");if(yn({id:re.id,sender:Se,text:re.text.slice(0,120)}),te==="channel"&&re.sender==="agent"&&re.agentName){const he=`@${re.agentName} `;Rt(Le=>Le.startsWith(he)?Le:he+Le)}fr.current?.focus()},[t?.name,te,a]),vc=async re=>{qt(re.id),tn(!1),Tn(!1),Ht.current=null;const Se=nt.current;Fe.current.delete(Se),dt([]),br(he=>he.some(Le=>Le.id===re.id)?he:[...he,re]),await Kr(re.id,Se)},sp=re=>{if(br(Se=>Se.filter(he=>he.id!==re)),It===re){const Se=An.filter(he=>he.id!==re);Se.length>0?vc(Se[Se.length-1]):ro()}},B0=x.useCallback(async re=>{if(re.length<2){ur([]);return}ha(!0);try{const Se=te==="channel"?"channel":te==="direct"?"direct":"all",he=te==="channel"?fe:void 0,{results:Le}=await le.messages.search(re,{scope:Se,channel:he,limit:30});ur(Le)}catch{ur([])}ha(!1)},[te,fe]),H0=x.useCallback(re=>{cr(re),pa.current&&clearTimeout(pa.current),pa.current=setTimeout(()=>B0(re),300)},[B0]),F0=x.useCallback(re=>{lr(!1),cr(""),ur([]),re.source==="channel"&&re.channel?(de("channel"),$e(re.channel)):re.source==="direct"&&re.agentId&&(de("direct"),se(re.agentId)),setTimeout(()=>{const Se=document.getElementById(`msg-${re.id}`);Se&&(Se.scrollIntoView({behavior:"smooth",block:"center"}),Se.classList.add("bg-brand-500/10"),setTimeout(()=>Se.classList.remove("bg-brand-500/10"),2e3))},500)},[]),ro=()=>{qt(ir);const re=nt.current;Fe.current.delete(re),dt([]),Tn(!1),Ht.current=null,tn(!1),br(Se=>{const he=Se.filter(Le=>Le.id!==ir);return[{id:ir,agentId:be??"",userId:null,title:a("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...he]})},El=re=>{if(Rt(re),te!=="channel"){Is(!1);return}const Se=fr.current?.selectionStart??re.length,he=re.slice(0,Se),Le=he.lastIndexOf("@");if(Le>=0){const xt=Le===0?"":he[Le-1];if(Le===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(xt)){const Lt=he.slice(Le+1);if(!Lt.includes(" ")&&!Lt.includes(`
658
- `)){Is(!0),js(Lt.toLowerCase()),Ns(0);return}}}Is(!1)},q0=re=>{const Se=fr.current?.selectionStart??Ve.length,Le=Ve.slice(0,Se).lastIndexOf("@"),xt=Ve.slice(Se),We=re.includes(" ")?`@[${re}]`:`@${re}`,Lt=Ve.slice(0,Le)+We+" "+xt;Rt(Lt),Is(!1),Ns(0);const Bt=Le+We.length+1;requestAnimationFrame(()=>{fr.current?.setSelectionRange(Bt,Bt)})},wc=10*1024*1024,Bd=5,U0=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),Ii=x.useCallback(re=>re.type.startsWith("image/")||U0.has(re.type),[]),Ml=re=>re.dataUrl.startsWith("data:image/"),V0=(re,Se)=>{if(Ml({dataUrl:Se}))return null;const he=re.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[he]??"📁"},Bo=x.useCallback(re=>{const Se=Array.from(re).filter(Ii);if(Se.length!==0)for(const he of Se){if(he.size>wc)continue;const Le=new FileReader;Le.onload=()=>{const xt=Le.result;mr(We=>We.length>=Bd||We.some(Lt=>Lt.dataUrl===xt)?We:[...We,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:xt,name:he.name}])},Le.readAsDataURL(he)}},[Ii]),K0=x.useCallback(re=>{mr(Se=>Se.filter(he=>he.id!==re))},[]),ap=x.useCallback(re=>{const Se=re.clipboardData?.files;if(Se&&Se.length>0){const he=Array.from(Se).filter(Ii);he.length>0&&(re.preventDefault(),Bo(he))}},[Bo,Ii]),ip=x.useCallback(re=>{re.preventDefault();const Se=re.dataTransfer?.files;Se&&Se.length>0&&Bo(Array.from(Se).filter(Ii))},[Bo,Ii]),op=x.useCallback(re=>{re.preventDefault()},[]),Jr=u.find(re=>re.id===be),Hd=t?.name??a("page.fallbackYou"),Xs=cn[cn.length-1],Dl=sn&&Xs?.sender==="agent",W0=Vn&&Xs?.sender==="agent",Fd=x.useMemo(()=>{if(te!=="channel")return null;if(fe.startsWith("group:custom:")){const Se=Mt.find(he=>he.channelKey===fe);return Se?.members?new Set(Se.members.filter(he=>he.type==="agent").map(he=>he.id)):null}if(!vr)return null;const re=Or.find(Se=>Se.id===vr);return re?new Set(re.members.filter(Se=>Se.type==="agent").map(Se=>Se.id)):null},[te,fe,vr,Or,Mt]),Li=u.filter(re=>Fd?Fd.has(re.id):!0).filter(re=>re.name.toLowerCase().includes(Kn)),kc=h.find(re=>re.id===Ne),Rl=Ne===t?.id||!Ne,aa=Mt.find(re=>re.channelKey===fe);x.useEffect(()=>{if(r||!fe.startsWith("group:custom:"))return;const re=Mt.find(Se=>Se.channelKey===fe);!re||re.members||le.groupChats.getById(re.id).then(Se=>{Se.chat.members&&Ln(he=>he.map(Le=>Le.id===re.id?{...Le,members:Se.chat.members}:Le))}).catch(()=>{})},[r,fe,Mt]);const so=te==="channel"?aa?.name??fe:te==="direct"?Jr?.name??a("page.selectAgent"):te==="dm"?Rl?a("chat.myNotes"):kc?.name??a("page.directMessage"):a("page.chatTitle"),qd=te==="channel"?aa?a("page.placeholder.channel",{name:aa.name}):a("page.placeholder.channelWithMention",{name:fe}):te==="dm"?Rl?a("page.placeholder.dmSelf"):a("page.placeholder.dmOther",{name:kc?.name??""}):a(be?"page.placeholder.direct":"page.placeholder.noAgent"),Il=v&&N==="chat";return n.jsxs("div",{ref:L,className:"flex-1 overflow-hidden flex relative",children:[n.jsx(KW,{authUser:t,agents:u,teams:Or,humans:h,tasks:cs,externalAgents:ga,groupChats:Mt,chatMode:te,selectedAgent:be,activeChannel:fe,activeDmUserId:Ne,previewMode:r,onSelectAgent:re=>{de("direct"),se(re),$("chat"),Pn(!1),v&&M()},onSelectChannel:re=>{de("channel"),$e(re),$("chat"),Pn(!1),v&&M()},onSelectDm:re=>{de("dm"),Ze(re),$("chat"),Pn(!1),v&&M()},onSelectTeam:re=>{const Se=Mt.find(he=>he.type==="team"&&he.teamId===re);v?D(re):Se&&(de("channel"),$e(Se.channelKey),$("chat"),Pn(!1),!U&&!z&&W(!0))},selectedTeamId:vr??(te==="direct"&&Jr?.teamId?Jr.teamId:null),onRefreshTeams:_s,onRefreshAgents:Zr,onRefreshHumans:ja,onRefreshGroupChats:va,onViewProfile:st,onManageGroupMembers:re=>{de("channel"),$e(re),$("chat"),Pn(!0),v&&M()},unreadByAgent:ya,unreadByChannel:$r,width:v?void 0:R.width,onResizeStart:v?void 0:R.onResizeStart,hidden:v&&N!=="roster",initialLoading:y}),v&&N==="team"&&S&&(()=>{const re=Or.find(Le=>Le.id===S);if(!re)return null;const Se=u.filter(Le=>Le.teamId===S),he=Mt.find(Le=>Le.type==="team"&&Le.teamId===S);return n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[n.jsx("button",{onClick:()=>{window.location.hash=Te.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:re.name}),n.jsx("p",{className:"text-[10px] text-fg-tertiary",children:a("chat.members_other",{count:re.members?.length||Se.length})})]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[he&&(()=>{const Le=$r[he.channelKey]??0;return n.jsxs("button",{onClick:()=>{de("channel"),$e(he.channelKey),$("chat"),M()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[n.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:he.name}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:a("chat.groupChat")})]}),Le>0?n.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:Le}):n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),Se.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:a("chat.agents")}),Se.map(Le=>{const xt=ya.get(Le.id)??0;return n.jsxs("button",{onClick:()=>{de("direct"),se(Le.id),$("chat"),M()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[n.jsx(Sr,{name:Le.name||"Agent",avatarUrl:Le.avatarUrl,size:36}),n.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:Le.name}),n.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:Le.role||Le.status})]}),xt>0?n.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:xt}):n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Le.status==="active"||Le.status==="idle"?"bg-green-500":Le.status==="working"||Le.status==="busy"?"bg-blue-500":Le.status==="paused"?"bg-amber-500":"bg-gray-400"}`})]},Le.id)})]})]})]})})(),U&&!z&&!v&&(()=>{const re=vr??(te==="direct"?Jr?.teamId:void 0);if(!re)return null;const Se=Or.find(Le=>Le.id===re);if(!Se)return null;const he=Mt.find(Le=>Le.type==="team"&&Le.teamId===re);return n.jsx(gk,{team:Se,agents:u,humans:h,authUser:t,groupChat:he,chatMode:te,selectedAgent:be,activeChannel:fe,teams:Or,onSelectAgent:Le=>{de("direct"),se(Le),$("chat"),Pn(!1)},onSelectChannel:Le=>{de("channel"),$e(Le),$("chat"),Pn(!1)},onSelectDm:Le=>{de("dm"),Ze(Le),$("chat"),Pn(!1)},onBack:()=>W(!1),onViewProfile:st,onRefreshAgents:Zr,onRefreshTeams:_s,unreadByAgent:ya,width:F.width,onResizeStart:F.onResizeStart})})(),_&&!v&&(()=>{const re=vr??(te==="direct"?Jr?.teamId:void 0);if(!re)return null;const Se=Or.find(Le=>Le.id===re);if(!Se)return null;const he=Mt.find(Le=>Le.type==="team"&&Le.teamId===re);return n.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:R.width+6},children:[n.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>G(!1)}),n.jsx("div",{className:"relative h-full",style:{width:F.width+8},children:n.jsx(gk,{team:Se,agents:u,humans:h,authUser:t,groupChat:he,chatMode:te,selectedAgent:be,activeChannel:fe,teams:Or,onSelectAgent:Le=>{de("direct"),se(Le),$("chat"),Pn(!1),G(!1)},onSelectChannel:Le=>{de("channel"),$e(Le),$("chat"),Pn(!1),G(!1)},onSelectDm:Le=>{de("dm"),Ze(Le),$("chat"),Pn(!1),G(!1)},onBack:()=>G(!1),onViewProfile:Le=>{st(Le),G(!1)},onRefreshAgents:Zr,onRefreshTeams:_s,unreadByAgent:ya,width:F.width})})]})})(),(!v||Il)&&n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v?"min-w-0":"min-w-[400px]"}`,children:[n.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[n.jsx("button",{onClick:()=>{window.location.hash=T.current},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsx("span",{className:"font-semibold text-sm truncate min-w-0 flex-1",children:so}),te==="direct"&&Jr&&n.jsx(Gk,{agent:Jr,tasks:cs,onViewProfile:st})]}),n.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[n.jsx("button",{onClick:()=>{jo(I)?history.back():$("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${I==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:a("page.chatTitle")}),n.jsx("button",{onClick:()=>{jo(I)||Ce()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${jo(I)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:a(te==="channel"?"page.teamTab":"page.profileTab")}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:()=>{lr(!on),on||(cr(""),ur([]))},className:`p-1 rounded-md transition-colors shrink-0 ${on?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),te==="channel"&&aa?.type==="custom"&&n.jsxs("button",{onClick:()=>Pn(!Jn),className:`text-[11px] px-2 py-1 rounded-md font-medium shrink-0 flex items-center gap-1 ${Jn?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),aa.members?.length??aa.memberCount??0]}),te==="direct"&&!jo(I)&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:ro,className:"text-[11px] text-brand-500 px-2 py-1 rounded-md bg-brand-500/10 font-medium shrink-0",children:a("page.newChatPlus")}),n.jsx("button",{ref:at,onClick:()=>tn(!Jt),className:`p-1 rounded-md transition-colors shrink-0 ${Jt?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,title:a("page.historyTitle"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}):(()=>{const re=vr?Or.find(jt=>jt.id===vr):void 0,Se=te==="direct"&&be?DG:te==="channel"&&vr?RG:["chat"],he=async()=>{const jt=Q.trim();if(!jt){ae(!1);return}try{te==="direct"&&be?(await le.agents.updateConfig(be,{name:jt}),Zr()):te==="channel"&&vr&&(await le.teams.update(vr,{name:jt}),_s())}catch{}ae(!1)},Le=async()=>{try{te==="direct"&&be?(await le.agents.updateConfig(be,{roleDescription:He}),Zr()):te==="channel"&&vr&&(await le.teams.update(vr,{description:He}),_s())}catch{}Me(!1)},xt=te==="direct"?Jr?.name:te==="channel"?re?.name??aa?.name:kc?.name??"",We=te==="direct"?Jr?.role||"":te==="channel"&&re?.description||"",Lt=te==="direct"?Jr?.avatarUrl:void 0,Bt=xt||"U",lt=te==="direct"&&be||te==="channel"&&vr;return n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("div",{className:"flex items-center px-4 h-14 gap-2.5",children:[(!U||z)&&(te==="channel"&&vr||te==="direct"&&Jr?.teamId)&&n.jsx("button",{onClick:V,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${_?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),n.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),lt&&(te==="channel"&&vr?n.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):n.jsx(Sr,{name:Bt,avatarUrl:Lt,size:36,className:"rounded-xl shrink-0"})),lt?n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[ee?n.jsx("input",{ref:xe,value:Q,onChange:jt=>me(jt.target.value),onBlur:he,onKeyDown:jt=>{jt.key==="Enter"&&he(),jt.key==="Escape"&&ae(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):n.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{me(xt??""),ae(!0)},title:"Click to edit name",children:xt}),te==="direct"&&Jr&&n.jsx(Gk,{agent:Jr,tasks:cs,onViewProfile:st})]}),(te==="direct"||te==="channel"&&vr)&&(Ae?n.jsx("input",{ref:Pe,value:He,onChange:jt=>je(jt.target.value),onBlur:Le,onKeyDown:jt=>{jt.key==="Enter"&&Le(),jt.key==="Escape"&&Me(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add description...",autoFocus:!0}):n.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{je(We),Me(!0)},title:"Click to edit description",children:We||"No description"}))]}):n.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[n.jsx("span",{className:"font-semibold text-sm truncate",children:so}),te==="dm"&&n.jsx("span",{className:"text-xs text-fg-tertiary",children:Rl?a("page.privateNotepad"):""})]}),n.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[n.jsx("button",{onClick:()=>{lr(!on),on||(cr(""),ur([]))},className:`p-1.5 rounded-md transition-colors ${on?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:a("page.searchMessages"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),te==="channel"&&aa?.type==="custom"&&n.jsxs("button",{onClick:()=>Pn(!Jn),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${Jn?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),aa.members?.length??aa.memberCount??0]}),te==="direct"&&Jr&&I==="chat"&&n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{onClick:ro,className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:a("page.newChatButton")}),n.jsx("button",{ref:at,onClick:()=>tn(!Jt),className:`p-1.5 rounded-md transition-colors ${Jt?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:a("page.historyTitle"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}),Se.length>1&&n.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:Se.map(jt=>n.jsxs("button",{onClick:()=>$(jt),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${I===jt?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[n.jsx("span",{children:LG(jt)}),IG(jt,a)]},jt))})]})})(),on&&n.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/50 px-4 py-2 space-y-2 animate-in slide-in-from-top-2 duration-200",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),n.jsx("input",{autoFocus:!0,value:qr,onChange:re=>H0(re.target.value),onKeyDown:re=>{re.key==="Escape"&&(lr(!1),cr(""),ur([]))},placeholder:a("page.searchPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),n.jsx("button",{onClick:()=>{lr(!1),cr(""),ur([])},className:"text-fg-tertiary hover:text-fg-secondary text-xs px-1",children:"✕"})]}),Rs&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary py-1",children:[n.jsxs("svg",{className:"animate-spin h-3 w-3",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a("page.searching")]}),!Rs&&qr.length>=2&&yr.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:a("page.noSearchResults")}),yr.length>0&&n.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:yr.map(re=>n.jsxs("button",{onClick:()=>F0(re),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-surface-elevated transition-colors group",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-tertiary mb-0.5",children:[n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${re.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:re.source==="channel"?"#":"1:1"}),re.senderName&&n.jsx("span",{children:re.senderName}),n.jsx("span",{children:new Date(re.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),n.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 group-hover:text-fg-primary transition-colors",children:re.text.length>200?re.text.slice(0,200)+"…":re.text})]},re.id))})]}),te==="direct"&&be&&I==="chat"&&An.length>1&&n.jsx("div",{className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:An.map(re=>n.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${re.id===It?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(re.id===ir){qt(ir);const Se=nt.current;Fe.current.delete(Se),dt([])}else vc(re)},children:[re.isMain&&n.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),n.jsx("span",{className:"truncate",children:re.id===ir?a("page.newChat"):re.isMain?a("page.sessionMain"):re.title||a("page.sessionConversation")}),!re.isMain&&n.jsx("button",{onClick:Se=>{Se.stopPropagation(),sp(re.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},re.id))}),te==="channel"&&aa?.type==="custom"&&Jn&&(()=>{const re=aa,Se=re.members??[],he=[];for(const Le of u)Se.some(xt=>xt.id===Le.id)||he.push({id:Le.id,name:Le.name,type:"agent",subtitle:Le.role||"Agent"});for(const Le of h)Se.some(xt=>xt.id===Le.id)||he.push({id:Le.id,name:Le.name,type:"human",subtitle:Le.email||Le.role||""});return n.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[a("page.members")," (",Se.length,")"]}),n.jsx("button",{onClick:()=>Pn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:Se.map(Le=>n.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${Le.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[n.jsx(Sr,{name:Le.name,size:16,bgClass:Le.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),Le.name,Le.id!==t?.id&&n.jsx("button",{onClick:async()=>{try{await le.groupChats.removeMember(re.id,Le.id),Ln(xt=>xt.map(We=>We.id===re.id?{...We,members:(We.members??[]).filter(Lt=>Lt.id!==Le.id),memberCount:(We.memberCount??1)-1}:We))}catch{}},className:"ml-0.5 hover:text-red-500 transition-colors",title:a("common:remove"),children:n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},Le.id))}),he.length>0&&n.jsx("div",{className:"mt-1",children:n.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:async Le=>{const xt=Le.target.value;if(!xt)return;const We=he.find(Lt=>Lt.id===xt);if(We)try{await le.groupChats.addMember(re.id,We.id,We.type,We.name),Ln(Lt=>Lt.map(Bt=>Bt.id===re.id?{...Bt,members:[...Bt.members??[],{id:We.id,name:We.name,type:We.type}],memberCount:(Bt.memberCount??0)+1}:Bt))}catch{}},children:[n.jsx("option",{value:"",children:a("page.addMemberPlaceholder")}),he.map(Le=>n.jsxs("option",{value:Le.id,children:["[",Le.type==="agent"?"Agent":"Human","] ",Le.name]},Le.id))]})})]})})(),te==="direct"&&be&&Jt&&n.jsxs("div",{ref:yt,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[n.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:a("page.historyTitle")}),n.jsx("button",{onClick:()=>tn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[Ie.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:a("page.noConversationsYet")}),(()=>{const re=new Date,Se=new Date(re.getFullYear(),re.getMonth(),re.getDate()).getTime(),he=Se-864e5,Le=Se-7*864e5,xt=[],We=[],Lt=[],Bt=[],lt=[];for(const jt of Ie){const nn=new Date(jt.lastMessageAt).getTime();nn>=Se?We.push(jt):nn>=he?Lt.push(jt):nn>=Le?Bt.push(jt):lt.push(jt)}return We.length>0&&xt.push({label:a("page.dateToday"),items:We}),Lt.length>0&&xt.push({label:a("page.dateYesterday"),items:Lt}),Bt.length>0&&xt.push({label:a("page.datePrevious7Days"),items:Bt}),lt.length>0&&xt.push({label:a("page.dateOlder"),items:lt}),xt.map(jt=>n.jsxs("div",{className:"mb-2",children:[n.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:jt.label}),jt.items.map(nn=>n.jsxs("button",{onClick:()=>{vc(nn)},className:`w-full text-left px-3 py-2.5 rounded-lg text-xs mb-0.5 transition-colors ${nn.id===It?"bg-brand-600/20 text-brand-500":"text-fg-secondary hover:bg-surface-elevated"}`,children:[n.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[nn.isMain&&n.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),nn.isMain?a("page.sessionMain"):nn.title||a("page.sessionConversation")]}),n.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(nn.lastMessageAt).toLocaleString()})]},nn.id))]},jt.label))})()]})]})]}),v&&I==="profile"&&te==="direct"&&be&&n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Sk,{agentId:be,onBack:()=>$("chat"),inline:!0,defaultTab:J,highlightMailboxId:Z,onSwipeBack:()=>{jo(B.current)?history.back():$("chat")},authUser:t})}),v&&I==="profile"&&te==="channel"&&vr&&n.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:v?ct.onTouchStart:void 0,onTouchEnd:v?ct.onTouchEnd:void 0,children:n.jsx(Hk,{teamId:vr,onBack:()=>$("chat"),inline:!0,onSelectAgent:re=>{de("direct"),se(re),Ce()}})}),!v&&jo(I)&&te==="direct"&&be&&n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Sk,{agentId:be,onBack:()=>$("chat"),inline:!0,headless:!0,activeTab:I,highlightMailboxId:Z,authUser:t})}),!v&&jo(I)&&te==="channel"&&vr&&n.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:n.jsx(Hk,{teamId:vr,onBack:()=>$("chat"),inline:!0,headless:!0,activeTab:I,onSelectAgent:re=>{de("direct"),se(re),$("overview"),!U&&!z&&W(!0)}})}),n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${I!=="chat"?"hidden":""}`,children:[_n&&n.jsxs("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center items-center gap-2 py-2 bg-gradient-to-b from-surface-primary/90 to-transparent pointer-events-none",children:[n.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:a("page.loadingEarlierMessages")})]}),n.jsxs("div",{ref:as,className:`flex-1 overflow-y-auto ${v?"p-2.5":"p-5 2xl:pr-[280px]"}`,onScroll:to,onTouchStart:v?ct.onTouchStart:void 0,onTouchEnd:v?ct.onTouchEnd:void 0,children:[cn.length===0&&!sn&&n.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-fg-tertiary text-sm space-y-2",children:[n.jsx("div",{className:"opacity-40",children:n.jsx("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:te==="channel"?n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H6l-4 4V6c0-1.1.9-2 2-2z"}),n.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),n.jsx("line",{x1:"8",y1:"14",x2:"13",y2:"14"})]}):n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),te==="channel"&&n.jsx("div",{children:a("page.emptyChannel",{name:aa?.name??fe})}),te==="direct"&&!be&&n.jsx("div",{children:a("page.emptySelectAgent")}),te==="direct"&&be&&n.jsx("div",{children:a("page.emptyNewConversation",{name:Jr?.name??""})})]}),cn.length>0&&n.jsx("div",{style:{height:bt.getTotalSize(),width:"100%",position:"relative"},children:bt.getVirtualItems().map(re=>{const Se=re.index,he=cn[Se],Le=Se>0?cn[Se-1]:null,xt=qk(he.rawCreatedAt),We=Le?qk(Le.rawCreatedAt):"",Lt=xt&&xt!==We,Bt=Se===cn.length-1,jt=Dl&&Bt&&sn,nn=W0&&Bt||jt,Rn=te==="channel"||!jt||he.isStopped;return n.jsx("div",{"data-index":Se,ref:bt.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${re.start}px)`},children:n.jsxs("div",{className:"pb-3",children:[Lt&&n.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[n.jsx("div",{className:"flex-1 h-px bg-border-default"}),n.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:jG(he.rawCreatedAt,l)}),n.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),n.jsxs("div",{id:`msg-${he.id}`,className:"group/msg flex gap-3 transition-colors rounded-lg",children:[te==="channel"?n.jsx("div",{className:"shrink-0 cursor-pointer",onClick:Wt=>{if(he.sender==="agent"&&he.agentId){const xn=Wt.currentTarget.getBoundingClientRect();q({agentId:he.agentId,top:xn.top,left:xn.right+8})}},children:n.jsx(Sr,{name:he.sender==="user"?Hd:he.agentName??a("page.fallbackAgent"),avatarUrl:he.sender==="user"?t?.avatarUrl:u.find(Wt=>Wt.id===he.agentId)?.avatarUrl,size:32,bgClass:he.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:he.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):n.jsx("div",{className:"shrink-0",children:n.jsx(Sr,{name:he.sender==="user"?Hd:he.agentName??(te==="direct"?Jr?.name??a("page.fallbackAgent"):a("page.fallbackAgent")),avatarUrl:he.sender==="user"?t?.avatarUrl:u.find(Wt=>Wt.id===(he.agentId??(te==="direct"?Jr?.id:void 0)))?.avatarUrl,size:32,bgClass:he.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:he.sender==="user"?Hd:te==="channel"?he.agentName??a("page.fallbackAgent"):n.jsx(TG,{name:he.agentName??(te==="direct"?Jr?.name??a("page.fallbackAgent"):a("page.fallbackAgent")),agentId:he.agentId??(te==="direct"?Jr?.id:void 0),agents:u,onViewProfile:st})}),n.jsx("span",{className:"text-xs text-fg-tertiary",title:he.rawCreatedAt?new Date(he.rawCreatedAt).toLocaleString():"",children:kG(he.time,he.rawCreatedAt,l)})]}),he.replyToId&&he.replyToSender&&n.jsxs("button",{onClick:()=>{const Wt=document.getElementById(`msg-${he.replyToId}`);Wt&&(Wt.scrollIntoView({behavior:"smooth",block:"center"}),Wt.classList.add("bg-brand-500/10"),setTimeout(()=>Wt.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[n.jsx("span",{className:"font-medium text-brand-500",children:he.replyToSender}),n.jsx("span",{className:"truncate max-w-[250px]",children:he.replyToText??"..."})]}),n.jsxs("div",{className:`mt-0.5 ${he.sender==="agent"?"bg-surface-chat-bubble rounded-2xl px-3.5 py-2.5":""} ${he.isError||he.sender==="agent"&&he.text.startsWith("⚠")?"border-b-2 border-red-500/60":""} ${nn&&he.sender==="agent"?"streaming-bubble":""}`,children:[he.sender==="user"?n.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[he.images&&he.images.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:he.images.map((Wt,xn)=>n.jsx("img",{src:Wt,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(Wt,"_blank")},xn))}),te==="channel"?pk(he.text,u,(Wt,xn)=>{const Mn=xn.currentTarget.getBoundingClientRect();q({agentId:Wt.id,top:Mn.bottom,left:Mn.left})}):he.text&&n.jsx("span",{className:"leading-relaxed",children:pk(he.text,u,(Wt,xn)=>{const Mn=xn.currentTarget.getBoundingClientRect();q({agentId:Wt.id,top:Mn.bottom,left:Mn.left})})})]}):he.sender==="agent"&&te==="channel"&&!(he.segments&&he.segments.length>0)?n.jsx(Gr,{content:he.text,className:"text-sm text-fg-secondary",onMentionClick:zt,knownNames:mt}):n.jsx(MG,{msg:he,isStreaming:jt,liveActivities:jt?Tt:[],onViewModeChange:Wt=>zs(xn=>{const Mn=new Set(xn);return Wt==="full"?Mn.add(he.id):Mn.delete(he.id),Mn}),onMentionClick:zt,knownNames:mt}),he.isNotification&&n.jsx(CG,{priority:he.notifyPriority})]}),Rn&&!r&&n.jsx("div",{className:`transition-opacity ${he.isStopped||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:n.jsx(EG,{msg:he,onCopy:_0,onRetry:z0,onResume:$0,onReply:$o,isCopied:hn===he.id,isLastAgentMsg:he.id===no})})]})]})]})},he.id)})}),te==="channel"&&jn.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:jn.map(re=>n.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors group/think",onClick:()=>st(re.id,{tab:"overview"}),children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:re.name,avatarUrl:re.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"text-sm font-medium text-fg-secondary truncate",children:re.name}),n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:a("page.agentThinking")})]}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary opacity-0 group-hover/think:opacity-100 transition-opacity",children:"→"})]},re.id))}),n.jsx("div",{ref:Ls})]}),Xe&&I==="chat"&&n.jsxs("button",{onClick:()=>{ds("smooth"),sa.current=!0,ie.current=!1,ot(!1),Dt.current=0,hr(0)},className:`absolute ${v?"bottom-4":"bottom-20"} left-1/2 -translate-x-1/2 z-10 flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/95 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary`,children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})}),fn>0?a("page.newMessages",{count:fn}):a("page.scrollToBottom")]})]}),O&&(()=>{const re=u.find(Se=>Se.id===O.agentId);return re?n.jsx(AG,{agent:re,anchorRect:{top:O.top,left:O.left},onClose:()=>q(null),onViewProfile:st}):null})(),n.jsx("div",{className:`${v?"px-3 py-2":"px-5 py-3 2xl:pr-[280px]"} relative shrink-0 ${I!=="chat"?"hidden":""}`,onDrop:ip,onDragOver:op,children:n.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/5 ${v?"rounded-2xl p-3":"rounded-2xl p-3 max-w-3xl"}`,children:[xa&&Li.length>0&&n.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-48 overflow-y-auto",children:[n.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:a("page.mentionAgent")}),Li.map((re,Se)=>n.jsxs("button",{ref:he=>{Se===ba&&he&&he.scrollIntoView({block:"nearest"})},onClick:()=>q0(re.name),onMouseEnter:()=>Ns(Se),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Se===ba?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[n.jsx(Sr,{name:re.name,avatarUrl:re.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),n.jsx("span",{className:"flex-1 min-w-0",children:re.name}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:re.role})]},re.id))]}),Fn.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Fn.map(re=>n.jsxs("div",{className:"relative group/img shrink-0",children:[Ml(re)?n.jsx("img",{src:re.dataUrl,alt:re.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):n.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:re.name,children:[n.jsx("span",{className:"text-xl leading-none",children:V0(re.name,re.dataUrl)}),n.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:re.name.split(".").pop()?.toUpperCase()})]}),n.jsx("button",{onClick:()=>K0(re.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},re.id)),Fn.length<Bd&&n.jsx("button",{onClick:()=>rr.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:a("page.addMoreFiles"),children:n.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),Fn.length>0&&Fn.some(re=>Ml(re))&&Jr&&Jr.modelSupportsVision===!1&&n.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[n.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),a("page.visionWarning")]}),n.jsx("input",{ref:rr,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:re=>{re.target.files&&Bo(re.target.files),re.target.value=""}}),un&&n.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[n.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[n.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:un.sender}),n.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:un.text})]}),n.jsx("button",{onClick:()=>yn(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:"flex gap-2 items-end",children:[n.jsx("button",{onClick:()=>rr.current?.click(),disabled:te==="direct"&&!be,className:"px-2.5 py-2.5 text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated",title:a("page.attachFilesTitle"),children:n.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsx("textarea",{ref:fr,value:Ve,onChange:re=>{El(re.target.value),Qn()},onKeyDown:re=>{if(xa&&Li.length>0){const Se=re.key==="ArrowUp"||re.ctrlKey&&re.key==="p",he=re.key==="ArrowDown"||re.ctrlKey&&re.key==="n",Le=re.key==="Enter"||re.key==="Tab",xt=re.key==="Escape";if(Se){re.preventDefault(),Ns(We=>(We-1+Li.length)%Li.length);return}if(he){re.preventDefault(),Ns(We=>(We+1)%Li.length);return}if(Le){re.preventDefault();const We=Li[ba];We&&q0(We.name);return}if(xt){re.preventDefault(),Is(!1);return}}re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),et())},onPaste:ap,placeholder:qd,disabled:te==="direct"&&!be,rows:2,className:"flex-1 px-4 py-3 bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-hidden leading-relaxed placeholder:text-fg-tertiary/60",style:{minHeight:"52px",maxHeight:"120px"}}),sn&&te!=="dm"&&n.jsx("button",{onClick:Ee,className:"px-3 py-2.5 bg-red-600 hover:bg-red-500 text-white text-sm rounded-xl transition-colors flex items-center gap-1.5",title:a("page.stopAgent"),children:n.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}),n.jsx("button",{onClick:()=>{et()},disabled:te==="direct"&&!be||!Ve.trim()&&Fn.length===0,className:"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a("common:send")})]})]})})]})]})}function Gk({agent:e,tasks:t,onViewProfile:r}){const{t:s}=ft(["team","common"]),[a,i]=x.useState(!1),l=x.useRef(null),d=x.useRef(null),u=e.status==="working",m=e.status==="error",h=!m&&!!e.lastError&&!!e.lastErrorAt&&Date.now()-new Date(e.lastErrorAt).getTime()<1800*1e3,p=u?t.find(C=>C.assignedAgentId===e.id&&C.status==="in_progress"):null,y=e.currentActivity;x.useEffect(()=>{if(!a)return;const C=w=>{l.current&&!l.current.contains(w.target)&&i(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[a]),x.useLayoutEffect(()=>{if(!a||!d.current)return;const C=d.current,w=C.getBoundingClientRect(),N=window.innerWidth;w.right>N-8&&(C.style.left="auto",C.style.right="0"),w.left<8&&(C.style.left="0",C.style.right="auto");const S=N-16;w.width>S&&(C.style.width=`${S}px`)},[a]);const g=m?"bg-red-400 animate-pulse":h?"bg-amber-400":u?"bg-blue-400 animate-pulse":"bg-green-400",v=s(m?"common:status.error":u?"common:status.working":"common:status.idle"),j=y?y.type==="heartbeat"?s("page.activityHeartbeat",{name:y.heartbeatName??y.label}):y.type==="chat"?y.label:y.type==="task"?s("page.activityTask",{label:y.label}):y.label:s("page.processing");return n.jsxs("div",{className:"relative",ref:l,children:[n.jsxs("button",{onClick:()=>i(C=>!C),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors ${u&&!h?"bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20":m?"bg-red-500/10 border border-red-500/20 hover:bg-red-500/20":h?"bg-amber-500/10 border border-amber-500/20 hover:bg-amber-500/20":"bg-green-500/10 border border-green-500/20 hover:bg-green-500/20"}`,children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${g}`}),n.jsx("span",{className:`text-xs ${m?"text-red-500":h?"text-amber-600":u?"text-blue-500":"text-green-600"}`,children:v}),h&&n.jsx("span",{className:"text-[9px] text-amber-500",children:"⚠"}),e.mailboxDepth!=null&&e.mailboxDepth>0&&n.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:e.mailboxDepth})]}),a&&m&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:s("page.errorDetails")}),n.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[n.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:e.lastError||s("page.agentErrorFallback")}),e.lastErrorAt&&n.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(e.lastErrorAt).toLocaleString()})]}),n.jsx("button",{onClick:()=>{i(!1),r?.(e.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:s("page.viewAgentProfileArrow")})]}),a&&h&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-amber-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-amber-600 uppercase font-semibold",children:s("page.recentErrorDetails")}),n.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-lg p-2.5",children:[n.jsx("pre",{className:"text-[10px] text-amber-600/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:e.lastError}),e.lastErrorAt&&n.jsx("div",{className:"text-[9px] text-amber-500/50 mt-1.5 border-t border-amber-500/10 pt-1",children:new Date(e.lastErrorAt).toLocaleString()})]}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:s("page.errorRecovered")})]}),a&&u&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:s("page.currentActivity")}),p?n.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{i(!1),pt.navigate(Te.WORK,{openTask:p.id})},children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-brand-500 truncate",children:p.title}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:s("page.workingOnTaskHint")})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):n.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${y?.type==="heartbeat"||y?.type==="chat","bg-blue-400 animate-pulse"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:j}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:y?.type==="heartbeat"?s("page.activityDescHeartbeat"):y?.type==="chat"?s("page.activityDescChat"):s("page.activityDescFallback")})]})]}),n.jsx("button",{onClick:()=>{i(!1),r?.(e.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:s("page.viewMindArrow")})]})]})}const _G=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"cyberpunk",label:"Cyberpunk"},{value:"mono",label:"Mono"}],Qb="markus-theme";function Yk(e){const t=document.documentElement;t.classList.remove("light","dark","cyberpunk","mono"),e==="light"?t.classList.add("light"):e==="dark"?t.classList.add("dark"):e==="cyberpunk"?t.classList.add("cyberpunk"):e==="mono"&&t.classList.add("mono")}function zG(){try{const e=localStorage.getItem(Qb);if(e==="midnight")return localStorage.setItem(Qb,"dark"),"dark";if(e==="light"||e==="dark"||e==="system"||e==="cyberpunk"||e==="mono")return e}catch{}return"system"}function $G(){const[e,t]=x.useState(zG),r=x.useCallback(s=>{t(s);try{localStorage.setItem(Qb,s)}catch{}Yk(s)},[]);return x.useEffect(()=>{Yk(e)},[e]),{mode:e,setMode:r}}function BG(e){return e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed((e%1e3===0,0))}K`:String(e)}function Xk(e){return e===0?"-":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(2)}`:`$${e.toFixed(e%1===0?0:2)}`}function HG(e){return e.maxInputTokens>0||e.inputCostPer1MTokens>0||e.outputCostPer1MTokens>0}function ch({models:e,selectedModel:t,onSelect:r,loading:s,compact:a,maxVisible:i}){const[l,d]=x.useState(""),[u,m]=x.useState(!1),h=x.useMemo(()=>{if(!l)return e;const v=l.toLowerCase();return e.filter(j=>j.id.toLowerCase().includes(v))},[e,l]),p=i??(a?5:10),y=u?h:h.slice(0,p),g=h.length>p;return s?n.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-fg-tertiary",children:[n.jsx("div",{className:"w-4 h-4 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),"Loading models..."]}):e.length===0?n.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:"No models available for this provider."}):n.jsxs("div",{className:"space-y-2",children:[e.length>5&&n.jsx("input",{type:"text",value:l,onChange:v=>{d(v.target.value),m(!1)},placeholder:"Filter models...",className:"w-full px-3 py-1.5 bg-surface-overlay border border-border-default rounded-lg text-xs text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:border-brand-500"}),n.jsx("div",{className:`space-y-1 ${a?"max-h-[280px] overflow-y-auto":""}`,children:y.map(v=>{const j=v.id===t;return n.jsxs("button",{type:"button",onClick:()=>r(v.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${j?"bg-brand-500/10 border border-brand-500/30":"hover:bg-surface-overlay border border-transparent"}`,children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${j?"border-brand-500":"border-border-default"}`,children:j&&n.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),n.jsx("span",{className:`text-xs font-medium ${j?"text-brand-500":"text-fg-primary"}`,children:v.id})]}),j&&n.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:"Active"})]}),HG(v)&&n.jsxs("div",{className:"ml-5 mt-0.5 flex items-center gap-2 text-[10px] text-fg-tertiary flex-wrap",children:[v.maxInputTokens>0&&n.jsxs("span",{children:[BG(v.maxInputTokens)," ctx"]}),v.maxInputTokens>0&&(v.inputCostPer1MTokens>0||v.outputCostPer1MTokens>0)&&n.jsx("span",{className:"text-fg-quaternary",children:"|"}),(v.inputCostPer1MTokens>0||v.outputCostPer1MTokens>0)&&n.jsxs("span",{children:[Xk(v.inputCostPer1MTokens),"/",Xk(v.outputCostPer1MTokens)," per 1M"]})]}),!a&&n.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[v.capabilities.functionCalling&&n.jsx(Mu,{label:"Tools"}),v.capabilities.vision&&n.jsx(Mu,{label:"Vision"}),v.capabilities.reasoning&&n.jsx(Mu,{label:"Reasoning"}),v.capabilities.promptCaching&&n.jsx(Mu,{label:"Caching"}),v.capabilities.webSearch&&n.jsx(Mu,{label:"Search"})]})]},v.id)})}),g&&!u&&n.jsxs("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:["Show all ",h.length," models..."]}),u&&g&&n.jsx("button",{type:"button",onClick:()=>m(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:"Show less"})]})}function Mu({label:e}){return n.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] bg-surface-overlay text-fg-tertiary border border-border-default",children:e})}const Bu=[{id:"anthropic",label:"Anthropic",envKey:"ANTHROPIC_API_KEY",defaultModel:"claude-opus-4-6"},{id:"openai",label:"OpenAI",envKey:"OPENAI_API_KEY",defaultModel:"gpt-5.4"},{id:"google",label:"Google Gemini",envKey:"GOOGLE_API_KEY",defaultModel:"gemini-3-1-pro"},{id:"deepseek",label:"DeepSeek",envKey:"DEEPSEEK_API_KEY",baseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash"},{id:"siliconflow",label:"SiliconFlow",envKey:"SILICONFLOW_API_KEY",baseUrl:"https://api.siliconflow.cn/v1",defaultModel:"Qwen/Qwen3.5-35B-A3B"},{id:"minimax",label:"MiniMax",envKey:"MINIMAX_API_KEY",baseUrl:"https://api.minimax.io/v1",defaultModel:"MiniMax-M2.7"},{id:"openrouter",label:"OpenRouter",envKey:"OPENROUTER_API_KEY",baseUrl:"https://openrouter.ai/api/v1",defaultModel:"xiaomi/mimo-v2-pro:free"},{id:"zai",label:"ZAI (GLM)",envKey:"ZAI_API_KEY",baseUrl:"https://api.z.ai/api/paas/v4",defaultModel:"glm-5.1"},{id:"xai",label:"xAI (Grok)",envKey:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",defaultModel:"grok-3"},{id:"mistral",label:"Mistral AI",envKey:"MISTRAL_API_KEY",baseUrl:"https://api.mistral.ai/v1",defaultModel:"mistral-large-latest"},{id:"groq",label:"Groq",envKey:"GROQ_API_KEY",baseUrl:"https://api.groq.com/openai/v1",defaultModel:"llama-3.3-70b-versatile"},{id:"perplexity",label:"Perplexity",envKey:"PERPLEXITY_API_KEY",baseUrl:"https://api.perplexity.ai",defaultModel:"sonar-pro"},{id:"cohere",label:"Cohere",envKey:"COHERE_API_KEY",baseUrl:"https://api.cohere.ai/compatibility/v1",defaultModel:"command-r-plus"},{id:"together_ai",label:"Together AI",envKey:"TOGETHER_API_KEY",baseUrl:"https://api.together.xyz/v1",defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo"},{id:"fireworks_ai",label:"Fireworks AI",envKey:"FIREWORKS_API_KEY",baseUrl:"https://api.fireworks.ai/inference/v1",defaultModel:"accounts/fireworks/models/llama-v3p3-70b-instruct"},{id:"moonshot",label:"Moonshot (Kimi)",envKey:"MOONSHOT_API_KEY",baseUrl:"https://api.moonshot.cn/v1",defaultModel:"moonshot-v1-auto"},{id:"volcengine",label:"Volcengine (Doubao)",envKey:"VOLCENGINE_API_KEY",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",defaultModel:"doubao-1.5-pro-32k"},{id:"dashscope",label:"DashScope (Qwen)",envKey:"DASHSCOPE_API_KEY",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModel:"qwen-max"},{id:"ollama",label:"Ollama (Local)",envKey:"OLLAMA_BASE_URL",baseUrl:"http://localhost:11434/v1",defaultModel:"llama3"}],XS=[{id:"appearance",labelKey:"nav.appearance"},{id:"providers",labelKey:"nav.providers",adminOnly:!0},{id:"execution",labelKey:"nav.execution",adminOnly:!0},{id:"browser",labelKey:"nav.browser",adminOnly:!0},{id:"search",labelKey:"nav.search",adminOnly:!0},{id:"storage",labelKey:"nav.storage",adminOnly:!0},{id:"users",labelKey:"nav.users",adminOnly:!0},{id:"remote",labelKey:"nav.remote",adminOnly:!0}];function Qk(){const t=window.location.hash.slice(1).split("/");if(t[0]==="settings"&&t[1]){const r=t[1];if(XS.some(s=>s.id===r))return r}return null}function Zk({theme:e,onThemeChange:t,authUser:r,onLogout:s,onUserUpdated:a}={}){const{t:i,i18n:l}=ft(["settings","common"]),d=Ds(),[u,m]=x.useState(!1),[h,p]=x.useState(!1),y=x.useRef(null),[g,v]=x.useState(Qk);x.useEffect(()=>{const oe=()=>v(Qk());return window.addEventListener("hashchange",oe),()=>window.removeEventListener("hashchange",oe)},[]);const j=x.useCallback(oe=>{v(oe),history.pushState(null,"",`#settings/${oe}`)},[]),C=x.useCallback(()=>{v(null),history.pushState(null,"","#settings")},[]),w=g??(d?null:"appearance");x.useEffect(()=>{const oe=()=>p(!0);return window.addEventListener("markus:open-edit-profile",oe),()=>window.removeEventListener("markus:open-edit-profile",oe)},[]),x.useEffect(()=>{if(!u)return;const oe=Ee=>{y.current&&!y.current.contains(Ee.target)&&m(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[u]);const[N,S]=x.useState(null),[T,M]=x.useState(null),[D,I]=x.useState(""),[$,B]=x.useState(!1),[R,U]=x.useState(null),[W,F]=x.useState(null),[L,z]=x.useState(null),[E,_]=x.useState({}),[G,V]=x.useState(null),[O,q]=x.useState(null),[J,H]=x.useState(!1),[Z,Y]=x.useState(null),[ee,ae]=x.useState(null),[Q,me]=x.useState(!1),[Ae,Me]=x.useState(null),[He,je]=x.useState({}),[xe,Pe]=x.useState(!1),[Ce,Ye]=x.useState(null),[Qe,ct]=x.useState(!1),[st,zt]=x.useState(""),[mt,te]=x.useState(!1),[de,be]=x.useState(null),[se,fe]=x.useState([]),[$e,Ne]=x.useState([]),[Ze,pe]=x.useState(null),[ze,Fe]=x.useState(null),[Je,gt]=x.useState(""),[nt,Et]=x.useState(null),dt=x.useRef(null),Ve=x.useRef(!1),[Rt,un]=x.useState(!1),[yn,sn]=x.useState(200),[In,jn]=x.useState(!1),[Vt,mn]=x.useState(null),[Vn,Xn]=x.useState(!1),[Rr,qe]=x.useState(1),[St,_e]=x.useState(!1),[Tt,Ot]=x.useState(null),[Gt,Tn]=x.useState(!1),[_n,Sn]=x.useState(0),[Fn,mr]=x.useState(!0),[rr,fr]=x.useState(!1),[Qn,ir]=x.useState(!1),[Ie,At]=x.useState(9333),[It,qt]=x.useState(!1),[Jt,tn]=x.useState(null),[An,br]=x.useState(null),[an,ye]=x.useState({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),[at,yt]=x.useState(!1),[Ht,ln]=x.useState(null),[Mt,Ln]=x.useState(null),[Zn,zn]=x.useState(!1),[Jn,Pn]=x.useState(new Set),[on,lr]=x.useState(null),[qr,cr]=x.useState(!1),yr=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`}),ur=x.useCallback(()=>{le.health().then(S).catch(()=>{}),fetch("/api/settings/llm").then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>{oe&&typeof oe=="object"&&"providers"in oe&&(M(oe),I(oe.defaultProvider))}).catch(()=>{})},[]),Rs=x.useCallback(()=>{fetch("/api/settings/oauth/providers").then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>fe(oe.providers??[])).catch(()=>{})},[]),ha=x.useCallback(()=>{fetch("/api/settings/oauth/profiles",{headers:yr()}).then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>Ne(oe.profiles??[])).catch(()=>{})},[]),pa=x.useCallback(()=>{le.settings.getAgent().then(oe=>{oe&&typeof oe.maxToolIterations=="number"&&sn(oe.maxToolIterations),oe?.cognitive&&(Xn(oe.cognitive.enabled??!1),qe(oe.cognitive.maxDepth??1))}).catch(()=>{})},[]),Or=x.useCallback(()=>{le.settings.getBrowser().then(oe=>{oe&&(Tn(oe.bringToFront??!1),Sn(oe.remoteDebuggingPort??0),mr(oe.autoCloseTabs??!0),fr(oe.autoClickAllowDialog??!1),ir(oe.extensionConnected??!1),At(oe.extensionBridgePort??9333))}).catch(()=>{})},[]),Ja=x.useCallback(()=>{le.settings.getSearch().then(oe=>{oe&&br(oe)}).catch(()=>{})},[]),ga=x.useCallback(()=>{zn(!0),le.system.storage().then(Ln).catch(()=>{}).finally(()=>zn(!1)),le.system.orphans().then(lr).catch(()=>{})},[]);x.useEffect(()=>{ur(),Rs(),ha(),pa(),Or(),Ja(),ga()},[ur,Rs,ha,pa,Or,Ja,ga]),x.useEffect(()=>{const oe=()=>ga();return window.addEventListener("markus:data-changed",oe),()=>window.removeEventListener("markus:data-changed",oe)},[ga]),x.useEffect(()=>{!W||E[W]||(V(W),le.modelCatalog.getLive(W).then(oe=>{_(Ee=>({...Ee,[W]:oe.models}))}).catch(()=>{le.modelCatalog.getByProvider(W).then(oe=>{_(Ee=>({...Ee,[W]:oe.models}))}).catch(()=>{})}).finally(()=>V(null)))},[W]);const na=x.useCallback(async()=>{me(!0),Me(null),ae(null),je({});try{const oe=await fetch("/api/settings/env-models",{headers:yr()});if(!oe.ok){Me({type:"err",text:i("envConfig.detectionFailedHttp",{status:oe.status})});return}const Ee=await oe.json();if(ae(Ee),Ee.detected.length===0)Me({type:"err",text:i("envConfig.noKeysFound")});else{const et={};for(const hn of Ee.detected)et[hn.provider]=!0;je(et)}}catch{Me({type:"err",text:i("envConfig.failedToDetect")})}finally{me(!1)}},[i]),cs=x.useCallback(async()=>{ct(!0),be(null),Ye(null);try{const oe=await fetch("/api/settings/detect-ollama",{headers:yr()});if(!oe.ok){be({type:"err",text:i("ollama.detectFailed")});return}const Ee=await oe.json();Ye(Ee),Ee.found&&Ee.models&&Ee.models.length>0?zt(Ee.models[0].name):Ee.found||be({type:"err",text:Ee.error||i("ollama.notRunning")})}catch{be({type:"err",text:i("ollama.detectFailed")})}finally{ct(!1)}},[i]),ei=T?Object.values(T.providers).some(oe=>oe.configured):!1;x.useEffect(()=>{T&&!ei&&!Ve.current&&(Ve.current=!0,na(),cs())},[T,ei,na,cs]);const ti=async()=>{if(!(!D||D===T?.defaultProvider)){B(!0),U(null);try{const oe=await fetch("/api/settings/llm",{method:"POST",headers:yr(),body:JSON.stringify({defaultProvider:D})}),Ee=await oe.json();oe.ok?(M(Ee),U({type:"ok",text:i("defaultProvider.updated",{name:Ee.defaultProvider})})):U({type:"err",text:Ee.error??i("modelProviders.saveFailed")})}catch{U({type:"err",text:i("common:networkError")})}finally{B(!1)}}},Oa=async(oe,Ee)=>{z(oe);try{const et=await fetch(`/api/settings/llm/providers/${oe}/toggle`,{method:"POST",headers:yr(),body:JSON.stringify({enabled:Ee})});if(et.ok){const hn=await et.json();M(hn)}}catch{}finally{z(null)}},bi=async()=>{H(!0),Y(null);try{const Ee=await(await fetch("/api/settings/import/openclaw",{method:"POST",headers:yr(),body:JSON.stringify({preview:!0})})).json();"error"in Ee?Y({type:"err",text:Ee.error}):q(Ee)}catch{Y({type:"err",text:i("openClaw.detectFailed")})}finally{H(!1)}},ni=async()=>{H(!0),Y(null);try{const Ee=await(await fetch("/api/settings/import/openclaw",{method:"POST",headers:yr(),body:JSON.stringify({preview:!1})})).json();"error"in Ee?Y({type:"err",text:Ee.error}):(Y({type:"ok",text:i("openClaw.importedFrom",{count:Ee.appliedModels})}),ur())}catch{Y({type:"err",text:i("openClaw.importFailed")})}finally{H(!1)}},ra=async()=>{if(!ee)return;const oe=ee.detected.filter(Ee=>He[Ee.provider]);if(oe.length===0){Me({type:"err",text:i("envConfig.selectAtLeastOne")});return}Pe(!0),Me(null);try{const Ee=await fetch("/api/settings/env-models",{method:"POST",headers:yr(),body:JSON.stringify({providers:oe.map(hn=>({provider:hn.provider,model:hn.model,baseUrl:hn.baseUrl,enabled:!0}))})});if(!Ee.ok){Me({type:"err",text:i("envConfig.applyFailed",{status:Ee.status})});return}const et=await Ee.json();Me({type:"ok",text:et.message}),ae(null),je({}),ur()}catch{Me({type:"err",text:i("envConfig.failedToApply")})}finally{Pe(!1)}},Gs=async()=>{if(!(!Ce?.found||!st)){te(!0),be(null);try{const oe=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:"ollama",model:st,baseUrl:Ce.baseUrl||"http://localhost:11434"})});if(oe.ok){const Ee=await oe.json();M(Ee),be({type:"ok",text:i("ollama.configured",{model:st})}),Ye(null)}else{const Ee=await oe.json();be({type:"err",text:Ee.error||i("ollama.applyFailed")})}}catch{be({type:"err",text:i("ollama.applyFailed")})}finally{te(!1)}}};x.useEffect(()=>()=>{dt.current&&clearInterval(dt.current)},[]),x.useEffect(()=>{if(w!=="browser"||Qn)return;const oe=setInterval(async()=>{try{(await le.settings.getBrowser()).extensionConnected&&(ir(!0),clearInterval(oe))}catch{}},5e3);return()=>clearInterval(oe)},[w,Qn]);const[xa,Is]=x.useState(!1),[Kn,js]=x.useState({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),[ba,Ns]=x.useState(!1),[vr,Ls]=x.useState(null),[as,Ur]=x.useState([]),[ri,Ss]=x.useState(!1),[sa,_a]=x.useState(null),[Wn,Cs]=x.useState({apiKey:"",baseUrl:"",model:"",contextWindow:0,maxOutputTokens:0,costInput:0,costOutput:0}),[Ps,Mi]=x.useState(!1),[_r,wn]=x.useState(null),[Os,Hs]=x.useState(""),[si,ai]=x.useState(!1),[Ys,$r]=x.useState(null),[Fs,ya]=x.useState(null),[qs,Zr]=x.useState({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1}),[_s,va]=x.useState(!1),Di=async(oe,Ee)=>{if(!oe||oe==="__custom__")return;Ss(!0),$r(null);const et=Bu.find(Cn=>Cn.id===oe),hn=Kn.baseUrl||et?.baseUrl;try{if(Ee){const Cn=await le.modelCatalog.validateKey(oe,Ee,hn||void 0);!Cn.valid&&Cn.error&&$r({type:"err",text:Cn.error}),Ur(Cn.models)}else{const Cn=await le.modelCatalog.getByProvider(oe);Ur(Cn.models)}}catch{Ur([])}finally{Ss(!1)}},wa=async()=>{if(!(!Kn.name||!Kn.model)){Ns(!0),Ls(null),$r(null);try{const oe=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:Kn.name,apiKey:Kn.apiKey||void 0,baseUrl:Kn.baseUrl||void 0,model:Kn.model,contextWindow:Kn.contextWindow||void 0,maxOutputTokens:Kn.maxOutputTokens||void 0,cost:Kn.costInput||Kn.costOutput?{input:Kn.costInput,output:Kn.costOutput}:void 0})}),Ee=await oe.json();oe.ok?(M(Ee),Is(!1),Hs(""),Ur([]),js({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),$r({type:"ok",text:i("modelProviders.providerAdded",{name:Kn.name})})):$r({type:"err",text:Ee.error??i("modelProviders.failedToAdd")})}catch{$r({type:"err",text:i("common:networkError")})}finally{Ns(!1)}}},ka=async(oe,Ee)=>{if(!Os.trim())return;ai(!0),$r(null);const et=Bu.find(zs=>zs.id===oe),hn=et?.defaultModel??oe,Cn=et?.baseUrl;try{const zs=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:oe,apiKey:Os.trim(),model:hn,baseUrl:Cn})}),no=await zs.json();zs.ok?(M(no),Hs(""),Ur([]),$r({type:"ok",text:i("modelProviders.quickSetupSuccess",{name:et?.label??oe})})):$r({type:"err",text:no.error??i("modelProviders.failedToAdd")})}catch{$r({type:"err",text:i("common:networkError")})}finally{ai(!1)}},ja=(oe,Ee)=>{_a(oe),Cs({apiKey:"",baseUrl:Ee.baseUrl??"",model:Ee.model,contextWindow:Ee.contextWindow??0,maxOutputTokens:Ee.maxOutputTokens??0,costInput:Ee.cost?.input??0,costOutput:Ee.cost?.output??0})},ie=async oe=>{Mi(!0);try{const Ee={};Wn.apiKey&&(Ee.apiKey=Wn.apiKey),Wn.baseUrl!==void 0&&(Ee.baseUrl=Wn.baseUrl),Wn.model&&(Ee.model=Wn.model),Wn.contextWindow&&(Ee.contextWindow=Wn.contextWindow),Wn.maxOutputTokens&&(Ee.maxOutputTokens=Wn.maxOutputTokens),(Wn.costInput||Wn.costOutput)&&(Ee.cost={input:Wn.costInput,output:Wn.costOutput});const et=await fetch(`/api/settings/llm/providers/${oe}`,{method:"PUT",headers:yr(),body:JSON.stringify(Ee)});if(et.ok){const hn=await et.json();M(hn),_a(null)}}catch{}finally{Mi(!1)}},Xe=async oe=>{wn(oe);try{const Ee=await fetch(`/api/settings/llm/providers/${oe}`,{method:"DELETE",headers:yr()});if(Ee.ok){const et=await Ee.json();M(et),I(et.defaultProvider)}}catch{}finally{wn(null)}},ot=async oe=>{if(!(!qs.id||!qs.name)){va(!0);try{const Ee=await fetch(`/api/settings/llm/providers/${oe}/models`,{method:"POST",headers:yr(),body:JSON.stringify({id:qs.id,name:qs.name,contextWindow:qs.contextWindow,maxOutputTokens:qs.maxOutputTokens,cost:{input:qs.costInput,output:qs.costOutput},reasoning:qs.reasoning||void 0,inputTypes:qs.vision?["text","image"]:["text"]})});if(Ee.ok){const et=await Ee.json();M(et),ya(null),Zr({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})}}catch{}finally{va(!1)}}},Dt=async(oe,Ee)=>{try{const et=await fetch(`/api/settings/llm/providers/${oe}/models/${encodeURIComponent(Ee)}`,{method:"DELETE",headers:yr()});if(et.ok){const hn=await et.json();M(hn)}}catch{}},fn=new Set(["claude-opus-4-6","claude-sonnet-4-20250514","claude-3-5-haiku-20241022","gpt-5.4","gpt-4o","o4-mini","gemini-3-1-pro","gemini-2.5-flash","MiniMax-M2.7","MiniMax-M2.5","xiaomi/mimo-v2-pro","anthropic/claude-opus-4-6","openai/gpt-5.4","google/gemini-3-1-pro","deepseek-v4-flash","deepseek-v4-pro","deepseek-chat","deepseek-reasoner"]),[hr,cn]=x.useState(null),[bt,ds]=x.useState(null),[Vr,us]=x.useState({}),is=async oe=>{ds(oe),us(Ee=>{const et={...Ee};return delete et[oe],et});try{const Ee=await fetch(`/api/settings/llm/providers/${oe}/test`,{method:"POST",headers:yr()});if(!Ee.ok){const hn=await Ee.json().catch(()=>({}));us(Cn=>({...Cn,[oe]:{ok:!1,error:hn.error??`HTTP ${Ee.status}`,errorCode:Ee.status}}));return}const et=await Ee.json();us(hn=>({...hn,[oe]:et}))}catch{us(Ee=>({...Ee,[oe]:{ok:!1,error:i("common:networkError")}}))}finally{ds(null)}},Kr=async(oe,Ee)=>{cn(`${oe}:${Ee}`);try{const et=await fetch(`/api/settings/llm/providers/${oe}/model`,{method:"POST",headers:yr(),body:JSON.stringify({model:Ee})});if(et.ok){const hn=await et.json();M(hn)}}catch{}finally{cn(null)}},ms=async()=>{if(an.serperApiKey||an.tavilyApiKey||an.bingApiKey||an.googleSearchApiKey||an.googleSearchCx||an.serpApiKey||an.braveApiKey||an.exaApiKey||an.bochaApiKey){yt(!0),ln(null);try{const Ee={};an.serperApiKey&&(Ee.serperApiKey=an.serperApiKey),an.tavilyApiKey&&(Ee.tavilyApiKey=an.tavilyApiKey),an.bingApiKey&&(Ee.bingApiKey=an.bingApiKey),an.googleSearchApiKey&&(Ee.googleSearchApiKey=an.googleSearchApiKey),an.googleSearchCx&&(Ee.googleSearchCx=an.googleSearchCx),an.serpApiKey&&(Ee.serpApiKey=an.serpApiKey),an.braveApiKey&&(Ee.braveApiKey=an.braveApiKey),an.exaApiKey&&(Ee.exaApiKey=an.exaApiKey),an.bochaApiKey&&(Ee.bochaApiKey=an.bochaApiKey);const et=await le.settings.updateSearch(Ee);br(et),ye({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),ln({type:"ok",text:i("searchApi.saved")})}catch{ln({type:"err",text:i("searchApi.failedToSave")})}finally{yt(!1)}}},Nr=T?.providers?Object.entries(T.providers).filter(([,oe])=>oe.configured&&oe.enabled).map(([oe])=>oe):[],eo=T&&!ei&&!Rt,Ri=r?.role==="owner"||r?.role==="admin",to=XS.filter(oe=>!oe.adminOnly||Ri);return n.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[h&&r&&n.jsx(WG,{authUser:r,onClose:()=>p(!1),onSaved:oe=>{p(!1),a?.(oe)}}),n.jsxs("aside",{className:"hidden md:flex flex-col w-56 shrink-0 border-r border-border-default bg-surface-secondary overflow-y-auto",children:[n.jsx("div",{className:"px-3 pt-4 pb-2",children:n.jsxs("button",{onClick:()=>{pt.navigate(Te.HOME)},className:"flex items-center gap-2 px-2 py-1.5 rounded-lg text-sm text-fg-secondary hover:text-fg-primary hover:bg-surface-overlay transition-colors",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]}),i("common:back",{defaultValue:"Back"})]})}),n.jsx("div",{className:"px-5 pb-4",children:n.jsx("h2",{className:"text-base font-semibold text-fg-primary",children:i("title")})}),n.jsx("nav",{className:"flex-1 px-3 pb-4 space-y-0.5",children:to.map(oe=>n.jsx("button",{onClick:()=>j(oe.id),className:`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${w===oe.id?"bg-brand-600/10 text-brand-600 dark:text-brand-400 font-medium":"text-fg-secondary hover:text-fg-primary hover:bg-surface-overlay"}`,children:i(`settings:${oe.labelKey}`)},oe.id))}),r&&n.jsx("div",{className:"px-3 pb-4 border-t border-border-default pt-3",children:n.jsxs("div",{ref:y,className:"relative",children:[n.jsxs("button",{onClick:()=>m(!u),className:"w-full flex items-center gap-2.5 px-3 py-2 rounded-lg hover:bg-surface-overlay transition-colors",children:[n.jsx(Sr,{name:r.name||i("common:userPlaceholder"),avatarUrl:r.avatarUrl,size:24}),n.jsx("span",{className:"text-sm text-fg-secondary truncate flex-1 text-left",children:r.name||i("common:userPlaceholder")})]}),u&&n.jsxs("div",{className:"absolute left-0 bottom-full mb-1 bg-surface-secondary border border-border-default rounded-xl shadow-xl z-50 overflow-hidden",style:{minWidth:200},children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-default",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:r.name||i("common:userPlaceholder")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r.email||r.role})]}),n.jsxs("div",{className:"py-1",children:[n.jsxs("button",{onClick:()=>{m(!1),p(!0)},className:"w-full flex items-center gap-2.5 px-4 py-2 text-sm text-fg-secondary hover:bg-surface-overlay transition-colors",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),i("common:profile.editProfile")]}),s&&n.jsxs("button",{onClick:()=>{m(!1),s()},className:"w-full flex items-center gap-2.5 px-4 py-2 text-sm text-red-500 hover:bg-red-500/10 transition-colors",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),i("common:signOut",{defaultValue:"Sign Out"})]})]})]})]})})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[d&&w===null&&n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary",children:[n.jsx("button",{onClick:()=>pt.navigate(Te.HOME),className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:i("title")})]}),n.jsx("nav",{className:"flex-1 overflow-y-auto py-2 px-3",children:to.map(oe=>n.jsxs("button",{onClick:()=>j(oe.id),className:"w-full flex items-center justify-between px-4 py-3 rounded-lg text-sm text-fg-primary hover:bg-surface-overlay transition-colors",children:[n.jsx("span",{children:i(`settings:${oe.labelKey}`)}),n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})]},oe.id))})]}),d&&w!==null&&n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary sticky top-0 z-10",children:[n.jsx("button",{onClick:C,className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:i(`settings:${to.find(oe=>oe.id===w)?.labelKey||"title"}`)})]}),w!==null&&n.jsxs("div",{className:"p-7 space-y-10 max-w-4xl mx-auto w-full",children:[w==="appearance"&&n.jsx(hi,{title:i("appearance.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("appearance.theme")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("appearance.themeDesc")})]}),n.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:_G.map(({value:oe})=>n.jsx("button",{onClick:()=>t?.(oe),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${e===oe?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:i(`appearance.modes.${oe}`)},oe))})]}),n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between mt-5 pt-5 border-t border-border-default/50",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("appearance.language")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("appearance.languageDesc")})]}),n.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:uw.map(({code:oe,label:Ee})=>n.jsx("button",{onClick:()=>{l.changeLanguage(oe)},className:`px-3 py-1.5 text-xs rounded-md transition-colors ${l.language===oe||oe==="en"&&!uw.some(et=>et.code===l.language)?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:Ee},oe))})]})]})}),Ri&&n.jsxs(n.Fragment,{children:[w==="providers"&&n.jsxs(n.Fragment,{children:[eo&&n.jsxs("div",{className:"relative bg-gradient-to-br from-brand-500/10 to-surface-secondary border border-brand-500/20 rounded-2xl p-6 space-y-5",children:[n.jsx("button",{onClick:()=>un(!0),className:"absolute top-4 right-4 text-fg-tertiary hover:text-fg-secondary text-xs",children:i("setupGuide.skip")}),n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:i("setupGuide.title")}),n.jsx("p",{className:"text-sm text-fg-secondary mt-1",children:i("setupGuide.subtitle")})]}),n.jsxs(Du,{step:i("setupGuide.fromEnv.step"),title:i("setupGuide.fromEnv.title"),description:i("setupGuide.fromEnv.description"),active:!!(ee&&ee.detected.length>0),children:[Q&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:detecting")}),ee&&ee.detected.length>0&&n.jsxs("div",{className:"space-y-2",children:[ee.detected.map(oe=>n.jsxs("label",{className:"flex items-center gap-3 bg-surface-elevated/30 rounded-lg px-3 py-2 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[n.jsx("input",{type:"checkbox",checked:He[oe.provider]??!1,onChange:Ee=>je({...He,[oe.provider]:Ee.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"text-sm text-fg-primary",children:oe.displayName}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-2",children:oe.model})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:oe.apiKeyPreview})]},oe.provider)),n.jsx("button",{onClick:()=>{ra()},disabled:xe||Object.values(He).filter(Boolean).length===0,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:xe?i("common:applying"):i("setupGuide.applyProviders",{count:Object.values(He).filter(Boolean).length})})]}),ee&&ee.detected.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:n.jsx(n0,{i18nKey:"settings:setupGuide.fromEnv.noKeysHint",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),Ae&&n.jsx(Ua,{type:Ae.type,text:Ae.text})]}),n.jsxs(Du,{step:i("setupGuide.fromOllama.step"),title:i("setupGuide.fromOllama.title"),description:i("setupGuide.fromOllama.description"),active:!!Ce?.found,children:[Qe&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:detecting")}),Ce?.found&&Ce.models&&Ce.models.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-green-600",children:i("ollama.foundModels",{count:Ce.models.length,url:Ce.baseUrl})}),n.jsx("select",{value:st,onChange:oe=>zt(oe.target.value),className:"w-full px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary focus:outline-none focus:ring-2 focus:ring-brand-500",children:Ce.models.map(oe=>n.jsxs("option",{value:oe.name,children:[oe.name,oe.parameterSize?` (${oe.parameterSize})`:"",oe.family?` — ${oe.family}`:""]},oe.name))}),n.jsx("button",{onClick:()=>{Gs()},disabled:mt||!st,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:mt?i("common:applying"):i("ollama.useModel",{model:st})})]}),!Qe&&!Ce&&n.jsx("button",{onClick:()=>{cs()},className:"px-4 py-2 border border-border-default hover:bg-surface-elevated text-fg-secondary text-sm rounded-lg transition-colors",children:i("ollama.detect")}),Ce&&!Ce.found&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("ollama.notRunning")}),de&&n.jsx(Ua,{type:de.type,text:de.text})]}),n.jsxs(Du,{step:i("setupGuide.fromOpenClaw.step"),title:i("setupGuide.fromOpenClaw.title"),description:i("setupGuide.fromOpenClaw.description"),children:[O?O.found?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"text-xs text-green-600",children:[i("setupGuide.foundPrefix")," ",n.jsx("code",{className:"text-fg-secondary",children:O.summary.configPath})]}),O.summary.models&&n.jsx("div",{className:"text-xs text-fg-secondary",children:i("openClaw.providersModels",{providers:O.summary.models.providerCount,models:O.summary.models.providers.reduce((oe,Ee)=>oe+Ee.modelCount,0)})}),n.jsx("button",{onClick:()=>{ni()},disabled:J,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:i(J?"common:importing":"openClaw.importConfigs")})]}):n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("openClaw.notFound")}):n.jsx("button",{onClick:()=>{bi()},disabled:J,className:"px-4 py-2 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-secondary text-sm rounded-lg transition-colors",children:i(J?"common:detecting":"openClaw.detectShort")}),Z&&n.jsx(Ua,{type:Z.type,text:Z.text})]}),n.jsx(Du,{step:i("setupGuide.manual.step"),title:i("setupGuide.manual.title"),description:n.jsx(n0,{i18nKey:"settings:setupGuide.manual.description",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),/Chrome\/\d/.test(navigator.userAgent)&&!/Edg\//.test(navigator.userAgent)&&n.jsx(Du,{step:i("setupGuide.browserExtension.step"),title:i("setupGuide.browserExtension.title"),description:i("setupGuide.browserExtension.description"),active:Qn,children:Qn?n.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-400",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),i("setupGuide.browserExtension.alreadyConnected")]}):n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0);try{await le.settings.downloadExtensionZip()}catch{}qt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40 inline-flex items-center gap-1.5",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),i("setupGuide.browserExtension.downloadBtn")]}),n.jsxs("button",{disabled:It,onClick:async()=>{try{await le.settings.openExtensionsPage()}catch{}},className:"px-3 py-1.5 text-xs border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40 inline-flex items-center gap-1.5",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),i("setupGuide.browserExtension.openChromeBtn")]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("setupGuide.browserExtension.loadHint")})]})})]}),n.jsx(hi,{title:i("systemStatus.title"),children:N?n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsx(Ux,{label:i("systemStatus.status"),value:N.status==="ok"?i("systemStatus.healthy"):N.status,color:"green"}),n.jsx(Ux,{label:i("systemStatus.version"),value:N.version,color:"indigo"}),n.jsx(Ux,{label:i("systemStatus.activeAgents"),value:String(N.agents),color:"purple"})]}):n.jsx("div",{className:"text-sm text-fg-tertiary",children:i("common:loading")})}),n.jsx(hi,{title:i("defaultProvider.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("defaultProvider.primaryProvider")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("defaultProvider.primaryProviderDesc")})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[T?n.jsx("select",{value:D,onChange:oe=>{I(oe.target.value),U(null)},className:"px-3 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-sm w-48 focus:border-brand-500 outline-none",children:Nr.length>0?Nr.map(oe=>n.jsx("option",{value:oe,children:T.providers[oe]?.displayName??oe},oe)):n.jsx("option",{value:"",children:i("defaultProvider.noProviders")})}):n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:loading")}),D!==T?.defaultProvider&&n.jsx("button",{onClick:()=>{ti()},disabled:$,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i($?"common:saving":"common:save")})]})]}),R&&n.jsx(Ua,{type:R.type,text:R.text}),n.jsxs("div",{className:"flex items-center justify-between border-t border-border-default pt-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("defaultProvider.autoFallback")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("defaultProvider.autoFallbackDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!(T?.autoFallback??!0);try{const Ee=await fetch("/api/settings/llm",{method:"POST",headers:yr(),body:JSON.stringify({autoFallback:oe})});if(Ee.ok){const et=await Ee.json();M(et)}}catch{}},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${T?.autoFallback??!0?"bg-green-500":"bg-gray-600"}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${T?.autoFallback??!0?"translate-x-4":"translate-x-1"}`})})]})]})}),n.jsxs(hi,{title:i("modelProviders.title"),children:[n.jsx("div",{className:"space-y-3",children:T&&(()=>{const oe=[],Ee=new Set;for(const[et,hn]of Object.entries(T.providers))oe.push([et,hn]),Ee.add(et);for(const et of Bu)Ee.has(et.id)||(oe.push([et.id,{name:et.id,displayName:et.label,model:et.defaultModel,configured:!1,enabled:!1}]),Ee.add(et.id));return oe})().map(([oe,Ee])=>n.jsxs("div",{className:`bg-surface-secondary border rounded-xl overflow-hidden transition-colors ${Ee.configured?"border-border-default hover:border-gray-600":"border-border-default/50 hover:border-brand-500/30"}`,children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-4 cursor-pointer",onClick:()=>{F(W===oe?null:oe),Hs(""),$r(null),Ur([]),js(et=>({...et,name:"",model:""}))},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${Ee.configured&&Ee.enabled?"bg-green-400":Ee.configured?"bg-amber-400":"bg-gray-600"}`}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm font-medium",children:Ee.displayName??oe}),oe===T.defaultProvider&&n.jsx("span",{className:"text-[10px] bg-brand-500/15 text-brand-500 px-1.5 py-0.5 rounded",children:i("modelProviders.badgeDefault")}),Ee.configured&&!Ee.enabled&&n.jsx("span",{className:"text-[10px] bg-amber-500/15 text-amber-600 px-1.5 py-0.5 rounded",children:i("modelProviders.disabled")}),Ee.oauthConnected&&n.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:i("modelProviders.badgeOAuth")}),Vr[oe]?.ok===!0&&n.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:i("modelProviders.testOk",{ms:Vr[oe].durationMs})}),Vr[oe]?.ok===!1&&n.jsx("span",{className:"text-[10px] bg-red-500/15 text-red-500 px-1.5 py-0.5 rounded",title:Vr[oe].error,children:Vr[oe].errorCode?i("modelProviders.testFailedCode",{code:Vr[oe].errorCode}):i("modelProviders.testFailed")})]}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:Ee.configured?n.jsxs(n.Fragment,{children:[Ee.model,Ee.apiKeyPreview&&n.jsxs(n.Fragment,{children:[" · ",n.jsx("code",{className:"text-fg-secondary",children:Ee.apiKeyPreview})]})]}):i("modelProviders.notConfigured")})]})]}),n.jsxs("div",{className:"flex items-center gap-4",children:[Ee.configured&&n.jsx("button",{onClick:et=>{et.stopPropagation(),Oa(oe,!Ee.enabled)},disabled:L===oe,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Ee.enabled?"bg-green-500":"bg-gray-600"} ${L===oe?"opacity-50":""}`,title:Ee.enabled?i("modelProviders.clickToDisable"):i("modelProviders.clickToEnable"),children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ee.enabled?"translate-x-4":"translate-x-1"}`})}),Ee.contextWindow!=null&&Ee.contextWindow>0&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("modelProviders.ctxTokens",{size:(Ee.contextWindow/1e3).toFixed(0)})}),Ee.cost&&(Ee.cost.input>0||Ee.cost.output>0)&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("modelProviders.costPerMillion",{input:Ee.cost.input,output:Ee.cost.output})}),n.jsx("span",{className:"text-fg-tertiary text-xs",children:W===oe?"▲":"▼"})]})]}),W===oe&&n.jsxs("div",{className:"px-5 pb-4 border-t border-border-default pt-4 space-y-4",children:[Ee.configured&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsx(ml,{label:i("modelProviders.model"),value:Ee.model}),n.jsx(ml,{label:i("modelProviders.contextWindow"),value:Ee.contextWindow?i("modelProviders.kTokens",{k:(Ee.contextWindow/1e3).toFixed(0)}):i("modelProviders.notApplicable")}),n.jsx(ml,{label:i("modelProviders.maxOutput"),value:Ee.maxOutputTokens?i("modelProviders.kTokens",{k:(Ee.maxOutputTokens/1e3).toFixed(0)}):i("modelProviders.notApplicable")}),n.jsx(ml,{label:i("modelProviders.baseUrlLabel"),value:Ee.baseUrl??i("modelProviders.baseUrlDisplayDefault")})]}),sa===oe?n.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-4 space-y-3",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:i("modelProviders.editProvider")}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:Wn.apiKey,onChange:et=>Cs({...Wn,apiKey:et.target.value}),placeholder:i("modelProviders.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.baseUrl")}),n.jsx("input",{type:"text",value:Wn.baseUrl,onChange:et=>Cs({...Wn,baseUrl:et.target.value}),placeholder:i("modelProviders.baseUrlDisplayDefault"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.model")}),n.jsx("input",{type:"text",value:Wn.model,onChange:et=>Cs({...Wn,model:et.target.value}),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.contextWindow")}),n.jsx("input",{type:"number",value:Wn.contextWindow||"",onChange:et=>Cs({...Wn,contextWindow:Number(et.target.value)}),placeholder:i("modelProviders.placeholderContextExample"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.maxOutputTokens")}),n.jsx("input",{type:"number",value:Wn.maxOutputTokens||"",onChange:et=>Cs({...Wn,maxOutputTokens:Number(et.target.value)}),placeholder:i("modelProviders.placeholderMaxOutputExample"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.inputCost")}),n.jsx("input",{type:"number",step:"0.01",value:Wn.costInput||"",onChange:et=>Cs({...Wn,costInput:Number(et.target.value)}),placeholder:i("modelProviders.placeholderCostInput"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.outputCost")}),n.jsx("input",{type:"number",step:"0.01",value:Wn.costOutput||"",onChange:et=>Cs({...Wn,costOutput:Number(et.target.value)}),placeholder:i("modelProviders.placeholderCostOutput"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>{ie(oe)},disabled:Ps,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(Ps?"common:saving":"common:save")}),n.jsx("button",{onClick:()=>_a(null),className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:cancel")})]})]}):n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:et=>{et.stopPropagation(),is(oe)},disabled:bt===oe,className:"px-3 py-1.5 text-xs border border-green-500/30 text-green-500 hover:bg-green-500/10 rounded-lg transition-colors disabled:opacity-40 flex items-center gap-1.5",children:bt===oe?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),i("modelProviders.testing")]}):i("modelProviders.test")}),n.jsx("button",{onClick:et=>{et.stopPropagation(),ja(oe,Ee)},className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:edit")}),n.jsx("button",{onClick:et=>{et.stopPropagation(),confirm(i("modelProviders.deleteConfirm",{name:Ee.displayName??oe}))&&Xe(oe)},disabled:_r===oe,className:"px-3 py-1.5 text-xs border border-red-500/30 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors disabled:opacity-40",children:i(_r===oe?"common:deleting":"common:delete")})]}),Vr[oe]&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${Vr[oe].ok?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:Vr[oe].ok?i("modelProviders.testSuccess",{ms:Vr[oe].durationMs,reply:Vr[oe].reply}):Vr[oe].error})]}),Ee.cost&&n.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-3",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-2",children:i("modelProviders.pricingTitle")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsx(ml,{label:i("modelProviders.input"),value:`$${Ee.cost.input}`}),n.jsx(ml,{label:i("modelProviders.output"),value:`$${Ee.cost.output}`}),Ee.cost.cacheRead!=null&&n.jsx(ml,{label:i("modelProviders.cacheRead"),value:`$${Ee.cost.cacheRead}`}),Ee.cost.cacheWrite!=null&&n.jsx(ml,{label:i("modelProviders.cacheWrite"),value:`$${Ee.cost.cacheWrite}`})]})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:i("modelProviders.availableModels")}),Ee.configured&&Fs!==oe&&n.jsx("button",{onClick:()=>{ya(oe),Zr({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})},className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:i("modelProviders.addModel")})]}),Fs===oe&&n.jsx("div",{className:"bg-surface-elevated/40 rounded-lg p-3 mb-2 space-y-2",children:n.jsx(VG,{providerName:oe,addModelForm:qs,setAddModelForm:Zr,addModelSaving:_s,onAdd:()=>{ot(oe)},onCancel:()=>ya(null),t:i})}),Ee.models&&Ee.models.length>0&&n.jsx("div",{className:"space-y-1.5",children:Ee.models.map(et=>{const hn=et.id===Ee.model,Cn=hr===`${oe}:${et.id}`,zs=!fn.has(et.id);return n.jsxs("div",{className:`flex items-center justify-between px-3 py-2 rounded-lg text-xs transition-colors ${hn?"bg-brand-500/15 border border-brand-500/30":Ee.configured?"bg-surface-elevated/30 hover:bg-surface-elevated/60 cursor-pointer":"bg-surface-elevated/30"}`,onClick:()=>{!hn&&Ee.configured&&!Cn&&Kr(oe,et.id)},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[hn&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 shrink-0"}),n.jsx("span",{className:hn?"text-brand-500 font-medium":"text-fg-secondary",children:et.name}),et.reasoning&&n.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:i("modelProviders.reasoning")}),et.inputTypes?.includes("image")&&n.jsx("span",{className:"text-[9px] bg-blue-500/15 text-blue-600 px-1 py-0.5 rounded",children:i("modelProviders.vision")}),zs&&n.jsx("span",{className:"text-[9px] bg-purple-500/15 text-purple-400 px-1 py-0.5 rounded",children:i("modelProviders.custom")})]}),n.jsxs("div",{className:"flex items-center gap-3 text-fg-tertiary",children:[et.contextWindow>0&&n.jsx("span",{children:i("modelProviders.ctxTokens",{size:(et.contextWindow/1e3).toFixed(0)})}),(et.cost.input>0||et.cost.output>0)&&n.jsx("span",{children:i("modelProviders.costPair",{input:et.cost.input,output:et.cost.output})}),Ee.configured&&!hn&&n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded transition-colors ${Cn?"bg-brand-500/30 text-brand-400":"bg-surface-overlay text-fg-tertiary hover:bg-brand-500/20 hover:text-brand-500"}`,children:i(Cn?"modelProviders.switching":"modelProviders.use")}),hn&&n.jsx("span",{className:"text-[9px] bg-brand-500/15 text-brand-500 px-1.5 py-0.5 rounded",children:i("modelProviders.active")}),zs&&!hn&&n.jsx("button",{onClick:no=>{no.stopPropagation(),Dt(oe,et.id)},className:"text-red-400 hover:text-red-300 transition-colors",title:i("modelProviders.deleteCustomModelTitle"),children:n.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]},et.id)})}),Ee.configured&&G===oe&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 text-xs text-fg-tertiary",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),i("modelProviders.loadingCatalog")]}),Ee.configured&&E[oe]&&E[oe].length>0&&(()=>{const et=new Set(Ee.models?.map(Cn=>Cn.id)??[]),hn=E[oe].filter(Cn=>!et.has(Cn.id));return hn.length===0?null:n.jsxs("details",{className:"mt-2 group",children:[n.jsx("summary",{className:"text-[10px] text-fg-tertiary cursor-pointer hover:text-fg-secondary select-none",children:i("modelProviders.moreCatalogModels",{count:hn.length})}),n.jsx("div",{className:"mt-1.5 space-y-1",children:hn.map(Cn=>{const zs=hr===`${oe}:${Cn.id}`;return n.jsxs("div",{onClick:()=>{zs||Kr(oe,Cn.id)},className:"flex items-center justify-between px-3 py-1.5 rounded-lg text-xs bg-surface-elevated/20 hover:bg-surface-elevated/50 cursor-pointer transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-fg-secondary",children:Cn.id}),Cn.capabilities.reasoning&&n.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:i("modelProviders.reasoning")}),Cn.capabilities.vision&&n.jsx("span",{className:"text-[9px] bg-blue-500/15 text-blue-600 px-1 py-0.5 rounded",children:i("modelProviders.vision")})]}),n.jsxs("div",{className:"flex items-center gap-3 text-fg-tertiary",children:[Cn.maxInputTokens>0&&n.jsxs("span",{children:[Math.round(Cn.maxInputTokens/1e3),"K ctx"]}),(Cn.inputCostPer1MTokens>0||Cn.outputCostPer1MTokens>0)&&n.jsxs("span",{children:["$",Cn.inputCostPer1MTokens,"/",Cn.outputCostPer1MTokens]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded transition-colors ${zs?"bg-brand-500/30 text-brand-400":"bg-surface-overlay text-fg-tertiary hover:bg-brand-500/20 hover:text-brand-500"}`,children:i(zs?"modelProviders.switching":"modelProviders.use")})]})]},Cn.id)})})]})})()]}),!Ee.configured&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:i("modelProviders.quickSetupHint")}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:W===oe?Os:"",onChange:et=>Hs(et.target.value),placeholder:i("modelProviders.quickSetupPlaceholder"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none",onBlur:()=>{Os.trim().length>=8&&W===oe&&Di(oe,Os.trim())},onKeyDown:et=>{et.key==="Enter"&&Os.trim().length>=8&&Di(oe,Os.trim())}}),ri&&W===oe&&n.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-xs text-fg-tertiary",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),i("modelProviders.validatingKey")]})]}),W===oe&&as.length>0&&n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-2",children:i("modelProviders.selectModel")}),n.jsx(ch,{provider:oe,models:as,selectedModel:Kn.model,onSelect:et=>{const hn=as.find(Cn=>Cn.id===et);js(Cn=>({...Cn,name:oe,model:et,apiKey:Os.trim(),baseUrl:Bu.find(zs=>zs.id===oe)?.baseUrl??"",contextWindow:hn?.maxInputTokens??Cn.contextWindow,maxOutputTokens:hn?.maxOutputTokens??Cn.maxOutputTokens,costInput:hn?.inputCostPer1MTokens??Cn.costInput,costOutput:hn?.outputCostPer1MTokens??Cn.costOutput}))},compact:!0,maxVisible:8})]}),W===oe&&Os.trim()&&n.jsx("button",{onClick:()=>{Kn.model&&Kn.name===oe?wa():ka(oe)},disabled:si||ba,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(si||ba?"modelProviders.quickSetupSaving":"modelProviders.quickSetupSubmit")}),Ys&&W===oe&&n.jsx(Ua,{type:Ys.type,text:Ys.text})]})]})]},oe))}),xa?n.jsxs("div",{className:"mt-3 bg-surface-secondary border border-brand-500/30 rounded-xl p-4 space-y-3",children:[n.jsx("div",{className:"text-xs font-medium text-fg-primary",children:i("modelProviders.customProvider")}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.providerName")}),n.jsx("input",{type:"text",value:Kn.name==="__custom__"?"":Kn.name,onChange:oe=>js(Ee=>({...Ee,name:oe.target.value||"__custom__"})),placeholder:"my-provider",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.baseUrl")}),n.jsx("input",{type:"text",value:Kn.baseUrl,onChange:oe=>js({...Kn,baseUrl:oe.target.value}),placeholder:"https://api.example.com/v1",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:Kn.apiKey,onChange:oe=>js({...Kn,apiKey:oe.target.value}),placeholder:i("modelProviders.placeholderApiKeySk"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.defaultModel")}),n.jsx("input",{type:"text",value:Kn.model,onChange:oe=>js({...Kn,model:oe.target.value}),placeholder:"gpt-4o",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>{wa()},disabled:ba||!Kn.name||Kn.name==="__custom__"||!Kn.model,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(ba?"modelProviders.adding":"modelProviders.addProviderSubmit")}),n.jsx("button",{onClick:()=>{Is(!1),Ls(null),Ur([]),js({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5})},className:"px-4 py-2 text-sm border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:cancel")})]}),vr&&n.jsx(Ua,{type:vr.type,text:vr.text})]}):n.jsxs("button",{onClick:()=>Is(!0),className:"w-full mt-3 px-4 py-2.5 border border-dashed border-border-default hover:border-brand-500/50 hover:bg-brand-500/5 rounded-xl text-xs text-fg-tertiary hover:text-brand-500 transition-colors",children:["+ ",i("modelProviders.customProvider")]})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsx(hi,{title:i("autoDetect.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[n.jsx("div",{className:"text-sm text-fg-secondary",children:i("autoDetect.description")}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("envConfig.title")}),n.jsxs("button",{onClick:()=>{na()},disabled:Q,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[n.jsx("svg",{className:`w-3.5 h-3.5 ${Q?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),i(Q?"common:detecting":"envConfig.refreshEnv")]})]}),ee&&ee.detected.length>0&&n.jsxs("div",{className:"space-y-2",children:[ee.detected.map(oe=>n.jsxs("label",{className:"flex items-center justify-between bg-surface-elevated/30 rounded-lg px-4 py-3 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"checkbox",checked:He[oe.provider]??!1,onChange:Ee=>je({...He,[oe.provider]:Ee.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm text-fg-primary font-medium",children:oe.displayName}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[i("envConfig.keyLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.apiKeyPreview})," / ",i("envConfig.modelLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.model}),oe.baseUrl&&n.jsxs(n.Fragment,{children:[" / ",i("envConfig.urlLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.baseUrl})]})]})]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:Object.keys(oe.envVars).map(Ee=>n.jsx("div",{children:n.jsx("code",{children:Ee})},Ee))})]},oe.provider)),ee.timeoutMs&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("envConfig.llmTimeout",{ms:ee.timeoutMs})}),n.jsx("button",{onClick:()=>{ra()},disabled:xe||Object.values(He).filter(Boolean).length===0,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:xe?i("common:applying"):i("envConfig.applyToConfig",{count:Object.values(He).filter(Boolean).length})})]}),Ae&&n.jsx(Ua,{type:Ae.type,text:Ae.text})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("ollama.title")}),n.jsxs("button",{onClick:()=>{cs()},disabled:Qe,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[n.jsx("svg",{className:`w-3.5 h-3.5 ${Qe?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),i(Qe?"common:detecting":"ollama.detect")]})]}),Ce?.found&&Ce.models&&Ce.models.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-green-600",children:i("ollama.foundModels",{count:Ce.models.length,url:Ce.baseUrl})}),n.jsx("div",{className:"space-y-1",children:Ce.models.map(oe=>n.jsx("label",{className:`flex items-center justify-between rounded-lg px-4 py-3 cursor-pointer transition-colors ${st===oe.name?"bg-brand-500/15 border border-brand-500/40":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"radio",name:"ollama-model",value:oe.name,checked:st===oe.name,onChange:()=>zt(oe.name),className:"w-4 h-4 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm text-fg-primary font-medium",children:oe.name}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[oe.parameterSize&&n.jsx("span",{children:oe.parameterSize}),oe.family&&n.jsx("span",{className:"ml-2",children:oe.family}),oe.quantization&&n.jsx("span",{className:"ml-2",children:oe.quantization}),oe.size&&n.jsx("span",{className:"ml-2",children:td(oe.size)})]})]})]})},oe.name))}),n.jsx("button",{onClick:()=>{Gs()},disabled:mt||!st,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:mt?i("common:applying"):i("ollama.useModel",{model:st})})]}),Ce&&!Ce.found&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:Ce.error||i("ollama.notRunning")}),de&&n.jsx(Ua,{type:de.type,text:de.text})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("openClaw.title")}),n.jsx("button",{onClick:()=>{bi()},disabled:J,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:i(J?"common:detecting":"openClaw.detectShort")})]}),O&&O.found&&n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"text-xs text-green-600",children:[i("openClaw.foundAt")," ",n.jsx("code",{className:"text-fg-secondary",children:O.summary.configPath})]}),O.summary.models&&n.jsxs("div",{className:"bg-surface-elevated/30 rounded-lg p-3",children:[n.jsx("div",{className:"text-xs text-fg-tertiary mb-2",children:i("openClaw.modelProvidersFound",{count:O.summary.models.providerCount})}),n.jsx("div",{className:"space-y-1",children:O.summary.models.providers.map(oe=>n.jsxs("div",{className:"flex items-center justify-between text-xs",children:[n.jsx("span",{className:"text-fg-secondary",children:oe.name}),n.jsxs("span",{className:"text-fg-tertiary",children:[i("openClaw.modelsCountSuffix",{count:oe.modelCount}),oe.baseUrl?i("openClaw.withBaseUrl",{url:oe.baseUrl}):""]})]},oe.name))})]}),O.summary.channels&&O.summary.channels.length>0&&n.jsx("div",{className:"bg-surface-elevated/30 rounded-lg p-3",children:n.jsxs("div",{className:"text-xs text-fg-tertiary mb-1",children:[i("openClaw.channelsPrefix")," ",O.summary.channels.join(", ")]})}),n.jsx("button",{onClick:()=>{ni()},disabled:J,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:i(J?"common:importing":"openClaw.importConfigs")})]}),Z&&n.jsx(Ua,{type:Z.type,text:Z.text})]})]})})]}),w==="execution"&&n.jsxs(n.Fragment,{children:[n.jsx(hi,{title:i("agentExecution.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("agentExecution.maxToolIterations")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("agentExecution.maxToolIterationsDesc")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"number",min:0,value:yn,onChange:oe=>{sn(Number(oe.target.value)),mn(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right"}),n.jsx("button",{disabled:In,onClick:async()=>{jn(!0),mn(null);try{const oe=await le.settings.updateAgent({maxToolIterations:yn});sn(oe.maxToolIterations),mn({type:"ok",text:i("agentExecution.saved")})}catch{mn({type:"err",text:i("agentExecution.failedToSave")})}jn(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(In?"common:saving":"common:save")})]})]}),Vt&&n.jsx(Ua,{type:Vt.type,text:Vt.text})]})}),n.jsx(hi,{title:i("cognitive.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("cognitive.description")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("cognitive.enabled")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("cognitive.enabledDesc")})]}),n.jsx("button",{onClick:()=>{Xn(!Vn),Ot(null)},className:`relative w-10 h-5 rounded-full transition-colors ${Vn?"bg-brand-500":"bg-fg-quaternary"}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${Vn?"translate-x-5":""}`})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("cognitive.maxDepth")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("cognitive.maxDepthDesc")})]}),n.jsxs("select",{value:Rr,onChange:oe=>{qe(Number(oe.target.value)),Ot(null)},className:"px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary",children:[n.jsxs("option",{value:1,children:["D1 — ",i("cognitive.depthD1")]}),n.jsxs("option",{value:2,children:["D2 — ",i("cognitive.depthD2")]}),n.jsxs("option",{value:3,children:["D3 — ",i("cognitive.depthD3")]})]})]}),n.jsx("div",{className:"flex items-center justify-end gap-2",children:n.jsx("button",{disabled:St,onClick:async()=>{_e(!0),Ot(null);try{const oe=await le.settings.updateAgent({cognitive:{enabled:Vn,maxDepth:Rr}});Xn(oe.cognitive.enabled),qe(oe.cognitive.maxDepth??1),Ot({type:"ok",text:i("cognitive.saved")})}catch{Ot({type:"err",text:i("cognitive.failedToSave")})}_e(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(St?"common:saving":"common:save")})}),Tt&&n.jsx(Ua,{type:Tt.type,text:Tt.text})]})})]}),w==="browser"&&n.jsxs(n.Fragment,{children:[n.jsxs(hi,{title:i("browserAutomation.title"),children:[n.jsxs("div",{className:`rounded-xl p-4 mb-4 flex items-start gap-3 ${Qn?"bg-green-500/10 border border-green-500/20":_n>0?"bg-blue-500/10 border border-blue-500/20":rr?"bg-amber-500/10 border border-amber-500/20":"bg-surface-elevated border border-border-default"}`,children:[n.jsx("div",{className:`mt-0.5 w-2.5 h-2.5 rounded-full shrink-0 ${Qn?"bg-green-400":_n>0?"bg-blue-400":rr?"bg-amber-400":"bg-gray-400"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:`text-sm font-semibold ${Qn?"text-green-400":_n>0?"text-blue-400":rr?"text-amber-400":"text-fg-secondary"}`,children:Qn?i("browserAutomation.modeExtension"):_n>0?i("browserAutomation.modeDebuggingPort",{port:_n}):i(rr?"browserAutomation.modeAutoClick":"browserAutomation.modeManual")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:Qn?i("browserAutomation.modeExtensionDesc"):_n>0?i("browserAutomation.modeDebuggingPortDesc"):i(rr?"browserAutomation.modeAutoClickDesc":"browserAutomation.modeManualDesc")})]})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4 mb-4",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.generalSettings")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.bringToFront")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.bringToFrontDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!Gt;Tn(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({bringToFront:oe});Tn(Ee.bringToFront),tn({type:"ok",text:i(oe?"browserAutomation.tabsForeground":"browserAutomation.tabsBackground")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),Tn(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Gt?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Gt?"translate-x-4":"translate-x-1"}`})})]}),n.jsxs("div",{className:"flex items-center justify-between border-t border-border-default pt-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.autoCloseTabs")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.autoCloseTabsDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!Fn;mr(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({autoCloseTabs:oe});mr(Ee.autoCloseTabs),tn({type:"ok",text:i("agentExecution.saved")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),mr(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Fn?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Fn?"translate-x-4":"translate-x-1"}`})})]})]}),n.jsxs("div",{className:`rounded-xl p-5 mb-4 transition-colors ${Qn?"bg-green-500/5 border border-green-500/20":"bg-surface-elevated"}`,children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStatus")}),n.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",i("browserAutomation.modeRecommended"),")"]})]}),n.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${Qn?"bg-green-500/20 text-green-400":"bg-gray-600/20 text-gray-400"}`,children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Qn?"bg-green-400":"bg-gray-400"}`}),i(Qn?"browserAutomation.extensionConnected":"browserAutomation.extensionDisconnected")]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("browserAutomation.extensionStatusDesc")}),Qn?n.jsxs("div",{className:"mt-3 flex items-center gap-1.5 text-xs text-green-400",children:[n.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),i("browserAutomation.extensionActiveNote")]}):n.jsxs("div",{className:"mt-4 space-y-3",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.extensionSetupTitle")}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"1"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep1")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep1Desc")}),n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{await le.settings.downloadExtensionZip()}catch{tn({type:"err",text:i("browserAutomation.extensionDownloadError")})}qt(!1)},className:"mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),i(It?"browserAutomation.extensionStep1Downloading":"browserAutomation.extensionStep1Btn")]})]})]}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"2"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep2")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep2Desc")}),n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{await le.settings.openExtensionsPage()}catch{tn({type:"err",text:i("browserAutomation.extensionOpenError")})}qt(!1)},className:"mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),i("browserAutomation.extensionStep2Btn")]})]})]}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"3"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep3")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep3Desc")})]})]})]})]}),!Qn&&n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.fallbackModes")}),n.jsx("div",{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex-1 mr-4",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.autoClickAllowDialog")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.autoClickAllowDialogDesc")}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-2 space-y-0.5",children:[n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogMacNote")}),n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogWinNote")}),n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogLinuxNote")})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{const oe=await le.settings.testAutoClick(),Ee={success:{type:"ok",text:i("browserAutomation.autoClickTestSuccess",{title:oe.pageTitle||"example.com"})},no_permission:{type:"err",text:i("browserAutomation.autoClickTestNoPermission")},chrome_not_running:{type:"err",text:i("browserAutomation.autoClickTestChromeNotRunning")},unsupported:{type:"err",text:i("browserAutomation.autoClickTestUnsupported")},error:{type:"err",text:i("browserAutomation.autoClickTestError",{error:oe.error||"unknown"})}};tn(Ee[oe.clickResult]??{type:"err",text:oe.clickResult})}catch{tn({type:"err",text:i("browserAutomation.autoClickTestError",{error:"request failed"})})}qt(!1)},className:"px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:i(It?"browserAutomation.autoClickTesting":"browserAutomation.autoClickTest")}),n.jsx("button",{onClick:async()=>{const oe=!rr;fr(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({autoClickAllowDialog:oe});fr(Ee.autoClickAllowDialog),tn({type:"ok",text:i("agentExecution.saved")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),fr(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${rr?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${rr?"translate-x-4":"translate-x-1"}`})})]})]})}),n.jsx("div",{className:"border-t border-border-default pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.remoteDebuggingPort")}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[i("browserAutomation.remoteDebuggingPortDescLead")," ",n.jsx("code",{className:"text-fg-secondary bg-surface-primary px-1 rounded",children:"--remote-debugging-port=9222"})," ",i("browserAutomation.remoteDebuggingPortDescTail")]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"number",min:0,max:65535,value:_n,onChange:oe=>{Sn(Number(oe.target.value)),tn(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right",placeholder:"0"}),n.jsx("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{const oe=await le.settings.updateBrowser({remoteDebuggingPort:_n});Sn(oe.remoteDebuggingPort),tn({type:"ok",text:oe.remoteDebuggingPort>0?i("browserAutomation.usingPort",{port:oe.remoteDebuggingPort}):i("browserAutomation.usingAutoConnect")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")})}qt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(It?"common:saving":"common:save")})]})]})})]}),Jt&&n.jsx("div",{className:"mt-4",children:n.jsx(Ua,{type:Jt.type,text:Jt.text})})]}),!1]}),w==="search"&&n.jsx(n.Fragment,{children:n.jsx(hi,{title:i("searchApi.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("searchApi.description")}),[{id:"serper",label:i("searchApi.serper"),hint:i("searchApi.serperHint"),field:"serperApiKey"},{id:"tavily",label:i("searchApi.tavily"),hint:i("searchApi.tavilyHint"),field:"tavilyApiKey"},{id:"bing",label:i("searchApi.bing"),hint:i("searchApi.bingHint"),field:"bingApiKey"},{id:"google",label:i("searchApi.google"),hint:i("searchApi.googleHint"),field:"googleSearchApiKey",extraField:"googleSearchCx",extraPlaceholder:i("searchApi.googleCxPlaceholder")},{id:"serpapi",label:i("searchApi.serpapi"),hint:i("searchApi.serpapiHint"),field:"serpApiKey"},{id:"brave",label:i("searchApi.brave"),hint:i("searchApi.braveHint"),field:"braveApiKey"},{id:"exa",label:i("searchApi.exa"),hint:i("searchApi.exaHint"),field:"exaApiKey"},{id:"bocha",label:i("searchApi.bocha"),hint:i("searchApi.bochaHint"),field:"bochaApiKey"}].map((oe,Ee)=>n.jsxs("div",{className:Ee>0?"border-t border-border-default pt-4":"",children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:oe.label}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:oe.hint})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[An?.[oe.id]?.configured&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-xs text-green-600",children:i("searchApi.configured")}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:An[oe.id].preview})]}),An&&!An[oe.id]?.configured&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:i("searchApi.notConfigured")})]})]})]}),n.jsx("input",{type:"password",value:an[oe.field],onChange:et=>ye({...an,[oe.field]:et.target.value}),placeholder:An?.[oe.id]?.configured?i("modelProviders.apiKeyPlaceholder"):i("searchApi.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),oe.extraField&&n.jsx("input",{type:"text",value:an[oe.extraField],onChange:et=>ye({...an,[oe.extraField]:et.target.value}),placeholder:oe.extraPlaceholder??"",className:"w-full mt-2 px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]},oe.id)),n.jsx("div",{className:"text-xs text-fg-tertiary italic",children:i("searchApi.freeBackend")}),n.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border-default",children:[Ht&&n.jsx(Ua,{type:Ht.type,text:Ht.text}),!Ht&&n.jsx("div",{}),n.jsx("button",{disabled:at||!an.serperApiKey&&!an.tavilyApiKey&&!an.bingApiKey&&!an.googleSearchApiKey&&!an.googleSearchCx&&!an.serpApiKey&&!an.braveApiKey&&!an.exaApiKey&&!an.bochaApiKey,onClick:()=>{ms()},className:"px-4 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(at?"common:saving":"common:save")})]})]})})}),w==="storage"&&n.jsx(n.Fragment,{children:n.jsx(hi,{title:i("dataStorage.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[Zn&&!Mt&&n.jsx("div",{className:"text-sm text-fg-tertiary",children:i("dataStorage.scanning")}),Mt&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-fg-primary",children:td(Mt.totalSize,i)}),n.jsx("div",{className:"text-xs text-fg-tertiary font-mono mt-0.5",children:Mt.dataDir})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>ga(),disabled:Zn,className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors disabled:opacity-40",children:i(Zn?"dataStorage.scanning":"common:refresh")}),n.jsx("button",{onClick:()=>{le.system.openPath(Mt.dataDir)},className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors",children:i("dataStorage.openInFinder")})]})]}),n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:i("dataStorage.storageBreakdown")}),n.jsx("div",{className:"space-y-1.5",children:Mt.breakdown.filter(oe=>oe.size>0).map(oe=>n.jsxs("div",{className:"flex items-center justify-between py-1.5 px-3 rounded-lg bg-surface-elevated/40",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"text-sm text-fg-primary",children:oe.name}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-2",children:oe.description})]}),n.jsx("span",{className:"text-sm font-medium text-fg-secondary tabular-nums shrink-0 ml-3",children:td(oe.size,i)})]},oe.name))})]}),Mt.agents.length>0&&n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:i("dataStorage.agentStorage",{count:Mt.agents.length})}),n.jsx("div",{className:"space-y-1",children:Mt.agents.map(oe=>{const Ee=Jn.has(oe.id);return n.jsxs("div",{className:"rounded-lg bg-surface-elevated/40 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between py-2 px-3 cursor-pointer hover:bg-surface-elevated/70",onClick:()=>Pn(et=>{const hn=new Set(et);return hn.has(oe.id)?hn.delete(oe.id):hn.add(oe.id),hn}),children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:Ee?"▼":"▶"}),n.jsx("button",{onClick:et=>{et.stopPropagation(),pt.navigate(Te.TEAM,{agentId:oe.id})},className:"text-sm text-brand-500 hover:text-brand-400 truncate",children:oe.name}),n.jsx("span",{className:"text-[10px] text-fg-tertiary font-mono truncate",children:oe.id})]}),n.jsx("span",{className:"text-xs font-medium text-fg-secondary tabular-nums shrink-0 ml-3",children:td(oe.size,i)})]}),Ee&&n.jsxs("div",{className:"px-3 pb-2 pt-0.5 space-y-0.5",children:[oe.subItems.filter(et=>et.size>0).map(et=>n.jsxs("div",{className:"flex items-center justify-between text-xs py-0.5 pl-5",children:[n.jsx("span",{className:"text-fg-tertiary",children:et.name}),n.jsx("span",{className:"text-fg-secondary tabular-nums",children:td(et.size,i)})]},et.name)),n.jsx("div",{className:"pl-5 pt-1",children:n.jsx("button",{onClick:()=>{le.system.openPath(Mt.dataDir+"/agents/"+oe.id)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary underline",children:i("dataStorage.openFolder")})})]})]},oe.id)})})]}),on&&(on.orphanAgents.length>0||on.orphanTeams.length>0)&&n.jsx(KG,{orphanInfo:on,dataDir:Mt.dataDir,onPurged:ga,formatBytes:oe=>td(oe,i)})]})]})})}),w==="users"&&n.jsx(UG,{authUser:r}),w==="remote"&&n.jsx(GG,{})]}),n.jsx("div",{className:"h-8"})]})]})]})}const FG=["owner","admin","member","guest"],qG={owner:"bg-amber-500/10 text-amber-600 border-amber-500/30",admin:"bg-brand-500/10 text-brand-500 border-brand-500/30",member:"bg-green-500/10 text-green-600 border-green-500/30",guest:"bg-gray-500/10 text-gray-500 border-gray-500/30"};function UG({authUser:e}){const{t}=ft(["settings","common"]),[r,s]=x.useState([]),[a,i]=x.useState(null),[l,d]=x.useState(""),[u,m]=x.useState(""),[h,p]=x.useState(""),[y,g]=x.useState(null),[v,j]=x.useState(""),[C,w]=x.useState(null),[N,S]=x.useState(null),[T,M]=x.useState(null),D=x.useCallback(()=>{le.users.list(e?.orgId).then(U=>s(U.users)).catch(()=>{})},[e?.orgId]);x.useEffect(()=>{D()},[D]);const I=U=>{i(U.id),d(U.name),m(U.role),p(U.email??""),M(null)},$=async()=>{if(a)try{await le.users.update(a,{name:l,role:u,email:h||void 0}),i(null),M({type:"ok",text:t("settings:userManagement.updateSuccess")}),D()}catch(U){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(U)}`})}},B=async()=>{if(!(!y||!v))try{await le.users.resetPassword(y,v),g(null),j(""),M({type:"ok",text:t("settings:userManagement.resetSuccess")})}catch(U){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(U)}`})}},R=async U=>{if(U===e?.id){M({type:"err",text:t("settings:userManagement.cannotDeleteSelf")}),w(null);return}if(r.find(F=>F.id===U)?.role==="owner"){M({type:"err",text:t("settings:userManagement.cannotDeleteOwner")}),w(null);return}try{await le.users.remove(U),w(null),M({type:"ok",text:t("settings:userManagement.deleteSuccess")}),D()}catch(F){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(F)}`})}};return n.jsx(hi,{title:t("settings:userManagement.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:[T&&n.jsx("div",{className:`px-4 py-2 text-xs border-b ${T.type==="ok"?"bg-green-500/10 text-green-600 border-green-500/20":"bg-red-500/10 text-red-500 border-red-500/20"}`,children:T.text}),N&&n.jsxs("div",{className:"px-4 py-3 bg-brand-500/5 border-b border-brand-500/20 flex items-center gap-3",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary mb-1",children:t("settings:userManagement.copyInviteLink")}),n.jsx("code",{className:"text-[10px] text-brand-500 bg-surface-elevated px-2 py-1 rounded block truncate",children:N})]}),n.jsx("button",{onClick:()=>{navigator.clipboard.writeText(N),M({type:"ok",text:t("settings:userManagement.linkCopied")})},className:"shrink-0 px-3 py-1.5 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium",children:t("settings:userManagement.copy")}),n.jsx("button",{onClick:()=>S(null),className:"shrink-0 text-fg-tertiary hover:text-fg-secondary text-sm",children:"×"})]}),n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border-default/60 text-fg-tertiary text-[11px] uppercase tracking-wider",children:[n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.name")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.email")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.role")}),n.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:t("settings:userManagement.actions")})]})}),n.jsxs("tbody",{children:[r.length===0&&n.jsx("tr",{children:n.jsx("td",{colSpan:4,className:"px-4 py-6 text-center text-fg-tertiary text-xs",children:t("settings:userManagement.noUsers")})}),r.map(U=>{const W=a===U.id,F=y===U.id,L=C===U.id,z=U.id===e?.id,E=U.role==="owner";return n.jsxs("tr",{className:"border-b border-border-default/40 last:border-b-0 hover:bg-surface-elevated/40 transition-colors",children:[n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("input",{value:l,onChange:_=>d(_.target.value),className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-fg-primary font-medium text-xs",children:U.name}),z&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500",children:"you"})]})}),n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("input",{value:h,onChange:_=>p(_.target.value),placeholder:"email@example.com",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):n.jsx("span",{className:"text-fg-secondary text-xs",children:U.email||"—"})}),n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("select",{value:u,onChange:_=>m(_.target.value),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50",children:FG.map(_=>n.jsx("option",{value:_,children:t(`settings:userManagement.roles.${_}`)},_))}):n.jsx("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full border font-medium ${qG[U.role]??""}`,children:t(`settings:userManagement.roles.${U.role}`)})}),n.jsx("td",{className:"px-4 py-2.5 text-right",children:W?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("button",{onClick:()=>i(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:$,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium",children:t("settings:userManagement.save")})]}):F?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("input",{type:"password",value:v,onChange:_=>j(_.target.value),placeholder:t("settings:userManagement.newPassword"),autoFocus:!0,className:"w-32 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{onClick:()=>{g(null),j("")},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:B,disabled:v.length<6,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium disabled:opacity-40",children:t("settings:userManagement.confirmReset")})]}):L?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("span",{className:"text-[10px] text-red-500",children:t("settings:userManagement.confirmDelete")}),n.jsx("button",{onClick:()=>w(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:()=>R(U.id),className:"text-[11px] text-red-500 hover:text-red-400 font-medium",children:t("settings:userManagement.deleteUser")})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[n.jsx("button",{onClick:()=>I(U),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:t("settings:userManagement.editUser")}),U.email&&n.jsx("button",{onClick:()=>{g(U.id),j(""),M(null)},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:t("settings:userManagement.resetPassword")}),U.email&&!E&&!U.hasJoined&&n.jsx("button",{onClick:async()=>{try{const{inviteToken:_}=await le.users.reinvite(U.id),G=`${window.location.origin}/#invite?token=${_}`;S(G),M({type:"ok",text:t("settings:userManagement.inviteLinkGenerated")})}catch(_){M({type:"err",text:String(_)})}},className:"text-[11px] text-brand-400 hover:text-brand-500 px-1.5 py-0.5 rounded hover:bg-brand-500/10",children:t("settings:userManagement.inviteLink")}),!E&&!z&&n.jsx("button",{onClick:()=>{w(U.id),M(null)},className:"text-[11px] text-red-400 hover:text-red-500 px-1.5 py-0.5 rounded hover:bg-red-500/10",children:t("settings:userManagement.deleteUser")})]})})]},U.id)})]})]})]})})}function VG({providerName:e,addModelForm:t,setAddModelForm:r,addModelSaving:s,onAdd:a,onCancel:i,t:l}){const[d,u]=x.useState([]),[m,h]=x.useState(!1),[p,y]=x.useState(!1),g=async()=>{h(!0);try{const v=await le.modelCatalog.getByProvider(e);u(v.models),y(!0)}catch{u([])}finally{h(!1)}};return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"text-[10px] text-fg-secondary",children:l("modelProviders.addModelTitle")}),n.jsx("button",{onClick:()=>{g()},disabled:m,className:"text-[10px] text-brand-500 hover:text-brand-400 disabled:opacity-40 transition-colors",children:m?"...":l("modelProviders.browseFromCatalog")})]}),p&&d.length>0&&n.jsx("div",{className:"border border-border-default rounded-lg p-2 mb-2",children:n.jsx(ch,{provider:e,models:d,selectedModel:t.id,onSelect:v=>{const j=d.find(C=>C.id===v);j&&r(C=>({...C,id:j.id,name:j.id,contextWindow:j.maxInputTokens,maxOutputTokens:j.maxOutputTokens,costInput:j.inputCostPer1MTokens,costOutput:j.outputCostPer1MTokens,reasoning:j.capabilities.reasoning,vision:j.capabilities.vision}))},compact:!0,maxVisible:5})}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[n.jsx("input",{type:"text",placeholder:l("modelProviders.modelId"),value:t.id,onChange:v=>r({...t,id:v.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"text",placeholder:l("modelProviders.displayName"),value:t.name,onChange:v=>r({...t,name:v.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"number",placeholder:l("modelProviders.placeholderContextTokens"),value:t.contextWindow,onChange:v=>r({...t,contextWindow:Number(v.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"number",placeholder:l("modelProviders.maxOutput"),value:t.maxOutputTokens,onChange:v=>r({...t,maxOutputTokens:Number(v.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modelProviders.costPerMillionIn")}),n.jsx("input",{type:"number",step:"0.01",value:t.costInput,onChange:v=>r({...t,costInput:Number(v.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modelProviders.costPerMillionOut")}),n.jsx("input",{type:"number",step:"0.01",value:t.costOutput,onChange:v=>r({...t,costOutput:Number(v.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.reasoning,onChange:v=>r({...t,reasoning:v.target.checked}),className:"rounded"}),l("modelProviders.reasoning")]}),n.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.vision,onChange:v=>r({...t,vision:v.target.checked}),className:"rounded"}),l("modelProviders.vision")]}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:a,disabled:s||!t.id||!t.name,className:"px-2 py-1 text-[10px] bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded transition-colors",children:l(s?"modelProviders.adding":"common:create")}),n.jsx("button",{onClick:i,className:"px-2 py-1 text-[10px] border border-border-default text-fg-secondary hover:bg-surface-elevated rounded transition-colors",children:l("common:cancel")})]})]})}function Du({step:e,title:t,description:r,active:s,children:a}){return n.jsxs("div",{className:`rounded-xl p-4 space-y-3 transition-colors ${s?"ring-1 ring-brand-500/60 bg-brand-500/10":"bg-surface-elevated"}`,children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("span",{className:"flex-none w-6 h-6 rounded-full bg-surface-overlay flex items-center justify-center text-xs font-bold text-fg-secondary",children:e}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:t}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r})]})]}),a&&n.jsx("div",{className:"pl-9",children:a})]})}function Ua({type:e,text:t}){return n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${e==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:t})}function hi({title:e,children:t}){return n.jsxs("section",{children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:e}),n.jsx("div",{className:"space-y-4",children:t})]})}function Ux({label:e,value:t,color:r}){const s=r==="green"?"bg-green-500/10 text-green-600":"bg-brand-500/10 text-brand-500";return n.jsxs("div",{className:`rounded-xl px-5 py-4 ${s}`,children:[n.jsx("div",{className:"text-2xl font-bold",children:t}),n.jsx("div",{className:"text-xs mt-1 opacity-70",children:e})]})}function ml({label:e,value:t}){return n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5 truncate",children:t})]})}function td(e,t){if(e===0)return t?t("dataStorage.bytesZero"):"0 B";const r=t?[t("dataStorage.unitB"),t("dataStorage.unitKB"),t("dataStorage.unitMB"),t("dataStorage.unitGB")]:["B","KB","MB","GB"],s=Math.min(Math.floor(Math.log(e)/Math.log(1024)),r.length-1),a=e/Math.pow(1024,s);return`${a<10?a.toFixed(1):Math.round(a)} ${r[s]}`}function KG({orphanInfo:e,dataDir:t,onPurged:r,formatBytes:s}){const{t:a}=ft(["settings","common"]),i=[...e.orphanAgents.map(w=>({...w,kind:"agent"})),...e.orphanTeams.map(w=>({...w,kind:"team"}))],[l,d]=x.useState(new Set),[u,m]=x.useState(!1),[h,p]=x.useState(null),y=w=>d(N=>{const S=new Set(N);return S.has(w)?S.delete(w):S.add(w),S}),g=l.size===i.length&&i.length>0,v=()=>d(g?new Set:new Set(i.map(w=>w.id))),j=i.filter(w=>l.has(w.id)).reduce((w,N)=>w+N.size,0),C=async w=>{m(!0),p(null);try{const N=await le.system.purgeOrphans(w),S=N.purgedAgents.length+N.purgedTeams.length,T=a("dataStorage.cleaned",{count:S,size:s(N.freedBytes)});p(N.failures.length?a("dataStorage.cleanedWithFailureNote",{base:T,count:N.failures.length}):T),d(new Set),r()}catch{p(a("dataStorage.cleanupFailed"))}finally{m(!1)}};return n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-amber-500 mb-2",children:a("dataStorage.orphanedDirectories")}),n.jsxs("p",{className:"text-xs text-fg-tertiary mb-3",children:[a("dataStorage.orphanedDesc")," ",a("dataStorage.orphanedTotal",{size:s(e.totalOrphanSize),count:i.length})]}),n.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[n.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary cursor-pointer select-none",children:[n.jsx("input",{type:"checkbox",checked:g,onChange:v,className:"rounded"}),a("common:selectAll")]}),l.size>0&&n.jsx("span",{className:"text-[10px] text-fg-secondary",children:a("dataStorage.selectedWithSize",{count:l.size,size:s(j)})})]}),n.jsx("div",{className:"space-y-0.5 mb-3 max-h-52 overflow-y-auto",children:i.map(w=>n.jsxs("div",{className:`flex items-center gap-2 text-xs py-1.5 px-2 rounded transition-colors ${l.has(w.id)?"bg-amber-500/10":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:[n.jsx("input",{type:"checkbox",checked:l.has(w.id),onChange:()=>y(w.id),className:"rounded shrink-0"}),w.kind==="team"&&n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:a("dataStorage.teamKind")}),n.jsx("span",{className:"text-fg-tertiary font-mono truncate min-w-0 flex-1",children:w.id}),n.jsx("span",{className:"text-fg-secondary tabular-nums shrink-0",children:s(w.size)}),n.jsx("button",{onClick:()=>{le.system.openPath(w.path)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary shrink-0 underline",children:a("common:open")})]},w.id))}),n.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[l.size>0&&n.jsx("button",{disabled:u,onClick:()=>{C([...l])},className:"px-3 py-1.5 text-xs bg-amber-600 hover:bg-amber-500 text-white rounded-lg transition-colors disabled:opacity-50",children:u?a("dataStorage.cleaning"):a("dataStorage.cleanSelected",{size:s(j)})}),n.jsx("button",{disabled:u,onClick:()=>{C()},className:"px-3 py-1.5 text-xs border border-amber-600/50 hover:bg-amber-600/10 text-amber-500 rounded-lg transition-colors disabled:opacity-50",children:u?a("dataStorage.cleaning"):a("dataStorage.cleanAll",{size:s(e.totalOrphanSize)})})]}),h&&n.jsx("div",{className:"text-xs text-fg-tertiary mt-2",children:h})]})}function WG({authUser:e,onClose:t,onSaved:r}){const{t:s}=ft("common"),[a,i]=x.useState(e.name||""),[l,d]=x.useState(e.email||""),[u,m]=x.useState(!1),[h,p]=x.useState(""),[y,g]=x.useState(e.avatarUrl),v=async j=>{if(j.preventDefault(),!a.trim()){p(s("profile.nameRequired"));return}if(l&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(l.trim())){p(s("profile.invalidEmail"));return}m(!0),p("");try{const{user:C}=await le.auth.updateProfile(a.trim(),l.trim());r({...C,avatarUrl:y??C.avatarUrl})}catch{p(s("profile.failedToSave"))}finally{m(!1)}};return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:t,children:n.jsxs("form",{onSubmit:v,className:"bg-surface-secondary border border-border-default rounded-xl p-6 w-[400px] shadow-2xl",onClick:j=>j.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold mb-5",children:s("profile.editProfile")}),n.jsx("div",{className:"flex justify-center mb-5",children:n.jsx(g6,{currentUrl:y,name:a,size:72,targetType:"user",targetId:e.id,onUploaded:j=>g(j)})}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-tertiary font-medium mb-1",children:s("profile.name")}),n.jsx("input",{value:a,onChange:j=>i(j.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-tertiary font-medium mb-1",children:s("profile.email")}),n.jsx("input",{value:l,onChange:j=>d(j.target.value),type:"email",className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none"})]}),h&&n.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h})]}),n.jsxs("div",{className:"flex justify-end gap-3 mt-5",children:[n.jsx("button",{type:"button",onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("cancel")}),n.jsx("button",{type:"submit",disabled:u,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white rounded-lg",children:s(u?"saving":"save")})]})]})})}function GG(){const{t:e}=ft(["settings","common"]),[t,r]=x.useState(null),[s,a]=x.useState(!0),[i,l]=x.useState(!1),[d,u]=x.useState(null),[m,h]=x.useState(!1),p=m6(),y=x.useCallback(async()=>{try{const N=await le.settings.getRemote();r(N)}catch{r(null)}finally{a(!1)}},[]);x.useEffect(()=>{y()},[y]),x.useEffect(()=>pn.on("remote:status",N=>{const S=N.payload;S&&(r(S),l(!1))}),[]);const g=async()=>{l(!0),u(null);try{t?.enabled?(await le.settings.disableRemote(),await y(),l(!1)):(Un.isAuthenticated()||await ki(),await le.settings.enableRemote())}catch(N){u(String(N instanceof Error?N.message:N)),l(!1)}},v=async()=>{try{await ki(),await y()}catch{}},j=()=>{t?.remoteUrl&&(navigator.clipboard.writeText(t.remoteUrl),h(!0),setTimeout(()=>h(!1),2e3))},C=i||t?.enabled&&!t?.connected&&t?.state!=="idle",w=t?.remoteUrl??null;return n.jsx(hi,{title:e("settings:remoteAccess.title"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-content-secondary",children:e("settings:remoteAccess.description")}),Un.isAuthenticated()?n.jsxs("div",{className:"flex items-center gap-2 text-sm text-content-secondary",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),e("settings:remoteAccess.signedInAs")," ",n.jsx("strong",{children:p?.username??p?.displayName})]}):n.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-amber-500/10 border border-amber-500/20",children:[n.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n.jsx("span",{className:"text-sm text-amber-600 dark:text-amber-400",children:e("settings:remoteAccess.loginRequired")}),n.jsx("button",{onClick:v,className:"ml-auto px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",children:e("settings:remoteAccess.signIn")})]}),Un.isAuthenticated()&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:g,disabled:i||s,className:`relative w-12 h-6 rounded-full transition-colors duration-200 ${t?.enabled?"bg-brand-600":"bg-gray-300 dark:bg-gray-600"} ${i||s?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:n.jsx("span",{className:`block w-5 h-5 bg-white rounded-full shadow transform transition-transform duration-200 ${t?.enabled?"translate-x-6":"translate-x-0.5"}`})}),n.jsx("span",{className:"text-sm font-medium",children:C?e("settings:remoteAccess.connecting"):t?.enabled?e("settings:remoteAccess.enabled"):e("settings:remoteAccess.disabled")}),C&&n.jsx(Jk,{})]}),t?.enabled&&n.jsxs("div",{className:`flex items-center gap-1.5 text-xs ${t.connected?"text-green-600 dark:text-green-400":t.state==="registering"||t.state==="connecting"?"text-blue-600 dark:text-blue-400":"text-amber-600 dark:text-amber-400"}`,children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${t.connected?"bg-green-500 animate-pulse":t.state==="registering"||t.state==="connecting"?"bg-blue-500 animate-pulse":"bg-amber-500"}`}),t.connected?e("settings:remoteAccess.connected"):t.state==="registering"?e("settings:remoteAccess.registering"):t.state==="connecting"?e("settings:remoteAccess.connecting"):e("settings:remoteAccess.disconnected"),t.connected&&t.peerCount>0&&n.jsxs(n.Fragment,{children:[" · ",e("settings:remoteAccess.peerCount",{count:t.peerCount})]}),(t.state==="registering"||t.state==="connecting")&&n.jsx(Jk,{})]})]}),d&&n.jsx("div",{className:"p-2 rounded-lg bg-red-500/10 text-red-500 text-sm",children:d}),t?.enabled&&t.peers&&t.peers.length>0&&n.jsxs("div",{className:"p-4 rounded-lg bg-surface-elevated border border-border-default space-y-2",children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.connectedPeers")}),n.jsx("div",{className:"space-y-2 mt-1",children:t.peers.map(N=>n.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg bg-surface-inset",children:[n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${N.transport==="p2p"?"bg-green-500":N.transport==="relay"?"bg-blue-500":"bg-amber-500 animate-pulse"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"text-sm font-mono text-content-primary truncate",children:[N.peerId.slice(0,8),"..."]}),n.jsx("div",{className:"text-xs text-content-tertiary",children:e("settings:remoteAccess.connectedSince",{time:new Date(N.connectedAt).toLocaleTimeString()})})]}),n.jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded-full ${N.transport==="p2p"?"bg-green-500/10 text-green-600 dark:text-green-400":N.transport==="relay"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"}`,children:N.transport==="p2p"?"P2P":N.transport==="relay"?"Relay":e("settings:remoteAccess.peerConnecting")})]},N.peerId))})]}),t?.enabled&&t.remoteUrl&&n.jsxs("div",{className:"p-4 rounded-lg bg-surface-elevated border border-border-default space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.url")}),n.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[n.jsx("code",{className:"flex-1 px-3 py-1.5 text-sm bg-surface-inset rounded font-mono truncate",children:t.remoteUrl}),n.jsx("button",{onClick:j,className:`px-2 py-1.5 text-xs border rounded transition-colors ${m?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:e(m?"settings:remoteAccess.copied":"settings:remoteAccess.copy")})]})]}),w&&n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.qrCode")}),n.jsx("p",{className:"text-xs text-content-secondary mt-0.5 mb-2",children:e("settings:remoteAccess.scanQr")}),n.jsx(YG,{url:w})]})]})]})]})})}function Jk(){return n.jsxs("svg",{className:"w-4 h-4 animate-spin text-content-secondary",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function YG({url:e}){const t=x.useRef(null),[r,s]=x.useState(!1);return x.useEffect(()=>{const a=t.current;a&&(s(!1),$d(()=>import("./browser-DC4fgOje.js").then(i=>i.b),[]).then(i=>{i.toCanvas(a,e,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"},errorCorrectionLevel:"M"})}).catch(()=>s(!0)))},[e]),r?n.jsx("a",{href:e,target:"_blank",rel:"noopener",className:"text-sm text-brand-500 underline",children:e}):n.jsx("div",{className:"inline-block p-2 bg-white rounded-lg",children:n.jsx("canvas",{ref:t,className:"block",style:{width:160,height:160}})})}const dh=new Map;function Xl(e,t){dh.has(e)||dh.set(e,t().catch(()=>{}))}function rc(e){const t=dh.get(e);return dh.delete(e),t}const Ra={builderArtifacts:"builder.artifacts",builderAgents:"builder.agents",builderHubMyItems:"builder.hubMyItems",builderInstalled:"builder.installed",hubAgents:"hub.agents",hubTeams:"hub.teams",hubSkills:"hub.skills"};function XG(e){const t=e.indexOf(".markus/builder-artifacts/");return t>=0?"~/"+e.slice(t):e}const QG=[{id:"hireAgent",icon:"✦",color:"from-brand-500 to-purple-600",borderColor:"border-brand-500/30 hover:border-brand-400/50",bgColor:"bg-brand-500/10"},{id:"buildTeam",icon:"◈",color:"from-blue-500 to-blue-600",borderColor:"border-blue-500/30 hover:border-blue-400/50",bgColor:"bg-blue-500/10"},{id:"createSkill",icon:"⬡",color:"from-green-500 to-green-600",borderColor:"border-green-500/30 hover:border-green-400/50",bgColor:"bg-green-500/10"}],ej={agent:{icon:"✦",color:"text-brand-500",bg:"bg-brand-500/10"},team:{icon:"◈",color:"text-blue-600",bg:"bg-blue-500/10"},skill:{icon:"⬡",color:"text-green-600",bg:"bg-green-500/10"}};function tj({title:e,message:t,cancelLabel:r,confirmLabel:s,onConfirm:a,onCancel:i}){return n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:i,children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-6 max-w-sm mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{className:"w-5 h-5 text-red-500",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),n.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:t})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:i,className:"px-4 py-1.5 text-xs text-fg-secondary hover:text-fg-primary border border-border-default hover:border-gray-600 rounded-lg transition-colors",children:r}),n.jsx("button",{onClick:a,className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-500 text-white rounded-lg transition-colors",children:s})]})]})})}function ZG(){const[e,t]=x.useState(()=>{const s=window.location.hash.slice(1).split("/");return s[0]==="builder"&&s[1]&&s[2]?{type:s[1],name:decodeURIComponent(s[2])}:null});return x.useEffect(()=>{const r=()=>{const a=window.location.hash.slice(1).split("/");a[0]==="builder"&&a[1]&&a[2]?t({type:a[1],name:decodeURIComponent(a[2])}):t(null)};return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]),e}function QS({authUser:e}={}){const{t}=ft(["builder","common"]),r=Ds(),s=ZG(),[a,i]=x.useState([]),[l,d]=x.useState([]),[u,m]=x.useState(!1),[h,p]=x.useState("all"),[y,g]=x.useState(null),[v,j]=x.useState(new Map),[C,w]=x.useState(null),[N,S]=x.useState(new Map),[T,M]=x.useState(null),[D,I]=x.useState(null),[$,B]=x.useState(null),R=x.useCallback(()=>{m(!0),Promise.all([(rc(Ra.builderArtifacts)??le.builder.artifacts.list()).then(V=>V?.artifacts??[]).catch(()=>[]),(rc(Ra.builderAgents)??le.agents.list()).then(V=>V?.agents??[]).catch(()=>[]),(rc(Ra.builderHubMyItems)??Un.myItems()).then(V=>V?.items??[]).catch(()=>[]),(rc(Ra.builderInstalled)??le.builder.artifacts.installed()).then(V=>V?.installed??{}).catch(()=>({}))]).then(([V,O,q,J])=>{if(d(V),i(O),q.length>0){const Z=new Map;for(const Y of q){const ee=Y.itemType==="agent"?"agent":Y.itemType==="team"?"team":"skill";for(const ae of V)ae.type===ee&&(Y.slug===ae.name||Y.name===(ae.meta.displayName||ae.meta.name||ae.name))&&Z.set(`${ae.type}/${ae.name}`,{id:Y.id,name:Y.name,slug:Y.slug||ae.name,version:Y.version||"1.0.0"})}Z.size>0&&S(Y=>{const ee=new Map(Y);for(const[ae,Q]of Z)ee.set(ae,Q);return ee})}const H=new Map;for(const Z of V){const Y=`${Z.type}/${Z.name}`,ee=J[Y];ee&&H.set(Y,{agentId:ee.agentId,agentIds:ee.agentIds,teamId:ee.teamId})}j(H)}).finally(()=>m(!1))},[]);x.useEffect(()=>{R();const V=O=>{O.detail?.page===Te.BUILDER&&R()};return window.addEventListener("markus:navigate",V),()=>window.removeEventListener("markus:navigate",V)},[R]);const U=V=>{const O=a.find(q=>q.role==="Secretary"||q.name==="Secretary");O?pt.navigate(Te.TEAM,{agentId:O.id,prefillMessage:V}):pt.navigate(Te.TEAM,{prefillMessage:V})},W=async V=>{const O=`${V.type}/${V.name}`;if(!v.has(O)){g({key:O,action:"install"});try{const q=await le.builder.artifacts.install(V.type,V.name),J={};q.agent&&typeof q.agent=="object"&&(J.agentId=q.agent.id),q.team&&typeof q.team=="object"&&(J.teamId=q.team.id),Array.isArray(q.agents)&&(J.agentIds=q.agents.map(H=>H.id)),j(H=>new Map(H).set(O,J)),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Install failed:",q),alert(t("installFailed",{error:String(q)}))}finally{g(null)}}},F=async V=>{const O=`${V.type}/${V.name}`;if(v.has(O)){g({key:O,action:"uninstall"});try{await le.builder.artifacts.uninstall(V.type,V.name),j(q=>{const J=new Map(q);return J.delete(O),J}),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Uninstall failed:",q),alert(t("uninstallFailed",{error:String(q)}))}finally{g(null)}}},L=async(V,O)=>{const q=`${V.type}/${V.name}`;g({key:q,action:"share"});try{const J=await le.builder.artifacts.get(V.type,V.name),H=V.meta.displayName||V.meta.name||V.name,Z=V.meta.description||"",Y=V.meta.category||"general",ee=Array.isArray(V.meta.tags)?V.meta.tags:[],ae=V.name;let Q=V.meta.icon||void 0;const me=V.meta.version||"1.0.0";if(Q&&!Q.startsWith("http")&&/\.(png|jpe?g|gif|webp|svg)$/i.test(Q)){const xe=Q.split("/").pop()??Q;try{const Pe=await fetch(`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(xe)}`);if(Pe.ok){const Ce=await Pe.blob(),Ye=new File([Ce],xe,{type:Ce.type}),Qe=await Un.uploadImage(Ye);Qe?.url&&(Q=Qe.url)}}catch{}}let Ae;const Me=[],He=Array.isArray(V.meta.screenshots)?V.meta.screenshots:[];for(let xe=0;xe<He.length;xe++){const Pe=He[xe],Ce=Pe.split("/").pop()??Pe;try{const Ye=await fetch(`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(Ce)}`);if(Ye.ok){const Qe=await Ye.blob(),ct=new File([Qe],Ce,{type:Qe.type}),st=await Un.uploadImage(ct);st?.url&&(Me.push({url:st.url,alt:Ce,order:xe}),(xe===0||V.meta.thumbnail===Pe)&&(Ae=st.url))}}catch{}}const je=await Un.publishViaProxy({itemType:V.type==="team"?"team":V.type==="skill"?"skill":"agent",name:H,slug:ae,description:Z,category:Y,tags:ee,icon:Q,version:me,config:V.meta,files:J.files&&Object.keys(J.files).length>0?J.files:void 0,thumbnailUrl:Ae,images:Me.length>0?Me:void 0,priceCents:O?.priceCents,donationsEnabled:O?.donationsEnabled});je.id&&S(xe=>{const Pe=new Map(xe);return Pe.set(q,{id:je.id,name:H,slug:je.slug??ae,version:me}),Pe})}catch(J){console.error("Share failed:",J),alert(t("shareFailed",{error:String(J)}))}finally{g(null)}},z=async()=>{if(!T)return;const{key:V}=T,O=N.get(V);if(M(null),!O)return;const q=O.id;g({key:V,action:"hubDelete"});try{await Un.deleteItem(q),S(J=>{const H=new Map(J);return H.delete(V),H})}catch(J){console.error("Hub delete failed:",J),alert(t("hubDeleteFailed",{error:String(J)}))}finally{g(null)}},E=async()=>{if(!C)return;const V=C,O=`${V.type}/${V.name}`;w(null),g({key:O,action:"delete"});try{await le.builder.artifacts.delete(V.type,V.name),d(q=>q.filter(J=>!(J.type===V.type&&J.name===V.name))),j(q=>{const J=new Map(q);return J.delete(O),J}),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Delete failed:",q)}finally{g(null)}},_=h==="all"?l:l.filter(V=>V.type===h),G=V=>{history.pushState(null,"",`#builder/${V.type}/${encodeURIComponent(V.name)}`),window.dispatchEvent(new HashChangeEvent("hashchange"))};return s?n.jsx(uc,{type:s.type,name:s.name,authUser:e,onBack:()=>{history.pushState(null,"","#builder"),window.dispatchEvent(new HashChangeEvent("hashchange"))}}):n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsxs("div",{className:`max-w-5xl mx-auto w-full ${r?"px-4 py-5":"px-6 py-6"}`,children:[n.jsxs("div",{className:"mb-6",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-xl font-bold text-fg-primary",children:t("title")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:t("subtitle")})]}),n.jsx("button",{onClick:R,className:"text-xs text-fg-tertiary hover:text-fg-secondary transition-colors px-3 py-1.5 rounded-lg border border-border-default hover:border-gray-600",children:t("common:refresh")})]}),n.jsx("div",{className:`grid ${r?"grid-cols-1 gap-2":"grid-cols-3 gap-3"}`,children:QG.map(V=>{const O=t(`prompts.${V.id}Prompt`),q=t(`prompts.${V.id}Examples`,{returnObjects:!0}),J=Array.isArray(q)?q:[];return n.jsx("button",{onClick:()=>U(O),className:`group text-left w-full rounded-xl border ${V.borderColor} bg-surface-secondary/60 p-4 transition-all hover:bg-surface-secondary/80 hover:shadow-lg`,children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:`w-10 h-10 text-xl rounded-lg ${V.bgColor} flex items-center justify-center shrink-0`,children:V.icon}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:`text-sm font-semibold bg-gradient-to-r ${V.color} bg-clip-text text-transparent`,children:t(`prompts.${V.id}`)}),n.jsx("p",{className:"text-[11px] text-fg-tertiary mt-1 leading-relaxed",children:t(`prompts.${V.id}Desc`)}),J.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.slice(0,2).map((H,Z)=>n.jsxs("span",{className:"text-[10px] text-fg-muted bg-surface-elevated/60 rounded-full px-2 py-0.5 border border-border-default",onClick:Y=>{Y.stopPropagation(),U(O+H)},children:["“",H,"”"]},Z))})]})]})},V.id)})})]}),n.jsx("div",{className:"mb-3",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg-secondary",children:t("myCreations.title")}),n.jsx("div",{className:"flex gap-1.5",children:["all","agent","team","skill"].map(V=>n.jsx("button",{onClick:()=>p(V),className:`text-xs px-2.5 py-1 rounded-lg transition-colors ${h===V?"bg-brand-600 text-white":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:t(V==="all"?"myCreations.filterAll":V==="agent"?"myCreations.filterAgents":V==="team"?"myCreations.filterTeams":"myCreations.filterSkills")},V))})]})}),u&&l.length===0?n.jsx("div",{className:"text-center text-fg-tertiary py-12 text-sm",children:t("myCreations.loadingArtifacts")}):_.length===0?n.jsxs("div",{className:"text-center py-12",children:[n.jsx("div",{className:"text-fg-tertiary text-sm",children:t("myCreations.noArtifacts")}),n.jsx("div",{className:"text-fg-muted text-xs mt-1",children:t("myCreations.noArtifactsHint")})]}):n.jsx("div",{className:"grid gap-3",children:_.map(V=>{const O=ej[V.type]??ej.agent,q=V.meta.displayName||V.meta.name||V.name,J=V.meta.description||"",H=`${V.type}/${V.name}`,Z=y?.key===H?y.action:null,Y=N.get(H),ee=V.meta.version||"1.0.0",ae=!!Y,Q=ae&&Y.version!==ee,me=()=>{const Me=Un.getUser();return!Y||!Me?null:`${Un.getUrl()}/${encodeURIComponent(Me.username)}/${encodeURIComponent(Y.slug)}`},Ae=n.jsxs("div",{className:`flex items-center gap-1.5 ${r?"flex-wrap":"shrink-0"}`,onClick:Me=>Me.stopPropagation(),children:[v.has(H)?n.jsx("button",{onClick:()=>F(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-green-600/30 text-green-600 hover:bg-red-500/10 hover:text-red-500 hover:border-red-500/30 transition-colors disabled:opacity-50",children:t(Z==="uninstall"?"common:uninstalling":"common:uninstall")}):n.jsx("button",{onClick:()=>W(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors disabled:opacity-50",children:t(Z==="install"?"common:installing":"common:install")}),ae&&Q?n.jsx("button",{onClick:()=>B(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-amber-500/30 text-amber-400 hover:bg-amber-500/10 hover:border-amber-500/50 transition-colors disabled:opacity-50",children:Z==="share"?t("common:sharing"):t("share.updateVersion",{version:ee})}):ae?n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsxs("a",{href:me()??"#",target:"_blank",rel:"noopener noreferrer",className:"text-xs px-3 py-1.5 rounded-lg border border-green-600/30 text-green-600 hover:text-green-500 hover:border-green-500/40 transition-colors inline-flex items-center gap-1",children:[n.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),t("common:shared")]}),n.jsx("button",{onClick:()=>M({key:H,name:q}),disabled:!!Z,className:"text-xs px-1.5 py-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50",title:t("removeFromHubTooltip"),children:n.jsxs("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]}):n.jsx("button",{onClick:async()=>{await Un.ensureAuth(),Array.isArray(V.meta.screenshots)&&V.meta.screenshots.length>0?L(V):I(V)},disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-border-default text-fg-secondary hover:text-green-600 hover:border-green-500/30 transition-colors disabled:opacity-50",children:t(Z==="share"?"common:sharing":"common:share")}),n.jsx("button",{onClick:()=>w(V),disabled:!!Z,className:"text-xs px-2 py-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50",title:t("common:delete"),children:n.jsxs("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]});return n.jsxs("div",{onClick:()=>G(V),className:"group rounded-lg bg-surface-elevated p-4 hover:bg-surface-overlay transition-all overflow-hidden cursor-pointer",children:[n.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[(()=>{const Me=V.meta.icon,je=Me&&(Me.startsWith("http")||Me.startsWith("/")||/\.(png|jpe?g|gif|webp|svg)$/i.test(Me))?Me.startsWith("http")||Me.startsWith("/")?Me:`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(Me.split("/").pop()??"")}`:null;return n.jsx("div",{className:`w-9 h-9 rounded-lg ${O.bg} flex items-center justify-center text-lg shrink-0 overflow-hidden`,children:je?n.jsx("img",{src:je,alt:"",className:"w-full h-full object-cover"}):Me?n.jsx("span",{children:Me}):O.icon})})(),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:q}),n.jsx("span",{className:`text-[10px] font-medium uppercase tracking-wider ${O.color}`,children:V.type})]}),J&&n.jsx("p",{className:"text-xs text-fg-tertiary line-clamp-2",children:J}),n.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[10px] text-fg-tertiary min-w-0",children:[n.jsx("button",{onClick:Me=>{Me.stopPropagation(),le.system.openPath(V.path).catch(()=>{})},className:"hover:text-fg-secondary transition-colors truncate min-w-0",title:V.path,children:XG(V.path)}),n.jsx("span",{className:"shrink-0",children:new Date(V.updatedAt).toLocaleDateString()})]})]}),!r&&Ae]}),r&&n.jsx("div",{className:"mt-3 pt-3 border-t border-border-default/50",children:Ae})]},H)})}),C&&n.jsx(tj,{title:t("confirmDelete"),message:t("deleteCannotUndo",{name:C.meta.displayName||C.meta.name||C.name}),cancelLabel:t("common:cancel"),confirmLabel:t("common:delete"),onConfirm:E,onCancel:()=>w(null)}),T&&n.jsx(tj,{title:t("confirmDelete"),message:t("removeFromHub",{name:T.name}),cancelLabel:t("common:cancel"),confirmLabel:t("common:delete"),onConfirm:()=>{z()},onCancel:()=>M(null)}),D&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>I(null),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl max-w-sm w-full mx-4 p-6 shadow-2xl",onClick:V=>V.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary mb-2",children:t("common:share")}),n.jsx("p",{className:"text-sm text-fg-secondary mb-5",children:t("share.imagePrompt")}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:()=>{const V=D;I(null),L(V)},className:"flex-1 text-sm px-4 py-2 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-fg-tertiary transition-colors",children:t("share.directly")}),n.jsx("button",{onClick:()=>{const V=D;I(null),G(V)},className:"flex-1 text-sm px-4 py-2 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors",children:t("share.addImagesFirst")})]})]})}),$&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>B(null),children:n.jsx("div",{className:"bg-surface-secondary border border-border-default rounded-xl max-w-sm w-full mx-4 p-6 shadow-2xl",onClick:V=>V.stopPropagation(),children:n.jsx(JG,{isUpdate:N.has(`${$.type}/${$.name}`),onCancel:()=>B(null),onConfirm:(V,O)=>{const q=$;B(null),L(q,{donationsEnabled:V==="donation",priceCents:V==="paid"?O:void 0})}})})})]})})}function JG({isUpdate:e,onCancel:t,onConfirm:r}){const{t:s}=ft(["builder","common"]),[a,i]=x.useState("free"),[l,d]=x.useState("");return n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary mb-4",children:s(e?"shareMode.titleUpdate":"shareMode.title")}),n.jsxs("div",{className:"space-y-2 mb-5",children:[n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="free"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="free",onChange:()=>i("free"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.free")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.freeDesc")})]})]}),n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="donation"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="donation",onChange:()=>i("donation"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.donation")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.donationDesc")})]})]}),n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="paid"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="paid",onChange:()=>i("paid"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.paid")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.paidDesc")})]})]})]}),a==="paid"&&n.jsxs("div",{className:"mb-5",children:[n.jsx("label",{className:"text-xs text-fg-secondary block mb-1.5",children:s("shareMode.priceLabel")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm text-fg-tertiary",children:"$"}),n.jsx("input",{type:"number",min:"0.5",step:"0.5",value:l,onChange:u=>d(u.target.value),placeholder:s("shareMode.pricePlaceholder"),className:"flex-1 text-sm px-3 py-2 rounded-lg bg-surface-elevated border border-border-default text-fg-primary placeholder:text-fg-muted"})]})]}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:t,className:"flex-1 text-sm px-4 py-2 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-gray-600 transition-colors",children:s("common:cancel")}),n.jsx("button",{onClick:()=>r(a,a==="paid"?Math.round(Number(l)*100):0),disabled:a==="paid"&&(!l||Number(l)<=0),className:"flex-1 text-sm px-4 py-2 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:s(e?"shareMode.update":"shareMode.share")})]})]})}const nj={agent:{icon:"✦",label:"Agent",color:"text-brand-500",gradient:"from-brand-500 to-purple-600",bg:"bg-brand-500/10",ring:"ring-brand-500/30"},team:{icon:"◈",label:"Team",color:"text-blue-600",gradient:"from-blue-500 to-blue-600",bg:"bg-blue-500/10",ring:"ring-blue-500/30"},skill:{icon:"⬡",label:"Skill",color:"text-green-600",gradient:"from-green-500 to-green-600",bg:"bg-green-500/10",ring:"ring-green-500/30"}},eY=["development","devops","management","productivity","browser","custom","general"],tY=[{label:"Tech",emojis:["✦","◈","⬡","⚡","🤖","🧠","💡","🎯","🔧","📦","🚀","💻","🛠️","⭐","🔥","💎","⚙️","🧩","🔌","💾","🖥️","📡","🔬","🧪","🏗️","📱","🎮","🕹️","📟","💽","🖨️","⌨️"]},{label:"People",emojis:["👤","👥","🧑‍💻","👨‍💼","👩‍🔬","🧙","🦸","🤝","💪","🎓","👷","🕵️","🧑‍🎨","🧑‍🏫","👨‍🚀","🥷","🧑‍🏭","🧑‍⚕️","🧑‍🔧","🧑‍🍳","👨‍🎤","🦹","🧝","🧞","🧑‍✈️","💂","🤴","👸","🧛","🧟","🧜","🧚"]},{label:"Objects",emojis:["📝","📊","🗂️","📁","🔍","🔑","🌐","💬","🔒","🎨","📐","🗃️","📋","✏️","🖊️","📌","📎","🧲","🪝","🧰","🪜","🧬","🔭","💊","🩺","📕","📗","📘","📙","📓","🗒️","📰"]},{label:"Symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","♠️","♥️","♦️","♣️","🎵","🎶","💯","✅","❌","⭕","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","🟤","🔶","🔷","▶️","⏸️","⏹️"]},{label:"Nature",emojis:["🌟","🌈","🌊","🌿","🍀","🔮","💫","✨","🌙","☀️","🦋","🐉","🦊","🐺","🦅","🐙","🦁","🐯","🦄","🐲","🌸","🌺","🍄","🌵","🎄","🌴","🍁","🌻","🐝","🦎","🐍","🦈"]},{label:"Activity",emojis:["🎯","🏆","🥇","🎖️","🏅","🎪","🎭","🎬","🎤","🎧","🎼","🎹","🥁","🎸","🎺","🎻","⚽","🏀","🎾","🏐","🎲","🧸","🪁","🎰","🎳","🏹","🥊","🤺","⛷️","🏄","🚴","🧗"]}],nY={shell:{icon:">",color:"bg-amber-500/15 text-amber-400 border-amber-500/30"},file:{icon:"◫",color:"bg-blue-500/15 text-blue-400 border-blue-500/30"},network:{icon:"◎",color:"bg-purple-500/15 text-purple-400 border-purple-500/30"},browser:{icon:"◉",color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30"}};function Vx({value:e,onChange:t,renderAs:r="span",className:s,editClassName:a,placeholder:i,multiline:l,readOnly:d}){if(d){const S=e||i,M=`${s??""} ${!e?"text-fg-muted italic":""}`;return r==="h1"?n.jsx("h1",{className:M,children:S}):r==="p"?n.jsx("p",{className:M,children:S}):n.jsx("span",{className:M,children:S})}const[u,m]=x.useState(!1),[h,p]=x.useState(e),y=x.useRef(null);x.useEffect(()=>{p(e)},[e]),x.useEffect(()=>{u&&y.current?.focus()},[u]);const g=()=>{m(!1),h!==e&&t(h)},v=()=>{p(e),m(!1)},j=S=>{S.key==="Escape"&&v(),S.key==="Enter"&&!l&&g()};if(u){const S=`bg-transparent outline-none w-full ${a??s??""} ring-1 ring-brand-500/50 rounded px-1 -mx-1`;return l?n.jsx("textarea",{ref:y,value:h,onChange:T=>p(T.target.value),onBlur:g,onKeyDown:j,className:`${S} resize-y min-h-[60px]`,placeholder:i}):n.jsx("input",{ref:y,value:h,onChange:T=>p(T.target.value),onBlur:g,onKeyDown:j,className:S,placeholder:i})}const C=e||i,w=!e,N="cursor-text hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 transition-all";return r==="h1"?n.jsx("h1",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):r==="p"?n.jsx("p",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):r==="badge"?n.jsx("span",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):n.jsx("span",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C})}function rY({value:e,options:t,onChange:r,className:s,readOnly:a}){if(a)return n.jsx("span",{className:s,children:e});const[i,l]=x.useState(!1),[d,u]=x.useState(e),m=x.useRef(null),h=x.useRef(null);x.useEffect(()=>{i&&(u(e),setTimeout(()=>m.current?.focus(),0))},[i,e]);const p=t.filter(g=>g.toLowerCase().includes(d.toLowerCase())),y=g=>{const v=g.trim();v&&v!==e&&r(v),l(!1)};return i?n.jsxs("div",{ref:h,className:"relative inline-block",children:[n.jsx("input",{ref:m,value:d,onChange:g=>u(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),y(d)):g.key==="Escape"&&l(!1)},onBlur:g=>{h.current?.contains(g.relatedTarget)||y(d)},className:`${s??""} bg-transparent outline-none ring-1 ring-brand-500/50 rounded w-28`}),p.length>0&&n.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 min-w-[120px] max-h-40 overflow-y-auto",children:p.map(g=>n.jsx("button",{onMouseDown:v=>{v.preventDefault(),y(g)},className:`block w-full text-left px-3 py-1.5 text-xs hover:bg-surface-secondary/80 transition-colors ${g===e?"text-brand-400 font-medium":"text-fg-secondary"}`,children:g},g))})]}):n.jsx("span",{onClick:()=>l(!0),className:`${s??""} cursor-pointer hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 transition-all`,children:e})}function sY({tags:e,onChange:t,readOnly:r}){if(r)return n.jsx("div",{className:"flex flex-wrap items-center gap-1.5 min-h-[24px]",children:e.map(h=>n.jsx("span",{className:"text-[10px] px-2 py-0.5 bg-surface-elevated text-fg-muted rounded-full border border-border-default",children:h},h))});const{t:s}=ft(["builder"]),[a,i]=x.useState(!1),[l,d]=x.useState(""),u=x.useRef(null);x.useEffect(()=>{a&&u.current?.focus()},[a]);const m=h=>{if((h.key==="Enter"||h.key===",")&&l.trim()){h.preventDefault();const p=l.trim().toLowerCase();e.includes(p)||t([...e,p]),d("")}else h.key==="Backspace"&&!l&&e.length>0?t(e.slice(0,-1)):h.key==="Escape"&&(i(!1),d(""))};return a?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 ring-1 ring-brand-500/50 rounded px-2 py-1 -mx-1 min-h-[32px]",children:[e.map(h=>n.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] bg-surface-elevated text-fg-secondary rounded-full px-2 py-0.5 border border-border-default",children:[h,n.jsx("button",{onClick:()=>t(e.filter(p=>p!==h)),className:"text-fg-muted hover:text-red-500",children:"×"})]},h)),n.jsx("input",{ref:u,value:l,onChange:h=>d(h.target.value),onKeyDown:m,onBlur:()=>{l||i(!1)},className:"flex-1 min-w-[80px] bg-transparent text-xs text-fg-primary placeholder:text-fg-muted focus:outline-none",placeholder:s("detail.typeTagAndEnter")})]}):n.jsx("div",{onClick:()=>i(!0),className:"flex flex-wrap items-center gap-1.5 cursor-text hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 py-0.5 transition-all min-h-[24px]",children:e.length>0?e.map(h=>n.jsx("span",{className:"text-[10px] px-2 py-0.5 bg-surface-elevated text-fg-muted rounded-full border border-border-default",children:h},h)):n.jsx("span",{className:"text-[10px] text-fg-muted italic",children:s("detail.typeTagAndEnter")})})}function Zb({content:e}){return n.jsx("div",{className:`prose prose-invert prose-sm max-w-none
658
+ `)){Is(!0),js(Lt.toLowerCase()),Ns(0);return}}}Is(!1)},q0=re=>{const Se=fr.current?.selectionStart??Ve.length,Le=Ve.slice(0,Se).lastIndexOf("@"),xt=Ve.slice(Se),We=re.includes(" ")?`@[${re}]`:`@${re}`,Lt=Ve.slice(0,Le)+We+" "+xt;Rt(Lt),Is(!1),Ns(0);const Bt=Le+We.length+1;requestAnimationFrame(()=>{fr.current?.setSelectionRange(Bt,Bt)})},wc=10*1024*1024,Bd=5,U0=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),Ii=x.useCallback(re=>re.type.startsWith("image/")||U0.has(re.type),[]),Ml=re=>re.dataUrl.startsWith("data:image/"),V0=(re,Se)=>{if(Ml({dataUrl:Se}))return null;const he=re.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[he]??"📁"},Bo=x.useCallback(re=>{const Se=Array.from(re).filter(Ii);if(Se.length!==0)for(const he of Se){if(he.size>wc)continue;const Le=new FileReader;Le.onload=()=>{const xt=Le.result;mr(We=>We.length>=Bd||We.some(Lt=>Lt.dataUrl===xt)?We:[...We,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:xt,name:he.name}])},Le.readAsDataURL(he)}},[Ii]),K0=x.useCallback(re=>{mr(Se=>Se.filter(he=>he.id!==re))},[]),ap=x.useCallback(re=>{const Se=re.clipboardData?.files;if(Se&&Se.length>0){const he=Array.from(Se).filter(Ii);he.length>0&&(re.preventDefault(),Bo(he))}},[Bo,Ii]),ip=x.useCallback(re=>{re.preventDefault();const Se=re.dataTransfer?.files;Se&&Se.length>0&&Bo(Array.from(Se).filter(Ii))},[Bo,Ii]),op=x.useCallback(re=>{re.preventDefault()},[]),Jr=u.find(re=>re.id===be),Hd=t?.name??a("page.fallbackYou"),Xs=cn[cn.length-1],Dl=sn&&Xs?.sender==="agent",W0=Vn&&Xs?.sender==="agent",Fd=x.useMemo(()=>{if(te!=="channel")return null;if(fe.startsWith("group:custom:")){const Se=Mt.find(he=>he.channelKey===fe);return Se?.members?new Set(Se.members.filter(he=>he.type==="agent").map(he=>he.id)):null}if(!vr)return null;const re=Or.find(Se=>Se.id===vr);return re?new Set(re.members.filter(Se=>Se.type==="agent").map(Se=>Se.id)):null},[te,fe,vr,Or,Mt]),Li=u.filter(re=>Fd?Fd.has(re.id):!0).filter(re=>re.name.toLowerCase().includes(Kn)),kc=h.find(re=>re.id===Ne),Rl=Ne===t?.id||!Ne,aa=Mt.find(re=>re.channelKey===fe);x.useEffect(()=>{if(r||!fe.startsWith("group:custom:"))return;const re=Mt.find(Se=>Se.channelKey===fe);!re||re.members||le.groupChats.getById(re.id).then(Se=>{Se.chat.members&&Ln(he=>he.map(Le=>Le.id===re.id?{...Le,members:Se.chat.members}:Le))}).catch(()=>{})},[r,fe,Mt]);const so=te==="channel"?aa?.name??fe:te==="direct"?Jr?.name??a("page.selectAgent"):te==="dm"?Rl?a("chat.myNotes"):kc?.name??a("page.directMessage"):a("page.chatTitle"),qd=te==="channel"?aa?a("page.placeholder.channel",{name:aa.name}):a("page.placeholder.channelWithMention",{name:fe}):te==="dm"?Rl?a("page.placeholder.dmSelf"):a("page.placeholder.dmOther",{name:kc?.name??""}):a(be?"page.placeholder.direct":"page.placeholder.noAgent"),Il=v&&N==="chat";return n.jsxs("div",{ref:L,className:"flex-1 overflow-hidden flex relative",children:[n.jsx(KW,{authUser:t,agents:u,teams:Or,humans:h,tasks:cs,externalAgents:ga,groupChats:Mt,chatMode:te,selectedAgent:be,activeChannel:fe,activeDmUserId:Ne,previewMode:r,onSelectAgent:re=>{de("direct"),se(re),$("chat"),Pn(!1),v&&M()},onSelectChannel:re=>{de("channel"),$e(re),$("chat"),Pn(!1),v&&M()},onSelectDm:re=>{de("dm"),Ze(re),$("chat"),Pn(!1),v&&M()},onSelectTeam:re=>{const Se=Mt.find(he=>he.type==="team"&&he.teamId===re);v?D(re):Se&&(de("channel"),$e(Se.channelKey),$("chat"),Pn(!1),!U&&!z&&W(!0))},selectedTeamId:vr??(te==="direct"&&Jr?.teamId?Jr.teamId:null),onRefreshTeams:_s,onRefreshAgents:Zr,onRefreshHumans:ja,onRefreshGroupChats:va,onViewProfile:st,onManageGroupMembers:re=>{de("channel"),$e(re),$("chat"),Pn(!0),v&&M()},unreadByAgent:ya,unreadByChannel:$r,width:v?void 0:R.width,onResizeStart:v?void 0:R.onResizeStart,hidden:v&&N!=="roster",initialLoading:y}),v&&N==="team"&&S&&(()=>{const re=Or.find(Le=>Le.id===S);if(!re)return null;const Se=u.filter(Le=>Le.teamId===S),he=Mt.find(Le=>Le.type==="team"&&Le.teamId===S);return n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[n.jsx("button",{onClick:()=>{window.location.hash=Te.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:re.name}),n.jsx("p",{className:"text-[10px] text-fg-tertiary",children:a("chat.members_other",{count:re.members?.length||Se.length})})]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[he&&(()=>{const Le=$r[he.channelKey]??0;return n.jsxs("button",{onClick:()=>{de("channel"),$e(he.channelKey),$("chat"),M()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[n.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:he.name}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:a("chat.groupChat")})]}),Le>0?n.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:Le}):n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),Se.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:a("chat.agents")}),Se.map(Le=>{const xt=ya.get(Le.id)??0;return n.jsxs("button",{onClick:()=>{de("direct"),se(Le.id),$("chat"),M()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[n.jsx(Sr,{name:Le.name||"Agent",avatarUrl:Le.avatarUrl,size:36}),n.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:Le.name}),n.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:Le.role||Le.status})]}),xt>0?n.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:xt}):n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Le.status==="active"||Le.status==="idle"?"bg-green-500":Le.status==="working"||Le.status==="busy"?"bg-blue-500":Le.status==="paused"?"bg-amber-500":"bg-gray-400"}`})]},Le.id)})]})]})]})})(),U&&!z&&!v&&(()=>{const re=vr??(te==="direct"?Jr?.teamId:void 0);if(!re)return null;const Se=Or.find(Le=>Le.id===re);if(!Se)return null;const he=Mt.find(Le=>Le.type==="team"&&Le.teamId===re);return n.jsx(gk,{team:Se,agents:u,humans:h,authUser:t,groupChat:he,chatMode:te,selectedAgent:be,activeChannel:fe,teams:Or,onSelectAgent:Le=>{de("direct"),se(Le),$("chat"),Pn(!1)},onSelectChannel:Le=>{de("channel"),$e(Le),$("chat"),Pn(!1)},onSelectDm:Le=>{de("dm"),Ze(Le),$("chat"),Pn(!1)},onBack:()=>W(!1),onViewProfile:st,onRefreshAgents:Zr,onRefreshTeams:_s,unreadByAgent:ya,width:F.width,onResizeStart:F.onResizeStart})})(),_&&!v&&(()=>{const re=vr??(te==="direct"?Jr?.teamId:void 0);if(!re)return null;const Se=Or.find(Le=>Le.id===re);if(!Se)return null;const he=Mt.find(Le=>Le.type==="team"&&Le.teamId===re);return n.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:R.width+6},children:[n.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>G(!1)}),n.jsx("div",{className:"relative h-full",style:{width:F.width+8},children:n.jsx(gk,{team:Se,agents:u,humans:h,authUser:t,groupChat:he,chatMode:te,selectedAgent:be,activeChannel:fe,teams:Or,onSelectAgent:Le=>{de("direct"),se(Le),$("chat"),Pn(!1),G(!1)},onSelectChannel:Le=>{de("channel"),$e(Le),$("chat"),Pn(!1),G(!1)},onSelectDm:Le=>{de("dm"),Ze(Le),$("chat"),Pn(!1),G(!1)},onBack:()=>G(!1),onViewProfile:Le=>{st(Le),G(!1)},onRefreshAgents:Zr,onRefreshTeams:_s,unreadByAgent:ya,width:F.width})})]})})(),(!v||Il)&&n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v?"min-w-0":"min-w-[400px]"}`,children:[n.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[n.jsx("button",{onClick:()=>{window.location.hash=T.current},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsx("span",{className:"font-semibold text-sm truncate min-w-0 flex-1",children:so}),te==="direct"&&Jr&&n.jsx(Gk,{agent:Jr,tasks:cs,onViewProfile:st})]}),n.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[n.jsx("button",{onClick:()=>{jo(I)?history.back():$("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${I==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:a("page.chatTitle")}),n.jsx("button",{onClick:()=>{jo(I)||Ce()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${jo(I)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:a(te==="channel"?"page.teamTab":"page.profileTab")}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:()=>{lr(!on),on||(cr(""),ur([]))},className:`p-1 rounded-md transition-colors shrink-0 ${on?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),te==="channel"&&aa?.type==="custom"&&n.jsxs("button",{onClick:()=>Pn(!Jn),className:`text-[11px] px-2 py-1 rounded-md font-medium shrink-0 flex items-center gap-1 ${Jn?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),aa.members?.length??aa.memberCount??0]}),te==="direct"&&!jo(I)&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:ro,className:"text-[11px] text-brand-500 px-2 py-1 rounded-md bg-brand-500/10 font-medium shrink-0",children:a("page.newChatPlus")}),n.jsx("button",{ref:at,onClick:()=>tn(!Jt),className:`p-1 rounded-md transition-colors shrink-0 ${Jt?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,title:a("page.historyTitle"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}):(()=>{const re=vr?Or.find(jt=>jt.id===vr):void 0,Se=te==="direct"&&be?DG:te==="channel"&&vr?RG:["chat"],he=async()=>{const jt=Q.trim();if(!jt){ae(!1);return}try{te==="direct"&&be?(await le.agents.updateConfig(be,{name:jt}),Zr()):te==="channel"&&vr&&(await le.teams.update(vr,{name:jt}),_s())}catch{}ae(!1)},Le=async()=>{try{te==="direct"&&be?(await le.agents.updateConfig(be,{roleDescription:He}),Zr()):te==="channel"&&vr&&(await le.teams.update(vr,{description:He}),_s())}catch{}Me(!1)},xt=te==="direct"?Jr?.name:te==="channel"?re?.name??aa?.name:kc?.name??"",We=te==="direct"?Jr?.role||"":te==="channel"&&re?.description||"",Lt=te==="direct"?Jr?.avatarUrl:void 0,Bt=xt||"U",lt=te==="direct"&&be||te==="channel"&&vr;return n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("div",{className:"flex items-center px-4 h-14 gap-2.5",children:[(!U||z)&&(te==="channel"&&vr||te==="direct"&&Jr?.teamId)&&n.jsx("button",{onClick:V,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${_?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),n.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),lt&&(te==="channel"&&vr?n.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):n.jsx(Sr,{name:Bt,avatarUrl:Lt,size:36,className:"rounded-xl shrink-0"})),lt?n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[ee?n.jsx("input",{ref:xe,value:Q,onChange:jt=>me(jt.target.value),onBlur:he,onKeyDown:jt=>{jt.key==="Enter"&&he(),jt.key==="Escape"&&ae(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):n.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{me(xt??""),ae(!0)},title:"Click to edit name",children:xt}),te==="direct"&&Jr&&n.jsx(Gk,{agent:Jr,tasks:cs,onViewProfile:st})]}),(te==="direct"||te==="channel"&&vr)&&(Ae?n.jsx("input",{ref:Pe,value:He,onChange:jt=>je(jt.target.value),onBlur:Le,onKeyDown:jt=>{jt.key==="Enter"&&Le(),jt.key==="Escape"&&Me(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add description...",autoFocus:!0}):n.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{je(We),Me(!0)},title:"Click to edit description",children:We||"No description"}))]}):n.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[n.jsx("span",{className:"font-semibold text-sm truncate",children:so}),te==="dm"&&n.jsx("span",{className:"text-xs text-fg-tertiary",children:Rl?a("page.privateNotepad"):""})]}),n.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[n.jsx("button",{onClick:()=>{lr(!on),on||(cr(""),ur([]))},className:`p-1.5 rounded-md transition-colors ${on?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:a("page.searchMessages"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})})}),te==="channel"&&aa?.type==="custom"&&n.jsxs("button",{onClick:()=>Pn(!Jn),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${Jn?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"9",cy:"7",r:"4"}),n.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),n.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),aa.members?.length??aa.memberCount??0]}),te==="direct"&&Jr&&I==="chat"&&n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{onClick:ro,className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:a("page.newChatButton")}),n.jsx("button",{ref:at,onClick:()=>tn(!Jt),className:`p-1.5 rounded-md transition-colors ${Jt?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:a("page.historyTitle"),children:n.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}),Se.length>1&&n.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:Se.map(jt=>n.jsxs("button",{onClick:()=>$(jt),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${I===jt?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[n.jsx("span",{children:LG(jt)}),IG(jt,a)]},jt))})]})})(),on&&n.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/50 px-4 py-2 space-y-2 animate-in slide-in-from-top-2 duration-200",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),n.jsx("input",{autoFocus:!0,value:qr,onChange:re=>H0(re.target.value),onKeyDown:re=>{re.key==="Escape"&&(lr(!1),cr(""),ur([]))},placeholder:a("page.searchPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),n.jsx("button",{onClick:()=>{lr(!1),cr(""),ur([])},className:"text-fg-tertiary hover:text-fg-secondary text-xs px-1",children:"✕"})]}),Rs&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary py-1",children:[n.jsxs("svg",{className:"animate-spin h-3 w-3",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a("page.searching")]}),!Rs&&qr.length>=2&&yr.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:a("page.noSearchResults")}),yr.length>0&&n.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:yr.map(re=>n.jsxs("button",{onClick:()=>F0(re),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-surface-elevated transition-colors group",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-tertiary mb-0.5",children:[n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${re.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:re.source==="channel"?"#":"1:1"}),re.senderName&&n.jsx("span",{children:re.senderName}),n.jsx("span",{children:new Date(re.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),n.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 group-hover:text-fg-primary transition-colors",children:re.text.length>200?re.text.slice(0,200)+"…":re.text})]},re.id))})]}),te==="direct"&&be&&I==="chat"&&An.length>1&&n.jsx("div",{className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:An.map(re=>n.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${re.id===It?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(re.id===ir){qt(ir);const Se=nt.current;Fe.current.delete(Se),dt([])}else vc(re)},children:[re.isMain&&n.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),n.jsx("span",{className:"truncate",children:re.id===ir?a("page.newChat"):re.isMain?a("page.sessionMain"):re.title||a("page.sessionConversation")}),!re.isMain&&n.jsx("button",{onClick:Se=>{Se.stopPropagation(),sp(re.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},re.id))}),te==="channel"&&aa?.type==="custom"&&Jn&&(()=>{const re=aa,Se=re.members??[],he=[];for(const Le of u)Se.some(xt=>xt.id===Le.id)||he.push({id:Le.id,name:Le.name,type:"agent",subtitle:Le.role||"Agent"});for(const Le of h)Se.some(xt=>xt.id===Le.id)||he.push({id:Le.id,name:Le.name,type:"human",subtitle:Le.email||Le.role||""});return n.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[a("page.members")," (",Se.length,")"]}),n.jsx("button",{onClick:()=>Pn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:Se.map(Le=>n.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${Le.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[n.jsx(Sr,{name:Le.name,size:16,bgClass:Le.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),Le.name,Le.id!==t?.id&&n.jsx("button",{onClick:async()=>{try{await le.groupChats.removeMember(re.id,Le.id),Ln(xt=>xt.map(We=>We.id===re.id?{...We,members:(We.members??[]).filter(Lt=>Lt.id!==Le.id),memberCount:(We.memberCount??1)-1}:We))}catch{}},className:"ml-0.5 hover:text-red-500 transition-colors",title:a("common:remove"),children:n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},Le.id))}),he.length>0&&n.jsx("div",{className:"mt-1",children:n.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:async Le=>{const xt=Le.target.value;if(!xt)return;const We=he.find(Lt=>Lt.id===xt);if(We)try{await le.groupChats.addMember(re.id,We.id,We.type,We.name),Ln(Lt=>Lt.map(Bt=>Bt.id===re.id?{...Bt,members:[...Bt.members??[],{id:We.id,name:We.name,type:We.type}],memberCount:(Bt.memberCount??0)+1}:Bt))}catch{}},children:[n.jsx("option",{value:"",children:a("page.addMemberPlaceholder")}),he.map(Le=>n.jsxs("option",{value:Le.id,children:["[",Le.type==="agent"?"Agent":"Human","] ",Le.name]},Le.id))]})})]})})(),te==="direct"&&be&&Jt&&n.jsxs("div",{ref:yt,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[n.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:a("page.historyTitle")}),n.jsx("button",{onClick:()=>tn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[Ie.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:a("page.noConversationsYet")}),(()=>{const re=new Date,Se=new Date(re.getFullYear(),re.getMonth(),re.getDate()).getTime(),he=Se-864e5,Le=Se-7*864e5,xt=[],We=[],Lt=[],Bt=[],lt=[];for(const jt of Ie){const nn=new Date(jt.lastMessageAt).getTime();nn>=Se?We.push(jt):nn>=he?Lt.push(jt):nn>=Le?Bt.push(jt):lt.push(jt)}return We.length>0&&xt.push({label:a("page.dateToday"),items:We}),Lt.length>0&&xt.push({label:a("page.dateYesterday"),items:Lt}),Bt.length>0&&xt.push({label:a("page.datePrevious7Days"),items:Bt}),lt.length>0&&xt.push({label:a("page.dateOlder"),items:lt}),xt.map(jt=>n.jsxs("div",{className:"mb-2",children:[n.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:jt.label}),jt.items.map(nn=>n.jsxs("button",{onClick:()=>{vc(nn)},className:`w-full text-left px-3 py-2.5 rounded-lg text-xs mb-0.5 transition-colors ${nn.id===It?"bg-brand-600/20 text-brand-500":"text-fg-secondary hover:bg-surface-elevated"}`,children:[n.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[nn.isMain&&n.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),nn.isMain?a("page.sessionMain"):nn.title||a("page.sessionConversation")]}),n.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(nn.lastMessageAt).toLocaleString()})]},nn.id))]},jt.label))})()]})]})]}),v&&I==="profile"&&te==="direct"&&be&&n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Sk,{agentId:be,onBack:()=>$("chat"),inline:!0,defaultTab:J,highlightMailboxId:Z,onSwipeBack:()=>{jo(B.current)?history.back():$("chat")},authUser:t})}),v&&I==="profile"&&te==="channel"&&vr&&n.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:v?ct.onTouchStart:void 0,onTouchEnd:v?ct.onTouchEnd:void 0,children:n.jsx(Hk,{teamId:vr,onBack:()=>$("chat"),inline:!0,onSelectAgent:re=>{de("direct"),se(re),Ce()}})}),!v&&jo(I)&&te==="direct"&&be&&n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Sk,{agentId:be,onBack:()=>$("chat"),inline:!0,headless:!0,activeTab:I,highlightMailboxId:Z,authUser:t})}),!v&&jo(I)&&te==="channel"&&vr&&n.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:n.jsx(Hk,{teamId:vr,onBack:()=>$("chat"),inline:!0,headless:!0,activeTab:I,onSelectAgent:re=>{de("direct"),se(re),$("overview"),!U&&!z&&W(!0)}})}),n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${I!=="chat"?"hidden":""}`,children:[_n&&n.jsxs("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center items-center gap-2 py-2 bg-gradient-to-b from-surface-primary/90 to-transparent pointer-events-none",children:[n.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:a("page.loadingEarlierMessages")})]}),n.jsxs("div",{ref:as,className:`flex-1 overflow-y-auto ${v?"p-2.5":"p-5 2xl:pr-[280px]"}`,onScroll:to,onTouchStart:v?ct.onTouchStart:void 0,onTouchEnd:v?ct.onTouchEnd:void 0,children:[cn.length===0&&!sn&&n.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-fg-tertiary text-sm space-y-2",children:[n.jsx("div",{className:"opacity-40",children:n.jsx("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:te==="channel"?n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H6l-4 4V6c0-1.1.9-2 2-2z"}),n.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),n.jsx("line",{x1:"8",y1:"14",x2:"13",y2:"14"})]}):n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),te==="channel"&&n.jsx("div",{children:a("page.emptyChannel",{name:aa?.name??fe})}),te==="direct"&&!be&&n.jsx("div",{children:a("page.emptySelectAgent")}),te==="direct"&&be&&n.jsx("div",{children:a("page.emptyNewConversation",{name:Jr?.name??""})})]}),cn.length>0&&n.jsx("div",{style:{height:bt.getTotalSize(),width:"100%",position:"relative"},children:bt.getVirtualItems().map(re=>{const Se=re.index,he=cn[Se],Le=Se>0?cn[Se-1]:null,xt=qk(he.rawCreatedAt),We=Le?qk(Le.rawCreatedAt):"",Lt=xt&&xt!==We,Bt=Se===cn.length-1,jt=Dl&&Bt&&sn,nn=W0&&Bt||jt,Rn=te==="channel"||!jt||he.isStopped;return n.jsx("div",{"data-index":Se,ref:bt.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${re.start}px)`},children:n.jsxs("div",{className:"pb-3",children:[Lt&&n.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[n.jsx("div",{className:"flex-1 h-px bg-border-default"}),n.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:jG(he.rawCreatedAt,l)}),n.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),n.jsxs("div",{id:`msg-${he.id}`,className:"group/msg flex gap-3 transition-colors rounded-lg",children:[te==="channel"?n.jsx("div",{className:"shrink-0 cursor-pointer",onClick:Wt=>{if(he.sender==="agent"&&he.agentId){const xn=Wt.currentTarget.getBoundingClientRect();q({agentId:he.agentId,top:xn.top,left:xn.right+8})}},children:n.jsx(Sr,{name:he.sender==="user"?Hd:he.agentName??a("page.fallbackAgent"),avatarUrl:he.sender==="user"?t?.avatarUrl:u.find(Wt=>Wt.id===he.agentId)?.avatarUrl,size:32,bgClass:he.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:he.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):n.jsx("div",{className:"shrink-0",children:n.jsx(Sr,{name:he.sender==="user"?Hd:he.agentName??(te==="direct"?Jr?.name??a("page.fallbackAgent"):a("page.fallbackAgent")),avatarUrl:he.sender==="user"?t?.avatarUrl:u.find(Wt=>Wt.id===(he.agentId??(te==="direct"?Jr?.id:void 0)))?.avatarUrl,size:32,bgClass:he.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:he.sender==="user"?Hd:te==="channel"?he.agentName??a("page.fallbackAgent"):n.jsx(TG,{name:he.agentName??(te==="direct"?Jr?.name??a("page.fallbackAgent"):a("page.fallbackAgent")),agentId:he.agentId??(te==="direct"?Jr?.id:void 0),agents:u,onViewProfile:st})}),n.jsx("span",{className:"text-xs text-fg-tertiary",title:he.rawCreatedAt?new Date(he.rawCreatedAt).toLocaleString():"",children:kG(he.time,he.rawCreatedAt,l)})]}),he.replyToId&&he.replyToSender&&n.jsxs("button",{onClick:()=>{const Wt=document.getElementById(`msg-${he.replyToId}`);Wt&&(Wt.scrollIntoView({behavior:"smooth",block:"center"}),Wt.classList.add("bg-brand-500/10"),setTimeout(()=>Wt.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[n.jsx("span",{className:"font-medium text-brand-500",children:he.replyToSender}),n.jsx("span",{className:"truncate max-w-[250px]",children:he.replyToText??"..."})]}),n.jsxs("div",{className:`mt-0.5 ${he.sender==="agent"?"bg-surface-chat-bubble rounded-2xl px-3.5 py-2.5":""} ${he.isError||he.sender==="agent"&&he.text.startsWith("⚠")?"border-b-2 border-red-500/60":""} ${nn&&he.sender==="agent"?"streaming-bubble":""}`,children:[he.sender==="user"?n.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[he.images&&he.images.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:he.images.map((Wt,xn)=>n.jsx("img",{src:Wt,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(Wt,"_blank")},xn))}),te==="channel"?pk(he.text,u,(Wt,xn)=>{const Mn=xn.currentTarget.getBoundingClientRect();q({agentId:Wt.id,top:Mn.bottom,left:Mn.left})}):he.text&&n.jsx("span",{className:"leading-relaxed",children:pk(he.text,u,(Wt,xn)=>{const Mn=xn.currentTarget.getBoundingClientRect();q({agentId:Wt.id,top:Mn.bottom,left:Mn.left})})})]}):he.sender==="agent"&&te==="channel"&&!(he.segments&&he.segments.length>0)?n.jsx(Gr,{content:he.text,className:"text-sm text-fg-secondary",onMentionClick:zt,knownNames:mt}):n.jsx(MG,{msg:he,isStreaming:jt,liveActivities:jt?Tt:[],onViewModeChange:Wt=>zs(xn=>{const Mn=new Set(xn);return Wt==="full"?Mn.add(he.id):Mn.delete(he.id),Mn}),onMentionClick:zt,knownNames:mt}),he.isNotification&&n.jsx(CG,{priority:he.notifyPriority})]}),Rn&&!r&&n.jsx("div",{className:`transition-opacity ${he.isStopped||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:n.jsx(EG,{msg:he,onCopy:_0,onRetry:z0,onResume:$0,onReply:$o,isCopied:hn===he.id,isLastAgentMsg:he.id===no})})]})]})]})},he.id)})}),te==="channel"&&jn.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:jn.map(re=>n.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors group/think",onClick:()=>st(re.id,{tab:"overview"}),children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:re.name,avatarUrl:re.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"text-sm font-medium text-fg-secondary truncate",children:re.name}),n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:a("page.agentThinking")})]}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary opacity-0 group-hover/think:opacity-100 transition-opacity",children:"→"})]},re.id))}),n.jsx("div",{ref:Ls})]}),Xe&&I==="chat"&&n.jsxs("button",{onClick:()=>{ds("smooth"),sa.current=!0,ie.current=!1,ot(!1),Dt.current=0,hr(0)},className:`absolute ${v?"bottom-4":"bottom-20"} left-1/2 -translate-x-1/2 z-10 flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/95 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary`,children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})}),fn>0?a("page.newMessages",{count:fn}):a("page.scrollToBottom")]})]}),O&&(()=>{const re=u.find(Se=>Se.id===O.agentId);return re?n.jsx(AG,{agent:re,anchorRect:{top:O.top,left:O.left},onClose:()=>q(null),onViewProfile:st}):null})(),n.jsx("div",{className:`${v?"px-3 py-2":"px-5 py-3 2xl:pr-[280px]"} relative shrink-0 ${I!=="chat"?"hidden":""}`,onDrop:ip,onDragOver:op,children:n.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/5 ${v?"rounded-2xl p-3":"rounded-2xl p-3 max-w-3xl"}`,children:[xa&&Li.length>0&&n.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-48 overflow-y-auto",children:[n.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:a("page.mentionAgent")}),Li.map((re,Se)=>n.jsxs("button",{ref:he=>{Se===ba&&he&&he.scrollIntoView({block:"nearest"})},onClick:()=>q0(re.name),onMouseEnter:()=>Ns(Se),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Se===ba?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[n.jsx(Sr,{name:re.name,avatarUrl:re.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),n.jsx("span",{className:"flex-1 min-w-0",children:re.name}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:re.role})]},re.id))]}),Fn.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Fn.map(re=>n.jsxs("div",{className:"relative group/img shrink-0",children:[Ml(re)?n.jsx("img",{src:re.dataUrl,alt:re.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):n.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:re.name,children:[n.jsx("span",{className:"text-xl leading-none",children:V0(re.name,re.dataUrl)}),n.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:re.name.split(".").pop()?.toUpperCase()})]}),n.jsx("button",{onClick:()=>K0(re.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},re.id)),Fn.length<Bd&&n.jsx("button",{onClick:()=>rr.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:a("page.addMoreFiles"),children:n.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),Fn.length>0&&Fn.some(re=>Ml(re))&&Jr&&Jr.modelSupportsVision===!1&&n.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[n.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),a("page.visionWarning")]}),n.jsx("input",{ref:rr,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:re=>{re.target.files&&Bo(re.target.files),re.target.value=""}}),un&&n.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[n.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[n.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:un.sender}),n.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:un.text})]}),n.jsx("button",{onClick:()=>yn(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:"flex gap-2 items-end",children:[n.jsx("button",{onClick:()=>rr.current?.click(),disabled:te==="direct"&&!be,className:"px-2.5 py-2.5 text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated",title:a("page.attachFilesTitle"),children:n.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:n.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsx("textarea",{ref:fr,value:Ve,onChange:re=>{El(re.target.value),Qn()},onKeyDown:re=>{if(xa&&Li.length>0){const Se=re.key==="ArrowUp"||re.ctrlKey&&re.key==="p",he=re.key==="ArrowDown"||re.ctrlKey&&re.key==="n",Le=re.key==="Enter"||re.key==="Tab",xt=re.key==="Escape";if(Se){re.preventDefault(),Ns(We=>(We-1+Li.length)%Li.length);return}if(he){re.preventDefault(),Ns(We=>(We+1)%Li.length);return}if(Le){re.preventDefault();const We=Li[ba];We&&q0(We.name);return}if(xt){re.preventDefault(),Is(!1);return}}re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),et())},onPaste:ap,placeholder:qd,disabled:te==="direct"&&!be,rows:2,className:"flex-1 px-4 py-3 bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-hidden leading-relaxed placeholder:text-fg-tertiary/60",style:{minHeight:"52px",maxHeight:"120px"}}),sn&&te!=="dm"&&n.jsx("button",{onClick:Ee,className:"px-3 py-2.5 bg-red-600 hover:bg-red-500 text-white text-sm rounded-xl transition-colors flex items-center gap-1.5",title:a("page.stopAgent"),children:n.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}),n.jsx("button",{onClick:()=>{et()},disabled:te==="direct"&&!be||!Ve.trim()&&Fn.length===0,className:"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a("common:send")})]})]})})]})]})}function Gk({agent:e,tasks:t,onViewProfile:r}){const{t:s}=ft(["team","common"]),[a,i]=x.useState(!1),l=x.useRef(null),d=x.useRef(null),u=e.status==="working",m=e.status==="error",h=!m&&!!e.lastError&&!!e.lastErrorAt&&Date.now()-new Date(e.lastErrorAt).getTime()<1800*1e3,p=u?t.find(C=>C.assignedAgentId===e.id&&C.status==="in_progress"):null,y=e.currentActivity;x.useEffect(()=>{if(!a)return;const C=w=>{l.current&&!l.current.contains(w.target)&&i(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[a]),x.useLayoutEffect(()=>{if(!a||!d.current)return;const C=d.current,w=C.getBoundingClientRect(),N=window.innerWidth;w.right>N-8&&(C.style.left="auto",C.style.right="0"),w.left<8&&(C.style.left="0",C.style.right="auto");const S=N-16;w.width>S&&(C.style.width=`${S}px`)},[a]);const g=m?"bg-red-400 animate-pulse":h?"bg-amber-400":u?"bg-blue-400 animate-pulse":"bg-green-400",v=s(m?"common:status.error":u?"common:status.working":"common:status.idle"),j=y?y.type==="heartbeat"?s("page.activityHeartbeat",{name:y.heartbeatName??y.label}):y.type==="chat"?y.label:y.type==="task"?s("page.activityTask",{label:y.label}):y.label:s("page.processing");return n.jsxs("div",{className:"relative",ref:l,children:[n.jsxs("button",{onClick:()=>i(C=>!C),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors ${u&&!h?"bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20":m?"bg-red-500/10 border border-red-500/20 hover:bg-red-500/20":h?"bg-amber-500/10 border border-amber-500/20 hover:bg-amber-500/20":"bg-green-500/10 border border-green-500/20 hover:bg-green-500/20"}`,children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${g}`}),n.jsx("span",{className:`text-xs ${m?"text-red-500":h?"text-amber-600":u?"text-blue-500":"text-green-600"}`,children:v}),h&&n.jsx("span",{className:"text-[9px] text-amber-500",children:"⚠"}),e.mailboxDepth!=null&&e.mailboxDepth>0&&n.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:e.mailboxDepth})]}),a&&m&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:s("page.errorDetails")}),n.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[n.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:e.lastError||s("page.agentErrorFallback")}),e.lastErrorAt&&n.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(e.lastErrorAt).toLocaleString()})]}),n.jsx("button",{onClick:()=>{i(!1),r?.(e.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:s("page.viewAgentProfileArrow")})]}),a&&h&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-amber-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-amber-600 uppercase font-semibold",children:s("page.recentErrorDetails")}),n.jsxs("div",{className:"bg-amber-500/10 border border-amber-500/20 rounded-lg p-2.5",children:[n.jsx("pre",{className:"text-[10px] text-amber-600/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:e.lastError}),e.lastErrorAt&&n.jsx("div",{className:"text-[9px] text-amber-500/50 mt-1.5 border-t border-amber-500/10 pt-1",children:new Date(e.lastErrorAt).toLocaleString()})]}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:s("page.errorRecovered")})]}),a&&u&&n.jsxs("div",{ref:d,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[n.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:s("page.currentActivity")}),p?n.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{i(!1),pt.navigate(Te.WORK,{openTask:p.id})},children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-brand-500 truncate",children:p.title}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:s("page.workingOnTaskHint")})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):n.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${y?.type==="heartbeat"||y?.type==="chat","bg-blue-400 animate-pulse"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:j}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:y?.type==="heartbeat"?s("page.activityDescHeartbeat"):y?.type==="chat"?s("page.activityDescChat"):s("page.activityDescFallback")})]})]}),n.jsx("button",{onClick:()=>{i(!1),r?.(e.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:s("page.viewMindArrow")})]})]})}const _G=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"cyberpunk",label:"Cyberpunk"},{value:"mono",label:"Mono"}],Qb="markus-theme";function Yk(e){const t=document.documentElement;t.classList.remove("light","dark","cyberpunk","mono"),e==="light"?t.classList.add("light"):e==="dark"?t.classList.add("dark"):e==="cyberpunk"?t.classList.add("cyberpunk"):e==="mono"&&t.classList.add("mono")}function zG(){try{const e=localStorage.getItem(Qb);if(e==="midnight")return localStorage.setItem(Qb,"dark"),"dark";if(e==="light"||e==="dark"||e==="system"||e==="cyberpunk"||e==="mono")return e}catch{}return"system"}function $G(){const[e,t]=x.useState(zG),r=x.useCallback(s=>{t(s);try{localStorage.setItem(Qb,s)}catch{}Yk(s)},[]);return x.useEffect(()=>{Yk(e)},[e]),{mode:e,setMode:r}}function BG(e){return e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed((e%1e3===0,0))}K`:String(e)}function Xk(e){return e===0?"-":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(2)}`:`$${e.toFixed(e%1===0?0:2)}`}function HG(e){return e.maxInputTokens>0||e.inputCostPer1MTokens>0||e.outputCostPer1MTokens>0}function ch({models:e,selectedModel:t,onSelect:r,loading:s,compact:a,maxVisible:i}){const[l,d]=x.useState(""),[u,m]=x.useState(!1),h=x.useMemo(()=>{if(!l)return e;const v=l.toLowerCase();return e.filter(j=>j.id.toLowerCase().includes(v))},[e,l]),p=i??(a?5:10),y=u?h:h.slice(0,p),g=h.length>p;return s?n.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-fg-tertiary",children:[n.jsx("div",{className:"w-4 h-4 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),"Loading models..."]}):e.length===0?n.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:"No models available for this provider."}):n.jsxs("div",{className:"space-y-2",children:[e.length>5&&n.jsx("input",{type:"text",value:l,onChange:v=>{d(v.target.value),m(!1)},placeholder:"Filter models...",className:"w-full px-3 py-1.5 bg-surface-overlay border border-border-default rounded-lg text-xs text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:border-brand-500"}),n.jsx("div",{className:`space-y-1 ${a?"max-h-[280px] overflow-y-auto":""}`,children:y.map(v=>{const j=v.id===t;return n.jsxs("button",{type:"button",onClick:()=>r(v.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${j?"bg-brand-500/10 border border-brand-500/30":"hover:bg-surface-overlay border border-transparent"}`,children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${j?"border-brand-500":"border-border-default"}`,children:j&&n.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),n.jsx("span",{className:`text-xs font-medium ${j?"text-brand-500":"text-fg-primary"}`,children:v.id})]}),j&&n.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:"Active"})]}),HG(v)&&n.jsxs("div",{className:"ml-5 mt-0.5 flex items-center gap-2 text-[10px] text-fg-tertiary flex-wrap",children:[v.maxInputTokens>0&&n.jsxs("span",{children:[BG(v.maxInputTokens)," ctx"]}),v.maxInputTokens>0&&(v.inputCostPer1MTokens>0||v.outputCostPer1MTokens>0)&&n.jsx("span",{className:"text-fg-quaternary",children:"|"}),(v.inputCostPer1MTokens>0||v.outputCostPer1MTokens>0)&&n.jsxs("span",{children:[Xk(v.inputCostPer1MTokens),"/",Xk(v.outputCostPer1MTokens)," per 1M"]})]}),!a&&n.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[v.capabilities.functionCalling&&n.jsx(Mu,{label:"Tools"}),v.capabilities.vision&&n.jsx(Mu,{label:"Vision"}),v.capabilities.reasoning&&n.jsx(Mu,{label:"Reasoning"}),v.capabilities.promptCaching&&n.jsx(Mu,{label:"Caching"}),v.capabilities.webSearch&&n.jsx(Mu,{label:"Search"})]})]},v.id)})}),g&&!u&&n.jsxs("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:["Show all ",h.length," models..."]}),u&&g&&n.jsx("button",{type:"button",onClick:()=>m(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:"Show less"})]})}function Mu({label:e}){return n.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] bg-surface-overlay text-fg-tertiary border border-border-default",children:e})}const Bu=[{id:"anthropic",label:"Anthropic",envKey:"ANTHROPIC_API_KEY",defaultModel:"claude-opus-4-6"},{id:"openai",label:"OpenAI",envKey:"OPENAI_API_KEY",defaultModel:"gpt-5.4"},{id:"google",label:"Google Gemini",envKey:"GOOGLE_API_KEY",defaultModel:"gemini-3-1-pro"},{id:"deepseek",label:"DeepSeek",envKey:"DEEPSEEK_API_KEY",baseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash"},{id:"siliconflow",label:"SiliconFlow",envKey:"SILICONFLOW_API_KEY",baseUrl:"https://api.siliconflow.cn/v1",defaultModel:"Qwen/Qwen3.5-35B-A3B"},{id:"minimax",label:"MiniMax",envKey:"MINIMAX_API_KEY",baseUrl:"https://api.minimax.io/v1",defaultModel:"MiniMax-M2.7"},{id:"openrouter",label:"OpenRouter",envKey:"OPENROUTER_API_KEY",baseUrl:"https://openrouter.ai/api/v1",defaultModel:"xiaomi/mimo-v2-pro:free"},{id:"zai",label:"ZAI (GLM)",envKey:"ZAI_API_KEY",baseUrl:"https://api.z.ai/api/paas/v4",defaultModel:"glm-5.1"},{id:"xai",label:"xAI (Grok)",envKey:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",defaultModel:"grok-3"},{id:"mistral",label:"Mistral AI",envKey:"MISTRAL_API_KEY",baseUrl:"https://api.mistral.ai/v1",defaultModel:"mistral-large-latest"},{id:"groq",label:"Groq",envKey:"GROQ_API_KEY",baseUrl:"https://api.groq.com/openai/v1",defaultModel:"llama-3.3-70b-versatile"},{id:"perplexity",label:"Perplexity",envKey:"PERPLEXITY_API_KEY",baseUrl:"https://api.perplexity.ai",defaultModel:"sonar-pro"},{id:"cohere",label:"Cohere",envKey:"COHERE_API_KEY",baseUrl:"https://api.cohere.ai/compatibility/v1",defaultModel:"command-r-plus"},{id:"together_ai",label:"Together AI",envKey:"TOGETHER_API_KEY",baseUrl:"https://api.together.xyz/v1",defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo"},{id:"fireworks_ai",label:"Fireworks AI",envKey:"FIREWORKS_API_KEY",baseUrl:"https://api.fireworks.ai/inference/v1",defaultModel:"accounts/fireworks/models/llama-v3p3-70b-instruct"},{id:"moonshot",label:"Moonshot (Kimi)",envKey:"MOONSHOT_API_KEY",baseUrl:"https://api.moonshot.cn/v1",defaultModel:"moonshot-v1-auto"},{id:"volcengine",label:"Volcengine (Doubao)",envKey:"VOLCENGINE_API_KEY",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",defaultModel:"doubao-1.5-pro-32k"},{id:"dashscope",label:"DashScope (Qwen)",envKey:"DASHSCOPE_API_KEY",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModel:"qwen-max"},{id:"ollama",label:"Ollama (Local)",envKey:"OLLAMA_BASE_URL",baseUrl:"http://localhost:11434/v1",defaultModel:"llama3"}],XS=[{id:"appearance",labelKey:"nav.appearance"},{id:"providers",labelKey:"nav.providers",adminOnly:!0},{id:"execution",labelKey:"nav.execution",adminOnly:!0},{id:"browser",labelKey:"nav.browser",adminOnly:!0},{id:"search",labelKey:"nav.search",adminOnly:!0},{id:"storage",labelKey:"nav.storage",adminOnly:!0},{id:"users",labelKey:"nav.users",adminOnly:!0},{id:"remote",labelKey:"nav.remote",adminOnly:!0}];function Qk(){const t=window.location.hash.slice(1).split("/");if(t[0]==="settings"&&t[1]){const r=t[1];if(XS.some(s=>s.id===r))return r}return null}function Zk({theme:e,onThemeChange:t,authUser:r,onLogout:s,onUserUpdated:a}={}){const{t:i,i18n:l}=ft(["settings","common"]),d=Ds(),[u,m]=x.useState(!1),[h,p]=x.useState(!1),y=x.useRef(null),[g,v]=x.useState(Qk);x.useEffect(()=>{const oe=()=>v(Qk());return window.addEventListener("hashchange",oe),()=>window.removeEventListener("hashchange",oe)},[]);const j=x.useCallback(oe=>{v(oe),history.pushState(null,"",`#settings/${oe}`)},[]),C=x.useCallback(()=>{v(null),history.pushState(null,"","#settings")},[]),w=g??(d?null:"appearance");x.useEffect(()=>{const oe=()=>p(!0);return window.addEventListener("markus:open-edit-profile",oe),()=>window.removeEventListener("markus:open-edit-profile",oe)},[]),x.useEffect(()=>{if(!u)return;const oe=Ee=>{y.current&&!y.current.contains(Ee.target)&&m(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[u]);const[N,S]=x.useState(null),[T,M]=x.useState(null),[D,I]=x.useState(""),[$,B]=x.useState(!1),[R,U]=x.useState(null),[W,F]=x.useState(null),[L,z]=x.useState(null),[E,_]=x.useState({}),[G,V]=x.useState(null),[O,q]=x.useState(null),[J,H]=x.useState(!1),[Z,Y]=x.useState(null),[ee,ae]=x.useState(null),[Q,me]=x.useState(!1),[Ae,Me]=x.useState(null),[He,je]=x.useState({}),[xe,Pe]=x.useState(!1),[Ce,Ye]=x.useState(null),[Qe,ct]=x.useState(!1),[st,zt]=x.useState(""),[mt,te]=x.useState(!1),[de,be]=x.useState(null),[se,fe]=x.useState([]),[$e,Ne]=x.useState([]),[Ze,pe]=x.useState(null),[ze,Fe]=x.useState(null),[Je,gt]=x.useState(""),[nt,Et]=x.useState(null),dt=x.useRef(null),Ve=x.useRef(!1),[Rt,un]=x.useState(!1),[yn,sn]=x.useState(200),[In,jn]=x.useState(!1),[Vt,mn]=x.useState(null),[Vn,Xn]=x.useState(!1),[Rr,qe]=x.useState(1),[St,_e]=x.useState(!1),[Tt,Ot]=x.useState(null),[Gt,Tn]=x.useState(!1),[_n,Sn]=x.useState(0),[Fn,mr]=x.useState(!0),[rr,fr]=x.useState(!1),[Qn,ir]=x.useState(!1),[Ie,At]=x.useState(9333),[It,qt]=x.useState(!1),[Jt,tn]=x.useState(null),[An,br]=x.useState(null),[an,ye]=x.useState({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),[at,yt]=x.useState(!1),[Ht,ln]=x.useState(null),[Mt,Ln]=x.useState(null),[Zn,zn]=x.useState(!1),[Jn,Pn]=x.useState(new Set),[on,lr]=x.useState(null),[qr,cr]=x.useState(!1),yr=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`}),ur=x.useCallback(()=>{le.health().then(S).catch(()=>{}),fetch("/api/settings/llm").then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>{oe&&typeof oe=="object"&&"providers"in oe&&(M(oe),I(oe.defaultProvider))}).catch(()=>{})},[]),Rs=x.useCallback(()=>{fetch("/api/settings/oauth/providers").then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>fe(oe.providers??[])).catch(()=>{})},[]),ha=x.useCallback(()=>{fetch("/api/settings/oauth/profiles",{headers:yr()}).then(oe=>oe.ok?oe.json():Promise.reject(oe.status)).then(oe=>Ne(oe.profiles??[])).catch(()=>{})},[]),pa=x.useCallback(()=>{le.settings.getAgent().then(oe=>{oe&&typeof oe.maxToolIterations=="number"&&sn(oe.maxToolIterations),oe?.cognitive&&(Xn(oe.cognitive.enabled??!1),qe(oe.cognitive.maxDepth??1))}).catch(()=>{})},[]),Or=x.useCallback(()=>{le.settings.getBrowser().then(oe=>{oe&&(Tn(oe.bringToFront??!1),Sn(oe.remoteDebuggingPort??0),mr(oe.autoCloseTabs??!0),fr(oe.autoClickAllowDialog??!1),ir(oe.extensionConnected??!1),At(oe.extensionBridgePort??9333))}).catch(()=>{})},[]),Ja=x.useCallback(()=>{le.settings.getSearch().then(oe=>{oe&&br(oe)}).catch(()=>{})},[]),ga=x.useCallback(()=>{zn(!0),le.system.storage().then(Ln).catch(()=>{}).finally(()=>zn(!1)),le.system.orphans().then(lr).catch(()=>{})},[]);x.useEffect(()=>{ur(),Rs(),ha(),pa(),Or(),Ja(),ga()},[ur,Rs,ha,pa,Or,Ja,ga]),x.useEffect(()=>{const oe=()=>ga();return window.addEventListener("markus:data-changed",oe),()=>window.removeEventListener("markus:data-changed",oe)},[ga]),x.useEffect(()=>{!W||E[W]||(V(W),le.modelCatalog.getLive(W).then(oe=>{_(Ee=>({...Ee,[W]:oe.models}))}).catch(()=>{le.modelCatalog.getByProvider(W).then(oe=>{_(Ee=>({...Ee,[W]:oe.models}))}).catch(()=>{})}).finally(()=>V(null)))},[W]);const na=x.useCallback(async()=>{me(!0),Me(null),ae(null),je({});try{const oe=await fetch("/api/settings/env-models",{headers:yr()});if(!oe.ok){Me({type:"err",text:i("envConfig.detectionFailedHttp",{status:oe.status})});return}const Ee=await oe.json();if(ae(Ee),Ee.detected.length===0)Me({type:"err",text:i("envConfig.noKeysFound")});else{const et={};for(const hn of Ee.detected)et[hn.provider]=!0;je(et)}}catch{Me({type:"err",text:i("envConfig.failedToDetect")})}finally{me(!1)}},[i]),cs=x.useCallback(async()=>{ct(!0),be(null),Ye(null);try{const oe=await fetch("/api/settings/detect-ollama",{headers:yr()});if(!oe.ok){be({type:"err",text:i("ollama.detectFailed")});return}const Ee=await oe.json();Ye(Ee),Ee.found&&Ee.models&&Ee.models.length>0?zt(Ee.models[0].name):Ee.found||be({type:"err",text:Ee.error||i("ollama.notRunning")})}catch{be({type:"err",text:i("ollama.detectFailed")})}finally{ct(!1)}},[i]),ei=T?Object.values(T.providers).some(oe=>oe.configured):!1;x.useEffect(()=>{T&&!ei&&!Ve.current&&(Ve.current=!0,na(),cs())},[T,ei,na,cs]);const ti=async()=>{if(!(!D||D===T?.defaultProvider)){B(!0),U(null);try{const oe=await fetch("/api/settings/llm",{method:"POST",headers:yr(),body:JSON.stringify({defaultProvider:D})}),Ee=await oe.json();oe.ok?(M(Ee),U({type:"ok",text:i("defaultProvider.updated",{name:Ee.defaultProvider})})):U({type:"err",text:Ee.error??i("modelProviders.saveFailed")})}catch{U({type:"err",text:i("common:networkError")})}finally{B(!1)}}},Oa=async(oe,Ee)=>{z(oe);try{const et=await fetch(`/api/settings/llm/providers/${oe}/toggle`,{method:"POST",headers:yr(),body:JSON.stringify({enabled:Ee})});if(et.ok){const hn=await et.json();M(hn)}}catch{}finally{z(null)}},bi=async()=>{H(!0),Y(null);try{const Ee=await(await fetch("/api/settings/import/openclaw",{method:"POST",headers:yr(),body:JSON.stringify({preview:!0})})).json();"error"in Ee?Y({type:"err",text:Ee.error}):q(Ee)}catch{Y({type:"err",text:i("openClaw.detectFailed")})}finally{H(!1)}},ni=async()=>{H(!0),Y(null);try{const Ee=await(await fetch("/api/settings/import/openclaw",{method:"POST",headers:yr(),body:JSON.stringify({preview:!1})})).json();"error"in Ee?Y({type:"err",text:Ee.error}):(Y({type:"ok",text:i("openClaw.importedFrom",{count:Ee.appliedModels})}),ur())}catch{Y({type:"err",text:i("openClaw.importFailed")})}finally{H(!1)}},ra=async()=>{if(!ee)return;const oe=ee.detected.filter(Ee=>He[Ee.provider]);if(oe.length===0){Me({type:"err",text:i("envConfig.selectAtLeastOne")});return}Pe(!0),Me(null);try{const Ee=await fetch("/api/settings/env-models",{method:"POST",headers:yr(),body:JSON.stringify({providers:oe.map(hn=>({provider:hn.provider,model:hn.model,baseUrl:hn.baseUrl,enabled:!0}))})});if(!Ee.ok){Me({type:"err",text:i("envConfig.applyFailed",{status:Ee.status})});return}const et=await Ee.json();Me({type:"ok",text:et.message}),ae(null),je({}),ur()}catch{Me({type:"err",text:i("envConfig.failedToApply")})}finally{Pe(!1)}},Gs=async()=>{if(!(!Ce?.found||!st)){te(!0),be(null);try{const oe=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:"ollama",model:st,baseUrl:Ce.baseUrl||"http://localhost:11434"})});if(oe.ok){const Ee=await oe.json();M(Ee),be({type:"ok",text:i("ollama.configured",{model:st})}),Ye(null)}else{const Ee=await oe.json();be({type:"err",text:Ee.error||i("ollama.applyFailed")})}}catch{be({type:"err",text:i("ollama.applyFailed")})}finally{te(!1)}}};x.useEffect(()=>()=>{dt.current&&clearInterval(dt.current)},[]),x.useEffect(()=>{if(w!=="browser"||Qn)return;const oe=setInterval(async()=>{try{(await le.settings.getBrowser()).extensionConnected&&(ir(!0),clearInterval(oe))}catch{}},5e3);return()=>clearInterval(oe)},[w,Qn]);const[xa,Is]=x.useState(!1),[Kn,js]=x.useState({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),[ba,Ns]=x.useState(!1),[vr,Ls]=x.useState(null),[as,Ur]=x.useState([]),[ri,Ss]=x.useState(!1),[sa,_a]=x.useState(null),[Wn,Cs]=x.useState({apiKey:"",baseUrl:"",model:"",contextWindow:0,maxOutputTokens:0,costInput:0,costOutput:0}),[Ps,Mi]=x.useState(!1),[_r,wn]=x.useState(null),[Os,Hs]=x.useState(""),[si,ai]=x.useState(!1),[Ys,$r]=x.useState(null),[Fs,ya]=x.useState(null),[qs,Zr]=x.useState({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1}),[_s,va]=x.useState(!1),Di=async(oe,Ee)=>{if(!oe||oe==="__custom__")return;Ss(!0),$r(null);const et=Bu.find(Cn=>Cn.id===oe),hn=Kn.baseUrl||et?.baseUrl;try{if(Ee){const Cn=await le.modelCatalog.validateKey(oe,Ee,hn||void 0);!Cn.valid&&Cn.error&&$r({type:"err",text:Cn.error}),Ur(Cn.models)}else{const Cn=await le.modelCatalog.getByProvider(oe);Ur(Cn.models)}}catch{Ur([])}finally{Ss(!1)}},wa=async()=>{if(!(!Kn.name||!Kn.model)){Ns(!0),Ls(null),$r(null);try{const oe=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:Kn.name,apiKey:Kn.apiKey||void 0,baseUrl:Kn.baseUrl||void 0,model:Kn.model,contextWindow:Kn.contextWindow||void 0,maxOutputTokens:Kn.maxOutputTokens||void 0,cost:Kn.costInput||Kn.costOutput?{input:Kn.costInput,output:Kn.costOutput}:void 0})}),Ee=await oe.json();oe.ok?(M(Ee),Is(!1),Hs(""),Ur([]),js({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),$r({type:"ok",text:i("modelProviders.providerAdded",{name:Kn.name})})):$r({type:"err",text:Ee.error??i("modelProviders.failedToAdd")})}catch{$r({type:"err",text:i("common:networkError")})}finally{Ns(!1)}}},ka=async(oe,Ee)=>{if(!Os.trim())return;ai(!0),$r(null);const et=Bu.find(zs=>zs.id===oe),hn=et?.defaultModel??oe,Cn=et?.baseUrl;try{const zs=await fetch("/api/settings/llm/providers",{method:"POST",headers:yr(),body:JSON.stringify({name:oe,apiKey:Os.trim(),model:hn,baseUrl:Cn})}),no=await zs.json();zs.ok?(M(no),Hs(""),Ur([]),$r({type:"ok",text:i("modelProviders.quickSetupSuccess",{name:et?.label??oe})})):$r({type:"err",text:no.error??i("modelProviders.failedToAdd")})}catch{$r({type:"err",text:i("common:networkError")})}finally{ai(!1)}},ja=(oe,Ee)=>{_a(oe),Cs({apiKey:"",baseUrl:Ee.baseUrl??"",model:Ee.model,contextWindow:Ee.contextWindow??0,maxOutputTokens:Ee.maxOutputTokens??0,costInput:Ee.cost?.input??0,costOutput:Ee.cost?.output??0})},ie=async oe=>{Mi(!0);try{const Ee={};Wn.apiKey&&(Ee.apiKey=Wn.apiKey),Wn.baseUrl!==void 0&&(Ee.baseUrl=Wn.baseUrl),Wn.model&&(Ee.model=Wn.model),Wn.contextWindow&&(Ee.contextWindow=Wn.contextWindow),Wn.maxOutputTokens&&(Ee.maxOutputTokens=Wn.maxOutputTokens),(Wn.costInput||Wn.costOutput)&&(Ee.cost={input:Wn.costInput,output:Wn.costOutput});const et=await fetch(`/api/settings/llm/providers/${oe}`,{method:"PUT",headers:yr(),body:JSON.stringify(Ee)});if(et.ok){const hn=await et.json();M(hn),_a(null)}}catch{}finally{Mi(!1)}},Xe=async oe=>{wn(oe);try{const Ee=await fetch(`/api/settings/llm/providers/${oe}`,{method:"DELETE",headers:yr()});if(Ee.ok){const et=await Ee.json();M(et),I(et.defaultProvider)}}catch{}finally{wn(null)}},ot=async oe=>{if(!(!qs.id||!qs.name)){va(!0);try{const Ee=await fetch(`/api/settings/llm/providers/${oe}/models`,{method:"POST",headers:yr(),body:JSON.stringify({id:qs.id,name:qs.name,contextWindow:qs.contextWindow,maxOutputTokens:qs.maxOutputTokens,cost:{input:qs.costInput,output:qs.costOutput},reasoning:qs.reasoning||void 0,inputTypes:qs.vision?["text","image"]:["text"]})});if(Ee.ok){const et=await Ee.json();M(et),ya(null),Zr({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})}}catch{}finally{va(!1)}}},Dt=async(oe,Ee)=>{try{const et=await fetch(`/api/settings/llm/providers/${oe}/models/${encodeURIComponent(Ee)}`,{method:"DELETE",headers:yr()});if(et.ok){const hn=await et.json();M(hn)}}catch{}},fn=new Set(["claude-opus-4-6","claude-sonnet-4-20250514","claude-3-5-haiku-20241022","gpt-5.4","gpt-4o","o4-mini","gemini-3-1-pro","gemini-2.5-flash","MiniMax-M2.7","MiniMax-M2.5","xiaomi/mimo-v2-pro","anthropic/claude-opus-4-6","openai/gpt-5.4","google/gemini-3-1-pro","deepseek-v4-flash","deepseek-v4-pro","deepseek-chat","deepseek-reasoner"]),[hr,cn]=x.useState(null),[bt,ds]=x.useState(null),[Vr,us]=x.useState({}),is=async oe=>{ds(oe),us(Ee=>{const et={...Ee};return delete et[oe],et});try{const Ee=await fetch(`/api/settings/llm/providers/${oe}/test`,{method:"POST",headers:yr()});if(!Ee.ok){const hn=await Ee.json().catch(()=>({}));us(Cn=>({...Cn,[oe]:{ok:!1,error:hn.error??`HTTP ${Ee.status}`,errorCode:Ee.status}}));return}const et=await Ee.json();us(hn=>({...hn,[oe]:et}))}catch{us(Ee=>({...Ee,[oe]:{ok:!1,error:i("common:networkError")}}))}finally{ds(null)}},Kr=async(oe,Ee)=>{cn(`${oe}:${Ee}`);try{const et=await fetch(`/api/settings/llm/providers/${oe}/model`,{method:"POST",headers:yr(),body:JSON.stringify({model:Ee})});if(et.ok){const hn=await et.json();M(hn)}}catch{}finally{cn(null)}},ms=async()=>{if(an.serperApiKey||an.tavilyApiKey||an.bingApiKey||an.googleSearchApiKey||an.googleSearchCx||an.serpApiKey||an.braveApiKey||an.exaApiKey||an.bochaApiKey){yt(!0),ln(null);try{const Ee={};an.serperApiKey&&(Ee.serperApiKey=an.serperApiKey),an.tavilyApiKey&&(Ee.tavilyApiKey=an.tavilyApiKey),an.bingApiKey&&(Ee.bingApiKey=an.bingApiKey),an.googleSearchApiKey&&(Ee.googleSearchApiKey=an.googleSearchApiKey),an.googleSearchCx&&(Ee.googleSearchCx=an.googleSearchCx),an.serpApiKey&&(Ee.serpApiKey=an.serpApiKey),an.braveApiKey&&(Ee.braveApiKey=an.braveApiKey),an.exaApiKey&&(Ee.exaApiKey=an.exaApiKey),an.bochaApiKey&&(Ee.bochaApiKey=an.bochaApiKey);const et=await le.settings.updateSearch(Ee);br(et),ye({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),ln({type:"ok",text:i("searchApi.saved")})}catch{ln({type:"err",text:i("searchApi.failedToSave")})}finally{yt(!1)}}},Nr=T?.providers?Object.entries(T.providers).filter(([,oe])=>oe.configured&&oe.enabled).map(([oe])=>oe):[],eo=T&&!ei&&!Rt,Ri=r?.role==="owner"||r?.role==="admin",to=XS.filter(oe=>!oe.adminOnly||Ri);return n.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[h&&r&&n.jsx(WG,{authUser:r,onClose:()=>p(!1),onSaved:oe=>{p(!1),a?.(oe)}}),n.jsxs("aside",{className:"hidden md:flex flex-col w-56 shrink-0 border-r border-border-default bg-surface-secondary overflow-y-auto",children:[n.jsx("div",{className:"px-3 pt-4 pb-2",children:n.jsxs("button",{onClick:()=>{pt.navigate(Te.HOME)},className:"flex items-center gap-2 px-2 py-1.5 rounded-lg text-sm text-fg-secondary hover:text-fg-primary hover:bg-surface-overlay transition-colors",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]}),i("common:back",{defaultValue:"Back"})]})}),n.jsx("div",{className:"px-5 pb-4",children:n.jsx("h2",{className:"text-base font-semibold text-fg-primary",children:i("title")})}),n.jsx("nav",{className:"flex-1 px-3 pb-4 space-y-0.5",children:to.map(oe=>n.jsx("button",{onClick:()=>j(oe.id),className:`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${w===oe.id?"bg-brand-600/10 text-brand-600 dark:text-brand-400 font-medium":"text-fg-secondary hover:text-fg-primary hover:bg-surface-overlay"}`,children:i(`settings:${oe.labelKey}`)},oe.id))}),r&&n.jsx("div",{className:"px-3 pb-4 border-t border-border-default pt-3",children:n.jsxs("div",{ref:y,className:"relative",children:[n.jsxs("button",{onClick:()=>m(!u),className:"w-full flex items-center gap-2.5 px-3 py-2 rounded-lg hover:bg-surface-overlay transition-colors",children:[n.jsx(Sr,{name:r.name||i("common:userPlaceholder"),avatarUrl:r.avatarUrl,size:24}),n.jsx("span",{className:"text-sm text-fg-secondary truncate flex-1 text-left",children:r.name||i("common:userPlaceholder")})]}),u&&n.jsxs("div",{className:"absolute left-0 bottom-full mb-1 bg-surface-secondary border border-border-default rounded-xl shadow-xl z-50 overflow-hidden",style:{minWidth:200},children:[n.jsxs("div",{className:"px-4 py-3 border-b border-border-default",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:r.name||i("common:userPlaceholder")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r.email||r.role})]}),n.jsxs("div",{className:"py-1",children:[n.jsxs("button",{onClick:()=>{m(!1),p(!0)},className:"w-full flex items-center gap-2.5 px-4 py-2 text-sm text-fg-secondary hover:bg-surface-overlay transition-colors",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),i("common:profile.editProfile")]}),s&&n.jsxs("button",{onClick:()=>{m(!1),s()},className:"w-full flex items-center gap-2.5 px-4 py-2 text-sm text-red-500 hover:bg-red-500/10 transition-colors",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),i("common:signOut",{defaultValue:"Sign Out"})]})]})]})]})})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[d&&w===null&&n.jsxs("div",{className:"flex flex-col h-full",children:[n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary",children:[n.jsx("button",{onClick:()=>pt.navigate(Te.HOME),className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:i("title")})]}),n.jsx("nav",{className:"flex-1 overflow-y-auto py-2 px-3",children:to.map(oe=>n.jsxs("button",{onClick:()=>j(oe.id),className:"w-full flex items-center justify-between px-4 py-3 rounded-lg text-sm text-fg-primary hover:bg-surface-overlay transition-colors",children:[n.jsx("span",{children:i(`settings:${oe.labelKey}`)}),n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})]},oe.id))})]}),d&&w!==null&&n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary sticky top-0 z-10",children:[n.jsx("button",{onClick:C,className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:i(`settings:${to.find(oe=>oe.id===w)?.labelKey||"title"}`)})]}),w!==null&&n.jsxs("div",{className:"p-7 space-y-10 max-w-4xl mx-auto w-full",children:[w==="appearance"&&n.jsx(hi,{title:i("appearance.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("appearance.theme")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("appearance.themeDesc")})]}),n.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:_G.map(({value:oe})=>n.jsx("button",{onClick:()=>t?.(oe),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${e===oe?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:i(`appearance.modes.${oe}`)},oe))})]}),n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between mt-5 pt-5 border-t border-border-default/50",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("appearance.language")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("appearance.languageDesc")})]}),n.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:uw.map(({code:oe,label:Ee})=>n.jsx("button",{onClick:()=>{l.changeLanguage(oe)},className:`px-3 py-1.5 text-xs rounded-md transition-colors ${l.language===oe||oe==="en"&&!uw.some(et=>et.code===l.language)?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:Ee},oe))})]})]})}),Ri&&n.jsxs(n.Fragment,{children:[w==="providers"&&n.jsxs(n.Fragment,{children:[eo&&n.jsxs("div",{className:"relative bg-gradient-to-br from-brand-500/10 to-surface-secondary border border-brand-500/20 rounded-2xl p-6 space-y-5",children:[n.jsx("button",{onClick:()=>un(!0),className:"absolute top-4 right-4 text-fg-tertiary hover:text-fg-secondary text-xs",children:i("setupGuide.skip")}),n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:i("setupGuide.title")}),n.jsx("p",{className:"text-sm text-fg-secondary mt-1",children:i("setupGuide.subtitle")})]}),n.jsxs(Du,{step:i("setupGuide.fromEnv.step"),title:i("setupGuide.fromEnv.title"),description:i("setupGuide.fromEnv.description"),active:!!(ee&&ee.detected.length>0),children:[Q&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:detecting")}),ee&&ee.detected.length>0&&n.jsxs("div",{className:"space-y-2",children:[ee.detected.map(oe=>n.jsxs("label",{className:"flex items-center gap-3 bg-surface-elevated/30 rounded-lg px-3 py-2 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[n.jsx("input",{type:"checkbox",checked:He[oe.provider]??!1,onChange:Ee=>je({...He,[oe.provider]:Ee.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"text-sm text-fg-primary",children:oe.displayName}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-2",children:oe.model})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:oe.apiKeyPreview})]},oe.provider)),n.jsx("button",{onClick:()=>{ra()},disabled:xe||Object.values(He).filter(Boolean).length===0,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:xe?i("common:applying"):i("setupGuide.applyProviders",{count:Object.values(He).filter(Boolean).length})})]}),ee&&ee.detected.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:n.jsx(n0,{i18nKey:"settings:setupGuide.fromEnv.noKeysHint",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),Ae&&n.jsx(Ua,{type:Ae.type,text:Ae.text})]}),n.jsxs(Du,{step:i("setupGuide.fromOllama.step"),title:i("setupGuide.fromOllama.title"),description:i("setupGuide.fromOllama.description"),active:!!Ce?.found,children:[Qe&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:detecting")}),Ce?.found&&Ce.models&&Ce.models.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-green-600",children:i("ollama.foundModels",{count:Ce.models.length,url:Ce.baseUrl})}),n.jsx("select",{value:st,onChange:oe=>zt(oe.target.value),className:"w-full px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary focus:outline-none focus:ring-2 focus:ring-brand-500",children:Ce.models.map(oe=>n.jsxs("option",{value:oe.name,children:[oe.name,oe.parameterSize?` (${oe.parameterSize})`:"",oe.family?` — ${oe.family}`:""]},oe.name))}),n.jsx("button",{onClick:()=>{Gs()},disabled:mt||!st,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:mt?i("common:applying"):i("ollama.useModel",{model:st})})]}),!Qe&&!Ce&&n.jsx("button",{onClick:()=>{cs()},className:"px-4 py-2 border border-border-default hover:bg-surface-elevated text-fg-secondary text-sm rounded-lg transition-colors",children:i("ollama.detect")}),Ce&&!Ce.found&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("ollama.notRunning")}),de&&n.jsx(Ua,{type:de.type,text:de.text})]}),n.jsxs(Du,{step:i("setupGuide.fromOpenClaw.step"),title:i("setupGuide.fromOpenClaw.title"),description:i("setupGuide.fromOpenClaw.description"),children:[O?O.found?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"text-xs text-green-600",children:[i("setupGuide.foundPrefix")," ",n.jsx("code",{className:"text-fg-secondary",children:O.summary.configPath})]}),O.summary.models&&n.jsx("div",{className:"text-xs text-fg-secondary",children:i("openClaw.providersModels",{providers:O.summary.models.providerCount,models:O.summary.models.providers.reduce((oe,Ee)=>oe+Ee.modelCount,0)})}),n.jsx("button",{onClick:()=>{ni()},disabled:J,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:i(J?"common:importing":"openClaw.importConfigs")})]}):n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("openClaw.notFound")}):n.jsx("button",{onClick:()=>{bi()},disabled:J,className:"px-4 py-2 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-secondary text-sm rounded-lg transition-colors",children:i(J?"common:detecting":"openClaw.detectShort")}),Z&&n.jsx(Ua,{type:Z.type,text:Z.text})]}),n.jsx(Du,{step:i("setupGuide.manual.step"),title:i("setupGuide.manual.title"),description:n.jsx(n0,{i18nKey:"settings:setupGuide.manual.description",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),/Chrome\/\d/.test(navigator.userAgent)&&!/Edg\//.test(navigator.userAgent)&&n.jsx(Du,{step:i("setupGuide.browserExtension.step"),title:i("setupGuide.browserExtension.title"),description:i("setupGuide.browserExtension.description"),active:Qn,children:Qn?n.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-400",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),i("setupGuide.browserExtension.alreadyConnected")]}):n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0);try{await le.settings.downloadExtensionZip()}catch{}qt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40 inline-flex items-center gap-1.5",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),i("setupGuide.browserExtension.downloadBtn")]}),n.jsxs("button",{disabled:It,onClick:async()=>{try{await le.settings.openExtensionsPage()}catch{}},className:"px-3 py-1.5 text-xs border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40 inline-flex items-center gap-1.5",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),i("setupGuide.browserExtension.openChromeBtn")]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("setupGuide.browserExtension.loadHint")})]})})]}),n.jsx(hi,{title:i("systemStatus.title"),children:N?n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsx(Ux,{label:i("systemStatus.status"),value:N.status==="ok"?i("systemStatus.healthy"):N.status,color:"green"}),n.jsx(Ux,{label:i("systemStatus.version"),value:N.version,color:"indigo"}),n.jsx(Ux,{label:i("systemStatus.activeAgents"),value:String(N.agents),color:"purple"})]}):n.jsx("div",{className:"text-sm text-fg-tertiary",children:i("common:loading")})}),n.jsx(hi,{title:i("defaultProvider.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium",children:i("defaultProvider.primaryProvider")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("defaultProvider.primaryProviderDesc")})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[T?n.jsx("select",{value:D,onChange:oe=>{I(oe.target.value),U(null)},className:"px-3 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-sm w-48 focus:border-brand-500 outline-none",children:Nr.length>0?Nr.map(oe=>n.jsx("option",{value:oe,children:T.providers[oe]?.displayName??oe},oe)):n.jsx("option",{value:"",children:i("defaultProvider.noProviders")})}):n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("common:loading")}),D!==T?.defaultProvider&&n.jsx("button",{onClick:()=>{ti()},disabled:$,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i($?"common:saving":"common:save")})]})]}),R&&n.jsx(Ua,{type:R.type,text:R.text}),n.jsxs("div",{className:"flex items-center justify-between border-t border-border-default pt-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("defaultProvider.autoFallback")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("defaultProvider.autoFallbackDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!(T?.autoFallback??!0);try{const Ee=await fetch("/api/settings/llm",{method:"POST",headers:yr(),body:JSON.stringify({autoFallback:oe})});if(Ee.ok){const et=await Ee.json();M(et)}}catch{}},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${T?.autoFallback??!0?"bg-green-500":"bg-gray-600"}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${T?.autoFallback??!0?"translate-x-4":"translate-x-1"}`})})]})]})}),n.jsxs(hi,{title:i("modelProviders.title"),children:[n.jsx("div",{className:"space-y-3",children:T&&(()=>{const oe=[],Ee=new Set;for(const[et,hn]of Object.entries(T.providers))oe.push([et,hn]),Ee.add(et);for(const et of Bu)Ee.has(et.id)||(oe.push([et.id,{name:et.id,displayName:et.label,model:et.defaultModel,configured:!1,enabled:!1}]),Ee.add(et.id));return oe})().map(([oe,Ee])=>n.jsxs("div",{className:`bg-surface-secondary border rounded-xl overflow-hidden transition-colors ${Ee.configured?"border-border-default hover:border-gray-600":"border-border-default/50 hover:border-brand-500/30"}`,children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-4 cursor-pointer",onClick:()=>{F(W===oe?null:oe),Hs(""),$r(null),Ur([]),js(et=>({...et,name:"",model:""}))},children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${Ee.configured&&Ee.enabled?"bg-green-400":Ee.configured?"bg-amber-400":"bg-gray-600"}`}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm font-medium",children:Ee.displayName??oe}),oe===T.defaultProvider&&n.jsx("span",{className:"text-[10px] bg-brand-500/15 text-brand-500 px-1.5 py-0.5 rounded",children:i("modelProviders.badgeDefault")}),Ee.configured&&!Ee.enabled&&n.jsx("span",{className:"text-[10px] bg-amber-500/15 text-amber-600 px-1.5 py-0.5 rounded",children:i("modelProviders.disabled")}),Ee.oauthConnected&&n.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:i("modelProviders.badgeOAuth")}),Vr[oe]?.ok===!0&&n.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:i("modelProviders.testOk",{ms:Vr[oe].durationMs})}),Vr[oe]?.ok===!1&&n.jsx("span",{className:"text-[10px] bg-red-500/15 text-red-500 px-1.5 py-0.5 rounded",title:Vr[oe].error,children:Vr[oe].errorCode?i("modelProviders.testFailedCode",{code:Vr[oe].errorCode}):i("modelProviders.testFailed")})]}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:Ee.configured?n.jsxs(n.Fragment,{children:[Ee.model,Ee.apiKeyPreview&&n.jsxs(n.Fragment,{children:[" · ",n.jsx("code",{className:"text-fg-secondary",children:Ee.apiKeyPreview})]})]}):i("modelProviders.notConfigured")})]})]}),n.jsxs("div",{className:"flex items-center gap-4",children:[Ee.configured&&n.jsx("button",{onClick:et=>{et.stopPropagation(),Oa(oe,!Ee.enabled)},disabled:L===oe,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Ee.enabled?"bg-green-500":"bg-gray-600"} ${L===oe?"opacity-50":""}`,title:Ee.enabled?i("modelProviders.clickToDisable"):i("modelProviders.clickToEnable"),children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ee.enabled?"translate-x-4":"translate-x-1"}`})}),Ee.contextWindow!=null&&Ee.contextWindow>0&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("modelProviders.ctxTokens",{size:(Ee.contextWindow/1e3).toFixed(0)})}),Ee.cost&&(Ee.cost.input>0||Ee.cost.output>0)&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("modelProviders.costPerMillion",{input:Ee.cost.input,output:Ee.cost.output})}),n.jsx("span",{className:"text-fg-tertiary text-xs",children:W===oe?"▲":"▼"})]})]}),W===oe&&n.jsxs("div",{className:"px-5 pb-4 border-t border-border-default pt-4 space-y-4",children:[Ee.configured&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsx(ml,{label:i("modelProviders.model"),value:Ee.model}),n.jsx(ml,{label:i("modelProviders.contextWindow"),value:Ee.contextWindow?i("modelProviders.kTokens",{k:(Ee.contextWindow/1e3).toFixed(0)}):i("modelProviders.notApplicable")}),n.jsx(ml,{label:i("modelProviders.maxOutput"),value:Ee.maxOutputTokens?i("modelProviders.kTokens",{k:(Ee.maxOutputTokens/1e3).toFixed(0)}):i("modelProviders.notApplicable")}),n.jsx(ml,{label:i("modelProviders.baseUrlLabel"),value:Ee.baseUrl??i("modelProviders.baseUrlDisplayDefault")})]}),sa===oe?n.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-4 space-y-3",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:i("modelProviders.editProvider")}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:Wn.apiKey,onChange:et=>Cs({...Wn,apiKey:et.target.value}),placeholder:i("modelProviders.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.baseUrl")}),n.jsx("input",{type:"text",value:Wn.baseUrl,onChange:et=>Cs({...Wn,baseUrl:et.target.value}),placeholder:i("modelProviders.baseUrlDisplayDefault"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.model")}),n.jsx("input",{type:"text",value:Wn.model,onChange:et=>Cs({...Wn,model:et.target.value}),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.contextWindow")}),n.jsx("input",{type:"number",value:Wn.contextWindow||"",onChange:et=>Cs({...Wn,contextWindow:Number(et.target.value)}),placeholder:i("modelProviders.placeholderContextExample"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.maxOutputTokens")}),n.jsx("input",{type:"number",value:Wn.maxOutputTokens||"",onChange:et=>Cs({...Wn,maxOutputTokens:Number(et.target.value)}),placeholder:i("modelProviders.placeholderMaxOutputExample"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.inputCost")}),n.jsx("input",{type:"number",step:"0.01",value:Wn.costInput||"",onChange:et=>Cs({...Wn,costInput:Number(et.target.value)}),placeholder:i("modelProviders.placeholderCostInput"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.outputCost")}),n.jsx("input",{type:"number",step:"0.01",value:Wn.costOutput||"",onChange:et=>Cs({...Wn,costOutput:Number(et.target.value)}),placeholder:i("modelProviders.placeholderCostOutput"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>{ie(oe)},disabled:Ps,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(Ps?"common:saving":"common:save")}),n.jsx("button",{onClick:()=>_a(null),className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:cancel")})]})]}):n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:et=>{et.stopPropagation(),is(oe)},disabled:bt===oe,className:"px-3 py-1.5 text-xs border border-green-500/30 text-green-500 hover:bg-green-500/10 rounded-lg transition-colors disabled:opacity-40 flex items-center gap-1.5",children:bt===oe?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),i("modelProviders.testing")]}):i("modelProviders.test")}),n.jsx("button",{onClick:et=>{et.stopPropagation(),ja(oe,Ee)},className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:edit")}),n.jsx("button",{onClick:et=>{et.stopPropagation(),confirm(i("modelProviders.deleteConfirm",{name:Ee.displayName??oe}))&&Xe(oe)},disabled:_r===oe,className:"px-3 py-1.5 text-xs border border-red-500/30 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors disabled:opacity-40",children:i(_r===oe?"common:deleting":"common:delete")})]}),Vr[oe]&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${Vr[oe].ok?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:Vr[oe].ok?i("modelProviders.testSuccess",{ms:Vr[oe].durationMs,reply:Vr[oe].reply}):Vr[oe].error})]}),Ee.cost&&n.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-3",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-2",children:i("modelProviders.pricingTitle")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[n.jsx(ml,{label:i("modelProviders.input"),value:`$${Ee.cost.input}`}),n.jsx(ml,{label:i("modelProviders.output"),value:`$${Ee.cost.output}`}),Ee.cost.cacheRead!=null&&n.jsx(ml,{label:i("modelProviders.cacheRead"),value:`$${Ee.cost.cacheRead}`}),Ee.cost.cacheWrite!=null&&n.jsx(ml,{label:i("modelProviders.cacheWrite"),value:`$${Ee.cost.cacheWrite}`})]})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:i("modelProviders.availableModels")}),Ee.configured&&Fs!==oe&&n.jsx("button",{onClick:()=>{ya(oe),Zr({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})},className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:i("modelProviders.addModel")})]}),Fs===oe&&n.jsx("div",{className:"bg-surface-elevated/40 rounded-lg p-3 mb-2 space-y-2",children:n.jsx(VG,{providerName:oe,addModelForm:qs,setAddModelForm:Zr,addModelSaving:_s,onAdd:()=>{ot(oe)},onCancel:()=>ya(null),t:i})}),Ee.models&&Ee.models.length>0&&n.jsx("div",{className:"space-y-1.5",children:Ee.models.map(et=>{const hn=et.id===Ee.model,Cn=hr===`${oe}:${et.id}`,zs=!fn.has(et.id);return n.jsxs("div",{className:`flex items-center justify-between px-3 py-2 rounded-lg text-xs transition-colors ${hn?"bg-brand-500/15 border border-brand-500/30":Ee.configured?"bg-surface-elevated/30 hover:bg-surface-elevated/60 cursor-pointer":"bg-surface-elevated/30"}`,onClick:()=>{!hn&&Ee.configured&&!Cn&&Kr(oe,et.id)},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[hn&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 shrink-0"}),n.jsx("span",{className:hn?"text-brand-500 font-medium":"text-fg-secondary",children:et.name}),et.reasoning&&n.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:i("modelProviders.reasoning")}),et.inputTypes?.includes("image")&&n.jsx("span",{className:"text-[9px] bg-blue-500/15 text-blue-600 px-1 py-0.5 rounded",children:i("modelProviders.vision")}),zs&&n.jsx("span",{className:"text-[9px] bg-purple-500/15 text-purple-400 px-1 py-0.5 rounded",children:i("modelProviders.custom")})]}),n.jsxs("div",{className:"flex items-center gap-3 text-fg-tertiary",children:[et.contextWindow>0&&n.jsx("span",{children:i("modelProviders.ctxTokens",{size:(et.contextWindow/1e3).toFixed(0)})}),(et.cost.input>0||et.cost.output>0)&&n.jsx("span",{children:i("modelProviders.costPair",{input:et.cost.input,output:et.cost.output})}),Ee.configured&&!hn&&n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded transition-colors ${Cn?"bg-brand-500/30 text-brand-400":"bg-surface-overlay text-fg-tertiary hover:bg-brand-500/20 hover:text-brand-500"}`,children:i(Cn?"modelProviders.switching":"modelProviders.use")}),hn&&n.jsx("span",{className:"text-[9px] bg-brand-500/15 text-brand-500 px-1.5 py-0.5 rounded",children:i("modelProviders.active")}),zs&&!hn&&n.jsx("button",{onClick:no=>{no.stopPropagation(),Dt(oe,et.id)},className:"text-red-400 hover:text-red-300 transition-colors",title:i("modelProviders.deleteCustomModelTitle"),children:n.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]},et.id)})}),Ee.configured&&G===oe&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 text-xs text-fg-tertiary",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),i("modelProviders.loadingCatalog")]}),Ee.configured&&E[oe]&&E[oe].length>0&&(()=>{const et=new Set(Ee.models?.map(Cn=>Cn.id)??[]),hn=E[oe].filter(Cn=>!et.has(Cn.id));return hn.length===0?null:n.jsxs("details",{className:"mt-2 group",children:[n.jsx("summary",{className:"text-[10px] text-fg-tertiary cursor-pointer hover:text-fg-secondary select-none",children:i("modelProviders.moreCatalogModels",{count:hn.length})}),n.jsx("div",{className:"mt-1.5 space-y-1",children:hn.map(Cn=>{const zs=hr===`${oe}:${Cn.id}`;return n.jsxs("div",{onClick:()=>{zs||Kr(oe,Cn.id)},className:"flex items-center justify-between px-3 py-1.5 rounded-lg text-xs bg-surface-elevated/20 hover:bg-surface-elevated/50 cursor-pointer transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-fg-secondary",children:Cn.id}),Cn.capabilities.reasoning&&n.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:i("modelProviders.reasoning")}),Cn.capabilities.vision&&n.jsx("span",{className:"text-[9px] bg-blue-500/15 text-blue-600 px-1 py-0.5 rounded",children:i("modelProviders.vision")})]}),n.jsxs("div",{className:"flex items-center gap-3 text-fg-tertiary",children:[Cn.maxInputTokens>0&&n.jsxs("span",{children:[Math.round(Cn.maxInputTokens/1e3),"K ctx"]}),(Cn.inputCostPer1MTokens>0||Cn.outputCostPer1MTokens>0)&&n.jsxs("span",{children:["$",Cn.inputCostPer1MTokens,"/",Cn.outputCostPer1MTokens]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded transition-colors ${zs?"bg-brand-500/30 text-brand-400":"bg-surface-overlay text-fg-tertiary hover:bg-brand-500/20 hover:text-brand-500"}`,children:i(zs?"modelProviders.switching":"modelProviders.use")})]})]},Cn.id)})})]})})()]}),!Ee.configured&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:i("modelProviders.quickSetupHint")}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:W===oe?Os:"",onChange:et=>Hs(et.target.value),placeholder:i("modelProviders.quickSetupPlaceholder"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none",onBlur:()=>{Os.trim().length>=8&&W===oe&&Di(oe,Os.trim())},onKeyDown:et=>{et.key==="Enter"&&Os.trim().length>=8&&Di(oe,Os.trim())}}),ri&&W===oe&&n.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-xs text-fg-tertiary",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),i("modelProviders.validatingKey")]})]}),W===oe&&as.length>0&&n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-2",children:i("modelProviders.selectModel")}),n.jsx(ch,{provider:oe,models:as,selectedModel:Kn.model,onSelect:et=>{const hn=as.find(Cn=>Cn.id===et);js(Cn=>({...Cn,name:oe,model:et,apiKey:Os.trim(),baseUrl:Bu.find(zs=>zs.id===oe)?.baseUrl??"",contextWindow:hn?.maxInputTokens??Cn.contextWindow,maxOutputTokens:hn?.maxOutputTokens??Cn.maxOutputTokens,costInput:hn?.inputCostPer1MTokens??Cn.costInput,costOutput:hn?.outputCostPer1MTokens??Cn.costOutput}))},compact:!0,maxVisible:8})]}),W===oe&&Os.trim()&&n.jsx("button",{onClick:()=>{Kn.model&&Kn.name===oe?wa():ka(oe)},disabled:si||ba,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(si||ba?"modelProviders.quickSetupSaving":"modelProviders.quickSetupSubmit")}),Ys&&W===oe&&n.jsx(Ua,{type:Ys.type,text:Ys.text})]})]})]},oe))}),xa?n.jsxs("div",{className:"mt-3 bg-surface-secondary border border-brand-500/30 rounded-xl p-4 space-y-3",children:[n.jsx("div",{className:"text-xs font-medium text-fg-primary",children:i("modelProviders.customProvider")}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.providerName")}),n.jsx("input",{type:"text",value:Kn.name==="__custom__"?"":Kn.name,onChange:oe=>js(Ee=>({...Ee,name:oe.target.value||"__custom__"})),placeholder:"my-provider",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.baseUrl")}),n.jsx("input",{type:"text",value:Kn.baseUrl,onChange:oe=>js({...Kn,baseUrl:oe.target.value}),placeholder:"https://api.example.com/v1",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.apiKey")}),n.jsx("input",{type:"password",value:Kn.apiKey,onChange:oe=>js({...Kn,apiKey:oe.target.value}),placeholder:i("modelProviders.placeholderApiKeySk"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:i("modelProviders.defaultModel")}),n.jsx("input",{type:"text",value:Kn.model,onChange:oe=>js({...Kn,model:oe.target.value}),placeholder:"gpt-4o",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>{wa()},disabled:ba||!Kn.name||Kn.name==="__custom__"||!Kn.model,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:i(ba?"modelProviders.adding":"modelProviders.addProviderSubmit")}),n.jsx("button",{onClick:()=>{Is(!1),Ls(null),Ur([]),js({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5})},className:"px-4 py-2 text-sm border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors",children:i("common:cancel")})]}),vr&&n.jsx(Ua,{type:vr.type,text:vr.text})]}):n.jsxs("button",{onClick:()=>Is(!0),className:"w-full mt-3 px-4 py-2.5 border border-dashed border-border-default hover:border-brand-500/50 hover:bg-brand-500/5 rounded-xl text-xs text-fg-tertiary hover:text-brand-500 transition-colors",children:["+ ",i("modelProviders.customProvider")]})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsx(hi,{title:i("autoDetect.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[n.jsx("div",{className:"text-sm text-fg-secondary",children:i("autoDetect.description")}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("envConfig.title")}),n.jsxs("button",{onClick:()=>{na()},disabled:Q,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[n.jsx("svg",{className:`w-3.5 h-3.5 ${Q?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),i(Q?"common:detecting":"envConfig.refreshEnv")]})]}),ee&&ee.detected.length>0&&n.jsxs("div",{className:"space-y-2",children:[ee.detected.map(oe=>n.jsxs("label",{className:"flex items-center justify-between bg-surface-elevated/30 rounded-lg px-4 py-3 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"checkbox",checked:He[oe.provider]??!1,onChange:Ee=>je({...He,[oe.provider]:Ee.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm text-fg-primary font-medium",children:oe.displayName}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[i("envConfig.keyLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.apiKeyPreview})," / ",i("envConfig.modelLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.model}),oe.baseUrl&&n.jsxs(n.Fragment,{children:[" / ",i("envConfig.urlLabel")," ",n.jsx("code",{className:"text-fg-secondary",children:oe.baseUrl})]})]})]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:Object.keys(oe.envVars).map(Ee=>n.jsx("div",{children:n.jsx("code",{children:Ee})},Ee))})]},oe.provider)),ee.timeoutMs&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("envConfig.llmTimeout",{ms:ee.timeoutMs})}),n.jsx("button",{onClick:()=>{ra()},disabled:xe||Object.values(He).filter(Boolean).length===0,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:xe?i("common:applying"):i("envConfig.applyToConfig",{count:Object.values(He).filter(Boolean).length})})]}),Ae&&n.jsx(Ua,{type:Ae.type,text:Ae.text})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("ollama.title")}),n.jsxs("button",{onClick:()=>{cs()},disabled:Qe,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[n.jsx("svg",{className:`w-3.5 h-3.5 ${Qe?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),i(Qe?"common:detecting":"ollama.detect")]})]}),Ce?.found&&Ce.models&&Ce.models.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-green-600",children:i("ollama.foundModels",{count:Ce.models.length,url:Ce.baseUrl})}),n.jsx("div",{className:"space-y-1",children:Ce.models.map(oe=>n.jsx("label",{className:`flex items-center justify-between rounded-lg px-4 py-3 cursor-pointer transition-colors ${st===oe.name?"bg-brand-500/15 border border-brand-500/40":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("input",{type:"radio",name:"ollama-model",value:oe.name,checked:st===oe.name,onChange:()=>zt(oe.name),className:"w-4 h-4 text-brand-500 focus:ring-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm text-fg-primary font-medium",children:oe.name}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[oe.parameterSize&&n.jsx("span",{children:oe.parameterSize}),oe.family&&n.jsx("span",{className:"ml-2",children:oe.family}),oe.quantization&&n.jsx("span",{className:"ml-2",children:oe.quantization}),oe.size&&n.jsx("span",{className:"ml-2",children:td(oe.size)})]})]})]})},oe.name))}),n.jsx("button",{onClick:()=>{Gs()},disabled:mt||!st,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:mt?i("common:applying"):i("ollama.useModel",{model:st})})]}),Ce&&!Ce.found&&n.jsx("div",{className:"text-xs text-fg-tertiary",children:Ce.error||i("ollama.notRunning")}),de&&n.jsx(Ua,{type:de.type,text:de.text})]}),n.jsx("div",{className:"border-t border-border-default"}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("openClaw.title")}),n.jsx("button",{onClick:()=>{bi()},disabled:J,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:i(J?"common:detecting":"openClaw.detectShort")})]}),O&&O.found&&n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"text-xs text-green-600",children:[i("openClaw.foundAt")," ",n.jsx("code",{className:"text-fg-secondary",children:O.summary.configPath})]}),O.summary.models&&n.jsxs("div",{className:"bg-surface-elevated/30 rounded-lg p-3",children:[n.jsx("div",{className:"text-xs text-fg-tertiary mb-2",children:i("openClaw.modelProvidersFound",{count:O.summary.models.providerCount})}),n.jsx("div",{className:"space-y-1",children:O.summary.models.providers.map(oe=>n.jsxs("div",{className:"flex items-center justify-between text-xs",children:[n.jsx("span",{className:"text-fg-secondary",children:oe.name}),n.jsxs("span",{className:"text-fg-tertiary",children:[i("openClaw.modelsCountSuffix",{count:oe.modelCount}),oe.baseUrl?i("openClaw.withBaseUrl",{url:oe.baseUrl}):""]})]},oe.name))})]}),O.summary.channels&&O.summary.channels.length>0&&n.jsx("div",{className:"bg-surface-elevated/30 rounded-lg p-3",children:n.jsxs("div",{className:"text-xs text-fg-tertiary mb-1",children:[i("openClaw.channelsPrefix")," ",O.summary.channels.join(", ")]})}),n.jsx("button",{onClick:()=>{ni()},disabled:J,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:i(J?"common:importing":"openClaw.importConfigs")})]}),Z&&n.jsx(Ua,{type:Z.type,text:Z.text})]})]})})]}),w==="execution"&&n.jsxs(n.Fragment,{children:[n.jsx(hi,{title:i("agentExecution.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("agentExecution.maxToolIterations")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("agentExecution.maxToolIterationsDesc")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"number",min:0,value:yn,onChange:oe=>{sn(Number(oe.target.value)),mn(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right"}),n.jsx("button",{disabled:In,onClick:async()=>{jn(!0),mn(null);try{const oe=await le.settings.updateAgent({maxToolIterations:yn});sn(oe.maxToolIterations),mn({type:"ok",text:i("agentExecution.saved")})}catch{mn({type:"err",text:i("agentExecution.failedToSave")})}jn(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(In?"common:saving":"common:save")})]})]}),Vt&&n.jsx(Ua,{type:Vt.type,text:Vt.text})]})}),n.jsx(hi,{title:i("cognitive.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("cognitive.description")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("cognitive.enabled")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("cognitive.enabledDesc")})]}),n.jsx("button",{onClick:()=>{Xn(!Vn),Ot(null)},className:`relative w-10 h-5 rounded-full transition-colors ${Vn?"bg-brand-500":"bg-fg-quaternary"}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${Vn?"translate-x-5":""}`})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("cognitive.maxDepth")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("cognitive.maxDepthDesc")})]}),n.jsxs("select",{value:Rr,onChange:oe=>{qe(Number(oe.target.value)),Ot(null)},className:"px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary",children:[n.jsxs("option",{value:1,children:["D1 — ",i("cognitive.depthD1")]}),n.jsxs("option",{value:2,children:["D2 — ",i("cognitive.depthD2")]}),n.jsxs("option",{value:3,children:["D3 — ",i("cognitive.depthD3")]})]})]}),n.jsx("div",{className:"flex items-center justify-end gap-2",children:n.jsx("button",{disabled:St,onClick:async()=>{_e(!0),Ot(null);try{const oe=await le.settings.updateAgent({cognitive:{enabled:Vn,maxDepth:Rr}});Xn(oe.cognitive.enabled),qe(oe.cognitive.maxDepth??1),Ot({type:"ok",text:i("cognitive.saved")})}catch{Ot({type:"err",text:i("cognitive.failedToSave")})}_e(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(St?"common:saving":"common:save")})}),Tt&&n.jsx(Ua,{type:Tt.type,text:Tt.text})]})})]}),w==="browser"&&n.jsxs(n.Fragment,{children:[n.jsxs(hi,{title:i("browserAutomation.title"),children:[n.jsxs("div",{className:`rounded-xl p-4 mb-4 flex items-start gap-3 ${Qn?"bg-green-500/10 border border-green-500/20":_n>0?"bg-blue-500/10 border border-blue-500/20":rr?"bg-amber-500/10 border border-amber-500/20":"bg-surface-elevated border border-border-default"}`,children:[n.jsx("div",{className:`mt-0.5 w-2.5 h-2.5 rounded-full shrink-0 ${Qn?"bg-green-400":_n>0?"bg-blue-400":rr?"bg-amber-400":"bg-gray-400"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:`text-sm font-semibold ${Qn?"text-green-400":_n>0?"text-blue-400":rr?"text-amber-400":"text-fg-secondary"}`,children:Qn?i("browserAutomation.modeExtension"):_n>0?i("browserAutomation.modeDebuggingPort",{port:_n}):i(rr?"browserAutomation.modeAutoClick":"browserAutomation.modeManual")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:Qn?i("browserAutomation.modeExtensionDesc"):_n>0?i("browserAutomation.modeDebuggingPortDesc"):i(rr?"browserAutomation.modeAutoClickDesc":"browserAutomation.modeManualDesc")})]})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4 mb-4",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.generalSettings")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.bringToFront")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.bringToFrontDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!Gt;Tn(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({bringToFront:oe});Tn(Ee.bringToFront),tn({type:"ok",text:i(oe?"browserAutomation.tabsForeground":"browserAutomation.tabsBackground")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),Tn(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Gt?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Gt?"translate-x-4":"translate-x-1"}`})})]}),n.jsxs("div",{className:"flex items-center justify-between border-t border-border-default pt-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.autoCloseTabs")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.autoCloseTabsDesc")})]}),n.jsx("button",{onClick:async()=>{const oe=!Fn;mr(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({autoCloseTabs:oe});mr(Ee.autoCloseTabs),tn({type:"ok",text:i("agentExecution.saved")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),mr(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Fn?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Fn?"translate-x-4":"translate-x-1"}`})})]})]}),n.jsxs("div",{className:`rounded-xl p-5 mb-4 transition-colors ${Qn?"bg-green-500/5 border border-green-500/20":"bg-surface-elevated"}`,children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStatus")}),n.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",i("browserAutomation.modeRecommended"),")"]})]}),n.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${Qn?"bg-green-500/20 text-green-400":"bg-gray-600/20 text-gray-400"}`,children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Qn?"bg-green-400":"bg-gray-400"}`}),i(Qn?"browserAutomation.extensionConnected":"browserAutomation.extensionDisconnected")]})]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("browserAutomation.extensionStatusDesc")}),Qn?n.jsxs("div",{className:"mt-3 flex items-center gap-1.5 text-xs text-green-400",children:[n.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),i("browserAutomation.extensionActiveNote")]}):n.jsxs("div",{className:"mt-4 space-y-3",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.extensionSetupTitle")}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"1"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep1")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep1Desc")}),n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{await le.settings.downloadExtensionZip()}catch{tn({type:"err",text:i("browserAutomation.extensionDownloadError")})}qt(!1)},className:"mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),i(It?"browserAutomation.extensionStep1Downloading":"browserAutomation.extensionStep1Btn")]})]})]}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"2"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep2")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep2Desc")}),n.jsxs("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{await le.settings.openExtensionsPage()}catch{tn({type:"err",text:i("browserAutomation.extensionOpenError")})}qt(!1)},className:"mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:[n.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),i("browserAutomation.extensionStep2Btn")]})]})]}),n.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[n.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"3"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.extensionStep3")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.extensionStep3Desc")})]})]})]})]}),!Qn&&n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[n.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("browserAutomation.fallbackModes")}),n.jsx("div",{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex-1 mr-4",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.autoClickAllowDialog")}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:i("browserAutomation.autoClickAllowDialogDesc")}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-2 space-y-0.5",children:[n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogMacNote")}),n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogWinNote")}),n.jsx("div",{children:i("browserAutomation.autoClickAllowDialogLinuxNote")})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{const oe=await le.settings.testAutoClick(),Ee={success:{type:"ok",text:i("browserAutomation.autoClickTestSuccess",{title:oe.pageTitle||"example.com"})},no_permission:{type:"err",text:i("browserAutomation.autoClickTestNoPermission")},chrome_not_running:{type:"err",text:i("browserAutomation.autoClickTestChromeNotRunning")},unsupported:{type:"err",text:i("browserAutomation.autoClickTestUnsupported")},error:{type:"err",text:i("browserAutomation.autoClickTestError",{error:oe.error||"unknown"})}};tn(Ee[oe.clickResult]??{type:"err",text:oe.clickResult})}catch{tn({type:"err",text:i("browserAutomation.autoClickTestError",{error:"request failed"})})}qt(!1)},className:"px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:i(It?"browserAutomation.autoClickTesting":"browserAutomation.autoClickTest")}),n.jsx("button",{onClick:async()=>{const oe=!rr;fr(oe),qt(!0),tn(null);try{const Ee=await le.settings.updateBrowser({autoClickAllowDialog:oe});fr(Ee.autoClickAllowDialog),tn({type:"ok",text:i("agentExecution.saved")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")}),fr(!oe)}qt(!1)},disabled:It,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${rr?"bg-green-500":"bg-gray-600"} ${It?"opacity-50":""}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${rr?"translate-x-4":"translate-x-1"}`})})]})]})}),n.jsx("div",{className:"border-t border-border-default pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:i("browserAutomation.remoteDebuggingPort")}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[i("browserAutomation.remoteDebuggingPortDescLead")," ",n.jsx("code",{className:"text-fg-secondary bg-surface-primary px-1 rounded",children:"--remote-debugging-port=9222"})," ",i("browserAutomation.remoteDebuggingPortDescTail")]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"number",min:0,max:65535,value:_n,onChange:oe=>{Sn(Number(oe.target.value)),tn(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right",placeholder:"0"}),n.jsx("button",{disabled:It,onClick:async()=>{qt(!0),tn(null);try{const oe=await le.settings.updateBrowser({remoteDebuggingPort:_n});Sn(oe.remoteDebuggingPort),tn({type:"ok",text:oe.remoteDebuggingPort>0?i("browserAutomation.usingPort",{port:oe.remoteDebuggingPort}):i("browserAutomation.usingAutoConnect")})}catch{tn({type:"err",text:i("agentExecution.failedToSave")})}qt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(It?"common:saving":"common:save")})]})]})})]}),Jt&&n.jsx("div",{className:"mt-4",children:n.jsx(Ua,{type:Jt.type,text:Jt.text})})]}),!1]}),w==="search"&&n.jsx(n.Fragment,{children:n.jsx(hi,{title:i("searchApi.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:i("searchApi.description")}),[{id:"serper",label:i("searchApi.serper"),hint:i("searchApi.serperHint"),field:"serperApiKey"},{id:"tavily",label:i("searchApi.tavily"),hint:i("searchApi.tavilyHint"),field:"tavilyApiKey"},{id:"bing",label:i("searchApi.bing"),hint:i("searchApi.bingHint"),field:"bingApiKey"},{id:"google",label:i("searchApi.google"),hint:i("searchApi.googleHint"),field:"googleSearchApiKey",extraField:"googleSearchCx",extraPlaceholder:i("searchApi.googleCxPlaceholder")},{id:"serpapi",label:i("searchApi.serpapi"),hint:i("searchApi.serpapiHint"),field:"serpApiKey"},{id:"brave",label:i("searchApi.brave"),hint:i("searchApi.braveHint"),field:"braveApiKey"},{id:"exa",label:i("searchApi.exa"),hint:i("searchApi.exaHint"),field:"exaApiKey"},{id:"bocha",label:i("searchApi.bocha"),hint:i("searchApi.bochaHint"),field:"bochaApiKey"}].map((oe,Ee)=>n.jsxs("div",{className:Ee>0?"border-t border-border-default pt-4":"",children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:oe.label}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:oe.hint})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[An?.[oe.id]?.configured&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-xs text-green-600",children:i("searchApi.configured")}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:An[oe.id].preview})]}),An&&!An[oe.id]?.configured&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:i("searchApi.notConfigured")})]})]})]}),n.jsx("input",{type:"password",value:an[oe.field],onChange:et=>ye({...an,[oe.field]:et.target.value}),placeholder:An?.[oe.id]?.configured?i("modelProviders.apiKeyPlaceholder"):i("searchApi.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),oe.extraField&&n.jsx("input",{type:"text",value:an[oe.extraField],onChange:et=>ye({...an,[oe.extraField]:et.target.value}),placeholder:oe.extraPlaceholder??"",className:"w-full mt-2 px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]},oe.id)),n.jsx("div",{className:"text-xs text-fg-tertiary italic",children:i("searchApi.freeBackend")}),n.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border-default",children:[Ht&&n.jsx(Ua,{type:Ht.type,text:Ht.text}),!Ht&&n.jsx("div",{}),n.jsx("button",{disabled:at||!an.serperApiKey&&!an.tavilyApiKey&&!an.bingApiKey&&!an.googleSearchApiKey&&!an.googleSearchCx&&!an.serpApiKey&&!an.braveApiKey&&!an.exaApiKey&&!an.bochaApiKey,onClick:()=>{ms()},className:"px-4 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:i(at?"common:saving":"common:save")})]})]})})}),w==="storage"&&n.jsx(n.Fragment,{children:n.jsx(hi,{title:i("dataStorage.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[Zn&&!Mt&&n.jsx("div",{className:"text-sm text-fg-tertiary",children:i("dataStorage.scanning")}),Mt&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-lg font-semibold text-fg-primary",children:td(Mt.totalSize,i)}),n.jsx("div",{className:"text-xs text-fg-tertiary font-mono mt-0.5",children:Mt.dataDir})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>ga(),disabled:Zn,className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors disabled:opacity-40",children:i(Zn?"dataStorage.scanning":"common:refresh")}),n.jsx("button",{onClick:()=>{le.system.openPath(Mt.dataDir)},className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors",children:i("dataStorage.openInFinder")})]})]}),n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:i("dataStorage.storageBreakdown")}),n.jsx("div",{className:"space-y-1.5",children:Mt.breakdown.filter(oe=>oe.size>0).map(oe=>n.jsxs("div",{className:"flex items-center justify-between py-1.5 px-3 rounded-lg bg-surface-elevated/40",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"text-sm text-fg-primary",children:oe.name}),n.jsx("span",{className:"text-xs text-fg-tertiary ml-2",children:oe.description})]}),n.jsx("span",{className:"text-sm font-medium text-fg-secondary tabular-nums shrink-0 ml-3",children:td(oe.size,i)})]},oe.name))})]}),Mt.agents.length>0&&n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:i("dataStorage.agentStorage",{count:Mt.agents.length})}),n.jsx("div",{className:"space-y-1",children:Mt.agents.map(oe=>{const Ee=Jn.has(oe.id);return n.jsxs("div",{className:"rounded-lg bg-surface-elevated/40 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between py-2 px-3 cursor-pointer hover:bg-surface-elevated/70",onClick:()=>Pn(et=>{const hn=new Set(et);return hn.has(oe.id)?hn.delete(oe.id):hn.add(oe.id),hn}),children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:Ee?"▼":"▶"}),n.jsx("button",{onClick:et=>{et.stopPropagation(),pt.navigate(Te.TEAM,{agentId:oe.id})},className:"text-sm text-brand-500 hover:text-brand-400 truncate",children:oe.name}),n.jsx("span",{className:"text-[10px] text-fg-tertiary font-mono truncate",children:oe.id})]}),n.jsx("span",{className:"text-xs font-medium text-fg-secondary tabular-nums shrink-0 ml-3",children:td(oe.size,i)})]}),Ee&&n.jsxs("div",{className:"px-3 pb-2 pt-0.5 space-y-0.5",children:[oe.subItems.filter(et=>et.size>0).map(et=>n.jsxs("div",{className:"flex items-center justify-between text-xs py-0.5 pl-5",children:[n.jsx("span",{className:"text-fg-tertiary",children:et.name}),n.jsx("span",{className:"text-fg-secondary tabular-nums",children:td(et.size,i)})]},et.name)),n.jsx("div",{className:"pl-5 pt-1",children:n.jsx("button",{onClick:()=>{le.system.openPath(Mt.dataDir+"/agents/"+oe.id)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary underline",children:i("dataStorage.openFolder")})})]})]},oe.id)})})]}),on&&(on.orphanAgents.length>0||on.orphanTeams.length>0)&&n.jsx(KG,{orphanInfo:on,dataDir:Mt.dataDir,onPurged:ga,formatBytes:oe=>td(oe,i)})]})]})})}),w==="users"&&n.jsx(UG,{authUser:r}),w==="remote"&&n.jsx(GG,{})]}),n.jsx("div",{className:"h-8"})]})]})]})}const FG=["owner","admin","member","guest"],qG={owner:"bg-amber-500/10 text-amber-600 border-amber-500/30",admin:"bg-brand-500/10 text-brand-500 border-brand-500/30",member:"bg-green-500/10 text-green-600 border-green-500/30",guest:"bg-gray-500/10 text-gray-500 border-gray-500/30"};function UG({authUser:e}){const{t}=ft(["settings","common"]),[r,s]=x.useState([]),[a,i]=x.useState(null),[l,d]=x.useState(""),[u,m]=x.useState(""),[h,p]=x.useState(""),[y,g]=x.useState(null),[v,j]=x.useState(""),[C,w]=x.useState(null),[N,S]=x.useState(null),[T,M]=x.useState(null),D=x.useCallback(()=>{le.users.list(e?.orgId).then(U=>s(U.users)).catch(()=>{})},[e?.orgId]);x.useEffect(()=>{D()},[D]);const I=U=>{i(U.id),d(U.name),m(U.role),p(U.email??""),M(null)},$=async()=>{if(a)try{await le.users.update(a,{name:l,role:u,email:h||void 0}),i(null),M({type:"ok",text:t("settings:userManagement.updateSuccess")}),D()}catch(U){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(U)}`})}},B=async()=>{if(!(!y||!v))try{await le.users.resetPassword(y,v),g(null),j(""),M({type:"ok",text:t("settings:userManagement.resetSuccess")})}catch(U){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(U)}`})}},R=async U=>{if(U===e?.id){M({type:"err",text:t("settings:userManagement.cannotDeleteSelf")}),w(null);return}if(r.find(F=>F.id===U)?.role==="owner"){M({type:"err",text:t("settings:userManagement.cannotDeleteOwner")}),w(null);return}try{await le.users.remove(U),w(null),M({type:"ok",text:t("settings:userManagement.deleteSuccess")}),D()}catch(F){M({type:"err",text:`${t("settings:userManagement.error")}: ${String(F)}`})}};return n.jsx(hi,{title:t("settings:userManagement.title"),children:n.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:[T&&n.jsx("div",{className:`px-4 py-2 text-xs border-b ${T.type==="ok"?"bg-green-500/10 text-green-600 border-green-500/20":"bg-red-500/10 text-red-500 border-red-500/20"}`,children:T.text}),N&&n.jsxs("div",{className:"px-4 py-3 bg-brand-500/5 border-b border-brand-500/20 flex items-center gap-3",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary mb-1",children:t("settings:userManagement.copyInviteLink")}),n.jsx("code",{className:"text-[10px] text-brand-500 bg-surface-elevated px-2 py-1 rounded block truncate",children:N})]}),n.jsx("button",{onClick:()=>{navigator.clipboard.writeText(N),M({type:"ok",text:t("settings:userManagement.linkCopied")})},className:"shrink-0 px-3 py-1.5 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium",children:t("settings:userManagement.copy")}),n.jsx("button",{onClick:()=>S(null),className:"shrink-0 text-fg-tertiary hover:text-fg-secondary text-sm",children:"×"})]}),n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border-default/60 text-fg-tertiary text-[11px] uppercase tracking-wider",children:[n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.name")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.email")}),n.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:t("settings:userManagement.role")}),n.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:t("settings:userManagement.actions")})]})}),n.jsxs("tbody",{children:[r.length===0&&n.jsx("tr",{children:n.jsx("td",{colSpan:4,className:"px-4 py-6 text-center text-fg-tertiary text-xs",children:t("settings:userManagement.noUsers")})}),r.map(U=>{const W=a===U.id,F=y===U.id,L=C===U.id,z=U.id===e?.id,E=U.role==="owner";return n.jsxs("tr",{className:"border-b border-border-default/40 last:border-b-0 hover:bg-surface-elevated/40 transition-colors",children:[n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("input",{value:l,onChange:_=>d(_.target.value),className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-fg-primary font-medium text-xs",children:U.name}),z&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500",children:"you"})]})}),n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("input",{value:h,onChange:_=>p(_.target.value),placeholder:"email@example.com",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):n.jsx("span",{className:"text-fg-secondary text-xs",children:U.email||"—"})}),n.jsx("td",{className:"px-4 py-2.5",children:W?n.jsx("select",{value:u,onChange:_=>m(_.target.value),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50",children:FG.map(_=>n.jsx("option",{value:_,children:t(`settings:userManagement.roles.${_}`)},_))}):n.jsx("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full border font-medium ${qG[U.role]??""}`,children:t(`settings:userManagement.roles.${U.role}`)})}),n.jsx("td",{className:"px-4 py-2.5 text-right",children:W?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("button",{onClick:()=>i(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:$,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium",children:t("settings:userManagement.save")})]}):F?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("input",{type:"password",value:v,onChange:_=>j(_.target.value),placeholder:t("settings:userManagement.newPassword"),autoFocus:!0,className:"w-32 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{onClick:()=>{g(null),j("")},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:B,disabled:v.length<6,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium disabled:opacity-40",children:t("settings:userManagement.confirmReset")})]}):L?n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsx("span",{className:"text-[10px] text-red-500",children:t("settings:userManagement.confirmDelete")}),n.jsx("button",{onClick:()=>w(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:t("settings:userManagement.cancel")}),n.jsx("button",{onClick:()=>R(U.id),className:"text-[11px] text-red-500 hover:text-red-400 font-medium",children:t("settings:userManagement.deleteUser")})]}):n.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[n.jsx("button",{onClick:()=>I(U),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:t("settings:userManagement.editUser")}),U.email&&n.jsx("button",{onClick:()=>{g(U.id),j(""),M(null)},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:t("settings:userManagement.resetPassword")}),U.email&&!E&&!U.hasJoined&&n.jsx("button",{onClick:async()=>{try{const{inviteToken:_}=await le.users.reinvite(U.id),G=`${window.location.origin}/#invite?token=${_}`;S(G),M({type:"ok",text:t("settings:userManagement.inviteLinkGenerated")})}catch(_){M({type:"err",text:String(_)})}},className:"text-[11px] text-brand-400 hover:text-brand-500 px-1.5 py-0.5 rounded hover:bg-brand-500/10",children:t("settings:userManagement.inviteLink")}),!E&&!z&&n.jsx("button",{onClick:()=>{w(U.id),M(null)},className:"text-[11px] text-red-400 hover:text-red-500 px-1.5 py-0.5 rounded hover:bg-red-500/10",children:t("settings:userManagement.deleteUser")})]})})]},U.id)})]})]})]})})}function VG({providerName:e,addModelForm:t,setAddModelForm:r,addModelSaving:s,onAdd:a,onCancel:i,t:l}){const[d,u]=x.useState([]),[m,h]=x.useState(!1),[p,y]=x.useState(!1),g=async()=>{h(!0);try{const v=await le.modelCatalog.getByProvider(e);u(v.models),y(!0)}catch{u([])}finally{h(!1)}};return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"text-[10px] text-fg-secondary",children:l("modelProviders.addModelTitle")}),n.jsx("button",{onClick:()=>{g()},disabled:m,className:"text-[10px] text-brand-500 hover:text-brand-400 disabled:opacity-40 transition-colors",children:m?"...":l("modelProviders.browseFromCatalog")})]}),p&&d.length>0&&n.jsx("div",{className:"border border-border-default rounded-lg p-2 mb-2",children:n.jsx(ch,{provider:e,models:d,selectedModel:t.id,onSelect:v=>{const j=d.find(C=>C.id===v);j&&r(C=>({...C,id:j.id,name:j.id,contextWindow:j.maxInputTokens,maxOutputTokens:j.maxOutputTokens,costInput:j.inputCostPer1MTokens,costOutput:j.outputCostPer1MTokens,reasoning:j.capabilities.reasoning,vision:j.capabilities.vision}))},compact:!0,maxVisible:5})}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[n.jsx("input",{type:"text",placeholder:l("modelProviders.modelId"),value:t.id,onChange:v=>r({...t,id:v.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"text",placeholder:l("modelProviders.displayName"),value:t.name,onChange:v=>r({...t,name:v.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"number",placeholder:l("modelProviders.placeholderContextTokens"),value:t.contextWindow,onChange:v=>r({...t,contextWindow:Number(v.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"}),n.jsx("input",{type:"number",placeholder:l("modelProviders.maxOutput"),value:t.maxOutputTokens,onChange:v=>r({...t,maxOutputTokens:Number(v.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modelProviders.costPerMillionIn")}),n.jsx("input",{type:"number",step:"0.01",value:t.costInput,onChange:v=>r({...t,costInput:Number(v.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:l("modelProviders.costPerMillionOut")}),n.jsx("input",{type:"number",step:"0.01",value:t.costOutput,onChange:v=>r({...t,costOutput:Number(v.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.reasoning,onChange:v=>r({...t,reasoning:v.target.checked}),className:"rounded"}),l("modelProviders.reasoning")]}),n.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.vision,onChange:v=>r({...t,vision:v.target.checked}),className:"rounded"}),l("modelProviders.vision")]}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:a,disabled:s||!t.id||!t.name,className:"px-2 py-1 text-[10px] bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded transition-colors",children:l(s?"modelProviders.adding":"common:create")}),n.jsx("button",{onClick:i,className:"px-2 py-1 text-[10px] border border-border-default text-fg-secondary hover:bg-surface-elevated rounded transition-colors",children:l("common:cancel")})]})]})}function Du({step:e,title:t,description:r,active:s,children:a}){return n.jsxs("div",{className:`rounded-xl p-4 space-y-3 transition-colors ${s?"ring-1 ring-brand-500/60 bg-brand-500/10":"bg-surface-elevated"}`,children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("span",{className:"flex-none w-6 h-6 rounded-full bg-surface-overlay flex items-center justify-center text-xs font-bold text-fg-secondary",children:e}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:t}),n.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r})]})]}),a&&n.jsx("div",{className:"pl-9",children:a})]})}function Ua({type:e,text:t}){return n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${e==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:t})}function hi({title:e,children:t}){return n.jsxs("section",{children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:e}),n.jsx("div",{className:"space-y-4",children:t})]})}function Ux({label:e,value:t,color:r}){const s=r==="green"?"bg-green-500/10 text-green-600":"bg-brand-500/10 text-brand-500";return n.jsxs("div",{className:`rounded-xl px-5 py-4 ${s}`,children:[n.jsx("div",{className:"text-2xl font-bold",children:t}),n.jsx("div",{className:"text-xs mt-1 opacity-70",children:e})]})}function ml({label:e,value:t}){return n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5 truncate",children:t})]})}function td(e,t){if(e===0)return t?t("dataStorage.bytesZero"):"0 B";const r=t?[t("dataStorage.unitB"),t("dataStorage.unitKB"),t("dataStorage.unitMB"),t("dataStorage.unitGB")]:["B","KB","MB","GB"],s=Math.min(Math.floor(Math.log(e)/Math.log(1024)),r.length-1),a=e/Math.pow(1024,s);return`${a<10?a.toFixed(1):Math.round(a)} ${r[s]}`}function KG({orphanInfo:e,dataDir:t,onPurged:r,formatBytes:s}){const{t:a}=ft(["settings","common"]),i=[...e.orphanAgents.map(w=>({...w,kind:"agent"})),...e.orphanTeams.map(w=>({...w,kind:"team"}))],[l,d]=x.useState(new Set),[u,m]=x.useState(!1),[h,p]=x.useState(null),y=w=>d(N=>{const S=new Set(N);return S.has(w)?S.delete(w):S.add(w),S}),g=l.size===i.length&&i.length>0,v=()=>d(g?new Set:new Set(i.map(w=>w.id))),j=i.filter(w=>l.has(w.id)).reduce((w,N)=>w+N.size,0),C=async w=>{m(!0),p(null);try{const N=await le.system.purgeOrphans(w),S=N.purgedAgents.length+N.purgedTeams.length,T=a("dataStorage.cleaned",{count:S,size:s(N.freedBytes)});p(N.failures.length?a("dataStorage.cleanedWithFailureNote",{base:T,count:N.failures.length}):T),d(new Set),r()}catch{p(a("dataStorage.cleanupFailed"))}finally{m(!1)}};return n.jsxs("div",{className:"border-t border-border-default pt-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-amber-500 mb-2",children:a("dataStorage.orphanedDirectories")}),n.jsxs("p",{className:"text-xs text-fg-tertiary mb-3",children:[a("dataStorage.orphanedDesc")," ",a("dataStorage.orphanedTotal",{size:s(e.totalOrphanSize),count:i.length})]}),n.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[n.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary cursor-pointer select-none",children:[n.jsx("input",{type:"checkbox",checked:g,onChange:v,className:"rounded"}),a("common:selectAll")]}),l.size>0&&n.jsx("span",{className:"text-[10px] text-fg-secondary",children:a("dataStorage.selectedWithSize",{count:l.size,size:s(j)})})]}),n.jsx("div",{className:"space-y-0.5 mb-3 max-h-52 overflow-y-auto",children:i.map(w=>n.jsxs("div",{className:`flex items-center gap-2 text-xs py-1.5 px-2 rounded transition-colors ${l.has(w.id)?"bg-amber-500/10":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:[n.jsx("input",{type:"checkbox",checked:l.has(w.id),onChange:()=>y(w.id),className:"rounded shrink-0"}),w.kind==="team"&&n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:a("dataStorage.teamKind")}),n.jsx("span",{className:"text-fg-tertiary font-mono truncate min-w-0 flex-1",children:w.id}),n.jsx("span",{className:"text-fg-secondary tabular-nums shrink-0",children:s(w.size)}),n.jsx("button",{onClick:()=>{le.system.openPath(w.path)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary shrink-0 underline",children:a("common:open")})]},w.id))}),n.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[l.size>0&&n.jsx("button",{disabled:u,onClick:()=>{C([...l])},className:"px-3 py-1.5 text-xs bg-amber-600 hover:bg-amber-500 text-white rounded-lg transition-colors disabled:opacity-50",children:u?a("dataStorage.cleaning"):a("dataStorage.cleanSelected",{size:s(j)})}),n.jsx("button",{disabled:u,onClick:()=>{C()},className:"px-3 py-1.5 text-xs border border-amber-600/50 hover:bg-amber-600/10 text-amber-500 rounded-lg transition-colors disabled:opacity-50",children:u?a("dataStorage.cleaning"):a("dataStorage.cleanAll",{size:s(e.totalOrphanSize)})})]}),h&&n.jsx("div",{className:"text-xs text-fg-tertiary mt-2",children:h})]})}function WG({authUser:e,onClose:t,onSaved:r}){const{t:s}=ft("common"),[a,i]=x.useState(e.name||""),[l,d]=x.useState(e.email||""),[u,m]=x.useState(!1),[h,p]=x.useState(""),[y,g]=x.useState(e.avatarUrl),v=async j=>{if(j.preventDefault(),!a.trim()){p(s("profile.nameRequired"));return}if(l&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(l.trim())){p(s("profile.invalidEmail"));return}m(!0),p("");try{const{user:C}=await le.auth.updateProfile(a.trim(),l.trim());r({...C,avatarUrl:y??C.avatarUrl})}catch{p(s("profile.failedToSave"))}finally{m(!1)}};return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:t,children:n.jsxs("form",{onSubmit:v,className:"bg-surface-secondary border border-border-default rounded-xl p-6 w-[400px] shadow-2xl",onClick:j=>j.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold mb-5",children:s("profile.editProfile")}),n.jsx("div",{className:"flex justify-center mb-5",children:n.jsx(g6,{currentUrl:y,name:a,size:72,targetType:"user",targetId:e.id,onUploaded:j=>g(j)})}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-tertiary font-medium mb-1",children:s("profile.name")}),n.jsx("input",{value:a,onChange:j=>i(j.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-tertiary font-medium mb-1",children:s("profile.email")}),n.jsx("input",{value:l,onChange:j=>d(j.target.value),type:"email",className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none"})]}),h&&n.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h})]}),n.jsxs("div",{className:"flex justify-end gap-3 mt-5",children:[n.jsx("button",{type:"button",onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("cancel")}),n.jsx("button",{type:"submit",disabled:u,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white rounded-lg",children:s(u?"saving":"save")})]})]})})}function GG(){const{t:e}=ft(["settings","common"]),[t,r]=x.useState(null),[s,a]=x.useState(!0),[i,l]=x.useState(!1),[d,u]=x.useState(null),[m,h]=x.useState(!1),p=m6(),y=x.useCallback(async()=>{try{const N=await le.settings.getRemote();r(N)}catch{r(null)}finally{a(!1)}},[]);x.useEffect(()=>{y()},[y]),x.useEffect(()=>pn.on("remote:status",N=>{const S=N.payload;S&&(r(S),l(!1))}),[]);const g=async()=>{l(!0),u(null);try{t?.enabled?(await le.settings.disableRemote(),await y(),l(!1)):(Un.isAuthenticated()||await ki(),await le.settings.enableRemote())}catch(N){u(String(N instanceof Error?N.message:N)),l(!1)}},v=async()=>{try{await ki(),await y()}catch{}},j=()=>{t?.remoteUrl&&(navigator.clipboard.writeText(t.remoteUrl),h(!0),setTimeout(()=>h(!1),2e3))},C=i||t?.enabled&&!t?.connected&&t?.state!=="idle",w=t?.remoteUrl??null;return n.jsx(hi,{title:e("settings:remoteAccess.title"),children:n.jsxs("div",{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-content-secondary",children:e("settings:remoteAccess.description")}),Un.isAuthenticated()?n.jsxs("div",{className:"flex items-center gap-2 text-sm text-content-secondary",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),e("settings:remoteAccess.signedInAs")," ",n.jsx("strong",{children:p?.username??p?.displayName})]}):n.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-amber-500/10 border border-amber-500/20",children:[n.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n.jsx("span",{className:"text-sm text-amber-600 dark:text-amber-400",children:e("settings:remoteAccess.loginRequired")}),n.jsx("button",{onClick:v,className:"ml-auto px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",children:e("settings:remoteAccess.signIn")})]}),Un.isAuthenticated()&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:g,disabled:i||s,className:`relative w-12 h-6 rounded-full transition-colors duration-200 ${t?.enabled?"bg-brand-600":"bg-gray-300 dark:bg-gray-600"} ${i||s?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:n.jsx("span",{className:`block w-5 h-5 bg-white rounded-full shadow transform transition-transform duration-200 ${t?.enabled?"translate-x-6":"translate-x-0.5"}`})}),n.jsx("span",{className:"text-sm font-medium",children:C?e("settings:remoteAccess.connecting"):t?.enabled?e("settings:remoteAccess.enabled"):e("settings:remoteAccess.disabled")}),C&&n.jsx(Jk,{})]}),t?.enabled&&n.jsxs("div",{className:`flex items-center gap-1.5 text-xs ${t.connected?"text-green-600 dark:text-green-400":t.state==="registering"||t.state==="connecting"?"text-blue-600 dark:text-blue-400":"text-amber-600 dark:text-amber-400"}`,children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${t.connected?"bg-green-500 animate-pulse":t.state==="registering"||t.state==="connecting"?"bg-blue-500 animate-pulse":"bg-amber-500"}`}),t.connected?e("settings:remoteAccess.connected"):t.state==="registering"?e("settings:remoteAccess.registering"):t.state==="connecting"?e("settings:remoteAccess.connecting"):e("settings:remoteAccess.disconnected"),t.connected&&t.peerCount>0&&n.jsxs(n.Fragment,{children:[" · ",e("settings:remoteAccess.peerCount",{count:t.peerCount})]}),(t.state==="registering"||t.state==="connecting")&&n.jsx(Jk,{})]})]}),d&&n.jsx("div",{className:"p-2 rounded-lg bg-red-500/10 text-red-500 text-sm",children:d}),t?.enabled&&t.peers&&t.peers.length>0&&n.jsxs("div",{className:"p-4 rounded-lg bg-surface-elevated border border-border-default space-y-2",children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.connectedPeers")}),n.jsx("div",{className:"space-y-2 mt-1",children:t.peers.map(N=>n.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg bg-surface-inset",children:[n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${N.transport==="p2p"?"bg-green-500":N.transport==="relay"?"bg-blue-500":"bg-amber-500 animate-pulse"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"text-sm font-mono text-content-primary truncate",children:[N.peerId.slice(0,8),"..."]}),n.jsx("div",{className:"text-xs text-content-tertiary",children:e("settings:remoteAccess.connectedSince",{time:new Date(N.connectedAt).toLocaleTimeString()})})]}),n.jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded-full ${N.transport==="p2p"?"bg-green-500/10 text-green-600 dark:text-green-400":N.transport==="relay"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"}`,children:N.transport==="p2p"?"P2P":N.transport==="relay"?"Relay":e("settings:remoteAccess.peerConnecting")})]},N.peerId))})]}),t?.enabled&&t.remoteUrl&&n.jsxs("div",{className:"p-4 rounded-lg bg-surface-elevated border border-border-default space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.url")}),n.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[n.jsx("code",{className:"flex-1 px-3 py-1.5 text-sm bg-surface-inset rounded font-mono truncate",children:t.remoteUrl}),n.jsx("button",{onClick:j,className:`px-2 py-1.5 text-xs border rounded transition-colors ${m?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:e(m?"settings:remoteAccess.copied":"settings:remoteAccess.copy")})]})]}),w&&n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:e("settings:remoteAccess.qrCode")}),n.jsx("p",{className:"text-xs text-content-secondary mt-0.5 mb-2",children:e("settings:remoteAccess.scanQr")}),n.jsx(YG,{url:w})]})]})]})]})})}function Jk(){return n.jsxs("svg",{className:"w-4 h-4 animate-spin text-content-secondary",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function YG({url:e}){const t=x.useRef(null),[r,s]=x.useState(!1);return x.useEffect(()=>{const a=t.current;a&&(s(!1),$d(()=>import("./browser-uDU2i9Yq.js").then(i=>i.b),[]).then(i=>{i.toCanvas(a,e,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"},errorCorrectionLevel:"M"})}).catch(()=>s(!0)))},[e]),r?n.jsx("a",{href:e,target:"_blank",rel:"noopener",className:"text-sm text-brand-500 underline",children:e}):n.jsx("div",{className:"inline-block p-2 bg-white rounded-lg",children:n.jsx("canvas",{ref:t,className:"block",style:{width:160,height:160}})})}const dh=new Map;function Xl(e,t){dh.has(e)||dh.set(e,t().catch(()=>{}))}function rc(e){const t=dh.get(e);return dh.delete(e),t}const Ra={builderArtifacts:"builder.artifacts",builderAgents:"builder.agents",builderHubMyItems:"builder.hubMyItems",builderInstalled:"builder.installed",hubAgents:"hub.agents",hubTeams:"hub.teams",hubSkills:"hub.skills"};function XG(e){const t=e.indexOf(".markus/builder-artifacts/");return t>=0?"~/"+e.slice(t):e}const QG=[{id:"hireAgent",icon:"✦",color:"from-brand-500 to-purple-600",borderColor:"border-brand-500/30 hover:border-brand-400/50",bgColor:"bg-brand-500/10"},{id:"buildTeam",icon:"◈",color:"from-blue-500 to-blue-600",borderColor:"border-blue-500/30 hover:border-blue-400/50",bgColor:"bg-blue-500/10"},{id:"createSkill",icon:"⬡",color:"from-green-500 to-green-600",borderColor:"border-green-500/30 hover:border-green-400/50",bgColor:"bg-green-500/10"}],ej={agent:{icon:"✦",color:"text-brand-500",bg:"bg-brand-500/10"},team:{icon:"◈",color:"text-blue-600",bg:"bg-blue-500/10"},skill:{icon:"⬡",color:"text-green-600",bg:"bg-green-500/10"}};function tj({title:e,message:t,cancelLabel:r,confirmLabel:s,onConfirm:a,onCancel:i}){return n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:i,children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-6 max-w-sm mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{className:"w-5 h-5 text-red-500",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),n.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:t})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:i,className:"px-4 py-1.5 text-xs text-fg-secondary hover:text-fg-primary border border-border-default hover:border-gray-600 rounded-lg transition-colors",children:r}),n.jsx("button",{onClick:a,className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-500 text-white rounded-lg transition-colors",children:s})]})]})})}function ZG(){const[e,t]=x.useState(()=>{const s=window.location.hash.slice(1).split("/");return s[0]==="builder"&&s[1]&&s[2]?{type:s[1],name:decodeURIComponent(s[2])}:null});return x.useEffect(()=>{const r=()=>{const a=window.location.hash.slice(1).split("/");a[0]==="builder"&&a[1]&&a[2]?t({type:a[1],name:decodeURIComponent(a[2])}):t(null)};return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]),e}function QS({authUser:e}={}){const{t}=ft(["builder","common"]),r=Ds(),s=ZG(),[a,i]=x.useState([]),[l,d]=x.useState([]),[u,m]=x.useState(!1),[h,p]=x.useState("all"),[y,g]=x.useState(null),[v,j]=x.useState(new Map),[C,w]=x.useState(null),[N,S]=x.useState(new Map),[T,M]=x.useState(null),[D,I]=x.useState(null),[$,B]=x.useState(null),R=x.useCallback(()=>{m(!0),Promise.all([(rc(Ra.builderArtifacts)??le.builder.artifacts.list()).then(V=>V?.artifacts??[]).catch(()=>[]),(rc(Ra.builderAgents)??le.agents.list()).then(V=>V?.agents??[]).catch(()=>[]),(rc(Ra.builderHubMyItems)??Un.myItems()).then(V=>V?.items??[]).catch(()=>[]),(rc(Ra.builderInstalled)??le.builder.artifacts.installed()).then(V=>V?.installed??{}).catch(()=>({}))]).then(([V,O,q,J])=>{if(d(V),i(O),q.length>0){const Z=new Map;for(const Y of q){const ee=Y.itemType==="agent"?"agent":Y.itemType==="team"?"team":"skill";for(const ae of V)ae.type===ee&&(Y.slug===ae.name||Y.name===(ae.meta.displayName||ae.meta.name||ae.name))&&Z.set(`${ae.type}/${ae.name}`,{id:Y.id,name:Y.name,slug:Y.slug||ae.name,version:Y.version||"1.0.0"})}Z.size>0&&S(Y=>{const ee=new Map(Y);for(const[ae,Q]of Z)ee.set(ae,Q);return ee})}const H=new Map;for(const Z of V){const Y=`${Z.type}/${Z.name}`,ee=J[Y];ee&&H.set(Y,{agentId:ee.agentId,agentIds:ee.agentIds,teamId:ee.teamId})}j(H)}).finally(()=>m(!1))},[]);x.useEffect(()=>{R();const V=O=>{O.detail?.page===Te.BUILDER&&R()};return window.addEventListener("markus:navigate",V),()=>window.removeEventListener("markus:navigate",V)},[R]);const U=V=>{const O=a.find(q=>q.role==="Secretary"||q.name==="Secretary");O?pt.navigate(Te.TEAM,{agentId:O.id,prefillMessage:V}):pt.navigate(Te.TEAM,{prefillMessage:V})},W=async V=>{const O=`${V.type}/${V.name}`;if(!v.has(O)){g({key:O,action:"install"});try{const q=await le.builder.artifacts.install(V.type,V.name),J={};q.agent&&typeof q.agent=="object"&&(J.agentId=q.agent.id),q.team&&typeof q.team=="object"&&(J.teamId=q.team.id),Array.isArray(q.agents)&&(J.agentIds=q.agents.map(H=>H.id)),j(H=>new Map(H).set(O,J)),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Install failed:",q),alert(t("installFailed",{error:String(q)}))}finally{g(null)}}},F=async V=>{const O=`${V.type}/${V.name}`;if(v.has(O)){g({key:O,action:"uninstall"});try{await le.builder.artifacts.uninstall(V.type,V.name),j(q=>{const J=new Map(q);return J.delete(O),J}),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Uninstall failed:",q),alert(t("uninstallFailed",{error:String(q)}))}finally{g(null)}}},L=async(V,O)=>{const q=`${V.type}/${V.name}`;g({key:q,action:"share"});try{const J=await le.builder.artifacts.get(V.type,V.name),H=V.meta.displayName||V.meta.name||V.name,Z=V.meta.description||"",Y=V.meta.category||"general",ee=Array.isArray(V.meta.tags)?V.meta.tags:[],ae=V.name;let Q=V.meta.icon||void 0;const me=V.meta.version||"1.0.0";if(Q&&!Q.startsWith("http")&&/\.(png|jpe?g|gif|webp|svg)$/i.test(Q)){const xe=Q.split("/").pop()??Q;try{const Pe=await fetch(`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(xe)}`);if(Pe.ok){const Ce=await Pe.blob(),Ye=new File([Ce],xe,{type:Ce.type}),Qe=await Un.uploadImage(Ye);Qe?.url&&(Q=Qe.url)}}catch{}}let Ae;const Me=[],He=Array.isArray(V.meta.screenshots)?V.meta.screenshots:[];for(let xe=0;xe<He.length;xe++){const Pe=He[xe],Ce=Pe.split("/").pop()??Pe;try{const Ye=await fetch(`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(Ce)}`);if(Ye.ok){const Qe=await Ye.blob(),ct=new File([Qe],Ce,{type:Qe.type}),st=await Un.uploadImage(ct);st?.url&&(Me.push({url:st.url,alt:Ce,order:xe}),(xe===0||V.meta.thumbnail===Pe)&&(Ae=st.url))}}catch{}}const je=await Un.publishViaProxy({itemType:V.type==="team"?"team":V.type==="skill"?"skill":"agent",name:H,slug:ae,description:Z,category:Y,tags:ee,icon:Q,version:me,config:V.meta,files:J.files&&Object.keys(J.files).length>0?J.files:void 0,thumbnailUrl:Ae,images:Me.length>0?Me:void 0,priceCents:O?.priceCents,donationsEnabled:O?.donationsEnabled});je.id&&S(xe=>{const Pe=new Map(xe);return Pe.set(q,{id:je.id,name:H,slug:je.slug??ae,version:me}),Pe})}catch(J){console.error("Share failed:",J),alert(t("shareFailed",{error:String(J)}))}finally{g(null)}},z=async()=>{if(!T)return;const{key:V}=T,O=N.get(V);if(M(null),!O)return;const q=O.id;g({key:V,action:"hubDelete"});try{await Un.deleteItem(q),S(J=>{const H=new Map(J);return H.delete(V),H})}catch(J){console.error("Hub delete failed:",J),alert(t("hubDeleteFailed",{error:String(J)}))}finally{g(null)}},E=async()=>{if(!C)return;const V=C,O=`${V.type}/${V.name}`;w(null),g({key:O,action:"delete"});try{await le.builder.artifacts.delete(V.type,V.name),d(q=>q.filter(J=>!(J.type===V.type&&J.name===V.name))),j(q=>{const J=new Map(q);return J.delete(O),J}),window.dispatchEvent(new CustomEvent("markus:data-changed"))}catch(q){console.error("Delete failed:",q)}finally{g(null)}},_=h==="all"?l:l.filter(V=>V.type===h),G=V=>{history.pushState(null,"",`#builder/${V.type}/${encodeURIComponent(V.name)}`),window.dispatchEvent(new HashChangeEvent("hashchange"))};return s?n.jsx(uc,{type:s.type,name:s.name,authUser:e,onBack:()=>{history.pushState(null,"","#builder"),window.dispatchEvent(new HashChangeEvent("hashchange"))}}):n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsxs("div",{className:`max-w-5xl mx-auto w-full ${r?"px-4 py-5":"px-6 py-6"}`,children:[n.jsxs("div",{className:"mb-6",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-xl font-bold text-fg-primary",children:t("title")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:t("subtitle")})]}),n.jsx("button",{onClick:R,className:"text-xs text-fg-tertiary hover:text-fg-secondary transition-colors px-3 py-1.5 rounded-lg border border-border-default hover:border-gray-600",children:t("common:refresh")})]}),n.jsx("div",{className:`grid ${r?"grid-cols-1 gap-2":"grid-cols-3 gap-3"}`,children:QG.map(V=>{const O=t(`prompts.${V.id}Prompt`),q=t(`prompts.${V.id}Examples`,{returnObjects:!0}),J=Array.isArray(q)?q:[];return n.jsx("button",{onClick:()=>U(O),className:`group text-left w-full rounded-xl border ${V.borderColor} bg-surface-secondary/60 p-4 transition-all hover:bg-surface-secondary/80 hover:shadow-lg`,children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:`w-10 h-10 text-xl rounded-lg ${V.bgColor} flex items-center justify-center shrink-0`,children:V.icon}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:`text-sm font-semibold bg-gradient-to-r ${V.color} bg-clip-text text-transparent`,children:t(`prompts.${V.id}`)}),n.jsx("p",{className:"text-[11px] text-fg-tertiary mt-1 leading-relaxed",children:t(`prompts.${V.id}Desc`)}),J.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.slice(0,2).map((H,Z)=>n.jsxs("span",{className:"text-[10px] text-fg-muted bg-surface-elevated/60 rounded-full px-2 py-0.5 border border-border-default",onClick:Y=>{Y.stopPropagation(),U(O+H)},children:["“",H,"”"]},Z))})]})]})},V.id)})})]}),n.jsx("div",{className:"mb-3",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg-secondary",children:t("myCreations.title")}),n.jsx("div",{className:"flex gap-1.5",children:["all","agent","team","skill"].map(V=>n.jsx("button",{onClick:()=>p(V),className:`text-xs px-2.5 py-1 rounded-lg transition-colors ${h===V?"bg-brand-600 text-white":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:t(V==="all"?"myCreations.filterAll":V==="agent"?"myCreations.filterAgents":V==="team"?"myCreations.filterTeams":"myCreations.filterSkills")},V))})]})}),u&&l.length===0?n.jsx("div",{className:"text-center text-fg-tertiary py-12 text-sm",children:t("myCreations.loadingArtifacts")}):_.length===0?n.jsxs("div",{className:"text-center py-12",children:[n.jsx("div",{className:"text-fg-tertiary text-sm",children:t("myCreations.noArtifacts")}),n.jsx("div",{className:"text-fg-muted text-xs mt-1",children:t("myCreations.noArtifactsHint")})]}):n.jsx("div",{className:"grid gap-3",children:_.map(V=>{const O=ej[V.type]??ej.agent,q=V.meta.displayName||V.meta.name||V.name,J=V.meta.description||"",H=`${V.type}/${V.name}`,Z=y?.key===H?y.action:null,Y=N.get(H),ee=V.meta.version||"1.0.0",ae=!!Y,Q=ae&&Y.version!==ee,me=()=>{const Me=Un.getUser();return!Y||!Me?null:`${Un.getUrl()}/${encodeURIComponent(Me.username)}/${encodeURIComponent(Y.slug)}`},Ae=n.jsxs("div",{className:`flex items-center gap-1.5 ${r?"flex-wrap":"shrink-0"}`,onClick:Me=>Me.stopPropagation(),children:[v.has(H)?n.jsx("button",{onClick:()=>F(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-green-600/30 text-green-600 hover:bg-red-500/10 hover:text-red-500 hover:border-red-500/30 transition-colors disabled:opacity-50",children:t(Z==="uninstall"?"common:uninstalling":"common:uninstall")}):n.jsx("button",{onClick:()=>W(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors disabled:opacity-50",children:t(Z==="install"?"common:installing":"common:install")}),ae&&Q?n.jsx("button",{onClick:()=>B(V),disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-amber-500/30 text-amber-400 hover:bg-amber-500/10 hover:border-amber-500/50 transition-colors disabled:opacity-50",children:Z==="share"?t("common:sharing"):t("share.updateVersion",{version:ee})}):ae?n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsxs("a",{href:me()??"#",target:"_blank",rel:"noopener noreferrer",className:"text-xs px-3 py-1.5 rounded-lg border border-green-600/30 text-green-600 hover:text-green-500 hover:border-green-500/40 transition-colors inline-flex items-center gap-1",children:[n.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),t("common:shared")]}),n.jsx("button",{onClick:()=>M({key:H,name:q}),disabled:!!Z,className:"text-xs px-1.5 py-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50",title:t("removeFromHubTooltip"),children:n.jsxs("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]}):n.jsx("button",{onClick:async()=>{await Un.ensureAuth(),Array.isArray(V.meta.screenshots)&&V.meta.screenshots.length>0?L(V):I(V)},disabled:!!Z,className:"text-xs px-3 py-1.5 rounded-lg border border-border-default text-fg-secondary hover:text-green-600 hover:border-green-500/30 transition-colors disabled:opacity-50",children:t(Z==="share"?"common:sharing":"common:share")}),n.jsx("button",{onClick:()=>w(V),disabled:!!Z,className:"text-xs px-2 py-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50",title:t("common:delete"),children:n.jsxs("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]});return n.jsxs("div",{onClick:()=>G(V),className:"group rounded-lg bg-surface-elevated p-4 hover:bg-surface-overlay transition-all overflow-hidden cursor-pointer",children:[n.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[(()=>{const Me=V.meta.icon,je=Me&&(Me.startsWith("http")||Me.startsWith("/")||/\.(png|jpe?g|gif|webp|svg)$/i.test(Me))?Me.startsWith("http")||Me.startsWith("/")?Me:`/api/builder/artifacts/${V.type}s/${encodeURIComponent(V.name)}/images/${encodeURIComponent(Me.split("/").pop()??"")}`:null;return n.jsx("div",{className:`w-9 h-9 rounded-lg ${O.bg} flex items-center justify-center text-lg shrink-0 overflow-hidden`,children:je?n.jsx("img",{src:je,alt:"",className:"w-full h-full object-cover"}):Me?n.jsx("span",{children:Me}):O.icon})})(),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:q}),n.jsx("span",{className:`text-[10px] font-medium uppercase tracking-wider ${O.color}`,children:V.type})]}),J&&n.jsx("p",{className:"text-xs text-fg-tertiary line-clamp-2",children:J}),n.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[10px] text-fg-tertiary min-w-0",children:[n.jsx("button",{onClick:Me=>{Me.stopPropagation(),le.system.openPath(V.path).catch(()=>{})},className:"hover:text-fg-secondary transition-colors truncate min-w-0",title:V.path,children:XG(V.path)}),n.jsx("span",{className:"shrink-0",children:new Date(V.updatedAt).toLocaleDateString()})]})]}),!r&&Ae]}),r&&n.jsx("div",{className:"mt-3 pt-3 border-t border-border-default/50",children:Ae})]},H)})}),C&&n.jsx(tj,{title:t("confirmDelete"),message:t("deleteCannotUndo",{name:C.meta.displayName||C.meta.name||C.name}),cancelLabel:t("common:cancel"),confirmLabel:t("common:delete"),onConfirm:E,onCancel:()=>w(null)}),T&&n.jsx(tj,{title:t("confirmDelete"),message:t("removeFromHub",{name:T.name}),cancelLabel:t("common:cancel"),confirmLabel:t("common:delete"),onConfirm:()=>{z()},onCancel:()=>M(null)}),D&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>I(null),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl max-w-sm w-full mx-4 p-6 shadow-2xl",onClick:V=>V.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary mb-2",children:t("common:share")}),n.jsx("p",{className:"text-sm text-fg-secondary mb-5",children:t("share.imagePrompt")}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:()=>{const V=D;I(null),L(V)},className:"flex-1 text-sm px-4 py-2 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-fg-tertiary transition-colors",children:t("share.directly")}),n.jsx("button",{onClick:()=>{const V=D;I(null),G(V)},className:"flex-1 text-sm px-4 py-2 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors",children:t("share.addImagesFirst")})]})]})}),$&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:()=>B(null),children:n.jsx("div",{className:"bg-surface-secondary border border-border-default rounded-xl max-w-sm w-full mx-4 p-6 shadow-2xl",onClick:V=>V.stopPropagation(),children:n.jsx(JG,{isUpdate:N.has(`${$.type}/${$.name}`),onCancel:()=>B(null),onConfirm:(V,O)=>{const q=$;B(null),L(q,{donationsEnabled:V==="donation",priceCents:V==="paid"?O:void 0})}})})})]})})}function JG({isUpdate:e,onCancel:t,onConfirm:r}){const{t:s}=ft(["builder","common"]),[a,i]=x.useState("free"),[l,d]=x.useState("");return n.jsxs(n.Fragment,{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary mb-4",children:s(e?"shareMode.titleUpdate":"shareMode.title")}),n.jsxs("div",{className:"space-y-2 mb-5",children:[n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="free"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="free",onChange:()=>i("free"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.free")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.freeDesc")})]})]}),n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="donation"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="donation",onChange:()=>i("donation"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.donation")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.donationDesc")})]})]}),n.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${a==="paid"?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-gray-600"}`,children:[n.jsx("input",{type:"radio",name:"shareMode",checked:a==="paid",onChange:()=>i("paid"),className:"accent-brand-500"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("shareMode.paid")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary",children:s("shareMode.paidDesc")})]})]})]}),a==="paid"&&n.jsxs("div",{className:"mb-5",children:[n.jsx("label",{className:"text-xs text-fg-secondary block mb-1.5",children:s("shareMode.priceLabel")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm text-fg-tertiary",children:"$"}),n.jsx("input",{type:"number",min:"0.5",step:"0.5",value:l,onChange:u=>d(u.target.value),placeholder:s("shareMode.pricePlaceholder"),className:"flex-1 text-sm px-3 py-2 rounded-lg bg-surface-elevated border border-border-default text-fg-primary placeholder:text-fg-muted"})]})]}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:t,className:"flex-1 text-sm px-4 py-2 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-gray-600 transition-colors",children:s("common:cancel")}),n.jsx("button",{onClick:()=>r(a,a==="paid"?Math.round(Number(l)*100):0),disabled:a==="paid"&&(!l||Number(l)<=0),className:"flex-1 text-sm px-4 py-2 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:s(e?"shareMode.update":"shareMode.share")})]})]})}const nj={agent:{icon:"✦",label:"Agent",color:"text-brand-500",gradient:"from-brand-500 to-purple-600",bg:"bg-brand-500/10",ring:"ring-brand-500/30"},team:{icon:"◈",label:"Team",color:"text-blue-600",gradient:"from-blue-500 to-blue-600",bg:"bg-blue-500/10",ring:"ring-blue-500/30"},skill:{icon:"⬡",label:"Skill",color:"text-green-600",gradient:"from-green-500 to-green-600",bg:"bg-green-500/10",ring:"ring-green-500/30"}},eY=["development","devops","management","productivity","browser","custom","general"],tY=[{label:"Tech",emojis:["✦","◈","⬡","⚡","🤖","🧠","💡","🎯","🔧","📦","🚀","💻","🛠️","⭐","🔥","💎","⚙️","🧩","🔌","💾","🖥️","📡","🔬","🧪","🏗️","📱","🎮","🕹️","📟","💽","🖨️","⌨️"]},{label:"People",emojis:["👤","👥","🧑‍💻","👨‍💼","👩‍🔬","🧙","🦸","🤝","💪","🎓","👷","🕵️","🧑‍🎨","🧑‍🏫","👨‍🚀","🥷","🧑‍🏭","🧑‍⚕️","🧑‍🔧","🧑‍🍳","👨‍🎤","🦹","🧝","🧞","🧑‍✈️","💂","🤴","👸","🧛","🧟","🧜","🧚"]},{label:"Objects",emojis:["📝","📊","🗂️","📁","🔍","🔑","🌐","💬","🔒","🎨","📐","🗃️","📋","✏️","🖊️","📌","📎","🧲","🪝","🧰","🪜","🧬","🔭","💊","🩺","📕","📗","📘","📙","📓","🗒️","📰"]},{label:"Symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","♠️","♥️","♦️","♣️","🎵","🎶","💯","✅","❌","⭕","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","🟤","🔶","🔷","▶️","⏸️","⏹️"]},{label:"Nature",emojis:["🌟","🌈","🌊","🌿","🍀","🔮","💫","✨","🌙","☀️","🦋","🐉","🦊","🐺","🦅","🐙","🦁","🐯","🦄","🐲","🌸","🌺","🍄","🌵","🎄","🌴","🍁","🌻","🐝","🦎","🐍","🦈"]},{label:"Activity",emojis:["🎯","🏆","🥇","🎖️","🏅","🎪","🎭","🎬","🎤","🎧","🎼","🎹","🥁","🎸","🎺","🎻","⚽","🏀","🎾","🏐","🎲","🧸","🪁","🎰","🎳","🏹","🥊","🤺","⛷️","🏄","🚴","🧗"]}],nY={shell:{icon:">",color:"bg-amber-500/15 text-amber-400 border-amber-500/30"},file:{icon:"◫",color:"bg-blue-500/15 text-blue-400 border-blue-500/30"},network:{icon:"◎",color:"bg-purple-500/15 text-purple-400 border-purple-500/30"},browser:{icon:"◉",color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30"}};function Vx({value:e,onChange:t,renderAs:r="span",className:s,editClassName:a,placeholder:i,multiline:l,readOnly:d}){if(d){const S=e||i,M=`${s??""} ${!e?"text-fg-muted italic":""}`;return r==="h1"?n.jsx("h1",{className:M,children:S}):r==="p"?n.jsx("p",{className:M,children:S}):n.jsx("span",{className:M,children:S})}const[u,m]=x.useState(!1),[h,p]=x.useState(e),y=x.useRef(null);x.useEffect(()=>{p(e)},[e]),x.useEffect(()=>{u&&y.current?.focus()},[u]);const g=()=>{m(!1),h!==e&&t(h)},v=()=>{p(e),m(!1)},j=S=>{S.key==="Escape"&&v(),S.key==="Enter"&&!l&&g()};if(u){const S=`bg-transparent outline-none w-full ${a??s??""} ring-1 ring-brand-500/50 rounded px-1 -mx-1`;return l?n.jsx("textarea",{ref:y,value:h,onChange:T=>p(T.target.value),onBlur:g,onKeyDown:j,className:`${S} resize-y min-h-[60px]`,placeholder:i}):n.jsx("input",{ref:y,value:h,onChange:T=>p(T.target.value),onBlur:g,onKeyDown:j,className:S,placeholder:i})}const C=e||i,w=!e,N="cursor-text hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 transition-all";return r==="h1"?n.jsx("h1",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):r==="p"?n.jsx("p",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):r==="badge"?n.jsx("span",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C}):n.jsx("span",{onClick:()=>m(!0),className:`${s??""} ${N} ${w?"text-fg-muted italic":""}`,children:C})}function rY({value:e,options:t,onChange:r,className:s,readOnly:a}){if(a)return n.jsx("span",{className:s,children:e});const[i,l]=x.useState(!1),[d,u]=x.useState(e),m=x.useRef(null),h=x.useRef(null);x.useEffect(()=>{i&&(u(e),setTimeout(()=>m.current?.focus(),0))},[i,e]);const p=t.filter(g=>g.toLowerCase().includes(d.toLowerCase())),y=g=>{const v=g.trim();v&&v!==e&&r(v),l(!1)};return i?n.jsxs("div",{ref:h,className:"relative inline-block",children:[n.jsx("input",{ref:m,value:d,onChange:g=>u(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),y(d)):g.key==="Escape"&&l(!1)},onBlur:g=>{h.current?.contains(g.relatedTarget)||y(d)},className:`${s??""} bg-transparent outline-none ring-1 ring-brand-500/50 rounded w-28`}),p.length>0&&n.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 min-w-[120px] max-h-40 overflow-y-auto",children:p.map(g=>n.jsx("button",{onMouseDown:v=>{v.preventDefault(),y(g)},className:`block w-full text-left px-3 py-1.5 text-xs hover:bg-surface-secondary/80 transition-colors ${g===e?"text-brand-400 font-medium":"text-fg-secondary"}`,children:g},g))})]}):n.jsx("span",{onClick:()=>l(!0),className:`${s??""} cursor-pointer hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 transition-all`,children:e})}function sY({tags:e,onChange:t,readOnly:r}){if(r)return n.jsx("div",{className:"flex flex-wrap items-center gap-1.5 min-h-[24px]",children:e.map(h=>n.jsx("span",{className:"text-[10px] px-2 py-0.5 bg-surface-elevated text-fg-muted rounded-full border border-border-default",children:h},h))});const{t:s}=ft(["builder"]),[a,i]=x.useState(!1),[l,d]=x.useState(""),u=x.useRef(null);x.useEffect(()=>{a&&u.current?.focus()},[a]);const m=h=>{if((h.key==="Enter"||h.key===",")&&l.trim()){h.preventDefault();const p=l.trim().toLowerCase();e.includes(p)||t([...e,p]),d("")}else h.key==="Backspace"&&!l&&e.length>0?t(e.slice(0,-1)):h.key==="Escape"&&(i(!1),d(""))};return a?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 ring-1 ring-brand-500/50 rounded px-2 py-1 -mx-1 min-h-[32px]",children:[e.map(h=>n.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] bg-surface-elevated text-fg-secondary rounded-full px-2 py-0.5 border border-border-default",children:[h,n.jsx("button",{onClick:()=>t(e.filter(p=>p!==h)),className:"text-fg-muted hover:text-red-500",children:"×"})]},h)),n.jsx("input",{ref:u,value:l,onChange:h=>d(h.target.value),onKeyDown:m,onBlur:()=>{l||i(!1)},className:"flex-1 min-w-[80px] bg-transparent text-xs text-fg-primary placeholder:text-fg-muted focus:outline-none",placeholder:s("detail.typeTagAndEnter")})]}):n.jsx("div",{onClick:()=>i(!0),className:"flex flex-wrap items-center gap-1.5 cursor-text hover:ring-1 hover:ring-border-default rounded px-1 -mx-1 py-0.5 transition-all min-h-[24px]",children:e.length>0?e.map(h=>n.jsx("span",{className:"text-[10px] px-2 py-0.5 bg-surface-elevated text-fg-muted rounded-full border border-border-default",children:h},h)):n.jsx("span",{className:"text-[10px] text-fg-muted italic",children:s("detail.typeTagAndEnter")})})}function Zb({content:e}){return n.jsx("div",{className:`prose prose-invert prose-sm max-w-none
659
659
  prose-headings:text-fg-primary prose-headings:font-semibold
660
660
  prose-p:text-fg-secondary prose-p:leading-relaxed
661
661
  prose-a:text-brand-400 prose-a:no-underline hover:prose-a:underline
@@ -706,4 +706,4 @@ l0,-`+(r+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
706
706
  `)),h=m.reduce((p,y)=>p.concat(...y),[]);return[m,h]}return[[],[]]},[e]);return x.useEffect(()=>{const u=t?.target??Xj,m=t?.actInsideInputWithModifier??!0;if(e!==null){const h=g=>{if(a.current=g.ctrlKey||g.metaKey||g.shiftKey||g.altKey,(!a.current||a.current&&!m)&&X7(g))return!1;const j=Zj(g.code,d);if(i.current.add(g[j]),Qj(l,i.current,!1)){const C=g.composedPath?.()?.[0]||g.target,w=C?.nodeName==="BUTTON"||C?.nodeName==="A";t.preventDefault!==!1&&(a.current||!w)&&g.preventDefault(),s(!0)}},p=g=>{const v=Zj(g.code,d);Qj(l,i.current,!0)?(s(!1),i.current.clear()):i.current.delete(g[v]),g.key==="Meta"&&i.current.clear(),a.current=!1},y=()=>{i.current.clear(),s(!1)};return u?.addEventListener("keydown",h),u?.addEventListener("keyup",p),window.addEventListener("blur",y),window.addEventListener("contextmenu",y),()=>{u?.removeEventListener("keydown",h),u?.removeEventListener("keyup",p),window.removeEventListener("blur",y),window.removeEventListener("contextmenu",y)}}},[e,s]),r}function Qj(e,t,r){return e.filter(s=>r||s.length===t.size).some(s=>s.every(a=>t.has(a)))}function Zj(e,t){return t.includes(e)?"code":"key"}const Dee=()=>{const e=Fr();return x.useMemo(()=>({zoomIn:t=>{const{panZoom:r}=e.getState();return r?r.scaleBy(1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:r}=e.getState();return r?r.scaleBy(1/1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomTo:(t,r)=>{const{panZoom:s}=e.getState();return s?s.scaleTo(t,{duration:r?.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,r)=>{const{transform:[s,a,i],panZoom:l}=e.getState();return l?(await l.setViewport({x:t.x??s,y:t.y??a,zoom:t.zoom??i},r),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,r,s]=e.getState().transform;return{x:t,y:r,zoom:s}},setCenter:async(t,r,s)=>e.getState().setCenter(t,r,s),fitBounds:async(t,r)=>{const{width:s,height:a,minZoom:i,maxZoom:l,panZoom:d}=e.getState(),u=wy(t,s,a,i,l,r?.padding??.1);return d?(await d.setViewport(u,{duration:r?.duration,ease:r?.ease,interpolate:r?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,r={})=>{const{transform:s,snapGrid:a,snapToGrid:i,domNode:l}=e.getState();if(!l)return t;const{x:d,y:u}=l.getBoundingClientRect(),m={x:t.x-d,y:t.y-u},h=r.snapGrid??a,p=r.snapToGrid??i;return O0(m,s,p,h)},flowToScreenPosition:t=>{const{transform:r,domNode:s}=e.getState();if(!s)return t;const{x:a,y:i}=s.getBoundingClientRect(),l=wh(t,r);return{x:l.x+a,y:l.y+i}}}),[])};function b8(e,t){const r=[],s=new Map,a=[];for(const i of e)if(i.type==="add"){a.push(i);continue}else if(i.type==="remove"||i.type==="replace")s.set(i.id,[i]);else{const l=s.get(i.id);l?l.push(i):s.set(i.id,[i])}for(const i of t){const l=s.get(i.id);if(!l){r.push(i);continue}if(l[0].type==="remove")continue;if(l[0].type==="replace"){r.push({...l[0].item});continue}const d={...i};for(const u of l)Ree(u,d);r.push(d)}return a.length&&a.forEach(i=>{i.index!==void 0?r.splice(i.index,0,{...i.item}):r.push({...i.item})}),r}function Ree(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function y8(e,t){return b8(e,t)}function v8(e,t){return b8(e,t)}function Jl(e,t){return{id:e,type:"select",selected:t}}function md(e,t=new Set,r=!1){const s=[];for(const[a,i]of e){const l=t.has(a);!(i.selected===void 0&&!l)&&i.selected!==l&&(r&&(i.selected=l),s.push(Jl(i.id,l)))}return s}function Jj({items:e=[],lookup:t}){const r=[],s=new Map(e.map(a=>[a.id,a]));for(const[a,i]of e.entries()){const l=t.get(i.id),d=l?.internals?.userNode??l;d!==void 0&&d!==i&&r.push({id:i.id,item:i,type:"replace"}),d===void 0&&r.push({item:i,type:"add",index:a})}for(const[a]of t)s.get(a)===void 0&&r.push({id:a,type:"remove"});return r}function e3(e){return{id:e.id,type:"remove"}}const t3=e=>sJ(e),Iee=e=>F7(e);function w8(e){return x.forwardRef(e)}const Lee=typeof window<"u"?x.useLayoutEffect:x.useEffect;function n3(e){const[t,r]=x.useState(BigInt(0)),[s]=x.useState(()=>Pee(()=>r(a=>a+BigInt(1))));return Lee(()=>{const a=s.get();a.length&&(e(a),s.reset())},[t]),s}function Pee(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:r=>{t.push(r),e()}}}const k8=x.createContext(null);function Oee({children:e}){const t=Fr(),r=x.useCallback(d=>{const{nodes:u=[],setNodes:m,hasDefaultNodes:h,onNodesChange:p,nodeLookup:y,fitViewQueued:g,onNodesChangeMiddlewareMap:v}=t.getState();let j=u;for(const w of d)j=typeof w=="function"?w(j):w;let C=Jj({items:j,lookup:y});for(const w of v.values())C=w(C);h&&m(j),C.length>0?p?.(C):g&&window.requestAnimationFrame(()=>{const{fitViewQueued:w,nodes:N,setNodes:S}=t.getState();w&&S(N)})},[]),s=n3(r),a=x.useCallback(d=>{const{edges:u=[],setEdges:m,hasDefaultEdges:h,onEdgesChange:p,edgeLookup:y}=t.getState();let g=u;for(const v of d)g=typeof v=="function"?v(g):v;h?m(g):p&&p(Jj({items:g,lookup:y}))},[]),i=n3(a),l=x.useMemo(()=>({nodeQueue:s,edgeQueue:i}),[]);return n.jsx(k8.Provider,{value:l,children:e})}function _ee(){const e=x.useContext(k8);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const zee=e=>!!e.panZoom;function Ay(){const e=Dee(),t=Fr(),r=_ee(),s=dr(zee),a=x.useMemo(()=>{const i=p=>t.getState().nodeLookup.get(p),l=p=>{r.nodeQueue.push(p)},d=p=>{r.edgeQueue.push(p)},u=p=>{const{nodeLookup:y,nodeOrigin:g}=t.getState(),v=t3(p)?p:y.get(p.id),j=v.parentId?G7(v.position,v.measured,v.parentId,y,g):v.position,C={...v,position:j,width:v.measured?.width??v.width,height:v.measured?.height??v.height};return Ad(C)},m=(p,y,g={replace:!1})=>{l(v=>v.map(j=>{if(j.id===p){const C=typeof y=="function"?y(j):y;return g.replace&&t3(C)?C:{...j,...C}}return j}))},h=(p,y,g={replace:!1})=>{d(v=>v.map(j=>{if(j.id===p){const C=typeof y=="function"?y(j):y;return g.replace&&Iee(C)?C:{...j,...C}}return j}))};return{getNodes:()=>t.getState().nodes.map(p=>({...p})),getNode:p=>i(p)?.internals.userNode,getInternalNode:i,getEdges:()=>{const{edges:p=[]}=t.getState();return p.map(y=>({...y}))},getEdge:p=>t.getState().edgeLookup.get(p),setNodes:l,setEdges:d,addNodes:p=>{const y=Array.isArray(p)?p:[p];r.nodeQueue.push(g=>[...g,...y])},addEdges:p=>{const y=Array.isArray(p)?p:[p];r.edgeQueue.push(g=>[...g,...y])},toObject:()=>{const{nodes:p=[],edges:y=[],transform:g}=t.getState(),[v,j,C]=g;return{nodes:p.map(w=>({...w})),edges:y.map(w=>({...w})),viewport:{x:v,y:j,zoom:C}}},deleteElements:async({nodes:p=[],edges:y=[]})=>{const{nodes:g,edges:v,onNodesDelete:j,onEdgesDelete:C,triggerNodeChanges:w,triggerEdgeChanges:N,onDelete:S,onBeforeDelete:T}=t.getState(),{nodes:M,edges:D}=await cJ({nodesToRemove:p,edgesToRemove:y,nodes:g,edges:v,onBeforeDelete:T}),I=D.length>0,$=M.length>0;if(I){const B=D.map(e3);C?.(D),N(B)}if($){const B=M.map(e3);j?.(M),w(B)}return($||I)&&S?.({nodes:M,edges:D}),{deletedNodes:M,deletedEdges:D}},getIntersectingNodes:(p,y=!0,g)=>{const v=Ej(p),j=v?p:u(p),C=g!==void 0;return j?(g||t.getState().nodes).filter(w=>{const N=t.getState().nodeLookup.get(w.id);if(N&&!v&&(w.id===p.id||!N.internals.positionAbsolute))return!1;const S=Ad(C?w:N),T=y0(S,j);return y&&T>0||T>=S.width*S.height||T>=j.width*j.height}):[]},isNodeIntersecting:(p,y,g=!0)=>{const j=Ej(p)?p:u(p);if(!j)return!1;const C=y0(j,y);return g&&C>0||C>=y.width*y.height||C>=j.width*j.height},updateNode:m,updateNodeData:(p,y,g={replace:!1})=>{m(p,v=>{const j=typeof y=="function"?y(v):y;return g.replace?{...v,data:j}:{...v,data:{...v.data,...j}}},g)},updateEdge:h,updateEdgeData:(p,y,g={replace:!1})=>{h(p,v=>{const j=typeof y=="function"?y(v):y;return g.replace?{...v,data:j}:{...v,data:{...v.data,...j}}},g)},getNodesBounds:p=>{const{nodeLookup:y,nodeOrigin:g}=t.getState();return aJ(p,{nodeLookup:y,nodeOrigin:g})},getHandleConnections:({type:p,id:y,nodeId:g})=>Array.from(t.getState().connectionLookup.get(`${g}-${p}${y?`-${y}`:""}`)?.values()??[]),getNodeConnections:({type:p,handleId:y,nodeId:g})=>Array.from(t.getState().connectionLookup.get(`${g}${p?y?`-${p}-${y}`:`-${p}`:""}`)?.values()??[]),fitView:async p=>{const y=t.getState().fitViewResolver??fJ();return t.setState({fitViewQueued:!0,fitViewOptions:p,fitViewResolver:y}),r.nodeQueue.push(g=>[...g]),y.promise}}},[]);return x.useMemo(()=>({...a,...e,viewportInitialized:s}),[s])}const r3=e=>e.selected,$ee=typeof window<"u"?window:void 0;function Bee({deleteKeyCode:e,multiSelectionKeyCode:t}){const r=Fr(),{deleteElements:s}=Ay(),a=w0(e,{actInsideInputWithModifier:!1}),i=w0(t,{target:$ee});x.useEffect(()=>{if(a){const{edges:l,nodes:d}=r.getState();s({nodes:d.filter(r3),edges:l.filter(r3)}),r.setState({nodesSelectionActive:!1})}},[a]),x.useEffect(()=>{r.setState({multiSelectionActive:i})},[i])}function Hee(e){const t=Fr();x.useEffect(()=>{const r=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;const s=ky(e.current);(s.height===0||s.width===0)&&t.getState().onError?.("004",Gi.error004()),t.setState({width:s.width||500,height:s.height||500})};if(e.current){r(),window.addEventListener("resize",r);const s=new ResizeObserver(()=>r());return s.observe(e.current),()=>{window.removeEventListener("resize",r),s&&e.current&&s.unobserve(e.current)}}},[])}const np={position:"absolute",width:"100%",height:"100%",top:0,left:0},Fee=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function qee({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:r=!0,panOnScroll:s=!1,panOnScrollSpeed:a=.5,panOnScrollMode:i=oc.Free,zoomOnDoubleClick:l=!0,panOnDrag:d=!0,defaultViewport:u,translateExtent:m,minZoom:h,maxZoom:p,zoomActivationKeyCode:y,preventScrolling:g=!0,children:v,noWheelClassName:j,noPanClassName:C,onViewportChange:w,isControlledViewport:N,paneClickDistance:S,selectionOnDrag:T}){const M=Fr(),D=x.useRef(null),{userSelectionActive:I,lib:$,connectionInProgress:B}=dr(Fee,Xr),R=w0(y),U=x.useRef();Hee(D);const W=x.useCallback(F=>{w?.({x:F[0],y:F[1],zoom:F[2]}),N||M.setState({transform:F})},[w,N]);return x.useEffect(()=>{if(D.current){U.current=XJ({domNode:D.current,minZoom:h,maxZoom:p,translateExtent:m,viewport:u,onDraggingChange:E=>M.setState(_=>_.paneDragging===E?_:{paneDragging:E}),onPanZoomStart:(E,_)=>{const{onViewportChangeStart:G,onMoveStart:V}=M.getState();V?.(E,_),G?.(_)},onPanZoom:(E,_)=>{const{onViewportChange:G,onMove:V}=M.getState();V?.(E,_),G?.(_)},onPanZoomEnd:(E,_)=>{const{onViewportChangeEnd:G,onMoveEnd:V}=M.getState();V?.(E,_),G?.(_)}});const{x:F,y:L,zoom:z}=U.current.getViewport();return M.setState({panZoom:U.current,transform:[F,L,z],domNode:D.current.closest(".react-flow")}),()=>{U.current?.destroy()}}},[]),x.useEffect(()=>{U.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:r,panOnScroll:s,panOnScrollSpeed:a,panOnScrollMode:i,zoomOnDoubleClick:l,panOnDrag:d,zoomActivationKeyPressed:R,preventScrolling:g,noPanClassName:C,userSelectionActive:I,noWheelClassName:j,lib:$,onTransformChange:W,connectionInProgress:B,selectionOnDrag:T,paneClickDistance:S})},[e,t,r,s,a,i,l,d,R,g,C,I,j,$,W,B,T,S]),n.jsx("div",{className:"react-flow__renderer",ref:D,style:np,children:v})}const Uee=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Vee(){const{userSelectionActive:e,userSelectionRect:t}=dr(Uee,Xr);return e&&t?n.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const sb=(e,t)=>r=>{r.target===t.current&&e?.(r)},Kee=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Wee({isSelecting:e,selectionKeyPressed:t,selectionMode:r=b0.Full,panOnDrag:s,paneClickDistance:a,selectionOnDrag:i,onSelectionStart:l,onSelectionEnd:d,onPaneClick:u,onPaneContextMenu:m,onPaneScroll:h,onPaneMouseEnter:p,onPaneMouseMove:y,onPaneMouseLeave:g,children:v}){const j=Fr(),{userSelectionActive:C,elementsSelectable:w,dragging:N,connectionInProgress:S}=dr(Kee,Xr),T=w&&(e||C),M=x.useRef(null),D=x.useRef(),I=x.useRef(new Set),$=x.useRef(new Set),B=x.useRef(!1),R=G=>{if(B.current||S){B.current=!1;return}u?.(G),j.getState().resetSelectedElements(),j.setState({nodesSelectionActive:!1})},U=G=>{if(Array.isArray(s)&&s?.includes(2)){G.preventDefault();return}m?.(G)},W=h?G=>h(G):void 0,F=G=>{B.current&&(G.stopPropagation(),B.current=!1)},L=G=>{const{domNode:V}=j.getState();if(D.current=V?.getBoundingClientRect(),!D.current)return;const O=G.target===M.current;if(!O&&!!G.target.closest(".nokey")||!e||!(i&&O||t)||G.button!==0||!G.isPrimary)return;G.target?.setPointerCapture?.(G.pointerId),B.current=!1;const{x:H,y:Z}=Ci(G.nativeEvent,D.current);j.setState({userSelectionRect:{width:0,height:0,startX:H,startY:Z,x:H,y:Z}}),O||(G.stopPropagation(),G.preventDefault())},z=G=>{const{userSelectionRect:V,transform:O,nodeLookup:q,edgeLookup:J,connectionLookup:H,triggerNodeChanges:Z,triggerEdgeChanges:Y,defaultEdgeOptions:ee,resetSelectedElements:ae}=j.getState();if(!D.current||!V)return;const{x:Q,y:me}=Ci(G.nativeEvent,D.current),{startX:Ae,startY:Me}=V;if(!B.current){const Ce=t?0:a;if(Math.hypot(Q-Ae,me-Me)<=Ce)return;ae(),l?.(G)}B.current=!0;const He={startX:Ae,startY:Me,x:Q<Ae?Q:Ae,y:me<Me?me:Me,width:Math.abs(Q-Ae),height:Math.abs(me-Me)},je=I.current,xe=$.current;I.current=new Set(vy(q,He,O,r===b0.Partial,!0).map(Ce=>Ce.id)),$.current=new Set;const Pe=ee?.selectable??!0;for(const Ce of I.current){const Ye=H.get(Ce);if(Ye)for(const{edgeId:Qe}of Ye.values()){const ct=J.get(Qe);ct&&(ct.selectable??Pe)&&$.current.add(Qe)}}if(!Mj(je,I.current)){const Ce=md(q,I.current,!0);Z(Ce)}if(!Mj(xe,$.current)){const Ce=md(J,$.current);Y(Ce)}j.setState({userSelectionRect:He,userSelectionActive:!0,nodesSelectionActive:!1})},E=G=>{G.button===0&&(G.target?.releasePointerCapture?.(G.pointerId),!C&&G.target===M.current&&j.getState().userSelectionRect&&R?.(G),j.setState({userSelectionActive:!1,userSelectionRect:null}),B.current&&(d?.(G),j.setState({nodesSelectionActive:I.current.size>0})))},_=s===!0||Array.isArray(s)&&s.includes(0);return n.jsxs("div",{className:ks(["react-flow__pane",{draggable:_,dragging:N,selection:e}]),onClick:T?void 0:sb(R,M),onContextMenu:sb(U,M),onWheel:sb(W,M),onPointerEnter:T?void 0:p,onPointerMove:T?z:y,onPointerUp:T?E:void 0,onPointerDownCapture:T?L:void 0,onClickCapture:T?F:void 0,onPointerLeave:g,ref:M,style:np,children:[v,n.jsx(Vee,{})]})}function g1({id:e,store:t,unselect:r=!1,nodeRef:s}){const{addSelectedNodes:a,unselectNodesAndEdges:i,multiSelectionActive:l,nodeLookup:d,onError:u}=t.getState(),m=d.get(e);if(!m){u?.("012",Gi.error012(e));return}t.setState({nodesSelectionActive:!1}),m.selected?(r||m.selected&&l)&&(i({nodes:[m],edges:[]}),requestAnimationFrame(()=>s?.current?.blur())):a([e])}function j8({nodeRef:e,disabled:t=!1,noDragClassName:r,handleSelector:s,nodeId:a,isSelectable:i,nodeClickDistance:l}){const d=Fr(),[u,m]=x.useState(!1),h=x.useRef();return x.useEffect(()=>{h.current=OJ({getStoreItems:()=>d.getState(),onNodeMouseDown:p=>{g1({id:p,store:d,nodeRef:e})},onDragStart:()=>{m(!0)},onDragStop:()=>{m(!1)}})},[]),x.useEffect(()=>{if(!(t||!e.current||!h.current))return h.current.update({noDragClassName:r,handleSelector:s,domNode:e.current,isSelectable:i,nodeId:a,nodeClickDistance:l}),()=>{h.current?.destroy()}},[r,s,t,i,e,a,l]),u}const Gee=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function N8(){const e=Fr();return x.useCallback(r=>{const{nodeExtent:s,snapToGrid:a,snapGrid:i,nodesDraggable:l,onError:d,updateNodePositions:u,nodeLookup:m,nodeOrigin:h}=e.getState(),p=new Map,y=Gee(l),g=a?i[0]:5,v=a?i[1]:5,j=r.direction.x*g*r.factor,C=r.direction.y*v*r.factor;for(const[,w]of m){if(!y(w))continue;let N={x:w.internals.positionAbsolute.x+j,y:w.internals.positionAbsolute.y+C};a&&(N=P0(N,i));const{position:S,positionAbsolute:T}=q7({nodeId:w.id,nextPosition:N,nodeLookup:m,nodeExtent:s,nodeOrigin:h,onError:d});w.position=S,w.internals.positionAbsolute=T,p.set(w.id,w)}u(p)},[])}const Ey=x.createContext(null),Yee=Ey.Provider;Ey.Consumer;const S8=()=>x.useContext(Ey),Xee=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Qee=(e,t,r)=>s=>{const{connectionClickStartHandle:a,connectionMode:i,connection:l}=s,{fromHandle:d,toHandle:u,isValid:m}=l,h=u?.nodeId===e&&u?.id===t&&u?.type===r;return{connectingFrom:d?.nodeId===e&&d?.id===t&&d?.type===r,connectingTo:h,clickConnecting:a?.nodeId===e&&a?.id===t&&a?.type===r,isPossibleEndHandle:i===Sd.Strict?d?.type!==r:e!==d?.nodeId||t!==d?.id,connectionInProcess:!!d,clickConnectionInProcess:!!a,valid:h&&m}};function Zee({type:e="source",position:t=Zt.Top,isValidConnection:r,isConnectable:s=!0,isConnectableStart:a=!0,isConnectableEnd:i=!0,id:l,onConnect:d,children:u,className:m,onMouseDown:h,onTouchStart:p,...y},g){const v=l||null,j=e==="target",C=Fr(),w=S8(),{connectOnClick:N,noPanClassName:S,rfId:T}=dr(Xee,Xr),{connectingFrom:M,connectingTo:D,clickConnecting:I,isPossibleEndHandle:$,connectionInProcess:B,clickConnectionInProcess:R,valid:U}=dr(Qee(w,v,e),Xr);w||C.getState().onError?.("010",Gi.error010());const W=z=>{const{defaultEdgeOptions:E,onConnect:_,hasDefaultEdges:G}=C.getState(),V={...E,...z};if(G){const{edges:O,setEdges:q}=C.getState();q(vJ(V,O))}_?.(V),d?.(V)},F=z=>{if(!w)return;const E=Q7(z.nativeEvent);if(a&&(E&&z.button===0||!E)){const _=C.getState();p1.onPointerDown(z.nativeEvent,{handleDomNode:z.currentTarget,autoPanOnConnect:_.autoPanOnConnect,connectionMode:_.connectionMode,connectionRadius:_.connectionRadius,domNode:_.domNode,nodeLookup:_.nodeLookup,lib:_.lib,isTarget:j,handleId:v,nodeId:w,flowId:_.rfId,panBy:_.panBy,cancelConnection:_.cancelConnection,onConnectStart:_.onConnectStart,onConnectEnd:(...G)=>C.getState().onConnectEnd?.(...G),updateConnection:_.updateConnection,onConnect:W,isValidConnection:r||((...G)=>C.getState().isValidConnection?.(...G)??!0),getTransform:()=>C.getState().transform,getFromHandle:()=>C.getState().connection.fromHandle,autoPanSpeed:_.autoPanSpeed,dragThreshold:_.connectionDragThreshold})}E?h?.(z):p?.(z)},L=z=>{const{onClickConnectStart:E,onClickConnectEnd:_,connectionClickStartHandle:G,connectionMode:V,isValidConnection:O,lib:q,rfId:J,nodeLookup:H,connection:Z}=C.getState();if(!w||!G&&!a)return;if(!G){E?.(z.nativeEvent,{nodeId:w,handleId:v,handleType:e}),C.setState({connectionClickStartHandle:{nodeId:w,type:e,id:v}});return}const Y=Y7(z.target),ee=r||O,{connection:ae,isValid:Q}=p1.isValid(z.nativeEvent,{handle:{nodeId:w,id:v,type:e},connectionMode:V,fromNodeId:G.nodeId,fromHandleId:G.id||null,fromType:G.type,isValidConnection:ee,flowId:J,doc:Y,lib:q,nodeLookup:H});Q&&ae&&W(ae);const me=structuredClone(Z);delete me.inProgress,me.toPosition=me.toHandle?me.toHandle.position:null,_?.(z,me),C.setState({connectionClickStartHandle:null})};return n.jsx("div",{"data-handleid":v,"data-nodeid":w,"data-handlepos":t,"data-id":`${T}-${w}-${v}-${e}`,className:ks(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",S,m,{source:!j,target:j,connectable:s,connectablestart:a,connectableend:i,clickconnecting:I,connectingfrom:M,connectingto:D,valid:U,connectionindicator:s&&(!B||$)&&(B||R?i:a)}]),onMouseDown:F,onTouchStart:F,onClick:N?L:void 0,ref:g,...y,children:u})}const Cl=x.memo(w8(Zee));function Jee({data:e,isConnectable:t,sourcePosition:r=Zt.Bottom}){return n.jsxs(n.Fragment,{children:[e?.label,n.jsx(Cl,{type:"source",position:r,isConnectable:t})]})}function ete({data:e,isConnectable:t,targetPosition:r=Zt.Top,sourcePosition:s=Zt.Bottom}){return n.jsxs(n.Fragment,{children:[n.jsx(Cl,{type:"target",position:r,isConnectable:t}),e?.label,n.jsx(Cl,{type:"source",position:s,isConnectable:t})]})}function tte(){return null}function nte({data:e,isConnectable:t,targetPosition:r=Zt.Top}){return n.jsxs(n.Fragment,{children:[n.jsx(Cl,{type:"target",position:r,isConnectable:t}),e?.label]})}const kh={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},s3={input:Jee,default:ete,output:nte,group:tte};function rte(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}const ste=e=>{const{width:t,height:r,x:s,y:a}=L0(e.nodeLookup,{filter:i=>!!i.selected});return{width:Si(t)?t:null,height:Si(r)?r:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${s}px,${a}px)`}};function ate({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:r}){const s=Fr(),{width:a,height:i,transformString:l,userSelectionActive:d}=dr(ste,Xr),u=N8(),m=x.useRef(null);x.useEffect(()=>{r||m.current?.focus({preventScroll:!0})},[r]);const h=!d&&a!==null&&i!==null;if(j8({nodeRef:m,disabled:!h}),!h)return null;const p=e?g=>{const v=s.getState().nodes.filter(j=>j.selected);e(g,v)}:void 0,y=g=>{Object.prototype.hasOwnProperty.call(kh,g.key)&&(g.preventDefault(),u({direction:kh[g.key],factor:g.shiftKey?4:1}))};return n.jsx("div",{className:ks(["react-flow__nodesselection","react-flow__container",t]),style:{transform:l},children:n.jsx("div",{ref:m,className:"react-flow__nodesselection-rect",onContextMenu:p,tabIndex:r?void 0:-1,onKeyDown:r?void 0:y,style:{width:a,height:i}})})}const a3=typeof window<"u"?window:void 0,ite=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function C8({children:e,onPaneClick:t,onPaneMouseEnter:r,onPaneMouseMove:s,onPaneMouseLeave:a,onPaneContextMenu:i,onPaneScroll:l,paneClickDistance:d,deleteKeyCode:u,selectionKeyCode:m,selectionOnDrag:h,selectionMode:p,onSelectionStart:y,onSelectionEnd:g,multiSelectionKeyCode:v,panActivationKeyCode:j,zoomActivationKeyCode:C,elementsSelectable:w,zoomOnScroll:N,zoomOnPinch:S,panOnScroll:T,panOnScrollSpeed:M,panOnScrollMode:D,zoomOnDoubleClick:I,panOnDrag:$,defaultViewport:B,translateExtent:R,minZoom:U,maxZoom:W,preventScrolling:F,onSelectionContextMenu:L,noWheelClassName:z,noPanClassName:E,disableKeyboardA11y:_,onViewportChange:G,isControlledViewport:V}){const{nodesSelectionActive:O,userSelectionActive:q}=dr(ite,Xr),J=w0(m,{target:a3}),H=w0(j,{target:a3}),Z=H||$,Y=H||T,ee=h&&Z!==!0,ae=J||q||ee;return Bee({deleteKeyCode:u,multiSelectionKeyCode:v}),n.jsx(qee,{onPaneContextMenu:i,elementsSelectable:w,zoomOnScroll:N,zoomOnPinch:S,panOnScroll:Y,panOnScrollSpeed:M,panOnScrollMode:D,zoomOnDoubleClick:I,panOnDrag:!J&&Z,defaultViewport:B,translateExtent:R,minZoom:U,maxZoom:W,zoomActivationKeyCode:C,preventScrolling:F,noWheelClassName:z,noPanClassName:E,onViewportChange:G,isControlledViewport:V,paneClickDistance:d,selectionOnDrag:ee,children:n.jsxs(Wee,{onSelectionStart:y,onSelectionEnd:g,onPaneClick:t,onPaneMouseEnter:r,onPaneMouseMove:s,onPaneMouseLeave:a,onPaneContextMenu:i,onPaneScroll:l,panOnDrag:Z,isSelecting:!!ae,selectionMode:p,selectionKeyPressed:J,paneClickDistance:d,selectionOnDrag:ee,children:[e,O&&n.jsx(ate,{onSelectionContextMenu:L,noPanClassName:E,disableKeyboardA11y:_})]})})}C8.displayName="FlowRenderer";const ote=x.memo(C8),lte=e=>t=>e?vy(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(r=>r.id):Array.from(t.nodeLookup.keys());function cte(e){return dr(x.useCallback(lte(e),[e]),Xr)}const dte=e=>e.updateNodeInternals;function ute(){const e=dr(dte),[t]=x.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(r=>{const s=new Map;r.forEach(a=>{const i=a.target.getAttribute("data-id");s.set(i,{id:i,nodeElement:a.target,force:!0})}),e(s)}));return x.useEffect(()=>()=>{t?.disconnect()},[t]),t}function mte({node:e,nodeType:t,hasDimensions:r,resizeObserver:s}){const a=Fr(),i=x.useRef(null),l=x.useRef(null),d=x.useRef(e.sourcePosition),u=x.useRef(e.targetPosition),m=x.useRef(t),h=r&&!!e.internals.handleBounds;return x.useEffect(()=>{i.current&&!e.hidden&&(!h||l.current!==i.current)&&(l.current&&s?.unobserve(l.current),s?.observe(i.current),l.current=i.current)},[h,e.hidden]),x.useEffect(()=>()=>{l.current&&(s?.unobserve(l.current),l.current=null)},[]),x.useEffect(()=>{if(i.current){const p=m.current!==t,y=d.current!==e.sourcePosition,g=u.current!==e.targetPosition;(p||y||g)&&(m.current=t,d.current=e.sourcePosition,u.current=e.targetPosition,a.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:i.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),i}function fte({id:e,onClick:t,onMouseEnter:r,onMouseMove:s,onMouseLeave:a,onContextMenu:i,onDoubleClick:l,nodesDraggable:d,elementsSelectable:u,nodesConnectable:m,nodesFocusable:h,resizeObserver:p,noDragClassName:y,noPanClassName:g,disableKeyboardA11y:v,rfId:j,nodeTypes:C,nodeClickDistance:w,onError:N}){const{node:S,internals:T,isParent:M}=dr(Q=>{const me=Q.nodeLookup.get(e),Ae=Q.parentLookup.has(e);return{node:me,internals:me.internals,isParent:Ae}},Xr);let D=S.type||"default",I=C?.[D]||s3[D];I===void 0&&(N?.("003",Gi.error003(D)),D="default",I=C?.default||s3.default);const $=!!(S.draggable||d&&typeof S.draggable>"u"),B=!!(S.selectable||u&&typeof S.selectable>"u"),R=!!(S.connectable||m&&typeof S.connectable>"u"),U=!!(S.focusable||h&&typeof S.focusable>"u"),W=Fr(),F=W7(S),L=mte({node:S,nodeType:D,hasDimensions:F,resizeObserver:p}),z=j8({nodeRef:L,disabled:S.hidden||!$,noDragClassName:y,handleSelector:S.dragHandle,nodeId:e,isSelectable:B,nodeClickDistance:w}),E=N8();if(S.hidden)return null;const _=zo(S),G=rte(S),V=B||$||t||r||s||a,O=r?Q=>r(Q,{...T.userNode}):void 0,q=s?Q=>s(Q,{...T.userNode}):void 0,J=a?Q=>a(Q,{...T.userNode}):void 0,H=i?Q=>i(Q,{...T.userNode}):void 0,Z=l?Q=>l(Q,{...T.userNode}):void 0,Y=Q=>{const{selectNodesOnDrag:me,nodeDragThreshold:Ae}=W.getState();B&&(!me||!$||Ae>0)&&g1({id:e,store:W,nodeRef:L}),t&&t(Q,{...T.userNode})},ee=Q=>{if(!(X7(Q.nativeEvent)||v)){if(z7.includes(Q.key)&&B){const me=Q.key==="Escape";g1({id:e,store:W,unselect:me,nodeRef:L})}else if($&&S.selected&&Object.prototype.hasOwnProperty.call(kh,Q.key)){Q.preventDefault();const{ariaLabelConfig:me}=W.getState();W.setState({ariaLiveMessage:me["node.a11yDescription.ariaLiveMessage"]({direction:Q.key.replace("Arrow","").toLowerCase(),x:~~T.positionAbsolute.x,y:~~T.positionAbsolute.y})}),E({direction:kh[Q.key],factor:Q.shiftKey?4:1})}}},ae=()=>{if(v||!L.current?.matches(":focus-visible"))return;const{transform:Q,width:me,height:Ae,autoPanOnNodeFocus:Me,setCenter:He}=W.getState();if(!Me)return;vy(new Map([[e,S]]),{x:0,y:0,width:me,height:Ae},Q,!0).length>0||He(S.position.x+_.width/2,S.position.y+_.height/2,{zoom:Q[2]})};return n.jsx("div",{className:ks(["react-flow__node",`react-flow__node-${D}`,{[g]:$},S.className,{selected:S.selected,selectable:B,parent:M,draggable:$,dragging:z}]),ref:L,style:{zIndex:T.z,transform:`translate(${T.positionAbsolute.x}px,${T.positionAbsolute.y}px)`,pointerEvents:V?"all":"none",visibility:F?"visible":"hidden",...S.style,...G},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:O,onMouseMove:q,onMouseLeave:J,onContextMenu:H,onClick:Y,onDoubleClick:Z,onKeyDown:U?ee:void 0,tabIndex:U?0:void 0,onFocus:U?ae:void 0,role:S.ariaRole??(U?"group":void 0),"aria-roledescription":"node","aria-describedby":v?void 0:`${p8}-${j}`,"aria-label":S.ariaLabel,...S.domAttributes,children:n.jsx(Yee,{value:e,children:n.jsx(I,{id:e,data:S.data,type:D,positionAbsoluteX:T.positionAbsolute.x,positionAbsoluteY:T.positionAbsolute.y,selected:S.selected??!1,selectable:B,draggable:$,deletable:S.deletable??!0,isConnectable:R,sourcePosition:S.sourcePosition,targetPosition:S.targetPosition,dragging:z,dragHandle:S.dragHandle,zIndex:T.z,parentId:S.parentId,..._})})})}var hte=x.memo(fte);const pte=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function T8(e){const{nodesDraggable:t,nodesConnectable:r,nodesFocusable:s,elementsSelectable:a,onError:i}=dr(pte,Xr),l=cte(e.onlyRenderVisibleElements),d=ute();return n.jsx("div",{className:"react-flow__nodes",style:np,children:l.map(u=>n.jsx(hte,{id:u,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:d,nodesDraggable:t,nodesConnectable:r,nodesFocusable:s,elementsSelectable:a,nodeClickDistance:e.nodeClickDistance,onError:i},u))})}T8.displayName="NodeRenderer";const gte=x.memo(T8);function xte(e){return dr(x.useCallback(r=>{if(!e)return r.edges.map(a=>a.id);const s=[];if(r.width&&r.height)for(const a of r.edges){const i=r.nodeLookup.get(a.source),l=r.nodeLookup.get(a.target);i&&l&&xJ({sourceNode:i,targetNode:l,width:r.width,height:r.height,transform:r.transform})&&s.push(a.id)}return s},[e]),Xr)}const bte=({color:e="none",strokeWidth:t=1})=>{const r={strokeWidth:t,...e&&{stroke:e}};return n.jsx("polyline",{className:"arrow",style:r,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},yte=({color:e="none",strokeWidth:t=1})=>{const r={strokeWidth:t,...e&&{stroke:e,fill:e}};return n.jsx("polyline",{className:"arrowclosed",style:r,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},i3={[Cd.Arrow]:bte,[Cd.ArrowClosed]:yte};function vte(e){const t=Fr();return x.useMemo(()=>Object.prototype.hasOwnProperty.call(i3,e)?i3[e]:(t.getState().onError?.("009",Gi.error009(e)),null),[e])}const wte=({id:e,type:t,color:r,width:s=12.5,height:a=12.5,markerUnits:i="strokeWidth",strokeWidth:l,orient:d="auto-start-reverse"})=>{const u=vte(t);return u?n.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${s}`,markerHeight:`${a}`,viewBox:"-10 -10 20 20",markerUnits:i,orient:d,refX:"0",refY:"0",children:n.jsx(u,{color:r,strokeWidth:l})}):null},A8=({defaultColor:e,rfId:t})=>{const r=dr(i=>i.edges),s=dr(i=>i.defaultEdgeOptions),a=x.useMemo(()=>SJ(r,{id:t,defaultColor:e,defaultMarkerStart:s?.markerStart,defaultMarkerEnd:s?.markerEnd}),[r,s,t,e]);return a.length?n.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:n.jsx("defs",{children:a.map(i=>n.jsx(wte,{id:i.id,type:i.type,color:i.color,width:i.width,height:i.height,markerUnits:i.markerUnits,strokeWidth:i.strokeWidth,orient:i.orient},i.id))})}):null};A8.displayName="MarkerDefinitions";var kte=x.memo(A8);function E8({x:e,y:t,label:r,labelStyle:s,labelShowBg:a=!0,labelBgStyle:i,labelBgPadding:l=[2,4],labelBgBorderRadius:d=2,children:u,className:m,...h}){const[p,y]=x.useState({x:1,y:0,width:0,height:0}),g=ks(["react-flow__edge-textwrapper",m]),v=x.useRef(null);return x.useEffect(()=>{if(v.current){const j=v.current.getBBox();y({x:j.x,y:j.y,width:j.width,height:j.height})}},[r]),r?n.jsxs("g",{transform:`translate(${e-p.width/2} ${t-p.height/2})`,className:g,visibility:p.width?"visible":"hidden",...h,children:[a&&n.jsx("rect",{width:p.width+2*l[0],x:-l[0],y:-l[1],height:p.height+2*l[1],className:"react-flow__edge-textbg",style:i,rx:d,ry:d}),n.jsx("text",{className:"react-flow__edge-text",y:p.height/2,dy:"0.3em",ref:v,style:s,children:r}),u]}):null}E8.displayName="EdgeText";const jte=x.memo(E8);function rp({path:e,labelX:t,labelY:r,label:s,labelStyle:a,labelShowBg:i,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:u,interactionWidth:m=20,...h}){return n.jsxs(n.Fragment,{children:[n.jsx("path",{...h,d:e,fill:"none",className:ks(["react-flow__edge-path",h.className])}),m?n.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:m,className:"react-flow__edge-interaction"}):null,s&&Si(t)&&Si(r)?n.jsx(jte,{x:t,y:r,label:s,labelStyle:a,labelShowBg:i,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:u}):null]})}function o3({pos:e,x1:t,y1:r,x2:s,y2:a}){return e===Zt.Left||e===Zt.Right?[.5*(t+s),r]:[t,.5*(r+a)]}function M8({sourceX:e,sourceY:t,sourcePosition:r=Zt.Bottom,targetX:s,targetY:a,targetPosition:i=Zt.Top}){const[l,d]=o3({pos:r,x1:e,y1:t,x2:s,y2:a}),[u,m]=o3({pos:i,x1:s,y1:a,x2:e,y2:t}),[h,p,y,g]=Z7({sourceX:e,sourceY:t,targetX:s,targetY:a,sourceControlX:l,sourceControlY:d,targetControlX:u,targetControlY:m});return[`M${e},${t} C${l},${d} ${u},${m} ${s},${a}`,h,p,y,g]}function D8(e){return x.memo(({id:t,sourceX:r,sourceY:s,targetX:a,targetY:i,sourcePosition:l,targetPosition:d,label:u,labelStyle:m,labelShowBg:h,labelBgStyle:p,labelBgPadding:y,labelBgBorderRadius:g,style:v,markerEnd:j,markerStart:C,interactionWidth:w})=>{const[N,S,T]=M8({sourceX:r,sourceY:s,sourcePosition:l,targetX:a,targetY:i,targetPosition:d}),M=e.isInternal?void 0:t;return n.jsx(rp,{id:M,path:N,labelX:S,labelY:T,label:u,labelStyle:m,labelShowBg:h,labelBgStyle:p,labelBgPadding:y,labelBgBorderRadius:g,style:v,markerEnd:j,markerStart:C,interactionWidth:w})})}const Nte=D8({isInternal:!1}),R8=D8({isInternal:!0});Nte.displayName="SimpleBezierEdge";R8.displayName="SimpleBezierEdgeInternal";function I8(e){return x.memo(({id:t,sourceX:r,sourceY:s,targetX:a,targetY:i,label:l,labelStyle:d,labelShowBg:u,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,sourcePosition:g=Zt.Bottom,targetPosition:v=Zt.Top,markerEnd:j,markerStart:C,pathOptions:w,interactionWidth:N})=>{const[S,T,M]=m1({sourceX:r,sourceY:s,sourcePosition:g,targetX:a,targetY:i,targetPosition:v,borderRadius:w?.borderRadius,offset:w?.offset,stepPosition:w?.stepPosition}),D=e.isInternal?void 0:t;return n.jsx(rp,{id:D,path:S,labelX:T,labelY:M,label:l,labelStyle:d,labelShowBg:u,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:j,markerStart:C,interactionWidth:N})})}const L8=I8({isInternal:!1}),P8=I8({isInternal:!0});L8.displayName="SmoothStepEdge";P8.displayName="SmoothStepEdgeInternal";function O8(e){return x.memo(({id:t,...r})=>{const s=e.isInternal?void 0:t;return n.jsx(L8,{...r,id:s,pathOptions:x.useMemo(()=>({borderRadius:0,offset:r.pathOptions?.offset}),[r.pathOptions?.offset])})})}const Ste=O8({isInternal:!1}),_8=O8({isInternal:!0});Ste.displayName="StepEdge";_8.displayName="StepEdgeInternal";function z8(e){return x.memo(({id:t,sourceX:r,sourceY:s,targetX:a,targetY:i,label:l,labelStyle:d,labelShowBg:u,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:g,markerStart:v,interactionWidth:j})=>{const[C,w,N]=t8({sourceX:r,sourceY:s,targetX:a,targetY:i}),S=e.isInternal?void 0:t;return n.jsx(rp,{id:S,path:C,labelX:w,labelY:N,label:l,labelStyle:d,labelShowBg:u,labelBgStyle:m,labelBgPadding:h,labelBgBorderRadius:p,style:y,markerEnd:g,markerStart:v,interactionWidth:j})})}const Cte=z8({isInternal:!1}),$8=z8({isInternal:!0});Cte.displayName="StraightEdge";$8.displayName="StraightEdgeInternal";function B8(e){return x.memo(({id:t,sourceX:r,sourceY:s,targetX:a,targetY:i,sourcePosition:l=Zt.Bottom,targetPosition:d=Zt.Top,label:u,labelStyle:m,labelShowBg:h,labelBgStyle:p,labelBgPadding:y,labelBgBorderRadius:g,style:v,markerEnd:j,markerStart:C,pathOptions:w,interactionWidth:N})=>{const[S,T,M]=J7({sourceX:r,sourceY:s,sourcePosition:l,targetX:a,targetY:i,targetPosition:d,curvature:w?.curvature}),D=e.isInternal?void 0:t;return n.jsx(rp,{id:D,path:S,labelX:T,labelY:M,label:u,labelStyle:m,labelShowBg:h,labelBgStyle:p,labelBgPadding:y,labelBgBorderRadius:g,style:v,markerEnd:j,markerStart:C,interactionWidth:N})})}const Tte=B8({isInternal:!1}),H8=B8({isInternal:!0});Tte.displayName="BezierEdge";H8.displayName="BezierEdgeInternal";const l3={default:H8,straight:$8,step:_8,smoothstep:P8,simplebezier:R8},c3={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},Ate=(e,t,r)=>r===Zt.Left?e-t:r===Zt.Right?e+t:e,Ete=(e,t,r)=>r===Zt.Top?e-t:r===Zt.Bottom?e+t:e,d3="react-flow__edgeupdater";function u3({position:e,centerX:t,centerY:r,radius:s=10,onMouseDown:a,onMouseEnter:i,onMouseOut:l,type:d}){return n.jsx("circle",{onMouseDown:a,onMouseEnter:i,onMouseOut:l,className:ks([d3,`${d3}-${d}`]),cx:Ate(t,s,e),cy:Ete(r,s,e),r:s,stroke:"transparent",fill:"transparent"})}function Mte({isReconnectable:e,reconnectRadius:t,edge:r,sourceX:s,sourceY:a,targetX:i,targetY:l,sourcePosition:d,targetPosition:u,onReconnect:m,onReconnectStart:h,onReconnectEnd:p,setReconnecting:y,setUpdateHover:g}){const v=Fr(),j=(T,M)=>{if(T.button!==0)return;const{autoPanOnConnect:D,domNode:I,connectionMode:$,connectionRadius:B,lib:R,onConnectStart:U,cancelConnection:W,nodeLookup:F,rfId:L,panBy:z,updateConnection:E}=v.getState(),_=M.type==="target",G=(q,J)=>{y(!1),p?.(q,r,M.type,J)},V=q=>m?.(r,q),O=(q,J)=>{y(!0),h?.(T,r,M.type),U?.(q,J)};p1.onPointerDown(T.nativeEvent,{autoPanOnConnect:D,connectionMode:$,connectionRadius:B,domNode:I,handleId:M.id,nodeId:M.nodeId,nodeLookup:F,isTarget:_,edgeUpdaterType:M.type,lib:R,flowId:L,cancelConnection:W,panBy:z,isValidConnection:(...q)=>v.getState().isValidConnection?.(...q)??!0,onConnect:V,onConnectStart:O,onConnectEnd:(...q)=>v.getState().onConnectEnd?.(...q),onReconnectEnd:G,updateConnection:E,getTransform:()=>v.getState().transform,getFromHandle:()=>v.getState().connection.fromHandle,dragThreshold:v.getState().connectionDragThreshold,handleDomNode:T.currentTarget})},C=T=>j(T,{nodeId:r.target,id:r.targetHandle??null,type:"target"}),w=T=>j(T,{nodeId:r.source,id:r.sourceHandle??null,type:"source"}),N=()=>g(!0),S=()=>g(!1);return n.jsxs(n.Fragment,{children:[(e===!0||e==="source")&&n.jsx(u3,{position:d,centerX:s,centerY:a,radius:t,onMouseDown:C,onMouseEnter:N,onMouseOut:S,type:"source"}),(e===!0||e==="target")&&n.jsx(u3,{position:u,centerX:i,centerY:l,radius:t,onMouseDown:w,onMouseEnter:N,onMouseOut:S,type:"target"})]})}function Dte({id:e,edgesFocusable:t,edgesReconnectable:r,elementsSelectable:s,onClick:a,onDoubleClick:i,onContextMenu:l,onMouseEnter:d,onMouseMove:u,onMouseLeave:m,reconnectRadius:h,onReconnect:p,onReconnectStart:y,onReconnectEnd:g,rfId:v,edgeTypes:j,noPanClassName:C,onError:w,disableKeyboardA11y:N}){let S=dr(He=>He.edgeLookup.get(e));const T=dr(He=>He.defaultEdgeOptions);S=T?{...T,...S}:S;let M=S.type||"default",D=j?.[M]||l3[M];D===void 0&&(w?.("011",Gi.error011(M)),M="default",D=j?.default||l3.default);const I=!!(S.focusable||t&&typeof S.focusable>"u"),$=typeof p<"u"&&(S.reconnectable||r&&typeof S.reconnectable>"u"),B=!!(S.selectable||s&&typeof S.selectable>"u"),R=x.useRef(null),[U,W]=x.useState(!1),[F,L]=x.useState(!1),z=Fr(),{zIndex:E,sourceX:_,sourceY:G,targetX:V,targetY:O,sourcePosition:q,targetPosition:J}=dr(x.useCallback(He=>{const je=He.nodeLookup.get(S.source),xe=He.nodeLookup.get(S.target);if(!je||!xe)return{zIndex:S.zIndex,...c3};const Pe=NJ({id:e,sourceNode:je,targetNode:xe,sourceHandle:S.sourceHandle||null,targetHandle:S.targetHandle||null,connectionMode:He.connectionMode,onError:w});return{zIndex:gJ({selected:S.selected,zIndex:S.zIndex,sourceNode:je,targetNode:xe,elevateOnSelect:He.elevateEdgesOnSelect,zIndexMode:He.zIndexMode}),...Pe||c3}},[S.source,S.target,S.sourceHandle,S.targetHandle,S.selected,S.zIndex]),Xr),H=x.useMemo(()=>S.markerStart?`url('#${f1(S.markerStart,v)}')`:void 0,[S.markerStart,v]),Z=x.useMemo(()=>S.markerEnd?`url('#${f1(S.markerEnd,v)}')`:void 0,[S.markerEnd,v]);if(S.hidden||_===null||G===null||V===null||O===null)return null;const Y=He=>{const{addSelectedEdges:je,unselectNodesAndEdges:xe,multiSelectionActive:Pe}=z.getState();B&&(z.setState({nodesSelectionActive:!1}),S.selected&&Pe?(xe({nodes:[],edges:[S]}),R.current?.blur()):je([e])),a&&a(He,S)},ee=i?He=>{i(He,{...S})}:void 0,ae=l?He=>{l(He,{...S})}:void 0,Q=d?He=>{d(He,{...S})}:void 0,me=u?He=>{u(He,{...S})}:void 0,Ae=m?He=>{m(He,{...S})}:void 0,Me=He=>{if(!N&&z7.includes(He.key)&&B){const{unselectNodesAndEdges:je,addSelectedEdges:xe}=z.getState();He.key==="Escape"?(R.current?.blur(),je({edges:[S]})):xe([e])}};return n.jsx("svg",{style:{zIndex:E},children:n.jsxs("g",{className:ks(["react-flow__edge",`react-flow__edge-${M}`,S.className,C,{selected:S.selected,animated:S.animated,inactive:!B&&!a,updating:U,selectable:B}]),onClick:Y,onDoubleClick:ee,onContextMenu:ae,onMouseEnter:Q,onMouseMove:me,onMouseLeave:Ae,onKeyDown:I?Me:void 0,tabIndex:I?0:void 0,role:S.ariaRole??(I?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":S.ariaLabel===null?void 0:S.ariaLabel||`Edge from ${S.source} to ${S.target}`,"aria-describedby":I?`${g8}-${v}`:void 0,ref:R,...S.domAttributes,children:[!F&&n.jsx(D,{id:e,source:S.source,target:S.target,type:S.type,selected:S.selected,animated:S.animated,selectable:B,deletable:S.deletable??!0,label:S.label,labelStyle:S.labelStyle,labelShowBg:S.labelShowBg,labelBgStyle:S.labelBgStyle,labelBgPadding:S.labelBgPadding,labelBgBorderRadius:S.labelBgBorderRadius,sourceX:_,sourceY:G,targetX:V,targetY:O,sourcePosition:q,targetPosition:J,data:S.data,style:S.style,sourceHandleId:S.sourceHandle,targetHandleId:S.targetHandle,markerStart:H,markerEnd:Z,pathOptions:"pathOptions"in S?S.pathOptions:void 0,interactionWidth:S.interactionWidth}),$&&n.jsx(Mte,{edge:S,isReconnectable:$,reconnectRadius:h,onReconnect:p,onReconnectStart:y,onReconnectEnd:g,sourceX:_,sourceY:G,targetX:V,targetY:O,sourcePosition:q,targetPosition:J,setUpdateHover:W,setReconnecting:L})]})})}var Rte=x.memo(Dte);const Ite=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function F8({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:r,edgeTypes:s,noPanClassName:a,onReconnect:i,onEdgeContextMenu:l,onEdgeMouseEnter:d,onEdgeMouseMove:u,onEdgeMouseLeave:m,onEdgeClick:h,reconnectRadius:p,onEdgeDoubleClick:y,onReconnectStart:g,onReconnectEnd:v,disableKeyboardA11y:j}){const{edgesFocusable:C,edgesReconnectable:w,elementsSelectable:N,onError:S}=dr(Ite,Xr),T=xte(t);return n.jsxs("div",{className:"react-flow__edges",children:[n.jsx(kte,{defaultColor:e,rfId:r}),T.map(M=>n.jsx(Rte,{id:M,edgesFocusable:C,edgesReconnectable:w,elementsSelectable:N,noPanClassName:a,onReconnect:i,onContextMenu:l,onMouseEnter:d,onMouseMove:u,onMouseLeave:m,onClick:h,reconnectRadius:p,onDoubleClick:y,onReconnectStart:g,onReconnectEnd:v,rfId:r,onError:S,edgeTypes:s,disableKeyboardA11y:j},M))]})}F8.displayName="EdgeRenderer";const Lte=x.memo(F8),Pte=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Ote({children:e}){const t=dr(Pte);return n.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function _te(e){const t=Ay(),r=x.useRef(!1);x.useEffect(()=>{!r.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),r.current=!0)},[e,t.viewportInitialized])}const zte=e=>e.panZoom?.syncViewport;function $te(e){const t=dr(zte),r=Fr();return x.useEffect(()=>{e&&(t?.(e),r.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Bte(e){return e.connection.inProgress?{...e.connection,to:O0(e.connection.to,e.transform)}:{...e.connection}}function Hte(e){return Bte}function Fte(e){const t=Hte();return dr(t,Xr)}const qte=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Ute({containerStyle:e,style:t,type:r,component:s}){const{nodesConnectable:a,width:i,height:l,isValid:d,inProgress:u}=dr(qte,Xr);return!(i&&a&&u)?null:n.jsx("svg",{style:e,width:i,height:l,className:"react-flow__connectionline react-flow__container",children:n.jsx("g",{className:ks(["react-flow__connection",H7(d)]),children:n.jsx(q8,{style:t,type:r,CustomComponent:s,isValid:d})})})}const q8=({style:e,type:t=xl.Bezier,CustomComponent:r,isValid:s})=>{const{inProgress:a,from:i,fromNode:l,fromHandle:d,fromPosition:u,to:m,toNode:h,toHandle:p,toPosition:y,pointer:g}=Fte();if(!a)return;if(r)return n.jsx(r,{connectionLineType:t,connectionLineStyle:e,fromNode:l,fromHandle:d,fromX:i.x,fromY:i.y,toX:m.x,toY:m.y,fromPosition:u,toPosition:y,connectionStatus:H7(s),toNode:h,toHandle:p,pointer:g});let v="";const j={sourceX:i.x,sourceY:i.y,sourcePosition:u,targetX:m.x,targetY:m.y,targetPosition:y};switch(t){case xl.Bezier:[v]=J7(j);break;case xl.SimpleBezier:[v]=M8(j);break;case xl.Step:[v]=m1({...j,borderRadius:0});break;case xl.SmoothStep:[v]=m1(j);break;default:[v]=t8(j)}return n.jsx("path",{d:v,fill:"none",className:"react-flow__connection-path",style:e})};q8.displayName="ConnectionLine";const Vte={};function m3(e=Vte){x.useRef(e),Fr(),x.useEffect(()=>{},[e])}function Kte(){Fr(),x.useRef(!1),x.useEffect(()=>{},[])}function U8({nodeTypes:e,edgeTypes:t,onInit:r,onNodeClick:s,onEdgeClick:a,onNodeDoubleClick:i,onEdgeDoubleClick:l,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:m,onNodeContextMenu:h,onSelectionContextMenu:p,onSelectionStart:y,onSelectionEnd:g,connectionLineType:v,connectionLineStyle:j,connectionLineComponent:C,connectionLineContainerStyle:w,selectionKeyCode:N,selectionOnDrag:S,selectionMode:T,multiSelectionKeyCode:M,panActivationKeyCode:D,zoomActivationKeyCode:I,deleteKeyCode:$,onlyRenderVisibleElements:B,elementsSelectable:R,defaultViewport:U,translateExtent:W,minZoom:F,maxZoom:L,preventScrolling:z,defaultMarkerColor:E,zoomOnScroll:_,zoomOnPinch:G,panOnScroll:V,panOnScrollSpeed:O,panOnScrollMode:q,zoomOnDoubleClick:J,panOnDrag:H,onPaneClick:Z,onPaneMouseEnter:Y,onPaneMouseMove:ee,onPaneMouseLeave:ae,onPaneScroll:Q,onPaneContextMenu:me,paneClickDistance:Ae,nodeClickDistance:Me,onEdgeContextMenu:He,onEdgeMouseEnter:je,onEdgeMouseMove:xe,onEdgeMouseLeave:Pe,reconnectRadius:Ce,onReconnect:Ye,onReconnectStart:Qe,onReconnectEnd:ct,noDragClassName:st,noWheelClassName:zt,noPanClassName:mt,disableKeyboardA11y:te,nodeExtent:de,rfId:be,viewport:se,onViewportChange:fe}){return m3(e),m3(t),Kte(),_te(r),$te(se),n.jsx(ote,{onPaneClick:Z,onPaneMouseEnter:Y,onPaneMouseMove:ee,onPaneMouseLeave:ae,onPaneContextMenu:me,onPaneScroll:Q,paneClickDistance:Ae,deleteKeyCode:$,selectionKeyCode:N,selectionOnDrag:S,selectionMode:T,onSelectionStart:y,onSelectionEnd:g,multiSelectionKeyCode:M,panActivationKeyCode:D,zoomActivationKeyCode:I,elementsSelectable:R,zoomOnScroll:_,zoomOnPinch:G,zoomOnDoubleClick:J,panOnScroll:V,panOnScrollSpeed:O,panOnScrollMode:q,panOnDrag:H,defaultViewport:U,translateExtent:W,minZoom:F,maxZoom:L,onSelectionContextMenu:p,preventScrolling:z,noDragClassName:st,noWheelClassName:zt,noPanClassName:mt,disableKeyboardA11y:te,onViewportChange:fe,isControlledViewport:!!se,children:n.jsxs(Ote,{children:[n.jsx(Lte,{edgeTypes:t,onEdgeClick:a,onEdgeDoubleClick:l,onReconnect:Ye,onReconnectStart:Qe,onReconnectEnd:ct,onlyRenderVisibleElements:B,onEdgeContextMenu:He,onEdgeMouseEnter:je,onEdgeMouseMove:xe,onEdgeMouseLeave:Pe,reconnectRadius:Ce,defaultMarkerColor:E,noPanClassName:mt,disableKeyboardA11y:te,rfId:be}),n.jsx(Ute,{style:j,type:v,component:C,containerStyle:w}),n.jsx("div",{className:"react-flow__edgelabel-renderer"}),n.jsx(gte,{nodeTypes:e,onNodeClick:s,onNodeDoubleClick:i,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:m,onNodeContextMenu:h,nodeClickDistance:Me,onlyRenderVisibleElements:B,noPanClassName:mt,noDragClassName:st,disableKeyboardA11y:te,nodeExtent:de,rfId:be}),n.jsx("div",{className:"react-flow__viewport-portal"})]})})}U8.displayName="GraphView";const Wte=x.memo(U8),f3=({nodes:e,edges:t,defaultNodes:r,defaultEdges:s,width:a,height:i,fitView:l,fitViewOptions:d,minZoom:u=.5,maxZoom:m=2,nodeOrigin:h,nodeExtent:p,zIndexMode:y="basic"}={})=>{const g=new Map,v=new Map,j=new Map,C=new Map,w=s??t??[],N=r??e??[],S=h??[0,0],T=p??x0;s8(j,C,w);const M=h1(N,g,v,{nodeOrigin:S,nodeExtent:T,zIndexMode:y});let D=[0,0,1];if(l&&a&&i){const I=L0(g,{filter:U=>!!((U.width||U.initialWidth)&&(U.height||U.initialHeight))}),{x:$,y:B,zoom:R}=wy(I,a,i,u,m,d?.padding??.1);D=[$,B,R]}return{rfId:"1",width:a??0,height:i??0,transform:D,nodes:N,nodesInitialized:M,nodeLookup:g,parentLookup:v,edges:w,edgeLookup:C,connectionLookup:j,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:r!==void 0,hasDefaultEdges:s!==void 0,panZoom:null,minZoom:u,maxZoom:m,translateExtent:x0,nodeExtent:T,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Sd.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:S,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:l??!1,fitViewOptions:d,fitViewResolver:null,connection:{...B7},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:dJ,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:$7,zIndexMode:y,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},Gte=({nodes:e,edges:t,defaultNodes:r,defaultEdges:s,width:a,height:i,fitView:l,fitViewOptions:d,minZoom:u,maxZoom:m,nodeOrigin:h,nodeExtent:p,zIndexMode:y})=>mee((g,v)=>{async function j(){const{nodeLookup:C,panZoom:w,fitViewOptions:N,fitViewResolver:S,width:T,height:M,minZoom:D,maxZoom:I}=v();w&&(await lJ({nodes:C,width:T,height:M,panZoom:w,minZoom:D,maxZoom:I},N),S?.resolve(!0),g({fitViewResolver:null}))}return{...f3({nodes:e,edges:t,width:a,height:i,fitView:l,fitViewOptions:d,minZoom:u,maxZoom:m,nodeOrigin:h,nodeExtent:p,defaultNodes:r,defaultEdges:s,zIndexMode:y}),setNodes:C=>{const{nodeLookup:w,parentLookup:N,nodeOrigin:S,elevateNodesOnSelect:T,fitViewQueued:M,zIndexMode:D}=v(),I=h1(C,w,N,{nodeOrigin:S,nodeExtent:p,elevateNodesOnSelect:T,checkEquality:!0,zIndexMode:D});M&&I?(j(),g({nodes:C,nodesInitialized:I,fitViewQueued:!1,fitViewOptions:void 0})):g({nodes:C,nodesInitialized:I})},setEdges:C=>{const{connectionLookup:w,edgeLookup:N}=v();s8(w,N,C),g({edges:C})},setDefaultNodesAndEdges:(C,w)=>{if(C){const{setNodes:N}=v();N(C),g({hasDefaultNodes:!0})}if(w){const{setEdges:N}=v();N(w),g({hasDefaultEdges:!0})}},updateNodeInternals:C=>{const{triggerNodeChanges:w,nodeLookup:N,parentLookup:S,domNode:T,nodeOrigin:M,nodeExtent:D,debug:I,fitViewQueued:$,zIndexMode:B}=v(),{changes:R,updatedInternals:U}=RJ(C,N,S,T,M,D,B);U&&(AJ(N,S,{nodeOrigin:M,nodeExtent:D,zIndexMode:B}),$?(j(),g({fitViewQueued:!1,fitViewOptions:void 0})):g({}),R?.length>0&&(I&&console.log("React Flow: trigger node changes",R),w?.(R)))},updateNodePositions:(C,w=!1)=>{const N=[];let S=[];const{nodeLookup:T,triggerNodeChanges:M,connection:D,updateConnection:I,onNodesChangeMiddlewareMap:$}=v();for(const[B,R]of C){const U=T.get(B),W=!!(U?.expandParent&&U?.parentId&&R?.position),F={id:B,type:"position",position:W?{x:Math.max(0,R.position.x),y:Math.max(0,R.position.y)}:R.position,dragging:w};if(U&&D.inProgress&&D.fromNode.id===U.id){const L=pc(U,D.fromHandle,Zt.Left,!0);I({...D,from:L})}W&&U.parentId&&N.push({id:B,parentId:U.parentId,rect:{...R.internals.positionAbsolute,width:R.measured.width??0,height:R.measured.height??0}}),S.push(F)}if(N.length>0){const{parentLookup:B,nodeOrigin:R}=v(),U=Ty(N,T,B,R);S.push(...U)}for(const B of $.values())S=B(S);M(S)},triggerNodeChanges:C=>{const{onNodesChange:w,setNodes:N,nodes:S,hasDefaultNodes:T,debug:M}=v();if(C?.length){if(T){const D=y8(C,S);N(D)}M&&console.log("React Flow: trigger node changes",C),w?.(C)}},triggerEdgeChanges:C=>{const{onEdgesChange:w,setEdges:N,edges:S,hasDefaultEdges:T,debug:M}=v();if(C?.length){if(T){const D=v8(C,S);N(D)}M&&console.log("React Flow: trigger edge changes",C),w?.(C)}},addSelectedNodes:C=>{const{multiSelectionActive:w,edgeLookup:N,nodeLookup:S,triggerNodeChanges:T,triggerEdgeChanges:M}=v();if(w){const D=C.map(I=>Jl(I,!0));T(D);return}T(md(S,new Set([...C]),!0)),M(md(N))},addSelectedEdges:C=>{const{multiSelectionActive:w,edgeLookup:N,nodeLookup:S,triggerNodeChanges:T,triggerEdgeChanges:M}=v();if(w){const D=C.map(I=>Jl(I,!0));M(D);return}M(md(N,new Set([...C]))),T(md(S,new Set,!0))},unselectNodesAndEdges:({nodes:C,edges:w}={})=>{const{edges:N,nodes:S,nodeLookup:T,triggerNodeChanges:M,triggerEdgeChanges:D}=v(),I=C||S,$=w||N,B=[];for(const U of I){if(!U.selected)continue;const W=T.get(U.id);W&&(W.selected=!1),B.push(Jl(U.id,!1))}const R=[];for(const U of $)U.selected&&R.push(Jl(U.id,!1));M(B),D(R)},setMinZoom:C=>{const{panZoom:w,maxZoom:N}=v();w?.setScaleExtent([C,N]),g({minZoom:C})},setMaxZoom:C=>{const{panZoom:w,minZoom:N}=v();w?.setScaleExtent([N,C]),g({maxZoom:C})},setTranslateExtent:C=>{v().panZoom?.setTranslateExtent(C),g({translateExtent:C})},resetSelectedElements:()=>{const{edges:C,nodes:w,triggerNodeChanges:N,triggerEdgeChanges:S,elementsSelectable:T}=v();if(!T)return;const M=w.reduce((I,$)=>$.selected?[...I,Jl($.id,!1)]:I,[]),D=C.reduce((I,$)=>$.selected?[...I,Jl($.id,!1)]:I,[]);N(M),S(D)},setNodeExtent:C=>{const{nodes:w,nodeLookup:N,parentLookup:S,nodeOrigin:T,elevateNodesOnSelect:M,nodeExtent:D,zIndexMode:I}=v();C[0][0]===D[0][0]&&C[0][1]===D[0][1]&&C[1][0]===D[1][0]&&C[1][1]===D[1][1]||(h1(w,N,S,{nodeOrigin:T,nodeExtent:C,elevateNodesOnSelect:M,checkEquality:!1,zIndexMode:I}),g({nodeExtent:C}))},panBy:C=>{const{transform:w,width:N,height:S,panZoom:T,translateExtent:M}=v();return IJ({delta:C,panZoom:T,transform:w,translateExtent:M,width:N,height:S})},setCenter:async(C,w,N)=>{const{width:S,height:T,maxZoom:M,panZoom:D}=v();if(!D)return Promise.resolve(!1);const I=typeof N?.zoom<"u"?N.zoom:M;return await D.setViewport({x:S/2-C*I,y:T/2-w*I,zoom:I},{duration:N?.duration,ease:N?.ease,interpolate:N?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{g({connection:{...B7}})},updateConnection:C=>{g({connection:C})},reset:()=>g({...f3()})}},Object.is);function Yte({initialNodes:e,initialEdges:t,defaultNodes:r,defaultEdges:s,initialWidth:a,initialHeight:i,initialMinZoom:l,initialMaxZoom:d,initialFitViewOptions:u,fitView:m,nodeOrigin:h,nodeExtent:p,zIndexMode:y,children:g}){const[v]=x.useState(()=>Gte({nodes:e,edges:t,defaultNodes:r,defaultEdges:s,width:a,height:i,fitView:m,minZoom:l,maxZoom:d,fitViewOptions:u,nodeOrigin:h,nodeExtent:p,zIndexMode:y}));return n.jsx(fee,{value:v,children:n.jsx(Oee,{children:g})})}function Xte({children:e,nodes:t,edges:r,defaultNodes:s,defaultEdges:a,width:i,height:l,fitView:d,fitViewOptions:u,minZoom:m,maxZoom:h,nodeOrigin:p,nodeExtent:y,zIndexMode:g}){return x.useContext(ep)?n.jsx(n.Fragment,{children:e}):n.jsx(Yte,{initialNodes:t,initialEdges:r,defaultNodes:s,defaultEdges:a,initialWidth:i,initialHeight:l,fitView:d,initialFitViewOptions:u,initialMinZoom:m,initialMaxZoom:h,nodeOrigin:p,nodeExtent:y,zIndexMode:g,children:e})}const Qte={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function Zte({nodes:e,edges:t,defaultNodes:r,defaultEdges:s,className:a,nodeTypes:i,edgeTypes:l,onNodeClick:d,onEdgeClick:u,onInit:m,onMove:h,onMoveStart:p,onMoveEnd:y,onConnect:g,onConnectStart:v,onConnectEnd:j,onClickConnectStart:C,onClickConnectEnd:w,onNodeMouseEnter:N,onNodeMouseMove:S,onNodeMouseLeave:T,onNodeContextMenu:M,onNodeDoubleClick:D,onNodeDragStart:I,onNodeDrag:$,onNodeDragStop:B,onNodesDelete:R,onEdgesDelete:U,onDelete:W,onSelectionChange:F,onSelectionDragStart:L,onSelectionDrag:z,onSelectionDragStop:E,onSelectionContextMenu:_,onSelectionStart:G,onSelectionEnd:V,onBeforeDelete:O,connectionMode:q,connectionLineType:J=xl.Bezier,connectionLineStyle:H,connectionLineComponent:Z,connectionLineContainerStyle:Y,deleteKeyCode:ee="Backspace",selectionKeyCode:ae="Shift",selectionOnDrag:Q=!1,selectionMode:me=b0.Full,panActivationKeyCode:Ae="Space",multiSelectionKeyCode:Me=v0()?"Meta":"Control",zoomActivationKeyCode:He=v0()?"Meta":"Control",snapToGrid:je,snapGrid:xe,onlyRenderVisibleElements:Pe=!1,selectNodesOnDrag:Ce,nodesDraggable:Ye,autoPanOnNodeFocus:Qe,nodesConnectable:ct,nodesFocusable:st,nodeOrigin:zt=x8,edgesFocusable:mt,edgesReconnectable:te,elementsSelectable:de=!0,defaultViewport:be=Cee,minZoom:se=.5,maxZoom:fe=2,translateExtent:$e=x0,preventScrolling:Ne=!0,nodeExtent:Ze,defaultMarkerColor:pe="#b1b1b7",zoomOnScroll:ze=!0,zoomOnPinch:Fe=!0,panOnScroll:Je=!1,panOnScrollSpeed:gt=.5,panOnScrollMode:nt=oc.Free,zoomOnDoubleClick:Et=!0,panOnDrag:dt=!0,onPaneClick:Ve,onPaneMouseEnter:Rt,onPaneMouseMove:un,onPaneMouseLeave:yn,onPaneScroll:sn,onPaneContextMenu:In,paneClickDistance:jn=1,nodeClickDistance:Vt=0,children:mn,onReconnect:Vn,onReconnectStart:Xn,onReconnectEnd:Rr,onEdgeContextMenu:qe,onEdgeDoubleClick:St,onEdgeMouseEnter:_e,onEdgeMouseMove:Tt,onEdgeMouseLeave:Ot,reconnectRadius:Gt=10,onNodesChange:Tn,onEdgesChange:_n,noDragClassName:Sn="nodrag",noWheelClassName:Fn="nowheel",noPanClassName:mr="nopan",fitView:rr,fitViewOptions:fr,connectOnClick:Qn,attributionPosition:ir,proOptions:Ie,defaultEdgeOptions:At,elevateNodesOnSelect:It=!0,elevateEdgesOnSelect:qt=!1,disableKeyboardA11y:Jt=!1,autoPanOnConnect:tn,autoPanOnNodeDrag:An,autoPanSpeed:br,connectionRadius:an,isValidConnection:ye,onError:at,style:yt,id:Ht,nodeDragThreshold:ln,connectionDragThreshold:Mt,viewport:Ln,onViewportChange:Zn,width:zn,height:Jn,colorMode:Pn="light",debug:on,onScroll:lr,ariaLabelConfig:qr,zIndexMode:cr="basic",...yr},ur){const Rs=Ht||"1",ha=Mee(Pn),pa=x.useCallback(Or=>{Or.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),lr?.(Or)},[lr]);return n.jsx("div",{"data-testid":"rf__wrapper",...yr,onScroll:pa,style:{...yt,...Qte},ref:ur,className:ks(["react-flow",a,ha]),id:Ht,role:"application",children:n.jsxs(Xte,{nodes:e,edges:t,width:zn,height:Jn,fitView:rr,fitViewOptions:fr,minZoom:se,maxZoom:fe,nodeOrigin:zt,nodeExtent:Ze,zIndexMode:cr,children:[n.jsx(Wte,{onInit:m,onNodeClick:d,onEdgeClick:u,onNodeMouseEnter:N,onNodeMouseMove:S,onNodeMouseLeave:T,onNodeContextMenu:M,onNodeDoubleClick:D,nodeTypes:i,edgeTypes:l,connectionLineType:J,connectionLineStyle:H,connectionLineComponent:Z,connectionLineContainerStyle:Y,selectionKeyCode:ae,selectionOnDrag:Q,selectionMode:me,deleteKeyCode:ee,multiSelectionKeyCode:Me,panActivationKeyCode:Ae,zoomActivationKeyCode:He,onlyRenderVisibleElements:Pe,defaultViewport:be,translateExtent:$e,minZoom:se,maxZoom:fe,preventScrolling:Ne,zoomOnScroll:ze,zoomOnPinch:Fe,zoomOnDoubleClick:Et,panOnScroll:Je,panOnScrollSpeed:gt,panOnScrollMode:nt,panOnDrag:dt,onPaneClick:Ve,onPaneMouseEnter:Rt,onPaneMouseMove:un,onPaneMouseLeave:yn,onPaneScroll:sn,onPaneContextMenu:In,paneClickDistance:jn,nodeClickDistance:Vt,onSelectionContextMenu:_,onSelectionStart:G,onSelectionEnd:V,onReconnect:Vn,onReconnectStart:Xn,onReconnectEnd:Rr,onEdgeContextMenu:qe,onEdgeDoubleClick:St,onEdgeMouseEnter:_e,onEdgeMouseMove:Tt,onEdgeMouseLeave:Ot,reconnectRadius:Gt,defaultMarkerColor:pe,noDragClassName:Sn,noWheelClassName:Fn,noPanClassName:mr,rfId:Rs,disableKeyboardA11y:Jt,nodeExtent:Ze,viewport:Ln,onViewportChange:Zn}),n.jsx(Eee,{nodes:e,edges:t,defaultNodes:r,defaultEdges:s,onConnect:g,onConnectStart:v,onConnectEnd:j,onClickConnectStart:C,onClickConnectEnd:w,nodesDraggable:Ye,autoPanOnNodeFocus:Qe,nodesConnectable:ct,nodesFocusable:st,edgesFocusable:mt,edgesReconnectable:te,elementsSelectable:de,elevateNodesOnSelect:It,elevateEdgesOnSelect:qt,minZoom:se,maxZoom:fe,nodeExtent:Ze,onNodesChange:Tn,onEdgesChange:_n,snapToGrid:je,snapGrid:xe,connectionMode:q,translateExtent:$e,connectOnClick:Qn,defaultEdgeOptions:At,fitView:rr,fitViewOptions:fr,onNodesDelete:R,onEdgesDelete:U,onDelete:W,onNodeDragStart:I,onNodeDrag:$,onNodeDragStop:B,onSelectionDrag:z,onSelectionDragStart:L,onSelectionDragStop:E,onMove:h,onMoveStart:p,onMoveEnd:y,noPanClassName:mr,nodeOrigin:zt,rfId:Rs,autoPanOnConnect:tn,autoPanOnNodeDrag:An,autoPanSpeed:br,onError:at,connectionRadius:an,isValidConnection:ye,selectNodesOnDrag:Ce,nodeDragThreshold:ln,connectionDragThreshold:Mt,onBeforeDelete:O,debug:on,ariaLabelConfig:qr,zIndexMode:cr}),n.jsx(See,{onSelectionChange:F}),mn,n.jsx(vee,{proOptions:Ie,position:ir}),n.jsx(yee,{rfId:Rs,disableKeyboardA11y:Jt})]})})}var Jte=w8(Zte);function ene(){const e=Fr();return x.useCallback(t=>{const{domNode:r,updateNodeInternals:s}=e.getState(),a=Array.isArray(t)?t:[t],i=new Map;a.forEach(l=>{const d=r?.querySelector(`.react-flow__node[data-id="${l}"]`);d&&i.set(l,{id:l,nodeElement:d,force:!0})}),requestAnimationFrame(()=>s(i,{triggerFitView:!1}))},[])}function tne(e){const[t,r]=x.useState(e),s=x.useCallback(a=>r(i=>y8(a,i)),[]);return[t,r,s]}function nne(e){const[t,r]=x.useState(e),s=x.useCallback(a=>r(i=>v8(a,i)),[]);return[t,r,s]}function rne({dimensions:e,lineWidth:t,variant:r,className:s}){return n.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:ks(["react-flow__background-pattern",r,s])})}function sne({radius:e,className:t}){return n.jsx("circle",{cx:e,cy:e,r:e,className:ks(["react-flow__background-pattern","dots",t])})}var vl;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(vl||(vl={}));const ane={[vl.Dots]:1,[vl.Lines]:1,[vl.Cross]:6},ine=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function V8({id:e,variant:t=vl.Dots,gap:r=20,size:s,lineWidth:a=1,offset:i=0,color:l,bgColor:d,style:u,className:m,patternClassName:h}){const p=x.useRef(null),{transform:y,patternId:g}=dr(ine,Xr),v=s||ane[t],j=t===vl.Dots,C=t===vl.Cross,w=Array.isArray(r)?r:[r,r],N=[w[0]*y[2]||1,w[1]*y[2]||1],S=v*y[2],T=Array.isArray(i)?i:[i,i],M=C?[S,S]:N,D=[T[0]*y[2]||1+M[0]/2,T[1]*y[2]||1+M[1]/2],I=`${g}${e||""}`;return n.jsxs("svg",{className:ks(["react-flow__background",m]),style:{...u,...np,"--xy-background-color-props":d,"--xy-background-pattern-color-props":l},ref:p,"data-testid":"rf__background",children:[n.jsx("pattern",{id:I,x:y[0]%N[0],y:y[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${D[0]},-${D[1]})`,children:j?n.jsx(sne,{radius:S/2,className:h}):n.jsx(rne,{dimensions:M,lineWidth:a,variant:t,className:h})}),n.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${I})`})]})}V8.displayName="Background";const one=x.memo(V8);function lne(){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:n.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function cne(){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:n.jsx("path",{d:"M0 0h32v4.2H0z"})})}function dne(){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:n.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function une(){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:n.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function mne(){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:n.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function jf({children:e,className:t,...r}){return n.jsx("button",{type:"button",className:ks(["react-flow__controls-button",t]),...r,children:e})}const fne=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function K8({style:e,showZoom:t=!0,showFitView:r=!0,showInteractive:s=!0,fitViewOptions:a,onZoomIn:i,onZoomOut:l,onFitView:d,onInteractiveChange:u,className:m,children:h,position:p="bottom-left",orientation:y="vertical","aria-label":g}){const v=Fr(),{isInteractive:j,minZoomReached:C,maxZoomReached:w,ariaLabelConfig:N}=dr(fne,Xr),{zoomIn:S,zoomOut:T,fitView:M}=Ay(),D=()=>{S(),i?.()},I=()=>{T(),l?.()},$=()=>{M(a),d?.()},B=()=>{v.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),u?.(!j)},R=y==="horizontal"?"horizontal":"vertical";return n.jsxs(tp,{className:ks(["react-flow__controls",R,m]),position:p,style:e,"data-testid":"rf__controls","aria-label":g??N["controls.ariaLabel"],children:[t&&n.jsxs(n.Fragment,{children:[n.jsx(jf,{onClick:D,className:"react-flow__controls-zoomin",title:N["controls.zoomIn.ariaLabel"],"aria-label":N["controls.zoomIn.ariaLabel"],disabled:w,children:n.jsx(lne,{})}),n.jsx(jf,{onClick:I,className:"react-flow__controls-zoomout",title:N["controls.zoomOut.ariaLabel"],"aria-label":N["controls.zoomOut.ariaLabel"],disabled:C,children:n.jsx(cne,{})})]}),r&&n.jsx(jf,{className:"react-flow__controls-fitview",onClick:$,title:N["controls.fitView.ariaLabel"],"aria-label":N["controls.fitView.ariaLabel"],children:n.jsx(dne,{})}),s&&n.jsx(jf,{className:"react-flow__controls-interactive",onClick:B,title:N["controls.interactive.ariaLabel"],"aria-label":N["controls.interactive.ariaLabel"],children:j?n.jsx(mne,{}):n.jsx(une,{})}),h]})}K8.displayName="Controls";const hne=x.memo(K8);function pne({id:e,x:t,y:r,width:s,height:a,style:i,color:l,strokeColor:d,strokeWidth:u,className:m,borderRadius:h,shapeRendering:p,selected:y,onClick:g}){const{background:v,backgroundColor:j}=i||{},C=l||v||j;return n.jsx("rect",{className:ks(["react-flow__minimap-node",{selected:y},m]),x:t,y:r,rx:h,ry:h,width:s,height:a,style:{fill:C,stroke:d,strokeWidth:u},shapeRendering:p,onClick:g?w=>g(w,e):void 0})}const gne=x.memo(pne),xne=e=>e.nodes.map(t=>t.id),ab=e=>e instanceof Function?e:()=>e;function bne({nodeStrokeColor:e,nodeColor:t,nodeClassName:r="",nodeBorderRadius:s=5,nodeStrokeWidth:a,nodeComponent:i=gne,onClick:l}){const d=dr(xne,Xr),u=ab(t),m=ab(e),h=ab(r),p=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return n.jsx(n.Fragment,{children:d.map(y=>n.jsx(vne,{id:y,nodeColorFunc:u,nodeStrokeColorFunc:m,nodeClassNameFunc:h,nodeBorderRadius:s,nodeStrokeWidth:a,NodeComponent:i,onClick:l,shapeRendering:p},y))})}function yne({id:e,nodeColorFunc:t,nodeStrokeColorFunc:r,nodeClassNameFunc:s,nodeBorderRadius:a,nodeStrokeWidth:i,shapeRendering:l,NodeComponent:d,onClick:u}){const{node:m,x:h,y:p,width:y,height:g}=dr(v=>{const j=v.nodeLookup.get(e);if(!j)return{node:void 0,x:0,y:0,width:0,height:0};const C=j.internals.userNode,{x:w,y:N}=j.internals.positionAbsolute,{width:S,height:T}=zo(C);return{node:C,x:w,y:N,width:S,height:T}},Xr);return!m||m.hidden||!W7(m)?null:n.jsx(d,{x:h,y:p,width:y,height:g,style:m.style,selected:!!m.selected,className:s(m),color:t(m),borderRadius:a,strokeColor:r(m),strokeWidth:i,shapeRendering:l,onClick:u,id:m.id})}const vne=x.memo(yne);var wne=x.memo(bne);const kne=200,jne=150,Nne=e=>!e.hidden,Sne=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?K7(L0(e.nodeLookup,{filter:Nne}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Cne="react-flow__minimap-desc";function W8({style:e,className:t,nodeStrokeColor:r,nodeColor:s,nodeClassName:a="",nodeBorderRadius:i=5,nodeStrokeWidth:l,nodeComponent:d,bgColor:u,maskColor:m,maskStrokeColor:h,maskStrokeWidth:p,position:y="bottom-right",onClick:g,onNodeClick:v,pannable:j=!1,zoomable:C=!1,ariaLabel:w,inversePan:N,zoomStep:S=1,offsetScale:T=5}){const M=Fr(),D=x.useRef(null),{boundingRect:I,viewBB:$,rfId:B,panZoom:R,translateExtent:U,flowWidth:W,flowHeight:F,ariaLabelConfig:L}=dr(Sne,Xr),z=e?.width??kne,E=e?.height??jne,_=I.width/z,G=I.height/E,V=Math.max(_,G),O=V*z,q=V*E,J=T*V,H=I.x-(O-I.width)/2-J,Z=I.y-(q-I.height)/2-J,Y=O+J*2,ee=q+J*2,ae=`${Cne}-${B}`,Q=x.useRef(0),me=x.useRef();Q.current=V,x.useEffect(()=>{if(D.current&&R)return me.current=FJ({domNode:D.current,panZoom:R,getTransform:()=>M.getState().transform,getViewScale:()=>Q.current}),()=>{me.current?.destroy()}},[R]),x.useEffect(()=>{me.current?.update({translateExtent:U,width:W,height:F,inversePan:N,pannable:j,zoomStep:S,zoomable:C})},[j,C,N,S,U,W,F]);const Ae=g?je=>{const[xe,Pe]=me.current?.pointer(je)||[0,0];g(je,{x:xe,y:Pe})}:void 0,Me=v?x.useCallback((je,xe)=>{const Pe=M.getState().nodeLookup.get(xe).internals.userNode;v(je,Pe)},[]):void 0,He=w??L["minimap.ariaLabel"];return n.jsx(tp,{position:y,style:{...e,"--xy-minimap-background-color-props":typeof u=="string"?u:void 0,"--xy-minimap-mask-background-color-props":typeof m=="string"?m:void 0,"--xy-minimap-mask-stroke-color-props":typeof h=="string"?h:void 0,"--xy-minimap-mask-stroke-width-props":typeof p=="number"?p*V:void 0,"--xy-minimap-node-background-color-props":typeof s=="string"?s:void 0,"--xy-minimap-node-stroke-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-width-props":typeof l=="number"?l:void 0},className:ks(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:n.jsxs("svg",{width:z,height:E,viewBox:`${H} ${Z} ${Y} ${ee}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":ae,ref:D,onClick:Ae,children:[He&&n.jsx("title",{id:ae,children:He}),n.jsx(wne,{onClick:Me,nodeColor:s,nodeStrokeColor:r,nodeBorderRadius:i,nodeClassName:a,nodeStrokeWidth:l,nodeComponent:d}),n.jsx("path",{className:"react-flow__minimap-mask",d:`M${H-J},${Z-J}h${Y+J*2}v${ee+J*2}h${-Y-J*2}z
707
707
  M${$.x},${$.y}h${$.width}v${$.height}h${-$.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}W8.displayName="MiniMap";const Tne=x.memo(W8),Ane=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Ene={[Md.Line]:"right",[Md.Handle]:"bottom-right"};function Mne({nodeId:e,position:t,variant:r=Md.Handle,className:s,style:a=void 0,children:i,color:l,minWidth:d=10,minHeight:u=10,maxWidth:m=Number.MAX_VALUE,maxHeight:h=Number.MAX_VALUE,keepAspectRatio:p=!1,resizeDirection:y,autoScale:g=!0,shouldResize:v,onResizeStart:j,onResize:C,onResizeEnd:w}){const N=S8(),S=typeof e=="string"?e:N,T=Fr(),M=x.useRef(null),D=r===Md.Handle,I=dr(x.useCallback(Ane(D&&g),[D,g]),Xr),$=x.useRef(null),B=t??Ene[r];x.useEffect(()=>{if(!(!M.current||!S))return $.current||($.current=nee({domNode:M.current,nodeId:S,getStoreItems:()=>{const{nodeLookup:U,transform:W,snapGrid:F,snapToGrid:L,nodeOrigin:z,domNode:E}=T.getState();return{nodeLookup:U,transform:W,snapGrid:F,snapToGrid:L,nodeOrigin:z,paneDomNode:E}},onChange:(U,W)=>{const{triggerNodeChanges:F,nodeLookup:L,parentLookup:z,nodeOrigin:E}=T.getState(),_=[],G={x:U.x,y:U.y},V=L.get(S);if(V&&V.expandParent&&V.parentId){const O=V.origin??E,q=U.width??V.measured.width??0,J=U.height??V.measured.height??0,H={id:V.id,parentId:V.parentId,rect:{width:q,height:J,...G7({x:U.x??V.position.x,y:U.y??V.position.y},{width:q,height:J},V.parentId,L,O)}},Z=Ty([H],L,z,E);_.push(...Z),G.x=U.x?Math.max(O[0]*q,U.x):void 0,G.y=U.y?Math.max(O[1]*J,U.y):void 0}if(G.x!==void 0&&G.y!==void 0){const O={id:S,type:"position",position:{...G}};_.push(O)}if(U.width!==void 0&&U.height!==void 0){const q={id:S,type:"dimensions",resizing:!0,setAttributes:y?y==="horizontal"?"width":"height":!0,dimensions:{width:U.width,height:U.height}};_.push(q)}for(const O of W){const q={...O,type:"position"};_.push(q)}F(_)},onEnd:({width:U,height:W})=>{const F={id:S,type:"dimensions",resizing:!1,dimensions:{width:U,height:W}};T.getState().triggerNodeChanges([F])}})),$.current.update({controlPosition:B,boundaries:{minWidth:d,minHeight:u,maxWidth:m,maxHeight:h},keepAspectRatio:p,resizeDirection:y,onResizeStart:j,onResize:C,onResizeEnd:w,shouldResize:v}),()=>{$.current?.destroy()}},[B,d,u,m,h,p,j,C,w,v]);const R=B.split("-");return n.jsx("div",{className:ks(["react-flow__resize-control","nodrag",...R,r,s]),ref:M,style:{...a,scale:I,...l&&{[D?"backgroundColor":"borderColor"]:l}},children:i})}x.memo(Mne);var Ar=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ai=Ar((e,t)=>{var r=Object.defineProperty,s=(F,L,z)=>L in F?r(F,L,{enumerable:!0,configurable:!0,writable:!0,value:z}):F[L]=z,a=(F,L)=>()=>(L||F((L={exports:{}}).exports,L),L.exports),i=(F,L,z)=>s(F,typeof L!="symbol"?L+"":L,z),l=a((F,L)=>{var z="\0",E="\0",_="",G=class{constructor(Z){i(this,"_isDirected",!0),i(this,"_isMultigraph",!1),i(this,"_isCompound",!1),i(this,"_label"),i(this,"_defaultNodeLabelFn",()=>{}),i(this,"_defaultEdgeLabelFn",()=>{}),i(this,"_nodes",{}),i(this,"_in",{}),i(this,"_preds",{}),i(this,"_out",{}),i(this,"_sucs",{}),i(this,"_edgeObjs",{}),i(this,"_edgeLabels",{}),i(this,"_nodeCount",0),i(this,"_edgeCount",0),i(this,"_parent"),i(this,"_children"),Z&&(this._isDirected=Object.hasOwn(Z,"directed")?Z.directed:!0,this._isMultigraph=Object.hasOwn(Z,"multigraph")?Z.multigraph:!1,this._isCompound=Object.hasOwn(Z,"compound")?Z.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[E]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(Z){return this._label=Z,this}graph(){return this._label}setDefaultNodeLabel(Z){return this._defaultNodeLabelFn=Z,typeof Z!="function"&&(this._defaultNodeLabelFn=()=>Z),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var Z=this;return this.nodes().filter(Y=>Object.keys(Z._in[Y]).length===0)}sinks(){var Z=this;return this.nodes().filter(Y=>Object.keys(Z._out[Y]).length===0)}setNodes(Z,Y){var ee=arguments,ae=this;return Z.forEach(function(Q){ee.length>1?ae.setNode(Q,Y):ae.setNode(Q)}),this}setNode(Z,Y){return Object.hasOwn(this._nodes,Z)?(arguments.length>1&&(this._nodes[Z]=Y),this):(this._nodes[Z]=arguments.length>1?Y:this._defaultNodeLabelFn(Z),this._isCompound&&(this._parent[Z]=E,this._children[Z]={},this._children[E][Z]=!0),this._in[Z]={},this._preds[Z]={},this._out[Z]={},this._sucs[Z]={},++this._nodeCount,this)}node(Z){return this._nodes[Z]}hasNode(Z){return Object.hasOwn(this._nodes,Z)}removeNode(Z){var Y=this;if(Object.hasOwn(this._nodes,Z)){var ee=ae=>Y.removeEdge(Y._edgeObjs[ae]);delete this._nodes[Z],this._isCompound&&(this._removeFromParentsChildList(Z),delete this._parent[Z],this.children(Z).forEach(function(ae){Y.setParent(ae)}),delete this._children[Z]),Object.keys(this._in[Z]).forEach(ee),delete this._in[Z],delete this._preds[Z],Object.keys(this._out[Z]).forEach(ee),delete this._out[Z],delete this._sucs[Z],--this._nodeCount}return this}setParent(Z,Y){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(Y===void 0)Y=E;else{Y+="";for(var ee=Y;ee!==void 0;ee=this.parent(ee))if(ee===Z)throw new Error("Setting "+Y+" as parent of "+Z+" would create a cycle");this.setNode(Y)}return this.setNode(Z),this._removeFromParentsChildList(Z),this._parent[Z]=Y,this._children[Y][Z]=!0,this}_removeFromParentsChildList(Z){delete this._children[this._parent[Z]][Z]}parent(Z){if(this._isCompound){var Y=this._parent[Z];if(Y!==E)return Y}}children(Z=E){if(this._isCompound){var Y=this._children[Z];if(Y)return Object.keys(Y)}else{if(Z===E)return this.nodes();if(this.hasNode(Z))return[]}}predecessors(Z){var Y=this._preds[Z];if(Y)return Object.keys(Y)}successors(Z){var Y=this._sucs[Z];if(Y)return Object.keys(Y)}neighbors(Z){var Y=this.predecessors(Z);if(Y){let ae=new Set(Y);for(var ee of this.successors(Z))ae.add(ee);return Array.from(ae.values())}}isLeaf(Z){var Y;return this.isDirected()?Y=this.successors(Z):Y=this.neighbors(Z),Y.length===0}filterNodes(Z){var Y=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});Y.setGraph(this.graph());var ee=this;Object.entries(this._nodes).forEach(function([me,Ae]){Z(me)&&Y.setNode(me,Ae)}),Object.values(this._edgeObjs).forEach(function(me){Y.hasNode(me.v)&&Y.hasNode(me.w)&&Y.setEdge(me,ee.edge(me))});var ae={};function Q(me){var Ae=ee.parent(me);return Ae===void 0||Y.hasNode(Ae)?(ae[me]=Ae,Ae):Ae in ae?ae[Ae]:Q(Ae)}return this._isCompound&&Y.nodes().forEach(me=>Y.setParent(me,Q(me))),Y}setDefaultEdgeLabel(Z){return this._defaultEdgeLabelFn=Z,typeof Z!="function"&&(this._defaultEdgeLabelFn=()=>Z),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(Z,Y){var ee=this,ae=arguments;return Z.reduce(function(Q,me){return ae.length>1?ee.setEdge(Q,me,Y):ee.setEdge(Q,me),me}),this}setEdge(){var Z,Y,ee,ae,Q=!1,me=arguments[0];typeof me=="object"&&me!==null&&"v"in me?(Z=me.v,Y=me.w,ee=me.name,arguments.length===2&&(ae=arguments[1],Q=!0)):(Z=me,Y=arguments[1],ee=arguments[3],arguments.length>2&&(ae=arguments[2],Q=!0)),Z=""+Z,Y=""+Y,ee!==void 0&&(ee=""+ee);var Ae=q(this._isDirected,Z,Y,ee);if(Object.hasOwn(this._edgeLabels,Ae))return Q&&(this._edgeLabels[Ae]=ae),this;if(ee!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(Z),this.setNode(Y),this._edgeLabels[Ae]=Q?ae:this._defaultEdgeLabelFn(Z,Y,ee);var Me=J(this._isDirected,Z,Y,ee);return Z=Me.v,Y=Me.w,Object.freeze(Me),this._edgeObjs[Ae]=Me,V(this._preds[Y],Z),V(this._sucs[Z],Y),this._in[Y][Ae]=Me,this._out[Z][Ae]=Me,this._edgeCount++,this}edge(Z,Y,ee){var ae=arguments.length===1?H(this._isDirected,arguments[0]):q(this._isDirected,Z,Y,ee);return this._edgeLabels[ae]}edgeAsObj(){let Z=this.edge(...arguments);return typeof Z!="object"?{label:Z}:Z}hasEdge(Z,Y,ee){var ae=arguments.length===1?H(this._isDirected,arguments[0]):q(this._isDirected,Z,Y,ee);return Object.hasOwn(this._edgeLabels,ae)}removeEdge(Z,Y,ee){var ae=arguments.length===1?H(this._isDirected,arguments[0]):q(this._isDirected,Z,Y,ee),Q=this._edgeObjs[ae];return Q&&(Z=Q.v,Y=Q.w,delete this._edgeLabels[ae],delete this._edgeObjs[ae],O(this._preds[Y],Z),O(this._sucs[Z],Y),delete this._in[Y][ae],delete this._out[Z][ae],this._edgeCount--),this}inEdges(Z,Y){return this.isDirected()?this.filterEdges(this._in[Z],Z,Y):this.nodeEdges(Z,Y)}outEdges(Z,Y){return this.isDirected()?this.filterEdges(this._out[Z],Z,Y):this.nodeEdges(Z,Y)}nodeEdges(Z,Y){if(Z in this._nodes)return this.filterEdges({...this._in[Z],...this._out[Z]},Z,Y)}filterEdges(Z,Y,ee){if(Z){var ae=Object.values(Z);return ee?ae.filter(function(Q){return Q.v===Y&&Q.w===ee||Q.v===ee&&Q.w===Y}):ae}}};function V(Z,Y){Z[Y]?Z[Y]++:Z[Y]=1}function O(Z,Y){--Z[Y]||delete Z[Y]}function q(Z,Y,ee,ae){var Q=""+Y,me=""+ee;if(!Z&&Q>me){var Ae=Q;Q=me,me=Ae}return Q+_+me+_+(ae===void 0?z:ae)}function J(Z,Y,ee,ae){var Q=""+Y,me=""+ee;if(!Z&&Q>me){var Ae=Q;Q=me,me=Ae}var Me={v:Q,w:me};return ae&&(Me.name=ae),Me}function H(Z,Y){return q(Z,Y.v,Y.w,Y.name)}L.exports=G}),d=a((F,L)=>{L.exports="3.0.2"}),u=a((F,L)=>{L.exports={Graph:l(),version:d()}}),m=a((F,L)=>{var z=l();L.exports={write:E,read:V};function E(O){var q={options:{directed:O.isDirected(),multigraph:O.isMultigraph(),compound:O.isCompound()},nodes:_(O),edges:G(O)};return O.graph()!==void 0&&(q.value=structuredClone(O.graph())),q}function _(O){return O.nodes().map(function(q){var J=O.node(q),H=O.parent(q),Z={v:q};return J!==void 0&&(Z.value=J),H!==void 0&&(Z.parent=H),Z})}function G(O){return O.edges().map(function(q){var J=O.edge(q),H={v:q.v,w:q.w};return q.name!==void 0&&(H.name=q.name),J!==void 0&&(H.value=J),H})}function V(O){var q=new z(O.options).setGraph(O.value);return O.nodes.forEach(function(J){q.setNode(J.v,J.value),J.parent&&q.setParent(J.v,J.parent)}),O.edges.forEach(function(J){q.setEdge({v:J.v,w:J.w,name:J.name},J.value)}),q}}),h=a((F,L)=>{L.exports=E;var z=()=>1;function E(G,V,O,q){return _(G,String(V),O||z,q||function(J){return G.outEdges(J)})}function _(G,V,O,q){var J={},H=!0,Z=0,Y=G.nodes(),ee=function(Ae){var Me=O(Ae);J[Ae.v].distance+Me<J[Ae.w].distance&&(J[Ae.w]={distance:J[Ae.v].distance+Me,predecessor:Ae.v},H=!0)},ae=function(){Y.forEach(function(Ae){q(Ae).forEach(function(Me){var He=Me.v===Ae?Me.v:Me.w,je=He===Me.v?Me.w:Me.v;ee({v:He,w:je})})})};Y.forEach(function(Ae){var Me=Ae===V?0:Number.POSITIVE_INFINITY;J[Ae]={distance:Me}});for(var Q=Y.length,me=1;me<Q&&(H=!1,Z++,ae(),!!H);me++);if(Z===Q-1&&(H=!1,ae(),H))throw new Error("The graph contains a negative weight cycle");return J}}),p=a((F,L)=>{L.exports=z;function z(E){var _={},G=[],V;function O(q){Object.hasOwn(_,q)||(_[q]=!0,V.push(q),E.successors(q).forEach(O),E.predecessors(q).forEach(O))}return E.nodes().forEach(function(q){V=[],O(q),V.length&&G.push(V)}),G}}),y=a((F,L)=>{var z=class{constructor(){i(this,"_arr",[]),i(this,"_keyIndices",{})}size(){return this._arr.length}keys(){return this._arr.map(function(E){return E.key})}has(E){return Object.hasOwn(this._keyIndices,E)}priority(E){var _=this._keyIndices[E];if(_!==void 0)return this._arr[_].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(E,_){var G=this._keyIndices;if(E=String(E),!Object.hasOwn(G,E)){var V=this._arr,O=V.length;return G[E]=O,V.push({key:E,priority:_}),this._decrease(O),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var E=this._arr.pop();return delete this._keyIndices[E.key],this._heapify(0),E.key}decrease(E,_){var G=this._keyIndices[E];if(_>this._arr[G].priority)throw new Error("New priority is greater than current priority. Key: "+E+" Old: "+this._arr[G].priority+" New: "+_);this._arr[G].priority=_,this._decrease(G)}_heapify(E){var _=this._arr,G=2*E,V=G+1,O=E;G<_.length&&(O=_[G].priority<_[O].priority?G:O,V<_.length&&(O=_[V].priority<_[O].priority?V:O),O!==E&&(this._swap(E,O),this._heapify(O)))}_decrease(E){for(var _=this._arr,G=_[E].priority,V;E!==0&&(V=E>>1,!(_[V].priority<G));)this._swap(E,V),E=V}_swap(E,_){var G=this._arr,V=this._keyIndices,O=G[E],q=G[_];G[E]=q,G[_]=O,V[q.key]=E,V[O.key]=_}};L.exports=z}),g=a((F,L)=>{var z=y();L.exports=_;var E=()=>1;function _(V,O,q,J){var H=function(Z){return V.outEdges(Z)};return G(V,String(O),q||E,J||H)}function G(V,O,q,J){var H={},Z=new z,Y,ee,ae=function(Q){var me=Q.v!==Y?Q.v:Q.w,Ae=H[me],Me=q(Q),He=ee.distance+Me;if(Me<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+Q+" Weight: "+Me);He<Ae.distance&&(Ae.distance=He,Ae.predecessor=Y,Z.decrease(me,He))};for(V.nodes().forEach(function(Q){var me=Q===O?0:Number.POSITIVE_INFINITY;H[Q]={distance:me},Z.add(Q,me)});Z.size()>0&&(Y=Z.removeMin(),ee=H[Y],ee.distance!==Number.POSITIVE_INFINITY);)J(Y).forEach(ae);return H}}),v=a((F,L)=>{var z=g();L.exports=E;function E(_,G,V){return _.nodes().reduce(function(O,q){return O[q]=z(_,q,G,V),O},{})}}),j=a((F,L)=>{L.exports=z;function z(_,G,V){if(_[G].predecessor!==void 0)throw new Error("Invalid source vertex");if(_[V].predecessor===void 0&&V!==G)throw new Error("Invalid destination vertex");return{weight:_[V].distance,path:E(_,G,V)}}function E(_,G,V){for(var O=[],q=V;q!==G;)O.push(q),q=_[q].predecessor;return O.push(G),O.reverse()}}),C=a((F,L)=>{L.exports=z;function z(E){var _=0,G=[],V={},O=[];function q(J){var H=V[J]={onStack:!0,lowlink:_,index:_++};if(G.push(J),E.successors(J).forEach(function(ee){Object.hasOwn(V,ee)?V[ee].onStack&&(H.lowlink=Math.min(H.lowlink,V[ee].index)):(q(ee),H.lowlink=Math.min(H.lowlink,V[ee].lowlink))}),H.lowlink===H.index){var Z=[],Y;do Y=G.pop(),V[Y].onStack=!1,Z.push(Y);while(J!==Y);O.push(Z)}}return E.nodes().forEach(function(J){Object.hasOwn(V,J)||q(J)}),O}}),w=a((F,L)=>{var z=C();L.exports=E;function E(_){return z(_).filter(function(G){return G.length>1||G.length===1&&_.hasEdge(G[0],G[0])})}}),N=a((F,L)=>{L.exports=E;var z=()=>1;function E(G,V,O){return _(G,V||z,O||function(q){return G.outEdges(q)})}function _(G,V,O){var q={},J=G.nodes();return J.forEach(function(H){q[H]={},q[H][H]={distance:0},J.forEach(function(Z){H!==Z&&(q[H][Z]={distance:Number.POSITIVE_INFINITY})}),O(H).forEach(function(Z){var Y=Z.v===H?Z.w:Z.v,ee=V(Z);q[H][Y]={distance:ee,predecessor:H}})}),J.forEach(function(H){var Z=q[H];J.forEach(function(Y){var ee=q[Y];J.forEach(function(ae){var Q=ee[H],me=Z[ae],Ae=ee[ae],Me=Q.distance+me.distance;Me<Ae.distance&&(Ae.distance=Me,Ae.predecessor=me.predecessor)})})}),q}}),S=a((F,L)=>{function z(_){var G={},V={},O=[];function q(J){if(Object.hasOwn(V,J))throw new E;Object.hasOwn(G,J)||(V[J]=!0,G[J]=!0,_.predecessors(J).forEach(q),delete V[J],O.push(J))}if(_.sinks().forEach(q),Object.keys(G).length!==_.nodeCount())throw new E;return O}var E=class extends Error{constructor(){super(...arguments)}};L.exports=z,z.CycleException=E}),T=a((F,L)=>{var z=S();L.exports=E;function E(_){try{z(_)}catch(G){if(G instanceof z.CycleException)return!1;throw G}return!0}}),M=a((F,L)=>{L.exports=z;function z(_,G,V,O,q){Array.isArray(G)||(G=[G]);var J=(_.isDirected()?_.successors:_.neighbors).bind(_),H={};return G.forEach(function(Z){if(!_.hasNode(Z))throw new Error("Graph does not have node: "+Z);q=E(_,Z,V==="post",H,J,O,q)}),q}function E(_,G,V,O,q,J,H){return Object.hasOwn(O,G)||(O[G]=!0,V||(H=J(H,G)),q(G).forEach(function(Z){H=E(_,Z,V,O,q,J,H)}),V&&(H=J(H,G))),H}}),D=a((F,L)=>{var z=M();L.exports=E;function E(_,G,V){return z(_,G,V,function(O,q){return O.push(q),O},[])}}),I=a((F,L)=>{var z=D();L.exports=E;function E(_,G){return z(_,G,"post")}}),$=a((F,L)=>{var z=D();L.exports=E;function E(_,G){return z(_,G,"pre")}}),B=a((F,L)=>{var z=l(),E=y();L.exports=_;function _(G,V){var O=new z,q={},J=new E,H;function Z(ee){var ae=ee.v===H?ee.w:ee.v,Q=J.priority(ae);if(Q!==void 0){var me=V(ee);me<Q&&(q[ae]=H,J.decrease(ae,me))}}if(G.nodeCount()===0)return O;G.nodes().forEach(function(ee){J.add(ee,Number.POSITIVE_INFINITY),O.setNode(ee)}),J.decrease(G.nodes()[0],0);for(var Y=!1;J.size()>0;){if(H=J.removeMin(),Object.hasOwn(q,H))O.setEdge(H,q[H]);else{if(Y)throw new Error("Input graph is not connected: "+G);Y=!0}G.nodeEdges(H).forEach(Z)}return O}}),R=a((F,L)=>{var z=g(),E=h();L.exports=_;function _(V,O,q,J){return G(V,O,q,J||function(H){return V.outEdges(H)})}function G(V,O,q,J){if(q===void 0)return z(V,O,q,J);for(var H=!1,Z=V.nodes(),Y=0;Y<Z.length;Y++){for(var ee=J(Z[Y]),ae=0;ae<ee.length;ae++){var Q=ee[ae],me=Q.v===Z[Y]?Q.v:Q.w,Ae=me===Q.v?Q.w:Q.v;q({v:me,w:Ae})<0&&(H=!0)}if(H)return E(V,O,q,J)}return z(V,O,q,J)}}),U=a((F,L)=>{L.exports={bellmanFord:h(),components:p(),dijkstra:g(),dijkstraAll:v(),extractPath:j(),findCycles:w(),floydWarshall:N(),isAcyclic:T(),postorder:I(),preorder:$(),prim:B(),shortestPaths:R(),reduce:M(),tarjan:C(),topsort:S()}}),W=u();t.exports={Graph:W.Graph,json:m(),alg:U(),version:W.version}}),Dne=Ar((e,t)=>{var r=class{constructor(){let i={};i._next=i._prev=i,this._sentinel=i}dequeue(){let i=this._sentinel,l=i._prev;if(l!==i)return s(l),l}enqueue(i){let l=this._sentinel;i._prev&&i._next&&s(i),i._next=l._next,l._next._prev=i,l._next=i,i._prev=l}toString(){let i=[],l=this._sentinel,d=l._prev;for(;d!==l;)i.push(JSON.stringify(d,a)),d=d._prev;return"["+i.join(", ")+"]"}};function s(i){i._prev._next=i._next,i._next._prev=i._prev,delete i._next,delete i._prev}function a(i,l){if(i!=="_next"&&i!=="_prev")return l}t.exports=r}),Rne=Ar((e,t)=>{var r=Ai().Graph,s=Dne();t.exports=i;var a=()=>1;function i(p,y){if(p.nodeCount()<=1)return[];let g=u(p,y||a);return l(g.graph,g.buckets,g.zeroIdx).flatMap(v=>p.outEdges(v.v,v.w))}function l(p,y,g){let v=[],j=y[y.length-1],C=y[0],w;for(;p.nodeCount();){for(;w=C.dequeue();)d(p,y,g,w);for(;w=j.dequeue();)d(p,y,g,w);if(p.nodeCount()){for(let N=y.length-2;N>0;--N)if(w=y[N].dequeue(),w){v=v.concat(d(p,y,g,w,!0));break}}}return v}function d(p,y,g,v,j){let C=j?[]:void 0;return p.inEdges(v.v).forEach(w=>{let N=p.edge(w),S=p.node(w.v);j&&C.push({v:w.v,w:w.w}),S.out-=N,m(y,g,S)}),p.outEdges(v.v).forEach(w=>{let N=p.edge(w),S=w.w,T=p.node(S);T.in-=N,m(y,g,T)}),p.removeNode(v.v),C}function u(p,y){let g=new r,v=0,j=0;p.nodes().forEach(N=>{g.setNode(N,{v:N,in:0,out:0})}),p.edges().forEach(N=>{let S=g.edge(N.v,N.w)||0,T=y(N),M=S+T;g.setEdge(N.v,N.w,M),j=Math.max(j,g.node(N.v).out+=T),v=Math.max(v,g.node(N.w).in+=T)});let C=h(j+v+3).map(()=>new s),w=v+1;return g.nodes().forEach(N=>{m(C,w,g.node(N))}),{graph:g,buckets:C,zeroIdx:w}}function m(p,y,g){g.out?g.in?p[g.out-g.in+y].enqueue(g):p[p.length-1].enqueue(g):p[0].enqueue(g)}function h(p){let y=[];for(let g=0;g<p;g++)y.push(g);return y}}),vs=Ar((e,t)=>{var r=Ai().Graph;t.exports={addBorderNode:y,addDummyNode:s,applyWithChunking:j,asNonCompoundGraph:i,buildLayerMatrix:m,intersectRect:u,mapValues:$,maxRank:C,normalizeRanks:h,notime:S,partition:w,pick:I,predecessorWeights:d,range:D,removeEmptyRanks:p,simplify:a,successorWeights:l,time:N,uniqueId:M,zipObject:B};function s(R,U,W,F){for(var L=F;R.hasNode(L);)L=M(F);return W.dummy=U,R.setNode(L,W),L}function a(R){let U=new r().setGraph(R.graph());return R.nodes().forEach(W=>U.setNode(W,R.node(W))),R.edges().forEach(W=>{let F=U.edge(W.v,W.w)||{weight:0,minlen:1},L=R.edge(W);U.setEdge(W.v,W.w,{weight:F.weight+L.weight,minlen:Math.max(F.minlen,L.minlen)})}),U}function i(R){let U=new r({multigraph:R.isMultigraph()}).setGraph(R.graph());return R.nodes().forEach(W=>{R.children(W).length||U.setNode(W,R.node(W))}),R.edges().forEach(W=>{U.setEdge(W,R.edge(W))}),U}function l(R){let U=R.nodes().map(W=>{let F={};return R.outEdges(W).forEach(L=>{F[L.w]=(F[L.w]||0)+R.edge(L).weight}),F});return B(R.nodes(),U)}function d(R){let U=R.nodes().map(W=>{let F={};return R.inEdges(W).forEach(L=>{F[L.v]=(F[L.v]||0)+R.edge(L).weight}),F});return B(R.nodes(),U)}function u(R,U){let W=R.x,F=R.y,L=U.x-W,z=U.y-F,E=R.width/2,_=R.height/2;if(!L&&!z)throw new Error("Not possible to find intersection inside of the rectangle");let G,V;return Math.abs(z)*E>Math.abs(L)*_?(z<0&&(_=-_),G=_*L/z,V=_):(L<0&&(E=-E),G=E,V=E*z/L),{x:W+G,y:F+V}}function m(R){let U=D(C(R)+1).map(()=>[]);return R.nodes().forEach(W=>{let F=R.node(W),L=F.rank;L!==void 0&&(U[L][F.order]=W)}),U}function h(R){let U=R.nodes().map(F=>{let L=R.node(F).rank;return L===void 0?Number.MAX_VALUE:L}),W=j(Math.min,U);R.nodes().forEach(F=>{let L=R.node(F);Object.hasOwn(L,"rank")&&(L.rank-=W)})}function p(R){let U=R.nodes().map(E=>R.node(E).rank).filter(E=>E!==void 0),W=j(Math.min,U),F=[];R.nodes().forEach(E=>{let _=R.node(E).rank-W;F[_]||(F[_]=[]),F[_].push(E)});let L=0,z=R.graph().nodeRankFactor;Array.from(F).forEach((E,_)=>{E===void 0&&_%z!==0?--L:E!==void 0&&L&&E.forEach(G=>R.node(G).rank+=L)})}function y(R,U,W,F){let L={width:0,height:0};return arguments.length>=4&&(L.rank=W,L.order=F),s(R,"border",L,U)}function g(R,U=v){let W=[];for(let F=0;F<R.length;F+=U){let L=R.slice(F,F+U);W.push(L)}return W}var v=65535;function j(R,U){if(U.length>v){let W=g(U);return R.apply(null,W.map(F=>R.apply(null,F)))}else return R.apply(null,U)}function C(R){let U=R.nodes().map(W=>{let F=R.node(W).rank;return F===void 0?Number.MIN_VALUE:F});return j(Math.max,U)}function w(R,U){let W={lhs:[],rhs:[]};return R.forEach(F=>{U(F)?W.lhs.push(F):W.rhs.push(F)}),W}function N(R,U){let W=Date.now();try{return U()}finally{console.log(R+" time: "+(Date.now()-W)+"ms")}}function S(R,U){return U()}var T=0;function M(R){var U=++T;return R+(""+U)}function D(R,U,W=1){U==null&&(U=R,R=0);let F=z=>z<U;W<0&&(F=z=>U<z);let L=[];for(let z=R;F(z);z+=W)L.push(z);return L}function I(R,U){let W={};for(let F of U)R[F]!==void 0&&(W[F]=R[F]);return W}function $(R,U){let W=U;return typeof U=="string"&&(W=F=>F[U]),Object.entries(R).reduce((F,[L,z])=>(F[L]=W(z,L),F),{})}function B(R,U){return R.reduce((W,F,L)=>(W[F]=U[L],W),{})}}),Ine=Ar((e,t)=>{var r=Rne(),s=vs().uniqueId;t.exports={run:a,undo:l};function a(d){(d.graph().acyclicer==="greedy"?r(d,u(d)):i(d)).forEach(m=>{let h=d.edge(m);d.removeEdge(m),h.forwardName=m.name,h.reversed=!0,d.setEdge(m.w,m.v,h,s("rev"))});function u(m){return h=>m.edge(h).weight}}function i(d){let u=[],m={},h={};function p(y){Object.hasOwn(h,y)||(h[y]=!0,m[y]=!0,d.outEdges(y).forEach(g=>{Object.hasOwn(m,g.w)?u.push(g):p(g.w)}),delete m[y])}return d.nodes().forEach(p),u}function l(d){d.edges().forEach(u=>{let m=d.edge(u);if(m.reversed){d.removeEdge(u);let h=m.forwardName;delete m.reversed,delete m.forwardName,d.setEdge(u.w,u.v,m,h)}})}}),Lne=Ar((e,t)=>{var r=vs();t.exports={run:s,undo:i};function s(l){l.graph().dummyChains=[],l.edges().forEach(d=>a(l,d))}function a(l,d){let u=d.v,m=l.node(u).rank,h=d.w,p=l.node(h).rank,y=d.name,g=l.edge(d),v=g.labelRank;if(p===m+1)return;l.removeEdge(d);let j,C,w;for(w=0,++m;m<p;++w,++m)g.points=[],C={width:0,height:0,edgeLabel:g,edgeObj:d,rank:m},j=r.addDummyNode(l,"edge",C,"_d"),m===v&&(C.width=g.width,C.height=g.height,C.dummy="edge-label",C.labelpos=g.labelpos),l.setEdge(u,j,{weight:g.weight},y),w===0&&l.graph().dummyChains.push(j),u=j;l.setEdge(u,h,{weight:g.weight},y)}function i(l){l.graph().dummyChains.forEach(d=>{let u=l.node(d),m=u.edgeLabel,h;for(l.setEdge(u.edgeObj,m);u.dummy;)h=l.successors(d)[0],l.removeNode(d),m.points.push({x:u.x,y:u.y}),u.dummy==="edge-label"&&(m.x=u.x,m.y=u.y,m.width=u.width,m.height=u.height),d=h,u=l.node(d)})}}),jh=Ar((e,t)=>{var{applyWithChunking:r}=vs();t.exports={longestPath:s,slack:a};function s(i){var l={};function d(u){var m=i.node(u);if(Object.hasOwn(l,u))return m.rank;l[u]=!0;let h=i.outEdges(u).map(y=>y==null?Number.POSITIVE_INFINITY:d(y.w)-i.edge(y).minlen);var p=r(Math.min,h);return p===Number.POSITIVE_INFINITY&&(p=0),m.rank=p}i.sources().forEach(d)}function a(i,l){return i.node(l.w).rank-i.node(l.v).rank-i.edge(l).minlen}}),G8=Ar((e,t)=>{var r=Ai().Graph,s=jh().slack;t.exports=a;function a(u){var m=new r({directed:!1}),h=u.nodes()[0],p=u.nodeCount();m.setNode(h,{});for(var y,g;i(m,u)<p;)y=l(m,u),g=m.hasNode(y.v)?s(u,y):-s(u,y),d(m,u,g);return m}function i(u,m){function h(p){m.nodeEdges(p).forEach(y=>{var g=y.v,v=p===g?y.w:g;!u.hasNode(v)&&!s(m,y)&&(u.setNode(v,{}),u.setEdge(p,v,{}),h(v))})}return u.nodes().forEach(h),u.nodeCount()}function l(u,m){return m.edges().reduce((h,p)=>{let y=Number.POSITIVE_INFINITY;return u.hasNode(p.v)!==u.hasNode(p.w)&&(y=s(m,p)),y<h[0]?[y,p]:h},[Number.POSITIVE_INFINITY,null])[1]}function d(u,m,h){u.nodes().forEach(p=>m.node(p).rank+=h)}}),Pne=Ar((e,t)=>{var r=G8(),s=jh().slack,a=jh().longestPath,i=Ai().alg.preorder,l=Ai().alg.postorder,d=vs().simplify;t.exports=u,u.initLowLimValues=y,u.initCutValues=m,u.calcCutValue=p,u.leaveEdge=v,u.enterEdge=j,u.exchangeEdges=C;function u(T){T=d(T),a(T);var M=r(T);y(M),m(M,T);for(var D,I;D=v(M);)I=j(M,T,D),C(M,T,D,I)}function m(T,M){var D=l(T,T.nodes());D=D.slice(0,D.length-1),D.forEach(I=>h(T,M,I))}function h(T,M,D){var I=T.node(D),$=I.parent;T.edge(D,$).cutvalue=p(T,M,D)}function p(T,M,D){var I=T.node(D),$=I.parent,B=!0,R=M.edge(D,$),U=0;return R||(B=!1,R=M.edge($,D)),U=R.weight,M.nodeEdges(D).forEach(W=>{var F=W.v===D,L=F?W.w:W.v;if(L!==$){var z=F===B,E=M.edge(W).weight;if(U+=z?E:-E,N(T,D,L)){var _=T.edge(D,L).cutvalue;U+=z?-_:_}}}),U}function y(T,M){arguments.length<2&&(M=T.nodes()[0]),g(T,{},1,M)}function g(T,M,D,I,$){var B=D,R=T.node(I);return M[I]=!0,T.neighbors(I).forEach(U=>{Object.hasOwn(M,U)||(D=g(T,M,D,U,I))}),R.low=B,R.lim=D++,$?R.parent=$:delete R.parent,D}function v(T){return T.edges().find(M=>T.edge(M).cutvalue<0)}function j(T,M,D){var I=D.v,$=D.w;M.hasEdge(I,$)||(I=D.w,$=D.v);var B=T.node(I),R=T.node($),U=B,W=!1;B.lim>R.lim&&(U=R,W=!0);var F=M.edges().filter(L=>W===S(T,T.node(L.v),U)&&W!==S(T,T.node(L.w),U));return F.reduce((L,z)=>s(M,z)<s(M,L)?z:L)}function C(T,M,D,I){var $=D.v,B=D.w;T.removeEdge($,B),T.setEdge(I.v,I.w,{}),y(T),m(T,M),w(T,M)}function w(T,M){var D=T.nodes().find($=>!M.node($).parent),I=i(T,D);I=I.slice(1),I.forEach($=>{var B=T.node($).parent,R=M.edge($,B),U=!1;R||(R=M.edge(B,$),U=!0),M.node($).rank=M.node(B).rank+(U?R.minlen:-R.minlen)})}function N(T,M,D){return T.hasEdge(M,D)}function S(T,M,D){return D.low<=M.lim&&M.lim<=D.lim}}),One=Ar((e,t)=>{var r=jh(),s=r.longestPath,a=G8(),i=Pne();t.exports=l;function l(h){var p=h.graph().ranker;if(p instanceof Function)return p(h);switch(h.graph().ranker){case"network-simplex":m(h);break;case"tight-tree":u(h);break;case"longest-path":d(h);break;case"none":break;default:m(h)}}var d=s;function u(h){s(h),a(h)}function m(h){i(h)}}),_ne=Ar((e,t)=>{t.exports=r;function r(i){let l=a(i);i.graph().dummyChains.forEach(d=>{let u=i.node(d),m=u.edgeObj,h=s(i,l,m.v,m.w),p=h.path,y=h.lca,g=0,v=p[g],j=!0;for(;d!==m.w;){if(u=i.node(d),j){for(;(v=p[g])!==y&&i.node(v).maxRank<u.rank;)g++;v===y&&(j=!1)}if(!j){for(;g<p.length-1&&i.node(v=p[g+1]).minRank<=u.rank;)g++;v=p[g]}i.setParent(d,v),d=i.successors(d)[0]}})}function s(i,l,d,u){let m=[],h=[],p=Math.min(l[d].low,l[u].low),y=Math.max(l[d].lim,l[u].lim),g,v;g=d;do g=i.parent(g),m.push(g);while(g&&(l[g].low>p||y>l[g].lim));for(v=g,g=u;(g=i.parent(g))!==v;)h.push(g);return{path:m.concat(h.reverse()),lca:v}}function a(i){let l={},d=0;function u(m){let h=d;i.children(m).forEach(u),l[m]={low:h,lim:d++}}return i.children().forEach(u),l}}),zne=Ar((e,t)=>{var r=vs();t.exports={run:s,cleanup:d};function s(u){let m=r.addDummyNode(u,"root",{},"_root"),h=i(u),p=Object.values(h),y=r.applyWithChunking(Math.max,p)-1,g=2*y+1;u.graph().nestingRoot=m,u.edges().forEach(j=>u.edge(j).minlen*=g);let v=l(u)+1;u.children().forEach(j=>a(u,m,g,v,y,h,j)),u.graph().nodeRankFactor=g}function a(u,m,h,p,y,g,v){let j=u.children(v);if(!j.length){v!==m&&u.setEdge(m,v,{weight:0,minlen:h});return}let C=r.addBorderNode(u,"_bt"),w=r.addBorderNode(u,"_bb"),N=u.node(v);u.setParent(C,v),N.borderTop=C,u.setParent(w,v),N.borderBottom=w,j.forEach(S=>{a(u,m,h,p,y,g,S);let T=u.node(S),M=T.borderTop?T.borderTop:S,D=T.borderBottom?T.borderBottom:S,I=T.borderTop?p:2*p,$=M!==D?1:y-g[v]+1;u.setEdge(C,M,{weight:I,minlen:$,nestingEdge:!0}),u.setEdge(D,w,{weight:I,minlen:$,nestingEdge:!0})}),u.parent(v)||u.setEdge(m,C,{weight:0,minlen:y+g[v]})}function i(u){var m={};function h(p,y){var g=u.children(p);g&&g.length&&g.forEach(v=>h(v,y+1)),m[p]=y}return u.children().forEach(p=>h(p,1)),m}function l(u){return u.edges().reduce((m,h)=>m+u.edge(h).weight,0)}function d(u){var m=u.graph();u.removeNode(m.nestingRoot),delete m.nestingRoot,u.edges().forEach(h=>{var p=u.edge(h);p.nestingEdge&&u.removeEdge(h)})}}),$ne=Ar((e,t)=>{var r=vs();t.exports=s;function s(i){function l(d){let u=i.children(d),m=i.node(d);if(u.length&&u.forEach(l),Object.hasOwn(m,"minRank")){m.borderLeft=[],m.borderRight=[];for(let h=m.minRank,p=m.maxRank+1;h<p;++h)a(i,"borderLeft","_bl",d,m,h),a(i,"borderRight","_br",d,m,h)}}i.children().forEach(l)}function a(i,l,d,u,m,h){let p={width:0,height:0,rank:h,borderType:l},y=m[l][h-1],g=r.addDummyNode(i,"border",p,d);m[l][h]=g,i.setParent(g,u),y&&i.setEdge(y,g,{weight:1})}}),Bne=Ar((e,t)=>{t.exports={adjust:r,undo:s};function r(h){let p=h.graph().rankdir.toLowerCase();(p==="lr"||p==="rl")&&a(h)}function s(h){let p=h.graph().rankdir.toLowerCase();(p==="bt"||p==="rl")&&l(h),(p==="lr"||p==="rl")&&(u(h),a(h))}function a(h){h.nodes().forEach(p=>i(h.node(p))),h.edges().forEach(p=>i(h.edge(p)))}function i(h){let p=h.width;h.width=h.height,h.height=p}function l(h){h.nodes().forEach(p=>d(h.node(p))),h.edges().forEach(p=>{let y=h.edge(p);y.points.forEach(d),Object.hasOwn(y,"y")&&d(y)})}function d(h){h.y=-h.y}function u(h){h.nodes().forEach(p=>m(h.node(p))),h.edges().forEach(p=>{let y=h.edge(p);y.points.forEach(m),Object.hasOwn(y,"x")&&m(y)})}function m(h){let p=h.x;h.x=h.y,h.y=p}}),Hne=Ar((e,t)=>{var r=vs();t.exports=s;function s(a){let i={},l=a.nodes().filter(p=>!a.children(p).length),d=l.map(p=>a.node(p).rank),u=r.applyWithChunking(Math.max,d),m=r.range(u+1).map(()=>[]);function h(p){if(i[p])return;i[p]=!0;let y=a.node(p);m[y.rank].push(p),a.successors(p).forEach(h)}return l.sort((p,y)=>a.node(p).rank-a.node(y).rank).forEach(h),m}}),Fne=Ar((e,t)=>{var r=vs().zipObject;t.exports=s;function s(i,l){let d=0;for(let u=1;u<l.length;++u)d+=a(i,l[u-1],l[u]);return d}function a(i,l,d){let u=r(d,d.map((v,j)=>j)),m=l.flatMap(v=>i.outEdges(v).map(j=>({pos:u[j.w],weight:i.edge(j).weight})).sort((j,C)=>j.pos-C.pos)),h=1;for(;h<d.length;)h<<=1;let p=2*h-1;h-=1;let y=new Array(p).fill(0),g=0;return m.forEach(v=>{let j=v.pos+h;y[j]+=v.weight;let C=0;for(;j>0;)j%2&&(C+=y[j+1]),j=j-1>>1,y[j]+=v.weight;g+=v.weight*C}),g}}),qne=Ar((e,t)=>{t.exports=r;function r(s,a=[]){return a.map(i=>{let l=s.inEdges(i);if(l.length){let d=l.reduce((u,m)=>{let h=s.edge(m),p=s.node(m.v);return{sum:u.sum+h.weight*p.order,weight:u.weight+h.weight}},{sum:0,weight:0});return{v:i,barycenter:d.sum/d.weight,weight:d.weight}}else return{v:i}})}}),Une=Ar((e,t)=>{var r=vs();t.exports=s;function s(l,d){let u={};l.forEach((h,p)=>{let y=u[h.v]={indegree:0,in:[],out:[],vs:[h.v],i:p};h.barycenter!==void 0&&(y.barycenter=h.barycenter,y.weight=h.weight)}),d.edges().forEach(h=>{let p=u[h.v],y=u[h.w];p!==void 0&&y!==void 0&&(y.indegree++,p.out.push(u[h.w]))});let m=Object.values(u).filter(h=>!h.indegree);return a(m)}function a(l){let d=[];function u(h){return p=>{p.merged||(p.barycenter===void 0||h.barycenter===void 0||p.barycenter>=h.barycenter)&&i(h,p)}}function m(h){return p=>{p.in.push(h),--p.indegree===0&&l.push(p)}}for(;l.length;){let h=l.pop();d.push(h),h.in.reverse().forEach(u(h)),h.out.forEach(m(h))}return d.filter(h=>!h.merged).map(h=>r.pick(h,["vs","i","barycenter","weight"]))}function i(l,d){let u=0,m=0;l.weight&&(u+=l.barycenter*l.weight,m+=l.weight),d.weight&&(u+=d.barycenter*d.weight,m+=d.weight),l.vs=d.vs.concat(l.vs),l.barycenter=u/m,l.weight=m,l.i=Math.min(d.i,l.i),d.merged=!0}}),Vne=Ar((e,t)=>{var r=vs();t.exports=s;function s(l,d){let u=r.partition(l,C=>Object.hasOwn(C,"barycenter")),m=u.lhs,h=u.rhs.sort((C,w)=>w.i-C.i),p=[],y=0,g=0,v=0;m.sort(i(!!d)),v=a(p,h,v),m.forEach(C=>{v+=C.vs.length,p.push(C.vs),y+=C.barycenter*C.weight,g+=C.weight,v=a(p,h,v)});let j={vs:p.flat(!0)};return g&&(j.barycenter=y/g,j.weight=g),j}function a(l,d,u){let m;for(;d.length&&(m=d[d.length-1]).i<=u;)d.pop(),l.push(m.vs),u++;return u}function i(l){return(d,u)=>d.barycenter<u.barycenter?-1:d.barycenter>u.barycenter?1:l?u.i-d.i:d.i-u.i}}),Kne=Ar((e,t)=>{var r=qne(),s=Une(),a=Vne();t.exports=i;function i(u,m,h,p){let y=u.children(m),g=u.node(m),v=g?g.borderLeft:void 0,j=g?g.borderRight:void 0,C={};v&&(y=y.filter(T=>T!==v&&T!==j));let w=r(u,y);w.forEach(T=>{if(u.children(T.v).length){let M=i(u,T.v,h,p);C[T.v]=M,Object.hasOwn(M,"barycenter")&&d(T,M)}});let N=s(w,h);l(N,C);let S=a(N,p);if(v&&(S.vs=[v,S.vs,j].flat(!0),u.predecessors(v).length)){let T=u.node(u.predecessors(v)[0]),M=u.node(u.predecessors(j)[0]);Object.hasOwn(S,"barycenter")||(S.barycenter=0,S.weight=0),S.barycenter=(S.barycenter*S.weight+T.order+M.order)/(S.weight+2),S.weight+=2}return S}function l(u,m){u.forEach(h=>{h.vs=h.vs.flatMap(p=>m[p]?m[p].vs:p)})}function d(u,m){u.barycenter!==void 0?(u.barycenter=(u.barycenter*u.weight+m.barycenter*m.weight)/(u.weight+m.weight),u.weight+=m.weight):(u.barycenter=m.barycenter,u.weight=m.weight)}}),Wne=Ar((e,t)=>{var r=Ai().Graph,s=vs();t.exports=a;function a(l,d,u,m){m||(m=l.nodes());let h=i(l),p=new r({compound:!0}).setGraph({root:h}).setDefaultNodeLabel(y=>l.node(y));return m.forEach(y=>{let g=l.node(y),v=l.parent(y);(g.rank===d||g.minRank<=d&&d<=g.maxRank)&&(p.setNode(y),p.setParent(y,v||h),l[u](y).forEach(j=>{let C=j.v===y?j.w:j.v,w=p.edge(C,y),N=w!==void 0?w.weight:0;p.setEdge(C,y,{weight:l.edge(j).weight+N})}),Object.hasOwn(g,"minRank")&&p.setNode(y,{borderLeft:g.borderLeft[d],borderRight:g.borderRight[d]}))}),p}function i(l){for(var d;l.hasNode(d=s.uniqueId("_root")););return d}}),Gne=Ar((e,t)=>{t.exports=r;function r(s,a,i){let l={},d;i.forEach(u=>{let m=s.parent(u),h,p;for(;m;){if(h=s.parent(m),h?(p=l[h],l[h]=m):(p=d,d=m),p&&p!==m){a.setEdge(p,m);return}m=h}})}}),Yne=Ar((e,t)=>{var r=Hne(),s=Fne(),a=Kne(),i=Wne(),l=Gne(),d=Ai().Graph,u=vs();t.exports=m;function m(g,v={}){if(typeof v.customOrder=="function"){v.customOrder(g,m);return}let j=u.maxRank(g),C=h(g,u.range(1,j+1),"inEdges"),w=h(g,u.range(j-1,-1,-1),"outEdges"),N=r(g);if(y(g,N),v.disableOptimalOrderHeuristic)return;let S=Number.POSITIVE_INFINITY,T,M=v.constraints||[];for(let D=0,I=0;I<4;++D,++I){p(D%2?C:w,D%4>=2,M),N=u.buildLayerMatrix(g);let $=s(g,N);$<S?(I=0,T=Object.assign({},N),S=$):$===S&&(T=structuredClone(N))}y(g,T)}function h(g,v,j){let C=new Map,w=(N,S)=>{C.has(N)||C.set(N,[]),C.get(N).push(S)};for(let N of g.nodes()){let S=g.node(N);if(typeof S.rank=="number"&&w(S.rank,N),typeof S.minRank=="number"&&typeof S.maxRank=="number")for(let T=S.minRank;T<=S.maxRank;T++)T!==S.rank&&w(T,N)}return v.map(function(N){return i(g,N,j,C.get(N)||[])})}function p(g,v,j){let C=new d;g.forEach(function(w){j.forEach(T=>C.setEdge(T.left,T.right));let N=w.graph().root,S=a(w,N,C,v);S.vs.forEach((T,M)=>w.node(T).order=M),l(w,C,S.vs)})}function y(g,v){Object.values(v).forEach(j=>j.forEach((C,w)=>g.node(C).order=w))}}),Xne=Ar((e,t)=>{var r=Ai().Graph,s=vs();t.exports={positionX:j,findType1Conflicts:a,findType2Conflicts:i,addConflict:d,hasConflict:u,verticalAlignment:m,horizontalCompaction:h,alignCoordinates:g,findSmallestWidthAlignment:y,balance:v};function a(N,S){let T={};function M(D,I){let $=0,B=0,R=D.length,U=I[I.length-1];return I.forEach((W,F)=>{let L=l(N,W),z=L?N.node(L).order:R;(L||W===U)&&(I.slice(B,F+1).forEach(E=>{N.predecessors(E).forEach(_=>{let G=N.node(_),V=G.order;(V<$||z<V)&&!(G.dummy&&N.node(E).dummy)&&d(T,_,E)})}),B=F+1,$=z)}),I}return S.length&&S.reduce(M),T}function i(N,S){let T={};function M(I,$,B,R,U){let W;s.range($,B).forEach(F=>{W=I[F],N.node(W).dummy&&N.predecessors(W).forEach(L=>{let z=N.node(L);z.dummy&&(z.order<R||z.order>U)&&d(T,L,W)})})}function D(I,$){let B=-1,R,U=0;return $.forEach((W,F)=>{if(N.node(W).dummy==="border"){let L=N.predecessors(W);L.length&&(R=N.node(L[0]).order,M($,U,F,B,R),U=F,B=R)}M($,U,$.length,R,I.length)}),$}return S.length&&S.reduce(D),T}function l(N,S){if(N.node(S).dummy)return N.predecessors(S).find(T=>N.node(T).dummy)}function d(N,S,T){if(S>T){let D=S;S=T,T=D}let M=N[S];M||(N[S]=M={}),M[T]=!0}function u(N,S,T){if(S>T){let M=S;S=T,T=M}return!!N[S]&&Object.hasOwn(N[S],T)}function m(N,S,T,M){let D={},I={},$={};return S.forEach(B=>{B.forEach((R,U)=>{D[R]=R,I[R]=R,$[R]=U})}),S.forEach(B=>{let R=-1;B.forEach(U=>{let W=M(U);if(W.length){W=W.sort((L,z)=>$[L]-$[z]);let F=(W.length-1)/2;for(let L=Math.floor(F),z=Math.ceil(F);L<=z;++L){let E=W[L];I[U]===U&&R<$[E]&&!u(T,U,E)&&(I[E]=U,I[U]=D[U]=D[E],R=$[E])}}})}),{root:D,align:I}}function h(N,S,T,M,D){let I={},$=p(N,S,T,D),B=D?"borderLeft":"borderRight";function R(F,L){let z=$.nodes().slice(),E={},_=z.pop();for(;_;){if(E[_])F(_);else{E[_]=!0,z.push(_);for(let G of L(_))z.push(G)}_=z.pop()}}function U(F){I[F]=$.inEdges(F).reduce((L,z)=>Math.max(L,I[z.v]+$.edge(z)),0)}function W(F){let L=$.outEdges(F).reduce((E,_)=>Math.min(E,I[_.w]-$.edge(_)),Number.POSITIVE_INFINITY),z=N.node(F);L!==Number.POSITIVE_INFINITY&&z.borderType!==B&&(I[F]=Math.max(I[F],L))}return R(U,$.predecessors.bind($)),R(W,$.successors.bind($)),Object.keys(M).forEach(F=>I[F]=I[T[F]]),I}function p(N,S,T,M){let D=new r,I=N.graph(),$=C(I.nodesep,I.edgesep,M);return S.forEach(B=>{let R;B.forEach(U=>{let W=T[U];if(D.setNode(W),R){var F=T[R],L=D.edge(F,W);D.setEdge(F,W,Math.max($(N,U,R),L||0))}R=U})}),D}function y(N,S){return Object.values(S).reduce((T,M)=>{let D=Number.NEGATIVE_INFINITY,I=Number.POSITIVE_INFINITY;Object.entries(M).forEach(([B,R])=>{let U=w(N,B)/2;D=Math.max(R+U,D),I=Math.min(R-U,I)});let $=D-I;return $<T[0]&&(T=[$,M]),T},[Number.POSITIVE_INFINITY,null])[1]}function g(N,S){let T=Object.values(S),M=s.applyWithChunking(Math.min,T),D=s.applyWithChunking(Math.max,T);["u","d"].forEach(I=>{["l","r"].forEach($=>{let B=I+$,R=N[B];if(R===S)return;let U=Object.values(R),W=M-s.applyWithChunking(Math.min,U);$!=="l"&&(W=D-s.applyWithChunking(Math.max,U)),W&&(N[B]=s.mapValues(R,F=>F+W))})})}function v(N,S){return s.mapValues(N.ul,(T,M)=>{if(S)return N[S.toLowerCase()][M];{let D=Object.values(N).map(I=>I[M]).sort((I,$)=>I-$);return(D[1]+D[2])/2}})}function j(N){let S=s.buildLayerMatrix(N),T=Object.assign(a(N,S),i(N,S)),M={},D;["u","d"].forEach($=>{D=$==="u"?S:Object.values(S).reverse(),["l","r"].forEach(B=>{B==="r"&&(D=D.map(F=>Object.values(F).reverse()));let R=($==="u"?N.predecessors:N.successors).bind(N),U=m(N,D,T,R),W=h(N,D,U.root,U.align,B==="r");B==="r"&&(W=s.mapValues(W,F=>-F)),M[$+B]=W})});let I=y(N,M);return g(M,I),v(M,N.graph().align)}function C(N,S,T){return(M,D,I)=>{let $=M.node(D),B=M.node(I),R=0,U;if(R+=$.width/2,Object.hasOwn($,"labelpos"))switch($.labelpos.toLowerCase()){case"l":U=-$.width/2;break;case"r":U=$.width/2;break}if(U&&(R+=T?U:-U),U=0,R+=($.dummy?S:N)/2,R+=(B.dummy?S:N)/2,R+=B.width/2,Object.hasOwn(B,"labelpos"))switch(B.labelpos.toLowerCase()){case"l":U=B.width/2;break;case"r":U=-B.width/2;break}return U&&(R+=T?U:-U),U=0,R}}function w(N,S){return N.node(S).width}}),Qne=Ar((e,t)=>{var r=vs(),s=Xne().positionX;t.exports=a;function a(l){l=r.asNonCompoundGraph(l),i(l),Object.entries(s(l)).forEach(([d,u])=>l.node(d).x=u)}function i(l){let d=r.buildLayerMatrix(l),u=l.graph().ranksep,m=l.graph().rankalign,h=0;d.forEach(p=>{let y=p.reduce((g,v)=>{let j=l.node(v).height;return g>j?g:j},0);p.forEach(g=>{let v=l.node(g);m==="top"?v.y=h+v.height/2:m==="bottom"?v.y=h+y-v.height/2:v.y=h+y/2}),h+=y+u})}}),Zne=Ar((e,t)=>{var r=Ine(),s=Lne(),a=One(),i=vs().normalizeRanks,l=_ne(),d=vs().removeEmptyRanks,u=zne(),m=$ne(),h=Bne(),p=Yne(),y=Qne(),g=vs(),v=Ai().Graph;t.exports=j;function j(Y,ee={}){let ae=ee.debugTiming?g.time:g.notime;return ae("layout",()=>{let Q=ae(" buildLayoutGraph",()=>R(Y));return ae(" runLayout",()=>C(Q,ae,ee)),ae(" updateInputGraph",()=>w(Y,Q)),Q})}function C(Y,ee,ae){ee(" makeSpaceForEdgeLabels",()=>U(Y)),ee(" removeSelfEdges",()=>O(Y)),ee(" acyclic",()=>r.run(Y)),ee(" nestingGraph.run",()=>u.run(Y)),ee(" rank",()=>a(g.asNonCompoundGraph(Y))),ee(" injectEdgeLabelProxies",()=>W(Y)),ee(" removeEmptyRanks",()=>d(Y)),ee(" nestingGraph.cleanup",()=>u.cleanup(Y)),ee(" normalizeRanks",()=>i(Y)),ee(" assignRankMinMax",()=>F(Y)),ee(" removeEdgeLabelProxies",()=>L(Y)),ee(" normalize.run",()=>s.run(Y)),ee(" parentDummyChains",()=>l(Y)),ee(" addBorderSegments",()=>m(Y)),ee(" order",()=>p(Y,ae)),ee(" insertSelfEdges",()=>q(Y)),ee(" adjustCoordinateSystem",()=>h.adjust(Y)),ee(" position",()=>y(Y)),ee(" positionSelfEdges",()=>J(Y)),ee(" removeBorderNodes",()=>V(Y)),ee(" normalize.undo",()=>s.undo(Y)),ee(" fixupEdgeLabelCoords",()=>_(Y)),ee(" undoCoordinateSystem",()=>h.undo(Y)),ee(" translateGraph",()=>z(Y)),ee(" assignNodeIntersects",()=>E(Y)),ee(" reversePoints",()=>G(Y)),ee(" acyclic.undo",()=>r.undo(Y))}function w(Y,ee){Y.nodes().forEach(ae=>{let Q=Y.node(ae),me=ee.node(ae);Q&&(Q.x=me.x,Q.y=me.y,Q.order=me.order,Q.rank=me.rank,ee.children(ae).length&&(Q.width=me.width,Q.height=me.height))}),Y.edges().forEach(ae=>{let Q=Y.edge(ae),me=ee.edge(ae);Q.points=me.points,Object.hasOwn(me,"x")&&(Q.x=me.x,Q.y=me.y)}),Y.graph().width=ee.graph().width,Y.graph().height=ee.graph().height}var N=["nodesep","edgesep","ranksep","marginx","marginy"],S={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb",rankalign:"center"},T=["acyclicer","ranker","rankdir","align","rankalign"],M=["width","height","rank"],D={width:0,height:0},I=["minlen","weight","width","height","labeloffset"],$={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},B=["labelpos"];function R(Y){let ee=new v({multigraph:!0,compound:!0}),ae=Z(Y.graph());return ee.setGraph(Object.assign({},S,H(ae,N),g.pick(ae,T))),Y.nodes().forEach(Q=>{let me=Z(Y.node(Q)),Ae=H(me,M);Object.keys(D).forEach(Me=>{Ae[Me]===void 0&&(Ae[Me]=D[Me])}),ee.setNode(Q,Ae),ee.setParent(Q,Y.parent(Q))}),Y.edges().forEach(Q=>{let me=Z(Y.edge(Q));ee.setEdge(Q,Object.assign({},$,H(me,I),g.pick(me,B)))}),ee}function U(Y){let ee=Y.graph();ee.ranksep/=2,Y.edges().forEach(ae=>{let Q=Y.edge(ae);Q.minlen*=2,Q.labelpos.toLowerCase()!=="c"&&(ee.rankdir==="TB"||ee.rankdir==="BT"?Q.width+=Q.labeloffset:Q.height+=Q.labeloffset)})}function W(Y){Y.edges().forEach(ee=>{let ae=Y.edge(ee);if(ae.width&&ae.height){let Q=Y.node(ee.v),me={rank:(Y.node(ee.w).rank-Q.rank)/2+Q.rank,e:ee};g.addDummyNode(Y,"edge-proxy",me,"_ep")}})}function F(Y){let ee=0;Y.nodes().forEach(ae=>{let Q=Y.node(ae);Q.borderTop&&(Q.minRank=Y.node(Q.borderTop).rank,Q.maxRank=Y.node(Q.borderBottom).rank,ee=Math.max(ee,Q.maxRank))}),Y.graph().maxRank=ee}function L(Y){Y.nodes().forEach(ee=>{let ae=Y.node(ee);ae.dummy==="edge-proxy"&&(Y.edge(ae.e).labelRank=ae.rank,Y.removeNode(ee))})}function z(Y){let ee=Number.POSITIVE_INFINITY,ae=0,Q=Number.POSITIVE_INFINITY,me=0,Ae=Y.graph(),Me=Ae.marginx||0,He=Ae.marginy||0;function je(xe){let Pe=xe.x,Ce=xe.y,Ye=xe.width,Qe=xe.height;ee=Math.min(ee,Pe-Ye/2),ae=Math.max(ae,Pe+Ye/2),Q=Math.min(Q,Ce-Qe/2),me=Math.max(me,Ce+Qe/2)}Y.nodes().forEach(xe=>je(Y.node(xe))),Y.edges().forEach(xe=>{let Pe=Y.edge(xe);Object.hasOwn(Pe,"x")&&je(Pe)}),ee-=Me,Q-=He,Y.nodes().forEach(xe=>{let Pe=Y.node(xe);Pe.x-=ee,Pe.y-=Q}),Y.edges().forEach(xe=>{let Pe=Y.edge(xe);Pe.points.forEach(Ce=>{Ce.x-=ee,Ce.y-=Q}),Object.hasOwn(Pe,"x")&&(Pe.x-=ee),Object.hasOwn(Pe,"y")&&(Pe.y-=Q)}),Ae.width=ae-ee+Me,Ae.height=me-Q+He}function E(Y){Y.edges().forEach(ee=>{let ae=Y.edge(ee),Q=Y.node(ee.v),me=Y.node(ee.w),Ae,Me;ae.points?(Ae=ae.points[0],Me=ae.points[ae.points.length-1]):(ae.points=[],Ae=me,Me=Q),ae.points.unshift(g.intersectRect(Q,Ae)),ae.points.push(g.intersectRect(me,Me))})}function _(Y){Y.edges().forEach(ee=>{let ae=Y.edge(ee);if(Object.hasOwn(ae,"x"))switch((ae.labelpos==="l"||ae.labelpos==="r")&&(ae.width-=ae.labeloffset),ae.labelpos){case"l":ae.x-=ae.width/2+ae.labeloffset;break;case"r":ae.x+=ae.width/2+ae.labeloffset;break}})}function G(Y){Y.edges().forEach(ee=>{let ae=Y.edge(ee);ae.reversed&&ae.points.reverse()})}function V(Y){Y.nodes().forEach(ee=>{if(Y.children(ee).length){let ae=Y.node(ee),Q=Y.node(ae.borderTop),me=Y.node(ae.borderBottom),Ae=Y.node(ae.borderLeft[ae.borderLeft.length-1]),Me=Y.node(ae.borderRight[ae.borderRight.length-1]);ae.width=Math.abs(Me.x-Ae.x),ae.height=Math.abs(me.y-Q.y),ae.x=Ae.x+ae.width/2,ae.y=Q.y+ae.height/2}}),Y.nodes().forEach(ee=>{Y.node(ee).dummy==="border"&&Y.removeNode(ee)})}function O(Y){Y.edges().forEach(ee=>{if(ee.v===ee.w){var ae=Y.node(ee.v);ae.selfEdges||(ae.selfEdges=[]),ae.selfEdges.push({e:ee,label:Y.edge(ee)}),Y.removeEdge(ee)}})}function q(Y){var ee=g.buildLayerMatrix(Y);ee.forEach(ae=>{var Q=0;ae.forEach((me,Ae)=>{var Me=Y.node(me);Me.order=Ae+Q,(Me.selfEdges||[]).forEach(He=>{g.addDummyNode(Y,"selfedge",{width:He.label.width,height:He.label.height,rank:Me.rank,order:Ae+ ++Q,e:He.e,label:He.label},"_se")}),delete Me.selfEdges})})}function J(Y){Y.nodes().forEach(ee=>{var ae=Y.node(ee);if(ae.dummy==="selfedge"){var Q=Y.node(ae.e.v),me=Q.x+Q.width/2,Ae=Q.y,Me=ae.x-me,He=Q.height/2;Y.setEdge(ae.e,ae.label),Y.removeNode(ee),ae.label.points=[{x:me+2*Me/3,y:Ae-He},{x:me+5*Me/6,y:Ae-He},{x:me+Me,y:Ae},{x:me+5*Me/6,y:Ae+He},{x:me+2*Me/3,y:Ae+He}],ae.label.x=ae.x,ae.label.y=ae.y}})}function H(Y,ee){return g.mapValues(g.pick(Y,ee),Number)}function Z(Y){var ee={};return Y&&Object.entries(Y).forEach(([ae,Q])=>{typeof ae=="string"&&(ae=ae.toLowerCase()),ee[ae]=Q}),ee}}),Jne=Ar((e,t)=>{var r=vs(),s=Ai().Graph;t.exports={debugOrdering:a};function a(i){let l=r.buildLayerMatrix(i),d=new s({compound:!0,multigraph:!0}).setGraph({});return i.nodes().forEach(u=>{d.setNode(u,{label:u}),d.setParent(u,"layer"+i.node(u).rank)}),i.edges().forEach(u=>d.setEdge(u.v,u.w,{},u.name)),l.forEach((u,m)=>{let h="layer"+m;d.setNode(h,{rank:"same"}),u.reduce((p,y)=>(d.setEdge(p,y,{style:"invis"}),y))}),d}}),ere=Ar((e,t)=>{t.exports="2.0.4"}),tre=Ar((e,t)=>{t.exports={graphlib:Ai(),layout:Zne(),debug:Jne(),util:{time:vs().time,notime:vs().notime},version:ere()}});const h3=tre();const p3={pending:{bg:"bg-blue-500/10",border:"border-blue-500/30",text:"text-blue-500"},in_progress:{bg:"bg-amber-500/10",border:"border-amber-500/30",text:"text-amber-600"},blocked:{bg:"bg-red-500/8",border:"border-red-500/25",text:"text-red-500"},review:{bg:"bg-brand-500/10",border:"border-brand-500/30",text:"text-brand-500"},completed:{bg:"bg-green-500/10",border:"border-green-500/30",text:"text-green-600"},failed:{bg:"bg-red-500/10",border:"border-red-500/30",text:"text-red-500"},rejected:{bg:"bg-red-500/8",border:"border-red-500/25",text:"text-red-500"},cancelled:{bg:"bg-gray-500/8",border:"border-gray-500/20",text:"text-fg-tertiary"},archived:{bg:"bg-gray-500/5",border:"border-gray-500/15",text:"text-fg-tertiary"}},nre={critical:"bg-red-500",high:"bg-amber-500",medium:"bg-amber-500",low:"bg-blue-500"};function rre({data:e}){const{t}=ft(["work","common"]),{task:r,agentName:s,selected:a,direction:i="TB",isExpandedRoot:l,onCollapse:d}=e,u=p3[r.status]??p3.pending,m=r.taskType==="scheduled"&&!!r.scheduleConfig,h=m?r.scheduleConfig.every?t("work:task.everyInterval",{interval:r.scheduleConfig.every}):r.scheduleConfig.cron?t("work:task.cronLabel"):"":"",p=i==="LR"?Zt.Left:Zt.Top,y=i==="LR"?Zt.Right:Zt.Bottom;return n.jsxs("div",{className:`relative rounded-lg border px-3 py-2 min-w-[180px] max-w-[220px] shadow-md backdrop-blur-sm ${m?`${u.bg} border-blue-500/40 ring-1 ring-blue-500/20`:`${u.bg} ${u.border}`} ${a?"ring-2 ring-brand-500 shadow-brand-500/25 shadow-lg":""}`,children:[n.jsx(Cl,{type:"target",position:p,className:"!bg-border-default !w-2 !h-2"}),n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${nre[r.priority]??"bg-gray-500"}`}),n.jsx("span",{className:`text-[10px] font-medium uppercase tracking-wider ${u.text}`,children:t(`work:status.task.${r.status}`,{defaultValue:r.status.replace("_"," ")})}),m&&n.jsxs("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/15 text-blue-600 ml-auto whitespace-nowrap inline-flex items-center gap-0.5",children:[n.jsx("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"})}),h]})]}),n.jsx("div",{className:"text-xs font-medium text-fg-primary leading-snug line-clamp-2 mb-1",children:r.title}),s&&n.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:s}),r.blockedBy&&r.blockedBy.length>0&&n.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:t("work:dag.depCount",{count:r.blockedBy.length})}),n.jsx(Cl,{type:"source",position:y,className:"!bg-border-default !w-2 !h-2"}),l&&d&&n.jsx("button",{onClick:g=>{g.stopPropagation(),d()},className:"absolute top-1/2 -translate-y-1/2 -right-7 w-5 h-5 rounded-full bg-surface-secondary border border-border-default flex items-center justify-center text-fg-tertiary hover:text-fg-primary hover:bg-surface-overlay transition-colors shadow-sm",title:t("work:dag.backToOverview"),children:n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})})]})}const g3={pending:{bg:"bg-amber-500/10",border:"border-amber-500/30",text:"text-amber-600"},in_progress:{bg:"bg-brand-500/10",border:"border-brand-500/30",text:"text-brand-500"},completed:{bg:"bg-green-500/10",border:"border-green-500/30",text:"text-green-600"},rejected:{bg:"bg-red-500/10",border:"border-red-500/30",text:"text-red-500"},cancelled:{bg:"bg-gray-500/8",border:"border-gray-500/20",text:"text-fg-tertiary"}},x3={pending:"todo",in_progress:"in_progress",completed:"done",rejected:"done",cancelled:"done",archived:"done"};function sre({data:e}){const{t}=ft(["work","common"]),{req:r,selected:s,direction:a="TB",isExpandedRoot:i,onCollapse:l}=e,d=g3[r.status]??g3.pending,u=a==="LR"?Zt.Left:Zt.Top,m=a==="LR"?Zt.Right:Zt.Bottom;return n.jsxs("div",{className:`relative rounded-lg border-2 border-dashed px-3 py-2 min-w-[180px] max-w-[220px] shadow-lg ${d.bg} ${d.border} ${s?"ring-2 ring-brand-500 shadow-brand-500/25":""}`,children:[n.jsx(Cl,{type:"target",position:u,className:"!bg-border-default !w-2 !h-2"}),n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded font-semibold bg-amber-500/15 text-amber-600",children:t("work:dag.reqLabel")}),n.jsx("span",{className:`text-[10px] font-medium uppercase tracking-wider ${d.text}`,children:t(`work:status.requirement.${r.status}`,{defaultValue:r.status.replace("_"," ")})})]}),n.jsx("div",{className:"text-xs font-medium text-fg-primary leading-snug line-clamp-2 mb-1",children:r.title}),r.taskIds.length>0&&n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:t("work:dag.taskCount",{count:r.taskIds.length})}),n.jsx(Cl,{type:"source",position:m,className:"!bg-border-default !w-2 !h-2"}),i&&l&&n.jsx("button",{onClick:h=>{h.stopPropagation(),l()},className:"absolute top-1/2 -translate-y-1/2 -right-7 w-5 h-5 rounded-full bg-surface-secondary border border-border-default flex items-center justify-center text-fg-tertiary hover:text-fg-primary hover:bg-surface-overlay transition-colors shadow-sm",title:t("work:dag.backToOverview"),children:n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})})]})}const are={task:rre,requirement:sre};function ire({nodeIds:e,rfRef:t}){const r=ene();return x.useEffect(()=>{if(e.length===0)return;const s=setTimeout(()=>{r(e),requestAnimationFrame(()=>{t.current?.fitView({padding:.2})})},300);return()=>clearTimeout(s)},[e.length]),null}const ore=()=>document.documentElement.classList.contains("light")||!document.documentElement.classList.contains("dark")&&!document.documentElement.classList.contains("cyberpunk")&&!document.documentElement.classList.contains("mono")&&window.matchMedia("(prefers-color-scheme: light)").matches,lre=e=>{const t=new MutationObserver(e);t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const r=window.matchMedia("(prefers-color-scheme: light)");return r.addEventListener("change",e),()=>{t.disconnect(),r.removeEventListener("change",e)}};function cre(){return x.useSyncExternalStore(lre,ore,()=>!1)}const qf=200,Uf=80;function b3(e,t,r="TB"){const s=i=>{const l=new h3.graphlib.Graph;l.setDefaultEdgeLabel(()=>({})),l.setGraph({rankdir:i,nodesep:40,ranksep:60});for(const d of e)l.setNode(d.id,{width:qf,height:Uf});for(const d of t)l.setEdge(d.source,d.target);return h3.layout(l),e.map(d=>{const u=l.node(d.id);return{...d,position:{x:(u?.x??0)-qf/2,y:(u?.y??0)-Uf/2}}})},a=s(r);if(t.length>0&&e.length>4){let i=1/0,l=-1/0,d=1/0,u=-1/0;for(const y of a)i=Math.min(i,y.position.x),l=Math.max(l,y.position.x+qf),d=Math.min(d,y.position.y),u=Math.max(u,y.position.y+Uf);const m=l-i,h=u-d,p=r==="TB"?"LR":"TB";if(m>h*3)return{nodes:s(p),direction:p}}return{nodes:a,direction:r}}function dre(e,t){const r=new Map,s=new Map;for(const l of e)s.set(l.id,l),r.set(l.id,new Set);for(const l of t)r.get(l.source)?.add(l.target),r.get(l.target)?.add(l.source);const a=new Set,i=[];for(const l of e){if(a.has(l.id))continue;const d=new Set,u=[l.id];for(;u.length>0;){const m=u.pop();if(!a.has(m)){a.add(m),d.add(m);for(const h of r.get(m)??[])a.has(h)||u.push(h)}}i.push({nodes:e.filter(m=>d.has(m.id)),edges:t.filter(m=>d.has(m.source)&&d.has(m.target))})}return i}function y3(e,t){if(e.length===0)return{nodes:[],direction:"TB"};const r=dre(e,t);if(r.length===1)return b3(e,t);let s="TB";const a=r.map(y=>{const{nodes:g,direction:v}=b3(y.nodes,y.edges);s=v;let j=1/0,C=-1/0,w=1/0,N=-1/0;for(const S of g)j=Math.min(j,S.position.x),C=Math.max(C,S.position.x+qf),w=Math.min(w,S.position.y),N=Math.max(N,S.position.y+Uf);for(const S of g)S.position.x-=j,S.position.y-=w;return{nodes:g,w:C-j,h:N-w}});a.sort((y,g)=>g.h-y.h);const i=60,l=a.reduce((y,g)=>y+(g.w+i)*(g.h+i),0),d=Math.sqrt(l)*1.1,u=[];let m=0,h=0,p=0;for(const y of a){m>0&&m+y.w>d&&(m=0,h+=p+i,p=0);for(const g of y.nodes)u.push({...g,position:{x:g.position.x+m,y:g.position.y+h}});m+=y.w+i,p=Math.max(p,y.h)}return{nodes:u,direction:s}}function ure(e,t,r){const s=new Set,a=[t];for(;a.length>0;){const i=a.pop();if(i===r)return!0;if(s.has(i))continue;s.add(i);const l=e.get(i);if(l?.blockedBy)for(const d of l.blockedBy)a.push(d)}return!1}const fd=[{id:"todo",statuses:new Set(["pending"]),color:{bg:"bg-blue-500/10",border:"border-blue-500/30",text:"text-blue-500"}},{id:"in_progress",statuses:new Set(["in_progress","blocked"]),color:{bg:"bg-amber-500/10",border:"border-amber-500/30",text:"text-amber-600"}},{id:"review",statuses:new Set(["review"]),color:{bg:"bg-brand-500/10",border:"border-brand-500/30",text:"text-brand-500"}},{id:"done",statuses:new Set(["completed","failed","rejected","cancelled","archived"]),color:{bg:"bg-green-500/10",border:"border-green-500/30",text:"text-green-600"}}];new Set(fd.map(e=>e.id));const Nf=new Set(fd.filter(e=>e.id!=="done").map(e=>e.id)),v3=e=>e.status==="archived";function mre(e,t,r,s){const a=new Set,i=[e];for(;i.length>0;){const l=i.pop();if(!a.has(l))if(a.add(l),l.startsWith("req-")){const d=r.get(l.slice(4));if(d)for(const u of d.taskIds)i.push(u)}else{const d=t.get(l);if(d?.blockedBy)for(const u of d.blockedBy)i.push(u);d?.requirementId&&i.push(`req-${d.requirementId}`)}}for(const l of s)l.requirementId&&a.has(l.id)&&a.add(`req-${l.requirementId}`);return a}function fre({tasks:e,requirements:t=[],agents:r,showArchived:s,onShowArchivedChange:a,onTaskClick:i,onReqClick:l,onCollapseDAG:d,onDependencyChange:u,selectedTaskId:m,selectedReqId:h,hasDetailPanel:p,defaultExpandedNodeId:y,previewMode:g}){const{t:v}=ft(["work","common"]),j=cre(),[C,w]=x.useState(null),[N,S]=x.useState(null),[T,M]=x.useState(()=>new Set(Nf)),[D,I]=x.useState(y??null),[$,B]=x.useState(s??!1),R=s??$,U=x.useCallback(te=>{const de=typeof te=="function"?te(R):te;B(de),a?.(de)},[R,a]);x.useEffect(()=>{s!==void 0&&B(s)},[s]),x.useEffect(()=>{y&&I(y)},[y]);const W=x.useMemo(()=>e.filter(te=>v3(te)).length,[e]),F=x.useMemo(()=>{const te=new Set;for(const de of fd)if(T.has(de.id))for(const be of de.statuses)te.add(be);return te},[T]),L=x.useMemo(()=>{const te=new Set;for(const de of e)for(const be of fd)if(be.statuses.has(de.status)){te.add(be.id);break}for(const de of t){const be=x3[de.status];be&&te.add(be)}return fd.filter(de=>te.has(de.id))},[e,t]),z=x.useCallback(te=>{M(de=>{const be=new Set(de);return be.has(te)?be.delete(te):be.add(te),be})},[]),E=x.useCallback((te,de="success")=>{w({msg:te,type:de}),setTimeout(()=>w(null),2500)},[]),_=x.useMemo(()=>{const te=new Map;for(const de of r)te.set(de.id,de.name);return te},[r]),G=x.useMemo(()=>{const te=new Map;for(const de of e)te.set(de.id,de);return te},[e]),V=x.useMemo(()=>{const te=new Map;for(const de of t)te.set(de.id,de);return te},[t]),O=x.useRef(!1),q=x.useCallback(()=>{O.current=!1,I(null),d?.()},[d]),J=j?"#94a3b8":"#6b7280",H=x.useCallback((te,de,be)=>({id:`${te}->${de}`,source:te,target:de,animated:be==="blocked",markerEnd:{type:Cd.ArrowClosed,width:14,height:14,color:be==="blocked"?"#ef4444":J},style:{stroke:be==="blocked"?"#ef4444":J,strokeWidth:1.5,cursor:"pointer"}}),[J]),{initialNodes:Z,initialEdges:Y,topLevelIds:ee}=x.useMemo(()=>{const te=(Ve,Rt)=>{const un=new Set,yn=Ve.map(Vt=>(un.add(Vt.id),{id:Vt.id,type:"task",data:{task:Vt,agentName:Vt.assignedAgentId?_.get(Vt.assignedAgentId):void 0,selected:Vt.id===m},position:{x:0,y:0}}));for(const Vt of Rt){const mn=`req-${Vt.id}`;un.add(mn),yn.push({id:mn,type:"requirement",data:{req:Vt,selected:Vt.id===h},position:{x:0,y:0}})}const sn=[];for(const Vt of Ve)if(Vt.blockedBy)for(const mn of Vt.blockedBy)un.has(mn)&&sn.push(H(mn,Vt.id,Vt.status));const In=new Set,jn=(Vt,mn)=>{const Vn=`${Vt}->${mn}`;In.has(Vn)||(In.add(Vn),sn.push({id:Vn,source:Vt,target:mn,markerEnd:{type:Cd.ArrowClosed,width:14,height:14,color:"#8b5cf6"},style:{stroke:"#8b5cf6",strokeWidth:1.5,strokeDasharray:"4 2"}}))};for(const Vt of Rt){const mn=`req-${Vt.id}`;for(const Vn of Vt.taskIds)un.has(Vn)&&jn(mn,Vn)}for(const Vt of Ve)if(Vt.requirementId){const mn=`req-${Vt.requirementId}`;un.has(mn)&&jn(mn,Vt.id)}return{nodes:yn,edges:sn}},de=e.filter(Ve=>F.has(Ve.status)&&(R||!v3(Ve))),be=new Set;for(const Ve of fd)T.has(Ve.id)&&be.add(Ve.id);const se=t.filter(Ve=>{const Rt=x3[Ve.status];return Rt&&be.has(Rt)}),{nodes:fe,edges:$e}=te(de,se),Ne=new Set;for(const Ve of $e)Ne.add(Ve.target);const Ze=new Set(fe.filter(Ve=>!Ne.has(Ve.id)).map(Ve=>Ve.id));if(!D||!Ze.has(D)){const Ve=fe.filter(sn=>Ze.has(sn.id)),{nodes:Rt,direction:un}=y3(Ve,[]);return{initialNodes:Rt.map(sn=>({...sn,data:{...sn.data,direction:un}})),initialEdges:[],topLevelIds:Ze}}const{nodes:pe,edges:ze}=te(e,t),Fe=mre(D,G,V,e),Je=pe.filter(Ve=>Fe.has(Ve.id)).map(Ve=>Ve.id===D?{...Ve,data:{...Ve.data,isExpandedRoot:!0,onCollapse:q}}:Ve),gt=ze.filter(Ve=>Fe.has(Ve.source)&&Fe.has(Ve.target)),{nodes:nt,direction:Et}=y3(Je,gt);return{initialNodes:nt.map(Ve=>({...Ve,data:{...Ve.data,direction:Et}})),initialEdges:gt,topLevelIds:Ze}},[e,t,_,G,V,H,F,T,R,m,h,D,q]),[ae,Q,me]=tne(Z),[Ae,Me,He]=nne(Y),je=x.useRef(null),xe=x.useRef({groupFilter:T,showArchived:R});x.useEffect(()=>{const te=xe.current;(te.groupFilter!==T||te.showArchived!==R)&&(O.current=!1,I(null),xe.current={groupFilter:T,showArchived:R})},[T,R]),x.useEffect(()=>{Q(Z),Me(Y),O.current||requestAnimationFrame(()=>{je.current?.fitView({padding:.2,duration:300})})},[Z,Y,Q,Me]),x.useEffect(()=>{const te=setTimeout(()=>{je.current?.fitView({padding:.2,duration:300})},50);return()=>clearTimeout(te)},[p]);const Pe=x.useCallback(te=>{te&&(O.current=!0)},[]),Ce=x.useCallback((te,de)=>{if(!D&&ee.has(de.id)&&(O.current=!1,I(de.id)),de.id.startsWith("req-")){const be=V.get(de.id.slice(4));be&&l&&l(be)}else{const be=G.get(de.id);be&&i&&i(be)}},[G,V,i,l,ee,D]),Ye=x.useCallback(async te=>{const{source:de,target:be}=te;if(!de||!be||de===be)return;const se=G.get(be);if(!se)return;if(se.blockedBy?.includes(de)){E(v("work:dag.toast.dependencyExists"),"error");return}if(ure(G,de,be)){E(v("work:dag.toast.cycleError"),"error");return}const fe=[...se.blockedBy??[],de];try{await le.tasks.update(be,{blockedBy:fe}),E(v("work:dag.toast.dependencyAdded")),u?.()}catch($e){E(v("work:dag.toast.failed",{message:$e instanceof Error?$e.message:String($e)}),"error")}},[G,E,u,v]),Qe=x.useCallback((te,de)=>{S(de)},[]),ct=x.useCallback(async()=>{if(!N)return;const te=G.get(N.target);if(!te){S(null);return}const de=(te.blockedBy??[]).filter(be=>be!==N.source);try{await le.tasks.update(N.target,{blockedBy:de}),E(v("work:dag.toast.dependencyRemoved")),u?.()}catch(be){E(v("work:dag.toast.failed",{message:be instanceof Error?be.message:String(be)}),"error")}S(null)},[N,G,E,u,v]);if(e.length===0)return n.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:v("work:dag.noTasks")});const st=T.size===Nf.size&&[...Nf].every(te=>T.has(te))&&!R,zt=N?G.get(N.source):null,mt=N?G.get(N.target):null;return n.jsxs("div",{className:"flex-1 min-h-0 relative",style:{height:"100%"},children:[n.jsxs(Jte,{nodes:ae,edges:Ae,onNodesChange:me,onEdgesChange:He,onNodeClick:Ce,onConnect:Ye,onEdgeClick:Qe,onMoveEnd:Pe,onInit:te=>{je.current=te},nodeTypes:are,fitView:!0,minZoom:.3,maxZoom:2,proOptions:{hideAttribution:!0},connectionLineStyle:{stroke:"#818cf8",strokeWidth:2,strokeDasharray:"6 3"},children:[g&&n.jsx(ire,{nodeIds:ae.map(te=>te.id),rfRef:je}),n.jsx(one,{color:j?"#cbd5e1":"#374151",gap:20,size:1}),n.jsx(hne,{showInteractive:!1,className:"!bg-surface-secondary !border-border-default !shadow-xl [&>button]:!bg-surface-elevated [&>button]:!border-border-default [&>button]:!text-fg-secondary [&>button:hover]:!bg-surface-overlay"}),n.jsx(Tne,{nodeColor:te=>{const de=te.data?.task,be=de?.status;return de?.taskType==="scheduled"?"#06b6d4":be==="completed"||be==="accepted"?"#10b981":be==="in_progress"?"#f59e0b":be==="blocked"||be==="failed"?"#ef4444":j?"#94a3b8":"#6b7280"},maskColor:j?"rgba(255,255,255,0.7)":"rgba(0,0,0,0.7)",className:"!bg-surface-secondary !border-border-default"})]}),n.jsxs("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 px-3 py-1.5 bg-surface-secondary/90 border border-border-default rounded-lg backdrop-blur-sm z-10 flex flex-col items-center gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1 flex-wrap justify-center",children:[L.map(te=>{const de=T.has(te.id);return n.jsx("button",{onClick:()=>z(te.id),className:`text-[10px] px-1.5 py-0.5 rounded border transition-colors ${de?`${te.color.bg} ${te.color.border} ${te.color.text}`:"bg-surface-elevated/50 border-border-default/50 text-fg-tertiary"}`,children:v(`work:dag.filter.${te.id}`)},te.id)}),W>0&&n.jsx("button",{onClick:()=>U(te=>!te),className:`text-[10px] px-1.5 py-0.5 rounded border transition-colors ${R?"bg-surface-overlay/60 border-gray-500/50 text-fg-secondary":"bg-surface-elevated/50 border-border-default/50 text-fg-tertiary"}`,children:v("work:dag.archivedToggle",{count:W})}),!st&&n.jsx("button",{onClick:()=>{M(new Set(Nf)),U(!1)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary px-1",children:v("work:dag.reset")})]}),n.jsxs("div",{className:"text-[10px] text-fg-tertiary select-none flex items-center gap-2",children:[D?n.jsx("button",{onClick:q,className:"text-brand-500 hover:text-brand-400 transition-colors",children:v("work:dag.backToOverview")}):n.jsx("span",{children:v("work:dag.expandHint")}),n.jsx("span",{className:"text-fg-tertiary/50",children:"·"}),n.jsx("span",{children:v("work:dag.dragHint")})]})]}),C&&n.jsx("div",{className:`absolute bottom-4 left-1/2 -translate-x-1/2 px-4 py-2 rounded-lg text-xs font-medium shadow-xl border backdrop-blur-sm transition-opacity ${C.type==="success"?"bg-green-500/15 border-green-500/30 text-green-600":"bg-red-500/15 border-red-500/30 text-red-600"}`,children:C.msg}),N&&n.jsx("div",{className:"absolute inset-0 bg-black/40 flex items-center justify-center z-50 backdrop-blur-[2px]",onClick:()=>S(null),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-5 shadow-2xl max-w-sm",onClick:te=>te.stopPropagation(),children:[n.jsx("h4",{className:"text-sm font-semibold text-fg-primary mb-2",children:v("work:dag.removeDependencyTitle")}),n.jsx("p",{className:"text-xs text-fg-secondary mb-4 leading-relaxed",children:v("work:dag.removeDependencyBody",{target:mt?.title??N.target.slice(-8),source:zt?.title??N.source.slice(-8)})}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>S(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary bg-surface-elevated rounded-lg border border-border-default hover:border-gray-600 transition-colors",children:v("common:cancel")}),n.jsx("button",{onClick:ct,className:"px-3 py-1.5 text-xs text-red-500 bg-red-600/20 hover:bg-red-600/30 rounded-lg border border-red-500/40 hover:border-red-500/60 transition-colors",children:v("common:remove")})]})]})})]})}function hre({orgId:e,onCreated:t,onClose:r}){const{t:s}=ft(["work","common"]),[a,i]=x.useState(""),[l,d]=x.useState(""),[u,m]=x.useState(""),[h,p]=x.useState("main"),[y,g]=x.useState([]),[v,j]=x.useState([]),[C,w]=x.useState(!1),[N,S]=x.useState(""),[T,M]=x.useState(!1),D=Ds();x.useEffect(()=>{le.teams.list().then(B=>j(B.teams)).catch(()=>{})},[]);const I=x.useCallback(async B=>{if(B?.preventDefault(),M(!0),!(!a.trim()||C)){w(!0),S("");try{const R=u.trim()?[{url:u.trim(),defaultBranch:h.trim()||"main"}]:[],U=await le.projects.create({name:a.trim(),description:l.trim()||void 0,repositories:R.length>0?R:void 0,teamIds:y.length>0?y:void 0,orgId:e??"default"});t(U.project)}catch(R){S(R instanceof Error?R.message:s("project.failedToCreate"))}w(!1)}},[a,l,u,h,y,e,C,t,s]),$=T&&!a.trim();return lc.createPortal(n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-3",onClick:r,children:n.jsxs("form",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 shadow-2xl max-h-[90dvh] overflow-y-auto ${D?"w-full":"w-[520px]"}`,onClick:B=>B.stopPropagation(),onSubmit:I,children:[n.jsx("h3",{className:"text-base font-semibold mb-5",children:s("project.newProject")}),n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s("project.projectName")}),n.jsx("input",{value:a,onChange:B=>{i(B.target.value),S("")},onBlur:()=>M(!0),placeholder:s("project.projectNamePlaceholder"),className:`input ${$?"!border-red-500 focus:!ring-red-500/25":""}`,autoFocus:!D}),$&&n.jsx("p",{className:"text-[11px] text-red-400 mt-1",children:s("project.projectNameRequired")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s("project.description")}),n.jsx("textarea",{value:l,onChange:B=>d(B.target.value),placeholder:s("project.descriptionPlaceholder"),className:"input",rows:3})]}),v.length>0&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s("project.assignTeams")}),n.jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:v.map(B=>{const R=y.includes(B.id);return n.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer hover:text-fg-primary py-0.5",children:[n.jsx("input",{type:"checkbox",checked:R,onChange:()=>g(U=>R?U.filter(W=>W!==B.id):[...U,B.id]),className:"accent-brand-500"}),n.jsx("span",{className:"truncate",children:B.name})]},B.id)})})]}),n.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s("project.repositoryUrl")}),n.jsx("input",{value:u,onChange:B=>m(B.target.value),placeholder:s("project.repositoryPlaceholder"),className:"input"})]}),u.trim()&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s("project.branch")}),n.jsx("input",{value:h,onChange:B=>p(B.target.value),placeholder:s("project.branchPlaceholder"),className:"input !w-24"})]})]}),N&&n.jsx("div",{className:"text-xs text-red-400 bg-red-500/10 rounded-lg px-3 py-2",children:N}),n.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[n.jsx("button",{type:"button",onClick:r,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{type:"submit",disabled:!a.trim()||C,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:s(C?"common:creating":"project.createProject")})]})]})]})}),document.body)}function Y8(e,t){const[r,s]=x.useState(null);return x.useEffect(()=>{if(!t||!e.current){s(null);return}const a=()=>{const i=e.current?.getBoundingClientRect();if(!i)return;const l=240,d=window.innerHeight-i.bottom-8,u=i.top-8,m=d<l&&u>d;s(m?{top:i.top-4,left:i.left,width:i.width,flipUp:!0}:{top:i.bottom+4,left:i.left,width:i.width,flipUp:!1})};return a(),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a),()=>{window.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a)}},[t,e]),r}function Lu({options:e,value:t,onChange:r,placeholder:s,noMatchesText:a,className:i}){const[l,d]=x.useState(!1),[u,m]=x.useState(""),h=x.useRef(null),p=x.useRef(null),y=x.useRef(null),g=x.useRef(null),v=Y8(p,l);x.useEffect(()=>{const w=N=>{h.current&&!h.current.contains(N.target)&&g.current&&!g.current.contains(N.target)&&d(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const j=e.find(w=>w.value===t)?.label??"",C=u?e.filter(w=>w.label.toLowerCase().includes(u.toLowerCase())):e;return n.jsxs("div",{ref:h,className:i??"",children:[n.jsxs("div",{ref:p,onClick:()=>{d(!l),m(""),setTimeout(()=>y.current?.focus(),0)},className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus-within:border-brand-500 outline-none flex items-center cursor-pointer",children:[l?n.jsx("input",{ref:y,value:u,onChange:w=>m(w.target.value),onClick:w=>w.stopPropagation(),className:"w-full bg-transparent outline-none text-fg-primary text-sm",placeholder:j||s,autoFocus:!0}):n.jsx("span",{className:j?"text-fg-primary":"text-fg-tertiary",children:j||s}),n.jsx("svg",{className:"w-4 h-4 ml-auto text-fg-tertiary shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),l&&v&&n.jsx("div",{ref:g,className:"fixed z-[100] max-h-60 overflow-y-auto bg-surface-elevated border border-border-default rounded-lg shadow-lg",style:v.flipUp?{bottom:window.innerHeight-v.top,left:v.left,width:v.width}:{top:v.top,left:v.left,width:v.width},children:C.length===0?n.jsx("div",{className:"px-3 py-2 text-sm text-fg-tertiary",children:a??"No matches"}):C.map(w=>n.jsx("div",{onClick:()=>{r(w.value),d(!1),m("")},className:`px-3 py-2 text-sm cursor-pointer hover:bg-brand-500/10 ${w.value===t?"bg-brand-500/10 text-brand-500 font-medium":"text-fg-primary"}`,children:w.label},w.value))})]})}function pre({options:e,selected:t,onAdd:r,placeholder:s,noMatchesText:a,className:i}){const[l,d]=x.useState(!1),[u,m]=x.useState(""),h=x.useRef(null),p=x.useRef(null),y=x.useRef(null),g=x.useRef(null),v=Y8(p,l);x.useEffect(()=>{const w=N=>{h.current&&!h.current.contains(N.target)&&g.current&&!g.current.contains(N.target)&&d(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const j=e.filter(w=>!t.includes(w.value)),C=u?j.filter(w=>w.label.toLowerCase().includes(u.toLowerCase())):j;return n.jsxs("div",{ref:h,className:i??"",children:[n.jsxs("div",{ref:p,onClick:()=>{d(!l),m(""),setTimeout(()=>y.current?.focus(),0)},className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus-within:border-brand-500 outline-none flex items-center cursor-pointer",children:[l?n.jsx("input",{ref:y,value:u,onChange:w=>m(w.target.value),onClick:w=>w.stopPropagation(),className:"w-full bg-transparent outline-none text-fg-primary text-sm",placeholder:s,autoFocus:!0}):n.jsx("span",{className:"text-fg-tertiary",children:s}),n.jsx("svg",{className:"w-4 h-4 ml-auto text-fg-tertiary shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),l&&v&&n.jsx("div",{ref:g,className:"fixed z-[100] max-h-60 overflow-y-auto bg-surface-elevated border border-border-default rounded-lg shadow-lg",style:v.flipUp?{bottom:window.innerHeight-v.top,left:v.left,width:v.width}:{top:v.top,left:v.left,width:v.width},children:C.length===0?n.jsx("div",{className:"px-3 py-2 text-sm text-fg-tertiary",children:a??"No matches"}):C.map(w=>n.jsx("div",{onClick:()=>{r(w.value),m("")},className:"px-3 py-2 text-sm cursor-pointer hover:bg-brand-500/10 text-fg-primary",children:w.label},w.value))})]})}function Dd(e,t,r,s="Admin"){if(!e)return null;const a=t.find(l=>l.id===e);if(a)return a.name;const i=r.find(l=>l.id===e);return i?i.name:e==="anonymous"?s:null}function w3({value:e,onSave:t,className:r,placeholder:s}){const{t:a}=ft(["work","common"]),[i,l]=x.useState(!1),[d,u]=x.useState(e),m=x.useRef(null);x.useEffect(()=>{u(e)},[e]),x.useEffect(()=>{i&&m.current?.focus()},[i]);const h=async()=>{l(!1);const p=d.trim();if(p&&p!==e)try{await t(p)}catch{u(e)}else u(e)};return i?n.jsx("input",{ref:m,value:d,onChange:p=>u(p.target.value),onBlur:()=>{h()},onKeyDown:p=>{p.key==="Enter"&&h(),p.key==="Escape"&&(u(e),l(!1))},className:`bg-transparent border-b border-brand-500/50 outline-none ${r??""}`,placeholder:s}):n.jsx("span",{onClick:()=>l(!0),className:`cursor-pointer hover:border-b hover:border-gray-600 transition-colors ${r??""}`,title:a("work:task.clickToEdit"),children:e||n.jsx("span",{className:"text-fg-tertiary italic",children:s??a("work:task.clickToEdit")})})}function gre({value:e,onSave:t,className:r,placeholder:s}){const{t:a}=ft(["work","common"]),[i,l]=x.useState(!1),[d,u]=x.useState(e),m=x.useRef(null);x.useEffect(()=>{u(e)},[e]),x.useEffect(()=>{i&&m.current&&(m.current.focus(),m.current.style.height="auto",m.current.style.height=m.current.scrollHeight+"px")},[i]);const h=async()=>{l(!1);const p=d.trim();if(p!==e)try{await t(p)}catch{u(e)}else u(e)};return i?n.jsx("textarea",{ref:m,value:d,onChange:p=>{u(p.target.value),p.target.style.height="auto",p.target.style.height=p.target.scrollHeight+"px"},onBlur:()=>{h()},onKeyDown:p=>{p.key==="Escape"&&(u(e),l(!1))},className:`bg-transparent border border-brand-500/30 rounded-lg p-2 outline-none resize-none w-full ${r??""}`,placeholder:s,rows:2}):n.jsx("p",{onClick:()=>l(!0),className:`cursor-pointer hover:bg-surface-elevated/50 rounded-lg transition-colors px-2 py-1 -mx-2 -my-1 ${r??""}`,title:a("work:task.clickToEdit"),children:e||n.jsx("span",{className:"text-fg-tertiary italic",children:s??a("work:task.addDescription")})})}const xre=/^\[([^\]]+?)(?:\s+by\s+([^\]]+))?\]\s*([\s\S]*)$/;function X8(e){const t=e.match(xre);return t?{timestamp:t[1].trim(),author:t[2]?.trim()??"System",content:t[3].trim()}:{timestamp:"",author:"",content:e}}function bre(e,t){if(!e)return"";const r=e.match(/^(\d{4})[/-](\d{2})[/-](\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?/);if(!r)return e;const s=new Date,a=+r[1],i=+r[2]-1,l=+r[3],d=+r[4],u=+r[5],m=new Date(a,i,l,d,u),h=s.getTime()-m.getTime();return h<6e4?t("work:relative.justNow"):h<36e5?t("work:relative.minutesAgo",{count:Math.floor(h/6e4)}):h<864e5?t("work:relative.hoursAgo",{count:Math.floor(h/36e5)}):h<6048e5?t("work:relative.daysAgo",{count:Math.floor(h/864e5)}):`${a}-${String(i+1).padStart(2,"0")}-${String(l).padStart(2,"0")}`}const k3=[{bg:"bg-brand-600/30",text:"text-brand-500",border:"border-brand-500/30"},{bg:"bg-blue-600/30",text:"text-blue-400",border:"border-blue-500/30"},{bg:"bg-green-600/30",text:"text-green-400",border:"border-green-500/30"},{bg:"bg-amber-600/30",text:"text-amber-400",border:"border-amber-500/30"},{bg:"bg-purple-600/30",text:"text-purple-400",border:"border-purple-500/30"},{bg:"bg-pink-600/30",text:"text-pink-400",border:"border-pink-500/30"}];function yre(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return k3[Math.abs(t)%k3.length]}function vre({note:e,compact:t}){const{t:r}=ft(["work","common"]),s=X8(e),a=r("work:task.systemAuthor"),i=yre(s.author||a),l=s.author?s.author.split(/[\s_-]+/).map(m=>m[0]).join("").slice(0,2).toUpperCase():"SY",d=bre(s.timestamp,r),u=!s.author||s.author==="System";return t?n.jsxs("div",{className:"flex gap-2.5 group",children:[n.jsx("div",{className:`w-6 h-6 rounded-full ${i.bg} flex items-center justify-center text-[9px] font-bold ${i.text} shrink-0 mt-0.5`,children:l}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-baseline gap-1.5 mb-0.5",children:[n.jsx("span",{className:`text-[11px] font-medium ${u?"text-fg-tertiary":i.text}`,children:u?a:s.author}),d&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:d})]}),n.jsx("div",{className:"text-xs text-fg-secondary",children:n.jsx(Gr,{content:s.content,className:"text-xs text-fg-secondary"})})]})]}):n.jsxs("div",{className:"flex gap-3 group",children:[n.jsxs("div",{className:"flex flex-col items-center shrink-0",children:[n.jsx("div",{className:`w-7 h-7 rounded-full ${i.bg} flex items-center justify-center text-[10px] font-bold ${i.text}`,children:l}),n.jsx("div",{className:"w-px flex-1 bg-border-default/60 mt-1.5"})]}),n.jsx("div",{className:"flex-1 min-w-0 pb-4",children:n.jsxs("div",{className:`border ${i.border} rounded-lg overflow-hidden`,children:[n.jsxs("div",{className:`flex items-center gap-2 px-3 py-1.5 ${i.bg} border-b ${i.border}`,children:[n.jsx("span",{className:`text-[11px] font-medium ${u?"text-fg-secondary":i.text}`,children:u?a:s.author}),d&&n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:d})]}),n.jsx("div",{className:"px-3 py-2.5",children:n.jsx(Gr,{content:s.content,className:"text-xs text-fg-secondary"})})]})})]})}const wre=new Set(["rejected","cancelled","archived"]),My=[{id:"failed",statuses:["failed"],accent:"border-t-red-500",dropStatus:"failed"},{id:"todo",statuses:["pending"],accent:"border-t-amber-500",dropStatus:"pending"},{id:"in_progress",statuses:["in_progress","blocked"],accent:"border-t-brand-500",dropStatus:"in_progress"},{id:"review",statuses:["review"],accent:"border-t-purple-500",dropStatus:"review"},{id:"done",statuses:["completed"],accent:"border-t-green-500",dropStatus:"completed"},{id:"closed",statuses:["rejected","cancelled","archived"],accent:"border-t-gray-500",dropStatus:"cancelled"}],j3={pending:"bg-amber-500/15 text-amber-600",blocked:"bg-amber-500/15 text-amber-600",failed:"bg-red-500/15 text-red-500",rejected:"bg-red-500/15 text-red-500"},N3={pending:"bg-amber-500/15 text-amber-600",in_progress:"bg-blue-500/15 text-blue-500",blocked:"bg-orange-500/15 text-orange-500",review:"bg-purple-500/15 text-purple-500",revision:"bg-amber-500/15 text-amber-600",completed:"bg-green-500/15 text-green-600",failed:"bg-red-500/15 text-red-500",rejected:"bg-red-500/15 text-red-500",cancelled:"bg-gray-500/15 text-fg-tertiary",archived:"bg-gray-500/15 text-fg-tertiary"},S3={low:"bg-gray-500/15 text-fg-tertiary",medium:"bg-blue-500/15 text-blue-500",high:"bg-amber-500/15 text-amber-600",urgent:"bg-red-500/15 text-red-500"},C3={pending:"bg-amber-500/15 text-amber-600",in_progress:"bg-brand-500/15 text-brand-500",completed:"bg-green-500/15 text-green-600",rejected:"bg-red-500/15 text-red-500",cancelled:"bg-gray-600/15 text-fg-tertiary",archived:"bg-gray-600/10 text-fg-tertiary/60"};function Q8(e){return Object.keys(N3).reduce((t,r)=>(t[r]={label:e(`work:status.task.${r}`),cls:N3[r]},t),{})}function Z8(e){return Object.keys(j3).reduce((t,r)=>(t[r]={label:e(`work:status.sub.${r}`),cls:j3[r]},t),{})}function kre(e){return Object.keys(S3).reduce((t,r)=>(t[r]={label:e(`work:priority.${r}`),cls:S3[r]},t),{})}function Dy(e){return Object.keys(C3).reduce((t,r)=>(t[r]={label:e(`work:status.requirement.${r}`),cls:C3[r]},t),{})}const T3=["low","medium","high","urgent"],A3=["pending","in_progress","blocked","review","completed","failed","rejected","cancelled"],E3=["pending","in_progress","completed","rejected","cancelled"],M3={pending:new Set(["in_progress","blocked","rejected","cancelled"]),in_progress:new Set(["review","blocked","failed","cancelled"]),blocked:new Set(["in_progress","cancelled"]),review:new Set(["completed","in_progress","cancelled"]),completed:new Set(["archived","in_progress"]),failed:new Set(["in_progress","archived"]),rejected:new Set(["archived"]),cancelled:new Set(["archived"]),archived:new Set([])},x1={pending:new Set(["in_progress","rejected","cancelled"]),in_progress:new Set(["completed","cancelled"]),completed:new Set([]),rejected:new Set([]),cancelled:new Set([])},k0={idle:"bg-green-400",working:"bg-blue-400",error:"bg-red-400",paused:"bg-amber-400",offline:"bg-gray-600",pending:"bg-amber-400",in_progress:"bg-brand-400",blocked:"bg-amber-400",review:"bg-brand-400",completed:"bg-green-400",failed:"bg-red-400",rejected:"bg-red-400",cancelled:"bg-gray-600",archived:"bg-surface-overlay"},D3={idle:"text-green-500",working:"text-blue-500",error:"text-red-500",paused:"text-amber-500",offline:"text-fg-muted"};function jre({agent:e,anchorRect:t,onClose:r}){const{t:s}=ft(["work","common"]),a=x.useRef(null);x.useEffect(()=>{const u=m=>{a.current&&!a.current.contains(m.target)&&r()};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]);const i=e.status!=="error"&&!!e.lastError&&!!e.lastErrorAt&&Date.now()-new Date(e.lastErrorAt).getTime()<1800*1e3,l=e.status==="idle"&&!i?"bg-green-400":e.status==="working"&&!i?"bg-blue-400 animate-pulse":e.status==="error"?"bg-red-400":i?"bg-amber-400":"bg-gray-500",d=e.status==="idle"?s("work:task.online"):e.status==="working"?s("work:task.working"):e.status==="error"?s("work:task.error"):e.status==="paused"?s("work:task.paused"):s("work:task.offline");return n.jsxs("div",{ref:a,className:"fixed z-50 w-56 bg-surface-secondary border border-border-default rounded-xl shadow-2xl p-3 space-y-2",style:{top:t.top+4,left:t.left},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-7 h-7 rounded-full bg-brand-500/15 flex items-center justify-center text-[10px] font-bold text-brand-600 shrink-0",children:e.name.slice(0,2).toUpperCase()}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-fg-primary font-medium truncate",children:e.name}),n.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e.role}),n.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${l}`}),n.jsx("span",{className:"text-[10px] text-fg-secondary",children:d})]})]})]}),n.jsx("button",{onClick:()=>{r(),pt.navigate(Te.TEAM,{selectAgent:e.id})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1 transition-colors",children:s("work:task.viewProfile")})]})}function Ju({comment:e,agents:t,onReply:r}){const{t:s}=ft(["work","common"]),a=e.authorType==="agent"||e.authorType==="system",i=new Date(e.createdAt),l=i.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),d=i.toLocaleDateString([],{month:"short",day:"numeric"}),[u,m]=x.useState(null),[h,p]=x.useState(!1),[y,g]=x.useState([]),[v,j]=x.useState(!1),C=x.useCallback((M,D)=>{const I=t.find($=>$.name.toLowerCase()===M.toLowerCase());if(I){const $=D.target.getBoundingClientRect();m({agent:I,top:$.bottom,left:$.left})}},[t]),w=x.useMemo(()=>t.map(M=>M.name),[t]),N=x.useCallback(M=>{const D=t.find(I=>I.name.toLowerCase()===e.authorName.toLowerCase());if(D){const I=M.currentTarget.getBoundingClientRect();m({agent:D,top:I.bottom,left:I.left})}},[t,e.authorName]),S=x.useCallback(async()=>{if(h){p(!1);return}const M=e.activityId;if(M&&(p(!0),!(y.length>0))){j(!0);try{const{logs:D}=await le.agents.getActivityLogs(e.authorId,M),I=D.map($=>u6($,M,e.authorId)).filter($=>$!==null).map($=>({...$,ts:new Date($.createdAt).getTime()}));g(I)}catch{}j(!1)}},[h,y.length,e]),T=x.useMemo(()=>c0(y.map(d0).filter(M=>M!==null)),[y]);return n.jsxs("div",{className:"flex gap-2.5 group py-1",id:`comment-${e.id}`,children:[n.jsx("div",{onClick:N,className:`flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center text-[10px] mt-0.5 cursor-pointer transition-all hover:ring-1 hover:ring-brand-500/40 ${a?"bg-indigo-500/20 text-indigo-400":"bg-blue-500/20 text-blue-400"}`,children:e.authorName.slice(0,2).toUpperCase()}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-baseline gap-1.5 mb-0.5",children:[n.jsx("span",{className:`text-[11px] font-medium cursor-pointer hover:underline ${a?"text-indigo-400":"text-blue-400"}`,onClick:N,children:e.authorName}),n.jsxs("span",{className:"text-fg-tertiary text-[10px]",children:[d," ",l]}),r&&n.jsx("button",{onClick:()=>r(e),className:"text-fg-tertiary hover:text-fg-secondary text-[10px] opacity-0 group-hover:opacity-100 transition-opacity ml-1",children:s("work:task.reply")}),e.activityId&&a&&n.jsx("button",{onClick:S,className:"text-fg-tertiary hover:text-brand-400 text-[10px] opacity-0 group-hover:opacity-100 transition-opacity ml-1",children:s(h?"work:task.hideLog":"work:task.viewLog")})]}),e.replyTo&&e.replyToAuthor&&n.jsxs("button",{onClick:()=>{const M=document.getElementById(`comment-${e.replyTo}`);M&&(M.scrollIntoView({behavior:"smooth",block:"center"}),M.classList.add("bg-brand-500/10"),setTimeout(()=>M.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[n.jsx("span",{className:"font-medium text-brand-500/70",children:e.replyToAuthor}),n.jsx("span",{className:"truncate max-w-[200px]",children:e.replyToContent??"..."})]}),n.jsx(Gr,{content:e.content,className:"text-xs text-fg-primary",onMentionClick:C,knownNames:w}),e.attachments?.map((M,D)=>M.type==="image"?n.jsx("img",{src:M.url,alt:M.name,className:"mt-1 max-w-[200px] rounded"},D):null),h&&n.jsx("div",{className:"mt-2 border border-border-subtle rounded-lg overflow-hidden bg-surface-secondary/30",children:v?n.jsx("div",{className:"p-3 text-xs text-fg-tertiary",children:s("work:task.loadingExecutionLog")}):T.length===0?n.jsx("div",{className:"p-3 text-xs text-fg-tertiary",children:s("work:task.noExecutionLogAvailable")}):n.jsx(Uh,{entries:y,isActive:!1,onCollapse:()=>p(!1),embedded:!0})})]}),u&&n.jsx(jre,{agent:u.agent,anchorRect:{top:u.top,left:u.left},onClose:()=>m(null)})]})}function Nre({task:e,agents:t,users:r,authUser:s}){const{t:a}=ft(["work","common"]),[i,l]=x.useState([]),[d,u]=x.useState([]),m=x.useRef(null),[h,p]=x.useState(new Map);x.useEffect(()=>{u([]),p(new Map),m.current&&(clearTimeout(m.current),m.current=null),le.tasks.getComments(e.id).then(w=>l(w.comments)).catch(()=>{})},[e.id]),x.useEffect(()=>pn.on("task:comment",N=>{if(N.payload?.taskId===e.id&&N.payload.comment){const S=N.payload.comment;l(T=>T.some(M=>M.id===S.id)?T:[...T,S]),(S.authorType==="agent"||S.authorId?.startsWith("agt_"))&&(u(T=>{const M=T.filter(D=>D.id!==S.authorId);return M.length===0&&m.current&&(clearTimeout(m.current),m.current=null),M}),p(T=>{const M=new Map(T);return M.delete(S.authorId),M}))}}),[e.id]),x.useEffect(()=>{if(d.length===0)return;const w=new Set(d.map(S=>S.id));return pn.on("agent:activity_log",S=>{const T=S.payload;if(!T)return;const M=T.agentId;if(!w.has(M))return;const D=T.type;if(D==="tool_start"||D==="tool_end"){const $={tool:T.content??T.metadata?.tool??"",phase:D==="tool_start"?"start":"end",success:D==="tool_end"?T.metadata?.success!==!1:void 0,ts:Date.now()};p(B=>{const R=new Map(B),U=[...R.get(M)??[],$];return R.set(M,U),R})}})},[d]);const y=x.useMemo(()=>{const w=[];for(const N of e.notes??[]){const S=X8(N);let T;if(S.timestamp){const M=S.timestamp.match(/^(\d{4})[/-](\d{2})[/-](\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?/);T=M?new Date(+M[1],+M[2]-1,+M[3],+M[4],+M[5],+(M[6]??0)):new Date(0)}else T=new Date(0);w.push({type:"note",note:N,ts:T})}for(const N of i)w.push({type:"comment",comment:N,ts:new Date(N.createdAt)});return w.sort((N,S)=>N.ts.getTime()-S.ts.getTime()),w},[e.notes,i]),[g,v]=x.useState(null),j=async(w,N,S,T)=>{let M;S.length>0&&(M=(await le.uploads.upload(S.map(R=>({dataUrl:R.dataUrl,name:R.name})),"comments")).files.map(R=>({type:"image",url:R.url,name:R.name}))),await le.tasks.addComment(e.id,w,s?.name,M,s?.id,N.length>0?N:void 0,T);const D=[],I=new Set,$=B=>{if(I.has(B)||B===s?.id)return;I.add(B);const R=t.find(U=>U.id===B);R&&D.push({id:R.id,name:R.name,avatarUrl:R.avatarUrl})};for(const B of N){const R=t.find(U=>U.name.toLowerCase()===B.toLowerCase());R&&$(R.id)}e.assignedAgentId&&$(e.assignedAgentId),e.createdBy?.startsWith("agt_")&&e.status!=="in_progress"&&$(e.createdBy),D.length>0&&(m.current&&clearTimeout(m.current),u(D),m.current=setTimeout(()=>u([]),12e4))},C=x.useCallback(w=>{v({id:w.id,authorName:w.authorName,content:w.content.slice(0,100)})},[]);return n.jsxs("div",{className:"mt-5",children:[n.jsx("p",{className:"text-xs font-semibold text-fg-tertiary uppercase tracking-wider mb-3",children:a("work:task.activityCommentsHeading")}),n.jsxs("div",{className:"space-y-0.5 mb-3",children:[y.length===0&&n.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:a("work:task.noActivityYet")}),y.map((w,N)=>w.type==="note"?n.jsx(vre,{note:w.note,compact:!0},`n-${N}`):n.jsx(Ju,{comment:w.comment,agents:t,onReply:C},`c-${w.comment.id}`)),d.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 pt-1",children:d.map(w=>{const N=h.get(w.id)??[];return n.jsxs("div",{className:"px-2 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors",onClick:()=>pt.navigate(Te.TEAM,{agentId:w.id,profileTab:"mind"}),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:w.name,avatarUrl:w.avatarUrl,size:22,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsx("span",{className:"text-xs font-medium text-fg-secondary",children:w.name}),N.length===0&&n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("work:task.agentProcessing")}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary",children:"→"})]}),N.length>0&&n.jsx("div",{className:"ml-8 mt-1",children:n.jsx(Vh,{activities:N,isActive:!0})})]},w.id)})})]}),n.jsx(OS,{agents:t,humans:r,onSubmit:j,replyTo:g,onCancelReply:()=>v(null),placeholder:a("work:task.commentPlaceholder")})]})}function Sre({task:e,isRunning:t,authUser:r,agents:s}){const a=e.id,{t:i}=ft(["work","common"]),[l,d]=x.useState([]),[u,m]=x.useState(new Map),[h,p]=x.useState(new Set),[y,g]=x.useState([]),[v,j]=x.useState(""),[C,w]=x.useState(t),[N,S]=x.useState(!0),[T,M]=x.useState(new Set),[D,I]=x.useState(""),[$,B]=x.useState(!1),[R,U]=x.useState([]),W=x.useRef(null),[F,L]=x.useState(new Map),[z,E]=x.useState([]),[_,G]=x.useState([]),[V,O]=x.useState(!1),q=x.useRef(null),J=x.useRef(null);x.useEffect(()=>{w(t)},[t]),x.useEffect(()=>{U([]),L(new Map),W.current&&(clearTimeout(W.current),W.current=null)},[a]),x.useEffect(()=>{S(!0),Promise.all([le.tasks.getLogsSummary(a).catch(()=>({rounds:[]})),le.tasks.getComments(a).catch(()=>({comments:[]}))]).then(([je,xe])=>{const Pe=je.rounds;if(d(Pe),g(xe.comments),Pe.length===0){S(!1);return}const Ce=Pe[Pe.length-1].round;M(new Set([Ce])),le.tasks.getLogs(a,Ce).catch(()=>({logs:[]})).then(Ye=>{m(new Map([[Ce,Ye.logs]])),S(!1)})})},[a]),x.useEffect(()=>{const je=e.assignedAgentId;je&&(O(!0),le.agents.getActivities(je,{taskId:a,limit:20}).then(xe=>G(xe.activities)).catch(()=>G([])).finally(()=>O(!1)))},[a,e.assignedAgentId]);const H=x.useCallback(je=>{u.has(je)||h.has(je)||(p(xe=>new Set(xe).add(je)),le.tasks.getLogs(a,je).catch(()=>({logs:[]})).then(xe=>{m(Pe=>new Map(Pe).set(je,xe.logs)),p(Pe=>{const Ce=new Set(Pe);return Ce.delete(je),Ce})}))},[a,u,h]),Z=x.useCallback(je=>{M(xe=>{const Pe=new Set(xe);return Pe.has(je)?Pe.delete(je):(Pe.add(je),u.has(je)||H(je)),Pe})},[u,H]);x.useEffect(()=>{const je=pn.on("task:log",Ce=>{const Ye=Ce.payload;if(Ye.taskId!==a)return;const Qe={id:Ye.id,taskId:Ye.taskId,agentId:Ye.agentId,seq:Ye.seq,type:Ye.logType,content:Ye.content,metadata:Ye.metadata,executionRound:Ye.executionRound,createdAt:Ye.createdAt},ct=Qe.executionRound??1;d(st=>st.find(mt=>mt.round===ct)?st:[...st,{round:ct,logCount:0,toolCount:0,firstAt:Qe.createdAt,lastAt:Qe.createdAt,status:"running"}]),M(st=>st.has(ct)?st:new Set(st).add(ct)),m(st=>{const zt=st.get(ct)??[];return Qe.id&&zt.some(mt=>mt.id===Qe.id)?st:new Map(st).set(ct,[...zt,Qe])}),Qe.type==="text"&&j(""),Qe.type==="status"&&(Qe.content==="started"||Qe.content==="resumed"?w(!0):["completed","failed","cancelled","execution_finished"].includes(Qe.content)&&(w(!1),d(st=>st.map(zt=>zt.round===ct?{...zt,status:Qe.content}:zt)))),Qe.type==="error"&&w(!1)}),xe=pn.on("task:log:delta",Ce=>{const Ye=Ce.payload;Ye.taskId===a&&j(Qe=>Qe+Ye.text)}),Pe=pn.on("task:comment",Ce=>{const Ye=Ce.payload;if(Ye.taskId!==a)return;const Qe=Ye.comment;g(ct=>ct.some(st=>st.id===Qe.id)?ct:[...ct,Qe]),(Qe.authorType==="agent"||Qe.authorId?.startsWith("agt_"))&&(U(ct=>{const st=ct.filter(zt=>zt.id!==Qe.authorId);return st.length===0&&W.current&&(clearTimeout(W.current),W.current=null),st}),L(ct=>{const st=new Map(ct);return st.delete(Qe.authorId),st}))});return()=>{je(),xe(),Pe()}},[a]),x.useEffect(()=>{if(R.length===0)return;const je=new Set(R.map(Pe=>Pe.id));return pn.on("agent:activity_log",Pe=>{const Ce=Pe.payload;if(!Ce)return;const Ye=Ce.agentId;if(!je.has(Ye))return;const Qe=Ce.type;if(Qe==="tool_start"||Qe==="tool_end"){const st={tool:Ce.content??Ce.metadata?.tool??"",phase:Qe==="tool_start"?"start":"end",success:Qe==="tool_end"?Ce.metadata?.success!==!1:void 0,ts:Date.now()};L(zt=>{const mt=new Map(zt),te=[...mt.get(Ye)??[],st];return mt.set(Ye,te),mt})}})},[R]);const Y=x.useMemo(()=>{const je=[];for(const[,xe]of u)je.push(...xe);return je.sort((xe,Pe)=>xe.seq-Pe.seq),je},[u]),ee=x.useMemo(()=>Y.map(je=>hb(je)),[Y]),ae=l.length>1,Q=je=>{const xe=je.target.files;if(xe){for(const Pe of Array.from(xe)){if(!Pe.type.startsWith("image/"))continue;const Ce=new FileReader;Ce.onload=()=>{E(Ye=>[...Ye,{type:"image",url:Ce.result,name:Pe.name}])},Ce.readAsDataURL(Pe)}je.target.value=""}},me=async()=>{if(!(!D.trim()&&z.length===0)){B(!0);try{let je;z.length>0&&(je=(await le.uploads.upload(z.map(ct=>({dataUrl:ct.url,name:ct.name})),"comments")).files.map(ct=>({type:"image",url:ct.url,name:ct.name})));const xe=await le.tasks.addComment(a,D,r?.name,je,r?.id);xe.comment&&g(Qe=>Qe.some(ct=>ct.id===xe.comment.id)?Qe:[...Qe,xe.comment]),I(""),E([]);const Pe=[],Ce=new Set,Ye=Qe=>{if(Ce.has(Qe)||Qe===r?.id)return;Ce.add(Qe);const ct=s.find(st=>st.id===Qe);ct&&Pe.push({id:ct.id,name:ct.name,avatarUrl:ct.avatarUrl})};e.assignedAgentId&&Ye(e.assignedAgentId),e.createdBy?.startsWith("agt_")&&e.status!=="in_progress"&&Ye(e.createdBy),Pe.length>0&&(W.current&&clearTimeout(W.current),U(Pe),W.current=setTimeout(()=>U([]),12e4))}catch{}B(!1)}},Ae=n.jsxs("div",{className:"border-t border-border-default px-4 py-3 sticky bottom-0 bg-surface-primary z-10",children:[z.length>0&&n.jsx("div",{className:"flex gap-2 mb-2 flex-wrap",children:z.map((je,xe)=>n.jsxs("div",{className:"relative group",children:[n.jsx("img",{src:je.url,alt:je.name,className:"w-16 h-16 object-cover rounded-lg border border-border-default"}),n.jsx("button",{onClick:()=>E(Pe=>Pe.filter((Ce,Ye)=>Ye!==xe)),className:"absolute -top-1 -right-1 w-4 h-4 rounded-full bg-red-600 text-white text-[10px] flex items-center justify-center opacity-0 group-hover:opacity-100",children:"×"})]},xe))}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"text",value:D,onChange:je=>I(je.target.value),onKeyDown:je=>{je.key==="Enter"&&!je.shiftKey&&(je.preventDefault(),me())},placeholder:i("work:task.commentInstructionPlaceholder"),className:"flex-1 px-3 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-blue-500 outline-none text-fg-primary placeholder-gray-600"}),n.jsx("input",{type:"file",ref:q,accept:"image/*",multiple:!0,onChange:Q,className:"hidden"}),n.jsx("button",{onClick:()=>q.current?.click(),className:"px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-fg-secondary hover:text-fg-primary text-sm",title:i("work:task.attachImage"),children:"📎"}),n.jsx("button",{onClick:()=>{me()},disabled:$||!D.trim()&&z.length===0,className:"px-3 py-1.5 bg-blue-600 hover:bg-blue-500 rounded-lg text-white text-xs disabled:opacity-50",children:i("common:send")})]})]});if(N)return n.jsx("div",{className:"flex-1 flex items-center justify-center text-xs text-fg-tertiary",children:i("work:task.loadingLogs")});if(l.length===0&&!v){const je=e.assignedAgentId?s.find(mt=>mt.id===e.assignedAgentId):void 0,xe=_.length>0,Pe=je&&je.currentTaskId&&je.currentTaskId!==e.id,Ce=e.status==="pending",Ye=e.status==="in_progress",Qe=!e.assignedAgentId;let ct="📋",st=i("work:task.emptyLogs.default"),zt=i("work:task.emptyLogs.defaultHint");return Qe?(ct="👤",st=i("work:task.emptyLogs.noAgent"),zt=i("work:task.emptyLogs.noAgentHint")):Ce?(ct="⏳",st=i("work:task.emptyLogs.pending"),zt=i("work:task.emptyLogs.pendingHint")):Ye&&Pe?(ct="🔄",st=i("work:task.emptyLogs.agentBusy",{agent:je?.name??e.assignedAgentId}),zt=i("work:task.emptyLogs.agentBusyHint")):Ye&&(ct="⏳",st=i("work:task.emptyLogs.starting"),zt=i("work:task.emptyLogs.startingHint")),n.jsxs("div",{className:"flex flex-col min-h-full",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:V?n.jsx("div",{className:"flex items-center justify-center py-8 text-xs text-fg-tertiary",children:i("work:task.loadingLogs")}):xe?n.jsxs("div",{className:"px-4 py-4",children:[n.jsxs("div",{className:"text-xs text-fg-secondary mb-3 flex items-center gap-1.5",children:[n.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-blue-500"}),i("work:task.relatedSessions",{agent:je?.name??i("work:task.agent"),count:_.length})]}),n.jsx("div",{className:"space-y-1.5",children:_.map(mt=>{const te=!mt.endedAt,de=mt.type==="task"?"🔧":mt.type==="chat"||mt.type==="respond_in_session"?"💬":mt.type==="heartbeat"?"💓":"📋";return n.jsxs("button",{className:"w-full flex items-center gap-2 px-3 py-2 rounded-lg bg-surface-elevated hover:bg-surface-elevated/80 border border-border-default/50 text-left transition-colors group",onClick:()=>pt.navigate(Te.TEAM,{agentId:e.assignedAgentId}),children:[n.jsx("span",{className:"text-sm shrink-0",children:de}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-xs text-fg-primary truncate",children:mt.label}),n.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[new Date(mt.startedAt).toLocaleString(),mt.endedAt?` — ${mt.totalTools} tools, ${mt.totalTokens.toLocaleString()} tokens`:""]})]}),te&&n.jsxs("span",{className:"shrink-0 flex items-center gap-1 text-[10px] text-green-500 font-medium",children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"}),i("work:task.sessionLive")]}),!te&&n.jsx("span",{className:`shrink-0 text-[10px] ${mt.success?"text-fg-tertiary":"text-red-400"}`,children:mt.success?"✓":"✗"}),n.jsx("span",{className:"shrink-0 text-fg-tertiary text-[10px] opacity-0 group-hover:opacity-100 transition-opacity",children:"→"})]},mt.id)})})]}):n.jsx("div",{className:"flex items-center justify-center py-8",children:n.jsxs("div",{className:"text-center text-fg-tertiary",children:[n.jsx("div",{className:"text-2xl mb-2",children:ct}),n.jsxs("div",{className:"text-xs",children:[st,n.jsx("br",{}),n.jsx("span",{className:"text-fg-muted",children:zt})]})]})})}),Ae]})}if(!ae){const je=ee.map(Ce=>d0(Ce)).filter(Ce=>Ce!==null),xe=yk(Y,c0(je)),Pe=[...xe.map(Ce=>({kind:"entry",entry:Ce,ts:Ce.timestamp?new Date(Ce.timestamp).getTime():0})),...y.map(Ce=>({kind:"comment",comment:Ce,ts:new Date(Ce.createdAt).getTime()}))];return Pe.sort((Ce,Ye)=>Ce.ts-Ye.ts),n.jsxs("div",{className:"flex flex-col min-h-full",children:[n.jsxs("div",{className:"px-4 py-3 flex-1 space-y-0.5",children:[Pe.map((Ce,Ye)=>Ce.kind==="comment"?n.jsx(Ju,{comment:Ce.comment,agents:s},`c-${Ce.comment.id}`):n.jsx(ih,{entry:Ce.entry,showTime:!0,isLast:Ye===Pe.length-1},`e-${Ye}`)),C&&v&&n.jsx(Wb,{content:v}),C&&!v&&xe.length>0&&n.jsx(Kb,{})]}),Ae]})}const Me=(je,xe)=>{const Pe=je.firstAt?new Date(je.firstAt).getTime():0,Ce=xe?.firstAt?new Date(xe.firstAt).getTime():1/0;return y.filter(Ye=>{const Qe=new Date(Ye.createdAt).getTime();return Qe>=Pe&&Qe<Ce})},He=l.length>0?y.filter(je=>new Date(je.createdAt).getTime()<new Date(l[0].firstAt).getTime()):[];return n.jsxs("div",{className:"flex flex-col min-h-full",children:[n.jsx("div",{ref:J}),n.jsxs("div",{className:"px-4 py-3 flex-1 space-y-2",children:[He.length>0&&n.jsx("div",{className:"space-y-0.5",children:He.map(je=>n.jsx(Ju,{comment:je,agents:s},je.id))}),l.map((je,xe)=>{const Pe=T.has(je.round),Ce=je.round===l[l.length-1].round,Ye=u.get(je.round),Qe=h.has(je.round),ct=Me(je,l[xe+1]),st=je.status==="completed"||je.status==="execution_finished"?"✅":je.status==="failed"?"❌":je.status==="cancelled"?"⏹":"🔄",zt=je.lastAt&&je.firstAt?Math.max(0,new Date(je.lastAt).getTime()-new Date(je.firstAt).getTime()):0,mt=zt>=6e4?`${Math.floor(zt/6e4)}m ${Math.floor(zt%6e4/1e3)}s`:zt>=1e3?`${Math.floor(zt/1e3)}s`:"";return n.jsxs("div",{className:"border border-border-default/50 rounded-lg overflow-hidden",children:[n.jsxs("button",{onClick:()=>Z(je.round),className:"w-full flex items-center justify-between px-3 py-2 bg-surface-elevated/30 hover:bg-surface-elevated/50 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm",children:st}),n.jsx("span",{className:"text-xs text-fg-secondary font-medium",children:i("work:task.roundHeader",{n:je.round})}),ct.length>0&&n.jsxs("span",{className:"text-[10px] text-blue-400",children:["💬 ",ct.length]}),Ce&&C&&n.jsxs("svg",{className:"w-3 h-3 animate-spin text-brand-500",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("work:task.toolCount",{count:je.toolCount})}),mt&&n.jsx("span",{className:"text-[10px] text-fg-tertiary tabular-nums",children:mt}),n.jsx("svg",{className:`w-3 h-3 text-fg-tertiary transition-transform ${Pe?"rotate-180":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]})]}),Pe&&n.jsxs("div",{className:"px-3 py-1.5 space-y-0.5",children:[Qe&&n.jsx("div",{className:"text-xs text-fg-tertiary py-2 text-center",children:i("work:task.loadingRound",{n:je.round})}),Ye&&(()=>{const de=Ye.map(fe=>hb(fe)).map(fe=>d0(fe)).filter(fe=>fe!==null),se=[...yk(Ye,c0(de)).map(fe=>({kind:"entry",entry:fe,ts:fe.timestamp?new Date(fe.timestamp).getTime():0})),...ct.map(fe=>({kind:"comment",comment:fe,ts:new Date(fe.createdAt).getTime()}))];return se.sort((fe,$e)=>fe.ts-$e.ts),se.map((fe,$e)=>fe.kind==="comment"?n.jsx(Ju,{comment:fe.comment,agents:s},`c-${fe.comment.id}`):n.jsx(ih,{entry:fe.entry,showTime:!0,isLast:$e===se.length-1},`e-${$e}`))})(),Ce&&C&&v&&n.jsx(Wb,{content:v}),Ce&&C&&!v&&!Qe&&n.jsx(Kb,{})]})]},je.round)}),R.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 mt-2",children:R.map(je=>{const xe=F.get(je.id)??[];return n.jsxs("div",{className:"px-3 py-2 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors",onClick:()=>pt.navigate(Te.TEAM,{agentId:je.id,profileTab:"mind"}),children:[n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:je.name,avatarUrl:je.avatarUrl,size:24,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"text-xs font-medium text-fg-secondary truncate",children:je.name}),xe.length===0&&n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("work:task.agentProcessing")})]}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary",children:"→"})]}),xe.length>0&&n.jsx("div",{className:"ml-9 mt-1",children:n.jsx(Vh,{activities:xe,isActive:!0})})]},je.id)})})]}),Ae]})}const R3=new Set([".md",".markdown",".txt",".json",".yaml",".yml",".toml",".csv",".xml",".html",".htm",".css",".js",".ts",".jsx",".tsx",".py",".sh",".log",".env",".cfg",".ini",".png",".jpg",".jpeg",".gif",".webp",".svg"]);function Cre(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Tre({filePath:e,onClose:t,onOpenExternal:r}){const{t:s}=ft(["work","common"]),[a,i]=x.useState([e]),l=a[a.length-1],[d,u]=x.useState(null),[m,h]=x.useState(null),[p,y]=x.useState(!0);x.useEffect(()=>{y(!0),h(null),u(null),le.files.preview(l).then(M=>u(M)).catch(M=>h(String(M))).finally(()=>y(!1))},[l]);const g=M=>i(D=>[...D,M]),v=()=>i(M=>M.length>1?M.slice(0,-1):M),j=a.length>1,C=M=>{le.files.reveal(M).catch(()=>{})},w=M=>{M.isDirectory||R3.has(M.ext)?g(M.path):C(M.path)},N=l.split("/").pop()??l,S=d?.type==="directory",T=(M,D)=>{if(D)return"📁";const I=[".md",".markdown"],$=[".png",".jpg",".jpeg",".gif",".webp",".svg"];return I.includes(M)?"📝":$.includes(M)?"🖼":[".json",".yaml",".yml",".toml",".xml"].includes(M)?"⚙":[".js",".ts",".jsx",".tsx",".py",".sh"].includes(M)?"💻":"📄"};return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",onClick:t,children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl w-[720px] max-w-[92vw] max-h-[85vh] flex flex-col shadow-2xl",onClick:M=>M.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border-default shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[j&&n.jsx("button",{onClick:v,className:"text-fg-tertiary hover:text-fg-primary text-sm shrink-0 p-1 -ml-1 rounded hover:bg-surface-elevated/60 transition-colors",title:s("common:back"),children:n.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),S?n.jsx("svg",{className:"w-4 h-4 text-amber-500 shrink-0",viewBox:"0 0 16 16",fill:"currentColor",children:n.jsx("path",{d:"M1 3.5A1.5 1.5 0 012.5 2h3.879a1.5 1.5 0 011.06.44l.872.87A.5.5 0 008.665 3.5H13.5A1.5 1.5 0 0115 5v8.5a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 011 13.5v-10z"})}):n.jsxs("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 16 16",fill:"currentColor",children:[n.jsx("path",{d:"M3 1h7l4 4v10H3V1zm7 1H4v12h10V5.5L10 2z"}),n.jsx("path",{d:"M10 1v4h4",fill:"none",stroke:"currentColor",strokeWidth:"1"})]}),n.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:N}),S&&d.entries&&n.jsxs("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:["(",d.entries.length,")"]})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-3",children:[n.jsx("button",{onClick:()=>r?r():C(l),className:"text-fg-tertiary hover:text-fg-primary p-1.5 rounded hover:bg-surface-elevated/60 transition-colors",title:s(r?"work:task.openInDeliverables":"work:task.openInFinder"),children:n.jsxs("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),n.jsx("button",{onClick:t,className:"text-fg-tertiary hover:text-fg-secondary text-lg shrink-0",children:"×"})]})]}),n.jsx("div",{className:"px-4 py-1 border-b border-border-default/60",children:n.jsx("p",{className:"text-[10px] text-fg-tertiary font-mono truncate",children:l})}),n.jsxs("div",{className:"flex-1 overflow-auto min-h-0",children:[p&&n.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:s("work:task.filePreviewLoading")}),m&&n.jsx("div",{className:"text-sm text-red-500 text-center py-8",children:m}),d?.type==="directory"&&d.entries&&n.jsxs("div",{className:"divide-y divide-border-default/50",children:[d.entries.length===0&&n.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:s("work:task.emptyDirectory")}),d.entries.map(M=>n.jsxs("button",{onClick:()=>w(M),className:"w-full flex items-center gap-3 px-5 py-2.5 hover:bg-surface-elevated/40 transition-colors text-left group",children:[n.jsx("span",{className:"text-sm shrink-0",children:T(M.ext,M.isDirectory)}),n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-fg-primary group-hover:text-brand-400 transition-colors",children:M.name}),!M.isDirectory&&M.size!=null&&n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:Cre(M.size)}),M.isDirectory&&n.jsx("svg",{className:"w-3.5 h-3.5 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})}),!M.isDirectory&&!R3.has(M.ext)&&n.jsxs("svg",{className:"w-3 h-3 text-fg-tertiary shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})]},M.path))]}),d&&d.type!=="directory"&&n.jsx("div",{className:"p-5",children:d.type==="image"?n.jsx("div",{className:"flex justify-center",children:n.jsx("img",{src:`data:${d.mimeType};base64,${d.content}`,alt:d.name,className:"max-w-full max-h-[60vh] rounded-lg"})}):n.jsx(uy,{content:d.content,format:d.type==="text"?"text":d.type,className:"text-sm text-fg-secondary leading-relaxed"})})]})]})})}function I3({task:e,agents:t,projects:r,requirements:s,allTasks:a,users:i,onClose:l,onRefresh:d,authUser:u,scrollToComments:m,onScrollToCommentsDone:h,onReqClick:p,onProjectClick:y}){const{t:g}=ft(["work","common"]),v=x.useMemo(()=>Q8(g),[g]),[j,C]=x.useState([]),[w,N]=x.useState(""),[S,T]=x.useState(!1),[M,D]=x.useState(!1),[I,$]=x.useState(null),[B,R]=x.useState(null),[U,W]=x.useState(!1),[F,L]=x.useState(!1),[z,E]=x.useState(!1),[_,G]=x.useState("every"),[V,O]=x.useState(""),[q,J]=x.useState(""),[H,Z]=x.useState(""),[Y,ee]=x.useState(!1),[ae,Q]=x.useState("details"),me=x.useRef(null),[Ae,Me]=x.useState("none"),He=x.useCallback(Ie=>{Q(Ie),requestAnimationFrame(()=>{me.current?.scrollTo({top:0,behavior:"instant"})})},[]),je=x.useMemo(()=>[{id:"details"},{id:"logs"},{id:"deliverables"},{id:"history"}],[]),xe=Sl(je,ae,He);x.useEffect(()=>{const Ie=me.current;if(!Ie)return;const At=()=>{const{scrollTop:qt,scrollHeight:Jt,clientHeight:tn}=Ie;if(!(Jt>tn+50)){Me("none");return}const br=qt<30,an=qt+tn>=Jt-30;Me(br?"top":an?"bottom":"middle")};At(),Ie.addEventListener("scroll",At,{passive:!0});const It=new ResizeObserver(At);return It.observe(Ie),()=>{Ie.removeEventListener("scroll",At),It.disconnect()}},[ae]),x.useEffect(()=>{if(!m)return;Q("details");const Ie=setTimeout(()=>{const At=me.current;At&&At.scrollTo({top:At.scrollHeight,behavior:"smooth"}),h?.()},300);return()=>clearTimeout(Ie)},[m,h]);const[Pe,Ce]=x.useState(null),[Ye,Qe]=x.useState(!1),[ct,st]=x.useState(null),[zt,mt]=x.useState(!1),[te,de]=x.useState(e.description),be=x.useRef(null),se=x.useRef(null),fe=x.useRef(80);x.useEffect(()=>{if(zt&&se.current){const Ie=se.current;Ie.style.height="auto",Ie.style.height=Math.max(Ie.scrollHeight,fe.current)+"px",Ie.focus()}},[zt]);const[$e,Ne]=x.useState(!1),[Ze,pe]=x.useState(""),[ze,Fe]=x.useState(1),[Je,gt]=x.useState(!1),nt=Ds(),Et=20,dt=x.useCallback(async()=>{try{const Ie=await le.tasks.listSubtasks(e.id);C(Ie.subtasks)}catch{}},[e.id]);x.useEffect(()=>{dt()},[dt]);const Ve=async Ie=>{if(!Y){ee(!0);try{await Ie(),d(),await dt()}catch(At){Ce(String(At).replace("Error: ",""))}finally{ee(!1)}}},Rt=Ie=>Ve(()=>le.tasks.update(e.id,{priority:Ie})),un=Ie=>Ve(()=>le.tasks.assign(e.id,Ie||null)),yn=Ie=>Ve(()=>le.tasks.update(e.id,{projectId:Ie||null})),sn=async()=>{if(!Y){ee(!0);try{await le.tasks.pause(e.id),d()}finally{ee(!1)}}},In=async()=>{if(!Y){ee(!0),Ce(null),He("logs");try{await le.tasks.resume(e.id),d()}catch(Ie){Ce(String(Ie).replace("Error: API error: 400","Server error").replace("Error: ",""))}finally{ee(!1)}}},jn=async()=>{w.trim()&&(await le.tasks.createSubtask(e.id,w.trim()),N(""),T(!1),dt(),d())},Vt=async Ie=>{Ie.status==="completed"?await le.tasks.cancelSubtask(e.id,Ie.id):await le.tasks.completeSubtask(e.id,Ie.id),dt(),d()},mn=async Ie=>{await le.tasks.deleteSubtask(e.id,Ie.id),$(null),dt(),d()},Vn=async()=>{if(!Y){ee(!0);try{await le.tasks.updateStatus(e.id,"in_progress"),d()}finally{ee(!1)}}},Xn=async()=>{if(!Y){ee(!0),Ce(null),He("logs");try{await le.tasks.retry(e.id),d()}catch(Ie){Ce(String(Ie).replace("Error: API error: 400","Server error").replace("Error: ",""))}finally{ee(!1)}}},Rr=async()=>{if(!Y){ee(!0),Ce(null),He("logs");try{await le.tasks.runNow(e.id),d()}catch(Ie){Ce(String(Ie).replace("Error: API error: 400","Server error").replace("Error: ","")),d()}finally{ee(!1)}}},qe=x.useRef(d);qe.current=d,x.useEffect(()=>pn.on("task:update",At=>{At.payload.taskId===e.id&&(dt(),qe.current())}),[e.id,dt]);const St=j.filter(Ie=>Ie.status==="completed").length,_e=e.status==="in_progress",Tt=e.status==="blocked",Ot=Tt&&(!e.blockedBy||e.blockedBy.length===0||e.blockedBy.every(Ie=>{const At=a.find(It=>It.id===Ie);return At&&At.status==="completed"})),Gt=e.status==="completed",Tn=e.status==="failed",_n=e.status==="rejected",Sn=e.status==="cancelled",Fn=e.status==="archived",mr=Gt||Tn||_n||Sn||Fn,rr=e.taskType==="scheduled"&&!!e.scheduleConfig,fr=rr&&!!e.scheduleConfig?.paused,Qn=(()=>{const Ie=r.find(At=>At.id===e.projectId);return Ie&&Ie.name!=="default"?Ie:void 0})(),ir=s.find(Ie=>Ie.id===e.requirementId);return t.find(Ie=>Ie.id===e.assignedAgentId),n.jsxs("div",{className:"flex flex-col w-full h-full overflow-hidden bg-surface-primary shadow-xl shadow-black/8 ring-1 ring-border-default/20",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 px-6 pt-5 pb-3 border-b border-border-default shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[nt&&n.jsx("button",{onClick:()=>history.back(),className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsxs("h3",{className:"flex-1 min-w-0 text-base font-semibold leading-snug text-fg-primary",children:[e.title," ",(()=>{const Ie=v[e.status];return Ie?n.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full font-medium whitespace-nowrap align-middle ${Ie.cls}`,children:Ie.label}):n.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium bg-gray-500/15 text-fg-tertiary whitespace-nowrap align-middle",children:e.status.replace(/_/g," ")})})(),Ot&&n.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium whitespace-nowrap align-middle bg-red-500/15 text-red-500",children:g("work:task.abnormalBlock")})]})]}),n.jsx("button",{onClick:l,className:"text-fg-tertiary hover:text-fg-secondary text-xl leading-none shrink-0 mt-1",children:"×"})]}),n.jsxs("div",{className:"flex gap-1 px-6 pt-2 pb-0 shrink-0",children:[n.jsx("button",{onClick:()=>He("details"),className:`px-3 py-1.5 text-xs rounded-t-md transition-colors ${ae==="details"?"bg-surface-elevated text-fg-primary font-medium":"text-fg-tertiary hover:text-fg-secondary"}`,children:g("work:task.detailsTab")}),n.jsxs("button",{onClick:()=>He("logs"),className:`px-3 py-1.5 text-xs rounded-t-md transition-colors flex items-center gap-1.5 ${ae==="logs"?"bg-surface-elevated text-fg-primary font-medium":"text-fg-tertiary hover:text-fg-secondary"}`,children:[g("work:task.executionLogTab"),_e&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse"})]}),n.jsx("button",{onClick:()=>He("deliverables"),className:`px-3 py-1.5 text-xs rounded-t-md transition-colors flex items-center gap-1.5 ${ae==="deliverables"?"bg-surface-elevated text-fg-primary font-medium":"text-fg-tertiary hover:text-fg-secondary"}`,children:(()=>{const Ie=(e.deliverables??[]).filter(At=>At.type!=="branch"&&typeof At.reference=="string"&&At.reference.length>0).length;return Ie>0?g("work:task.deliverablesCount",{count:Ie}):g("work:task.deliverables")})()}),n.jsx("button",{onClick:()=>He("history"),className:`px-3 py-1.5 text-xs rounded-t-md transition-colors ${ae==="history"?"bg-surface-elevated text-fg-primary font-medium":"text-fg-tertiary hover:text-fg-secondary"}`,children:g("work:task.historyTab")})]}),n.jsxs("div",{className:"flex-1 min-h-0 relative",children:[n.jsxs("div",{ref:me,className:"h-full overflow-y-auto overflow-x-hidden",onTouchStart:xe.onTouchStart,onTouchEnd:xe.onTouchEnd,children:[n.jsxs("div",{className:ae==="logs"?"min-w-0 min-h-full":"hidden",children:[Pe&&n.jsxs("div",{className:"mx-4 mt-3 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:[n.jsx("span",{className:"font-medium",children:g("work:task.failedToStart")})," ",Pe]}),n.jsx(Sre,{task:e,isRunning:e.status==="in_progress",authUser:u,agents:t})]}),n.jsxs("div",{className:ae==="details"?"":"hidden",children:[n.jsx("div",{className:"px-6 pt-4 pb-3 border-b border-border-default",children:zt?n.jsx("textarea",{ref:se,value:te,onChange:Ie=>{de(Ie.target.value);const At=Ie.target;At.style.height="auto",At.style.height=At.scrollHeight+"px"},onBlur:()=>{te!==e.description&&Ve(()=>le.tasks.update(e.id,{description:te})),mt(!1)},onKeyDown:Ie=>{Ie.key==="Escape"&&(Ie.preventDefault(),de(e.description),mt(!1))},className:"w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none -mx-2 px-2 -my-1 py-1",placeholder:g("work:task.addDescription")}):n.jsx("div",{ref:be,className:"group relative cursor-pointer rounded-lg -mx-2 px-2 -my-1 py-1 hover:bg-surface-elevated/50 transition-colors",onClick:Ie=>{Ie.target.closest("a, button, [data-entity-link]")||(fe.current=Math.max(be.current?.offsetHeight??80,60),de(e.description),mt(!0))},role:"button",tabIndex:0,onKeyDown:Ie=>Ie.key==="Enter"&&(de(e.description),mt(!0)),children:e.description?n.jsxs("div",{children:[n.jsx("div",{className:nt&&!Je?"line-clamp-3":"",children:n.jsx(Gr,{content:e.description,className:"text-sm text-fg-secondary leading-relaxed"})}),nt&&e.description.length>150&&n.jsx("button",{onClick:Ie=>{Ie.stopPropagation(),gt(!Je)},className:"text-[11px] text-brand-500 mt-1 font-medium",children:g(Je?"work:task.collapse":"common:showMore")})]}):n.jsx("p",{className:"text-sm text-fg-tertiary italic",children:g("work:task.noDescription")})})}),(Qn||ir)&&n.jsxs("div",{className:"px-6 py-2.5 border-b border-border-default flex flex-wrap items-center gap-2",children:[Qn&&n.jsxs("span",{className:`flex items-center gap-1 text-[11px] px-2 py-0.5 bg-brand-500/10 text-brand-500 rounded-full ${y?"cursor-pointer hover:bg-brand-500/20 transition-colors":""}`,onClick:y?()=>y(Qn.id):void 0,role:y?"button":void 0,tabIndex:y?0:void 0,onKeyDown:y?Ie=>Ie.key==="Enter"&&y(Qn.id):void 0,children:[n.jsx("span",{className:"text-[9px] text-brand-500/60",children:g("work:task.projectLabel")}),Qn.name]}),ir&&n.jsxs("span",{className:`flex items-center gap-1 text-[11px] px-2 py-0.5 bg-brand-500/10 text-brand-500 rounded-full ${p?"cursor-pointer hover:bg-brand-500/20 transition-colors":""}`,onClick:p?()=>p(ir):void 0,role:p?"button":void 0,tabIndex:p?0:void 0,onKeyDown:p?Ie=>Ie.key==="Enter"&&p(ir):void 0,children:[n.jsx("span",{className:"text-[9px] text-brand-500/60",children:g("work:task.requirementLabel")}),ir.title.length>40?ir.title.slice(0,40)+"…":ir.title]})]}),n.jsxs("div",{className:"px-6 py-2.5 border-b border-border-default",children:[n.jsx("div",{className:"flex items-center justify-between mb-1.5",children:n.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:g("work:task.dependencies")})}),e.blockedBy&&e.blockedBy.length>0?n.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:e.blockedBy.map(Ie=>{const At=a.find(qt=>qt.id===Ie),It=At&&(At.status==="completed"||At.status==="cancelled");return n.jsxs("span",{className:`inline-flex items-center gap-1 text-[11px] px-2 py-1 rounded-full ${It?"bg-green-500/10 text-green-600":"bg-amber-500/10 text-amber-600"}`,children:[n.jsx("span",{className:"text-[9px]",children:It?"✓":"⏳"}),n.jsx("span",{className:`font-mono ${It?"line-through opacity-60":""}`,children:At?At.title.slice(0,30):Ie.slice(-8)}),!mr&&n.jsx("button",{onClick:async()=>{const qt=(e.blockedBy??[]).filter(Jt=>Jt!==Ie);await le.tasks.update(e.id,{blockedBy:qt}),d()},className:"ml-0.5 text-current opacity-40 hover:opacity-100 transition-opacity",title:g("work:task.removeDependency"),children:"×"})]},Ie)})}):n.jsx("p",{className:"text-[11px] text-fg-tertiary mb-2",children:g("work:task.noDependencies")}),Ot&&n.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 bg-red-500/10 border border-red-500/20 rounded-lg text-xs text-red-500 mb-2",children:[n.jsxs("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),n.jsx("span",{children:g("work:task.abnormalBlockHint")})]}),!mr&&n.jsxs("select",{value:"",onChange:async Ie=>{const At=Ie.target.value;if(!At)return;const It=[...e.blockedBy??[],At];await le.tasks.update(e.id,{blockedBy:It}),d()},className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-[11px] text-fg-secondary focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"",children:g("work:task.addDependency")}),a.filter(Ie=>Ie.id!==e.id&&!(e.blockedBy??[]).includes(Ie.id)).map(Ie=>n.jsx("option",{value:Ie.id,children:Ie.title},Ie.id))]})]}),n.jsxs("div",{className:"px-6 py-4 border-b border-border-default/60 space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1",children:g("work:task.projectLabel")}),n.jsxs("select",{value:e.projectId??"",onChange:Ie=>{yn(Ie.target.value)},disabled:Y,className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-xs text-fg-primary focus:border-brand-500 outline-none disabled:opacity-50 cursor-pointer",children:[n.jsx("option",{value:"",children:g("work:task.noProject")}),r.map(Ie=>n.jsx("option",{value:Ie.id,children:Ie.name},Ie.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1",children:g("work:task.requirementLabel")}),n.jsxs("select",{value:e.requirementId??"",onChange:Ie=>Ve(()=>le.tasks.update(e.id,{requirementId:Ie.target.value||null})),disabled:Y,className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-xs text-fg-primary focus:border-brand-500 outline-none disabled:opacity-50 cursor-pointer",children:[n.jsx("option",{value:"",children:g("work:task.noRequirement")}),s.filter(Ie=>!e.projectId||Ie.projectId===e.projectId).map(Ie=>n.jsx("option",{value:Ie.id,children:Ie.title},Ie.id))]})]})]}),n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1",children:g("work:task.assignee")}),n.jsxs("select",{value:e.assignedAgentId??"",onChange:Ie=>{un(Ie.target.value)},disabled:Y,className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-xs text-fg-primary focus:border-brand-500 outline-none disabled:opacity-50 cursor-pointer",children:[n.jsx("option",{value:"",children:g("work:task.unassigned")}),t.map(Ie=>n.jsxs("option",{value:Ie.id,children:[Ie.name," (",Ie.status,")"]},Ie.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1",children:g("work:task.reviewer")}),n.jsxs("select",{value:`${e.reviewerType??"agent"}:${e.reviewerId??""}`,onChange:Ie=>{const At=Ie.target.value;if(!At)return;const It=At.startsWith("human:"),qt=At.replace(/^(human|agent):/,"");(qt!==e.reviewerId||(It?"human":"agent")!==(e.reviewerType??"agent"))&&Ve(()=>le.tasks.update(e.id,{reviewerId:qt,reviewerType:It?"human":"agent"}))},disabled:Y,className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-xs text-fg-primary focus:border-brand-500 outline-none disabled:opacity-50 cursor-pointer",children:[i.map(Ie=>n.jsx("option",{value:`human:${Ie.id}`,children:Ie.name},`human:${Ie.id}`)),t.map(Ie=>n.jsx("option",{value:`agent:${Ie.id}`,children:Ie.name},`agent:${Ie.id}`))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1",children:g("work:task.priority")}),n.jsxs("select",{value:e.priority,onChange:Ie=>{Rt(Ie.target.value)},disabled:Y,className:"w-full px-2 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-xs text-fg-primary focus:border-brand-500 outline-none disabled:opacity-50 cursor-pointer",children:[n.jsx("option",{value:"low",children:g("work:priority.low")}),n.jsx("option",{value:"medium",children:g("work:priority.medium")}),n.jsx("option",{value:"high",children:g("work:priority.high")}),n.jsx("option",{value:"urgent",children:g("work:priority.urgent")})]})]})]})]}),n.jsxs("div",{className:"px-6 py-3 border-b border-border-default/60 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-fg-tertiary",children:[e.createdBy&&n.jsx("span",{children:g("work:task.createdBy",{name:Dd(e.createdBy,t,i)??e.createdBy})}),e.updatedBy&&n.jsx("span",{children:g("work:task.updatedBy",{name:Dd(e.updatedBy,t,i)??e.updatedBy})}),e.createdAt&&n.jsx("span",{children:new Date(e.createdAt).toLocaleDateString()}),e.startedAt&&n.jsx("span",{children:g("work:task.started",{date:new Date(e.startedAt).toLocaleDateString()})}),e.updatedAt&&n.jsx("span",{children:g("work:task.updatedMeta",{date:new Date(e.updatedAt).toLocaleDateString()})}),e.projectId&&n.jsxs("span",{className:"font-mono text-blue-600/70",children:["task/",e.id]}),(e.executionRound??1)>1&&n.jsx("span",{className:"text-amber-600",children:g("work:task.executionRound",{n:e.executionRound})})]}),n.jsxs("div",{className:"px-6 py-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:[g("work:task.subtasks")," ",j.length>0&&n.jsx("span",{className:"ml-1.5 text-fg-tertiary font-normal normal-case",children:g("work:task.subtasksProgress",{done:St,total:j.length})})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[St>0&&n.jsx("button",{onClick:()=>D(Ie=>!Ie),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${M?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-tertiary border-border-default hover:text-fg-secondary"}`,children:M?g("work:task.hideCompleted"):g("work:task.showCompleted",{count:St})}),n.jsx("button",{onClick:()=>T(!0),className:"text-xs text-brand-500 hover:text-brand-500 transition-colors",children:g("work:task.addSubtask")})]})]}),(()=>{const Ie=M?j:j.filter(At=>At.status!=="completed");return Ie.length>0?n.jsx("div",{className:"space-y-1.5 mb-3",children:Ie.map(At=>n.jsxs("div",{className:"group flex items-center gap-2.5 py-1.5 px-2 rounded-lg hover:bg-surface-elevated/50 transition-colors",children:[n.jsx("button",{onClick:()=>{Vt(At)},className:`shrink-0 w-4 h-4 rounded border flex items-center justify-center transition-colors ${At.status==="completed"?"bg-green-600 border-green-600 text-white":"border-gray-600 hover:border-brand-500"}`,children:At.status==="completed"&&n.jsx("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 12 12",fill:"none",children:n.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsx("span",{className:`flex-1 text-sm ${At.status==="completed"?"line-through text-fg-tertiary":"text-fg-secondary"}`,children:At.title}),n.jsx("button",{onClick:()=>$(At),className:"shrink-0 opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-red-500 transition-all text-xs",children:"✕"})]},At.id))}):null})(),j.length===0&&!S&&n.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:g("work:task.noSubtasksYet")}),S&&n.jsxs("div",{className:"flex gap-2 mt-2",children:[n.jsx("input",{autoFocus:!0,value:w,onChange:Ie=>N(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&jn(),Ie.key==="Escape"&&(T(!1),N(""))},placeholder:g("work:task.subtaskTitlePlaceholder"),className:"flex-1 px-3 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none"}),n.jsx("button",{onClick:()=>{jn()},className:"px-3 py-1.5 bg-brand-600 hover:bg-brand-500 text-white text-xs rounded-lg",children:g("work:task.add")}),n.jsx("button",{onClick:()=>{T(!1),N("")},className:"px-3 py-1.5 border border-border-default text-xs rounded-lg hover:bg-surface-elevated",children:g("common:cancel")})]}),(()=>{const Ie=(e.deliverables??[]).filter(qt=>qt.type!=="branch"&&typeof qt.reference=="string"&&qt.reference.length>0);if(Ie.length===0)return null;const At={file:"bg-blue-500/15 text-blue-600",document:"bg-blue-500/15 text-blue-600",report:"bg-brand-500/15 text-brand-500",directory:"bg-green-500/15 text-green-600",url:"bg-brand-500/15 text-brand-500",text:"bg-gray-500/15 text-fg-secondary"},It=Ie.slice(0,3);return n.jsxs("div",{className:"mt-5",children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("p",{className:"text-xs font-semibold text-fg-tertiary uppercase tracking-wider",children:g("work:task.deliverablesCount",{count:Ie.length})}),Ie.length>3&&n.jsx("button",{onClick:()=>He("deliverables"),className:"text-[10px] text-brand-500 hover:text-brand-500",children:g("work:task.viewAll")})]}),n.jsx("div",{className:"space-y-1.5",children:It.map((qt,Jt)=>{const tn=/^https?:\/\//i.test(qt.reference),An=tn?qt.summary||qt.reference:qt.reference.split("/").pop()??qt.reference;return n.jsxs("div",{className:"flex items-start gap-2.5 bg-surface-elevated/60 rounded-lg px-3 py-2 group hover:bg-surface-elevated/80 transition-colors",children:[n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 mt-0.5 ${At[qt.type]??"bg-gray-500/15 text-fg-secondary"}`,children:qt.type}),n.jsxs("div",{className:"flex-1 min-w-0",children:[tn?n.jsxs("a",{href:qt.reference,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-brand-500 hover:text-brand-500 font-medium truncate block max-w-full text-left hover:underline",title:qt.reference,children:[An," ",n.jsxs("svg",{className:"w-3 h-3 inline -mt-0.5 ml-0.5 opacity-60",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 6.5v3a.5.5 0 0 1-.5.5h-6a.5.5 0 0 1-.5-.5v-6A.5.5 0 0 1 2.5 3H6"}),n.jsx("path",{d:"M7 2h3v3"}),n.jsx("path",{d:"M5 7 10 2"})]})]}):n.jsx("button",{onClick:()=>st(qt.reference),className:"text-sm text-brand-500 hover:text-brand-500 font-medium truncate block max-w-full text-left hover:underline",title:qt.reference,children:An}),qt.summary&&!tn&&n.jsx("p",{className:"text-[11px] text-fg-secondary mt-0.5 line-clamp-2",children:qt.summary}),n.jsx("p",{className:"text-[10px] text-fg-tertiary font-mono truncate mt-0.5",children:qt.reference})]})]},Jt)})})]})})(),n.jsx(Nre,{task:e,agents:t,users:i,authUser:u})]})]}),n.jsx("div",{className:ae==="history"?"":"hidden",children:n.jsx(tC,{entityType:"task",entityId:e.id})}),n.jsx("div",{className:ae==="deliverables"?"px-6 py-4":"hidden",children:(()=>{const Ie=(e.deliverables??[]).filter(Jt=>Jt.type!=="branch"&&typeof Jt.reference=="string"&&Jt.reference.length>0);if(Ie.length===0)return n.jsx("div",{className:"flex items-center justify-center py-12 text-xs text-fg-tertiary",children:g("work:task.noDeliverablesYet")});const At={file:"bg-blue-500/15 text-blue-600",document:"bg-blue-500/15 text-blue-600",report:"bg-brand-500/15 text-brand-500",directory:"bg-green-500/15 text-green-600",url:"bg-brand-500/15 text-brand-500",text:"bg-gray-500/15 text-fg-secondary"},It=Math.ceil(Ie.length/Et),qt=Ie.slice((ze-1)*Et,ze*Et);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("p",{className:"text-xs font-semibold text-fg-tertiary uppercase tracking-wider",children:g("work:task.deliverablesCount",{count:Ie.length})}),It>1&&n.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary",children:[n.jsx("button",{disabled:ze<=1,onClick:()=>Fe(Jt=>Jt-1),className:"px-1.5 py-0.5 rounded bg-surface-elevated hover:bg-surface-overlay disabled:opacity-30",children:"‹"}),n.jsxs("span",{children:[ze,"/",It]}),n.jsx("button",{disabled:ze>=It,onClick:()=>Fe(Jt=>Jt+1),className:"px-1.5 py-0.5 rounded bg-surface-elevated hover:bg-surface-overlay disabled:opacity-30",children:"›"})]})]}),n.jsx("div",{className:"space-y-1.5",children:qt.map((Jt,tn)=>{const An=/^https?:\/\//i.test(Jt.reference),br=An?Jt.summary||Jt.reference:Jt.reference.split("/").pop()??Jt.reference;return n.jsxs("div",{className:"flex items-start gap-2.5 bg-surface-elevated/60 rounded-lg px-3 py-2 group hover:bg-surface-elevated/80 transition-colors",children:[n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 mt-0.5 ${At[Jt.type]??"bg-gray-500/15 text-fg-secondary"}`,children:Jt.type}),n.jsxs("div",{className:"flex-1 min-w-0",children:[An?n.jsxs("a",{href:Jt.reference,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-brand-500 hover:text-brand-500 font-medium truncate block max-w-full text-left hover:underline",title:Jt.reference,children:[br," ",n.jsxs("svg",{className:"w-3 h-3 inline -mt-0.5 ml-0.5 opacity-60",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 6.5v3a.5.5 0 0 1-.5.5h-6a.5.5 0 0 1-.5-.5v-6A.5.5 0 0 1 2.5 3H6"}),n.jsx("path",{d:"M7 2h3v3"}),n.jsx("path",{d:"M5 7 10 2"})]})]}):n.jsx("button",{onClick:()=>st(Jt.reference),className:"text-sm text-brand-500 hover:text-brand-500 font-medium truncate block max-w-full text-left hover:underline",title:Jt.reference,children:br}),Jt.summary&&!An&&n.jsx("p",{className:"text-[11px] text-fg-secondary mt-0.5 line-clamp-2",children:Jt.summary}),n.jsx("p",{className:"text-[10px] text-fg-tertiary font-mono truncate mt-0.5",children:Jt.reference})]})]},tn)})})]})})()})]}),Ae!=="none"&&Ae!=="top"&&n.jsx("button",{onClick:()=>me.current?.scrollTo({top:0,behavior:"smooth"}),className:"absolute bottom-36 right-4 md:bottom-28 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:g("work:task.scrollToTop"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M14.77 12.79a.75.75 0 01-1.06-.02L10 8.832l-3.71 3.938a.75.75 0 11-1.08-1.04l4.25-4.5a.75.75 0 011.08 0l4.25 4.5a.75.75 0 01-.02 1.06z",clipRule:"evenodd"})})}),Ae!=="none"&&Ae!=="bottom"&&n.jsx("button",{onClick:()=>{const Ie=me.current;Ie&&Ie.scrollTo({top:Ie.scrollHeight,behavior:"smooth"})},className:"absolute bottom-22 right-4 md:bottom-18 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:g("work:task.scrollToBottom"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})})]}),rr&&e.scheduleConfig&&n.jsxs("div",{className:`mx-6 mt-3 mb-0 px-4 py-2.5 rounded-lg border text-xs ${fr?"bg-amber-500/5 border-amber-500/20":"bg-brand-500/5 border-brand-500/20"} ${!_e&&!z&&!e.scheduleConfig.runAt?"cursor-pointer hover:border-brand-500/40 transition-colors":""}`,onClick:()=>{_e||z||e.scheduleConfig?.runAt||(G(e.scheduleConfig?.cron?"cron":"every"),O(e.scheduleConfig?.every??"4h"),J(e.scheduleConfig?.cron??""),Z(e.scheduleConfig?.maxRuns&&e.scheduleConfig.maxRuns>0?String(e.scheduleConfig.maxRuns):""),E(!0))},children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:fr?"text-amber-600":"text-brand-500",children:fr?g("work:task.schedulePaused"):n.jsxs(n.Fragment,{children:[n.jsx("svg",{className:"w-3.5 h-3.5 inline -mt-0.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"})})," ",g("work:task.scheduled")]})}),n.jsx("span",{className:"text-fg-tertiary",children:"·"}),n.jsx("span",{className:"text-fg-secondary",children:e.scheduleConfig.every?g("work:task.scheduleEvery",{interval:e.scheduleConfig.every}):e.scheduleConfig.cron?g("work:task.scheduleCron",{expr:e.scheduleConfig.cron}):e.scheduleConfig.runAt?g("work:task.scheduleOneShot"):g("work:task.scheduleNA")}),!fr&&e.scheduleConfig.nextRunAt&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-fg-tertiary",children:"·"}),n.jsx("span",{className:"text-fg-secondary",children:g("work:task.scheduleNext",{when:(()=>{const Ie=new Date(e.scheduleConfig.nextRunAt).getTime()-Date.now();if(Ie<=0)return g("work:task.scheduleDueNow");const At=Math.floor(Ie/6e4);if(At<60)return g("work:task.scheduleInMinutes",{count:At});const It=Math.floor(At/60);return It<24?g("work:task.scheduleInHoursMinutes",{h:It,m:At%60}):g("work:task.scheduleInDaysHours",{d:Math.floor(It/24),h:It%24})})()})})]}),!_e&&!z&&!e.scheduleConfig.runAt&&n.jsxs("svg",{className:"w-3 h-3 text-brand-500 ml-auto shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})]}),z?n.jsxs("div",{className:"mt-2 pt-2 border-t border-border-default/50 space-y-2",onClick:Ie=>Ie.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("select",{value:_,onChange:Ie=>G(Ie.target.value),className:"px-2 py-1 text-xs bg-surface-elevated border border-border-default rounded-lg",children:[n.jsx("option",{value:"every",children:g("work:task.scheduleEveryMode")}),n.jsx("option",{value:"cron",children:g("work:task.scheduleCronMode")})]}),_==="every"?n.jsxs("select",{value:V,onChange:Ie=>O(Ie.target.value),className:"flex-1 px-2 py-1 text-xs bg-surface-elevated border border-border-default rounded-lg",children:[n.jsx("option",{value:"30m",children:g("work:task.freq30m")}),n.jsx("option",{value:"1h",children:g("work:task.freq1h")}),n.jsx("option",{value:"2h",children:g("work:task.freq2h")}),n.jsx("option",{value:"4h",children:g("work:task.freq4h")}),n.jsx("option",{value:"8h",children:g("work:task.freq8h")}),n.jsx("option",{value:"12h",children:g("work:task.freq12h")}),n.jsx("option",{value:"1d",children:g("work:task.freq1d")}),n.jsx("option",{value:"1w",children:g("work:task.freq1w")})]}):n.jsx("input",{value:q,onChange:Ie=>J(Ie.target.value),placeholder:"0 9 * * 1-5",className:"flex-1 px-2 py-1 text-xs bg-surface-elevated border border-border-default rounded-lg outline-none focus:border-brand-500"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("label",{className:"text-fg-tertiary shrink-0",children:g("work:task.scheduleMaxRuns")}),n.jsx("input",{value:H,onChange:Ie=>Z(Ie.target.value.replace(/\D/g,"")),placeholder:g("work:task.scheduleMaxRunsPlaceholder"),className:"w-20 px-2 py-1 text-xs bg-surface-elevated border border-border-default rounded-lg outline-none focus:border-brand-500"})]}),n.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[n.jsx("button",{onClick:async()=>{const Ie={};_==="every"?Ie.every=V:Ie.cron=q.trim(),H&&(Ie.maxRuns=parseInt(H,10)),await Ve(()=>le.tasks.updateSchedule(e.id,Ie)),E(!1)},disabled:Y,className:"px-3 py-1 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-50",children:g("common:save")}),n.jsx("button",{onClick:()=>E(!1),className:"px-3 py-1 text-xs text-fg-secondary hover:text-fg-primary",children:g("common:cancel")})]})]}):n.jsxs("div",{className:"flex items-center gap-2 mt-1 text-fg-tertiary",children:[n.jsx("span",{children:g("work:task.scheduleRuns",{current:e.scheduleConfig.currentRuns??0,max:e.scheduleConfig.maxRuns&&e.scheduleConfig.maxRuns>0?g("work:task.scheduleRunsMax",{max:e.scheduleConfig.maxRuns}):""})}),e.scheduleConfig.lastRunAt&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"·"}),n.jsx("span",{children:g("work:task.scheduleLast",{when:(()=>{const Ie=Date.now()-new Date(e.scheduleConfig.lastRunAt).getTime(),At=Math.floor(Ie/6e4);if(At<1)return g("work:task.noteTimeJustNow");if(At<60)return g("work:task.noteTimeMinutes",{count:At});const It=Math.floor(At/60);return It<24?g("work:task.noteTimeHours",{count:It}):g("work:task.noteTimeDays",{count:Math.floor(It/24)})})()})})]})]})]}),n.jsx("div",{className:"px-6 py-4 border-t border-border-default flex items-center justify-between gap-2",children:n.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.status==="pending"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>{if(rr){Qe(!0);return}Ve(()=>le.tasks.approve(e.id))},disabled:Y,className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 rounded-lg text-white disabled:opacity-50",children:e.createdBy&&!e.createdBy.startsWith("agt_")?g("work:task.startExecution"):g("work:task.approve")}),e.createdBy&&!e.createdBy.startsWith("agt_")?n.jsx("button",{onClick:()=>{Ve(()=>le.tasks.cancel(e.id))},disabled:Y,className:"px-3 py-1.5 text-xs text-red-500 border border-red-500/30 rounded-lg hover:bg-red-500/10 disabled:opacity-50",children:g("work:task.cancelTask")}):n.jsx("button",{onClick:()=>W(!0),disabled:Y,className:"px-3 py-1.5 text-xs text-red-500 border border-red-500/30 rounded-lg hover:bg-red-500/10 disabled:opacity-50",children:g("work:task.reject")})]}),e.status==="review"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>{Ve(()=>le.tasks.accept(e.id,u?.id))},disabled:Y,className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 rounded-lg text-white disabled:opacity-50",children:g("work:task.approveCheck")}),$e?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("input",{type:"text",value:Ze,onChange:Ie=>pe(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&Ze.trim()&&(Ve(()=>le.tasks.revision(e.id,Ze.trim(),u?.id)),Ne(!1),pe(""))},placeholder:g("work:task.revisionReasonPlaceholder"),autoFocus:!0,className:"px-2 py-1 text-xs bg-surface-elevated border border-amber-500/40 rounded-lg text-fg-primary focus:border-amber-400 outline-none w-48"}),n.jsx("button",{onClick:()=>{Ve(()=>le.tasks.revision(e.id,Ze.trim()||g("work:task.revisionsNeededDefault"),u?.id)),Ne(!1),pe("")},disabled:Y,className:"px-2.5 py-1 text-xs bg-amber-600 hover:bg-amber-500 rounded-lg text-white disabled:opacity-50",children:g("common:send")}),n.jsx("button",{onClick:()=>{Ne(!1),pe("")},className:"px-1.5 py-1 text-xs text-fg-secondary hover:text-fg-primary",children:"✕"})]}):n.jsx("button",{onClick:()=>Ne(!0),disabled:Y,className:"px-3 py-1.5 text-xs bg-amber-600 hover:bg-amber-500 rounded-lg text-white disabled:opacity-50",children:g("work:task.requestRevision")})]}),_e&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:()=>{sn()},disabled:Y,className:"px-3 py-1.5 text-xs border border-amber-500/30 text-amber-600 rounded-lg hover:bg-amber-500/10 disabled:opacity-50 flex items-center gap-1",children:[n.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"currentColor",children:[n.jsx("rect",{x:"2",y:"1.5",width:"3",height:"9",rx:"0.5"}),n.jsx("rect",{x:"7",y:"1.5",width:"3",height:"9",rx:"0.5"})]}),g("work:task.pause")]}),n.jsxs("button",{onClick:()=>{Xn()},disabled:Y,className:"px-3 py-1.5 text-xs border border-blue-500/30 text-blue-600 rounded-lg hover:bg-blue-500/10 disabled:opacity-50 flex items-center gap-1",children:[n.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[n.jsx("path",{d:"M1.5 6a4.5 4.5 0 1 1 1.3 3.2",strokeLinecap:"round"}),n.jsx("path",{d:"M1 3.5V6h2.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),g("work:task.retry")]})]}),Tt&&n.jsx("button",{onClick:()=>{In()},disabled:Y,className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 rounded-lg text-white disabled:opacity-50 flex items-center gap-1",children:Y?n.jsx(n.Fragment,{children:g("work:task.resuming")}):n.jsxs(n.Fragment,{children:[n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"currentColor",children:n.jsx("path",{d:"M3 1.5v9l7-4.5-7-4.5z"})}),g("work:task.resume")]})}),Tn&&!rr&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:()=>{Xn()},disabled:Y,className:"px-3 py-1.5 text-xs bg-blue-600 hover:bg-blue-500 rounded-lg text-white disabled:opacity-50 flex items-center gap-1",children:[n.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[n.jsx("path",{d:"M1.5 6a4.5 4.5 0 1 1 1.3 3.2",strokeLinecap:"round"}),n.jsx("path",{d:"M1 3.5V6h2.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),g("work:task.retry")]}),n.jsxs("button",{onClick:()=>{Vn()},disabled:Y,className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 rounded-lg text-white disabled:opacity-50 flex items-center gap-1",children:[n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"currentColor",children:n.jsx("path",{d:"M3 1.5v9l7-4.5-7-4.5z"})}),g("work:task.continueTask")]})]}),rr&&(Gt||Tn)&&!Fn&&n.jsx("button",{onClick:()=>{Rr()},disabled:Y,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-50 flex items-center gap-1.5",children:Y?n.jsx(n.Fragment,{children:g("work:task.running")}):n.jsxs(n.Fragment,{children:[n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 12 12",fill:"currentColor",children:n.jsx("path",{d:"M3 1.5v9l7-4.5-7-4.5z"})}),g("work:task.runNow")]})}),rr&&!_e&&!Fn&&!_n&&(fr?n.jsx("button",{onClick:()=>{Ve(()=>le.tasks.resumeSchedule(e.id))},disabled:Y,className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 rounded-lg text-white disabled:opacity-50",children:g("work:task.resumeSchedule")}):n.jsx("button",{onClick:()=>{Ve(()=>le.tasks.pauseSchedule(e.id))},disabled:Y,className:"px-3 py-1.5 text-xs border border-amber-500/30 text-amber-600 rounded-lg hover:bg-amber-500/10 disabled:opacity-50",children:g("work:task.pauseSchedule")})),(Gt||Tn||_n||Sn)&&n.jsx("button",{onClick:()=>L(!0),disabled:Y,className:"px-3 py-1.5 text-xs bg-gray-600 hover:bg-gray-500 rounded-lg text-white disabled:opacity-50",children:g("work:task.archive")}),Gt&&!rr&&n.jsx("button",{onClick:()=>{Vn()},disabled:Y,className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary disabled:opacity-50",children:g("work:task.reopen")}),!mr&&e.status!=="pending"&&n.jsx("button",{onClick:async()=>{const{count:Ie}=await le.tasks.getDependentCount(e.id);R({dependentCount:Ie})},disabled:Y,className:"px-3 py-1.5 text-xs text-red-500 border border-red-500/30 rounded-lg hover:bg-red-500/10 disabled:opacity-50",children:g("work:task.cancelTask")})]})}),I&&n.jsx(dd,{title:g("work:task.deleteSubtaskTitle",{title:I.title}),message:g("work:task.deleteSubtaskMessage"),confirmLabel:g("common:delete"),onConfirm:()=>{mn(I)},onCancel:()=>$(null)}),U&&n.jsx(dd,{title:g("work:task.rejectConfirmTitle"),message:g("work:task.rejectConfirmMessage"),confirmLabel:g("work:task.reject"),onConfirm:()=>{W(!1),Ve(()=>le.tasks.reject(e.id))},onCancel:()=>W(!1)}),F&&n.jsx(dd,{title:g("work:task.archiveConfirmTitle"),message:g(rr?"work:task.archiveScheduledConfirmMessage":"work:task.archiveConfirmMessage"),confirmLabel:g("work:task.archive"),onConfirm:()=>{L(!1),Ve(()=>le.tasks.archive(e.id))},onCancel:()=>L(!1)}),B&&B.dependentCount>0?n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:()=>R(null),children:n.jsxs("div",{className:"bg-surface-default border border-border-default rounded-xl p-6 max-w-md w-full shadow-2xl",onClick:Ie=>Ie.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary mb-2",children:g("work:task.cancelTaskModalTitle")}),n.jsx("p",{className:"text-sm text-fg-secondary mb-4",children:g("work:task.cancelTaskDependent",{count:B.dependentCount})}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("button",{onClick:()=>{R(null),Ve(()=>le.tasks.cancel(e.id,!1))},className:"w-full px-4 py-2.5 text-sm bg-surface-elevated border border-border-default rounded-lg hover:bg-surface-overlay text-fg-primary text-left",children:[n.jsx("span",{className:"font-medium",children:g("work:task.cancelTaskOnly")}),n.jsx("span",{className:"block text-xs text-fg-tertiary mt-0.5",children:g("work:task.cancelTaskOnlyHint")})]}),n.jsxs("button",{onClick:()=>{R(null),Ve(()=>le.tasks.cancel(e.id,!0))},className:"w-full px-4 py-2.5 text-sm bg-red-500/10 border border-red-500/30 rounded-lg hover:bg-red-500/20 text-red-500 text-left",children:[n.jsx("span",{className:"font-medium",children:g("work:task.cancelWithDependents")}),n.jsx("span",{className:"block text-xs text-red-500/70 mt-0.5",children:g("work:task.cancelWithDependentsHint",{count:B.dependentCount})})]}),n.jsx("button",{onClick:()=>R(null),className:"w-full px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary",children:g("work:task.keepTaskRunning")})]})]})}):B&&n.jsx(dd,{title:g("work:task.cancelTaskModalTitle"),message:g("work:task.cancelConfirmMessage"),confirmLabel:g("work:task.cancelTask"),onConfirm:()=>{R(null),Ve(()=>le.tasks.cancel(e.id))},onCancel:()=>R(null)}),ct&&n.jsx(Tre,{filePath:ct,onClose:()=>st(null),onOpenExternal:()=>{st(null),le.deliverables.search({taskId:e.id,limit:100}).then(({results:Ie})=>{const At=Ie.find(It=>It.reference===ct);At?pt.navigate(Te.DELIVERABLES,{openDeliverable:At.id}):pt.navigate(Te.DELIVERABLES)}).catch(()=>pt.navigate(Te.DELIVERABLES))}}),Ye&&e.scheduleConfig&&n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:()=>Qe(!1),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-6 w-[380px] shadow-2xl",onClick:Ie=>Ie.stopPropagation(),children:[n.jsx("h3",{className:"font-semibold text-base mb-2",children:g("work:task.scheduleApproveTitle")}),n.jsx("p",{className:"text-sm text-fg-secondary mb-5 leading-relaxed",children:g("work:task.scheduleApproveDesc",{schedule:e.scheduleConfig.cron?`Cron: ${e.scheduleConfig.cron}`:e.scheduleConfig.every?g("work:task.scheduleEvery",{interval:e.scheduleConfig.every}):"",nextRun:e.scheduleConfig.nextRunAt?new Date(e.scheduleConfig.nextRunAt).toLocaleString():g("work:task.scheduleNA")})}),n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("button",{disabled:Y,onClick:()=>{Qe(!1),Ve(()=>le.tasks.approve(e.id,!0))},className:"w-full px-4 py-2.5 text-sm bg-green-600 hover:bg-green-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50",children:g("work:task.scheduleApproveRunNow")}),n.jsx("button",{disabled:Y,onClick:()=>{Qe(!1),Ve(()=>le.tasks.approve(e.id,!1))},className:"w-full px-4 py-2.5 text-sm bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50",children:g("work:task.scheduleApproveWait")}),n.jsx("button",{onClick:()=>Qe(!1),className:"w-full px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary",children:g("common:cancel")})]})]})})]})}function Are({project:e,tasks:t,requirements:r,agents:s,onDeleteProject:a,onUpdateProject:i,onRefresh:l}){const d=x.useMemo(()=>t.filter(B=>B.projectId===e.id),[t,e.id]),u=x.useMemo(()=>r.filter(B=>B.projectId===e.id),[r,e.id]),m=x.useMemo(()=>{const B={total:d.length,completed:0,inProgress:0,inReview:0,blocked:0,pending:0,failed:0,reqs:u.length,reqsDone:0};for(const R of d)R.status==="completed"||R.status==="accepted"?B.completed++:R.status==="in_progress"?B.inProgress++:R.status==="review"||R.status==="revision"?B.inReview++:R.status==="blocked"?B.blocked++:R.status==="failed"?B.failed++:B.pending++;for(const R of u)R.status==="completed"&&B.reqsDone++;return B},[d,u]),h=x.useMemo(()=>new Set(d.map(B=>B.assignedAgentId).filter(Boolean)),[d]),p=x.useMemo(()=>s.filter(B=>h.has(B.id)),[s,h]),[y,g]=x.useState(!1),[v,j]=x.useState(""),[C,w]=x.useState("main"),[N,S]=x.useState(!1),{t:T}=ft(["work","common"]),M=[{value:"active",label:T("work:project.statusActive"),desc:T("work:project.statusActiveDesc")},{value:"paused",label:T("work:project.statusPaused"),desc:T("work:project.statusPausedDesc")},{value:"archived",label:T("work:project.statusArchived"),desc:T("work:project.statusArchivedDesc")}],D=async B=>{if(B!==e.status){S(!0);try{await i({status:B}),l()}finally{S(!1)}}},I=async()=>{const B=v.trim();if(!B)return;const R=[...e.repositories??[],{url:"",localPath:B,defaultBranch:C||"main"}];await i({repositories:R}),j(""),w("main"),g(!1),l()},$=async B=>{const R=(e.repositories??[]).filter((U,W)=>W!==B);await i({repositories:R}),l()};return n.jsxs("div",{className:"p-5 space-y-5 max-w-3xl",children:[n.jsxs("div",{className:"space-y-3",children:[n.jsx(gre,{value:e.description??"",onSave:async B=>{await i({description:B}),l()},className:"text-sm text-fg-secondary",placeholder:T("work:project.descriptionPlaceholderLong")}),n.jsxs("div",{className:"flex items-center gap-3 text-xs text-fg-tertiary",children:[e.createdAt&&n.jsxs("span",{children:[T("work:project.createdLabel")," ",new Date(e.createdAt).toLocaleDateString()]}),e.updatedAt&&n.jsxs("span",{children:[T("work:project.updatedLabel")," ",new Date(e.updatedAt).toLocaleDateString()]})]})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:T("work:project.projectStatusHeading")}),n.jsx("div",{className:"flex gap-2",children:M.map(B=>n.jsxs("button",{disabled:N,onClick:()=>D(B.value),className:`flex-1 px-3 py-2 rounded-lg text-xs font-medium transition-all ${e.status===B.value?B.value==="active"?"bg-green-500/15 text-green-600 ring-1 ring-green-500/30":B.value==="paused"?"bg-amber-500/15 text-amber-600 ring-1 ring-amber-500/30":"bg-gray-500/15 text-fg-tertiary ring-1 ring-gray-500/30":"bg-surface-elevated text-fg-tertiary hover:text-fg-secondary hover:bg-surface-overlay"} ${N?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:[n.jsx("div",{children:B.label}),n.jsx("div",{className:"text-[10px] opacity-70 mt-0.5",children:B.desc})]},B.value))})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:T("work:project.taskOverview")}),n.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-6 gap-3",children:[n.jsx(So,{label:T("work:project.statTotal"),value:m.total,color:"text-fg-primary"}),n.jsx(So,{label:T("work:project.statCompleted"),value:m.completed,color:"text-green-600"}),n.jsx(So,{label:T("work:project.statInProgress"),value:m.inProgress,color:"text-brand-500"}),n.jsx(So,{label:T("work:project.statInReview"),value:m.inReview,color:"text-brand-500"}),n.jsx(So,{label:T("work:project.statBlocked"),value:m.blocked,color:"text-amber-600"}),n.jsx(So,{label:T("work:project.statFailed"),value:m.failed,color:"text-red-500"})]}),m.total>0&&n.jsxs("div",{className:"mt-3 flex h-2 rounded-full overflow-hidden bg-surface-elevated",children:[m.completed>0&&n.jsx("div",{className:"bg-green-500",style:{width:`${m.completed/m.total*100}%`}}),m.inProgress>0&&n.jsx("div",{className:"bg-brand-500",style:{width:`${m.inProgress/m.total*100}%`}}),m.inReview>0&&n.jsx("div",{className:"bg-brand-500",style:{width:`${m.inReview/m.total*100}%`}}),m.blocked>0&&n.jsx("div",{className:"bg-amber-500",style:{width:`${m.blocked/m.total*100}%`}}),m.pending>0&&n.jsx("div",{className:"bg-blue-500/40",style:{width:`${m.pending/m.total*100}%`}}),m.failed>0&&n.jsx("div",{className:"bg-red-500",style:{width:`${m.failed/m.total*100}%`}})]})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:T("work:project.requirementsHeading")}),n.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[n.jsx(So,{label:T("work:project.statTotal"),value:m.reqs,color:"text-fg-primary"}),n.jsx(So,{label:T("work:project.statCompleted"),value:m.reqsDone,color:"text-green-600"}),n.jsx(So,{label:T("work:project.statActive"),value:m.reqs-m.reqsDone,color:"text-brand-500"})]})]}),p.length>0&&n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary mb-3",children:T("work:project.agentsHeading",{count:p.length})}),n.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(B=>{const R=d.filter(W=>W.assignedAgentId===B.id),U=R.filter(W=>!["completed","failed","cancelled","archived"].includes(W.status));return n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-surface-elevated/60 rounded-lg",children:[n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${B.status==="working"?"bg-blue-500":B.status==="idle"?"bg-green-500":"bg-gray-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary",children:B.name}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:T("work:project.agentTaskCounts",{active:U.length,total:R.length})})]},B.id)})})]}),n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h4",{className:"text-xs font-semibold text-fg-secondary",children:T("work:project.repositories")}),n.jsx("button",{onClick:()=>g(!y),className:"text-[10px] text-brand-500 hover:text-brand-500",children:T(y?"common:cancel":"work:project.addRepo")})]}),(e.repositories??[]).length===0&&!y&&n.jsx("p",{className:"text-xs text-fg-tertiary",children:T("work:project.noReposLinked")}),(e.repositories??[]).map((B,R)=>n.jsxs("div",{className:"flex items-center gap-2 py-1.5 group",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:[n.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),n.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 min-w-0 truncate",children:B.url||B.localPath}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:B.defaultBranch}),n.jsx("button",{onClick:()=>$(R),className:"text-fg-tertiary hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",title:T("work:project.removeRepo"),children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},R)),y&&n.jsxs("div",{className:"mt-2 space-y-2 p-3 bg-surface-elevated rounded-lg border border-border-default",children:[n.jsx("input",{value:v,onChange:B=>j(B.target.value),placeholder:T("work:project.repoPathPlaceholder"),className:"w-full px-2.5 py-1.5 text-xs bg-surface-primary border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{value:C,onChange:B=>w(B.target.value),placeholder:T("work:project.repoBranchPlaceholder"),className:"flex-1 px-2.5 py-1.5 text-xs bg-surface-primary border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary"}),n.jsx("button",{onClick:I,disabled:!v.trim(),className:"px-3 py-1.5 text-xs bg-brand-600 text-white rounded-md hover:bg-brand-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:T("work:task.add")})]})]})]}),n.jsxs("div",{className:"border border-red-500/20 rounded-xl p-4",children:[n.jsx("h4",{className:"text-xs font-semibold text-red-500/80 mb-2",children:T("work:project.dangerZone")}),n.jsx("p",{className:"text-[11px] text-fg-tertiary mb-3",children:T("work:project.dangerZoneDeleteHint")}),n.jsx("button",{onClick:a,className:"px-3 py-1.5 text-xs text-red-500 border border-red-500/30 hover:bg-red-500/10 rounded-lg transition-colors",children:T("work:project.deleteProject")})]})]})}function So({label:e,value:t,color:r}){return n.jsxs("div",{className:"text-center py-2",children:[n.jsx("div",{className:`text-xl font-bold ${r}`,children:t}),n.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:e})]})}const J8={pending:"todo",in_progress:"in_progress",completed:"done",rejected:"closed",cancelled:"closed",archived:"closed"},eC={failed:"rejected",todo:"pending",in_progress:"in_progress",review:"in_progress",done:"completed",closed:"cancelled"},Ere={urgent:0,high:1,medium:2,low:3},L3={failed:0,todo:1,in_progress:2,review:3,done:4,closed:5},P3={failed:"border-l-red-500 bg-red-500/5",todo:"border-l-blue-500 bg-blue-500/5",in_progress:"border-l-brand-500 bg-brand-500/5",review:"border-l-purple-500 bg-brand-500/5",done:"border-l-green-500 bg-green-500/5",closed:"border-l-gray-500 bg-gray-500/5"},Mre={failed:"border-l-red-500 text-red-500",todo:"border-l-blue-500 text-blue-600",in_progress:"border-l-brand-500 text-brand-500",review:"border-l-purple-500 text-brand-500",done:"border-l-green-500 text-green-600",closed:"border-l-gray-500 text-fg-tertiary"},Dre=["pending","in_progress","completed","rejected","cancelled","archived"];function Rre(e){for(const t of My)if(t.statuses.includes(e))return t.id;return"closed"}function O3(e,t){const r=Date.now()-new Date(e).getTime(),s=Math.floor(r/6e4);if(s<1)return t("work:relative.justNow");if(s<60)return t("work:relative.minutesAgo",{count:s});const a=Math.floor(s/60);if(a<24)return t("work:relative.hoursAgo",{count:a});const i=Math.floor(a/24);return t("work:relative.daysAgo",{count:i})}function Sf({value:e,options:t,onSelect:r,allowedValues:s}){const[a,i]=x.useState(!1),l=x.useRef(null),d=x.useRef(null),u=t.find(m=>m.value===e);return x.useEffect(()=>{if(!a)return;const m=h=>{d.current&&!d.current.contains(h.target)&&l.current&&!l.current.contains(h.target)&&i(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]),n.jsxs("div",{className:"relative",children:[n.jsx("button",{ref:l,onClick:()=>i(m=>!m),className:`text-[11px] px-2 py-0.5 rounded-full font-medium transition-colors cursor-pointer hover:ring-1 hover:ring-current/30 ${u?.cls??"bg-gray-500/15 text-fg-tertiary"}`,children:u?.label??e}),a&&n.jsx("div",{ref:d,className:"absolute top-full left-0 mt-1 w-40 bg-surface-overlay border border-border-default rounded-lg shadow-xl z-50 py-1 max-h-64 overflow-y-auto",children:t.map(m=>{const h=m.value===e,p=h||!s||s.has(m.value);return n.jsxs("button",{disabled:!p,onClick:()=>{!h&&p&&r(m.value),i(!1)},className:`w-full text-left px-3 py-1.5 text-[11px] flex items-center gap-2 transition-colors ${h?"bg-surface-elevated":p?"hover:bg-surface-elevated/60":"opacity-35 cursor-not-allowed"}`,children:[n.jsx("span",{className:`inline-block w-2 h-2 rounded-full shrink-0 ${p?m.cls.split(" ")[0]:"bg-gray-600"}`}),n.jsx("span",{className:`font-medium ${h?"text-fg-primary":p?"text-fg-secondary":"text-fg-muted"}`,children:m.label}),h&&n.jsx("svg",{className:"w-3 h-3 ml-auto text-brand-500",viewBox:"0 0 12 12",fill:"none",children:n.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},m.value)})})]})}function _3({row:e,idx:t,dragIdx:r,agentMap:s,projMap:a,onTaskClick:i,onReqClick:l,onRowDragStart:d,onRowDragEnd:u,handleStatusChange:m,handlePriorityChange:h,selected:p,isMobile:y,isAbnormalBlocked:g}){const{t:v}=ft(["work","common"]),j=x.useMemo(()=>Q8(v),[v]),C=x.useMemo(()=>Dy(v),[v]),w=x.useMemo(()=>kre(v),[v]),N=e.data.status,S=e.data.priority,T=e.kind==="task"?s.get(e.data.assignedAgentId??""):void 0,M=(()=>{const I=a.get((e.kind==="task",e.data.projectId??""));return I&&I.name!=="default"?I:void 0})(),D=e.kind==="req"?n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded font-semibold bg-amber-500/15 text-amber-600",children:v("work:task.requirementShort")}):e.data.taskType==="scheduled"?n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded font-semibold bg-blue-500/15 text-blue-600",children:v("work:task.schedShort")}):n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded font-semibold bg-gray-500/15 text-fg-secondary",children:v("work:task.taskShort")});return y?n.jsxs("div",{onClick:()=>e.kind==="task"?i(e.data):l(e.data),className:`px-3 py-2 border-b border-border-default/40 cursor-pointer transition-colors border-l-2 ${P3[e.group]??"border-l-gray-700"} ${p?"bg-brand-500/10 border-l-brand-500":"active:bg-surface-elevated/50"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[D,g&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded font-semibold bg-red-500/15 text-red-500",children:"⚠"}),n.jsx("span",{className:"text-sm text-fg-primary truncate flex-1",children:e.data.title})]}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[n.jsx("div",{onClick:I=>I.stopPropagation(),children:n.jsx(Sf,{value:N,options:e.kind==="task"?A3.map(I=>({value:I,label:j[I]?.label??I,cls:j[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})):E3.map(I=>({value:I,label:C[I]?.label??I,cls:C[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})),allowedValues:e.kind==="task"?M3[N]:x1[N],onSelect:I=>{m(e,I)}})}),n.jsx("div",{onClick:I=>I.stopPropagation(),children:n.jsx(Sf,{value:S,options:T3.map(I=>({value:I,label:w[I]?.label??I,cls:w[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})),onSelect:I=>{h(e,I)}})}),T&&n.jsxs("span",{className:"flex items-center gap-1 text-[10px]",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[T.status]??"bg-gray-500"}`}),n.jsx("span",{className:`${D3[T.status]??"text-fg-secondary"}`,children:T.name})]}),M?.name&&n.jsx("span",{className:"text-[10px] text-brand-400/70 truncate max-w-[80px]",children:M.name}),n.jsx("span",{className:"text-[9px] text-fg-muted ml-auto",children:O3(e.data.updatedAt??"",v)})]})]}):n.jsxs("div",{draggable:!0,onDragStart:I=>d(I,t),onDragEnd:u,onClick:()=>e.kind==="task"?i(e.data):l(e.data),className:`flex items-center gap-2 px-6 py-2 border-b border-border-default/40 cursor-pointer transition-colors border-l-2 ${P3[e.group]??"border-l-gray-700"} ${r===t?"opacity-40":""} ${p?"bg-brand-500/10 border-l-brand-500 hover:bg-brand-500/15":"hover:bg-surface-elevated/50"}`,children:[n.jsx("div",{className:"w-12 shrink-0",children:D}),n.jsxs("div",{className:"flex-1 min-w-[200px] text-sm text-fg-primary truncate flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate",children:e.data.title}),g&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded font-semibold bg-red-500/15 text-red-500 shrink-0",children:"⚠"})]}),n.jsx("div",{className:"w-[130px] shrink-0",onClick:I=>I.stopPropagation(),children:n.jsx(Sf,{value:N,options:e.kind==="task"?A3.map(I=>({value:I,label:j[I]?.label??I,cls:j[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})):E3.map(I=>({value:I,label:C[I]?.label??I,cls:C[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})),allowedValues:e.kind==="task"?M3[N]:x1[N],onSelect:I=>{m(e,I)}})}),n.jsx("div",{className:"w-[100px] shrink-0",onClick:I=>I.stopPropagation(),children:n.jsx(Sf,{value:S,options:T3.map(I=>({value:I,label:w[I]?.label??I,cls:w[I]?.cls??"bg-gray-500/15 text-fg-tertiary"})),onSelect:I=>{h(e,I)}})}),n.jsx("div",{className:"w-[120px] shrink-0 text-[11px] truncate",children:T?n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[T.status]??"bg-gray-500"}`}),n.jsx("span",{className:`font-medium ${D3[T.status]??"text-fg-secondary"}`,children:T.name})]}):n.jsx("span",{className:"text-fg-muted",children:"—"})}),n.jsx("div",{className:"w-[120px] shrink-0 text-[11px] truncate",children:M?.name?n.jsx("span",{className:"text-brand-400/70",children:M.name}):n.jsx("span",{className:"text-fg-muted",children:"—"})}),n.jsx("div",{className:"w-[90px] shrink-0 text-[10px] text-fg-muted text-right",children:O3(e.data.updatedAt??"",v)})]})}function Ire({tasks:e,requirements:t,agents:r,projects:s,onTaskClick:a,onReqClick:i,onRefresh:l,selectedTaskId:d,selectedReqId:u}){const{t:m}=ft(["work","common"]),h=Ds(),[p,y]=x.useState("status"),[g,v]=x.useState(null),[j,C]=x.useState(null),w=x.useMemo(()=>{const _=new Map;for(const G of e)_.set(G.id,G);return _},[e]),N=x.useCallback(_=>_.status!=="blocked"?!1:!_.blockedBy||_.blockedBy.length===0?!0:_.blockedBy.every(G=>{const V=w.get(G);return V&&V.status==="completed"}),[w]),S=x.useMemo(()=>{const _=[];for(const G of e){const V=Rre(G.status);_.push({kind:"task",data:G,group:V,groupOrder:L3[V]??5})}for(const G of t){const V=J8[G.status]??"todo";_.push({kind:"req",data:G,group:V,groupOrder:L3[V]??5})}if(p==="status")_.sort((G,V)=>{if(G.groupOrder!==V.groupOrder)return G.groupOrder-V.groupOrder;const O=new Date(G.data.updatedAt??0).getTime();return new Date(V.data.updatedAt??0).getTime()-O});else{const G=V=>Ere[V.data.priority]??2;_.sort((V,O)=>{const q=G(V),J=G(O);return q!==J?q-J:new Date(O.data.updatedAt??0).getTime()-new Date(V.data.updatedAt??0).getTime()})}return _},[e,t,p]),T=async(_,G)=>{try{_.kind==="task"?await le.tasks.updateStatus(_.data.id,G):await le.requirements.updateStatus(_.data.id,G),l()}catch{}},M=async(_,G)=>{try{_.kind==="task"?await le.tasks.update(_.data.id,{priority:G}):await le.requirements.update(_.data.id,{priority:G}),l()}catch{}},D=(_,G)=>{v(G),_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/plain",String(G)),_.currentTarget.style.opacity="0.4"},I=_=>{_.currentTarget.style.opacity="1",v(null),C(null)},$=(_,G)=>{_.preventDefault(),_.dataTransfer.dropEffect="move",j!==G&&C(G)},B=async(_,G)=>{if(_.preventDefault(),C(null),g==null)return;const V=S[g];if(!V||V.group===G)return;const O=My.find(q=>q.id===G);if(O){try{if(V.kind==="task"){if(V.data.status==="pending")return;await le.tasks.updateStatus(V.data.id,O.dropStatus)}else{const q=eC[G];q&&await le.requirements.updateStatus(V.data.id,q)}l()}catch{}v(null)}},R=x.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),U=x.useMemo(()=>new Map(s.map(_=>[_.id,_])),[s]),W=["todo","in_progress","review","done"],F=x.useMemo(()=>{const _={};for(const G of S)_[G.group]=(_[G.group]??0)+1;return _},[S]),{rowsByGroup:L,rowIndexMap:z}=x.useMemo(()=>{const _=new Map,G=new Map;for(let V=0;V<S.length;V++){const O=S[V];G.set(O,V);const q=_.get(O.group)??[];q.push(O),_.set(O.group,q)}return{rowsByGroup:_,rowIndexMap:G}},[S]),E=x.useMemo(()=>{if(p!=="status")return null;const _=new Set(S.map(O=>O.group)),G=[],V=new Set;_.has("failed")&&(G.push("failed"),V.add("failed"));for(const O of W)G.push(O),V.add(O);for(const O of S)V.has(O.group)||(G.push(O.group),V.add(O.group));return G},[S,p]);return n.jsx("div",{className:`flex-1 min-h-0 overflow-auto bg-surface-primary ${h?"overflow-x-hidden w-full":""}`,children:n.jsxs("div",{className:h?"w-full":"w-fit min-w-full",children:[!h&&n.jsxs("div",{className:"flex items-center gap-2 px-6 py-2 border-b border-border-default text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider sticky top-0 z-20 bg-surface-primary",children:[n.jsx("div",{className:"w-12 shrink-0 text-fg-muted normal-case font-normal",children:S.length}),n.jsx("div",{className:"flex-1 min-w-[200px]",children:m("work:task.backlogTitle")}),n.jsxs("button",{onClick:()=>y("status"),className:`w-[130px] shrink-0 text-left flex items-center gap-1 transition-colors ${p==="status"?"text-brand-500":"hover:text-fg-secondary"}`,children:[m("work:filters.status")," ",p==="status"&&n.jsx("span",{className:"text-[8px]",children:"▼"})]}),n.jsxs("button",{onClick:()=>y("priority"),className:`w-[100px] shrink-0 text-left flex items-center gap-1 transition-colors ${p==="priority"?"text-brand-500":"hover:text-fg-secondary"}`,children:[m("work:filters.priority")," ",p==="priority"&&n.jsx("span",{className:"text-[8px]",children:"▼"})]}),n.jsx("div",{className:"w-[120px] shrink-0",children:m("work:filters.assignee")}),n.jsx("div",{className:"w-[120px] shrink-0",children:m("work:task.projectLabel")}),n.jsx("div",{className:"w-[90px] shrink-0 text-right",children:m("work:task.backlogUpdated")})]}),n.jsxs("div",{children:[p==="status"&&E?E.map(_=>{const G=L.get(_)??[];return n.jsxs("div",{children:[n.jsxs("div",{className:`flex items-center gap-2 px-6 py-2 border-l-2 bg-surface-primary/80 sticky top-0 z-10 ${Mre[_]??""} ${j===_?"ring-1 ring-brand-500/40":""}`,onDragOver:V=>$(V,_),onDragLeave:()=>C(null),onDrop:V=>{B(V,_)},children:[n.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider",children:m(`work:boardColumn.${_}`)}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:F[_]??0})]}),G.map(V=>n.jsx(_3,{row:V,idx:z.get(V)??0,dragIdx:g,agentMap:R,projMap:U,onTaskClick:a,onReqClick:i,onRowDragStart:D,onRowDragEnd:I,handleStatusChange:T,handlePriorityChange:M,selected:V.kind==="task"?V.data.id===d:V.data.id===u,isMobile:h,isAbnormalBlocked:V.kind==="task"?N(V.data):!1},`${V.kind}-${V.data.id}`))]},_)}):S.map((_,G)=>n.jsx(_3,{row:_,idx:G,dragIdx:g,agentMap:R,projMap:U,onTaskClick:a,onReqClick:i,onRowDragStart:D,onRowDragEnd:I,handleStatusChange:T,handlePriorityChange:M,selected:_.kind==="task"?_.data.id===d:_.data.id===u,isMobile:h,isAbnormalBlocked:_.kind==="task"?N(_.data):!1},`${_.kind}-${_.data.id}`)),S.length===0&&n.jsx("div",{className:"flex items-center justify-center py-16 text-sm text-fg-tertiary",children:m("work:task.noItems")})]})]})})}function z3({authUser:e,previewMode:t,previewData:r}={}){const{t:s}=ft(["work","common"]),a=Rd(Te.WORK),i=x.useMemo(()=>My.map(ie=>({...ie,label:s(`work:boardColumn.${ie.id}`)})),[s]),l=x.useMemo(()=>Z8(s),[s]),d=x.useMemo(()=>Dy(s),[s]),u=Ds(),m=x.useRef(null),[h,p]=x.useState(0);x.useEffect(()=>{const ie=m.current;if(!ie)return;const Xe=new ResizeObserver(([ot])=>p(ot.contentRect.width));return Xe.observe(ie),p(ie.clientWidth),()=>Xe.disconnect()},[]);const y=h||window.innerWidth,g=x.useRef(!1),v=m0({side:"right",defaultWidth:Math.round(y/2),minWidth:380,maxWidth:Math.round(y*.8),storageKey:"markus_projects_detail_v4"});x.useEffect(()=>{h>0&&!g.current&&(g.current=!0,v.setWidth(Math.round(h/2)))},[h]);const[j,C]=x.useState(!1),w=x.useRef(j);w.current=j;const[N,S]=x.useState(r?.projects??[]),[T,M]=x.useState("all"),[D,I]=x.useState(null),[$,B]=x.useState(r?.board??{}),[R,U]=x.useState(r?.agents??[]),[W,F]=x.useState(r?.users??[]),[L,z]=x.useState(r?.allRequirements??[]),[E,_]=x.useState(!r),[G,V]=x.useState(""),[O,q]=x.useState(!1),[J,H]=x.useState(null),Z=x.useCallback(()=>{qt(D??""),mr(!0)},[D]),[Y,ee]=x.useState(!1),[ae,Q]=x.useState(!1),[me,Ae]=x.useState(""),[Me,He]=x.useState(""),[je,xe]=x.useState("medium"),[Pe,Ce]=x.useState(""),[Ye,Qe]=x.useState(""),[ct,st]=x.useState(""),[zt,mt]=x.useState(""),[te,de]=x.useState([]),[be,se]=x.useState("standard"),[fe,$e]=x.useState("4h"),[Ne,Ze]=x.useState(""),[pe,ze]=x.useState(null),[Fe,Je]=x.useState(()=>r?.initialSelectedReqId&&r.allRequirements?r.allRequirements.find(ie=>ie.id===r.initialSelectedReqId)??null:null),[gt,nt]=x.useState(new Set),[Et,dt]=x.useState(!1),[Ve,Rt]=x.useState(new Set),un=x.useRef(new Set),yn=x.useRef(new Set),[sn,In]=x.useState(null),[jn,Vt]=x.useState(r?.initialBoardType??"backlog"),mn=x.useMemo(()=>[{id:"backlog"},{id:"kanban"},{id:"dag"}],[]),Vn=Sl(mn,jn,Vt),Xn=x.useRef(null),Rr=x.useMemo(()=>({scrollContainerRef:Xn}),[]),qe=Sl(mn,jn,Vt,Rr),[St,_e]=x.useState(!1),[Tt,Ot]=x.useState(null),[Gt,Tn]=x.useState(!1),_n=x.useRef(null),Sn=x.useRef(null),[Fn,mr]=x.useState(!1),[rr,fr]=x.useState(""),[Qn,ir]=x.useState(""),[Ie,At]=x.useState("medium"),[It,qt]=x.useState(""),[Jt,tn]=x.useState(null),[An,br]=x.useState(""),[an,ye]=x.useState(""),[at,yt]=x.useState(""),[Ht,ln]=x.useState(null),Mt=ie=>{V(ie),setTimeout(()=>V(""),3e3)},Ln=N.find(ie=>ie.id===D)??null,Zn=Ln??N.find(ie=>ie.id===J)??null,zn=x.useCallback(()=>{q(!1),H(null)},[]),Jn=x.useCallback(ie=>{if(O&&(D===ie||J===ie)){zn();return}D||H(ie),q(!0)},[O,D,J,zn]);x.useEffect(()=>{yn.current=Ve},[Ve]);const Pn=x.useCallback(async()=>{try{const{projects:ie}=await le.projects.list();S(ie)}catch{}},[]),on=x.useCallback(async()=>{const ie={};T==="project"&&D&&(ie.projectId=D);try{const{board:Xe}=await le.tasks.board(ie);B(Xe)}catch{}},[T,D]),lr=x.useCallback(async()=>{try{const{agents:ie}=await le.agents.list();U(ie)}catch{}},[]),qr=x.useCallback(async()=>{try{const{users:ie}=await le.users.list(e?.orgId);F(ie)}catch{}},[e?.orgId]),cr=x.useCallback(async()=>{try{const{requirements:ie}=await le.requirements.list({});z(ie)}catch{}},[]),yr=x.useCallback(async()=>{await Promise.all([Pn(),on(),lr(),qr(),cr()]),_(!1)},[Pn,on,lr,qr,cr]);x.useEffect(()=>{t||yr()},[t,yr]),x.useEffect(()=>{!t||!r||(S(r.projects??[]),B(r.board??{}),U(r.agents??[]),F(r.users??[]),z(r.allRequirements??[]))},[t,r]);const ur=x.useCallback(ie=>{ze(Xe=>Xe?.id===ie.id?(u&&w.current&&C(!1),null):(u&&(C(!0),history.pushState({mobileDetail:Te.WORK},"",window.location.hash)),ie)),Je(null)},[u]),Rs=x.useCallback(ie=>{Je(Xe=>Xe?.id===ie.id?(u&&w.current&&C(!1),null):(u&&(C(!0),history.pushState({mobileDetail:Te.WORK},"",window.location.hash)),ie)),ze(null)},[u]),ha=x.useCallback(()=>{ze(null),Je(null),u&&w.current&&C(!1)},[u]),pa=x.useCallback(()=>{ze(null),!Ja.current&&u&&w.current&&C(!1)},[u]);x.useEffect(()=>{if(!u)return;const ie=()=>{w.current&&(C(!1),ze(null),Je(null))};return window.addEventListener("popstate",ie),()=>window.removeEventListener("popstate",ie)},[u]);const Or=x.useRef(pe);Or.current=pe;const Ja=x.useRef(Fe);Ja.current=Fe,x.useEffect(()=>{const ie=Xe=>{if(Xe.key!=="Escape")return;const ot=Xe.target?.tagName;if(!(ot==="INPUT"||ot==="TEXTAREA"||ot==="SELECT")){if(Or.current){ze(null);return}if(Ja.current){Je(null);return}}};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]),x.useEffect(()=>{if(t||!a)return;const ie=Or.current?12e4:45e3,Xe=setInterval(()=>{on(),lr(),cr()},ie);let ot=null;const Dt=()=>{ot||(ot=setTimeout(()=>{ot=null,on()},800))};let fn=null;const hr=()=>{fn||(fn=setTimeout(()=>{fn=null,cr()},800))},cn=pn.on("task:update",is=>{Dt();const Kr=is?.payload;Kr?.taskId&&ze(ms=>{if(!ms||ms.id!==Kr.taskId)return ms;const Nr={};return typeof Kr.status=="string"&&(Nr.status=Kr.status),Array.isArray(Kr.deliverables)&&(Nr.deliverables=Kr.deliverables),Array.isArray(Kr.notes)&&(Nr.notes=Kr.notes),Kr.result!==void 0&&(Nr.result=Kr.result),{...ms,...Nr}})}),bt=pn.on("task:create",()=>{Dt()}),Vr=["requirement:created","requirement:approved","requirement:rejected","requirement:updated","requirement:completed","requirement:cancelled","requirement:resubmitted"].map(is=>pn.on(is,()=>{hr()})),us=()=>{pl("/taskboard"),on(),cr()};return window.addEventListener("markus:data-changed",us),()=>{clearInterval(Xe),cn(),bt(),Vr.forEach(is=>is()),window.removeEventListener("markus:data-changed",us),ot&&clearTimeout(ot),fn&&clearTimeout(fn)}},[t,a,on,lr,cr]);const ga=x.useRef($);ga.current=$;const na=x.useRef(L);na.current=L;const cs=x.useCallback(ie=>{if(!ie)return;const Xe=yn.current;Xe.size>0&&!Xe.has(ie)&&Rt(ot=>new Set([...ot,ie]))},[]),[ei,ti]=x.useState(!1),Oa=x.useCallback((ie,Xe)=>{ze(ie),Je(null),Xe?.scrollToComments&&ti(!0),u&&C(!0)},[u]),bi=x.useCallback((ie,Xe)=>{Je(ie),ze(null),Xe?.scrollToComments&&ti(!0),u&&C(!0)},[u]),ni=x.useRef(null);x.useEffect(()=>{const ie=ni.current||localStorage.getItem("markus_nav_openTask");if(!ie)return;const ot=Object.values($).flat().find(Dt=>Dt.id===ie);ot?(ni.current=null,cs(ot.projectId),Oa(ot),localStorage.removeItem("markus_nav_openTask")):ni.current||(ni.current=ie,localStorage.removeItem("markus_nav_openTask"),le.tasks.get(ie).then(Dt=>{Dt.task&&(ni.current=null,cs(Dt.task.projectId),Oa(Dt.task))}).catch(()=>{ni.current=null}))},[$,Oa,cs]);const ra=x.useRef(null);x.useEffect(()=>{const ie=ra.current||localStorage.getItem("markus_nav_openRequirement");if(!ie)return;const Xe=L.find(ot=>ot.id===ie);Xe?(ra.current=null,cs(Xe.projectId),bi(Xe),localStorage.removeItem("markus_nav_openRequirement")):ra.current||(ra.current=ie,localStorage.removeItem("markus_nav_openRequirement"),le.requirements.get(ie).then(ot=>{ot.requirement&&(ra.current=null,cs(ot.requirement.projectId),bi(ot.requirement))}).catch(()=>{ra.current=null}))},[L,bi,cs]),x.useEffect(()=>{const ie=window.location.hash.slice(1).split("/");if(nc(ie[0])===Te.WORK&&ie[1])xa(ie[1]);else{const Xe=localStorage.getItem("markus_nav_projectId");Xe&&(localStorage.removeItem("markus_nav_projectId"),xa(Xe))}},[]);const Gs=x.useRef(nc(window.location.hash.slice(1).split("/")[0]));x.useEffect(()=>{if(t)return;const ie=()=>{const ot=window.location.hash.slice(1).split("/"),Dt=nc(ot[0]),fn=Gs.current===Te.WORK;Gs.current=Dt,Dt===Te.WORK&&(Dt===Te.WORK&&ot[1]?xa(ot[1]):fn&&Is())},Xe=async ot=>{const Dt=ot.detail;if(nc(Dt.page)===Te.WORK){if(Dt.params?.openTask){const fn=Dt.params.openTask,hr=Dt.params.scrollToComments==="true";localStorage.removeItem("markus_nav_openTask");let cn=Object.values(ga.current).flat().find(bt=>bt.id===fn);if(!cn)try{cn=(await le.tasks.get(fn)).task}catch{}cn&&(cs(cn.projectId),Oa(cn,{scrollToComments:hr}))}if(Dt.params?.openRequirement){const fn=Dt.params.openRequirement,hr=Dt.params.scrollToComments==="true";let cn=na.current.find(bt=>bt.id===fn);if(!cn)try{cn=(await le.requirements.get(fn)).requirement}catch{}cn&&(cs(cn.projectId),bi(cn,{scrollToComments:hr}))}if(Dt.params?.projectId&&xa(Dt.params.projectId),Dt.params?.statusFilter){const fn=Dt.params.statusFilter;localStorage.removeItem("markus_nav_statusFilter"),wre.has(fn)&&_e(!0),Ot(fn)}}};return window.addEventListener("markus:navigate",Xe),window.addEventListener("hashchange",ie),()=>{window.removeEventListener("markus:navigate",Xe),window.removeEventListener("hashchange",ie)}},[t]);const xa=ie=>{yn.current.size>0&&(un.current=new Set(yn.current)),Rt(new Set),I(ie),M("project"),H(null),q(!1),history.replaceState(null,"",mw(Te.WORK,ie))},Is=()=>{Rt(un.current),I(null),M("all"),H(null),q(!1),history.replaceState(null,"",mw(Te.WORK))},Kn=()=>{ee(!1),Mt(s("work:task.projectCreated")),Pn()},js=async ie=>{if(confirm("Delete this project and unlink all its tasks?"))try{await le.projects.delete(ie),D===ie&&Is(),Mt("Project deleted"),Pn(),on()}catch(Xe){Mt(`Error: ${Xe}`)}},ba=async()=>{if(!me||!Pe||!Ye)return;Ze("");const ie=Ye.startsWith("human:"),Xe=Ye.replace(/^(human|agent):/,"");if(Pe===Xe&&!ie){Mt(s("work:task.assignedReviewerDifferent"));return}const ot=ct||void 0,Dt=zt||void 0;try{const{task:fn}=await le.tasks.create(me,Me,Pe,Xe,je,ot,te.length>0?te:void 0,Dt,be!=="standard"?be:void 0,be==="scheduled"?{every:fe}:void 0,ie?"human":"agent");Ae(""),He(""),de([]),mt(""),se("standard"),$e("4h"),Q(!1),on(),fn&&Oa(fn)}catch(fn){const cn=`work:task.errorCode_${(fn instanceof d6?fn.code:void 0)||"unknown"}`,bt=s(cn,{defaultValue:""});Ze(bt||s("work:task.errorCreatingTask",{message:fn instanceof Error?fn.message:String(fn)}))}},Ns=ie=>{window.dispatchEvent(new CustomEvent("markus:mark-read-by-ref",{detail:ie}))},vr=()=>{on(),pe&&(Ns({taskId:pe.id}),setTimeout(()=>{const ie={};T==="project"&&D&&(ie.projectId=D),le.tasks.board(ie).then(Xe=>{const Dt=Object.values(Xe.board).flat().find(fn=>fn.id===pe.id);ze(Dt||null)}).catch(()=>{})},150))},Ls=()=>{cr(),Fe&&setTimeout(()=>{le.requirements.list({}).then(({requirements:ie})=>{const Xe=ie.find(ot=>ot.id===Fe.id);Je(Xe||null)}).catch(()=>{})},150)},as=async()=>{if(!rr.trim()){ye(s("work:task.pleaseReqTitle"));return}if(!Qn.trim()){ye(s("work:task.pleaseReqDesc"));return}if(!It){ye(s("work:task.pleaseReqProject"));return}ye("");try{const{requirement:ie}=await le.requirements.create({title:rr.trim(),description:Qn.trim(),priority:Ie,projectId:It});Mt(s("work:task.requirementCreated")),fr(""),ir(""),mr(!1),cr(),ie&&bi(ie)}catch(ie){ye(ie instanceof Error?ie.message:String(ie))}},Ur=async ie=>{try{await le.requirements.approve(ie),Mt("Requirement approved"),Ns({requirementId:ie}),Ls(),on()}catch(Xe){Mt(`Error: ${Xe}`)}},ri=async()=>{if(Jt){yt("");try{await le.requirements.reject(Jt,An),Mt("Requirement rejected"),Ns({requirementId:Jt}),tn(null),br(""),yt(""),Ls()}catch(ie){yt(ie instanceof Error?ie.message:String(ie))}}},Ss=async ie=>{try{await le.requirements.cancel(ie),Mt("Requirement cancelled"),Ns({requirementId:ie}),Ls()}catch(Xe){Mt(`Error: ${Xe}`)}},sa=(ie,Xe)=>{_n.current=Xe,Sn.current=null,ie.dataTransfer.effectAllowed="move",ie.dataTransfer.setData("text/plain",`task:${Xe.id}`),ie.currentTarget.style.opacity="0.4"},_a=(ie,Xe)=>{Sn.current=Xe,_n.current=null,ie.dataTransfer.effectAllowed="move",ie.dataTransfer.setData("text/plain",`req:${Xe.id}`),ie.currentTarget.style.opacity="0.4"},Wn=ie=>{ie.currentTarget.style.opacity="1",_n.current=null,Sn.current=null,In(null)},Cs=(ie,Xe)=>{ie.preventDefault(),ie.dataTransfer.dropEffect="move",sn!==Xe&&In(Xe)},Ps=(ie,Xe)=>{const ot=ie.currentTarget.getBoundingClientRect(),{clientX:Dt,clientY:fn}=ie;(Dt<ot.left||Dt>ot.right||fn<ot.top||fn>ot.bottom)&&sn===Xe&&In(null)},Mi=async(ie,Xe)=>{ie.preventDefault(),In(null);const ot=_n.current,Dt=Sn.current;if(ot){const fn=i.find(cn=>cn.id===Xe);if(!fn)return;const hr=fn.dropStatus;if(ot.status===hr||ot.status==="pending")return;try{await le.tasks.updateStatus(ot.id,hr),on()}catch{}}else if(Dt){const fn=eC[Xe];if(!fn||Dt.status===fn)return;try{await le.requirements.updateStatus(Dt.id,fn),cr()}catch{}}},_r=ie=>{nt(Xe=>{const ot=new Set(Xe);return ot.has(ie)?ot.delete(ie):ot.add(ie),ot})},wn=ie=>{T==="project"?D===ie?Is():xa(ie):Rt(Xe=>{const ot=new Set(Xe);return ot.has(ie)?ot.delete(ie):ot.add(ie),ot})},Os=new Set(["rejected","cancelled","archived"]),Hs=ie=>Os.has(ie.status),si=(ie,Xe=!1)=>{let ot=ie.filter(Dt=>St||!Hs(Dt));return Tt&&(ot=ot.filter(Dt=>Dt.status===Tt)),T==="project"&&D&&(ot=ot.filter(Dt=>Dt.projectId===D)),Ve.size>0&&(ot=ot.filter(Dt=>Dt.projectId&&Ve.has(Dt.projectId))),gt.size>0&&(ot=ot.filter(Dt=>Dt.assignedAgentId&&gt.has(Dt.assignedAgentId))),Et&&e?.id&&(ot=ot.filter(Dt=>Dt.createdBy===e.id)),ot},ai=x.useMemo(()=>{const ie=new Map;for(const Xe of Object.values($))for(const ot of Xe)ie.set(ot.id,ot);return ie},[$]),Ys=x.useMemo(()=>new Set(R.map(ie=>ie.id)),[R]),$r=ie=>ie.statuses.flatMap(Xe=>si($[Xe]??[])),Fs=x.useMemo(()=>{let ie=L;if(St||(ie=ie.filter(Xe=>!Hs(Xe))),T==="project"&&D&&(ie=ie.filter(Xe=>Xe.projectId===D)),Ve.size>0&&(ie=ie.filter(Xe=>Xe.projectId&&Ve.has(Xe.projectId))),gt.size>0){const Xe=e?.id;ie=ie.filter(ot=>gt.has(ot.createdBy)||Xe!=null&&ot.createdBy===Xe||!Ys.has(ot.createdBy))}return Et&&e?.id&&(ie=ie.filter(Xe=>Xe.createdBy===e.id)),ie},[L,St,T,D,Ve,gt,Et,e?.id,Ys]),ya=x.useCallback(ie=>Fs.filter(Xe=>J8[Xe.status]===ie.id),[Fs]),qs=i.filter(ie=>{if(ie.id==="failed"||ie.id==="closed"){const Xe=$r(ie),ot=ya(ie);return Xe.length+ot.length>0}return!0}),Zr=Object.values($).flat().filter(ie=>Hs(ie)).length+L.filter(ie=>Hs(ie)).length,_s=x.useMemo(()=>{const ie=new Set(["completed","failed","cancelled","archived"]),Xe=Object.values($).flat(),ot=new Set;for(const Dt of Xe)Dt.assignedAgentId&&!ie.has(Dt.status)&&(!D||Dt.projectId===D)&&ot.add(Dt.assignedAgentId);return[...R].sort((Dt,fn)=>{const hr=ot.has(Dt.id)?0:1,cn=ot.has(fn.id)?0:1;return hr-cn})},[R,$,D]),va=x.useMemo(()=>{const ie=new Set(["completed","failed","cancelled","archived"]),Xe=Object.values($).flat(),ot=new Set;for(const Dt of Xe)Dt.projectId&&!ie.has(Dt.status)&&ot.add(Dt.projectId);return[...N].sort((Dt,fn)=>{const hr=Dt.status==="archived"?1:0,cn=fn.status==="archived"?1:0;if(hr!==cn)return hr-cn;const bt=ot.has(Dt.id)?0:1,ds=ot.has(fn.id)?0:1;return bt!==ds?bt-ds:Dt.name.localeCompare(fn.name)})},[N,$]),Di=x.useMemo(()=>{const ie={};for(const Xe of Object.values($))for(const ot of Xe){const Dt=ot.projectId??"__none__";ie[Dt]=(ie[Dt]??0)+1}return ie},[$]),wa=Object.values(Di).reduce((ie,Xe)=>ie+Xe,0);if(E)return n.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary",children:s("work:task.loadingPage")});const ka=!!(pe||Fe),ja=!u&&!!(pe&&Fe);return n.jsxs("div",{ref:m,className:"flex-1 overflow-hidden flex bg-surface-primary",children:[n.jsxs("div",{className:`${u?"flex-1 min-w-0":ka?"shrink-0 min-w-0":"flex-1"} overflow-hidden flex flex-col bg-surface-primary`,style:u?j?{display:"none"}:void 0:ja?{width:0}:ka?{width:`calc(100% - ${v.width}px - 4px)`}:void 0,children:[G&&n.jsx("div",{className:"mx-6 mt-2 px-3 py-1.5 bg-green-500/15 text-green-600 text-xs rounded-lg",children:G}),u?n.jsxs("div",{className:"shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 px-3 h-11",children:[n.jsx(gc,{}),Ln?n.jsxs("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[n.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate",children:Ln.name}),n.jsx("button",{onClick:()=>Jn(Ln.id),className:`w-6 h-6 flex items-center justify-center rounded-md transition-colors shrink-0 ${O?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]}):n.jsx("h2",{className:"text-sm font-semibold text-fg-primary min-w-0 flex-1 truncate",children:N.length===1?N[0].name:s("work:task.projectsCount",{count:N.length})}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n.jsx("button",{onClick:()=>ee(!0),className:"px-2 py-1 text-[11px] bg-teal-600 text-white rounded-md",children:s("work:task.shortProject")}),n.jsx("button",{onClick:Z,className:"px-2 py-1 text-[11px] bg-brand-600 text-white rounded-md",children:s("work:task.shortReq")}),n.jsx("button",{onClick:()=>{st(D??""),Q(!0)},className:"px-2 py-1 text-[11px] border border-amber-500/60 text-amber-600 rounded-md",children:s("work:task.shortTask")})]})]}),n.jsxs("div",{className:"flex items-center gap-2 px-3 h-9",children:[n.jsx("div",{className:"flex items-center border border-border-default/60 rounded-md overflow-hidden shrink-0",children:["backlog","kanban","dag"].map(ie=>n.jsx("button",{onClick:()=>Vt(ie),className:`px-2 py-0.5 text-[10px] font-medium transition-colors ${jn===ie?"bg-brand-600/25 text-brand-500":"text-fg-tertiary"}`,children:s(ie==="backlog"?"work:task.backlog":ie==="kanban"?"work:task.kanban":"work:task.dag")},ie))}),Zr>0&&n.jsx("button",{onClick:()=>_e(ie=>!ie),className:`text-[10px] shrink-0 px-2 py-0.5 rounded-md transition-colors ${St?"bg-surface-overlay text-fg-secondary":"text-fg-tertiary"}`,children:St?s("work:task.hideArchived"):s("work:task.archivedCount",{count:Zr})}),n.jsx("div",{className:"flex-1"}),Tt&&n.jsxs("button",{onClick:()=>Ot(null),className:"px-2 py-0.5 text-[11px] rounded-md font-medium bg-brand-600/20 text-brand-500 ring-1 ring-brand-500/30 flex items-center gap-1",children:[s(`common:status.${Tt==="in_progress"?"inProgress":Tt}`),n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})]}),(Ve.size>0||gt.size>0||Et||N.length>1||R.length>0)&&n.jsxs("button",{onClick:()=>Tn(!0),className:`px-2 py-1 text-[11px] rounded-md font-medium transition-colors flex items-center gap-1 ${Ve.size>0||gt.size>0||Et?"bg-brand-600/20 text-brand-500 ring-1 ring-brand-500/30":"border border-border-default text-fg-secondary"}`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"})}),Ve.size+gt.size+(Et?1:0)>0?s("work:task.filterWithCount",{count:Ve.size+gt.size+(Et?1:0)}):s("work:task.filter")]})]})]}):n.jsxs("div",{className:"flex items-center gap-3 px-6 h-14 shrink-0",children:[Ln?n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n.jsx(w3,{value:Ln.name,onSave:async ie=>{await le.projects.update(Ln.id,{name:ie}),Pn()},className:"text-sm font-semibold text-fg-primary"}),n.jsx("button",{onClick:()=>Jn(Ln.id),className:`w-6 h-6 flex items-center justify-center rounded-md transition-colors ${O?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:s("work:project.settingsTitle"),children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]}):n.jsx("h2",{className:"text-sm font-semibold text-fg-primary shrink-0",children:N.length===1?N[0].name:s("work:task.projectsCount",{count:N.length})}),Zr>0&&n.jsx("button",{onClick:()=>_e(ie=>!ie),className:`text-[10px] shrink-0 px-2 py-0.5 rounded-md transition-colors ${St?"bg-surface-overlay text-fg-secondary":"text-fg-tertiary hover:text-fg-secondary"}`,children:St?s("work:task.hideArchivedWithCount",{count:Zr}):s("work:task.archivedCount",{count:Zr})}),n.jsx("div",{className:"flex items-center border border-border-default/60 rounded-md overflow-hidden shrink-0",children:["backlog","kanban","dag"].map(ie=>n.jsx("button",{onClick:()=>Vt(ie),className:`px-2.5 py-1 text-[10px] font-medium transition-colors ${jn===ie?"bg-brand-600/25 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:s(ie==="backlog"?"work:task.backlog":ie==="kanban"?"work:task.kanban":"work:task.dag")},ie))}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[n.jsx("button",{onClick:()=>ee(!0),className:"px-3 py-1.5 bg-teal-600 hover:bg-teal-500 text-white text-xs rounded-lg font-medium transition-colors",children:s("work:task.shortProject")}),n.jsx("button",{onClick:Z,className:"px-3 py-1.5 bg-brand-600 hover:bg-brand-500 text-white text-xs rounded-lg font-medium transition-colors",children:s("work:task.newRequirement")}),n.jsx("button",{onClick:()=>{st(D??""),Q(!0)},className:"px-3 py-1.5 border border-amber-500/60 text-amber-600 hover:bg-amber-500/10 text-xs rounded-lg font-medium transition-colors",children:s("work:task.newTaskBtn")})]}),n.jsx("div",{className:"flex-1"})]}),!u&&N.length>1&&!D&&!O&&(wa>0||L.length>0)&&n.jsxs("div",{className:"px-6 py-1.5 flex items-center gap-1.5 overflow-x-auto scrollbar-hide shrink-0",children:[n.jsx("button",{onClick:()=>Rt(new Set),className:`text-[10px] text-fg-tertiary hover:text-fg-secondary px-2 py-1 rounded-md bg-surface-elevated/60 hover:bg-surface-overlay shrink-0 transition-all ${Ve.size>0?"visible opacity-100":"invisible opacity-0"}`,children:s("work:task.clear")}),va.map(ie=>{const Xe=Ve.has(ie.id),ot=Di[ie.id]??0,Dt=O&&J===ie.id;return n.jsxs("div",{className:`flex items-center shrink-0 rounded-md overflow-hidden transition-all ${Xe?"bg-brand-500/15 ring-1 ring-brand-500/30":""}`,children:[n.jsxs("button",{onClick:()=>wn(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1 text-[11px] shrink-0 transition-all ${Xe?"text-brand-600":"text-fg-tertiary hover:bg-surface-elevated hover:text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-sm flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-secondary"}`,children:ie.name[0]?.toUpperCase()}),ie.name,ot>0&&n.jsx("span",{className:"text-[9px] text-fg-tertiary ml-0.5",children:ot})]}),Xe&&n.jsx("button",{onClick:()=>Jn(ie.id),className:`px-1.5 py-1 self-stretch flex items-center border-l border-brand-500/20 transition-colors ${Dt?"text-fg-primary bg-surface-overlay":"text-fg-tertiary hover:text-brand-600 hover:bg-brand-500/10"}`,title:s("work:project.editProject"),children:n.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},ie.id)})]}),!u&&(R.length>0||e?.id)&&!O&&(wa>0||L.length>0)&&n.jsxs("div",{className:"px-6 py-1.5 flex items-center gap-1.5 overflow-x-auto scrollbar-hide shrink-0",children:[n.jsx("button",{type:"button",onClick:()=>{nt(new Set),dt(!1)},className:`text-[10px] text-fg-tertiary hover:text-fg-secondary px-2 py-1 rounded-md bg-surface-elevated/60 hover:bg-surface-overlay shrink-0 transition-all ${gt.size>0||Et?"visible opacity-100":"invisible opacity-0"}`,children:s("work:task.clear")}),e?.id&&n.jsx("button",{type:"button",onClick:()=>dt(ie=>!ie),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] shrink-0 transition-all ${Et?"bg-green-600/20 text-green-500 ring-1 ring-green-500/40":"text-fg-tertiary hover:bg-surface-elevated hover:text-fg-secondary"}`,children:s("work:task.myTasks")}),_s.map(ie=>{const Xe=gt.has(ie.id);return n.jsxs("button",{onClick:()=>_r(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] shrink-0 transition-all ${Xe?"bg-brand-600/20 text-brand-500 ring-1 ring-brand-500/40":"text-fg-tertiary hover:bg-surface-elevated hover:text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-secondary"}`,children:ie.name[0]?.toUpperCase()}),ie.name]},ie.id)})]}),O&&Zn?n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[!Ln&&n.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 border-b border-border-default/60 shrink-0",children:[n.jsxs("button",{onClick:zn,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium flex items-center gap-1 shrink-0",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})}),s("common:back")]}),n.jsx(w3,{value:Zn.name,onSave:async ie=>{await le.projects.update(Zn.id,{name:ie}),Pn()},className:"text-sm font-semibold text-fg-primary truncate min-w-0"})]}),n.jsx(Are,{project:Zn,tasks:Object.values($).flat(),requirements:L,agents:R,onDeleteProject:()=>js(Zn.id),onUpdateProject:async ie=>{await le.projects.update(Zn.id,ie)},onRefresh:()=>{Pn()}})]}):wa===0&&Fs.length===0?n.jsx("div",{className:"flex-1 flex items-center justify-center p-8",children:N.length===0?n.jsxs("div",{className:"max-w-sm w-full text-center space-y-3",children:[n.jsx("div",{className:"w-12 h-12 mx-auto rounded-xl bg-brand-500/10 flex items-center justify-center",children:n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-brand-500",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),n.jsx("h3",{className:"text-sm font-medium text-fg-secondary",children:s("work:task.emptyNoProjectsTitle")}),n.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed",children:s("work:task.emptyNoProjectsHint")}),n.jsx("button",{onClick:()=>ee(!0),className:"inline-flex items-center gap-1.5 px-4 py-2 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium transition-colors",children:s("work:project.newProject")})]}):n.jsxs("div",{className:"max-w-sm w-full text-center space-y-3",children:[n.jsx("div",{className:"w-12 h-12 mx-auto rounded-xl bg-brand-500/10 flex items-center justify-center",children:n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-brand-500",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n.jsx("h3",{className:"text-sm font-medium text-fg-secondary",children:s("work:task.emptyNoReqsTitle")}),n.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed whitespace-pre-line",children:s("work:task.emptyNoReqsHint")}),n.jsx("button",{onClick:Z,className:"inline-flex items-center gap-1.5 px-4 py-2 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium transition-colors",children:s("work:task.createRequirementCta")})]})}):jn==="backlog"?n.jsx("div",{className:"flex-1 min-h-0 flex flex-col",onTouchStart:u?Vn.onTouchStart:void 0,onTouchEnd:u?Vn.onTouchEnd:void 0,children:n.jsx(Ire,{tasks:si(Object.values($).flat()),requirements:Fs,agents:R,projects:N,onTaskClick:ie=>ur(ie),onReqClick:ie=>Rs(ie),onRefresh:()=>{on(),cr()},selectedTaskId:pe?.id,selectedReqId:Fe?.id})}):jn==="dag"?n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col relative",onTouchStart:u?Vn.onTouchStart:void 0,onTouchEnd:u?Vn.onTouchEnd:void 0,children:[n.jsx(fre,{tasks:(()=>{const ie=si(Object.values($).flat(),!0);if(t&&Fe){const Xe=new Set(Fe.taskIds??[]);return ie.filter(ot=>Xe.has(ot.id))}return ie})(),requirements:t&&Fe?[Fe]:Fs,agents:R,showArchived:St,onShowArchivedChange:_e,onTaskClick:ie=>ur(ie),onReqClick:ie=>Rs(ie),onCollapseDAG:()=>{ze(null),Je(null)},onDependencyChange:on,selectedTaskId:pe?.id,selectedReqId:Fe?.id,hasDetailPanel:ka,defaultExpandedNodeId:t&&Fe?`req-${Fe.id}`:void 0,previewMode:t}),u&&n.jsx("button",{onClick:()=>Vt("kanban"),className:"absolute left-3 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-brand-500 border border-brand-400/60 shadow-xl shadow-brand-500/30 flex items-center justify-center text-white active:bg-brand-400 backdrop-blur-sm z-10",title:s("work:task.backToKanban"),children:n.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z",clipRule:"evenodd"})})})]}):n.jsx("div",{ref:Xn,className:"flex-1 min-h-0 overflow-x-auto overflow-y-hidden px-4 py-5",onTouchStart:u?qe.onTouchStart:void 0,onTouchEnd:u?qe.onTouchEnd:void 0,children:n.jsx("div",{className:"flex gap-3 h-full",children:qs.map(ie=>{const Xe=$r(ie),ot=ya(ie),Dt=Xe.length+ot.length,fn=sn===ie.id;return n.jsxs("div",{className:`w-[280px] shrink-0 rounded-xl flex flex-col h-full transition-colors ${fn?"bg-surface-elevated/60 ring-1 ring-brand-500/30":"bg-surface-secondary/50"}`,onDragOver:hr=>Cs(hr,ie.id),onDragLeave:hr=>Ps(hr,ie.id),onDrop:hr=>{Mi(hr,ie.id)},children:[n.jsxs("div",{className:"flex justify-between items-center px-3 py-2.5 shrink-0 border-b border-border-default/30",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${ie.accent.replace("border-t-","bg-")}`}),n.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:ie.label})]}),n.jsx("span",{className:"text-[11px] text-fg-tertiary font-medium tabular-nums",children:Dt})]}),n.jsx("div",{className:"space-y-2 flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 py-2",children:(()=>{const hr=[...ot.map(cn=>({kind:"req",data:cn,time:new Date(cn.updatedAt??cn.createdAt).getTime()})),...Xe.map(cn=>({kind:"task",data:cn,time:new Date(cn.updatedAt??cn.createdAt??0).getTime()}))];return hr.sort((cn,bt)=>bt.time-cn.time),hr.map(cn=>{if(cn.kind==="req"){const bt=cn.data,ds=d[bt.status]??{label:bt.status,cls:"bg-gray-500/15 text-fg-secondary"},us=bt.source==="agent"&&bt.status==="pending",is=T==="all"&&bt.projectId?N.find(Nr=>Nr.id===bt.projectId):null,Kr=Dd(bt.createdBy,R,W)??bt.createdBy.slice(0,10),ms=Fe?.id===bt.id;return n.jsxs("div",{role:"button",tabIndex:0,draggable:!0,onDragStart:Nr=>_a(Nr,bt),onDragEnd:Wn,onClick:()=>Rs(bt),onKeyDown:Nr=>Nr.key==="Enter"&&Rs(bt),className:`group rounded-lg p-2.5 border border-transparent transition-all cursor-grab active:cursor-grabbing
708
708
  ${us?"bg-amber-500/[0.06] border-amber-500/30 ring-1 ring-amber-500/15":"bg-surface-elevated/80 hover:bg-surface-elevated border-border-default/50 hover:border-brand-400/40"}
709
- ${ms?"ring-2 ring-brand-500/50 border-brand-500/40":""}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-purple-500 shrink-0"}),n.jsx("span",{className:"text-[10px] font-semibold text-purple-500 uppercase tracking-wide shrink-0",children:s("work:task.requirementShort")}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-md shrink-0 ml-auto ${ds.cls}`,children:ds.label})]}),n.jsx("div",{className:"text-[13px] font-medium leading-snug text-fg-primary line-clamp-2 mb-1",children:bt.title}),bt.description&&n.jsx("div",{className:"text-[11px] text-fg-tertiary line-clamp-1 mb-1.5",children:bt.description}),n.jsxs("div",{className:"flex items-center justify-between mt-auto pt-1.5 border-t border-border-default/20",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[is&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-surface-overlay/60 text-fg-secondary rounded truncate max-w-[90px]",title:is.name,children:is.name}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:bt.priority}),n.jsxs("span",{className:"text-[10px] text-fg-quaternary",children:["by ",Kr]})]}),n.jsx("div",{className:"flex items-center gap-1",children:bt.taskIds.length>0&&n.jsxs("span",{className:"text-[10px] text-brand-500/70 bg-brand-500/8 px-1.5 py-0.5 rounded-md",children:["📋 ",bt.taskIds.length]})})]}),us&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-amber-500/15",children:[n.jsx("button",{onClick:Nr=>{Nr.stopPropagation(),Ur(bt.id)},className:"flex-1 py-1 bg-green-600 hover:bg-green-500 text-white text-[10px] rounded-md font-medium transition-colors",children:s("work:task.approve")}),n.jsx("button",{onClick:Nr=>{Nr.stopPropagation(),tn(bt.id)},className:"flex-1 py-1 border border-red-500/30 hover:bg-red-500/10 text-red-500 text-[10px] rounded-md font-medium transition-colors",children:s("work:task.reject")})]})]},`req-${bt.id}`)}else{const bt=cn.data,ds=bt.subtasks?.length??0,Vr=l[bt.status],us=bt.status==="pending",is=bt.taskType==="scheduled"&&!!bt.scheduleConfig,Kr=is?bt.scheduleConfig.every?s("work:task.everyInterval",{interval:bt.scheduleConfig.every}):bt.scheduleConfig.cron?s("work:task.cronLabel"):s("work:task.scheduledShort"):null,ms=T==="all"&&bt.projectId?(()=>{const Ee=N.find(et=>et.id===bt.projectId)?.name;return Ee&&Ee!=="default"?Ee:null})():null,Nr=bt.requirementId?L.find(Ee=>Ee.id===bt.requirementId)?.title:null,eo=bt.createdBy?Dd(bt.createdBy,R,W)??bt.createdBy:null,Ri=pe?.id===bt.id,to={urgent:"bg-red-500",high:"bg-amber-500",medium:"bg-blue-500",low:"bg-gray-400"},oe=bt.status==="blocked"&&(!bt.blockedBy||bt.blockedBy.length===0||bt.blockedBy.every(Ee=>{const et=ai.get(Ee);return et&&et.status==="completed"}));return n.jsxs("div",{role:"button",tabIndex:0,"aria-label":bt.title,draggable:!us,onDragStart:Ee=>!us&&sa(Ee,bt),onDragEnd:Wn,onClick:()=>ur(bt),onKeyDown:Ee=>Ee.key==="Enter"&&ur(bt),className:`group rounded-lg p-2.5 border border-transparent transition-all ${oe?"bg-red-500/[0.06] border-red-500/30 ring-1 ring-red-500/15 cursor-pointer":us?"bg-amber-500/[0.06] border-amber-500/30 ring-1 ring-amber-500/15 cursor-pointer":is?"bg-blue-500/[0.04] border-blue-500/20 hover:border-blue-400/40 cursor-pointer":"bg-surface-elevated/80 hover:bg-surface-elevated border-border-default/50 hover:border-brand-400/40 cursor-grab active:cursor-grabbing"} ${Ri?"ring-2 ring-brand-500/50 border-brand-500/40":""}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${to[bt.priority]??"bg-gray-400"}`,title:bt.priority}),is&&n.jsx("span",{className:"text-blue-500 shrink-0",title:Kr??"Scheduled",children:n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"})})}),is&&Kr&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-500/10 text-blue-500 whitespace-nowrap",children:Kr}),Vr&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-md ml-auto shrink-0 ${Vr.cls}`,children:Vr.label}),oe&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md shrink-0 bg-red-500/15 text-red-500 font-medium",children:"⚠"})]}),n.jsx("div",{className:"text-[13px] font-medium leading-snug text-fg-primary line-clamp-2 mb-1",children:bt.title}),bt.description&&n.jsx("div",{className:"text-[11px] text-fg-tertiary line-clamp-1 mb-1.5",children:bt.description}),(ms||Nr||bt.blockedBy&&bt.blockedBy.length>0)&&n.jsxs("div",{className:"flex flex-wrap gap-1 mb-1.5",children:[ms&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-surface-overlay/60 text-fg-secondary rounded-md truncate max-w-[100px]",title:ms,children:ms}),Nr&&n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 bg-brand-500/8 text-brand-500 rounded-md truncate max-w-[110px]",title:Nr,children:["# ",Nr]}),bt.blockedBy&&bt.blockedBy.length>0&&n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/10 text-amber-600 rounded-md",children:["⏳ ",bt.blockedBy.length," dep",bt.blockedBy.length>1?"s":""]})]}),n.jsxs("div",{className:"flex items-center justify-between mt-auto pt-1.5 border-t border-border-default/20",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:eo&&n.jsxs("span",{className:"text-[10px] text-fg-quaternary",title:`by ${eo}`,children:["by ",eo]})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[ds>0&&n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["⋮ ",ds]}),bt.notes&&bt.notes.length>0&&n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["📝 ",bt.notes.length]}),bt.assignedAgentId&&n.jsxs("span",{className:"text-[10px] text-brand-500 bg-brand-500/8 px-1.5 py-0.5 rounded-md flex items-center gap-1",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${k0[R.find(Ee=>Ee.id===bt.assignedAgentId)?.status??""]??"bg-gray-500"}`}),R.find(Ee=>Ee.id===bt.assignedAgentId)?.name??bt.assignedAgentId.slice(0,8)]})]})]})]},bt.id)}})})()}),fn&&n.jsx("div",{className:"mx-2 mb-2 border-2 border-dashed border-brand-500/25 rounded-lg h-10 flex items-center justify-center shrink-0",children:n.jsx("span",{className:"text-[11px] text-brand-500/50",children:s("work:task.dropHere")})})]},ie.id)})})})]}),!u&&ka&&n.jsx("div",{className:"w-1.5 shrink-0 cursor-col-resize group relative flex items-center justify-center",onMouseDown:v.onResizeStart,children:n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),(!u||j)&&ka&&n.jsx("div",{className:`${u||ja?"flex-1":"shrink-0"} overflow-hidden min-w-0 flex`,style:u||ja?void 0:{width:v.width},children:ja?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx($3,{req:Fe,agents:R,projects:N,allTasks:Object.values($).flat(),users:W,onClose:()=>{Je(null)},onApprove:ie=>{Ur(ie)},onReject:ie=>{tn(ie)},onCancel:ie=>{Ss(ie),Je(null)},onStatusChange:async(ie,Xe)=>{try{await le.requirements.updateStatus(ie,Xe),Mt(`Requirement status → ${Xe}`),Ns({requirementId:ie}),Ls(),on()}catch(ot){Mt(`Error: ${ot}`)}},onRefresh:Ls,authUser:e,onTaskClick:ie=>{ze(ie)},onCreateTask:(ie,Xe)=>{mt(ie),Xe&&st(Xe),Q(!0)},onProjectClick:wn,previewMode:t})}),n.jsx("div",{className:"w-px shrink-0 bg-border-default"}),n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx(I3,{task:pe,agents:R,projects:N,requirements:L,allTasks:Object.values($).flat(),users:W,onClose:pa,onRefresh:vr,authUser:e,scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onReqClick:ie=>{Je(Xe=>Xe?.id===ie.id?null:ie)},onProjectClick:wn})})]}):pe?n.jsx(I3,{task:pe,agents:R,projects:N,requirements:L,allTasks:Object.values($).flat(),users:W,onClose:ha,onRefresh:vr,authUser:e,scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onReqClick:ie=>{Je(Xe=>Xe?.id===ie.id?null:ie)},onProjectClick:wn}):Fe?n.jsx($3,{req:Fe,agents:R,projects:N,allTasks:Object.values($).flat(),users:W,onClose:ha,onApprove:ie=>{Ur(ie)},onReject:ie=>{tn(ie)},onCancel:ie=>{Ss(ie),ha()},onStatusChange:async(ie,Xe)=>{try{await le.requirements.updateStatus(ie,Xe),Mt(`Requirement status → ${Xe}`),Ns({requirementId:ie}),Ls(),on()}catch(ot){Mt(`Error: ${ot}`)}},scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onRefresh:Ls,authUser:e,onTaskClick:ie=>{ze(ie),u&&(C(!0),history.pushState({mobileDetail:Te.WORK},"",window.location.hash))},onCreateTask:(ie,Xe)=>{mt(ie),Xe&&st(Xe),Q(!0)},onProjectClick:wn,previewMode:t}):null}),Y&&n.jsx(hre,{orgId:e?.orgId,onCreated:Kn,onClose:()=>ee(!1)}),ae&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{Q(!1),Ze("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 max-h-[90dvh] overflow-y-auto ${u?"w-full":"w-[28rem]"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.newTask")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.titleLabel")}),n.jsx("input",{autoFocus:!u,value:me,onChange:ie=>Ae(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&ba()},className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.descriptionField")}),n.jsx("textarea",{value:Me,onChange:ie=>He(ie.target.value),rows:2,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none resize-none"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.projectLabel")}),n.jsx(Lu,{options:[{value:"",label:s("work:task.noProject")},...N.map(ie=>({value:ie.id,label:ie.name}))],value:ct,onChange:ie=>{st(ie),mt("")},placeholder:s("work:task.noProject"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.requirementLabel")}),n.jsx(Lu,{options:[{value:"",label:s("work:task.selectRequirement")},...L.filter(ie=>ie.status==="in_progress"&&(!ct||ie.projectId===ct)).map(ie=>({value:ie.id,label:ie.title}))],value:zt,onChange:mt,placeholder:s("work:task.selectRequirement"),noMatchesText:s("work:task.noMatches")})]})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.assignToRequired")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:R.map(ie=>({value:ie.id,label:`${ie.name} (${ie.status})`})),value:Pe,onChange:Ce,placeholder:s("work:task.selectAgent"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.reviewerRequired")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:[...W.map(ie=>({value:`human:${ie.id}`,label:ie.name})),...R.filter(ie=>ie.id!==Pe).map(ie=>({value:`agent:${ie.id}`,label:`${ie.name} (${ie.status})`}))],value:Ye,onChange:Qe,placeholder:s("work:task.selectReviewer"),noMatchesText:s("work:task.noMatches")})]})]}),n.jsxs("div",{className:`grid gap-4 ${be==="scheduled"?"grid-cols-3":"grid-cols-2"}`,children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.priorityField")}),n.jsxs("select",{value:je,onChange:ie=>xe(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"low",children:s("work:priority.low")}),n.jsx("option",{value:"medium",children:s("work:priority.medium")}),n.jsx("option",{value:"high",children:s("work:priority.high")}),n.jsx("option",{value:"urgent",children:s("work:priority.urgent")})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.taskType")}),n.jsxs("select",{value:be,onChange:ie=>se(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"standard",children:s("work:task.taskTypeStandard")}),n.jsx("option",{value:"scheduled",children:s("work:task.taskTypeScheduled")})]})]}),be==="scheduled"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.frequency")}),n.jsxs("select",{value:fe,onChange:ie=>$e(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"30m",children:s("work:task.freq30m")}),n.jsx("option",{value:"1h",children:s("work:task.freq1h")}),n.jsx("option",{value:"2h",children:s("work:task.freq2h")}),n.jsx("option",{value:"4h",children:s("work:task.freq4h")}),n.jsx("option",{value:"8h",children:s("work:task.freq8h")}),n.jsx("option",{value:"12h",children:s("work:task.freq12h")}),n.jsx("option",{value:"1d",children:s("work:task.freq1d")}),n.jsx("option",{value:"1w",children:s("work:task.freq1w")})]})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.blockedBy")}),n.jsx(pre,{options:Object.values($).flat().filter(ie=>ie.status!=="completed"&&ie.status!=="cancelled").map(ie=>({value:ie.id,label:ie.title})),selected:te,onAdd:ie=>de([...te,ie]),placeholder:s("work:task.selectDependency"),noMatchesText:s("work:task.noMatches")}),te.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:te.map(ie=>{const Xe=Object.values($).flat().find(ot=>ot.id===ie);return n.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-1 bg-amber-500/10 text-amber-600 rounded-full",children:[Xe?Xe.title.slice(0,30):ie.slice(-8),n.jsx("button",{onClick:()=>de(te.filter(ot=>ot!==ie)),className:"ml-0.5 text-amber-600/60 hover:text-amber-600",children:"×"})]},ie)})})]}),Ne&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:Ne}),n.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[n.jsx("button",{onClick:()=>{Q(!1),Ze("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{ba()},disabled:!me.trim()||!Pe||!Ye,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-50",children:s("common:create")})]})]})}),Fn&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{mr(!1),fr(""),ir(""),ye("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 max-h-[90dvh] overflow-y-auto ${u?"w-full":"w-[28rem]"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.newRequirementModalTitle")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:s("work:task.newRequirementModalHint")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.projectLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:N.map(ie=>({value:ie.id,label:ie.name})),value:It,onChange:qt,placeholder:s("work:task.selectProject"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.titleField")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{value:rr,onChange:ie=>fr(ie.target.value),placeholder:s("work:task.reqTitleExample"),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none",autoFocus:!u,onKeyDown:ie=>{ie.key==="Enter"&&rr.trim()&&as()}})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.descriptionField")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("textarea",{value:Qn,onChange:ie=>ir(ie.target.value),placeholder:s("work:task.reqDescPlaceholder"),rows:3,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.priorityField")}),n.jsxs("select",{value:Ie,onChange:ie=>At(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"low",children:s("work:priority.low")}),n.jsx("option",{value:"medium",children:s("work:priority.medium")}),n.jsx("option",{value:"high",children:s("work:priority.high")}),n.jsx("option",{value:"urgent",children:s("work:priority.urgent")})]})]}),an&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:an}),n.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[n.jsx("button",{onClick:()=>{mr(!1),fr(""),ir(""),ye("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{as()},disabled:!rr.trim()||!Qn.trim()||!It,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-40 disabled:cursor-not-allowed",children:s("common:create")})]})]})}),Jt&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{tn(null),yt("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 ${u?"w-full":"w-96"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.rejectRequirementTitle")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.rejectReasonLabel")}),n.jsx("textarea",{value:An,onChange:ie=>br(ie.target.value),placeholder:s("work:task.rejectReasonPlaceholder"),rows:3,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-red-500 outline-none resize-none",autoFocus:!u})]}),at&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:at}),n.jsxs("div",{className:"flex justify-end gap-3",children:[n.jsx("button",{onClick:()=>{tn(null),yt("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{ri()},className:"px-4 py-2 text-sm bg-red-600 hover:bg-red-500 rounded-lg text-white",children:s("work:task.reject")})]})]})}),Gt&&n.jsxs("div",{className:"fixed inset-0 z-[60] flex flex-col justify-end",onClick:()=>Tn(!1),children:[n.jsx("div",{className:"absolute inset-0 bg-black/50"}),n.jsxs("div",{className:"relative bg-surface-secondary rounded-t-2xl border-t border-border-default max-h-[70vh] overflow-y-auto pb-16",onClick:ie=>ie.stopPropagation(),children:[n.jsxs("div",{className:"sticky top-0 bg-surface-secondary z-10 px-4 pt-3 pb-2 flex items-center justify-between border-b border-border-default/60",children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:s("work:task.filtersSheetTitle")}),n.jsxs("div",{className:"flex items-center gap-2",children:[(Ve.size>0||gt.size>0||Et)&&n.jsx("button",{onClick:()=>{Rt(new Set),nt(new Set),dt(!1)},className:"text-[11px] text-brand-500 font-medium",children:s("work:task.clearAll")}),n.jsx("button",{onClick:()=>Tn(!1),className:"w-7 h-7 flex items-center justify-center rounded-full bg-surface-elevated text-fg-tertiary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),N.length>1&&n.jsxs("div",{className:"px-4 py-3",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary font-medium uppercase tracking-wider mb-2",children:s("work:task.projectsFilterGroup")}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:va.map(ie=>{const Xe=Ve.has(ie.id),ot=Di[ie.id]??0;return n.jsxs("div",{className:`flex items-center rounded-lg overflow-hidden transition-all ${Xe?"bg-brand-500/15 ring-1 ring-brand-500/30":""}`,children:[n.jsxs("button",{onClick:()=>wn(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] transition-all ${Xe?"text-brand-600":"bg-surface-elevated text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-sm flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-tertiary"}`,children:ie.name[0]?.toUpperCase()}),ie.name,ot>0&&n.jsx("span",{className:"text-[9px] text-fg-tertiary",children:ot})]}),Xe&&n.jsx("button",{onClick:()=>{Tn(!1),Jn(ie.id)},className:"px-2 py-1.5 self-stretch flex items-center border-l border-brand-500/20 text-fg-tertiary hover:text-brand-600",title:s("work:project.editProject"),children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},ie.id)})})]}),e?.id&&n.jsx("div",{className:"px-4 py-3 border-t border-border-default/40",children:n.jsx("button",{type:"button",onClick:()=>dt(ie=>!ie),className:`w-full text-left px-2.5 py-1.5 rounded-lg text-[11px] transition-all ${Et?"bg-green-600/20 text-green-500 ring-1 ring-green-500/40":"bg-surface-elevated text-fg-secondary"}`,children:s("work:task.myTasks")})}),R.length>0&&n.jsxs("div",{className:"px-4 py-3 border-t border-border-default/40",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary font-medium uppercase tracking-wider mb-2",children:s("work:task.agentsFilterGroup")}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:_s.map(ie=>{const Xe=gt.has(ie.id);return n.jsxs("button",{onClick:()=>_r(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] transition-all ${Xe?"bg-brand-600/20 text-brand-500 ring-1 ring-brand-500/40":"bg-surface-elevated text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-tertiary"}`,children:ie.name[0]?.toUpperCase()}),ie.name]},ie.id)})})]}),n.jsx("div",{className:"h-[env(safe-area-inset-bottom,0px)]"})]})]})]})}function Lre({requirementId:e,createdBy:t,agents:r,users:s,authUser:a}){const{t:i}=ft(["work","common"]),[l,d]=x.useState([]),[u,m]=x.useState([]),h=x.useRef(null),[p,y]=x.useState(new Map);x.useEffect(()=>{m([]),y(new Map),h.current&&(clearTimeout(h.current),h.current=null),le.requirements.getComments(e).then(w=>d(w.comments)).catch(()=>{})},[e]),x.useEffect(()=>pn.on("requirement:comment",N=>{if(N.payload?.requirementId===e&&N.payload.comment){const S=N.payload.comment;d(T=>T.some(M=>M.id===S.id)?T:[...T,S]),(S.authorType==="agent"||S.authorId?.startsWith("agt_"))&&(m(T=>{const M=T.filter(D=>D.id!==S.authorId);return M.length===0&&h.current&&(clearTimeout(h.current),h.current=null),M}),y(T=>{const M=new Map(T);return M.delete(S.authorId),M}))}}),[e]),x.useEffect(()=>{if(u.length===0)return;const w=new Set(u.map(S=>S.id));return pn.on("agent:activity_log",S=>{const T=S.payload;if(!T)return;const M=T.agentId;if(!w.has(M))return;const D=T.type;if(D==="tool_start"||D==="tool_end"){const $={tool:T.content??T.metadata?.tool??"",phase:D==="tool_start"?"start":"end",success:D==="tool_end"?T.metadata?.success!==!1:void 0,ts:Date.now()};y(B=>{const R=new Map(B),U=[...R.get(M)??[],$];return R.set(M,U),R})}})},[u]);const[g,v]=x.useState(null),j=async(w,N,S,T)=>{let M;S.length>0&&(M=(await le.uploads.upload(S.map(R=>({dataUrl:R.dataUrl,name:R.name})),"comments")).files.map(R=>({type:"image",url:R.url,name:R.name}))),await le.requirements.addComment(e,w,a?.name,M,a?.id,N.length>0?N:void 0,T);const D=[],I=new Set,$=B=>{if(I.has(B)||B===a?.id)return;I.add(B);const R=r.find(U=>U.id===B);R&&D.push({id:R.id,name:R.name,avatarUrl:R.avatarUrl})};for(const B of N){const R=r.find(U=>U.name.toLowerCase()===B.toLowerCase());R&&$(R.id)}t?.startsWith("agt_")&&$(t),D.length>0&&(h.current&&clearTimeout(h.current),m(D),h.current=setTimeout(()=>m([]),12e4))},C=x.useCallback(w=>{v({id:w.id,authorName:w.authorName,content:w.content.slice(0,100)})},[]);return n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 block",children:l.length>0?i("work:task.commentsWithCount",{count:l.length}):i("work:task.comments")}),n.jsxs("div",{className:"space-y-0.5 mb-3",children:[l.length===0&&n.jsx("p",{className:"text-xs text-fg-tertiary text-center py-4",children:i("work:task.noCommentsYet")}),l.map(w=>n.jsx(Ju,{comment:w,agents:r,onReply:C},w.id)),u.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 pt-1",children:u.map(w=>{const N=p.get(w.id)??[];return n.jsxs("div",{className:"px-2 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors",onClick:()=>pt.navigate(Te.TEAM,{agentId:w.id,profileTab:"mind"}),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:w.name,avatarUrl:w.avatarUrl,size:22,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsx("span",{className:"text-xs font-medium text-fg-secondary",children:w.name}),N.length===0&&n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("work:task.agentProcessing")}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary",children:"→"})]}),N.length>0&&n.jsx("div",{className:"ml-8 mt-1",children:n.jsx(Vh,{activities:N,isActive:!0})})]},w.id)})})]}),n.jsx(OS,{agents:r,humans:s,onSubmit:j,replyTo:g,onCancelReply:()=>v(null)})]})}function $3({req:e,agents:t,projects:r,allTasks:s,users:a,onClose:i,onApprove:l,onReject:d,onCancel:u,onStatusChange:m,onRefresh:h,authUser:p,scrollToComments:y,onScrollToCommentsDone:g,onTaskClick:v,onCreateTask:j,onProjectClick:C,previewMode:w}){const{t:N}=ft(["work","common"]),S=x.useMemo(()=>Dy(N),[N]),T=x.useMemo(()=>Z8(N),[N]),M=Ds(),[D,I]=x.useState(!1),[$,B]=x.useState(e.description),[R,U]=x.useState(!1),[W,F]=x.useState(!1),L=x.useRef(null),[z,E]=x.useState("none"),_=x.useRef(null),G=x.useRef(null),V=x.useRef(80);x.useEffect(()=>{const Q=L.current;if(!Q)return;const me=()=>{const{scrollTop:Me,scrollHeight:He,clientHeight:je}=Q;if(!(He>je+50)){E("none");return}const Pe=Me<30,Ce=Me+je>=He-30;E(Pe?"top":Ce?"bottom":"middle")};me(),Q.addEventListener("scroll",me,{passive:!0});const Ae=new ResizeObserver(me);return Ae.observe(Q),()=>{Q.removeEventListener("scroll",me),Ae.disconnect()}},[]),x.useEffect(()=>{if(D&&G.current){const Q=G.current;Q.style.height="auto",Q.style.height=Math.max(Q.scrollHeight,V.current)+"px",Q.focus()}},[D]),x.useEffect(()=>{if(!y)return;const Q=setTimeout(()=>{const me=L.current;me&&me.scrollTo({top:me.scrollHeight,behavior:"smooth"}),g?.()},300);return()=>clearTimeout(Q)},[y,g]);const O=S[e.status]??{label:e.status,cls:"bg-gray-500/15 text-fg-secondary"},q=e.source==="agent",J=q&&e.status==="pending",H=e.status==="pending"||e.status==="in_progress",Z=e.status==="completed"||e.status==="rejected"||e.status==="cancelled"||e.status==="archived",Y=e.projectId?r.find(Q=>Q.id===e.projectId):null,ee=Dd(e.createdBy,t,a)??e.createdBy.slice(0,12),ae=s.filter(Q=>e.taskIds.includes(Q.id));return x.useEffect(()=>{B(e.description),I(!1)},[e.id,e.description]),n.jsxs("div",{className:"flex flex-col w-full h-full overflow-hidden bg-surface-primary shadow-xl shadow-black/8 ring-1 ring-border-default/20",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 p-5 pb-0 border-b border-border-default",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[M&&n.jsx("button",{onClick:()=>history.back(),className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsxs("h2",{className:"flex-1 min-w-0 pb-4 text-lg font-semibold text-fg-primary leading-snug",children:[e.title," ",n.jsx("span",{className:"text-[10px] font-bold text-brand-500 bg-brand-500/15 px-2 py-0.5 rounded align-middle",children:N("work:task.requirementShort")})," ",n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium align-middle ${O.cls}`,children:O.label})," ",e.priority==="high"||e.priority==="urgent"?n.jsx("span",{className:`text-[10px] font-medium align-middle ${e.priority==="urgent"?"text-red-500":"text-amber-600"}`,children:N("common:priority."+e.priority,{defaultValue:e.priority})}):n.jsx("span",{className:"text-[10px] text-fg-tertiary align-middle",children:N("common:priority."+e.priority,{defaultValue:e.priority})})]})]}),n.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xl leading-none shrink-0 mt-1",children:"×"})]}),n.jsxs("div",{className:"flex-1 min-h-0 relative",children:[n.jsxs("div",{ref:L,className:"h-full overflow-y-auto p-5 space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1 block",children:N("work:task.requirementDetailDescription")}),D?n.jsx("textarea",{ref:G,value:$,onChange:Q=>{B(Q.target.value);const me=Q.target;me.style.height="auto",me.style.height=me.scrollHeight+"px"},onBlur:async()=>{if($!==e.description){U(!0);try{await le.requirements.update(e.id,{description:$}),h?.()}catch{}finally{U(!1)}}I(!1)},onKeyDown:Q=>{Q.key==="Escape"&&(Q.preventDefault(),B(e.description),I(!1))},className:"w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none -mx-2 px-2 -my-1 py-1",placeholder:N("work:task.requirementDetailDescription")}):n.jsx("div",{ref:_,className:`group relative rounded-lg -mx-2 px-2 -my-1 py-1 transition-colors ${Z?"":"cursor-pointer hover:bg-surface-elevated/50"}`,onClick:Z?void 0:Q=>{Q.target.closest("a, button, [data-entity-link]")||(V.current=Math.max(_.current?.offsetHeight??80,60),B(e.description),I(!0))},role:Z?void 0:"button",tabIndex:Z?void 0:0,onKeyDown:Z?void 0:Q=>Q.key==="Enter"&&(B(e.description),I(!0)),children:e.description?n.jsx(Gr,{content:e.description,className:"text-sm text-fg-secondary leading-relaxed"}):n.jsx("p",{className:"text-sm text-fg-tertiary italic",children:N("work:task.requirementNoDescription")})})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.createdByLabel")}),n.jsx("span",{className:"text-fg-secondary",children:ee}),q&&n.jsx("span",{className:"text-[10px] text-brand-500 ml-1.5",children:N("work:task.agentTag")})]}),n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.createdLabel")}),n.jsx("span",{className:"text-fg-secondary",children:new Date(e.createdAt).toLocaleString()})]}),Y&&n.jsxs("div",{className:`bg-surface-elevated/60 rounded-lg p-2.5 ${C?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,onClick:C?()=>C(Y.id):void 0,role:C?"button":void 0,tabIndex:C?0:void 0,onKeyDown:C?Q=>Q.key==="Enter"&&C(Y.id):void 0,children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.projectLabel")}),n.jsx("span",{className:"text-fg-secondary",children:Y.name})]}),e.approvedBy&&n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.approvedBy")}),n.jsx("span",{className:"text-fg-secondary",children:Dd(e.approvedBy,t,a)??e.approvedBy.slice(0,12)}),e.approvedAt&&n.jsx("span",{className:"text-[10px] text-fg-tertiary ml-1",children:new Date(e.approvedAt).toLocaleDateString()})]})]}),e.rejectedReason&&n.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[n.jsx("span",{className:"text-[10px] font-semibold text-red-500 uppercase tracking-wider block mb-1",children:N("work:task.rejectionReason")}),n.jsx("p",{className:"text-sm text-red-500/80",children:e.rejectedReason})]}),Array.isArray(e.tags)&&e.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:e.tags.map(Q=>n.jsxs("span",{className:"text-[10px] bg-surface-elevated text-fg-secondary px-2 py-0.5 rounded-full",children:["#",Q]},Q))}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:N("work:task.linkedTasks",{count:ae.length})}),!Z&&j&&n.jsxs("button",{onClick:()=>j(e.id,e.projectId),className:"text-[11px] text-amber-500 hover:text-amber-400 font-medium flex items-center gap-1",children:[n.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),N("work:requirement.createTask")]})]}),ae.length>0?(()=>{const Q=new Map(ae.map(xe=>[xe.id,xe]));if(!ae.some(xe=>xe.blockedBy?.some(Pe=>Q.has(Pe))))return n.jsx("div",{className:"space-y-1.5",children:ae.map(xe=>{const Pe=T[xe.status];return n.jsxs("div",{onClick:()=>v?.(xe),className:`flex items-center gap-2 bg-surface-elevated/60 rounded-lg px-3 py-2 ${v?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[xe.status]??"bg-gray-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:xe.title}),Pe&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${Pe.cls}`,children:Pe.label})]},xe.id)})});const Ae=new Map,Me=new Set;for(const xe of ae)for(const Pe of xe.blockedBy??[])if(Q.has(Pe)){Me.add(xe.id);const Ce=Ae.get(Pe)??[];Ce.push(xe.id),Ae.set(Pe,Ce)}const He=ae.filter(xe=>!Me.has(xe.id)),je=(xe,Pe)=>{const Ce=T[xe.status],Ye=(Ae.get(xe.id)??[]).map(Qe=>Q.get(Qe)).filter(Boolean);return n.jsxs("div",{children:[n.jsxs("div",{onClick:()=>v?.(xe),className:`flex items-center gap-2 bg-surface-elevated/60 rounded-lg px-3 py-2 ${v?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,style:Pe>0?{marginLeft:Pe*20}:void 0,children:[Pe>0&&n.jsx("span",{className:"text-fg-quaternary text-[10px] shrink-0",children:"↳"}),n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[xe.status]??"bg-gray-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:xe.title}),Ce&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${Ce.cls}`,children:Ce.label})]}),Ye.map(Qe=>je(Qe,Pe+1))]},xe.id)};return n.jsx("div",{className:"space-y-1.5",children:He.map(xe=>je(xe,0))})})():n.jsx("div",{className:"text-xs text-fg-tertiary italic py-2",children:N("work:requirement.noLinkedTasks")})]}),!w&&n.jsx(Lre,{requirementId:e.id,createdBy:e.createdBy,agents:t,users:a,authUser:p}),!w&&n.jsx(tC,{entityType:"requirement",entityId:e.id})]}),z!=="none"&&z!=="top"&&n.jsx("button",{onClick:()=>L.current?.scrollTo({top:0,behavior:"smooth"}),className:"absolute bottom-20 right-4 md:bottom-14 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:N("work:task.scrollToTop"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M14.77 12.79a.75.75 0 01-1.06-.02L10 8.832l-3.71 3.938a.75.75 0 11-1.08-1.04l4.25-4.5a.75.75 0 011.08 0l4.25 4.5a.75.75 0 01-.02 1.06z",clipRule:"evenodd"})})}),z!=="none"&&z!=="bottom"&&n.jsx("button",{onClick:()=>{const Q=L.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"})},className:"absolute bottom-6 right-4 md:bottom-4 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:N("work:task.scrollToBottom"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})})]}),n.jsxs("div",{className:"flex items-center gap-2 p-5 pt-3 border-t border-border-default",children:[J&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>l(e.id),className:"px-4 py-2 bg-green-600 hover:bg-green-500 text-white text-sm rounded-lg font-medium transition-colors",children:N("work:requirement.approveRequirement")}),n.jsx("button",{onClick:()=>d(e.id),className:"px-4 py-2 border border-red-500/30 hover:bg-red-500/10 text-red-500 text-sm rounded-lg font-medium transition-colors",children:N("work:requirement.rejectRequirement")})]}),!J&&m&&!Z&&n.jsx("select",{value:e.status,onChange:Q=>{Q.target.value!==e.status&&m(e.id,Q.target.value)},className:"px-2 py-1.5 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-secondary cursor-pointer hover:border-gray-500 transition-colors",children:Dre.map(Q=>{const me=S[Q],Ae=Q===e.status||(x1[e.status]?.has(Q)??!1);return n.jsx("option",{value:Q,disabled:!Ae,children:me?.label??Q},Q)})}),Z&&m&&n.jsx("button",{onClick:()=>m(e.id,"in_progress"),className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors",children:N("work:task.reopen")}),n.jsx("div",{className:"flex-1"}),H&&!J&&n.jsx("button",{onClick:()=>F(!0),className:"px-3 py-1.5 text-xs text-red-500/70 hover:text-red-500 hover:bg-red-500/10 border border-transparent hover:border-red-500/20 rounded-lg transition-colors",children:N("work:task.cancelRequirement")})]}),W&&n.jsx(dd,{title:N("work:requirement.cancelConfirmTitle","Cancel Requirement"),message:N("work:requirement.cancelConfirmMessage","Are you sure you want to cancel this requirement? This action cannot be undone."),confirmLabel:N("work:requirement.cancelConfirmLabel","Cancel Requirement"),onConfirm:()=>{F(!1),u(e.id)},onCancel:()=>F(!1)})]})}function tC({entityType:e,entityId:t}){const{t:r}=ft(["work"]),[s,a]=x.useState([]),[i,l]=x.useState(!0),[d,u]=x.useState(!1);if(x.useEffect(()=>{l(!0),(e==="task"?le.tasks.getHistory:le.requirements.getHistory)(t).then(g=>a(g.history)).catch(()=>a([])).finally(()=>l(!1))},[e,t]),i)return n.jsx("div",{className:"px-6 py-4 text-xs text-fg-tertiary",children:r("work:task.loadingHistory","Loading history...")});if(s.length===0)return n.jsx("div",{className:"px-6 py-4 text-xs text-fg-tertiary italic",children:r("work:task.noHistory","No status change history.")});const m=d?s:s.slice(-5),h=s.length>5&&!d,p=y=>{const g=y.changedByName||y.changedById||(y.changedByType==="human"?"User":y.changedByType==="agent"?"Agent":"System"),v=y.changedByType==="human"?"bg-blue-500/20 text-blue-500":y.changedByType==="agent"?"bg-brand-500/20 text-brand-500":"bg-gray-500/20 text-fg-tertiary";return n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium shrink-0 ${v}`,children:g})};return n.jsxs("div",{className:"px-6 py-4",children:[n.jsx("p",{className:"text-xs font-semibold text-fg-tertiary uppercase tracking-wider mb-3",children:r("work:task.statusHistory","Status History")}),h&&n.jsx("button",{onClick:()=>u(!0),className:"text-[11px] text-brand-500 hover:underline mb-2",children:r("work:task.showAllHistory",{count:s.length})}),n.jsxs("div",{className:"relative ml-2",children:[n.jsx("div",{className:"absolute left-[2.5px] top-1 bottom-1 w-px bg-border-default"}),n.jsx("div",{className:"space-y-3",children:m.map(y=>n.jsxs("div",{className:"flex items-start gap-3 relative",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full mt-[7px] shrink-0 relative z-10",style:{background:y.changedByType==="human"?"#3b82f6":y.changedByType==="agent"?"var(--color-brand-500)":"#6b7280"}}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[p(y),n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-fg-tertiary line-through",children:y.fromStatus}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"}),n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-brand-500/15 text-brand-500 font-medium",children:y.toStatus})]}),y.reason&&n.jsx("p",{className:"text-[10px] text-fg-secondary mt-0.5 leading-snug",children:y.reason}),n.jsx("p",{className:"text-[9px] text-fg-tertiary mt-0.5",children:new Date(y.createdAt).toLocaleString()})]})]},y.id))})]})]})}function Bi(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"&&e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Pre(e){return e.files&&typeof e.files=="object"&&!Array.isArray(e.files)?e.files:null}function Ql({label:e,value:t}){return t?n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:t})]}):null}function rd({label:e,value:t,color:r}){if(!t)return null;const s={purple:"bg-brand-500/15 text-brand-500",cyan:"bg-blue-500/15 text-blue-600",indigo:"bg-brand-500/15 text-brand-500",gray:"bg-gray-500/15 text-fg-secondary",emerald:"bg-green-500/15 text-green-600"};return n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:e}),n.jsx("div",{className:`mt-0.5 px-2 py-0.5 rounded-full text-[10px] font-medium ${s[r]??s.gray} capitalize inline-block`,children:t})]})}function ib({files:e}){const{t}=ft(["builder","common"]),[r,s]=x.useState(Object.keys(e)[0]??""),a=Object.keys(e);return a.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:t("builder:artifact.files",{count:a.length})}),n.jsxs("div",{className:"mt-1 bg-surface-elevated/50 rounded-lg border border-border-default/30 overflow-hidden",children:[n.jsx("div",{className:"flex gap-0.5 px-1.5 py-1 border-b border-border-default/30 overflow-x-auto",children:a.map(i=>n.jsx("button",{onClick:()=>s(i),className:`px-2 py-0.5 text-[10px] rounded whitespace-nowrap transition-colors ${r===i?"bg-brand-600/30 text-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:i},i))}),r&&e[r]!=null&&n.jsx("pre",{className:"p-2 text-[10px] text-fg-secondary max-h-[120px] overflow-auto whitespace-pre-wrap font-mono",children:e[r]})]})]})}function Ore({artifact:e,mode:t}){const{t:r}=ft(["builder","common"]),s=Pre(e),a=e.agent,i=e.team,l=e.dependencies,d=e.displayName??e.name;if(t==="agent"){const u=a?.roleName,m=a?.agentRole,h=a?.llmProvider,p=a?.llmModel,y=Bi(l?.env),g=Bi(l?.skills);return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[u&&n.jsx(rd,{label:r("builder:artifact.baseTemplate"),value:u,color:"indigo"}),n.jsx(rd,{label:r("builder:artifact.agentRole"),value:m,color:m==="manager"?"purple":"cyan"})]}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(v=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:v},v))}),(h||p)&&n.jsxs("div",{className:"flex gap-2",children:[h&&n.jsx(rd,{label:r("builder:artifact.llmProvider"),value:h,color:"gray"}),p&&n.jsx(rd,{label:r("builder:artifact.llmModel"),value:p,color:"gray"})]}),y.length>0&&n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:r("builder:artifact.requiredEnv")}),n.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:y.map(v=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/10 text-amber-600 rounded font-mono",children:v},v))})]}),g.length>0&&n.jsx(Ql,{label:r("builder:artifact.skills"),value:g.join(", ")}),s&&n.jsx(ib,{files:s})]})}if(t==="team"){const m=i?.members??[];return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsx("div",{className:"flex flex-wrap gap-2",children:n.jsx(rd,{label:r("builder:artifact.category"),value:e.category,color:"indigo"})}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(h=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:h},h))}),s&&n.jsx(ib,{files:s}),n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:r("builder:artifact.members",{count:m.length})}),n.jsx("div",{className:"mt-1.5 space-y-1.5",children:m.map((h,p)=>n.jsxs("div",{className:"bg-surface-elevated/30 rounded-lg px-2 py-1.5 border border-border-default/20",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-5 h-5 rounded flex items-center justify-center text-[10px] font-bold ${h.role==="manager"?"bg-brand-500/20 text-brand-500":"bg-blue-500/20 text-blue-600"}`,children:h.role==="manager"?"★":p+1}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:h.name}),typeof h.roleName=="string"&&h.roleName&&n.jsx("span",{className:"text-[10px] text-brand-500/70 font-mono",children:h.roleName}),n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["x",String(h.count??1)]})]}),Bi(h.skills).length>0&&n.jsx("div",{className:"mt-1 ml-7 flex flex-wrap gap-1",children:Bi(h.skills).map(y=>n.jsx("span",{className:"px-1 py-0.5 text-[9px] bg-green-500/10 text-green-600 rounded font-mono",children:y},y))})]},p))})]})]})}return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsx("div",{className:"flex gap-2",children:n.jsx(rd,{label:r("builder:artifact.category"),value:e.category,color:"indigo"})}),s&&n.jsx(ib,{files:s}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(u=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:u},u))})]})}const Pu={file:{icon:"📄",color:"bg-green-500/10 text-green-600"},directory:{icon:"📁",color:"bg-blue-500/10 text-blue-600"}},_re={active:{color:"text-green-600 bg-green-500/10"},verified:{color:"text-blue-600 bg-blue-500/10"},outdated:{color:"text-red-500 bg-red-500/10"}},zre=["file","directory"];function Cf(e){return/^https?:\/\//i.test(e)}const Zl={agent:{icon:"✦",color:"bg-brand-500/10 text-brand-500"},team:{icon:"◈",color:"bg-blue-500/10 text-blue-600"},skill:{icon:"⬡",color:"bg-amber-500/10 text-amber-600"}};function B3({authUser:e,previewMode:t,previewData:r}={}){const{t:s}=ft(["deliverables","common"]),a=Ds(),i=Rd(Te.DELIVERABLES),l=m0({side:"left",defaultWidth:384,minWidth:280,maxWidth:600,storageKey:"markus_deliverables_list"}),[d,u]=x.useState(!1),m=x.useRef(d);m.current=d,x.useEffect(()=>{if(!a)return;const _e=()=>{m.current&&u(!1)};return window.addEventListener("popstate",_e),()=>window.removeEventListener("popstate",_e)},[a]);const h=100,[p,y]=x.useState(r?.items??[]),[g,v]=x.useState(r?.items?.length??0),[j,C]=x.useState(!1),[w,N]=x.useState(r?.projects??[]),[S,T]=x.useState(r?.agents??[]),[M,D]=x.useState(!r),[I,$]=x.useState(""),[B,R]=x.useState(""),[U,W]=x.useState(""),[F,L]=x.useState(""),[z,E]=x.useState(""),[_,G]=x.useState(""),[V,O]=x.useState(""),[q,J]=x.useState("date"),[H,Z]=x.useState(()=>r?.initialSelectedId&&r.items?r.items.find(_e=>_e.id===r.initialSelectedId)??r.items[0]??null:r?.items?.[0]??null),[Y,ee]=x.useState(null),[ae,Q]=x.useState(""),[me,Ae]=x.useState(new Set),Me=x.useMemo(()=>[{id:"date"},{id:"project"},{id:"agent"},{id:"type"}],[]),He=x.useCallback(_e=>{J(_e),Ae(new Set)},[]),je=Sl(Me,q,He),xe=x.useRef(null),[Pe,Ce]=x.useState(null),[Ye,Qe]=x.useState("markdown"),[ct,st]=x.useState(null),[zt,mt]=x.useState(!1),[te,de]=x.useState(!1),[be,se]=x.useState(!1),[fe,$e]=x.useState(null),[Ne,Ze]=x.useState(""),[pe,ze]=x.useState(new Set),Fe=x.useRef(void 0),Je=(_e,Tt)=>{ee({type:_e,text:Tt}),setTimeout(()=>ee(null),3e3)},gt=async _e=>{await sy(_e)?(se(!0),setTimeout(()=>se(!1),1500)):Je("error",s("detail.copyFailed"))},nt=x.useMemo(()=>new Map(S.map(_e=>[_e.id,_e])),[S]),Et=x.useMemo(()=>new Map(w.map(_e=>[_e.id,_e])),[w]),dt=x.useCallback(_e=>{if(!_e||_e==="default")return null;const Tt=Et.get(_e)?.name;return!Tt||Tt==="default"?null:Tt},[Et]);x.useEffect(()=>{t||(le.projects.list().then(_e=>N(_e.projects)).catch(()=>{}),le.agents.list().then(_e=>T(_e.agents??[])).catch(()=>{}),le.system.storage().then(_e=>Ze(_e.dataDir+"/shared")).catch(()=>{}),le.deliverables.checkHealth().then(_e=>ze(new Set(_e.missingFiles))).catch(()=>{}))},[t]),x.useEffect(()=>(Fe.current=setTimeout(()=>R(I),300),()=>clearTimeout(Fe.current)),[I]);const Ve=x.useMemo(()=>({q:B||void 0,projectId:F||void 0,agentId:z||void 0,type:U||void 0,status:_||void 0,artifactType:V||void 0}),[B,F,z,U,_,V]),Rt=x.useCallback(async()=>{D(!0);try{const{results:_e,total:Tt}=await le.deliverables.search({...Ve,offset:0,limit:h});y(_e),v(Tt)}catch{y([]),v(0)}D(!1)},[Ve]),un=x.useCallback(async()=>{if(!(j||p.length>=g)){C(!0);try{const{results:_e,total:Tt}=await le.deliverables.search({...Ve,offset:p.length,limit:h});y(Ot=>[...Ot,..._e]),v(Tt)}catch{}C(!1)}},[Ve,p.length,g,j]);x.useEffect(()=>{t||Rt()},[Rt,t]),x.useEffect(()=>{!t||!r||(y(r.items??[]),v(r.items?.length??0),N(r.projects??[]),T(r.agents??[]),r.initialSelectedId&&Z(r.items?.find(_e=>_e.id===r.initialSelectedId)??r.items?.[0]??null))},[t,r]),x.useEffect(()=>{if(t||!i)return;const _e=pn.on("deliverable:created",()=>Rt()),Tt=pn.on("deliverable:updated",()=>Rt()),Ot=pn.on("deliverable:removed",()=>Rt());return()=>{_e(),Tt(),Ot()}},[Rt,i,t]);const yn=x.useRef(null),sn=x.useRef(p);sn.current=p;const In=x.useCallback(_e=>{const Tt=Gt=>{Z(Gt),a&&(u(!0),history.pushState({mobileDetail:Te.DELIVERABLES},"",window.location.hash))},Ot=sn.current.find(Gt=>Gt.id===_e);if(Ot){Tt(Ot);return}le.deliverables.get(_e).then(Gt=>{Gt.deliverable&&Tt(Gt.deliverable)}).catch(()=>{})},[a]);x.useEffect(()=>{if(t)return;const _e=localStorage.getItem("markus_nav_openDeliverable");_e&&(localStorage.removeItem("markus_nav_openDeliverable"),sn.current.length>0?In(_e):yn.current=_e);const Tt=Ot=>{const Gt=Ot.detail;Gt?.params?.openDeliverable&&(localStorage.removeItem("markus_nav_openDeliverable"),In(Gt.params.openDeliverable))};return window.addEventListener("markus:navigate",Tt),()=>window.removeEventListener("markus:navigate",Tt)},[In,t]),x.useEffect(()=>{const _e=yn.current;!_e||p.length===0||(yn.current=null,In(_e))},[p,In]);const jn=x.useCallback(()=>{const _e=xe.current;!_e||M||j||p.length>=g||_e.scrollHeight<=_e.clientHeight+100&&un()},[M,j,p.length,g,un]);x.useEffect(()=>{const _e=xe.current;if(!_e)return;const Tt=()=>{_e.scrollTop+_e.clientHeight>=_e.scrollHeight-100&&un()};return _e.addEventListener("scroll",Tt,{passive:!0}),()=>_e.removeEventListener("scroll",Tt)},[un]),x.useEffect(()=>{jn()},[jn,me]);const Vt=x.useMemo(()=>{const _e=new Map;for(const Ot of p){let Gt,Tn;if(q==="project"){const _n=dt(Ot.projectId);Gt=_n?Ot.projectId??"_none":"_none",Tn=_n??s("noProject")}else if(q==="agent")Gt=Ot.agentId??"_none",Tn=Ot.agentId?nt.get(Ot.agentId)?.name??Ot.agentId:s("common:unknown");else if(q==="type")Gt=Ot.type,Tn=Ot.type.charAt(0).toUpperCase()+Ot.type.slice(1);else{const _n=new Date(Ot.updatedAt);Gt=`${_n.getFullYear()}-${String(_n.getMonth()+1).padStart(2,"0")}-${String(_n.getDate()).padStart(2,"0")}`,Tn=Gt}_e.has(Gt)||_e.set(Gt,{label:Tn,items:[]}),_e.get(Gt).items.push(Ot)}const Tt=[..._e.entries()];return q==="date"?Tt.sort((Ot,Gt)=>Gt[0].localeCompare(Ot[0])):Tt.sort((Ot,Gt)=>Ot[1].label.localeCompare(Gt[1].label)),Tt},[p,q,Et,nt,s]),mn=async _e=>{Q("remove");try{await le.deliverables.remove(_e.id),Je("success",s("removed")),Z(null),Rt()}catch(Tt){Je("error",s("common:error",{message:String(Tt)}))}Q("")},Vn=()=>{pt.navigate(Te.BUILDER)},Xn=async _e=>{if(_e.reference&&!Cf(_e.reference)){if(_e.type==="directory"){de(!0);return}mt(!0);try{const Tt=await le.files.preview(_e.reference);Tt.type==="image"&&Tt.mimeType?st({src:`data:${Tt.mimeType};base64,${Tt.content}`,name:Tt.name}):(Ce(Tt.content),Qe(o7({format:_e.format,reference:_e.reference,content:Tt.content})))}catch{Ce(null),_e.type==="file"&&de(!0)}mt(!1)}};x.useEffect(()=>{t||(Ce(null),Qe("markdown"),st(null),de(!1),H&&Xn(H))},[H?.id,t]);const Rr=x.useCallback(_e=>{Ae(Tt=>{const Ot=new Set(Tt);return Ot.has(_e)?Ot.delete(_e):Ot.add(_e),Ot})},[]),qe=x.useCallback(()=>{me.size===Vt.length?Ae(new Set):Ae(new Set(Vt.map(([_e])=>_e)))},[me.size,Vt]),St=_e=>{Z(_e),a&&(u(!0),history.pushState({mobileDetail:Te.DELIVERABLES},"",window.location.hash))};return n.jsxs("div",{className:"flex-1 overflow-hidden flex",children:[n.jsxs("div",{className:`${a?"flex-1 min-w-0":"shrink-0"} flex flex-col bg-surface-secondary rounded-xl m-1 mr-0`,style:a?d?{display:"none"}:void 0:{width:l.width},children:[n.jsxs("div",{className:"p-4 space-y-3",children:[n.jsx("div",{className:"flex items-center justify-between gap-2",children:n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a&&n.jsx(gc,{}),n.jsxs("h2",{className:"text-sm font-semibold text-fg-secondary truncate",children:[s("title"),g>0&&n.jsxs("span",{className:"ml-1.5 text-fg-tertiary font-normal",children:["(",g,")"]})]})]})}),n.jsx("input",{value:I,onChange:_e=>$(_e.target.value),placeholder:s("searchPlaceholder"),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary focus:border-brand-500 focus:outline-none transition-colors"}),Ne&&n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 bg-surface-elevated rounded-lg text-[10px] text-fg-tertiary",children:[n.jsx("span",{className:"truncate font-mono",children:Ne}),n.jsx("button",{onClick:()=>{le.system.openPath(Ne)},className:"shrink-0 underline hover:text-fg-secondary transition-colors",children:s("common:open")})]}),n.jsxs("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:[n.jsx(Ou,{label:s("filters.allTypes"),value:"",current:U||V||"",onClick:()=>{W(""),O("")}}),zre.map(_e=>n.jsx(Ou,{label:`${Pu[_e]?.icon??""} ${_e}`,value:_e,current:U,onClick:Tt=>{W(Tt),O("")}},_e)),["agent","team","skill"].map(_e=>n.jsx(Ou,{label:`${Zl[_e].icon} ${s(`artifactTypes.${_e}`)}`,value:_e,current:V,onClick:Tt=>{O(Tt),W("")}},_e))]}),w.length>0&&n.jsxs("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:[n.jsx(Ou,{label:s("filters.allProjects"),value:"",current:F,onClick:L}),w.map(_e=>n.jsx(Ou,{label:_e.name,value:_e.id,current:F,onClick:L},_e.id))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("filters.group")}),["date","project","agent","type"].map(_e=>n.jsx("button",{onClick:()=>{J(_e),Ae(new Set)},className:`px-2 py-1 rounded text-xs transition-colors ${q===_e?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:bg-surface-overlay"}`,children:s(`groupBy.${_e}`)},_e)),Vt.length>1&&n.jsx("button",{onClick:qe,className:"ml-auto px-1.5 py-1 rounded text-[10px] text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated transition-colors",title:me.size===Vt.length?s("expandAllTooltip"):s("collapseAllTooltip"),children:me.size===Vt.length?s("expandAll"):s("collapseAll")})]})]}),Y&&n.jsx("div",{className:`mx-4 mt-2 px-3 py-1.5 text-xs rounded-lg ${Y.type==="success"?"bg-green-500/15 text-green-600":"bg-red-500/15 text-red-500"}`,children:Y.text}),n.jsxs("div",{ref:xe,className:"flex-1 overflow-y-auto p-2 space-y-1",onTouchStart:a?je.onTouchStart:void 0,onTouchEnd:a?je.onTouchEnd:void 0,children:[M?n.jsx("div",{className:"p-4 space-y-3",children:[1,2,3].map(_e=>n.jsxs("div",{className:"animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),n.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},_e))}):p.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center",children:[n.jsx("svg",{className:"w-12 h-12 text-fg-muted mb-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),n.jsx("p",{className:"text-sm text-fg-secondary",children:s("empty.title")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1 mb-3",children:s("empty.subtitle")}),n.jsx("button",{onClick:()=>pt.navigate(Te.WORK),className:"text-xs px-3 py-1.5 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors",children:s("empty.goToWork")})]}):Vt.map(([_e,Tt])=>{const Ot=me.has(_e);return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>Rr(_e),className:"w-full flex items-center gap-1.5 px-2 py-1.5 rounded-md hover:bg-surface-elevated/50 transition-colors group/header",children:[n.jsx("svg",{className:`w-3 h-3 text-fg-tertiary transition-transform duration-200 shrink-0 ${Ot?"":"rotate-90"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})}),n.jsx("span",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider truncate",children:Tt.label}),n.jsxs("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:["(",Tt.items.length,")"]})]}),!Ot&&Tt.items.map(Gt=>n.jsx("button",{onClick:()=>St(Gt),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${H?.id===Gt.id?"bg-brand-600/20 border border-brand-500/30":"hover:bg-surface-elevated/60 border border-transparent"}`,children:n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[Gt.artifactType&&Zl[Gt.artifactType]?n.jsx("span",{className:`text-[10px] px-1 py-0.5 rounded font-medium shrink-0 ${Zl[Gt.artifactType].color}`,children:Zl[Gt.artifactType].icon}):n.jsx("span",{className:`text-[10px] px-1 py-0.5 rounded font-medium uppercase shrink-0 ${Pu[Gt.type]?.color??"bg-surface-overlay text-fg-secondary"}`,children:Pu[Gt.type]?.icon??Gt.type.charAt(0)}),n.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:Gt.title}),pe.has(Gt.id)&&n.jsx("span",{className:"shrink-0 text-amber-500",title:s("detail.fileMissing"),children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${_re[Gt.status]?.color??"bg-surface-elevated text-fg-tertiary"}`,children:s(`common:status.${Gt.status}`,{defaultValue:Gt.status})})]})},Gt.id))]},_e)}),j&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 text-fg-tertiary",children:[n.jsx(H3,{})," ",n.jsx("span",{className:"text-[10px]",children:s("common:loadingMore")})]}),!M&&p.length>0&&n.jsx("div",{className:"text-center text-[10px] text-fg-tertiary py-2",children:p.length<g?s("count.partial",{loaded:p.length,total:g}):s("count.total",{total:g})})]})]}),!a&&n.jsx("div",{className:"w-1.5 shrink-0 cursor-col-resize group relative flex items-center justify-center",onMouseDown:l.onResizeStart,children:n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),(!a||d)&&n.jsxs("div",{className:"flex-1 overflow-y-auto min-w-0",children:[a&&n.jsxs("div",{className:"sticky top-0 z-10 bg-surface-secondary px-4 py-2.5 flex items-center gap-2",children:[n.jsx("button",{onClick:()=>history.back(),className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsx("span",{className:"text-sm font-medium truncate",children:H?.title??s("detail.details")})]}),H?n.jsxs("div",{className:"p-6 space-y-4",children:[!t&&pe.has(H.id)&&n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-500/10 border border-amber-500/20 rounded-lg text-amber-600 text-xs",children:[n.jsxs("svg",{className:"w-4 h-4 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),n.jsx("span",{children:s("detail.fileMissing")})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:H.title}),!t&&n.jsx("button",{onClick:()=>$e(H),disabled:!!ae,className:"p-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50 shrink-0",title:s("common:remove"),children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-medium uppercase ${Pu[H.type]?.color??"bg-surface-overlay text-fg-secondary"}`,children:[Pu[H.type]?.icon??""," ",H.type]}),H.artifactType&&Zl[H.artifactType]&&n.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${Zl[H.artifactType].color}`,children:[Zl[H.artifactType].icon," ",s("detail.builderWithType",{type:s(`artifactTypes.${H.artifactType}`)})]}),H.tags.length>0&&H.tags.map(_e=>n.jsx("span",{className:"px-2 py-0.5 text-xs bg-surface-elevated text-fg-secondary rounded",children:_e},_e))]}),(H.taskId||H.agentId||dt(H.projectId))&&n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[H.taskId&&n.jsx("button",{onClick:()=>pt.navigate(Te.WORK,{openTask:H.taskId}),className:"text-xs text-brand-500 hover:underline bg-brand-500/10 px-2 py-0.5 rounded",children:s("links.task",{id:`${H.taskId.slice(0,12)}...`})}),H.agentId&&n.jsx("button",{onClick:()=>pt.navigate(Te.TEAM,{selectAgent:H.agentId}),className:"text-xs text-blue-600 hover:underline bg-blue-500/10 px-2 py-0.5 rounded",children:s("links.agent",{name:nt.get(H.agentId)?.name??H.agentId.slice(0,12)})}),dt(H.projectId)&&n.jsx("button",{onClick:()=>pt.navigate(Te.WORK,{projectId:H.projectId}),className:"text-xs text-blue-600 hover:underline bg-blue-500/10 px-2 py-0.5 rounded",children:s("links.project",{name:dt(H.projectId)})})]}),(H.diffStats||H.testResults)&&n.jsxs("div",{className:"flex gap-3 flex-wrap",children:[H.diffStats&&n.jsxs("div",{className:"bg-surface-elevated rounded-lg px-3 py-2 text-xs flex items-center gap-2",children:[n.jsxs("span",{className:"text-fg-tertiary font-medium",children:[s("diffStats.title"),":"]}),n.jsx("span",{className:"text-fg-secondary",children:s("diffStats.files",{count:H.diffStats.filesChanged})}),n.jsxs("span",{className:"text-green-600",children:["+",H.diffStats.additions]}),n.jsxs("span",{className:"text-red-500",children:["-",H.diffStats.deletions]})]}),H.testResults&&n.jsxs("div",{className:"bg-surface-elevated rounded-lg px-3 py-2 text-xs flex items-center gap-2",children:[n.jsxs("span",{className:"text-fg-tertiary font-medium",children:[s("testResults.title"),":"]}),n.jsx("span",{className:"text-green-600",children:s("testResults.passed",{count:H.testResults.passed})}),n.jsx("span",{className:"text-red-500",children:s("testResults.failed",{count:H.testResults.failed})}),n.jsx("span",{className:"text-fg-secondary",children:s("testResults.skipped",{count:H.testResults.skipped})})]})]}),n.jsxs("div",{className:"flex items-center gap-4 text-[10px] text-fg-tertiary flex-wrap",children:[n.jsxs("span",{children:[s("metadata.created")," ",new Date(H.createdAt).toLocaleDateString()]}),n.jsxs("span",{children:[s("metadata.updated")," ",new Date(H.updatedAt).toLocaleDateString()]}),n.jsx("span",{className:"text-fg-muted select-all",children:H.id.slice(0,12)})]}),H.reference&&!Cf(H.reference)&&H.type==="file"&&n.jsxs("div",{className:"flex items-center gap-2 bg-surface-elevated rounded-lg px-3 py-2",children:[n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"text-xs font-mono text-brand-500 hover:text-brand-500 hover:underline truncate flex-1 text-left cursor-pointer",title:s("detail.openInFileBrowser"),children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"px-2 py-1 text-[10px] rounded bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",title:s("detail.revealInFinder"),children:s("common:open")}),n.jsx("button",{onClick:()=>gt(H.reference),className:`px-2 py-1 text-[10px] rounded transition-colors shrink-0 ${be?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,title:s("detail.copyPath"),children:s(be?"common:copied":"common:copy")})]}),H.reference&&!Cf(H.reference)&&H.type!=="file"&&H.type!=="directory"&&n.jsx("span",{className:"text-xs text-fg-tertiary font-mono break-all",children:H.reference})]}),H.artifactType&&H.artifactData?n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Ore,{artifact:H.artifactData,mode:H.artifactType})}),H.reference&&n.jsxs("div",{className:"px-3 py-2 bg-surface-elevated rounded-lg",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider block mb-1",children:s("detail.artifactDirectory")}),n.jsx("span",{className:"text-xs text-fg-secondary font-mono break-all",children:H.reference})]}),n.jsx("div",{className:"flex gap-2",children:n.jsx("button",{onClick:Vn,className:"flex-1 px-4 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openInBuilder")})}),H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})})]}):H.reference&&Cf(H.reference)?n.jsxs("div",{className:"space-y-4",children:[H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})}),n.jsxs("div",{className:"flex flex-col items-center justify-center py-10",children:[n.jsxs("svg",{className:"w-10 h-10 text-fg-muted mb-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),n.jsx("p",{className:"text-xs text-fg-tertiary font-mono mb-4 px-4 text-center break-all select-all",children:H.reference}),n.jsx("button",{onClick:()=>window.open(H.reference,"_blank","noopener,noreferrer"),className:"px-6 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openUrl")})]})]}):H.type==="directory"&&H.reference?n.jsxs("div",{className:"space-y-4",children:[H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})}),n.jsxs("div",{className:"flex flex-col items-center justify-center py-10",children:[n.jsx("svg",{className:"w-10 h-10 text-fg-muted mb-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-xs text-fg-tertiary font-mono mb-4 px-4 text-center break-all select-all",children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"px-6 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openInFileBrowser")})]})]}):n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:zt?n.jsxs("div",{className:"flex items-center gap-2 text-fg-tertiary text-sm",children:[n.jsx(H3,{})," ",s("detail.loadingPreview")]}):ct?n.jsxs("div",{className:"flex flex-col items-center gap-2",children:[n.jsx("img",{src:ct.src,alt:ct.name,className:"max-w-full max-h-[60vh] rounded-lg object-contain"}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:ct.name})]}):Pe?n.jsx(uy,{content:Pe,format:Ye,className:"text-fg-secondary text-sm"}):te?n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-fg-secondary",children:s("detail.cannotPreview",{type:H.type})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpen")))},className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:s("detail.openInFileBrowser"),children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpen")))},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:s("common:open")}),n.jsx("button",{onClick:()=>gt(H.reference),className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${be?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:s(be?"common:copied":"common:copy")})]})]}):H.summary?n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"}):n.jsx("p",{className:"text-sm text-fg-tertiary italic",children:s("detail.noContent")})})]}):n.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:n.jsxs("div",{className:"text-center text-fg-tertiary space-y-2",children:[n.jsx("svg",{className:"w-12 h-12 mx-auto text-fg-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),n.jsx("p",{className:"text-sm",children:s("detail.selectToView")})]})})]}),fe&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:()=>$e(null),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-6 max-w-sm mx-4 shadow-2xl",onClick:_e=>_e.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{className:"w-5 h-5 text-red-500",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("detail.confirmRemoveTitle")}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:s("detail.confirmRemoveMessage",{name:fe.title})})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>$e(null),className:"px-4 py-1.5 text-xs text-fg-secondary hover:text-fg-primary border border-border-default hover:border-gray-600 rounded-lg transition-colors",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{const _e=fe;$e(null),mn(_e)},disabled:!!ae,className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-500 text-white rounded-lg transition-colors disabled:opacity-50",children:s("common:remove")})]})]})})]})}function Ou({label:e,value:t,current:r,onClick:s}){return n.jsx("button",{onClick:()=>s(r===t?"":t),className:`px-2 py-1 rounded text-xs whitespace-nowrap shrink-0 transition-colors ${r===t?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:bg-surface-overlay"}`,children:e})}function H3(){return n.jsxs("svg",{className:"animate-spin h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function Co(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function ld(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function $re(e){return e>=1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)} GB`:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function F3({authUser:e}){const{t}=ft(["reports","common"]),r=Ds(),s=Rd(Te.REPORTS),[a,i]=x.useState("weekly"),[l,d]=x.useState(null),[u,m]=x.useState(!0),[h,p]=x.useState(""),[y,g]=x.useState(null),[v,j]=x.useState([]),[C,w]=x.useState("totalTokens"),[N,S]=x.useState(!0),[T,M]=x.useState("generate"),[D,I]=x.useState([]),[$,B]=x.useState(null),[R,U]=x.useState([]),[W,F]=x.useState(""),[L,z]=x.useState(""),E=Q=>{z(Q),setTimeout(()=>z(""),3e3)},_=x.useCallback(async Q=>{m(!0),p("");try{const{report:me}=await le.reports.generate({period:Q,scope:"org",orgId:"default"});d(me)}catch(me){p(String(me)),d(null)}m(!1)},[]),G=x.useCallback(()=>{le.usage.summary().then(Q=>g(Q.usage)).catch(()=>{}),le.usage.agents().then(Q=>j(Q.agents)).catch(()=>{})},[]),V=x.useCallback(async()=>{try{const{reports:Q}=await le.reports.list();I(Q)}catch{}},[]),O=x.useCallback(async Q=>{B(Q);try{const{feedback:me}=await le.reports.getFeedback(Q.id);U(me)}catch{U([])}},[]);x.useEffect(()=>{_(a)},[a,_]),x.useEffect(()=>{if(!s)return;G();const Q=setInterval(G,3e4);return()=>clearInterval(Q)},[G,s]),x.useEffect(()=>{T==="history"&&V()},[T,V]);const q=x.useMemo(()=>[...v].sort((Q,me)=>{const Ae=Q[C],Me=me[C];return N?Me-Ae:Ae-Me}),[v,C,N]),J=v.reduce((Q,me)=>Q+me.estimatedCost,0),H=v.reduce((Q,me)=>Q+me.tokensUsedToday,0),Z=v.reduce((Q,me)=>Q+(me.costToday??0),0),Y=Math.max(1,...v.map(Q=>Q.totalTokens)),ee=Q=>{C===Q?S(!N):(w(Q),S(!0))},ae=x.useMemo(()=>({daily:t("period.today"),weekly:t("period.thisWeek"),monthly:t("period.thisMonth")}),[t]);return n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsxs("div",{className:"max-w-5xl mx-auto w-full p-6 space-y-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[n.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[r&&n.jsx(gc,{}),n.jsx("h1",{className:"text-xl font-semibold text-fg-primary",children:t("title")}),n.jsxs("div",{className:"flex gap-1 bg-surface-elevated rounded-lg p-0.5",children:[n.jsx("button",{onClick:()=>M("generate"),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${T==="generate"?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:t("tabs.generate")}),n.jsxs("button",{onClick:()=>M("history"),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${T==="history"?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:[t("tabs.history"),D.length>0?` (${D.length})`:""]})]})]}),n.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[L&&n.jsx("span",{className:"px-2.5 py-1 bg-green-500/10 text-green-600 text-xs rounded-lg",children:L}),T==="generate"&&n.jsx("div",{className:"flex gap-1 bg-surface-elevated rounded-lg p-0.5",children:["daily","weekly","monthly"].map(Q=>n.jsx("button",{onClick:()=>i(Q),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${a===Q?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:t(`period.${Q}`)},Q))})]})]}),T==="history"&&!$&&n.jsx("section",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:D.length===0?n.jsx("div",{className:"p-8 text-center text-fg-tertiary text-sm",children:t("noReportsYet")}):n.jsx("div",{className:"divide-y divide-border-default/50",children:D.map(Q=>n.jsxs("button",{onClick:()=>O(Q),className:"w-full text-left px-5 py-3 flex items-center gap-4 hover:bg-surface-elevated/30 transition-colors",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:t("reportType",{type:Q.type})}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[new Date(Q.periodStart).toLocaleDateString()," — ",new Date(Q.periodEnd).toLocaleDateString()]})]}),Q.plan&&n.jsx("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-medium shrink-0 ${Q.plan.status==="approved"?"bg-green-500/10 text-green-600":Q.plan.status==="rejected"?"bg-red-500/10 text-red-500":"bg-amber-500/10 text-amber-600"}`,children:Q.plan.status==="pending"?t("upcomingPlan.planPending"):t("upcomingPlan.planStatus",{status:Q.plan.status})}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(Q.generatedAt).toLocaleDateString()})]},Q.id))})}),T==="history"&&$&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:()=>{B(null),U([])},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:t("backToList")}),n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t("reportType",{type:$.type})}),n.jsxs("span",{className:"text-xs text-fg-tertiary",children:[new Date($.periodStart).toLocaleDateString()," — ",new Date($.periodEnd).toLocaleDateString()]})]}),$.metrics&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskMetrics.title")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[n.jsx(Hi,{label:t("taskMetrics.completed"),value:$.metrics.tasksCompleted,color:"text-green-600"}),n.jsx(Hi,{label:t("taskMetrics.inProgress"),value:$.metrics.tasksInProgress,color:"text-brand-500"}),n.jsx(Hi,{label:t("taskMetrics.created"),value:$.metrics.tasksCreated,color:"text-blue-600"}),n.jsx(Hi,{label:t("taskMetrics.blocked"),value:$.metrics.tasksBlocked,color:"text-amber-600"}),n.jsx(Hi,{label:t("taskMetrics.failed"),value:$.metrics.tasksFailed,color:"text-red-500"})]})]}),$.costSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("costOverview.title")}),n.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:$.costSummary.totalTokens.toLocaleString()}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.totalTokens")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld($.costSummary.totalEstimatedCost)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.estimatedCost")})]}),n.jsxs("div",{children:[n.jsxs("div",{className:`text-2xl font-bold ${$.costSummary.trend==="decreasing"?"text-green-600":$.costSummary.trend==="increasing"?"text-red-500":"text-fg-primary"}`,children:[$.costSummary.trend==="decreasing"?"↓":$.costSummary.trend==="increasing"?"↑":"→"," ",$.costSummary.trend]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.trend")})]})]}),$.costSummary.byAgent&&$.costSummary.byAgent.length>0&&n.jsx("div",{className:"mt-4 pt-3 border-t border-border-default/50 space-y-1.5",children:$.costSummary.byAgent.map((Q,me)=>n.jsxs("div",{className:"flex items-center justify-between text-xs",children:[n.jsx("span",{className:"text-fg-secondary",children:Q.agentId}),n.jsx("span",{className:"text-fg-tertiary tabular-nums",children:t("costOverview.byAgentRow",{tokens:Co(Q.tokens),cost:ld(Q.cost)})})]},me))})]}),$.taskSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5 overflow-hidden",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskSummary.title")}),n.jsxs("div",{className:"space-y-4 min-w-0",children:[$.taskSummary.completed.length>0&&n.jsx(sd,{title:t("taskSummary.completedCount",{count:$.taskSummary.completed.length}),color:"emerald",items:$.taskSummary.completed.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),$.taskSummary.inProgress.length>0&&n.jsx(sd,{title:t("taskSummary.inProgressCount",{count:$.taskSummary.inProgress.length}),color:"indigo",items:$.taskSummary.inProgress.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),$.taskSummary.blocked.length>0&&n.jsx(sd,{title:t("taskSummary.blockedCount",{count:$.taskSummary.blocked.length}),color:"amber",items:$.taskSummary.blocked.map(Q=>({id:Q.id,label:Q.title,sub:Q.reason||Q.agent}))}),$.taskSummary.completed.length===0&&$.taskSummary.inProgress.length===0&&$.taskSummary.blocked.length===0&&n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("taskSummary.noTasksInPeriod")})]})]}),$.highlights&&$.highlights.length>0&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-2",children:t("highlights")}),n.jsx("ul",{className:"list-disc list-inside space-y-1 text-sm text-fg-secondary",children:$.highlights.map((Q,me)=>n.jsx("li",{children:Q},me))})]}),$.blockers&&$.blockers.length>0&&n.jsxs("section",{className:"bg-surface-secondary border border-amber-500/20 rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-amber-600 mb-2",children:t("blockers")}),n.jsx("ul",{className:"list-disc list-inside space-y-1 text-sm text-fg-secondary",children:$.blockers.map((Q,me)=>n.jsx("li",{children:Q},me))})]}),$.plan&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("h3",{className:"text-xs font-semibold text-fg-secondary",children:[t("upcomingPlan.title"),n.jsx("span",{className:`ml-2 px-1.5 py-0.5 rounded text-[10px] font-medium ${$.plan.status==="approved"?"bg-green-500/10 text-green-600":$.plan.status==="rejected"?"bg-red-500/10 text-red-500":"bg-amber-500/10 text-amber-600"}`,children:t(`common:status.${$.plan.status}`,{defaultValue:$.plan.status})})]}),$.plan.status==="pending"&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:async()=>{try{const{report:Q}=await le.reports.approvePlan($.id,{approvedBy:e?.id??"unknown"});B(Q),E(t("upcomingPlan.planApproved")),V()}catch(Q){E(t("common:error",{message:String(Q)}))}},className:"px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-500 transition-colors",children:t("upcomingPlan.approvePlan")}),n.jsx("button",{onClick:async()=>{const Q=prompt(t("upcomingPlan.rejectionReason"));if(Q)try{const{report:me}=await le.reports.rejectPlan($.id,{rejectedBy:e?.id??"unknown",reason:Q});B(me),E(t("upcomingPlan.planRejected")),V()}catch(me){E(t("common:error",{message:String(me)}))}},className:"px-3 py-1.5 text-xs font-medium border border-border-default text-fg-secondary rounded-lg hover:bg-surface-overlay transition-colors",children:t("upcomingPlan.rejectPlan")})]})]}),$.plan.items&&$.plan.items.length>0&&n.jsx("div",{className:"space-y-1.5",children:$.plan.items.map((Q,me)=>n.jsxs("div",{className:"flex items-center gap-2 text-sm text-fg-secondary",children:[n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${Q.priority==="high"?"bg-red-500/10 text-red-500":Q.priority==="medium"?"bg-amber-500/10 text-amber-600":"bg-gray-500/10 text-fg-tertiary"}`,children:Q.priority}),n.jsx("span",{children:Q.title}),Q.assignee&&n.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:Q.assignee})]},me))})]}),!$.metrics&&!$.taskSummary&&!$.costSummary&&n.jsx("section",{className:"bg-surface-elevated rounded-xl p-8 text-center",children:n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("noDetailedMetrics")})}),n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("feedback.title",{count:R.length})}),R.length>0&&n.jsx("div",{className:"space-y-2 mb-4",children:R.map(Q=>n.jsxs("div",{className:"p-3 bg-surface-elevated/50 rounded-lg",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary mb-1",children:[n.jsx("span",{className:"font-medium text-fg-secondary",children:Q.authorName}),n.jsx("span",{children:Q.type}),n.jsx("span",{children:new Date(Q.createdAt).toLocaleDateString()})]}),n.jsx("p",{className:"text-xs text-fg-secondary",children:Q.content})]},Q.id))}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{value:W,onChange:Q=>F(Q.target.value),placeholder:t("feedback.placeholder"),className:"flex-1 px-3 py-2 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder:text-fg-tertiary",onKeyDown:Q=>{Q.key==="Enter"&&W.trim()&&le.reports.addFeedback($.id,{author:e?.id??"unknown",type:"comment",content:W.trim()}).then(({feedback:me})=>{U(Ae=>[...Ae,me]),F(""),E(t("feedback.added"))}).catch(me=>E(t("common:error",{message:String(me)})))}}),n.jsx("button",{onClick:()=>{W.trim()&&le.reports.addFeedback($.id,{author:e?.id??"unknown",type:"comment",content:W.trim()}).then(({feedback:Q})=>{U(me=>[...me,Q]),F(""),E(t("feedback.added"))}).catch(Q=>E(t("common:error",{message:String(Q)})))},disabled:!W.trim(),className:"px-3 py-2 text-xs bg-brand-600 text-white rounded-lg hover:bg-brand-500 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:t("common:send")})]})]})]}),T==="generate"&&y&&n.jsxs("div",{className:`grid gap-4 ${y.storageBytes>0?"grid-cols-2 lg:grid-cols-4":"grid-cols-3"}`,children:[n.jsx(Tf,{label:t("usage.llmTokens"),value:Co(y.llmTokens),color:"text-brand-500"}),n.jsx(Tf,{label:t("usage.toolCalls"),value:Co(y.toolCalls),color:"text-blue-600"}),n.jsx(Tf,{label:t("usage.messages"),value:Co(y.messages),color:"text-green-600"}),y.storageBytes>0&&n.jsx(Tf,{label:t("usage.storage"),value:$re(y.storageBytes),color:"text-amber-600"})]}),T==="generate"&&(u?n.jsx("div",{className:"flex items-center justify-center h-32 text-fg-tertiary text-sm",children:t("common:loading")}):h?n.jsx("div",{className:"flex items-center justify-center h-32 text-red-500 text-sm",children:h}):l?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae[a]," · ",new Date(l.periodStart).toLocaleDateString()," — ",new Date(l.periodEnd).toLocaleDateString()]}),l.metrics&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskMetrics.title")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[n.jsx(Hi,{label:t("taskMetrics.completed"),value:l.metrics.tasksCompleted,color:"text-green-600"}),n.jsx(Hi,{label:t("taskMetrics.inProgress"),value:l.metrics.tasksInProgress,color:"text-brand-500"}),n.jsx(Hi,{label:t("taskMetrics.created"),value:l.metrics.tasksCreated,color:"text-blue-600"}),n.jsx(Hi,{label:t("taskMetrics.blocked"),value:l.metrics.tasksBlocked,color:"text-amber-600"}),n.jsx(Hi,{label:t("taskMetrics.failed"),value:l.metrics.tasksFailed,color:"text-red-500"})]})]}),n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("costOverview.title")}),n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld(J)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.estCostAllTime")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:Co(H)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.tokensToday")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld(Z)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.costToday")})]})]})]}),l.taskSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskSummary.title")}),n.jsxs("div",{className:"space-y-4",children:[l.taskSummary.completed.length>0&&n.jsx(sd,{title:t("taskSummary.completedCount",{count:l.taskSummary.completed.length}),color:"emerald",items:l.taskSummary.completed.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),l.taskSummary.inProgress.length>0&&n.jsx(sd,{title:t("taskSummary.inProgressCount",{count:l.taskSummary.inProgress.length}),color:"indigo",items:l.taskSummary.inProgress.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),l.taskSummary.blocked.length>0&&n.jsx(sd,{title:t("taskSummary.blockedCount",{count:l.taskSummary.blocked.length}),color:"amber",items:l.taskSummary.blocked.map(Q=>({id:Q.id,label:Q.title,sub:Q.reason||Q.agent}))}),l.taskSummary.completed.length===0&&l.taskSummary.inProgress.length===0&&l.taskSummary.blocked.length===0&&n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("taskSummary.noTasksInPeriod")})]})]})]}):null),T==="generate"&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:[n.jsx("div",{className:"px-5 py-4 border-b border-border-default",children:n.jsx("h3",{className:"text-sm font-semibold text-fg-secondary",children:t("perAgentUsage.title")})}),v.length===0?n.jsx("div",{className:"p-8 text-center text-fg-tertiary text-sm",children:t("perAgentUsage.noData")}):n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border-default text-xs text-fg-tertiary uppercase tracking-wider",children:[n.jsx("th",{className:"px-4 py-3 text-left font-medium",children:t("perAgentUsage.agent")}),n.jsx(_u,{label:t("perAgentUsage.totalTokens"),col:"totalTokens",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.today"),col:"tokensUsedToday",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.requests"),col:"requestCount",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.toolCalls"),col:"toolCalls",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.estCost"),col:"estimatedCost",current:C,desc:N,onSort:ee,align:"right"})]})}),n.jsx("tbody",{children:q.map(Q=>n.jsx(Bre,{agent:Q,maxTokens:Y},Q.agentId))}),n.jsx("tfoot",{children:n.jsxs("tr",{className:"border-t border-border-default bg-surface-elevated/30",children:[n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary",children:t("perAgentUsage.totalAgents",{count:v.length})}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:Co(v.reduce((Q,me)=>Q+me.totalTokens,0))}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:Co(H)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:v.reduce((Q,me)=>Q+me.requestCount,0)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:v.reduce((Q,me)=>Q+me.toolCalls,0)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-right text-fg-secondary tabular-nums",children:ld(J)})]})})]})})]})]})})}function Hi({label:e,value:t,color:r}){return n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:`text-2xl font-bold ${r}`,children:t}),n.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:e})]})}function sd({title:e,color:t,items:r}){return n.jsxs("div",{className:"min-w-0 overflow-hidden",children:[n.jsx("div",{className:`text-xs font-medium text-${t}-400 mb-1.5`,children:e}),n.jsx("div",{className:"space-y-1.5",children:r.map((s,a)=>n.jsxs("div",{className:`text-sm text-fg-secondary min-w-0 ${s.id?"cursor-pointer hover:text-fg-primary group":""}`,onClick:s.id?()=>pt.navigate(Te.WORK,{openTask:s.id}):void 0,children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full bg-${t}-500 shrink-0`}),n.jsx("span",{className:`truncate min-w-0 ${s.id?"group-hover:text-brand-500 transition-colors":""}`,children:s.label})]}),s.sub&&s.sub!=="unassigned"&&n.jsx("div",{className:"text-[10px] text-fg-tertiary ml-3.5 mt-0.5 break-all line-clamp-2",children:s.sub})]},s.id??a))})]})}function Tf({label:e,value:t,color:r}){return n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("div",{className:"text-sm text-fg-secondary mb-2",children:e}),n.jsx("div",{className:`text-2xl font-bold ${r}`,children:t})]})}function _u({label:e,col:t,current:r,desc:s,onSort:a,align:i}){const l=r===t?s?"↓":"↑":"↕",d=r===t?"text-brand-500":"text-fg-muted";return n.jsxs("th",{className:`px-4 py-3 ${i==="right"?"text-right":"text-left"} font-medium cursor-pointer select-none hover:text-fg-secondary`,onClick:()=>a(t),children:[e,n.jsx("span",{className:`ml-1 ${d}`,children:l})]})}function Bre({agent:e,maxTokens:t}){const r=t>0?Math.min(100,e.totalTokens/t*100):0,s=e.status==="working"?"bg-blue-500":e.status==="idle"?"bg-green-500":e.status==="paused"?"bg-amber-500":e.status==="error"?"bg-red-500":"bg-gray-600";return n.jsxs("tr",{className:"border-b border-border-default/50 hover:bg-surface-elevated/30 transition-colors cursor-pointer",onClick:()=>pt.navigate(Te.TEAM,{selectAgent:e.agentId}),children:[n.jsx("td",{className:"px-4 py-3",children:n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsx("div",{className:`w-2 h-2 rounded-full ${s}`}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary hover:text-brand-500 transition-colors",children:e.agentName}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:e.role})]})]})}),n.jsx("td",{className:"px-4 py-3",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"flex-1 bg-surface-elevated rounded-full h-1.5 overflow-hidden max-w-[120px]",children:n.jsx("div",{className:"h-full bg-brand-500 rounded-full",style:{width:`${r}%`}})}),n.jsx("span",{className:"text-sm text-fg-secondary tabular-nums",children:Co(e.totalTokens)})]})}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:Co(e.tokensUsedToday)}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:e.requestCount}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:e.toolCalls}),n.jsx("td",{className:"px-4 py-3 text-sm text-right text-fg-secondary tabular-nums",children:ld(e.estimatedCost)})]})}const Af={urgent:"bg-red-500",high:"bg-amber-500",normal:"bg-blue-500",low:"bg-gray-400"},ad={approval_request:"M9 12l2 2 4-4 M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z",task_completed:"M22 11.08V12a10 10 0 1 1-5.93-9.14 M22 4L12 14.01l-3-3",task_created:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",task_review:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",task_failed:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",requirement_created:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7 M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z",requirement_decision:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",agent_report:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8",direct_message:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",group_message:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2 M9 7a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M23 21v-2a4 4 0 0 0-3-3.87 M16 3.13a4 4 0 0 1 0 7.75",system:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"},q3={approval_request:"text-amber-500",task_completed:"text-green-500",task_failed:"text-red-500",task_created:"text-blue-500",task_review:"text-purple-500",requirement_created:"text-amber-500",requirement_decision:"text-green-500",agent_report:"text-blue-500",direct_message:"text-green-500",group_message:"text-brand-500",system:"text-fg-tertiary"};function id(e,t){const r=Date.now()-new Date(e).getTime(),s=Math.floor(r/6e4);if(s<1)return t("common:time.now");if(s<60)return t("common:time.minutesAgo",{count:s});const a=Math.floor(s/60);return a<24?t("common:time.hoursAgo",{count:a}):t("common:time.daysAgo",{count:Math.floor(a/24)})}function Ef(e,t){const r=e.actionType;if(r==="open_chat")return t("team:notifications.actionHints.openChat");if(r==="navigate")return t("team:notifications.actionHints.viewDetails");const s=e.metadata??{};switch(e.type){case"task_completed":case"task_created":case"task_review":case"task_failed":return s.taskId?t("team:notifications.actionHints.viewTask"):null;case"requirement_created":case"requirement_decision":return s.requirementId?t("team:notifications.actionHints.viewRequirement"):null;case"agent_report":return s.agentId?t("team:notifications.actionHints.viewAgent"):null;case"direct_message":return t("team:notifications.actionHints.openChat");case"group_message":return t("team:notifications.actionHints.openChat");case"approval_request":return t("team:notifications.actionHints.viewApproval");default:return s.taskId?t("team:notifications.actionHints.viewTask"):s.requirementId?t("team:notifications.actionHints.viewRequirement"):s.agentId?t("team:notifications.actionHints.viewAgent"):null}}function Hre(){try{const e=new AudioContext,t=e.currentTime,r=e.createGain();r.connect(e.destination),r.gain.setValueAtTime(.15,t),r.gain.exponentialRampToValueAtTime(.01,t+.6);const s=e.createOscillator();s.type="sine",s.frequency.setValueAtTime(880,t),s.frequency.setValueAtTime(1174.66,t+.15),s.connect(r),s.start(t),s.stop(t+.6),s.onended=()=>e.close()}catch{}}function nC({collapsed:e,userId:t,embeddedMode:r,onClose:s,sidebarMode:a,isActive:i,label:l,iconPath:d}){const{t:u}=ft(["team","common"]),[m,h]=x.useState(!1),[p,y]=x.useState("approvals"),[g,v]=x.useState([]),[j,C]=x.useState([]),[w,N]=x.useState(null),[S,T]=x.useState(null),[M,D]=x.useState({}),[I,$]=x.useState(0),B=x.useRef(null),R=x.useRef(null),[U,W]=x.useState({top:0,left:0,width:448,maxHeight:576}),F=x.useRef(null),L=x.useRef(!1),[z,E]=x.useState(!0),[_,G]=x.useState(!1),V=x.useRef(null),O=x.useRef("approvals"),q=30,J=x.useCallback(async()=>{try{const[se,fe]=await Promise.all([le.notifications.list(t,!1,{limit:q,offset:0}),le.approvals.list()]);if(v(se.notifications),$(se.unreadCount??se.notifications.filter($e=>!$e.read).length),E(se.totalCount!=null?se.notifications.length<se.totalCount:se.notifications.length>=q),C(fe.approvals),!L.current){const $e=fe.approvals.filter(Ne=>Ne.status==="pending").length;F.current=$e,L.current=!0}}catch{}},[t]),H=x.useCallback(async()=>{if(!(_||!z)){G(!0);try{const se=await le.notifications.list(t,!1,{limit:q,offset:g.length});se.notifications.length>0&&v(fe=>[...fe,...se.notifications.filter($e=>!fe.some(Ne=>Ne.id===$e.id))]),E(se.totalCount!=null?g.length+se.notifications.length<se.totalCount:se.notifications.length>=q)}catch{}G(!1)}},[t,g.length,_,z]),Z=x.useCallback(se=>{const fe=se.detail;if(!fe)return;const{taskId:$e,requirementId:Ne}=fe;!$e&&!Ne||v(Ze=>{const pe=Ze.filter(ze=>!ze.read&&($e&&ze.metadata?.taskId===$e||Ne&&ze.metadata?.requirementId===Ne));if(pe.length===0)return Ze;for(const ze of pe)le.notifications.markRead(ze.id).catch(()=>{});return $(ze=>Math.max(0,ze-pe.length)),Ze.map(ze=>pe.some(Fe=>Fe.id===ze.id)?{...ze,read:!0}:ze)})},[]);x.useEffect(()=>{J();const se=setInterval(J,6e4),fe=()=>J(),$e=()=>{h(!0),J()};window.addEventListener("markus:notifications-changed",fe),window.addEventListener("markus:mark-read-by-ref",Z),window.addEventListener("markus:open-notifications",$e);const Ne=pn.on("notification:created",()=>J()),Ze=pn.on("approval:created",()=>J());return()=>{clearInterval(se),window.removeEventListener("markus:notifications-changed",fe),window.removeEventListener("markus:mark-read-by-ref",Z),window.removeEventListener("markus:open-notifications",$e),Ne(),Ze()}},[J,Z]);const Y=x.useCallback(()=>{if(!B.current)return;const se=B.current.getBoundingClientRect(),fe=window.innerWidth,$e=window.innerHeight,Ne=Math.min(448,fe-16),Ze=Math.min(576,$e-16);let pe=se.right+8,ze=se.top;pe+Ne>fe-8&&(pe=Math.max(8,fe-Ne-8)),ze+Ze>$e-8&&(ze=Math.max(8,$e-Ze-8)),W({top:ze,left:pe,width:Ne,maxHeight:Ze})},[]);x.useLayoutEffect(()=>{m&&Y()},[m,Y]),x.useEffect(()=>{if(m)return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[m,Y]),x.useEffect(()=>{if(!m)return;const se=fe=>{B.current?.contains(fe.target)||R.current?.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[m]),x.useEffect(()=>{if(!m)return;const se=j.some($e=>$e.status==="pending"),fe=g.some($e=>!$e.read);y(se&&!fe?"approvals":!se&&fe?"notifications":O.current)},[m]);const ee=new Set(j.filter(se=>se.status==="pending").map(se=>se.id)),ae=new Set(j.map(se=>se.id)),Q=g.filter(se=>!(se.type==="approval_request"&&se.metadata?.approvalId&&ae.has(se.metadata.approvalId))),me=g.filter(se=>se.type==="approval_request"&&!se.read&&se.metadata?.approvalId&&ee.has(se.metadata.approvalId)).length,Ae=Math.max(0,I-me),Me=ee.size,He=Ae+Me;x.useEffect(()=>{F.current!==null&&Me>F.current&&Hre(),F.current=Me},[Me]);const je=async se=>{await le.notifications.markRead(se),v(fe=>fe.map($e=>$e.id===se?{...$e,read:!0}:$e)),$(fe=>Math.max(0,fe-1))},xe=se=>{const fe=se.metadata??{},$e=se.actionType,Ne=se.actionTarget;if($e==="open_chat"&&Ne)try{const Ze=typeof Ne=="string"?JSON.parse(Ne):Ne;if(Ze.agentId){const pe={agentId:Ze.agentId};Ze.sessionId&&(pe.sessionId=Ze.sessionId),pt.navigate(Te.TEAM,pe);return}}catch{}if($e==="navigate"&&Ne)try{const Ze=typeof Ne=="string"?JSON.parse(Ne):Ne;if(Ze.path){if(Ze.path.startsWith("/team")){const pe={},ze=new URLSearchParams(Ze.path.split("?")[1]||"");for(const[Fe,Je]of ze.entries())pe[Fe]=Je;pt.navigate(Te.TEAM,pe);return}if(Ze.path.startsWith("/work")){const pe={},ze=new URLSearchParams(Ze.path.split("?")[1]||"");for(const[Fe,Je]of ze.entries())pe[Fe]=Je;pt.navigate(Te.WORK,pe);return}}}catch{}switch(se.type){case"approval_request":{const Ze=fe.approvalId,pe=Ze?j.find(gt=>gt.id===Ze):void 0,ze=pe?.details?.taskId??fe.taskId,Fe=pe?.details?.requirementId??fe.requirementId,Je=pe?.details?.agentId??pe?.agentId;ze?pt.navigate(Te.WORK,{openTask:ze}):Fe?pt.navigate(Te.WORK,{openRequirement:Fe}):Je?pt.navigate(Te.TEAM,{agentId:Je}):pt.navigate(Te.WORK);break}case"task_completed":case"task_created":case"task_review":case"task_failed":fe.taskId?pt.navigate(Te.WORK,{openTask:fe.taskId}):pt.navigate(Te.WORK);break;case"requirement_created":case"requirement_decision":fe.requirementId?pt.navigate(Te.WORK,{openRequirement:fe.requirementId}):pt.navigate(Te.WORK);break;case"agent_report":case"system":{if(fe.agentId){const Ze={agentId:fe.agentId};fe.sessionId&&(Ze.sessionId=fe.sessionId),pt.navigate(Te.TEAM,Ze)}else pt.navigate(Te.TEAM);break}case"direct_message":{const Ze=fe.senderId;Ze?pt.navigate(Te.TEAM,{dm:Ze}):pt.navigate(Te.TEAM);break}case"group_message":{const Ze=fe.channel;Ze?pt.navigate(Te.TEAM,{channel:Ze}):pt.navigate(Te.TEAM);break}default:fe.taskId?pt.navigate(Te.WORK,{openTask:fe.taskId}):fe.requirementId?pt.navigate(Te.WORK,{openRequirement:fe.requirementId}):fe.projectId?pt.navigate(Te.WORK,{projectId:fe.projectId}):fe.agentId&&pt.navigate(Te.TEAM,{agentId:fe.agentId});break}},Pe=async se=>{se.read||je(se.id);const fe=se.metadata??{},$e=fe.taskId,Ne=fe.requirementId;if($e||Ne){const Ze=g.filter(pe=>pe.id!==se.id&&!pe.read&&($e&&pe.metadata?.taskId===$e||Ne&&pe.metadata?.requirementId===Ne));for(const pe of Ze)je(pe.id)}xe(se)},Ce=async(se,fe,$e,Ne)=>{N(se);try{const{approval:Ze}=await le.approvals.respond(se,fe,t,$e,Ne);C(Je=>Je.map(gt=>gt.id===se?Ze:gt)),T(null),D(Je=>{const gt={...Je};return delete gt[se],gt});const pe=Ze.details?.taskId,ze=Ze.details?.requirementId,Fe=g.filter(Je=>!Je.read&&(Je.type==="approval_request"&&Je.metadata?.approvalId===se||pe&&Je.metadata?.taskId===pe||ze&&Je.metadata?.requirementId===ze));if(Fe.length>0){for(const gt of Fe)le.notifications.markRead(gt.id).catch(()=>{});const Je=new Set(Fe.map(gt=>gt.id));v(gt=>gt.map(nt=>Je.has(nt.id)?{...nt,read:!0}:nt)),$(gt=>Math.max(0,gt-Fe.length))}pl("/approvals"),pl("/notifications"),pl("/tasks"),pl("/taskboard"),pl("/requirements"),window.dispatchEvent(new CustomEvent("markus:data-changed")),window.dispatchEvent(new CustomEvent("markus:notifications-changed")),setTimeout(()=>J(),800)}catch{}N(null)},Ye=async()=>{try{if(!t)return;await le.notifications.markAllRead(t),v(se=>se.map(fe=>({...fe,read:!0}))),$(0),pl("/notifications")}catch{const se=Q.filter(fe=>!fe.read);await Promise.all(se.map(fe=>le.notifications.markRead(fe.id))),v(fe=>fe.map($e=>({...$e,read:!0}))),$(0),pl("/notifications")}},Qe=se=>{const fe=se.details?.subType;return fe==="requirement_resubmit"?u("team:notifications.approvalType.requirementResubmit"):fe==="requirement"||se.details?.requirementId?u("team:notifications.approvalType.requirement"):fe==="task_review"?u("team:notifications.approvalType.taskReview"):fe==="task"||se.details?.taskId?u("team:notifications.approvalType.task"):se.details?.toolName?u("team:notifications.approvalType.toolExecution"):null},ct=se=>{const fe=[];fe.push(se.agentName);const $e=se.details?.taskTitle,Ne=se.details?.taskId;$e?fe.push($e):Ne&&fe.push(`Task ${Ne.slice(0,8)}`);const Ze=se.details?.requirementId;return Ze&&!Ne&&fe.push(`Req ${Ze.slice(0,8)}`),fe.join(" · ")},st=[...j].sort((se,fe)=>new Date(fe.requestedAt).getTime()-new Date(se.requestedAt).getTime()),zt=st.filter(se=>se.status==="pending"),mt=st.filter(se=>se.status!=="pending"),te=se=>{const fe=se.details?.taskId,$e=se.details?.requirementId,Ne=se.details?.agentId??se.agentId;fe?pt.navigate(Te.WORK,{openTask:fe}):$e?pt.navigate(Te.WORK,{openRequirement:$e}):Ne?pt.navigate(Te.TEAM,{agentId:Ne}):pt.navigate(Te.WORK)},de=()=>{h(!1),s?.()},be=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex border-b border-border-default shrink-0",children:[n.jsxs("button",{onClick:()=>{y("approvals"),O.current="approvals"},className:`flex-1 px-3 py-2.5 text-xs font-medium transition-colors ${p==="approvals"?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:[u("team:notifications.approvals"),Me>0?` (${Me})`:""]}),n.jsxs("button",{onClick:()=>{y("notifications"),O.current="notifications"},className:`flex-1 px-3 py-2.5 text-xs font-medium transition-colors ${p==="notifications"?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:[u("team:notifications.notifications"),Ae>0?` (${Ae})`:""]}),n.jsx("button",{onClick:de,className:"px-2 py-2 text-fg-tertiary hover:text-fg-primary transition-colors shrink-0",title:u("common:close"),children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),p==="notifications"&&I>0&&n.jsx("div",{className:"flex justify-end px-3 py-1.5 border-b border-border-default/50 shrink-0",children:n.jsx("button",{onClick:Ye,className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:u("team:notifications.markAllRead")})}),n.jsxs("div",{ref:V,className:"flex-1 overflow-y-auto",onScroll:se=>{if(p!=="notifications"||!z||_)return;const fe=se.currentTarget;fe.scrollTop+fe.clientHeight>=fe.scrollHeight-80&&H()},children:[p==="approvals"&&(j.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noApprovals")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[zt.map(se=>{const fe=se.details?.command,$e=fe?se.description.replace(/\s*Command:.*$/,""):se.description;return n.jsxs("div",{className:"px-3 py-3 space-y-2.5",children:[n.jsxs("div",{className:"cursor-pointer hover:bg-surface-overlay/50 -mx-3 -mt-3 px-3 pt-3 pb-1 rounded-t-md transition-colors",onClick:()=>te(se),children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-amber-500 mt-0.5 shrink-0",children:n.jsx("path",{d:ad.approval_request})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[Qe(se)&&n.jsx("span",{className:"text-[10px] text-amber-500 font-medium shrink-0",children:Qe(se)}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:se.title}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:id(se.requestedAt,u)})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:se.agentName})]})]}),n.jsx("div",{className:"mt-2.5 text-[11px] text-fg-secondary leading-relaxed",children:n.jsx(Gr,{content:$e,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]"})}),fe&&n.jsx("pre",{className:"text-[11px] text-fg-primary bg-surface-overlay border border-border-default rounded-md px-2.5 py-2 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed mt-2",children:fe})]}),(()=>{const Ne=se.details?.subType,Ze=Ne==="task"||Ne==="requirement"||Ne==="requirement_resubmit",pe=se.options&&se.options.length>0,ze=(M[se.id]??"").trim();return pe?n.jsxs("div",{className:"space-y-1.5",children:[se.options.map((Fe,Je)=>n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,Fe.id!=="reject",ze||void 0,Fe.id),className:`w-full px-3 py-2 text-left text-[11px] font-medium rounded-md disabled:opacity-50 transition-colors flex items-center gap-2 ${Fe.id==="reject"||Fe.id==="request_changes"?"border border-border-default text-fg-secondary hover:bg-surface-overlay":"bg-brand-600 text-white hover:bg-brand-700"}`,title:Fe.description,children:[n.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-[10px] font-bold shrink-0",children:String.fromCharCode(65+Je)}),Fe.label]},Fe.id)),n.jsxs("div",{className:"flex gap-1.5 mt-1",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.freeformPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&(M[se.id]??"").trim()&&Ce(se.id,!0,(M[se.id]??"").trim(),"custom")},className:"flex-1 px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{disabled:w===se.id||!(M[se.id]??"").trim(),onClick:()=>Ce(se.id,!0,(M[se.id]??"").trim(),"custom"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 disabled:opacity-50 transition-colors",children:u("common:send")})]})]}):Ze?n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!0,void 0,"approve"),className:"px-3 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6L9 17l-5-5"})}),u("common:approve")]}),n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!1,void 0,"reject"),className:"px-3 py-1.5 text-[11px] font-medium bg-red-600/80 text-white rounded-md hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]}),u("common:reject")]}),S!==se.id&&n.jsxs("button",{disabled:w===se.id,onClick:()=>T(se.id),className:"px-3 py-1.5 text-[11px] font-medium border border-amber-500/50 text-amber-500 rounded-md hover:bg-amber-500/10 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),u("team:notifications.needsAdjustment")]})]}),S===se.id&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",autoFocus:!0,placeholder:u("team:notifications.adjustmentPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&(M[se.id]??"").trim()&&Ce(se.id,!1,(M[se.id]??"").trim(),"needs_adjustment"),Fe.key==="Escape"&&T(null)},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-amber-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===se.id||!(M[se.id]??"").trim(),onClick:()=>Ce(se.id,!1,(M[se.id]??"").trim(),"needs_adjustment"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50 transition-colors",children:u("team:notifications.confirmAdjustment")}),n.jsx("button",{onClick:()=>T(null),className:"px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:u("common:cancel")})]})]})]}):n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.commentPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&Ce(se.id,!0,ze||void 0,"approve")},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!0,ze||void 0,"approve"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors",children:u("common:approve")}),n.jsx("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!1,ze||void 0,"reject"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay disabled:opacity-50 transition-colors",children:u("common:reject")})]})]})})()]},se.id)}),mt.length>0&&n.jsxs(n.Fragment,{children:[zt.length>0&&n.jsx("div",{className:"px-3 py-1.5 text-[10px] font-medium text-fg-tertiary uppercase tracking-wider bg-surface-overlay/30",children:u("team:notifications.approvalHistory")}),mt.slice(0,50).map(se=>n.jsxs("button",{onClick:()=>te(se),className:"w-full text-left px-3 py-2.5 hover:bg-surface-overlay/50 transition-colors group",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${se.status==="approved"?"bg-green-500":se.status==="cancelled"||se.status==="expired"?"bg-gray-400":"bg-red-500"}`}),Qe(se)&&n.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium shrink-0",children:Qe(se)}),n.jsx("span",{className:"text-xs text-fg-secondary truncate flex-1 group-hover:text-fg-primary",children:se.title}),n.jsx("span",{className:`text-[10px] font-medium shrink-0 ${se.status==="approved"?"text-green-500":se.status==="cancelled"||se.status==="expired"?"text-fg-muted":"text-red-500"}`,children:u(`common:status.${se.status}`,{defaultValue:se.status})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 pl-3.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted truncate",children:ct(se)}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:"·"}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:id(se.respondedAt??se.requestedAt,u)})]}),se.responseComment&&n.jsxs("p",{className:"text-[10px] text-fg-muted mt-0.5 pl-3.5 truncate",children:["“",se.responseComment,"”"]})]},se.id))]})]})),p==="notifications"&&(Q.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noNotifications")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[Q.map(se=>{const fe=q3[se.type]??"text-fg-tertiary";return n.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Pe(se),onKeyDown:$e=>{($e.key==="Enter"||$e.key===" ")&&($e.preventDefault(),Pe(se))},className:`w-full text-left px-3 py-2.5 flex gap-2.5 transition-colors cursor-pointer ${se.read?"opacity-50 hover:opacity-70":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"shrink-0 mt-0.5",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:fe,children:n.jsx("path",{d:ad[se.type]??ad.system})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[!se.read&&n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Af[se.priority]??Af.normal}`}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:se.title})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5 ",children:n.jsx(Gr,{content:se.body,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px] [&_p]:text-fg-tertiary"})}),n.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted",children:id(se.createdAt,u)}),Ef(se,u)&&n.jsx("span",{className:`text-[10px] font-medium ${fe}`,children:Ef(se,u)})]})]})]},se.id)}),_&&n.jsx("div",{className:"py-3 text-center",children:n.jsxs("svg",{className:"animate-spin h-4 w-4 text-fg-tertiary mx-auto",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})})]}))]})]});if(r){const se=["approvals","notifications"],fe=se.indexOf(p),$e=(()=>{let Ne=0,Ze=0;return{onTouchStart:pe=>{Ne=pe.touches[0].clientX,Ze=pe.touches[0].clientY},onTouchEnd:pe=>{const ze=pe.changedTouches[0].clientX-Ne,Fe=pe.changedTouches[0].clientY-Ze;Math.abs(ze)>60&&Math.abs(ze)>Math.abs(Fe)*1.5&&(ze<0&&fe<se.length-1&&y(se[fe+1]),ze>0&&fe>0&&y(se[fe-1]))}}})();return n.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[n.jsx("div",{className:"flex border-b border-border-default shrink-0",children:se.map(Ne=>n.jsx("button",{onClick:()=>y(Ne),className:`flex-1 px-3 py-3 text-sm font-medium transition-colors ${p===Ne?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary"}`,children:Ne==="approvals"?n.jsxs(n.Fragment,{children:[u("team:notifications.approvals"),Me>0?` (${Me})`:""]}):n.jsxs(n.Fragment,{children:[u("team:notifications.notifications"),Ae>0?` (${Ae})`:""]})},Ne))}),p==="notifications"&&I>0&&n.jsx("div",{className:"flex justify-end px-3 py-1.5 border-b border-border-default/50 shrink-0",children:n.jsx("button",{onClick:Ye,className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:u("team:notifications.markAllRead")})}),n.jsx("div",{className:"flex-1 overflow-hidden relative",...$e,children:n.jsxs("div",{className:"flex h-full transition-transform duration-300 ease-out",style:{transform:`translateX(-${fe*100}%)`},children:[n.jsx("div",{className:"w-full shrink-0 h-full overflow-y-auto scrollbar-thin",children:j.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noApprovals")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[zt.map(Ne=>{const Ze=Ne.details?.command,pe=Ze?Ne.description.replace(/\s*Command:.*$/,""):Ne.description;return n.jsxs("div",{className:"px-3 py-3 space-y-2.5",children:[n.jsxs("div",{className:"cursor-pointer hover:bg-surface-overlay/50 -mx-3 -mt-3 px-3 pt-3 pb-1 rounded-t-md transition-colors",onClick:()=>te(Ne),children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-amber-500 mt-0.5 shrink-0",children:n.jsx("path",{d:ad.approval_request})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[Qe(Ne)&&n.jsx("span",{className:"text-[10px] text-amber-500 font-medium shrink-0",children:Qe(Ne)}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:Ne.title}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:id(Ne.requestedAt,u)})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:Ne.agentName})]})]}),n.jsx("div",{className:"mt-2.5 text-[11px] text-fg-secondary leading-relaxed",children:n.jsx(Gr,{content:pe,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]"})}),Ze&&n.jsx("pre",{className:"text-[11px] text-fg-primary bg-surface-overlay border border-border-default rounded-md px-2.5 py-2 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed mt-2",children:Ze})]}),(()=>{const ze=Ne.details?.subType,Fe=ze==="task"||ze==="requirement"||ze==="requirement_resubmit",Je=Ne.options&&Ne.options.length>0,gt=(M[Ne.id]??"").trim();return Je?n.jsxs("div",{className:"space-y-1.5",children:[Ne.options.map((nt,Et)=>n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,nt.id!=="reject",gt||void 0,nt.id),className:`w-full px-3 py-2 text-left text-[11px] font-medium rounded-md disabled:opacity-50 transition-colors flex items-center gap-2 ${nt.id==="reject"||nt.id==="request_changes"?"border border-border-default text-fg-secondary hover:bg-surface-overlay":"bg-brand-600 text-white hover:bg-brand-700"}`,title:nt.description,children:[n.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-[10px] font-bold shrink-0",children:String.fromCharCode(65+Et)}),nt.label]},nt.id)),n.jsxs("div",{className:"flex gap-1.5 mt-1",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.freeformPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&(M[Ne.id]??"").trim()&&Ce(Ne.id,!0,(M[Ne.id]??"").trim(),"custom")},className:"flex-1 px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{disabled:w===Ne.id||!(M[Ne.id]??"").trim(),onClick:()=>Ce(Ne.id,!0,(M[Ne.id]??"").trim(),"custom"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 disabled:opacity-50 transition-colors",children:u("common:send")})]})]}):Fe?n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!0,void 0,"approve"),className:"px-3 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6L9 17l-5-5"})}),u("common:approve")]}),n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!1,void 0,"reject"),className:"px-3 py-1.5 text-[11px] font-medium bg-red-600/80 text-white rounded-md hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]}),u("common:reject")]}),S!==Ne.id&&n.jsxs("button",{disabled:w===Ne.id,onClick:()=>T(Ne.id),className:"px-3 py-1.5 text-[11px] font-medium border border-amber-500/50 text-amber-500 rounded-md hover:bg-amber-500/10 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),u("team:notifications.needsAdjustment")]})]}),S===Ne.id&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",autoFocus:!0,placeholder:u("team:notifications.adjustmentPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&(M[Ne.id]??"").trim()&&Ce(Ne.id,!1,(M[Ne.id]??"").trim(),"needs_adjustment"),nt.key==="Escape"&&T(null)},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-amber-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===Ne.id||!(M[Ne.id]??"").trim(),onClick:()=>Ce(Ne.id,!1,(M[Ne.id]??"").trim(),"needs_adjustment"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50 transition-colors",children:u("team:notifications.confirmAdjustment")}),n.jsx("button",{onClick:()=>T(null),className:"px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:u("common:cancel")})]})]})]}):n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.commentPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&Ce(Ne.id,!0,gt||void 0,"approve")},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!0,gt||void 0,"approve"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors",children:u("common:approve")}),n.jsx("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!1,gt||void 0,"reject"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay disabled:opacity-50 transition-colors",children:u("common:reject")})]})]})})()]},Ne.id)}),mt.length>0&&n.jsxs(n.Fragment,{children:[zt.length>0&&n.jsx("div",{className:"px-3 py-1.5 text-[10px] font-medium text-fg-tertiary uppercase tracking-wider bg-surface-overlay/30",children:u("team:notifications.approvalHistory")}),mt.slice(0,50).map(Ne=>n.jsxs("button",{onClick:()=>te(Ne),className:"w-full text-left px-3 py-2.5 hover:bg-surface-overlay/50 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Ne.status==="approved"?"bg-green-500":Ne.status==="cancelled"||Ne.status==="expired"?"bg-gray-400":"bg-red-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary truncate flex-1",children:Ne.title}),n.jsx("span",{className:`text-[10px] font-medium shrink-0 ${Ne.status==="approved"?"text-green-500":Ne.status==="cancelled"||Ne.status==="expired"?"text-fg-muted":"text-red-500"}`,children:u(`common:status.${Ne.status}`,{defaultValue:Ne.status})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 pl-3.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted truncate",children:ct(Ne)}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:"·"}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:id(Ne.respondedAt??Ne.requestedAt,u)})]})]},Ne.id))]})]})}),n.jsx("div",{className:"w-full shrink-0 h-full overflow-y-auto scrollbar-thin",children:Q.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noNotifications")}):n.jsx("div",{className:"divide-y divide-border-default/50",children:Q.slice(0,50).map(Ne=>{const Ze=q3[Ne.type]??"text-fg-tertiary";return n.jsxs("button",{onClick:()=>Pe(Ne),className:`w-full text-left px-3 py-2.5 flex gap-2.5 transition-colors ${Ne.read?"opacity-50 hover:opacity-70":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"shrink-0 mt-0.5",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Ze,children:n.jsx("path",{d:ad[Ne.type]??ad.system})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[!Ne.read&&n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Af[Ne.priority]??Af.normal}`}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:Ne.title})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5 ",children:n.jsx(Gr,{content:Ne.body,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px] [&_p]:text-fg-tertiary"})}),n.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted",children:id(Ne.createdAt,u)}),Ef(Ne,u)&&n.jsx("span",{className:`text-[10px] font-medium ${Ze}`,children:Ef(Ne,u)})]})]})]},Ne.id)})})})]})})]})}if(a){const se=d||"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9 M13.73 21a2 2 0 0 1-3.46 0";return n.jsxs(n.Fragment,{children:[n.jsxs("button",{ref:B,onClick:()=>{h(!m),m||J()},title:e?l||u("team:notifications.bellTitle"):void 0,className:`w-full flex items-center ${e?"flex-col justify-center px-1 py-1.5 gap-0.5":"gap-3 px-3 py-[7px]"} rounded-xl text-[13px] mb-0.5 transition-all relative ${m||i?"bg-brand-600 text-white shadow-sm shadow-brand-900/30 font-medium":"text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary"}`,children:[n.jsx("svg",{width:e?16:18,height:e?16:18,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:se})}),e?n.jsx("span",{className:"text-[9px] leading-tight truncate w-full text-center",children:l}):n.jsx("span",{className:"truncate",children:l}),He>0&&n.jsx("span",{className:`absolute ${e?"top-0.5 right-1":"top-1 left-[22px]"} min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center leading-none`,children:He>99?u("common:badgeOverLimit"):He})]}),m&&lc.createPortal(n.jsx("div",{ref:R,className:"fixed bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-[9999] flex flex-col overflow-hidden",style:{top:U.top,left:U.left,width:U.width,maxHeight:U.maxHeight},children:be}),document.body)]})}return n.jsxs(n.Fragment,{children:[n.jsxs("button",{ref:B,onClick:()=>{h(!m),m||J()},className:`relative flex items-center justify-center rounded-md transition-colors ${e?"w-8 h-8":"w-7 h-7"} ${m?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-overlay"}`,title:u("team:notifications.bellTitle"),children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]}),He>0&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center leading-none",children:He>99?u("common:badgeOverLimit"):He})]}),m&&lc.createPortal(n.jsx("div",{ref:R,className:"fixed bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-[9999] flex flex-col overflow-hidden",style:{top:U.top,left:U.left,width:U.width,maxHeight:U.maxHeight},children:be}),document.body)]})}function Fre({authUser:e}){const{t}=ft("nav"),r=Ds();return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-4 h-14",children:[r&&n.jsx(gc,{}),n.jsx("h2",{className:"text-base font-bold",children:t("notifications")})]}),n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(nC,{collapsed:!1,userId:e?.id,embeddedMode:!0})})]})}function qre(){const{t:e}=ft(["common","home","work"]),[t,r]=x.useState(""),[s,a]=x.useState("all"),[i,l]=x.useState({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),[d,u]=x.useState(!1),[m,h]=x.useState(!1),p=x.useRef(null),y=x.useRef(void 0);x.useEffect(()=>{setTimeout(()=>p.current?.focus(),100)},[]);const g=x.useCallback(async w=>{if(!w.trim()){l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),h(!1);return}u(!0),h(!0);const N=w.toLowerCase();try{const[S,T,M,D,I]=await Promise.allSettled([le.agents.list(),le.tasks.list({search:w,pageSize:20}),le.requirements.list(),le.projects.list(),le.deliverables.search({q:w,limit:20})]),$=S.status==="fulfilled"?S.value.agents.filter(F=>F.name?.toLowerCase().includes(N)||F.role?.toLowerCase().includes(N)):[],B=T.status==="fulfilled"?T.value.tasks:[],R=M.status==="fulfilled"?M.value.requirements.filter(F=>F.title?.toLowerCase().includes(N)||F.description?.toLowerCase().includes(N)):[],U=D.status==="fulfilled"?D.value.projects.filter(F=>F.name?.toLowerCase().includes(N)||F.description?.toLowerCase().includes(N)):[],W=I.status==="fulfilled"?I.value.results:[];l({agents:$,tasks:B,requirements:R,projects:U,deliverables:W})}catch{l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]})}finally{u(!1)}},[]),v=w=>{r(w),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>g(w),400)},j=[{id:"all",label:e("common:all",{defaultValue:"全部"})},{id:"agents",label:e("common:agents",{defaultValue:"智能体"})},{id:"tasks",label:e("common:tasks",{defaultValue:"任务"})},{id:"requirements",label:e("common:requirements",{defaultValue:"需求"})},{id:"projects",label:e("common:projects",{defaultValue:"项目"})},{id:"deliverables",label:e("common:deliverables",{defaultValue:"交付物"})}],C=i.agents.length>0||i.tasks.length>0||i.requirements.length>0||i.projects.length>0||i.deliverables.length>0;return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"shrink-0 px-4 pt-4 pb-2 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>pt.navigate(Te.HOME),className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors shrink-0",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsxs("div",{className:"flex-1 relative",children:[n.jsxs("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg-tertiary",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("input",{ref:p,value:t,onChange:w=>v(w.target.value),placeholder:e("common:search"),className:"w-full bg-surface-elevated border border-border-default rounded-xl pl-9 pr-3 py-2.5 text-sm text-fg-primary placeholder:text-fg-tertiary focus:border-brand-500 focus:outline-none transition-colors"}),t&&n.jsx("button",{onClick:()=>{r(""),l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),h(!1),p.current?.focus()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-fg-tertiary hover:text-fg-secondary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),n.jsx("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:j.map(w=>n.jsx("button",{onClick:()=>a(w.id),className:`px-3 py-1.5 text-xs rounded-lg whitespace-nowrap transition-colors ${s===w.id?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:text-fg-primary"}`,children:w.label},w.id))})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:[d&&n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:e("common:loading")})}),!d&&m&&!C&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-3",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:e("common:noResults",{defaultValue:"没有找到相关结果"})})]}),!d&&C&&n.jsxs("div",{className:"space-y-4",children:[(s==="all"||s==="agents")&&i.agents.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:agents",{defaultValue:"智能体"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.agents.slice(0,8):i.agents).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.TEAM,{agentId:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx(Sr,{name:w.name||"Agent",avatarUrl:w.avatarUrl,size:32}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:w.name}),n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:w.role||w.status})]}),n.jsx(Ure,{status:w.status})]},w.id))}),s==="all"&&i.agents.length>8&&n.jsxs("button",{onClick:()=>a("agents"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.agents.length,")"]})]}),(s==="all"||s==="tasks")&&i.tasks.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:tasks",{defaultValue:"任务"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.tasks.slice(0,8):i.tasks).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{openTask:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx(Vre,{status:w.status}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.status," · ",w.priority||""]})]})]},w.id))}),s==="all"&&i.tasks.length>8&&n.jsxs("button",{onClick:()=>a("tasks"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.tasks.length,")"]})]}),(s==="all"||s==="requirements")&&i.requirements.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:requirements",{defaultValue:"需求"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.requirements.slice(0,8):i.requirements).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{openRequirement:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${w.status==="approved"?"text-green-500 bg-green-500/15":w.status==="pending"?"text-amber-500 bg-amber-500/15":w.status==="rejected"?"text-red-500 bg-red-500/15":"text-fg-tertiary bg-surface-elevated"}`,children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),n.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.status," · ",w.priority||""]})]})]},w.id))}),s==="all"&&i.requirements.length>8&&n.jsxs("button",{onClick:()=>a("requirements"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.requirements.length,")"]})]}),(s==="all"||s==="projects")&&i.projects.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:projects",{defaultValue:"项目"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.projects.slice(0,8):i.projects).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{projectId:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-teal-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-teal-500",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.name}),w.description&&n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:w.description})]})]},w.id))}),s==="all"&&i.projects.length>8&&n.jsxs("button",{onClick:()=>a("projects"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.projects.length,")"]})]}),(s==="all"||s==="deliverables")&&i.deliverables.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:deliverables",{defaultValue:"交付物"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.deliverables.slice(0,8):i.deliverables).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.DELIVERABLES,{openDeliverable:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-purple-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-purple-500",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.type," · ",w.status]})]})]},w.id))}),s==="all"&&i.deliverables.length>8&&n.jsxs("button",{onClick:()=>a("deliverables"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.deliverables.length,")"]})]})]}),!d&&!m&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-3",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:e("common:search")})]})]})]})}function Ure({status:e}){const t=e==="active"||e==="idle"?"bg-green-500":e==="working"||e==="busy"?"bg-blue-500":e==="paused"?"bg-amber-500":"bg-gray-400";return n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`})}function Vre({status:e}){const t=e==="completed"?"text-green-500 bg-green-500/15":e==="in_progress"?"text-blue-500 bg-blue-500/15":e==="pending"?"text-amber-500 bg-amber-500/15":"text-fg-tertiary bg-surface-elevated";return n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${t}`,children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 11l3 3L22 4"}),n.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})})}function Kre({d:e,size:t=18}){return n.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:e})})}function Wre({currentPage:e,onNavigate:t,authUser:r,collapsed:s,onToggleCollapse:a}){const{t:i}=ft(["nav","common"]);return n.jsxs("aside",{className:"h-dvh bg-surface-secondary flex flex-col shrink-0 overflow-hidden rounded-r-2xl",children:[n.jsx("div",{className:`flex items-center ${s?"px-2 py-3.5 justify-center":"px-4 h-14 justify-between"}`,children:n.jsxs("button",{onClick:a,title:i(s?"sidebar.expandSidebar":"sidebar.collapseSidebar"),className:"flex items-center gap-2.5 min-w-0 group",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-8 h-8 rounded-lg shadow-md shadow-black/30 shrink-0 group-hover:ring-2 group-hover:ring-brand-500/40 transition-all"}),!s&&n.jsx("span",{className:"text-[15px] font-bold tracking-tight text-fg-primary whitespace-nowrap",children:"Markus"})]})}),n.jsx("nav",{className:`${s?"p-1":"px-3 py-2"} flex-1 overflow-y-auto scrollbar-thin`,children:j_.map((l,d)=>{const u=i(`sections.${l.key}`);return n.jsx("div",{children:n.jsxs("div",{className:d>0?"mt-3":"",children:[!s&&u&&n.jsx("div",{className:"px-3 py-1.5 mb-1 text-[10px] font-semibold text-fg-muted uppercase tracking-[0.1em]",children:u}),s&&d>0&&n.jsx("div",{className:"my-3"}),N_.filter(m=>m.section===l.key).map(m=>{if(m.id===Te.NOTIFICATIONS)return n.jsx(nC,{sidebarMode:!0,collapsed:s,userId:r?.id,label:i(m.id),iconPath:fb[m.id],isActive:e===m.id},m.id);const h=e===m.id;return n.jsxs("button",{onClick:()=>t(m.id),title:s?i(m.id):void 0,className:`w-full flex items-center ${s?"flex-col justify-center px-1 py-1.5 gap-0.5":"gap-3 px-3 py-[7px]"} rounded-xl text-[13px] mb-0.5 transition-all ${h?"bg-brand-600 text-white shadow-sm shadow-brand-900/30 font-medium":"text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary"}`,children:[n.jsx(Kre,{d:fb[m.id]??"",size:s?16:18}),s?n.jsx("span",{className:"text-[9px] leading-tight truncate w-full text-center",children:i(m.id)}):n.jsx("span",{className:"truncate",children:i(m.id)})]},m.id)})]})},l.key)})}),!s&&n.jsxs("div",{className:"px-4 pb-2 text-[10px] text-fg-muted",children:["v","0.7.10"]})]})}function Gre({currentPage:e,onNavigate:t,userId:r}){const{t:s}=ft("nav"),[a,i]=x.useState(0),{counts:l}=WS({enabled:!0}),d=x.useMemo(()=>{let m=0;for(const h of Object.values(l))m+=h;return m},[l]),u=x.useCallback(async()=>{try{const m=await le.notifications.list(r,!1);i(m.unreadCount??m.notifications.filter(h=>!h.read).length)}catch{}},[r]);return x.useEffect(()=>{u();const m=setInterval(u,15e3),h=()=>u();return window.addEventListener("markus:notifications-changed",h),()=>{clearInterval(m),window.removeEventListener("markus:notifications-changed",h)}},[u]),n.jsx("nav",{className:"fixed bottom-0 left-0 right-0 z-50 bg-surface-secondary flex items-stretch h-14 safe-area-bottom",children:S_.map(m=>{const h=m.group.includes(e),p=m.id===Te.NOTIFICATIONS,y=m.id===Te.TEAM;return n.jsxs("button",{onClick:()=>t(m.id),className:`flex-1 flex flex-col items-center justify-center gap-0.5 transition-colors ${h?"text-brand-500":"text-fg-tertiary active:text-fg-secondary"}`,children:[n.jsxs("div",{className:"relative",children:[n.jsx("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:h?2:1.75,strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:fb[m.id]})}),p&&a>0&&n.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-[16px] h-4 px-1 flex items-center justify-center bg-red-500 text-white text-[9px] font-bold rounded-full leading-none",children:a>99?"99+":a}),y&&d>0&&n.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-[16px] h-4 px-1 flex items-center justify-center bg-red-500 text-white text-[9px] font-bold rounded-full leading-none",children:d>99?"99+":d})]}),n.jsx("span",{className:`text-[10px] leading-tight ${h?"font-semibold":""}`,children:s(m.id)})]},m.id)})})}const rC=["builder","agents","teams","skills"];function Yre(){const e=localStorage.getItem("markus_nav_storeTab");return e&&(localStorage.removeItem("markus_nav_storeTab"),rC.includes(e))?e:"builder"}function Xre({authUser:e}){const{t}=ft(["nav","common"]),r=x.useMemo(()=>[{id:"builder",label:t("nav:builder")},{id:"agents",label:t("nav:tabs.agents")},{id:"teams",label:t("nav:tabs.teams")},{id:"skills",label:t("nav:tabs.skills")}],[t]),[s,a]=x.useState(Yre),i=Sl(r,s,a);return x.useEffect(()=>{const l=d=>{const u=d.detail;u.params?.storeTab&&rC.includes(u.params.storeTab)&&a(u.params.storeTab)};return window.addEventListener("markus:navigate",l),()=>window.removeEventListener("markus:navigate",l)},[]),n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",onTouchStart:i.onTouchStart,onTouchEnd:i.onTouchEnd,children:[n.jsxs("div",{className:"flex items-center shrink-0 overflow-x-auto scrollbar-hide",children:[n.jsx(gc,{className:"ml-2"}),r.map(l=>n.jsx("button",{onClick:()=>a(l.id),className:`flex-1 min-w-0 px-3 py-2.5 text-xs font-medium text-center whitespace-nowrap transition-colors border-b-2 ${s===l.id?"border-brand-500 text-brand-500":"border-transparent text-fg-tertiary"}`,children:l.label},l.id))]}),n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[s==="builder"&&n.jsx(QS,{}),s==="agents"&&n.jsx(e7,{authUser:e}),s==="teams"&&n.jsx(r7,{}),s==="skills"&&n.jsx(s7,{})]})]})}const ob="profile",U3="llm",V3="search";function Qre({onComplete:e,theme:t,onThemeChange:r,skipProfile:s}){const{t:a}=ft(["onboarding","common"]),[i,l]=x.useState(0),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(""),[g,v]=x.useState(""),[j,C]=x.useState(!1),[w,N]=x.useState(""),[S,T]=x.useState(!1),[M,D]=x.useState(null);x.useEffect(()=>{le.auth.me().then(({user:qe})=>{qe.name&&u(qe.name),qe.email&&h(qe.email),qe.avatarUrl&&D(qe.avatarUrl)}).catch(()=>{})},[]);const[I,$]=x.useState(null),[B,R]=x.useState(!1),[U,W]=x.useState({}),[F,L]=x.useState(!1),[z,E]=x.useState(!1),[_,G]=x.useState([]),[V,O]=x.useState(null),[q,J]=x.useState(!0),[H,Z]=x.useState(""),Y=x.useRef(!1),[ee,ae]=x.useState({}),[Q,me]=x.useState({}),[Ae,Me]=x.useState("anthropic"),[He,je]=x.useState(""),[xe,Pe]=x.useState(!1),[Ce,Ye]=x.useState([]),[Qe,ct]=x.useState(""),[st,zt]=x.useState(""),[mt,te]=x.useState(null),[de,be]=x.useState({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),[se,fe]=x.useState(!1),[$e,Ne]=x.useState(!1),[Ze,pe]=x.useState(null),ze=x.useRef(!1),Fe=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`});x.useEffect(()=>{fetch("/api/settings/llm").then(qe=>qe.ok?qe.json():null).then(qe=>{if(qe?.providers){const St=Object.entries(qe.providers).filter(([,_e])=>_e.configured).map(([_e,Tt])=>({name:_e,displayName:Tt.displayName??_e,model:Tt.model??"",apiKeyPreview:Tt.apiKeyPreview}));St.length>0&&(E(!0),G(St))}qe?.defaultProvider&&Z(qe.defaultProvider),typeof qe?.autoFallback=="boolean"&&J(qe.autoFallback)}).catch(()=>{})},[]);const Je=s?2:3;x.useEffect(()=>{i===Je&&!Y.current&&!z&&(Y.current=!0,nt())},[i,z,Je]);const gt=s?3:4;x.useEffect(()=>{i===gt&&!ze.current&&(ze.current=!0,Rt())},[i,gt]);const nt=async()=>{R(!0);try{const qe=await fetch("/api/settings/env-models",{headers:Fe()});if(qe.ok){const St=await qe.json();if($(St),St.detected.length>0){const _e={},Tt={};for(const Ot of St.detected)_e[Ot.provider]=!0,Tt[Ot.provider]=Ot.model;W(_e),me(Tt);for(const Ot of St.detected)le.modelCatalog.getByProvider(Ot.provider).then(Gt=>{ae(Tn=>({...Tn,[Ot.provider]:Gt.models}))}).catch(()=>{})}}}catch{}finally{R(!1)}},Et=async()=>{if(He.trim()){Pe(!0),zt(""),Ye([]);try{const qe=await le.modelCatalog.validateKey(Ae,He.trim());qe.valid?(Ye(qe.models),qe.models.length>0&&ct(qe.models[0].id)):(zt(qe.error||"Invalid API key"),qe.models.length>0&&(Ye(qe.models),ct(qe.models[0].id)))}catch(qe){zt(qe instanceof Error?qe.message:"Validation failed")}finally{Pe(!1)}}},dt=async()=>{if(Qe){L(!0),O(null);try{const qe=await fetch("/api/settings/llm/providers",{method:"POST",headers:Fe(),body:JSON.stringify({name:Ae,apiKey:He.trim(),model:Qe})});if(qe.ok)E(!0),Z(Ae),G([{name:Ae,displayName:Ae,model:Qe}]),O({type:"ok",text:`Provider ${Ae} configured successfully`});else{const St=await qe.json();O({type:"err",text:St.error||"Failed to add provider"})}}catch{O({type:"err",text:"Network error"})}finally{L(!1)}}},Ve=async()=>{if(!I)return;const qe=I.detected.filter(St=>U[St.provider]);if(qe.length!==0){L(!0),O(null);try{const St=await fetch("/api/settings/env-models",{method:"POST",headers:Fe(),body:JSON.stringify({providers:qe.map(_e=>({provider:_e.provider,model:Q[_e.provider]||_e.model,baseUrl:_e.baseUrl,enabled:!0}))})});if(St.ok){const _e=await St.json();if(_e.settings?.providers){const Ot=Object.entries(_e.settings.providers).filter(([,Gt])=>Gt.configured).map(([Gt,Tn])=>({name:Gt,displayName:Tn.displayName??Gt,model:Tn.model??"",apiKeyPreview:Tn.apiKeyPreview}));G(Ot)}else G(qe.map(Ot=>({name:Ot.provider,displayName:Ot.displayName,model:Ot.model,apiKeyPreview:Ot.apiKeyPreview})));const Tt=_e.settings?.defaultProvider||_e.applied[0]||qe[0]?.provider||"";Z(Tt),Tt&&fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({defaultProvider:Tt})}).catch(()=>{}),O({type:"ok",text:_e.message}),E(!0)}else O({type:"err",text:a("llm.failedToApply")})}catch{O({type:"err",text:a("common:networkError")})}finally{L(!1)}}},Rt=async()=>{try{const qe=await fetch("/api/settings/search",{headers:Fe()});if(qe.ok){const St=await qe.json();te(St),St&&(St.serper.configured||St.tavily.configured||St.bing.configured||St.google.configured||St.serpapi.configured||St.brave.configured||St.exa.configured||St.bocha.configured)&&Ne(!0)}}catch{}},un=async()=>{if(de.serperApiKey||de.tavilyApiKey||de.bingApiKey||de.googleSearchApiKey||de.googleSearchCx||de.serpApiKey||de.braveApiKey||de.exaApiKey||de.bochaApiKey){fe(!0),pe(null);try{const St={};de.serperApiKey&&(St.serperApiKey=de.serperApiKey),de.tavilyApiKey&&(St.tavilyApiKey=de.tavilyApiKey),de.bingApiKey&&(St.bingApiKey=de.bingApiKey),de.googleSearchApiKey&&(St.googleSearchApiKey=de.googleSearchApiKey),de.googleSearchCx&&(St.googleSearchCx=de.googleSearchCx),de.serpApiKey&&(St.serpApiKey=de.serpApiKey),de.braveApiKey&&(St.braveApiKey=de.braveApiKey),de.exaApiKey&&(St.exaApiKey=de.exaApiKey),de.bochaApiKey&&(St.bochaApiKey=de.bochaApiKey);const _e=await fetch("/api/settings/search",{method:"POST",headers:Fe(),body:JSON.stringify(St)});if(_e.ok){const Tt=await _e.json();te(Tt),Ne(!0),be({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),pe({type:"ok",text:a("search.saved")})}else pe({type:"err",text:a("search.failedToSave")})}catch{pe({type:"err",text:a("common:networkError")})}finally{fe(!1)}}},yn=async()=>{if(N(""),!d.trim()){N(a("profile.errors.nameRequired"));return}if(!m.trim()){N(a("profile.errors.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){N(a("profile.errors.emailInvalid"));return}if(p&&p.length<6){N(a("profile.errors.passwordTooShort"));return}if(p&&p!==g){N(a("profile.errors.passwordMismatch"));return}C(!0);try{await le.auth.updateProfile(d.trim(),m.trim()),p&&await le.auth.changePassword("",p),T(!0)}catch{N(a("profile.errors.saveFailed"))}finally{C(!1)}},sn=[{value:"system",label:a("theme.system"),icon:"💻",desc:a("theme.systemDesc")},{value:"light",label:a("theme.light"),icon:"☀️",desc:a("theme.lightDesc")},{value:"dark",label:a("theme.dark"),icon:"🌊",desc:a("theme.darkDesc")},{value:"cyberpunk",label:a("theme.cyberpunk"),icon:"🔮",desc:a("theme.cyberpunkDesc")},{value:"mono",label:a("theme.mono"),icon:"⬛",desc:a("theme.monoDesc")}],In=[{id:"welcome",title:a("welcome.title"),subtitle:a("welcome.subtitle"),content:n.jsxs("div",{className:"space-y-4 text-fg-secondary text-sm leading-relaxed",children:[n.jsx("p",{className:"text-fg-secondary",children:n.jsx(n0,{i18nKey:"welcome.description",ns:"onboarding",components:{strong:n.jsx("strong",{className:"text-fg-primary"})}})}),n.jsx("div",{className:"grid grid-cols-2 gap-3 mt-6",children:[[a("welcome.features.operation"),a("welcome.features.operationDesc")],[a("welcome.features.collaboration"),a("welcome.features.collaborationDesc")],[a("welcome.features.memory"),a("welcome.features.memoryDesc")],[a("welcome.features.anyLlm"),a("welcome.features.anyLlmDesc")]].map(([qe,St])=>n.jsxs("div",{className:"bg-surface-elevated/50 rounded-lg p-3",children:[n.jsx("div",{className:"font-medium text-fg-primary text-xs",children:qe}),n.jsx("div",{className:"text-fg-secondary text-xs mt-1",children:St})]},qe))})]})},{id:ob,title:a("profile.title"),subtitle:a("profile.subtitle"),content:S?n.jsxs("div",{className:"flex items-center gap-3 bg-green-500/10 border border-green-500/30 rounded-xl p-4",children:[n.jsx("span",{className:"text-green-600 text-lg",children:"✓"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-green-600",children:a("profile.saved")}),n.jsxs("div",{className:"text-xs text-fg-secondary mt-0.5",children:[d," · ",m]})]})]}):n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"flex justify-center",children:n.jsx(g6,{currentUrl:M,name:d,size:64,targetType:"user"})}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("label",{className:"text-xs text-fg-tertiary font-medium",children:[a("profile.nameLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{type:"text",value:d,onChange:qe=>u(qe.target.value),placeholder:a("profile.namePlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",autoFocus:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("label",{className:"text-xs text-fg-tertiary font-medium",children:[a("profile.emailLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{type:"email",value:m,onChange:qe=>h(qe.target.value),placeholder:a("profile.emailPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:a("profile.newPasswordLabel")}),n.jsx("input",{type:"password",value:p,onChange:qe=>y(qe.target.value),placeholder:a("profile.newPasswordPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),p&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:a("profile.confirmPasswordLabel")}),n.jsx("input",{type:"password",value:g,onChange:qe=>v(qe.target.value),placeholder:a("profile.confirmPasswordPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),w&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:w}),n.jsx("button",{onClick:()=>{yn()},disabled:j||!d.trim()||!m.trim(),className:"w-full px-4 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a(j?"common:saving":"profile.saveProfile")})]})},{id:"theme",title:a("theme.title"),subtitle:a("theme.subtitle"),content:n.jsx("div",{className:"grid grid-cols-3 gap-3",children:sn.map(qe=>n.jsxs("button",{onClick:()=>r(qe.value),className:`flex flex-col items-center gap-2 rounded-xl border-2 p-5 transition-all ${t===qe.value?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-fg-tertiary bg-surface-elevated/30"}`,children:[n.jsx("span",{className:"text-2xl",children:qe.icon}),n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:qe.label}),n.jsx("span",{className:"text-[11px] text-fg-tertiary leading-tight text-center",children:qe.desc})]},qe.value))})},{id:U3,title:a("llm.title"),subtitle:a("llm.subtitle"),content:z?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-sm font-medium mb-1",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("llm.configured")})]}),_.length>1&&n.jsx("div",{className:"text-xs text-fg-secondary mb-1",children:a("llm.selectDefault")}),_.map(qe=>{const St=H===qe.name;return n.jsxs("button",{onClick:async()=>{const _e=H;Z(qe.name);try{await fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({defaultProvider:qe.name})})}catch{Z(_e)}},className:`w-full flex items-center justify-between rounded-lg px-4 py-2.5 text-left transition-colors ${St?"bg-brand-500/15 border-2 border-brand-500":"bg-green-500/10 border border-green-500/30 hover:border-brand-500/50"}`,children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-3.5 h-3.5 rounded-full border-2 flex items-center justify-center shrink-0 ${St?"border-brand-500":"border-fg-tertiary"}`,children:St&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.displayName}),qe.model&&n.jsx("span",{className:"text-xs text-fg-tertiary",children:qe.model}),St&&n.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:a("llm.default")})]}),qe.apiKeyPreview&&n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:qe.apiKeyPreview})]},qe.name)}),n.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:a("llm.configuredHint")}),n.jsxs("div",{className:"flex items-center justify-between bg-surface-elevated/40 rounded-lg px-4 py-3 mt-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-primary",children:a("llm.autoFallback")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:a("llm.autoFallbackDesc")})]}),n.jsx("button",{onClick:async()=>{const qe=!q;J(qe);try{await fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({autoFallback:qe})})}catch{J(!qe)}},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 ${q?"bg-green-500":"bg-gray-600"}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${q?"translate-x-4":"translate-x-1"}`})})]})]}):n.jsxs("div",{className:"space-y-4",children:[B&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary animate-pulse",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),a("llm.detectingKeys")]}),I&&I.detected.length>0&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-xs font-medium",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("llm.fromEnv")})]}),I.detected.map(qe=>n.jsxs("div",{className:"border border-border-default rounded-lg overflow-hidden",children:[n.jsxs("label",{className:"flex items-center gap-3 px-3 py-2.5 bg-surface-elevated/40 cursor-pointer hover:bg-surface-elevated/60 transition-colors",children:[n.jsx("input",{type:"checkbox",checked:U[qe.provider]??!1,onChange:St=>W({...U,[qe.provider]:St.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.displayName})}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:qe.apiKeyPreview})]}),U[qe.provider]&&n.jsx("div",{className:"px-3 py-2 border-t border-border-default",children:n.jsx(ch,{provider:qe.provider,models:ee[qe.provider]??[],selectedModel:Q[qe.provider]||qe.model,onSelect:St=>me(_e=>({..._e,[qe.provider]:St})),loading:!ee[qe.provider],compact:!0,maxVisible:4})})]},qe.provider)),I.detected.filter(qe=>U[qe.provider]).length>1&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs text-fg-secondary",children:"Default:"}),n.jsx("select",{value:H||I.detected[0]?.provider||"",onChange:qe=>Z(qe.target.value),className:"px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary",children:I.detected.filter(qe=>U[qe.provider]).map(qe=>n.jsx("option",{value:qe.provider,children:qe.displayName},qe.provider))})]}),n.jsx("button",{onClick:()=>{Ve()},disabled:F||Object.values(U).filter(Boolean).length===0,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:F?a("common:applying"):a("llm.applyProviders",{count:Object.values(U).filter(Boolean).length})})]}),I&&I.detected.length===0&&!B&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:n.jsx(n0,{i18nKey:"llm.noKeysFound",ns:"onboarding",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"text-xs text-fg-secondary",children:"Provider"}),n.jsx("select",{value:Ae,onChange:qe=>{Me(qe.target.value),Ye([]),zt(""),ct("")},className:"w-full px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary",children:Bu.map(qe=>n.jsx("option",{value:qe.id,children:qe.label},qe.id))})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"text-xs text-fg-secondary",children:"API Key"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"password",value:He,onChange:qe=>je(qe.target.value),onBlur:()=>{He.trim().length>=8&&Et()},onKeyDown:qe=>{qe.key==="Enter"&&He.trim().length>=8&&Et()},placeholder:"sk-...",className:"flex-1 px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary placeholder:text-fg-tertiary"}),n.jsx("button",{onClick:()=>{Et()},disabled:xe||!He.trim(),className:"px-3 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-xs rounded-lg transition-colors whitespace-nowrap",children:xe?"Validating...":"Validate"})]})]}),st&&n.jsx("div",{className:"text-xs px-3 py-2 rounded-lg bg-red-500/10 text-red-500 border border-red-500/30",children:st}),Ce.length>0&&n.jsxs("div",{className:"border border-border-default rounded-lg p-3",children:[n.jsx("div",{className:"text-xs text-fg-secondary mb-2",children:"Select Model"}),n.jsx(ch,{provider:Ae,models:Ce,selectedModel:Qe,onSelect:ct,compact:!0,maxVisible:5}),n.jsx("button",{onClick:()=>{dt()},disabled:F||!Qe,className:"w-full mt-3 px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:F?a("common:applying"):"Activate Provider"})]})]}),V&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${V.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:V.text})]})},{id:V3,title:a("search.title"),subtitle:a("search.subtitle"),content:$e?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-sm font-medium mb-1",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("search.saved")})]}),mt&&[{id:"serper",label:a("search.serper")},{id:"tavily",label:a("search.tavily")},{id:"bing",label:a("search.bing")},{id:"google",label:a("search.google")},{id:"serpapi",label:a("search.serpapi")},{id:"brave",label:a("search.brave")},{id:"exa",label:a("search.exa")},{id:"bocha",label:a("search.bocha")}].filter(qe=>mt[qe.id]?.configured).map(qe=>n.jsxs("div",{className:"flex items-center justify-between bg-green-500/10 border border-green-500/30 rounded-lg px-4 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.label})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:mt[qe.id].preview})]},qe.id)),n.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:a("search.savedHint")})]}):n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:a("search.description")}),mt&&(mt.serper.configured||mt.tavily.configured||mt.bing.configured||mt.google.configured||mt.serpapi.configured||mt.brave.configured||mt.exa.configured||mt.bocha.configured)&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-fg-secondary uppercase tracking-wider",children:a("search.detected")}),[{id:"serper",label:a("search.serper")},{id:"tavily",label:a("search.tavily")},{id:"bing",label:a("search.bing")},{id:"google",label:a("search.google")},{id:"serpapi",label:a("search.serpapi")},{id:"brave",label:a("search.brave")},{id:"exa",label:a("search.exa")},{id:"bocha",label:a("search.bocha")}].filter(qe=>mt[qe.id]?.configured).map(qe=>n.jsxs("div",{className:"flex items-center justify-between bg-green-500/10 border border-green-500/30 rounded-lg px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-sm text-fg-primary",children:qe.label})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:mt[qe.id].preview})]},qe.id))]}),n.jsx("div",{className:"space-y-3",children:[{label:a("search.serper"),field:"serperApiKey"},{label:a("search.tavily"),field:"tavilyApiKey"},{label:a("search.bing"),field:"bingApiKey"},{label:a("search.google"),field:"googleSearchApiKey"},{label:a("search.serpapi"),field:"serpApiKey"},{label:a("search.brave"),field:"braveApiKey"},{label:a("search.exa"),field:"exaApiKey"},{label:a("search.bocha"),field:"bochaApiKey"}].map(qe=>n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:qe.label}),n.jsx("input",{type:"password",value:de[qe.field],onChange:St=>be({...de,[qe.field]:St.target.value}),placeholder:a("search.apiKeyPlaceholder"),className:"w-full px-4 py-2 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]},qe.field))}),n.jsx("button",{onClick:()=>{un()},disabled:se||!de.serperApiKey&&!de.tavilyApiKey&&!de.bingApiKey&&!de.googleSearchApiKey&&!de.serpApiKey&&!de.braveApiKey&&!de.exaApiKey&&!de.bochaApiKey,className:"w-full px-4 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a(se?"search.saving":"search.save")}),Ze&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${Ze.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:Ze.text})]})},{id:"done",title:a("done.title"),subtitle:a("done.subtitle"),content:n.jsx("div",{className:"space-y-2 text-fg-secondary text-sm",children:[[a("done.chat"),a("done.chatDesc")],[a("done.projects"),a("done.projectsDesc")],[a("done.builder"),a("done.builderDesc")],[a("done.settings"),a("done.settingsDesc")]].map(([qe,St])=>n.jsxs("div",{className:"flex gap-3 bg-surface-elevated/50 rounded-lg p-3",children:[n.jsx("div",{className:"text-brand-500 mt-0.5 shrink-0",children:"→"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-fg-primary text-xs",children:qe}),n.jsx("div",{className:"text-fg-secondary text-xs",children:St})]})]},qe))})}],jn=s?In.filter(qe=>qe.id!==ob):In,Vt=jn.findIndex(qe=>qe.id===ob),mn=jn.findIndex(qe=>qe.id===U3),Vn=jn.findIndex(qe=>qe.id===V3),Xn=()=>{i===Vt&&Vt>=0&&!S||(i<jn.length-1?l(i+1):e())},Rr=jn[i];return n.jsx("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4",children:n.jsx("div",{className:"w-full max-w-lg",children:n.jsxs("div",{className:"bg-surface-elevated rounded-2xl p-8",children:[n.jsx("div",{className:"flex gap-1.5 mb-8",children:jn.map((qe,St)=>n.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${St<=i?"bg-brand-500":"bg-surface-elevated"}`},St))}),n.jsx("h2",{className:"text-2xl font-bold text-fg-primary",children:Rr.title}),n.jsx("p",{className:"text-sm text-fg-secondary mt-1 mb-6",children:Rr.subtitle}),Rr.content,n.jsxs("div",{className:"flex justify-between mt-8",children:[i>0?n.jsx("button",{onClick:()=>l(i-1),className:"px-4 py-2 text-sm text-fg-secondary hover:text-fg-primary transition-colors",children:a("common:back")}):n.jsx("button",{onClick:e,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("common:skip")}),n.jsxs("div",{className:"flex items-center gap-3",children:[Vt>=0&&i===Vt&&!S&&n.jsx("button",{onClick:()=>l(i+1),className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("llm.skipForNow")}),mn>=0&&i===mn&&!z&&n.jsx("button",{onClick:Xn,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("llm.skipForNow")}),Vn>=0&&i===Vn&&!$e&&n.jsx("button",{onClick:Xn,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("search.skipForNow")}),n.jsx("button",{onClick:Xn,disabled:Vt>=0&&i===Vt&&!S,className:`px-6 py-2.5 text-white text-sm rounded-xl transition-colors ${Vt>=0&&i===Vt&&!S?"bg-brand-600/40 cursor-not-allowed":"bg-brand-600 hover:bg-brand-500"}`,children:i===jn.length-1?a("getStarted"):a("common:next")})]})]})]})})})}function Zre({onSetup:e}){const{t}=ft("auth"),[r,s]=x.useState(""),[a,i]=x.useState(""),[l,d]=x.useState(""),[u,m]=x.useState(""),[h,p]=x.useState(null),[y,g]=x.useState(""),[v,j]=x.useState(!1),C=x.useRef(null),w=x.useCallback(S=>{if(!S.type.startsWith("image/")||S.size>2*1024*1024)return;const T=new FileReader;T.onload=()=>p(T.result),T.readAsDataURL(S)},[]),N=async S=>{if(S.preventDefault(),g(""),l.length<6){g(t("setup.passwordMinLength"));return}if(l!==u){g(t("setup.passwordsDoNotMatch"));return}j(!0);try{const{user:T,needsOnboarding:M}=await le.auth.init(r.trim(),a.trim(),l);if(h)try{await le.auth.uploadAvatar(h,"user")}catch{}e(T,M??!0)}catch{g(t("setup.error"))}finally{j(!1)}};return r.trim()&&r.trim()[0].toUpperCase(),n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:t("setup.subtitle")})]}),n.jsxs("form",{onSubmit:N,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:t("setup.title")}),n.jsxs("div",{className:"flex flex-col items-center gap-2",children:[n.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>C.current?.click(),children:[h?n.jsx("img",{src:h,alt:"",className:"w-16 h-16 rounded-full object-cover ring-2 ring-border-default group-hover:ring-brand-500 transition-all"}):n.jsx("div",{className:"w-16 h-16 rounded-full bg-surface-elevated border-2 border-dashed border-border-default group-hover:border-brand-500 flex items-center justify-center transition-all",children:n.jsxs("svg",{className:"w-6 h-6 text-fg-tertiary group-hover:text-brand-500 transition-colors",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"}),n.jsx("circle",{cx:"12",cy:"13",r:"3"})]})}),n.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-brand-600 flex items-center justify-center ring-2 ring-surface-secondary",children:n.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),n.jsx("input",{ref:C,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:S=>{const T=S.target.files?.[0];T&&w(T)}})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:t("setup.uploadAvatar")})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.name")}),n.jsx("input",{type:"text",value:r,onChange:S=>s(S.target.value),autoComplete:"name",autoFocus:!0,placeholder:"Admin",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.email")}),n.jsx("input",{type:"email",value:a,onChange:S=>i(S.target.value),autoComplete:"email",placeholder:"your@email.com",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.password")}),n.jsx("input",{type:"password",value:l,onChange:S=>d(S.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.confirmPassword")}),n.jsx("input",{type:"password",value:u,onChange:S=>m(S.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),y&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:y}),n.jsx("button",{type:"submit",disabled:v||!r||!a||!l||!u,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:t(v?"setup.creating":"setup.createAccount")})]})]})]})}function Jre({onLogin:e}){const{t}=ft("auth"),[r,s]=x.useState(""),[a,i]=x.useState(""),[l,d]=x.useState(""),[u,m]=x.useState(!1),h=async p=>{if(p.preventDefault(),!(!r.trim()||!a)){d(""),m(!0);try{const{user:y,needsOnboarding:g}=await le.auth.login(r.trim(),a);e(y,g??!1)}catch{d(t("login.invalidCredentials"))}finally{m(!1)}}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:t("login.subtitle")})]}),n.jsxs("form",{onSubmit:h,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:t("login.signIn")}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("login.email")}),n.jsx("input",{type:"email",value:r,onChange:p=>s(p.target.value),autoComplete:"email",placeholder:"your@email.com",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("login.password")}),n.jsx("input",{type:"password",value:a,onChange:p=>i(p.target.value),autoComplete:"current-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),l&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:l}),n.jsx("button",{type:"submit",disabled:u||!r||!a,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:t(u?"login.signingIn":"login.signIn")}),n.jsx("p",{className:"text-center text-xs text-fg-tertiary",children:t("login.defaultCredentials")})]})]})]})}function ese({token:e,onComplete:t}){const{t:r}=ft("auth"),[s,a]=x.useState(null),[i,l]=x.useState(""),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(!1),[g,v]=x.useState(!1),[j,C]=x.useState(!1);x.useEffect(()=>{le.auth.inviteInfo(e).then(N=>a(N)).catch(()=>C(!0))},[e]);const w=async N=>{if(N.preventDefault(),h(""),i.length<6){h(r("invite.passwordMinLength"));return}if(i!==d){h(r("invite.passwordsDoNotMatch"));return}y(!0);try{await le.auth.setup(e,i),v(!0),setTimeout(()=>{window.location.hash="",t()},2e3)}catch{h(r("invite.error"))}finally{y(!1)}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:r("invite.subtitle")})]}),n.jsx("div",{className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:j?n.jsxs("div",{className:"text-center space-y-3",children:[n.jsx("div",{className:"text-red-500 text-3xl",children:"⚠"}),n.jsx("p",{className:"text-sm text-fg-secondary",children:r("invite.invalidLink")}),n.jsx("button",{onClick:()=>{window.location.hash="",t()},className:"text-sm text-brand-500 hover:text-brand-400",children:r("login.signIn")})]}):g?n.jsxs("div",{className:"text-center space-y-3",children:[n.jsx("div",{className:"text-green-500 text-3xl",children:"✓"}),n.jsx("p",{className:"text-sm text-fg-secondary",children:r("invite.setupComplete")})]}):s?n.jsxs("form",{onSubmit:w,className:"space-y-5",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:r("invite.greeting",{name:s.name})}),n.jsx("p",{className:"text-xs text-fg-tertiary text-center",children:s.email}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("invite.setPassword")}),n.jsx("input",{type:"password",value:i,onChange:N=>l(N.target.value),autoComplete:"new-password",autoFocus:!0,className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("invite.confirmPassword")}),n.jsx("input",{type:"password",value:d,onChange:N=>u(N.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),m&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:m}),n.jsx("button",{type:"submit",disabled:p||!i||!d,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:r(p?"invite.settingUp":"invite.setupAccount")})]}):n.jsx("div",{className:"text-center text-fg-tertiary text-sm animate-pulse py-4",children:"Loading…"})})]})]})}function tse({onComplete:e,isFirstTime:t}){const{t:r}=ft("auth"),[s,a]=x.useState(""),[i,l]=x.useState(""),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(!1),g=async v=>{if(v.preventDefault(),h(""),i.length<6){h(r("changePassword.passwordMinLength"));return}if(i!==d){h(r("changePassword.passwordsDoNotMatch"));return}y(!0);try{await le.auth.changePassword(s,i),e()}catch{h(r("changePassword.failedToChange"))}finally{y(!1)}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:r("login.subtitle")})]}),n.jsxs("form",{onSubmit:g,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:r(t?"changePassword.setYourPassword":"changePassword.changePassword")}),t&&n.jsx("p",{className:"text-xs text-amber-600/80 text-center mt-2",children:r("changePassword.defaultPasswordWarning")})]}),!t&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.currentPassword")}),n.jsx("input",{type:"password",value:s,onChange:v=>a(v.target.value),autoComplete:"current-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.newPassword")}),n.jsx("input",{type:"password",value:i,onChange:v=>l(v.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0,minLength:6})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.confirmNewPassword")}),n.jsx("input",{type:"password",value:d,onChange:v=>u(v.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),m&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:m}),n.jsx("button",{type:"submit",disabled:p||!i||!d,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-colors",children:r(p?"changePassword.saving":t?"changePassword.setPasswordAndContinue":"changePassword.changePassword")})]})]})]})}const Vf={agents:[],tasks:[],requirements:[],projects:[],deliverables:[]},nse={team:["agents","tasks","requirements","projects","deliverables"],work:["projects","requirements","tasks","agents","deliverables"],deliverables:["deliverables","agents","tasks","requirements","projects"]},rse=["agents","tasks","requirements","projects","deliverables"];let K3="",W3="all",G3=Vf,Y3=!1;function sse({onClose:e,currentPage:t}){const{t:r}=ft(["common","home","work"]),[s,a]=x.useState(K3),[i,l]=x.useState(W3),[d,u]=x.useState(G3),[m,h]=x.useState(!1),[p,y]=x.useState(Y3),[g,v]=x.useState(-1);x.useEffect(()=>{K3=s},[s]),x.useEffect(()=>{W3=i},[i]),x.useEffect(()=>{G3=d},[d]),x.useEffect(()=>{Y3=p},[p]);const j=x.useRef(null),C=x.useRef(void 0),w=x.useRef(null),N=x.useRef(null);x.useEffect(()=>{setTimeout(()=>{j.current?.focus(),j.current?.select()},100)},[]);const S=x.useCallback(async F=>{if(!F.trim()){u(Vf),y(!1),v(-1);return}h(!0),y(!0),v(-1);const L=F.toLowerCase();try{const[z,E,_,G,V]=await Promise.allSettled([le.agents.list(),le.tasks.list({search:F,pageSize:20}),le.requirements.list(),le.projects.list(),le.deliverables.search({q:F,limit:20})]),O=z.status==="fulfilled"?z.value.agents.filter(Y=>Y.name?.toLowerCase().includes(L)||Y.role?.toLowerCase().includes(L)):[],q=E.status==="fulfilled"?E.value.tasks:[],J=_.status==="fulfilled"?_.value.requirements.filter(Y=>Y.title?.toLowerCase().includes(L)||Y.description?.toLowerCase().includes(L)):[],H=G.status==="fulfilled"?G.value.projects.filter(Y=>Y.name?.toLowerCase().includes(L)||Y.description?.toLowerCase().includes(L)):[],Z=V.status==="fulfilled"?V.value.results:[];u({agents:O,tasks:q,requirements:J,projects:H,deliverables:Z})}catch{u(Vf)}finally{h(!1)}},[]),T=F=>{a(F),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>S(F),400)},M=x.useCallback((F,L)=>{e(),pt.navigate(F,L)},[e]),D=[{id:"all",label:r("common:all",{defaultValue:"全部"})},{id:"agents",label:r("common:agents",{defaultValue:"智能体"})},{id:"tasks",label:r("common:tasks",{defaultValue:"任务"})},{id:"requirements",label:r("common:requirements",{defaultValue:"需求"})},{id:"projects",label:r("common:projects",{defaultValue:"项目"})},{id:"deliverables",label:r("common:deliverables",{defaultValue:"交付物"})}],I=x.useMemo(()=>nse[t||""]||rse,[t]),$=x.useMemo(()=>{const F=[],L=i==="all"?8:void 0,z=E=>{if(i!=="all"&&i!==E)return;const _=d[E==="agents"?"agents":E==="tasks"?"tasks":E==="requirements"?"requirements":E==="projects"?"projects":"deliverables"],G=L?_.slice(0,L):_;for(const V of G)switch(E){case"agents":F.push({id:V.id,type:"agent",page:Te.TEAM,params:{agentId:V.id}});break;case"tasks":F.push({id:V.id,type:"task",page:Te.WORK,params:{openTask:V.id}});break;case"requirements":F.push({id:V.id,type:"requirement",page:Te.WORK,params:{openRequirement:V.id}});break;case"projects":F.push({id:V.id,type:"project",page:Te.WORK,params:{projectId:V.id}});break;case"deliverables":F.push({id:V.id,type:"deliverable",page:Te.DELIVERABLES,params:{openDeliverable:V.id}});break}L&&_.length>L&&F.push({id:`more_${E}`,type:"showMore",page:"",expandCategory:E,totalCount:_.length})};for(const E of I)z(E);return F},[d,i,I]),B=x.useCallback(F=>{if(F.type==="showMore"&&F.expandCategory){l(F.expandCategory),v(-1);return}M(F.page,F.params)},[M]);x.useEffect(()=>{const F=N.current;if(!F||g<0)return;const L=F.querySelector(`[data-idx="${g}"]`);L&&L.scrollIntoView({block:"nearest"})},[g]);const R=x.useCallback(F=>{if(F.key==="Escape"){e();return}if(F.key==="Tab"){F.preventDefault();const E=D.map(V=>V.id),_=E.indexOf(i),G=F.shiftKey?_<=0?E.length-1:_-1:_>=E.length-1?0:_+1;l(E[G]),v(-1);return}const L=F.ctrlKey&&F.key==="n"||F.key==="ArrowDown",z=F.ctrlKey&&F.key==="p"||F.key==="ArrowUp";if(L||z){F.preventDefault(),v(E=>{const _=$.length-1;return _<0?-1:L?E>=_?0:E+1:E<=0?_:E-1});return}F.key==="Enter"&&(F.preventDefault(),g>=0&&g<$.length&&B($[g]))},[e,$,g,B,D,i]);x.useEffect(()=>(document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)),[R]);const U=$.length>0;let W=0;return n.jsx("div",{ref:w,className:"fixed inset-0 bg-black/50 flex items-start justify-center z-50 pt-[8vh]",onClick:F=>{F.target===w.current&&e()},children:n.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-2xl shadow-2xl w-full max-w-3xl max-h-[78vh] flex flex-col overflow-hidden animate-fadeIn",children:[n.jsxs("div",{className:"shrink-0 px-5 pt-4 pb-3 border-b border-border-default space-y-3",children:[n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg-tertiary",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("input",{ref:j,value:s,onChange:F=>T(F.target.value),placeholder:r("common:search"),className:"w-full bg-surface-elevated border border-border-default rounded-xl pl-9 pr-9 py-2.5 text-sm text-fg-primary placeholder:text-fg-tertiary focus:border-brand-500 focus:outline-none transition-colors"}),s&&n.jsx("button",{onClick:()=>{a(""),u(Vf),y(!1),v(-1),j.current?.focus()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-fg-tertiary hover:text-fg-secondary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:D.map(F=>n.jsx("button",{onClick:()=>{l(F.id),v(-1)},className:`px-3 py-1.5 text-xs rounded-lg whitespace-nowrap transition-colors ${i===F.id?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:text-fg-primary"}`,children:F.label},F.id))})]}),n.jsxs("div",{ref:N,className:"flex-1 overflow-y-auto px-5 py-3",children:[m&&n.jsx("div",{className:"flex items-center justify-center py-8",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:r("common:loading")})}),!m&&p&&!U&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[n.jsxs("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-2",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:r("common:noResults",{defaultValue:"没有找到相关结果"})})]}),!m&&U&&n.jsx("div",{className:"space-y-4",children:I.map(F=>{if(i!=="all"&&i!==F)return null;const L=i==="all"?8:void 0,z=E=>{const _=W++,G=E==="agents"?d.agents.length:E==="tasks"?d.tasks.length:E==="requirements"?d.requirements.length:E==="projects"?d.projects.length:d.deliverables.length;return n.jsxs("button",{"data-idx":_,onClick:()=>{l(E),v(-1)},className:`mt-1 w-full text-xs py-1.5 rounded-lg transition-colors ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40 text-brand-500":"text-brand-500 hover:text-brand-400 hover:bg-surface-overlay"}`,children:[r("common:showAll",{defaultValue:"查看全部"})," (",G,")"]})};return F==="agents"&&d.agents.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:agents",{defaultValue:"智能体"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.agents.slice(0,L):d.agents).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.TEAM,{agentId:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx(Sr,{name:E.name||"Agent",avatarUrl:E.avatarUrl,size:28}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:E.name}),n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:E.role||E.status})]}),n.jsx(ase,{status:E.status})]},E.id)})}),L&&d.agents.length>L&&z("agents")]},"agents"):F==="tasks"&&d.tasks.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:tasks",{defaultValue:"任务"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.tasks.slice(0,L):d.tasks).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{openTask:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx(ise,{status:E.status}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.status," · ",E.priority||""]})]})]},E.id)})}),L&&d.tasks.length>L&&z("tasks")]},"tasks"):F==="requirements"&&d.requirements.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:requirements",{defaultValue:"需求"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.requirements.slice(0,L):d.requirements).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{openRequirement:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${E.status==="approved"?"text-green-500 bg-green-500/15":E.status==="pending"?"text-amber-500 bg-amber-500/15":E.status==="rejected"?"text-red-500 bg-red-500/15":"text-fg-tertiary bg-surface-elevated"}`,children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),n.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.status," · ",E.priority||""]})]})]},E.id)})}),L&&d.requirements.length>L&&z("requirements")]},"requirements"):F==="projects"&&d.projects.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:projects",{defaultValue:"项目"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.projects.slice(0,L):d.projects).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{projectId:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"w-7 h-7 rounded-lg bg-teal-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-teal-500",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.name}),E.description&&n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:E.description})]})]},E.id)})}),L&&d.projects.length>L&&z("projects")]},"projects"):F==="deliverables"&&d.deliverables.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:deliverables",{defaultValue:"交付物"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.deliverables.slice(0,L):d.deliverables).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.DELIVERABLES,{openDeliverable:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"w-7 h-7 rounded-lg bg-purple-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-purple-500",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.type," · ",E.status]})]})]},E.id)})}),L&&d.deliverables.length>L&&z("deliverables")]},"deliverables"):null})}),!m&&!p&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[n.jsxs("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-2",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:r("common:searchHint",{defaultValue:"输入关键词搜索"})})]})]}),n.jsxs("div",{className:"shrink-0 px-5 py-2 border-t border-border-default flex items-center gap-4 text-xs text-fg-tertiary flex-wrap",children:[n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:navigator.platform.toUpperCase().includes("MAC")?"Cmd+P":"Ctrl+P"})," ",r("common:toggle",{defaultValue:"唤起/关闭"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Tab"})," ",r("common:switchTab",{defaultValue:"切换分类"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"↑↓"})," ",r("common:navigate",{defaultValue:"导航"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Enter"})," ",r("common:open",{defaultValue:"打开"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Esc"})," ",r("common:close",{defaultValue:"关闭"})]})]})]})})}function ase({status:e}){const t=e==="active"||e==="idle"?"bg-green-500":e==="working"||e==="busy"?"bg-blue-500":e==="paused"?"bg-amber-500":"bg-gray-400";return n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`})}function ise({status:e}){const t=e==="completed"?"text-green-500 bg-green-500/15":e==="in_progress"?"text-blue-500 bg-blue-500/15":e==="pending"?"text-amber-500 bg-amber-500/15":"text-fg-tertiary bg-surface-elevated";return n.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${t}`,children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 11l3 3L22 4"}),n.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})})}const ose={visibility:"hidden",position:"absolute",inset:0,pointerEvents:"none",zIndex:-1},lse=x.memo(function({id:t,activePage:r,children:s}){const a=t===r;return n.jsx("div",{className:"flex-1 overflow-hidden flex flex-col",style:a?void 0:ose,children:s})},(e,t)=>{const r=e.id===e.activePage,s=t.id===t.activePage;return r!==s?!1:s?e.children===t.children:!0}),lb={};function cse(){const{t:e}=ft("common"),[t,r]=x.useState(ec),[s,a]=x.useState(()=>!localStorage.getItem("markus_onboarded")),[i,l]=x.useState(!0),d=Ds(),u=$G(),m=m0({side:"left",defaultWidth:160,minWidth:140,maxWidth:400,collapsedWidth:64,storageKey:"markus_sidebar"}),[h,p]=x.useState(()=>new Set([ec()])),[y,g]=x.useState("loading"),[v,j]=x.useState(null),[C,w]=x.useState(!1),[N,S]=x.useState(!1),[T,M]=x.useState(null),[D,I]=x.useState(!1),[$,B]=x.useState(null),[R,U]=x.useState(()=>{const O=localStorage.getItem("markus_update_dismissed");return O||null}),[W,F]=x.useState(!1);x.useEffect(()=>{if(d)return;const O=navigator.platform.toUpperCase().includes("MAC"),q=H=>{O&&H.metaKey&&!H.ctrlKey&&H.key==="p"?(H.preventDefault(),F(Z=>!Z)):!O&&H.ctrlKey&&!H.metaKey&&H.key==="p"&&(H.preventDefault(),F(Z=>!Z))},J=()=>F(!0);return document.addEventListener("keydown",q),window.addEventListener("markus:open-search",J),()=>{document.removeEventListener("keydown",q),window.removeEventListener("markus:open-search",J)}},[d]);const L=x.useCallback(O=>{let q=nc(O);d?q=k_[q]??q:q===Te.NOTIFICATIONS&&(q=Te.HOME);const J=ec(),H=window.location.hash.slice(1);H!==J?lb[J]=H:delete lb[J];const Z=q!==Te.WORK?lb[q]:void 0;Z&&Z!==q?(history.pushState(null,"","#"+q),history.pushState(null,"","#"+Z)):history.pushState(null,"","#"+q),window.dispatchEvent(new HashChangeEvent("hashchange")),r(q),p(Y=>Y.has(q)?Y:new Set([...Y,q]))},[d]);x.useEffect(()=>{pt.setHandler(O=>L(O))},[L]);const z=x.useCallback(()=>{fetch("/api/settings/llm").then(O=>O.ok?O.json():null).then(O=>{if(O?.providers){const q=Object.values(O.providers).some(J=>J.configured);M(q)}}).catch(()=>{})},[]);x.useEffect(()=>{const O=new URLSearchParams(window.location.search),q=O.get("install");if(q&&ec()!==Te.STORE){const Z=O.get("type"),ee=Z&&{agent:"agents",team:"teams",skill:"skills"}[Z]||"agents";localStorage.setItem("markus_nav_installItem",q),localStorage.setItem("markus_nav_storeTab",ee),O.delete("install"),O.delete("type");const ae=O.toString();window.history.replaceState(null,"",window.location.pathname+(ae?`?${ae}`:"")+"#store"),setTimeout(()=>pt.navigate(Te.STORE,{storeTab:ee,installItem:q}),300)}le.auth.me().then(({user:Z})=>{g(Z),j(!0),pn.connect(Z.id),z(),le.health().then(ee=>{ee.updateAvailable&&ee.latestVersion&&B({latestVersion:ee.latestVersion,currentVersion:ee.version})}).catch(()=>{});const Y=()=>{Xl(Ra.builderArtifacts,()=>le.builder.artifacts.list()),Xl(Ra.builderAgents,()=>le.agents.list()),Xl(Ra.builderHubMyItems,()=>Un.myItems()),Xl(Ra.builderInstalled,()=>le.builder.artifacts.installed()),Xl(Ra.hubAgents,()=>Un.search({type:"agent",limit:50})),Xl(Ra.hubTeams,()=>Un.search({type:"team",limit:50})),Xl(Ra.hubSkills,()=>Un.search({type:"skill",limit:50}))};typeof requestIdleCallback=="function"?requestIdleCallback(Y,{timeout:5e3}):setTimeout(Y,3e3)}).catch(()=>{g(null),le.auth.status().then(({initialized:Z})=>j(Z)).catch(()=>j(!0))}),pn.connect();const J=pn.on("notification",()=>{window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}),H=()=>{const Z=ec();r(Z),p(Y=>Y.has(Z)?Y:new Set([...Y,Z]))};return window.addEventListener("hashchange",H),window.addEventListener("popstate",H),()=>{J(),pn.disconnect(),window.removeEventListener("hashchange",H),window.removeEventListener("popstate",H)}},[]);const E=y!=="loading"&&y!==null?y:void 0,_=x.useMemo(()=>d?{[Te.HOME]:n.jsx(gw,{authUser:E}),[Te.TEAM]:n.jsx(Wk,{authUser:E}),[Te.BUILDER]:n.jsx(Xre,{authUser:E}),[Te.SETTINGS]:n.jsx(Zk,{theme:u.mode,onThemeChange:u.setMode,authUser:E,onLogout:()=>g(null),onUserUpdated:O=>g(O)}),[Te.WORK]:n.jsx(z3,{authUser:E}),[Te.DELIVERABLES]:n.jsx(B3,{authUser:E}),[Te.NOTIFICATIONS]:n.jsx(Fre,{authUser:E}),[Te.REPORTS]:n.jsx(F3,{authUser:E}),[Te.SEARCH]:n.jsx(qre,{})}:{[Te.HOME]:n.jsx(gw,{authUser:E}),[Te.TEAM]:n.jsx(Wk,{authUser:E}),[Te.SETTINGS]:n.jsx(Zk,{theme:u.mode,onThemeChange:u.setMode,authUser:E,onLogout:()=>g(null),onUserUpdated:O=>g(O)}),[Te.STORE]:n.jsx(vY,{authUser:E}),[Te.BUILDER]:n.jsx(QS,{authUser:E}),[Te.WORK]:n.jsx(z3,{authUser:E}),[Te.DELIVERABLES]:n.jsx(B3,{authUser:E}),[Te.REPORTS]:n.jsx(F3,{authUser:E})},[E?.id,E?.role,u.mode,d]);if(y==="loading"||y===null&&v===null)return n.jsx("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:e("loading")})});const V=(typeof window<"u"?window.location.hash:"").match(/^#invite\?token=([a-f0-9]+)/);return V?n.jsx(ese,{token:V[1],onComplete:()=>{window.location.hash="",localStorage.removeItem("markus_onboarded"),a(!0),w(!0),g("loading"),le.auth.me().then(O=>g(O.user)).catch(()=>g(null))}}):y===null?v===!1?n.jsx(Zre,{onSetup:(O,q)=>{g(O),j(!0),w(!0),q&&(localStorage.removeItem("markus_onboarded"),a(!0))}}):n.jsx(Jre,{onLogin:(O,q)=>{g(O),q?(localStorage.removeItem("markus_onboarded"),a(!0)):localStorage.getItem("markus_onboarded")||(localStorage.setItem("markus_onboarded","1"),a(!1))}}):N?n.jsx(tse,{onComplete:()=>S(!1),isFirstTime:!0}):s?n.jsx(Qre,{theme:u.mode,onThemeChange:u.setMode,skipProfile:C,onComplete:()=>{localStorage.setItem("markus_onboarded","1"),a(!1),w(!1),z(),L(Te.HOME)}}):n.jsxs("div",{className:`flex h-dvh bg-surface-primary text-fg-primary overflow-x-hidden ${d?"flex-col":""}`,children:[!d&&t!==Te.SETTINGS&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"relative z-40 shrink-0",style:{width:m.width},children:n.jsx(Wre,{currentPage:t,onNavigate:O=>{L(O),l(!1)},authUser:y,collapsed:m.collapsed,onToggleCollapse:m.toggle})}),n.jsx("div",{className:`${m.collapsed?"w-0":"w-1.5 cursor-col-resize"} shrink-0 group relative z-10 flex items-center justify-center`,onMouseDown:m.collapsed?void 0:m.onResizeStart,children:!m.collapsed&&n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})})]}),n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col min-w-0 ${d&&t!==Te.SETTINGS&&t!==Te.SEARCH?"pb-14":""}`,children:[T===!1&&!D&&t!==Te.SETTINGS&&n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-amber-500/10 border-b border-amber-500/30 text-amber-600 text-sm shrink-0",children:[n.jsx("span",{className:d?"text-xs":"",children:"No LLM provider configured — agents cannot process requests."}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:()=>{L(Te.SETTINGS)},className:"px-3 py-1 bg-amber-700/50 hover:bg-amber-700/70 text-white text-xs rounded-lg transition-colors",children:"Go to Settings"}),n.jsx("button",{onClick:()=>I(!0),className:"text-amber-500 hover:text-amber-600 text-xs",children:e("dismiss")})]})]}),$&&R!==$.latestVersion&&n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-brand-500/10 border-b border-brand-500/30 text-brand-400 text-sm shrink-0",children:[n.jsxs("span",{className:d?"text-xs":"",children:["New version available: ",n.jsxs("strong",{children:["v",$.latestVersion]})," (current: v",$.currentVersion,")",!d&&n.jsxs("span",{className:"text-fg-tertiary ml-2",children:["— run ",n.jsx("code",{className:"bg-surface-overlay px-1.5 py-0.5 rounded text-xs font-mono",children:"npm i -g @markus-global/cli"})," to upgrade"]})]}),n.jsx("button",{onClick:()=>{U($.latestVersion),localStorage.setItem("markus_update_dismissed",$.latestVersion)},className:"text-brand-400 hover:text-brand-300 text-xs shrink-0",children:e("dismiss")})]}),n.jsx("main",{className:"flex-1 overflow-hidden flex flex-col relative",children:Object.keys(_).map(O=>h.has(O)?n.jsx(lse,{id:O,activePage:t,children:_[O]},O):null)})]}),d&&t!==Te.SETTINGS&&t!==Te.SEARCH&&n.jsx(Gre,{currentPage:t,onNavigate:L,userId:E?.id}),d&&n.jsx(A_,{authUser:E,onNavigate:L}),!d&&W&&n.jsx(sse,{onClose:()=>F(!1),currentPage:t})]})}E9.createRoot(document.getElementById("root")).render(n.jsx(x.StrictMode,{children:n.jsx(cse,{})}));export{j0 as g};
709
+ ${ms?"ring-2 ring-brand-500/50 border-brand-500/40":""}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-purple-500 shrink-0"}),n.jsx("span",{className:"text-[10px] font-semibold text-purple-500 uppercase tracking-wide shrink-0",children:s("work:task.requirementShort")}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-md shrink-0 ml-auto ${ds.cls}`,children:ds.label})]}),n.jsx("div",{className:"text-[13px] font-medium leading-snug text-fg-primary line-clamp-2 mb-1",children:bt.title}),bt.description&&n.jsx("div",{className:"text-[11px] text-fg-tertiary line-clamp-1 mb-1.5",children:bt.description}),n.jsxs("div",{className:"flex items-center justify-between mt-auto pt-1.5 border-t border-border-default/20",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[is&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-surface-overlay/60 text-fg-secondary rounded truncate max-w-[90px]",title:is.name,children:is.name}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:bt.priority}),n.jsxs("span",{className:"text-[10px] text-fg-quaternary",children:["by ",Kr]})]}),n.jsx("div",{className:"flex items-center gap-1",children:bt.taskIds.length>0&&n.jsxs("span",{className:"text-[10px] text-brand-500/70 bg-brand-500/8 px-1.5 py-0.5 rounded-md",children:["📋 ",bt.taskIds.length]})})]}),us&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-amber-500/15",children:[n.jsx("button",{onClick:Nr=>{Nr.stopPropagation(),Ur(bt.id)},className:"flex-1 py-1 bg-green-600 hover:bg-green-500 text-white text-[10px] rounded-md font-medium transition-colors",children:s("work:task.approve")}),n.jsx("button",{onClick:Nr=>{Nr.stopPropagation(),tn(bt.id)},className:"flex-1 py-1 border border-red-500/30 hover:bg-red-500/10 text-red-500 text-[10px] rounded-md font-medium transition-colors",children:s("work:task.reject")})]})]},`req-${bt.id}`)}else{const bt=cn.data,ds=bt.subtasks?.length??0,Vr=l[bt.status],us=bt.status==="pending",is=bt.taskType==="scheduled"&&!!bt.scheduleConfig,Kr=is?bt.scheduleConfig.every?s("work:task.everyInterval",{interval:bt.scheduleConfig.every}):bt.scheduleConfig.cron?s("work:task.cronLabel"):s("work:task.scheduledShort"):null,ms=T==="all"&&bt.projectId?(()=>{const Ee=N.find(et=>et.id===bt.projectId)?.name;return Ee&&Ee!=="default"?Ee:null})():null,Nr=bt.requirementId?L.find(Ee=>Ee.id===bt.requirementId)?.title:null,eo=bt.createdBy?Dd(bt.createdBy,R,W)??bt.createdBy:null,Ri=pe?.id===bt.id,to={urgent:"bg-red-500",high:"bg-amber-500",medium:"bg-blue-500",low:"bg-gray-400"},oe=bt.status==="blocked"&&(!bt.blockedBy||bt.blockedBy.length===0||bt.blockedBy.every(Ee=>{const et=ai.get(Ee);return et&&et.status==="completed"}));return n.jsxs("div",{role:"button",tabIndex:0,"aria-label":bt.title,draggable:!us,onDragStart:Ee=>!us&&sa(Ee,bt),onDragEnd:Wn,onClick:()=>ur(bt),onKeyDown:Ee=>Ee.key==="Enter"&&ur(bt),className:`group rounded-lg p-2.5 border border-transparent transition-all ${oe?"bg-red-500/[0.06] border-red-500/30 ring-1 ring-red-500/15 cursor-pointer":us?"bg-amber-500/[0.06] border-amber-500/30 ring-1 ring-amber-500/15 cursor-pointer":is?"bg-blue-500/[0.04] border-blue-500/20 hover:border-blue-400/40 cursor-pointer":"bg-surface-elevated/80 hover:bg-surface-elevated border-border-default/50 hover:border-brand-400/40 cursor-grab active:cursor-grabbing"} ${Ri?"ring-2 ring-brand-500/50 border-brand-500/40":""}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${to[bt.priority]??"bg-gray-400"}`,title:bt.priority}),is&&n.jsx("span",{className:"text-blue-500 shrink-0",title:Kr??"Scheduled",children:n.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"})})}),is&&Kr&&n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-500/10 text-blue-500 whitespace-nowrap",children:Kr}),Vr&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-md ml-auto shrink-0 ${Vr.cls}`,children:Vr.label}),oe&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md shrink-0 bg-red-500/15 text-red-500 font-medium",children:"⚠"})]}),n.jsx("div",{className:"text-[13px] font-medium leading-snug text-fg-primary line-clamp-2 mb-1",children:bt.title}),bt.description&&n.jsx("div",{className:"text-[11px] text-fg-tertiary line-clamp-1 mb-1.5",children:bt.description}),(ms||Nr||bt.blockedBy&&bt.blockedBy.length>0)&&n.jsxs("div",{className:"flex flex-wrap gap-1 mb-1.5",children:[ms&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-surface-overlay/60 text-fg-secondary rounded-md truncate max-w-[100px]",title:ms,children:ms}),Nr&&n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 bg-brand-500/8 text-brand-500 rounded-md truncate max-w-[110px]",title:Nr,children:["# ",Nr]}),bt.blockedBy&&bt.blockedBy.length>0&&n.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/10 text-amber-600 rounded-md",children:["⏳ ",bt.blockedBy.length," dep",bt.blockedBy.length>1?"s":""]})]}),n.jsxs("div",{className:"flex items-center justify-between mt-auto pt-1.5 border-t border-border-default/20",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:eo&&n.jsxs("span",{className:"text-[10px] text-fg-quaternary",title:`by ${eo}`,children:["by ",eo]})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[ds>0&&n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["⋮ ",ds]}),bt.notes&&bt.notes.length>0&&n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["📝 ",bt.notes.length]}),bt.assignedAgentId&&n.jsxs("span",{className:"text-[10px] text-brand-500 bg-brand-500/8 px-1.5 py-0.5 rounded-md flex items-center gap-1",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${k0[R.find(Ee=>Ee.id===bt.assignedAgentId)?.status??""]??"bg-gray-500"}`}),R.find(Ee=>Ee.id===bt.assignedAgentId)?.name??bt.assignedAgentId.slice(0,8)]})]})]})]},bt.id)}})})()}),fn&&n.jsx("div",{className:"mx-2 mb-2 border-2 border-dashed border-brand-500/25 rounded-lg h-10 flex items-center justify-center shrink-0",children:n.jsx("span",{className:"text-[11px] text-brand-500/50",children:s("work:task.dropHere")})})]},ie.id)})})})]}),!u&&ka&&n.jsx("div",{className:"w-1.5 shrink-0 cursor-col-resize group relative flex items-center justify-center",onMouseDown:v.onResizeStart,children:n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),(!u||j)&&ka&&n.jsx("div",{className:`${u||ja?"flex-1":"shrink-0"} overflow-hidden min-w-0 flex`,style:u||ja?void 0:{width:v.width},children:ja?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx($3,{req:Fe,agents:R,projects:N,allTasks:Object.values($).flat(),users:W,onClose:()=>{Je(null)},onApprove:ie=>{Ur(ie)},onReject:ie=>{tn(ie)},onCancel:ie=>{Ss(ie),Je(null)},onStatusChange:async(ie,Xe)=>{try{await le.requirements.updateStatus(ie,Xe),Mt(`Requirement status → ${Xe}`),Ns({requirementId:ie}),Ls(),on()}catch(ot){Mt(`Error: ${ot}`)}},onRefresh:Ls,authUser:e,onTaskClick:ie=>{ze(ie)},onCreateTask:(ie,Xe)=>{mt(ie),Xe&&st(Xe),Q(!0)},onProjectClick:wn,previewMode:t})}),n.jsx("div",{className:"w-px shrink-0 bg-border-default"}),n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx(I3,{task:pe,agents:R,projects:N,requirements:L,allTasks:Object.values($).flat(),users:W,onClose:pa,onRefresh:vr,authUser:e,scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onReqClick:ie=>{Je(Xe=>Xe?.id===ie.id?null:ie)},onProjectClick:wn})})]}):pe?n.jsx(I3,{task:pe,agents:R,projects:N,requirements:L,allTasks:Object.values($).flat(),users:W,onClose:ha,onRefresh:vr,authUser:e,scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onReqClick:ie=>{Je(Xe=>Xe?.id===ie.id?null:ie)},onProjectClick:wn}):Fe?n.jsx($3,{req:Fe,agents:R,projects:N,allTasks:Object.values($).flat(),users:W,onClose:ha,onApprove:ie=>{Ur(ie)},onReject:ie=>{tn(ie)},onCancel:ie=>{Ss(ie),ha()},onStatusChange:async(ie,Xe)=>{try{await le.requirements.updateStatus(ie,Xe),Mt(`Requirement status → ${Xe}`),Ns({requirementId:ie}),Ls(),on()}catch(ot){Mt(`Error: ${ot}`)}},scrollToComments:ei,onScrollToCommentsDone:()=>ti(!1),onRefresh:Ls,authUser:e,onTaskClick:ie=>{ze(ie),u&&(C(!0),history.pushState({mobileDetail:Te.WORK},"",window.location.hash))},onCreateTask:(ie,Xe)=>{mt(ie),Xe&&st(Xe),Q(!0)},onProjectClick:wn,previewMode:t}):null}),Y&&n.jsx(hre,{orgId:e?.orgId,onCreated:Kn,onClose:()=>ee(!1)}),ae&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{Q(!1),Ze("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 max-h-[90dvh] overflow-y-auto ${u?"w-full":"w-[28rem]"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.newTask")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.titleLabel")}),n.jsx("input",{autoFocus:!u,value:me,onChange:ie=>Ae(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&ba()},className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.descriptionField")}),n.jsx("textarea",{value:Me,onChange:ie=>He(ie.target.value),rows:2,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none resize-none"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.projectLabel")}),n.jsx(Lu,{options:[{value:"",label:s("work:task.noProject")},...N.map(ie=>({value:ie.id,label:ie.name}))],value:ct,onChange:ie=>{st(ie),mt("")},placeholder:s("work:task.noProject"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.requirementLabel")}),n.jsx(Lu,{options:[{value:"",label:s("work:task.selectRequirement")},...L.filter(ie=>ie.status==="in_progress"&&(!ct||ie.projectId===ct)).map(ie=>({value:ie.id,label:ie.title}))],value:zt,onChange:mt,placeholder:s("work:task.selectRequirement"),noMatchesText:s("work:task.noMatches")})]})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.assignToRequired")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:R.map(ie=>({value:ie.id,label:`${ie.name} (${ie.status})`})),value:Pe,onChange:Ce,placeholder:s("work:task.selectAgent"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.reviewerRequired")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:[...W.map(ie=>({value:`human:${ie.id}`,label:ie.name})),...R.filter(ie=>ie.id!==Pe).map(ie=>({value:`agent:${ie.id}`,label:`${ie.name} (${ie.status})`}))],value:Ye,onChange:Qe,placeholder:s("work:task.selectReviewer"),noMatchesText:s("work:task.noMatches")})]})]}),n.jsxs("div",{className:`grid gap-4 ${be==="scheduled"?"grid-cols-3":"grid-cols-2"}`,children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.priorityField")}),n.jsxs("select",{value:je,onChange:ie=>xe(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"low",children:s("work:priority.low")}),n.jsx("option",{value:"medium",children:s("work:priority.medium")}),n.jsx("option",{value:"high",children:s("work:priority.high")}),n.jsx("option",{value:"urgent",children:s("work:priority.urgent")})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.taskType")}),n.jsxs("select",{value:be,onChange:ie=>se(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"standard",children:s("work:task.taskTypeStandard")}),n.jsx("option",{value:"scheduled",children:s("work:task.taskTypeScheduled")})]})]}),be==="scheduled"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.frequency")}),n.jsxs("select",{value:fe,onChange:ie=>$e(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"30m",children:s("work:task.freq30m")}),n.jsx("option",{value:"1h",children:s("work:task.freq1h")}),n.jsx("option",{value:"2h",children:s("work:task.freq2h")}),n.jsx("option",{value:"4h",children:s("work:task.freq4h")}),n.jsx("option",{value:"8h",children:s("work:task.freq8h")}),n.jsx("option",{value:"12h",children:s("work:task.freq12h")}),n.jsx("option",{value:"1d",children:s("work:task.freq1d")}),n.jsx("option",{value:"1w",children:s("work:task.freq1w")})]})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.blockedBy")}),n.jsx(pre,{options:Object.values($).flat().filter(ie=>ie.status!=="completed"&&ie.status!=="cancelled").map(ie=>({value:ie.id,label:ie.title})),selected:te,onAdd:ie=>de([...te,ie]),placeholder:s("work:task.selectDependency"),noMatchesText:s("work:task.noMatches")}),te.length>0&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:te.map(ie=>{const Xe=Object.values($).flat().find(ot=>ot.id===ie);return n.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-1 bg-amber-500/10 text-amber-600 rounded-full",children:[Xe?Xe.title.slice(0,30):ie.slice(-8),n.jsx("button",{onClick:()=>de(te.filter(ot=>ot!==ie)),className:"ml-0.5 text-amber-600/60 hover:text-amber-600",children:"×"})]},ie)})})]}),Ne&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:Ne}),n.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[n.jsx("button",{onClick:()=>{Q(!1),Ze("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{ba()},disabled:!me.trim()||!Pe||!Ye,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-50",children:s("common:create")})]})]})}),Fn&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{mr(!1),fr(""),ir(""),ye("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 max-h-[90dvh] overflow-y-auto ${u?"w-full":"w-[28rem]"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.newRequirementModalTitle")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:s("work:task.newRequirementModalHint")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.projectLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx(Lu,{options:N.map(ie=>({value:ie.id,label:ie.name})),value:It,onChange:qt,placeholder:s("work:task.selectProject"),noMatchesText:s("work:task.noMatches")})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.titleField")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{value:rr,onChange:ie=>fr(ie.target.value),placeholder:s("work:task.reqTitleExample"),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none",autoFocus:!u,onKeyDown:ie=>{ie.key==="Enter"&&rr.trim()&&as()}})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-fg-secondary mb-1.5",children:[s("work:task.descriptionField")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("textarea",{value:Qn,onChange:ie=>ir(ie.target.value),placeholder:s("work:task.reqDescPlaceholder"),rows:3,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.priorityField")}),n.jsxs("select",{value:Ie,onChange:ie=>At(ie.target.value),className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none",children:[n.jsx("option",{value:"low",children:s("work:priority.low")}),n.jsx("option",{value:"medium",children:s("work:priority.medium")}),n.jsx("option",{value:"high",children:s("work:priority.high")}),n.jsx("option",{value:"urgent",children:s("work:priority.urgent")})]})]}),an&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:an}),n.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[n.jsx("button",{onClick:()=>{mr(!1),fr(""),ir(""),ye("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{as()},disabled:!rr.trim()||!Qn.trim()||!It,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 rounded-lg text-white disabled:opacity-40 disabled:cursor-not-allowed",children:s("common:create")})]})]})}),Jt&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3",onClick:()=>{tn(null),yt("")},children:n.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 space-y-4 ${u?"w-full":"w-96"}`,onClick:ie=>ie.stopPropagation(),children:[n.jsx("h3",{className:"text-base font-semibold text-fg-primary",children:s("work:task.rejectRequirementTitle")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-fg-secondary mb-1.5",children:s("work:task.rejectReasonLabel")}),n.jsx("textarea",{value:An,onChange:ie=>br(ie.target.value),placeholder:s("work:task.rejectReasonPlaceholder"),rows:3,className:"w-full px-3 py-2 bg-surface-elevated border border-border-default rounded-lg text-sm text-fg-primary focus:border-red-500 outline-none resize-none",autoFocus:!u})]}),at&&n.jsx("div",{className:"px-3 py-2 bg-red-500/15 text-red-500 text-xs rounded-lg",children:at}),n.jsxs("div",{className:"flex justify-end gap-3",children:[n.jsx("button",{onClick:()=>{tn(null),yt("")},className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated text-fg-secondary",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{ri()},className:"px-4 py-2 text-sm bg-red-600 hover:bg-red-500 rounded-lg text-white",children:s("work:task.reject")})]})]})}),Gt&&n.jsxs("div",{className:"fixed inset-0 z-[60] flex flex-col justify-end",onClick:()=>Tn(!1),children:[n.jsx("div",{className:"absolute inset-0 bg-black/50"}),n.jsxs("div",{className:"relative bg-surface-secondary rounded-t-2xl border-t border-border-default max-h-[70vh] overflow-y-auto pb-16",onClick:ie=>ie.stopPropagation(),children:[n.jsxs("div",{className:"sticky top-0 bg-surface-secondary z-10 px-4 pt-3 pb-2 flex items-center justify-between border-b border-border-default/60",children:[n.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:s("work:task.filtersSheetTitle")}),n.jsxs("div",{className:"flex items-center gap-2",children:[(Ve.size>0||gt.size>0||Et)&&n.jsx("button",{onClick:()=>{Rt(new Set),nt(new Set),dt(!1)},className:"text-[11px] text-brand-500 font-medium",children:s("work:task.clearAll")}),n.jsx("button",{onClick:()=>Tn(!1),className:"w-7 h-7 flex items-center justify-center rounded-full bg-surface-elevated text-fg-tertiary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),N.length>1&&n.jsxs("div",{className:"px-4 py-3",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary font-medium uppercase tracking-wider mb-2",children:s("work:task.projectsFilterGroup")}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:va.map(ie=>{const Xe=Ve.has(ie.id),ot=Di[ie.id]??0;return n.jsxs("div",{className:`flex items-center rounded-lg overflow-hidden transition-all ${Xe?"bg-brand-500/15 ring-1 ring-brand-500/30":""}`,children:[n.jsxs("button",{onClick:()=>wn(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] transition-all ${Xe?"text-brand-600":"bg-surface-elevated text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-sm flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-tertiary"}`,children:ie.name[0]?.toUpperCase()}),ie.name,ot>0&&n.jsx("span",{className:"text-[9px] text-fg-tertiary",children:ot})]}),Xe&&n.jsx("button",{onClick:()=>{Tn(!1),Jn(ie.id)},className:"px-2 py-1.5 self-stretch flex items-center border-l border-brand-500/20 text-fg-tertiary hover:text-brand-600",title:s("work:project.editProject"),children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},ie.id)})})]}),e?.id&&n.jsx("div",{className:"px-4 py-3 border-t border-border-default/40",children:n.jsx("button",{type:"button",onClick:()=>dt(ie=>!ie),className:`w-full text-left px-2.5 py-1.5 rounded-lg text-[11px] transition-all ${Et?"bg-green-600/20 text-green-500 ring-1 ring-green-500/40":"bg-surface-elevated text-fg-secondary"}`,children:s("work:task.myTasks")})}),R.length>0&&n.jsxs("div",{className:"px-4 py-3 border-t border-border-default/40",children:[n.jsx("div",{className:"text-[11px] text-fg-tertiary font-medium uppercase tracking-wider mb-2",children:s("work:task.agentsFilterGroup")}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:_s.map(ie=>{const Xe=gt.has(ie.id);return n.jsxs("button",{onClick:()=>_r(ie.id),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] transition-all ${Xe?"bg-brand-600/20 text-brand-500 ring-1 ring-brand-500/40":"bg-surface-elevated text-fg-secondary"}`,children:[n.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center text-[9px] font-bold shrink-0 ${Xe?"bg-brand-600 text-white":"bg-surface-overlay text-fg-tertiary"}`,children:ie.name[0]?.toUpperCase()}),ie.name]},ie.id)})})]}),n.jsx("div",{className:"h-[env(safe-area-inset-bottom,0px)]"})]})]})]})}function Lre({requirementId:e,createdBy:t,agents:r,users:s,authUser:a}){const{t:i}=ft(["work","common"]),[l,d]=x.useState([]),[u,m]=x.useState([]),h=x.useRef(null),[p,y]=x.useState(new Map);x.useEffect(()=>{m([]),y(new Map),h.current&&(clearTimeout(h.current),h.current=null),le.requirements.getComments(e).then(w=>d(w.comments)).catch(()=>{})},[e]),x.useEffect(()=>pn.on("requirement:comment",N=>{if(N.payload?.requirementId===e&&N.payload.comment){const S=N.payload.comment;d(T=>T.some(M=>M.id===S.id)?T:[...T,S]),(S.authorType==="agent"||S.authorId?.startsWith("agt_"))&&(m(T=>{const M=T.filter(D=>D.id!==S.authorId);return M.length===0&&h.current&&(clearTimeout(h.current),h.current=null),M}),y(T=>{const M=new Map(T);return M.delete(S.authorId),M}))}}),[e]),x.useEffect(()=>{if(u.length===0)return;const w=new Set(u.map(S=>S.id));return pn.on("agent:activity_log",S=>{const T=S.payload;if(!T)return;const M=T.agentId;if(!w.has(M))return;const D=T.type;if(D==="tool_start"||D==="tool_end"){const $={tool:T.content??T.metadata?.tool??"",phase:D==="tool_start"?"start":"end",success:D==="tool_end"?T.metadata?.success!==!1:void 0,ts:Date.now()};y(B=>{const R=new Map(B),U=[...R.get(M)??[],$];return R.set(M,U),R})}})},[u]);const[g,v]=x.useState(null),j=async(w,N,S,T)=>{let M;S.length>0&&(M=(await le.uploads.upload(S.map(R=>({dataUrl:R.dataUrl,name:R.name})),"comments")).files.map(R=>({type:"image",url:R.url,name:R.name}))),await le.requirements.addComment(e,w,a?.name,M,a?.id,N.length>0?N:void 0,T);const D=[],I=new Set,$=B=>{if(I.has(B)||B===a?.id)return;I.add(B);const R=r.find(U=>U.id===B);R&&D.push({id:R.id,name:R.name,avatarUrl:R.avatarUrl})};for(const B of N){const R=r.find(U=>U.name.toLowerCase()===B.toLowerCase());R&&$(R.id)}t?.startsWith("agt_")&&$(t),D.length>0&&(h.current&&clearTimeout(h.current),m(D),h.current=setTimeout(()=>m([]),12e4))},C=x.useCallback(w=>{v({id:w.id,authorName:w.authorName,content:w.content.slice(0,100)})},[]);return n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 block",children:l.length>0?i("work:task.commentsWithCount",{count:l.length}):i("work:task.comments")}),n.jsxs("div",{className:"space-y-0.5 mb-3",children:[l.length===0&&n.jsx("p",{className:"text-xs text-fg-tertiary text-center py-4",children:i("work:task.noCommentsYet")}),l.map(w=>n.jsx(Ju,{comment:w,agents:r,onReply:C},w.id)),u.length>0&&n.jsx("div",{className:"flex flex-col gap-1.5 pt-1",children:u.map(w=>{const N=p.get(w.id)??[];return n.jsxs("div",{className:"px-2 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors",onClick:()=>pt.navigate(Te.TEAM,{agentId:w.id,profileTab:"mind"}),children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(Sr,{name:w.name,avatarUrl:w.avatarUrl,size:22,bgClass:"bg-brand-500/15 text-brand-600"}),n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),n.jsx("span",{className:"text-xs font-medium text-fg-secondary",children:w.name}),N.length===0&&n.jsxs("span",{className:"flex items-center gap-0.5",children:[n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),n.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("work:task.agentProcessing")}),n.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary",children:"→"})]}),N.length>0&&n.jsx("div",{className:"ml-8 mt-1",children:n.jsx(Vh,{activities:N,isActive:!0})})]},w.id)})})]}),n.jsx(OS,{agents:r,humans:s,onSubmit:j,replyTo:g,onCancelReply:()=>v(null)})]})}function $3({req:e,agents:t,projects:r,allTasks:s,users:a,onClose:i,onApprove:l,onReject:d,onCancel:u,onStatusChange:m,onRefresh:h,authUser:p,scrollToComments:y,onScrollToCommentsDone:g,onTaskClick:v,onCreateTask:j,onProjectClick:C,previewMode:w}){const{t:N}=ft(["work","common"]),S=x.useMemo(()=>Dy(N),[N]),T=x.useMemo(()=>Z8(N),[N]),M=Ds(),[D,I]=x.useState(!1),[$,B]=x.useState(e.description),[R,U]=x.useState(!1),[W,F]=x.useState(!1),L=x.useRef(null),[z,E]=x.useState("none"),_=x.useRef(null),G=x.useRef(null),V=x.useRef(80);x.useEffect(()=>{const Q=L.current;if(!Q)return;const me=()=>{const{scrollTop:Me,scrollHeight:He,clientHeight:je}=Q;if(!(He>je+50)){E("none");return}const Pe=Me<30,Ce=Me+je>=He-30;E(Pe?"top":Ce?"bottom":"middle")};me(),Q.addEventListener("scroll",me,{passive:!0});const Ae=new ResizeObserver(me);return Ae.observe(Q),()=>{Q.removeEventListener("scroll",me),Ae.disconnect()}},[]),x.useEffect(()=>{if(D&&G.current){const Q=G.current;Q.style.height="auto",Q.style.height=Math.max(Q.scrollHeight,V.current)+"px",Q.focus()}},[D]),x.useEffect(()=>{if(!y)return;const Q=setTimeout(()=>{const me=L.current;me&&me.scrollTo({top:me.scrollHeight,behavior:"smooth"}),g?.()},300);return()=>clearTimeout(Q)},[y,g]);const O=S[e.status]??{label:e.status,cls:"bg-gray-500/15 text-fg-secondary"},q=e.source==="agent",J=q&&e.status==="pending",H=e.status==="pending"||e.status==="in_progress",Z=e.status==="completed"||e.status==="rejected"||e.status==="cancelled"||e.status==="archived",Y=e.projectId?r.find(Q=>Q.id===e.projectId):null,ee=Dd(e.createdBy,t,a)??e.createdBy.slice(0,12),ae=s.filter(Q=>e.taskIds.includes(Q.id));return x.useEffect(()=>{B(e.description),I(!1)},[e.id,e.description]),n.jsxs("div",{className:"flex flex-col w-full h-full overflow-hidden bg-surface-primary shadow-xl shadow-black/8 ring-1 ring-border-default/20",children:[n.jsxs("div",{className:"flex items-start justify-between gap-4 p-5 pb-0 border-b border-border-default",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[M&&n.jsx("button",{onClick:()=>history.back(),className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsxs("h2",{className:"flex-1 min-w-0 pb-4 text-lg font-semibold text-fg-primary leading-snug",children:[e.title," ",n.jsx("span",{className:"text-[10px] font-bold text-brand-500 bg-brand-500/15 px-2 py-0.5 rounded align-middle",children:N("work:task.requirementShort")})," ",n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium align-middle ${O.cls}`,children:O.label})," ",e.priority==="high"||e.priority==="urgent"?n.jsx("span",{className:`text-[10px] font-medium align-middle ${e.priority==="urgent"?"text-red-500":"text-amber-600"}`,children:N("common:priority."+e.priority,{defaultValue:e.priority})}):n.jsx("span",{className:"text-[10px] text-fg-tertiary align-middle",children:N("common:priority."+e.priority,{defaultValue:e.priority})})]})]}),n.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xl leading-none shrink-0 mt-1",children:"×"})]}),n.jsxs("div",{className:"flex-1 min-h-0 relative",children:[n.jsxs("div",{ref:L,className:"h-full overflow-y-auto p-5 space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-1 block",children:N("work:task.requirementDetailDescription")}),D?n.jsx("textarea",{ref:G,value:$,onChange:Q=>{B(Q.target.value);const me=Q.target;me.style.height="auto",me.style.height=me.scrollHeight+"px"},onBlur:async()=>{if($!==e.description){U(!0);try{await le.requirements.update(e.id,{description:$}),h?.()}catch{}finally{U(!1)}}I(!1)},onKeyDown:Q=>{Q.key==="Escape"&&(Q.preventDefault(),B(e.description),I(!1))},className:"w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none -mx-2 px-2 -my-1 py-1",placeholder:N("work:task.requirementDetailDescription")}):n.jsx("div",{ref:_,className:`group relative rounded-lg -mx-2 px-2 -my-1 py-1 transition-colors ${Z?"":"cursor-pointer hover:bg-surface-elevated/50"}`,onClick:Z?void 0:Q=>{Q.target.closest("a, button, [data-entity-link]")||(V.current=Math.max(_.current?.offsetHeight??80,60),B(e.description),I(!0))},role:Z?void 0:"button",tabIndex:Z?void 0:0,onKeyDown:Z?void 0:Q=>Q.key==="Enter"&&(B(e.description),I(!0)),children:e.description?n.jsx(Gr,{content:e.description,className:"text-sm text-fg-secondary leading-relaxed"}):n.jsx("p",{className:"text-sm text-fg-tertiary italic",children:N("work:task.requirementNoDescription")})})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.createdByLabel")}),n.jsx("span",{className:"text-fg-secondary",children:ee}),q&&n.jsx("span",{className:"text-[10px] text-brand-500 ml-1.5",children:N("work:task.agentTag")})]}),n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.createdLabel")}),n.jsx("span",{className:"text-fg-secondary",children:new Date(e.createdAt).toLocaleString()})]}),Y&&n.jsxs("div",{className:`bg-surface-elevated/60 rounded-lg p-2.5 ${C?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,onClick:C?()=>C(Y.id):void 0,role:C?"button":void 0,tabIndex:C?0:void 0,onKeyDown:C?Q=>Q.key==="Enter"&&C(Y.id):void 0,children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.projectLabel")}),n.jsx("span",{className:"text-fg-secondary",children:Y.name})]}),e.approvedBy&&n.jsxs("div",{className:"bg-surface-elevated/60 rounded-lg p-2.5",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary block mb-1",children:N("work:task.approvedBy")}),n.jsx("span",{className:"text-fg-secondary",children:Dd(e.approvedBy,t,a)??e.approvedBy.slice(0,12)}),e.approvedAt&&n.jsx("span",{className:"text-[10px] text-fg-tertiary ml-1",children:new Date(e.approvedAt).toLocaleDateString()})]})]}),e.rejectedReason&&n.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[n.jsx("span",{className:"text-[10px] font-semibold text-red-500 uppercase tracking-wider block mb-1",children:N("work:task.rejectionReason")}),n.jsx("p",{className:"text-sm text-red-500/80",children:e.rejectedReason})]}),Array.isArray(e.tags)&&e.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:e.tags.map(Q=>n.jsxs("span",{className:"text-[10px] bg-surface-elevated text-fg-secondary px-2 py-0.5 rounded-full",children:["#",Q]},Q))}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("label",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:N("work:task.linkedTasks",{count:ae.length})}),!Z&&j&&n.jsxs("button",{onClick:()=>j(e.id,e.projectId),className:"text-[11px] text-amber-500 hover:text-amber-400 font-medium flex items-center gap-1",children:[n.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),N("work:requirement.createTask")]})]}),ae.length>0?(()=>{const Q=new Map(ae.map(xe=>[xe.id,xe]));if(!ae.some(xe=>xe.blockedBy?.some(Pe=>Q.has(Pe))))return n.jsx("div",{className:"space-y-1.5",children:ae.map(xe=>{const Pe=T[xe.status];return n.jsxs("div",{onClick:()=>v?.(xe),className:`flex items-center gap-2 bg-surface-elevated/60 rounded-lg px-3 py-2 ${v?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[xe.status]??"bg-gray-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:xe.title}),Pe&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${Pe.cls}`,children:Pe.label})]},xe.id)})});const Ae=new Map,Me=new Set;for(const xe of ae)for(const Pe of xe.blockedBy??[])if(Q.has(Pe)){Me.add(xe.id);const Ce=Ae.get(Pe)??[];Ce.push(xe.id),Ae.set(Pe,Ce)}const He=ae.filter(xe=>!Me.has(xe.id)),je=(xe,Pe)=>{const Ce=T[xe.status],Ye=(Ae.get(xe.id)??[]).map(Qe=>Q.get(Qe)).filter(Boolean);return n.jsxs("div",{children:[n.jsxs("div",{onClick:()=>v?.(xe),className:`flex items-center gap-2 bg-surface-elevated/60 rounded-lg px-3 py-2 ${v?"cursor-pointer hover:bg-surface-elevated transition-colors":""}`,style:Pe>0?{marginLeft:Pe*20}:void 0,children:[Pe>0&&n.jsx("span",{className:"text-fg-quaternary text-[10px] shrink-0",children:"↳"}),n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${k0[xe.status]??"bg-gray-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:xe.title}),Ce&&n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${Ce.cls}`,children:Ce.label})]}),Ye.map(Qe=>je(Qe,Pe+1))]},xe.id)};return n.jsx("div",{className:"space-y-1.5",children:He.map(xe=>je(xe,0))})})():n.jsx("div",{className:"text-xs text-fg-tertiary italic py-2",children:N("work:requirement.noLinkedTasks")})]}),!w&&n.jsx(Lre,{requirementId:e.id,createdBy:e.createdBy,agents:t,users:a,authUser:p}),!w&&n.jsx(tC,{entityType:"requirement",entityId:e.id})]}),z!=="none"&&z!=="top"&&n.jsx("button",{onClick:()=>L.current?.scrollTo({top:0,behavior:"smooth"}),className:"absolute bottom-20 right-4 md:bottom-14 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:N("work:task.scrollToTop"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M14.77 12.79a.75.75 0 01-1.06-.02L10 8.832l-3.71 3.938a.75.75 0 11-1.08-1.04l4.25-4.5a.75.75 0 011.08 0l4.25 4.5a.75.75 0 01-.02 1.06z",clipRule:"evenodd"})})}),z!=="none"&&z!=="bottom"&&n.jsx("button",{onClick:()=>{const Q=L.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"})},className:"absolute bottom-6 right-4 md:bottom-4 md:right-3 z-10 w-12 h-12 md:w-8 md:h-8 rounded-full bg-brand-500 md:bg-brand-600/90 border border-brand-400/60 shadow-xl shadow-brand-500/30 md:shadow-lg md:shadow-brand-500/20 flex items-center justify-center text-white hover:bg-brand-400 transition-colors backdrop-blur-sm",title:N("work:task.scrollToBottom"),children:n.jsx("svg",{className:"w-6 h-6 md:w-4 md:h-4",viewBox:"0 0 20 20",fill:"currentColor",children:n.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})})]}),n.jsxs("div",{className:"flex items-center gap-2 p-5 pt-3 border-t border-border-default",children:[J&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>l(e.id),className:"px-4 py-2 bg-green-600 hover:bg-green-500 text-white text-sm rounded-lg font-medium transition-colors",children:N("work:requirement.approveRequirement")}),n.jsx("button",{onClick:()=>d(e.id),className:"px-4 py-2 border border-red-500/30 hover:bg-red-500/10 text-red-500 text-sm rounded-lg font-medium transition-colors",children:N("work:requirement.rejectRequirement")})]}),!J&&m&&!Z&&n.jsx("select",{value:e.status,onChange:Q=>{Q.target.value!==e.status&&m(e.id,Q.target.value)},className:"px-2 py-1.5 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-secondary cursor-pointer hover:border-gray-500 transition-colors",children:Dre.map(Q=>{const me=S[Q],Ae=Q===e.status||(x1[e.status]?.has(Q)??!1);return n.jsx("option",{value:Q,disabled:!Ae,children:me?.label??Q},Q)})}),Z&&m&&n.jsx("button",{onClick:()=>m(e.id,"in_progress"),className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors",children:N("work:task.reopen")}),n.jsx("div",{className:"flex-1"}),H&&!J&&n.jsx("button",{onClick:()=>F(!0),className:"px-3 py-1.5 text-xs text-red-500/70 hover:text-red-500 hover:bg-red-500/10 border border-transparent hover:border-red-500/20 rounded-lg transition-colors",children:N("work:task.cancelRequirement")})]}),W&&n.jsx(dd,{title:N("work:requirement.cancelConfirmTitle","Cancel Requirement"),message:N("work:requirement.cancelConfirmMessage","Are you sure you want to cancel this requirement? This action cannot be undone."),confirmLabel:N("work:requirement.cancelConfirmLabel","Cancel Requirement"),onConfirm:()=>{F(!1),u(e.id)},onCancel:()=>F(!1)})]})}function tC({entityType:e,entityId:t}){const{t:r}=ft(["work"]),[s,a]=x.useState([]),[i,l]=x.useState(!0),[d,u]=x.useState(!1);if(x.useEffect(()=>{l(!0),(e==="task"?le.tasks.getHistory:le.requirements.getHistory)(t).then(g=>a(g.history)).catch(()=>a([])).finally(()=>l(!1))},[e,t]),i)return n.jsx("div",{className:"px-6 py-4 text-xs text-fg-tertiary",children:r("work:task.loadingHistory","Loading history...")});if(s.length===0)return n.jsx("div",{className:"px-6 py-4 text-xs text-fg-tertiary italic",children:r("work:task.noHistory","No status change history.")});const m=d?s:s.slice(-5),h=s.length>5&&!d,p=y=>{const g=y.changedByName||y.changedById||(y.changedByType==="human"?"User":y.changedByType==="agent"?"Agent":"System"),v=y.changedByType==="human"?"bg-blue-500/20 text-blue-500":y.changedByType==="agent"?"bg-brand-500/20 text-brand-500":"bg-gray-500/20 text-fg-tertiary";return n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full font-medium shrink-0 ${v}`,children:g})};return n.jsxs("div",{className:"px-6 py-4",children:[n.jsx("p",{className:"text-xs font-semibold text-fg-tertiary uppercase tracking-wider mb-3",children:r("work:task.statusHistory","Status History")}),h&&n.jsx("button",{onClick:()=>u(!0),className:"text-[11px] text-brand-500 hover:underline mb-2",children:r("work:task.showAllHistory",{count:s.length})}),n.jsxs("div",{className:"relative ml-2",children:[n.jsx("div",{className:"absolute left-[2.5px] top-1 bottom-1 w-px bg-border-default"}),n.jsx("div",{className:"space-y-3",children:m.map(y=>n.jsxs("div",{className:"flex items-start gap-3 relative",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full mt-[7px] shrink-0 relative z-10",style:{background:y.changedByType==="human"?"#3b82f6":y.changedByType==="agent"?"var(--color-brand-500)":"#6b7280"}}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[p(y),n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-fg-tertiary line-through",children:y.fromStatus}),n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"}),n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-brand-500/15 text-brand-500 font-medium",children:y.toStatus})]}),y.reason&&n.jsx("p",{className:"text-[10px] text-fg-secondary mt-0.5 leading-snug",children:y.reason}),n.jsx("p",{className:"text-[9px] text-fg-tertiary mt-0.5",children:new Date(y.createdAt).toLocaleString()})]})]},y.id))})]})]})}function Bi(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"&&e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Pre(e){return e.files&&typeof e.files=="object"&&!Array.isArray(e.files)?e.files:null}function Ql({label:e,value:t}){return t?n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:e}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:t})]}):null}function rd({label:e,value:t,color:r}){if(!t)return null;const s={purple:"bg-brand-500/15 text-brand-500",cyan:"bg-blue-500/15 text-blue-600",indigo:"bg-brand-500/15 text-brand-500",gray:"bg-gray-500/15 text-fg-secondary",emerald:"bg-green-500/15 text-green-600"};return n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:e}),n.jsx("div",{className:`mt-0.5 px-2 py-0.5 rounded-full text-[10px] font-medium ${s[r]??s.gray} capitalize inline-block`,children:t})]})}function ib({files:e}){const{t}=ft(["builder","common"]),[r,s]=x.useState(Object.keys(e)[0]??""),a=Object.keys(e);return a.length===0?null:n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:t("builder:artifact.files",{count:a.length})}),n.jsxs("div",{className:"mt-1 bg-surface-elevated/50 rounded-lg border border-border-default/30 overflow-hidden",children:[n.jsx("div",{className:"flex gap-0.5 px-1.5 py-1 border-b border-border-default/30 overflow-x-auto",children:a.map(i=>n.jsx("button",{onClick:()=>s(i),className:`px-2 py-0.5 text-[10px] rounded whitespace-nowrap transition-colors ${r===i?"bg-brand-600/30 text-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:i},i))}),r&&e[r]!=null&&n.jsx("pre",{className:"p-2 text-[10px] text-fg-secondary max-h-[120px] overflow-auto whitespace-pre-wrap font-mono",children:e[r]})]})]})}function Ore({artifact:e,mode:t}){const{t:r}=ft(["builder","common"]),s=Pre(e),a=e.agent,i=e.team,l=e.dependencies,d=e.displayName??e.name;if(t==="agent"){const u=a?.roleName,m=a?.agentRole,h=a?.llmProvider,p=a?.llmModel,y=Bi(l?.env),g=Bi(l?.skills);return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[u&&n.jsx(rd,{label:r("builder:artifact.baseTemplate"),value:u,color:"indigo"}),n.jsx(rd,{label:r("builder:artifact.agentRole"),value:m,color:m==="manager"?"purple":"cyan"})]}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(v=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:v},v))}),(h||p)&&n.jsxs("div",{className:"flex gap-2",children:[h&&n.jsx(rd,{label:r("builder:artifact.llmProvider"),value:h,color:"gray"}),p&&n.jsx(rd,{label:r("builder:artifact.llmModel"),value:p,color:"gray"})]}),y.length>0&&n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:r("builder:artifact.requiredEnv")}),n.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:y.map(v=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/10 text-amber-600 rounded font-mono",children:v},v))})]}),g.length>0&&n.jsx(Ql,{label:r("builder:artifact.skills"),value:g.join(", ")}),s&&n.jsx(ib,{files:s})]})}if(t==="team"){const m=i?.members??[];return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsx("div",{className:"flex flex-wrap gap-2",children:n.jsx(rd,{label:r("builder:artifact.category"),value:e.category,color:"indigo"})}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(h=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:h},h))}),s&&n.jsx(ib,{files:s}),n.jsxs("div",{children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:r("builder:artifact.members",{count:m.length})}),n.jsx("div",{className:"mt-1.5 space-y-1.5",children:m.map((h,p)=>n.jsxs("div",{className:"bg-surface-elevated/30 rounded-lg px-2 py-1.5 border border-border-default/20",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-5 h-5 rounded flex items-center justify-center text-[10px] font-bold ${h.role==="manager"?"bg-brand-500/20 text-brand-500":"bg-blue-500/20 text-blue-600"}`,children:h.role==="manager"?"★":p+1}),n.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:h.name}),typeof h.roleName=="string"&&h.roleName&&n.jsx("span",{className:"text-[10px] text-brand-500/70 font-mono",children:h.roleName}),n.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["x",String(h.count??1)]})]}),Bi(h.skills).length>0&&n.jsx("div",{className:"mt-1 ml-7 flex flex-wrap gap-1",children:Bi(h.skills).map(y=>n.jsx("span",{className:"px-1 py-0.5 text-[9px] bg-green-500/10 text-green-600 rounded font-mono",children:y},y))})]},p))})]})]})}return n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsx(Ql,{label:r("builder:artifact.name"),value:d}),n.jsx(Ql,{label:r("builder:artifact.description"),value:e.description}),n.jsx("div",{className:"flex gap-2",children:n.jsx(rd,{label:r("builder:artifact.category"),value:e.category,color:"indigo"})}),s&&n.jsx(ib,{files:s}),Bi(e.tags).length>0&&n.jsx("div",{className:"flex flex-wrap gap-1",children:Bi(e.tags).map(u=>n.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-surface-elevated text-fg-tertiary rounded",children:u},u))})]})}const Pu={file:{icon:"📄",color:"bg-green-500/10 text-green-600"},directory:{icon:"📁",color:"bg-blue-500/10 text-blue-600"}},_re={active:{color:"text-green-600 bg-green-500/10"},verified:{color:"text-blue-600 bg-blue-500/10"},outdated:{color:"text-red-500 bg-red-500/10"}},zre=["file","directory"];function Cf(e){return/^https?:\/\//i.test(e)}const Zl={agent:{icon:"✦",color:"bg-brand-500/10 text-brand-500"},team:{icon:"◈",color:"bg-blue-500/10 text-blue-600"},skill:{icon:"⬡",color:"bg-amber-500/10 text-amber-600"}};function B3({authUser:e,previewMode:t,previewData:r}={}){const{t:s}=ft(["deliverables","common"]),a=Ds(),i=Rd(Te.DELIVERABLES),l=m0({side:"left",defaultWidth:384,minWidth:280,maxWidth:600,storageKey:"markus_deliverables_list"}),[d,u]=x.useState(!1),m=x.useRef(d);m.current=d,x.useEffect(()=>{if(!a)return;const _e=()=>{m.current&&u(!1)};return window.addEventListener("popstate",_e),()=>window.removeEventListener("popstate",_e)},[a]);const h=100,[p,y]=x.useState(r?.items??[]),[g,v]=x.useState(r?.items?.length??0),[j,C]=x.useState(!1),[w,N]=x.useState(r?.projects??[]),[S,T]=x.useState(r?.agents??[]),[M,D]=x.useState(!r),[I,$]=x.useState(""),[B,R]=x.useState(""),[U,W]=x.useState(""),[F,L]=x.useState(""),[z,E]=x.useState(""),[_,G]=x.useState(""),[V,O]=x.useState(""),[q,J]=x.useState("date"),[H,Z]=x.useState(()=>r?.initialSelectedId&&r.items?r.items.find(_e=>_e.id===r.initialSelectedId)??r.items[0]??null:r?.items?.[0]??null),[Y,ee]=x.useState(null),[ae,Q]=x.useState(""),[me,Ae]=x.useState(new Set),Me=x.useMemo(()=>[{id:"date"},{id:"project"},{id:"agent"},{id:"type"}],[]),He=x.useCallback(_e=>{J(_e),Ae(new Set)},[]),je=Sl(Me,q,He),xe=x.useRef(null),[Pe,Ce]=x.useState(null),[Ye,Qe]=x.useState("markdown"),[ct,st]=x.useState(null),[zt,mt]=x.useState(!1),[te,de]=x.useState(!1),[be,se]=x.useState(!1),[fe,$e]=x.useState(null),[Ne,Ze]=x.useState(""),[pe,ze]=x.useState(new Set),Fe=x.useRef(void 0),Je=(_e,Tt)=>{ee({type:_e,text:Tt}),setTimeout(()=>ee(null),3e3)},gt=async _e=>{await sy(_e)?(se(!0),setTimeout(()=>se(!1),1500)):Je("error",s("detail.copyFailed"))},nt=x.useMemo(()=>new Map(S.map(_e=>[_e.id,_e])),[S]),Et=x.useMemo(()=>new Map(w.map(_e=>[_e.id,_e])),[w]),dt=x.useCallback(_e=>{if(!_e||_e==="default")return null;const Tt=Et.get(_e)?.name;return!Tt||Tt==="default"?null:Tt},[Et]);x.useEffect(()=>{t||(le.projects.list().then(_e=>N(_e.projects)).catch(()=>{}),le.agents.list().then(_e=>T(_e.agents??[])).catch(()=>{}),le.system.storage().then(_e=>Ze(_e.dataDir+"/shared")).catch(()=>{}),le.deliverables.checkHealth().then(_e=>ze(new Set(_e.missingFiles))).catch(()=>{}))},[t]),x.useEffect(()=>(Fe.current=setTimeout(()=>R(I),300),()=>clearTimeout(Fe.current)),[I]);const Ve=x.useMemo(()=>({q:B||void 0,projectId:F||void 0,agentId:z||void 0,type:U||void 0,status:_||void 0,artifactType:V||void 0}),[B,F,z,U,_,V]),Rt=x.useCallback(async()=>{D(!0);try{const{results:_e,total:Tt}=await le.deliverables.search({...Ve,offset:0,limit:h});y(_e),v(Tt)}catch{y([]),v(0)}D(!1)},[Ve]),un=x.useCallback(async()=>{if(!(j||p.length>=g)){C(!0);try{const{results:_e,total:Tt}=await le.deliverables.search({...Ve,offset:p.length,limit:h});y(Ot=>[...Ot,..._e]),v(Tt)}catch{}C(!1)}},[Ve,p.length,g,j]);x.useEffect(()=>{t||Rt()},[Rt,t]),x.useEffect(()=>{!t||!r||(y(r.items??[]),v(r.items?.length??0),N(r.projects??[]),T(r.agents??[]),r.initialSelectedId&&Z(r.items?.find(_e=>_e.id===r.initialSelectedId)??r.items?.[0]??null))},[t,r]),x.useEffect(()=>{if(t||!i)return;const _e=pn.on("deliverable:created",()=>Rt()),Tt=pn.on("deliverable:updated",()=>Rt()),Ot=pn.on("deliverable:removed",()=>Rt());return()=>{_e(),Tt(),Ot()}},[Rt,i,t]);const yn=x.useRef(null),sn=x.useRef(p);sn.current=p;const In=x.useCallback(_e=>{const Tt=Gt=>{Z(Gt),a&&(u(!0),history.pushState({mobileDetail:Te.DELIVERABLES},"",window.location.hash))},Ot=sn.current.find(Gt=>Gt.id===_e);if(Ot){Tt(Ot);return}le.deliverables.get(_e).then(Gt=>{Gt.deliverable&&Tt(Gt.deliverable)}).catch(()=>{})},[a]);x.useEffect(()=>{if(t)return;const _e=localStorage.getItem("markus_nav_openDeliverable");_e&&(localStorage.removeItem("markus_nav_openDeliverable"),sn.current.length>0?In(_e):yn.current=_e);const Tt=Ot=>{const Gt=Ot.detail;Gt?.params?.openDeliverable&&(localStorage.removeItem("markus_nav_openDeliverable"),In(Gt.params.openDeliverable))};return window.addEventListener("markus:navigate",Tt),()=>window.removeEventListener("markus:navigate",Tt)},[In,t]),x.useEffect(()=>{const _e=yn.current;!_e||p.length===0||(yn.current=null,In(_e))},[p,In]);const jn=x.useCallback(()=>{const _e=xe.current;!_e||M||j||p.length>=g||_e.scrollHeight<=_e.clientHeight+100&&un()},[M,j,p.length,g,un]);x.useEffect(()=>{const _e=xe.current;if(!_e)return;const Tt=()=>{_e.scrollTop+_e.clientHeight>=_e.scrollHeight-100&&un()};return _e.addEventListener("scroll",Tt,{passive:!0}),()=>_e.removeEventListener("scroll",Tt)},[un]),x.useEffect(()=>{jn()},[jn,me]);const Vt=x.useMemo(()=>{const _e=new Map;for(const Ot of p){let Gt,Tn;if(q==="project"){const _n=dt(Ot.projectId);Gt=_n?Ot.projectId??"_none":"_none",Tn=_n??s("noProject")}else if(q==="agent")Gt=Ot.agentId??"_none",Tn=Ot.agentId?nt.get(Ot.agentId)?.name??Ot.agentId:s("common:unknown");else if(q==="type")Gt=Ot.type,Tn=Ot.type.charAt(0).toUpperCase()+Ot.type.slice(1);else{const _n=new Date(Ot.updatedAt);Gt=`${_n.getFullYear()}-${String(_n.getMonth()+1).padStart(2,"0")}-${String(_n.getDate()).padStart(2,"0")}`,Tn=Gt}_e.has(Gt)||_e.set(Gt,{label:Tn,items:[]}),_e.get(Gt).items.push(Ot)}const Tt=[..._e.entries()];return q==="date"?Tt.sort((Ot,Gt)=>Gt[0].localeCompare(Ot[0])):Tt.sort((Ot,Gt)=>Ot[1].label.localeCompare(Gt[1].label)),Tt},[p,q,Et,nt,s]),mn=async _e=>{Q("remove");try{await le.deliverables.remove(_e.id),Je("success",s("removed")),Z(null),Rt()}catch(Tt){Je("error",s("common:error",{message:String(Tt)}))}Q("")},Vn=()=>{pt.navigate(Te.BUILDER)},Xn=async _e=>{if(_e.reference&&!Cf(_e.reference)){if(_e.type==="directory"){de(!0);return}mt(!0);try{const Tt=await le.files.preview(_e.reference);Tt.type==="image"&&Tt.mimeType?st({src:`data:${Tt.mimeType};base64,${Tt.content}`,name:Tt.name}):(Ce(Tt.content),Qe(o7({format:_e.format,reference:_e.reference,content:Tt.content})))}catch{Ce(null),_e.type==="file"&&de(!0)}mt(!1)}};x.useEffect(()=>{t||(Ce(null),Qe("markdown"),st(null),de(!1),H&&Xn(H))},[H?.id,t]);const Rr=x.useCallback(_e=>{Ae(Tt=>{const Ot=new Set(Tt);return Ot.has(_e)?Ot.delete(_e):Ot.add(_e),Ot})},[]),qe=x.useCallback(()=>{me.size===Vt.length?Ae(new Set):Ae(new Set(Vt.map(([_e])=>_e)))},[me.size,Vt]),St=_e=>{Z(_e),a&&(u(!0),history.pushState({mobileDetail:Te.DELIVERABLES},"",window.location.hash))};return n.jsxs("div",{className:"flex-1 overflow-hidden flex",children:[n.jsxs("div",{className:`${a?"flex-1 min-w-0":"shrink-0"} flex flex-col bg-surface-secondary rounded-xl m-1 mr-0`,style:a?d?{display:"none"}:void 0:{width:l.width},children:[n.jsxs("div",{className:"p-4 space-y-3",children:[n.jsx("div",{className:"flex items-center justify-between gap-2",children:n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a&&n.jsx(gc,{}),n.jsxs("h2",{className:"text-sm font-semibold text-fg-secondary truncate",children:[s("title"),g>0&&n.jsxs("span",{className:"ml-1.5 text-fg-tertiary font-normal",children:["(",g,")"]})]})]})}),n.jsx("input",{value:I,onChange:_e=>$(_e.target.value),placeholder:s("searchPlaceholder"),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary focus:border-brand-500 focus:outline-none transition-colors"}),Ne&&n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 bg-surface-elevated rounded-lg text-[10px] text-fg-tertiary",children:[n.jsx("span",{className:"truncate font-mono",children:Ne}),n.jsx("button",{onClick:()=>{le.system.openPath(Ne)},className:"shrink-0 underline hover:text-fg-secondary transition-colors",children:s("common:open")})]}),n.jsxs("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:[n.jsx(Ou,{label:s("filters.allTypes"),value:"",current:U||V||"",onClick:()=>{W(""),O("")}}),zre.map(_e=>n.jsx(Ou,{label:`${Pu[_e]?.icon??""} ${_e}`,value:_e,current:U,onClick:Tt=>{W(Tt),O("")}},_e)),["agent","team","skill"].map(_e=>n.jsx(Ou,{label:`${Zl[_e].icon} ${s(`artifactTypes.${_e}`)}`,value:_e,current:V,onClick:Tt=>{O(Tt),W("")}},_e))]}),w.length>0&&n.jsxs("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:[n.jsx(Ou,{label:s("filters.allProjects"),value:"",current:F,onClick:L}),w.map(_e=>n.jsx(Ou,{label:_e.name,value:_e.id,current:F,onClick:L},_e.id))]}),n.jsxs("div",{className:"flex gap-1.5 items-center",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("filters.group")}),["date","project","agent","type"].map(_e=>n.jsx("button",{onClick:()=>{J(_e),Ae(new Set)},className:`px-2 py-1 rounded text-xs transition-colors ${q===_e?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:bg-surface-overlay"}`,children:s(`groupBy.${_e}`)},_e)),Vt.length>1&&n.jsx("button",{onClick:qe,className:"ml-auto px-1.5 py-1 rounded text-[10px] text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated transition-colors",title:me.size===Vt.length?s("expandAllTooltip"):s("collapseAllTooltip"),children:me.size===Vt.length?s("expandAll"):s("collapseAll")})]})]}),Y&&n.jsx("div",{className:`mx-4 mt-2 px-3 py-1.5 text-xs rounded-lg ${Y.type==="success"?"bg-green-500/15 text-green-600":"bg-red-500/15 text-red-500"}`,children:Y.text}),n.jsxs("div",{ref:xe,className:"flex-1 overflow-y-auto p-2 space-y-1",onTouchStart:a?je.onTouchStart:void 0,onTouchEnd:a?je.onTouchEnd:void 0,children:[M?n.jsx("div",{className:"p-4 space-y-3",children:[1,2,3].map(_e=>n.jsxs("div",{className:"animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),n.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},_e))}):p.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center",children:[n.jsx("svg",{className:"w-12 h-12 text-fg-muted mb-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),n.jsx("p",{className:"text-sm text-fg-secondary",children:s("empty.title")}),n.jsx("p",{className:"text-xs text-fg-tertiary mt-1 mb-3",children:s("empty.subtitle")}),n.jsx("button",{onClick:()=>pt.navigate(Te.WORK),className:"text-xs px-3 py-1.5 rounded-lg bg-brand-600 hover:bg-brand-500 text-white transition-colors",children:s("empty.goToWork")})]}):Vt.map(([_e,Tt])=>{const Ot=me.has(_e);return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>Rr(_e),className:"w-full flex items-center gap-1.5 px-2 py-1.5 rounded-md hover:bg-surface-elevated/50 transition-colors group/header",children:[n.jsx("svg",{className:`w-3 h-3 text-fg-tertiary transition-transform duration-200 shrink-0 ${Ot?"":"rotate-90"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})}),n.jsx("span",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider truncate",children:Tt.label}),n.jsxs("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:["(",Tt.items.length,")"]})]}),!Ot&&Tt.items.map(Gt=>n.jsx("button",{onClick:()=>St(Gt),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${H?.id===Gt.id?"bg-brand-600/20 border border-brand-500/30":"hover:bg-surface-elevated/60 border border-transparent"}`,children:n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[Gt.artifactType&&Zl[Gt.artifactType]?n.jsx("span",{className:`text-[10px] px-1 py-0.5 rounded font-medium shrink-0 ${Zl[Gt.artifactType].color}`,children:Zl[Gt.artifactType].icon}):n.jsx("span",{className:`text-[10px] px-1 py-0.5 rounded font-medium uppercase shrink-0 ${Pu[Gt.type]?.color??"bg-surface-overlay text-fg-secondary"}`,children:Pu[Gt.type]?.icon??Gt.type.charAt(0)}),n.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:Gt.title}),pe.has(Gt.id)&&n.jsx("span",{className:"shrink-0 text-amber-500",title:s("detail.fileMissing"),children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${_re[Gt.status]?.color??"bg-surface-elevated text-fg-tertiary"}`,children:s(`common:status.${Gt.status}`,{defaultValue:Gt.status})})]})},Gt.id))]},_e)}),j&&n.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 text-fg-tertiary",children:[n.jsx(H3,{})," ",n.jsx("span",{className:"text-[10px]",children:s("common:loadingMore")})]}),!M&&p.length>0&&n.jsx("div",{className:"text-center text-[10px] text-fg-tertiary py-2",children:p.length<g?s("count.partial",{loaded:p.length,total:g}):s("count.total",{total:g})})]})]}),!a&&n.jsx("div",{className:"w-1.5 shrink-0 cursor-col-resize group relative flex items-center justify-center",onMouseDown:l.onResizeStart,children:n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),(!a||d)&&n.jsxs("div",{className:"flex-1 overflow-y-auto min-w-0",children:[a&&n.jsxs("div",{className:"sticky top-0 z-10 bg-surface-secondary px-4 py-2.5 flex items-center gap-2",children:[n.jsx("button",{onClick:()=>history.back(),className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1",children:n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}),n.jsx("span",{className:"text-sm font-medium truncate",children:H?.title??s("detail.details")})]}),H?n.jsxs("div",{className:"p-6 space-y-4",children:[!t&&pe.has(H.id)&&n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-500/10 border border-amber-500/20 rounded-lg text-amber-600 text-xs",children:[n.jsxs("svg",{className:"w-4 h-4 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),n.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),n.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),n.jsx("span",{children:s("detail.fileMissing")})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:H.title}),!t&&n.jsx("button",{onClick:()=>$e(H),disabled:!!ae,className:"p-1.5 rounded-lg text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors disabled:opacity-50 shrink-0",title:s("common:remove"),children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-medium uppercase ${Pu[H.type]?.color??"bg-surface-overlay text-fg-secondary"}`,children:[Pu[H.type]?.icon??""," ",H.type]}),H.artifactType&&Zl[H.artifactType]&&n.jsxs("span",{className:`px-2 py-0.5 rounded text-xs font-medium ${Zl[H.artifactType].color}`,children:[Zl[H.artifactType].icon," ",s("detail.builderWithType",{type:s(`artifactTypes.${H.artifactType}`)})]}),H.tags.length>0&&H.tags.map(_e=>n.jsx("span",{className:"px-2 py-0.5 text-xs bg-surface-elevated text-fg-secondary rounded",children:_e},_e))]}),(H.taskId||H.agentId||dt(H.projectId))&&n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[H.taskId&&n.jsx("button",{onClick:()=>pt.navigate(Te.WORK,{openTask:H.taskId}),className:"text-xs text-brand-500 hover:underline bg-brand-500/10 px-2 py-0.5 rounded",children:s("links.task",{id:`${H.taskId.slice(0,12)}...`})}),H.agentId&&n.jsx("button",{onClick:()=>pt.navigate(Te.TEAM,{selectAgent:H.agentId}),className:"text-xs text-blue-600 hover:underline bg-blue-500/10 px-2 py-0.5 rounded",children:s("links.agent",{name:nt.get(H.agentId)?.name??H.agentId.slice(0,12)})}),dt(H.projectId)&&n.jsx("button",{onClick:()=>pt.navigate(Te.WORK,{projectId:H.projectId}),className:"text-xs text-blue-600 hover:underline bg-blue-500/10 px-2 py-0.5 rounded",children:s("links.project",{name:dt(H.projectId)})})]}),(H.diffStats||H.testResults)&&n.jsxs("div",{className:"flex gap-3 flex-wrap",children:[H.diffStats&&n.jsxs("div",{className:"bg-surface-elevated rounded-lg px-3 py-2 text-xs flex items-center gap-2",children:[n.jsxs("span",{className:"text-fg-tertiary font-medium",children:[s("diffStats.title"),":"]}),n.jsx("span",{className:"text-fg-secondary",children:s("diffStats.files",{count:H.diffStats.filesChanged})}),n.jsxs("span",{className:"text-green-600",children:["+",H.diffStats.additions]}),n.jsxs("span",{className:"text-red-500",children:["-",H.diffStats.deletions]})]}),H.testResults&&n.jsxs("div",{className:"bg-surface-elevated rounded-lg px-3 py-2 text-xs flex items-center gap-2",children:[n.jsxs("span",{className:"text-fg-tertiary font-medium",children:[s("testResults.title"),":"]}),n.jsx("span",{className:"text-green-600",children:s("testResults.passed",{count:H.testResults.passed})}),n.jsx("span",{className:"text-red-500",children:s("testResults.failed",{count:H.testResults.failed})}),n.jsx("span",{className:"text-fg-secondary",children:s("testResults.skipped",{count:H.testResults.skipped})})]})]}),n.jsxs("div",{className:"flex items-center gap-4 text-[10px] text-fg-tertiary flex-wrap",children:[n.jsxs("span",{children:[s("metadata.created")," ",new Date(H.createdAt).toLocaleDateString()]}),n.jsxs("span",{children:[s("metadata.updated")," ",new Date(H.updatedAt).toLocaleDateString()]}),n.jsx("span",{className:"text-fg-muted select-all",children:H.id.slice(0,12)})]}),H.reference&&!Cf(H.reference)&&H.type==="file"&&n.jsxs("div",{className:"flex items-center gap-2 bg-surface-elevated rounded-lg px-3 py-2",children:[n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"text-xs font-mono text-brand-500 hover:text-brand-500 hover:underline truncate flex-1 text-left cursor-pointer",title:s("detail.openInFileBrowser"),children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"px-2 py-1 text-[10px] rounded bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",title:s("detail.revealInFinder"),children:s("common:open")}),n.jsx("button",{onClick:()=>gt(H.reference),className:`px-2 py-1 text-[10px] rounded transition-colors shrink-0 ${be?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,title:s("detail.copyPath"),children:s(be?"common:copied":"common:copy")})]}),H.reference&&!Cf(H.reference)&&H.type!=="file"&&H.type!=="directory"&&n.jsx("span",{className:"text-xs text-fg-tertiary font-mono break-all",children:H.reference})]}),H.artifactType&&H.artifactData?n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Ore,{artifact:H.artifactData,mode:H.artifactType})}),H.reference&&n.jsxs("div",{className:"px-3 py-2 bg-surface-elevated rounded-lg",children:[n.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider block mb-1",children:s("detail.artifactDirectory")}),n.jsx("span",{className:"text-xs text-fg-secondary font-mono break-all",children:H.reference})]}),n.jsx("div",{className:"flex gap-2",children:n.jsx("button",{onClick:Vn,className:"flex-1 px-4 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openInBuilder")})}),H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})})]}):H.reference&&Cf(H.reference)?n.jsxs("div",{className:"space-y-4",children:[H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})}),n.jsxs("div",{className:"flex flex-col items-center justify-center py-10",children:[n.jsxs("svg",{className:"w-10 h-10 text-fg-muted mb-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),n.jsx("p",{className:"text-xs text-fg-tertiary font-mono mb-4 px-4 text-center break-all select-all",children:H.reference}),n.jsx("button",{onClick:()=>window.open(H.reference,"_blank","noopener,noreferrer"),className:"px-6 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openUrl")})]})]}):H.type==="directory"&&H.reference?n.jsxs("div",{className:"space-y-4",children:[H.summary&&n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"})}),n.jsxs("div",{className:"flex flex-col items-center justify-center py-10",children:[n.jsx("svg",{className:"w-10 h-10 text-fg-muted mb-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-xs text-fg-tertiary font-mono mb-4 px-4 text-center break-all select-all",children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpenBrowser")))},className:"px-6 py-2.5 bg-brand-600 hover:bg-brand-500 text-white text-sm font-medium rounded-lg transition-colors",children:s("detail.openInFileBrowser")})]})]}):n.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:zt?n.jsxs("div",{className:"flex items-center gap-2 text-fg-tertiary text-sm",children:[n.jsx(H3,{})," ",s("detail.loadingPreview")]}):ct?n.jsxs("div",{className:"flex flex-col items-center gap-2",children:[n.jsx("img",{src:ct.src,alt:ct.name,className:"max-w-full max-h-[60vh] rounded-lg object-contain"}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:ct.name})]}):Pe?n.jsx(uy,{content:Pe,format:Ye,className:"text-fg-secondary text-sm"}):te?n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-fg-secondary",children:s("detail.cannotPreview",{type:H.type})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpen")))},className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:s("detail.openInFileBrowser"),children:H.reference}),n.jsx("button",{onClick:()=>{le.files.reveal(H.reference).catch(()=>Je("error",s("detail.failedToOpen")))},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:s("common:open")}),n.jsx("button",{onClick:()=>gt(H.reference),className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${be?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:s(be?"common:copied":"common:copy")})]})]}):H.summary?n.jsx(Gr,{content:H.summary,className:"text-fg-secondary text-sm"}):n.jsx("p",{className:"text-sm text-fg-tertiary italic",children:s("detail.noContent")})})]}):n.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:n.jsxs("div",{className:"text-center text-fg-tertiary space-y-2",children:[n.jsx("svg",{className:"w-12 h-12 mx-auto text-fg-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1,children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),n.jsx("p",{className:"text-sm",children:s("detail.selectToView")})]})})]}),fe&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:()=>$e(null),children:n.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-6 max-w-sm mx-4 shadow-2xl",onClick:_e=>_e.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{className:"w-5 h-5 text-red-500",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("detail.confirmRemoveTitle")}),n.jsx("div",{className:"text-xs text-fg-secondary mt-0.5",children:s("detail.confirmRemoveMessage",{name:fe.title})})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>$e(null),className:"px-4 py-1.5 text-xs text-fg-secondary hover:text-fg-primary border border-border-default hover:border-gray-600 rounded-lg transition-colors",children:s("common:cancel")}),n.jsx("button",{onClick:()=>{const _e=fe;$e(null),mn(_e)},disabled:!!ae,className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-500 text-white rounded-lg transition-colors disabled:opacity-50",children:s("common:remove")})]})]})})]})}function Ou({label:e,value:t,current:r,onClick:s}){return n.jsx("button",{onClick:()=>s(r===t?"":t),className:`px-2 py-1 rounded text-xs whitespace-nowrap shrink-0 transition-colors ${r===t?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:bg-surface-overlay"}`,children:e})}function H3(){return n.jsxs("svg",{className:"animate-spin h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function Co(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function ld(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function $re(e){return e>=1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)} GB`:e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function F3({authUser:e}){const{t}=ft(["reports","common"]),r=Ds(),s=Rd(Te.REPORTS),[a,i]=x.useState("weekly"),[l,d]=x.useState(null),[u,m]=x.useState(!0),[h,p]=x.useState(""),[y,g]=x.useState(null),[v,j]=x.useState([]),[C,w]=x.useState("totalTokens"),[N,S]=x.useState(!0),[T,M]=x.useState("generate"),[D,I]=x.useState([]),[$,B]=x.useState(null),[R,U]=x.useState([]),[W,F]=x.useState(""),[L,z]=x.useState(""),E=Q=>{z(Q),setTimeout(()=>z(""),3e3)},_=x.useCallback(async Q=>{m(!0),p("");try{const{report:me}=await le.reports.generate({period:Q,scope:"org",orgId:"default"});d(me)}catch(me){p(String(me)),d(null)}m(!1)},[]),G=x.useCallback(()=>{le.usage.summary().then(Q=>g(Q.usage)).catch(()=>{}),le.usage.agents().then(Q=>j(Q.agents)).catch(()=>{})},[]),V=x.useCallback(async()=>{try{const{reports:Q}=await le.reports.list();I(Q)}catch{}},[]),O=x.useCallback(async Q=>{B(Q);try{const{feedback:me}=await le.reports.getFeedback(Q.id);U(me)}catch{U([])}},[]);x.useEffect(()=>{_(a)},[a,_]),x.useEffect(()=>{if(!s)return;G();const Q=setInterval(G,3e4);return()=>clearInterval(Q)},[G,s]),x.useEffect(()=>{T==="history"&&V()},[T,V]);const q=x.useMemo(()=>[...v].sort((Q,me)=>{const Ae=Q[C],Me=me[C];return N?Me-Ae:Ae-Me}),[v,C,N]),J=v.reduce((Q,me)=>Q+me.estimatedCost,0),H=v.reduce((Q,me)=>Q+me.tokensUsedToday,0),Z=v.reduce((Q,me)=>Q+(me.costToday??0),0),Y=Math.max(1,...v.map(Q=>Q.totalTokens)),ee=Q=>{C===Q?S(!N):(w(Q),S(!0))},ae=x.useMemo(()=>({daily:t("period.today"),weekly:t("period.thisWeek"),monthly:t("period.thisMonth")}),[t]);return n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsxs("div",{className:"max-w-5xl mx-auto w-full p-6 space-y-6",children:[n.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[n.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[r&&n.jsx(gc,{}),n.jsx("h1",{className:"text-xl font-semibold text-fg-primary",children:t("title")}),n.jsxs("div",{className:"flex gap-1 bg-surface-elevated rounded-lg p-0.5",children:[n.jsx("button",{onClick:()=>M("generate"),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${T==="generate"?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:t("tabs.generate")}),n.jsxs("button",{onClick:()=>M("history"),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${T==="history"?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:[t("tabs.history"),D.length>0?` (${D.length})`:""]})]})]}),n.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[L&&n.jsx("span",{className:"px-2.5 py-1 bg-green-500/10 text-green-600 text-xs rounded-lg",children:L}),T==="generate"&&n.jsx("div",{className:"flex gap-1 bg-surface-elevated rounded-lg p-0.5",children:["daily","weekly","monthly"].map(Q=>n.jsx("button",{onClick:()=>i(Q),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${a===Q?"bg-surface-overlay text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:t(`period.${Q}`)},Q))})]})]}),T==="history"&&!$&&n.jsx("section",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:D.length===0?n.jsx("div",{className:"p-8 text-center text-fg-tertiary text-sm",children:t("noReportsYet")}):n.jsx("div",{className:"divide-y divide-border-default/50",children:D.map(Q=>n.jsxs("button",{onClick:()=>O(Q),className:"w-full text-left px-5 py-3 flex items-center gap-4 hover:bg-surface-elevated/30 transition-colors",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary",children:t("reportType",{type:Q.type})}),n.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[new Date(Q.periodStart).toLocaleDateString()," — ",new Date(Q.periodEnd).toLocaleDateString()]})]}),Q.plan&&n.jsx("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-medium shrink-0 ${Q.plan.status==="approved"?"bg-green-500/10 text-green-600":Q.plan.status==="rejected"?"bg-red-500/10 text-red-500":"bg-amber-500/10 text-amber-600"}`,children:Q.plan.status==="pending"?t("upcomingPlan.planPending"):t("upcomingPlan.planStatus",{status:Q.plan.status})}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(Q.generatedAt).toLocaleDateString()})]},Q.id))})}),T==="history"&&$&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:()=>{B(null),U([])},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:t("backToList")}),n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t("reportType",{type:$.type})}),n.jsxs("span",{className:"text-xs text-fg-tertiary",children:[new Date($.periodStart).toLocaleDateString()," — ",new Date($.periodEnd).toLocaleDateString()]})]}),$.metrics&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskMetrics.title")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[n.jsx(Hi,{label:t("taskMetrics.completed"),value:$.metrics.tasksCompleted,color:"text-green-600"}),n.jsx(Hi,{label:t("taskMetrics.inProgress"),value:$.metrics.tasksInProgress,color:"text-brand-500"}),n.jsx(Hi,{label:t("taskMetrics.created"),value:$.metrics.tasksCreated,color:"text-blue-600"}),n.jsx(Hi,{label:t("taskMetrics.blocked"),value:$.metrics.tasksBlocked,color:"text-amber-600"}),n.jsx(Hi,{label:t("taskMetrics.failed"),value:$.metrics.tasksFailed,color:"text-red-500"})]})]}),$.costSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("costOverview.title")}),n.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:$.costSummary.totalTokens.toLocaleString()}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.totalTokens")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld($.costSummary.totalEstimatedCost)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.estimatedCost")})]}),n.jsxs("div",{children:[n.jsxs("div",{className:`text-2xl font-bold ${$.costSummary.trend==="decreasing"?"text-green-600":$.costSummary.trend==="increasing"?"text-red-500":"text-fg-primary"}`,children:[$.costSummary.trend==="decreasing"?"↓":$.costSummary.trend==="increasing"?"↑":"→"," ",$.costSummary.trend]}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.trend")})]})]}),$.costSummary.byAgent&&$.costSummary.byAgent.length>0&&n.jsx("div",{className:"mt-4 pt-3 border-t border-border-default/50 space-y-1.5",children:$.costSummary.byAgent.map((Q,me)=>n.jsxs("div",{className:"flex items-center justify-between text-xs",children:[n.jsx("span",{className:"text-fg-secondary",children:Q.agentId}),n.jsx("span",{className:"text-fg-tertiary tabular-nums",children:t("costOverview.byAgentRow",{tokens:Co(Q.tokens),cost:ld(Q.cost)})})]},me))})]}),$.taskSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5 overflow-hidden",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskSummary.title")}),n.jsxs("div",{className:"space-y-4 min-w-0",children:[$.taskSummary.completed.length>0&&n.jsx(sd,{title:t("taskSummary.completedCount",{count:$.taskSummary.completed.length}),color:"emerald",items:$.taskSummary.completed.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),$.taskSummary.inProgress.length>0&&n.jsx(sd,{title:t("taskSummary.inProgressCount",{count:$.taskSummary.inProgress.length}),color:"indigo",items:$.taskSummary.inProgress.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),$.taskSummary.blocked.length>0&&n.jsx(sd,{title:t("taskSummary.blockedCount",{count:$.taskSummary.blocked.length}),color:"amber",items:$.taskSummary.blocked.map(Q=>({id:Q.id,label:Q.title,sub:Q.reason||Q.agent}))}),$.taskSummary.completed.length===0&&$.taskSummary.inProgress.length===0&&$.taskSummary.blocked.length===0&&n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("taskSummary.noTasksInPeriod")})]})]}),$.highlights&&$.highlights.length>0&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-2",children:t("highlights")}),n.jsx("ul",{className:"list-disc list-inside space-y-1 text-sm text-fg-secondary",children:$.highlights.map((Q,me)=>n.jsx("li",{children:Q},me))})]}),$.blockers&&$.blockers.length>0&&n.jsxs("section",{className:"bg-surface-secondary border border-amber-500/20 rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-amber-600 mb-2",children:t("blockers")}),n.jsx("ul",{className:"list-disc list-inside space-y-1 text-sm text-fg-secondary",children:$.blockers.map((Q,me)=>n.jsx("li",{children:Q},me))})]}),$.plan&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("h3",{className:"text-xs font-semibold text-fg-secondary",children:[t("upcomingPlan.title"),n.jsx("span",{className:`ml-2 px-1.5 py-0.5 rounded text-[10px] font-medium ${$.plan.status==="approved"?"bg-green-500/10 text-green-600":$.plan.status==="rejected"?"bg-red-500/10 text-red-500":"bg-amber-500/10 text-amber-600"}`,children:t(`common:status.${$.plan.status}`,{defaultValue:$.plan.status})})]}),$.plan.status==="pending"&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:async()=>{try{const{report:Q}=await le.reports.approvePlan($.id,{approvedBy:e?.id??"unknown"});B(Q),E(t("upcomingPlan.planApproved")),V()}catch(Q){E(t("common:error",{message:String(Q)}))}},className:"px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-500 transition-colors",children:t("upcomingPlan.approvePlan")}),n.jsx("button",{onClick:async()=>{const Q=prompt(t("upcomingPlan.rejectionReason"));if(Q)try{const{report:me}=await le.reports.rejectPlan($.id,{rejectedBy:e?.id??"unknown",reason:Q});B(me),E(t("upcomingPlan.planRejected")),V()}catch(me){E(t("common:error",{message:String(me)}))}},className:"px-3 py-1.5 text-xs font-medium border border-border-default text-fg-secondary rounded-lg hover:bg-surface-overlay transition-colors",children:t("upcomingPlan.rejectPlan")})]})]}),$.plan.items&&$.plan.items.length>0&&n.jsx("div",{className:"space-y-1.5",children:$.plan.items.map((Q,me)=>n.jsxs("div",{className:"flex items-center gap-2 text-sm text-fg-secondary",children:[n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${Q.priority==="high"?"bg-red-500/10 text-red-500":Q.priority==="medium"?"bg-amber-500/10 text-amber-600":"bg-gray-500/10 text-fg-tertiary"}`,children:Q.priority}),n.jsx("span",{children:Q.title}),Q.assignee&&n.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:Q.assignee})]},me))})]}),!$.metrics&&!$.taskSummary&&!$.costSummary&&n.jsx("section",{className:"bg-surface-elevated rounded-xl p-8 text-center",children:n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("noDetailedMetrics")})}),n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("feedback.title",{count:R.length})}),R.length>0&&n.jsx("div",{className:"space-y-2 mb-4",children:R.map(Q=>n.jsxs("div",{className:"p-3 bg-surface-elevated/50 rounded-lg",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary mb-1",children:[n.jsx("span",{className:"font-medium text-fg-secondary",children:Q.authorName}),n.jsx("span",{children:Q.type}),n.jsx("span",{children:new Date(Q.createdAt).toLocaleDateString()})]}),n.jsx("p",{className:"text-xs text-fg-secondary",children:Q.content})]},Q.id))}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{value:W,onChange:Q=>F(Q.target.value),placeholder:t("feedback.placeholder"),className:"flex-1 px-3 py-2 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder:text-fg-tertiary",onKeyDown:Q=>{Q.key==="Enter"&&W.trim()&&le.reports.addFeedback($.id,{author:e?.id??"unknown",type:"comment",content:W.trim()}).then(({feedback:me})=>{U(Ae=>[...Ae,me]),F(""),E(t("feedback.added"))}).catch(me=>E(t("common:error",{message:String(me)})))}}),n.jsx("button",{onClick:()=>{W.trim()&&le.reports.addFeedback($.id,{author:e?.id??"unknown",type:"comment",content:W.trim()}).then(({feedback:Q})=>{U(me=>[...me,Q]),F(""),E(t("feedback.added"))}).catch(Q=>E(t("common:error",{message:String(Q)})))},disabled:!W.trim(),className:"px-3 py-2 text-xs bg-brand-600 text-white rounded-lg hover:bg-brand-500 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:t("common:send")})]})]})]}),T==="generate"&&y&&n.jsxs("div",{className:`grid gap-4 ${y.storageBytes>0?"grid-cols-2 lg:grid-cols-4":"grid-cols-3"}`,children:[n.jsx(Tf,{label:t("usage.llmTokens"),value:Co(y.llmTokens),color:"text-brand-500"}),n.jsx(Tf,{label:t("usage.toolCalls"),value:Co(y.toolCalls),color:"text-blue-600"}),n.jsx(Tf,{label:t("usage.messages"),value:Co(y.messages),color:"text-green-600"}),y.storageBytes>0&&n.jsx(Tf,{label:t("usage.storage"),value:$re(y.storageBytes),color:"text-amber-600"})]}),T==="generate"&&(u?n.jsx("div",{className:"flex items-center justify-center h-32 text-fg-tertiary text-sm",children:t("common:loading")}):h?n.jsx("div",{className:"flex items-center justify-center h-32 text-red-500 text-sm",children:h}):l?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae[a]," · ",new Date(l.periodStart).toLocaleDateString()," — ",new Date(l.periodEnd).toLocaleDateString()]}),l.metrics&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskMetrics.title")}),n.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[n.jsx(Hi,{label:t("taskMetrics.completed"),value:l.metrics.tasksCompleted,color:"text-green-600"}),n.jsx(Hi,{label:t("taskMetrics.inProgress"),value:l.metrics.tasksInProgress,color:"text-brand-500"}),n.jsx(Hi,{label:t("taskMetrics.created"),value:l.metrics.tasksCreated,color:"text-blue-600"}),n.jsx(Hi,{label:t("taskMetrics.blocked"),value:l.metrics.tasksBlocked,color:"text-amber-600"}),n.jsx(Hi,{label:t("taskMetrics.failed"),value:l.metrics.tasksFailed,color:"text-red-500"})]})]}),n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("costOverview.title")}),n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld(J)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.estCostAllTime")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:Co(H)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.tokensToday")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-2xl font-bold text-fg-primary",children:ld(Z)}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:t("costOverview.costToday")})]})]})]}),l.taskSummary&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("h3",{className:"text-xs font-semibold text-fg-secondary mb-3",children:t("taskSummary.title")}),n.jsxs("div",{className:"space-y-4",children:[l.taskSummary.completed.length>0&&n.jsx(sd,{title:t("taskSummary.completedCount",{count:l.taskSummary.completed.length}),color:"emerald",items:l.taskSummary.completed.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),l.taskSummary.inProgress.length>0&&n.jsx(sd,{title:t("taskSummary.inProgressCount",{count:l.taskSummary.inProgress.length}),color:"indigo",items:l.taskSummary.inProgress.map(Q=>({id:Q.id,label:Q.title,sub:Q.agent}))}),l.taskSummary.blocked.length>0&&n.jsx(sd,{title:t("taskSummary.blockedCount",{count:l.taskSummary.blocked.length}),color:"amber",items:l.taskSummary.blocked.map(Q=>({id:Q.id,label:Q.title,sub:Q.reason||Q.agent}))}),l.taskSummary.completed.length===0&&l.taskSummary.inProgress.length===0&&l.taskSummary.blocked.length===0&&n.jsx("p",{className:"text-sm text-fg-tertiary",children:t("taskSummary.noTasksInPeriod")})]})]})]}):null),T==="generate"&&n.jsxs("section",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:[n.jsx("div",{className:"px-5 py-4 border-b border-border-default",children:n.jsx("h3",{className:"text-sm font-semibold text-fg-secondary",children:t("perAgentUsage.title")})}),v.length===0?n.jsx("div",{className:"p-8 text-center text-fg-tertiary text-sm",children:t("perAgentUsage.noData")}):n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border-default text-xs text-fg-tertiary uppercase tracking-wider",children:[n.jsx("th",{className:"px-4 py-3 text-left font-medium",children:t("perAgentUsage.agent")}),n.jsx(_u,{label:t("perAgentUsage.totalTokens"),col:"totalTokens",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.today"),col:"tokensUsedToday",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.requests"),col:"requestCount",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.toolCalls"),col:"toolCalls",current:C,desc:N,onSort:ee}),n.jsx(_u,{label:t("perAgentUsage.estCost"),col:"estimatedCost",current:C,desc:N,onSort:ee,align:"right"})]})}),n.jsx("tbody",{children:q.map(Q=>n.jsx(Bre,{agent:Q,maxTokens:Y},Q.agentId))}),n.jsx("tfoot",{children:n.jsxs("tr",{className:"border-t border-border-default bg-surface-elevated/30",children:[n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary",children:t("perAgentUsage.totalAgents",{count:v.length})}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:Co(v.reduce((Q,me)=>Q+me.totalTokens,0))}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:Co(H)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:v.reduce((Q,me)=>Q+me.requestCount,0)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-fg-secondary tabular-nums",children:v.reduce((Q,me)=>Q+me.toolCalls,0)}),n.jsx("td",{className:"px-4 py-3 text-sm font-medium text-right text-fg-secondary tabular-nums",children:ld(J)})]})})]})})]})]})})}function Hi({label:e,value:t,color:r}){return n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:`text-2xl font-bold ${r}`,children:t}),n.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:e})]})}function sd({title:e,color:t,items:r}){return n.jsxs("div",{className:"min-w-0 overflow-hidden",children:[n.jsx("div",{className:`text-xs font-medium text-${t}-400 mb-1.5`,children:e}),n.jsx("div",{className:"space-y-1.5",children:r.map((s,a)=>n.jsxs("div",{className:`text-sm text-fg-secondary min-w-0 ${s.id?"cursor-pointer hover:text-fg-primary group":""}`,onClick:s.id?()=>pt.navigate(Te.WORK,{openTask:s.id}):void 0,children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full bg-${t}-500 shrink-0`}),n.jsx("span",{className:`truncate min-w-0 ${s.id?"group-hover:text-brand-500 transition-colors":""}`,children:s.label})]}),s.sub&&s.sub!=="unassigned"&&n.jsx("div",{className:"text-[10px] text-fg-tertiary ml-3.5 mt-0.5 break-all line-clamp-2",children:s.sub})]},s.id??a))})]})}function Tf({label:e,value:t,color:r}){return n.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[n.jsx("div",{className:"text-sm text-fg-secondary mb-2",children:e}),n.jsx("div",{className:`text-2xl font-bold ${r}`,children:t})]})}function _u({label:e,col:t,current:r,desc:s,onSort:a,align:i}){const l=r===t?s?"↓":"↑":"↕",d=r===t?"text-brand-500":"text-fg-muted";return n.jsxs("th",{className:`px-4 py-3 ${i==="right"?"text-right":"text-left"} font-medium cursor-pointer select-none hover:text-fg-secondary`,onClick:()=>a(t),children:[e,n.jsx("span",{className:`ml-1 ${d}`,children:l})]})}function Bre({agent:e,maxTokens:t}){const r=t>0?Math.min(100,e.totalTokens/t*100):0,s=e.status==="working"?"bg-blue-500":e.status==="idle"?"bg-green-500":e.status==="paused"?"bg-amber-500":e.status==="error"?"bg-red-500":"bg-gray-600";return n.jsxs("tr",{className:"border-b border-border-default/50 hover:bg-surface-elevated/30 transition-colors cursor-pointer",onClick:()=>pt.navigate(Te.TEAM,{selectAgent:e.agentId}),children:[n.jsx("td",{className:"px-4 py-3",children:n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsx("div",{className:`w-2 h-2 rounded-full ${s}`}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary hover:text-brand-500 transition-colors",children:e.agentName}),n.jsx("div",{className:"text-xs text-fg-tertiary",children:e.role})]})]})}),n.jsx("td",{className:"px-4 py-3",children:n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"flex-1 bg-surface-elevated rounded-full h-1.5 overflow-hidden max-w-[120px]",children:n.jsx("div",{className:"h-full bg-brand-500 rounded-full",style:{width:`${r}%`}})}),n.jsx("span",{className:"text-sm text-fg-secondary tabular-nums",children:Co(e.totalTokens)})]})}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:Co(e.tokensUsedToday)}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:e.requestCount}),n.jsx("td",{className:"px-4 py-3 text-sm text-fg-secondary tabular-nums",children:e.toolCalls}),n.jsx("td",{className:"px-4 py-3 text-sm text-right text-fg-secondary tabular-nums",children:ld(e.estimatedCost)})]})}const Af={urgent:"bg-red-500",high:"bg-amber-500",normal:"bg-blue-500",low:"bg-gray-400"},ad={approval_request:"M9 12l2 2 4-4 M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z",task_completed:"M22 11.08V12a10 10 0 1 1-5.93-9.14 M22 4L12 14.01l-3-3",task_created:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",task_review:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",task_failed:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8",requirement_created:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7 M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z",requirement_decision:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",agent_report:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8",direct_message:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",group_message:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2 M9 7a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M23 21v-2a4 4 0 0 0-3-3.87 M16 3.13a4 4 0 0 1 0 7.75",system:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"},q3={approval_request:"text-amber-500",task_completed:"text-green-500",task_failed:"text-red-500",task_created:"text-blue-500",task_review:"text-purple-500",requirement_created:"text-amber-500",requirement_decision:"text-green-500",agent_report:"text-blue-500",direct_message:"text-green-500",group_message:"text-brand-500",system:"text-fg-tertiary"};function id(e,t){const r=Date.now()-new Date(e).getTime(),s=Math.floor(r/6e4);if(s<1)return t("common:time.now");if(s<60)return t("common:time.minutesAgo",{count:s});const a=Math.floor(s/60);return a<24?t("common:time.hoursAgo",{count:a}):t("common:time.daysAgo",{count:Math.floor(a/24)})}function Ef(e,t){const r=e.actionType;if(r==="open_chat")return t("team:notifications.actionHints.openChat");if(r==="navigate")return t("team:notifications.actionHints.viewDetails");const s=e.metadata??{};switch(e.type){case"task_completed":case"task_created":case"task_review":case"task_failed":return s.taskId?t("team:notifications.actionHints.viewTask"):null;case"requirement_created":case"requirement_decision":return s.requirementId?t("team:notifications.actionHints.viewRequirement"):null;case"agent_report":return s.agentId?t("team:notifications.actionHints.viewAgent"):null;case"direct_message":return t("team:notifications.actionHints.openChat");case"group_message":return t("team:notifications.actionHints.openChat");case"approval_request":return t("team:notifications.actionHints.viewApproval");default:return s.taskId?t("team:notifications.actionHints.viewTask"):s.requirementId?t("team:notifications.actionHints.viewRequirement"):s.agentId?t("team:notifications.actionHints.viewAgent"):null}}function Hre(){try{const e=new AudioContext,t=e.currentTime,r=e.createGain();r.connect(e.destination),r.gain.setValueAtTime(.15,t),r.gain.exponentialRampToValueAtTime(.01,t+.6);const s=e.createOscillator();s.type="sine",s.frequency.setValueAtTime(880,t),s.frequency.setValueAtTime(1174.66,t+.15),s.connect(r),s.start(t),s.stop(t+.6),s.onended=()=>e.close()}catch{}}function nC({collapsed:e,userId:t,embeddedMode:r,onClose:s,sidebarMode:a,isActive:i,label:l,iconPath:d}){const{t:u}=ft(["team","common"]),[m,h]=x.useState(!1),[p,y]=x.useState("approvals"),[g,v]=x.useState([]),[j,C]=x.useState([]),[w,N]=x.useState(null),[S,T]=x.useState(null),[M,D]=x.useState({}),[I,$]=x.useState(0),B=x.useRef(null),R=x.useRef(null),[U,W]=x.useState({top:0,left:0,width:448,maxHeight:576}),F=x.useRef(null),L=x.useRef(!1),[z,E]=x.useState(!0),[_,G]=x.useState(!1),V=x.useRef(null),O=x.useRef("approvals"),q=30,J=x.useCallback(async()=>{try{const[se,fe]=await Promise.all([le.notifications.list(t,!1,{limit:q,offset:0}),le.approvals.list()]);if(v(se.notifications),$(se.unreadCount??se.notifications.filter($e=>!$e.read).length),E(se.totalCount!=null?se.notifications.length<se.totalCount:se.notifications.length>=q),C(fe.approvals),!L.current){const $e=fe.approvals.filter(Ne=>Ne.status==="pending").length;F.current=$e,L.current=!0}}catch{}},[t]),H=x.useCallback(async()=>{if(!(_||!z)){G(!0);try{const se=await le.notifications.list(t,!1,{limit:q,offset:g.length});se.notifications.length>0&&v(fe=>[...fe,...se.notifications.filter($e=>!fe.some(Ne=>Ne.id===$e.id))]),E(se.totalCount!=null?g.length+se.notifications.length<se.totalCount:se.notifications.length>=q)}catch{}G(!1)}},[t,g.length,_,z]),Z=x.useCallback(se=>{const fe=se.detail;if(!fe)return;const{taskId:$e,requirementId:Ne}=fe;!$e&&!Ne||v(Ze=>{const pe=Ze.filter(ze=>!ze.read&&($e&&ze.metadata?.taskId===$e||Ne&&ze.metadata?.requirementId===Ne));if(pe.length===0)return Ze;for(const ze of pe)le.notifications.markRead(ze.id).catch(()=>{});return $(ze=>Math.max(0,ze-pe.length)),Ze.map(ze=>pe.some(Fe=>Fe.id===ze.id)?{...ze,read:!0}:ze)})},[]);x.useEffect(()=>{J();const se=setInterval(J,6e4),fe=()=>J(),$e=()=>{h(!0),J()};window.addEventListener("markus:notifications-changed",fe),window.addEventListener("markus:mark-read-by-ref",Z),window.addEventListener("markus:open-notifications",$e);const Ne=pn.on("notification:created",()=>J()),Ze=pn.on("approval:created",()=>J());return()=>{clearInterval(se),window.removeEventListener("markus:notifications-changed",fe),window.removeEventListener("markus:mark-read-by-ref",Z),window.removeEventListener("markus:open-notifications",$e),Ne(),Ze()}},[J,Z]);const Y=x.useCallback(()=>{if(!B.current)return;const se=B.current.getBoundingClientRect(),fe=window.innerWidth,$e=window.innerHeight,Ne=Math.min(448,fe-16),Ze=Math.min(576,$e-16);let pe=se.right+8,ze=se.top;pe+Ne>fe-8&&(pe=Math.max(8,fe-Ne-8)),ze+Ze>$e-8&&(ze=Math.max(8,$e-Ze-8)),W({top:ze,left:pe,width:Ne,maxHeight:Ze})},[]);x.useLayoutEffect(()=>{m&&Y()},[m,Y]),x.useEffect(()=>{if(m)return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[m,Y]),x.useEffect(()=>{if(!m)return;const se=fe=>{B.current?.contains(fe.target)||R.current?.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[m]),x.useEffect(()=>{if(!m)return;const se=j.some($e=>$e.status==="pending"),fe=g.some($e=>!$e.read);y(se&&!fe?"approvals":!se&&fe?"notifications":O.current)},[m]);const ee=new Set(j.filter(se=>se.status==="pending").map(se=>se.id)),ae=new Set(j.map(se=>se.id)),Q=g.filter(se=>!(se.type==="approval_request"&&se.metadata?.approvalId&&ae.has(se.metadata.approvalId))),me=g.filter(se=>se.type==="approval_request"&&!se.read&&se.metadata?.approvalId&&ee.has(se.metadata.approvalId)).length,Ae=Math.max(0,I-me),Me=ee.size,He=Ae+Me;x.useEffect(()=>{F.current!==null&&Me>F.current&&Hre(),F.current=Me},[Me]);const je=async se=>{await le.notifications.markRead(se),v(fe=>fe.map($e=>$e.id===se?{...$e,read:!0}:$e)),$(fe=>Math.max(0,fe-1))},xe=se=>{const fe=se.metadata??{},$e=se.actionType,Ne=se.actionTarget;if($e==="open_chat"&&Ne)try{const Ze=typeof Ne=="string"?JSON.parse(Ne):Ne;if(Ze.agentId){const pe={agentId:Ze.agentId};Ze.sessionId&&(pe.sessionId=Ze.sessionId),pt.navigate(Te.TEAM,pe);return}}catch{}if($e==="navigate"&&Ne)try{const Ze=typeof Ne=="string"?JSON.parse(Ne):Ne;if(Ze.path){if(Ze.path.startsWith("/team")){const pe={},ze=new URLSearchParams(Ze.path.split("?")[1]||"");for(const[Fe,Je]of ze.entries())pe[Fe]=Je;pt.navigate(Te.TEAM,pe);return}if(Ze.path.startsWith("/work")){const pe={},ze=new URLSearchParams(Ze.path.split("?")[1]||"");for(const[Fe,Je]of ze.entries())pe[Fe]=Je;pt.navigate(Te.WORK,pe);return}}}catch{}switch(se.type){case"approval_request":{const Ze=fe.approvalId,pe=Ze?j.find(gt=>gt.id===Ze):void 0,ze=pe?.details?.taskId??fe.taskId,Fe=pe?.details?.requirementId??fe.requirementId,Je=pe?.details?.agentId??pe?.agentId;ze?pt.navigate(Te.WORK,{openTask:ze}):Fe?pt.navigate(Te.WORK,{openRequirement:Fe}):Je?pt.navigate(Te.TEAM,{agentId:Je}):pt.navigate(Te.WORK);break}case"task_completed":case"task_created":case"task_review":case"task_failed":fe.taskId?pt.navigate(Te.WORK,{openTask:fe.taskId}):pt.navigate(Te.WORK);break;case"requirement_created":case"requirement_decision":fe.requirementId?pt.navigate(Te.WORK,{openRequirement:fe.requirementId}):pt.navigate(Te.WORK);break;case"agent_report":case"system":{if(fe.agentId){const Ze={agentId:fe.agentId};fe.sessionId&&(Ze.sessionId=fe.sessionId),pt.navigate(Te.TEAM,Ze)}else pt.navigate(Te.TEAM);break}case"direct_message":{const Ze=fe.senderId;Ze?pt.navigate(Te.TEAM,{dm:Ze}):pt.navigate(Te.TEAM);break}case"group_message":{const Ze=fe.channel;Ze?pt.navigate(Te.TEAM,{channel:Ze}):pt.navigate(Te.TEAM);break}default:fe.taskId?pt.navigate(Te.WORK,{openTask:fe.taskId}):fe.requirementId?pt.navigate(Te.WORK,{openRequirement:fe.requirementId}):fe.projectId?pt.navigate(Te.WORK,{projectId:fe.projectId}):fe.agentId&&pt.navigate(Te.TEAM,{agentId:fe.agentId});break}},Pe=async se=>{se.read||je(se.id);const fe=se.metadata??{},$e=fe.taskId,Ne=fe.requirementId;if($e||Ne){const Ze=g.filter(pe=>pe.id!==se.id&&!pe.read&&($e&&pe.metadata?.taskId===$e||Ne&&pe.metadata?.requirementId===Ne));for(const pe of Ze)je(pe.id)}xe(se)},Ce=async(se,fe,$e,Ne)=>{N(se);try{const{approval:Ze}=await le.approvals.respond(se,fe,t,$e,Ne);C(Je=>Je.map(gt=>gt.id===se?Ze:gt)),T(null),D(Je=>{const gt={...Je};return delete gt[se],gt});const pe=Ze.details?.taskId,ze=Ze.details?.requirementId,Fe=g.filter(Je=>!Je.read&&(Je.type==="approval_request"&&Je.metadata?.approvalId===se||pe&&Je.metadata?.taskId===pe||ze&&Je.metadata?.requirementId===ze));if(Fe.length>0){for(const gt of Fe)le.notifications.markRead(gt.id).catch(()=>{});const Je=new Set(Fe.map(gt=>gt.id));v(gt=>gt.map(nt=>Je.has(nt.id)?{...nt,read:!0}:nt)),$(gt=>Math.max(0,gt-Fe.length))}pl("/approvals"),pl("/notifications"),pl("/tasks"),pl("/taskboard"),pl("/requirements"),window.dispatchEvent(new CustomEvent("markus:data-changed")),window.dispatchEvent(new CustomEvent("markus:notifications-changed")),setTimeout(()=>J(),800)}catch{}N(null)},Ye=async()=>{try{if(!t)return;await le.notifications.markAllRead(t),v(se=>se.map(fe=>({...fe,read:!0}))),$(0),pl("/notifications")}catch{const se=Q.filter(fe=>!fe.read);await Promise.all(se.map(fe=>le.notifications.markRead(fe.id))),v(fe=>fe.map($e=>({...$e,read:!0}))),$(0),pl("/notifications")}},Qe=se=>{const fe=se.details?.subType;return fe==="requirement_resubmit"?u("team:notifications.approvalType.requirementResubmit"):fe==="requirement"||se.details?.requirementId?u("team:notifications.approvalType.requirement"):fe==="task_review"?u("team:notifications.approvalType.taskReview"):fe==="task"||se.details?.taskId?u("team:notifications.approvalType.task"):se.details?.toolName?u("team:notifications.approvalType.toolExecution"):null},ct=se=>{const fe=[];fe.push(se.agentName);const $e=se.details?.taskTitle,Ne=se.details?.taskId;$e?fe.push($e):Ne&&fe.push(`Task ${Ne.slice(0,8)}`);const Ze=se.details?.requirementId;return Ze&&!Ne&&fe.push(`Req ${Ze.slice(0,8)}`),fe.join(" · ")},st=[...j].sort((se,fe)=>new Date(fe.requestedAt).getTime()-new Date(se.requestedAt).getTime()),zt=st.filter(se=>se.status==="pending"),mt=st.filter(se=>se.status!=="pending"),te=se=>{const fe=se.details?.taskId,$e=se.details?.requirementId,Ne=se.details?.agentId??se.agentId;fe?pt.navigate(Te.WORK,{openTask:fe}):$e?pt.navigate(Te.WORK,{openRequirement:$e}):Ne?pt.navigate(Te.TEAM,{agentId:Ne}):pt.navigate(Te.WORK)},de=()=>{h(!1),s?.()},be=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex border-b border-border-default shrink-0",children:[n.jsxs("button",{onClick:()=>{y("approvals"),O.current="approvals"},className:`flex-1 px-3 py-2.5 text-xs font-medium transition-colors ${p==="approvals"?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:[u("team:notifications.approvals"),Me>0?` (${Me})`:""]}),n.jsxs("button",{onClick:()=>{y("notifications"),O.current="notifications"},className:`flex-1 px-3 py-2.5 text-xs font-medium transition-colors ${p==="notifications"?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary hover:text-fg-secondary"}`,children:[u("team:notifications.notifications"),Ae>0?` (${Ae})`:""]}),n.jsx("button",{onClick:de,className:"px-2 py-2 text-fg-tertiary hover:text-fg-primary transition-colors shrink-0",title:u("common:close"),children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),p==="notifications"&&I>0&&n.jsx("div",{className:"flex justify-end px-3 py-1.5 border-b border-border-default/50 shrink-0",children:n.jsx("button",{onClick:Ye,className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:u("team:notifications.markAllRead")})}),n.jsxs("div",{ref:V,className:"flex-1 overflow-y-auto",onScroll:se=>{if(p!=="notifications"||!z||_)return;const fe=se.currentTarget;fe.scrollTop+fe.clientHeight>=fe.scrollHeight-80&&H()},children:[p==="approvals"&&(j.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noApprovals")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[zt.map(se=>{const fe=se.details?.command,$e=fe?se.description.replace(/\s*Command:.*$/,""):se.description;return n.jsxs("div",{className:"px-3 py-3 space-y-2.5",children:[n.jsxs("div",{className:"cursor-pointer hover:bg-surface-overlay/50 -mx-3 -mt-3 px-3 pt-3 pb-1 rounded-t-md transition-colors",onClick:()=>te(se),children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-amber-500 mt-0.5 shrink-0",children:n.jsx("path",{d:ad.approval_request})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[Qe(se)&&n.jsx("span",{className:"text-[10px] text-amber-500 font-medium shrink-0",children:Qe(se)}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:se.title}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:id(se.requestedAt,u)})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:se.agentName})]})]}),n.jsx("div",{className:"mt-2.5 text-[11px] text-fg-secondary leading-relaxed",children:n.jsx(Gr,{content:$e,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]"})}),fe&&n.jsx("pre",{className:"text-[11px] text-fg-primary bg-surface-overlay border border-border-default rounded-md px-2.5 py-2 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed mt-2",children:fe})]}),(()=>{const Ne=se.details?.subType,Ze=Ne==="task"||Ne==="requirement"||Ne==="requirement_resubmit",pe=se.options&&se.options.length>0,ze=(M[se.id]??"").trim();return pe?n.jsxs("div",{className:"space-y-1.5",children:[se.options.map((Fe,Je)=>n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,Fe.id!=="reject",ze||void 0,Fe.id),className:`w-full px-3 py-2 text-left text-[11px] font-medium rounded-md disabled:opacity-50 transition-colors flex items-center gap-2 ${Fe.id==="reject"||Fe.id==="request_changes"?"border border-border-default text-fg-secondary hover:bg-surface-overlay":"bg-brand-600 text-white hover:bg-brand-700"}`,title:Fe.description,children:[n.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-[10px] font-bold shrink-0",children:String.fromCharCode(65+Je)}),Fe.label]},Fe.id)),n.jsxs("div",{className:"flex gap-1.5 mt-1",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.freeformPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&(M[se.id]??"").trim()&&Ce(se.id,!0,(M[se.id]??"").trim(),"custom")},className:"flex-1 px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{disabled:w===se.id||!(M[se.id]??"").trim(),onClick:()=>Ce(se.id,!0,(M[se.id]??"").trim(),"custom"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 disabled:opacity-50 transition-colors",children:u("common:send")})]})]}):Ze?n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!0,void 0,"approve"),className:"px-3 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6L9 17l-5-5"})}),u("common:approve")]}),n.jsxs("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!1,void 0,"reject"),className:"px-3 py-1.5 text-[11px] font-medium bg-red-600/80 text-white rounded-md hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]}),u("common:reject")]}),S!==se.id&&n.jsxs("button",{disabled:w===se.id,onClick:()=>T(se.id),className:"px-3 py-1.5 text-[11px] font-medium border border-amber-500/50 text-amber-500 rounded-md hover:bg-amber-500/10 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),u("team:notifications.needsAdjustment")]})]}),S===se.id&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",autoFocus:!0,placeholder:u("team:notifications.adjustmentPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&(M[se.id]??"").trim()&&Ce(se.id,!1,(M[se.id]??"").trim(),"needs_adjustment"),Fe.key==="Escape"&&T(null)},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-amber-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===se.id||!(M[se.id]??"").trim(),onClick:()=>Ce(se.id,!1,(M[se.id]??"").trim(),"needs_adjustment"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50 transition-colors",children:u("team:notifications.confirmAdjustment")}),n.jsx("button",{onClick:()=>T(null),className:"px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:u("common:cancel")})]})]})]}):n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.commentPlaceholder"),value:M[se.id]??"",onChange:Fe=>D(Je=>({...Je,[se.id]:Fe.target.value})),onKeyDown:Fe=>{Fe.key==="Enter"&&Ce(se.id,!0,ze||void 0,"approve")},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!0,ze||void 0,"approve"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors",children:u("common:approve")}),n.jsx("button",{disabled:w===se.id,onClick:()=>Ce(se.id,!1,ze||void 0,"reject"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay disabled:opacity-50 transition-colors",children:u("common:reject")})]})]})})()]},se.id)}),mt.length>0&&n.jsxs(n.Fragment,{children:[zt.length>0&&n.jsx("div",{className:"px-3 py-1.5 text-[10px] font-medium text-fg-tertiary uppercase tracking-wider bg-surface-overlay/30",children:u("team:notifications.approvalHistory")}),mt.slice(0,50).map(se=>n.jsxs("button",{onClick:()=>te(se),className:"w-full text-left px-3 py-2.5 hover:bg-surface-overlay/50 transition-colors group",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${se.status==="approved"?"bg-green-500":se.status==="cancelled"||se.status==="expired"?"bg-gray-400":"bg-red-500"}`}),Qe(se)&&n.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium shrink-0",children:Qe(se)}),n.jsx("span",{className:"text-xs text-fg-secondary truncate flex-1 group-hover:text-fg-primary",children:se.title}),n.jsx("span",{className:`text-[10px] font-medium shrink-0 ${se.status==="approved"?"text-green-500":se.status==="cancelled"||se.status==="expired"?"text-fg-muted":"text-red-500"}`,children:u(`common:status.${se.status}`,{defaultValue:se.status})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 pl-3.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted truncate",children:ct(se)}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:"·"}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:id(se.respondedAt??se.requestedAt,u)})]}),se.responseComment&&n.jsxs("p",{className:"text-[10px] text-fg-muted mt-0.5 pl-3.5 truncate",children:["“",se.responseComment,"”"]})]},se.id))]})]})),p==="notifications"&&(Q.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noNotifications")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[Q.map(se=>{const fe=q3[se.type]??"text-fg-tertiary";return n.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Pe(se),onKeyDown:$e=>{($e.key==="Enter"||$e.key===" ")&&($e.preventDefault(),Pe(se))},className:`w-full text-left px-3 py-2.5 flex gap-2.5 transition-colors cursor-pointer ${se.read?"opacity-50 hover:opacity-70":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"shrink-0 mt-0.5",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:fe,children:n.jsx("path",{d:ad[se.type]??ad.system})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[!se.read&&n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Af[se.priority]??Af.normal}`}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:se.title})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5 ",children:n.jsx(Gr,{content:se.body,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px] [&_p]:text-fg-tertiary"})}),n.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted",children:id(se.createdAt,u)}),Ef(se,u)&&n.jsx("span",{className:`text-[10px] font-medium ${fe}`,children:Ef(se,u)})]})]})]},se.id)}),_&&n.jsx("div",{className:"py-3 text-center",children:n.jsxs("svg",{className:"animate-spin h-4 w-4 text-fg-tertiary mx-auto",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})})]}))]})]});if(r){const se=["approvals","notifications"],fe=se.indexOf(p),$e=(()=>{let Ne=0,Ze=0;return{onTouchStart:pe=>{Ne=pe.touches[0].clientX,Ze=pe.touches[0].clientY},onTouchEnd:pe=>{const ze=pe.changedTouches[0].clientX-Ne,Fe=pe.changedTouches[0].clientY-Ze;Math.abs(ze)>60&&Math.abs(ze)>Math.abs(Fe)*1.5&&(ze<0&&fe<se.length-1&&y(se[fe+1]),ze>0&&fe>0&&y(se[fe-1]))}}})();return n.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[n.jsx("div",{className:"flex border-b border-border-default shrink-0",children:se.map(Ne=>n.jsx("button",{onClick:()=>y(Ne),className:`flex-1 px-3 py-3 text-sm font-medium transition-colors ${p===Ne?"text-fg-primary border-b-2 border-brand-500":"text-fg-tertiary"}`,children:Ne==="approvals"?n.jsxs(n.Fragment,{children:[u("team:notifications.approvals"),Me>0?` (${Me})`:""]}):n.jsxs(n.Fragment,{children:[u("team:notifications.notifications"),Ae>0?` (${Ae})`:""]})},Ne))}),p==="notifications"&&I>0&&n.jsx("div",{className:"flex justify-end px-3 py-1.5 border-b border-border-default/50 shrink-0",children:n.jsx("button",{onClick:Ye,className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:u("team:notifications.markAllRead")})}),n.jsx("div",{className:"flex-1 overflow-hidden relative",...$e,children:n.jsxs("div",{className:"flex h-full transition-transform duration-300 ease-out",style:{transform:`translateX(-${fe*100}%)`},children:[n.jsx("div",{className:"w-full shrink-0 h-full overflow-y-auto scrollbar-thin",children:j.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noApprovals")}):n.jsxs("div",{className:"divide-y divide-border-default/50",children:[zt.map(Ne=>{const Ze=Ne.details?.command,pe=Ze?Ne.description.replace(/\s*Command:.*$/,""):Ne.description;return n.jsxs("div",{className:"px-3 py-3 space-y-2.5",children:[n.jsxs("div",{className:"cursor-pointer hover:bg-surface-overlay/50 -mx-3 -mt-3 px-3 pt-3 pb-1 rounded-t-md transition-colors",onClick:()=>te(Ne),children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-amber-500 mt-0.5 shrink-0",children:n.jsx("path",{d:ad.approval_request})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[Qe(Ne)&&n.jsx("span",{className:"text-[10px] text-amber-500 font-medium shrink-0",children:Qe(Ne)}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:Ne.title}),n.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:id(Ne.requestedAt,u)})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:Ne.agentName})]})]}),n.jsx("div",{className:"mt-2.5 text-[11px] text-fg-secondary leading-relaxed",children:n.jsx(Gr,{content:pe,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]"})}),Ze&&n.jsx("pre",{className:"text-[11px] text-fg-primary bg-surface-overlay border border-border-default rounded-md px-2.5 py-2 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed mt-2",children:Ze})]}),(()=>{const ze=Ne.details?.subType,Fe=ze==="task"||ze==="requirement"||ze==="requirement_resubmit",Je=Ne.options&&Ne.options.length>0,gt=(M[Ne.id]??"").trim();return Je?n.jsxs("div",{className:"space-y-1.5",children:[Ne.options.map((nt,Et)=>n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,nt.id!=="reject",gt||void 0,nt.id),className:`w-full px-3 py-2 text-left text-[11px] font-medium rounded-md disabled:opacity-50 transition-colors flex items-center gap-2 ${nt.id==="reject"||nt.id==="request_changes"?"border border-border-default text-fg-secondary hover:bg-surface-overlay":"bg-brand-600 text-white hover:bg-brand-700"}`,title:nt.description,children:[n.jsx("span",{className:"w-5 h-5 rounded-full bg-white/20 flex items-center justify-center text-[10px] font-bold shrink-0",children:String.fromCharCode(65+Et)}),nt.label]},nt.id)),n.jsxs("div",{className:"flex gap-1.5 mt-1",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.freeformPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&(M[Ne.id]??"").trim()&&Ce(Ne.id,!0,(M[Ne.id]??"").trim(),"custom")},className:"flex-1 px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsx("button",{disabled:w===Ne.id||!(M[Ne.id]??"").trim(),onClick:()=>Ce(Ne.id,!0,(M[Ne.id]??"").trim(),"custom"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 disabled:opacity-50 transition-colors",children:u("common:send")})]})]}):Fe?n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!0,void 0,"approve"),className:"px-3 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6L9 17l-5-5"})}),u("common:approve")]}),n.jsxs("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!1,void 0,"reject"),className:"px-3 py-1.5 text-[11px] font-medium bg-red-600/80 text-white rounded-md hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]}),u("common:reject")]}),S!==Ne.id&&n.jsxs("button",{disabled:w===Ne.id,onClick:()=>T(Ne.id),className:"px-3 py-1.5 text-[11px] font-medium border border-amber-500/50 text-amber-500 rounded-md hover:bg-amber-500/10 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),u("team:notifications.needsAdjustment")]})]}),S===Ne.id&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",autoFocus:!0,placeholder:u("team:notifications.adjustmentPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&(M[Ne.id]??"").trim()&&Ce(Ne.id,!1,(M[Ne.id]??"").trim(),"needs_adjustment"),nt.key==="Escape"&&T(null)},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-amber-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===Ne.id||!(M[Ne.id]??"").trim(),onClick:()=>Ce(Ne.id,!1,(M[Ne.id]??"").trim(),"needs_adjustment"),className:"px-2.5 py-1.5 text-[11px] font-medium bg-amber-600 text-white rounded-md hover:bg-amber-700 disabled:opacity-50 transition-colors",children:u("team:notifications.confirmAdjustment")}),n.jsx("button",{onClick:()=>T(null),className:"px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:u("common:cancel")})]})]})]}):n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("input",{type:"text",placeholder:u("team:notifications.commentPlaceholder"),value:M[Ne.id]??"",onChange:nt=>D(Et=>({...Et,[Ne.id]:nt.target.value})),onKeyDown:nt=>{nt.key==="Enter"&&Ce(Ne.id,!0,gt||void 0,"approve")},className:"w-full px-2.5 py-1.5 text-[11px] bg-surface-overlay border border-border-default rounded-md text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!0,gt||void 0,"approve"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors",children:u("common:approve")}),n.jsx("button",{disabled:w===Ne.id,onClick:()=>Ce(Ne.id,!1,gt||void 0,"reject"),className:"flex-1 px-2.5 py-1.5 text-[11px] font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay disabled:opacity-50 transition-colors",children:u("common:reject")})]})]})})()]},Ne.id)}),mt.length>0&&n.jsxs(n.Fragment,{children:[zt.length>0&&n.jsx("div",{className:"px-3 py-1.5 text-[10px] font-medium text-fg-tertiary uppercase tracking-wider bg-surface-overlay/30",children:u("team:notifications.approvalHistory")}),mt.slice(0,50).map(Ne=>n.jsxs("button",{onClick:()=>te(Ne),className:"w-full text-left px-3 py-2.5 hover:bg-surface-overlay/50 transition-colors",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Ne.status==="approved"?"bg-green-500":Ne.status==="cancelled"||Ne.status==="expired"?"bg-gray-400":"bg-red-500"}`}),n.jsx("span",{className:"text-xs text-fg-secondary truncate flex-1",children:Ne.title}),n.jsx("span",{className:`text-[10px] font-medium shrink-0 ${Ne.status==="approved"?"text-green-500":Ne.status==="cancelled"||Ne.status==="expired"?"text-fg-muted":"text-red-500"}`,children:u(`common:status.${Ne.status}`,{defaultValue:Ne.status})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 pl-3.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted truncate",children:ct(Ne)}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:"·"}),n.jsx("span",{className:"text-[10px] text-fg-muted shrink-0",children:id(Ne.respondedAt??Ne.requestedAt,u)})]})]},Ne.id))]})]})}),n.jsx("div",{className:"w-full shrink-0 h-full overflow-y-auto scrollbar-thin",children:Q.length===0?n.jsx("div",{className:"p-6 text-center text-xs text-fg-tertiary",children:u("team:notifications.noNotifications")}):n.jsx("div",{className:"divide-y divide-border-default/50",children:Q.slice(0,50).map(Ne=>{const Ze=q3[Ne.type]??"text-fg-tertiary";return n.jsxs("button",{onClick:()=>Pe(Ne),className:`w-full text-left px-3 py-2.5 flex gap-2.5 transition-colors ${Ne.read?"opacity-50 hover:opacity-70":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"shrink-0 mt-0.5",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Ze,children:n.jsx("path",{d:ad[Ne.type]??ad.system})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[!Ne.read&&n.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Af[Ne.priority]??Af.normal}`}),n.jsx("span",{className:"text-xs text-fg-primary font-medium truncate",children:Ne.title})]}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5 ",children:n.jsx(Gr,{content:Ne.body,className:"text-[11px] [&_h1]:text-xs [&_h2]:text-[11px] [&_h3]:text-[11px] [&_p]:text-[11px] [&_li]:text-[11px] [&_p]:text-fg-tertiary"})}),n.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[n.jsx("span",{className:"text-[10px] text-fg-muted",children:id(Ne.createdAt,u)}),Ef(Ne,u)&&n.jsx("span",{className:`text-[10px] font-medium ${Ze}`,children:Ef(Ne,u)})]})]})]},Ne.id)})})})]})})]})}if(a){const se=d||"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9 M13.73 21a2 2 0 0 1-3.46 0";return n.jsxs(n.Fragment,{children:[n.jsxs("button",{ref:B,onClick:()=>{h(!m),m||J()},title:e?l||u("team:notifications.bellTitle"):void 0,className:`w-full flex items-center ${e?"flex-col justify-center px-1 py-1.5 gap-0.5":"gap-3 px-3 py-[7px]"} rounded-xl text-[13px] mb-0.5 transition-all relative ${m||i?"bg-brand-600 text-white shadow-sm shadow-brand-900/30 font-medium":"text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary"}`,children:[n.jsx("svg",{width:e?16:18,height:e?16:18,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:se})}),e?n.jsx("span",{className:"text-[9px] leading-tight truncate w-full text-center",children:l}):n.jsx("span",{className:"truncate",children:l}),He>0&&n.jsx("span",{className:`absolute ${e?"top-0.5 right-1":"top-1 left-[22px]"} min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center leading-none`,children:He>99?u("common:badgeOverLimit"):He})]}),m&&lc.createPortal(n.jsx("div",{ref:R,className:"fixed bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-[9999] flex flex-col overflow-hidden",style:{top:U.top,left:U.left,width:U.width,maxHeight:U.maxHeight},children:be}),document.body)]})}return n.jsxs(n.Fragment,{children:[n.jsxs("button",{ref:B,onClick:()=>{h(!m),m||J()},className:`relative flex items-center justify-center rounded-md transition-colors ${e?"w-8 h-8":"w-7 h-7"} ${m?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-overlay"}`,title:u("team:notifications.bellTitle"),children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),n.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]}),He>0&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center leading-none",children:He>99?u("common:badgeOverLimit"):He})]}),m&&lc.createPortal(n.jsx("div",{ref:R,className:"fixed bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-[9999] flex flex-col overflow-hidden",style:{top:U.top,left:U.left,width:U.width,maxHeight:U.maxHeight},children:be}),document.body)]})}function Fre({authUser:e}){const{t}=ft("nav"),r=Ds();return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-4 h-14",children:[r&&n.jsx(gc,{}),n.jsx("h2",{className:"text-base font-bold",children:t("notifications")})]}),n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(nC,{collapsed:!1,userId:e?.id,embeddedMode:!0})})]})}function qre(){const{t:e}=ft(["common","home","work"]),[t,r]=x.useState(""),[s,a]=x.useState("all"),[i,l]=x.useState({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),[d,u]=x.useState(!1),[m,h]=x.useState(!1),p=x.useRef(null),y=x.useRef(void 0);x.useEffect(()=>{setTimeout(()=>p.current?.focus(),100)},[]);const g=x.useCallback(async w=>{if(!w.trim()){l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),h(!1);return}u(!0),h(!0);const N=w.toLowerCase();try{const[S,T,M,D,I]=await Promise.allSettled([le.agents.list(),le.tasks.list({search:w,pageSize:20}),le.requirements.list(),le.projects.list(),le.deliverables.search({q:w,limit:20})]),$=S.status==="fulfilled"?S.value.agents.filter(F=>F.name?.toLowerCase().includes(N)||F.role?.toLowerCase().includes(N)):[],B=T.status==="fulfilled"?T.value.tasks:[],R=M.status==="fulfilled"?M.value.requirements.filter(F=>F.title?.toLowerCase().includes(N)||F.description?.toLowerCase().includes(N)):[],U=D.status==="fulfilled"?D.value.projects.filter(F=>F.name?.toLowerCase().includes(N)||F.description?.toLowerCase().includes(N)):[],W=I.status==="fulfilled"?I.value.results:[];l({agents:$,tasks:B,requirements:R,projects:U,deliverables:W})}catch{l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]})}finally{u(!1)}},[]),v=w=>{r(w),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>g(w),400)},j=[{id:"all",label:e("common:all",{defaultValue:"全部"})},{id:"agents",label:e("common:agents",{defaultValue:"智能体"})},{id:"tasks",label:e("common:tasks",{defaultValue:"任务"})},{id:"requirements",label:e("common:requirements",{defaultValue:"需求"})},{id:"projects",label:e("common:projects",{defaultValue:"项目"})},{id:"deliverables",label:e("common:deliverables",{defaultValue:"交付物"})}],C=i.agents.length>0||i.tasks.length>0||i.requirements.length>0||i.projects.length>0||i.deliverables.length>0;return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n.jsxs("div",{className:"shrink-0 px-4 pt-4 pb-2 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>pt.navigate(Te.HOME),className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors shrink-0",children:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M19 12H5"}),n.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),n.jsxs("div",{className:"flex-1 relative",children:[n.jsxs("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg-tertiary",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("input",{ref:p,value:t,onChange:w=>v(w.target.value),placeholder:e("common:search"),className:"w-full bg-surface-elevated border border-border-default rounded-xl pl-9 pr-3 py-2.5 text-sm text-fg-primary placeholder:text-fg-tertiary focus:border-brand-500 focus:outline-none transition-colors"}),t&&n.jsx("button",{onClick:()=>{r(""),l({agents:[],tasks:[],requirements:[],projects:[],deliverables:[]}),h(!1),p.current?.focus()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-fg-tertiary hover:text-fg-secondary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),n.jsx("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:j.map(w=>n.jsx("button",{onClick:()=>a(w.id),className:`px-3 py-1.5 text-xs rounded-lg whitespace-nowrap transition-colors ${s===w.id?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:text-fg-primary"}`,children:w.label},w.id))})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:[d&&n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:e("common:loading")})}),!d&&m&&!C&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-3",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:e("common:noResults",{defaultValue:"没有找到相关结果"})})]}),!d&&C&&n.jsxs("div",{className:"space-y-4",children:[(s==="all"||s==="agents")&&i.agents.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:agents",{defaultValue:"智能体"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.agents.slice(0,8):i.agents).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.TEAM,{agentId:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx(Sr,{name:w.name||"Agent",avatarUrl:w.avatarUrl,size:32}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:w.name}),n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:w.role||w.status})]}),n.jsx(Ure,{status:w.status})]},w.id))}),s==="all"&&i.agents.length>8&&n.jsxs("button",{onClick:()=>a("agents"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.agents.length,")"]})]}),(s==="all"||s==="tasks")&&i.tasks.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:tasks",{defaultValue:"任务"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.tasks.slice(0,8):i.tasks).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{openTask:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx(Vre,{status:w.status}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.status," · ",w.priority||""]})]})]},w.id))}),s==="all"&&i.tasks.length>8&&n.jsxs("button",{onClick:()=>a("tasks"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.tasks.length,")"]})]}),(s==="all"||s==="requirements")&&i.requirements.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:requirements",{defaultValue:"需求"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.requirements.slice(0,8):i.requirements).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{openRequirement:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${w.status==="approved"?"text-green-500 bg-green-500/15":w.status==="pending"?"text-amber-500 bg-amber-500/15":w.status==="rejected"?"text-red-500 bg-red-500/15":"text-fg-tertiary bg-surface-elevated"}`,children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),n.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.status," · ",w.priority||""]})]})]},w.id))}),s==="all"&&i.requirements.length>8&&n.jsxs("button",{onClick:()=>a("requirements"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.requirements.length,")"]})]}),(s==="all"||s==="projects")&&i.projects.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:projects",{defaultValue:"项目"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.projects.slice(0,8):i.projects).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.WORK,{projectId:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-teal-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-teal-500",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.name}),w.description&&n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:w.description})]})]},w.id))}),s==="all"&&i.projects.length>8&&n.jsxs("button",{onClick:()=>a("projects"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.projects.length,")"]})]}),(s==="all"||s==="deliverables")&&i.deliverables.length>0&&n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:e("common:deliverables",{defaultValue:"交付物"})}),n.jsx("div",{className:"space-y-1",children:(s==="all"?i.deliverables.slice(0,8):i.deliverables).map(w=>n.jsxs("button",{onClick:()=>pt.navigate(Te.DELIVERABLES,{openDeliverable:w.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors text-left",children:[n.jsx("div",{className:"w-8 h-8 rounded-lg bg-purple-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-purple-500",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:w.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[w.type," · ",w.status]})]})]},w.id))}),s==="all"&&i.deliverables.length>8&&n.jsxs("button",{onClick:()=>a("deliverables"),className:"mt-1 w-full text-xs text-brand-500 hover:text-brand-400 py-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:[e("common:showAll",{defaultValue:"查看全部"})," (",i.deliverables.length,")"]})]})]}),!d&&!m&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-3",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:e("common:search")})]})]})]})}function Ure({status:e}){const t=e==="active"||e==="idle"?"bg-green-500":e==="working"||e==="busy"?"bg-blue-500":e==="paused"?"bg-amber-500":"bg-gray-400";return n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`})}function Vre({status:e}){const t=e==="completed"?"text-green-500 bg-green-500/15":e==="in_progress"?"text-blue-500 bg-blue-500/15":e==="pending"?"text-amber-500 bg-amber-500/15":"text-fg-tertiary bg-surface-elevated";return n.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${t}`,children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 11l3 3L22 4"}),n.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})})}function Kre({d:e,size:t=18}){return n.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:e})})}function Wre({currentPage:e,onNavigate:t,authUser:r,collapsed:s,onToggleCollapse:a}){const{t:i}=ft(["nav","common"]);return n.jsxs("aside",{className:"h-dvh bg-surface-secondary flex flex-col shrink-0 overflow-hidden rounded-r-2xl",children:[n.jsx("div",{className:`flex items-center ${s?"px-2 py-3.5 justify-center":"px-4 h-14 justify-between"}`,children:n.jsxs("button",{onClick:a,title:i(s?"sidebar.expandSidebar":"sidebar.collapseSidebar"),className:"flex items-center gap-2.5 min-w-0 group",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-8 h-8 rounded-lg shadow-md shadow-black/30 shrink-0 group-hover:ring-2 group-hover:ring-brand-500/40 transition-all"}),!s&&n.jsx("span",{className:"text-[15px] font-bold tracking-tight text-fg-primary whitespace-nowrap",children:"Markus"})]})}),n.jsx("nav",{className:`${s?"p-1":"px-3 py-2"} flex-1 overflow-y-auto scrollbar-thin`,children:j_.map((l,d)=>{const u=i(`sections.${l.key}`);return n.jsx("div",{children:n.jsxs("div",{className:d>0?"mt-3":"",children:[!s&&u&&n.jsx("div",{className:"px-3 py-1.5 mb-1 text-[10px] font-semibold text-fg-muted uppercase tracking-[0.1em]",children:u}),s&&d>0&&n.jsx("div",{className:"my-3"}),N_.filter(m=>m.section===l.key).map(m=>{if(m.id===Te.NOTIFICATIONS)return n.jsx(nC,{sidebarMode:!0,collapsed:s,userId:r?.id,label:i(m.id),iconPath:fb[m.id],isActive:e===m.id},m.id);const h=e===m.id;return n.jsxs("button",{onClick:()=>t(m.id),title:s?i(m.id):void 0,className:`w-full flex items-center ${s?"flex-col justify-center px-1 py-1.5 gap-0.5":"gap-3 px-3 py-[7px]"} rounded-xl text-[13px] mb-0.5 transition-all ${h?"bg-brand-600 text-white shadow-sm shadow-brand-900/30 font-medium":"text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary"}`,children:[n.jsx(Kre,{d:fb[m.id]??"",size:s?16:18}),s?n.jsx("span",{className:"text-[9px] leading-tight truncate w-full text-center",children:i(m.id)}):n.jsx("span",{className:"truncate",children:i(m.id)})]},m.id)})]})},l.key)})}),!s&&n.jsxs("div",{className:"px-4 pb-2 text-[10px] text-fg-muted",children:["v","0.7.11"]})]})}function Gre({currentPage:e,onNavigate:t,userId:r}){const{t:s}=ft("nav"),[a,i]=x.useState(0),{counts:l}=WS({enabled:!0}),d=x.useMemo(()=>{let m=0;for(const h of Object.values(l))m+=h;return m},[l]),u=x.useCallback(async()=>{try{const m=await le.notifications.list(r,!1);i(m.unreadCount??m.notifications.filter(h=>!h.read).length)}catch{}},[r]);return x.useEffect(()=>{u();const m=setInterval(u,15e3),h=()=>u();return window.addEventListener("markus:notifications-changed",h),()=>{clearInterval(m),window.removeEventListener("markus:notifications-changed",h)}},[u]),n.jsx("nav",{className:"fixed bottom-0 left-0 right-0 z-50 bg-surface-secondary flex items-stretch h-14 safe-area-bottom",children:S_.map(m=>{const h=m.group.includes(e),p=m.id===Te.NOTIFICATIONS,y=m.id===Te.TEAM;return n.jsxs("button",{onClick:()=>t(m.id),className:`flex-1 flex flex-col items-center justify-center gap-0.5 transition-colors ${h?"text-brand-500":"text-fg-tertiary active:text-fg-secondary"}`,children:[n.jsxs("div",{className:"relative",children:[n.jsx("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:h?2:1.75,strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:n.jsx("path",{d:fb[m.id]})}),p&&a>0&&n.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-[16px] h-4 px-1 flex items-center justify-center bg-red-500 text-white text-[9px] font-bold rounded-full leading-none",children:a>99?"99+":a}),y&&d>0&&n.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-[16px] h-4 px-1 flex items-center justify-center bg-red-500 text-white text-[9px] font-bold rounded-full leading-none",children:d>99?"99+":d})]}),n.jsx("span",{className:`text-[10px] leading-tight ${h?"font-semibold":""}`,children:s(m.id)})]},m.id)})})}const rC=["builder","agents","teams","skills"];function Yre(){const e=localStorage.getItem("markus_nav_storeTab");return e&&(localStorage.removeItem("markus_nav_storeTab"),rC.includes(e))?e:"builder"}function Xre({authUser:e}){const{t}=ft(["nav","common"]),r=x.useMemo(()=>[{id:"builder",label:t("nav:builder")},{id:"agents",label:t("nav:tabs.agents")},{id:"teams",label:t("nav:tabs.teams")},{id:"skills",label:t("nav:tabs.skills")}],[t]),[s,a]=x.useState(Yre),i=Sl(r,s,a);return x.useEffect(()=>{const l=d=>{const u=d.detail;u.params?.storeTab&&rC.includes(u.params.storeTab)&&a(u.params.storeTab)};return window.addEventListener("markus:navigate",l),()=>window.removeEventListener("markus:navigate",l)},[]),n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",onTouchStart:i.onTouchStart,onTouchEnd:i.onTouchEnd,children:[n.jsxs("div",{className:"flex items-center shrink-0 overflow-x-auto scrollbar-hide",children:[n.jsx(gc,{className:"ml-2"}),r.map(l=>n.jsx("button",{onClick:()=>a(l.id),className:`flex-1 min-w-0 px-3 py-2.5 text-xs font-medium text-center whitespace-nowrap transition-colors border-b-2 ${s===l.id?"border-brand-500 text-brand-500":"border-transparent text-fg-tertiary"}`,children:l.label},l.id))]}),n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[s==="builder"&&n.jsx(QS,{}),s==="agents"&&n.jsx(e7,{authUser:e}),s==="teams"&&n.jsx(r7,{}),s==="skills"&&n.jsx(s7,{})]})]})}const ob="profile",U3="llm",V3="search";function Qre({onComplete:e,theme:t,onThemeChange:r,skipProfile:s}){const{t:a}=ft(["onboarding","common"]),[i,l]=x.useState(0),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(""),[g,v]=x.useState(""),[j,C]=x.useState(!1),[w,N]=x.useState(""),[S,T]=x.useState(!1),[M,D]=x.useState(null);x.useEffect(()=>{le.auth.me().then(({user:qe})=>{qe.name&&u(qe.name),qe.email&&h(qe.email),qe.avatarUrl&&D(qe.avatarUrl)}).catch(()=>{})},[]);const[I,$]=x.useState(null),[B,R]=x.useState(!1),[U,W]=x.useState({}),[F,L]=x.useState(!1),[z,E]=x.useState(!1),[_,G]=x.useState([]),[V,O]=x.useState(null),[q,J]=x.useState(!0),[H,Z]=x.useState(""),Y=x.useRef(!1),[ee,ae]=x.useState({}),[Q,me]=x.useState({}),[Ae,Me]=x.useState("anthropic"),[He,je]=x.useState(""),[xe,Pe]=x.useState(!1),[Ce,Ye]=x.useState([]),[Qe,ct]=x.useState(""),[st,zt]=x.useState(""),[mt,te]=x.useState(null),[de,be]=x.useState({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),[se,fe]=x.useState(!1),[$e,Ne]=x.useState(!1),[Ze,pe]=x.useState(null),ze=x.useRef(!1),Fe=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`});x.useEffect(()=>{fetch("/api/settings/llm").then(qe=>qe.ok?qe.json():null).then(qe=>{if(qe?.providers){const St=Object.entries(qe.providers).filter(([,_e])=>_e.configured).map(([_e,Tt])=>({name:_e,displayName:Tt.displayName??_e,model:Tt.model??"",apiKeyPreview:Tt.apiKeyPreview}));St.length>0&&(E(!0),G(St))}qe?.defaultProvider&&Z(qe.defaultProvider),typeof qe?.autoFallback=="boolean"&&J(qe.autoFallback)}).catch(()=>{})},[]);const Je=s?2:3;x.useEffect(()=>{i===Je&&!Y.current&&!z&&(Y.current=!0,nt())},[i,z,Je]);const gt=s?3:4;x.useEffect(()=>{i===gt&&!ze.current&&(ze.current=!0,Rt())},[i,gt]);const nt=async()=>{R(!0);try{const qe=await fetch("/api/settings/env-models",{headers:Fe()});if(qe.ok){const St=await qe.json();if($(St),St.detected.length>0){const _e={},Tt={};for(const Ot of St.detected)_e[Ot.provider]=!0,Tt[Ot.provider]=Ot.model;W(_e),me(Tt);for(const Ot of St.detected)le.modelCatalog.getByProvider(Ot.provider).then(Gt=>{ae(Tn=>({...Tn,[Ot.provider]:Gt.models}))}).catch(()=>{})}}}catch{}finally{R(!1)}},Et=async()=>{if(He.trim()){Pe(!0),zt(""),Ye([]);try{const qe=await le.modelCatalog.validateKey(Ae,He.trim());qe.valid?(Ye(qe.models),qe.models.length>0&&ct(qe.models[0].id)):(zt(qe.error||"Invalid API key"),qe.models.length>0&&(Ye(qe.models),ct(qe.models[0].id)))}catch(qe){zt(qe instanceof Error?qe.message:"Validation failed")}finally{Pe(!1)}}},dt=async()=>{if(Qe){L(!0),O(null);try{const qe=await fetch("/api/settings/llm/providers",{method:"POST",headers:Fe(),body:JSON.stringify({name:Ae,apiKey:He.trim(),model:Qe})});if(qe.ok)E(!0),Z(Ae),G([{name:Ae,displayName:Ae,model:Qe}]),O({type:"ok",text:`Provider ${Ae} configured successfully`});else{const St=await qe.json();O({type:"err",text:St.error||"Failed to add provider"})}}catch{O({type:"err",text:"Network error"})}finally{L(!1)}}},Ve=async()=>{if(!I)return;const qe=I.detected.filter(St=>U[St.provider]);if(qe.length!==0){L(!0),O(null);try{const St=await fetch("/api/settings/env-models",{method:"POST",headers:Fe(),body:JSON.stringify({providers:qe.map(_e=>({provider:_e.provider,model:Q[_e.provider]||_e.model,baseUrl:_e.baseUrl,enabled:!0}))})});if(St.ok){const _e=await St.json();if(_e.settings?.providers){const Ot=Object.entries(_e.settings.providers).filter(([,Gt])=>Gt.configured).map(([Gt,Tn])=>({name:Gt,displayName:Tn.displayName??Gt,model:Tn.model??"",apiKeyPreview:Tn.apiKeyPreview}));G(Ot)}else G(qe.map(Ot=>({name:Ot.provider,displayName:Ot.displayName,model:Ot.model,apiKeyPreview:Ot.apiKeyPreview})));const Tt=_e.settings?.defaultProvider||_e.applied[0]||qe[0]?.provider||"";Z(Tt),Tt&&fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({defaultProvider:Tt})}).catch(()=>{}),O({type:"ok",text:_e.message}),E(!0)}else O({type:"err",text:a("llm.failedToApply")})}catch{O({type:"err",text:a("common:networkError")})}finally{L(!1)}}},Rt=async()=>{try{const qe=await fetch("/api/settings/search",{headers:Fe()});if(qe.ok){const St=await qe.json();te(St),St&&(St.serper.configured||St.tavily.configured||St.bing.configured||St.google.configured||St.serpapi.configured||St.brave.configured||St.exa.configured||St.bocha.configured)&&Ne(!0)}}catch{}},un=async()=>{if(de.serperApiKey||de.tavilyApiKey||de.bingApiKey||de.googleSearchApiKey||de.googleSearchCx||de.serpApiKey||de.braveApiKey||de.exaApiKey||de.bochaApiKey){fe(!0),pe(null);try{const St={};de.serperApiKey&&(St.serperApiKey=de.serperApiKey),de.tavilyApiKey&&(St.tavilyApiKey=de.tavilyApiKey),de.bingApiKey&&(St.bingApiKey=de.bingApiKey),de.googleSearchApiKey&&(St.googleSearchApiKey=de.googleSearchApiKey),de.googleSearchCx&&(St.googleSearchCx=de.googleSearchCx),de.serpApiKey&&(St.serpApiKey=de.serpApiKey),de.braveApiKey&&(St.braveApiKey=de.braveApiKey),de.exaApiKey&&(St.exaApiKey=de.exaApiKey),de.bochaApiKey&&(St.bochaApiKey=de.bochaApiKey);const _e=await fetch("/api/settings/search",{method:"POST",headers:Fe(),body:JSON.stringify(St)});if(_e.ok){const Tt=await _e.json();te(Tt),Ne(!0),be({serperApiKey:"",tavilyApiKey:"",bingApiKey:"",googleSearchApiKey:"",googleSearchCx:"",serpApiKey:"",braveApiKey:"",exaApiKey:"",bochaApiKey:""}),pe({type:"ok",text:a("search.saved")})}else pe({type:"err",text:a("search.failedToSave")})}catch{pe({type:"err",text:a("common:networkError")})}finally{fe(!1)}}},yn=async()=>{if(N(""),!d.trim()){N(a("profile.errors.nameRequired"));return}if(!m.trim()){N(a("profile.errors.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){N(a("profile.errors.emailInvalid"));return}if(p&&p.length<6){N(a("profile.errors.passwordTooShort"));return}if(p&&p!==g){N(a("profile.errors.passwordMismatch"));return}C(!0);try{await le.auth.updateProfile(d.trim(),m.trim()),p&&await le.auth.changePassword("",p),T(!0)}catch{N(a("profile.errors.saveFailed"))}finally{C(!1)}},sn=[{value:"system",label:a("theme.system"),icon:"💻",desc:a("theme.systemDesc")},{value:"light",label:a("theme.light"),icon:"☀️",desc:a("theme.lightDesc")},{value:"dark",label:a("theme.dark"),icon:"🌊",desc:a("theme.darkDesc")},{value:"cyberpunk",label:a("theme.cyberpunk"),icon:"🔮",desc:a("theme.cyberpunkDesc")},{value:"mono",label:a("theme.mono"),icon:"⬛",desc:a("theme.monoDesc")}],In=[{id:"welcome",title:a("welcome.title"),subtitle:a("welcome.subtitle"),content:n.jsxs("div",{className:"space-y-4 text-fg-secondary text-sm leading-relaxed",children:[n.jsx("p",{className:"text-fg-secondary",children:n.jsx(n0,{i18nKey:"welcome.description",ns:"onboarding",components:{strong:n.jsx("strong",{className:"text-fg-primary"})}})}),n.jsx("div",{className:"grid grid-cols-2 gap-3 mt-6",children:[[a("welcome.features.operation"),a("welcome.features.operationDesc")],[a("welcome.features.collaboration"),a("welcome.features.collaborationDesc")],[a("welcome.features.memory"),a("welcome.features.memoryDesc")],[a("welcome.features.anyLlm"),a("welcome.features.anyLlmDesc")]].map(([qe,St])=>n.jsxs("div",{className:"bg-surface-elevated/50 rounded-lg p-3",children:[n.jsx("div",{className:"font-medium text-fg-primary text-xs",children:qe}),n.jsx("div",{className:"text-fg-secondary text-xs mt-1",children:St})]},qe))})]})},{id:ob,title:a("profile.title"),subtitle:a("profile.subtitle"),content:S?n.jsxs("div",{className:"flex items-center gap-3 bg-green-500/10 border border-green-500/30 rounded-xl p-4",children:[n.jsx("span",{className:"text-green-600 text-lg",children:"✓"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-sm font-medium text-green-600",children:a("profile.saved")}),n.jsxs("div",{className:"text-xs text-fg-secondary mt-0.5",children:[d," · ",m]})]})]}):n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"flex justify-center",children:n.jsx(g6,{currentUrl:M,name:d,size:64,targetType:"user"})}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("label",{className:"text-xs text-fg-tertiary font-medium",children:[a("profile.nameLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{type:"text",value:d,onChange:qe=>u(qe.target.value),placeholder:a("profile.namePlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",autoFocus:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsxs("label",{className:"text-xs text-fg-tertiary font-medium",children:[a("profile.emailLabel")," ",n.jsx("span",{className:"text-red-500",children:"*"})]}),n.jsx("input",{type:"email",value:m,onChange:qe=>h(qe.target.value),placeholder:a("profile.emailPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:a("profile.newPasswordLabel")}),n.jsx("input",{type:"password",value:p,onChange:qe=>y(qe.target.value),placeholder:a("profile.newPasswordPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),p&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:a("profile.confirmPasswordLabel")}),n.jsx("input",{type:"password",value:g,onChange:qe=>v(qe.target.value),placeholder:a("profile.confirmPasswordPlaceholder"),className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),w&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:w}),n.jsx("button",{onClick:()=>{yn()},disabled:j||!d.trim()||!m.trim(),className:"w-full px-4 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a(j?"common:saving":"profile.saveProfile")})]})},{id:"theme",title:a("theme.title"),subtitle:a("theme.subtitle"),content:n.jsx("div",{className:"grid grid-cols-3 gap-3",children:sn.map(qe=>n.jsxs("button",{onClick:()=>r(qe.value),className:`flex flex-col items-center gap-2 rounded-xl border-2 p-5 transition-all ${t===qe.value?"border-brand-500 bg-brand-500/10":"border-border-default hover:border-fg-tertiary bg-surface-elevated/30"}`,children:[n.jsx("span",{className:"text-2xl",children:qe.icon}),n.jsx("span",{className:"text-sm font-medium text-fg-primary",children:qe.label}),n.jsx("span",{className:"text-[11px] text-fg-tertiary leading-tight text-center",children:qe.desc})]},qe.value))})},{id:U3,title:a("llm.title"),subtitle:a("llm.subtitle"),content:z?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-sm font-medium mb-1",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("llm.configured")})]}),_.length>1&&n.jsx("div",{className:"text-xs text-fg-secondary mb-1",children:a("llm.selectDefault")}),_.map(qe=>{const St=H===qe.name;return n.jsxs("button",{onClick:async()=>{const _e=H;Z(qe.name);try{await fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({defaultProvider:qe.name})})}catch{Z(_e)}},className:`w-full flex items-center justify-between rounded-lg px-4 py-2.5 text-left transition-colors ${St?"bg-brand-500/15 border-2 border-brand-500":"bg-green-500/10 border border-green-500/30 hover:border-brand-500/50"}`,children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-3.5 h-3.5 rounded-full border-2 flex items-center justify-center shrink-0 ${St?"border-brand-500":"border-fg-tertiary"}`,children:St&&n.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.displayName}),qe.model&&n.jsx("span",{className:"text-xs text-fg-tertiary",children:qe.model}),St&&n.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:a("llm.default")})]}),qe.apiKeyPreview&&n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:qe.apiKeyPreview})]},qe.name)}),n.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:a("llm.configuredHint")}),n.jsxs("div",{className:"flex items-center justify-between bg-surface-elevated/40 rounded-lg px-4 py-3 mt-3",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-primary",children:a("llm.autoFallback")}),n.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:a("llm.autoFallbackDesc")})]}),n.jsx("button",{onClick:async()=>{const qe=!q;J(qe);try{await fetch("/api/settings/llm",{method:"POST",headers:Fe(),body:JSON.stringify({autoFallback:qe})})}catch{J(!qe)}},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 ${q?"bg-green-500":"bg-gray-600"}`,children:n.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${q?"translate-x-4":"translate-x-1"}`})})]})]}):n.jsxs("div",{className:"space-y-4",children:[B&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary animate-pulse",children:[n.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),a("llm.detectingKeys")]}),I&&I.detected.length>0&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-xs font-medium",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("llm.fromEnv")})]}),I.detected.map(qe=>n.jsxs("div",{className:"border border-border-default rounded-lg overflow-hidden",children:[n.jsxs("label",{className:"flex items-center gap-3 px-3 py-2.5 bg-surface-elevated/40 cursor-pointer hover:bg-surface-elevated/60 transition-colors",children:[n.jsx("input",{type:"checkbox",checked:U[qe.provider]??!1,onChange:St=>W({...U,[qe.provider]:St.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.displayName})}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:qe.apiKeyPreview})]}),U[qe.provider]&&n.jsx("div",{className:"px-3 py-2 border-t border-border-default",children:n.jsx(ch,{provider:qe.provider,models:ee[qe.provider]??[],selectedModel:Q[qe.provider]||qe.model,onSelect:St=>me(_e=>({..._e,[qe.provider]:St})),loading:!ee[qe.provider],compact:!0,maxVisible:4})})]},qe.provider)),I.detected.filter(qe=>U[qe.provider]).length>1&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs text-fg-secondary",children:"Default:"}),n.jsx("select",{value:H||I.detected[0]?.provider||"",onChange:qe=>Z(qe.target.value),className:"px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary",children:I.detected.filter(qe=>U[qe.provider]).map(qe=>n.jsx("option",{value:qe.provider,children:qe.displayName},qe.provider))})]}),n.jsx("button",{onClick:()=>{Ve()},disabled:F||Object.values(U).filter(Boolean).length===0,className:"w-full px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:F?a("common:applying"):a("llm.applyProviders",{count:Object.values(U).filter(Boolean).length})})]}),I&&I.detected.length===0&&!B&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"text-xs text-fg-tertiary",children:n.jsx(n0,{i18nKey:"llm.noKeysFound",ns:"onboarding",components:{code:n.jsx("code",{className:"text-fg-secondary"})}})}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"text-xs text-fg-secondary",children:"Provider"}),n.jsx("select",{value:Ae,onChange:qe=>{Me(qe.target.value),Ye([]),zt(""),ct("")},className:"w-full px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary",children:Bu.map(qe=>n.jsx("option",{value:qe.id,children:qe.label},qe.id))})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"text-xs text-fg-secondary",children:"API Key"}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"password",value:He,onChange:qe=>je(qe.target.value),onBlur:()=>{He.trim().length>=8&&Et()},onKeyDown:qe=>{qe.key==="Enter"&&He.trim().length>=8&&Et()},placeholder:"sk-...",className:"flex-1 px-3 py-2 bg-surface-overlay border border-border-default rounded-lg text-sm text-fg-primary placeholder:text-fg-tertiary"}),n.jsx("button",{onClick:()=>{Et()},disabled:xe||!He.trim(),className:"px-3 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-xs rounded-lg transition-colors whitespace-nowrap",children:xe?"Validating...":"Validate"})]})]}),st&&n.jsx("div",{className:"text-xs px-3 py-2 rounded-lg bg-red-500/10 text-red-500 border border-red-500/30",children:st}),Ce.length>0&&n.jsxs("div",{className:"border border-border-default rounded-lg p-3",children:[n.jsx("div",{className:"text-xs text-fg-secondary mb-2",children:"Select Model"}),n.jsx(ch,{provider:Ae,models:Ce,selectedModel:Qe,onSelect:ct,compact:!0,maxVisible:5}),n.jsx("button",{onClick:()=>{dt()},disabled:F||!Qe,className:"w-full mt-3 px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:F?a("common:applying"):"Activate Provider"})]})]}),V&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${V.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:V.text})]})},{id:V3,title:a("search.title"),subtitle:a("search.subtitle"),content:$e?n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 text-green-600 text-sm font-medium mb-1",children:[n.jsx("span",{children:"✓"}),n.jsx("span",{children:a("search.saved")})]}),mt&&[{id:"serper",label:a("search.serper")},{id:"tavily",label:a("search.tavily")},{id:"bing",label:a("search.bing")},{id:"google",label:a("search.google")},{id:"serpapi",label:a("search.serpapi")},{id:"brave",label:a("search.brave")},{id:"exa",label:a("search.exa")},{id:"bocha",label:a("search.bocha")}].filter(qe=>mt[qe.id]?.configured).map(qe=>n.jsxs("div",{className:"flex items-center justify-between bg-green-500/10 border border-green-500/30 rounded-lg px-4 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-sm text-fg-primary font-medium",children:qe.label})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:mt[qe.id].preview})]},qe.id)),n.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:a("search.savedHint")})]}):n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"text-xs text-fg-secondary",children:a("search.description")}),mt&&(mt.serper.configured||mt.tavily.configured||mt.bing.configured||mt.google.configured||mt.serpapi.configured||mt.brave.configured||mt.exa.configured||mt.bocha.configured)&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-xs text-fg-secondary uppercase tracking-wider",children:a("search.detected")}),[{id:"serper",label:a("search.serper")},{id:"tavily",label:a("search.tavily")},{id:"bing",label:a("search.bing")},{id:"google",label:a("search.google")},{id:"serpapi",label:a("search.serpapi")},{id:"brave",label:a("search.brave")},{id:"exa",label:a("search.exa")},{id:"bocha",label:a("search.bocha")}].filter(qe=>mt[qe.id]?.configured).map(qe=>n.jsxs("div",{className:"flex items-center justify-between bg-green-500/10 border border-green-500/30 rounded-lg px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"}),n.jsx("span",{className:"text-sm text-fg-primary",children:qe.label})]}),n.jsx("code",{className:"text-[10px] text-fg-tertiary",children:mt[qe.id].preview})]},qe.id))]}),n.jsx("div",{className:"space-y-3",children:[{label:a("search.serper"),field:"serperApiKey"},{label:a("search.tavily"),field:"tavilyApiKey"},{label:a("search.bing"),field:"bingApiKey"},{label:a("search.google"),field:"googleSearchApiKey"},{label:a("search.serpapi"),field:"serpApiKey"},{label:a("search.brave"),field:"braveApiKey"},{label:a("search.exa"),field:"exaApiKey"},{label:a("search.bocha"),field:"bochaApiKey"}].map(qe=>n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:qe.label}),n.jsx("input",{type:"password",value:de[qe.field],onChange:St=>be({...de,[qe.field]:St.target.value}),placeholder:a("search.apiKeyPlaceholder"),className:"w-full px-4 py-2 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]},qe.field))}),n.jsx("button",{onClick:()=>{un()},disabled:se||!de.serperApiKey&&!de.tavilyApiKey&&!de.bingApiKey&&!de.googleSearchApiKey&&!de.serpApiKey&&!de.braveApiKey&&!de.exaApiKey&&!de.bochaApiKey,className:"w-full px-4 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",children:a(se?"search.saving":"search.save")}),Ze&&n.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${Ze.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:Ze.text})]})},{id:"done",title:a("done.title"),subtitle:a("done.subtitle"),content:n.jsx("div",{className:"space-y-2 text-fg-secondary text-sm",children:[[a("done.chat"),a("done.chatDesc")],[a("done.projects"),a("done.projectsDesc")],[a("done.builder"),a("done.builderDesc")],[a("done.settings"),a("done.settingsDesc")]].map(([qe,St])=>n.jsxs("div",{className:"flex gap-3 bg-surface-elevated/50 rounded-lg p-3",children:[n.jsx("div",{className:"text-brand-500 mt-0.5 shrink-0",children:"→"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium text-fg-primary text-xs",children:qe}),n.jsx("div",{className:"text-fg-secondary text-xs",children:St})]})]},qe))})}],jn=s?In.filter(qe=>qe.id!==ob):In,Vt=jn.findIndex(qe=>qe.id===ob),mn=jn.findIndex(qe=>qe.id===U3),Vn=jn.findIndex(qe=>qe.id===V3),Xn=()=>{i===Vt&&Vt>=0&&!S||(i<jn.length-1?l(i+1):e())},Rr=jn[i];return n.jsx("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4",children:n.jsx("div",{className:"w-full max-w-lg",children:n.jsxs("div",{className:"bg-surface-elevated rounded-2xl p-8",children:[n.jsx("div",{className:"flex gap-1.5 mb-8",children:jn.map((qe,St)=>n.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${St<=i?"bg-brand-500":"bg-surface-elevated"}`},St))}),n.jsx("h2",{className:"text-2xl font-bold text-fg-primary",children:Rr.title}),n.jsx("p",{className:"text-sm text-fg-secondary mt-1 mb-6",children:Rr.subtitle}),Rr.content,n.jsxs("div",{className:"flex justify-between mt-8",children:[i>0?n.jsx("button",{onClick:()=>l(i-1),className:"px-4 py-2 text-sm text-fg-secondary hover:text-fg-primary transition-colors",children:a("common:back")}):n.jsx("button",{onClick:e,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("common:skip")}),n.jsxs("div",{className:"flex items-center gap-3",children:[Vt>=0&&i===Vt&&!S&&n.jsx("button",{onClick:()=>l(i+1),className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("llm.skipForNow")}),mn>=0&&i===mn&&!z&&n.jsx("button",{onClick:Xn,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("llm.skipForNow")}),Vn>=0&&i===Vn&&!$e&&n.jsx("button",{onClick:Xn,className:"px-4 py-2 text-sm text-fg-tertiary hover:text-fg-secondary transition-colors",children:a("search.skipForNow")}),n.jsx("button",{onClick:Xn,disabled:Vt>=0&&i===Vt&&!S,className:`px-6 py-2.5 text-white text-sm rounded-xl transition-colors ${Vt>=0&&i===Vt&&!S?"bg-brand-600/40 cursor-not-allowed":"bg-brand-600 hover:bg-brand-500"}`,children:i===jn.length-1?a("getStarted"):a("common:next")})]})]})]})})})}function Zre({onSetup:e}){const{t}=ft("auth"),[r,s]=x.useState(""),[a,i]=x.useState(""),[l,d]=x.useState(""),[u,m]=x.useState(""),[h,p]=x.useState(null),[y,g]=x.useState(""),[v,j]=x.useState(!1),C=x.useRef(null),w=x.useCallback(S=>{if(!S.type.startsWith("image/")||S.size>2*1024*1024)return;const T=new FileReader;T.onload=()=>p(T.result),T.readAsDataURL(S)},[]),N=async S=>{if(S.preventDefault(),g(""),l.length<6){g(t("setup.passwordMinLength"));return}if(l!==u){g(t("setup.passwordsDoNotMatch"));return}j(!0);try{const{user:T,needsOnboarding:M}=await le.auth.init(r.trim(),a.trim(),l);if(h)try{await le.auth.uploadAvatar(h,"user")}catch{}e(T,M??!0)}catch{g(t("setup.error"))}finally{j(!1)}};return r.trim()&&r.trim()[0].toUpperCase(),n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:t("setup.subtitle")})]}),n.jsxs("form",{onSubmit:N,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:t("setup.title")}),n.jsxs("div",{className:"flex flex-col items-center gap-2",children:[n.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>C.current?.click(),children:[h?n.jsx("img",{src:h,alt:"",className:"w-16 h-16 rounded-full object-cover ring-2 ring-border-default group-hover:ring-brand-500 transition-all"}):n.jsx("div",{className:"w-16 h-16 rounded-full bg-surface-elevated border-2 border-dashed border-border-default group-hover:border-brand-500 flex items-center justify-center transition-all",children:n.jsxs("svg",{className:"w-6 h-6 text-fg-tertiary group-hover:text-brand-500 transition-colors",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"}),n.jsx("circle",{cx:"12",cy:"13",r:"3"})]})}),n.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-brand-600 flex items-center justify-center ring-2 ring-surface-secondary",children:n.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),n.jsx("input",{ref:C,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:S=>{const T=S.target.files?.[0];T&&w(T)}})]}),n.jsx("span",{className:"text-xs text-fg-tertiary",children:t("setup.uploadAvatar")})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.name")}),n.jsx("input",{type:"text",value:r,onChange:S=>s(S.target.value),autoComplete:"name",autoFocus:!0,placeholder:"Admin",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.email")}),n.jsx("input",{type:"email",value:a,onChange:S=>i(S.target.value),autoComplete:"email",placeholder:"your@email.com",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.password")}),n.jsx("input",{type:"password",value:l,onChange:S=>d(S.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("setup.confirmPassword")}),n.jsx("input",{type:"password",value:u,onChange:S=>m(S.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),y&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:y}),n.jsx("button",{type:"submit",disabled:v||!r||!a||!l||!u,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:t(v?"setup.creating":"setup.createAccount")})]})]})]})}function Jre({onLogin:e}){const{t}=ft("auth"),[r,s]=x.useState(""),[a,i]=x.useState(""),[l,d]=x.useState(""),[u,m]=x.useState(!1),h=async p=>{if(p.preventDefault(),!(!r.trim()||!a)){d(""),m(!0);try{const{user:y,needsOnboarding:g}=await le.auth.login(r.trim(),a);e(y,g??!1)}catch{d(t("login.invalidCredentials"))}finally{m(!1)}}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:t("login.subtitle")})]}),n.jsxs("form",{onSubmit:h,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:t("login.signIn")}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("login.email")}),n.jsx("input",{type:"email",value:r,onChange:p=>s(p.target.value),autoComplete:"email",placeholder:"your@email.com",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors placeholder:text-fg-tertiary",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:t("login.password")}),n.jsx("input",{type:"password",value:a,onChange:p=>i(p.target.value),autoComplete:"current-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),l&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:l}),n.jsx("button",{type:"submit",disabled:u||!r||!a,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:t(u?"login.signingIn":"login.signIn")}),n.jsx("p",{className:"text-center text-xs text-fg-tertiary",children:t("login.defaultCredentials")})]})]})]})}function ese({token:e,onComplete:t}){const{t:r}=ft("auth"),[s,a]=x.useState(null),[i,l]=x.useState(""),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(!1),[g,v]=x.useState(!1),[j,C]=x.useState(!1);x.useEffect(()=>{le.auth.inviteInfo(e).then(N=>a(N)).catch(()=>C(!0))},[e]);const w=async N=>{if(N.preventDefault(),h(""),i.length<6){h(r("invite.passwordMinLength"));return}if(i!==d){h(r("invite.passwordsDoNotMatch"));return}y(!0);try{await le.auth.setup(e,i),v(!0),setTimeout(()=>{window.location.hash="",t()},2e3)}catch{h(r("invite.error"))}finally{y(!1)}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:r("invite.subtitle")})]}),n.jsx("div",{className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:j?n.jsxs("div",{className:"text-center space-y-3",children:[n.jsx("div",{className:"text-red-500 text-3xl",children:"⚠"}),n.jsx("p",{className:"text-sm text-fg-secondary",children:r("invite.invalidLink")}),n.jsx("button",{onClick:()=>{window.location.hash="",t()},className:"text-sm text-brand-500 hover:text-brand-400",children:r("login.signIn")})]}):g?n.jsxs("div",{className:"text-center space-y-3",children:[n.jsx("div",{className:"text-green-500 text-3xl",children:"✓"}),n.jsx("p",{className:"text-sm text-fg-secondary",children:r("invite.setupComplete")})]}):s?n.jsxs("form",{onSubmit:w,className:"space-y-5",children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:r("invite.greeting",{name:s.name})}),n.jsx("p",{className:"text-xs text-fg-tertiary text-center",children:s.email}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("invite.setPassword")}),n.jsx("input",{type:"password",value:i,onChange:N=>l(N.target.value),autoComplete:"new-password",autoFocus:!0,className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("invite.confirmPassword")}),n.jsx("input",{type:"password",value:d,onChange:N=>u(N.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),m&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:m}),n.jsx("button",{type:"submit",disabled:p||!i||!d,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-all shadow-md shadow-brand-900/40 hover:shadow-lg hover:shadow-brand-900/50",children:r(p?"invite.settingUp":"invite.setupAccount")})]}):n.jsx("div",{className:"text-center text-fg-tertiary text-sm animate-pulse py-4",children:"Loading…"})})]})]})}function tse({onComplete:e,isFirstTime:t}){const{t:r}=ft("auth"),[s,a]=x.useState(""),[i,l]=x.useState(""),[d,u]=x.useState(""),[m,h]=x.useState(""),[p,y]=x.useState(!1),g=async v=>{if(v.preventDefault(),h(""),i.length<6){h(r("changePassword.passwordMinLength"));return}if(i!==d){h(r("changePassword.passwordsDoNotMatch"));return}y(!0);try{await le.auth.changePassword(s,i),e()}catch{h(r("changePassword.failedToChange"))}finally{y(!1)}};return n.jsxs("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center p-4 relative overflow-hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-brand-950/50 via-transparent to-transparent"}),n.jsxs("div",{className:"w-full max-w-sm relative z-10",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("img",{src:"/logo.png",alt:"Markus",className:"w-14 h-14 mx-auto mb-3 rounded-xl shadow-lg shadow-black/40"}),n.jsx("div",{className:"text-2xl font-extrabold tracking-tight text-fg-primary mb-1",children:"Markus"}),n.jsx("div",{className:"text-sm text-fg-tertiary",children:r("login.subtitle")})]}),n.jsxs("form",{onSubmit:g,className:"bg-surface-secondary/80 backdrop-blur-sm border border-border-default rounded-2xl p-8 space-y-5 shadow-2xl shadow-black/30",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-fg-primary text-center",children:r(t?"changePassword.setYourPassword":"changePassword.changePassword")}),t&&n.jsx("p",{className:"text-xs text-amber-600/80 text-center mt-2",children:r("changePassword.defaultPasswordWarning")})]}),!t&&n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.currentPassword")}),n.jsx("input",{type:"password",value:s,onChange:v=>a(v.target.value),autoComplete:"current-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors"})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.newPassword")}),n.jsx("input",{type:"password",value:i,onChange:v=>l(v.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0,minLength:6})]}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("label",{className:"text-xs text-fg-tertiary font-medium",children:r("changePassword.confirmNewPassword")}),n.jsx("input",{type:"password",value:d,onChange:v=>u(v.target.value),autoComplete:"new-password",className:"w-full px-4 py-2.5 bg-surface-elevated border border-border-default rounded-xl text-sm text-fg-primary focus:border-brand-500 outline-none transition-colors",required:!0})]}),m&&n.jsx("div",{className:"px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg text-xs text-red-500",children:m}),n.jsx("button",{type:"submit",disabled:p||!i||!d,className:"w-full py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white text-sm font-medium rounded-xl transition-colors",children:r(p?"changePassword.saving":t?"changePassword.setPasswordAndContinue":"changePassword.changePassword")})]})]})]})}const Vf={agents:[],tasks:[],requirements:[],projects:[],deliverables:[]},nse={team:["agents","tasks","requirements","projects","deliverables"],work:["projects","requirements","tasks","agents","deliverables"],deliverables:["deliverables","agents","tasks","requirements","projects"]},rse=["agents","tasks","requirements","projects","deliverables"];let K3="",W3="all",G3=Vf,Y3=!1;function sse({onClose:e,currentPage:t}){const{t:r}=ft(["common","home","work"]),[s,a]=x.useState(K3),[i,l]=x.useState(W3),[d,u]=x.useState(G3),[m,h]=x.useState(!1),[p,y]=x.useState(Y3),[g,v]=x.useState(-1);x.useEffect(()=>{K3=s},[s]),x.useEffect(()=>{W3=i},[i]),x.useEffect(()=>{G3=d},[d]),x.useEffect(()=>{Y3=p},[p]);const j=x.useRef(null),C=x.useRef(void 0),w=x.useRef(null),N=x.useRef(null);x.useEffect(()=>{setTimeout(()=>{j.current?.focus(),j.current?.select()},100)},[]);const S=x.useCallback(async F=>{if(!F.trim()){u(Vf),y(!1),v(-1);return}h(!0),y(!0),v(-1);const L=F.toLowerCase();try{const[z,E,_,G,V]=await Promise.allSettled([le.agents.list(),le.tasks.list({search:F,pageSize:20}),le.requirements.list(),le.projects.list(),le.deliverables.search({q:F,limit:20})]),O=z.status==="fulfilled"?z.value.agents.filter(Y=>Y.name?.toLowerCase().includes(L)||Y.role?.toLowerCase().includes(L)):[],q=E.status==="fulfilled"?E.value.tasks:[],J=_.status==="fulfilled"?_.value.requirements.filter(Y=>Y.title?.toLowerCase().includes(L)||Y.description?.toLowerCase().includes(L)):[],H=G.status==="fulfilled"?G.value.projects.filter(Y=>Y.name?.toLowerCase().includes(L)||Y.description?.toLowerCase().includes(L)):[],Z=V.status==="fulfilled"?V.value.results:[];u({agents:O,tasks:q,requirements:J,projects:H,deliverables:Z})}catch{u(Vf)}finally{h(!1)}},[]),T=F=>{a(F),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>S(F),400)},M=x.useCallback((F,L)=>{e(),pt.navigate(F,L)},[e]),D=[{id:"all",label:r("common:all",{defaultValue:"全部"})},{id:"agents",label:r("common:agents",{defaultValue:"智能体"})},{id:"tasks",label:r("common:tasks",{defaultValue:"任务"})},{id:"requirements",label:r("common:requirements",{defaultValue:"需求"})},{id:"projects",label:r("common:projects",{defaultValue:"项目"})},{id:"deliverables",label:r("common:deliverables",{defaultValue:"交付物"})}],I=x.useMemo(()=>nse[t||""]||rse,[t]),$=x.useMemo(()=>{const F=[],L=i==="all"?8:void 0,z=E=>{if(i!=="all"&&i!==E)return;const _=d[E==="agents"?"agents":E==="tasks"?"tasks":E==="requirements"?"requirements":E==="projects"?"projects":"deliverables"],G=L?_.slice(0,L):_;for(const V of G)switch(E){case"agents":F.push({id:V.id,type:"agent",page:Te.TEAM,params:{agentId:V.id}});break;case"tasks":F.push({id:V.id,type:"task",page:Te.WORK,params:{openTask:V.id}});break;case"requirements":F.push({id:V.id,type:"requirement",page:Te.WORK,params:{openRequirement:V.id}});break;case"projects":F.push({id:V.id,type:"project",page:Te.WORK,params:{projectId:V.id}});break;case"deliverables":F.push({id:V.id,type:"deliverable",page:Te.DELIVERABLES,params:{openDeliverable:V.id}});break}L&&_.length>L&&F.push({id:`more_${E}`,type:"showMore",page:"",expandCategory:E,totalCount:_.length})};for(const E of I)z(E);return F},[d,i,I]),B=x.useCallback(F=>{if(F.type==="showMore"&&F.expandCategory){l(F.expandCategory),v(-1);return}M(F.page,F.params)},[M]);x.useEffect(()=>{const F=N.current;if(!F||g<0)return;const L=F.querySelector(`[data-idx="${g}"]`);L&&L.scrollIntoView({block:"nearest"})},[g]);const R=x.useCallback(F=>{if(F.key==="Escape"){e();return}if(F.key==="Tab"){F.preventDefault();const E=D.map(V=>V.id),_=E.indexOf(i),G=F.shiftKey?_<=0?E.length-1:_-1:_>=E.length-1?0:_+1;l(E[G]),v(-1);return}const L=F.ctrlKey&&F.key==="n"||F.key==="ArrowDown",z=F.ctrlKey&&F.key==="p"||F.key==="ArrowUp";if(L||z){F.preventDefault(),v(E=>{const _=$.length-1;return _<0?-1:L?E>=_?0:E+1:E<=0?_:E-1});return}F.key==="Enter"&&(F.preventDefault(),g>=0&&g<$.length&&B($[g]))},[e,$,g,B,D,i]);x.useEffect(()=>(document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)),[R]);const U=$.length>0;let W=0;return n.jsx("div",{ref:w,className:"fixed inset-0 bg-black/50 flex items-start justify-center z-50 pt-[8vh]",onClick:F=>{F.target===w.current&&e()},children:n.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-2xl shadow-2xl w-full max-w-3xl max-h-[78vh] flex flex-col overflow-hidden animate-fadeIn",children:[n.jsxs("div",{className:"shrink-0 px-5 pt-4 pb-3 border-b border-border-default space-y-3",children:[n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg-tertiary",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("input",{ref:j,value:s,onChange:F=>T(F.target.value),placeholder:r("common:search"),className:"w-full bg-surface-elevated border border-border-default rounded-xl pl-9 pr-9 py-2.5 text-sm text-fg-primary placeholder:text-fg-tertiary focus:border-brand-500 focus:outline-none transition-colors"}),s&&n.jsx("button",{onClick:()=>{a(""),u(Vf),y(!1),v(-1),j.current?.focus()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-fg-tertiary hover:text-fg-secondary",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"flex gap-1 overflow-x-auto scrollbar-hide",children:D.map(F=>n.jsx("button",{onClick:()=>{l(F.id),v(-1)},className:`px-3 py-1.5 text-xs rounded-lg whitespace-nowrap transition-colors ${i===F.id?"bg-brand-600 text-white":"bg-surface-elevated text-fg-secondary hover:text-fg-primary"}`,children:F.label},F.id))})]}),n.jsxs("div",{ref:N,className:"flex-1 overflow-y-auto px-5 py-3",children:[m&&n.jsx("div",{className:"flex items-center justify-center py-8",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:r("common:loading")})}),!m&&p&&!U&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[n.jsxs("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-2",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:r("common:noResults",{defaultValue:"没有找到相关结果"})})]}),!m&&U&&n.jsx("div",{className:"space-y-4",children:I.map(F=>{if(i!=="all"&&i!==F)return null;const L=i==="all"?8:void 0,z=E=>{const _=W++,G=E==="agents"?d.agents.length:E==="tasks"?d.tasks.length:E==="requirements"?d.requirements.length:E==="projects"?d.projects.length:d.deliverables.length;return n.jsxs("button",{"data-idx":_,onClick:()=>{l(E),v(-1)},className:`mt-1 w-full text-xs py-1.5 rounded-lg transition-colors ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40 text-brand-500":"text-brand-500 hover:text-brand-400 hover:bg-surface-overlay"}`,children:[r("common:showAll",{defaultValue:"查看全部"})," (",G,")"]})};return F==="agents"&&d.agents.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:agents",{defaultValue:"智能体"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.agents.slice(0,L):d.agents).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.TEAM,{agentId:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx(Sr,{name:E.name||"Agent",avatarUrl:E.avatarUrl,size:28}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:E.name}),n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:E.role||E.status})]}),n.jsx(ase,{status:E.status})]},E.id)})}),L&&d.agents.length>L&&z("agents")]},"agents"):F==="tasks"&&d.tasks.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:tasks",{defaultValue:"任务"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.tasks.slice(0,L):d.tasks).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{openTask:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx(ise,{status:E.status}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.status," · ",E.priority||""]})]})]},E.id)})}),L&&d.tasks.length>L&&z("tasks")]},"tasks"):F==="requirements"&&d.requirements.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:requirements",{defaultValue:"需求"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.requirements.slice(0,L):d.requirements).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{openRequirement:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${E.status==="approved"?"text-green-500 bg-green-500/15":E.status==="pending"?"text-amber-500 bg-amber-500/15":E.status==="rejected"?"text-red-500 bg-red-500/15":"text-fg-tertiary bg-surface-elevated"}`,children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"}),n.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),n.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.status," · ",E.priority||""]})]})]},E.id)})}),L&&d.requirements.length>L&&z("requirements")]},"requirements"):F==="projects"&&d.projects.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:projects",{defaultValue:"项目"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.projects.slice(0,L):d.projects).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.WORK,{projectId:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"w-7 h-7 rounded-lg bg-teal-500/15 flex items-center justify-center shrink-0",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-teal-500",children:n.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.name}),E.description&&n.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:E.description})]})]},E.id)})}),L&&d.projects.length>L&&z("projects")]},"projects"):F==="deliverables"&&d.deliverables.length>0?n.jsxs("section",{children:[n.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase mb-2",children:r("common:deliverables",{defaultValue:"交付物"})}),n.jsx("div",{className:"space-y-0.5",children:(L?d.deliverables.slice(0,L):d.deliverables).map(E=>{const _=W++;return n.jsxs("button",{"data-idx":_,onClick:()=>M(Te.DELIVERABLES,{openDeliverable:E.id}),className:`w-full flex items-center gap-3 px-3 py-2 rounded-xl transition-colors text-left ${_===g?"bg-brand-600/15 ring-1 ring-brand-500/40":"hover:bg-surface-overlay"}`,children:[n.jsx("div",{className:"w-7 h-7 rounded-lg bg-purple-500/15 flex items-center justify-center shrink-0",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-purple-500",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-fg-primary truncate",children:E.title}),n.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[E.type," · ",E.status]})]})]},E.id)})}),L&&d.deliverables.length>L&&z("deliverables")]},"deliverables"):null})}),!m&&!p&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[n.jsxs("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"text-fg-tertiary mb-2",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),n.jsx("p",{className:"text-sm text-fg-tertiary",children:r("common:searchHint",{defaultValue:"输入关键词搜索"})})]})]}),n.jsxs("div",{className:"shrink-0 px-5 py-2 border-t border-border-default flex items-center gap-4 text-xs text-fg-tertiary flex-wrap",children:[n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:navigator.platform.toUpperCase().includes("MAC")?"Cmd+P":"Ctrl+P"})," ",r("common:toggle",{defaultValue:"唤起/关闭"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Tab"})," ",r("common:switchTab",{defaultValue:"切换分类"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"↑↓"})," ",r("common:navigate",{defaultValue:"导航"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Enter"})," ",r("common:open",{defaultValue:"打开"})]}),n.jsxs("span",{children:[n.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-surface-elevated border border-border-default text-[11px] font-medium",children:"Esc"})," ",r("common:close",{defaultValue:"关闭"})]})]})]})})}function ase({status:e}){const t=e==="active"||e==="idle"?"bg-green-500":e==="working"||e==="busy"?"bg-blue-500":e==="paused"?"bg-amber-500":"bg-gray-400";return n.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`})}function ise({status:e}){const t=e==="completed"?"text-green-500 bg-green-500/15":e==="in_progress"?"text-blue-500 bg-blue-500/15":e==="pending"?"text-amber-500 bg-amber-500/15":"text-fg-tertiary bg-surface-elevated";return n.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${t}`,children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 11l3 3L22 4"}),n.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})})}const ose={visibility:"hidden",position:"absolute",inset:0,pointerEvents:"none",zIndex:-1},lse=x.memo(function({id:t,activePage:r,children:s}){const a=t===r;return n.jsx("div",{className:"flex-1 overflow-hidden flex flex-col",style:a?void 0:ose,children:s})},(e,t)=>{const r=e.id===e.activePage,s=t.id===t.activePage;return r!==s?!1:s?e.children===t.children:!0}),lb={};function cse(){const{t:e}=ft("common"),[t,r]=x.useState(ec),[s,a]=x.useState(()=>!localStorage.getItem("markus_onboarded")),[i,l]=x.useState(!0),d=Ds(),u=$G(),m=m0({side:"left",defaultWidth:160,minWidth:140,maxWidth:400,collapsedWidth:64,storageKey:"markus_sidebar"}),[h,p]=x.useState(()=>new Set([ec()])),[y,g]=x.useState("loading"),[v,j]=x.useState(null),[C,w]=x.useState(!1),[N,S]=x.useState(!1),[T,M]=x.useState(null),[D,I]=x.useState(!1),[$,B]=x.useState(null),[R,U]=x.useState(()=>{const O=localStorage.getItem("markus_update_dismissed");return O||null}),[W,F]=x.useState(!1);x.useEffect(()=>{if(d)return;const O=navigator.platform.toUpperCase().includes("MAC"),q=H=>{O&&H.metaKey&&!H.ctrlKey&&H.key==="p"?(H.preventDefault(),F(Z=>!Z)):!O&&H.ctrlKey&&!H.metaKey&&H.key==="p"&&(H.preventDefault(),F(Z=>!Z))},J=()=>F(!0);return document.addEventListener("keydown",q),window.addEventListener("markus:open-search",J),()=>{document.removeEventListener("keydown",q),window.removeEventListener("markus:open-search",J)}},[d]);const L=x.useCallback(O=>{let q=nc(O);d?q=k_[q]??q:q===Te.NOTIFICATIONS&&(q=Te.HOME);const J=ec(),H=window.location.hash.slice(1);H!==J?lb[J]=H:delete lb[J];const Z=q!==Te.WORK?lb[q]:void 0;Z&&Z!==q?(history.pushState(null,"","#"+q),history.pushState(null,"","#"+Z)):history.pushState(null,"","#"+q),window.dispatchEvent(new HashChangeEvent("hashchange")),r(q),p(Y=>Y.has(q)?Y:new Set([...Y,q]))},[d]);x.useEffect(()=>{pt.setHandler(O=>L(O))},[L]);const z=x.useCallback(()=>{fetch("/api/settings/llm").then(O=>O.ok?O.json():null).then(O=>{if(O?.providers){const q=Object.values(O.providers).some(J=>J.configured);M(q)}}).catch(()=>{})},[]);x.useEffect(()=>{const O=new URLSearchParams(window.location.search),q=O.get("install");if(q&&ec()!==Te.STORE){const Z=O.get("type"),ee=Z&&{agent:"agents",team:"teams",skill:"skills"}[Z]||"agents";localStorage.setItem("markus_nav_installItem",q),localStorage.setItem("markus_nav_storeTab",ee),O.delete("install"),O.delete("type");const ae=O.toString();window.history.replaceState(null,"",window.location.pathname+(ae?`?${ae}`:"")+"#store"),setTimeout(()=>pt.navigate(Te.STORE,{storeTab:ee,installItem:q}),300)}le.auth.me().then(({user:Z})=>{g(Z),j(!0),pn.connect(Z.id),z(),le.health().then(ee=>{ee.updateAvailable&&ee.latestVersion&&B({latestVersion:ee.latestVersion,currentVersion:ee.version})}).catch(()=>{});const Y=()=>{Xl(Ra.builderArtifacts,()=>le.builder.artifacts.list()),Xl(Ra.builderAgents,()=>le.agents.list()),Xl(Ra.builderHubMyItems,()=>Un.myItems()),Xl(Ra.builderInstalled,()=>le.builder.artifacts.installed()),Xl(Ra.hubAgents,()=>Un.search({type:"agent",limit:50})),Xl(Ra.hubTeams,()=>Un.search({type:"team",limit:50})),Xl(Ra.hubSkills,()=>Un.search({type:"skill",limit:50}))};typeof requestIdleCallback=="function"?requestIdleCallback(Y,{timeout:5e3}):setTimeout(Y,3e3)}).catch(()=>{g(null),le.auth.status().then(({initialized:Z})=>j(Z)).catch(()=>j(!0))}),pn.connect();const J=pn.on("notification",()=>{window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}),H=()=>{const Z=ec();r(Z),p(Y=>Y.has(Z)?Y:new Set([...Y,Z]))};return window.addEventListener("hashchange",H),window.addEventListener("popstate",H),()=>{J(),pn.disconnect(),window.removeEventListener("hashchange",H),window.removeEventListener("popstate",H)}},[]);const E=y!=="loading"&&y!==null?y:void 0,_=x.useMemo(()=>d?{[Te.HOME]:n.jsx(gw,{authUser:E}),[Te.TEAM]:n.jsx(Wk,{authUser:E}),[Te.BUILDER]:n.jsx(Xre,{authUser:E}),[Te.SETTINGS]:n.jsx(Zk,{theme:u.mode,onThemeChange:u.setMode,authUser:E,onLogout:()=>g(null),onUserUpdated:O=>g(O)}),[Te.WORK]:n.jsx(z3,{authUser:E}),[Te.DELIVERABLES]:n.jsx(B3,{authUser:E}),[Te.NOTIFICATIONS]:n.jsx(Fre,{authUser:E}),[Te.REPORTS]:n.jsx(F3,{authUser:E}),[Te.SEARCH]:n.jsx(qre,{})}:{[Te.HOME]:n.jsx(gw,{authUser:E}),[Te.TEAM]:n.jsx(Wk,{authUser:E}),[Te.SETTINGS]:n.jsx(Zk,{theme:u.mode,onThemeChange:u.setMode,authUser:E,onLogout:()=>g(null),onUserUpdated:O=>g(O)}),[Te.STORE]:n.jsx(vY,{authUser:E}),[Te.BUILDER]:n.jsx(QS,{authUser:E}),[Te.WORK]:n.jsx(z3,{authUser:E}),[Te.DELIVERABLES]:n.jsx(B3,{authUser:E}),[Te.REPORTS]:n.jsx(F3,{authUser:E})},[E?.id,E?.role,u.mode,d]);if(y==="loading"||y===null&&v===null)return n.jsx("div",{className:"min-h-dvh bg-surface-primary flex items-center justify-center",children:n.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:e("loading")})});const V=(typeof window<"u"?window.location.hash:"").match(/^#invite\?token=([a-f0-9]+)/);return V?n.jsx(ese,{token:V[1],onComplete:()=>{window.location.hash="",localStorage.removeItem("markus_onboarded"),a(!0),w(!0),g("loading"),le.auth.me().then(O=>g(O.user)).catch(()=>g(null))}}):y===null?v===!1?n.jsx(Zre,{onSetup:(O,q)=>{g(O),j(!0),w(!0),q&&(localStorage.removeItem("markus_onboarded"),a(!0))}}):n.jsx(Jre,{onLogin:(O,q)=>{g(O),q?(localStorage.removeItem("markus_onboarded"),a(!0)):localStorage.getItem("markus_onboarded")||(localStorage.setItem("markus_onboarded","1"),a(!1))}}):N?n.jsx(tse,{onComplete:()=>S(!1),isFirstTime:!0}):s?n.jsx(Qre,{theme:u.mode,onThemeChange:u.setMode,skipProfile:C,onComplete:()=>{localStorage.setItem("markus_onboarded","1"),a(!1),w(!1),z(),L(Te.HOME)}}):n.jsxs("div",{className:`flex h-dvh bg-surface-primary text-fg-primary overflow-x-hidden ${d?"flex-col":""}`,children:[!d&&t!==Te.SETTINGS&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"relative z-40 shrink-0",style:{width:m.width},children:n.jsx(Wre,{currentPage:t,onNavigate:O=>{L(O),l(!1)},authUser:y,collapsed:m.collapsed,onToggleCollapse:m.toggle})}),n.jsx("div",{className:`${m.collapsed?"w-0":"w-1.5 cursor-col-resize"} shrink-0 group relative z-10 flex items-center justify-center`,onMouseDown:m.collapsed?void 0:m.onResizeStart,children:!m.collapsed&&n.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})})]}),n.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col min-w-0 ${d&&t!==Te.SETTINGS&&t!==Te.SEARCH?"pb-14":""}`,children:[T===!1&&!D&&t!==Te.SETTINGS&&n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-amber-500/10 border-b border-amber-500/30 text-amber-600 text-sm shrink-0",children:[n.jsx("span",{className:d?"text-xs":"",children:"No LLM provider configured — agents cannot process requests."}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{onClick:()=>{L(Te.SETTINGS)},className:"px-3 py-1 bg-amber-700/50 hover:bg-amber-700/70 text-white text-xs rounded-lg transition-colors",children:"Go to Settings"}),n.jsx("button",{onClick:()=>I(!0),className:"text-amber-500 hover:text-amber-600 text-xs",children:e("dismiss")})]})]}),$&&R!==$.latestVersion&&n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-brand-500/10 border-b border-brand-500/30 text-brand-400 text-sm shrink-0",children:[n.jsxs("span",{className:d?"text-xs":"",children:["New version available: ",n.jsxs("strong",{children:["v",$.latestVersion]})," (current: v",$.currentVersion,")",!d&&n.jsxs("span",{className:"text-fg-tertiary ml-2",children:["— run ",n.jsx("code",{className:"bg-surface-overlay px-1.5 py-0.5 rounded text-xs font-mono",children:"npm i -g @markus-global/cli"})," to upgrade"]})]}),n.jsx("button",{onClick:()=>{U($.latestVersion),localStorage.setItem("markus_update_dismissed",$.latestVersion)},className:"text-brand-400 hover:text-brand-300 text-xs shrink-0",children:e("dismiss")})]}),n.jsx("main",{className:"flex-1 overflow-hidden flex flex-col relative",children:Object.keys(_).map(O=>h.has(O)?n.jsx(lse,{id:O,activePage:t,children:_[O]},O):null)})]}),d&&t!==Te.SETTINGS&&t!==Te.SEARCH&&n.jsx(Gre,{currentPage:t,onNavigate:L,userId:E?.id}),d&&n.jsx(A_,{authUser:E,onNavigate:L}),!d&&W&&n.jsx(sse,{onClose:()=>F(!1),currentPage:t})]})}E9.createRoot(document.getElementById("root")).render(n.jsx(x.StrictMode,{children:n.jsx(cse,{})}));export{j0 as g};