@markus-global/cli 0.12.5-rc.3 → 0.12.5-rc.4
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.
- package/dist/web-ui/assets/{AsyncState-BBjWt0U4.js → AsyncState-CeDmMBla.js} +1 -1
- package/dist/web-ui/assets/{ChatComponents-BM9ia4hU.js → ChatComponents-u_iLnHEf.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-qTQ3LGXo.js → ContentRenderer-CHzFmlGx.js} +2 -2
- package/dist/web-ui/assets/{DeliverableShareModal-DvipfOxG.js → DeliverableShareModal-By9CYH0Q.js} +1 -1
- package/dist/web-ui/assets/{Deliverables-BPy0ggqv.js → Deliverables-Cn_DRg-F.js} +1 -1
- package/dist/web-ui/assets/{MarkdownMessage-CRj69Rnh.js → MarkdownMessage-BX6YVVx8.js} +1 -1
- package/dist/web-ui/assets/{Search-C46Sjd5C.js → Search-BGSuNeNO.js} +1 -1
- package/dist/web-ui/assets/{SendToChat-LdFPpuOR.js → SendToChat-BR3-e7d4.js} +1 -1
- package/dist/web-ui/assets/{Settings-AG1s3e8i.js → Settings-DJyCWAY9.js} +1 -1
- package/dist/web-ui/assets/{Store-DO5KoBp1.js → Store-Cl-05eXo.js} +1 -1
- package/dist/web-ui/assets/{Switch-BZ1GkhRR.js → Switch-DGrHkwcq.js} +1 -1
- package/dist/web-ui/assets/{Team-D5iZnF6B.js → Team-DfNOc2Oj.js} +4 -4
- package/dist/web-ui/assets/{Work-Drx3sVyM.js → Work-Cwkb9n7H.js} +1 -1
- package/dist/web-ui/assets/{arc-Eq03OxxX.js → arc-DUrpNW2s.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BBdoQyhl.js → architectureDiagram-3BPJPVTR-_itbdqjs.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-CiHhkXz1.js → blockDiagram-GPEHLZMM-7gcaAgpE.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BNuNa7JZ.js → c4Diagram-AAUBKEIU-BqKuOXWt.js} +1 -1
- package/dist/web-ui/assets/channel-BNcjWETI.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-CHUGrp-l.js → chunk-2J33WTMH-DmFCktA6.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-d_lgDORf.js → chunk-4BX2VUAB-w8YtZlZ5.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-D3qv6MEj.js → chunk-55IACEB6-4k-E46Qp.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-zcDvjE2C.js → chunk-727SXJPM-C1-6Iiik.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-Cu6Z10dm.js → chunk-AQP2D5EJ-CO4NtkeR.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-CIFOVD2g.js → chunk-FMBD7UC4-CS_sseZh.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-tQ2G7DnL.js → chunk-ND2GUHAM-D7-BkEUG.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-C-cdIAYv.js → chunk-QZHKN3VN-BPCz16Gj.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-v3_2DQPV.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-v3_2DQPV.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DmSgdwYx.js → cose-bilkent-S5V4N54A-CpYmq76O.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-wjgriNhd.js → dagre-BM42HDAG-DrBF0YKT.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-a-NcMwjk.js → diagram-2AECGRRQ-CzQkjw5L.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-SpkaU5yE.js → diagram-5GNKFQAL-SneRBO1C.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-CUgGNLiQ.js → diagram-KO2AKTUF-C8iAMOJw.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-B8fsKgAc.js → diagram-LMA3HP47-C2lb4oU1.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-BzlaeBBK.js → diagram-OG6HWLK6-P-NuPlh6.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-BCuJY_I2.js → docx-preview-YtzS0xMU.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BbKnb5vg.js → erDiagram-TEJ5UH35-BXcYtaBT.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-v-NewzE2.js → flowDiagram-I6XJVG4X-Dm48mLdd.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-B2AU3vrG.js → ganttDiagram-6RSMTGT7-BXrfFYnN.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-Dwxnlf1q.js → gitGraphDiagram-PVQCEYII-CxO9AKdS.js} +1 -1
- package/dist/web-ui/assets/{index-D5uPD4Tz.js → index-CudHikwU.js} +6 -6
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-BdzCNxZz.js → infoDiagram-5YYISTIA-DSP5_m8e.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-CLyFQ2jy.js → ishikawaDiagram-YF4QCWOH-Bsmqh7_N.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-B3LiOP2U.js → journeyDiagram-JHISSGLW-CCBod5iD.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-B8Oj05-K.js → kanban-definition-UN3LZRKU-BGbAEz6s.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-DMZzuUz0.js → mermaid.core-B17l8z4S.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-VJJ6L2az.js → mindmap-definition-RKZ34NQL-7pahuML0.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-DS0GmvNe.js → pieDiagram-4H26LBE5-AtMgK6F2.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-B5zgEbvf.js → quadrantDiagram-W4KKPZXB-DxwCSN_z.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-BC9P_pkc.js → requirementDiagram-4Y6WPE33-DQ4GULQe.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-DWJUUU8z.js → sankeyDiagram-5OEKKPKP-DJaWWRUa.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CwDKp_Kn.js → sequenceDiagram-3UESZ5HK-ChrFC_0T.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-D3xJAfNC.js → stateDiagram-AJRCARHV-DZthn0Xq.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CFMNtQOk.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-Bs2r0u8I.js → timeline-definition-PNZ67QCA-BM0bxJB9.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Dn7ElyME.js → vennDiagram-CIIHVFJN-Buu596v7.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-DzsSSCmk.js → wardley-L42UT6IY-FsFYXKCE.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CQAHS6du.js → wardleyDiagram-YWT4CUSO-CEl-G6gD.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-a8vJ9G8_.js → xychartDiagram-2RQKCTM6-c-k0Gyas.js} +1 -1
- package/dist/web-ui/index.html +1 -1
- package/docs/architecture/desktop-auto-update.md +46 -2
- package/package.json +1 -1
- package/dist/web-ui/assets/channel-h2PMJJlX.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D1AgiP6_.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D1AgiP6_.js +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DMjww8Bc.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as e,r as i,u as ce,a7 as Cs,aa as Hr,V as Un,k as U,h as Gt,a5 as zo,ab as Wo,a1 as Go,a3 as Jo,ac as Yo,ad as Qo,ae as Zo,af as Xo,U as ei,ag as ti,a0 as si,ah as ri,ai as ni,aj as ai,ak as Kn,al as oi,n as ws,P as qr,_ as ii,am as li,an as di,ao as ci,ap as ui,aq as mi,ar as Hn,as as gr,at as fr,au as qn,av as xi,a as gi,b as fi,c as pi,aw as zn,ax as hi,ay as bi,az as Wn,aA as Ha,aB as yi,i as vi,aC as ji}from"./index-D5uPD4Tz.js";import{L as Ni}from"./AsyncState-BBjWt0U4.js";import{i as wi,n as ki,S as Ye}from"./Switch-BZ1GkhRR.js";function Si(t,r){for(var n=0;n<r.length;n++){const a=r[n];if(typeof a!="string"&&!Array.isArray(a)){for(const o in a)if(o!=="default"&&!(o in t)){const s=Object.getOwnPropertyDescriptor(a,o);s&&Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:()=>a[o]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}const Ci=/ECONNREFUSED|EPIPE|ECONNRESET/i,Ai=/ENOTFOUND|EAI_AGAIN/i,Pi=/TIMEDOUT|timeout|ABORT_ERR|UND_ERR_(CONNECT|HEADERS|BODY)_TIMEOUT/i;function Mi(t){const r=(t?.detail??"").trim(),n=t?.code??"",a=r||n||"unknown";return n==="probe_http_error"?{key:"networkProxy.failProbeHttp",params:{detail:a}}:n==="network_unreachable"?Ci.test(r)?{key:"networkProxy.failRefused",params:{detail:a}}:Ai.test(r)?{key:"networkProxy.failDns",params:{detail:a}}:Pi.test(r)?{key:"networkProxy.failTimeout",params:{detail:a}}:{key:"networkProxy.failUnreachable",params:{detail:a}}:{key:"networkProxy.failUnknown",params:{detail:a}}}const we="bg-surface-elevated rounded-xl border border-border-default/40",Fe={pageTitle:"text-lg font-semibold",groupTitle:"text-[13px] font-semibold",groupDesc:"text-xs leading-relaxed",hint:"text-[11px] leading-relaxed",badge:"text-[11px] font-medium"},Qe={strong:"text-fg-primary",desc:"text-fg-tertiary"},kt="px-3 py-2 text-[13px] bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder:text-fg-tertiary/50 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 outline-none transition-colors",zr="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-[13px] font-medium bg-brand-600 hover:bg-brand-500 text-on-brand disabled:opacity-40 rounded-lg transition-colors",it="inline-flex items-center justify-center gap-1.5 px-3 py-2 text-[13px] font-medium border border-border-default text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary disabled:opacity-40 rounded-lg transition-colors";function Je({tone:t="neutral",children:r,title:n}){const a={neutral:"bg-fg-tertiary/10 text-fg-tertiary",ok:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",warn:"bg-amber-500/15 text-amber-600 dark:text-amber-400",danger:"bg-red-500/15 text-red-500",brand:"bg-brand-500/15 text-brand-500"};return e.jsx("span",{title:n,className:`${Fe.badge} rounded px-1.5 py-0.5 ${a[t]}`,children:r})}function je({label:t,hint:r,children:n}){return e.jsxs("div",{className:"flex flex-wrap items-start gap-x-6 gap-y-2 px-5 py-3.5",children:[e.jsxs("div",{className:"min-w-[7rem] flex-1",children:[t&&e.jsx("div",{className:"text-[13px] font-medium text-fg-primary",children:t}),r&&e.jsx("div",{className:"mt-0.5 text-[11px] leading-relaxed text-fg-tertiary",children:r})]}),n&&e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n})]})}function ke({title:t,description:r,action:n,children:a}){return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),n]}),e.jsx("div",{className:"space-y-3",children:a})]})}function Gn({title:t,description:r,children:n,defaultOpen:a=!0}){const[o,s]=i.useState(a);return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("button",{type:"button",onClick:()=>s(!o),className:"flex items-start justify-between w-full group text-left",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),e.jsx("span",{className:`text-fg-tertiary mt-0.5 transition-transform group-hover:text-fg-secondary ${o?"":"-rotate-90"}`,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),o&&e.jsx("div",{className:"space-y-3",children:n})]})}function Ti(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${(t/1e3).toFixed((t%1e3===0,0))}K`:String(t)}function Ei(t){return t.maxInputTokens>0||t.inputCostPer1MTokens>0||t.outputCostPer1MTokens>0}function pr(t){if(t.tier)return t.tier;const r=t.id.toLowerCase(),n=/opus|5\.4|o3-(?!mini)|o1-(?!mini)|gemini.*ultra|sonnet-4-20/,a=/haiku|flash|nano|lite|small|fast|free|8b|7b|1b|3b/;return/o4-mini|o3-mini|o1-mini|gpt-4o-mini/.test(r)?"pro":n.test(r)?"max":a.test(r)?"base":"pro"}const Jn={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30"};function qa({models:t,selectedModel:r,onSelect:n,loading:a,compact:o,maxVisible:s,showTiers:d}){const{t:c}=ce("settings"),[u,h]=i.useState(""),[x,v]=i.useState(!1),[j,k]=i.useState(""),P=i.useMemo(()=>{let m=t;if(u){const w=u.toLowerCase();m=m.filter(V=>V.id.toLowerCase().includes(w))}return j&&(m=m.filter(w=>pr(w)===j)),m},[t,u,j]),N=i.useMemo(()=>{const m={max:0,pro:0,base:0};for(const w of t)m[pr(w)]++;return m},[t]),y=s??(o?5:10),b=x?P:P.slice(0,y),A=P.length>y;return a?e.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-fg-tertiary",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),c("modelPicker.loading")]}):t.length===0?e.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:c("modelPicker.empty")}):e.jsxs("div",{className:"space-y-2",children:[d&&t.length>3&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>k(""),className:`px-2 py-0.5 rounded text-[10px] transition-colors ${j?"bg-surface-overlay text-fg-tertiary hover:text-fg-secondary":"bg-brand-500/20 text-brand-500"}`,children:c("modelPicker.allCount",{count:t.length})}),["max","pro","base"].filter(m=>N[m]>0).map(m=>e.jsx("button",{onClick:()=>k(j===m?"":m),className:`px-2 py-0.5 rounded text-[10px] font-medium uppercase transition-colors border ${j===m?Jn[m]:"border-transparent bg-surface-overlay text-fg-tertiary hover:text-fg-secondary"}`,children:c("modelPicker.tierCount",{tier:c(`modelRouting.tier.${m}`),count:N[m]})},m))]}),t.length>5&&e.jsx("input",{type:"text",value:u,onChange:m=>{h(m.target.value),v(!1)},placeholder:c("modelPicker.filterPlaceholder"),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"}),e.jsx("div",{className:`space-y-1 ${o?"max-h-[280px] overflow-y-auto":""}`,children:b.map(m=>{const w=m.id===r,V=pr(m);return e.jsxs("button",{type:"button",onClick:()=>n(m.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${w?"bg-brand-500/10 border border-brand-500/30":"hover:bg-surface-overlay border border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${w?"border-brand-500":"border-border-default"}`,children:w&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),e.jsx("span",{className:`text-xs font-medium ${w?"text-brand-500":"text-fg-primary"}`,children:m.id}),d&&e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-semibold uppercase border ${Jn[V]}`,children:c(`modelRouting.tier.${V}`)})]}),e.jsx("div",{className:"flex items-center gap-2",children:w&&e.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:c("modelPicker.active")})})]}),Ei(m)&&m.maxInputTokens>0&&e.jsx("div",{className:"ml-5 mt-0.5 flex items-center gap-2 text-[10px] text-fg-tertiary flex-wrap",children:e.jsxs("span",{children:[Ti(m.maxInputTokens)," ",c("modelPicker.ctx")]})}),!o&&e.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[m.capabilities.functionCalling&&e.jsx(Ft,{label:c("modelPicker.capabilities.tools")}),m.capabilities.vision&&e.jsx(Ft,{label:c("modelPicker.capabilities.vision")}),m.capabilities.reasoning&&e.jsx(Ft,{label:c("modelPicker.capabilities.reasoning")}),m.capabilities.promptCaching&&e.jsx(Ft,{label:c("modelPicker.capabilities.caching")}),m.capabilities.webSearch&&e.jsx(Ft,{label:c("modelPicker.capabilities.search")})]})]},m.id)})}),A&&!x&&e.jsx("button",{type:"button",onClick:()=>v(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:c("modelPicker.showAll",{count:P.length})}),x&&A&&e.jsx("button",{type:"button",onClick:()=>v(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:c("modelPicker.showLess")})]})}function Ft({label:t}){return e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] bg-surface-overlay text-fg-tertiary border border-border-default",children:t})}function Yt({value:t,options:r,placeholder:n,onChange:a}){const{t:o}=ce("settings"),[s,d]=i.useState(!1),[c,u]=i.useState(""),h=i.useRef(null),x=i.useRef(null),v=i.useRef(null),[j,k]=i.useState(-1);i.useEffect(()=>{function m(w){h.current&&!h.current.contains(w.target)&&d(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),i.useEffect(()=>{s&&x.current&&x.current.focus()},[s]);const P=i.useMemo(()=>{if(!c.trim())return r;const m=c.toLowerCase();return r.filter(w=>w.modelId.toLowerCase().includes(m)||w.modelName.toLowerCase().includes(m)||w.provider.toLowerCase().includes(m)||w.providerLabel.toLowerCase().includes(m)||w.tier&&w.tier.toLowerCase().includes(m))},[r,c]),N=i.useMemo(()=>{const m=new Map;for(const V of P){const T=V.providerLabel;m.has(T)||m.set(T,[]),m.get(T).push(V)}const w={max:0,pro:1,base:2};for(const V of m.values())V.sort((T,I)=>(w[T.tier??"base"]??9)-(w[I.tier??"base"]??9));return m},[P]),y=i.useMemo(()=>{const m=[];for(const w of N.values())m.push(...w);return m},[N]),b=i.useMemo(()=>{if(!t)return n??o("modelRouting.auto");const m=r.find(w=>`${w.provider}/${w.modelId}`===t);return m?`${m.providerLabel}/${m.modelName}`:t},[t,r,n,o]);function A(m){if(!s){(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d(!0));return}switch(m.key){case"ArrowDown":m.preventDefault(),k(w=>Math.min(w+1,y.length-1));break;case"ArrowUp":m.preventDefault(),k(w=>Math.max(w-1,-1));break;case"Enter":if(m.preventDefault(),j===-1)a("",null);else if(y[j]){const w=y[j];a(`${w.provider}/${w.modelId}`,w)}d(!1),u("");break;case"Escape":d(!1),u("");break}}return i.useEffect(()=>{v.current&&j>=0&&v.current.querySelector(`[data-focus-index="${j}"]`)?.scrollIntoView({block:"nearest"})},[j]),e.jsxs("div",{ref:h,className:"relative min-w-0",onKeyDown:A,children:[e.jsx("button",{type:"button",onClick:()=>{d(!s),u(""),k(-1)},className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary text-left truncate focus:outline-none focus:border-brand-500",children:b}),s&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[240px] max-h-[280px] bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden flex flex-col",children:[e.jsx("div",{className:"p-1.5 border-b border-border-default",children:e.jsx("input",{ref:x,type:"text",value:c,onChange:m=>{u(m.target.value),k(-1)},placeholder:o("modelPicker.searchPlaceholder")||"Search models...",className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary focus:outline-none focus:border-brand-500"})}),e.jsxs("div",{ref:v,className:"overflow-y-auto flex-1",children:[e.jsx("div",{className:`px-3 py-1.5 text-xs cursor-pointer ${j===-1?"bg-brand-500/20 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,onClick:()=>{a("",null),d(!1),u("")},children:n??o("modelRouting.auto")}),[...N.entries()].map(([m,w])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 py-1 text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider bg-surface-overlay/50 sticky top-0",children:m}),w.map(V=>{const T=y.indexOf(V),I=`${V.provider}/${V.modelId}`===t;return e.jsxs("div",{"data-focus-index":T,className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${T===j?"bg-brand-500/20":I?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,onClick:()=>{a(`${V.provider}/${V.modelId}`,V),d(!1),u("")},children:[e.jsx("span",{className:"flex-1 truncate text-fg-primary",children:V.modelName}),V.tier&&e.jsx(Ri,{tier:V.tier}),V.costTier&&e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:V.costTier})]},`${V.provider}/${V.modelId}`)})]},m)),y.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:o("modelPicker.empty")})]})]})]})}function Ri({tier:t}){const r={max:"bg-purple-500/20 text-purple-400",pro:"bg-blue-500/20 text-blue-400",base:"bg-gray-500/20 text-gray-400"};return e.jsx("span",{className:`px-1 py-0.5 rounded text-[8px] font-bold uppercase ${r[t]??r.base}`,children:t})}const Ii=500,Yn=[{groupKey:"image",capabilities:["image_recognition","image_generation"]},{groupKey:"audio",capabilities:["audio_tts","audio_stt"]},{groupKey:"video",capabilities:["video_generation"]}];function Li({onSave:t,configuredProviders:r}){const{t:n}=ce(["settings","common"]),[a,o]=i.useState({}),[s,d]=i.useState(null),[c,u]=i.useState(!1),[h,x]=i.useState(null),[v,j]=i.useState(!0),[k,P]=i.useState("idle"),[N,y]=i.useState(null),[b,A]=i.useState({}),[m,w]=i.useState(!1),[V,T]=i.useState("idle"),[I,F]=i.useState(null),[C,$]=i.useState(!1),D=i.useRef(null),B=i.useRef(null),S=i.useMemo(()=>r.map(f=>f.name).sort().join(","),[r]);i.useEffect(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null),u(!0)}).catch(f=>{x(String(f)),u(!0)})},[S]),i.useEffect(()=>{let f=!1;return j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(R=>{if(!R.ok)throw new Error(`HTTP ${R.status}`);return R.json()}).then(R=>{if(f)return;const p=[];for(const K of R.providers)for(const z of K.models)p.push({provider:K.provider,providerLabel:K.displayName,modelId:z.id,modelName:z.name,mode:z.mode,tier:z.tier,costTier:z.costTier,capabilities:z.capabilities});y(p)}).catch(()=>{f||y(null)}).finally(()=>{f||j(!1)}),()=>{f=!0}},[S]),i.useEffect(()=>{fetch("/api/models/suggested-assignments",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{A(f.suggestions),w(!0)}).catch(()=>w(!0))},[S]);const L=i.useCallback(f=>{P("saving"),t(f).then(()=>{P("saved"),setTimeout(()=>P(R=>R==="saved"?"idle":R),2e3)}).catch(()=>{P("error"),setTimeout(()=>P(R=>R==="error"?"idle":R),3e3)})},[t]),J=i.useCallback((f,R)=>{B.current={capabilityRouting:f!==void 0?{assignments:f}:B.current?.capabilityRouting,routingDefaultModel:R!==void 0?R:B.current?.routingDefaultModel},D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const p=B.current;B.current=null,p&&L(p)},Ii)},[L]),_=i.useMemo(()=>r.flatMap(f=>(f.models??[{id:f.model,name:f.model}]).map(R=>({provider:f.name,providerLabel:f.displayName??f.name,modelId:R.id,modelName:R.name}))),[r]),H=N??_,X=i.useMemo(()=>Object.entries(a).map(([f,R])=>`${f}:${R?.provider??""}/${R?.model??""}`).sort().join("|"),[a]);i.useEffect(()=>{!c||!N||N.length===0||N.some(f=>!!f.modelId)&&(o(f=>{let R=!1;const p={...f};for(const K of Yn)for(const z of K.capabilities){const se=p[z];if(!se?.model)continue;const ae=za(N,z);if(ae.length===0)continue;ae.some(te=>te.provider===se.provider&&te.modelId===se.model)||(delete p[z],R=!0)}return R?(J(p),p):f}),d(f=>{if(!f?.model||N.some(z=>z.provider===f.provider&&z.modelId===f.model))return f;const p=N.find(z=>z.provider==="markus"),K=p?{provider:p.provider,model:p.modelId}:{provider:N[0].provider,model:N[0].modelId};return t({routingDefaultModel:K}),K}))},[c,N,S,J,X]);const me=i.useCallback(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null)}).catch(()=>{}),j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{const R=[];for(const p of f.providers)for(const K of p.models)R.push({provider:p.provider,providerLabel:p.displayName,modelId:K.id,modelName:K.name,mode:K.mode,tier:K.tier,costTier:K.costTier,capabilities:K.capabilities});y(R)}).catch(()=>{}).finally(()=>j(!1))},[]),ie=i.useCallback(async()=>{if(V!=="working"){T("working"),F(null);try{const f=await fetch("/api/settings/llm/restore-recommended",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}),R=await f.json().catch(()=>({}));if(!f.ok||!R.ok)throw new Error(R.error??`HTTP ${f.status}`);R.capabilityRouting&&o(R.capabilityRouting.assignments??{}),R.routingDefaultModel!==void 0&&d(R.routingDefaultModel),me(),T("idle"),P("saved"),setTimeout(()=>P(p=>p==="saved"?"idle":p),2e3)}catch(f){T("error"),F(f instanceof Error?f.message:String(f)),setTimeout(()=>T("idle"),4e3)}}},[V,me]),ee=H.length>0;return c?h?e.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-xs text-red-400",children:n("modelRouting.loadError",{error:h})}):v&&!ee?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-secondary",children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin text-brand-500",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),e.jsx("span",{children:n("modelRouting.loadingModels")})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Bi,{status:k,t:n}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("button",{type:"button",onClick:()=>$(!0),disabled:V==="working",className:"text-xs px-3 py-1.5 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40 disabled:opacity-50 transition-colors",children:n(V==="working"?"modelRouting.restoreWorking":"modelRouting.restoreRecommended")}),I&&e.jsx("span",{className:"text-[10px] text-red-400 max-w-xs text-right",children:I})]})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:n("modelRouting.defaultModelTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("modelRouting.defaultModelDesc")})]}),e.jsx("div",{className:"max-w-md",children:e.jsx(Yt,{value:s?`${s.provider}/${s.model}`:"",options:H,placeholder:n("modelRouting.defaultModelPlaceholder"),onChange:f=>{if(!f)d(null),J(void 0,null);else{const[R,...p]=f.split("/"),K={provider:R,model:p.join("/")};if(d(K),a.text){const z={...a};delete z.text,o(z),J(z,K)}else J(void 0,K)}}})})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:n("modelRouting.capabilityAssignTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("modelRouting.capabilityAssignDesc")})]}),r.length===0&&e.jsx("div",{className:"p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-xs text-yellow-400",children:n("modelRouting.noProvidersHint")}),r.length>0&&e.jsx("div",{className:"space-y-4",children:Yn.map(f=>e.jsx(Oi,{groupKey:f.groupKey,capabilities:f.capabilities,assignments:a,suggestions:b,allModels:H,configuredProviderNames:new Set(r.map(R=>R.name)),t:n,onAssign:(R,p)=>{const K={...a};p?K[R]=p:delete K[R],o(K),J(K)}},f.groupKey))})]}),C&&e.jsx(Cs,{variant:"primary",title:n("modelRouting.restoreRecommended"),message:n("modelRouting.restoreConfirm"),confirmLabel:n("common:confirm"),onConfirm:()=>{$(!1),ie()},onCancel:()=>$(!1)})]}):e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 animate-pulse",children:[e.jsx("div",{className:"h-4 bg-surface-overlay rounded w-1/3 mb-3"}),e.jsx("div",{className:"h-3 bg-surface-overlay rounded w-2/3 mb-4"}),e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(f=>e.jsx("div",{className:"h-10 bg-surface-overlay rounded-lg"},f))})]})})}function Oi({groupKey:t,capabilities:r,assignments:n,suggestions:a,allModels:o,configuredProviderNames:s,t:d,onAssign:c}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 px-1",children:d(`modelRouting.capabilityGroups.${t}`)}),e.jsx("div",{className:"space-y-1",children:r.map(u=>{const h=n[u],x=a[u],v=h?`${h.provider}/${h.model}`:"",j=za(o,u),k=x?j.find(A=>A.provider===x.provider&&A.modelId===x.model)?.modelName??x.model:void 0,P=j.length>0,N=h?$i(o,h.provider,h.model):void 0,y=h&&!s.has(h.provider),b=!!(h&&P&&u!=="text"&&!j.some(A=>A.provider===h.provider&&A.modelId===h.model));return e.jsxs("div",{className:`flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg md:flex-nowrap md:gap-3 ${b?"bg-red-500/10 border border-red-500/30":y?"bg-yellow-500/10 border border-yellow-500/30":!P&&!h?"bg-amber-500/5 border border-amber-500/20":"bg-surface-overlay/40"}`,children:[e.jsx("div",{className:"w-full shrink-0 md:w-28",children:e.jsx("span",{className:"text-xs text-fg-primary",children:d(`modelRouting.capabilities.${u}`)})}),e.jsx("div",{className:"flex-1 min-w-0",children:b?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs text-red-400",children:["⚠ ",h.model]}),e.jsx("span",{className:"text-[10px] text-red-400/70",children:d("modelRouting.mismatchHint")})]}),e.jsx(Yt,{value:"",options:j,placeholder:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}})]}):P?e.jsx(Yt,{value:v,options:j,placeholder:k?`${k} (${d("modelRouting.suggested")})`:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}}):e.jsxs("span",{className:"text-xs text-amber-400",children:[d("modelRouting.noModelAvailable"),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",d("modelRouting.addProviderHint")]})]})}),e.jsxs("div",{className:"w-14 shrink-0 flex justify-end",children:[b&&e.jsx("span",{className:"text-[10px] text-red-400 font-medium",title:d("modelRouting.mismatchHint"),children:"⚠"}),!b&&y&&e.jsx("span",{className:"text-[10px] text-yellow-400 font-medium",title:d("modelRouting.staleProvider"),children:"⚠"}),!b&&!y&&N&&e.jsx(Qn,{tier:N}),!b&&!y&&!N&&h&&e.jsx(Qn,{tier:"unknown"})]}),e.jsx("div",{className:"w-8 shrink-0 flex justify-end",children:h&&e.jsx("button",{onClick:()=>c(u,null),className:"text-fg-tertiary hover:text-red-400 transition-colors",title:d("modelRouting.clear"),children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})})]},u)})})]})}function $i(t,r,n){return t.find(o=>o.provider===r&&o.modelId===n)?.tier}function Bi({status:t,t:r}){if(t==="idle")return null;const n={idle:"",saving:"text-fg-tertiary",saved:"text-green-400",error:"text-red-400"},a={idle:"",saving:r("modelRouting.saving"),saved:r("modelRouting.saved"),error:r("modelRouting.saveError")};return e.jsx("div",{className:`text-xs font-medium transition-opacity ${n[t]}`,children:a[t]})}function Qn({tier:t}){const r={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30",unknown:"bg-gray-500/10 text-fg-tertiary border-border-default"};return e.jsx("span",{className:`px-1.5 py-0.5 text-[9px] rounded font-semibold uppercase border ${r[t]??r.unknown}`,children:t==="unknown"?"—":t})}function za(t,r){if(r==="text")return t.filter(d=>wi(d));const n={image_generation:["image_generation"],audio_tts:["audio_speech"],audio_stt:["audio_transcription"],video_generation:["video_generation"]},a={image_recognition:["vision"],image_generation:["imageGeneration"],audio_tts:["tts"],audio_stt:["stt"],video_generation:["videoGeneration"]},o=n[r],s=a[r];return t.filter(d=>!!(d.capabilities&&d.capabilities.length>0&&s&&s.some(c=>d.capabilities.includes(c))||o&&d.mode&&o.includes(d.mode)))}function Di({orgId:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null);return i.useEffect(()=>{if(!t)return;let o=!1;return fetch(`/api/orgs/${t}/slug`,{credentials:"include"}).then(s=>s.ok?s.json():null).then(s=>{!o&&s&&a(s)}).catch(()=>{}),()=>{o=!0}},[t]),n?.hubOrgId?e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-brand-500/25 bg-brand-600/[0.06] px-3 py-2",children:[e.jsx("span",{className:"shrink-0 text-xs text-fg-tertiary",children:r("orgIdentity.label")}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("code",{className:"truncate font-mono text-xs text-fg-primary",children:n.orgSlug||r("orgIdentity.unset")}),e.jsx("span",{className:"shrink-0 rounded bg-green-500/15 px-1.5 py-0.5 text-[10px] text-green-600",children:r("orgIdentity.synced")})]})]}):null}function Ut({w:t="w-16"}){return e.jsx("span",{className:`inline-block h-3 ${t} animate-pulse rounded bg-surface-elevated`,"aria-hidden":"true"})}function Vi({authUser:t}){const{t:r}=ce(["settings","common"]),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState([]),[u,h]=i.useState(()=>Hr()||Un()?"loading":"not-connected"),x=u==="loading",[v,j]=i.useState(null),k=i.useCallback(()=>{U.hubOrgs.mine().catch(T=>(j({type:"err",text:T instanceof Error?T.message:r("org.loadFailed")}),{orgs:[]})).then(T=>{s(T.orgs),U.hubOrgs.invitations().then(I=>c(I.invitations)).catch(()=>{})})},[r]);i.useEffect(()=>{if(!Hr()&&!Un()){h("not-connected");return}k(),Gt.user.plan().then(T=>a(T)).catch(()=>{}).finally(()=>h("ready"))},[k]);const P=async T=>{try{await U.hubOrgs.acceptInvitation(T),c(I=>I.filter(F=>F.orgId!==T)),k()}catch(I){j({type:"err",text:I instanceof Error?I.message:"Failed"})}},N=o.find(T=>T.id===n?.orgId)??o[0],y=n?n.creditsBudgetCu??(n.monthlyQuotaCu??0)+(n.bonusCu??0)+(n.purchasedCu??0):0,b=!!(n?.memberCuLimit!=null&&n.memberCuLimit>0&&N&&N.role!=="owner"&&N.role!=="admin"&&N.memberCount>1),A=Math.round(b?n?.memberCuUsed??0:n?.totalConsumedThisPeriod??n?.cuUsed??0),m=b?n?.memberCuLimit??0:y,w=x||m>0,V=x||!!N;return e.jsxs("div",{className:"space-y-3",children:[v&&e.jsxs("div",{className:`flex items-center gap-2 rounded-lg px-4 py-3 text-sm ${v.type==="ok"?"border border-green-500/20 bg-green-500/10 text-green-600":"border border-red-500/20 bg-red-500/10 text-red-500"}`,children:[e.jsx("span",{children:v.type==="ok"?"✓":"✕"}),e.jsx("span",{children:v.text})]}),d.length>0&&e.jsx("div",{className:"space-y-2",children:d.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-fg-primary",children:T.orgName}),e.jsxs("span",{className:"ml-1 text-fg-tertiary",children:["— ",r("org.invitedBy")," ",T.invitedBy]})]}),e.jsx("button",{type:"button",onClick:()=>{P(T.orgId)},className:"rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("org.accept")})]},T.orgId))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Di,{orgId:t?.orgId}),e.jsx("div",{className:"space-y-3 rounded-lg border border-border-default px-5 py-4",children:u==="not-connected"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:r("orgSummary.notConnectedTitle")}),e.jsx("p",{className:"text-xs leading-relaxed text-fg-tertiary",children:r("orgSummary.notConnectedDesc")}),e.jsx("button",{type:"button",onClick:()=>{zo(Wo("markus://auth"))},className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("orgSummary.connectHub")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("orgSummary.plan")}),x?e.jsx(Ut,{w:"w-14"}):e.jsx("span",{className:"rounded border border-brand-500/15 bg-brand-600/10 px-2 py-0.5 text-xs font-semibold capitalize text-brand-500",children:n?.planType??r("orgSummary.planUnknown")})]}),w&&e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r(b?"account.personalLimit":"account.credits")}),e.jsx("span",{className:"font-medium tabular-nums text-fg-primary",children:x?e.jsx(Ut,{w:"w-24"}):e.jsxs(e.Fragment,{children:[A.toLocaleString()," / ",m.toLocaleString()]})})]}),V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.nameLabel")}),x?e.jsx(Ut,{w:"w-28"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.name})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("account.memberCount")}),x?e.jsx(Ut,{w:"w-6"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.memberCount})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.orgId")}),x?e.jsx(Ut,{w:"w-40"}):e.jsx("code",{className:"rounded bg-surface-elevated px-1.5 py-0.5 text-[11px] text-fg-secondary",children:N?.id})]})]}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:r("account.noOrg")}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=billing`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand no-underline transition-colors hover:bg-brand-500",children:r("orgSummary.manageBilling")}),e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=organization`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg border border-border-default px-4 py-2 text-xs font-medium text-fg-secondary no-underline transition-colors hover:bg-surface-elevated",children:r("orgSummary.manageMembers")})]})]})})]})]})}function _i({configuredProviders:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>t.map(N=>`${N.name}:${N.models?.length??0}`).sort().join(","),[t]),v=i.useCallback(async()=>{c(null);try{const[{agents:N},y]=await Promise.all([U.agents.list({lean:!0}),U.teams.list()]),b=y.teams.map(m=>({id:m.id,name:m.name}));s(b);const A=await Promise.all(N.map(async m=>{try{const V=(await U.agents.get(m.id)).config?.llmConfig;return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:V?.modelMode==="custom"&&V.primary&&V.defaultModel?`${V.primary}/${V.defaultModel}`:null,llmConfig:{modelMode:V?.modelMode,primary:V?.primary??"",defaultModel:V?.defaultModel}}}catch{return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:null,llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}}}));a(N.length?A:null)}catch(N){c(String(N))}},[x]);i.useEffect(()=>{v()},[v,x]);const j=i.useMemo(()=>{const N=[];for(const y of t)for(const b of y.models??[])N.push({provider:y.name,providerLabel:y.displayName??y.name,modelId:b.id,modelName:b.name??b.id});return N},[t]),k=async(N,y)=>{h(N),c(null);try{y?await U.agents.updateConfig(N,{llmConfig:{modelMode:"custom",primary:y.provider,defaultModel:y.modelId}}):await U.agents.updateConfig(N,{llmConfig:{modelMode:"default",primary:"",defaultModel:null}});const b=y?`${y.provider}/${y.modelId}`:null;a(A=>A?.map(m=>m.id===N?{...m,override:b}:m)??A),ki(N)}catch(b){c(String(b))}finally{h(null)}},P=i.useMemo(()=>{if(!n)return[];const N=new Map,y=[];for(const A of n)if(A.teamId){const m=N.get(A.teamId)??[];m.push(A),N.set(A.teamId,m)}else y.push(A);const b=[];y.length&&b.push({key:"ungrouped",label:r("perAgentModel.ungrouped",{defaultValue:"Ungrouped"}),rows:y});for(const A of o){const m=N.get(A.id);m?.length&&b.push({key:`team:${A.id}`,label:A.name,rows:m})}for(const[A,m]of N)o.some(w=>w.id===A)||b.push({key:`team:${A}`,label:A,rows:m});return b},[n,o,r]);return n===null&&!d?e.jsx("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 text-sm text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}):e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:r("perAgentModel.title",{defaultValue:"Per-agent default model"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r("perAgentModel.desc",{defaultValue:'Bind a specific provider+model to an agent, or leave it following the global default. This is what the composer "Apply to current agent" writes.'})})]})}),d&&e.jsx("div",{className:"text-xs text-red-500",children:d}),(!n||n.length===0)&&!d&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:r("perAgentModel.noAgents",{defaultValue:"No agents available."})}),n&&n.length>0&&e.jsx("div",{className:"space-y-5",children:P.map(N=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-fg-tertiary truncate",children:N.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary/70 tabular-nums shrink-0",children:N.rows.length})]}),e.jsx("div",{className:"space-y-2",children:N.rows.map(y=>e.jsxs("div",{title:y.id,className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:y.name}),e.jsxs("div",{className:"flex w-[55%] max-w-[320px] min-w-0 shrink-0 items-center gap-1.5 sm:w-[320px]",children:[y.override?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{value:y.override,options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),e.jsx("button",{type:"button",disabled:u===y.id,onClick:()=>{k(y.id,null)},className:"shrink-0 px-2.5 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-primary disabled:opacity-40 transition-colors",children:r("perAgentModel.reset",{defaultValue:"Reset"})})]}):e.jsx(Yt,{value:"",options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),u===y.id&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary",children:r("common:loading",{defaultValue:"…"})})]})]},y.id))})]},N.key))})]})}let ks=[],ys=null;async function Fi(){return ys||(ys=(async()=>{try{ks=(await U.modelCatalog.providerCatalog()).providers??[]}catch{ks=[]}return ks})(),ys)}function Ui(){const[t,r]=i.useState(ks);return i.useEffect(()=>{let n=!0;return Fi().then(a=>{n&&r(a)}),()=>{n=!1}},[]),t}const Ki="integrations.platforms",Xr=(t,r)=>`settings:${Ki}.${t}.${r}`,Hi={feishu:"https://open.feishu.cn/app",telegram:"https://t.me/BotFather",slack:"https://api.slack.com/apps",whatsapp:"https://developers.facebook.com/apps",discord:"https://discord.com/developers/applications"};function qi(t){return Hi[t]}function zi(t,r){return t(Xr(r.id,"label"),{defaultValue:r.label})}function Wa(t,r,n){const a=Xr(r,`fields.${n.key}`);return{label:t(`${a}.label`,{defaultValue:n.label}),help:n.help?t(`${a}.help`,{defaultValue:n.help}):void 0,placeholder:n.placeholder?t(`${a}.placeholder`,{defaultValue:n.placeholder}):void 0,options:n.options?.map(o=>({value:o.value,label:t(`${a}.options.${o.value}`,{defaultValue:o.label})}))}}function Wi(t,r,n){const a=[],o=Xr(n,"guide");for(let s=1;s<=20;s+=1){const d=`${o}.step${s}.title`;if(!t.exists(d))break;const c=`${o}.step${s}.desc`,u=t.exists(c)?r(c):void 0;a.push({title:r(d),...u?{desc:u}:{}})}return a}function Gi(t){return t("settings:integrations.guide.heading",{defaultValue:"Setup guide"})}function Ji(t){return t.type==="boolean"?t.default===!0:t.multiple?Array.isArray(t.default)?[...t.default]:[]:t.default!==void 0?t.default:""}function As(t,r){return r==null?!0:t.type==="boolean"?!1:t.multiple?!Array.isArray(r)||r.length===0:typeof r=="string"?r.trim()==="":!1}function Zn(t){const r={};for(const n of t.fields){if(n.secret){r[n.key]="";continue}const a=t.values[n.key];r[n.key]=a??Ji(n)}return r}function Xn(t,r,n={}){const a=[];for(const o of t)if(o.required){if(o.secret){if(!As(o,r[o.key]))continue;n[o.key]?.hasValue||a.push(o.key);continue}As(o,r[o.key])&&a.push(o.key)}return a}function Yi(t,r,n){const a={enabled:n};for(const o of t.fields){const s=r[o.key];if(o.secret){if(As(o,s))continue;a[o.key]=s;continue}s!==void 0&&(a[o.key]=s)}return a}function Qi(t){return t.filter(r=>r.required||r.type==="agent")}function Zi(t){return t.filter(r=>!(r.required||r.type==="agent"))}function Wr(t){return Array.isArray(t)?`[${t.map(Wr).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[a])=>n<a?-1:n>a?1:0).map(([n,a])=>`${JSON.stringify(n)}:${Wr(a)}`).join(",")}}`:JSON.stringify(t)??"null"}function Xi(t){return Wr({id:t.id,enabled:t.enabled,fields:t.fields.map(r=>({key:r.key,type:r.type,required:r.required,secret:r.secret===!0,multiple:r.multiple===!0,default:r.default??null,value:r.secret?!1:t.values[r.key]??null,hasValue:r.secret?t.secrets[r.key]?.hasValue===!0:!1}))})}function el(t){const r=t.ok===!0||t.success===!0;return{ok:r,text:t.message??t.error??(r?"OK":"Failed"),code:t.code}}function tl(t){return t?.status==="awaiting_reply"||t?.status==="awaiting_inbound"}function sl(t,r=!1){return t.hasConfig?t.enabled?t.lastVerifiedAt||r?"verified":"unverified":"off":"unconfigured"}function rl(t){return{id:"",platform:t.id,label:"",enabled:!0,connected:!1,hasConfig:!1,capabilities:t.capabilities,fields:t.fields,values:{},secrets:nl(t.fields),agentId:null,notifyAgentId:null,channels:[],lastError:null,canListChannels:!1,lastVerifiedAt:null}}function nl(t){const r={};for(const n of t)n.secret&&(r[n.key]={hasValue:!1});return r}function al(t){return t.id===""}function ea(t){return{id:t.platform,label:t.label,capabilities:t.capabilities,fields:t.fields,defaultEnabled:!1,enabled:t.enabled,connected:t.connected,hasConfig:t.hasConfig,values:{...t.values,agentId:t.agentId??""},secrets:t.secrets}}function hr(t,r){return t.find(n=>n.nativeId===r)}function ta(t,r,n,a){const o=t.filter(s=>s.nativeId!==r);return o.push({nativeId:r,kind:a??null,agentId:n}),o.sort((s,d)=>s.nativeId.localeCompare(d.nativeId))}function sa(t,r){return t.filter(n=>n.nativeId!==r)}function ol(t,r){const n=new Set(r.map(a=>a.id));return t.filter(a=>!n.has(a.nativeId))}function il(t,r){const n=r.trim().toLowerCase();return n?t.filter(a=>a.name.toLowerCase().includes(n)||a.id.toLowerCase().includes(n)):t}function ll(t){const r=new Map;for(const n of t){const a=r.get(n.platform);a?a.push(n):r.set(n.platform,[n])}return[...r.entries()].map(([n,a])=>({platform:n,instances:a}))}function dl(t,r,n={}){const a=n.devMode??!1,o=new Set(t.filter(c=>c.devOnly&&!a).map(c=>c.id)),s=[],d=new Set;for(const c of t)o.has(c.id)||d.has(c.id)||(d.add(c.id),s.push(c.id));for(const c of r)o.has(c.platform)||d.has(c.platform)||(d.add(c.platform),s.push(c.platform));return s}function cl(t,r,n){const[a,o]=i.useState([]),[s,d]=i.useState(null),[c,u]=i.useState(!1),h=i.useRef(t);h.current=t;const x=i.useRef(0),v=i.useCallback(()=>{if(!n||!r)return;const j=++x.current;u(!0),h.current(r).then(k=>{j===x.current&&(o(k.channels??[]),d(k.error??null))}).catch(k=>{j===x.current&&(o([]),d(k instanceof Error?k.message:String(k)))}).finally(()=>{j===x.current&&u(!1)})},[n,r]);return i.useEffect(()=>(v(),()=>{x.current+=1}),[v]),{channels:a,error:s,loading:c,reloadChannels:v}}const Ga=/^notify[A-Z]/,Ja="notifyEnabled";function ul(t){return t.find(r=>r.key===Ja)}function ml(t){return t.notifyTarget==="chat"||t.notifyTarget==="user"||Ga.test(t.key)}function Qt(t){return t.filter(r=>r.notifyTarget==="chat"||r.notifyTarget==="user")}function xl(t){return t.filter(r=>!r.notifyTarget&&!r.secret&&r.key!==Ja&&Ga.test(r.key))}function gl(t){return t.filter(ml)}function Ya(t){return Qt(t).find(r=>r.notifyTarget==="chat")}function fl(t,r){const n=Qt(t);return n.length===0?"unsupported":n.some(a=>!As(a,r[a.key]))?"configured":"not-configured"}function ra(t){return typeof t=="string"?{value:t,label:t}:{value:t.value,label:t.label??t.value,hint:t.hint}}function na(t,r,n){const a=t.label.toLowerCase(),o=t.value.toLowerCase(),s=`${a} ${o} ${(t.hint??"").toLowerCase()}`;for(const c of r)if(!s.includes(c))return null;if(a.startsWith(n)||o.startsWith(n))return 0;const d=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[\\s./:_-])${d}`).test(a)?1:2}function Qa({value:t,options:r,onChange:n,placeholder:a,filterPlaceholder:o,emptyText:s,customHint:d,disabled:c,ariaLabel:u,className:h}){const[x,v]=i.useState(!1),[j,k]=i.useState(""),[P,N]=i.useState(!1),[y,b]=i.useState(-1),A=i.useRef(null),m=i.useRef(null),w=i.useRef(null),V=i.useRef(null),T=i.useId(),[I,F]=i.useState({}),C=i.useMemo(()=>t?r.map(ra).find(_=>_.value===t)?.label??t:a??"",[t,r,a]);i.useEffect(()=>{x||(k(C),N(!1))},[C,x]),i.useEffect(()=>{function _(H){const X=H.target;V.current?.contains(X)||A.current&&!A.current.contains(X)&&v(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);function $(){const _=m.current;if(!_)return;const H=_.getBoundingClientRect(),X=Math.max(H.width,240),me=window.innerHeight-H.bottom-8,ie=me<180&&H.top>me;F({position:"fixed",left:H.left,width:X,maxHeight:Math.min(260,ie?Math.max(H.top-12,120):me),...ie?{bottom:window.innerHeight-H.top+4}:{top:H.bottom+4}})}i.useLayoutEffect(()=>{if(!x)return;$();const _=()=>$();return window.addEventListener("scroll",_,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("scroll",_,!0),window.removeEventListener("resize",_)}},[x]);const D=i.useMemo(()=>{const _=r.map(ra),H=j.trim(),X=P?H.toLowerCase().split(/\s+/).filter(Boolean):[],me=[];_.forEach((f,R)=>{const p=X.length?na(f,X,H.toLowerCase()):0;p!==null&&me.push({row:f,score:p,idx:R})}),me.sort((f,R)=>f.score-R.score||f.idx-R.idx);const ie=[];if(a!==void 0){const f={value:"",label:a};(X.length?na(f,X,H.toLowerCase()):0)!==null&&ie.push(f)}ie.push(...me.map(f=>f.row));const ee=H&&!_.some(f=>f.value.toLowerCase()===H.toLowerCase());return d&&P&&ee&&ie.push({value:H,label:H,custom:!0}),ie},[r,j,P,a,d]);i.useEffect(()=>{if(!x||y<0||!w.current)return;w.current.querySelector(`[data-index="${y}"]`)?.scrollIntoView({block:"nearest"})},[y,x,D.length]);function B(){c||(k(C),N(!1),b(D.findIndex(_=>_.value===t)),v(!0),requestAnimationFrame(()=>m.current?.select()))}function S(){v(!1),k(C),N(!1),b(-1)}function L(_){n(_.value),v(!1),k(_.value?_.label:a??""),N(!1),b(-1),m.current?.focus()}function J(_){if(_.key==="ArrowDown"||_.key==="ArrowUp"){if(_.preventDefault(),!x){B();return}b(H=>{const X=_.key==="ArrowDown"?H+1:H-1;return Math.max(-1,Math.min(X,D.length-1))});return}if(_.key==="Enter"){if(!x){_.preventDefault(),B();return}const H=D[y];H?(_.preventDefault(),L(H)):S();return}if(_.key==="Escape"&&x){_.preventDefault(),_.stopPropagation(),S();return}_.key==="Tab"&&x&&S()}return e.jsxs("div",{ref:A,className:`relative ${h??""}`,children:[e.jsx("input",{ref:m,type:"text",role:"combobox","aria-expanded":x,"aria-controls":x?T:void 0,"aria-autocomplete":"list","aria-label":u,"aria-activedescendant":x&&y>=0?`${T}-opt-${y}`:void 0,disabled:c,value:x?j:C,placeholder:o,onMouseDown:()=>{x?v(!1):B()},onChange:_=>{x||v(!0),k(_.target.value),N(!0),b(0)},onKeyDown:J,onBlur:()=>{x&&S()},className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none truncate"}),x&&Go.createPortal(e.jsxs("div",{id:T,role:"listbox",ref:_=>{w.current=_,V.current=_},style:I,onMouseDown:_=>_.preventDefault(),"data-keep-edit-focus":!0,className:"z-50 overflow-y-auto bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1",children:[D.map((_,H)=>e.jsxs("div",{id:`${T}-opt-${H}`,"data-index":H,role:"option","aria-selected":_.value===t,onMouseDown:X=>{X.preventDefault(),L(_)},className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${H===y?"bg-brand-500/20":_.value===t?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,children:[e.jsx("span",{className:`flex-1 truncate ${_.custom?"text-brand-500":"text-fg-primary"}`,children:_.label}),_.hint&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:_.hint}),_.custom&&d&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:typeof d=="function"?d(_.value):d})]},`${_.custom?"custom:":""}${_.value}`)),D.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:s})]}),document.body)]})}async function pl(){const{agents:t}=await U.agents.list({lean:!0});return t.map(r=>({id:r.id,name:r.name,role:r.role}))}let vs=null;function Za(){return vs||(vs=pl().catch(t=>{throw vs=null,t})),vs}function hl(t=Za,r=!0){const[n,a]=i.useState([]);return i.useEffect(()=>{if(!r)return;let o=!0;return t().then(s=>{o&&a(s)}).catch(()=>{o&&a([])}),()=>{o=!1}},[t,r]),n}function Ps({value:t,options:r,onChange:n,fieldKey:a,ariaLabel:o,disabled:s}){const{t:d}=ce(["settings"]);return e.jsx(Qa,{value:typeof t=="string"?t:"",options:r.map(c=>({value:c.id,label:c.name,hint:c.role})),onChange:c=>n(a,c),disabled:s,placeholder:d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),filterPlaceholder:d("settings:integrations.agentSelect.search",{defaultValue:"Search agents…"}),emptyText:d("settings:integrations.agentSelect.empty",{defaultValue:"No matching agent"}),ariaLabel:o??d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),className:"w-full"})}function Xa({loading:t,error:r,onReload:n,buttonTestId:a,errorTestId:o,empty:s=!1}){const{t:d}=ce(["settings","common"]);return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-h-[1.25rem]",children:[e.jsxs("button",{type:"button",onClick:n,disabled:t,"aria-busy":t,"data-testid":a,className:"inline-flex items-center gap-1 text-[11px] font-medium text-fg-tertiary hover:text-fg-secondary disabled:opacity-60 transition-colors",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${t?"animate-spin":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{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"})}),t?d("settings:instances.channels.refreshing",{defaultValue:"Refreshing…"}):s?d("settings:integrations.loadGroups",{defaultValue:"Load groups"}):d("settings:instances.channels.refresh",{defaultValue:"Refresh"})]}),r&&e.jsx("span",{"data-testid":o,className:"text-[11px] text-red-600",children:r})]})}const Ss="rounded-xl border border-border-default bg-surface-secondary p-4",Wt="text-sm font-semibold text-fg-primary",eo="flex flex-wrap items-center justify-between gap-x-4 gap-y-2",bl="flex flex-wrap items-start justify-between gap-x-4 gap-y-2",Gr="shrink-0 text-sm text-fg-secondary",to="flex-1 min-w-[10rem] flex justify-end",Ct="text-xs text-fg-tertiary",Jr="w-full px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500 transition-colors";function Yr(t){return"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-lg border transition-colors "+(t?"bg-selected-bg border-selected-border text-selected-fg":"bg-surface-primary border-border-default text-fg-secondary hover:border-fg-tertiary")}const yl={verified:"bg-green-500/10 text-green-600 border-green-500/30",unverified:"bg-amber-500/10 text-amber-600 border-amber-500/30",off:"bg-gray-500/10 text-fg-tertiary border-border-default",unconfigured:"bg-gray-500/10 text-fg-tertiary border-border-default"},vl={verified:"bg-green-500",unverified:"bg-amber-400",off:"bg-gray-400",unconfigured:"bg-gray-400"},jl={verified:"settings:integrations.status.verified",unverified:"settings:integrations.status.unverified",off:"settings:integrations.status.off",unconfigured:"settings:integrations.status.unconfigured"},Nl={verified:"Connected",unverified:"Not verified",off:"Off",unconfigured:"Not configured"};function wl({state:t}){const{t:r}=ce(["settings"]);return e.jsxs("span",{"data-testid":"integration-status","data-state":t,"data-connected":t==="verified"?"true":"false",className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${yl[t]}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${vl[t]}`}),r(jl[t],{defaultValue:Nl[t]})]})}function Jt({type:t,text:r}){return e.jsx("div",{"data-testid":t==="ok"?"integration-msg-ok":"integration-msg-err",className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs ${t==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-600 border border-red-500/30"}`,children:r})}function Kt({label:t,control:r,help:n,htmlFor:a,start:o=!1}){return e.jsxs("div",{children:[e.jsxs("div",{className:o?bl:eo,children:[a?e.jsx("label",{htmlFor:a,className:Gr,children:t}):e.jsx("span",{className:Gr,children:t}),e.jsx("div",{className:to,children:r})]}),n?e.jsx("p",{className:`${Ct} mt-1.5`,children:n}):null]})}function kl({field:t,value:r,hasStored:n,onChange:a,platformId:o="",agentOptions:s=[]}){const{t:d}=ce(["settings"]),c=`integration-field-${t.key}`,[u,h]=i.useState(!1),x=i.useMemo(()=>o?Wa(d,o,t):{label:t.label,help:t.help,placeholder:t.placeholder,options:t.options},[d,o,t]),v=x.label,j=x.help,k=x.placeholder,P=x.options??t.options??[],N=e.jsxs(e.Fragment,{children:[v,t.required&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),y=t.secret&&n?d("settings:integrations.secretStored"):j||void 0;if(t.type==="boolean"){const m=r===!0;return e.jsx(Kt,{label:v,help:j,control:e.jsx(Ye,{checked:m,onChange:w=>a(t.key,w),label:v,size:"md",testId:`integration-field-${t.key}`})})}if(t.type==="agent")return e.jsx(Kt,{label:N,help:y,control:e.jsx("div",{className:"w-full","data-testid":`integration-field-${t.key}`,children:e.jsx(Ps,{value:r,options:s,onChange:a,fieldKey:t.key,ariaLabel:v})})});if(t.type==="select"&&t.multiple){const m=Array.isArray(r)?r.map(String):[];return e.jsx(Kt,{start:!0,label:N,help:y,control:e.jsx("div",{className:"flex flex-wrap justify-end gap-1.5","data-testid":`integration-field-${t.key}`,children:P.map(w=>{const V=m.includes(w.value);return e.jsx("button",{type:"button","aria-pressed":V,"data-option":w.value,onClick:()=>a(t.key,V?m.filter(T=>T!==w.value):[...m,w.value]),className:Yr(V),children:w.label},w.value)})})})}if(t.type==="select")return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsx("select",{id:c,"data-testid":`integration-field-${t.key}`,value:typeof r=="string"?r:"",onChange:m=>a(t.key,m.target.value),className:Jr,children:(t.options??[]).map(m=>{const w=P.find(V=>V.value===m.value)?.label??m.label;return e.jsx("option",{value:m.value,children:w},m.value)})})});const b=t.type==="password",A=t.type==="number";return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsxs("div",{className:"relative w-full",children:[e.jsx("input",{id:c,"data-testid":`integration-field-${t.key}`,type:A?"number":b&&!u?"password":"text",value:r==null?"":String(r),placeholder:b&&n?d("settings:integrations.secretStoredPlaceholder"):k,onChange:m=>a(t.key,m.target.value),className:`${Jr}${b?" font-mono pr-10":""}`}),b&&e.jsx("button",{type:"button","aria-label":u?d("settings:integrations.hide",{defaultValue:"Hide"}):d("settings:integrations.show",{defaultValue:"Show"}),onClick:()=>h(m=>!m),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:u?"🙈":"👁"})]})})}function At({status:t,draft:r,fields:n=t.fields,onChange:a,agentOptions:o=[]}){return e.jsx(e.Fragment,{children:n.map(s=>e.jsx(kl,{field:s,platformId:t.id,value:r[s.key],hasStored:t.secrets[s.key]?.hasValue===!0,agentOptions:o,onChange:a},s.key))})}const aa={pending:"bg-amber-400 animate-pulse",ok:"bg-emerald-500",failed:"bg-red-500"};function oa({label:t,hint:r,leg:n}){const{t:a}=ce("settings");return e.jsxs("div",{className:"flex items-start gap-2.5","data-testid":"connection-test-leg",children:[e.jsx("span",{className:`mt-1.5 w-2 h-2 rounded-full shrink-0 ${aa[n.state]??aa.pending}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm text-fg-primary",children:t}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 break-words",children:n.state==="ok"?n.detail??a("integrations.connectionTest.legOk",{defaultValue:"Verified"}):n.state==="failed"?n.detail??a("integrations.connectionTest.legFailed",{defaultValue:"Failed"}):r})]})]})}function Sl(t,r){const n=new Date(t);return Number.isNaN(n.getTime())?t:n.toLocaleString(r,{dateStyle:"medium",timeStyle:"short"})}function Cl({test:t,starting:r,onStart:n,lastVerifiedAt:a=null}){const{t:o,i18n:s}=ce("settings"),d=(()=>{if(!t)return null;switch(t.status){case"awaiting_reply":return o("integrations.connectionTest.awaitingReply",{defaultValue:"A test message was sent to {{target}}. Reply to it in {{platform}} to finish — include {{code}} if you can.",target:t.targetChannelName??t.targetChannelId??"",platform:t.platform,code:t.code??""});case"awaiting_inbound":return o("integrations.connectionTest.awaitingInbound",{defaultValue:"Send any message to this bot in {{platform}} — we will answer it to confirm both directions.",platform:t.platform});case"verified":return o("integrations.connectionTest.verified",{defaultValue:"Both directions work — Markus can send to and receive from this bot."});case"expired":return o("integrations.connectionTest.expired",{defaultValue:"No reply arrived in time. Check the bot is in the conversation, then try again."});default:return null}})();return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:o("integrations.connectionTest.title",{defaultValue:"Connection verification"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:o("integrations.connectionTest.subtitle",{defaultValue:"Sends a real message and waits for your reply — proves both directions."})})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(oa,{label:o("integrations.connectionTest.outbound",{defaultValue:"Outbound (bot → IM)"}),hint:o("integrations.connectionTest.outboundPending",{defaultValue:"Not sent yet"}),leg:t.outbound}),e.jsx(oa,{label:o("integrations.connectionTest.inbound",{defaultValue:"Inbound (IM → bot)"}),hint:o("integrations.connectionTest.inboundPending",{defaultValue:"Waiting for your reply"}),leg:t.inbound})]}),d&&(t.status==="verified"||t.status==="expired"?e.jsx(Jt,{type:t.status==="verified"?"ok":"err",text:d}):e.jsx("div",{className:"px-3 py-2 rounded-lg text-xs bg-surface-elevated text-fg-secondary",children:d}))]}):a?e.jsx(Jt,{type:"ok",text:o("integrations.connectionTest.lastVerified",{defaultValue:"Verified {{when}}.",when:Sl(a,s.language)})}):e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("integrations.connectionTest.idle",{defaultValue:"Not verified yet. Verify to send a real message to the bot and confirm the round trip."})}),e.jsxs("button",{type:"button",onClick:n,disabled:r,"data-testid":"connection-test-start",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-fg-primary border border-border-default rounded-lg hover:bg-surface-elevated disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[r?e.jsx("div",{className:"w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"}):null,t?o("integrations.connectionTest.retry",{defaultValue:"Verify again"}):o("integrations.connectionTest.start",{defaultValue:"Verify connection"})," "]})]})}function Al({status:t,values:r,setValue:n,channels:a=[],canListChannels:o=!1,channelsLoading:s=!1,channelsError:d=null,onReloadChannels:c=()=>{},channelsGuidance:u=null,testSlot:h}){const{t:x}=ce(["settings","common"]),[v,j]=i.useState(!1),k=Qt(t.fields),P=xl(t.fields),N=ul(t.fields),y=fl(t.fields,r),b=Ya(t.fields),A=N?r[N.key]!==!1:!0,m=o&&b?b.key:null,w=m!==null?String(r[m]??""):"",V={configured:x("settings:instances.notify.reachConfigured",{defaultValue:"Configured"}),"not-configured":x("settings:instances.notify.reachNotConfigured",{defaultValue:"Not set"}),unsupported:x("settings:instances.notify.reachUnsupported",{defaultValue:"Not supported"})},T={configured:"text-green-600","not-configured":"text-amber-600",unsupported:"text-fg-tertiary"},I={configured:"bg-green-500","not-configured":"bg-amber-400",unsupported:"bg-gray-400"},F=x("settings:instances.notify.guidanceFallback",{defaultValue:"This platform can’t list its conversations — enter the destination ID manually."}),C=u?x(u,{defaultValue:F}):F,$=m!==null&&!s&&w!==""&&!a.some(B=>B.id===w),D="text-xs font-medium text-fg-secondary mb-2";return e.jsxs("section",{"data-testid":"notification-panel","data-reachability":y,className:Ss,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsx("h3",{className:Wt,children:x("settings:instances.notify.title",{defaultValue:"Notifications"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs ${T[y]}`,"data-testid":"notification-reachability","data-state":y,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I[y]}`}),V[y]]}),N&&e.jsx(Ye,{checked:A,onChange:B=>n(N.key,B),label:x("settings:instances.notify.masterLabel",{defaultValue:"Enable notifications"}),size:"md",testId:`integration-field-${N.key}`})]})]}),e.jsxs("div",{className:`space-y-4${A?"":" opacity-60"}`,children:[k.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:D,children:x("settings:instances.notify.destination",{defaultValue:"Destination"})}),m!==null&&e.jsxs("div",{"data-testid":"notification-chat-list",className:"space-y-1.5",children:[e.jsx(Xa,{loading:s,error:d,onReload:c,empty:a.length===0,buttonTestId:"notification-chat-refresh",errorTestId:"notification-chat-error"}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(B=>e.jsx("button",{type:"button","aria-pressed":w===B.id,"data-testid":`notification-chat-pick-${B.id}`,onClick:()=>n(m,B.id),className:Yr(w===B.id),children:B.name},B.id))}),a.length===0&&!s&&!d&&e.jsx("p",{"data-testid":"notification-chat-empty",className:Ct,children:x("settings:instances.notify.pickEmpty",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}),$&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:e.jsx("button",{type:"button","aria-pressed":"true","data-testid":"notification-chat-pick-current",onClick:()=>n(m,w),className:Yr(!0),children:w})})]}),m===null&&e.jsx("p",{"data-testid":"notification-chat-guidance",className:Ct,children:C}),m!==null?e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","aria-expanded":v,"data-testid":"notification-manual-toggle",onClick:()=>j(B=>!B),className:"inline-flex items-center gap-1 text-xs font-medium text-fg-tertiary hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-3 h-3 transition-transform ${v?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),x("settings:instances.notify.manualInput",{defaultValue:"Enter an ID manually"})]}),v&&e.jsx("div",{className:"space-y-4 mt-3","data-testid":"notification-manual-fields",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}):e.jsx("div",{className:"mt-2",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}),P.length>0&&e.jsxs("div",{"data-testid":"notification-preferences",className:"space-y-3",children:[e.jsx("div",{className:D,children:x("settings:instances.notify.content",{defaultValue:"What to send"})}),e.jsx(At,{status:t,draft:r,fields:P,onChange:n})]}),h]})]})}const St={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"},Pl={color:"#64748b",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z"})})},Ml={feishu:{color:"#3370ff",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M21 5 3 11l5.5 2.2L19 7l-7.5 8.3L12 21l3-4.5L21 5z"})})},telegram:{color:"#229ed9",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M22 3 2.5 10.5l5.5 2L21 6l-9 10v5l3.5-4.5L20 19 22 3z"})})},slack:{color:"#611f69",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M9.5 3 7.5 20M16.5 4 14.5 21M3.5 9h17M2.5 15h17"})})},whatsapp:{color:"#1faa59",glyph:e.jsxs("g",{...St,children:[e.jsx("path",{d:"M21 11.5a8.5 8.5 0 0 1-12.6 7.4L3 20.5l1.6-5.3A8.5 8.5 0 1 1 21 11.5z"}),e.jsx("path",{d:"M9 8.8c.3 2.6 2.6 4.9 5.2 5.2l1-1.3 1.9.8"})]})},discord:{color:"#5865f2",glyph:e.jsxs("g",{...St,children:[e.jsx("rect",{x:"3",y:"7",width:"18",height:"10",rx:"4.5"}),e.jsx("path",{d:"M7.5 11.5h3M9 10v3"}),e.jsx("circle",{cx:"15",cy:"10.7",r:"0.9"}),e.jsx("circle",{cx:"17.3",cy:"13",r:"0.9"})]})}};function Tl(t){return Ml[t]??Pl}function so({id:t,size:r=36}){const n=Tl(t);return e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded-lg",style:{width:r,height:r,backgroundColor:`${n.color}1a`,color:n.color},"aria-hidden":"true","data-testid":`platform-icon-${t}`,children:e.jsx("svg",{width:Math.round(r*.58),height:Math.round(r*.58),viewBox:"0 0 24 24",children:n.glyph})})}function El({status:t,configured:r,canListChannels:n=!1,channelsGuidance:a=null}){const{t:o,i18n:s}=ce(["settings","common"]),[d,c]=i.useState(!r),u=i.useMemo(()=>{const v=Wi(s,o,t.id);if(Qt(t.fields).length===0)return v;const j=o("settings:integrations.guide.destinationStep.desc",{defaultValue:"Pick the chat or user that should receive approvals and notifications — without it they have nowhere to go."}),k=n?{title:o("settings:integrations.guide.selectChatStep.title",{defaultValue:"Pick the notification group"}),desc:o("settings:integrations.guide.selectChatStep.desc",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}:{title:o("settings:integrations.guide.destinationStep.title",{defaultValue:"Set a notification destination"}),desc:a?o(a,{defaultValue:j}):j};return[...v,k]},[s,o,t.id,t.fields,n,a]),h=qi(t.id),x=o(`settings:integrations.platforms.${t.id}.description`,{defaultValue:""});return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl overflow-hidden","data-testid":"integration-guide","data-open":d?"true":"false",children:[e.jsxs("button",{type:"button",onClick:()=>c(v=>!v),"aria-expanded":d,"data-testid":"integration-guide-toggle",className:"w-full flex items-center gap-2.5 px-4 py-3 text-left hover:bg-white/[0.02] transition-colors",children:[e.jsx("span",{className:"text-base leading-none","aria-hidden":"true",children:"🧭"}),e.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary",children:Gi(o)}),e.jsx("svg",{className:`w-4 h-4 text-fg-tertiary transition-transform ${d?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),d&&e.jsxs("div",{className:"px-4 pb-4 pt-1 space-y-3 border-t border-border-default",children:[x&&e.jsx("p",{className:"text-xs text-fg-tertiary",children:x}),u.length>0?e.jsx("ol",{className:"space-y-2.5","data-testid":"integration-guide-steps",children:u.map((v,j)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"shrink-0 w-5 h-5 mt-0.5 rounded-full bg-brand-500/15 text-brand-600 text-[11px] font-semibold flex items-center justify-center",children:j+1}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-medium text-fg-primary",children:v.title}),v.desc&&e.jsx("span",{className:"block text-[11px] text-fg-tertiary mt-0.5",children:v.desc})]})]},v.title))}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:o("settings:integrations.guide.fallback",{defaultValue:"Fill in the credentials from the platform’s developer console below."})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:[h&&e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer","data-testid":"integration-guide-console",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-brand-600 text-on-brand rounded-lg hover:bg-brand-700 transition-colors",children:[o("settings:integrations.guide.openConsole",{defaultValue:"Open developer console"}),e.jsx("span",{"aria-hidden":"true",children:"↗"})]}),t.docsUrl&&e.jsx("a",{href:t.docsUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-brand-600 hover:text-brand-700",children:o("settings:integrations.docs",{defaultValue:"Setup docs"})})]})]})]})}const ro={create:(t,r)=>U.settings.createInstance(t,r).then(n=>n.instance),save:(t,r)=>U.settings.saveInstance(t,r).then(()=>{}),test:(t,r)=>U.settings.testInstance(t,r),remove:t=>U.settings.deleteInstance(t).then(()=>{}),listChannels:t=>U.settings.listInstanceChannels(t),saveChannels:(t,r)=>U.settings.saveInstanceChannels(t,r).then(()=>{}),startConnectionTest:(t,r)=>U.settings.startConnectionTest(t,r).then(n=>n.test),getConnectionTest:t=>U.settings.getConnectionTest(t).then(r=>r.test)},Rl=700;function ia({instance:t,client:r=ro,extras:n={},onChanged:a,onCreated:o,loadAgents:s,defaultExpanded:d}){const{t:c}=ce(["settings","common"]),u=al(t),[h,x]=i.useState(d??u),[v,j]=i.useState(!1),k=i.useMemo(()=>ea(t),[t]),[P,N]=i.useState(t.label),[y,b]=i.useState(()=>Zn(k)),[A,m]=i.useState(t.enabled),[w,V]=i.useState(t.channels),[T,I]=i.useState(typeof t.notifyAgentId=="string"?t.notifyAgentId:""),[F,C]=i.useState({kind:"idle"}),$=!!n[t.platform]?.guidedSetup,[D,B]=i.useState($&&!t.hasConfig?"guided":"manual"),S=$&&D==="guided",{channels:L,error:J,loading:_,reloadChannels:H}=cl(r.listChannels,t.id,h&&t.canListChannels),[X,me]=i.useState(""),[ie,ee]=i.useState(null),[f,R]=i.useState(!1),[p,K]=i.useState(null),z=tl(ie),[se,ae]=i.useState(!1),ge=t.fields.some(E=>E.type==="agent"),te=hl(i.useMemo(()=>s??Za,[s]),ge),Ze=i.useCallback(E=>E?te.find(ne=>ne.id===E)?.name??E:"",[te]),Me=Xi(k),Pe=i.useRef(t);Pe.current=t;const Be=i.useRef(!1),ct=i.useRef(!1);i.useEffect(()=>{if(Be.current)return;const E=Pe.current;N(E.label),b(Zn(ea(E))),m(E.enabled),V(E.channels),I(typeof E.notifyAgentId=="string"?E.notifyAgentId:"")},[Me]),i.useEffect(()=>{C({kind:"idle"}),ee(null),K(null),gt(!1)},[t.id]),i.useEffect(()=>{B($&&!t.hasConfig?"guided":"manual")},[t.id,t.hasConfig,$]);const Se=i.useCallback(()=>{Be.current=!0,C({kind:"idle"})},[]),fe=i.useCallback((E,ne)=>{Se(),b(ue=>({...ue,[E]:ne}))},[Se]),Zt=i.useCallback(E=>{Se(),N(E)},[Se]),Xe=i.useCallback(E=>{Se(),m(E)},[Se]),Pt=i.useRef(()=>Promise.resolve()),De=i.useCallback(async()=>{if(!ct.current){ct.current=!0,C({kind:"saving"});try{let E=Pe.current.id;E||(E=(await r.create(Pe.current.platform,P.trim())).id),await r.save(E,{...Yi(k,y,A),notifyAgentId:T}),Pe.current.canListChannels&&await r.saveChannels(E,w);let ne=null;try{const{ok:ue,text:He,code:Le}=el(await r.test(E,{}));!ue&&!/not supported/i.test(He)&&(ne=Le==="network_unreachable"?c("settings:integrations.savedNotVerifiedNetwork"):c("settings:integrations.savedNotVerified",{reason:He}))}catch(ue){ne=c("settings:integrations.savedNotVerified",{reason:String(ue)})}Be.current=!1,C(ne?{kind:"error",text:ne}:{kind:"saved"}),await a?.(),Pe.current.id===""&&o?.(E)}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}finally{ct.current=!1}}},[r,k,y,A,T,w,P,c,a,o]);Pt.current=De;const ut=Xn(k.fields,y,t.secrets),Xt=u&&P.trim()==="",es=w.every(E=>E.agentId),et=!S&&!Xt&&ut.length===0&&es,Ie=i.useMemo(()=>JSON.stringify([P,A,T,w,y]),[P,A,T,w,y]);i.useEffect(()=>{if(!Be.current||!et)return;const E=setTimeout(()=>{Pt.current()},Rl);return()=>clearTimeout(E)},[Ie,et]),i.useEffect(()=>{if(!h||u)return;let E=!0;return r.getConnectionTest(t.id).then(ne=>{E&&ne&&ee(ne)}).catch(()=>{}),()=>{E=!1}},[h,u,r,t.id]),i.useEffect(()=>{if(!h||!z)return;let E=!0;const ne=setInterval(()=>{r.getConnectionTest(t.id).then(ue=>{E&&ue&&ee(ue)}).catch(()=>{})},2500);return()=>{E=!1,clearInterval(ne)}},[h,z,r,t.id]);const Mt=i.useRef(null);i.useEffect(()=>{ie?.status==="verified"&&Mt.current!==t.id&&(Mt.current=t.id,a?.())},[ie?.status,t.id,a]);const ts=i.useCallback(async()=>{R(!0),K(null);try{ee(await r.startConnectionTest(t.id))}catch(E){K(E instanceof Error?E.message:String(E))}finally{R(!1)}},[r,t.id]),ye=n[t.platform],Ue=i.useMemo(()=>({platformId:t.platform,instanceId:t.id||void 0,status:k,values:y,setValue:fe,reload:()=>{a?.()},agents:te,onCreated:o,setupMethod:$?D:void 0,setSetupMethod:$?B:void 0}),[t.platform,t.id,k,y,fe,a,te,o,$,D]),ss=i.useMemo(()=>new Set(ye?.ownedFields??[]),[ye]),mt=Qt(k.fields).length>0,rs=i.useMemo(()=>new Set(mt?gl(k.fields).map(E=>E.key):[]),[k.fields,mt]),xt=i.useMemo(()=>k.fields.filter(E=>!ss.has(E.key)&&!rs.has(E.key)),[k.fields,ss,rs]),Tt=i.useMemo(()=>Qi(xt),[xt]),ns=i.useMemo(()=>Zi(xt),[xt]),Ts=i.useMemo(()=>Tt.filter(E=>E.type==="agent"),[Tt]),Et=i.useMemo(()=>Tt.filter(E=>E.type!=="agent"),[Tt]),[Rt,gt]=i.useState(!1),It=i.useMemo(()=>Xn(t.fields,t.values,t.secrets),[t.fields,t.values,t.secrets]),tt=t.hasConfig&&!It.some(E=>Et.some(ne=>ne.key===E)),tn=i.useMemo(()=>il(L,X),[L,X]),as=i.useMemo(()=>ol(w,L),[w,L]),Lt=w.filter(E=>!E.agentId).length,Es=i.useCallback((E,ne)=>{Se(),V(ue=>ne?ta(ue,E.id,hr(ue,E.id)?.agentId??t.agentId??"",E.kind??null):sa(ue,E.id))},[Se,t.agentId]),Te=i.useCallback((E,ne)=>{Se(),V(ue=>ta(ue,E,ne,hr(ue,E)?.kind??null))},[Se]),Rs=i.useCallback(async()=>{ae(!1);try{await r.remove(t.id),await a?.()}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}},[r,t.id,a]),ft=sl(t,ie?.status==="verified"),re=t.id||`new-${t.platform}`,Ke=`instance-name-${re}`,pt=ut.map(E=>{const ne=k.fields.find(ue=>ue.key===E);return ne?Wa(c,t.platform,ne).label:E}).join(", ");return e.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden border border-border-default","data-testid":`instance-card-${re}`,"data-instance":t.id,"data-platform":t.platform,"data-draft":u?"true":"false","data-expanded":h?"true":"false","data-connection":ft,children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":h,"data-testid":`instance-toggle-${re}`,className:"flex-1 min-w-0 flex items-center gap-3 text-left",children:[e.jsx(so,{id:t.platform}),e.jsxs("span",{className:"flex-1 min-w-0 flex items-center gap-2.5",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate","data-testid":`instance-label-${re}`,children:P.trim()===""?c("settings:instances.newBot",{defaultValue:"New bot"}):P}),!u&&e.jsx("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[10px] font-medium bg-surface-secondary border border-border-default text-fg-tertiary","data-testid":`instance-platform-${re}`,children:t.platform}),!u&&t.agentId&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1.5 text-xs text-fg-tertiary truncate","data-testid":`instance-agent-${re}`,title:c("settings:instances.boundAgent",{defaultValue:"Bound agent"}),children:[e.jsx("span",{className:"text-fg-muted",children:"→"}),Ze(t.agentId)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[e.jsx(wl,{state:ft}),!u&&e.jsx(Ye,{checked:A,onChange:Xe,size:"md",testId:`instance-enabled-${re}`,label:c("settings:instances.toggleLabel",{defaultValue:"Turn this bot on or off"})}),e.jsx("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":h,"data-testid":`instance-chevron-${re}`,className:"p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:e.jsx("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})})]})]}),h&&e.jsxs("div",{className:"px-6 pb-6 pt-5 border-t border-border-default space-y-6",children:[!t.hasConfig&&!S&&e.jsx(El,{status:k,configured:t.hasConfig,canListChannels:t.canListChannels,channelsGuidance:t.channelsGuidance??null}),!$&&ye?.placement==="before"&&ye.render(Ue),e.jsxs("section",{"data-testid":`instance-credentials-${re}`,className:Ss,children:[e.jsx("h3",{className:`${Wt} mb-3`,children:t.hasConfig?c("settings:instances.setup.configuredTitle",{defaultValue:"Bot setup"}):$?c("settings:instances.setup.title",{defaultValue:"Connection"}):c("settings:instances.credentials",{defaultValue:"Credentials"})}),$&&!t.hasConfig&&e.jsx("div",{role:"tablist",className:"inline-flex rounded-lg border border-border-default bg-surface-secondary p-0.5 mb-4",children:["guided","manual"].map(E=>e.jsx("button",{type:"button",role:"tab","aria-selected":D===E,onClick:()=>B(E),"data-testid":`setup-method-${E}-${re}`,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${D===E?"bg-surface-elevated text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:E==="guided"?c("settings:instances.setup.guided",{defaultValue:"Scan to create (recommended)"}):c("settings:instances.setup.manual",{defaultValue:"Enter credentials manually"})},E))}),S?e.jsx("div",{className:"space-y-4",children:ye.render(Ue)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:eo,children:[e.jsxs("label",{htmlFor:Ke,className:Gr,children:[c("settings:instances.addBot.name",{defaultValue:"Bot name"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),e.jsx("div",{className:to,children:e.jsx("input",{id:Ke,"data-testid":`new-bot-name-${t.platform}`,value:P,onChange:E=>Zt(E.target.value),placeholder:c("settings:instances.addBot.namePlaceholder",{defaultValue:"e.g. Sales"}),className:Jr})})]}),Ts.length>0&&e.jsx(At,{status:k,draft:y,fields:Ts,onChange:fe,agentOptions:te}),Et.length>0&&(tt&&!Rt?e.jsx("div",{"data-testid":`instance-credentials-configured-${re}`,className:"space-y-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!0),"data-testid":`instance-credentials-edit-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsEdit",{defaultValue:"Change"})})]})}):e.jsxs("div",{className:"space-y-3",children:[tt&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!1),"data-testid":`instance-credentials-hide-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsHide",{defaultValue:"Hide"})})]}),e.jsx(At,{status:k,draft:y,fields:Et,onChange:fe,agentOptions:te})]}))]}),e.jsx("div",{className:"mt-3 min-h-[1.25rem]","data-testid":`instance-save-state-${re}`,children:e.jsxs("span",{"data-state":F.kind,className:"inline-flex items-center gap-2 text-xs text-fg-tertiary",children:[F.kind==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),c("settings:instances.autosave.saving",{defaultValue:"Saving…"})]}),F.kind==="saved"&&e.jsxs("span",{className:"text-green-600",children:["✓ ",c("settings:instances.autosave.saved",{defaultValue:"Saved"})]}),!et&&!S&&e.jsx("span",{"data-testid":`instance-missing-${re}`,children:ut.length>0?c("settings:integrations.missingRequired",{defaultValue:"Required: {{fields}}",fields:pt}):c("settings:instances.addBot.labelRequired",{defaultValue:"Give the bot a name."})})]})}),F.kind==="error"&&e.jsx("div",{className:"mt-2",children:e.jsx(Jt,{type:"err",text:F.text})})]}),!u&&e.jsxs("section",{children:[e.jsx(Cl,{test:ie,starting:f,lastVerifiedAt:t.lastVerifiedAt,onStart:()=>{ts()}}),p&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:p})})]}),!u&&mt&&e.jsx(Al,{status:k,values:y,setValue:fe,channels:L,canListChannels:t.canListChannels,channelsLoading:_,channelsError:J,onReloadChannels:H,channelsGuidance:t.channelsGuidance??null,testSlot:ye?.sendTest?.(Ue)}),e.jsxs("section",{"data-testid":`instance-more-${re}`,children:[e.jsxs("button",{type:"button",onClick:()=>j(E=>!E),"aria-expanded":v,"data-testid":`instance-more-toggle-${re}`,className:"w-full flex items-center gap-2 text-left group px-1",children:[e.jsx("span",{className:Wt,children:c("settings:instances.moreSettings",{defaultValue:"Advanced"})}),e.jsx("span",{className:`${Ct} truncate hidden sm:inline`,children:c("settings:instances.moreSettingsHint",{defaultValue:"Chat routing and platform options"})}),e.jsx("svg",{className:`ml-auto w-3.5 h-3.5 text-fg-tertiary transition-transform ${v?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),v&&e.jsxs("div",{className:"mt-3 space-y-4",children:[ns.length>0&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.advancedTitle",{defaultValue:"Platform options"})}),!u&&e.jsx("p",{className:`${Ct} mb-3`,children:c("settings:instances.advancedHint",{defaultValue:"These default to the right value for almost every setup — leave them alone unless you know you need them."})}),e.jsx(At,{status:k,draft:y,fields:ns,onChange:fe,agentOptions:te})]}),!u&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.routing.chats",{defaultValue:"Chat routing"})}),e.jsx("p",{className:`${Ct} mb-3`,children:c("settings:instances.routing.chatsHint",{defaultValue:"The agent bound above answers every chat by default. Route a specific chat to a different agent here."})}),!t.canListChannels&&e.jsx("p",{className:"text-[11px] text-fg-tertiary","data-testid":`instance-chats-unsupported-${re}`,children:t.channelsGuidance?c(t.channelsGuidance,{defaultValue:c("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}):c("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}),t.canListChannels&&e.jsx("div",{className:"mb-2",children:e.jsx(Xa,{loading:_,error:J,onReload:H,empty:L.length===0,buttonTestId:`instance-chats-refresh-${re}`,errorTestId:`instance-chats-error-${re}`})}),t.canListChannels&&L.length>0&&e.jsx("input",{type:"text",value:X,onChange:E=>me(E.target.value),placeholder:c("settings:instances.routing.searchChats",{defaultValue:"Search chats…"}),"data-testid":`instance-chat-search-${re}`,className:"w-full mb-2 px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500"}),e.jsxs("div",{className:"space-y-2","data-testid":`instance-chats-${re}`,children:[tn.map(E=>{const ne=hr(w,E.id);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!!ne,"data-testid":`instance-chat-toggle-${re}-${E.id}`,onChange:ue=>Es(E,ue.target.checked),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate",title:E.id,children:E.name})]}),ne&&e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.id}`,children:e.jsx(Ps,{value:ne.agentId,options:te,onChange:(ue,He)=>Te(E.id,typeof He=="string"?He:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.id)}),as.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!0,"data-testid":`instance-chat-toggle-${re}-${E.nativeId}`,onChange:()=>V(ne=>sa(ne,E.nativeId)),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate font-mono text-xs",title:E.nativeId,children:E.nativeId})]}),e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.nativeId}`,children:e.jsx(Ps,{value:E.agentId,options:te,onChange:(ne,ue)=>Te(E.nativeId,typeof ue=="string"?ue:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.nativeId))]}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-2",children:c("settings:instances.routing.autoSaved",{defaultValue:"Changes are saved automatically."})}),Lt>0&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:c("settings:instances.routing.agentRequired",{defaultValue:"Pick an agent for every selected chat ({{count}} still unassigned).",count:Lt})})})]})]})]}),!$&&ye&&ye.placement!=="before"&&ye.render(Ue),!u&&e.jsx("div",{className:"pt-1",children:e.jsx("button",{type:"button",onClick:()=>ae(!0),"data-testid":`instance-disconnect-${re}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-600 border border-red-500/30 rounded-lg hover:bg-red-500/10 transition-colors",children:c("settings:integrations.disconnect",{defaultValue:"Disconnect"})})})]}),se&&e.jsx(Cs,{title:c("settings:integrations.disconnectConfirmTitle",{defaultValue:"Disconnect this bot?"}),message:c("settings:integrations.disconnectConfirmMessage",{defaultValue:"Its stored credentials are removed and it stops sending and receiving messages. This cannot be undone."}),confirmLabel:c("settings:integrations.disconnect",{defaultValue:"Disconnect"}),variant:"danger",onConfirm:()=>{Rs()},onCancel:()=>ae(!1)})]})}var Nt={},br,la;function Il(){return la||(la=1,br=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),br}var yr={},Ge={},da;function lt(){if(da)return Ge;da=1;let t;const r=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ge.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},Ge.getSymbolTotalCodewords=function(a){return r[a]},Ge.getBCHDigit=function(n){let a=0;for(;n!==0;)a++,n>>>=1;return a},Ge.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');t=a},Ge.isKanjiModeEnabled=function(){return typeof t<"u"},Ge.toSJIS=function(a){return t(a)},Ge}var vr={},ca;function en(){return ca||(ca=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function r(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,o){if(t.isValid(a))return a;try{return r(a)}catch{return o}}})(vr)),vr}var jr,ua;function Ll(){if(ua)return jr;ua=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(r){const n=Math.floor(r/8);return(this.buffer[n]>>>7-r%8&1)===1},put:function(r,n){for(let a=0;a<n;a++)this.putBit((r>>>n-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),r&&(this.buffer[n]|=128>>>this.length%8),this.length++}},jr=t,jr}var Nr,ma;function Ol(){if(ma)return Nr;ma=1;function t(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}return t.prototype.set=function(r,n,a,o){const s=r*this.size+n;this.data[s]=a,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(r,n){return this.data[r*this.size+n]},t.prototype.xor=function(r,n,a){this.data[r*this.size+n]^=a},t.prototype.isReserved=function(r,n){return this.reservedBit[r*this.size+n]},Nr=t,Nr}var wr={},xa;function $l(){return xa||(xa=1,(function(t){const r=lt().getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const o=Math.floor(a/7)+2,s=r(a),d=s===145?26:Math.ceil((s-13)/(2*o-2))*2,c=[s-7];for(let u=1;u<o-1;u++)c[u]=c[u-1]-d;return c.push(6),c.reverse()},t.getPositions=function(a){const o=[],s=t.getRowColCoords(a),d=s.length;for(let c=0;c<d;c++)for(let u=0;u<d;u++)c===0&&u===0||c===0&&u===d-1||c===d-1&&u===0||o.push([s[c],s[u]]);return o}})(wr)),wr}var kr={},ga;function Bl(){if(ga)return kr;ga=1;const t=lt().getSymbolSize,r=7;return kr.getPositions=function(a){const o=t(a);return[[0,0],[o-r,0],[0,o-r]]},kr}var Sr={},fa;function Dl(){return fa||(fa=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const r={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let d=0,c=0,u=0,h=null,x=null;for(let v=0;v<s;v++){c=u=0,h=x=null;for(let j=0;j<s;j++){let k=o.get(v,j);k===h?c++:(c>=5&&(d+=r.N1+(c-5)),h=k,c=1),k=o.get(j,v),k===x?u++:(u>=5&&(d+=r.N1+(u-5)),x=k,u=1)}c>=5&&(d+=r.N1+(c-5)),u>=5&&(d+=r.N1+(u-5))}return d},t.getPenaltyN2=function(o){const s=o.size;let d=0;for(let c=0;c<s-1;c++)for(let u=0;u<s-1;u++){const h=o.get(c,u)+o.get(c,u+1)+o.get(c+1,u)+o.get(c+1,u+1);(h===4||h===0)&&d++}return d*r.N2},t.getPenaltyN3=function(o){const s=o.size;let d=0,c=0,u=0;for(let h=0;h<s;h++){c=u=0;for(let x=0;x<s;x++)c=c<<1&2047|o.get(h,x),x>=10&&(c===1488||c===93)&&d++,u=u<<1&2047|o.get(x,h),x>=10&&(u===1488||u===93)&&d++}return d*r.N3},t.getPenaltyN4=function(o){let s=0;const d=o.data.length;for(let u=0;u<d;u++)s+=o.data[u];return Math.abs(Math.ceil(s*100/d/5)-10)*r.N4};function n(a,o,s){switch(a){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(o,s){const d=s.size;for(let c=0;c<d;c++)for(let u=0;u<d;u++)s.isReserved(u,c)||s.xor(u,c,n(o,u,c))},t.getBestMask=function(o,s){const d=Object.keys(t.Patterns).length;let c=0,u=1/0;for(let h=0;h<d;h++){s(h),t.applyMask(h,o);const x=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(h,o),x<u&&(u=x,c=h)}return c}})(Sr)),Sr}var js={},pa;function no(){if(pa)return js;pa=1;const t=en(),r=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return js.getBlocksCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},js.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},js}var Cr={},Ht={},ha;function Vl(){if(ha)return Ht;ha=1;const t=new Uint8Array(512),r=new Uint8Array(256);return(function(){let a=1;for(let o=0;o<255;o++)t[o]=a,r[a]=o,a<<=1,a&256&&(a^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Ht.log=function(a){if(a<1)throw new Error("log("+a+")");return r[a]},Ht.exp=function(a){return t[a]},Ht.mul=function(a,o){return a===0||o===0?0:t[r[a]+r[o]]},Ht}var ba;function _l(){return ba||(ba=1,(function(t){const r=Vl();t.mul=function(a,o){const s=new Uint8Array(a.length+o.length-1);for(let d=0;d<a.length;d++)for(let c=0;c<o.length;c++)s[d+c]^=r.mul(a[d],o[c]);return s},t.mod=function(a,o){let s=new Uint8Array(a);for(;s.length-o.length>=0;){const d=s[0];for(let u=0;u<o.length;u++)s[u]^=r.mul(o[u],d);let c=0;for(;c<s.length&&s[c]===0;)c++;s=s.slice(c)}return s},t.generateECPolynomial=function(a){let o=new Uint8Array([1]);for(let s=0;s<a;s++)o=t.mul(o,new Uint8Array([1,r.exp(s)]));return o}})(Cr)),Cr}var Ar,ya;function Fl(){if(ya)return Ar;ya=1;const t=_l();function r(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return r.prototype.initialize=function(a){this.degree=a,this.genPoly=t.generateECPolynomial(this.degree)},r.prototype.encode=function(a){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(a.length+this.degree);o.set(a);const s=t.mod(o,this.genPoly),d=this.degree-s.length;if(d>0){const c=new Uint8Array(this.degree);return c.set(s,d),c}return s},Ar=r,Ar}var Pr={},Mr={},Tr={},va;function ao(){return va||(va=1,Tr.isValid=function(r){return!isNaN(r)&&r>=1&&r<=40}),Tr}var $e={},ja;function oo(){if(ja)return $e;ja=1;const t="[0-9]+",r="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
|
|
1
|
+
import{j as e,r as i,u as ce,a7 as Cs,aa as Hr,V as Un,k as U,h as Gt,a5 as zo,ab as Wo,a1 as Go,a3 as Jo,ac as Yo,ad as Qo,ae as Zo,af as Xo,U as ei,ag as ti,a0 as si,ah as ri,ai as ni,aj as ai,ak as Kn,al as oi,n as ws,P as qr,_ as ii,am as li,an as di,ao as ci,ap as ui,aq as mi,ar as Hn,as as gr,at as fr,au as qn,av as xi,a as gi,b as fi,c as pi,aw as zn,ax as hi,ay as bi,az as Wn,aA as Ha,aB as yi,i as vi,aC as ji}from"./index-CudHikwU.js";import{L as Ni}from"./AsyncState-CeDmMBla.js";import{i as wi,n as ki,S as Ye}from"./Switch-DGrHkwcq.js";function Si(t,r){for(var n=0;n<r.length;n++){const a=r[n];if(typeof a!="string"&&!Array.isArray(a)){for(const o in a)if(o!=="default"&&!(o in t)){const s=Object.getOwnPropertyDescriptor(a,o);s&&Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:()=>a[o]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}const Ci=/ECONNREFUSED|EPIPE|ECONNRESET/i,Ai=/ENOTFOUND|EAI_AGAIN/i,Pi=/TIMEDOUT|timeout|ABORT_ERR|UND_ERR_(CONNECT|HEADERS|BODY)_TIMEOUT/i;function Mi(t){const r=(t?.detail??"").trim(),n=t?.code??"",a=r||n||"unknown";return n==="probe_http_error"?{key:"networkProxy.failProbeHttp",params:{detail:a}}:n==="network_unreachable"?Ci.test(r)?{key:"networkProxy.failRefused",params:{detail:a}}:Ai.test(r)?{key:"networkProxy.failDns",params:{detail:a}}:Pi.test(r)?{key:"networkProxy.failTimeout",params:{detail:a}}:{key:"networkProxy.failUnreachable",params:{detail:a}}:{key:"networkProxy.failUnknown",params:{detail:a}}}const we="bg-surface-elevated rounded-xl border border-border-default/40",Fe={pageTitle:"text-lg font-semibold",groupTitle:"text-[13px] font-semibold",groupDesc:"text-xs leading-relaxed",hint:"text-[11px] leading-relaxed",badge:"text-[11px] font-medium"},Qe={strong:"text-fg-primary",desc:"text-fg-tertiary"},kt="px-3 py-2 text-[13px] bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder:text-fg-tertiary/50 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 outline-none transition-colors",zr="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-[13px] font-medium bg-brand-600 hover:bg-brand-500 text-on-brand disabled:opacity-40 rounded-lg transition-colors",it="inline-flex items-center justify-center gap-1.5 px-3 py-2 text-[13px] font-medium border border-border-default text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary disabled:opacity-40 rounded-lg transition-colors";function Je({tone:t="neutral",children:r,title:n}){const a={neutral:"bg-fg-tertiary/10 text-fg-tertiary",ok:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",warn:"bg-amber-500/15 text-amber-600 dark:text-amber-400",danger:"bg-red-500/15 text-red-500",brand:"bg-brand-500/15 text-brand-500"};return e.jsx("span",{title:n,className:`${Fe.badge} rounded px-1.5 py-0.5 ${a[t]}`,children:r})}function je({label:t,hint:r,children:n}){return e.jsxs("div",{className:"flex flex-wrap items-start gap-x-6 gap-y-2 px-5 py-3.5",children:[e.jsxs("div",{className:"min-w-[7rem] flex-1",children:[t&&e.jsx("div",{className:"text-[13px] font-medium text-fg-primary",children:t}),r&&e.jsx("div",{className:"mt-0.5 text-[11px] leading-relaxed text-fg-tertiary",children:r})]}),n&&e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n})]})}function ke({title:t,description:r,action:n,children:a}){return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),n]}),e.jsx("div",{className:"space-y-3",children:a})]})}function Gn({title:t,description:r,children:n,defaultOpen:a=!0}){const[o,s]=i.useState(a);return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("button",{type:"button",onClick:()=>s(!o),className:"flex items-start justify-between w-full group text-left",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),e.jsx("span",{className:`text-fg-tertiary mt-0.5 transition-transform group-hover:text-fg-secondary ${o?"":"-rotate-90"}`,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),o&&e.jsx("div",{className:"space-y-3",children:n})]})}function Ti(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${(t/1e3).toFixed((t%1e3===0,0))}K`:String(t)}function Ei(t){return t.maxInputTokens>0||t.inputCostPer1MTokens>0||t.outputCostPer1MTokens>0}function pr(t){if(t.tier)return t.tier;const r=t.id.toLowerCase(),n=/opus|5\.4|o3-(?!mini)|o1-(?!mini)|gemini.*ultra|sonnet-4-20/,a=/haiku|flash|nano|lite|small|fast|free|8b|7b|1b|3b/;return/o4-mini|o3-mini|o1-mini|gpt-4o-mini/.test(r)?"pro":n.test(r)?"max":a.test(r)?"base":"pro"}const Jn={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30"};function qa({models:t,selectedModel:r,onSelect:n,loading:a,compact:o,maxVisible:s,showTiers:d}){const{t:c}=ce("settings"),[u,h]=i.useState(""),[x,v]=i.useState(!1),[j,k]=i.useState(""),P=i.useMemo(()=>{let m=t;if(u){const w=u.toLowerCase();m=m.filter(V=>V.id.toLowerCase().includes(w))}return j&&(m=m.filter(w=>pr(w)===j)),m},[t,u,j]),N=i.useMemo(()=>{const m={max:0,pro:0,base:0};for(const w of t)m[pr(w)]++;return m},[t]),y=s??(o?5:10),b=x?P:P.slice(0,y),A=P.length>y;return a?e.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-fg-tertiary",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),c("modelPicker.loading")]}):t.length===0?e.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:c("modelPicker.empty")}):e.jsxs("div",{className:"space-y-2",children:[d&&t.length>3&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>k(""),className:`px-2 py-0.5 rounded text-[10px] transition-colors ${j?"bg-surface-overlay text-fg-tertiary hover:text-fg-secondary":"bg-brand-500/20 text-brand-500"}`,children:c("modelPicker.allCount",{count:t.length})}),["max","pro","base"].filter(m=>N[m]>0).map(m=>e.jsx("button",{onClick:()=>k(j===m?"":m),className:`px-2 py-0.5 rounded text-[10px] font-medium uppercase transition-colors border ${j===m?Jn[m]:"border-transparent bg-surface-overlay text-fg-tertiary hover:text-fg-secondary"}`,children:c("modelPicker.tierCount",{tier:c(`modelRouting.tier.${m}`),count:N[m]})},m))]}),t.length>5&&e.jsx("input",{type:"text",value:u,onChange:m=>{h(m.target.value),v(!1)},placeholder:c("modelPicker.filterPlaceholder"),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"}),e.jsx("div",{className:`space-y-1 ${o?"max-h-[280px] overflow-y-auto":""}`,children:b.map(m=>{const w=m.id===r,V=pr(m);return e.jsxs("button",{type:"button",onClick:()=>n(m.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${w?"bg-brand-500/10 border border-brand-500/30":"hover:bg-surface-overlay border border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${w?"border-brand-500":"border-border-default"}`,children:w&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),e.jsx("span",{className:`text-xs font-medium ${w?"text-brand-500":"text-fg-primary"}`,children:m.id}),d&&e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-semibold uppercase border ${Jn[V]}`,children:c(`modelRouting.tier.${V}`)})]}),e.jsx("div",{className:"flex items-center gap-2",children:w&&e.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:c("modelPicker.active")})})]}),Ei(m)&&m.maxInputTokens>0&&e.jsx("div",{className:"ml-5 mt-0.5 flex items-center gap-2 text-[10px] text-fg-tertiary flex-wrap",children:e.jsxs("span",{children:[Ti(m.maxInputTokens)," ",c("modelPicker.ctx")]})}),!o&&e.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[m.capabilities.functionCalling&&e.jsx(Ft,{label:c("modelPicker.capabilities.tools")}),m.capabilities.vision&&e.jsx(Ft,{label:c("modelPicker.capabilities.vision")}),m.capabilities.reasoning&&e.jsx(Ft,{label:c("modelPicker.capabilities.reasoning")}),m.capabilities.promptCaching&&e.jsx(Ft,{label:c("modelPicker.capabilities.caching")}),m.capabilities.webSearch&&e.jsx(Ft,{label:c("modelPicker.capabilities.search")})]})]},m.id)})}),A&&!x&&e.jsx("button",{type:"button",onClick:()=>v(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:c("modelPicker.showAll",{count:P.length})}),x&&A&&e.jsx("button",{type:"button",onClick:()=>v(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:c("modelPicker.showLess")})]})}function Ft({label:t}){return e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] bg-surface-overlay text-fg-tertiary border border-border-default",children:t})}function Yt({value:t,options:r,placeholder:n,onChange:a}){const{t:o}=ce("settings"),[s,d]=i.useState(!1),[c,u]=i.useState(""),h=i.useRef(null),x=i.useRef(null),v=i.useRef(null),[j,k]=i.useState(-1);i.useEffect(()=>{function m(w){h.current&&!h.current.contains(w.target)&&d(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),i.useEffect(()=>{s&&x.current&&x.current.focus()},[s]);const P=i.useMemo(()=>{if(!c.trim())return r;const m=c.toLowerCase();return r.filter(w=>w.modelId.toLowerCase().includes(m)||w.modelName.toLowerCase().includes(m)||w.provider.toLowerCase().includes(m)||w.providerLabel.toLowerCase().includes(m)||w.tier&&w.tier.toLowerCase().includes(m))},[r,c]),N=i.useMemo(()=>{const m=new Map;for(const V of P){const T=V.providerLabel;m.has(T)||m.set(T,[]),m.get(T).push(V)}const w={max:0,pro:1,base:2};for(const V of m.values())V.sort((T,I)=>(w[T.tier??"base"]??9)-(w[I.tier??"base"]??9));return m},[P]),y=i.useMemo(()=>{const m=[];for(const w of N.values())m.push(...w);return m},[N]),b=i.useMemo(()=>{if(!t)return n??o("modelRouting.auto");const m=r.find(w=>`${w.provider}/${w.modelId}`===t);return m?`${m.providerLabel}/${m.modelName}`:t},[t,r,n,o]);function A(m){if(!s){(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d(!0));return}switch(m.key){case"ArrowDown":m.preventDefault(),k(w=>Math.min(w+1,y.length-1));break;case"ArrowUp":m.preventDefault(),k(w=>Math.max(w-1,-1));break;case"Enter":if(m.preventDefault(),j===-1)a("",null);else if(y[j]){const w=y[j];a(`${w.provider}/${w.modelId}`,w)}d(!1),u("");break;case"Escape":d(!1),u("");break}}return i.useEffect(()=>{v.current&&j>=0&&v.current.querySelector(`[data-focus-index="${j}"]`)?.scrollIntoView({block:"nearest"})},[j]),e.jsxs("div",{ref:h,className:"relative min-w-0",onKeyDown:A,children:[e.jsx("button",{type:"button",onClick:()=>{d(!s),u(""),k(-1)},className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary text-left truncate focus:outline-none focus:border-brand-500",children:b}),s&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[240px] max-h-[280px] bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden flex flex-col",children:[e.jsx("div",{className:"p-1.5 border-b border-border-default",children:e.jsx("input",{ref:x,type:"text",value:c,onChange:m=>{u(m.target.value),k(-1)},placeholder:o("modelPicker.searchPlaceholder")||"Search models...",className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary focus:outline-none focus:border-brand-500"})}),e.jsxs("div",{ref:v,className:"overflow-y-auto flex-1",children:[e.jsx("div",{className:`px-3 py-1.5 text-xs cursor-pointer ${j===-1?"bg-brand-500/20 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,onClick:()=>{a("",null),d(!1),u("")},children:n??o("modelRouting.auto")}),[...N.entries()].map(([m,w])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 py-1 text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider bg-surface-overlay/50 sticky top-0",children:m}),w.map(V=>{const T=y.indexOf(V),I=`${V.provider}/${V.modelId}`===t;return e.jsxs("div",{"data-focus-index":T,className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${T===j?"bg-brand-500/20":I?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,onClick:()=>{a(`${V.provider}/${V.modelId}`,V),d(!1),u("")},children:[e.jsx("span",{className:"flex-1 truncate text-fg-primary",children:V.modelName}),V.tier&&e.jsx(Ri,{tier:V.tier}),V.costTier&&e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:V.costTier})]},`${V.provider}/${V.modelId}`)})]},m)),y.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:o("modelPicker.empty")})]})]})]})}function Ri({tier:t}){const r={max:"bg-purple-500/20 text-purple-400",pro:"bg-blue-500/20 text-blue-400",base:"bg-gray-500/20 text-gray-400"};return e.jsx("span",{className:`px-1 py-0.5 rounded text-[8px] font-bold uppercase ${r[t]??r.base}`,children:t})}const Ii=500,Yn=[{groupKey:"image",capabilities:["image_recognition","image_generation"]},{groupKey:"audio",capabilities:["audio_tts","audio_stt"]},{groupKey:"video",capabilities:["video_generation"]}];function Li({onSave:t,configuredProviders:r}){const{t:n}=ce(["settings","common"]),[a,o]=i.useState({}),[s,d]=i.useState(null),[c,u]=i.useState(!1),[h,x]=i.useState(null),[v,j]=i.useState(!0),[k,P]=i.useState("idle"),[N,y]=i.useState(null),[b,A]=i.useState({}),[m,w]=i.useState(!1),[V,T]=i.useState("idle"),[I,F]=i.useState(null),[C,$]=i.useState(!1),D=i.useRef(null),B=i.useRef(null),S=i.useMemo(()=>r.map(f=>f.name).sort().join(","),[r]);i.useEffect(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null),u(!0)}).catch(f=>{x(String(f)),u(!0)})},[S]),i.useEffect(()=>{let f=!1;return j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(R=>{if(!R.ok)throw new Error(`HTTP ${R.status}`);return R.json()}).then(R=>{if(f)return;const p=[];for(const K of R.providers)for(const z of K.models)p.push({provider:K.provider,providerLabel:K.displayName,modelId:z.id,modelName:z.name,mode:z.mode,tier:z.tier,costTier:z.costTier,capabilities:z.capabilities});y(p)}).catch(()=>{f||y(null)}).finally(()=>{f||j(!1)}),()=>{f=!0}},[S]),i.useEffect(()=>{fetch("/api/models/suggested-assignments",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{A(f.suggestions),w(!0)}).catch(()=>w(!0))},[S]);const L=i.useCallback(f=>{P("saving"),t(f).then(()=>{P("saved"),setTimeout(()=>P(R=>R==="saved"?"idle":R),2e3)}).catch(()=>{P("error"),setTimeout(()=>P(R=>R==="error"?"idle":R),3e3)})},[t]),J=i.useCallback((f,R)=>{B.current={capabilityRouting:f!==void 0?{assignments:f}:B.current?.capabilityRouting,routingDefaultModel:R!==void 0?R:B.current?.routingDefaultModel},D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const p=B.current;B.current=null,p&&L(p)},Ii)},[L]),_=i.useMemo(()=>r.flatMap(f=>(f.models??[{id:f.model,name:f.model}]).map(R=>({provider:f.name,providerLabel:f.displayName??f.name,modelId:R.id,modelName:R.name}))),[r]),H=N??_,X=i.useMemo(()=>Object.entries(a).map(([f,R])=>`${f}:${R?.provider??""}/${R?.model??""}`).sort().join("|"),[a]);i.useEffect(()=>{!c||!N||N.length===0||N.some(f=>!!f.modelId)&&(o(f=>{let R=!1;const p={...f};for(const K of Yn)for(const z of K.capabilities){const se=p[z];if(!se?.model)continue;const ae=za(N,z);if(ae.length===0)continue;ae.some(te=>te.provider===se.provider&&te.modelId===se.model)||(delete p[z],R=!0)}return R?(J(p),p):f}),d(f=>{if(!f?.model||N.some(z=>z.provider===f.provider&&z.modelId===f.model))return f;const p=N.find(z=>z.provider==="markus"),K=p?{provider:p.provider,model:p.modelId}:{provider:N[0].provider,model:N[0].modelId};return t({routingDefaultModel:K}),K}))},[c,N,S,J,X]);const me=i.useCallback(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null)}).catch(()=>{}),j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{const R=[];for(const p of f.providers)for(const K of p.models)R.push({provider:p.provider,providerLabel:p.displayName,modelId:K.id,modelName:K.name,mode:K.mode,tier:K.tier,costTier:K.costTier,capabilities:K.capabilities});y(R)}).catch(()=>{}).finally(()=>j(!1))},[]),ie=i.useCallback(async()=>{if(V!=="working"){T("working"),F(null);try{const f=await fetch("/api/settings/llm/restore-recommended",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}),R=await f.json().catch(()=>({}));if(!f.ok||!R.ok)throw new Error(R.error??`HTTP ${f.status}`);R.capabilityRouting&&o(R.capabilityRouting.assignments??{}),R.routingDefaultModel!==void 0&&d(R.routingDefaultModel),me(),T("idle"),P("saved"),setTimeout(()=>P(p=>p==="saved"?"idle":p),2e3)}catch(f){T("error"),F(f instanceof Error?f.message:String(f)),setTimeout(()=>T("idle"),4e3)}}},[V,me]),ee=H.length>0;return c?h?e.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-xs text-red-400",children:n("modelRouting.loadError",{error:h})}):v&&!ee?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-secondary",children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin text-brand-500",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),e.jsx("span",{children:n("modelRouting.loadingModels")})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Bi,{status:k,t:n}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("button",{type:"button",onClick:()=>$(!0),disabled:V==="working",className:"text-xs px-3 py-1.5 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40 disabled:opacity-50 transition-colors",children:n(V==="working"?"modelRouting.restoreWorking":"modelRouting.restoreRecommended")}),I&&e.jsx("span",{className:"text-[10px] text-red-400 max-w-xs text-right",children:I})]})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:n("modelRouting.defaultModelTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("modelRouting.defaultModelDesc")})]}),e.jsx("div",{className:"max-w-md",children:e.jsx(Yt,{value:s?`${s.provider}/${s.model}`:"",options:H,placeholder:n("modelRouting.defaultModelPlaceholder"),onChange:f=>{if(!f)d(null),J(void 0,null);else{const[R,...p]=f.split("/"),K={provider:R,model:p.join("/")};if(d(K),a.text){const z={...a};delete z.text,o(z),J(z,K)}else J(void 0,K)}}})})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:n("modelRouting.capabilityAssignTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("modelRouting.capabilityAssignDesc")})]}),r.length===0&&e.jsx("div",{className:"p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-xs text-yellow-400",children:n("modelRouting.noProvidersHint")}),r.length>0&&e.jsx("div",{className:"space-y-4",children:Yn.map(f=>e.jsx(Oi,{groupKey:f.groupKey,capabilities:f.capabilities,assignments:a,suggestions:b,allModels:H,configuredProviderNames:new Set(r.map(R=>R.name)),t:n,onAssign:(R,p)=>{const K={...a};p?K[R]=p:delete K[R],o(K),J(K)}},f.groupKey))})]}),C&&e.jsx(Cs,{variant:"primary",title:n("modelRouting.restoreRecommended"),message:n("modelRouting.restoreConfirm"),confirmLabel:n("common:confirm"),onConfirm:()=>{$(!1),ie()},onCancel:()=>$(!1)})]}):e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 animate-pulse",children:[e.jsx("div",{className:"h-4 bg-surface-overlay rounded w-1/3 mb-3"}),e.jsx("div",{className:"h-3 bg-surface-overlay rounded w-2/3 mb-4"}),e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(f=>e.jsx("div",{className:"h-10 bg-surface-overlay rounded-lg"},f))})]})})}function Oi({groupKey:t,capabilities:r,assignments:n,suggestions:a,allModels:o,configuredProviderNames:s,t:d,onAssign:c}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 px-1",children:d(`modelRouting.capabilityGroups.${t}`)}),e.jsx("div",{className:"space-y-1",children:r.map(u=>{const h=n[u],x=a[u],v=h?`${h.provider}/${h.model}`:"",j=za(o,u),k=x?j.find(A=>A.provider===x.provider&&A.modelId===x.model)?.modelName??x.model:void 0,P=j.length>0,N=h?$i(o,h.provider,h.model):void 0,y=h&&!s.has(h.provider),b=!!(h&&P&&u!=="text"&&!j.some(A=>A.provider===h.provider&&A.modelId===h.model));return e.jsxs("div",{className:`flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg md:flex-nowrap md:gap-3 ${b?"bg-red-500/10 border border-red-500/30":y?"bg-yellow-500/10 border border-yellow-500/30":!P&&!h?"bg-amber-500/5 border border-amber-500/20":"bg-surface-overlay/40"}`,children:[e.jsx("div",{className:"w-full shrink-0 md:w-28",children:e.jsx("span",{className:"text-xs text-fg-primary",children:d(`modelRouting.capabilities.${u}`)})}),e.jsx("div",{className:"flex-1 min-w-0",children:b?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs text-red-400",children:["⚠ ",h.model]}),e.jsx("span",{className:"text-[10px] text-red-400/70",children:d("modelRouting.mismatchHint")})]}),e.jsx(Yt,{value:"",options:j,placeholder:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}})]}):P?e.jsx(Yt,{value:v,options:j,placeholder:k?`${k} (${d("modelRouting.suggested")})`:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}}):e.jsxs("span",{className:"text-xs text-amber-400",children:[d("modelRouting.noModelAvailable"),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",d("modelRouting.addProviderHint")]})]})}),e.jsxs("div",{className:"w-14 shrink-0 flex justify-end",children:[b&&e.jsx("span",{className:"text-[10px] text-red-400 font-medium",title:d("modelRouting.mismatchHint"),children:"⚠"}),!b&&y&&e.jsx("span",{className:"text-[10px] text-yellow-400 font-medium",title:d("modelRouting.staleProvider"),children:"⚠"}),!b&&!y&&N&&e.jsx(Qn,{tier:N}),!b&&!y&&!N&&h&&e.jsx(Qn,{tier:"unknown"})]}),e.jsx("div",{className:"w-8 shrink-0 flex justify-end",children:h&&e.jsx("button",{onClick:()=>c(u,null),className:"text-fg-tertiary hover:text-red-400 transition-colors",title:d("modelRouting.clear"),children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})})]},u)})})]})}function $i(t,r,n){return t.find(o=>o.provider===r&&o.modelId===n)?.tier}function Bi({status:t,t:r}){if(t==="idle")return null;const n={idle:"",saving:"text-fg-tertiary",saved:"text-green-400",error:"text-red-400"},a={idle:"",saving:r("modelRouting.saving"),saved:r("modelRouting.saved"),error:r("modelRouting.saveError")};return e.jsx("div",{className:`text-xs font-medium transition-opacity ${n[t]}`,children:a[t]})}function Qn({tier:t}){const r={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30",unknown:"bg-gray-500/10 text-fg-tertiary border-border-default"};return e.jsx("span",{className:`px-1.5 py-0.5 text-[9px] rounded font-semibold uppercase border ${r[t]??r.unknown}`,children:t==="unknown"?"—":t})}function za(t,r){if(r==="text")return t.filter(d=>wi(d));const n={image_generation:["image_generation"],audio_tts:["audio_speech"],audio_stt:["audio_transcription"],video_generation:["video_generation"]},a={image_recognition:["vision"],image_generation:["imageGeneration"],audio_tts:["tts"],audio_stt:["stt"],video_generation:["videoGeneration"]},o=n[r],s=a[r];return t.filter(d=>!!(d.capabilities&&d.capabilities.length>0&&s&&s.some(c=>d.capabilities.includes(c))||o&&d.mode&&o.includes(d.mode)))}function Di({orgId:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null);return i.useEffect(()=>{if(!t)return;let o=!1;return fetch(`/api/orgs/${t}/slug`,{credentials:"include"}).then(s=>s.ok?s.json():null).then(s=>{!o&&s&&a(s)}).catch(()=>{}),()=>{o=!0}},[t]),n?.hubOrgId?e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-brand-500/25 bg-brand-600/[0.06] px-3 py-2",children:[e.jsx("span",{className:"shrink-0 text-xs text-fg-tertiary",children:r("orgIdentity.label")}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("code",{className:"truncate font-mono text-xs text-fg-primary",children:n.orgSlug||r("orgIdentity.unset")}),e.jsx("span",{className:"shrink-0 rounded bg-green-500/15 px-1.5 py-0.5 text-[10px] text-green-600",children:r("orgIdentity.synced")})]})]}):null}function Ut({w:t="w-16"}){return e.jsx("span",{className:`inline-block h-3 ${t} animate-pulse rounded bg-surface-elevated`,"aria-hidden":"true"})}function Vi({authUser:t}){const{t:r}=ce(["settings","common"]),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState([]),[u,h]=i.useState(()=>Hr()||Un()?"loading":"not-connected"),x=u==="loading",[v,j]=i.useState(null),k=i.useCallback(()=>{U.hubOrgs.mine().catch(T=>(j({type:"err",text:T instanceof Error?T.message:r("org.loadFailed")}),{orgs:[]})).then(T=>{s(T.orgs),U.hubOrgs.invitations().then(I=>c(I.invitations)).catch(()=>{})})},[r]);i.useEffect(()=>{if(!Hr()&&!Un()){h("not-connected");return}k(),Gt.user.plan().then(T=>a(T)).catch(()=>{}).finally(()=>h("ready"))},[k]);const P=async T=>{try{await U.hubOrgs.acceptInvitation(T),c(I=>I.filter(F=>F.orgId!==T)),k()}catch(I){j({type:"err",text:I instanceof Error?I.message:"Failed"})}},N=o.find(T=>T.id===n?.orgId)??o[0],y=n?n.creditsBudgetCu??(n.monthlyQuotaCu??0)+(n.bonusCu??0)+(n.purchasedCu??0):0,b=!!(n?.memberCuLimit!=null&&n.memberCuLimit>0&&N&&N.role!=="owner"&&N.role!=="admin"&&N.memberCount>1),A=Math.round(b?n?.memberCuUsed??0:n?.totalConsumedThisPeriod??n?.cuUsed??0),m=b?n?.memberCuLimit??0:y,w=x||m>0,V=x||!!N;return e.jsxs("div",{className:"space-y-3",children:[v&&e.jsxs("div",{className:`flex items-center gap-2 rounded-lg px-4 py-3 text-sm ${v.type==="ok"?"border border-green-500/20 bg-green-500/10 text-green-600":"border border-red-500/20 bg-red-500/10 text-red-500"}`,children:[e.jsx("span",{children:v.type==="ok"?"✓":"✕"}),e.jsx("span",{children:v.text})]}),d.length>0&&e.jsx("div",{className:"space-y-2",children:d.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-fg-primary",children:T.orgName}),e.jsxs("span",{className:"ml-1 text-fg-tertiary",children:["— ",r("org.invitedBy")," ",T.invitedBy]})]}),e.jsx("button",{type:"button",onClick:()=>{P(T.orgId)},className:"rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("org.accept")})]},T.orgId))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Di,{orgId:t?.orgId}),e.jsx("div",{className:"space-y-3 rounded-lg border border-border-default px-5 py-4",children:u==="not-connected"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:r("orgSummary.notConnectedTitle")}),e.jsx("p",{className:"text-xs leading-relaxed text-fg-tertiary",children:r("orgSummary.notConnectedDesc")}),e.jsx("button",{type:"button",onClick:()=>{zo(Wo("markus://auth"))},className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("orgSummary.connectHub")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("orgSummary.plan")}),x?e.jsx(Ut,{w:"w-14"}):e.jsx("span",{className:"rounded border border-brand-500/15 bg-brand-600/10 px-2 py-0.5 text-xs font-semibold capitalize text-brand-500",children:n?.planType??r("orgSummary.planUnknown")})]}),w&&e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r(b?"account.personalLimit":"account.credits")}),e.jsx("span",{className:"font-medium tabular-nums text-fg-primary",children:x?e.jsx(Ut,{w:"w-24"}):e.jsxs(e.Fragment,{children:[A.toLocaleString()," / ",m.toLocaleString()]})})]}),V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.nameLabel")}),x?e.jsx(Ut,{w:"w-28"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.name})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("account.memberCount")}),x?e.jsx(Ut,{w:"w-6"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.memberCount})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.orgId")}),x?e.jsx(Ut,{w:"w-40"}):e.jsx("code",{className:"rounded bg-surface-elevated px-1.5 py-0.5 text-[11px] text-fg-secondary",children:N?.id})]})]}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:r("account.noOrg")}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=billing`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand no-underline transition-colors hover:bg-brand-500",children:r("orgSummary.manageBilling")}),e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=organization`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg border border-border-default px-4 py-2 text-xs font-medium text-fg-secondary no-underline transition-colors hover:bg-surface-elevated",children:r("orgSummary.manageMembers")})]})]})})]})]})}function _i({configuredProviders:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>t.map(N=>`${N.name}:${N.models?.length??0}`).sort().join(","),[t]),v=i.useCallback(async()=>{c(null);try{const[{agents:N},y]=await Promise.all([U.agents.list({lean:!0}),U.teams.list()]),b=y.teams.map(m=>({id:m.id,name:m.name}));s(b);const A=await Promise.all(N.map(async m=>{try{const V=(await U.agents.get(m.id)).config?.llmConfig;return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:V?.modelMode==="custom"&&V.primary&&V.defaultModel?`${V.primary}/${V.defaultModel}`:null,llmConfig:{modelMode:V?.modelMode,primary:V?.primary??"",defaultModel:V?.defaultModel}}}catch{return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:null,llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}}}));a(N.length?A:null)}catch(N){c(String(N))}},[x]);i.useEffect(()=>{v()},[v,x]);const j=i.useMemo(()=>{const N=[];for(const y of t)for(const b of y.models??[])N.push({provider:y.name,providerLabel:y.displayName??y.name,modelId:b.id,modelName:b.name??b.id});return N},[t]),k=async(N,y)=>{h(N),c(null);try{y?await U.agents.updateConfig(N,{llmConfig:{modelMode:"custom",primary:y.provider,defaultModel:y.modelId}}):await U.agents.updateConfig(N,{llmConfig:{modelMode:"default",primary:"",defaultModel:null}});const b=y?`${y.provider}/${y.modelId}`:null;a(A=>A?.map(m=>m.id===N?{...m,override:b}:m)??A),ki(N)}catch(b){c(String(b))}finally{h(null)}},P=i.useMemo(()=>{if(!n)return[];const N=new Map,y=[];for(const A of n)if(A.teamId){const m=N.get(A.teamId)??[];m.push(A),N.set(A.teamId,m)}else y.push(A);const b=[];y.length&&b.push({key:"ungrouped",label:r("perAgentModel.ungrouped",{defaultValue:"Ungrouped"}),rows:y});for(const A of o){const m=N.get(A.id);m?.length&&b.push({key:`team:${A.id}`,label:A.name,rows:m})}for(const[A,m]of N)o.some(w=>w.id===A)||b.push({key:`team:${A}`,label:A,rows:m});return b},[n,o,r]);return n===null&&!d?e.jsx("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 text-sm text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}):e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:r("perAgentModel.title",{defaultValue:"Per-agent default model"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r("perAgentModel.desc",{defaultValue:'Bind a specific provider+model to an agent, or leave it following the global default. This is what the composer "Apply to current agent" writes.'})})]})}),d&&e.jsx("div",{className:"text-xs text-red-500",children:d}),(!n||n.length===0)&&!d&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:r("perAgentModel.noAgents",{defaultValue:"No agents available."})}),n&&n.length>0&&e.jsx("div",{className:"space-y-5",children:P.map(N=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-fg-tertiary truncate",children:N.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary/70 tabular-nums shrink-0",children:N.rows.length})]}),e.jsx("div",{className:"space-y-2",children:N.rows.map(y=>e.jsxs("div",{title:y.id,className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:y.name}),e.jsxs("div",{className:"flex w-[55%] max-w-[320px] min-w-0 shrink-0 items-center gap-1.5 sm:w-[320px]",children:[y.override?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{value:y.override,options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),e.jsx("button",{type:"button",disabled:u===y.id,onClick:()=>{k(y.id,null)},className:"shrink-0 px-2.5 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-primary disabled:opacity-40 transition-colors",children:r("perAgentModel.reset",{defaultValue:"Reset"})})]}):e.jsx(Yt,{value:"",options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),u===y.id&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary",children:r("common:loading",{defaultValue:"…"})})]})]},y.id))})]},N.key))})]})}let ks=[],ys=null;async function Fi(){return ys||(ys=(async()=>{try{ks=(await U.modelCatalog.providerCatalog()).providers??[]}catch{ks=[]}return ks})(),ys)}function Ui(){const[t,r]=i.useState(ks);return i.useEffect(()=>{let n=!0;return Fi().then(a=>{n&&r(a)}),()=>{n=!1}},[]),t}const Ki="integrations.platforms",Xr=(t,r)=>`settings:${Ki}.${t}.${r}`,Hi={feishu:"https://open.feishu.cn/app",telegram:"https://t.me/BotFather",slack:"https://api.slack.com/apps",whatsapp:"https://developers.facebook.com/apps",discord:"https://discord.com/developers/applications"};function qi(t){return Hi[t]}function zi(t,r){return t(Xr(r.id,"label"),{defaultValue:r.label})}function Wa(t,r,n){const a=Xr(r,`fields.${n.key}`);return{label:t(`${a}.label`,{defaultValue:n.label}),help:n.help?t(`${a}.help`,{defaultValue:n.help}):void 0,placeholder:n.placeholder?t(`${a}.placeholder`,{defaultValue:n.placeholder}):void 0,options:n.options?.map(o=>({value:o.value,label:t(`${a}.options.${o.value}`,{defaultValue:o.label})}))}}function Wi(t,r,n){const a=[],o=Xr(n,"guide");for(let s=1;s<=20;s+=1){const d=`${o}.step${s}.title`;if(!t.exists(d))break;const c=`${o}.step${s}.desc`,u=t.exists(c)?r(c):void 0;a.push({title:r(d),...u?{desc:u}:{}})}return a}function Gi(t){return t("settings:integrations.guide.heading",{defaultValue:"Setup guide"})}function Ji(t){return t.type==="boolean"?t.default===!0:t.multiple?Array.isArray(t.default)?[...t.default]:[]:t.default!==void 0?t.default:""}function As(t,r){return r==null?!0:t.type==="boolean"?!1:t.multiple?!Array.isArray(r)||r.length===0:typeof r=="string"?r.trim()==="":!1}function Zn(t){const r={};for(const n of t.fields){if(n.secret){r[n.key]="";continue}const a=t.values[n.key];r[n.key]=a??Ji(n)}return r}function Xn(t,r,n={}){const a=[];for(const o of t)if(o.required){if(o.secret){if(!As(o,r[o.key]))continue;n[o.key]?.hasValue||a.push(o.key);continue}As(o,r[o.key])&&a.push(o.key)}return a}function Yi(t,r,n){const a={enabled:n};for(const o of t.fields){const s=r[o.key];if(o.secret){if(As(o,s))continue;a[o.key]=s;continue}s!==void 0&&(a[o.key]=s)}return a}function Qi(t){return t.filter(r=>r.required||r.type==="agent")}function Zi(t){return t.filter(r=>!(r.required||r.type==="agent"))}function Wr(t){return Array.isArray(t)?`[${t.map(Wr).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[a])=>n<a?-1:n>a?1:0).map(([n,a])=>`${JSON.stringify(n)}:${Wr(a)}`).join(",")}}`:JSON.stringify(t)??"null"}function Xi(t){return Wr({id:t.id,enabled:t.enabled,fields:t.fields.map(r=>({key:r.key,type:r.type,required:r.required,secret:r.secret===!0,multiple:r.multiple===!0,default:r.default??null,value:r.secret?!1:t.values[r.key]??null,hasValue:r.secret?t.secrets[r.key]?.hasValue===!0:!1}))})}function el(t){const r=t.ok===!0||t.success===!0;return{ok:r,text:t.message??t.error??(r?"OK":"Failed"),code:t.code}}function tl(t){return t?.status==="awaiting_reply"||t?.status==="awaiting_inbound"}function sl(t,r=!1){return t.hasConfig?t.enabled?t.lastVerifiedAt||r?"verified":"unverified":"off":"unconfigured"}function rl(t){return{id:"",platform:t.id,label:"",enabled:!0,connected:!1,hasConfig:!1,capabilities:t.capabilities,fields:t.fields,values:{},secrets:nl(t.fields),agentId:null,notifyAgentId:null,channels:[],lastError:null,canListChannels:!1,lastVerifiedAt:null}}function nl(t){const r={};for(const n of t)n.secret&&(r[n.key]={hasValue:!1});return r}function al(t){return t.id===""}function ea(t){return{id:t.platform,label:t.label,capabilities:t.capabilities,fields:t.fields,defaultEnabled:!1,enabled:t.enabled,connected:t.connected,hasConfig:t.hasConfig,values:{...t.values,agentId:t.agentId??""},secrets:t.secrets}}function hr(t,r){return t.find(n=>n.nativeId===r)}function ta(t,r,n,a){const o=t.filter(s=>s.nativeId!==r);return o.push({nativeId:r,kind:a??null,agentId:n}),o.sort((s,d)=>s.nativeId.localeCompare(d.nativeId))}function sa(t,r){return t.filter(n=>n.nativeId!==r)}function ol(t,r){const n=new Set(r.map(a=>a.id));return t.filter(a=>!n.has(a.nativeId))}function il(t,r){const n=r.trim().toLowerCase();return n?t.filter(a=>a.name.toLowerCase().includes(n)||a.id.toLowerCase().includes(n)):t}function ll(t){const r=new Map;for(const n of t){const a=r.get(n.platform);a?a.push(n):r.set(n.platform,[n])}return[...r.entries()].map(([n,a])=>({platform:n,instances:a}))}function dl(t,r,n={}){const a=n.devMode??!1,o=new Set(t.filter(c=>c.devOnly&&!a).map(c=>c.id)),s=[],d=new Set;for(const c of t)o.has(c.id)||d.has(c.id)||(d.add(c.id),s.push(c.id));for(const c of r)o.has(c.platform)||d.has(c.platform)||(d.add(c.platform),s.push(c.platform));return s}function cl(t,r,n){const[a,o]=i.useState([]),[s,d]=i.useState(null),[c,u]=i.useState(!1),h=i.useRef(t);h.current=t;const x=i.useRef(0),v=i.useCallback(()=>{if(!n||!r)return;const j=++x.current;u(!0),h.current(r).then(k=>{j===x.current&&(o(k.channels??[]),d(k.error??null))}).catch(k=>{j===x.current&&(o([]),d(k instanceof Error?k.message:String(k)))}).finally(()=>{j===x.current&&u(!1)})},[n,r]);return i.useEffect(()=>(v(),()=>{x.current+=1}),[v]),{channels:a,error:s,loading:c,reloadChannels:v}}const Ga=/^notify[A-Z]/,Ja="notifyEnabled";function ul(t){return t.find(r=>r.key===Ja)}function ml(t){return t.notifyTarget==="chat"||t.notifyTarget==="user"||Ga.test(t.key)}function Qt(t){return t.filter(r=>r.notifyTarget==="chat"||r.notifyTarget==="user")}function xl(t){return t.filter(r=>!r.notifyTarget&&!r.secret&&r.key!==Ja&&Ga.test(r.key))}function gl(t){return t.filter(ml)}function Ya(t){return Qt(t).find(r=>r.notifyTarget==="chat")}function fl(t,r){const n=Qt(t);return n.length===0?"unsupported":n.some(a=>!As(a,r[a.key]))?"configured":"not-configured"}function ra(t){return typeof t=="string"?{value:t,label:t}:{value:t.value,label:t.label??t.value,hint:t.hint}}function na(t,r,n){const a=t.label.toLowerCase(),o=t.value.toLowerCase(),s=`${a} ${o} ${(t.hint??"").toLowerCase()}`;for(const c of r)if(!s.includes(c))return null;if(a.startsWith(n)||o.startsWith(n))return 0;const d=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[\\s./:_-])${d}`).test(a)?1:2}function Qa({value:t,options:r,onChange:n,placeholder:a,filterPlaceholder:o,emptyText:s,customHint:d,disabled:c,ariaLabel:u,className:h}){const[x,v]=i.useState(!1),[j,k]=i.useState(""),[P,N]=i.useState(!1),[y,b]=i.useState(-1),A=i.useRef(null),m=i.useRef(null),w=i.useRef(null),V=i.useRef(null),T=i.useId(),[I,F]=i.useState({}),C=i.useMemo(()=>t?r.map(ra).find(_=>_.value===t)?.label??t:a??"",[t,r,a]);i.useEffect(()=>{x||(k(C),N(!1))},[C,x]),i.useEffect(()=>{function _(H){const X=H.target;V.current?.contains(X)||A.current&&!A.current.contains(X)&&v(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);function $(){const _=m.current;if(!_)return;const H=_.getBoundingClientRect(),X=Math.max(H.width,240),me=window.innerHeight-H.bottom-8,ie=me<180&&H.top>me;F({position:"fixed",left:H.left,width:X,maxHeight:Math.min(260,ie?Math.max(H.top-12,120):me),...ie?{bottom:window.innerHeight-H.top+4}:{top:H.bottom+4}})}i.useLayoutEffect(()=>{if(!x)return;$();const _=()=>$();return window.addEventListener("scroll",_,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("scroll",_,!0),window.removeEventListener("resize",_)}},[x]);const D=i.useMemo(()=>{const _=r.map(ra),H=j.trim(),X=P?H.toLowerCase().split(/\s+/).filter(Boolean):[],me=[];_.forEach((f,R)=>{const p=X.length?na(f,X,H.toLowerCase()):0;p!==null&&me.push({row:f,score:p,idx:R})}),me.sort((f,R)=>f.score-R.score||f.idx-R.idx);const ie=[];if(a!==void 0){const f={value:"",label:a};(X.length?na(f,X,H.toLowerCase()):0)!==null&&ie.push(f)}ie.push(...me.map(f=>f.row));const ee=H&&!_.some(f=>f.value.toLowerCase()===H.toLowerCase());return d&&P&&ee&&ie.push({value:H,label:H,custom:!0}),ie},[r,j,P,a,d]);i.useEffect(()=>{if(!x||y<0||!w.current)return;w.current.querySelector(`[data-index="${y}"]`)?.scrollIntoView({block:"nearest"})},[y,x,D.length]);function B(){c||(k(C),N(!1),b(D.findIndex(_=>_.value===t)),v(!0),requestAnimationFrame(()=>m.current?.select()))}function S(){v(!1),k(C),N(!1),b(-1)}function L(_){n(_.value),v(!1),k(_.value?_.label:a??""),N(!1),b(-1),m.current?.focus()}function J(_){if(_.key==="ArrowDown"||_.key==="ArrowUp"){if(_.preventDefault(),!x){B();return}b(H=>{const X=_.key==="ArrowDown"?H+1:H-1;return Math.max(-1,Math.min(X,D.length-1))});return}if(_.key==="Enter"){if(!x){_.preventDefault(),B();return}const H=D[y];H?(_.preventDefault(),L(H)):S();return}if(_.key==="Escape"&&x){_.preventDefault(),_.stopPropagation(),S();return}_.key==="Tab"&&x&&S()}return e.jsxs("div",{ref:A,className:`relative ${h??""}`,children:[e.jsx("input",{ref:m,type:"text",role:"combobox","aria-expanded":x,"aria-controls":x?T:void 0,"aria-autocomplete":"list","aria-label":u,"aria-activedescendant":x&&y>=0?`${T}-opt-${y}`:void 0,disabled:c,value:x?j:C,placeholder:o,onMouseDown:()=>{x?v(!1):B()},onChange:_=>{x||v(!0),k(_.target.value),N(!0),b(0)},onKeyDown:J,onBlur:()=>{x&&S()},className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none truncate"}),x&&Go.createPortal(e.jsxs("div",{id:T,role:"listbox",ref:_=>{w.current=_,V.current=_},style:I,onMouseDown:_=>_.preventDefault(),"data-keep-edit-focus":!0,className:"z-50 overflow-y-auto bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1",children:[D.map((_,H)=>e.jsxs("div",{id:`${T}-opt-${H}`,"data-index":H,role:"option","aria-selected":_.value===t,onMouseDown:X=>{X.preventDefault(),L(_)},className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${H===y?"bg-brand-500/20":_.value===t?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,children:[e.jsx("span",{className:`flex-1 truncate ${_.custom?"text-brand-500":"text-fg-primary"}`,children:_.label}),_.hint&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:_.hint}),_.custom&&d&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:typeof d=="function"?d(_.value):d})]},`${_.custom?"custom:":""}${_.value}`)),D.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:s})]}),document.body)]})}async function pl(){const{agents:t}=await U.agents.list({lean:!0});return t.map(r=>({id:r.id,name:r.name,role:r.role}))}let vs=null;function Za(){return vs||(vs=pl().catch(t=>{throw vs=null,t})),vs}function hl(t=Za,r=!0){const[n,a]=i.useState([]);return i.useEffect(()=>{if(!r)return;let o=!0;return t().then(s=>{o&&a(s)}).catch(()=>{o&&a([])}),()=>{o=!1}},[t,r]),n}function Ps({value:t,options:r,onChange:n,fieldKey:a,ariaLabel:o,disabled:s}){const{t:d}=ce(["settings"]);return e.jsx(Qa,{value:typeof t=="string"?t:"",options:r.map(c=>({value:c.id,label:c.name,hint:c.role})),onChange:c=>n(a,c),disabled:s,placeholder:d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),filterPlaceholder:d("settings:integrations.agentSelect.search",{defaultValue:"Search agents…"}),emptyText:d("settings:integrations.agentSelect.empty",{defaultValue:"No matching agent"}),ariaLabel:o??d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),className:"w-full"})}function Xa({loading:t,error:r,onReload:n,buttonTestId:a,errorTestId:o,empty:s=!1}){const{t:d}=ce(["settings","common"]);return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-h-[1.25rem]",children:[e.jsxs("button",{type:"button",onClick:n,disabled:t,"aria-busy":t,"data-testid":a,className:"inline-flex items-center gap-1 text-[11px] font-medium text-fg-tertiary hover:text-fg-secondary disabled:opacity-60 transition-colors",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${t?"animate-spin":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{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"})}),t?d("settings:instances.channels.refreshing",{defaultValue:"Refreshing…"}):s?d("settings:integrations.loadGroups",{defaultValue:"Load groups"}):d("settings:instances.channels.refresh",{defaultValue:"Refresh"})]}),r&&e.jsx("span",{"data-testid":o,className:"text-[11px] text-red-600",children:r})]})}const Ss="rounded-xl border border-border-default bg-surface-secondary p-4",Wt="text-sm font-semibold text-fg-primary",eo="flex flex-wrap items-center justify-between gap-x-4 gap-y-2",bl="flex flex-wrap items-start justify-between gap-x-4 gap-y-2",Gr="shrink-0 text-sm text-fg-secondary",to="flex-1 min-w-[10rem] flex justify-end",Ct="text-xs text-fg-tertiary",Jr="w-full px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500 transition-colors";function Yr(t){return"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-lg border transition-colors "+(t?"bg-selected-bg border-selected-border text-selected-fg":"bg-surface-primary border-border-default text-fg-secondary hover:border-fg-tertiary")}const yl={verified:"bg-green-500/10 text-green-600 border-green-500/30",unverified:"bg-amber-500/10 text-amber-600 border-amber-500/30",off:"bg-gray-500/10 text-fg-tertiary border-border-default",unconfigured:"bg-gray-500/10 text-fg-tertiary border-border-default"},vl={verified:"bg-green-500",unverified:"bg-amber-400",off:"bg-gray-400",unconfigured:"bg-gray-400"},jl={verified:"settings:integrations.status.verified",unverified:"settings:integrations.status.unverified",off:"settings:integrations.status.off",unconfigured:"settings:integrations.status.unconfigured"},Nl={verified:"Connected",unverified:"Not verified",off:"Off",unconfigured:"Not configured"};function wl({state:t}){const{t:r}=ce(["settings"]);return e.jsxs("span",{"data-testid":"integration-status","data-state":t,"data-connected":t==="verified"?"true":"false",className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${yl[t]}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${vl[t]}`}),r(jl[t],{defaultValue:Nl[t]})]})}function Jt({type:t,text:r}){return e.jsx("div",{"data-testid":t==="ok"?"integration-msg-ok":"integration-msg-err",className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs ${t==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-600 border border-red-500/30"}`,children:r})}function Kt({label:t,control:r,help:n,htmlFor:a,start:o=!1}){return e.jsxs("div",{children:[e.jsxs("div",{className:o?bl:eo,children:[a?e.jsx("label",{htmlFor:a,className:Gr,children:t}):e.jsx("span",{className:Gr,children:t}),e.jsx("div",{className:to,children:r})]}),n?e.jsx("p",{className:`${Ct} mt-1.5`,children:n}):null]})}function kl({field:t,value:r,hasStored:n,onChange:a,platformId:o="",agentOptions:s=[]}){const{t:d}=ce(["settings"]),c=`integration-field-${t.key}`,[u,h]=i.useState(!1),x=i.useMemo(()=>o?Wa(d,o,t):{label:t.label,help:t.help,placeholder:t.placeholder,options:t.options},[d,o,t]),v=x.label,j=x.help,k=x.placeholder,P=x.options??t.options??[],N=e.jsxs(e.Fragment,{children:[v,t.required&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),y=t.secret&&n?d("settings:integrations.secretStored"):j||void 0;if(t.type==="boolean"){const m=r===!0;return e.jsx(Kt,{label:v,help:j,control:e.jsx(Ye,{checked:m,onChange:w=>a(t.key,w),label:v,size:"md",testId:`integration-field-${t.key}`})})}if(t.type==="agent")return e.jsx(Kt,{label:N,help:y,control:e.jsx("div",{className:"w-full","data-testid":`integration-field-${t.key}`,children:e.jsx(Ps,{value:r,options:s,onChange:a,fieldKey:t.key,ariaLabel:v})})});if(t.type==="select"&&t.multiple){const m=Array.isArray(r)?r.map(String):[];return e.jsx(Kt,{start:!0,label:N,help:y,control:e.jsx("div",{className:"flex flex-wrap justify-end gap-1.5","data-testid":`integration-field-${t.key}`,children:P.map(w=>{const V=m.includes(w.value);return e.jsx("button",{type:"button","aria-pressed":V,"data-option":w.value,onClick:()=>a(t.key,V?m.filter(T=>T!==w.value):[...m,w.value]),className:Yr(V),children:w.label},w.value)})})})}if(t.type==="select")return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsx("select",{id:c,"data-testid":`integration-field-${t.key}`,value:typeof r=="string"?r:"",onChange:m=>a(t.key,m.target.value),className:Jr,children:(t.options??[]).map(m=>{const w=P.find(V=>V.value===m.value)?.label??m.label;return e.jsx("option",{value:m.value,children:w},m.value)})})});const b=t.type==="password",A=t.type==="number";return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsxs("div",{className:"relative w-full",children:[e.jsx("input",{id:c,"data-testid":`integration-field-${t.key}`,type:A?"number":b&&!u?"password":"text",value:r==null?"":String(r),placeholder:b&&n?d("settings:integrations.secretStoredPlaceholder"):k,onChange:m=>a(t.key,m.target.value),className:`${Jr}${b?" font-mono pr-10":""}`}),b&&e.jsx("button",{type:"button","aria-label":u?d("settings:integrations.hide",{defaultValue:"Hide"}):d("settings:integrations.show",{defaultValue:"Show"}),onClick:()=>h(m=>!m),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:u?"🙈":"👁"})]})})}function At({status:t,draft:r,fields:n=t.fields,onChange:a,agentOptions:o=[]}){return e.jsx(e.Fragment,{children:n.map(s=>e.jsx(kl,{field:s,platformId:t.id,value:r[s.key],hasStored:t.secrets[s.key]?.hasValue===!0,agentOptions:o,onChange:a},s.key))})}const aa={pending:"bg-amber-400 animate-pulse",ok:"bg-emerald-500",failed:"bg-red-500"};function oa({label:t,hint:r,leg:n}){const{t:a}=ce("settings");return e.jsxs("div",{className:"flex items-start gap-2.5","data-testid":"connection-test-leg",children:[e.jsx("span",{className:`mt-1.5 w-2 h-2 rounded-full shrink-0 ${aa[n.state]??aa.pending}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm text-fg-primary",children:t}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 break-words",children:n.state==="ok"?n.detail??a("integrations.connectionTest.legOk",{defaultValue:"Verified"}):n.state==="failed"?n.detail??a("integrations.connectionTest.legFailed",{defaultValue:"Failed"}):r})]})]})}function Sl(t,r){const n=new Date(t);return Number.isNaN(n.getTime())?t:n.toLocaleString(r,{dateStyle:"medium",timeStyle:"short"})}function Cl({test:t,starting:r,onStart:n,lastVerifiedAt:a=null}){const{t:o,i18n:s}=ce("settings"),d=(()=>{if(!t)return null;switch(t.status){case"awaiting_reply":return o("integrations.connectionTest.awaitingReply",{defaultValue:"A test message was sent to {{target}}. Reply to it in {{platform}} to finish — include {{code}} if you can.",target:t.targetChannelName??t.targetChannelId??"",platform:t.platform,code:t.code??""});case"awaiting_inbound":return o("integrations.connectionTest.awaitingInbound",{defaultValue:"Send any message to this bot in {{platform}} — we will answer it to confirm both directions.",platform:t.platform});case"verified":return o("integrations.connectionTest.verified",{defaultValue:"Both directions work — Markus can send to and receive from this bot."});case"expired":return o("integrations.connectionTest.expired",{defaultValue:"No reply arrived in time. Check the bot is in the conversation, then try again."});default:return null}})();return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:o("integrations.connectionTest.title",{defaultValue:"Connection verification"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:o("integrations.connectionTest.subtitle",{defaultValue:"Sends a real message and waits for your reply — proves both directions."})})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(oa,{label:o("integrations.connectionTest.outbound",{defaultValue:"Outbound (bot → IM)"}),hint:o("integrations.connectionTest.outboundPending",{defaultValue:"Not sent yet"}),leg:t.outbound}),e.jsx(oa,{label:o("integrations.connectionTest.inbound",{defaultValue:"Inbound (IM → bot)"}),hint:o("integrations.connectionTest.inboundPending",{defaultValue:"Waiting for your reply"}),leg:t.inbound})]}),d&&(t.status==="verified"||t.status==="expired"?e.jsx(Jt,{type:t.status==="verified"?"ok":"err",text:d}):e.jsx("div",{className:"px-3 py-2 rounded-lg text-xs bg-surface-elevated text-fg-secondary",children:d}))]}):a?e.jsx(Jt,{type:"ok",text:o("integrations.connectionTest.lastVerified",{defaultValue:"Verified {{when}}.",when:Sl(a,s.language)})}):e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("integrations.connectionTest.idle",{defaultValue:"Not verified yet. Verify to send a real message to the bot and confirm the round trip."})}),e.jsxs("button",{type:"button",onClick:n,disabled:r,"data-testid":"connection-test-start",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-fg-primary border border-border-default rounded-lg hover:bg-surface-elevated disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[r?e.jsx("div",{className:"w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"}):null,t?o("integrations.connectionTest.retry",{defaultValue:"Verify again"}):o("integrations.connectionTest.start",{defaultValue:"Verify connection"})," "]})]})}function Al({status:t,values:r,setValue:n,channels:a=[],canListChannels:o=!1,channelsLoading:s=!1,channelsError:d=null,onReloadChannels:c=()=>{},channelsGuidance:u=null,testSlot:h}){const{t:x}=ce(["settings","common"]),[v,j]=i.useState(!1),k=Qt(t.fields),P=xl(t.fields),N=ul(t.fields),y=fl(t.fields,r),b=Ya(t.fields),A=N?r[N.key]!==!1:!0,m=o&&b?b.key:null,w=m!==null?String(r[m]??""):"",V={configured:x("settings:instances.notify.reachConfigured",{defaultValue:"Configured"}),"not-configured":x("settings:instances.notify.reachNotConfigured",{defaultValue:"Not set"}),unsupported:x("settings:instances.notify.reachUnsupported",{defaultValue:"Not supported"})},T={configured:"text-green-600","not-configured":"text-amber-600",unsupported:"text-fg-tertiary"},I={configured:"bg-green-500","not-configured":"bg-amber-400",unsupported:"bg-gray-400"},F=x("settings:instances.notify.guidanceFallback",{defaultValue:"This platform can’t list its conversations — enter the destination ID manually."}),C=u?x(u,{defaultValue:F}):F,$=m!==null&&!s&&w!==""&&!a.some(B=>B.id===w),D="text-xs font-medium text-fg-secondary mb-2";return e.jsxs("section",{"data-testid":"notification-panel","data-reachability":y,className:Ss,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsx("h3",{className:Wt,children:x("settings:instances.notify.title",{defaultValue:"Notifications"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs ${T[y]}`,"data-testid":"notification-reachability","data-state":y,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I[y]}`}),V[y]]}),N&&e.jsx(Ye,{checked:A,onChange:B=>n(N.key,B),label:x("settings:instances.notify.masterLabel",{defaultValue:"Enable notifications"}),size:"md",testId:`integration-field-${N.key}`})]})]}),e.jsxs("div",{className:`space-y-4${A?"":" opacity-60"}`,children:[k.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:D,children:x("settings:instances.notify.destination",{defaultValue:"Destination"})}),m!==null&&e.jsxs("div",{"data-testid":"notification-chat-list",className:"space-y-1.5",children:[e.jsx(Xa,{loading:s,error:d,onReload:c,empty:a.length===0,buttonTestId:"notification-chat-refresh",errorTestId:"notification-chat-error"}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(B=>e.jsx("button",{type:"button","aria-pressed":w===B.id,"data-testid":`notification-chat-pick-${B.id}`,onClick:()=>n(m,B.id),className:Yr(w===B.id),children:B.name},B.id))}),a.length===0&&!s&&!d&&e.jsx("p",{"data-testid":"notification-chat-empty",className:Ct,children:x("settings:instances.notify.pickEmpty",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}),$&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:e.jsx("button",{type:"button","aria-pressed":"true","data-testid":"notification-chat-pick-current",onClick:()=>n(m,w),className:Yr(!0),children:w})})]}),m===null&&e.jsx("p",{"data-testid":"notification-chat-guidance",className:Ct,children:C}),m!==null?e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","aria-expanded":v,"data-testid":"notification-manual-toggle",onClick:()=>j(B=>!B),className:"inline-flex items-center gap-1 text-xs font-medium text-fg-tertiary hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-3 h-3 transition-transform ${v?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),x("settings:instances.notify.manualInput",{defaultValue:"Enter an ID manually"})]}),v&&e.jsx("div",{className:"space-y-4 mt-3","data-testid":"notification-manual-fields",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}):e.jsx("div",{className:"mt-2",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}),P.length>0&&e.jsxs("div",{"data-testid":"notification-preferences",className:"space-y-3",children:[e.jsx("div",{className:D,children:x("settings:instances.notify.content",{defaultValue:"What to send"})}),e.jsx(At,{status:t,draft:r,fields:P,onChange:n})]}),h]})]})}const St={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"},Pl={color:"#64748b",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z"})})},Ml={feishu:{color:"#3370ff",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M21 5 3 11l5.5 2.2L19 7l-7.5 8.3L12 21l3-4.5L21 5z"})})},telegram:{color:"#229ed9",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M22 3 2.5 10.5l5.5 2L21 6l-9 10v5l3.5-4.5L20 19 22 3z"})})},slack:{color:"#611f69",glyph:e.jsx("g",{...St,children:e.jsx("path",{d:"M9.5 3 7.5 20M16.5 4 14.5 21M3.5 9h17M2.5 15h17"})})},whatsapp:{color:"#1faa59",glyph:e.jsxs("g",{...St,children:[e.jsx("path",{d:"M21 11.5a8.5 8.5 0 0 1-12.6 7.4L3 20.5l1.6-5.3A8.5 8.5 0 1 1 21 11.5z"}),e.jsx("path",{d:"M9 8.8c.3 2.6 2.6 4.9 5.2 5.2l1-1.3 1.9.8"})]})},discord:{color:"#5865f2",glyph:e.jsxs("g",{...St,children:[e.jsx("rect",{x:"3",y:"7",width:"18",height:"10",rx:"4.5"}),e.jsx("path",{d:"M7.5 11.5h3M9 10v3"}),e.jsx("circle",{cx:"15",cy:"10.7",r:"0.9"}),e.jsx("circle",{cx:"17.3",cy:"13",r:"0.9"})]})}};function Tl(t){return Ml[t]??Pl}function so({id:t,size:r=36}){const n=Tl(t);return e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded-lg",style:{width:r,height:r,backgroundColor:`${n.color}1a`,color:n.color},"aria-hidden":"true","data-testid":`platform-icon-${t}`,children:e.jsx("svg",{width:Math.round(r*.58),height:Math.round(r*.58),viewBox:"0 0 24 24",children:n.glyph})})}function El({status:t,configured:r,canListChannels:n=!1,channelsGuidance:a=null}){const{t:o,i18n:s}=ce(["settings","common"]),[d,c]=i.useState(!r),u=i.useMemo(()=>{const v=Wi(s,o,t.id);if(Qt(t.fields).length===0)return v;const j=o("settings:integrations.guide.destinationStep.desc",{defaultValue:"Pick the chat or user that should receive approvals and notifications — without it they have nowhere to go."}),k=n?{title:o("settings:integrations.guide.selectChatStep.title",{defaultValue:"Pick the notification group"}),desc:o("settings:integrations.guide.selectChatStep.desc",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}:{title:o("settings:integrations.guide.destinationStep.title",{defaultValue:"Set a notification destination"}),desc:a?o(a,{defaultValue:j}):j};return[...v,k]},[s,o,t.id,t.fields,n,a]),h=qi(t.id),x=o(`settings:integrations.platforms.${t.id}.description`,{defaultValue:""});return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl overflow-hidden","data-testid":"integration-guide","data-open":d?"true":"false",children:[e.jsxs("button",{type:"button",onClick:()=>c(v=>!v),"aria-expanded":d,"data-testid":"integration-guide-toggle",className:"w-full flex items-center gap-2.5 px-4 py-3 text-left hover:bg-white/[0.02] transition-colors",children:[e.jsx("span",{className:"text-base leading-none","aria-hidden":"true",children:"🧭"}),e.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary",children:Gi(o)}),e.jsx("svg",{className:`w-4 h-4 text-fg-tertiary transition-transform ${d?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),d&&e.jsxs("div",{className:"px-4 pb-4 pt-1 space-y-3 border-t border-border-default",children:[x&&e.jsx("p",{className:"text-xs text-fg-tertiary",children:x}),u.length>0?e.jsx("ol",{className:"space-y-2.5","data-testid":"integration-guide-steps",children:u.map((v,j)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"shrink-0 w-5 h-5 mt-0.5 rounded-full bg-brand-500/15 text-brand-600 text-[11px] font-semibold flex items-center justify-center",children:j+1}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-medium text-fg-primary",children:v.title}),v.desc&&e.jsx("span",{className:"block text-[11px] text-fg-tertiary mt-0.5",children:v.desc})]})]},v.title))}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:o("settings:integrations.guide.fallback",{defaultValue:"Fill in the credentials from the platform’s developer console below."})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:[h&&e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer","data-testid":"integration-guide-console",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-brand-600 text-on-brand rounded-lg hover:bg-brand-700 transition-colors",children:[o("settings:integrations.guide.openConsole",{defaultValue:"Open developer console"}),e.jsx("span",{"aria-hidden":"true",children:"↗"})]}),t.docsUrl&&e.jsx("a",{href:t.docsUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-brand-600 hover:text-brand-700",children:o("settings:integrations.docs",{defaultValue:"Setup docs"})})]})]})]})}const ro={create:(t,r)=>U.settings.createInstance(t,r).then(n=>n.instance),save:(t,r)=>U.settings.saveInstance(t,r).then(()=>{}),test:(t,r)=>U.settings.testInstance(t,r),remove:t=>U.settings.deleteInstance(t).then(()=>{}),listChannels:t=>U.settings.listInstanceChannels(t),saveChannels:(t,r)=>U.settings.saveInstanceChannels(t,r).then(()=>{}),startConnectionTest:(t,r)=>U.settings.startConnectionTest(t,r).then(n=>n.test),getConnectionTest:t=>U.settings.getConnectionTest(t).then(r=>r.test)},Rl=700;function ia({instance:t,client:r=ro,extras:n={},onChanged:a,onCreated:o,loadAgents:s,defaultExpanded:d}){const{t:c}=ce(["settings","common"]),u=al(t),[h,x]=i.useState(d??u),[v,j]=i.useState(!1),k=i.useMemo(()=>ea(t),[t]),[P,N]=i.useState(t.label),[y,b]=i.useState(()=>Zn(k)),[A,m]=i.useState(t.enabled),[w,V]=i.useState(t.channels),[T,I]=i.useState(typeof t.notifyAgentId=="string"?t.notifyAgentId:""),[F,C]=i.useState({kind:"idle"}),$=!!n[t.platform]?.guidedSetup,[D,B]=i.useState($&&!t.hasConfig?"guided":"manual"),S=$&&D==="guided",{channels:L,error:J,loading:_,reloadChannels:H}=cl(r.listChannels,t.id,h&&t.canListChannels),[X,me]=i.useState(""),[ie,ee]=i.useState(null),[f,R]=i.useState(!1),[p,K]=i.useState(null),z=tl(ie),[se,ae]=i.useState(!1),ge=t.fields.some(E=>E.type==="agent"),te=hl(i.useMemo(()=>s??Za,[s]),ge),Ze=i.useCallback(E=>E?te.find(ne=>ne.id===E)?.name??E:"",[te]),Me=Xi(k),Pe=i.useRef(t);Pe.current=t;const Be=i.useRef(!1),ct=i.useRef(!1);i.useEffect(()=>{if(Be.current)return;const E=Pe.current;N(E.label),b(Zn(ea(E))),m(E.enabled),V(E.channels),I(typeof E.notifyAgentId=="string"?E.notifyAgentId:"")},[Me]),i.useEffect(()=>{C({kind:"idle"}),ee(null),K(null),gt(!1)},[t.id]),i.useEffect(()=>{B($&&!t.hasConfig?"guided":"manual")},[t.id,t.hasConfig,$]);const Se=i.useCallback(()=>{Be.current=!0,C({kind:"idle"})},[]),fe=i.useCallback((E,ne)=>{Se(),b(ue=>({...ue,[E]:ne}))},[Se]),Zt=i.useCallback(E=>{Se(),N(E)},[Se]),Xe=i.useCallback(E=>{Se(),m(E)},[Se]),Pt=i.useRef(()=>Promise.resolve()),De=i.useCallback(async()=>{if(!ct.current){ct.current=!0,C({kind:"saving"});try{let E=Pe.current.id;E||(E=(await r.create(Pe.current.platform,P.trim())).id),await r.save(E,{...Yi(k,y,A),notifyAgentId:T}),Pe.current.canListChannels&&await r.saveChannels(E,w);let ne=null;try{const{ok:ue,text:He,code:Le}=el(await r.test(E,{}));!ue&&!/not supported/i.test(He)&&(ne=Le==="network_unreachable"?c("settings:integrations.savedNotVerifiedNetwork"):c("settings:integrations.savedNotVerified",{reason:He}))}catch(ue){ne=c("settings:integrations.savedNotVerified",{reason:String(ue)})}Be.current=!1,C(ne?{kind:"error",text:ne}:{kind:"saved"}),await a?.(),Pe.current.id===""&&o?.(E)}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}finally{ct.current=!1}}},[r,k,y,A,T,w,P,c,a,o]);Pt.current=De;const ut=Xn(k.fields,y,t.secrets),Xt=u&&P.trim()==="",es=w.every(E=>E.agentId),et=!S&&!Xt&&ut.length===0&&es,Ie=i.useMemo(()=>JSON.stringify([P,A,T,w,y]),[P,A,T,w,y]);i.useEffect(()=>{if(!Be.current||!et)return;const E=setTimeout(()=>{Pt.current()},Rl);return()=>clearTimeout(E)},[Ie,et]),i.useEffect(()=>{if(!h||u)return;let E=!0;return r.getConnectionTest(t.id).then(ne=>{E&&ne&&ee(ne)}).catch(()=>{}),()=>{E=!1}},[h,u,r,t.id]),i.useEffect(()=>{if(!h||!z)return;let E=!0;const ne=setInterval(()=>{r.getConnectionTest(t.id).then(ue=>{E&&ue&&ee(ue)}).catch(()=>{})},2500);return()=>{E=!1,clearInterval(ne)}},[h,z,r,t.id]);const Mt=i.useRef(null);i.useEffect(()=>{ie?.status==="verified"&&Mt.current!==t.id&&(Mt.current=t.id,a?.())},[ie?.status,t.id,a]);const ts=i.useCallback(async()=>{R(!0),K(null);try{ee(await r.startConnectionTest(t.id))}catch(E){K(E instanceof Error?E.message:String(E))}finally{R(!1)}},[r,t.id]),ye=n[t.platform],Ue=i.useMemo(()=>({platformId:t.platform,instanceId:t.id||void 0,status:k,values:y,setValue:fe,reload:()=>{a?.()},agents:te,onCreated:o,setupMethod:$?D:void 0,setSetupMethod:$?B:void 0}),[t.platform,t.id,k,y,fe,a,te,o,$,D]),ss=i.useMemo(()=>new Set(ye?.ownedFields??[]),[ye]),mt=Qt(k.fields).length>0,rs=i.useMemo(()=>new Set(mt?gl(k.fields).map(E=>E.key):[]),[k.fields,mt]),xt=i.useMemo(()=>k.fields.filter(E=>!ss.has(E.key)&&!rs.has(E.key)),[k.fields,ss,rs]),Tt=i.useMemo(()=>Qi(xt),[xt]),ns=i.useMemo(()=>Zi(xt),[xt]),Ts=i.useMemo(()=>Tt.filter(E=>E.type==="agent"),[Tt]),Et=i.useMemo(()=>Tt.filter(E=>E.type!=="agent"),[Tt]),[Rt,gt]=i.useState(!1),It=i.useMemo(()=>Xn(t.fields,t.values,t.secrets),[t.fields,t.values,t.secrets]),tt=t.hasConfig&&!It.some(E=>Et.some(ne=>ne.key===E)),tn=i.useMemo(()=>il(L,X),[L,X]),as=i.useMemo(()=>ol(w,L),[w,L]),Lt=w.filter(E=>!E.agentId).length,Es=i.useCallback((E,ne)=>{Se(),V(ue=>ne?ta(ue,E.id,hr(ue,E.id)?.agentId??t.agentId??"",E.kind??null):sa(ue,E.id))},[Se,t.agentId]),Te=i.useCallback((E,ne)=>{Se(),V(ue=>ta(ue,E,ne,hr(ue,E)?.kind??null))},[Se]),Rs=i.useCallback(async()=>{ae(!1);try{await r.remove(t.id),await a?.()}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}},[r,t.id,a]),ft=sl(t,ie?.status==="verified"),re=t.id||`new-${t.platform}`,Ke=`instance-name-${re}`,pt=ut.map(E=>{const ne=k.fields.find(ue=>ue.key===E);return ne?Wa(c,t.platform,ne).label:E}).join(", ");return e.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden border border-border-default","data-testid":`instance-card-${re}`,"data-instance":t.id,"data-platform":t.platform,"data-draft":u?"true":"false","data-expanded":h?"true":"false","data-connection":ft,children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":h,"data-testid":`instance-toggle-${re}`,className:"flex-1 min-w-0 flex items-center gap-3 text-left",children:[e.jsx(so,{id:t.platform}),e.jsxs("span",{className:"flex-1 min-w-0 flex items-center gap-2.5",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate","data-testid":`instance-label-${re}`,children:P.trim()===""?c("settings:instances.newBot",{defaultValue:"New bot"}):P}),!u&&e.jsx("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[10px] font-medium bg-surface-secondary border border-border-default text-fg-tertiary","data-testid":`instance-platform-${re}`,children:t.platform}),!u&&t.agentId&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1.5 text-xs text-fg-tertiary truncate","data-testid":`instance-agent-${re}`,title:c("settings:instances.boundAgent",{defaultValue:"Bound agent"}),children:[e.jsx("span",{className:"text-fg-muted",children:"→"}),Ze(t.agentId)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[e.jsx(wl,{state:ft}),!u&&e.jsx(Ye,{checked:A,onChange:Xe,size:"md",testId:`instance-enabled-${re}`,label:c("settings:instances.toggleLabel",{defaultValue:"Turn this bot on or off"})}),e.jsx("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":h,"data-testid":`instance-chevron-${re}`,className:"p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:e.jsx("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})})]})]}),h&&e.jsxs("div",{className:"px-6 pb-6 pt-5 border-t border-border-default space-y-6",children:[!t.hasConfig&&!S&&e.jsx(El,{status:k,configured:t.hasConfig,canListChannels:t.canListChannels,channelsGuidance:t.channelsGuidance??null}),!$&&ye?.placement==="before"&&ye.render(Ue),e.jsxs("section",{"data-testid":`instance-credentials-${re}`,className:Ss,children:[e.jsx("h3",{className:`${Wt} mb-3`,children:t.hasConfig?c("settings:instances.setup.configuredTitle",{defaultValue:"Bot setup"}):$?c("settings:instances.setup.title",{defaultValue:"Connection"}):c("settings:instances.credentials",{defaultValue:"Credentials"})}),$&&!t.hasConfig&&e.jsx("div",{role:"tablist",className:"inline-flex rounded-lg border border-border-default bg-surface-secondary p-0.5 mb-4",children:["guided","manual"].map(E=>e.jsx("button",{type:"button",role:"tab","aria-selected":D===E,onClick:()=>B(E),"data-testid":`setup-method-${E}-${re}`,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${D===E?"bg-surface-elevated text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:E==="guided"?c("settings:instances.setup.guided",{defaultValue:"Scan to create (recommended)"}):c("settings:instances.setup.manual",{defaultValue:"Enter credentials manually"})},E))}),S?e.jsx("div",{className:"space-y-4",children:ye.render(Ue)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:eo,children:[e.jsxs("label",{htmlFor:Ke,className:Gr,children:[c("settings:instances.addBot.name",{defaultValue:"Bot name"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),e.jsx("div",{className:to,children:e.jsx("input",{id:Ke,"data-testid":`new-bot-name-${t.platform}`,value:P,onChange:E=>Zt(E.target.value),placeholder:c("settings:instances.addBot.namePlaceholder",{defaultValue:"e.g. Sales"}),className:Jr})})]}),Ts.length>0&&e.jsx(At,{status:k,draft:y,fields:Ts,onChange:fe,agentOptions:te}),Et.length>0&&(tt&&!Rt?e.jsx("div",{"data-testid":`instance-credentials-configured-${re}`,className:"space-y-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!0),"data-testid":`instance-credentials-edit-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsEdit",{defaultValue:"Change"})})]})}):e.jsxs("div",{className:"space-y-3",children:[tt&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!1),"data-testid":`instance-credentials-hide-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsHide",{defaultValue:"Hide"})})]}),e.jsx(At,{status:k,draft:y,fields:Et,onChange:fe,agentOptions:te})]}))]}),e.jsx("div",{className:"mt-3 min-h-[1.25rem]","data-testid":`instance-save-state-${re}`,children:e.jsxs("span",{"data-state":F.kind,className:"inline-flex items-center gap-2 text-xs text-fg-tertiary",children:[F.kind==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),c("settings:instances.autosave.saving",{defaultValue:"Saving…"})]}),F.kind==="saved"&&e.jsxs("span",{className:"text-green-600",children:["✓ ",c("settings:instances.autosave.saved",{defaultValue:"Saved"})]}),!et&&!S&&e.jsx("span",{"data-testid":`instance-missing-${re}`,children:ut.length>0?c("settings:integrations.missingRequired",{defaultValue:"Required: {{fields}}",fields:pt}):c("settings:instances.addBot.labelRequired",{defaultValue:"Give the bot a name."})})]})}),F.kind==="error"&&e.jsx("div",{className:"mt-2",children:e.jsx(Jt,{type:"err",text:F.text})})]}),!u&&e.jsxs("section",{children:[e.jsx(Cl,{test:ie,starting:f,lastVerifiedAt:t.lastVerifiedAt,onStart:()=>{ts()}}),p&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:p})})]}),!u&&mt&&e.jsx(Al,{status:k,values:y,setValue:fe,channels:L,canListChannels:t.canListChannels,channelsLoading:_,channelsError:J,onReloadChannels:H,channelsGuidance:t.channelsGuidance??null,testSlot:ye?.sendTest?.(Ue)}),e.jsxs("section",{"data-testid":`instance-more-${re}`,children:[e.jsxs("button",{type:"button",onClick:()=>j(E=>!E),"aria-expanded":v,"data-testid":`instance-more-toggle-${re}`,className:"w-full flex items-center gap-2 text-left group px-1",children:[e.jsx("span",{className:Wt,children:c("settings:instances.moreSettings",{defaultValue:"Advanced"})}),e.jsx("span",{className:`${Ct} truncate hidden sm:inline`,children:c("settings:instances.moreSettingsHint",{defaultValue:"Chat routing and platform options"})}),e.jsx("svg",{className:`ml-auto w-3.5 h-3.5 text-fg-tertiary transition-transform ${v?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),v&&e.jsxs("div",{className:"mt-3 space-y-4",children:[ns.length>0&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.advancedTitle",{defaultValue:"Platform options"})}),!u&&e.jsx("p",{className:`${Ct} mb-3`,children:c("settings:instances.advancedHint",{defaultValue:"These default to the right value for almost every setup — leave them alone unless you know you need them."})}),e.jsx(At,{status:k,draft:y,fields:ns,onChange:fe,agentOptions:te})]}),!u&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.routing.chats",{defaultValue:"Chat routing"})}),e.jsx("p",{className:`${Ct} mb-3`,children:c("settings:instances.routing.chatsHint",{defaultValue:"The agent bound above answers every chat by default. Route a specific chat to a different agent here."})}),!t.canListChannels&&e.jsx("p",{className:"text-[11px] text-fg-tertiary","data-testid":`instance-chats-unsupported-${re}`,children:t.channelsGuidance?c(t.channelsGuidance,{defaultValue:c("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}):c("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}),t.canListChannels&&e.jsx("div",{className:"mb-2",children:e.jsx(Xa,{loading:_,error:J,onReload:H,empty:L.length===0,buttonTestId:`instance-chats-refresh-${re}`,errorTestId:`instance-chats-error-${re}`})}),t.canListChannels&&L.length>0&&e.jsx("input",{type:"text",value:X,onChange:E=>me(E.target.value),placeholder:c("settings:instances.routing.searchChats",{defaultValue:"Search chats…"}),"data-testid":`instance-chat-search-${re}`,className:"w-full mb-2 px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500"}),e.jsxs("div",{className:"space-y-2","data-testid":`instance-chats-${re}`,children:[tn.map(E=>{const ne=hr(w,E.id);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!!ne,"data-testid":`instance-chat-toggle-${re}-${E.id}`,onChange:ue=>Es(E,ue.target.checked),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate",title:E.id,children:E.name})]}),ne&&e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.id}`,children:e.jsx(Ps,{value:ne.agentId,options:te,onChange:(ue,He)=>Te(E.id,typeof He=="string"?He:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.id)}),as.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!0,"data-testid":`instance-chat-toggle-${re}-${E.nativeId}`,onChange:()=>V(ne=>sa(ne,E.nativeId)),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate font-mono text-xs",title:E.nativeId,children:E.nativeId})]}),e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.nativeId}`,children:e.jsx(Ps,{value:E.agentId,options:te,onChange:(ne,ue)=>Te(E.nativeId,typeof ue=="string"?ue:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.nativeId))]}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-2",children:c("settings:instances.routing.autoSaved",{defaultValue:"Changes are saved automatically."})}),Lt>0&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:c("settings:instances.routing.agentRequired",{defaultValue:"Pick an agent for every selected chat ({{count}} still unassigned).",count:Lt})})})]})]})]}),!$&&ye&&ye.placement!=="before"&&ye.render(Ue),!u&&e.jsx("div",{className:"pt-1",children:e.jsx("button",{type:"button",onClick:()=>ae(!0),"data-testid":`instance-disconnect-${re}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-600 border border-red-500/30 rounded-lg hover:bg-red-500/10 transition-colors",children:c("settings:integrations.disconnect",{defaultValue:"Disconnect"})})})]}),se&&e.jsx(Cs,{title:c("settings:integrations.disconnectConfirmTitle",{defaultValue:"Disconnect this bot?"}),message:c("settings:integrations.disconnectConfirmMessage",{defaultValue:"Its stored credentials are removed and it stops sending and receiving messages. This cannot be undone."}),confirmLabel:c("settings:integrations.disconnect",{defaultValue:"Disconnect"}),variant:"danger",onConfirm:()=>{Rs()},onCancel:()=>ae(!1)})]})}var Nt={},br,la;function Il(){return la||(la=1,br=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),br}var yr={},Ge={},da;function lt(){if(da)return Ge;da=1;let t;const r=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ge.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},Ge.getSymbolTotalCodewords=function(a){return r[a]},Ge.getBCHDigit=function(n){let a=0;for(;n!==0;)a++,n>>>=1;return a},Ge.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');t=a},Ge.isKanjiModeEnabled=function(){return typeof t<"u"},Ge.toSJIS=function(a){return t(a)},Ge}var vr={},ca;function en(){return ca||(ca=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function r(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,o){if(t.isValid(a))return a;try{return r(a)}catch{return o}}})(vr)),vr}var jr,ua;function Ll(){if(ua)return jr;ua=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(r){const n=Math.floor(r/8);return(this.buffer[n]>>>7-r%8&1)===1},put:function(r,n){for(let a=0;a<n;a++)this.putBit((r>>>n-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),r&&(this.buffer[n]|=128>>>this.length%8),this.length++}},jr=t,jr}var Nr,ma;function Ol(){if(ma)return Nr;ma=1;function t(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}return t.prototype.set=function(r,n,a,o){const s=r*this.size+n;this.data[s]=a,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(r,n){return this.data[r*this.size+n]},t.prototype.xor=function(r,n,a){this.data[r*this.size+n]^=a},t.prototype.isReserved=function(r,n){return this.reservedBit[r*this.size+n]},Nr=t,Nr}var wr={},xa;function $l(){return xa||(xa=1,(function(t){const r=lt().getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const o=Math.floor(a/7)+2,s=r(a),d=s===145?26:Math.ceil((s-13)/(2*o-2))*2,c=[s-7];for(let u=1;u<o-1;u++)c[u]=c[u-1]-d;return c.push(6),c.reverse()},t.getPositions=function(a){const o=[],s=t.getRowColCoords(a),d=s.length;for(let c=0;c<d;c++)for(let u=0;u<d;u++)c===0&&u===0||c===0&&u===d-1||c===d-1&&u===0||o.push([s[c],s[u]]);return o}})(wr)),wr}var kr={},ga;function Bl(){if(ga)return kr;ga=1;const t=lt().getSymbolSize,r=7;return kr.getPositions=function(a){const o=t(a);return[[0,0],[o-r,0],[0,o-r]]},kr}var Sr={},fa;function Dl(){return fa||(fa=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const r={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let d=0,c=0,u=0,h=null,x=null;for(let v=0;v<s;v++){c=u=0,h=x=null;for(let j=0;j<s;j++){let k=o.get(v,j);k===h?c++:(c>=5&&(d+=r.N1+(c-5)),h=k,c=1),k=o.get(j,v),k===x?u++:(u>=5&&(d+=r.N1+(u-5)),x=k,u=1)}c>=5&&(d+=r.N1+(c-5)),u>=5&&(d+=r.N1+(u-5))}return d},t.getPenaltyN2=function(o){const s=o.size;let d=0;for(let c=0;c<s-1;c++)for(let u=0;u<s-1;u++){const h=o.get(c,u)+o.get(c,u+1)+o.get(c+1,u)+o.get(c+1,u+1);(h===4||h===0)&&d++}return d*r.N2},t.getPenaltyN3=function(o){const s=o.size;let d=0,c=0,u=0;for(let h=0;h<s;h++){c=u=0;for(let x=0;x<s;x++)c=c<<1&2047|o.get(h,x),x>=10&&(c===1488||c===93)&&d++,u=u<<1&2047|o.get(x,h),x>=10&&(u===1488||u===93)&&d++}return d*r.N3},t.getPenaltyN4=function(o){let s=0;const d=o.data.length;for(let u=0;u<d;u++)s+=o.data[u];return Math.abs(Math.ceil(s*100/d/5)-10)*r.N4};function n(a,o,s){switch(a){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(o,s){const d=s.size;for(let c=0;c<d;c++)for(let u=0;u<d;u++)s.isReserved(u,c)||s.xor(u,c,n(o,u,c))},t.getBestMask=function(o,s){const d=Object.keys(t.Patterns).length;let c=0,u=1/0;for(let h=0;h<d;h++){s(h),t.applyMask(h,o);const x=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(h,o),x<u&&(u=x,c=h)}return c}})(Sr)),Sr}var js={},pa;function no(){if(pa)return js;pa=1;const t=en(),r=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return js.getBlocksCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},js.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},js}var Cr={},Ht={},ha;function Vl(){if(ha)return Ht;ha=1;const t=new Uint8Array(512),r=new Uint8Array(256);return(function(){let a=1;for(let o=0;o<255;o++)t[o]=a,r[a]=o,a<<=1,a&256&&(a^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Ht.log=function(a){if(a<1)throw new Error("log("+a+")");return r[a]},Ht.exp=function(a){return t[a]},Ht.mul=function(a,o){return a===0||o===0?0:t[r[a]+r[o]]},Ht}var ba;function _l(){return ba||(ba=1,(function(t){const r=Vl();t.mul=function(a,o){const s=new Uint8Array(a.length+o.length-1);for(let d=0;d<a.length;d++)for(let c=0;c<o.length;c++)s[d+c]^=r.mul(a[d],o[c]);return s},t.mod=function(a,o){let s=new Uint8Array(a);for(;s.length-o.length>=0;){const d=s[0];for(let u=0;u<o.length;u++)s[u]^=r.mul(o[u],d);let c=0;for(;c<s.length&&s[c]===0;)c++;s=s.slice(c)}return s},t.generateECPolynomial=function(a){let o=new Uint8Array([1]);for(let s=0;s<a;s++)o=t.mul(o,new Uint8Array([1,r.exp(s)]));return o}})(Cr)),Cr}var Ar,ya;function Fl(){if(ya)return Ar;ya=1;const t=_l();function r(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return r.prototype.initialize=function(a){this.degree=a,this.genPoly=t.generateECPolynomial(this.degree)},r.prototype.encode=function(a){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(a.length+this.degree);o.set(a);const s=t.mod(o,this.genPoly),d=this.degree-s.length;if(d>0){const c=new Uint8Array(this.degree);return c.set(s,d),c}return s},Ar=r,Ar}var Pr={},Mr={},Tr={},va;function ao(){return va||(va=1,Tr.isValid=function(r){return!isNaN(r)&&r>=1&&r<=40}),Tr}var $e={},ja;function oo(){if(ja)return $e;ja=1;const t="[0-9]+",r="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
|
|
2
2
|
]))+`;$e.KANJI=new RegExp(n,"g"),$e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),$e.BYTE=new RegExp(a,"g"),$e.NUMERIC=new RegExp(t,"g"),$e.ALPHANUMERIC=new RegExp(r,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),d=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return $e.testKanji=function(u){return o.test(u)},$e.testNumeric=function(u){return s.test(u)},$e.testAlphanumeric=function(u){return d.test(u)},$e}var Na;function dt(){return Na||(Na=1,(function(t){const r=ao(),n=oo();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,d){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!r.isValid(d))throw new Error("Invalid version: "+d);return d>=1&&d<10?s.ccBits[0]:d<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,d){if(t.isValid(s))return s;try{return a(s)}catch{return d}}})(Mr)),Mr}var wa;function Ul(){return wa||(wa=1,(function(t){const r=lt(),n=no(),a=en(),o=dt(),s=ao(),d=7973,c=r.getBCHDigit(d);function u(j,k,P){for(let N=1;N<=40;N++)if(k<=t.getCapacity(N,P,j))return N}function h(j,k){return o.getCharCountIndicator(j,k)+4}function x(j,k){let P=0;return j.forEach(function(N){const y=h(N.mode,k);P+=y+N.getBitsLength()}),P}function v(j,k){for(let P=1;P<=40;P++)if(x(j,P)<=t.getCapacity(P,k,o.MIXED))return P}t.from=function(k,P){return s.isValid(k)?parseInt(k,10):P},t.getCapacity=function(k,P,N){if(!s.isValid(k))throw new Error("Invalid QR Code version");typeof N>"u"&&(N=o.BYTE);const y=r.getSymbolTotalCodewords(k),b=n.getTotalCodewordsCount(k,P),A=(y-b)*8;if(N===o.MIXED)return A;const m=A-h(N,k);switch(N){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},t.getBestVersionForData=function(k,P){let N;const y=a.from(P,a.M);if(Array.isArray(k)){if(k.length>1)return v(k,y);if(k.length===0)return 1;N=k[0]}else N=k;return u(N.mode,N.getLength(),y)},t.getEncodedBits=function(k){if(!s.isValid(k)||k<7)throw new Error("Invalid QR Code version");let P=k<<12;for(;r.getBCHDigit(P)-c>=0;)P^=d<<r.getBCHDigit(P)-c;return k<<12|P}})(Pr)),Pr}var Er={},ka;function Kl(){if(ka)return Er;ka=1;const t=lt(),r=1335,n=21522,a=t.getBCHDigit(r);return Er.getEncodedBits=function(s,d){const c=s.bit<<3|d;let u=c<<10;for(;t.getBCHDigit(u)-a>=0;)u^=r<<t.getBCHDigit(u)-a;return(c<<10|u)^n},Er}var Rr={},Ir,Sa;function Hl(){if(Sa)return Ir;Sa=1;const t=dt();function r(n){this.mode=t.NUMERIC,this.data=n.toString()}return r.getBitsLength=function(a){return 10*Math.floor(a/3)+(a%3?a%3*3+1:0)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(a){let o,s,d;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),d=parseInt(s,10),a.put(d,10);const c=this.data.length-o;c>0&&(s=this.data.substr(o),d=parseInt(s,10),a.put(d,c*3+1))},Ir=r,Ir}var Lr,Ca;function ql(){if(Ca)return Lr;Ca=1;const t=dt(),r=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(a){this.mode=t.ALPHANUMERIC,this.data=a}return n.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let d=r.indexOf(this.data[s])*45;d+=r.indexOf(this.data[s+1]),o.put(d,11)}this.data.length%2&&o.put(r.indexOf(this.data[s]),6)},Lr=n,Lr}var Or,Aa;function zl(){if(Aa)return Or;Aa=1;const t=dt();function r(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return r.getBitsLength=function(a){return a*8},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){for(let a=0,o=this.data.length;a<o;a++)n.put(this.data[a],8)},Or=r,Or}var $r,Pa;function Wl(){if(Pa)return $r;Pa=1;const t=dt(),r=lt();function n(a){this.mode=t.KANJI,this.data=a}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(a){let o;for(o=0;o<this.data.length;o++){let s=r.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
|
|
3
3
|
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),a.put(s,13)}},$r=n,$r}var Br={exports:{}},Ma;function Gl(){return Ma||(Ma=1,(function(t){var r={single_source_shortest_paths:function(n,a,o){var s={},d={};d[a]=0;var c=r.PriorityQueue.make();c.push(a,0);for(var u,h,x,v,j,k,P,N,y;!c.empty();){u=c.pop(),h=u.value,v=u.cost,j=n[h]||{};for(x in j)j.hasOwnProperty(x)&&(k=j[x],P=v+k,N=d[x],y=typeof d[x]>"u",(y||N>P)&&(d[x]=P,c.push(x,P),s[x]=h))}if(typeof o<"u"&&typeof d[o]>"u"){var b=["Could not find a path from ",a," to ",o,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(n,a){for(var o=[],s=a;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,a,o){var s=r.single_source_shortest_paths(n,a,o);return r.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var a=r.PriorityQueue,o={},s;n=n||{};for(s in a)a.hasOwnProperty(s)&&(o[s]=a[s]);return o.queue=[],o.sorter=n.sorter||a.default_sorter,o},default_sorter:function(n,a){return n.cost-a.cost},push:function(n,a){var o={value:n,cost:a};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=r})(Br)),Br.exports}var Ta;function Jl(){return Ta||(Ta=1,(function(t){const r=dt(),n=Hl(),a=ql(),o=zl(),s=Wl(),d=oo(),c=lt(),u=Gl();function h(b){return unescape(encodeURIComponent(b)).length}function x(b,A,m){const w=[];let V;for(;(V=b.exec(m))!==null;)w.push({data:V[0],index:V.index,mode:A,length:V[0].length});return w}function v(b){const A=x(d.NUMERIC,r.NUMERIC,b),m=x(d.ALPHANUMERIC,r.ALPHANUMERIC,b);let w,V;return c.isKanjiModeEnabled()?(w=x(d.BYTE,r.BYTE,b),V=x(d.KANJI,r.KANJI,b)):(w=x(d.BYTE_KANJI,r.BYTE,b),V=[]),A.concat(m,w,V).sort(function(I,F){return I.index-F.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function j(b,A){switch(A){case r.NUMERIC:return n.getBitsLength(b);case r.ALPHANUMERIC:return a.getBitsLength(b);case r.KANJI:return s.getBitsLength(b);case r.BYTE:return o.getBitsLength(b)}}function k(b){return b.reduce(function(A,m){const w=A.length-1>=0?A[A.length-1]:null;return w&&w.mode===m.mode?(A[A.length-1].data+=m.data,A):(A.push(m),A)},[])}function P(b){const A=[];for(let m=0;m<b.length;m++){const w=b[m];switch(w.mode){case r.NUMERIC:A.push([w,{data:w.data,mode:r.ALPHANUMERIC,length:w.length},{data:w.data,mode:r.BYTE,length:w.length}]);break;case r.ALPHANUMERIC:A.push([w,{data:w.data,mode:r.BYTE,length:w.length}]);break;case r.KANJI:A.push([w,{data:w.data,mode:r.BYTE,length:h(w.data)}]);break;case r.BYTE:A.push([{data:w.data,mode:r.BYTE,length:h(w.data)}])}}return A}function N(b,A){const m={},w={start:{}};let V=["start"];for(let T=0;T<b.length;T++){const I=b[T],F=[];for(let C=0;C<I.length;C++){const $=I[C],D=""+T+C;F.push(D),m[D]={node:$,lastCount:0},w[D]={};for(let B=0;B<V.length;B++){const S=V[B];m[S]&&m[S].node.mode===$.mode?(w[S][D]=j(m[S].lastCount+$.length,$.mode)-j(m[S].lastCount,$.mode),m[S].lastCount+=$.length):(m[S]&&(m[S].lastCount=$.length),w[S][D]=j($.length,$.mode)+4+r.getCharCountIndicator($.mode,A))}}V=F}for(let T=0;T<V.length;T++)w[V[T]].end=0;return{map:w,table:m}}function y(b,A){let m;const w=r.getBestModeForData(b);if(m=r.from(A,w),m!==r.BYTE&&m.bit<w.bit)throw new Error('"'+b+'" cannot be encoded with mode '+r.toString(m)+`.
|
|
4
4
|
Suggested mode is: `+r.toString(w));switch(m===r.KANJI&&!c.isKanjiModeEnabled()&&(m=r.BYTE),m){case r.NUMERIC:return new n(b);case r.ALPHANUMERIC:return new a(b);case r.KANJI:return new s(b);case r.BYTE:return new o(b)}}t.fromArray=function(A){return A.reduce(function(m,w){return typeof w=="string"?m.push(y(w,null)):w.data&&m.push(y(w.data,w.mode)),m},[])},t.fromString=function(A,m){const w=v(A,c.isKanjiModeEnabled()),V=P(w),T=N(V,m),I=u.find_path(T.map,"start","end"),F=[];for(let C=1;C<I.length-1;C++)F.push(T.table[I[C]].node);return t.fromArray(k(F))},t.rawSplit=function(A){return t.fromArray(v(A,c.isKanjiModeEnabled()))}})(Rr)),Rr}var Ea;function Yl(){if(Ea)return yr;Ea=1;const t=lt(),r=en(),n=Ll(),a=Ol(),o=$l(),s=Bl(),d=Dl(),c=no(),u=Fl(),h=Ul(),x=Kl(),v=dt(),j=Jl();function k(T,I){const F=T.size,C=s.getPositions(I);for(let $=0;$<C.length;$++){const D=C[$][0],B=C[$][1];for(let S=-1;S<=7;S++)if(!(D+S<=-1||F<=D+S))for(let L=-1;L<=7;L++)B+L<=-1||F<=B+L||(S>=0&&S<=6&&(L===0||L===6)||L>=0&&L<=6&&(S===0||S===6)||S>=2&&S<=4&&L>=2&&L<=4?T.set(D+S,B+L,!0,!0):T.set(D+S,B+L,!1,!0))}}function P(T){const I=T.size;for(let F=8;F<I-8;F++){const C=F%2===0;T.set(F,6,C,!0),T.set(6,F,C,!0)}}function N(T,I){const F=o.getPositions(I);for(let C=0;C<F.length;C++){const $=F[C][0],D=F[C][1];for(let B=-2;B<=2;B++)for(let S=-2;S<=2;S++)B===-2||B===2||S===-2||S===2||B===0&&S===0?T.set($+B,D+S,!0,!0):T.set($+B,D+S,!1,!0)}}function y(T,I){const F=T.size,C=h.getEncodedBits(I);let $,D,B;for(let S=0;S<18;S++)$=Math.floor(S/3),D=S%3+F-8-3,B=(C>>S&1)===1,T.set($,D,B,!0),T.set(D,$,B,!0)}function b(T,I,F){const C=T.size,$=x.getEncodedBits(I,F);let D,B;for(D=0;D<15;D++)B=($>>D&1)===1,D<6?T.set(D,8,B,!0):D<8?T.set(D+1,8,B,!0):T.set(C-15+D,8,B,!0),D<8?T.set(8,C-D-1,B,!0):D<9?T.set(8,15-D-1+1,B,!0):T.set(8,15-D-1,B,!0);T.set(C-8,8,1,!0)}function A(T,I){const F=T.size;let C=-1,$=F-1,D=7,B=0;for(let S=F-1;S>0;S-=2)for(S===6&&S--;;){for(let L=0;L<2;L++)if(!T.isReserved($,S-L)){let J=!1;B<I.length&&(J=(I[B]>>>D&1)===1),T.set($,S-L,J),D--,D===-1&&(B++,D=7)}if($+=C,$<0||F<=$){$-=C,C=-C;break}}}function m(T,I,F){const C=new n;F.forEach(function(L){C.put(L.mode.bit,4),C.put(L.getLength(),v.getCharCountIndicator(L.mode,T)),L.write(C)});const $=t.getSymbolTotalCodewords(T),D=c.getTotalCodewordsCount(T,I),B=($-D)*8;for(C.getLengthInBits()+4<=B&&C.put(0,4);C.getLengthInBits()%8!==0;)C.putBit(0);const S=(B-C.getLengthInBits())/8;for(let L=0;L<S;L++)C.put(L%2?17:236,8);return w(C,T,I)}function w(T,I,F){const C=t.getSymbolTotalCodewords(I),$=c.getTotalCodewordsCount(I,F),D=C-$,B=c.getBlocksCount(I,F),S=C%B,L=B-S,J=Math.floor(C/B),_=Math.floor(D/B),H=_+1,X=J-_,me=new u(X);let ie=0;const ee=new Array(B),f=new Array(B);let R=0;const p=new Uint8Array(T.buffer);for(let ge=0;ge<B;ge++){const te=ge<L?_:H;ee[ge]=p.slice(ie,ie+te),f[ge]=me.encode(ee[ge]),ie+=te,R=Math.max(R,te)}const K=new Uint8Array(C);let z=0,se,ae;for(se=0;se<R;se++)for(ae=0;ae<B;ae++)se<ee[ae].length&&(K[z++]=ee[ae][se]);for(se=0;se<X;se++)for(ae=0;ae<B;ae++)K[z++]=f[ae][se];return K}function V(T,I,F,C){let $;if(Array.isArray(T))$=j.fromArray(T);else if(typeof T=="string"){let J=I;if(!J){const _=j.rawSplit(T);J=h.getBestVersionForData(_,F)}$=j.fromString(T,J||40)}else throw new Error("Invalid data");const D=h.getBestVersionForData($,F);if(!D)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=D;else if(I<D)throw new Error(`
|