ima2-gen 3.7.1 → 3.7.2

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.
Files changed (31) hide show
  1. package/docs/migration/runtime-test-inventory.md +3 -1
  2. package/lib/grokProxyLauncher.js +110 -1
  3. package/package.json +2 -2
  4. package/routes/auth.js +6 -3
  5. package/routes/grok.js +13 -3
  6. package/routes/index.js +1 -1
  7. package/routes/models.js +33 -4
  8. package/server.js +46 -23
  9. package/ui/dist/.vite/manifest.json +36 -36
  10. package/ui/dist/assets/{AgentWorkspace-DU9efUdT.js → AgentWorkspace-JQ0K_ndE.js} +1 -1
  11. package/ui/dist/assets/{AssetGenWorkspace-ldEVBldg.js → AssetGenWorkspace-B2d-aiIb.js} +2 -2
  12. package/ui/dist/assets/{AssetsWorkspace-D_kJ7dP_.js → AssetsWorkspace-Di0BYZZW.js} +1 -1
  13. package/ui/dist/assets/{CardNewsWorkspace-DIhk26qD.js → CardNewsWorkspace-F3LrEj0b.js} +1 -1
  14. package/ui/dist/assets/{GenerationRequestLogPanel-BZZJh4w_.js → GenerationRequestLogPanel-CpyvTE6t.js} +1 -1
  15. package/ui/dist/assets/{HomeWorkspace-DwRS4Cim.js → HomeWorkspace-KplbVQT9.js} +1 -1
  16. package/ui/dist/assets/{KeyingPanel-YkL9305F.js → KeyingPanel-BY_xV317.js} +1 -1
  17. package/ui/dist/assets/{NodeCanvas-CaFDJn_9.js → NodeCanvas-scDxt0LA.js} +1 -1
  18. package/ui/dist/assets/{PromptBuilderPanel-Bl5-fDQs.js → PromptBuilderPanel-DeSY9dl-.js} +1 -1
  19. package/ui/dist/assets/{PromptImportDialog-5RbU95_Y.js → PromptImportDialog-BTP0imZl.js} +2 -2
  20. package/ui/dist/assets/{PromptImportDiscoverySection-uhS5xI0p.js → PromptImportDiscoverySection-BBThhJZM.js} +1 -1
  21. package/ui/dist/assets/{PromptImportFolderSection-COwFVcbE.js → PromptImportFolderSection-6sXWWJoK.js} +1 -1
  22. package/ui/dist/assets/{PromptLibraryPanel-DCtxfzy1.js → PromptLibraryPanel-BYTG-mBa.js} +2 -2
  23. package/ui/dist/assets/{SettingsWorkspace-aHoTeB4-.js → SettingsWorkspace-chsddbrB.js} +1 -1
  24. package/ui/dist/assets/{SpriteRecipeWorkspace-B0fR6yXF.js → SpriteRecipeWorkspace-HgacgO0x.js} +1 -1
  25. package/ui/dist/assets/{index-Bj2sxDP3.js → index-BqFlxfzT.js} +2 -2
  26. package/ui/dist/assets/{index-DBh-jt0i.js → index-VXkP0z69.js} +3 -3
  27. package/ui/dist/assets/index-waPOg2eb.css +1 -0
  28. package/ui/dist/assets/{pptxgen.es-AWrWIHuf.js → pptxgen.es-DX8PxAzM.js} +1 -1
  29. package/ui/dist/assets/{useAgentDialogFocus-BB6ds9jo.js → useAgentDialogFocus-DYjA7lCJ.js} +1 -1
  30. package/ui/dist/index.html +2 -2
  31. package/ui/dist/assets/index-BnMUy9kc.css +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NodeCanvas-CaFDJn_9.js","assets/NodeCanvas-BnuhLJ6X.css","assets/AgentWorkspace-DU9efUdT.js","assets/useAgentDialogFocus-BB6ds9jo.js","assets/AssetsWorkspace-D_kJ7dP_.js","assets/KeyingPanel-YkL9305F.js","assets/AssetsWorkspace-BkUjPPKU.css","assets/AssetGenWorkspace-ldEVBldg.js","assets/AssetGenWorkspace-Dkr80l12.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NodeCanvas-scDxt0LA.js","assets/NodeCanvas-BnuhLJ6X.css","assets/AgentWorkspace-JQ0K_ndE.js","assets/useAgentDialogFocus-DYjA7lCJ.js","assets/AssetsWorkspace-Di0BYZZW.js","assets/KeyingPanel-BY_xV317.js","assets/AssetsWorkspace-BkUjPPKU.css","assets/AssetGenWorkspace-B2d-aiIb.js","assets/AssetGenWorkspace-Dkr80l12.css"])))=>i.map(i=>d[i]);
2
2
  (function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const c of s)if(c.type==="childList")for(const m of c.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&o(m)}).observe(document,{childList:!0,subtree:!0});function i(s){const c={};return s.integrity&&(c.integrity=s.integrity),s.referrerPolicy&&(c.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?c.credentials="include":s.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function o(s){if(s.ep)return;s.ep=!0;const c=i(s);fetch(s.href,c)}})();var ZO=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function eT(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var uu={exports:{}},ri={};var Vh;function tT(){if(Vh)return ri;Vh=1;var e=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function i(o,s,c){var m=null;if(c!==void 0&&(m=""+c),s.key!==void 0&&(m=""+s.key),"key"in s){c={};for(var p in s)p!=="key"&&(c[p]=s[p])}else c=s;return s=c.ref,{$$typeof:e,type:o,key:m,ref:s!==void 0?s:null,props:c}}return ri.Fragment=a,ri.jsx=i,ri.jsxs=i,ri}var Kh;function nT(){return Kh||(Kh=1,uu.exports=tT()),uu.exports}var d=nT(),mu={exports:{}},Ce={};var $h;function aT(){if($h)return Ce;$h=1;var e=Symbol.for("react.transitional.element"),a=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),m=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),y=Symbol.iterator;function x(T){return T===null||typeof T!="object"?null:(T=y&&T[y]||T["@@iterator"],typeof T=="function"?T:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},P=Object.assign,I={};function k(T,F,W){this.props=T,this.context=F,this.refs=I,this.updater=W||E}k.prototype.isReactComponent={},k.prototype.setState=function(T,F){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,F,"setState")},k.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function C(){}C.prototype=k.prototype;function _(T,F,W){this.props=T,this.context=F,this.refs=I,this.updater=W||E}var N=_.prototype=new C;N.constructor=_,P(N,k.prototype),N.isPureReactComponent=!0;var j=Array.isArray;function $(){}var L={H:null,A:null,T:null,S:null},J=Object.prototype.hasOwnProperty;function re(T,F,W){var U=W.ref;return{$$typeof:e,type:T,key:F,ref:U!==void 0?U:null,props:W}}function he(T,F){return re(T.type,F,T.props)}function V(T){return typeof T=="object"&&T!==null&&T.$$typeof===e}function ee(T){var F={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(W){return F[W]})}var oe=/\/+/g;function Ne(T,F){return typeof T=="object"&&T!==null&&T.key!=null?ee(""+T.key):F.toString(36)}function ne(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then($,$):(T.status="pending",T.then(function(F){T.status==="pending"&&(T.status="fulfilled",T.value=F)},function(F){T.status==="pending"&&(T.status="rejected",T.reason=F)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function H(T,F,W,U,le){var pe=typeof T;(pe==="undefined"||pe==="boolean")&&(T=null);var xe=!1;if(T===null)xe=!0;else switch(pe){case"bigint":case"string":case"number":xe=!0;break;case"object":switch(T.$$typeof){case e:case a:xe=!0;break;case S:return xe=T._init,H(xe(T._payload),F,W,U,le)}}if(xe)return le=le(T),xe=U===""?"."+Ne(T,0):U,j(le)?(W="",xe!=null&&(W=xe.replace(oe,"$&/")+"/"),H(le,F,W,"",function(Ze){return Ze})):le!=null&&(V(le)&&(le=he(le,W+(le.key==null||T&&T.key===le.key?"":(""+le.key).replace(oe,"$&/")+"/")+xe)),F.push(le)),1;xe=0;var Oe=U===""?".":U+":";if(j(T))for(var Re=0;Re<T.length;Re++)U=T[Re],pe=Oe+Ne(U,Re),xe+=H(U,F,W,pe,le);else if(Re=x(T),typeof Re=="function")for(T=Re.call(T),Re=0;!(U=T.next()).done;)U=U.value,pe=Oe+Ne(U,Re++),xe+=H(U,F,W,pe,le);else if(pe==="object"){if(typeof T.then=="function")return H(ne(T),F,W,U,le);throw F=String(T),Error("Objects are not valid as a React child (found: "+(F==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":F)+"). If you meant to render a collection of children, use an array instead.")}return xe}function ae(T,F,W){if(T==null)return T;var U=[],le=0;return H(T,U,"","",function(pe){return F.call(W,pe,le++)}),U}function ce(T){if(T._status===-1){var F=T._result;F=F(),F.then(function(W){(T._status===0||T._status===-1)&&(T._status=1,T._result=W)},function(W){(T._status===0||T._status===-1)&&(T._status=2,T._result=W)}),T._status===-1&&(T._status=0,T._result=F)}if(T._status===1)return T._result.default;throw T._result}var be=typeof reportError=="function"?reportError:function(T){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var F=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof T=="object"&&T!==null&&typeof T.message=="string"?String(T.message):String(T),error:T});if(!window.dispatchEvent(F))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",T);return}console.error(T)},Se={map:ae,forEach:function(T,F,W){ae(T,function(){F.apply(this,arguments)},W)},count:function(T){var F=0;return ae(T,function(){F++}),F},toArray:function(T){return ae(T,function(F){return F})||[]},only:function(T){if(!V(T))throw Error("React.Children.only expected to receive a single React element child.");return T}};return Ce.Activity=v,Ce.Children=Se,Ce.Component=k,Ce.Fragment=i,Ce.Profiler=s,Ce.PureComponent=_,Ce.StrictMode=o,Ce.Suspense=h,Ce.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=L,Ce.__COMPILER_RUNTIME={__proto__:null,c:function(T){return L.H.useMemoCache(T)}},Ce.cache=function(T){return function(){return T.apply(null,arguments)}},Ce.cacheSignal=function(){return null},Ce.cloneElement=function(T,F,W){if(T==null)throw Error("The argument must be a React element, but you passed "+T+".");var U=P({},T.props),le=T.key;if(F!=null)for(pe in F.key!==void 0&&(le=""+F.key),F)!J.call(F,pe)||pe==="key"||pe==="__self"||pe==="__source"||pe==="ref"&&F.ref===void 0||(U[pe]=F[pe]);var pe=arguments.length-2;if(pe===1)U.children=W;else if(1<pe){for(var xe=Array(pe),Oe=0;Oe<pe;Oe++)xe[Oe]=arguments[Oe+2];U.children=xe}return re(T.type,le,U)},Ce.createContext=function(T){return T={$$typeof:m,_currentValue:T,_currentValue2:T,_threadCount:0,Provider:null,Consumer:null},T.Provider=T,T.Consumer={$$typeof:c,_context:T},T},Ce.createElement=function(T,F,W){var U,le={},pe=null;if(F!=null)for(U in F.key!==void 0&&(pe=""+F.key),F)J.call(F,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(le[U]=F[U]);var xe=arguments.length-2;if(xe===1)le.children=W;else if(1<xe){for(var Oe=Array(xe),Re=0;Re<xe;Re++)Oe[Re]=arguments[Re+2];le.children=Oe}if(T&&T.defaultProps)for(U in xe=T.defaultProps,xe)le[U]===void 0&&(le[U]=xe[U]);return re(T,pe,le)},Ce.createRef=function(){return{current:null}},Ce.forwardRef=function(T){return{$$typeof:p,render:T}},Ce.isValidElement=V,Ce.lazy=function(T){return{$$typeof:S,_payload:{_status:-1,_result:T},_init:ce}},Ce.memo=function(T,F){return{$$typeof:g,type:T,compare:F===void 0?null:F}},Ce.startTransition=function(T){var F=L.T,W={};L.T=W;try{var U=T(),le=L.S;le!==null&&le(W,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then($,be)}catch(pe){be(pe)}finally{F!==null&&W.types!==null&&(F.types=W.types),L.T=F}},Ce.unstable_useCacheRefresh=function(){return L.H.useCacheRefresh()},Ce.use=function(T){return L.H.use(T)},Ce.useActionState=function(T,F,W){return L.H.useActionState(T,F,W)},Ce.useCallback=function(T,F){return L.H.useCallback(T,F)},Ce.useContext=function(T){return L.H.useContext(T)},Ce.useDebugValue=function(){},Ce.useDeferredValue=function(T,F){return L.H.useDeferredValue(T,F)},Ce.useEffect=function(T,F){return L.H.useEffect(T,F)},Ce.useEffectEvent=function(T){return L.H.useEffectEvent(T)},Ce.useId=function(){return L.H.useId()},Ce.useImperativeHandle=function(T,F,W){return L.H.useImperativeHandle(T,F,W)},Ce.useInsertionEffect=function(T,F){return L.H.useInsertionEffect(T,F)},Ce.useLayoutEffect=function(T,F){return L.H.useLayoutEffect(T,F)},Ce.useMemo=function(T,F){return L.H.useMemo(T,F)},Ce.useOptimistic=function(T,F){return L.H.useOptimistic(T,F)},Ce.useReducer=function(T,F,W){return L.H.useReducer(T,F,W)},Ce.useRef=function(T){return L.H.useRef(T)},Ce.useState=function(T){return L.H.useState(T)},Ce.useSyncExternalStore=function(T,F,W){return L.H.useSyncExternalStore(T,F,W)},Ce.useTransition=function(){return L.H.useTransition()},Ce.version="19.2.8",Ce}var Yh;function am(){return Yh||(Yh=1,mu.exports=aT()),mu.exports}var R=am();const Hl=eT(R);var pu={exports:{}},ii={},fu={exports:{}},gu={};var Xh;function oT(){return Xh||(Xh=1,(function(e){function a(H,ae){var ce=H.length;H.push(ae);e:for(;0<ce;){var be=ce-1>>>1,Se=H[be];if(0<s(Se,ae))H[be]=ae,H[ce]=Se,ce=be;else break e}}function i(H){return H.length===0?null:H[0]}function o(H){if(H.length===0)return null;var ae=H[0],ce=H.pop();if(ce!==ae){H[0]=ce;e:for(var be=0,Se=H.length,T=Se>>>1;be<T;){var F=2*(be+1)-1,W=H[F],U=F+1,le=H[U];if(0>s(W,ce))U<Se&&0>s(le,W)?(H[be]=le,H[U]=ce,be=U):(H[be]=W,H[F]=ce,be=F);else if(U<Se&&0>s(le,ce))H[be]=le,H[U]=ce,be=U;else break e}}return ae}function s(H,ae){var ce=H.sortIndex-ae.sortIndex;return ce!==0?ce:H.id-ae.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;e.unstable_now=function(){return c.now()}}else{var m=Date,p=m.now();e.unstable_now=function(){return m.now()-p}}var h=[],g=[],S=1,v=null,y=3,x=!1,E=!1,P=!1,I=!1,k=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;function N(H){for(var ae=i(g);ae!==null;){if(ae.callback===null)o(g);else if(ae.startTime<=H)o(g),ae.sortIndex=ae.expirationTime,a(h,ae);else break;ae=i(g)}}function j(H){if(P=!1,N(H),!E)if(i(h)!==null)E=!0,$||($=!0,ee());else{var ae=i(g);ae!==null&&ne(j,ae.startTime-H)}}var $=!1,L=-1,J=5,re=-1;function he(){return I?!0:!(e.unstable_now()-re<J)}function V(){if(I=!1,$){var H=e.unstable_now();re=H;var ae=!0;try{e:{E=!1,P&&(P=!1,C(L),L=-1),x=!0;var ce=y;try{t:{for(N(H),v=i(h);v!==null&&!(v.expirationTime>H&&he());){var be=v.callback;if(typeof be=="function"){v.callback=null,y=v.priorityLevel;var Se=be(v.expirationTime<=H);if(H=e.unstable_now(),typeof Se=="function"){v.callback=Se,N(H),ae=!0;break t}v===i(h)&&o(h),N(H)}else o(h);v=i(h)}if(v!==null)ae=!0;else{var T=i(g);T!==null&&ne(j,T.startTime-H),ae=!1}}break e}finally{v=null,y=ce,x=!1}ae=void 0}}finally{ae?ee():$=!1}}}var ee;if(typeof _=="function")ee=function(){_(V)};else if(typeof MessageChannel<"u"){var oe=new MessageChannel,Ne=oe.port2;oe.port1.onmessage=V,ee=function(){Ne.postMessage(null)}}else ee=function(){k(V,0)};function ne(H,ae){L=k(function(){H(e.unstable_now())},ae)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):J=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_next=function(H){switch(y){case 1:case 2:case 3:var ae=3;break;default:ae=y}var ce=y;y=ae;try{return H()}finally{y=ce}},e.unstable_requestPaint=function(){I=!0},e.unstable_runWithPriority=function(H,ae){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var ce=y;y=H;try{return ae()}finally{y=ce}},e.unstable_scheduleCallback=function(H,ae,ce){var be=e.unstable_now();switch(typeof ce=="object"&&ce!==null?(ce=ce.delay,ce=typeof ce=="number"&&0<ce?be+ce:be):ce=be,H){case 1:var Se=-1;break;case 2:Se=250;break;case 5:Se=1073741823;break;case 4:Se=1e4;break;default:Se=5e3}return Se=ce+Se,H={id:S++,callback:ae,priorityLevel:H,startTime:ce,expirationTime:Se,sortIndex:-1},ce>be?(H.sortIndex=ce,a(g,H),i(h)===null&&H===i(g)&&(P?(C(L),L=-1):P=!0,ne(j,ce-be))):(H.sortIndex=Se,a(h,H),E||x||(E=!0,$||($=!0,ee()))),H},e.unstable_shouldYield=he,e.unstable_wrapCallback=function(H){var ae=y;return function(){var ce=y;y=ae;try{return H.apply(this,arguments)}finally{y=ce}}}})(gu)),gu}var Qh;function rT(){return Qh||(Qh=1,fu.exports=oT()),fu.exports}var hu={exports:{}},Nt={};var Jh;function iT(){if(Jh)return Nt;Jh=1;var e=am();function a(h){var g="https://react.dev/errors/"+h;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var S=2;S<arguments.length;S++)g+="&args[]="+encodeURIComponent(arguments[S])}return"Minified React error #"+h+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(){}var o={d:{f:i,r:function(){throw Error(a(522))},D:i,C:i,L:i,m:i,X:i,S:i,M:i},p:0,findDOMNode:null},s=Symbol.for("react.portal");function c(h,g,S){var v=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:v==null?null:""+v,children:h,containerInfo:g,implementation:S}}var m=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function p(h,g){if(h==="font")return"";if(typeof g=="string")return g==="use-credentials"?g:""}return Nt.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=o,Nt.createPortal=function(h,g){var S=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)throw Error(a(299));return c(h,g,null,S)},Nt.flushSync=function(h){var g=m.T,S=o.p;try{if(m.T=null,o.p=2,h)return h()}finally{m.T=g,o.p=S,o.d.f()}},Nt.preconnect=function(h,g){typeof h=="string"&&(g?(g=g.crossOrigin,g=typeof g=="string"?g==="use-credentials"?g:"":void 0):g=null,o.d.C(h,g))},Nt.prefetchDNS=function(h){typeof h=="string"&&o.d.D(h)},Nt.preinit=function(h,g){if(typeof h=="string"&&g&&typeof g.as=="string"){var S=g.as,v=p(S,g.crossOrigin),y=typeof g.integrity=="string"?g.integrity:void 0,x=typeof g.fetchPriority=="string"?g.fetchPriority:void 0;S==="style"?o.d.S(h,typeof g.precedence=="string"?g.precedence:void 0,{crossOrigin:v,integrity:y,fetchPriority:x}):S==="script"&&o.d.X(h,{crossOrigin:v,integrity:y,fetchPriority:x,nonce:typeof g.nonce=="string"?g.nonce:void 0})}},Nt.preinitModule=function(h,g){if(typeof h=="string")if(typeof g=="object"&&g!==null){if(g.as==null||g.as==="script"){var S=p(g.as,g.crossOrigin);o.d.M(h,{crossOrigin:S,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0})}}else g==null&&o.d.M(h)},Nt.preload=function(h,g){if(typeof h=="string"&&typeof g=="object"&&g!==null&&typeof g.as=="string"){var S=g.as,v=p(S,g.crossOrigin);o.d.L(h,S,{crossOrigin:v,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0,type:typeof g.type=="string"?g.type:void 0,fetchPriority:typeof g.fetchPriority=="string"?g.fetchPriority:void 0,referrerPolicy:typeof g.referrerPolicy=="string"?g.referrerPolicy:void 0,imageSrcSet:typeof g.imageSrcSet=="string"?g.imageSrcSet:void 0,imageSizes:typeof g.imageSizes=="string"?g.imageSizes:void 0,media:typeof g.media=="string"?g.media:void 0})}},Nt.preloadModule=function(h,g){if(typeof h=="string")if(g){var S=p(g.as,g.crossOrigin);o.d.m(h,{as:typeof g.as=="string"&&g.as!=="script"?g.as:void 0,crossOrigin:S,integrity:typeof g.integrity=="string"?g.integrity:void 0})}else o.d.m(h)},Nt.requestFormReset=function(h){o.d.r(h)},Nt.unstable_batchedUpdates=function(h,g){return h(g)},Nt.useFormState=function(h,g,S){return m.H.useFormState(h,g,S)},Nt.useFormStatus=function(){return m.H.useHostTransitionStatus()},Nt.version="19.2.8",Nt}var Wh;function mv(){if(Wh)return hu.exports;Wh=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(a){console.error(a)}}return e(),hu.exports=iT(),hu.exports}var Zh;function lT(){if(Zh)return ii;Zh=1;var e=rT(),a=am(),i=mv();function o(t){var n="https://react.dev/errors/"+t;if(1<arguments.length){n+="?args[]="+encodeURIComponent(arguments[1]);for(var r=2;r<arguments.length;r++)n+="&args[]="+encodeURIComponent(arguments[r])}return"Minified React error #"+t+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function c(t){var n=t,r=t;if(t.alternate)for(;n.return;)n=n.return;else{t=n;do n=t,(n.flags&4098)!==0&&(r=n.return),t=n.return;while(t)}return n.tag===3?r:null}function m(t){if(t.tag===13){var n=t.memoizedState;if(n===null&&(t=t.alternate,t!==null&&(n=t.memoizedState)),n!==null)return n.dehydrated}return null}function p(t){if(t.tag===31){var n=t.memoizedState;if(n===null&&(t=t.alternate,t!==null&&(n=t.memoizedState)),n!==null)return n.dehydrated}return null}function h(t){if(c(t)!==t)throw Error(o(188))}function g(t){var n=t.alternate;if(!n){if(n=c(t),n===null)throw Error(o(188));return n!==t?null:t}for(var r=t,l=n;;){var u=r.return;if(u===null)break;var f=u.alternate;if(f===null){if(l=u.return,l!==null){r=l;continue}break}if(u.child===f.child){for(f=u.child;f;){if(f===r)return h(u),t;if(f===l)return h(u),n;f=f.sibling}throw Error(o(188))}if(r.return!==l.return)r=u,l=f;else{for(var b=!1,A=u.child;A;){if(A===r){b=!0,r=u,l=f;break}if(A===l){b=!0,l=u,r=f;break}A=A.sibling}if(!b){for(A=f.child;A;){if(A===r){b=!0,r=f,l=u;break}if(A===l){b=!0,l=f,r=u;break}A=A.sibling}if(!b)throw Error(o(189))}}if(r.alternate!==l)throw Error(o(190))}if(r.tag!==3)throw Error(o(188));return r.stateNode.current===r?t:n}function S(t){var n=t.tag;if(n===5||n===26||n===27||n===6)return t;for(t=t.child;t!==null;){if(n=S(t),n!==null)return n;t=t.sibling}return null}var v=Object.assign,y=Symbol.for("react.element"),x=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),P=Symbol.for("react.fragment"),I=Symbol.for("react.strict_mode"),k=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),_=Symbol.for("react.context"),N=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),J=Symbol.for("react.lazy"),re=Symbol.for("react.activity"),he=Symbol.for("react.memo_cache_sentinel"),V=Symbol.iterator;function ee(t){return t===null||typeof t!="object"?null:(t=V&&t[V]||t["@@iterator"],typeof t=="function"?t:null)}var oe=Symbol.for("react.client.reference");function Ne(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===oe?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case P:return"Fragment";case k:return"Profiler";case I:return"StrictMode";case j:return"Suspense";case $:return"SuspenseList";case re:return"Activity"}if(typeof t=="object")switch(t.$$typeof){case E:return"Portal";case _:return t.displayName||"Context";case C:return(t._context.displayName||"Context")+".Consumer";case N:var n=t.render;return t=t.displayName,t||(t=n.displayName||n.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case L:return n=t.displayName||null,n!==null?n:Ne(t.type)||"Memo";case J:n=t._payload,t=t._init;try{return Ne(t(n))}catch{}}return null}var ne=Array.isArray,H=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ae=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},be=[],Se=-1;function T(t){return{current:t}}function F(t){0>Se||(t.current=be[Se],be[Se]=null,Se--)}function W(t,n){Se++,be[Se]=t.current,t.current=n}var U=T(null),le=T(null),pe=T(null),xe=T(null);function Oe(t,n){switch(W(pe,n),W(le,t),W(U,null),n.nodeType){case 9:case 11:t=(t=n.documentElement)&&(t=t.namespaceURI)?fh(t):0;break;default:if(t=n.tagName,n=n.namespaceURI)n=fh(n),t=gh(n,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}F(U),W(U,t)}function Re(){F(U),F(le),F(pe)}function Ze(t){t.memoizedState!==null&&W(xe,t);var n=U.current,r=gh(n,t.type);n!==r&&(W(le,t),W(U,r))}function ie(t){le.current===t&&(F(U),F(le)),xe.current===t&&(F(xe),ti._currentValue=ce)}var lt,at;function st(t){if(lt===void 0)try{throw Error()}catch(r){var n=r.stack.trim().match(/\n( *(at )?)/);lt=n&&n[1]||"",at=-1<r.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<r.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+lt+t+at}var bt=!1;function se(t,n){if(!t||bt)return"";bt=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(n){var Q=function(){throw Error()};if(Object.defineProperty(Q.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Q,[])}catch(K){var B=K}Reflect.construct(t,[],Q)}else{try{Q.call()}catch(K){B=K}t.call(Q.prototype)}}else{try{throw Error()}catch(K){B=K}(Q=t())&&typeof Q.catch=="function"&&Q.catch(function(){})}}catch(K){if(K&&B&&typeof K.stack=="string")return[K.stack,B.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var f=l.DetermineComponentFrameRoot(),b=f[0],A=f[1];if(b&&A){var M=b.split(`
@@ -27,4 +27,4 @@ Frame`,copyPrompt:"Copy prompt",continueHere:"Continue here",continueHereTitle:"
27
27
  `)}}function Bb(e){if(!e?.entries?.length)return null;const a=e.entries[e.entries.length-1];return`${e.entries.length}/4 clips · last frame · ${a?.filename??"unsaved source"}`}async function lN(e,a){const i=a();if(!xi(i.prompt,i.insertedPrompts)||km(a))return;if(i.videoModelSelected)return a().runVideoGenerate();const s=i.uiMode==="classic"&&i.multimode,c=Us(i,{kind:s?"multimode":"classic"});if(c){e({customSizeConfirm:c});return}if(s){await a().generateMultimode();return}await a().runGenerate()}function sN(e,a){const i=a().multimodePreviewFlightId;i&&(Nb(i),a().cancelInFlightJob(i),e(o=>{const s=o.multimodeSequences[i];return s?{multimodeSequences:{...o.multimodeSequences,[i]:{...s,status:"canceled"}}}:{}}))}function km(e){return(e().missingElementIds??[]).length>0?(e().showToast(Z("toast.missingElements"),!0),!0):!1}async function cN(e,a){const i=a().customSizeConfirm;if(!i||(i.continuation.kind==="classic"||i.continuation.kind==="multimode")&&km(a))return;const o=LR(i.adjustedW,i.adjustedH);if(e({customW:i.adjustedW,customH:i.adjustedH,customSizeConfirm:null}),i.continuation.kind==="classic"){await a().runGenerate(o);return}if(i.continuation.kind==="multimode"){await a().generateMultimode(o);return}if(i.continuation.kind==="node-in-place"){await a().runGenerateNodeInPlace(i.continuation.clientId,{sizeOverride:o});return}if(i.continuation.kind==="node-variation"){await a().generateNodeVariation(i.continuation.clientId,o);return}await a().runGenerateNode(i.continuation.clientId,o)}async function dN(e,a,i){const o=i().graphNodes.find(m=>m.id===e);if(!o)return;const{prompt:s}=o.data;if(!s.trim()){i().showToast(Z("toast.promptRequired"),!0);return}if(i().videoModelSelected)return i().runVideoGenerate(e);const c=Us(i(),{kind:"node",clientId:e});if(c){a({customSizeConfirm:c});return}await i().runGenerateNode(e)}async function uN(e,a,i){const o=i().graphNodes.find(c=>c.id===e);if(!o)return;if(!o.data.prompt.trim()){i().showToast(Z("toast.promptRequired"),!0);return}if(i().videoModelSelected)return i().runVideoGenerate(e);const s=Us(i(),{kind:"node-in-place",clientId:e});if(s){a({customSizeConfirm:s});return}await i().runGenerateNodeInPlace(e)}async function mN(e,a,i,o){const s=o().graphNodes.find(m=>m.id===e);if(!s)return;if(!s.data.prompt.trim()){o().showToast(Z("toast.promptRequired"),!0);return}if(o().videoModelSelected){const m=o().addSiblingNode(e);return o().runVideoGenerate(m)}if(!a){const m=Us(o(),{kind:"node-variation",clientId:e});if(m){i({customSizeConfirm:m});return}}const c=o().addSiblingNode(e);await o().runGenerateNodeInPlace(c,{sizeOverride:a})}async function pN(e,a,i,o){const c=o().graphNodes.find(m=>m.id===e)?.data.status==="ready"?o().addSiblingNode(e):e;await o().runGenerateNodeInPlace(c,{sizeOverride:a})}function Vb(e){const a=e.selectedElementIds;return Array.isArray(a)?a.filter(i=>typeof i=="string"):[]}function Kb(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function fN(e,a,i){const o=e?i().graphNodes.find(N=>N.id===e):null,s=o?o.data.referenceImages??[]:i().referenceImages,c=Rv(s.length),m=o?o.data.prompt.trim():xi(i().prompt,i().insertedPrompts);if(!m.trim()){i().showToast(Ts,!0);return}const p=i(),h=Vs({catalog:Ks(),presetIds:p.selectedPresetIds,provider:Kb(p.provider),mode:"video"}),g=h.promptFragment?`${h.promptFragment} ${m}`:m;let S,v,y=o?o.data.videoContinuity??null:i().videoContinuityLineage,x;if(o&&s.length===0&&o.data.parentServerNodeId){const N=i().graphNodes.find(j=>j.data.serverNodeId===o.data.parentServerNodeId);if(N?.data.imageUrl)if(kn(N.data.imageUrl))try{const j=N.data.imageUrl.replace(/^\/generated\//,"");v=(await oN.extractFrame({kind:"generated",filename:j},"last")).dataUrl,y=N.data.videoContinuity??Hb({filename:j,prompt:N.data.prompt,userPrompt:N.data.prompt,revisedPrompt:N.data.prompt,createdAt:Date.now(),videoContinuity:null}),x=j}catch{i().showToast(Z("video.continuationFallbackT2V"),!0)}else S=N.data.imageUrl.replace(/^\/generated\//,"")}const E=Date.now(),P=E,I=`vid_${E}_${Math.random().toString(36).slice(2,6)}`,k=new AbortController;ur(I,k);const C=i().activeSessionId,_=[...i().inFlight,{id:I,prompt:g,startedAt:E,kind:"video",sessionId:C,clientNodeId:e??null}];jt(_),o&&a({graphNodes:i().graphNodes.map(N=>N.id===e?{...N,data:{...N.data,status:"pending",pendingRequestId:I,pendingPhase:"queued",pendingStartedAt:E,partialImageUrl:null,error:void 0}}:N)}),a({inFlight:_,activeGenerations:_.length,videoProgress:0}),i().startInFlightPolling();try{const N=i().providerUrlReference,j={prompt:g,requestId:I,provider:i().provider==="grok-api"?"grok-api":"grok",model:typeof i().videoModelSelected=="string"&&i().videoModelSelected||void 0,referenceImages:s.length>=2?s:void 0,sourceImage:s.length===1?s[0]:v,sourceFilename:s.length===0&&!v?S:void 0,continueFromVideo:x,continuityLineage:y,duration:m0(i().videoDuration,c),resolution:i().videoResolution,aspectRatio:i().videoAspectRatio,topic:i().videoTopic||void 0,storyboard:i().storyboardActive||void 0,presetIds:h.appliedPresetIds,elementIds:Vb(i()),sessionId:C,clientNodeId:e??null,...N?{providerUrl:N}:{}},$=await rm(j,{onPlanning:()=>a({inFlight:i().inFlight.map(L=>L.id===I?{...L,phase:"planning"}:L)}),onSubmitted:()=>a({inFlight:i().inFlight.map(L=>L.id===I?{...L,phase:"streaming"}:L)}),onProgress:({progress:L})=>a({videoProgress:L??null})},{signal:k.signal});if(o&&$&&i().activeSessionId===C&&(a({graphNodes:i().graphNodes.map(L=>L.id===e?{...L,data:{...L.data,serverNodeId:$.filename.replace(/\.[^.]+$/,""),imageUrl:$.url,status:"ready",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:$.elapsed??void 0,model:$.effectiveModel??$.requestedModel??o.data.model??null,videoContinuity:$.videoContinuity??y,video:{...$.video??{},...$.videoSeries?.topic?{topic:$.videoSeries.topic}:{}}}}:L)}),i().scheduleGraphSave(),i().flushGraphSave("video-node-complete")),$){const L={image:$.url,filename:$.filename,url:$.url,mediaType:"video",prompt:g,elapsed:$.elapsed,video:$.video??{},videoSeries:$.videoSeries??null,videoContinuity:$.videoContinuity??null,revisedPrompt:$.revisedPrompt??null,requestId:$.requestId??I,createdAt:Date.now(),sessionId:C};await Ra(L,a,i,{autoSelectStartedAt:P})}}catch(N){if(sr(N))o&&i().activeSessionId===C&&a({graphNodes:i().graphNodes.map(j=>j.id===e?{...j,data:{...j.data,status:j.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0}}:j)});else{const j=N instanceof Error?N.message:"Video generation failed";o&&i().activeSessionId===C&&a({graphNodes:i().graphNodes.map($=>$.id===e?{...$,data:{...$.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:j}}:$)}),i().showToast(j,!0)}}finally{const N=i().inFlight.filter(j=>j.id!==I);jt(N),mr(I),a({inFlight:N,activeGenerations:N.length,videoProgress:null}),i().startInFlightPolling()}}async function gN(e,a,i,o){const s=a?.trim();if(!s)throw o().showToast(Ts,!0),new Error(Ts);if(km(o))return!1;const c=o(),m=Vs({catalog:Ks(),presetIds:c.selectedPresetIds,provider:Kb(c.provider),mode:"video"}),p=m.promptFragment?`${m.promptFragment} ${s}`:s,h=Date.now(),g=h,S=`vid_${h}_${Math.random().toString(36).slice(2,6)}`,v=new AbortController;ur(S,v);const y=[...o().inFlight,{id:S,prompt:p,startedAt:h,kind:"video",sessionId:o().activeSessionId,clientNodeId:null}];jt(y),i({inFlight:y,activeGenerations:y.length,videoProgress:0}),o().startInFlightPolling();try{const x={prompt:p,presetIds:m.appliedPresetIds,elementIds:Vb(o()),requestId:S,provider:o().provider==="grok-api"?"grok-api":"grok",mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},E=await rm(x,{onPlanning:()=>i({inFlight:o().inFlight.map(I=>I.id===S?{...I,phase:"planning"}:I)}),onSubmitted:()=>i({inFlight:o().inFlight.map(I=>I.id===S?{...I,phase:"streaming"}:I)}),onProgress:({progress:I})=>i({videoProgress:I??null})},{signal:v.signal}),P={image:E.url,filename:E.filename,url:E.url,mediaType:"video",prompt:p,elapsed:E.elapsed,video:E.video??{},videoSeries:E.videoSeries??null,videoContinuity:E.videoContinuity??null,revisedPrompt:E.revisedPrompt??null,requestId:E.requestId??S,createdAt:Date.now(),sessionId:o().activeSessionId};await Ra(P,i,o,{autoSelectStartedAt:g})}catch(x){if(!sr(x)){const E=x instanceof Error?x.message:"Video generation failed";o().showToast(E,!0)}}finally{const x=o().inFlight.filter(E=>E.id!==S);jt(x),mr(S),i({inFlight:x,activeGenerations:x.length,videoProgress:null}),o().startInFlightPolling()}return!0}function hN(e,a){if(typeof window>"u")return;const i=window;if(i.__ima2InflightTimer)return;const o=async()=>{const c=a().inFlight.length===0&&a().activeGenerations===0;c?(i.__ima2StopTicks=(i.__ima2StopTicks??0)+1,i.__ima2StopTicks>=2&&i.__ima2InflightTimer&&(clearInterval(i.__ima2InflightTimer),i.__ima2InflightTimer=void 0,i.__ima2StopTicks=0)):i.__ima2StopTicks=0;let m=new Set;if(!c)try{const p=ib(a()),{jobs:h,terminalJobs:g=[]}=await sb(p);m=new Set(h.map(C=>C.requestId));const S=new Map(h.map(C=>[C.requestId,C])),v=new Map(g.map(C=>[C.requestId,C])),y=[];let x=!1;const E=Date.now(),P=5e3,I=[];for(const C of a().inFlight){if(!lb(C,p)){I.push(C);continue}const _=v.get(C.id);if(_){x=!0,_.status==="error"&&y.push(cb(_));continue}if(!S.has(C.id)&&E-C.startedAt>P){x=!0;continue}const N=S.get(C.id);if(N){const j=xs(N),$={...C,phase:j.phase,sessionId:j.sessionId,parentNodeId:j.parentNodeId,clientNodeId:j.clientNodeId,kind:j.kind};($.phase!==C.phase||$.sessionId!==C.sessionId||$.parentNodeId!==C.parentNodeId||$.clientNodeId!==C.clientNodeId||$.kind!==C.kind)&&(x=!0),I.push($)}else I.push(C)}const k=new Set(I.map(C=>C.id));for(const C of h)k.has(C.requestId)||(I.push(xs(C)),x=!0);x&&(jt(I),e({inFlight:I,activeGenerations:I.length}));for(const C of y)dr(C,a())}catch{}try{const p=a().history.reduce((y,x)=>x.createdAt&&x.createdAt>y?x.createdAt:y,0),{items:h}=await rr({limit:An,since:p}),g=h.map(Ci);g.length>0&&e(y=>{const x=new Set(y.history.map(Sn)),E=g.filter(I=>{const k=Sn(I);return x.has(k)?!1:(x.add(k),!0)});if(E.length===0)return{};const P=y.currentImage??E[0];return!y.currentImage&&E[0]?.filename&&Ln(E[0].filename),{history:qs([...E,...y.history],Math.max(An,y.history.length+E.length)),currentImage:P,loadedHistoryRetainLimit:Math.max(y.loadedHistoryRetainLimit,y.history.length+E.length)}});const S=Date.now(),v=a().inFlight.filter(y=>m.has(y.id)||S-y.startedAt<rb);v.length!==a().inFlight.length&&(jt(v),e({inFlight:v,activeGenerations:v.length}))}catch{}};i.__ima2InflightTimer=window.setInterval(o,1500)}async function yN(e,a){try{const i=ib(a()),{jobs:o,terminalJobs:s=[]}=await sb(i),c=new Map(o.map(x=>[x.requestId,x])),m=new Map(s.map(x=>[x.requestId,x])),p=[],h=Date.now(),g=a().inFlight,v=(g.length>0?g:db()).flatMap(x=>{const E=c.get(x.id);if(E){const I=xs(E);return[{...x,...I,prompt:x.prompt||I.prompt,phase:x.phase||I.phase}]}if(!lb(x,i))return[x];const P=m.get(x.id);return P?(P.status==="error"&&p.push(cb(P)),[]):h-x.startedAt<1e4?[x]:[]}),y=new Set(v.map(x=>x.id));for(const x of o)y.has(x.requestId)||v.push(xs(x));jt(v),e({inFlight:v,activeGenerations:v.length});for(const x of p)dr(x,a());v.length>0&&a().startInFlightPolling()}catch{}}const ro=()=>"nc_"+Math.random().toString(36).slice(2,10);function Ny(e,a){return{x:e*360,y:a*320}}const vN=360,$b=320;function bN(e,a,i){const o=new Set(i.filter(s=>s.source===e).map(s=>s.target));return a.filter(s=>o.has(s.id))}function _m(e){const a=e.filter(o=>!o.data.parentServerNodeId);if(a.length===0)return Ny(0,0);const i=Math.max(...a.map(o=>o.position.y));return{x:Ny(0,0).x,y:i+$b}}function Yb(e,a,i){const o=bN(e.id,a,i),s=e.position.x+vN;if(o.length===0)return{x:s,y:e.position.y};const c=Math.max(...o.map(m=>m.position.y));return{x:s,y:c+$b}}const vi="source-right",bi="target-left";function $s(e,a,i,o){return`${e}:${i??"auto"}->${a}:${o??"auto"}`}function SN(e,a){return e&&e.startsWith(`${a}-`)?e:null}function xN(e){switch(e){case"source-top":return"target-bottom";case"source-right":return"target-left";case"source-bottom":return"target-top";case"source-left":return"target-right";default:return null}}function AN(e,a){const i=ro();a().recordGraphHistory("add-root");const o={id:i,type:"imageNode",position:_m(a().graphNodes),data:{clientId:i,serverNodeId:null,parentServerNodeId:null,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return e({graphNodes:[...a().graphNodes,o]}),a().scheduleGraphSave(),i}function TN(e,a,i){const o=ro();i().recordGraphHistory("add-root-from-history");const s={id:o,type:"imageNode",position:_m(i().graphNodes),data:{clientId:o,serverNodeId:e.nodeId??null,parentServerNodeId:null,prompt:e.prompt??"",imageUrl:e.image,status:"ready",pendingRequestId:null,pendingPhase:null,model:e.model??null,size:e.size??null,elapsed:e.elapsed??void 0,video:e.video??null}};return a({uiMode:"node",graphNodes:[...i().graphNodes,s]}),i().scheduleGraphSave(),o}function CN(e,a,i){const o=i().graphNodes.find(p=>p.id===e);if(!o)return e;i().recordGraphHistory("add-child");const s=ro(),c={id:s,type:"imageNode",position:Yb(o,i().graphNodes,i().graphEdges),data:{clientId:s,serverNodeId:null,parentServerNodeId:o.data.serverNodeId,prompt:kn(o.data.imageUrl)&&o.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},m={id:$s(e,s,vi,bi),source:e,target:s,sourceHandle:vi,targetHandle:bi};if(a({graphNodes:[...i().graphNodes,c],graphEdges:[...i().graphEdges,m]}),i().scheduleGraphSave(),o.data.imageUrl&&kn(o.data.imageUrl)){const p=o.data.imageUrl;o.data.video&&o.data.video.topic&&i().setVideoTopic(o.data.video.topic),(async()=>{try{const h=await cr(p);a({graphNodes:i().graphNodes.map(g=>g.id===s?{...g,data:{...g.data,referenceImages:[h]}}:g)}),i().scheduleGraphSave()}catch{}})()}return s}function wN(e,a,i){const o=i().graphNodes.find(S=>S.id===e);if(!o)return e;i().recordGraphHistory("add-sibling");const s=i().graphEdges.find(S=>S.target===e);if(!s){const S=ro(),v={id:S,type:"imageNode",position:_m(i().graphNodes),data:{clientId:S,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return a({graphNodes:[...i().graphNodes,v]}),i().scheduleGraphSave(),S}const c=s.source,m=i().graphNodes.find(S=>S.id===c);if(!m)return e;const p=ro(),h={id:p,type:"imageNode",position:Yb(m,i().graphNodes,i().graphEdges),data:{clientId:p,serverNodeId:null,parentServerNodeId:o.data.parentServerNodeId,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},g={id:$s(c,p,vi,bi),source:c,target:p,sourceHandle:vi,targetHandle:bi};return a({graphNodes:[...i().graphNodes,h],graphEdges:[...i().graphEdges,g]}),i().scheduleGraphSave(),p}function IN(e,a,i,o,s){const c=s().graphNodes.find(v=>v.id===e);if(!c)return e;s().recordGraphHistory("add-child-at");const m=ro(),p=SN(i,"source")??vi,h=xN(p)??bi,g={id:m,type:"imageNode",position:a,data:{clientId:m,serverNodeId:null,parentServerNodeId:c.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},S={id:$s(e,m,p,h),source:e,target:m,sourceHandle:p,targetHandle:h};return o({graphNodes:[...s().graphNodes,g],graphEdges:[...s().graphEdges,S]}),s().scheduleGraphSave(),m}function EN(e,a,i){const o=i().graphNodes.find(m=>m.id===e);if(!o)return e;i().recordGraphHistory("duplicate-branch");const s=ro(),c={id:s,type:"imageNode",position:{x:o.position.x+420,y:o.position.y+40},data:{clientId:s,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};if(a({graphNodes:[...i().graphNodes,c]}),i().scheduleGraphSave(),o.data.imageUrl){const m=o.data.imageUrl;(async()=>{try{const p=await wi(m,"node-reference.png");a({graphNodes:i().graphNodes.map(h=>h.id===s?{...h,data:{...h.data,referenceImages:[p]}}:h)})}catch{}})()}return s}function RN(e,a,i,o){i({graphNodes:o().graphNodes.map(s=>s.id===e?{...s,data:{...s.data,prompt:a}}:s)}),o().scheduleGraphSave()}function NN(e,a,i){const o=i().graphNodes.find(p=>p.id===e);if(!o)return;i().recordGraphHistory("delete-node");const s=o?.data?.pendingRequestId;s&&Mt(s),wm(i().activeSessionId,e);const c=i().graphNodes.filter(p=>p.id!==e),m=i().graphEdges.filter(p=>p.source!==e&&p.target!==e);a({graphNodes:Mn(c,m),graphEdges:m}),i().scheduleGraphSave()}function kN(e,a,i){const o=new Set(e);if(o.size===0)return;i().recordGraphHistory("delete-nodes");for(const m of o)wm(i().activeSessionId,m);for(const m of i().graphNodes)o.has(m.id)&&m.data?.pendingRequestId&&Mt(m.data.pendingRequestId);const s=i().graphNodes.filter(m=>!o.has(m.id)),c=i().graphEdges.filter(m=>!o.has(m.source)&&!o.has(m.target));a({graphNodes:Mn(s,c),graphEdges:c}),i().scheduleGraphSave()}function _N(e,a,i){const o=new Set(e);if(o.size===0)return;const s=i().graphEdges.filter(h=>o.has(h.id));if(s.length===0)return;i().recordGraphHistory("disconnect-edges");const c=i().graphEdges.filter(h=>!o.has(h.id)),m=new Set(s.map(h=>h.target)),p=i().graphNodes.map(h=>{if(!m.has(h.id))return h;const g=c.find(v=>v.target===h.id),S=g?i().graphNodes.find(v=>v.id===g.source):null;return{...h,data:{...h.data,parentServerNodeId:S?.data.serverNodeId??null}}});a({graphNodes:Mn(p,c),graphEdges:c}),i().scheduleGraphSave(),i().flushGraphSave("edge-disconnect"),i().showToast(Z("edge.disconnected"))}function MN(e,a,i,o,s,c){if(e===a||c().graphEdges.find(g=>g.source===e&&g.target===a))return;if(YR(c().graphEdges,e,a)){c().showToast(Z("edge.parentConflict"),!0);return}if(XR(c().graphEdges,e,a)){c().showToast(Z("edge.cycleBlocked"),!0);return}if(!c().graphNodes.find(g=>g.id===e))return;c().recordGraphHistory("connect-nodes");const h=[...c().graphEdges,{id:$s(e,a,i,o),source:e,target:a,sourceHandle:i,targetHandle:o}];s({graphNodes:Mn(c().graphNodes,h),graphEdges:h}),c().scheduleGraphSave()}async function PN(e,a,i,o){const s=o().graphNodes.find(x=>x.id===e);if(!s)return;const c=s.data.referenceImages??[],p=o().referenceLimit-c.length;if(p<=0){o().showToast(Z("toast.refLimitExceeded"),!0);return}const h=a.slice(0,Math.max(0,p)),g=h.filter(Ss),S=h.filter(x=>!Ss(x)),y=(await Promise.all(S.map(async x=>{try{return await Sm(x,{preserveTransparency:ob(x)})}catch(E){return console.warn("[addNodeReferences] compress failed",E),null}}))).filter(x=>!!x);if(y.length>0){const x=o().activeSessionId;i({graphNodes:o().graphNodes.map(E=>{if(E.id!==e)return E;const P=[...E.data.referenceImages??[],...y].slice(0,o().referenceLimit);return Hs(x,e,P),{...E,data:{...E.data,referenceImages:P}}})}),o().scheduleGraphSave()}g.length>0&&o().showToast(Z("toast.refHeicUnsupported"),!0),S.length-y.length>0&&o().showToast(Z("toast.refTooLarge"),!0),a.length>p&&o().showToast(Z("toast.refLimitExceeded"),!0)}function Xb(e,a,i,o){o().graphNodes.find(c=>c.id===e)&&(i({graphNodes:o().graphNodes.map(c=>{if(c.id!==e)return c;const m=c.data.referenceImages??[];if(m.length>=o().referenceLimit)return c;const p=[...m,a];return Hs(o().activeSessionId,e,p),{...c,data:{...c.data,referenceImages:p}}})}),o().scheduleGraphSave())}async function LN(e,a,i,o,s){const c=s().graphNodes.find(p=>p.id===e);if(!c)return;if((c.data.referenceImages??[]).length>=s().referenceLimit){s().showToast(Z("toast.refLimitExceeded"),!0);return}let m;try{m=kn(a)||kn(i)?await cr(a):await wi(a,i||"node-reference.png")}catch{s().showToast(Z("toast.currentImageLoadFailed"),!0);return}Xb(e,m,o,s)}function ON(e,a,i,o){i({graphNodes:o().graphNodes.map(s=>{if(s.id!==e)return s;const c=(s.data.referenceImages??[]).filter((m,p)=>p!==a);return Hs(o().activeSessionId,e,c),{...s,data:{...s.data,referenceImages:c}}})}),o().scheduleGraphSave()}function jN(e,a,i){wm(i().activeSessionId,e),a({graphNodes:i().graphNodes.map(o=>o.id===e?{...o,data:{...o.data,referenceImages:void 0}}:o)}),i().scheduleGraphSave()}const ky=10;function Qb(e,a){return a?a.filename&&e.filename===a.filename?!0:e.image===a.image:!1}function GN(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(a=>!!a)}function so(e){return e.filter(a=>!a.canvasVersion)}function Pn(e,a){if(!a)return null;const i=so(e);if(!a.canvasVersion)return i.find(c=>Qb(c,a))??null;const o=GN(a);return i.find(c=>c.filename?o.includes(c.filename):!1)??null}function DN(e,a){const i=so(e),o=Pn(e,a);return i.findIndex(s=>Qb(s,o))}function FN(e,a,i){const o=so(e);if(o.length===0)return null;if(i==="first")return o[0]??null;if(i==="last")return o[o.length-1]??null;const s=DN(e,a);if(s<0)return null;if(i==="pagePrevious"||i==="pageNext"){const m=i==="pagePrevious"?-ky:ky,p=Math.max(0,Math.min(o.length-1,s+m));return o[p]??null}const c=i==="previous"?s-1:s+1;return o[c]??null}function Jb(e,a){const i=so(e),o=i.findIndex(s=>s.filename===a);return o<0?null:i[o+1]??i[o-1]??null}function Ot(e){return e.filename||e.image}function mi(e){return!e.canvasVersion}function hs(e){const a=new Set;return e.filter(i=>{const o=Ot(i);return a.has(o)?!1:(a.add(o),!0)})}const Wb=72,_y=10;function Zb(e,a){const i=e.sequenceIndex??Number.MAX_SAFE_INTEGER,o=a.sequenceIndex??Number.MAX_SAFE_INTEGER;return i!==o?i-o:(e.createdAt??0)-(a.createdAt??0)}function zN(e){return e<=1?1:e===2?2:4}function eS(e){const a=new Set,i=new Map,o=[];for(const s of e){if(!mi(s))continue;if(s.sequenceId){const m=`sequence:${s.sequenceId}`;let p=i.get(s.sequenceId);p||(p={type:"sequence",key:m,sequenceId:s.sequenceId,items:[]},i.set(s.sequenceId,p),o.push(p)),p.items.push(s);continue}const c=Ot(s);a.has(c)||(a.add(c),o.push({type:"image",key:c,item:s}))}for(const s of i.values())s.items.sort(Zb);return o}function tS(e,a){return a?`sequence:${a}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Ot(e):null}function Au(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function qN(e,a,i,o,s=Wb){const c=eS(e).slice(0,s);if(c.length===0)return null;const m=c[0],p=c[c.length-1];if(!m||!p)return null;if(i==="first")return Au(m);if(i==="last")return Au(p);const h=tS(a,o),g=h?c.findIndex(x=>x.key===h):-1;if(g<0)return null;const S=i==="pagePrevious"?-_y:i==="pageNext"?_y:i==="previous"?-1:1,v=Math.max(0,Math.min(c.length-1,g+S));if(v===g)return null;const y=c[v];return y?Au(y):null}const nS={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},UN={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},HN={default:nS,"prompt-studio":UN};function Ei(e,a){return HN[e]??nS}function BN(e,a){return Ei(e).promptBuilderSurface!=="off"}const VN="history:";function aS(e,a,i){if(!a||i||!a.startsWith(VN)||!(a in e))return e;const o={...e};return delete o[a],o}function KN(e){const a=e.multimodePreviewFlightId;return a?a.startsWith("history:")?a.slice(8):e.multimodeSequences[a]?.sequenceId??null:null}async function $N(e,a){const i=a().historyNextCursor;if(!(!i||a().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const o=await rr({limit:An,cursor:i}),s=o.items.map(Ci);e(c=>{const m=new Set(c.history.map(h=>h.filename??h.image)),p=s.filter(h=>{const g=h.filename??h.image;return m.has(g)?!1:(m.add(g),!0)});return{history:[...c.history,...p],historyNextCursor:o.nextCursor,historyLoadingOlder:!1,loadedHistoryRetainLimit:Math.max(c.loadedHistoryRetainLimit,c.history.length+p.length)}})}catch{e({historyLoadingOlder:!1}),a().showToast(Z("gallery.loadOlderFailed"),!0)}}}async function YN(e,a){try{const i=await rr({limit:An,favoritesOnly:!0}),o=i.items.map(Ci);e(s=>{const c=fb(s.history,o);return{history:c,favoriteHistoryNextCursor:i.nextCursor,loadedHistoryRetainLimit:Math.max(s.loadedHistoryRetainLimit,c.length),galleryFavorites:new Set([...Array.from(s.galleryFavorites),...o.filter(m=>m.filename).map(m=>m.filename)])}})}catch{a().showToast(Z("gallery.loadOlderFailed"),!0)}}async function XN(e,a){const i=a().favoriteHistoryNextCursor;if(!(!i||a().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const o=await rr({limit:An,cursor:i,favoritesOnly:!0}),s=o.items.map(Ci);e(c=>{const m=fb(c.history,s);return{history:m,favoriteHistoryNextCursor:o.nextCursor,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:Math.max(c.loadedHistoryRetainLimit,m.length),galleryFavorites:new Set([...Array.from(c.galleryFavorites),...s.filter(p=>p.filename).map(p=>p.filename)])}})}catch{e({favoriteHistoryLoadingOlder:!1}),a().showToast(Z("gallery.loadOlderFailed"),!0)}}}function QN(e,a,i){const o=Date.now(),s=i().history,c=e.canvasVersion?Pn(s,e)??so(s)[0]??null:Pn(s,e)??e;Ln(c?.filename??null);const m=Ei(i().workspaceProfile).restoreComposerFromHistory,p=i().prompt,h=i().insertedPrompts,g=p.trim()!==""||h.length>0,S=m&&c&&!g?wR(c):{},v=i().multimodePreviewFlightId,y=v?i().multimodeSequences[v]:null,x=y&&c&&y.images.some(E=>E.filename===c.filename);a(E=>({currentImage:c,lastHistorySelectedAt:o,unseenGeneratedCount:0,multimodePreviewFlightId:x?v:null,multimodeSequences:aS(E.multimodeSequences,v,!!x),...S}))}function JN(e,a,i){const o=Date.now(),s=i().history.filter(g=>g.sequenceId===e&&!g.canvasVersion).sort(Zb);if(s.length===0)return;const c=`history:${e}`,m=Math.max(s.length,...s.map(g=>g.sequenceTotalRequested??0)),p=s.length,h=s[0]?.sequenceStatus==="empty"?"empty":p>=m?"complete":"partial";Ln(null),a(g=>({currentImage:null,lastHistorySelectedAt:o,unseenGeneratedCount:0,canvasOpen:!1,multimodePreviewFlightId:c,multimodeSequences:{...aS(g.multimodeSequences,g.multimodePreviewFlightId,!1),[c]:{sequenceId:e,requestId:c,requested:m,returned:p,images:s,partials:[],status:h}}}))}function WN(e,a,i){const o=i(),s=Ei(o.workspaceProfile);if(o.uiMode==="classic"&&s.multimodeHistoryGrouping==="sequence"){const m=qN(o.history,o.currentImage,e,KN(o));if(!m)return;if(m.type==="sequence"){i().showHistorySequence(m.sequenceId);return}i().selectHistory(m.item);return}const c=FN(o.history,o.currentImage,e);c&&i().selectHistory(c)}async function ZN(e,a,i){const o=e.canvasVersion?Pn(i().history,e):e;if(!o||o.canvasVersion||!o.filename){i().showToast(Z("gallery.deleteFailed"),!0);return}const s=o.filename,c=i().currentImage,p=(c?Pn(i().history,c)??c:null)?.filename===s,h=p?Jb(i().history,s):c;try{await vv(s),a(g=>{const S=UR(g.multimodeSequences,s),v=g.multimodePreviewFlightId&&!S[g.multimodePreviewFlightId]?null:g.multimodePreviewFlightId;return{history:g.history.filter(y=>y.filename!==s),currentImage:h,multimodePreviewFlightId:v,multimodeSequences:S,trashPending:null}}),p&&Ln(h?.filename??null),i().showToast(Z("gallery.movedToSystemTrash",{filename:s}))}catch(g){console.error("[history] trash failed",g),i().showToast(Z("gallery.deleteFailed"),!0)}}async function ek(e,a,i){const o=i().history.filter(g=>g.sequenceId===e&&!g.canvasVersion&&!!g.filename);if(o.length===0){i().showToast(Z("gallery.deleteFailed"),!0);return}if(!window.confirm(Z("history.deleteSequenceConfirm",{count:o.length})))return;const c=new Set(o.map(g=>g.filename).filter(g=>!!g)),m=i().currentImage,p=!!(m?.filename&&c.has(m.filename)),h=i().multimodePreviewFlightId===`history:${e}`||i().multimodePreviewFlightId===e;try{for(const g of c)await vv(g);a(g=>{const S={...g.multimodeSequences};return delete S[`history:${e}`],delete S[e],{history:g.history.filter(v=>!v.filename||!c.has(v.filename)),currentImage:p?null:g.currentImage,multimodePreviewFlightId:h?null:g.multimodePreviewFlightId,multimodeSequences:S,trashPending:null}}),p&&Ln(null),i().showToast(Z("history.sequenceDeleted",{count:c.size}))}catch(g){console.error("[history] sequence trash failed",g),i().showToast(Z("gallery.deleteFailed"),!0)}}async function tk(e,a){const i=a().trashPending;if(i)try{await GT(i.filename,i.trashId),a().addHistoryItem(i.item),e({trashPending:null})}catch(o){console.error("[history] restore failed",o),a().showToast(Z("gallery.restoreFailed"),!0)}}async function nk(e,a,i){const o=e.canvasVersion?Pn(i().history,e):e;if(!o||o.canvasVersion||!o.filename){i().showToast(Z("gallery.deleteFailed"),!0);return}const s=o.filename;if(!window.confirm(Z("result.permanentDeleteConfirm",{filename:s})))return;const m=i().currentImage,h=(m?Pn(i().history,m)??m:null)?.filename===s,g=h?Jb(i().history,s):m;try{await jT(s),a(S=>({history:S.history.filter(v=>v.filename!==s),currentImage:g,trashPending:S.trashPending?.filename===s?null:S.trashPending})),h&&Ln(g?.filename??null),i().showToast(Z("gallery.permanentDeleted",{filename:s}))}catch(S){console.error("[history] permanent delete failed",S),i().showToast(Z("gallery.deleteFailed"),!0)}}function ak(e,a,i){const o=i(),s=o.history.filter(m=>m.filename!==e),c=o.currentImage&&o.currentImage.filename===e?null:o.currentImage;a({history:s,currentImage:c}),c===null&&Ln(null)}function ok(e,a,i){const o=i(),s={...e,createdAt:e.createdAt||Date.now()},c=mb(o.history,s),m=pb(s,c),p=ub(o.history,m);a({history:qs([m,...p],o.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(o.loadedHistoryRetainLimit,Math.min(o.history.length+1,o.loadedHistoryRetainLimit+1))})}async function rk(e,a,i){if(!e.type||!/^image\/(png|jpeg|webp)$/.test(e.type))return i().showToast(Z("toast.localImportInvalid"),!0),null;try{const o=await _T(e);return i().addHistoryItem(o),a({currentImage:o,unseenGeneratedCount:0}),o.filename&&Ln(o.filename),i().showToast(Z("toast.localImportSuccess")),o}catch{return i().showToast(Z("toast.localImportFailed"),!0),null}}function ik(e,a){(async()=>{try{const i=await rr({limit:An}),o=i.items.map(Ci);if(e({historyNextCursor:i.nextCursor,loadedHistoryRetainLimit:An}),o.length>0){const s=Zv(),c=s?o.find(h=>h.filename===s):null,m=so(o),p=(c?Pn(o,c):null)??m[0]??null;e({history:o,currentImage:p,historyNextCursor:i.nextCursor,loadedHistoryRetainLimit:Math.max(An,o.length)}),p?.filename!==s&&Ln(p?.filename??null)}}catch(i){console.warn("[history] load failed:",i)}})()}async function oS(e,a){try{const{sessions:i}=await FT();if(e({sessions:i}),!a().activeSessionId){const s=PR(),c=s?i.some(m=>m.id===s):!1;s&&c?await a().switchSession(s):await a().createAndSwitchSession(Z("session.firstGraph"))}}catch(i){console.warn("[sessions] load failed:",i),a().showToast(Z("modal.sessionInitialLoadFailed"),!0),window.confirm(Z("modal.sessionInitialLoadRetry"))&&await oS(e,a)}}async function lk(e,a,i){if(e!==i().activeSessionId){try{await i().flushGraphSave("switch-session")}catch(o){console.warn("[sessions] switch blocked by save failure:",o),a({sessionLoading:!1}),i().showToast(Z("modal.sessionSwitchSaveFailed"),!0);return}a({sessionLoading:!0});try{const{session:o}=await bv(e),{graphNodes:s,graphEdges:c,graphVersion:m}=bb(o);a({activeSessionId:e,activeSessionGraphVersion:m,graphNodes:s,graphEdges:c,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),bm(e),await i().reconcileGraphPending().catch(()=>{})}catch(o){console.warn("[sessions] switch failed:",o),a({sessionLoading:!1}),i().showToast(Z("toast.sessionLoadFailed"),!0)}}}async function sk(e,a){const i=a().activeSessionId;if(!i)return;if(a().graphNodes.filter(s=>s.data?.pendingRequestId&&(s.data.status==="pending"||s.data.status==="reconciling")).length>0){let s=[];try{s=(await gv({kind:"node",sessionId:i})).jobs}catch{s=[]}const c=new Map(s.map(g=>[g.requestId,g.phase])),m=Date.now(),p=1e4,h=a().graphNodes.map(g=>{const S=g.data?.pendingRequestId;if(!S||g.data.status!=="pending"&&g.data.status!=="reconciling")return g;if(c.has(S)){const x=c.get(S)??null;return{...g,data:{...g.data,status:"reconciling",pendingPhase:x}}}const v=g.data.pendingStartedAt??0;if(v&&m-v<p)return{...g,data:{...g.data,status:"reconciling"}};const y=!!g.data.imageUrl||!!g.data.serverNodeId;return{...g,data:{...g.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:y?"ready":"stale",error:y?void 0:Z("session.assetAbortedError")}}});e({graphNodes:h})}await Cb(a,e).catch(()=>{})}async function ck(e,a,i){e==null&&(e=Z("session.untitled"));try{const{session:o}=await zT(e);a({sessions:[o,...i().sessions],activeSessionId:o.id,activeSessionGraphVersion:o.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),bm(o.id)}catch(o){console.warn("[sessions] create failed:",o),i().showToast(Z("toast.sessionCreateFailed"),!0)}}async function dk(e,a,i){const o=i().activeSessionId;if(o)try{await qT(o,e),a({sessions:i().sessions.map(s=>s.id===o?{...s,title:e,updatedAt:Date.now()}:s)})}catch{i().showToast(Z("toast.sessionRenameFailed"),!0)}}async function uk(e,a,i){try{await UT(e);const o=i().sessions.filter(s=>s.id!==e);a({sessions:o}),i().activeSessionId===e&&(a({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),bm(null),o.length>0?await i().switchSession(o[0].id):await i().createAndSwitchSession(Z("session.firstGraph")))}catch{i().showToast(Z("toast.sessionDeleteFailed"),!0)}}function mk(e,a){const i={},o=a.userPrompt||a.prompt;typeof o=="string"&&(i.prompt=o),tb(a.quality)&&(i.quality=a.quality),nb(a.format)&&(i.format=a.format),ab(a.moderation)&&(i.moderation=a.moderation),(a.promptMode==="auto"||a.promptMode==="direct")&&(i.promptMode=a.promptMode),a.model&&Tv(a.model)&&(i.imageModel=a.model);const s=OR(a.size);return s.preset&&(i.sizePreset=s.preset),s.preset==="custom"&&s.w&&s.h&&(i.customW=_n(s.w,e.customW),i.customH=_n(s.h,e.customH)),i}function Ri(e,a){return Nm(e,a)}function Mm(e){const a=/^data:(image\/(?:png|jpeg|webp));/i.exec(e)?.[1]?.toLowerCase();return a==="image/png"||a==="image/jpeg"||a==="image/webp"?a:null}function rS(e,a){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:a,insertedAt:Date.now(),source:e}}function Pm(e,a){return Ri(a,(i,o)=>{const s=[...i.trayItems];let c=i.retiredTags;const m=new Set(s.map(g=>g.tag)),p=[];let h=i.nextAttachmentOrdinal;for(const g of e){if(!Em(s,o))break;const S=Mb(h,m),v=rS(g,S.tag);s.push(v),p.push(v),m.add(v.tag),c=Rm(c,v.tag),h=S.nextAttachmentOrdinal}return p.length===0?{result:p}:{result:p,patch:{trayItems:s,nextAttachmentOrdinal:h,retiredTags:c,providerUrlReference:null}}})}function pk(e,a,i){return Pm(e,a)}function Ys(e,a,i,o){const s=Mm(e);return s?Pm([{dataUrl:e,mimeType:s,origin:a}],i)[0]??null:null}function fk(e,a,i){Ys(e,"gallery",a)}async function gk(e,a,i){const o=i().activeReferenceLimit(),s=Math.max(0,o-i().trayItems.length),c=e.slice(0,s),m=c.filter(Ss),p=c.filter(v=>!Ss(v)),g=(await Promise.all(p.map(async v=>{try{const y=await Sm(v,{preserveTransparency:ob(v)}),x=Mm(y);return x?{dataUrl:y,mimeType:x,originalName:v.name,byteSize:v.size,origin:"file"}:null}catch(y){return console.warn("[addReferences] compress failed",y),null}}))).filter(v=>v!==null),S=Pm(g,a);m.length>0&&i().showToast(Z("toast.refHeicUnsupported"),!0),p.length-g.length>0&&i().showToast(Z("toast.refTooLarge"),!0),(e.length>s||g.length>S.length)&&i().showToast(Z("toast.refLimitExceeded"),!0)}async function hk(e,a,i,o){if(!e.type.startsWith("image/"))return!1;let s="";try{s=await Tm(e);const c=await BT({filename:e.name,dataUrl:s});return c.metadata?(i({metadataRestore:{filename:e.name,image:s,metadata:c.metadata,source:c.source??"xmp",targetNodeId:a}}),!0):!1}catch{return o().showToast(Z("metadata.readFailed"),!0),!1}}function yk(e,a){const i=a().metadataRestore;if(!i)return;const o=mk(a(),i.metadata);if(o.imageModel&&Wa(o.imageModel),i.targetNodeId&&typeof o.prompt=="string"){const s=o.prompt;e({...o,metadataRestore:null,graphNodes:a().graphNodes.map(c=>c.id===i.targetNodeId?{...c,data:{...c.data,prompt:s}}:c)}),a().scheduleGraphSave()}else e({...o,metadataRestore:null});a().showToast(Z("metadata.applied"))}function Lm(e){return e.insertedPrompts.filter(a=>!a.id.startsWith("video-continuity:"))}function Om(e,a){a.length!==e.length&&Ge({insertedPrompts:a})}function iS(e,a,i){const o=i().insertedPrompts;Ri(a,s=>{const c=s.trayItems.find(h=>h.tokenId===e);if(!c)return{result:void 0};const m=s.trayItems.filter(h=>h.tokenId!==e),p={trayItems:m,retiredTags:Bs(s.retiredTags,[c])};if(c.kind==="attachment"){const h=Ii({trayItems:m}).length===0;p.canvasReferenceImage=c.source.dataUrl===s.canvasReferenceImage?null:s.canvasReferenceImage,h&&(p.insertedPrompts=Lm(s),p.videoContinuityLineage=null)}return{result:void 0,patch:p}}),Om(o,i().insertedPrompts)}function vk(e,a,i){const o=Ii(i())[e];o&&iS(o.tokenId,a,i)}function bk(e,a){const i=a().insertedPrompts;Ri(e,o=>{const s=Ii(o);return{result:void 0,patch:{trayItems:o.trayItems.filter(m=>m.kind!=="attachment"),retiredTags:Bs(o.retiredTags,s),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Lm(o),providerUrlReference:null}}}),Om(i,a().insertedPrompts)}function Sk(e,a){const i=a().insertedPrompts;Ri(e,o=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Lm(o),providerUrlReference:null}})),Om(i,a().insertedPrompts)}function xk(e,a,i){const o=Ii(e).filter(g=>g.source.dataUrl===i.dataUrl||g.source.dataUrl===e.canvasReferenceImage),s=new Set(o.map(g=>g.tokenId)),c=e.trayItems.filter(g=>!s.has(g.tokenId));if(!Em(c,a))return{result:!1};const m=Mb(e.nextAttachmentOrdinal,c.map(g=>g.tag)),p=rS(i,m.tag),h=Rm(Bs(e.retiredTags,o),p.tag);return{result:!0,patch:{trayItems:[p,...c],nextAttachmentOrdinal:m.nextAttachmentOrdinal,retiredTags:h,canvasReferenceImage:i.dataUrl,providerUrlReference:null}}}async function Ak(e,a,i,o){let s;try{s=await wi(o??e.image,e.filename||"canvas-version-reference.png")}catch{throw i().showToast(Z("toast.currentImageLoadFailed"),!0),new Error("canvas_reference_attach_failed")}const c=Mm(s);if(!c){i().showToast(Z("toast.currentImageLoadFailed"),!0);return}if(!Ri(a,(p,h)=>xk(p,h,{dataUrl:s,mimeType:c,originalName:e.filename||"canvas-version-reference.png",origin:"canvas"}))){i().showToast(Z("toast.refSlotFull"),!0);return}i().showToast(Z("canvas.version.usingAsReference"))}function lS(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Tk(e,a){const i=a().currentImage;if(!i){a().showToast(Z("toast.noCurrentImageForRef"),!0);return}if(a().trayItems.length>=a().activeReferenceLimit()){a().showToast(Z("toast.refSlotFull"),!0);return}let o;try{o=await wi(lS(i),i.canvasSourceFilename||i.filename||"current-reference.png")}catch{a().showToast(Z("toast.currentImageLoadFailed"),!0);return}if(!Ys(o,"gallery",e)){a().showToast(Z("toast.refSlotFull"),!0);return}a().showToast(Z("toast.addedCurrentAsRef"))}async function Ck(e,a,i){if(i().trayItems.length>=i().activeReferenceLimit()){i().showToast(Z("toast.refSlotFull"),!0);return}let o;try{o=await wi(lS(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{i().showToast(Z("toast.currentImageLoadFailed"),!0);return}if(!Ys(o,"gallery",a)){i().showToast(Z("toast.refSlotFull"),!0);return}i().showToast(Z("toast.addedCurrentAsRef"))}function wk(e,a,i){const o=i.data?.parentServerNodeId;if(o){const c=e.find(m=>m.data?.serverNodeId===o);if(c)return c}const s=a.find(c=>c.target===i.id);return s?e.find(c=>c.id===s.source):void 0}function Ik(e){if(e.providerUrlReference)return 1;if(e.uiMode==="node"){const a=e.graphNodes??[],i=a.find(c=>c.selected),o=i?.data?.referenceImages?.length??0;return o>0?o:i&&wk(a,e.graphEdges??[],i)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const Ek=1e4;let Si=[];async function jm(e){const a=await ue("/api/mcp/providers",{signal:e});return Si=Array.isArray(a.providers)?a.providers:[],Si}function Rk(){return Si}async function Rj(e){const a=window.open("about:blank",`ima2_mcp_${e}`);try{const i=await ue(`/api/mcp/providers/${encodeURIComponent(e)}/connect`,{method:"POST"}),o=i.status.authorizationUrl;if(o){if(!a)throw new Error("MCP_POPUP_BLOCKED");a.location.href=o}else a?.close();return i.status}catch(i){throw a?.close(),i}}async function Nj(e){return(await ue(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function kj(e){return(await ue(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function sS(e,a){const o=(await ue(`/api/mcp/providers/${encodeURIComponent(e)}/models`,{signal:a})).models;return{image:Array.isArray(o?.image)?o.image:[],video:Array.isArray(o?.video)?o.video:[]}}function Nk(e,a){if(typeof e.filename!="string"||typeof e.url!="string"||e.mediaType!=="image"&&e.mediaType!=="video")return null;const i=e.model;return{requestId:a,filename:e.filename,url:e.url,mediaType:e.mediaType,provider:typeof e.provider=="string"?e.provider:void 0,model:typeof i=="string"||i===null?i:void 0,createdAt:typeof e.createdAt=="number"?e.createdAt:void 0}}function kk(e,a){let i=!1;const o=()=>i?!1:(i=!0,s(),c(),!0),s=io(e,null,(m,p)=>{if(m==="done"){const h=Nk(p,e);if(!h||!o())return;Promise.resolve(a.onDone(h)).catch(g=>{a.onError?.(g instanceof Error?g:new Error(String(g)))});return}if(m==="error"&&o()){const h=new Error(typeof p.message=="string"?p.message:"MCP generation failed");typeof p.code=="string"&&(h.code=p.code),a.onError?.(h)}}),c=or(()=>{if(!o())return;const m=new Error("MCP generation timed out");m.code="MCP_STREAM_TIMEOUT",a.onError?.(m)});return o}async function _k(e,a){const i=e.requestId??`mcp_ui_${Date.now()}`,o=kk(i,a);try{const c=(await jm()).find(m=>m.id===e.provider);if(!c||c.status.state!=="connected"){const m=new Error("MCP provider is not connected");throw m.code=c?"MCP_NOT_CONNECTED":"MCP_PROVIDER_UNKNOWN",m}return await ue("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:i})}),i}catch(s){throw o(),s}}function cS(){const[e,a]=R.useState(()=>[...Si]),[i,o]=R.useState(Si.length===0),[s,c]=R.useState(null),m=R.useCallback(async()=>{try{const p=await jm();a([...p]),c(null)}catch(p){c(p instanceof Error?p:new Error(String(p)))}finally{o(!1)}},[]);return R.useEffect(()=>{m();const p=window.setInterval(()=>{m()},Ek);return()=>window.clearInterval(p)},[m]),{providers:e,loading:i,error:s,refresh:m}}let Cs=null;function dS(e){const a=e,i=a.code??a.message??"";return i.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")||a.message?.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")?Z("mcp.errorUnsupportedInput"):i==="MCP_END_FRAME_REQUIRES_START"?Z("mcp.errorEndRequiresStart"):i==="INVALID_MCP_REFERENCES"?Z("mcp.errorInvalidReferences"):i==="INVALID_START_FRAME"?Z("mcp.errorInvalidFrame"):i.startsWith("INVALID_MCP_TEMP_REFERENCE")||i==="MCP_TEMP_REFERENCES_FAILED"?Z("mcp.errorTempReferences"):Z(i==="MCP_NOT_CONNECTED"||i==="MCP_PROVIDER_UNKNOWN"?"mcp.selectionUnavailable":"mcp.generateFailed")}async function Mk(e){const a=e.references.filter(c=>c.dataUrl);if(a.length===0)return{selection:e,batchId:null};const i=await ue("/api/mcp/temp-references",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({images:a.map(c=>({dataUrl:c.dataUrl,...c.tag?{tag:c.tag}:{}}))})});if(i.files.length!==a.length)throw new Error("MCP_TEMP_REFERENCES_FAILED");let o=0;const s=e.references.map(c=>c.dataUrl?{filename:i.files[o++].filename,...c.tag?{tag:c.tag}:{}}:c);return{selection:{...e,references:s},batchId:i.batchId}}async function Pk(e){try{await ue(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(a){console.error("[mcp] temporary reference cleanup failed",a)}}async function Lk(e,a,i){let o=()=>{};const s=new Promise(m=>{o=m});if(await _k(e,{onDone:()=>{a().hydrateHistory(),o()},onError:m=>{a().showToast(dS(m),!0),o()}}),!i){await a().reconcileInflight(),a().startInFlightPolling();return}let c=null;try{await a().reconcileInflight(),a().startInFlightPolling()}catch(m){c=m}if(await s,c)throw c}async function Ok(e){const a=e();if((a.mcpProvider?Rk().find(h=>h.id===a.mcpProvider):void 0)?.executable===!1){e().showToast(Z("mcp.higgsfieldLocked"),!0);return}const o=xi(a.prompt,a.insertedPrompts);if(!o)return;const s=a.mcpReferenceSelection??Tn();if(yR(s)){e().showToast(Z("mcp.referenceTagInvalid"),!0);return}const c=a.selectedElementIds??[];if(a.mcpCharacterElementId&&c.length>0){e().showToast(Z("mcp.characterSlotConflictHint"),!0);return}const m=c.map(h=>a.assets.find(g=>g.id===h)).flatMap(h=>{const g=h?.metadata?.refs;if(!Array.isArray(g))return[];const S=h?.name?Qv(h.name):null;return g.filter(v=>typeof v=="string").map(v=>({filename:v,...S?{tag:S}:{}}))}).slice(0,3);let p=null;try{const h=await Mk(s);p=h.batchId;const g=TR({mcpProvider:a.mcpProvider,mcpModel:a.mcpModel,mcpMediaKind:a.mcpMediaKind,mcpRatio:a.mcpRatio,mcpParameters:a.mcpParameters,mcpInputRoles:a.mcpInputRoles??[],mcpReferenceSelection:h.selection,currentImageFilename:a.currentImage?.filename??null,mcpCharacterElementId:a.mcpCharacterElementId??null,...m.length>0?{elementReferences:m}:{}},o,`mcp_ui_${Date.now()}`);if(!g)return;await Lk(g,e,!!p)}catch(h){e().showToast(dS(h),!0)}finally{p&&await Pk(p)}}function Xs(e){Ti(null,null,"image"),Ge({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Tn(),mcpCharacterElementId:null,...Cs?{generate:Cs}:{}})}function Qs(e,a,i,o=null,s){if(!e){Xs(a);return}Cs||(Cs=i().generate);const c=i().mcpProvider===e?i().mcpModel??o:o,m=s??i().mcpMediaKind??"image",p=i().mcpProvider!==e;Ti(e,c,m),Ge({count:1,multimode:!1,...p?{mcpRatio:null,mcpParameters:{}}:{}}),a({mcpProvider:e,mcpModel:c,mcpMediaKind:m,...p?{mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Tn()}:{},count:1,multimode:!1,generate:()=>Ok(i)})}function jk(e,a,i){Ti(i().mcpProvider??null,e,i().mcpMediaKind??"image"),Ge({mcpRatio:null,mcpParameters:{}}),a({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Tn()})}function Gk(e,a,i,o,s){const c=bR(s);let m=s?hm(s.inputRoles,o().mcpReferenceSelection):Tn();const p=o().currentImage;s?.inputRoles.includes("start_image")&&!m.startFrameFilename&&p?.filename&&!gt(p)&&(m={...m,startFrameFilename:p.filename}),Ti(o().mcpProvider??null,e,a),Ge({mcpRatio:c.ratio,mcpParameters:c.parameters}),i({mcpModel:e,mcpMediaKind:a,mcpRatio:c.ratio,mcpParameters:c.parameters,mcpInputRoles:s?[...s.inputRoles]:[],mcpReferenceSelection:m})}function Dk(e,a,i){(i().mcpMediaKind??"image")!==e&&(Ti(i().mcpProvider??null,null,e),Ge({mcpRatio:null,mcpParameters:{}}),a({mcpMediaKind:e,mcpModel:null,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Tn()}))}function Fk(e,a){Ge({mcpRatio:e}),a({mcpRatio:e})}function zk(e,a,i,o){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))return;const s={...o().mcpParameters??{}};a===null?delete s[e]:s[e]=a,Ge({mcpParameters:s}),i({mcpParameters:s})}function qk(e,a,i){const o=hm(i().mcpInputRoles??[],gm(e)),s=i().mcpReferenceSelection??Tn();Xv(s,o)||a({mcpReferenceSelection:o})}function Uk(e,a,i){const o={ratio:i().mcpRatio??null,parameters:i().mcpParameters??{}},s=$v(e,o.ratio,o.parameters),c=i().mcpReferenceSelection??Tn(),m=hm(e.inputRoles,c),p=JSON.stringify(i().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),h=!SR(o,s),g=!Xv(c,m);!h&&!g&&!p||(h&&Ge({mcpRatio:s.ratio,mcpParameters:s.parameters}),a({...h?{mcpRatio:s.ratio,mcpParameters:s.parameters}:{},mcpInputRoles:[...e.inputRoles],mcpReferenceSelection:m}))}function Hk(e,a){const i=FR();i.provider&&(Qs(i.provider,e,a,i.model,i.kind),Ge({mcpRatio:i.ratio,mcpParameters:i.parameters}),e({mcpRatio:i.ratio,mcpParameters:i.parameters}))}function Bk(e,a,i){Xs(a),Ge({provider:e});const o=i().imageModel;if(!(e==="grok"||e==="grok-api")&&i().videoModelSelected&&(a({videoModelSelected:!1}),Zo({model:!1})),(e==="grok"||e==="grok-api")&&!fi(o)){const c="grok-imagine-image-2.0";Wa(c),a({provider:e,imageModel:c})}else if((e==="agy"||e==="gemini-api")&&!vs(o)){const c=e==="gemini-api"?"nano-banana-pro":"nano-banana-2";Wa(c),a({provider:e,imageModel:c})}else if(e==="atlascloud"&&!Hu(o)){const c="openai/gpt-image-2/text-to-image";Wa(c),a({provider:e,imageModel:c})}else if(e==="minimax"&&!Bu(o)){const c="image-01";Wa(c),a({provider:e,imageModel:c})}else e!=="grok"&&e!=="grok-api"&&e!=="agy"&&e!=="gemini-api"&&e!=="atlascloud"&&e!=="minimax"&&(fi(o)||vs(o)||Hu(o)||Bu(o))?(a({provider:e,imageModel:Uu}),Wa(Uu)):a({provider:e})}function Vk(e,a){Ge({quality:e}),a({quality:e})}function Kk(e,a){Ge({sizePreset:e}),a({sizePreset:e})}function $k(e,a,i,o){const s=_n(e,o().customW),c=_n(a,o().customH);Ge({customW:s,customH:c}),i({customW:s,customH:c})}function Yk(e,a){Ge({grokAspectRatio:e}),a({grokAspectRatio:e})}function Xk(e,a){Ge({grokResolution:e}),a({grokResolution:e})}function Qk(e,a){Ge({format:e}),a({format:e})}function Jk(e,a){Ge({moderation:e}),a({moderation:e})}function Wk(e,a,i){if(Xs(a),Wa(e),a({videoModelSelected:!1}),Zo({model:!1}),fi(e)){Ge({provider:"grok"}),a({provider:"grok",imageModel:e});return}if(vs(e)){const o=i().provider;o!=="agy"&&o!=="gemini-api"?(Ge({provider:"agy"}),a({provider:"agy",imageModel:e})):a({imageModel:e});return}if(Hu(e)){Ge({provider:"atlascloud"}),a({provider:"atlascloud",imageModel:e});return}if(Bu(e)){Ge({provider:"minimax"}),a({provider:"minimax",imageModel:e});return}if(i().provider==="grok"||i().provider==="agy"||i().provider==="gemini-api"||i().provider==="atlascloud"||i().provider==="minimax"){Ge({provider:"oauth"}),a({provider:"oauth",imageModel:e});return}a({imageModel:e})}function Zk(e,a,i){Xs(a);const o=Iv(e)||Ea;a({videoModelSelected:o}),Zo({model:o});const s=i().provider;s!=="grok"&&s!=="grok-api"&&i().setProvider("grok")}function e_(e){return Ik(e())}function t_(e,a){kR(e),a({reasoningEffort:e})}function n_(e,a){MR(e),a({webSearchEnabled:e})}function a_(e,a){const i=hi(e);Ge({count:i}),a({count:i})}function o_(e,a,i){if(e&&i().uiMode!=="classic")return;Ge({multimode:e});const o=i();a({multimode:e,multimodeSequences:e?o.multimodeSequences:{},multimodePreviewFlightId:e?o.multimodePreviewFlightId:null})}function r_(e,a){const i=hi(e);Ge({multimodeMaxImages:i}),a({multimodeMaxImages:i})}function i_(e,a){Ge({promptMode:e}),a({promptMode:e})}function l_(e,a){Ge({prompt:e}),a({prompt:e})}function s_(e){const{provider:a,sizePreset:i,customW:o,customH:s,grokAspectRatio:c,grokResolution:m}=e();return a==="grok"||a==="grok-api"?`grok:${c}:${m}`:i==="custom"?`${o}x${s}`:i}const Tu="starred";async function c_(e,a){const o=(await a.getAssets({kind:null,folderId:null,tag:null,q:"",filePath:e.filename,limit:1})).assets[0];if(o?.tags.includes(Tu))return"noop";if(o)return await a.updateAsset(o.id,{tags:[...new Set([...o.tags,Tu])]}),"tagged";const s=gt({...e,image:e.image??""})?"video":"image";return await a.createAsset({filePath:e.filename,kind:s,name:e.prompt?.trim().slice(0,80)||e.filename,tags:[Tu],metadata:{origin:"star",mediaType:s}}),"created"}function d_(e,a){a(i=>{const o=i.insertedPrompts.some(m=>m.id===e.id),s={...e,placement:e.placement==="after"?"after":"before"},c=o?i.insertedPrompts:[...i.insertedPrompts,s];return Ge({insertedPrompts:c}),{insertedPrompts:c}})}function u_(e,a){a(i=>{const o=i.insertedPrompts.filter(s=>s.id!==e);return Ge({insertedPrompts:o}),{insertedPrompts:o,videoContinuityLineage:e.startsWith("video-continuity:")?null:i.videoContinuityLineage}})}function m_(e,a,i){i(o=>{const s=o.insertedPrompts.filter(y=>y.placement!=="after"),c=o.insertedPrompts.filter(y=>y.placement==="after"),m=[...s.map(y=>({kind:"prompt",prompt:y})),{kind:"main"},...c.map(y=>({kind:"prompt",prompt:y}))],p=m.findIndex(y=>y.kind==="prompt"&&y.prompt.id===e);if(p<0)return{};const h=a==="up"?p-1:p+1;if(h<0||h>=m.length)return{};const[g]=m.splice(p,1);m.splice(h,0,g);const S=m.findIndex(y=>y.kind==="main"),v=m.filter(y=>y.kind==="prompt").map((y,x)=>({...y.prompt,placement:x<S?"before":"after"}));return Ge({insertedPrompts:v}),{insertedPrompts:v}})}function p_(e){Ge({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function f_(e){e({promptLibraryLoading:!0});try{const a=await VT();e({promptLibrary:{prompts:a.prompts,folders:a.folders},promptLibraryLoading:!1})}catch(a){console.error("[PromptLibrary] load failed",a),e({promptLibraryLoading:!1})}}async function g_(e,a,i){try{await KT(e),await i().loadPromptLibrary(),i().showToast(Z("promptLibrary.saved"))}catch(o){console.error("[PromptLibrary] save failed",o),i().showToast(Z("promptLibrary.saveFailed"),!0)}}async function h_(e,a,i){try{await $T(e),await i().loadPromptLibrary()}catch(o){console.error("[PromptLibrary] delete failed",o)}}async function y_(e,a,i){try{await YT(e),await i().loadPromptLibrary()}catch(o){console.error("[PromptLibrary] favorite toggle failed",o)}}async function v_(e,a,i){try{const o=[];for(const c of e){if(!/\.(txt|md|markdown)$/i.test(c.name))continue;const m=await c.text();if(!m.trim())continue;const p=c.name.replace(/\.(txt|md|markdown)$/i,"");o.push({name:p.trim()||Z("promptLibrary.untitled"),text:m.trim(),tags:[]})}if(o.length===0){i().showToast(Z("promptLibrary.importNoValidFiles"),!0);return}const s=await XT({prompts:o});await i().loadPromptLibrary(),i().showToast(Z("promptLibrary.imported",{count:s.promptsImported}))}catch(o){console.error("[PromptLibrary] import failed",o),i().showToast(Z("promptLibrary.importFailed"),!0)}}async function b_(e,a,i){const o=e.filename;if(!o)return null;let s;try{s=(await PT(o)).isFavorite,a(m=>{const p=new Set(m.galleryFavorites);return s?p.add(o):p.delete(o),{galleryFavorites:p}}),a(m=>({history:m.history.map(p=>p.filename===o?{...p,isFavorite:s}:p),currentImage:m.currentImage?.filename===o?{...m.currentImage,isFavorite:s}:m.currentImage}))}catch(c){return console.error("[GalleryFavorite] toggle failed",c),i().showToast(Z("gallery.favoriteFailed"),!0),null}if(!s)return s;try{await c_({...e,filename:o},{getAssets:im,createAsset:Ps,updateAsset:Sv})!=="noop"&&i().showToast(Z("assets.starSaved"))}catch(c){console.error("[GalleryFavorite] asset sync failed",c),i().showToast(Z("assets.starSaveFailed"),!0)}return s}async function S_(e,a,i){if(e){Nb(e),a(o=>{const s=o.inFlight.map(c=>c.id===e?{...c,phase:"canceling"}:c);return jt(s),{inFlight:s}});try{await Mt(e),i().startInFlightPolling()}catch{i().showToast(Z("toast.cancelFailed"),!0)}}}function x_(e,a){const i=db(),o=Zv(),s=Wv(),c=vm();e(m=>{const p=o?m.history.find(v=>v.filename===o)??null:null,h=p?Pn(m.history,p):null,g=so(m.history)[0]??null,S=m.currentImage?.canvasVersion?Pn(m.history,m.currentImage)??g:m.currentImage;return{inFlight:i,activeGenerations:i.length,imageModel:s,videoModelSelected:c.model,videoDuration:c.duration,videoResolution:c.resolution,videoAspectRatio:c.aspectRatio,currentImage:o&&S?.filename!==o?h??S:S}}),i.length>0&&a().startInFlightPolling()}function A_(e,a){a(i=>({history:e.filename?i.history.some(o=>o.filename===e.filename)?i.history.map(o=>o.filename===e.filename?e:o):qs([e,...i.history],i.loadedHistoryRetainLimit+1):i.history,loadedHistoryRetainLimit:Math.max(i.loadedHistoryRetainLimit,Math.min(i.history.length+1,i.loadedHistoryRetainLimit+1))}))}function T_(e,a){const i=a().metadataRestore;i&&(i.targetNodeId?a().addNodeReferenceDataUrl(i.targetNodeId,i.image):a().addReferenceDataUrl(i.image),e({metadataRestore:null}))}function C_(e,a){const i=!a().rightPanelOpen;try{localStorage.setItem(Nv,JSON.stringify(i))}catch{}e({rightPanelOpen:i})}function w_(e,a){try{localStorage.setItem(um,e)}catch{}a({galleryScope:e})}function I_(e,a){try{localStorage.setItem(Dv,e),localStorage.setItem(um,e)}catch{}a({galleryDefaultScope:e,galleryScope:e})}function E_(e,a){const i=e==="card-news"&&!Hv?"classic":e;try{localStorage.setItem(kv,i)}catch{}a({uiMode:i})}function R_(e,a){try{localStorage.setItem(_v,e)}catch{}a({historyStripLayout:e})}function N_(e,a,i){const o=Date.now(),s={message:e,error:a,id:o+Math.random(),createdAt:o};i(c=>({toast:s,toastLog:[...c.toastLog,s].slice(-50)}))}function k_(e,a){a(i=>{const o=i.toastLog.filter(s=>s.id!==e);return{toastLog:o,toast:i.toast?.id===e?o[o.length-1]??null:i.toast}})}function __(e,a,i){const o=Date.now(),s={code:e,cardKey:a?.cardKey,cta:a?.cta,fallbackMessage:a?.fallbackMessage,id:o+Math.random(),createdAt:o};i(c=>({errorCard:s,errorCardLog:[...c.errorCardLog,s]}))}function M_(e,a){a(i=>{if(e==null)return{errorCard:null,errorCardLog:[]};const o=i.errorCardLog.filter(s=>s.id!==e);return{errorCardLog:o,errorCard:i.errorCard?.id===e?o[o.length-1]??null:i.errorCard}})}function P_(e,a,i){a({graphNodes:Mn(e,i().graphEdges)}),i().scheduleGraphSave()}function L_(e,a,i){a({graphEdges:e,graphNodes:Mn(i().graphNodes,e)}),i().scheduleGraphSave()}function O_(e,a){const i=!a().nodeSelectionMode;e({nodeSelectionMode:i,...i?{}:{graphNodes:gi(a().graphNodes,[])}})}function j_(e,a,i,o){i({graphNodes:f0(o().graphNodes,o().graphEdges,e,a)})}function G_(e,a){a().nodeBatchRunning&&(e({nodeBatchStopping:!0}),a().showToast(Z("nodeBatch.stopQueued")))}function D_(e,a,i){i({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,a))})}function F_(e,a,i){a({canvasExportBackground:e}),Jv(e,i().canvasExportMatteColor)}function z_(e,a,i){a({canvasExportMatteColor:e}),Jv(i().canvasExportBackground,e)}const ea=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let Cu=0;async function uS(e){const{folders:a}=await lm();e({assetsFolders:a})}const Gm=uS;async function Dm(e,a,i){const o=e!==!1;if(!o&&i().assetsLoading)return;const s=++Cu;a({assetsLoading:!0,...o?{assetsLoadError:!1}:{}});try{const c=i().assetsFilters,m=await im({...c,cursor:o?null:i().assetsCursor}),p=o?await Promise.all([lm(),sm()]):null;if(s!==Cu)return;a(h=>({assets:o?m.assets:[...h.assets,...m.assets.filter(g=>!h.assets.some(S=>S.id===g.id))],assetsCursor:m.nextCursor,assetsLoading:!1,...p?{assetsFolders:p[0].folders,assetsTags:p[1].tags}:{}}))}catch(c){ea(c),s===Cu&&a({assetsLoading:!1,...o?{assetsLoadError:!0}:{}})}}async function q_(e,a){!a().assetsCursor||a().assetsLoading||await Dm(!1,e,a)}function My(e,a,i){a(o=>({assetsFilters:{...o.assetsFilters,...e}})),Dm(!0,a,i)}async function U_(e,a,i){if(!e.filename)return!1;const o=Object.fromEntries(Object.entries({prompt:e.prompt,provider:e.provider,model:e.model,mediaType:e.mediaType,requestId:e.requestId,sessionId:e.sessionId,createdAt:e.createdAt}).filter(([,s])=>s!==void 0));try{const s=i().selectedProjectId??void 0,{asset:c}=await Ps({filePath:e.filename,kind:gt(e)?"video":"image",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:s,tags:[],metadata:o}),m=i().assetsFilters;return(!m.kind||m.kind===c.kind)&&!m.tag&&!(m.q||"").trim()&&!m.folderId&&a(h=>({assets:[c,...h.assets.filter(g=>g.id!==c.id)]})),!0}catch(s){return ea(s),!1}}async function H_(e,a,i){try{const{asset:o}=await Sv(e,a);let s=null;try{s=(await sm()).tags}catch(c){ea(c)}return i(c=>{const m=c.assetsFilters.tag;return{assets:m&&!o.tags.includes(m)?c.assets.filter(h=>h.id!==e):c.assets.map(h=>h.id===e?o:h),...s?{assetsTags:s}:{}}}),!0}catch(o){return ea(o),!1}}async function B_(e,a){try{return await JT(e),a(i=>({assets:i.assets.filter(o=>o.id!==e)})),!0}catch(i){return ea(i),!1}}async function V_(e,a,i){try{return await WT({name:e,parentId:a}),await Gm(i),!0}catch(o){return ea(o),!1}}async function K_(e,a,i){try{return await xv(e,{name:a}),await Gm(i),!0}catch(o){return ea(o),!1}}async function $_(e,a,i){try{return await xv(e,{parentId:a}),await Gm(i),!0}catch(o){return ea(o),!1}}async function Y_(e,a){try{await ZT(e);const[{folders:i},{tags:o}]=await Promise.all([lm(),sm()]);return a({assetsFolders:i,assetsTags:o}),!0}catch(i){return ea(i),!1}}function X_(e){const a=e.assetGenProvider;if(a==="grok"||a==="grok-api")return"grok-imagine-image-2.0";if(!(fi(e.imageModel)||vs(e.imageModel)))return e.imageModel}async function mS(e,a,i){if(!e.filename)return;const o=i();try{await Ps({filePath:e.filename,kind:"image",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:o.selectedProjectId??void 0,tags:[],metadata:{source:"asset-gen",backgroundPreset:o.assetGenBackground,prompt:e.prompt,provider:e.provider,requestId:e.requestId}}),a(s=>({assetGenSaveFailures:s.assetGenSaveFailures.filter(c=>c!==e.requestId)}))}catch{a(s=>({assetGenSaveFailures:s.assetGenSaveFailures.includes(e.requestId??"")?s.assetGenSaveFailures:[...s.assetGenSaveFailures,e.requestId??""]}))}}async function Q_(e,a,i){const o=i().assetGenItems.find(s=>s.requestId===e);o&&(o.mediaType==="video"?await pS(o,a,i):await mS(o,a,i))}async function J_(e,a,i,o){const s=i(),c=s.assetGenPrompt.trim(),m=await rm({prompt:c,provider:"grok",duration:s.assetGenVideoDuration,resolution:s.assetGenVideoResolution,aspectRatio:s.assetGenVideoAspect,requestId:e,backgroundPreset:s.assetGenBackground},{},{signal:o.signal}),p={image:m.url,url:m.url,filename:m.filename,mediaType:"video",video:m.video??null,prompt:c,provider:"grok",requestId:m.requestId??e,elapsed:m.elapsed,createdAt:Date.now()};await Ra(p,a,i,{autoSelectStartedAt:Date.now()}),a(h=>({assetGenItems:[p,...h.assetGenItems]})),await pS(p,a,i),i().showToast(Z("toast.generatedSingle",{elapsed:String(m.elapsed??"")}))}async function pS(e,a,i){if(!e.filename)return;const o=i();try{await Ps({filePath:e.filename,kind:"video",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:o.selectedProjectId??void 0,tags:[],metadata:{source:"asset-gen",backgroundPreset:o.assetGenBackground,prompt:e.prompt,provider:e.provider,requestId:e.requestId}}),a(s=>({assetGenSaveFailures:s.assetGenSaveFailures.filter(c=>c!==e.requestId)}))}catch{a(s=>({assetGenSaveFailures:s.assetGenSaveFailures.includes(e.requestId??"")?s.assetGenSaveFailures:[...s.assetGenSaveFailures,e.requestId??""]}))}}async function W_(e,a){const i=a(),o=i.assetGenPrompt.trim();if(!o)return;const s=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,c=new AbortController;ur(s,c);const m=Date.now(),p=[...i.inFlight,{id:s,prompt:o,startedAt:m}];jt(p),e({assetGenLastError:null,activeGenerations:i.activeGenerations+1,inFlight:p}),a().startInFlightPolling();try{if(i.assetGenKind==="video"){await J_(s,e,a,c);return}const h={prompt:o,quality:i.quality,size:"1024x1024",format:"png",moderation:i.moderation,provider:i.assetGenProvider,n:1,model:X_(i),requestId:s,mode:i.promptMode,backgroundPreset:i.assetGenBackground},g=await yv(h,{signal:c.signal}),S=Zu(g)?g.images[0]:null,v={image:S?S.image:g.image,filename:S?S.filename:g.filename,reasoningEffort:g.reasoningEffort,prompt:o,elapsed:g.elapsed,provider:g.provider,providerUrl:(S?S.providerUrl:g.providerUrl)??null,usage:g.usage,requestId:g.requestId??s,quality:g.quality,size:g.size,model:g.model??null,createdAt:(S?S.createdAt:g.createdAt)??Date.now()};await Ra(v,e,a,{autoSelectStartedAt:m}),e(y=>({assetGenItems:[v,...y.assetGenItems]})),await mS(v,e,a),a().showToast(Z("toast.generatedSingle",{elapsed:g.elapsed}))}catch(h){if(!sr(h)){dr(h,a());const g=h instanceof Error?h.message:String(h);e({assetGenLastError:g})}}finally{const h=a().inFlight.filter(g=>g.id!==s);jt(h),mr(s),e({activeGenerations:Math.max(0,a().activeGenerations-1),inFlight:h})}}function Z_(e){return[...new Set(e.filter(a=>typeof a=="string"))]}function si(e){Ge({presetIds:e})}const eM=e=>({selectedPresetIds:zs().presetIds??[],addPreset:a=>e(i=>{if(i.selectedPresetIds.includes(a))return i;const o=[...i.selectedPresetIds,a];return si(o),{selectedPresetIds:o}}),removePreset:a=>e(i=>{const o=i.selectedPresetIds.filter(s=>s!==a);return si(o),{selectedPresetIds:o}}),togglePreset:a=>e(i=>{const o=i.selectedPresetIds.includes(a)?i.selectedPresetIds.filter(s=>s!==a):[...i.selectedPresetIds,a];return si(o),{selectedPresetIds:o}}),clearPresets:()=>{si([]),e({selectedPresetIds:[]})},restorePresetIds:a=>{const i=Z_(a);si(i),e({selectedPresetIds:i})}});function tM(){return{name:"",characterId:"",description:"",style:"",baseAssetId:"",cell:{width:256,height:256,safeMarginX:8,safeMarginY:8},chroma:{preset:"green",hex:"#00ff00"},states:[{key:"idle",frames:4,fps:8,loop:!0,action:"idle"}]}}const Ni=(e,a="POST",i)=>({method:a,signal:i,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),nM=e=>ue("/api/sprite-recipes",{signal:e}),aM=(e,a)=>ue(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:a}),oM=(e,a)=>ue("/api/sprite-recipes",Ni(e,"POST",a)),rM=(e,a,i)=>ue(`/api/sprite-recipes/${encodeURIComponent(e)}`,Ni(a,"PATCH",i)),iM=(e,a={},i)=>ue(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Ni({...a,async:!0},"POST",i)),lM=(e,a,i)=>ue(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Ni({assetId:a},"POST",i)),sM=(e,a={},i)=>ue(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Ni({...a,async:!0},"POST",i)),er=new Map,pr=e=>e instanceof Error?e.message:String(e),fS=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function cM(e,a){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:i}=await nM();e({spriteRecipes:i.map(fS)}),a().activeSpriteRecipeId&&await Fm(a().activeSpriteRecipeId,e,a)}catch(i){e({spriteRecipeError:pr(i)})}finally{e({spriteRecipeLoading:!1})}}async function Fm(e,a,i){if(a({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){a({activeSpriteRecipe:null});return}a({spriteRecipeLoading:!0});try{const{recipe:o}=await aM(e);a({activeSpriteRecipe:o,spriteRecipeDraft:o,spriteRecipeDirty:!1})}catch(o){a({spriteRecipeError:pr(o)})}finally{a({spriteRecipeLoading:!1})}}async function dM(e,a){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const i=a(),o=i.activeSpriteRecipeId?await rM(i.activeSpriteRecipeId,i.spriteRecipeDraft):await oM(i.spriteRecipeDraft);return e(s=>({activeSpriteRecipeId:o.recipe.id,activeSpriteRecipe:o.recipe,spriteRecipeDraft:o.recipe,spriteRecipeDirty:!1,spriteRecipes:[fS(o.recipe),...s.spriteRecipes.filter(c=>c.id!==o.recipe.id)]})),o.recipe.id}catch(i){return e({spriteRecipeError:pr(i)}),null}finally{e({spriteRecipeSaving:!1})}}function gS(e,a,i){er.get(e)?.(),er.set(e,io(e,null,(o,s)=>gM({event:o,data:{...s,requestId:e}},a,i)))}async function uM(e,a){const i=a().activeSpriteRecipeId;if(i){e({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const o=crypto.randomUUID();gS(o,e,a),await iM(i,{requestId:o,async:!0})}catch(o){e({spriteRecipeError:pr(o),spriteRecipeGenerating:!1})}}}async function mM(e,a,i){const o=i().activeSpriteRecipeId;if(o){a({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:s}=await lM(o,e);a({activeSpriteRecipe:s,spriteRecipeDraft:s,spriteRecipeDirty:!1})}catch(s){a({spriteRecipeError:pr(s)})}finally{a({spriteRecipeGenerating:!1})}}}async function pM(e,a,i){const o=i().activeSpriteRecipeId;if(o){a({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const s=crypto.randomUUID();gS(s,a,i),await sM(o,{requestId:s,stateKeys:e,async:!0})}catch(s){a({spriteRecipeError:pr(s),spriteRecipeGenerating:!1})}}}async function fM(e,a,i){er.get(e)?.(),er.delete(e),a({spriteRecipeGenerating:!1})}function gM(e,a,i){const o=e.data.stateKey,s=e.data.url??e.data.image??e.data.previewUrl;if(o&&s&&a(c=>({spritePartialPreviews:{...c.spritePartialPreviews,[o]:s}})),e.event==="error"&&a({spriteRecipeError:String(e.data.message??"Generation failed"),spriteRecipeGenerating:!1}),e.event==="done"){const c=String(e.data.requestId??"");er.get(c)?.(),er.delete(c),a({spriteRecipeGenerating:!1});const m=i().activeSpriteRecipeId;m&&Fm(m,a)}}function hM(e,a){a(i=>({spriteRecipeDraft:{...i.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const kt=zs(),hS=Wv(),ui=vm(),Jl=ui.model||fi(hS)?"grok":(kt.provider??"oauth")==="grok"?"oauth":kt.provider??"oauth",w=pv((e,a,i)=>({...eM(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:o=>e({assetGenWorkflow:o}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:tM(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>cM(e,a),selectSpriteRecipe:o=>Fm(o,e),updateSpriteRecipeDraft:o=>hM(o,e),saveSpriteRecipe:()=>dM(e,a),generateSpriteAnchor:()=>uM(e,a),approveSpriteAnchor:o=>mM(o,e,a),generateSpriteRows:o=>pM(o,e,a),cancelSpriteJob:o=>fM(o,e),assetsFolders:[],assetsTags:[],assetsLoading:!1,assetsLoadError:!1,assetsCursor:null,assetsFilters:{kind:null,folderId:null,tag:null,q:""},assetGenPrompt:"",assetGenBackground:"chroma-green",assetGenProvider:Jl==="grok"||Jl==="grok-api"?Jl:"oauth",assetGenKind:"image",assetGenVideoDuration:5,assetGenVideoResolution:"720p",assetGenVideoAspect:"1:1",setAssetGenVideoDuration:o=>e({assetGenVideoDuration:o}),setAssetGenVideoResolution:o=>e({assetGenVideoResolution:o}),setAssetGenVideoAspect:o=>e({assetGenVideoAspect:o}),assetGenItems:[],assetGenSaveFailures:[],assetGenLastError:null,setAssetGenLastError:o=>e({assetGenLastError:o}),keyingTarget:null,setKeyingTarget:o=>e({keyingTarget:o}),spriteCuratorTarget:null,setCuratorTarget:o=>e({spriteCuratorTarget:o}),addAssetGenDerivedItem:o=>e(s=>o.filename&&s.assetGenItems.some(c=>c.filename===o.filename)?{}:{assetGenItems:[o,...s.assetGenItems]}),selectedProjectId:null,setSelectedProject:o=>{e({selectedProjectId:o}),My({folderId:o},e,a)},loadAssetFolders:()=>uS(e),retryAssetGenSave:o=>Q_(o,e,a),setAssetGenPrompt:o=>e({assetGenPrompt:o}),setAssetGenBackground:o=>e({assetGenBackground:o}),setAssetGenProvider:o=>e({assetGenProvider:o}),setAssetGenKind:o=>e({assetGenKind:o}),generateAssetGen:()=>W_(e,a),loadAssets:o=>Dm(o,e,a),loadMoreAssets:()=>q_(e,a),setAssetsFilters:o=>My(o,e,a),saveToAssets:o=>U_(o,e,a),updateAssetItem:(o,s)=>H_(o,s,e),deleteAssetItem:o=>B_(o,e),createAssetFolder:(o,s)=>V_(o,s,e),renameAssetFolder:(o,s)=>K_(o,s,e),moveAssetFolder:(o,s)=>$_(o,s,e),deleteAssetFolder:o=>Y_(o,e),provider:Jl,quality:kt.quality??"medium",sizePreset:kt.sizePreset??"1024x1024",customW:kt.customW??1920,customH:kt.customH??1088,grokAspectRatio:kt.grokAspectRatio??"1:1",grokResolution:kt.grokResolution??"1k",format:kt.format??"png",moderation:kt.moderation??"low",count:kt.count??1,multimode:kt.multimode??!1,multimodeMaxImages:kt.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:kt.promptMode??"auto",prompt:kt.prompt??"",insertedPrompts:kt.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:Tn(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:xm,activeReferenceLimit:()=>Rb({provider:a().provider,serverLimit:a().referenceLimit,videoModelSelected:!!a().videoModelSelected,mcpProvider:a().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>q1(a().trayItems),workspaceProfile:(()=>{try{return localStorage.getItem("ima2.workspaceProfile")==="prompt-studio"?"prompt-studio":"default"}catch{return"default"}})(),promptBuilderOpen:!1,storyboardActive:!1,promptLibraryOpen:!1,promptLibrary:{prompts:[],folders:[]},promptLibraryLoading:!1,galleryFavorites:new Set,browserId:fv(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:vy().mode,canvasExportMatteColor:vy().matteColor,syncCapabilities:()=>BR(e),addTrayAttachments:async o=>pk(o,e),addTrayAttachmentDataUrl:(o,s)=>Ys(o,s,e),addTrayElement:o=>gs(o,e),addElementFromMention:o=>gs(o.id,e,a,o),syncElementCatalog:o=>Gb(o,e),openAssetDetail:o=>e({uiMode:"assets",pendingAssetDetailId:o}),removeTrayItem:o=>iS(o,e,a),clearTray:()=>Sk(e,a),addElementId:o=>{gs(o,e)},removeElementId:o=>B1(o,e),addReferences:o=>gk(o,e,a),addReferenceDataUrl:o=>fk(o,e),metadataRestore:null,readDroppedImageMetadata:(o,s=null)=>hk(o,s,e,a),applyMetadataRestore:()=>yk(e,a),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>T_(e,a),removeReference:o=>vk(o,e,a),setProviderUrlReference:o=>e({providerUrlReference:o}),clearReferences:()=>bk(e,a),attachCanvasVersionReference:(o,s)=>Ak(o,e,a,s),useCurrentAsReference:()=>Tk(e,a),useImageAsReference:o=>Ck(o,e,a),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:o=>S_(o,e,a),startInFlightPolling:()=>{hN(e,a)},reconcileInflight:async()=>{await yN(e,a)},syncFromStorage:()=>x_(e,a),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:o=>A_(o,e),addGeneratedHistoryItem:async o=>{await Ra(o,e,a)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:An,loadOlderHistory:async()=>$N(e,a),loadFavoriteHistory:async()=>YN(e,a),loadOlderFavoriteHistory:async()=>XN(e,a),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:IR(),toggleRightPanel:()=>C_(e,a),composeSheetOpen:!1,composeSheetTab:"prompt",openComposeSheet:(o="prompt")=>e({composeSheetOpen:!0,composeSheetTab:o}),setComposeSheetTab:o=>e({composeSheetTab:o}),closeComposeSheet:()=>e({composeSheetOpen:!1}),galleryOpen:!1,openGallery:()=>e(o=>({galleryOpen:!0,galleryScope:o.galleryDefaultScope})),closeGallery:()=>e({galleryOpen:!1}),galleryScope:yy(um),galleryDefaultScope:yy(Dv),setGalleryScope:o=>w_(o,e),setGalleryDefaultScope:o=>I_(o,e),imageModel:hS,reasoningEffort:NR(),webSearchEnabled:_R(),settingsOpen:!1,activeSettingsSection:"providers",readinessPopupOpen:!1,openSettings:(o="providers")=>e({settingsOpen:!0,activeSettingsSection:o}),closeSettings:()=>e({settingsOpen:!1}),toggleSettings:()=>e(o=>({settingsOpen:!o.settingsOpen,activeSettingsSection:o.settingsOpen?o.activeSettingsSection:"providers"})),setActiveSettingsSection:o=>e({activeSettingsSection:o}),openReadinessPopup:()=>e({readinessPopupOpen:!0}),closeReadinessPopup:()=>e({readinessPopupOpen:!1}),uiMode:ER(),setUIMode:o=>E_(o,e),historyStripLayout:RR(),setHistoryStripLayout:o=>R_(o,e),locale:YE(),setLocale:o=>{XE(o),e({locale:o})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:o=>{const s=a();e({graphHistoryPast:l1(s.graphHistoryPast,xu(s.graphNodes,s.graphEdges,o)),graphHistoryFuture:[]})},undoGraph:()=>{const o=a(),s=s1(o.graphHistoryPast,xu(o.graphNodes,o.graphEdges,"current"),o.graphHistoryFuture);if(!s)return!1;const c=Cy(s.restored,o.graphNodes);return e({graphNodes:Mn(c.nodes,c.edges),graphEdges:c.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),a().scheduleGraphSave(),!0},redoGraph:()=>{const o=a(),s=c1(o.graphHistoryPast,xu(o.graphNodes,o.graphEdges,"current"),o.graphHistoryFuture);if(!s)return!1;const c=Cy(s.restored,o.graphNodes);return e({graphNodes:Mn(c.nodes,c.edges),graphEdges:c.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),a().scheduleGraphSave(),!0},setGraphNodes:o=>P_(o,e,a),setGraphEdges:o=>L_(o,e,a),disconnectEdge:o=>{a().disconnectEdges([o])},disconnectEdges:o=>_N(o,e,a),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>O_(e,a),selectAllGraphNodes:()=>{e({graphNodes:gi(a().graphNodes,a().graphNodes.map(o=>o.id))})},selectNodeGraph:(o,s)=>j_(o,s,e,a),clearNodeSelection:()=>{e({graphNodes:gi(a().graphNodes,[])})},cancelNodeBatch:()=>G_(e,a),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await oS(e,a)},async switchSession(o){await lk(o,e,a)},async reconcileGraphPending(){await sk(e,a)},async createAndSwitchSession(o){await ck(o,e,a)},async renameCurrentSession(o){await dk(o,e,a)},async deleteSessionById(o){await uk(o,e,a)},scheduleGraphSave(){Ib(a,e)},async flushGraphSave(o="manual"){await a1(a,e,o)},addRootNode:()=>AN(e,a),createRootNodeFromHistoryItem:o=>TN(o,e,a),addChildNode:o=>CN(o,e,a),addSiblingNode:o=>wN(o,e,a),updateNodePrompt:(o,s)=>RN(o,s,e,a),addNodeReferences:async(o,s)=>PN(o,s,e,a),addNodeReferenceDataUrl:(o,s)=>Xb(o,s,e,a),addNodeReferenceFromUrl:async(o,s,c)=>LN(o,s,c,e,a),removeNodeReference:(o,s)=>ON(o,s,e,a),clearNodeReferences:o=>jN(o,e,a),duplicateBranchRoot:o=>EN(o,e,a),generateNode:o=>dN(o,e,a),generateNodeInPlace:o=>uN(o,e,a),generateNodeVariation:(o,s)=>mN(o,s,e,a),runGenerateNode:(o,s)=>pN(o,s,e,a),async runGenerateNodeInPlace(o,s={}){return $1(o,s,e,a,jt)},async runNodeBatch(o){await Y1(o,e,a)},deleteNode:o=>NN(o,e,a),deleteNodes:o=>kN(o,e,a),addChildNodeAt:(o,s,c)=>IN(o,s,c,e,a),connectNodes:(o,s,c,m)=>MN(o,s,c,m,e,a),setProvider:o=>Bk(o,e,a),setQuality:o=>Vk(o,e),setSizePreset:o=>Kk(o,e),setCustomSize:(o,s)=>$k(o,s,e,a),setGrokAspectRatio:o=>Yk(o,e),setGrokResolution:o=>Xk(o,e),setFormat:o=>Qk(o,e),setModeration:o=>Jk(o,e),setImageModel:o=>Wk(o,e,a),videoModelSelected:ui.model,videoDuration:ui.duration,videoResolution:ui.resolution,videoAspectRatio:ui.aspectRatio,videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:o=>Zk(o,e,a),setVideoDuration:o=>{e({videoDuration:o}),Zo({duration:o})},setVideoResolution:o=>{e({videoResolution:o}),Zo({resolution:o})},setVideoAspectRatio:o=>{e({videoAspectRatio:o}),Zo({aspectRatio:o})},setVideoTopic:o=>e({videoTopic:o}),setVideoContinuityLineage:o=>e({videoContinuityLineage:o}),activeVideoRefCount:()=>e_(a),runVideoGenerate:async o=>{await fN(o,e,a)},animateImage:async(o,s)=>gN(o,s,e,a),setReasoningEffort:o=>t_(o,e),setWebSearchEnabled:o=>n_(o,e),setCount:o=>a_(o,e),setMultimode:o=>o_(o,e,a),setMultimodeMaxImages:o=>r_(o,e),setPromptMode:o=>i_(o,e),setPrompt:o=>l_(o,e),insertPromptToComposer:o=>d_(o,e),removeInsertedPromptFromComposer:o=>u_(o,e),moveInsertedPromptInComposer:(o,s)=>m_(o,s,e),clearInsertedPrompts:()=>p_(e),selectHistory:o=>QN(o,e,a),showHistorySequence:o=>JN(o,e,a),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:o=>WN(o,e,a),trashHistoryItem:async o=>ZN(o,e,a),trashHistorySequence:async o=>ek(o,e,a),restorePendingTrash:async()=>tk(e,a),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async o=>{await a().permanentlyDeleteHistoryItemByShortcut(o)},permanentlyDeleteHistoryItemByShortcut:async o=>nk(o,e,a),removeFromHistory:o=>ak(o,e,a),addHistoryItem:o=>ok(o,e,a),importLocalImageToHistory:async o=>rk(o,e,a),getResolvedSize:()=>s_(a),generate:()=>lN(e,a),async generateMultimode(o){await Z1(o,e,a)},cancelMultimode:()=>sN(e,a),async runGenerate(o){await eN(o,e,a)},confirmCustomSizeAdjustment:()=>cN(e,a),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){ik(e)},showToast:(o,s=!1)=>N_(o,s,e),dismissToast:o=>k_(o,e),showErrorCard:(o,s)=>__(o,s,e),dismissErrorCard:o=>M_(o,e),setWorkspaceProfile(o){e({workspaceProfile:o});try{localStorage.setItem("ima2.workspaceProfile",o)}catch{}},togglePromptBuilder(){e(o=>({promptBuilderOpen:!o.promptBuilderOpen}))},toggleStoryboard(){e(o=>({storyboardActive:!o.storyboardActive}))},setPromptLibraryOpen(o){e({promptLibraryOpen:o})},togglePromptLibrary(){e(o=>({promptLibraryOpen:!o.promptLibraryOpen}))},loadPromptLibrary:()=>f_(e),savePromptToLibrary:o=>g_(o,e,a),deletePromptFromLibrary:o=>h_(o,e,a),togglePromptFavorite:o=>y_(o,e,a),importPromptsToLibrary:o=>v_(o,e,a),toggleGalleryFavorite:o=>b_(o,e,a),openCanvas:()=>e({canvasOpen:!0,canvasZoom:1,canvasPanX:0,canvasPanY:0}),closeCanvas:()=>e({canvasOpen:!1}),setCanvasZoom:o=>e({canvasZoom:Math.max(.5,Math.min(3,o))}),resetCanvasZoom:()=>e({canvasZoom:1,canvasPanX:0,canvasPanY:0}),setCanvasPan:(o,s)=>D_(o,s,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:o=>F_(o,e,a),setCanvasExportMatteColor:o=>z_(o,e,a)})),yM=/^[\p{L}\p{N}_-]$/u,vM=new Set([" "," ","(","["]);function bM(e,a){const i=Math.max(0,Math.min(a,e.length));let o=i;for(;o>0&&e[o-1]!=="@"&&e[o-1]!==`
28
28
  `;){if(!yM.test(e[o-1]))return null;o-=1}if(o===0||e[o-1]!=="@")return null;const s=o-1,c=e[s-1];return c!==void 0&&!vM.has(c)&&c!==`
29
29
  `?null:{start:s,end:i,query:e.slice(o,i)}}function xn({title:e,help:a,items:i,value:o,onChange:s,className:c}){const m=R.useRef(null),p=h=>{if(h.key!=="ArrowLeft"&&h.key!=="ArrowRight")return;const g=i.filter(x=>!x.disabled);if(g.length===0)return;const S=g.findIndex(x=>x.value===o),v=h.key==="ArrowRight"?1:-1,y=g[(S+v+g.length)%g.length];h.preventDefault(),s(y.value),m.current?.querySelector(`[data-value="${y.value}"]`)?.focus()};return d.jsxs("div",{className:`option-group${c?` ${c}`:""}`,children:[e?d.jsx("div",{className:"section-title",children:e}):null,d.jsx("div",{className:"option-row",role:"group",ref:m,onKeyDown:p,children:i.map(h=>d.jsxs("button",{type:"button","data-value":h.value,className:`option-btn${h.value===o?" active":""}`,style:h.color?{color:h.color}:void 0,disabled:h.disabled,"aria-pressed":h.value===o,onClick:()=>s(h.value),children:[h.label,h.sub?d.jsxs(d.Fragment,{children:[d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:h.sub})]}):null]},h.value))}),a?d.jsx("p",{className:"option-help",children:a}):null]})}var Js=mv();function SM(e,a){if(!e||!a)return!0;const i=e.target;return!(i&&typeof i=="object"&&"nodeType"in i&&a.contains(i))}const xM=(e,a)=>{if(e&&e.length>0){const o=e.filter(s=>s.items.length>0);return{flat:o.flatMap(s=>[...s.items]),rendered:o}}const i=a??[];return{flat:[...i],rendered:[{items:i}]}},Py=(e,a,i)=>{if(a==="first"){const o=e.findIndex(s=>!s.disabled);return o>=0?o:i}for(let o=e.length-1;o>=0;o-=1)if(!e[o]?.disabled)return o;return i};function tr({items:e,groups:a,value:i,onChange:o,ariaLabel:s,className:c,id:m,disabled:p,portal:h=!1,triggerLabel:g,triggerSub:S,placeholder:v,title:y}){const x=R.useId(),E=R.useRef(null),P=R.useRef(null),I=R.useRef(null),[k,C]=R.useState(!1),[_,N]=R.useState({top:0,left:0,width:200,maxHeight:260}),{flat:j,rendered:$}=xM(a,e),L=j.length===0,[J,re]=R.useState(()=>Math.max(0,j.findIndex(T=>T.value===i))),he=R.useRef({buffer:"",at:0}),V=j.find(T=>T.value===i),ee=T=>`${x}-opt-${T}`,oe=T=>T.searchText?T.searchText:typeof T.label=="string"?T.label:T.value,Ne=T=>{const F=Date.now(),W=he.current;W.buffer=F-W.at>1e3?T:W.buffer+T,W.at=F;const U=W.buffer.toLowerCase(),le=W.buffer.length===1?J+1:J;for(let pe=0;pe<j.length;pe+=1){const xe=(le+pe+j.length)%j.length,Oe=j[xe];if(!(!Oe||Oe.disabled)&&oe(Oe).toLowerCase().startsWith(U)){re(xe);return}}};R.useEffect(()=>{if(!k)return;const T=F=>{const W=F.target;W instanceof Node&&(E.current?.contains(W)||I.current?.contains(W)||C(!1))};return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[k]),R.useLayoutEffect(()=>{if(!h||!k)return;const T=P.current?.getBoundingClientRect();if(T){const le=Math.max(0,window.innerWidth-24),pe=Math.min(300,le,Math.max(190,T.width)),xe=Math.max(12,window.innerWidth-pe-12),Oe=Math.min(Math.max(12,T.left),xe),Re=window.innerHeight-T.bottom-12,Ze=T.top-12,ie=Re>=160||Re>=Ze?"down":"up",lt=Math.max(0,ie==="down"?Re:Ze),at=Math.min(420,lt),st=8+j.length*44,bt=I.current?.scrollHeight??st,se=Math.min(bt,at);N({top:ie==="down"?T.bottom+4:Math.max(12,T.top-se-4),left:Oe,width:pe,maxHeight:at})}const F=()=>C(!1),W=U=>{SM(U,I.current)&&C(!1)};return window.addEventListener("resize",F),window.addEventListener("scroll",W,!0),()=>{window.removeEventListener("resize",F),window.removeEventListener("scroll",W,!0)}},[h,k]),R.useEffect(()=>{k&&I.current?.querySelector(`[data-index="${J}"]`)?.scrollIntoView({block:"nearest"})},[k,J]);const ne=()=>{L||(re(Math.max(0,j.findIndex(T=>T.value===i))),C(!0))};R.useEffect(()=>{L&&(C(!1),re(0))},[L]);const H=T=>{let F=J;for(let W=0;W<j.length&&(F=(F+T+j.length)%j.length,!!j[F]?.disabled);W+=1);re(F)},ae=T=>{const F=j[T];!F||F.disabled||(o(F.value),C(!1),P.current?.focus())},ce=T=>{if(!k){["Enter"," ","ArrowDown","ArrowUp"].includes(T.key)&&(T.preventDefault(),ne());return}if(T.key==="Escape")T.preventDefault(),C(!1);else if(T.key==="ArrowDown")T.preventDefault(),H(1);else if(T.key==="ArrowUp")T.preventDefault(),H(-1);else if(T.key==="Home")T.preventDefault(),re(Py(j,"first",J));else if(T.key==="End")T.preventDefault(),re(Py(j,"last",J));else if(T.key==="Enter"||T.key===" "){if(T.key===" "&&Date.now()-he.current.at<=1e3&&he.current.buffer){T.preventDefault(),Ne(" ");return}T.preventDefault(),ae(J)}else T.key==="Tab"?C(!1):T.key.length===1&&!T.metaKey&&!T.ctrlKey&&!T.altKey&&(T.preventDefault(),Ne(T.key))};let be=-1;const Se=k&&!L?d.jsx("ul",{className:`ctl-select__list${h?" ctl-select__list--portal":""}`,role:"listbox",id:x,ref:I,style:h?{position:"fixed",top:_.top,left:_.left,width:_.width,maxHeight:_.maxHeight}:void 0,children:$.map((T,F)=>d.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[T.label?d.jsx("div",{className:"ctl-select__group-label",children:T.label}):null,d.jsx("ul",{role:"group","aria-label":typeof T.label=="string"?T.label:void 0,className:"ctl-select__group-items",children:T.items.map(W=>{be+=1;const U=be;return d.jsxs("li",{role:"option",id:ee(U),"data-index":U,"aria-selected":W.value===i,"aria-disabled":W.disabled||void 0,className:`ctl-select__item${W.value===i?" is-selected":""}${U===J?" is-active":""}${W.disabled?" is-disabled":""}`,onPointerEnter:()=>re(U),onClick:()=>ae(U),children:[d.jsx("span",{className:"ctl-select__item-label",children:W.label}),W.sub?d.jsx("span",{className:"ctl-select__item-sub",children:W.sub}):null]},W.value)})})]},`g-${F}`))}):null;return d.jsxs("div",{className:`ctl-select${c?` ${c}`:""}`,ref:E,children:[d.jsxs("button",{type:"button",id:m,ref:P,className:`ctl-select__trigger${k?" is-open":""}`,role:"combobox","aria-haspopup":"listbox","aria-expanded":k,"aria-controls":k?x:void 0,"aria-activedescendant":k&&j[J]?ee(J):void 0,"aria-label":s,disabled:p||L,title:y,onClick:()=>k?C(!1):ne(),onKeyDown:ce,children:[d.jsx("span",{className:"ctl-select__value",children:g??V?.label??v??""}),S??V?.sub?d.jsx("span",{className:"ctl-select__value-sub",children:S??V?.sub}):null,d.jsx("svg",{className:"ctl-select__caret",width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:d.jsx("path",{d:"M2 3.5 5 6.5 8 3.5",fill:"none",stroke:"currentColor",strokeWidth:"1.4"})})]}),Se?h?Js.createPortal(Se,document.body):Se:null]})}function AM({checked:e,onChange:a,label:i,ariaLabel:o,className:s,disabled:c,id:m}){return d.jsxs("button",{type:"button",id:m,role:"switch","aria-checked":e,"aria-label":o,disabled:c,className:`ctl-toggle${e?" is-on":""}${s?` ${s}`:""}`,onClick:()=>a(!e),children:[d.jsx("span",{className:"ctl-toggle__track","aria-hidden":"true",children:d.jsx("span",{className:"ctl-toggle__thumb"})}),i?d.jsx("span",{className:"ctl-toggle__label",children:i}):null]})}function yS({selected:e,onSelect:a,onRemove:i,removeLabel:o,disabled:s,className:c,children:m,title:p}){return d.jsxs("span",{className:`ctl-chip${e?" is-selected":""}${s?" is-disabled":""}${c?` ${c}`:""}`,children:[d.jsx("button",{type:"button",className:"ctl-chip__body","aria-pressed":a?e:void 0,disabled:s,title:p,onClick:a,children:m}),i?d.jsx("button",{type:"button",className:"ctl-chip__remove","aria-label":o,disabled:s,onClick:i,children:d.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8","aria-hidden":"true",children:d.jsx("path",{d:"M1 1l6 6M7 1L1 7",stroke:"currentColor",strokeWidth:"1.3"})})}):null]})}function zm({className:e,children:a,ariaLabel:i}){return d.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":i,children:a})}function TM(){return d.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:d.jsx("path",{d:"m12 2.75 2.78 5.63 6.22.9-4.5 4.39 1.06 6.2L12 16.94 6.44 19.87l1.06-6.2L3 9.28l6.22-.9L12 2.75Z"})})}function vS({active:e,label:a,variant:i,busy:o=!1,onToggle:s}){const c=h=>{h.stopPropagation()},m=h=>{h.stopPropagation()},p=h=>{(h.key==="Enter"||h.key===" ")&&h.stopPropagation()};return d.jsx("button",{type:"button",className:`favorite-star favorite-star--${i}${e?" is-active":""}`,title:a,"aria-label":a,"aria-pressed":e,"aria-busy":o||void 0,disabled:o,onPointerDown:c,onDoubleClick:m,onKeyDown:p,onClick:h=>{h.stopPropagation(),s()},children:d.jsx(TM,{})})}function CM(){return d.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:d.jsx("path",{d:"M4 20h4l10-10a2.5 2.5 0 0 0-3.5-3.5L4.5 16.5 4 20Z",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinejoin:"round"})})}const Ly=12,wM=240;function IM(e,a){const i=getComputedStyle(e),o=document.createElement("div");["boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","textIndent","textAlign","wordSpacing","tabSize"].forEach(g=>{o.style[g]=i[g]}),o.style.cssText+=";position:fixed;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;top:0;left:-9999px;",o.textContent=e.value.slice(0,a);const c=document.createElement("span");c.textContent=e.value.slice(a)||".",o.append(c),document.body.append(o);const m=o.getBoundingClientRect(),p=c.getBoundingClientRect();o.remove();const h=e.getBoundingClientRect();return new DOMRect(h.left+p.left-m.left-e.scrollLeft,h.top+p.top-m.top-e.scrollTop,1,p.height||parseFloat(i.lineHeight)||16)}function EM(e,a){const i=IM(e,a),o=window.innerHeight-i.bottom,s=o<wM?"top":"bottom",c=s==="bottom"?o:i.top;return{left:Math.max(Ly,Math.min(i.left,window.innerWidth-332)),top:s==="bottom"?i.bottom+6:Math.max(Ly,i.top-Math.min(320,c-8)),placement:s,maxHeight:Math.max(120,Math.min(320,c-12))}}function RM(){return window.matchMedia("(max-width: 640px)").matches}function NM({open:e,textareaRef:a,caret:i,query:o,elements:s,ariaLabel:c,emptyLabel:m,kindLabel:p,onSelect:h,onClose:g,onActiveChange:S}){const v=R.useId(),[y,x]=R.useState(0),[E,P]=R.useState(null),[I,k]=R.useState(!1),C=R.useRef(null),_=R.useMemo(()=>{const L=o.trim().toLocaleLowerCase();return L?s.filter(J=>[J.name,...J.tags??[]].some(re=>re.toLocaleLowerCase().includes(L))):s},[s,o]),N=L=>{x(L),S?.(L)},j=()=>{const L=_[y];L&&h(L)};if(R.useLayoutEffect(()=>{if(!e||!a.current)return;const L=()=>{if(!a.current){g();return}k(RM()),P(EM(a.current,i))},J=()=>requestAnimationFrame(L);return L(),window.addEventListener("resize",J),a.current.addEventListener("scroll",J),()=>{window.removeEventListener("resize",J),a.current?.removeEventListener("scroll",J)}},[e,a,i,g]),R.useEffect(()=>{N(0)},[o,_.length]),R.useEffect(()=>{if(!e)return;const L=a.current;if(!L)return;L.setAttribute("aria-controls",v),L.setAttribute("aria-expanded","true");const J=re=>{if(document.activeElement===L){if(re.key==="Escape"){re.preventDefault(),g();return}re.key==="ArrowDown"||re.key==="ArrowUp"?(re.preventDefault(),N((y+(re.key==="ArrowDown"?1:-1)+_.length)%Math.max(1,_.length))):re.key==="Home"?(re.preventDefault(),N(0)):re.key==="End"?(re.preventDefault(),N(Math.max(0,_.length-1))):re.key==="Enter"?_.length&&(re.preventDefault(),j()):re.key==="Tab"&&_.length&&j()}};return L.addEventListener("keydown",J),()=>{L.removeAttribute("aria-controls"),L.removeAttribute("aria-expanded"),L.removeAttribute("aria-activedescendant"),L.removeEventListener("keydown",J)}},[e,a,v,y,_,g]),R.useEffect(()=>{const L=a.current,J=_[y];L&&J&&L.setAttribute("aria-activedescendant",`${v}-${J.id}`)},[y,_,v,a]),R.useEffect(()=>{C.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[y]),!e||!E||typeof document>"u")return null;const $=d.jsx("section",{className:`element-mention-menu${I?" is-mobile":""}`,style:I?void 0:{left:E.left,top:E.top,maxHeight:E.maxHeight},"aria-label":c,children:d.jsx("ul",{id:v,className:"element-mention-menu__list",role:"listbox",ref:C,children:_.length?_.map((L,J)=>d.jsxs("li",{id:`${v}-${L.id}`,role:"option","aria-selected":J===y,className:`element-mention-menu__option${J===y?" is-active":""}`,onPointerEnter:()=>N(J),onMouseDown:re=>{re.preventDefault(),h(L)},children:[L.thumbnail?d.jsx("img",{src:L.thumbnail,alt:"",className:"element-mention-menu__thumbnail"}):d.jsx("span",{className:"element-mention-menu__thumbnail is-empty","aria-hidden":"true"}),d.jsxs("span",{className:"element-mention-menu__copy",children:[d.jsx("strong",{children:L.name}),d.jsx("small",{children:p(L.kind)})]})]},L.id)):d.jsx("li",{className:"element-mention-menu__empty",role:"presentation",children:m})})});return Js.createPortal($,document.body)}function kM(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function _M(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??kM(e.source.referenceFilenames[0])}function MM({items:e,limit:a,onRemove:i,onAdd:o}){const{t:s}=ge(),c=e.length>a,m=e.length>=a;return d.jsxs("div",{className:"composer__tray-wrap",children:[d.jsxs("div",{className:"composer__tray",role:"list","aria-label":s("prompt.trayAria",{count:e.length,max:a}),children:[e.map((p,h)=>{const g=_M(p);return d.jsxs("div",{className:"composer__tray-slot",role:"listitem","aria-label":`@${p.tag}, ${h+1}/${a}`,children:[d.jsxs("span",{className:"composer__tray-thumbnail",children:[g?d.jsx("img",{src:g,alt:"",loading:"lazy",decoding:"async"}):d.jsx("span",{className:"composer__tray-thumbnail-empty","aria-hidden":"true",children:"@"}),d.jsx("button",{type:"button",className:"composer__tray-remove",onClick:()=>i(p.tokenId),"aria-label":`${s("prompt.refRemoveAria",{n:h+1})}: @${p.tag}`,children:"×"})]}),d.jsxs("span",{className:"composer__tray-tag",title:`@${p.tag}`,children:["@",p.tag]})]},p.tokenId)}),d.jsx("button",{type:"button",className:"composer__tray-slot composer__tray-slot--add",onClick:o,disabled:m,"aria-label":s("prompt.attachTitle"),title:s("prompt.attachTitle"),children:d.jsx("span",{"aria-hidden":"true",children:"+"})})]}),c?d.jsx("p",{className:"composer__ref-warning",role:"alert",children:s("prompt.refOverProviderLimit",{max:a,excess:e.length-a})}):null]})}function PM({kind:e="character"}){const a={character:"M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm-5 6c.4-2.2 2.2-3.5 5-3.5s4.6 1.3 5 3.5",product:"M3 5.5 8 2l5 3.5v6L8 15l-5-3.5v-6ZM3 5.5 8 9l5-3.5M8 9v6",style:"m3 11 5-8 5 8-5 2-5-2Zm5-8v10",scene:"M2 13 6.5 8l3 3 2-2 2.5 4H2ZM2 3h12v12H2z",reference:"M2 3h12v10H2zM2 10l3.5-3.5 3 3L11 7l3 3"};return d.jsx("svg",{className:"element-mention-chip__kind",viewBox:"0 0 16 16","aria-hidden":"true",children:d.jsx("path",{d:a[e]})})}function LM({elementId:e,name:a,kind:i,thumbnail:o,missing:s,ariaLabel:c,unavailableLabel:m,removeLabel:p,onRemove:h,onOpen:g}){return d.jsxs("span",{className:`element-mention-chip${s?" is-missing":""}`,"data-element-id":e,children:[d.jsxs("button",{type:"button",className:"element-mention-chip__body",onClick:()=>g?.(e),"aria-label":c,children:[o?d.jsx("img",{className:"element-mention-chip__thumbnail",src:o,alt:""}):d.jsx("span",{className:"element-mention-chip__thumbnail is-empty","aria-hidden":"true"}),s?d.jsx("span",{className:"element-mention-chip__warning","aria-label":m,children:"!"}):d.jsx(PM,{kind:i}),d.jsx("span",{className:"element-mention-chip__name",children:a})]}),d.jsx("button",{type:"button",className:"element-mention-chip__remove",onClick:()=>h(e),"aria-label":p,children:d.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:d.jsx("path",{d:"m4 4 8 8m0-8-8 8"})})})]})}const OM=new Set(["character","product","style","scene"]);function jM(e){const a=e?.metadata?.elementKind;return typeof a=="string"&&OM.has(a)?a:"character"}function GM(e){if(!e)return;const a=e.metadata?.refs,i=Array.isArray(a)?a.find(o=>typeof o=="string"&&o.length>0):void 0;return i?`/generated/${i.split("/").map(encodeURIComponent).join("/")}`:void 0}function DM(e,a,i){const o=new Map((a??[]).map(c=>[c.id,c])),s=new Set(i);return Pb({trayItems:[...e]}).map(c=>{const m=o.get(c.source.elementId);return{elementId:c.source.elementId,name:m?.name??c.source.nameAtInsertion,kind:jM(m),thumbnail:GM(m)??c.source.thumbnailUrl,missing:s.has(c.source.elementId)||a!==null&&!m}})}function FM(e){const a=DM(e.items,e.assets,e.missingElementIds);return a.length===0?null:d.jsx(zm,{ariaLabel:e.selectedLabel,children:a.map(i=>{const o=e.kindLabel(i.kind);return d.jsx(LM,{...i,ariaLabel:e.mentionLabel(i.name,o,i.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(i.name),onRemove:e.onRemove},i.elementId)})})}const zM=["boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","textIndent","textAlign","wordSpacing","tabSize","whiteSpace","overflowWrap","wordBreak"];function qM({prompt:e,retiredTags:a,textareaRef:i}){const{t:o}=ge(),s=R.useRef(null),c=R.useRef(null),[m,p]=R.useState([]),h=R.useMemo(()=>z1(e).filter(S=>Object.prototype.hasOwnProperty.call(a,S.tag)),[e,a]),g=R.useMemo(()=>[...new Set(h.map(S=>`@${S.tag}`))],[h]);return R.useLayoutEffect(()=>{const S=i.current,v=s.current,y=c.current?.firstChild;if(!S||!v||!(y instanceof Text)){p([]);return}const x=()=>{const P=getComputedStyle(S);zM.forEach(C=>{v.style[C]=P[C]}),v.scrollTop=S.scrollTop,v.scrollLeft=S.scrollLeft;const I=v.getBoundingClientRect(),k=[];for(const C of h){const _=document.createRange();_.setStart(y,C.start),_.setEnd(y,C.end),Array.from(_.getClientRects()).forEach((N,j)=>{k.push({key:`${C.start}-${C.end}-${j}`,left:N.left-I.left+v.scrollLeft,top:N.top-I.top+v.scrollTop,width:N.width,height:N.height})})}p(k)};x(),S.addEventListener("scroll",x,{passive:!0});const E=new ResizeObserver(x);return E.observe(S),()=>{S.removeEventListener("scroll",x),E.disconnect()}},[i,e,h]),d.jsxs(d.Fragment,{children:[d.jsxs("div",{ref:s,className:"composer__prompt-mirror","aria-hidden":"true",children:[d.jsx("span",{ref:c,children:e}),m.map(S=>d.jsx("span",{className:"dead-tag",style:S},S.key))]}),d.jsx("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:g.length>0?o("prompt.deadTagStatus",{tags:g.join(", ")}):""})]})}async function Ws(e){const a=w.getState(),i=gt(e),o=!!e.prompt;if(a.clearReferences(),a.setPrompt(o&&!i?e.prompt:""),i){const s=e.url||e.image,c=await cr(s);a.addReferenceDataUrl(c);const m=Hb(e);a.setVideoContinuityLineage(m),m&&a.insertPromptToComposer(iN(m)),e.videoSeries?.topic&&a.setVideoTopic(e.videoSeries.topic),a.videoModelSelected||a.selectVideoModel("grok-imagine-video-1.5")}else await a.useImageAsReference(e);return{ok:!0,isVideo:i,hasPrompt:o}}async function bS(e){const a=await Ws(e);return e.providerUrl&&w.getState().setProviderUrlReference(e.providerUrl),a}const UM=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:Ws,continueFromItemAsUrl:bS},Symbol.toStringTag,{value:"Module"}));function HM({text:e,mode:a,onClose:i}){const{t:o}=ge(),s=w(E=>E.savePromptToLibrary),[c,m]=R.useState(e.slice(0,30)),[p,h]=R.useState(e),[g,S]=R.useState(""),[v,y]=R.useState(!1),x=async()=>{p.trim()&&(y(!0),await s({name:c.trim()||p.slice(0,30),text:p.trim(),tags:g.split(",").map(E=>E.trim()).filter(Boolean),mode:a||void 0}),y(!1),i())};return d.jsxs("div",{className:"save-prompt-popover",onClick:E=>E.stopPropagation(),children:[d.jsxs("div",{className:"save-prompt-popover__header",children:[d.jsx("span",{children:o("promptLibrary.saveTitle")}),d.jsx("button",{className:"save-prompt-popover__close",onClick:i,"aria-label":o("common.close"),children:"×"})]}),d.jsxs("div",{className:"save-prompt-popover__body",children:[d.jsxs("label",{children:[o("promptLibrary.name"),d.jsx("input",{type:"text",value:c,onChange:E=>m(E.target.value),placeholder:p.slice(0,30)})]}),d.jsxs("label",{children:[o("promptLibrary.content"),d.jsx("textarea",{value:p,onChange:E=>h(E.target.value),placeholder:o("common.enterPrompt"),rows:4,autoFocus:!0})]}),d.jsxs("label",{children:[o("promptLibrary.tags"),d.jsx("input",{type:"text",value:g,onChange:E=>S(E.target.value),placeholder:"cta, product, summer"})]})]}),d.jsx("div",{className:"save-prompt-popover__footer",children:d.jsx("button",{onClick:x,disabled:v||!p.trim(),className:"save-prompt-popover__save",children:o(v?"common.saving":"promptLibrary.save")})})]})}function BM({variant:e="label"}){const{t:a}=ge(),i=w(c=>c.webSearchEnabled),o=w(c=>c.setWebSearchEnabled),s=a(i?"settings.webSearch.on":"settings.webSearch.off");return e==="label"?d.jsx(AM,{checked:i,onChange:o,label:s,className:"web-search-toggle web-search-toggle--label"}):d.jsx("button",{type:"button",className:`${e==="compact"?"composer__tool ":""}web-search-toggle web-search-toggle--${e}${i?" is-active":""}`,onClick:()=>o(!i),"aria-pressed":i,"aria-label":s,title:s,children:e==="compact"?d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("path",{d:"M2 12h20"}),d.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 0 20"}),d.jsx("path",{d:"M12 2a15.3 15.3 0 0 0 0 20"})]}):d.jsx("span",{children:s})})}function VM({canAddMore:e,onAttach:a}){const{t:i}=ge(),o=w(P=>P.prompt),s=w(P=>P.currentImage),c=w(P=>P.videoModelSelected),m=w(P=>P.selectVideoModel),p=w(P=>P.setImageModel),h=w(P=>P.promptMode),g=w(P=>P.setPromptMode),S=w(P=>P.storyboardActive),v=w(P=>P.toggleStoryboard),[y,x]=R.useState(!1),E=h==="direct";return d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"composer__hint-row",children:d.jsx("span",{className:"composer__hint",children:i("prompt.hint")})}),d.jsxs("div",{className:"composer__toolbar",children:[d.jsx("button",{type:"button",className:"composer__tool",onClick:a,disabled:!e,title:i("prompt.attachTitle"),"aria-label":i("prompt.attachTitle"),children:d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),d.jsx("button",{type:"button",className:"composer__tool",onClick:()=>s&&void Ws(s).catch(()=>{}),disabled:!s||!e,title:i("prompt.continueTitle"),children:i("prompt.continue")}),d.jsx("button",{type:"button",className:`composer__tool${c?" composer__tool--on":""}`,onClick:()=>{c?p("gpt-5.6-luna"):m("grok-imagine-video-1.5")},title:i("prompt.videoToggleTitle"),"aria-label":i("prompt.videoToggleTitle"),"aria-pressed":!!c,children:d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("polygon",{points:"23 7 16 12 23 17 23 7"}),d.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2",ry:"2"})]})}),d.jsx("button",{type:"button",className:`composer__tool${E?" composer__tool--on":""}`,onClick:()=>g(E?"auto":"direct"),title:i("prompt.directModeTitle"),"aria-label":i("prompt.directModeTitle"),"aria-pressed":E,children:d.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"})}),d.jsx(BM,{variant:"compact"}),d.jsxs("div",{className:"composer__tool-wrap",children:[d.jsx("button",{type:"button",className:"composer__tool composer__tool--full",onClick:()=>x(P=>!P),disabled:!o.trim(),title:i("promptLibrary.saveTitle"),"aria-label":i("promptLibrary.saveTitle"),children:i("prompt.savePrompt")}),y&&d.jsx(HM,{text:o,mode:h,onClose:()=>x(!1)})]})]}),d.jsx("div",{className:"composer__storyboard-row",children:d.jsx("button",{type:"button",className:`composer__tool composer__tool--storyboard${S?" composer__tool--on":""}`,onClick:v,title:i("prompt.storyboardTitle"),"aria-pressed":S,children:i("prompt.storyboard")})})]})}function Oy(e){return e?Array.from(e).flatMap(a=>{if(a.kind!=="file"||!a.type.startsWith("image/"))return[];const i=a.getAsFile();return i?[i]:[]}):[]}function KM(e){const{maxRefs:a,trayItemCount:i,captureAttachmentCaret:o,addFilesAtCaret:s}=e,{t:c}=ge(),m=async(h,g)=>{const S=Math.max(0,a-i);if(S===0){w.getState().showToast(c("toast.refLimitTrayFull",{max:a}),!0);return}const v=h.slice(0,S),y=await s(v,g,!1);h.length>v.length&&w.getState().showToast(c("toast.refLimitPartial",{added:y,total:h.length,max:a}),!1)},p=h=>{const g=Oy(h.clipboardData?.items??null);g.length!==0&&(h.preventDefault(),m(g,o()))};return R.useEffect(()=>{const h=g=>{const S=g.target;if(["INPUT","TEXTAREA"].includes(S?.tagName??"")||S?.isContentEditable)return;const v=Oy(g.clipboardData?.items??null);v.length!==0&&(g.preventDefault(),m(v,w.getState().prompt.length))};return window.addEventListener("paste",h),()=>window.removeEventListener("paste",h)},[s,a,c,i]),p}const wu="tray:";function jy(e){return`${e.start}:${e.end}:${e.query}`}function $M(e){const a=w.getState();return a.addElementFromMention?a.addElementFromMention(e):gs(e.id,w.setState,w.getState,e)}function YM(e){const a=w.getState();a.syncElementCatalog?a.syncElementCatalog(e):Gb(e,w.setState,w.getState)}function XM(e){const a=Number.parseFloat(e);return Number.isFinite(a)&&a>0?a:null}function qm({variant:e="sidebar"}){const a=w(D=>D.prompt),i=w(D=>D.setPrompt),o=w(D=>D.insertedPrompts),s=w(D=>D.removeInsertedPromptFromComposer),c=w(D=>D.moveInsertedPromptInComposer),m=w(D=>D.generate),p=w(D=>D.selectedPresetIds),h=w(D=>D.removePreset),g=w(D=>D),S=g.addElementId,v=g.elementCatalog??null,y=g.missingElementIds??[],[x,E]=R.useState([]),P=D=>{const Ae=x.find(ke=>ke.id===D);return Ae?$M(Ae):(S?.(D),null)};R.useEffect(()=>{let D=!1;return M1().then(Ae=>{D||(E(Ae),YM(Ae))}).catch(Ae=>console.error("[ElementMention] load failed",Ae)),()=>{D=!0}},[]);const{t:I}=ge(),k=w(D=>D.trayItems),C=w(D=>D.retiredTags),_=w(D=>D.removeTrayItem),N=w(D=>D.activeReferenceLimit()),j=w(D=>D.providerUrlReference),$=w(D=>D.setProviderUrlReference),L=w(D=>D.addReferences),J=w(D=>D.addReferenceDataUrl),re=w(D=>D.useImageAsReference),he=w(D=>D.readDroppedImageMetadata),V=R.useRef(null),ee=R.useRef(null),oe=R.useRef(null),[Ne,ne]=R.useState(!1),[H,ae]=R.useState(null),ce=R.useRef(!1),be=R.useRef(null),Se=R.useRef(null),T=w(D=>D.promptMode),F=w(D=>D.multimode),W=w(D=>D.multimodeMaxImages),U=T==="direct",le=o.filter(D=>D.placement!=="after"),pe=o.filter(D=>D.placement==="after"),xe=[...le.map(D=>D.id),"__main_prompt__",...pe.map(D=>D.id)],Oe=k.length<N,Re=F?k.length>0?I("multimode.promptPlaceholderWithRefs"):I("multimode.promptPlaceholder"):k.length>0?I("prompt.placeholderWithRefs"):I("prompt.placeholder"),Ze=()=>ee.current?.selectionStart??w.getState().prompt.length,ie=(D,Ae)=>{const ke=w.getState().trayItems.filter(At=>At.kind==="attachment"&&!D.has(At.tokenId));if(ke.length===0)return 0;const Qe=w.getState().prompt,pt=Math.max(0,Math.min(Ae,Qe.length)),Dt=ke.map(At=>`@${At.tag} `).join("");i(`${Qe.slice(0,pt)}${Dt}${Qe.slice(pt)}`);const _a=pt+Dt.length;return requestAnimationFrame(()=>ee.current?.setSelectionRange(_a,_a)),ke.length},lt=(D,Ae)=>{const ke=`@${D} `,Qe=w.getState().prompt,pt=`${Qe.slice(0,Ae.start)}${ke}${Qe.slice(Ae.end)}`,Dt=Ae.start+ke.length;i(pt),requestAnimationFrame(()=>ee.current?.setSelectionRange(Dt,Dt))},at=(D,Ae)=>{if(ce.current)return;const ke=bM(D,Ae);ae(ke&&jy(ke)!==Se.current?ke:null)},st=async(D,Ae,ke)=>{if(D.length===0)return 0;const Qe=new Set(w.getState().trayItems.map(pt=>pt.tokenId));try{return ke&&D.length===1&&await he(D[0])?0:(await L(D),ie(Qe,Ae))}catch{return 0}},bt=async D=>{const Ae=oe.current??Ze();oe.current=null,await st(D,Ae,!0)},se=()=>{Oe&&(oe.current=Ze(),V.current?.click())},qe=async(D,Ae)=>{const ke=new Set(w.getState().trayItems.map(Qe=>Qe.tokenId));try{const Qe=D.url||D.image;if(!Qe)return;const pt={image:Qe,url:D.url,filename:D.filename};if(gt(pt)){const Dt=await cr(Qe);Dt&&J(Dt)}else await re(pt);ie(ke,Ae)}catch{}},ot=D=>{D.preventDefault(),ne(!1);const Ae=D.dataTransfer.getData("application/ima2-ref");if(Ae){try{const Qe=JSON.parse(Ae);qe(Qe,Ze())}catch{}return}const ke=Array.from(D.dataTransfer.files).filter(Qe=>Qe.type.startsWith("image/"));ke.length>0&&bt(ke)},St=D=>{D.preventDefault(),Ne||ne(!0)},xt=D=>{D.currentTarget.contains(D.relatedTarget)||ne(!1)},nn=KM({maxRefs:N,trayItemCount:k.length,captureAttachmentCaret:Ze,addFilesAtCaret:st}),Yt=R.useRef(null),fn=R.useRef(e);R.useLayoutEffect(()=>{const D=ee.current;if(!D)return;(Yt.current===null||fn.current!==e)&&(Yt.current=XM(window.getComputedStyle(D).maxHeight)??0,fn.current=e),D.style.height="auto";const Ae=Yt.current,ke=Ae?Math.min(D.scrollHeight,Ae):D.scrollHeight;D.style.height=`${ke}px`},[a,e]);const et=(D,Ae)=>{const ke=xe.indexOf(D);return ke<0?!1:Ae==="up"?ke>0:ke<xe.length-1},On=D=>d.jsxs("div",{className:"composer__prompt-chip",title:D.name,children:[d.jsx("span",{className:"composer__prompt-chip-plus","aria-hidden":"true",children:"+"}),d.jsx("span",{className:"composer__prompt-chip-title",children:D.name}),d.jsxs("div",{className:"composer__prompt-chip-actions",children:[d.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>c(D.id,"up"),disabled:!et(D.id,"up"),"aria-label":I("prompt.moveBlockUp",{name:D.name}),title:I("prompt.moveBlockUp",{name:D.name}),children:"^"}),d.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>c(D.id,"down"),disabled:!et(D.id,"down"),"aria-label":I("prompt.moveBlockDown",{name:D.name}),title:I("prompt.moveBlockDown",{name:D.name}),children:"v"}),d.jsx("button",{type:"button",className:"composer__prompt-chip-remove",onClick:()=>s(D.id),"aria-label":I("promptLibrary.removeInserted",{name:D.name}),children:"x"})]})]},D.id);return d.jsxs("div",{className:`composer composer--${e}${Ne?" composer--drag":""}${U?" composer--direct":""}${F?" composer--multimode":""}${U&&F?" composer--combined-modes":""}`,role:"group","aria-label":F?I("multimode.composerAriaLabel",{count:W}):I("prompt.label"),onDrop:ot,onDragOver:St,onDragLeave:xt,onPaste:nn,children:[d.jsxs("div",{className:"composer__header",children:[d.jsx("span",{className:"section-title composer__label",children:I("prompt.label")}),d.jsxs("div",{className:"composer__header-meta",children:[F&&d.jsx("span",{className:"composer__mode-badge",children:I("multimode.composerBadge",{count:W})}),U&&d.jsx("span",{className:"composer__direct-badge",children:I("prompt.directModeActive")}),j&&d.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>$(null),title:I("prompt.urlRefActiveTitle"),"aria-label":I("prompt.urlRefClear"),children:[d.jsx("span",{className:"composer__url-ref-dot","aria-hidden":"true"}),I("prompt.urlRefActive")]}),k.length>0&&d.jsx("span",{className:"composer__count",children:I("prompt.refCount",{count:k.length,max:N})})]})]}),d.jsx(MM,{items:k,limit:N,onRemove:_,onAdd:se}),le.length>0&&d.jsx("div",{className:"composer__prompt-chips",children:le.map(On)}),p.length>0&&d.jsx(zm,{ariaLabel:I("home.selectedPresets"),children:p.map(D=>{const Ae=zb(D);return Ae?d.jsx(yS,{onRemove:()=>h(D),removeLabel:I("common.removeNamed",{name:Ae.name}),children:Ae.name},D):null})}),d.jsx(FM,{items:k,assets:v,missingElementIds:y,selectedLabel:I("element.selected"),unavailableLabel:I("common.elementUnavailable"),kindLabel:D=>I(`element.kind${D[0].toUpperCase()}${D.slice(1)}`),mentionLabel:(D,Ae,ke)=>ke?I("element.unavailableAria",{name:D}):I("element.mentionAria",{name:D,kind:Ae}),removeLabel:D=>I("element.removeAria",{name:D}),onRemove:D=>g.removeElementId?.(D)}),d.jsxs("div",{className:"composer__prompt-stack",children:[d.jsx(qM,{prompt:a,retiredTags:C,textareaRef:ee}),d.jsx("textarea",{ref:ee,className:"prompt-area composer__textarea",value:a,placeholder:Re,onCompositionStart:()=>{ce.current=!0,ae(null)},onCompositionEnd:D=>{ce.current=!1,be.current=D.currentTarget.value,queueMicrotask(()=>{be.current=null}),at(D.currentTarget.value,D.currentTarget.selectionStart)},onChange:D=>{Se.current=null,i(D.target.value),be.current!==D.target.value&&at(D.target.value,D.target.selectionStart)},onClick:D=>at(D.currentTarget.value,D.currentTarget.selectionStart),onKeyDown:D=>{if(D.key==="Escape"&&H){D.preventDefault(),Se.current=jy(H),ae(null);return}if(D.key==="Enter"&&(D.metaKey||D.ctrlKey)){if(D.preventDefault(),y.length>0)return;m()}}})]}),d.jsx(NM,{open:H!==null,textareaRef:ee,caret:H?.end??0,query:H?.query??"",elements:[...k.filter(D=>D.kind==="attachment").map(D=>({id:`${wu}${D.tokenId}`,name:D.tag,kind:"reference",thumbnail:D.source.dataUrl})),...x.map(D=>{const Ae=kb(D);return{id:D.id,name:D.name,kind:typeof D.metadata?.elementKind=="string"?D.metadata.elementKind:"character",thumbnail:Ae?`/generated/${Ae.split("/").map(encodeURIComponent).join("/")}`:void 0,tags:D.tags}})],ariaLabel:I("common.elementSuggestions"),emptyLabel:I("common.noMatchingElements"),kindLabel:D=>I(`element.kind${D[0].toUpperCase()}${D.slice(1)}`),onSelect:D=>{const Ae=Wu(w.getState().trayItems,D.id);if(D.id.startsWith(wu)){const Qe=D.id.slice(wu.length),pt=w.getState().trayItems.find(Dt=>Dt.tokenId===Qe);pt&&H&&lt(pt.tag,H),ae(null);return}if(P?.(D.id),Ae){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(D.id)}"] .element-mention-chip__body`)?.focus()),ae(null);return}const ke=Wu(w.getState().trayItems,D.id);!ke||!H||(lt(ke.tag,H),ae(null))},onClose:()=>ae(null)}),pe.length>0&&d.jsxs("div",{className:"composer__prompt-chips composer__prompt-chips--after",children:[d.jsx("span",{className:"composer__prompt-chips-label",children:I("prompt.afterBlocks")}),pe.map(On)]}),d.jsx(VM,{canAddMore:Oe,onAttach:se}),Ne&&d.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:I("prompt.dropHere",{max:N})}),d.jsx("input",{ref:V,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:D=>{const Ae=Array.from(D.target.files??[]);Ae.length>0?bt(Ae):oe.current=null,D.target.value=""}})]})}function Um(){const e=w(p=>p.activeGenerations),a=w(p=>p.generate),i=w(p=>p.openReadinessPopup),o=w(p=>p.missingElementIds??[]),{t:s}=ge(),c=e>0,m=o.length>0;return d.jsxs("div",{className:"generate-row",children:[d.jsxs("button",{type:"button",className:`generate-btn foil-hover${c?" generate-btn--active":""}`,disabled:m,title:m?s("toast.missingElements"):void 0,onClick:()=>{a()},children:[s("generate.button"),c?d.jsx("span",{className:"generate-btn__count","aria-label":s("generate.buttonLoading",{n:e}),children:e}):null]}),d.jsx("button",{type:"button",className:"generate-row__readiness",onClick:i,title:s("readiness.openTitle"),"aria-label":s("readiness.openTitle"),children:"?"})]})}function SS(e,a=28){const i=e.trim().replace(/\s+/g," ");return i.length>a?`${i.slice(0,a)}...`:i}function Hm(e={}){const a=w(m=>m.inFlight),i=w(m=>m.cancelInFlightJob),o=w(m=>m.videoProgress),{t:s}=ge(),c={queued:s("inflight.queued"),planning:s("inflight.planning"),streaming:s("inflight.streaming"),decoding:s("inflight.decoding"),canceling:s("inflight.canceling")};return a.length===0?null:"panelId"in e?d.jsx(WM,{jobs:a,phaseLabels:c,videoProgress:o,cancelInFlightJob:i,t:s,variant:e.variant,panelId:e.panelId}):d.jsx(QM,{jobs:a,phaseLabels:c,videoProgress:o,cancelInFlightJob:i,t:s})}function QM(e){return d.jsx("ul",{className:"in-flight-list",children:e.jobs.map(a=>d.jsx(JM,{f:a,...e},a.id))})}function JM({f:e,phaseLabels:a,videoProgress:i,cancelInFlightJob:o,t:s}){const c=e.phase?a[e.phase]??e.phase:s("inflight.queued"),p=e.prompt.trim().replace(/\s+/g," ")||s("inflight.noPrompt");return d.jsxs("li",{className:"in-flight-item","data-phase":e.phase??"queued",title:p,"aria-label":`${c}: ${p}`,children:[d.jsx("span",{className:"in-flight-prompt",children:SS(e.prompt)}),d.jsx("span",{className:"in-flight-phase",children:e.kind==="video"&&i!=null&&i>0?`${Math.round(i*100)}%`:c}),d.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{o(e.id)},disabled:e.phase==="canceling","aria-label":s("inflight.cancelAria",{prompt:p}),title:s("common.cancel"),children:"×"}),d.jsx("span",{className:"in-flight-spinner","aria-hidden":"true","data-motion-essential":!0})]})}function WM(e){const a=e.jobs.filter(s=>s.kind==="video"||s.kind==="mcp-video"),i=a.length===1?a[0]?.id:null,o=e.videoProgress!=null&&e.videoProgress>=0&&e.videoProgress<=1?e.videoProgress:null;return d.jsx("ul",{id:e.panelId,className:`in-flight-list in-flight-list--${e.variant}`,children:e.jobs.map(s=>d.jsx(ZM,{f:s,determinateVideoId:i,validVideoProgress:o,...e},s.id))})}function ZM({f:e,determinateVideoId:a,validVideoProgress:i,phaseLabels:o,cancelInFlightJob:s,t:c}){const m=e.phase?o[e.phase]??e.phase:c("inflight.queued"),h=e.prompt.trim().replace(/\s+/g," ")||c("inflight.noPrompt"),g=e.kind==="video"||e.kind==="mcp-video",S=t2(e)??n2(e.kind,c),v=e.id===a&&i!=null?Math.round(i*100):null;return d.jsxs("li",{className:"in-flight-rich-item","data-phase":e.phase??"queued",title:h,"aria-label":`${S}, ${m}: ${h}`,children:[d.jsx("span",{className:`in-flight-placeholder${g?" in-flight-placeholder--video":""}`,"aria-hidden":"true",children:d.jsx(a2,{video:g})}),d.jsxs("span",{className:"in-flight-rich-copy",children:[d.jsx("span",{className:"in-flight-rich-title",children:S}),d.jsx("span",{className:"in-flight-rich-prompt",title:h,children:SS(e.prompt,54)}),d.jsxs("span",{className:"in-flight-rich-status",children:[d.jsx("span",{className:"in-flight-phase",children:v==null?m:`${m} · ${v}%`}),d.jsx(e2,{progressPercent:v,phaseLabel:m,t:c})]})]}),d.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{s(e.id)},disabled:e.phase==="canceling","aria-label":c("inflight.cancelAria",{prompt:h}),title:c("common.cancel"),children:"×"})]})}function e2({progressPercent:e,phaseLabel:a,t:i}){return d.jsx("span",{className:`in-flight-progress${e==null?" in-flight-progress--indeterminate":""}`,role:"progressbar","data-motion-essential":!0,"aria-label":e==null?a:i("inflight.progressAria",{n:e}),"aria-valuemin":e==null?void 0:0,"aria-valuemax":e==null?void 0:100,"aria-valuenow":e??void 0,children:d.jsx("span",{style:e==null?void 0:{width:`${e}%`}})})}function t2(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function n2(e,a){return e?.startsWith("mcp-")?a("inflight.kindMcp"):a(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function a2({video:e}){return d.jsxs("svg",{viewBox:"0 0 24 24",focusable:"false",children:[d.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),e?d.jsx("path",{d:"m10 9 5 3-5 3Z"}):d.jsxs(d.Fragment,{children:[d.jsx("circle",{cx:"9",cy:"9",r:"1.5"}),d.jsx("path",{d:"m5.5 17 4.2-4 2.7 2.4 2.2-2 3.9 3.6"})]})]})}const Gy="(max-width: 800px)";function ka(){const[e,a]=R.useState(()=>typeof window<"u"?window.matchMedia(Gy).matches:!1);return R.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia(Gy),o=()=>a(i.matches);return i.addEventListener("change",o),()=>i.removeEventListener("change",o)},[]),e}const o2=10,wa=12;function r2({anchorRef:e,panelId:a,focusOnOpen:i,onRequestClose:o,onPointerEnter:s,onPointerLeave:c}){const{t:m}=ge(),p=R.useRef(null),h=R.useRef(null),g=R.useRef(null),[S,v]=R.useState({left:wa,top:wa,caretTop:24}),[y,x]=R.useState(!1);R.useLayoutEffect(()=>{const I=()=>{const _=e.current,N=p.current;if(!_||!N)return;const j=_.getBoundingClientRect(),$=_.closest(".sidebar")?.getBoundingClientRect(),L=N.getBoundingClientRect(),J=$?$.right:j.right,re=Math.max(wa,window.innerWidth-L.width-wa),he=Math.max(wa,window.innerHeight-L.height-wa),V=Math.min(Math.max(J+o2,wa),re),ee=Math.min(Math.max(j.bottom-L.height,wa),he),oe=Math.min(Math.max(j.top+j.height/2-ee,16),L.height-16);v({left:V,top:ee,caretTop:oe}),x(!0)},k=()=>{g.current!=null&&cancelAnimationFrame(g.current),g.current=requestAnimationFrame(I)};I(),window.addEventListener("resize",k),window.addEventListener("scroll",k,!0);const C=new ResizeObserver(k);return e.current&&C.observe(e.current),p.current&&C.observe(p.current),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0),C.disconnect(),g.current!=null&&cancelAnimationFrame(g.current)}},[e]),R.useLayoutEffect(()=>{i&&h.current?.focus()},[i]),R.useEffect(()=>{const I=C=>{const _=C.target;_&&(e.current?.contains(_)||p.current?.contains(_))||o(!1)},k=C=>{C.key==="Escape"&&(C.preventDefault(),o(!0))};return document.addEventListener("pointerdown",I,!0),document.addEventListener("keydown",k),()=>{document.removeEventListener("pointerdown",I,!0),document.removeEventListener("keydown",k)}},[e,o]);const E=`${a}-title`,P={left:S.left,top:S.top,"--inflight-caret-top":`${S.caretTop}px`};return Js.createPortal(d.jsxs("div",{ref:p,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":E,"data-positioned":y,style:P,onPointerEnter:s,onPointerLeave:c,children:[d.jsxs("header",{className:"inflight-popup__header",children:[d.jsx("h2",{ref:h,id:E,tabIndex:-1,children:m("inflight.title")}),d.jsx("button",{type:"button",className:"inflight-popup__close","aria-label":m("common.close"),title:m("common.close"),onClick:()=>o(!0),children:d.jsx("span",{"aria-hidden":"true",children:"×"})})]}),d.jsx(Hm,{variant:"popup",panelId:a}),d.jsx("footer",{className:"inflight-popup__footer",children:m("inflight.footerHint")})]}),document.body)}const i2=180,l2=180;function xS({variant:e="popup",panelId:a,expanded:i=!1,onToggle:o}){const s=w(he=>he.inFlight.length),c=ka(),{t:m}=ge(),[p,h]=R.useState("closed"),[g,S]=R.useState(!1),v=R.useRef(null),y=R.useRef(null),x=R.useRef(null),E=e==="inline"?i:p!=="closed",P=()=>{y.current!=null&&window.clearTimeout(y.current),x.current!=null&&window.clearTimeout(x.current),y.current=null,x.current=null};if(R.useEffect(()=>P,[]),R.useLayoutEffect(()=>{if(s!==0)return;const he=document.activeElement;E&&he instanceof HTMLElement&&he.closest(".inflight-popup")&&v.current?.focus(),P(),h("closed"),S(!1),e==="inline"&&i&&o?.(!1)},[s,i,o,E,e]),s===0&&!(s===0&&e==="popup"&&E)||e==="popup"&&c)return null;const k=()=>window.matchMedia("(hover: hover) and (pointer: fine)").matches,C=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=null},_=()=>{e!=="popup"||p==="pinned"||!k()||(C(),y.current!=null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>h("hover"),i2))},N=()=>{y.current!=null&&window.clearTimeout(y.current),y.current=null,!(e!=="popup"||p!=="hover")&&(x.current=window.setTimeout(()=>h("closed"),l2))},j=he=>{P(),h("closed"),S(!1),he&&v.current?.focus()},$=he=>{if(e==="inline"){o?.(!i);return}if(P(),p==="pinned"){j(!1);return}S(he.detail===0),h("pinned")},L=he=>{he.pointerType==="mouse"&&_()},J=s>99?"99+":String(s),re=E?"inflight.badgeClose":"inflight.badgeOpen";return d.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:L,onPointerLeave:N,children:[d.jsxs("button",{ref:v,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:$,"aria-live":"polite","aria-expanded":E,"aria-controls":a,"aria-haspopup":e==="popup"?"dialog":void 0,"aria-label":m(re,{n:s}),title:m(re,{n:s}),children:[d.jsx("span",{className:"inflight-badge__spinner","aria-hidden":"true"}),d.jsx("span",{className:"inflight-badge__count","aria-hidden":"true",children:J})]}),e==="popup"&&E?d.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&E?d.jsx(r2,{anchorRef:v,panelId:a,focusOnOpen:g,onRequestClose:j,onPointerEnter:C,onPointerLeave:N}):null]})}function s2(){const{t:e}=ge(),a=w(y=>y.sessions),i=w(y=>y.activeSessionId),o=w(y=>y.switchSession),s=w(y=>y.createAndSwitchSession),c=w(y=>y.renameCurrentSession),m=w(y=>y.deleteSessionById),[p,h]=R.useState(!1),g=a.find(y=>y.id===i),S=()=>{const y=window.prompt(e("session.renamePrompt"),g?.title??e("session.newSession"));y&&y.trim()&&c(y.trim())},v=(y,x)=>{window.confirm(e("session.deleteConfirm",{title:x}))&&m(y)};return d.jsxs("div",{className:"session-picker",children:[d.jsxs("div",{className:"session-picker-row",children:[d.jsxs("button",{type:"button",className:"session-current",onClick:()=>h(y=>!y),title:e("session.switchTitle"),children:[d.jsx("span",{className:"session-title",children:g?.title??e("session.loading")}),d.jsx("span",{className:"session-caret",children:p?"▴":"▾"})]}),d.jsx("button",{type:"button",className:"session-btn",onClick:()=>{s(e("session.newSession"))},title:e("session.newSessionTitle"),children:"+"}),d.jsx("button",{type:"button",className:"session-btn",onClick:S,title:e("session.renameTitle"),disabled:!g,children:d.jsx(CM,{})})]}),p&&d.jsxs("ul",{className:"session-list",children:[a.map(y=>d.jsxs("li",{className:y.id===i?"is-active":"",children:[d.jsxs("button",{type:"button",className:"session-item",onClick:()=>{h(!1),o(y.id)},children:[d.jsx("span",{className:"session-item-title",children:y.title}),d.jsx("span",{className:"session-item-count",children:y.nodeCount})]}),d.jsx("button",{type:"button",className:"session-del",onClick:()=>v(y.id,y.title),title:e("session.deleteTitle"),children:"×"})]},y.id)),a.length===0&&d.jsx("li",{className:"session-empty",children:e("session.empty")})]})]})}const c2=[{value:"oauth",label:"GPT"},{value:"api",label:"GPT API"},{value:"grok",label:"Grok"},{value:"grok-api",label:"xAI API"},{value:"agy",label:"agy"},{value:"gemini-api",label:"Gem API"},{value:"atlascloud",label:"Atlas"},{value:"minimax",label:"MiniMax"}],Wl="mcp:",Zl="core:",es="video:",Iu="effort:";function d2(e){Qs(e,w.setState,w.getState)}function u2(e){jk(e,w.setState,w.getState)}function m2(e,a,i){Gk(e,a,w.setState,w.getState,i)}const Eu={image:[],video:[]};function Dy(e){return e.replace(/(^|-)([a-z])/g,(a,i,o)=>`${i}${o.toUpperCase()}`)}function AS({compact:e=!1}={}){const{t:a}=ge(),i=w(U=>U.provider),o=w(U=>U.imageModel),s=w(U=>U.videoModelSelected),c=w(U=>U.mcpProvider??null),m=w(U=>U.mcpModel??null),p=w(U=>U.mcpMediaKind??"image"),h=w(U=>U.setProvider),g=w(U=>U.setImageModel),S=w(U=>U.selectVideoModel),v=w(U=>U.setReasoningEffort),y=w(U=>U.reasoningEffort),{providers:x,loading:E,error:P}=cS(),[I,k]=R.useState(Eu),[C,_]=R.useState(!1),[N,j]=R.useState(0),[$,L]=R.useState(!1);R.useEffect(()=>{Hk(w.setState,w.getState)},[]);const J=c?x.find(U=>U.id===c)??null:null,re=!!(J?.enabled&&J.status.state==="connected");R.useEffect(()=>{if(!c||!re){k(Eu),_(!1);return}const U=new AbortController;return L(!0),_(!1),sS(c,U.signal).then(le=>{if(U.signal.aborted)return;k(le);const pe=w.getState(),Oe=(pe.mcpMediaKind==="video"?le.video:le.image).find(Re=>Re.id===pe.mcpModel);Oe&&Uk(Oe.capabilities,w.setState,w.getState)}).catch(le=>{le.name!=="AbortError"&&(U.signal.aborted||(k(Eu),_(!0)))}).finally(()=>{U.signal.aborted||L(!1)}),()=>U.abort()},[c,re,N]);const he=R.useMemo(()=>x.filter(U=>U.enabled&&U.status.state==="connected"),[x]),V=c?`${Wl}${c}`:`${Zl}${i}`,ee=c0(i),oe=s?`${es}${s}`:o,Ne=c?m?$l(p,m):"":oe,ne=!c&&(i==="oauth"||i==="api")&&!s,H=!!(m&&(I.image.some(U=>U.id===m)||I.video.some(U=>U.id===m))),ae=J?.executable===!1?J.lockReason??a("mcp.higgsfieldLocked"):null,ce=c?J?J.status.state!=="connected"?a("mcp.disconnectedSelection"):J.enabled?null:a("mcp.disabledProvider"):a("mcp.unknownProvider",{provider:c}):null,be=U=>{if(U.startsWith(Zl)){h(U.slice(Zl.length));return}const le=U.slice(Wl.length),pe=x.find(xe=>xe.id===le);!pe||pe.status.state!=="connected"||d2(le)},Se=U=>{if(U.startsWith(Iu)){v(U.slice(Iu.length));return}if(c){const le=AR(U);if(le){const xe=(le.kind==="video"?I.video:I.image).find(Oe=>Oe.id===le.model);m2(le.model,le.kind,xe?.capabilities)}else u2(U||null);return}if(U.startsWith(es)){S(U.slice(es.length));return}g(U)},T=[{label:a("mcp.coreProviders"),items:c2.map(U=>({value:`${Zl}${U.value}`,label:U.label}))}];he.length>0&&T.push({label:a("mcp.connectedProviders"),items:he.map(U=>({value:`${Wl}${U.id}`,label:Dy(U.id),sub:U.executable===!1?a("mcp.locked"):void 0}))}),c&&!he.some(U=>U.id===c)&&T.push({items:[{value:`${Wl}${c}`,label:Dy(c),sub:a("mcp.unavailable"),disabled:!0}]});const F=[];if(c)m&&!H&&F.push({items:[{value:$l(p,m),label:m}]}),F.push({label:a("mcp.imageModels"),items:I.image.map(U=>({value:$l("image",U.id),label:U.label}))}),F.push({label:a("mcp.videoModels"),items:I.video.map(U=>({value:$l("video",U.id),label:U.label}))});else{const U=i==="grok"||i==="grok-api";F.push({label:a("mcp.imageModels"),items:ee.map(le=>({value:le.value,label:le.shortLabel}))}),(U||s)&&F.push({label:a("mcp.videoModels"),items:d0.map(le=>({value:`${es}${le.value}`,label:le.shortLabel}))}),ne&&F.push({label:a("sidebar.reasoningLabel"),items:$u.map(le=>({value:`${Iu}${le.value}`,label:le.shortLabel,sub:le.value===y?"●":void 0}))})}const W=$u.find(U=>U.value===y);return d.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[d.jsx(tr,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:T,value:V,onChange:be,ariaLabel:a("mcp.providerLabel"),title:ce??a("mcp.providerLabel"),portal:!0}),d.jsx(tr,{id:"sidebar-generation-model",className:"gen-provider-model__select gen-provider-model__select--model",groups:F,value:Ne,onChange:Se,ariaLabel:a("mcp.modelLabel"),title:ce??a("mcp.modelLabel"),disabled:!!ce,placeholder:c?a($?"mcp.loadingModels":"mcp.chooseModel"):void 0,triggerSub:ne&&W?W.shortLabel:void 0,portal:!0}),ce||ae||P||C?d.jsx("span",{className:"image-model-select__trigger-effort",role:"status",children:ce??ae??(C?d.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>j(U=>U+1),children:a("mcp.modelsLoadFailed")}):a(E?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function TS(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function pi(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(TS):[]}}async function co(e,a){const i=await fetch(e,a),o=await i.json().catch(()=>({}));if(!i.ok){const s=o,c=typeof s.error=="string"?s.error:s.error?.message||`Request failed: ${i.status}`,m=new Error(c);throw typeof s.error!="string"&&(m.code=s.error?.code),m}return o}function p2(){return co("/api/cardnews/image-templates")}function f2(){return co("/api/cardnews/role-templates")}async function g2(e){const a=await co("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...a,plan:pi(a.plan)}}function h2(e){return co("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function y2(e){return co(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function v2(e){const i=(await co(`/api/cardnews/cards/${encodeURIComponent(e.card.id)}/regenerate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,cards:[e.card]})})).cards.find(o=>o.id===e.card.id);if(!i)throw new Error("Regenerated card not found");return{card:i}}function Fy(e){return co(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(a=>({...a,plan:pi(a.plan)}))}function b2(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function S2(e){return e[0]?.id||"academy-lesson-square"}function x2(e){return e.find(a=>a.id==="mid-5")?.id||e[0]?.id||"mid-5"}function A2(e){return Math.round(e/16)*16}function ws(e){return Math.min(mm,Math.max(1024,A2(e)))}function zy(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${ws(e.customW)}x${ws(e.customH)}`}function CS(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&"message"in e){const a=e.message;return typeof a=="string"?a:void 0}return String(e)}}function T2(e,a){const i=a.status||"generated";return{...e,...a,textFields:Array.isArray(a.textFields)?a.textFields:e.textFields,status:i,error:i==="error"?CS(a.error)||Z("cardNews.error"):void 0}}function C2(e){return new Promise(a=>setTimeout(a,e))}function Ru(e,a){const i=new Map(a.cards.map(o=>[o.id,o]));return{...e,cards:e.cards.map(o=>{const s=i.get(o.id);return s?{...o,...s,textFields:Array.isArray(s.textFields)?s.textFields:o.textFields,status:s.status||o.status,error:CS(s.error)}:o})}}const vt=pv((e,a)=>({templates:[],roleTemplates:[],activePlan:null,selectedCardId:null,selectedTextFieldId:null,topic:"",audience:"",goal:"",contentBrief:"",imageTemplateId:"academy-lesson-square",roleTemplateId:"mid-5",outputSizePreset:"2048x2048",customW:2048,customH:2048,loading:!1,generating:!1,error:null,draftError:null,plannerMeta:null,async hydrate(){if(!(a().loading||a().templates.length>0)){e({loading:!0,error:null});try{const[i,o]=await Promise.all([p2(),f2()]);e({templates:i.templates,roleTemplates:o.templates,imageTemplateId:S2(i.templates),roleTemplateId:x2(o.templates),loading:!1})}catch(i){e({loading:!1,error:i instanceof Error?i.message:String(i)})}}},setBriefField(i,o){e({[i]:o})},setImageTemplate(i){e({imageTemplateId:i})},setRoleTemplate(i){e({roleTemplateId:i})},setOutputSizePreset(i){e({outputSizePreset:i})},setCustomSize(i,o){e({customW:ws(i),customH:ws(o)})},async draft(){const i=a();e({loading:!0,error:null,draftError:null});try{const{plan:o,planner:s}=await g2({topic:i.topic,audience:i.audience,goal:i.goal,contentBrief:i.contentBrief,imageTemplateId:i.imageTemplateId,roleTemplateId:i.roleTemplateId,size:zy(i)});e({activePlan:pi(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,plannerMeta:s||null,loading:!1})}catch(o){const s=o instanceof Error?o.message:String(o);e({loading:!1,draftError:s,error:s})}},updateCard(i,o){e(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.activePlan.cards.map(c=>c.id===i?{...c,...o}:c)}:null}))},updateTextField(i,o,s){e(c=>({activePlan:c.activePlan?{...c.activePlan,cards:c.activePlan.cards.map(m=>m.id!==i||m.locked?m:{...m,textFields:m.textFields.map(p=>p.id===o?{...p,...s,source:s.source||"user"}:p)})}:null}))},addTextField(i,o){e(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.activePlan.cards.map(c=>c.id===i&&!c.locked?{...c,textFields:[...c.textFields,{...o,source:"user"}]}:c)}:null,selectedTextFieldId:o.id}))},removeTextField(i,o){e(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.activePlan.cards.map(c=>c.id===i&&!c.locked?{...c,textFields:c.textFields.filter(m=>m.id!==o)}:c)}:null,selectedTextFieldId:s.selectedTextFieldId===o?null:s.selectedTextFieldId}))},selectCard(i){e({selectedCardId:i,selectedTextFieldId:null})},selectTextField(i){e({selectedTextFieldId:i})},getGenerationSummary(){const i=a().activePlan?.cards||[];return{total:i.length,done:i.filter(o=>o.status==="generated").length,queued:i.filter(o=>o.status==="queued").length,generating:i.filter(o=>o.status==="generating").length,errors:i.filter(o=>o.status==="error").length,skipped:i.filter(o=>o.locked||o.status==="skipped").length}},async generateSet(){const i=a();if(!i.activePlan)return;const o=w.getState();e({generating:!0,error:null,activePlan:{...i.activePlan,cards:i.activePlan.cards.map(s=>s.locked?{...s,status:"skipped"}:{...s,status:"queued",error:void 0})}});try{const s=a().activePlan||i.activePlan;let m=await h2({...s,size:zy(i),quality:o.quality,moderation:o.moderation,model:o.imageModel,sessionId:o.activeSessionId});for(e(h=>({activePlan:h.activePlan?Ru(h.activePlan,m):h.activePlan}));["queued","running"].includes(m.status);)await C2(900),m=await y2(m.jobId),e(h=>({activePlan:h.activePlan?Ru(h.activePlan,m):h.activePlan}));const p=await Fy(m.setId).catch(()=>null);e(h=>({generating:!1,activePlan:p?.plan?pi(p.plan):h.activePlan?Ru(h.activePlan,m):h.activePlan,selectedTextFieldId:null})),o.showToast(Z("cardNews.generated",{count:m.generated}))}catch(s){const c=s instanceof Error?s.message:String(s);e(m=>({generating:!1,error:c,activePlan:m.activePlan?{...m.activePlan,cards:m.activePlan.cards.map(p=>p.status==="queued"||p.status==="generating"?{...p,status:"error",error:c}:p)}:m.activePlan}))}},async retryCard(i){const s=a().activePlan,c=s?.cards.find(p=>p.id===i);if(!s||!c||c.locked||!["draft","error"].includes(c.status))return;const m=w.getState();e({error:null,activePlan:{...s,cards:s.cards.map(p=>p.id===i?{...p,status:"generating",error:void 0}:p)}});try{const{card:p}=await v2({setId:s.setId,card:c,quality:m.quality,moderation:m.moderation,model:m.imageModel});e(h=>({activePlan:h.activePlan?{...h.activePlan,cards:h.activePlan.cards.map(g=>g.id===i?T2(g,TS(p)):g)}:h.activePlan}))}catch(p){const h=p instanceof Error?p.message:String(p);e(g=>({error:h,activePlan:g.activePlan?{...g.activePlan,cards:g.activePlan.cards.map(S=>S.id===i?{...S,status:"error",error:h}:S)}:g.activePlan}))}},async loadSet(i){e({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:o}=await Fy(i);e({activePlan:pi(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,loading:!1})}catch(o){e({loading:!1,error:o instanceof Error?o.message:String(o)})}}}));function w2(){const{t:e}=ge(),a=vt(N=>N.hydrate),i=vt(N=>N.topic),o=vt(N=>N.audience),s=vt(N=>N.goal),c=vt(N=>N.contentBrief),m=vt(N=>N.outputSizePreset),p=vt(N=>N.customW),h=vt(N=>N.customH),g=vt(N=>N.setBriefField),S=vt(N=>N.setOutputSizePreset),v=vt(N=>N.setCustomSize),y=vt(N=>N.draft),x=vt(N=>N.loading),E=vt(N=>N.generating),P=vt(N=>N.draftError),I=vt(N=>N.generateSet),k=vt(N=>N.activePlan),C=k?.cards||[],_={total:C.length,done:C.filter(N=>N.status==="generated").length};return R.useEffect(()=>{a()},[a]),d.jsxs("section",{className:"card-news-composer","aria-label":e("cardNews.composer"),children:[d.jsx("div",{className:"card-news-composer__head",children:d.jsxs("div",{children:[d.jsx("div",{className:"section-title",children:e("cardNews.composer")}),d.jsx("p",{children:e("cardNews.composerHint")})]})}),d.jsxs("label",{className:"card-news-field",children:[d.jsx("span",{children:e("cardNews.topic")}),d.jsx("input",{value:i,placeholder:e("cardNews.topicPlaceholder"),onChange:N=>g("topic",N.target.value)})]}),d.jsxs("label",{className:"card-news-field",children:[d.jsx("span",{children:e("cardNews.audience")}),d.jsx("input",{value:o,placeholder:e("cardNews.audiencePlaceholder"),onChange:N=>g("audience",N.target.value)})]}),d.jsxs("label",{className:"card-news-field",children:[d.jsx("span",{children:e("cardNews.goal")}),d.jsx("input",{value:s,placeholder:e("cardNews.goalPlaceholder"),onChange:N=>g("goal",N.target.value)})]}),d.jsxs("label",{className:"card-news-field",children:[d.jsx("span",{children:e("cardNews.brief")}),d.jsx("textarea",{value:c,placeholder:e("cardNews.briefPlaceholder"),onChange:N=>g("contentBrief",N.target.value)})]}),d.jsxs("div",{className:"card-news-field",children:[d.jsx("span",{children:e("cardNews.outputSize")}),d.jsx("div",{className:"card-news-size-row",role:"group","aria-label":e("cardNews.outputSize"),children:["1024x1024","2048x2048","custom"].map(N=>d.jsx("button",{type:"button",className:`option-btn${m===N?" active":""}`,onClick:()=>S(N),children:N==="custom"?e("cardNews.customSize"):N==="1024x1024"?"1024²":"2048²"},N))}),m==="custom"?d.jsxs("div",{className:"card-news-custom-size",children:[d.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:p,onChange:N=>v(Number.parseInt(N.target.value,10)||p,h),"aria-label":e("size.width")}),d.jsx("span",{children:"×"}),d.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:h,onChange:N=>v(p,Number.parseInt(N.target.value,10)||h),"aria-label":e("size.height")})]}):null]}),d.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{y()},disabled:x||!i.trim(),children:[x?d.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,e(x?"cardNews.drafting":"cardNews.draft")]}),P?d.jsx("div",{className:"card-news-error",role:"alert",children:P}):null,x?d.jsxs("div",{className:"card-news-inline-status",role:"status",children:[d.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}),d.jsx("span",{children:e("cardNews.drafting")})]}):null,d.jsxs("button",{type:"button",className:"composer__tool card-news-generate-btn",onClick:()=>{I()},disabled:!k||E||k.cards.every(N=>N.locked),children:[E?d.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,E?e("cardNews.progress.generating",{done:_.done,total:_.total}):e("cardNews.batchGenerate")]})]})}function nr({className:e}){return d.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function I2({item:e,active:a,selectLabel:i,deleteLabel:o,setRef:s,onSelect:c,onDelete:m}){const p=Ot(e),h=gt(e),g=S=>{S.dataTransfer.setData("application/ima2-ref",JSON.stringify(h?yi(e):{image:e.url||e.image,filename:e.filename})),S.dataTransfer.effectAllowed="copy"};return d.jsxs("div",{className:"sidebar-history__item",children:[d.jsx("button",{ref:S=>s(p,S),type:"button",className:`sidebar-history__thumb${a?" active":""}${h?" sidebar-history__thumb--video":""}`,onClick:()=>c(e),"aria-label":i,title:e.prompt??"",draggable:!0,onDragStart:g,children:h?d.jsxs(d.Fragment,{children:[e.thumb?d.jsx("img",{src:e.thumb,alt:"",loading:"lazy",decoding:"async"}):d.jsx(nr,{}),d.jsx("span",{className:"sidebar-history__play-badge","aria-hidden":"true",children:"▶"})]}):d.jsx("img",{src:e.thumb||e.url||e.image,alt:"",loading:"lazy",decoding:"async"})}),d.jsx("button",{type:"button",className:"sidebar-history__delete",onClick:S=>{S.preventDefault(),S.stopPropagation(),m(e)},"aria-label":o,title:o,children:"x"})]})}function E2({entry:e,active:a,selectLabel:i,deleteLabel:o,setRef:s,onSelect:c,onDelete:m}){const p=zN(e.items.length);return d.jsxs("div",{className:"sidebar-history__item",children:[d.jsxs("button",{ref:h=>s(e.key,h),type:"button",className:`sidebar-history__sequence${a?" active":""}`,onClick:()=>c(e.sequenceId),"aria-label":i,children:[d.jsx("span",{className:`sidebar-history__sequence-grid count-${p}`,"aria-hidden":"true",children:Array.from({length:p}).map((h,g)=>{const S=e.items[g];return S&&gt(S)&&!S.thumb?d.jsx(nr,{},Ot(S)):S?d.jsx("img",{src:S.thumb||S.url||S.image,alt:"",loading:"lazy",decoding:"async"},Ot(S)):d.jsx("span",{className:"sidebar-history__sequence-placeholder"},`sequence-placeholder-${e.sequenceId}-${g}`)})}),d.jsx("span",{className:"sidebar-history__sequence-badge",children:e.items.length})]}),d.jsx("button",{type:"button",className:"sidebar-history__delete",onClick:h=>{h.preventDefault(),h.stopPropagation(),m(e.sequenceId)},"aria-label":o,title:o,children:"x"})]})}const qy="ima2.sidebarHistoryCollapsed";function Uy(){const{t:e}=ge();return d.jsx("div",{className:"sidebar-history__item",children:d.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--skeleton","aria-label":e("common.generating")})})}function R2({count:e}){const a=Math.min(e,4);return d.jsx("div",{className:"sidebar-history__item",children:d.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--collection-skeleton",children:Array.from({length:a},(i,o)=>d.jsx("div",{className:"sidebar-collection-mini sidebar-collection-mini--skeleton"},o))})})}function N2(){const e=w(k=>k.history),a=w(k=>k.currentImage),i=w(k=>k.selectHistory),o=w(k=>k.showHistorySequence),s=w(k=>k.trashHistoryItem),c=w(k=>k.trashHistorySequence),m=w(k=>k.inFlight),p=w(k=>k.multimodeSequences),h=w(k=>{const C=k.multimodePreviewFlightId;return C?C.startsWith("history:")?C.slice(8):k.multimodeSequences[C]?.sequenceId??null:null}),g=w(k=>k.openGallery),S=R.useRef({}),[v,y]=R.useState(()=>{try{return localStorage.getItem(qy)==="1"}catch{return!1}}),{t:x}=ge(),E=tS(a,h),P=R.useMemo(()=>eS(e).slice(0,Wb),[e]);R.useEffect(()=>{!E||v||S.current[E]?.scrollIntoView({block:"nearest",inline:"nearest"})},[E,v,P]),R.useEffect(()=>{try{localStorage.setItem(qy,v?"1":"0")}catch{}},[v]);const I=(k,C)=>{S.current[k]=C};return d.jsxs("section",{className:`sidebar-history${v?" sidebar-history--collapsed":""}`,"aria-label":x("history.recentTitle"),children:[d.jsxs("div",{className:"sidebar-history__header",children:[d.jsx("span",{className:"section-title",children:x("history.recentTitle")}),d.jsxs("div",{className:"sidebar-history__header-actions",children:[d.jsx("button",{type:"button",className:"sidebar-history__gallery-button",onClick:g,"aria-label":x("history.galleryCard"),title:x("history.openGalleryTitle"),children:d.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),d.jsx("button",{type:"button",className:"sidebar-history__toggle",onClick:()=>y(k=>!k),title:x(v?"history.expandRecent":"history.collapseRecent"),"aria-expanded":!v,children:x(v?"history.expandRecentShort":"history.collapseRecentShort")})]})]}),v?null:d.jsxs("div",{className:"sidebar-history__grid",children:[m.map(k=>{const C=p[k.id];if(k.kind==="multimode"&&C){const _=[d.jsx(R2,{count:C.requested},`coll-sk-${k.id}`)];for(let N=0;N<C.requested;N++)C.images[N]||_.push(d.jsx(Uy,{},`sk-${k.id}-${N}`));return _}return d.jsx(Uy,{},`sk-${k.id}`)}),P.length===0&&m.length===0?d.jsx("button",{type:"button",className:"sidebar-history__empty",onClick:g,children:x("history.emptyRecent")}):null,P.map(k=>k.type==="sequence"?d.jsx(E2,{entry:k,active:E===k.key,selectLabel:x("history.selectRecent"),deleteLabel:x("history.deleteSequenceAria",{count:k.items.length}),setRef:I,onSelect:o,onDelete:C=>{c(C)}},k.key):d.jsx(I2,{item:k.item,active:E===k.key,selectLabel:x("history.selectRecent"),deleteLabel:x("history.deleteImageAria"),setRef:I,onSelect:i,onDelete:C=>{s(C)}},k.key))]})]})}const k2="sidebar-inflight-panel";function _2(){const{t:e}=ge(),a=w(g=>g.uiMode),i=w(g=>g.workspaceProfile),o=w(g=>g.referenceImages),s=w(g=>g.clearReferences),c=ka(),m=a==="agent"&&lr?"agent":a==="node"&&ir?"node":a==="assets"?"assets":a==="asset-gen"?"asset-gen":"classic",p=Ei(i),h=!c&&m==="classic"&&p.composerPlacement==="bottom"&&p.multimodeHistoryGrouping==="sequence";return d.jsxs(d.Fragment,{children:[d.jsx(M2,{}),m==="classic"?h?d.jsx(d.Fragment,{children:d.jsx(N2,{})}):d.jsxs(d.Fragment,{children:[d.jsx(qm,{}),d.jsxs("div",{className:"sidebar-generate-with-inflight",children:[d.jsx(Um,{}),d.jsx(xS,{variant:"popup",panelId:k2})]})]}):m==="card-news"?d.jsx(d.Fragment,{children:d.jsx(w2,{})}):m==="node"?d.jsxs(d.Fragment,{children:[d.jsx(s2,{}),o.length>0?d.jsxs("div",{className:"node-mode-ref-warning",role:"status",children:[d.jsx("strong",{children:e("node.classicRefsParkedTitle")}),d.jsx("span",{children:e("node.classicRefsParkedBody")}),d.jsx("button",{type:"button",onClick:s,children:e("node.clearParkedRefs")})]}):null,d.jsx("div",{className:"sidebar__node-hint",children:e("sidebar.nodeModeHint")}),d.jsx(Hm,{})]}):null]})}function M2(){const e=ka();return d.jsx(d.Fragment,{children:d.jsxs("div",{className:"logo",children:[d.jsx("div",{className:"logo-mark","aria-hidden":"true"}),d.jsxs("div",{className:"logo-copy",children:[d.jsx("div",{className:"logo-title",children:"ima2"}),d.jsx("div",{className:"logo-title logo-title--gen",children:"gen"})]}),d.jsxs("div",{className:"logo-actions",children:[d.jsx(L2,{}),d.jsx(AS,{compact:e})]})]})})}function P2(){return d.jsx("aside",{className:"sidebar",children:d.jsx("div",{className:"sidebar__scroll",children:d.jsx(_2,{})})})}function L2(){const{t:e}=ge(),a=w(m=>m.togglePromptLibrary),i=w(m=>m.promptLibraryOpen),o=w(m=>m.rightPanelOpen),s=w(m=>m.toggleRightPanel),c=()=>{!i&&!o&&s(),a()};return d.jsx("button",{type:"button",className:"settings-button",onClick:c,title:e("promptLibrary.title"),"aria-label":e("promptLibrary.title"),children:d.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})})}const O2=1024,j2=1024,G2="blank-canvas.png";function Hy(e,a){return typeof e!="number"||!Number.isFinite(e)||e<=0?a:Math.max(1,Math.round(e))}async function D2(e){const a=Hy(e?.width,O2),i=Hy(e?.height,j2),o=document.createElement("canvas");o.width=a,o.height=i;const s=o.getContext("2d");if(!s)throw new Error("blank_canvas_context_unavailable");s.fillStyle="#ffffff",s.fillRect(0,0,o.width,o.height);const c=await new Promise((m,p)=>{o.toBlob(h=>{h?m(h):p(new Error("blank_canvas_blob_unavailable"))},"image/png")});return new File([c],G2,{type:"image/png"})}const ts=1024;function F2(e){const a=/^(\d+)x(\d+)$/.exec(e);if(!a)return{width:ts,height:ts};const i=Number.parseInt(a[1]??"",10),o=Number.parseInt(a[2]??"",10);return!Number.isFinite(i)||!Number.isFinite(o)||i<=0||o<=0?{width:ts,height:ts}:{width:i,height:o}}function z2(){const e=w(h=>h.importLocalImageToHistory),a=w(h=>h.openCanvas),i=w(h=>h.showToast),o=w(h=>h.getResolvedSize),{t:s}=ge(),[c,m]=R.useState(!1),p=R.useCallback(async()=>{if(!c){m(!0);try{const h=F2(o()),g=await D2(h);await e(g)&&a()}catch{i(s("canvas.blank.failed"),!0)}finally{m(!1)}}},[c,o,e,a,i,s]);return{creatingBlankCanvas:c,createBlankCanvas:p}}function q2(e,a){return{image:e.url,url:e.url,providerUrl:e.providerUrl,filename:e.filename,mediaType:"video",prompt:e.prompt,userPrompt:e.userPrompt,revisedPrompt:e.revisedPrompt,provider:e.provider,model:e.model,format:"mp4",elapsed:e.elapsed,usage:e.usage??void 0,webSearchCalls:e.webSearchCalls,video:e.video,videoSeries:null,videoContinuity:e.videoContinuity,videoLineage:e.videoLineage,requestId:e.requestId,createdAt:e.createdAt,sessionId:null}}async function U2(e,a){try{const i=await fetch("/api/video/extend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:a}),o=await i.json().catch(()=>({}));if(!i.ok)throw ao(o,`Request failed: ${i.status}`);if(i.status!==202||o.requestId!==e.requestId||o.sourceVideoId!==e.sourceVideoId||o.workflow!=="last-frame-i2v")throw new Error("Video extension returned an invalid acceptance response")}catch(i){throw i instanceof Error?i:new Error(String(i))}}function H2(e,a){return lo(),new Promise((i,o)=>{let s=!1,c=()=>{},m=()=>{};const p=v=>{s||(s=!0,c(),m(),a.removeEventListener("abort",g),v())},h=()=>{Mt(e.requestId).catch(()=>{})},g=()=>p(()=>{h(),o(new DOMException("Aborted","AbortError"))});if(m=io(e.requestId,null,(v,y)=>{v==="done"?p(()=>i(y)):v==="error"&&p(()=>o(ao(y,"Video extension failed")))}),c=or(()=>p(()=>{h(),o(new Error("Video extension stream timed out"))})),a.aborted)return g();a.addEventListener("abort",g,{once:!0}),IT().then(()=>U2(e,a)).catch(v=>p(()=>o(v)))})}const B2={oauth:"GPT OAuth / Codex login",api:"GPT API key",grok:"Grok OAuth / progrok","grok-api":"Grok API key",agy:"Antigravity Gemini CLI","gemini-api":"Gemini API / Vertex",atlascloud:"Atlas Cloud API",minimax:"MiniMax API"};function V2(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function Bm(e){return V2(e)?String(e):null}function K2(e,a){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(a,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function By(e){return e?e.replace("x","×"):null}function $2(e){if(e==null)return null;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ee(e,a,i,o={}){const s=Bm(i);s&&e.push({label:a,value:s,...o})}function Nu(e,a,i,o={}){typeof i!="number"||i<=0||Ee(e,a,i,o)}function Y2(e,a,i){const o=$2(i);!o||o==="{}"||o==="[]"||e.push({label:a,value:o,copyValue:o,pre:!0})}function X2(e){if(!e.sequenceId)return null;const a=[e.sequenceIndex!=null&&e.sequenceTotalReturned!=null?`${e.sequenceIndex+1}/${e.sequenceTotalReturned}`:null,e.sequenceTotalRequested!=null?`requested ${e.sequenceTotalRequested}`:null,e.sequenceStatus??null].filter(Boolean);return a.length?`${e.sequenceId} (${a.join(", ")})`:e.sequenceId}function Q2(e){return e?B2[e]??e:null}function J2(e){return e.trim().replace(/\s+/g," ")}function ns(e,a,i,o){const s=Bm(o);if(!s)return;const c=J2(s);!c||a.has(c)||(a.add(c),e.push({label:i,value:s,copyValue:s,pre:!0}))}function Vy(e,a){const i=e?.[a];return typeof i=="number"&&Number.isFinite(i)?i:null}function Ky(e,a,i){const o=e?.[a];if(!o||typeof o!="object"||Array.isArray(o))return null;const s=o[i];return typeof s=="number"&&Number.isFinite(s)?s:null}function W2(e){const a=["metadata-modal__row"];return e.pre&&a.push("metadata-modal__row--pre"),e.compact&&a.push("metadata-modal__row--compact"),a.join(" ")}function Z2({item:e,onClose:a,onCopy:i}){const{t:o,locale:s}=ge(),c=R.useMemo(()=>JSON.stringify(e,null,2),[e]),m=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,p=Q2(e.provider),h=[[p,e.model].filter(Boolean).join(" · "),By(e.size),e.elapsed!=null?`${e.elapsed}s`:null,e.usage?.total_tokens!=null?`${e.usage.total_tokens} ${o("metadata.fields.tokens").toLowerCase()}`:null].filter(C=>!!C),g=[],S=[];Ee(S,o("metadata.fields.provider"),p,{compact:!0}),Ee(S,o("metadata.fields.model"),e.model,{compact:!0}),Ee(S,o("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Ee(S,o("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),S.length&&g.push({title:o("metadata.sections.provider"),fields:S,compact:!0});const v=[];Ee(v,o("metadata.fields.quality"),e.quality,{compact:!0}),Ee(v,o("metadata.fields.size"),By(e.size),{compact:!0}),Ee(v,o("metadata.fields.format"),e.format,{compact:!0}),Ee(v,o("metadata.fields.moderation"),e.moderation,{compact:!0}),Ee(v,o("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Ee(v,o("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Ee(v,o("metadata.fields.kind"),e.kind,{compact:!0}),Ee(v,o("metadata.fields.mediaType"),e.mediaType,{compact:!0}),v.length&&g.push({title:o("metadata.sections.settings"),fields:v,compact:!0});const y=[];Ee(y,o("metadata.fields.elapsed"),e.elapsed!=null?`${e.elapsed}s`:null,{compact:!0}),Ee(y,o("metadata.fields.totalTokens"),e.usage?.total_tokens,{compact:!0}),Ee(y,o("metadata.fields.inputTokens"),Vy(e.usage,"input_tokens"),{compact:!0}),Nu(y,o("metadata.fields.cachedTokens"),Ky(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Ee(y,o("metadata.fields.outputTokens"),Vy(e.usage,"output_tokens"),{compact:!0}),Nu(y,o("metadata.fields.reasoningTokens"),Ky(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),Nu(y,o("metadata.fields.webSearchCalls"),e.webSearchCalls,{compact:!0}),e.usage?.grok_cost_usd_ticks!=null&&Ee(y,o("metadata.fields.grokCostTicks"),e.usage.grok_cost_usd_ticks,{compact:!0}),y.length&&g.push({title:o("metadata.sections.usage"),fields:y,compact:!0});const x=[];Ee(x,o("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Ee(x,o("metadata.fields.createdAt"),K2(e.createdAt,s)),Ee(x,o("metadata.fields.sessionId"),e.sessionId),Ee(x,o("metadata.fields.nodeId"),e.nodeId),Ee(x,o("metadata.fields.parentNodeId"),e.parentNodeId),Ee(x,o("metadata.fields.clientNodeId"),e.clientNodeId),Ee(x,o("metadata.fields.refsCount"),e.refsCount),Ee(x,o("metadata.fields.sequence"),X2(e)),Ee(x,o("metadata.fields.setId"),e.setId),Ee(x,o("metadata.fields.cardId"),e.cardId),x.length&&g.push({title:o("metadata.sections.lineage"),fields:x});const E=[];Ee(E,o("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),Ee(E,o("metadata.fields.videoResolution"),e.video?.resolution),Ee(E,o("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),Ee(E,o("metadata.fields.videoRequestedModel"),e.video?.requestedModel),Ee(E,o("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),Ee(E,o("metadata.fields.videoModelFallback"),e.video?.modelFallback),Ee(E,o("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:Bm(e.video?.xaiVideoRequestId)??void 0}),Ee(E,o("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),E.length&&g.push({title:o("metadata.sections.video"),fields:E});const P=[];Ee(P,o("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Ee(P,o("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Ee(P,o("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Ee(P,o("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Ee(P,o("metadata.fields.latestContinuityPrompt"),m?.revisedPrompt,{copyValue:m?.revisedPrompt,pre:!0}),P.length&&g.push({title:o("metadata.sections.videoContinuity"),fields:P});const I=[],k=new Set;return ns(I,k,o("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),ns(I,k,o("metadata.fields.revisedPrompt"),e.revisedPrompt),ns(I,k,o("metadata.fields.prompt"),e.prompt),ns(I,k,o("metadata.fields.composerPrompt"),e.composerPrompt),Y2(I,o("metadata.fields.insertedPrompts"),e.composerInsertedPrompts),I.length&&g.push({title:o("metadata.sections.prompts"),fields:I}),d.jsx("div",{className:"modal-backdrop metadata-modal-backdrop",onClick:a,children:d.jsxs("section",{className:"modal metadata-modal",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-modal-title",onClick:C=>C.stopPropagation(),children:[d.jsxs("header",{className:"metadata-modal__header",children:[d.jsxs("div",{children:[d.jsx("h3",{id:"metadata-modal-title",children:o("metadata.title")}),d.jsx("p",{children:[e.mediaType??o("metadata.asset"),e.filename].filter(Boolean).join(" · ")}),h.length?d.jsx("div",{className:"metadata-modal__summary","aria-label":o("metadata.summary"),children:h.map(C=>d.jsx("span",{children:C},C))}):null]}),d.jsx("button",{type:"button",className:"metadata-modal__close",onClick:a,"aria-label":o("common.close"),children:"×"})]}),d.jsxs("div",{className:"metadata-modal__body",children:[g.map(C=>d.jsxs("section",{className:C.compact?"metadata-modal__section metadata-modal__section--compact":"metadata-modal__section",children:[d.jsx("h4",{children:C.title}),d.jsx("dl",{children:C.fields.map(_=>d.jsxs("div",{className:W2(_),children:[d.jsx("dt",{children:_.label}),d.jsxs("dd",{children:[_.pre?d.jsx("pre",{children:_.value}):d.jsx("span",{children:_.value}),_.copyValue?d.jsx("button",{type:"button",onClick:()=>i(_.copyValue),"aria-label":o("metadata.copyField",{label:_.label}),children:o("metadata.copy")}):null]})]},`${C.title}:${_.label}`))})]},C.title)),d.jsxs("details",{className:"metadata-modal__raw",children:[d.jsx("summary",{children:o("metadata.rawJson")}),d.jsx("div",{className:"metadata-modal__raw-actions",children:d.jsx("button",{type:"button",onClick:()=>i(c),children:o("metadata.copyRaw")})}),d.jsx("pre",{children:c})]})]})]})})}function eP(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function wS(e,a){return e==="video"&&Object.values(a).some(i=>i!==void 0)?"video upscale takes no parameters":a.scaleFactor!==void 0&&![2,4,8,16].includes(a.scaleFactor)?"scaleFactor must be 2, 4, 8, or 16":a.scaleFactor!==void 0&&a.scaleFactor>2&&a.flavor!==void 0&&a.flavor!=="sublime"?"scaleFactor above 2 requires flavor sublime":null}function tP(e,a){const i=eP(e);if(!i||wS(i,a))return null;const o=i==="image"?"upscale-image":"upscale-video",s=Object.fromEntries(Object.entries(a).filter(([,c])=>c!==void 0));return{action:o,files:[e],...Object.keys(s).length>0?{parameters:s}:{}}}const nP=[2,4,8,16],aP=["sublime","photo","photo_denoiser"];function oP({pending:e,onSubmit:a,onClose:i}){const{t:o}=ge(),[s,c]=R.useState(2),[m,p]=R.useState(""),[h,g]=R.useState(10),[S,v]=R.useState(10),[y,x]=R.useState(30),E={scaleFactor:s,...m?{flavor:m}:{},sharpen:h,smartGrain:S,ultraDetail:y},P=wS("image",E);return d.jsxs("div",{className:"upscale-popover",role:"dialog","aria-label":o("result.upscaleTitle"),children:[d.jsx("div",{className:"option-row",role:"group","aria-label":"scaleFactor",children:nP.map(I=>d.jsxs("button",{type:"button",className:`option-btn${s===I?" active":""}`,"aria-pressed":s===I,onClick:()=>c(I),children:[I,"x"]},I))}),d.jsxs("label",{className:"upscale-popover__field",children:[d.jsx("span",{children:o("result.upscaleFlavor")}),d.jsxs("select",{value:m,onChange:I=>p(I.target.value),children:[d.jsx("option",{value:"",children:o("result.upscaleFlavorAuto")}),aP.map(I=>d.jsx("option",{value:I,children:I},I))]})]}),[["sharpen",h,g],["smartGrain",S,v],["ultraDetail",y,x]].map(([I,k,C])=>d.jsxs("label",{className:"upscale-popover__field",children:[d.jsxs("span",{children:[I," ",d.jsx("output",{children:k})]}),d.jsx("input",{type:"range",min:0,max:100,step:5,value:k,onChange:_=>C(Number(_.target.value))})]},I)),P?d.jsx("p",{className:"element-detail__error",role:"alert",children:P}):null,d.jsxs("div",{className:"upscale-popover__actions",children:[d.jsx("button",{type:"button",className:"action-btn action-btn--primary",disabled:e||!!P,onClick:()=>a(E),children:o(e?"inflight.streaming":"result.upscaleStart")}),d.jsx("button",{type:"button",className:"action-btn",onClick:i,children:o("common.cancel")})]})]})}const rP="canvas-mode-context",iP="Canvas Mode",$y=36e5,lP=["Canvas Mode context:","The user edited or annotated the reference image on a canvas.","If the image is a blank white canvas or paper with user-drawn strokes, treat those strokes as source content and preserve/complete them.","If the image is an existing picture with circles, arrows, sticky notes, handwritten marks, or memo notes over it, treat those marks as edit instructions. Apply the instruction, then remove the marks from the final image unless explicitly asked to keep them.","Infer the intended edit from the canvas marks and memo text. Preserve unrelated image content."].join(`
30
- `);function sP({imageOverride:e=null,onAfterDeleteFocus:a}){const{t:i}=ge(),o=w(se=>se.currentImage),s=w(se=>se.showToast),c=w(se=>se.insertPromptToComposer),m=w(se=>se.createRootNodeFromHistoryItem),p=w(se=>se.trashHistoryItem),h=w(se=>se.saveToAssets),g=w(se=>se.permanentlyDeleteHistoryItemByClick),S=w(se=>se.canvasOpen),v=w(se=>se.openCanvas),[y,x]=R.useState(!1),[E,P]=R.useState(!1),[I,k]=R.useState("idle"),[C,_]=R.useState(!1),[N,j]=R.useState(!1),[$,L]=R.useState(!1),[J,re]=R.useState(!1),he=R.useRef(null);R.useEffect(()=>{let se=!0;return jm().then(qe=>{se&&re(qe.some(ot=>ot.id==="runway"&&ot.status.state==="connected"))}).catch(()=>{}),()=>{se=!1}},[]);const V=async se=>{if(!ee?.filename||$)return;const qe=tP(ee.filename,se);if(!qe){s(i("result.upscaleInvalid"),!0);return}L(!0);try{await ue("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(qe)}),j(!1),s(i("result.upscaleStarted"))}catch{s(i("result.upscaleFailed"),!0)}finally{L(!1)}};R.useEffect(()=>()=>he.current?.abort(),[]);const ee=e??o;if(!ee)return null;const oe=gt(ee),Ne=oe?ee.url||ee.image:"",ne=!!ee.filename,H=!!ee.filename&&!oe,ae=oe&&!!ee.filename,be=!!((ee.provider==="grok"||ee.provider==="grok-api")&&!oe&&ee.providerUrl&&ee.createdAt&&Date.now()-ee.createdAt<$y),Se=async()=>{if(!(!ee.filename||E)){P(!0);try{await w.getState().animateImage(ee.filename,ee.prompt??void 0)&&s(i("toast.animateDone"))}catch(se){const qe=se instanceof Error?se.message:i("toast.animateFailed");s(qe,!0)}finally{P(!1)}}},T=async()=>{if(!ee.filename||I==="pending")return;const se=`vext_${crypto.randomUUID()}`,qe=new AbortController;he.current=qe,k("pending");try{const ot=await H2({requestId:se,sourceVideoId:ee.filename,prompt:ee.prompt?.trim()||void 0,provider:ee.provider==="grok-api"?"grok-api":"grok",model:ee.model??void 0},qe.signal);w.getState().addHistoryItem(q2(ot,ee)),k("idle"),s(i("toast.animateDone"))}catch(ot){const St=ot instanceof DOMException&&ot.name==="AbortError";k(St?"idle":"error"),St||s(ot instanceof Error?ot.message:i("toast.animateFailed"),!0)}finally{he.current===qe&&(he.current=null)}},F=()=>he.current?.abort(),W=()=>{const se=document.createElement("a");se.href=ee.image,se.download=ee.filename||"generated.png",se.click()},U=async se=>{const ot=await(await fetch(se)).blob();let St;if(ot.type==="image/png")St=ot;else{const xt=new Image;xt.crossOrigin="anonymous";const nn=URL.createObjectURL(ot);await new Promise((fn,et)=>{xt.onload=()=>fn(),xt.onerror=et,xt.src=nn});const Yt=document.createElement("canvas");Yt.width=xt.naturalWidth,Yt.height=xt.naturalHeight,Yt.getContext("2d").drawImage(xt,0,0),URL.revokeObjectURL(nn),St=await new Promise((fn,et)=>Yt.toBlob(On=>On?fn(On):et(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":St})])},le=async()=>{try{if(oe){const se=await cr(Ne);await U(se)}else await U(ee.image);s(i(oe?"toast.frameCopied":"toast.imageCopied"))}catch{s(i("toast.copyFailed"),!0)}},pe=async()=>{try{const se=await yb(Ne);await U(se),s(i("toast.frameCopied"))}catch{s(i("toast.copyFailed"),!0)}},xe=async()=>{try{const se=await vb(Ne);await U(se),s(i("toast.frameCopied"))}catch{s(i("toast.copyFailed"),!0)}},Oe=async()=>{if(ee.prompt)try{await navigator.clipboard.writeText(ee.prompt),s(i("toast.promptCopied"))}catch{s(i("clipboard.writeFailed"),!0)}},Re=async se=>{try{await navigator.clipboard.writeText(se),s(i("toast.metadataCopied"))}catch{s(i("clipboard.writeFailed"),!0)}},Ze=async()=>{let se={ok:!1,isVideo:!1,hasPrompt:!1};try{se=await Ws(ee)}catch{}S&&e&&c({id:rP,name:iP,text:lP});const qe=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');qe&&(qe.focus(),qe.setSelectionRange(qe.value.length,qe.value.length)),s(i(se.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ie=async()=>{if(oe||!ee.providerUrl||!ee.createdAt||Date.now()-ee.createdAt>=$y){s(i("toast.continueAsUrlExpired"),!0);return}try{await bS(ee)}catch{}const se=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');se&&(se.focus(),se.setSelectionRange(se.value.length,se.value.length)),s(i("toast.continueAsUrlStarted"))},lt=async()=>{if(!(!ee.filename||y)){x(!0);try{const se=await DT({filename:ee.filename});s(i("toast.comfyExported",{filename:se.uploadedFilename}))}catch(se){const qe=se instanceof Error?se.code:void 0;s(i(qe==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":qe==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":qe==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{x(!1)}}},at=()=>{m(ee),s(i("toast.nodeRootCreated"))},st=async()=>{try{await p(ee)}finally{a?.()}},bt=async()=>{try{await g(ee)}finally{a?.()}};return d.jsxs("div",{className:"result-actions",children:[d.jsx("button",{type:"button",className:"action-btn",onClick:W,children:i("result.download")}),d.jsx("button",{type:"button",className:`action-btn${oe?" action-btn--frame":""}`,onClick:le,children:i(oe?"result.copyLastFrame":"result.copyImage")}),oe&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:pe,children:i("result.copyFirstFrame")}),d.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:xe,children:i("result.copyMidFrame")})]}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Oe()},children:i("result.copyPrompt")}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const se=await h(ee);s(i(se?"chain.savedToAssets":"chain.saveToAssetsFailed"),!se)})()},title:i("chain.saveToAssets"),children:i("chain.saveToAssets")}),d.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:Ze,title:i("result.continueHereTitle"),children:i("result.continueHere")}),be&&d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ie()},title:i("result.continueAsUrlTitle"),children:i("result.continueAsUrl")}),H&&d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Se()},disabled:E,title:i("result.animateTitle"),children:i(E?"result.animating":"result.animate")}),J&&ee.filename&&(oe?d.jsx("button",{type:"button",className:"action-btn",disabled:$,onClick:()=>{V({})},title:i("result.upscaleTitle"),children:i($?"inflight.streaming":"result.upscale")}):d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn",disabled:$,onClick:()=>j(se=>!se),title:i("result.upscaleTitle"),children:i("result.upscale")}),N?d.jsx(oP,{pending:$,onSubmit:se=>{V(se)},onClose:()=>j(!1)}):null]})),ae&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn",onClick:T,disabled:I==="pending","aria-busy":I==="pending",title:i("result.extendTitle")??"이어가기",children:I==="pending"?i("inflight.streaming"):I==="error"?i("gallery.retry"):i("result.extend")??"이어가기"}),I==="pending"&&d.jsx("button",{type:"button",className:"action-btn",onClick:F,children:i("common.cancel")})]}),d.jsx("button",{type:"button",className:"action-btn",onClick:at,title:i("result.firstNodeTitle"),children:i("result.firstNode")}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>_(!0),title:i("result.infoTitle"),children:i("result.info")}),!S&&d.jsx("button",{type:"button",className:"action-btn",onClick:v,title:i("canvas.open"),"aria-label":i("canvas.openAria"),children:d.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:d.jsx("path",{d:"M4 4h8v8M12 4l-8 8"})})}),ee.filename&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{st()},title:i("result.deleteTitle"),children:i("result.delete")}),d.jsxs("details",{className:"result-actions__more",children:[d.jsx("summary",{className:"action-btn",children:i("result.more")}),d.jsxs("div",{className:"result-actions__menu",children:[ne&&d.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{lt()},title:i("result.sendToComfyUITitle"),disabled:y,children:i("result.sendToComfyUI")}),d.jsx("button",{type:"button",className:"result-actions__menu-item result-actions__danger-item",onClick:()=>{bt()},children:i("result.permanentDelete")})]})]})]}),C&&d.jsx(Z2,{item:ee,onClose:()=>_(!1),onCopy:se=>{Re(se)}})]})}function cP({prompt:e,onCopy:a}){const{t:i}=ge(),o=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),a())};return d.jsx("div",{className:"result-prompt",onClick:a,onKeyDown:o,role:"button",tabIndex:0,title:i("result.copyPrompt"),"aria-label":i("result.copyPrompt"),children:d.jsx("span",{className:"result-prompt__text",children:e})})}function dP(){const e=w(y=>{const x=y.multimodePreviewFlightId;return x?y.multimodeSequences[x]??null:null}),a=w(y=>y.cancelMultimode),i=w(y=>{const x=y.multimodePreviewFlightId;return!!(x&&(y.activeFlightIds.has(x)||y.inFlight.some(E=>E.id===x)))}),o=w(y=>y.selectHistory),s=w(y=>y.currentImage),c=w(y=>y.openCanvas),{t:m}=ge(),p=y=>{o(y)},h=y=>{o(y),c()};if(!e)return null;const g=new Map,S=e.partials.filter(y=>y.index==null);for(const y of e.partials)y.index!=null&&g.set(y.index,y);const v=Array.from({length:e.requested},(y,x)=>{const E=e.images[x],P=g.get(x)??(E?void 0:S.shift());return{index:x,image:E,partial:P}});return d.jsxs("section",{className:"multimode-sequence","aria-live":"polite",children:[d.jsxs("div",{className:"multimode-sequence__header",children:[d.jsxs("div",{children:[d.jsx("div",{className:"multimode-sequence__title",children:m("multimode.sequenceTitle")}),d.jsx("div",{className:"multimode-sequence__meta",children:m("multimode.sequenceProgress",{returned:e.returned,requested:e.requested})})]}),i?d.jsx("button",{type:"button",className:"secondary-btn",onClick:a,children:m("multimode.cancel")}):null]}),d.jsx("div",{className:`multimode-sequence__grid count-${Math.min(e.requested,4)}`,children:v.map(({index:y,image:x,partial:E})=>{const P=x&&s?.filename&&x.filename===s.filename;return d.jsxs("article",{className:`multimode-sequence__slot${x?" done":""}${P?" active":""}`,onClick:x?()=>p(x):void 0,onDoubleClick:x?()=>h(x):void 0,role:x?"button":void 0,tabIndex:x?0:void 0,onKeyDown:x?I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),p(x))}:void 0,children:[d.jsx("div",{className:"multimode-sequence__badge",children:m("multimode.stageLabel",{index:y+1})}),x?d.jsx("img",{src:x.url??x.image,alt:m("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):E?d.jsx("img",{src:E.image,alt:m("multimode.partialAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):e.status==="pending"||e.status==="complete"?d.jsx("div",{className:"multimode-sequence__skeleton"}):d.jsx("div",{className:"multimode-sequence__empty",children:e.status==="error"?m("multimode.error"):e.status==="empty"?m("multimode.empty"):e.status==="canceled"?m("multimode.canceled"):e.status==="partial"?m("multimode.notReturned"):m("multimode.generating")})]},x?.filename??y)})})]})}function uP({zoom:e,minZoom:a,maxZoom:i,onZoomIn:o,onZoomOut:s,onReset:c,labels:m}){return d.jsxs("div",{className:"viewer-controls","aria-label":m.controls,onPointerDown:p=>p.stopPropagation(),onDoubleClick:p=>p.stopPropagation(),onWheel:p=>p.stopPropagation(),children:[d.jsx("button",{type:"button",className:"viewer-control-btn",onClick:p=>{p.stopPropagation(),s()},disabled:e<=a,"aria-label":m.zoomOut,children:"-"}),d.jsxs("button",{type:"button",className:"viewer-control-btn viewer-control-btn--label",onClick:p=>{p.stopPropagation(),c()},"aria-label":m.reset,children:[Math.round(e*100),"%"]}),d.jsx("button",{type:"button",className:"viewer-control-btn",onClick:p=>{p.stopPropagation(),o()},disabled:e>=i,"aria-label":m.zoomIn,children:"+"})]})}function ys(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function mP(e,a,i,o){if(!e)return!1;const s=a.find(c=>c.filename===e);return s?!!s.isFavorite:o!==void 0?o:i.has(e)}function _j(e,a){return a?e.filter(i=>i!=="starred"):Array.from(new Set([...e,"starred"]))}const no=1,IS=5,as=.22;function pP(e){return Math.min(IS,Math.max(no,e))}function fP(e){const[a,i]=R.useState(1),[o,s]=R.useState({x:0,y:0}),[c,m]=R.useState(null),p=R.useRef(0),h=R.useRef(null),g=R.useCallback(()=>{cancelAnimationFrame(p.current),p.current=0,h.current=null,i(1),s({x:0,y:0}),m(null)},[]);R.useEffect(()=>{g()},[g,e]),R.useEffect(()=>()=>{cancelAnimationFrame(p.current)},[]);const S=R.useCallback(I=>{i(k=>{const C=pP(k+I);return C<=no?(s({x:0,y:0}),no):Number(C.toFixed(2))})},[]),v=R.useCallback(I=>{I.preventDefault(),S(I.deltaY<0?as:-as)},[S]),y=R.useCallback(()=>{if(a>no){g();return}i(2)},[g,a]),x=R.useCallback(I=>{a<=no||I.button!==0||(I.preventDefault(),I.currentTarget.setPointerCapture(I.pointerId),m({pointerId:I.pointerId,startX:I.clientX,startY:I.clientY,baseX:o.x,baseY:o.y}))},[o.x,o.y,a]),E=R.useCallback(I=>{if(!c||c.pointerId!==I.pointerId)return;const k={x:c.baseX+I.clientX-c.startX,y:c.baseY+I.clientY-c.startY};h.current=k,cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{s(k),h.current=null})},[c]),P=R.useCallback(I=>{!c||c.pointerId!==I.pointerId||(cancelAnimationFrame(p.current),p.current=0,h.current&&(s(h.current),h.current=null),m(null),I.currentTarget.releasePointerCapture(I.pointerId))},[c]);return{zoom:a,pan:o,reset:g,zoomIn:()=>S(as),zoomOut:()=>S(-as),handleWheel:v,handleDoubleClick:y,handlePointerDown:x,handlePointerMove:E,handlePointerUp:P}}const gP=R.lazy(()=>$t(()=>import("./index-DBh-jt0i.js"),[]).then(e=>({default:e.CanvasModeWorkspace})));function hP(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function yP(e){if(!e)return null;const a=e.match(/^(\d+)x\1$/);return a?`${a[1]}²`:e.replace("x","×")}function vP(e){const a=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||a.startsWith("data:"))return a;const i=a.includes("?")?"&":"?";return`${a}${i}canvasMergedAt=${e.canvasMergedAt}`}function em(){const e=w(T=>T.currentImage),a=w(T=>T.importLocalImageToHistory),i=w(T=>{const F=T.multimodePreviewFlightId;return F?T.multimodeSequences[F]??null:null}),o=w(T=>T.selectHistoryShortcutTarget),s=w(T=>T.trashHistoryItem),c=w(T=>T.permanentlyDeleteHistoryItemByShortcut),m=w(T=>T.markGeneratedResultsSeen),p=w(T=>T.activeGenerations),h=w(T=>T.canvasOpen),g=w(T=>T.openCanvas),S=w(T=>T.showToast),v=w(T=>T.history),y=w(T=>T.galleryFavorites),x=w(T=>T.toggleGalleryFavorite),{t:E}=ge(),[P,I]=R.useState(!1),[k,C]=R.useState(null),{creatingBlankCanvas:_,createBlankCanvas:N}=z2(),j=R.useRef(null),$=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,L=fP($),J=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),S(E("toast.promptCopied")))},re=T=>{if(T.key==="Delete"||T.key==="Backspace"){if(!e||T.target!==T.currentTarget||ys(T.target))return;if(T.preventDefault(),T.shiftKey){c(e);return}s(e);return}T.key!=="ArrowLeft"&&T.key!=="ArrowRight"&&T.key!=="Home"&&T.key!=="End"||T.target===T.currentTarget&&(ys(T.target)||(T.preventDefault(),T.key==="ArrowLeft"?o("previous"):T.key==="ArrowRight"?o("next"):T.key==="Home"?o("first"):T.key==="End"&&o("last")))},he=T=>{ys(T.target)||(m(),T.currentTarget.focus())},V=R.useCallback(()=>{window.requestAnimationFrame(()=>j.current?.focus())},[]),ee=async()=>{const T=e?.filename;if(!(!e||!T||k===T)){C(T);try{await x(e)}finally{C(F=>F===T?null:F)}}},oe=R.useCallback(T=>{Array.from(T.dataTransfer.types).includes("Files")&&(T.preventDefault(),I(F=>F||!0))},[]),Ne=R.useCallback(T=>{T.currentTarget.contains(T.relatedTarget)||I(!1)},[]),ne=R.useCallback(async T=>{if(!Array.from(T.dataTransfer.types).includes("Files"))return;T.preventDefault(),I(!1);const F=Array.from(T.dataTransfer.files).filter(W=>/^image\/(png|jpeg|webp)$/.test(W.type));F.length!==0&&await a(F[0])},[a]);if(h&&e)return d.jsx(R.Suspense,{fallback:d.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:d.jsx(gP,{currentImage:e})});const H=hP(e?.quality),ae=yP(e?.size),ce=Cv(e?.model,e?.provider),be=e?vP(e):null,Se=mP(e?.filename,v,y,e?.isFavorite);return d.jsxs("main",{className:`canvas${P?" canvas--drop-active":""}`,onDragOver:oe,onDragLeave:Ne,onDrop:ne,children:[P?d.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:d.jsx("span",{className:"canvas__drop-hint",children:E("canvas.drop.hint")})}):null,d.jsx("div",{className:`progress-bar${p>0?" active":""}`}),i?d.jsx(dP,{}):e&&be?d.jsxs("div",{ref:j,className:"result-container visible",tabIndex:0,onMouseDown:he,onKeyDown:re,"aria-label":E("canvas.imageViewerAria"),children:[d.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${L.zoom>no?" canvas-annotation-frame--zoomed":""}`,onWheel:L.handleWheel,onDoubleClick:L.handleDoubleClick,onPointerDown:L.handlePointerDown,onPointerMove:L.handlePointerMove,onPointerUp:L.handlePointerUp,onPointerCancel:L.handlePointerUp,children:[e.filename?d.jsx(vS,{variant:"result",active:Se,busy:k===e.filename,label:E(Se?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:ee}):null,gt(e)?d.jsxs(d.Fragment,{children:[d.jsx("video",{className:"result-img",src:be,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${L.pan.x}px, ${L.pan.y}px) scale(${L.zoom})`}},$??void 0),d.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:T=>{T.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi(e))),T.dataTransfer.effectAllowed="copy"},title:E("canvas.dragToComposer"),"aria-label":E("canvas.dragToComposer"),children:E("canvas.dragHint")})]}):d.jsxs(d.Fragment,{children:[d.jsx("img",{className:"result-img",src:be,alt:E("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${L.pan.x}px, ${L.pan.y}px) scale(${L.zoom})`},onDoubleClick:T=>{T.stopPropagation(),g()}},$??void 0),d.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:T=>{T.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),T.dataTransfer.effectAllowed="copy"},title:E("canvas.dragToComposer"),"aria-label":E("canvas.dragToComposer"),children:E("canvas.dragHint")})]}),d.jsx(uP,{zoom:L.zoom,minZoom:no,maxZoom:IS,onZoomIn:L.zoomIn,onZoomOut:L.zoomOut,onReset:L.reset,labels:{controls:E("viewer.controls"),zoomIn:E("viewer.zoomIn"),zoomOut:E("viewer.zoomOut"),reset:E("viewer.reset")}})]}),d.jsx("div",{className:"result-meta",children:(gt(e)?[e.elapsed!=null?`${e.elapsed}s`:null,e.video?.duration?`${e.video.duration}s clip`:null,e.video?.resolution??null,e.video?.aspectRatio??null,Bb(e.videoContinuity),ce]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?E("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,WE(e.reasoningEffort),H,ae,ce]).filter(T=>!!T).join(" · ")}),d.jsx(sP,{onAfterDeleteFocus:V}),e.prompt?d.jsx(cP,{prompt:e.prompt,onCopy:J}):null]}):e?null:d.jsxs("div",{className:"canvas__blank-entry",children:[d.jsx("div",{className:"canvas__blank-sheet","aria-hidden":!0}),d.jsxs("div",{className:"canvas__blank-copy",children:[d.jsx("strong",{children:E("canvas.blank.title")}),d.jsx("span",{children:E("canvas.blank.subtitle")})]}),d.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{N()},disabled:_,children:E(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function bP(){return d.jsxs("div",{className:"classic-workspace",children:[d.jsx("div",{className:"classic-workspace__stage",children:d.jsx(em,{})}),d.jsxs("div",{className:"classic-workspace__dock",children:[d.jsx(qm,{variant:"bottom"}),d.jsx(Um,{})]})]})}const ES="ima2.customSizeSlots";function SP(e){if(!e||typeof e!="object")return!1;const a=e;return typeof a.id=="string"&&typeof a.w=="number"&&typeof a.h=="number"&&typeof a.updatedAt=="number"}function xP(){try{const e=localStorage.getItem(ES);if(!e)return[];const a=JSON.parse(e);return Array.isArray(a)?Wo(a.filter(SP)):[]}catch{return[]}}function AP(e){try{localStorage.setItem(ES,JSON.stringify(Wo(e)))}catch{}}function TP(e,a,i){return Gs({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:a,ratio:i,updatedAt:Date.now()})}function ci(e){return e.map(a=>({value:a.value,label:a.label,sub:a.sub}))}function CP(){const e=w(ne=>ne.sizePreset),a=w(ne=>ne.setSizePreset),i=w(ne=>ne.customW),o=w(ne=>ne.customH),s=w(ne=>ne.setCustomSize),{t:c}=ge(),[m,p]=R.useState(String(i)),[h,g]=R.useState(String(o)),[S,v]=R.useState(e==="custom"),[y,x]=R.useState(()=>xP()),[E,P]=R.useState(null),[I,k]=R.useState("free"),C=e==="custom",_=pm(m,h,i,o),N=gR().filter(ne=>ne.value==="auto");R.useEffect(()=>{p(String(i)),g(String(o))},[i,o]),R.useEffect(()=>{C||(v(!1),P(null))},[C]);function j(ne){x(ne),AP(ne)}function $(){const ne=_n(m,i),H=_n(h,o);s(ne,H),p(String(ne)),g(String(H))}function L(ne){ne.key==="Enter"&&(ne.preventDefault(),$())}function J(){a("custom"),v(!0),P(y.length>=Jo?y[0]?.id??null:null)}function re(ne){a(ne),ne!=="custom"&&(v(!1),P(null))}function he(ne){a("custom"),s(ne.w,ne.h),p(String(ne.w)),g(String(ne.h)),v(!1),P(ne.id)}function V(ne){k(ne.id);const H=sR(ne);H&&(p(String(H.w)),g(String(H.h)))}function ee(){const ne=TP(_.w,_.h,I),H=y.length>=Jo&&E?dR(y,E,ne):cR(y,ne);j(H),a("custom"),s(_.w,_.h),p(String(_.w)),g(String(_.h)),P(ne.id),v(!1)}const oe=_.reasons.length>0?_.reasons.map(ne=>c(`size.adjustedReasons.${ne}`)).join(", "):c("size.noAdjustment"),Ne=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?c("size.squareMaxHint",{size:`${uy}×${uy}`}):null;return d.jsxs("div",{className:"option-group size-picker",children:[d.jsx("div",{className:"section-title",children:c("size.title")}),d.jsx(xn,{title:"",items:ci(uR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(mR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(pR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(fR),value:e,onChange:re}),d.jsxs("div",{className:"option-row size-picker__quick-row",children:[ci(N).map(ne=>d.jsxs("button",{type:"button",className:`option-btn${e===ne.value?" active":""}`,onClick:()=>re(ne.value),children:[ne.label,ne.sub?d.jsxs(d.Fragment,{children:[d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:ne.sub})]}):null]},ne.value)),d.jsxs("button",{type:"button",className:`option-btn${C?" active":""}`,onClick:J,children:[c("size.customPlus"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:c("size.customSub")})]})]}),y.length>0?d.jsx("div",{className:"option-row size-picker__slot-row",children:y.map(ne=>d.jsxs("button",{type:"button",className:`option-btn size-picker__slot${C&&i===ne.w&&o===ne.h?" active":""}`,onClick:()=>he(ne),children:[ne.w,"×",ne.h,d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:ne.ratio||c("size.customSlot")})]},ne.id))}):null,S?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"size-picker__ratio-row",children:iR.map(ne=>d.jsx("button",{type:"button",className:`size-picker__ratio${I===ne.id?" active":""}`,onClick:()=>V(ne),children:ne.id==="free"?c("size.ratioFree"):ne.label},ne.id))}),d.jsxs("div",{className:"option-row size-picker__custom-row",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:m,onChange:ne=>p(ne.target.value.replace(/\D/g,"")),onBlur:$,onKeyDown:L,placeholder:c("size.width")}),d.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:h,onChange:ne=>g(ne.target.value.replace(/\D/g,"")),onBlur:$,onKeyDown:L,placeholder:c("size.height")})]}),d.jsxs("div",{className:"size-picker__preview",children:[d.jsx("span",{children:c("size.normalizedPreview")}),d.jsx("strong",{children:lR(_.w,_.h)})]}),d.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:oe}),Ne?d.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:Ne}):null,y.length>=Jo?d.jsxs("div",{className:"size-picker__replace-row",children:[d.jsx("span",{children:c("size.replaceCustomSlot")}),y.map(ne=>d.jsxs("button",{type:"button",className:`size-picker__replace${E===ne.id?" active":""}`,onClick:()=>P(ne.id),children:[ne.w,"×",ne.h]},ne.id))]}):null,d.jsx("button",{type:"button",className:"size-picker__save",onClick:ee,children:y.length>=Jo?c("size.replaceCustomSlot"):c("size.saveCustomSlot")}),d.jsx("div",{className:"size-hint",children:c("size.hint")})]}):null]})}const ku=[1,2,4];function wP(){const e=w(C=>C.count),a=w(C=>C.setCount),i=w(C=>C.uiMode),o=w(C=>C.multimode),s=w(C=>C.multimodeMaxImages),c=w(C=>C.setMultimodeMaxImages),{t:m}=ge(),p=i==="classic"&&o,h=p?s:e,g=p?c:a,[S,v]=R.useState(!ku.includes(h)),[y,x]=R.useState(String(h));R.useEffect(()=>{v(!ku.includes(h)),x(String(h))},[p,h]);function E(C=y){const _=Yu(Number.parseInt(C,10));g(_),x(String(_))}function P(C){v(!1),x(String(C)),g(C)}function I(C){const _=Yu(h+C);v(!0),x(String(_)),g(_)}function k(C){C.key==="Enter"&&(C.preventDefault(),E())}return d.jsxs("div",{className:"option-group count-picker",children:[d.jsx("div",{className:"section-title",children:m(p?"multimode.maxStages":"count.title")}),d.jsxs("div",{className:"option-row",children:[ku.map(C=>d.jsx("button",{type:"button",className:`option-btn${h===C&&!S?" active":""}`,onClick:()=>P(C),children:C},C)),d.jsx("button",{type:"button",className:`option-btn${S?" active":""}`,onClick:()=>{v(C=>!C),x(String(h))},children:m("count.customPlus")})]}),S?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"count-picker__custom",children:[d.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>I(-1),"aria-label":m("count.decrease"),children:"-"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"count-picker__input",value:y,onChange:C=>x(C.target.value.replace(/\D/g,"")),onBlur:()=>E(),onKeyDown:k,"aria-label":m("count.customLabel")}),d.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>I(1),"aria-label":m("count.increase"),children:"+"})]}),d.jsx("p",{className:"option-help",children:h>=5?m(p?"multimode.highCountHint":"count.highCountHint"):m(p?"multimode.minMaxHint":"count.minMaxHint")})]}):null]})}const IP={low:{"1024x1024":.006,"1024x1536":.005,"1536x1024":.005,"1024x1360":.005,"1360x1024":.005,"1024x1824":.006,"1824x1024":.006,"2048x2048":.012,"2048x1152":.009,"1152x2048":.009,"3840x2160":.023,"2160x3840":.023,auto:.006},medium:{"1024x1024":.053,"1024x1536":.041,"1536x1024":.041,"1024x1360":.041,"1360x1024":.041,"1024x1824":.05,"1824x1024":.05,"2048x2048":.106,"2048x1152":.08,"1152x2048":.08,"3840x2160":.2,"2160x3840":.2,auto:.053},high:{"1024x1024":.211,"1024x1536":.165,"1536x1024":.165,"1024x1360":.165,"1360x1024":.165,"1024x1824":.2,"1824x1024":.2,"2048x2048":.422,"2048x1152":.32,"1152x2048":.32,"3840x2160":.8,"2160x3840":.8,auto:.211}},EP={512:.045,"1K":.067,"2K":.101,"4K":.151},RP={512:.134,"1K":.134,"2K":.134,"4K":.24};function NP(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function kP(e,a){const i=e.match(/^(\d+)x(\d+)$/);if(!i)return .003;const o=Math.max(Number(i[1]),Number(i[2])),s=NP(o),m=a==="nano-banana-pro"?RP:EP;return m[s]??m["1K"]??.003}function _P(e,a,i,o){return i==="gemini-api"?kP(a,o):IP[e]?.[a]??0}function MP(){const{t:e}=ge(),a=w(y=>y.provider),i=w(y=>y.quality),o=w(y=>y.multimode),s=w(y=>y.multimodeMaxImages),m=w(y=>y.getResolvedSize)(),p=w(y=>y.imageModel),h=a==="oauth"||a==="grok"||a==="agy",g=_P(i,m,a,p),S=h?e("cost.free"):o?e("cost.multimodeApprox",{amount:(g*s).toFixed(3),count:s}):e("cost.approx",{amount:g.toFixed(3)}),v=h?"var(--green)":void 0;return d.jsxs("div",{className:"cost-estimate",children:[d.jsx("span",{children:e("cost.label")}),d.jsx("span",{className:"price",style:v?{color:v}:void 0,children:S})]})}function RS(){const[e,a]=R.useState(null);return R.useEffect(()=>{let i=!1,o=null;const s=async()=>{try{const c=await hT();if(i)return;a(c),c.status==="starting"&&(o=setTimeout(s,3e3))}catch{i||a(null)}};return s(),()=>{i=!0,o&&clearTimeout(o)}},[]),e}function PP(){const[e,a]=R.useState(null),[i,o]=R.useState(!1);return R.useEffect(()=>{let s=!1;return yT().then(c=>{s||a(c)}).catch(()=>{s||o(!0)}),()=>{s=!0}},[]),{data:e,error:i}}function NS(){const[e,a]=R.useState(null);return R.useEffect(()=>{let i=!1,o=null;const s=async()=>{try{const c=await fetch("/api/grok/status");if(i)return;const m=await c.json();a(m),m.status!=="ready"&&(o=setTimeout(s,1e4))}catch{i||a({status:"offline"})}};return s(),()=>{i=!0,o&&clearTimeout(o)}},[]),e}function kS(){const[e,a]=R.useState(null),[i,o]=R.useState(null),s=R.useCallback(async()=>{try{const m=await(await fetch("/api/keys/status")).json();a(m),o(null)}catch(c){o(c instanceof Error?c:new Error(String(c)))}},[]);return R.useEffect(()=>{let c=!1,m=null;return(async()=>(await s(),c||(m=setInterval(s,3e4))))(),()=>{c=!0,m&&clearInterval(m)}},[s]),{data:e,error:i,mutate:s}}function _S(){const{t:e}=ge(),a=RS(),{data:i}=PP(),o=NS(),{data:s}=kS(),c=a?.status==="ready";let m=e("provider.oauthNotReady"),p;a?.status==="auth_required"?(m=e("provider.codexLoginRequired"),p=e("provider.codexLoginHint")):a?.status==="starting"?m=e("provider.oauthStarting"):a||(m=e("provider.serverUnreachable"));const h=i?.apiKeyValid===!0,g=o?.status==="ready",S=o?o.status==="offline"?e("provider.grokOffline"):o.status==="no_image_model"?e("provider.grokNoImageModel"):o.status==="error"?e("provider.grokNotReady"):"":e("provider.grokNotReady"),v=s?.xai?.valid===!0,y=s?.gemini?.valid===!0||s?.vertex?.valid===!0,x=s?.atlascloud?.valid===!0,E=s?.minimax?.valid===!0;return{oauth:{ok:c,reason:m,hint:p},api:{ok:h,reason:h?"":e("provider.apiInvalid")},grok:{ok:g,reason:S,hint:g?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:v,reason:v?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:y,reason:y?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:x,reason:x?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:E,reason:E?"":e("provider.minimaxApiKeyRequired")}}}const LP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");function uo(e,a){const i=R.useRef(null),o=R.useRef(a);return o.current=a,R.useEffect(()=>{if(!e)return;const s=document.activeElement instanceof HTMLElement?document.activeElement:null,c=i.current,m=()=>Array.from(c?.querySelectorAll(LP)??[]).filter(h=>!h.hidden&&h.getAttribute("aria-hidden")!=="true");window.requestAnimationFrame(()=>{(c?.querySelector("[data-modal-initial-focus]")??m()[0]??c)?.focus()});const p=h=>{if(h.key==="Escape"){h.preventDefault(),o.current();return}if(h.key!=="Tab")return;const g=m();if(g.length===0){h.preventDefault(),c?.focus();return}const S=g[0],v=g[g.length-1];h.shiftKey&&document.activeElement===S?(h.preventDefault(),v.focus()):!h.shiftKey&&document.activeElement===v&&(h.preventDefault(),S.focus())};return document.addEventListener("keydown",p),()=>{document.removeEventListener("keydown",p),window.requestAnimationFrame(()=>s?.focus())}},[e]),i}function OP({open:e,providerLabel:a,reason:i,hint:o,onClose:s}){const{t:c}=ge(),m=uo(e,s);if(!e)return null;const p=c("apiDisabled.title",{provider:a});return d.jsx("div",{className:"modal-backdrop",onClick:s,role:"presentation",children:d.jsxs("div",{ref:m,className:"modal",role:"dialog","aria-modal":"true","aria-label":p,tabIndex:-1,onClick:h=>h.stopPropagation(),children:[d.jsx("div",{className:"modal__title",children:p}),d.jsxs("div",{className:"modal__body",children:[d.jsx("p",{children:i}),o?d.jsx("p",{className:"modal__hint",children:o}):null]}),d.jsx("div",{className:"modal__actions",children:d.jsx("button",{type:"button",className:"modal__btn",onClick:s,"data-modal-initial-focus":!0,children:c("common.ok")})})]})})}const os="core:",_u="mcp:",Mu=[{value:"oauth",provider:"GPT",method:"OAuth"},{value:"api",provider:"GPT",method:"API"},{value:"grok",provider:"Grok",method:"OAuth"},{value:"grok-api",provider:"Grok",method:"API"},{value:"agy",provider:"Gemini",method:"agy"},{value:"gemini-api",provider:"Gemini",method:"API"},{value:"atlascloud",provider:"Atlas Cloud",method:"API"},{value:"minimax",provider:"MiniMax",method:"API"}];function Pu(e){return e.replace(/(^|-)([a-z])/g,(a,i,o)=>`${i}${o.toUpperCase()}`)}function Lu({tone:e}){return d.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function Yy(e){return e.enabled?e.status.state==="connected"?e.executable===!1?"warn":"ok":e.status.state==="connecting"||e.status.state==="auth_required"?"warn":"bad":"bad"}function Xy({mcpProviders:e}){const{t:a}=ge(),i=w(_=>_.provider),o=w(_=>_.mcpProvider??null),s=w(_=>_.setProvider),c=_S(),[m,p]=R.useState(null),h=_=>{const N=c[_.value];return N.ok?a("provider.statusReady"):N.reason},g=_=>_.enabled?_.status.state==="connected"?_.executable===!1?`${a("provider.statusConnected")} · ${a("mcp.locked")}`:a("provider.statusConnected"):_.status.state==="connecting"?a("mcp.connecting"):_.status.state==="auth_required"?a("provider.statusAuthRequired"):a("provider.statusDisconnected"):a("mcp.disabledProvider"),S=[{label:a("mcp.coreProviders"),items:Mu.map(_=>{const N=c[_.value];return{value:`${os}${_.value}`,searchText:`${_.provider} ${_.method}`,label:d.jsxs("span",{className:"provider-option",children:[d.jsx(Lu,{tone:N.ok?"ok":"bad"}),d.jsxs("span",{children:[_.provider," ",_.method]})]}),sub:h(_)}})}],v=e.filter(_=>_.enabled).map(_=>({value:`${_u}${_.id}`,searchText:Pu(_.id),label:d.jsxs("span",{className:"provider-option",children:[d.jsx(Lu,{tone:Yy(_)}),d.jsx("span",{children:Pu(_.id)})]}),sub:g(_)}));v.length>0&&S.push({label:"MCP",items:v});const y=o?`${_u}${o}`:`${os}${i}`,x=o?null:Mu.find(_=>_.value===i)??null,E=o?e.find(_=>_.id===o)??null:null,P=x?h(x):E?g(E):a("provider.statusDisconnected"),I=x?c[x.value].ok?"ok":"bad":E?Yy(E):"bad",k=x?x.method:"MCP",C=_=>{if(_.startsWith(os)){const $=_.slice(os.length),L=Mu.find(re=>re.value===$),J=c[$];if(!J.ok){p({label:L?`${L.provider} ${L.method}`:$,reason:J.reason,hint:J.hint});return}s($);return}const N=_.slice(_u.length),j=e.find($=>$.id===N);if(!j||!j.enabled||j.status.state!=="connected"){p({label:Pu(N),reason:!j||!j.enabled?a("mcp.disabledProvider"):a("mcp.disconnectedSelection")});return}Qs(N,w.setState,w.getState)};return d.jsxs("div",{className:"option-group provider-status-select","data-testid":"provider-status-select",children:[d.jsx("div",{className:"section-title",children:a("provider.authTitle")}),d.jsx(tr,{groups:S,value:y,onChange:C,portal:!0,ariaLabel:a("provider.authTitle"),className:"provider-status-select__select"}),d.jsxs("div",{className:"provider-status-line","data-tone":I,children:[d.jsx(Lu,{tone:I}),d.jsxs("span",{className:"provider-status-line__key",children:[a("provider.statusLineTitle"),":"]}),d.jsx("span",{className:"provider-status-line__value",children:P})]}),d.jsxs("div",{className:"provider-auth-chip",title:a("provider.authMethodTitle"),children:[d.jsx("span",{children:k}),I!=="bad"?d.jsx("span",{className:"provider-auth-chip__state",children:a("provider.authActive")}):null]}),d.jsx(OP,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>p(null)})]})}const jP=[{value:"1:1",label:"1:1"},{value:"3:2",label:"3:2"},{value:"2:3",label:"2:3"},{value:"4:3",label:"4:3"},{value:"3:4",label:"3:4"},{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"2:1",label:"2:1"},{value:"1:2",label:"1:2"},{value:"auto",label:"Auto"}],GP=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function DP(){const{t:e}=ge(),a=w(c=>c.grokAspectRatio),i=w(c=>c.grokResolution),o=w(c=>c.setGrokAspectRatio),s=w(c=>c.setGrokResolution);return d.jsxs("div",{className:"option-group grok-size-picker",children:[d.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")}),d.jsx("div",{className:"grok-size-picker__aspects",children:jP.map(c=>d.jsx("button",{type:"button",className:`option-btn grok-size-picker__aspect${a===c.value?" active":""}`,onClick:()=>o(c.value),children:c.label},c.value))}),d.jsx("div",{className:"section-title",style:{marginTop:8},children:e("size.grokResolutionTitle")}),d.jsx("div",{className:"grok-size-picker__resolutions",children:GP.map(c=>d.jsx("button",{type:"button",className:`option-btn grok-size-picker__res${i===c.value?" active":""}`,onClick:()=>s(c.value),children:c.label},c.value))})]})}const FP=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function zP(){const{t:e}=ge(),a=w(o=>o.imageModel),i=w(o=>o.setImageModel);return d.jsx(xn,{title:e("quality.grokModelTitle"),items:FP,value:a,onChange:i})}function MS({values:e,value:a,defaultValue:i,onChange:o,allowAuto:s=!1,disabled:c,ariaLabel:m}){const{t:p}=ge(),h=R.useId();if(e.length===0)return null;const g=a??i??e[0],S=e.reduce((E,P,I)=>Math.abs(P-g)<Math.abs(e[E]-g)?I:E,0),v=a===null,y=e[0],x=e[e.length-1];return d.jsxs("div",{className:`ctl-duration${v?" is-auto":""}${c?" is-disabled":""}`,children:[d.jsxs("div",{className:"ctl-duration__head",children:[d.jsx("output",{htmlFor:h,className:"ctl-duration__value",children:v?`${p("size.autoLabel")} · ${e[S]}s`:`${e[S]}s`}),s?d.jsx("button",{type:"button",className:`option-btn ctl-duration__auto${v?" active":""}`,"aria-pressed":v,disabled:c,onClick:()=>o(null),children:p("size.autoLabel")}):null]}),d.jsx("input",{id:h,type:"range",className:"ctl-duration__range",min:0,max:e.length-1,step:1,value:S,disabled:c,"aria-label":m,"aria-valuetext":`${e[S]}s`,onChange:E=>o(e[Number(E.target.value)]??e[0])}),d.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[d.jsxs("span",{children:[y,"s"]}),d.jsxs("span",{children:[x,"s"]})]})]})}const qP=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],UP=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),Qy=[3,5,8,10,12,15],HP=[{value:dm,label:"Grok V",sub:"Fast"},{value:Ea,label:"Grok V1.5",sub:"HD"}];function BP(){const{t:e}=ge(),a=w(V=>V.videoModelSelected),i=w(V=>V.selectVideoModel),o=w(V=>V.activeVideoRefCount()),s=w(V=>V.videoDuration),c=w(V=>V.setVideoDuration),m=w(V=>V.videoResolution),p=w(V=>V.setVideoResolution),h=w(V=>V.videoAspectRatio),g=w(V=>V.setVideoAspectRatio),S=w(V=>V.videoTopic),v=w(V=>V.setVideoTopic),y=w(V=>V.showToast),x=w(V=>V.videoContinuityLineage),E=w(V=>V.selectedPresetIds),P=w(V=>V.removePreset),I=E.map(V=>zb(V)).filter(V=>V?.category==="camera-motion"),k=o>=2?Ev:15,C=Rv(o),_=Bb(x),N=vu(a,"1080p",C),j=vu(Ea,"1080p",C),$=qP.map(V=>V.value==="1080p"?{...V,disabled:!j}:V);R.useEffect(()=>{vu(a,m,C)||p("720p")},[C,m,p,a]);const L=V=>{if(V==="1080p"){if(!j)return;N||i(Ea)}p(V)},[J,re]=R.useState(null);R.useEffect(()=>{fetch("/api/config/grok-planner").then(V=>V.json()).then(re).catch(()=>{})},[]);const he=async V=>{const ee=J?.model;re(oe=>oe?{...oe,model:V}:null);try{const oe=await fetch("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:V})});if(!oe.ok)throw new Error(`HTTP ${oe.status}`)}catch{re(oe=>oe&&ee?{...oe,model:ee}:oe),y(e("video.plannerUpdateFailed"),!0)}};return d.jsxs("div",{className:"right-panel-settings video-controls",children:[d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")??"Model"}),d.jsx("div",{className:"option-row",children:HP.map(V=>d.jsxs("button",{type:"button",className:`option-btn${a===V.value?" active":""}`,onClick:()=>i(V.value),children:[V.label,d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:V.sub})]},V.value))})]}),d.jsxs("div",{className:"provider-compat-note",role:"note",children:[d.jsx("strong",{children:e("video.modeLabel")}),d.jsx("span",{children:e(`video.mode.${C}`,{n:o})})]}),_?d.jsxs("div",{className:"provider-compat-note",role:"note",children:[d.jsx("strong",{children:e("common.continuity")}),d.jsx("span",{children:_})]}):null,I.length>0&&d.jsx(zm,{ariaLabel:e("video.selectedCameraPresets"),children:I.map(V=>d.jsx(yS,{onRemove:()=>P(V.id),removeLabel:e("common.removeNamed",{name:V.name}),children:V.name},V.id))}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("video.seriesTopicTitle")??"시리즈 주제"}),d.jsx("input",{type:"text",className:"video-topic-input",placeholder:e("video.seriesTopicPlaceholder")??"예: 한국 여행 브이로그",value:S,onChange:V=>v(V.target.value)})]}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("video.durationTitle")}),d.jsx(MS,{values:Qy.filter(V=>V<=k),value:s,ariaLabel:e("video.durationTitle"),onChange:V=>c(V??Qy[0])})]}),d.jsx(xn,{title:e("video.resolutionTitle"),help:j?void 0:e("video.resolution1080Help"),items:$,value:m,onChange:L}),d.jsx(xn,{title:e("video.aspectTitle"),items:UP,value:h,onChange:g}),J&&d.jsx("div",{className:"video-controls__pills",children:d.jsx(tr,{className:"video-controls__pill",items:J.options.map(V=>({value:V,label:V})),value:J.model,onChange:V=>{he(V)},ariaLabel:e("video.plannerModelTitle")})}),d.jsxs("details",{className:"provider-compat-details",style:{marginTop:8},children:[d.jsx("summary",{children:e("common.activePrompt")}),d.jsx("p",{children:Ts})]})]})}const VP="",PS=3;function Jy(e,a,i,o){const s=[],c=new Set;for(const m of[a,...e])!m?.filename||c.has(m.filename)||gt(m)!==o||o&&!/\.(?:mp4|mov)$/i.test(m.filename)||(c.add(m.filename),s.push({filename:m.filename,current:m===a}));for(const m of i){const p=m.filePath,h=o?m.kind==="video":m.kind==="image"||m.kind==="element",g=o?/\.(?:mp4|mov)$/i.test(p??""):/\.(?:png|jpe?g|webp)$/i.test(p??"");!p||!h||!g||c.has(p)||(c.add(p),s.push({filename:p,current:!1,label:m.name||p,source:m.kind==="element"?"element":"asset"}))}return s}function KP(e,a){return e[a]??null}function LS(e,a,i){const o=!a||e.some(s=>s.filename===a);return[{value:VP,label:i("mcp.referenceNone")},...o?[]:[{value:a,label:a,sub:i("mcp.referenceMissing")}],...e.map(s=>({value:s.filename,label:s.label??s.filename,sub:s.current?i("mcp.referenceCurrent"):s.source?i(`mcp.referenceSource.${s.source}`):void 0}))]}function Ou({id:e,label:a,value:i,candidates:o,disabled:s,title:c,help:m,onChange:p,t:h}){return d.jsxs("div",{className:"mcp-reference-slot",children:[d.jsx("label",{className:"mcp-reference-slot__label",htmlFor:e,children:a}),d.jsx(tr,{id:e,items:LS(o,i??"",h),value:i??"",onChange:p,ariaLabel:a,placeholder:h("mcp.referenceSelect"),disabled:s,title:c,portal:!0}),m?d.jsx("p",{className:"option-help",children:m}):null]})}function $P({index:e,images:a,selection:i,disabled:o,onChange:s,t:c}){const m=KP(i.references,e),p=new Set(i.references.filter((E,P)=>P!==e).map(E=>E.filename)),h=m?.dataUrl?{filename:m.filename,current:!1,label:m.displayName??c("mcp.referenceLocalFallback"),source:"local"}:null,g=[...h?[h]:[],...a.filter(E=>!p.has(E.filename))],S=E=>{const P=[...i.references];E?P[e]={filename:E,...m?.tag?{tag:m.tag}:{}}:P.splice(e,1),s({...i,references:P})},v=E=>{if(!m)return;const P=[...i.references],{tag:I,...k}=m;P[e]={...k,...E?{tag:E}:{}},s({...i,references:P})},y=!!(m?.tag&&!fm(m.tag)),x=`mcp-reference-tag-error-${e}`;return d.jsxs("div",{className:"mcp-reference-slot__reference",children:[d.jsx(tr,{items:LS(g,m?.filename??"",c),value:m?.filename??"",onChange:S,ariaLabel:c("mcp.imageReferenceAria",{index:e+1}),placeholder:c("mcp.referenceSelect"),disabled:o,portal:!0}),d.jsxs("div",{children:[d.jsx("input",{type:"text",value:m?.tag??"",onChange:E=>v(E.target.value),"aria-label":c("mcp.referenceTagAria",{index:e+1}),placeholder:c("mcp.referenceTagPlaceholder"),"aria-invalid":y,"aria-describedby":y?x:void 0,maxLength:32,disabled:o||!m}),y?d.jsx("p",{id:x,className:"settings-row__microcopy",role:"alert",children:c("mcp.referenceTagInvalid")}):null]})]})}function YP({selection:e,disabled:a,onChange:i,t:o}){const s=R.useRef(null),[c,m]=R.useState(null),p=e.references.length>=PS,h=async g=>{const S=g.target.files?.[0];if(g.target.value="",!!S){if(!/^image\/(?:png|jpeg|webp)$/i.test(S.type)){m(o("mcp.referenceLocalInvalidType"));return}try{const v=await Tm(S),y=`local:${globalThis.crypto.randomUUID()}`;i({...e,references:[...e.references,{filename:y,displayName:S.name,dataUrl:v}]}),m(null)}catch{m(o("mcp.referenceLocalReadFailed"))}}};return d.jsxs("div",{children:[d.jsx("input",{ref:s,className:"sr-only",type:"file",accept:"image/png,image/jpeg,image/webp",onChange:g=>{h(g)},disabled:a||p}),d.jsx("button",{type:"button",className:"option-btn",onClick:()=>s.current?.click(),disabled:a||p,children:o("mcp.referenceAttachLocal")}),d.jsx("p",{className:"option-help",children:o("mcp.referenceAttachHelp")}),c?d.jsx("p",{className:"settings-row__microcopy",role:"alert",children:c}):null]})}function XP({images:e,selection:a,disabled:i,onChange:o,t:s}){return d.jsxs("div",{className:"mcp-reference-slot",children:[d.jsx("div",{className:"mcp-reference-slot__label",children:s("mcp.imageReferencesLabel")}),Array.from({length:PS},(c,m)=>d.jsx($P,{index:m,images:e,selection:a,disabled:i,onChange:o,t:s},m)),d.jsx(YP,{selection:a,disabled:i,onChange:o,t:s})]})}function QP({inputRoles:e,disabled:a}){const{t:i}=ge(),o=w(v=>v.history),s=w(v=>v.currentImage),c=w(v=>v.assets),m=w(v=>v.mcpReferenceSelection)??Tn(),p=R.useMemo(()=>Jy(o,s,c,!1),[o,s,c]),h=R.useMemo(()=>Jy(o,s,c,!0),[o,s,c]),g=v=>qk(v,w.setState,w.getState),S=m.startFrameFilename?void 0:i("mcp.endFrameNeedsStart");return d.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?d.jsx(Ou,{id:"mcp-start-frame",label:i("mcp.startFrameLabel"),value:m.startFrameFilename,candidates:p,disabled:a,t:i,onChange:v=>g({...m,startFrameFilename:v||null,...v?{}:{endFrameFilename:null}})}):null,e.includes("end_image")?d.jsx(Ou,{id:"mcp-end-frame",label:i("mcp.endFrameLabel"),value:m.endFrameFilename,candidates:p,disabled:a||!m.startFrameFilename,title:S,help:S,t:i,onChange:v=>g({...m,endFrameFilename:v||null})}):null,e.includes("image_references")?d.jsx(XP,{images:p,selection:m,disabled:a,onChange:g,t:i}):null,e.includes("video_references")?d.jsx(Ou,{id:"mcp-video-reference",label:i("mcp.videoReferenceLabel"),value:m.referenceVideoFilename,candidates:h,disabled:a,t:i,help:i("mcp.videoReferenceCostNote"),onChange:v=>g({...m,referenceVideoFilename:v||null})}):null]})}function JP(e){return Array.isArray(e)&&e.includes("image_references")}function WP(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function Mj(e,a){return a.mode!=="trained-id"||!Array.isArray(a.trainedFromRefs)?!1:a.trainedFromRefs.length!==e.length?!0:a.trainedFromRefs.some((i,o)=>e[o]!==i)}function Pj(e){return e.length>3}function ZP({inputRoles:e,disabled:a}){const{t:i}=ge(),o=w(g=>g.assets),s=w(g=>g.mcpCharacterElementId??null),c=w(g=>g.selectedElementIds??[]);if(!JP(e))return null;const m=o.filter(g=>g.kind==="element"&&g.metadata?.elementKind==="character"),p=WP({mentionElementIds:c,characterElementId:s})==="conflict",h=!!a||c.length>0;return d.jsxs("div",{className:"mcp-character-slot","data-testid":"mcp-character-slot",children:[d.jsx("div",{className:"section-title",children:i("mcp.characterSlotLabel")}),d.jsxs("select",{value:s??"",disabled:h,"aria-label":i("mcp.characterSlotLabel"),title:c.length>0?i("mcp.characterSlotConflictHint"):void 0,onChange:g=>w.setState({mcpCharacterElementId:g.target.value||null}),children:[d.jsx("option",{value:"",children:i("mcp.characterSlotNone")}),m.map(g=>d.jsx("option",{value:g.id,children:g.name},g.id))]}),p?d.jsx("p",{className:"option-help",role:"alert",children:i("mcp.characterSlotConflictHint")}):null]})}const Wy=new Set(["duration","resolution","quality","mode"]);function Zy(e){return e.filter((a,i)=>e.findIndex(o=>o===a)===i)}function Vm(e){return e.options&&e.options.length>0?Zy(e.options):e.type==="boolean"?[!0,!1]:e.type!=="number"||e.min===void 0||e.max===void 0?[]:Number.isInteger(e.min)&&Number.isInteger(e.max)&&e.max-e.min<=20?Array.from({length:e.max-e.min+1},(a,i)=>e.min+i):Zy([e.min,...e.default!==void 0?[e.default]:[],e.max])}function ev(e,a){return{duration:a("mcp.durationLabel"),resolution:a("mcp.resolutionLabel"),quality:a("mcp.qualityLabel"),mode:a("mcp.modeLabel"),generateAudio:a("mcp.audioLabel"),generate_audio:a("mcp.audioLabel"),sound:a("mcp.audioLabel")}[e]??e.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}function eL(e,a){return typeof e=="boolean"?a(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function tL(e){return[...Vm(e).filter(i=>typeof i=="number")].sort((i,o)=>i-o)}function nL({parameter:e,value:a,disabled:i,onChange:o}){const{t:s}=ge();if(e.name==="duration"&&e.type==="number"){const p=tL(e);if(p.length>1){const h=ev(e.name,s);return d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:h}),d.jsx(MS,{values:p,value:typeof a=="number"?a:null,defaultValue:typeof e.default=="number"?e.default:void 0,allowAuto:!e.required,disabled:i,ariaLabel:h,onChange:o})]})}}const c=Vm(e);if(c.length===0)return null;const m=ev(e.name,s);return d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:m}),d.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":m,children:[e.required?null:d.jsx("button",{type:"button",className:`option-btn${a===void 0?" active":""}`,"aria-pressed":a===void 0,disabled:i,onClick:()=>o(null),children:s("size.autoLabel")}),c.map(p=>d.jsx("button",{type:"button",className:`option-btn${a===p?" active":""}`,"aria-pressed":a===p,disabled:i,onClick:()=>o(p),title:e.description,children:eL(p,s)},`${typeof p}:${String(p)}`))]})]})}function tv({entries:e,parameters:a,disabled:i,onParameter:o}){return d.jsx(d.Fragment,{children:e.map(s=>d.jsx(nL,{parameter:s,value:a[s.name],disabled:i,onChange:c=>o(s.name,c)},s.name))})}function aL({entry:e,ratio:a,parameters:i,disabled:o,onRatio:s,onParameter:c}){const{t:m}=ge(),p=e.capabilities.aspectRatios.filter(y=>y!=="auto"),h=e.capabilities.parameters.filter(y=>Vm(y).length>0),g=h.filter(y=>Wy.has(y.name)),S=h.filter(y=>!Wy.has(y.name)),v=e.capabilities.inputRoles.some(y=>y==="start_image"||y==="end_image"||y==="image_references"||y==="video_references");return d.jsxs("div",{className:"mcp-model-presets","data-capability-source":e.capabilities.source,children:[p.length>0?d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:m("mcp.aspectRatioLabel")}),d.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":m("mcp.aspectRatioLabel"),children:[d.jsx("button",{type:"button",className:`option-btn${a===null?" active":""}`,"aria-pressed":a===null,disabled:o,onClick:()=>s(null),children:m("size.autoLabel")}),p.map(y=>d.jsx("button",{type:"button",className:`option-btn${a===y?" active":""}`,"aria-pressed":a===y,disabled:o,onClick:()=>s(y),children:y},y))]})]}):null,d.jsx(tv,{entries:g,parameters:i,disabled:o,onParameter:c}),v?d.jsxs("div",{className:"mcp-tool-inputs",children:[d.jsx("div",{className:"section-title",children:m("mcp.toolInputsLabel")}),d.jsx(QP,{inputRoles:e.capabilities.inputRoles,disabled:o}),d.jsx(ZP,{inputRoles:e.capabilities.inputRoles,disabled:o})]}):null,S.length>0?d.jsxs("details",{className:"mcp-advanced-presets",children:[d.jsx("summary",{children:m("mcp.advancedPresetsLabel")}),d.jsx(tv,{entries:S,parameters:i,disabled:o,onParameter:c})]}):null,p.length===0&&h.length===0?d.jsx("p",{className:"option-help",children:m("mcp.providerDefaultsHelp")}):null]})}const rs={image:[],video:[]},oL={};function rL(e){return e.replace(/(^|-)([a-z])/g,(a,i,o)=>`${i}${o.toUpperCase()}`)}function iL({record:e}){const{t:a}=ge(),i=w(_=>_.mcpProvider??null),o=w(_=>_.mcpModel??null),s=w(_=>_.mcpMediaKind??"image"),c=w(_=>_.mcpRatio??null),p=w(_=>_.mcpParameters)??oL,[h,g]=R.useState(rs),[S,v]=R.useState("idle"),[y,x]=R.useState(0),E=e?.executable===!1,P=e?.status.state==="connected";if(R.useEffect(()=>{if(!i||!P){g(rs),v("idle");return}const _=new AbortController;return g(rs),v("loading"),sS(i,_.signal).then(N=>{_.signal.aborted||(g(N),v("ready"))}).catch(N=>{N.name!=="AbortError"&&(_.signal.aborted||(g(rs),v("error")))}),()=>_.abort()},[i,P,y]),!i)return null;const I=s==="video"?h.video:h.image,k=I.find(_=>_.id===o)??null,C=_=>Dk(_,w.setState,w.getState);return d.jsxs("div",{className:"mcp-generation-controls","data-testid":"mcp-generation-controls",children:[d.jsxs("div",{className:"option-group",children:[d.jsxs("div",{className:"section-title mcp-generation-controls__header",children:[d.jsxs("span",{children:[rL(i)," · MCP"]}),d.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>Qs(null,w.setState,w.getState),children:a("mcp.exitLane")})]}),P?null:d.jsx("p",{className:"option-help",children:a("mcp.disconnectedSelection")}),E?d.jsx("p",{className:"option-help",children:a("mcp.higgsfieldLocked")}):null]}),d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"option-group",children:d.jsxs("div",{className:"option-row",children:[d.jsx("button",{type:"button",className:`option-btn${s==="image"?" active":""}`,"aria-pressed":s==="image",onClick:()=>C("image"),children:a("grokMode.image")}),d.jsx("button",{type:"button",className:`option-btn${s==="video"?" active":""}`,"aria-pressed":s==="video",onClick:()=>C("video"),children:a("grokMode.video")})]})}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:a("mcp.modelSectionTitle")}),S==="loading"?d.jsx("p",{className:"option-help",role:"status",children:a("mcp.loadingModels")}):S==="error"?d.jsxs("div",{className:"mcp-catalog-state",role:"alert",children:[d.jsx("span",{children:a("mcp.modelsLoadFailed")}),d.jsx("button",{type:"button",className:"settings-action-btn",onClick:()=>x(_=>_+1),children:a("mcp.retryModels")})]}):S==="ready"&&I.length===0?d.jsx("p",{className:"option-help",children:a("mcp.noModels")}):k?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"mcp-selected-model",children:[d.jsx("strong",{children:k.label}),k.description?d.jsx("span",{children:k.description}):null]}),d.jsx(aL,{entry:k,ratio:c,parameters:p,disabled:E,onRatio:_=>Fk(_,w.setState),onParameter:(_,N)=>zk(_,N,w.setState,w.getState)})]}):d.jsx("p",{className:"option-help",children:a(o?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}const lL=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],is=[{value:"1:1",label:"1:1"},{value:"2:3",label:"2:3"},{value:"3:2",label:"3:2"},{value:"3:4",label:"3:4"},{value:"4:3",label:"4:3"},{value:"4:5",label:"4:5"},{value:"5:4",label:"5:4"},{value:"9:16",label:"9:16"},{value:"16:9",label:"16:9"},{value:"21:9",label:"21:9"}],sL=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Is={"1:1":{512:"512x512","1K":"1024x1024","2K":"2048x2048","4K":"4096x4096"},"2:3":{512:"424x632","1K":"848x1264","2K":"1696x2528","4K":"3392x5056"},"3:2":{512:"632x424","1K":"1264x848","2K":"2528x1696","4K":"5056x3392"},"3:4":{512:"448x600","1K":"896x1200","2K":"1792x2400","4K":"3584x4800"},"4:3":{512:"600x448","1K":"1200x896","2K":"2400x1792","4K":"4800x3584"},"4:5":{512:"464x576","1K":"928x1152","2K":"1856x2304","4K":"3712x4608"},"5:4":{512:"576x464","1K":"1152x928","2K":"2304x1856","4K":"4608x3712"},"9:16":{512:"384x688","1K":"768x1376","2K":"1536x2752","4K":"3072x5504"},"16:9":{512:"688x384","1K":"1376x768","2K":"2752x1536","4K":"5504x3072"},"21:9":{512:"792x168","1K":"1584x672","2K":"3168x1344","4K":"6336x2688"}};function cL(e){for(const[a,i]of Object.entries(Is))for(const[o,s]of Object.entries(i))if(s===e)return{ratio:a,res:o};return null}function dL(e,a){const i=e/a;let o="1:1",s=1/0;const c=[...Object.keys(Is),"1:8","8:1","1:4","4:1"];for(const h of c){const[g,S]=h.split(":").map(Number),v=Math.abs(i-g/S);v<s&&(s=v,o=h)}const m=Math.max(e,a),p=m<=512?"512":m<=1024?"1K":m<=2048?"2K":"4K";return{ratio:o,res:p}}function OS(){const{t:e}=ge(),a=w(ie=>ie.provider),i=w(ie=>ie.quality),o=w(ie=>ie.setQuality),s=w(ie=>ie.format),c=w(ie=>ie.setFormat),m=w(ie=>ie.moderation),p=w(ie=>ie.setModeration),h=w(ie=>ie.multimode),g=w(ie=>ie.setMultimode),S=w(ie=>ie.imageModel),v=w(ie=>ie.setImageModel),y=w(ie=>ie.selectVideoModel),x=w(ie=>ie.sizePreset),E=w(ie=>ie.customW),P=w(ie=>ie.customH),I=w(ie=>ie.setSizePreset),k=w(ie=>ie.setCustomSize),C=w(ie=>ie.uiMode),_=w(ie=>ie.videoModelSelected),N=w(ie=>ie.mcpProvider??null),{providers:j}=cS(),$=C==="classic",L=a==="grok"||a==="grok-api",J=a==="agy",re=a==="gemini-api",he=J||re,V=L||he,ee=x==="custom"?`${E}x${P}`:"1024x1024",oe=re&&x==="auto",Ne=re&&!oe?cL(ee):null,ne=Ne??{ratio:"",res:""},H=re&&!oe&&x==="custom"&&!Ne,ae=S==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[ce,be]=R.useState(!1),[Se,T]=R.useState(String(E)),[F,W]=R.useState(String(P)),U=(ie,lt)=>{const at=Is[ie||"1:1"]?.[lt||"1K"]||"1024x1024",[st,bt]=at.split("x").map(Number);be(!1),I("custom"),k(st,bt)},le=()=>{const ie=Number(Se),lt=Number(F);!Number.isFinite(ie)||!Number.isFinite(lt)||ie<=0||lt<=0||(I("custom"),k(ie,lt),be(!1))},pe=[{value:"low",label:e("quality.lowLabel"),sub:e("quality.lowSub")},{value:"medium",label:e("quality.mediumLabel"),sub:e("quality.mediumSub")},{value:"high",label:e("quality.highLabel"),sub:e("quality.highSub")}],xe=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],Oe=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],Re=L?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:J?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:re?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},Ze=ie=>{ie==="video"?y("grok-imagine-video"):v(S)};return N?d.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[d.jsx(Xy,{mcpProviders:j}),d.jsx(iL,{record:j.find(ie=>ie.id===N)??null})]}):d.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[d.jsx(Xy,{mcpProviders:j}),d.jsxs("details",{className:"provider-compat-details",children:[d.jsx("summary",{children:Re.title}),d.jsx("p",{children:Re.body})]}),L&&d.jsx("div",{className:"option-group grok-mode-toggle",children:d.jsxs("div",{className:"option-row",children:[d.jsx("button",{type:"button",className:`option-btn${_?"":" active"}`,onClick:()=>Ze("image"),children:e("grokMode.image")}),d.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>Ze("video"),children:e("grokMode.video")})]})}),_?d.jsx(BP,{}):d.jsxs(d.Fragment,{children:[J?null:L?d.jsxs(d.Fragment,{children:[d.jsx(zP,{}),d.jsx(DP,{})]}):re?d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("quality.grokModelTitle"),items:Oe,value:ae,onChange:v}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")||"Aspect Ratio"}),[is.slice(0,3),is.slice(3,6),is.slice(6,8),is.slice(8)].map((ie,lt)=>d.jsx("div",{className:"option-row",children:ie.map(at=>d.jsx("button",{type:"button",className:`option-btn${ne.ratio===at.value?" active":""}`,onClick:()=>U(at.value,ne.res),children:at.label},at.value))},lt))]}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("size.grokResolutionTitle")||"Resolution"}),d.jsx("div",{className:"gemini-resolution-grid",children:sL.map(ie=>d.jsxs("button",{type:"button",className:`option-btn${ne.res===ie.value?" active":""}`,onClick:()=>U(ne.ratio,ie.value),children:[d.jsx("span",{children:ie.label}),d.jsx("br",{}),d.jsx("small",{children:Is[ne.ratio]?.[ie.value]?.replace("x","×")||""})]},ie.value))})]}),d.jsxs("div",{className:"option-group",children:[d.jsxs("div",{className:"option-row",children:[d.jsxs("button",{type:"button",className:`option-btn${oe?" active":""}`,onClick:()=>{be(!1),I("auto")},children:[e("size.autoLabel"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:e("size.autoSub")})]}),d.jsxs("button",{type:"button",className:`option-btn${H||ce?" active":""}`,onClick:()=>be(ie=>!ie),children:[e("size.customPlus"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),ce?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"option-row size-picker__custom-row",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:Se,onChange:ie=>T(ie.target.value.replace(/\D/g,"")),placeholder:e("size.width")}),d.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:F,onChange:ie=>W(ie.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(Se)>0&&Number(F)>0?d.jsxs("div",{className:"size-picker__preview",children:[d.jsx("span",{children:e("size.normalizedPreview")}),d.jsx("strong",{children:(()=>{const ie=dL(Number(Se),Number(F));return`${ie.ratio} · ${ie.res}`})()})]}):null,d.jsx("button",{type:"button",className:"size-picker__save",onClick:le,children:e("settings.apiKeys.save")})]}):null]})]}):d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("quality.title"),items:pe,value:i,onChange:o}),d.jsx(CP,{})]}),V?null:d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("format.title"),items:lL,value:s,onChange:c}),d.jsx(xn,{title:e("moderation.title"),items:xe,value:m,onChange:p}),d.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),$&&!he&&d.jsx("div",{className:"option-group multimode-toggle",children:d.jsxs("button",{type:"button",className:`multimode-toggle__button${h?" active":""}`,"aria-pressed":h,title:e("multimode.tooltip"),onClick:()=>g(!h),children:[d.jsx("span",{children:e("multimode.label")}),d.jsx("span",{children:e("multimode.shortHint")})]})}),he?null:d.jsx(wP,{}),d.jsx(MP,{})]})]})}const uL=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-DCtxfzy1.js"),[]).then(e=>({default:e.PromptLibraryPanel}))),mL=R.lazy(()=>$t(()=>import("./PromptBuilderPanel-Bl5-fDQs.js"),[]).then(e=>({default:e.PromptBuilderPanel}))),pL=R.lazy(()=>$t(()=>import("./GenerationRequestLogPanel-BZZJh4w_.js"),[]).then(e=>({default:e.GenerationRequestLogPanel})));function fL(){const e=w(k=>k.rightPanelOpen),a=w(k=>k.toggleRightPanel),i=w(k=>k.promptLibraryOpen),o=w(k=>k.setPromptLibraryOpen),s=w(k=>k.promptBuilderOpen),c=w(k=>k.togglePromptBuilder),m=w(k=>k.workspaceProfile),{t:p}=ge(),[h,g]=R.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);R.useEffect(()=>{if(typeof window>"u")return;const k=window.matchMedia("(max-width: 800px)"),C=()=>g(k.matches);return k.addEventListener("change",C),()=>k.removeEventListener("change",C)},[]);const[S,v]=R.useState(!1),y=BN(m)&&!h,x=h?e:!0,E=uo(h&&e,a),P=S?"log":s&&y?"builder":i?"library":"settings",I=k=>{v(k==="log"),k==="builder"?(s||c(),i&&o(!1)):k==="library"?(s&&c(),i||o(!0)):(s&&c(),i&&o(!1))};return d.jsxs(d.Fragment,{children:[h&&e?d.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":p("panel.closeSettings"),onClick:a}):null,d.jsxs("aside",{ref:E,className:`right-panel${e?"":" collapsed"}${h&&x?" drawer-open":""}`,"aria-label":p("panel.detailSettings"),"aria-modal":h&&e?"true":void 0,role:h&&e?"dialog":void 0,tabIndex:h?-1:void 0,children:[!h&&d.jsx("button",{type:"button",className:"right-panel-toggle","aria-expanded":e,"aria-controls":"right-panel-body",onClick:a,title:p(e?"panel.toggleHide":"panel.toggleShow"),children:e?">":"<"}),d.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!e,children:[d.jsxs("div",{className:"right-panel-tabs",role:"tablist","aria-label":p("panel.detailSettings"),children:[y?d.jsx("button",{type:"button",role:"tab","aria-selected":P==="builder","aria-controls":"right-panel-tab-builder",title:p("promptBuilder.title"),className:`right-panel-tabs__button${P==="builder"?" active":""}`,onClick:()=>I("builder"),children:p("promptBuilder.title")}):null,d.jsx("button",{type:"button",role:"tab","aria-selected":P==="log","aria-controls":"right-panel-tab-log",title:p("generationLog.title"),className:`right-panel-tabs__button${y?"":" right-panel-tabs__button--full"}${P==="log"?" active":""}`,onClick:()=>I("log"),children:p("generationLog.title")}),d.jsx("button",{type:"button",role:"tab","aria-selected":P==="library","aria-controls":"right-panel-tab-library",title:p("promptLibrary.title"),className:`right-panel-tabs__button right-panel-tabs__button--full${P==="library"?" active":""}`,onClick:()=>I("library"),children:p("promptLibrary.title")}),d.jsx("button",{type:"button",role:"tab","aria-selected":P==="settings","aria-controls":"right-panel-tab-settings",title:p("panel.detailSettings"),className:`right-panel-tabs__button right-panel-tabs__button--full${P==="settings"?" active":""}`,onClick:()=>I("settings"),children:p("panel.detailSettings")})]}),P==="builder"&&y?d.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(mL,{variant:"sidebar"})})}):P==="library"?d.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(uL,{variant:"embedded"})})}):P==="log"?d.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(pL,{})})}):d.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:d.jsx(OS,{})})]})]})]})}function gL(e){const a=e.currentTarget;if(a.scrollWidth<=a.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const o=a.scrollLeft<=0,s=a.scrollLeft+a.clientWidth>=a.scrollWidth-1,c=e.deltaY<0,m=e.deltaY>0;c&&o||m&&s||(e.preventDefault(),a.scrollLeft+=e.deltaY)}function hL({id:e}){const{t:a}=ge();return d.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":a("common.generating")},e)}function yL({id:e,count:a}){const{t:i}=ge(),o=Math.min(a,4);return d.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":i("history.generatingCollection",{count:a}),children:Array.from({length:o},(s,c)=>d.jsx("div",{className:"collection-mini collection-mini--skeleton"},c))},`coll-${e}`)}function vL({sequenceId:e,images:a}){const i=w(p=>p.showHistorySequence),s=w(p=>p.multimodePreviewFlightId)===`history:${e}`,c=a.slice(0,4),{t:m}=ge();return d.jsx("button",{type:"button",className:`history-thumb history-thumb--collection${s?" active":""}`,onClick:()=>i(e),"aria-label":m("common.imageCollection",{n:a.length}),children:c.map((p,h)=>!p.thumb&&(kn(p.url)||kn(p.image))?d.jsx(nr,{className:"collection-mini"},h):d.jsx("img",{className:"collection-mini",src:p.thumb||p.url||p.image,alt:"",loading:"lazy",decoding:"async"},h))})}function bL(e){const a=R.useRef(null),i=R.useRef(new Map),[o,s]=R.useState(()=>new Set);R.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const m=new IntersectionObserver(p=>{const h=p.filter(g=>g.isIntersecting);h.length!==0&&s(g=>{const S=new Set(g);for(const v of h){const y=v.target.dataset.historyLazyKey;y&&S.add(y)}return S})},{root:e,rootMargin:"0px 200% 0px 200%"});a.current=m;for(const p of i.current.values())m.observe(p);return()=>{m.disconnect(),a.current=null}},[e]);const c=R.useCallback((m,p)=>{const h=i.current.get(m);h&&h!==p&&a.current?.unobserve(h),p?(i.current.set(m,p),a.current?.observe(p)):i.current.delete(m)},[]);return{visibleKeys:o,register:c,supported:typeof IntersectionObserver<"u"}}function SL(){const e=w(C=>C.history),a=w(C=>C.currentImage),i=w(C=>C.historyStripLayout),o=w(C=>C.selectHistory),s=w(C=>C.openGallery),c=w(C=>C.inFlight),m=w(C=>C.multimodeSequences),p=R.useRef({}),[h,g]=R.useState(null),S=bL(h),{t:v}=ge(),y=a?Ot(a):null,x=R.useMemo(()=>hs(e.filter(mi)),[e]),E=R.useMemo(()=>{const C=[];for(const _ of c){const N=m[_.id];if(_.kind==="multimode"&&N){C.push({type:"collection-skeleton",id:_.id,count:N.requested});for(let j=0;j<N.requested;j++)N.images[j]||C.push({type:"skeleton",id:`${_.id}_${j}`,count:1})}else C.push({type:"skeleton",id:_.id,count:1})}return C},[c,m]),{completedSequences:P,sequenceFirstKeys:I}=R.useMemo(()=>{const C=new Map,_=new Set;for(const N of x)if(N.sequenceId&&(N.sequenceTotalRequested??0)>1){C.has(N.sequenceId)||_.add(Ot(N));const j=C.get(N.sequenceId)||[];j.push(N),C.set(N.sequenceId,j)}return{completedSequences:C,sequenceFirstKeys:_}},[x]);R.useEffect(()=>{y&&p.current[y]?.scrollIntoView({block:"nearest",inline:"nearest"})},[y,x]);const k=(C,_)=>{const N=S.supported?S.visibleKeys.has(C):!0;return d.jsx("div",{ref:j=>{p.current[C]=j,S.register(C,j)},className:"history-thumb","data-history-lazy-key":C,"aria-hidden":N?void 0:!0,style:{padding:0,overflow:"hidden"},children:N?_:null},C)};return d.jsxs("div",{ref:g,className:`history-strip${i==="horizontal"?" history-strip--horizontal":""}${i==="sidebar"?" history-strip--sidebar":""}`,onWheel:gL,"data-layout":i,children:[d.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:s,"aria-label":v("history.openGalleryAria"),title:v("history.openGalleryTitle"),children:d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),E.map(C=>C.type==="collection-skeleton"?d.jsx(yL,{id:C.id,count:C.count},`coll-${C.id}`):d.jsx(hL,{id:C.id},C.id)),x.map(C=>{const _=Ot(C),N=y===_;if(C.sequenceId&&P.has(C.sequenceId)&&I.has(_)){const j=P.get(C.sequenceId);return[k(`coll-${C.sequenceId}`,d.jsx(vL,{sequenceId:C.sequenceId,images:j})),...j.map($=>{const L=Ot($),J=y===L;return gt($)?k(L,d.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${J?" active":""}`,onClick:()=>o($),draggable:!0,onDragStart:re=>{re.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi($))),re.dataTransfer.effectAllowed="copy"},children:[$.thumb?d.jsx("img",{src:$.thumb,alt:"",loading:"lazy",decoding:"async"}):d.jsx(nr,{}),d.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):k(L,d.jsx("img",{src:$.thumb||$.url||$.image,alt:"",className:`history-thumb history-thumb--fade-in${J?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>o($),draggable:!0,onDragStart:re=>{re.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:$.url||$.image,filename:$.filename})),re.dataTransfer.effectAllowed="copy"}}))})]}return C.sequenceId&&P.has(C.sequenceId)&&!I.has(_)?null:gt(C)?k(_,d.jsxs("div",{className:`history-thumb history-thumb--video${N?" active":""}`,onClick:()=>o(C),draggable:!0,onDragStart:j=>{j.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi(C))),j.dataTransfer.effectAllowed="copy"},children:[C.thumb?d.jsx("img",{src:C.thumb,alt:"",loading:"lazy",decoding:"async"}):d.jsx(nr,{}),d.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):k(_,d.jsx("img",{src:C.thumb||C.url||C.image,alt:"",className:`history-thumb${N?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>o(C),draggable:!0,onDragStart:j=>{j.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:C.url||C.image,filename:C.filename})),j.dataTransfer.effectAllowed="copy"}}))})]})}const nv=3e3;function xL(){const{t:e}=ge(),a=w(g=>g.toastLog),i=w(g=>g.errorCardLog),o=w(g=>g.dismissToast),s=w(g=>g.dismissErrorCard),[c,m]=R.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),p=R.useRef(new Map);R.useEffect(()=>{const g=()=>m(document.visibilityState==="visible");return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),window.addEventListener("blur",g),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g),window.removeEventListener("blur",g)}},[]),R.useEffect(()=>{const g=p.current,S=new Set([...a.map(v=>`toast-${v.id}`),...i.map(v=>`error-card-${v.id}`)]);for(const[v,y]of g)(!S.has(v)||!c)&&(clearTimeout(y),g.delete(v));if(c){for(const v of a){const y=`toast-${v.id}`;if(g.has(y))continue;const x=setTimeout(()=>{g.delete(y),o(v.id)},nv);g.set(y,x)}for(const v of i){const y=`error-card-${v.id}`;if(g.has(y))continue;const x=setTimeout(()=>{g.delete(y),s(v.id)},nv);g.set(y,x)}}},[s,o,i,c,a]),R.useEffect(()=>()=>{for(const g of p.current.values())clearTimeout(g);p.current.clear()},[]);const h=[...a.map(g=>({kind:"toast",id:g.id,key:`toast-${g.id}`,message:g.message,error:g.error,createdAt:g.createdAt,cta:void 0,cardKey:void 0})),...i.map(g=>{const S=eo[g.code],v=g.cardKey??S?.cardKey??"errorCard.unknown",y=e(`${v}.title`),x=e(`${v}.body`),E=g.cta??S?.cta;return{kind:"error-card",id:g.id,key:`error-card-${g.id}`,message:g.fallbackMessage?`${y}: ${x} ${g.fallbackMessage}`:`${y}: ${x}`,error:!0,createdAt:g.createdAt,cta:E,cardKey:v}})].sort((g,S)=>g.createdAt-S.createdAt).slice(-5);return h.length===0?null:d.jsx("div",{className:"toast-stack","aria-live":"polite","aria-relevant":"additions removals",children:h.map(g=>{const S=["toast","visible",g.error?"error":"",g.kind==="error-card"?"toast--card":""].filter(Boolean).join(" ");return d.jsxs("div",{className:S,role:g.error?"alert":"status",children:[d.jsx("span",{className:"toast__message",children:g.message}),g.kind==="error-card"&&(g.cta==="reauth"||g.cta==="reload")?d.jsx("button",{type:"button",className:"toast__cta",onClick:()=>{g.cta==="reauth"&&w.getState().openSettings("providers"),g.cta==="reload"&&window.location.reload()},children:e(`${g.cardKey??"errorCard.unknown"}.cta`)}):null,d.jsx("button",{type:"button",className:"toast__dismiss","aria-label":e("common.dismiss"),onClick:()=>g.kind==="error-card"?s(g.id):o(g.id),children:d.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:d.jsx("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round"})})})]},g.key)})})}function AL(){return null}function TL(e,a="en"){if(!e)return"earlier";const i=new Date(e);if(Number.isNaN(i.getTime()))return"earlier";const s=Math.floor((new Date().getTime()-i.getTime())/864e5);return s===0?"today":s===1?"yesterday":s<7?"thisWeek":new Intl.DateTimeFormat(a,{year:"numeric",month:"short",day:"numeric"}).format(i)}function CL(e,a,i){async function o(m){if(m.setId)try{await vt.getState().loadSet(m.setId),w.getState().setUIMode("card-news"),e()}catch{a(i("gallery.openCardNewsSetFailed"),!0)}}async function s(m,p){if(p.stopPropagation(),!m.setId)return;const h=`generated/cardnews/${m.setId}`;try{await navigator.clipboard?.writeText(h),a(i("gallery.cardNewsPathCopied"))}catch{a(i("toast.copyFailed"),!0)}}function c(m,p){p.stopPropagation(),m.setId&&window.open(b2(m.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:o,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:c}}const wL=["ArrowLeft","ArrowRight","Home","End"];function IL(){return R.useCallback(e=>{if(!wL.includes(e.key))return;const a=e.currentTarget,i=Array.from(a.querySelectorAll("[role='tab']")).filter(p=>!p.hasAttribute("disabled"));if(i.length===0)return;e.preventDefault();const o=document.activeElement,s=o?i.indexOf(o):-1,c=e.key==="Home"?0:e.key==="End"?i.length-1:s<0?0:(s+(e.key==="ArrowRight"?1:-1)+i.length)%i.length,m=i[c];m?.focus(),m?.click()},[])}function ju({className:e,ariaLabel:a,tabs:i,value:o,onChange:s}){const c=IL(),m=i.find(h=>h.value===o),p=m&&!m.disabled?m.value:i.find(h=>!h.disabled)?.value;return d.jsx("div",{className:e,role:"tablist","aria-label":a,onKeyDown:c,children:i.map(h=>d.jsx("button",{type:"button",role:"tab","aria-selected":h.value===o,tabIndex:h.value===p?0:-1,className:h.value===o?"active":"",onClick:()=>s(h.value),disabled:h.disabled,children:h.label},h.value))})}function EL({item:e,onOpen:a,onCopyPath:i,onDownloadManifest:o}){const{t:s}=ge(),m=e.cards?.find(p=>p.headline)?.headline||e.headline||s("gallery.cardNewsSet");return d.jsxs(d.Fragment,{children:[d.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>a(e),title:m,children:[e.image?d.jsx("img",{src:e.image,alt:m,loading:"lazy"}):null,d.jsxs("div",{className:"gallery__caption",children:[d.jsx("small",{children:s("gallery.cardNewsSet")}),d.jsx("span",{className:"gallery__caption-text",children:m})]}),d.jsx("div",{className:"gallery-card-news-strip",children:(e.cards||[]).slice(0,5).map((p,h)=>d.jsxs("span",{children:[p.url?d.jsx("img",{src:p.url,alt:p.headline??"",loading:"lazy"}):null,d.jsx("em",{children:p.cardOrder??h+1})]},`${p.url}-${h}`))})]}),d.jsxs("div",{className:"gallery-card-news-actions",children:[d.jsx("span",{children:s("gallery.cardNewsCount",{n:e.cards?.length??0})}),d.jsx("button",{type:"button",onClick:()=>a(e),children:s("gallery.openCardNewsSet")}),d.jsx("button",{type:"button",onClick:p=>i(e,p),children:s("gallery.copyCardNewsSetPath")}),d.jsx("button",{type:"button",onClick:p=>o(e,p),children:s("gallery.downloadCardNewsManifest")})]})]})}const RL=[{id:"animate",labelKey:"chain.animate",available:e=>!!e.filename&&!gt(e)},{id:"edit",labelKey:"chain.edit",available:e=>!!e.filename&&!gt(e)},{id:"useAsRef",labelKey:"chain.useAsRef",available:e=>!!(e.image||e.url)},{id:"rebake",labelKey:"chain.rebake",available:e=>!!(e.prompt||e.filename)},{id:"saveToAssets",labelKey:"chain.saveToAssets",available:e=>!!e.filename},{id:"saveAsElement",labelKey:"chain.saveAsElement",available:e=>!!e.filename&&!gt(e)}];async function NL(e,a,i,o){const s=i();switch(e){case"animate":{if(!a.filename)return;try{await s.animateImage(a.filename,a.prompt??void 0)&&s.showToast(o("toast.animateDone"))}catch(c){s.showToast(c instanceof Error?c.message:o("toast.animateFailed"),!0)}break}case"edit":{s.selectHistory(a),s.openCanvas();break}case"useAsRef":{const c=a.url||a.image;if(!c)return;try{const p=await(await fetch(c)).blob(),h=new File([p],a.filename||"reference.png",{type:p.type});await s.addReferences([h]),s.showToast(o("chain.refAdded"))}catch{s.showToast(o("chain.refFailed"),!0)}break}case"rebake":{try{const{continueFromItem:m}=await $t(async()=>{const{continueFromItem:h}=await Promise.resolve().then(()=>UM);return{continueFromItem:h}},void 0),p=await m(a);s.showToast(o(p.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))}catch{s.showToast(o("toast.forkFailed"),!0)}const c=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');c&&(c.focus(),c.setSelectionRange(c.value.length,c.value.length));break}case"saveToAssets":{try{const c=await s.saveToAssets(a);s.showToast(o(c?"chain.savedToAssets":"chain.saveToAssetsFailed"),!c)}catch{s.showToast(o("chain.saveToAssetsFailed"),!0)}break}case"saveAsElement":{try{const c=await s.saveAsElement?.(a);s.showToast(o(c?"chain.savedToAssets":"chain.saveToAssetsFailed"),!c)}catch{s.showToast(o("chain.saveToAssetsFailed"),!0)}break}}}function kL(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function _L(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function ML(e){return{modelLabel:Cv(e.model,e.provider),derivation:kL(e),sourceLabel:_L(e)}}function PL(e){return!e.modelLabel&&!e.derivation}function LL({view:e,size:a="sm"}){const{t:i}=ge();return PL(e)?null:d.jsxs("span",{className:`provenance-chip provenance-chip--${a}`,children:[e.modelLabel?d.jsx("span",{className:"provenance-chip__model",children:e.modelLabel}):null,e.derivation?d.jsx("span",{className:"provenance-chip__derivation",children:i(`provenance.${e.derivation}`)}):null]})}function OL({id:e}){switch(e){case"animate":return d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})});case"edit":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),d.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]});case"useAsRef":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),d.jsx("polyline",{points:"17 8 12 3 7 8"}),d.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]});case"rebake":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]});case"saveToAssets":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),d.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),d.jsx("path",{d:"M10 12h4"})]})}}function jL({item:e,active:a,itemRef:i,onSelect:o,onDelete:s,onToggleFavorite:c,favoriteBusy:m=!1,t:p}){const h=R.useMemo(()=>RL.filter(v=>v.available(e)),[e]),g=R.useCallback(async(v,y)=>{y.stopPropagation(),await NL(v,e,()=>{const x=w.getState();return{animateImage:x.animateImage,openCanvas:x.openCanvas,selectHistory:x.selectHistory,addReferences:x.addReferences,showToast:x.showToast,saveToAssets:x.saveToAssets}},p)},[e,p]),S=v=>{v.dataTransfer.setData("application/ima2-ref",JSON.stringify(gt(e)?yi(e):{image:e.url||e.image,filename:e.filename})),v.dataTransfer.effectAllowed="copy"};return d.jsxs("div",{ref:i,className:`gallery__tile-wrap${a?" gallery__tile-wrap--active":""}${e.isFavorite?" gallery__tile-wrap--favorite":""}`,children:[d.jsxs("button",{type:"button",className:`gallery__tile${a?" gallery__tile--active":""}`,onClick:()=>o(e),title:e.prompt??"",draggable:!0,onDragStart:S,children:[gt(e)?d.jsxs("div",{className:"gallery__tile-video-wrap",children:[e.thumb?d.jsx("img",{src:e.thumb,alt:e.prompt??p("gallery.imageAltFallback"),loading:"lazy",decoding:"async",className:"gallery__tile-video"}):d.jsx(nr,{className:"gallery__tile-video"}),d.jsx("span",{className:"gallery__play-badge","aria-hidden":"true",children:"▶"})]}):d.jsx("img",{src:e.thumb||e.image,alt:e.prompt??p("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),e.prompt&&d.jsx("div",{className:"gallery__caption",children:d.jsx("span",{className:"gallery__caption-text",children:e.prompt})})]}),h.length>0?d.jsx("div",{className:"gallery__chain-overlay",role:"group","aria-label":p("chain.ariaLabel"),children:h.map(v=>d.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:y=>{g(v.id,y)},title:p(v.labelKey),"aria-label":p(v.labelKey),children:d.jsx(OL,{id:v.id})},v.id))}):null,e.filename&&c&&d.jsx(vS,{variant:"gallery",active:!!e.isFavorite,busy:m,label:e.isFavorite?p("gallery.unfavoriteAria"):p("gallery.favoriteAria"),onToggle:()=>c(e)}),e.filename&&d.jsx("button",{type:"button",className:"gallery__delete",onClick:v=>s(e,v),title:p("gallery.deleteTitle"),"aria-label":p("gallery.deleteAria"),children:"×"}),d.jsx(LL,{view:ML(e)})]})}function GL(e,a,i){const o=new Array(e);return new Proxy(o,{get(s,c,m){if(typeof c=="string"){const p=c.charCodeAt(0);if(p>=48&&p<=57){const h=+c;if(Number.isInteger(h)&&h>=0&&h<e){let g=s[h];if(!g){const S=a[h*2];g=s[h]={index:h,key:i(h),start:S,size:a[h*2+1],end:S+a[h*2+1],lane:0}}return g}}if(c==="length")return e}return Reflect.get(s,c,m)}})}function Qo(e,a,i){let o=i.initialDeps??[],s,c=!0;function m(){const p=e();return(p.length!==o.length||p.some((g,S)=>o[S]!==g))&&(o=p,s=a(...p),i?.onChange&&!(c&&i.skipInitialOnChange)&&i.onChange(s),c=!1),s}return m.updateDeps=p=>{o=p},m}function av(e,a){if(e===void 0)throw new Error("Unexpected undefined");return e}const DL=(e,a)=>Math.abs(e-a)<1.01,FL=(e,a,i)=>{let o;return function(...s){e.clearTimeout(o),o=e.setTimeout(()=>a.apply(this,s),i)}};let di;const Gu=()=>{if(di!==void 0)return di;if(typeof navigator>"u")return di=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return di=!0;const e=navigator.maxTouchPoints;return di=navigator.platform==="MacIntel"&&e!==void 0&&e>0},ov=e=>{const{offsetWidth:a,offsetHeight:i}=e;return{width:a,height:i}},zL=e=>e,qL=e=>{const a=Math.max(e.startIndex-e.overscan,0),o=Math.min(e.endIndex+e.overscan,e.count-1)-a+1,s=new Array(o);for(let c=0;c<o;c++)s[c]=a+c;return s},UL=(e,a)=>{const i=e.scrollElement;if(!i)return;const o=e.targetWindow;if(!o)return;const s=m=>{const{width:p,height:h}=m;a({width:Math.round(p),height:Math.round(h)})};if(s(ov(i)),!o.ResizeObserver)return()=>{};const c=new o.ResizeObserver(m=>{const p=()=>{const h=m[0];if(h?.borderBoxSize){const g=h.borderBoxSize[0];if(g){s({width:g.inlineSize,height:g.blockSize});return}}s(ov(i))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(p):p()});return c.observe(i,{box:"border-box"}),()=>{c.unobserve(i)}},Es={passive:!0},HL=typeof window>"u"?!0:"onscrollend"in window,BL=(e,a,i)=>{const o=e.scrollElement;if(!o)return;const s=e.targetWindow;if(!s)return;const c=e.options.useScrollendEvent&&HL;let m=0;const p=c?null:FL(s,()=>a(m,!1),e.options.isScrollingResetDelay),h=v=>()=>{m=i(o),p?.(),a(m,v)},g=h(!0),S=h(!1);return o.addEventListener("scroll",g,Es),c&&o.addEventListener("scrollend",S,Es),()=>{o.removeEventListener("scroll",g),c&&o.removeEventListener("scrollend",S)}},VL=(e,a)=>BL(e,a,i=>{const{horizontal:o,isRtl:s}=e.options;return o?i.scrollLeft*(s&&-1||1):i.scrollTop}),KL=(e,a,i)=>{if(i.options.useCachedMeasurements){const o=i.indexFromElement(e),s=i.options.getItemKey(o);return i.itemSizeCache.get(s)??i.options.estimateSize(o)}if(a?.borderBoxSize){const o=a.borderBoxSize[0];if(o)return Math.round(o[i.options.horizontal?"inlineSize":"blockSize"])}if(!a){const o=i.indexFromElement(e),s=i.options.getItemKey(o),c=i.itemSizeCache.get(s);if(c!==void 0)return c}return e[i.options.horizontal?"offsetWidth":"offsetHeight"]},$L=(e,{adjustments:a=0,behavior:i},o)=>{var s,c;(c=(s=o.scrollElement)==null?void 0:s.scrollTo)==null||c.call(s,{[o.options.horizontal?"left":"top"]:e+a,behavior:i})},YL=$L;class XL{constructor(a){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var i,o,s;return((s=(o=(i=this.targetWindow)==null?void 0:i.performance)==null?void 0:o.now)==null?void 0:s.call(o))??Date.now()},this.observer=(()=>{let i=null;const o=()=>i||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:i=new this.targetWindow.ResizeObserver(s=>{s.forEach(c=>{const m=()=>{const p=c.target,h=this.indexFromElement(p);if(!p.isConnected){this.observer.unobserve(p);for(const[g,S]of this.elementsCache)if(S===p){this.elementsCache.delete(g);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(p,c,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()})}));return{disconnect:()=>{var s;(s=o())==null||s.disconnect(),i=null},observe:s=>{var c;return(c=o())==null?void 0:c.observe(s,{box:"border-box"})},unobserve:s=>{var c;return(c=o())==null?void 0:c.unobserve(s)}}})(),this.range=null,this.setOptions=i=>{var o,s;const c={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:zL,rangeExtractor:qL,onChange:()=>{},measureElement:KL,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const y in i){const x=i[y];x!==void 0&&(c[y]=x)}const m=this.options;let p=null,h=null,g=!1;if(m!==void 0&&m.enabled&&c.enabled&&c.anchorTo==="end"&&this.scrollElement!==null){const y=m.count,x=c.count,E=this.getMeasurements(),P=y>0?((o=E[0])==null?void 0:o.key)??m.getItemKey(0):null,I=y>0?((s=E[y-1])==null?void 0:s.key)??m.getItemKey(y-1):null;if(x!==y||y>0&&x>0&&(c.getItemKey(0)!==P||c.getItemKey(x-1)!==I)){g=!0;const _=y>0?this.getVirtualItemForOffset(this.getScrollOffset())??E[0]:null;_&&(p=[_.key,this.getScrollOffset()-_.start]);const N=c.followOnAppend===!0?"auto":c.followOnAppend||null;N&&x>y&&this.isAtEnd(m.scrollEndThreshold)&&(y===0||c.getItemKey(x-1)!==I)&&(h=N)}}this.options=c,g&&(this.pendingMin=0,this.itemSizeCacheVersion++);let S=!1,v=0;if(p&&this.scrollOffset!==null){const[y,x]=p,E=this.getMeasurements(),{count:P,getItemKey:I}=this.options;let k=0;for(;k<P&&I(k)!==y;)k++;if(k<P){const C=E[k];if(C){const _=Math.max(0,C.start+x);_!==this.scrollOffset&&(v=_-this.scrollOffset,this.scrollOffset=_,S=!0)}}}(S||h)&&(this.pendingScrollAnchor=[S?p[0]:null,S?p[1]:0,h,v])},this.notify=i=>{var o,s;(s=(o=this.options).onChange)==null||s.call(o,this,i)},this.maybeNotify=Qo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),i=>{this.notify(i)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(i=>i()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var i;const o=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==o){if(this.cleanup(),!o){this.maybeNotify();return}if(this.scrollElement=o,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((i=this.scrollElement)==null?void 0:i.window)??null,this.elementsCache.forEach(c=>{this.observer.observe(c)}),this.unsubs.push(this.options.observeElementRect(this,c=>{this.scrollRect=c,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(c,m)=>{if(m&&this._intendedScrollOffset===null&&c===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(c-this._intendedScrollOffset)<1.5&&(c=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const p=this.getScrollOffset();this.scrollDirection=m?p===c?this.scrollDirection:p<c?"forward":"backward":null,this.scrollOffset=c,this.isScrolling=m,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const c=this.scrollElement,m=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},p=()=>{this._iosTouching=!1,!(!Gu()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};c.addEventListener("touchstart",m,Es),c.addEventListener("touchend",p,Es),this.unsubs.push(()=>{c.removeEventListener("touchstart",m),c.removeEventListener("touchend",p),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[c,m,p,h]=s;c!==null&&!p&&(Gu()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),p&&this.scrollToEnd({behavior:p})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const i=this.getScrollOffset(),o=this.getMaxScrollOffset();if(i<0||i>o)return;if(this._iosDeferredAdjustment<0&&i>=o-1){this._iosDeferredAdjustment=0;return}const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(i,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Qo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(i,o,s,c,m,p,h,g)=>(this.prevLanes!==void 0&&this.prevLanes!==p&&(this.lanesChangedFlag=!0),this.prevLanes=p,this.pendingMin=null,{count:i,paddingStart:o,scrollMargin:s,getItemKey:c,enabled:m,lanes:p,laneAssignmentMode:h,gap:g}),{key:!1}),this.getMeasurements=Qo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:i,paddingStart:o,scrollMargin:s,getItemKey:c,enabled:m,lanes:p,laneAssignmentMode:h,gap:g},S)=>{const v=this.itemSizeCache;if(!m)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>i)for(const k of this.laneAssignments.keys())k>=i&&this.laneAssignments.delete(k);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(k=>{this.itemSizeCache.set(k.key,k.size)}));const y=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===i&&(this.lanesSettling=!1),p===1){const k=i*2;let C=this._flatMeasurements;if(!C||C.length<k){const j=new Float64Array(k);C&&y>0&&j.set(C.subarray(0,y*2)),C=j,this._flatMeasurements=C}let _;if(y===0)_=o+s;else{const j=y-1;_=C[j*2]+C[j*2+1]+g}for(let j=y;j<i;j++){const $=c(j),L=v.get($),J=typeof L=="number"?L:this.options.estimateSize(j);C[j*2]=_,C[j*2+1]=J,_+=J+g}const N=GL(i,C,c);return this.measurementsCache=N,N}const x=this.measurementsCache.slice(0,y),E=new Array(p).fill(void 0),P=new Float64Array(p);let I=0;for(let k=0;k<y;k++){const C=x[k];C&&(E[C.lane]===void 0&&I++,E[C.lane]=k,P[C.lane]=C.end)}for(let k=y;k<i;k++){const C=c(k),_=this.laneAssignments.get(k);let N,j;const $=h==="estimate"||v.has(C);if(_!==void 0&&this.options.lanes>1){N=_;const he=E[N],V=he!==void 0?x[he]:void 0;j=V?V.end+g:o+s}else if(I===p){let he=0,V=P[0],ee=E[0];for(let oe=1;oe<p;oe++){const Ne=P[oe];(Ne<V||Ne===V&&E[oe]<ee)&&(he=oe,V=Ne,ee=E[oe])}N=he,j=V+g,$&&this.laneAssignments.set(k,N)}else N=k%this.options.lanes,j=o+s,$&&this.laneAssignments.set(k,N);const L=v.get(C),J=typeof L=="number"?L:this.options.estimateSize(k),re=j+J;x[k]={index:k,start:j,size:J,end:re,key:C,lane:N},E[N]===void 0&&I++,E[N]=k,P[N]=re}return this.measurementsCache=x,x},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Qo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(i,o,s,c)=>i.length===0||o===0?(this.range=null,null):(this.range=JL(i,o,s,c,c===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Qo(()=>{let i=null,o=null;const s=this.calculateRange();return s&&(i=s.startIndex,o=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,i,o]),[this.options.rangeExtractor,this.options.overscan,this.options.count,i,o]},(i,o,s,c,m)=>c===null||m===null?[]:i({startIndex:c,endIndex:m,overscan:o,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=i=>{const o=this.options.indexAttribute,s=i.getAttribute(o);return s?parseInt(s,10):(console.warn(`Missing attribute name '${o}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=i=>{var o;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((o=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:o.index);if(s!==void 0&&this.range){const c=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),m=Math.max(0,s-c),p=Math.min(this.options.count-1,s+c);return i>=m&&i<=p}return!0},this.measureElement=i=>{if(!i){this.elementsCache.forEach((m,p)=>{m.isConnected||(this.observer.unobserve(m),this.elementsCache.delete(p))});return}const o=this.indexFromElement(i),s=this.options.getItemKey(o),c=this.elementsCache.get(s);c!==i&&(c&&this.observer.unobserve(c),this.observer.observe(i),this.elementsCache.set(s,i)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(o)&&this.resizeItem(o,this.options.measureElement(i,void 0,this))},this.resizeItem=(i,o)=>{var s,c;if(i<0||i>=this.options.count)return;let m,p,h;const g=this._flatMeasurements;if(this.options.lanes===1&&g!==null)h=this.options.getItemKey(i),p=g[i*2],m=g[i*2+1];else{const y=this.measurementsCache[i];if(!y)return;h=y.key,p=y.start,m=y.size}const S=this.itemSizeCache.get(h)??m,v=o-S;if(v!==0){const y=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=y?this.getTotalSize():0,E=this.getScrollOffset()+this.scrollAdjustments,I=!this.itemSizeCache.has(h)?p<E:p+S<=E&&this.scrollDirection!=="backward",k=((c=this.scrollState)==null?void 0:c.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[i]??{index:i,key:h,start:p,size:m,end:p+m,lane:0},v,this):I);(this.pendingMin===null||i<this.pendingMin)&&(this.pendingMin=i),this.itemSizeCache.set(h,o),this.itemSizeCacheVersion++;let C=!1;y?C=this.applyScrollAdjustment(this.getTotalSize()-x):k&&(C=this.applyScrollAdjustment(v)),this.notify(C)}},this.getVirtualItems=Qo(()=>[this.getVirtualIndexes(),this.getMeasurements()],(i,o)=>{const s=[];for(let c=0,m=i.length;c<m;c++){const p=i[c],h=o[p];s.push(h)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=i=>{const o=this.getMeasurements();if(o.length===0)return;const s=this._flatMeasurements,c=this.options.lanes===1&&s!=null,m=jS(0,o.length-1,c?p=>s[p*2]:p=>av(o[p]).start,i);return av(o[m])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const i=this.scrollElement.document.documentElement;return this.options.horizontal?i.scrollWidth-this.scrollElement.innerWidth:i.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(i=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=i,this.getOffsetForAlignment=(i,o,s=0)=>{if(!this.scrollElement)return 0;const c=this.getSize(),m=this.getScrollOffset();o==="auto"&&(o=i>=m+c?"end":"start"),o==="center"?i+=(s-c)/2:o==="end"&&(i-=c);const p=this.getMaxScrollOffset();return Math.max(Math.min(p,i),0)},this.getOffsetForIndex=(i,o="auto")=>{i=Math.max(0,Math.min(i,this.options.count-1));const s=this.getSize(),c=this.getScrollOffset(),m=this.measurementsCache[i];if(!m)return;if(o==="auto")if(m.end>=c+s-this.options.scrollPaddingEnd)o="end";else if(m.start<=c+this.options.scrollPaddingStart)o="start";else return[c,o];if(o==="end"&&i===this.options.count-1)return[this.getMaxScrollOffset(),o];const p=o==="end"?m.end+this.options.scrollPaddingEnd:m.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(p,o,m.size),o]},this.scrollToOffset=(i,{align:o="start",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0;const c=this.getOffsetForAlignment(i,o),m=this.now();this.scrollState={index:null,align:o,behavior:s,startedAt:m,lastTargetOffset:c,stableFrames:0},this._scrollToOffset(c,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(i,{align:o="auto",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0,i=Math.max(0,Math.min(i,this.options.count-1));const c=this.getOffsetForIndex(i,o);if(!c)return;const[m,p]=c,h=this.now();this.scrollState={index:i,align:p,behavior:s,startedAt:h,lastTargetOffset:m,stableFrames:0},this._scrollToOffset(m,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(i,{behavior:o="auto"}={})=>{const s=this.getScrollOffset()+i,c=this.now();this.scrollState={index:null,align:"start",behavior:o,startedAt:c,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:i="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:i});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:i})},this.getTotalSize=()=>{var i;const o=this.getMeasurements();let s;if(o.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const c=o.length-1,m=this._flatMeasurements;m!=null?s=m[c*2]+m[c*2+1]:s=((i=o[c])==null?void 0:i.end)??0}else{const c=Array(this.options.lanes).fill(null);let m=o.length-1;for(;m>=0&&c.some(p=>p===null);){const p=o[m];c[p.lane]===null&&(c[p.lane]=p.end),m--}s=Math.max(...c.filter(p=>p!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const i=[];if(this.itemSizeCache.size===0)return i;const o=this.getMeasurements();for(const s of o)s&&this.itemSizeCache.has(s.key)&&i.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return i},this._scrollToOffset=(i,{adjustments:o,behavior:s})=>{this._intendedScrollOffset=i+(o??0),this.options.scrollToFn(i,{behavior:s,adjustments:o},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(a)}applyScrollAdjustment(a,i){return a===0?!1:Gu()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=a,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:i}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const o=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=o?o[0]:this.scrollState.lastTargetOffset,c=1,m=s!==this.scrollState.lastTargetOffset;if(!m&&DL(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=c){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,m){const p=this.getSize()||600,h=Math.abs(s-this.getScrollOffset()),g=this.scrollState.behavior==="smooth"&&h>p;this.scrollState.lastTargetOffset=s,g||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:g?"smooth":"auto"})}this.scheduleScrollReconcile()}}const jS=(e,a,i,o)=>{for(;e<=a;){const s=(e+a)/2|0,c=i(s);if(c<o)e=s+1;else if(c>o)a=s-1;else return s}return e>0?e-1:0};function QL(e,a,i){let o=0;for(;o<=a;){const s=(o+a)/2|0,c=e[s*2];if(c<i)o=s+1;else if(c>i)a=s-1;else return s}return o>0?o-1:0}function JL(e,a,i,o,s){const c=e.length-1;if(e.length<=o)return{startIndex:0,endIndex:c};if(o===1&&s!==null){const g=QL(s,c,i);let S=g;const v=i+a;for(;S<c&&s[S*2]+s[S*2+1]<v;)S++;return{startIndex:g,endIndex:S}}let p=jS(0,c,g=>e[g].start,i),h=p;if(o===1)for(;h<c&&e[h].end<i+a;)h++;else if(o>1){const g=Array(o).fill(0);for(;h<c&&g.some(v=>v<i+a);){const v=e[h];g[v.lane]=v.end,h++}const S=Array(o).fill(i+a);for(;p>=0&&S.some(v=>v>=i);){const v=e[p];S[v.lane]=v.start,p--}p=Math.max(0,p-p%o),h=Math.min(c,h+(o-1-h%o))}return{startIndex:p,endIndex:h}}const Du=typeof document<"u"?R.useLayoutEffect:R.useEffect;function WL({useFlushSync:e=!0,directDomUpdates:a=!1,directDomUpdatesMode:i="transform",...o}){const s=R.useReducer(S=>S+1,0)[1],c=R.useRef({enabled:a,mode:i,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});c.current.enabled=a,c.current.mode=i;const m=S=>{const v=c.current;if(!v.enabled||!v.container)return;const y=S.getTotalSize();if(y!==v.lastSize){v.lastSize=y;const x=S.options.horizontal?"width":"height";v.container.style[x]=`${y}px`}},p=S=>{const v=c.current;if(!v.enabled||!v.container)return;m(S);const y=!!S.options.horizontal,x=v.mode==="transform",E=y?"left":"top",P=S.options.scrollMargin,I=S.getVirtualItems();for(const k of I){const C=k.start-P,_=S.elementsCache.get(k.key);_&&v.lastPositions.get(_)!==C&&(v.lastPositions.set(_,C),x?_.style.transform=y?`translate3d(${C}px, 0, 0)`:`translate3d(0, ${C}px, 0)`:_.style[E]=`${C}px`)}},h={...o,onChange:(S,v)=>{var y;const x=c.current;let E=!0;if(x.enabled){p(S);const P=S.range,I=x.prevRange;E=!I||I.isScrolling!==S.isScrolling||I.startIndex!==P?.startIndex||I.endIndex!==P?.endIndex,E&&(x.prevRange=P?{startIndex:P.startIndex,endIndex:P.endIndex,isScrolling:S.isScrolling}:null)}E&&(e&&v?Js.flushSync(s):s()),(y=o.onChange)==null||y.call(o,S,v)}},[g]=R.useState(()=>{const S=new XL(h);return Object.assign(S,{containerRef:v=>{const y=c.current;if(y.container=v,y.lastSize=null,v&&y.enabled){const x=S.getTotalSize();y.lastSize=x;const E=S.options.horizontal?"width":"height";v.style[E]=`${x}px`}}})});return g.setOptions(h),Du(()=>g._didMount(),[]),Du(()=>(m(g),g._willUpdate())),Du(()=>{p(g)}),g}function ZL(e){return WL({observeElementRect:UL,observeElementOffset:VL,scrollToFn:YL,...e})}const Rs=170,Ns=10,GS=36,eO=44;function tO(e){const a=Math.max(Rs,e-GS);return Math.max(1,Math.floor((a+Ns)/(Rs+Ns)))}function nO(e,a){const i=Math.max(Rs,e-GS);return Math.max(Rs,Math.floor((i-Ns*Math.max(0,a-1))/a))+Ns}function aO(e,a){const i=[];for(const[o,s]of e){i.push({type:"header",id:`h-${o}`,label:o,count:s.length});for(let c=0;c<s.length;c+=a)i.push({type:"items",id:`r-${o}-${c}`,items:s.slice(c,c+a)})}return i}function oO({dateGroups:e,selectedKey:a,scrollElement:i,localizeBucket:o,renderTile:s}){const c=R.useRef(null),[m,p]=R.useState(0),h=R.useMemo(()=>tO(m||960),[m]),g=R.useMemo(()=>nO(m||960,h),[m,h]),S=R.useMemo(()=>aO(e,h),[e,h]);R.useEffect(()=>{const y=c.current;if(!y)return;const x=()=>p(y.clientWidth);x();const E=new ResizeObserver(x);return E.observe(y),()=>E.disconnect()},[]);const v=ZL({count:S.length,getScrollElement:()=>i,estimateSize:y=>S[y]?.type==="header"?eO:g,overscan:6});return R.useEffect(()=>{if(!a)return;const y=S.findIndex(x=>x.type==="items"&&x.items.some(E=>Ot(E)===a));y>=0&&v.scrollToIndex(y,{align:"center"})},[S,a,v]),d.jsx("div",{ref:c,className:"gallery__virtual",style:{height:v.getTotalSize()},children:v.getVirtualItems().map(y=>{const x=S[y.index];return x?d.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${y.start}px)`},children:x.type==="header"?d.jsxs("header",{className:"gallery__group-header gallery__group-header--virtual",children:[d.jsx("span",{className:"gallery__group-label",children:o(x.label)}),d.jsx("span",{className:"gallery__group-count",children:x.count})]}):d.jsx("div",{className:"gallery__grid gallery__grid--virtual",children:x.items.map((E,P)=>s(E,x.id,P))})},x.id):null})})}function rv({showSessions:e,favoritesOnly:a,query:i,historyNextCursor:o,favoriteHistoryNextCursor:s,historyLoadingOlder:c,favoriteHistoryLoadingOlder:m,onLoadOlder:p,onLoadOlderFavorites:h,t:g}){return e?d.jsx("div",{className:"gallery__load-more gallery__load-more--hint",children:g("gallery.sessionPaginationHint")}):i.trim()?null:a?s?d.jsx("div",{className:"gallery__load-more",children:d.jsx("button",{type:"button",onClick:h,disabled:m,children:g(m?"gallery.loadingOlderFavorites":"gallery.loadOlderFavorites")})}):null:o?d.jsx("div",{className:"gallery__load-more",children:d.jsx("button",{type:"button",onClick:p,disabled:c,children:g(c?"gallery.loadingOlder":"gallery.loadOlder")})}):null}function rO({groups:e,loose:a,favoritesOnly:i,galleryScope:o,setGalleryScope:s,renderTile:c,t:m}){return e.length===0&&a.length===0?d.jsx("div",{className:"gallery__empty",children:i?m("gallery.emptyFavorites"):o==="current-session"?d.jsxs(d.Fragment,{children:[d.jsx("p",{children:m("gallery.empty.currentSession")}),d.jsx("button",{type:"button",onClick:()=>s("all"),children:m("gallery.scope.all")})]}):m("gallery.emptySessions")}):d.jsxs(d.Fragment,{children:[e.map(p=>d.jsxs("section",{className:"gallery__group",children:[d.jsxs("header",{className:"gallery__group-header",children:[d.jsx("span",{className:"gallery__group-label",title:p.sessionId,children:p.title?p.displayLabel:m("gallery.sessionLabel",{name:p.displayLabel})}),d.jsx("span",{className:"gallery__group-count",children:p.items.length})]}),d.jsx("div",{className:"gallery__grid",children:p.items.map((h,g)=>c(h,p.sessionId,g))})]},p.sessionId)),a.length>0&&d.jsxs("section",{className:"gallery__group",children:[d.jsxs("header",{className:"gallery__group-header",children:[d.jsx("span",{className:"gallery__group-label",children:m("gallery.standalone")}),d.jsx("span",{className:"gallery__group-count",children:a.length})]}),d.jsx("div",{className:"gallery__grid",children:a.map((p,h)=>c(p,"loose",h))})]})]})}function iO({status:e,dismissed:a,onOpenFolder:i,onDismiss:o,t:s}){const c=e!=null&&e.state!=="ok"&&!a,m=e?.state==="recoverable"?"gallery.storageNoticeRecoverable":e?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return d.jsxs("div",{className:`gallery__storage-bar${c?" gallery__storage-bar--notice":""}`,children:[c?d.jsxs("div",{className:"gallery__storage-copy",children:[d.jsx("div",{className:"gallery__storage-title",children:s("gallery.storageNoticeTitle")}),d.jsx("div",{className:"gallery__storage-text",children:s(m)})]}):d.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:e?.generatedDirLabel??"~/.ima2/generated"}),d.jsxs("div",{className:"gallery__storage-actions",children:[d.jsx("button",{type:"button",className:"gallery__storage-button",onClick:i,title:s("gallery.openGeneratedDirTitle"),children:s("gallery.openGeneratedDir")}),c&&d.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:o,children:s("common.close")})]})]})}const iv="ima2.storageNoticeDismissed.0.09.23";function lO(e){const a=R.useRef(null),i=R.useRef(new Map),[o,s]=R.useState(()=>new Set);R.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const m=new IntersectionObserver(p=>{const h=p.filter(g=>g.isIntersecting);h.length!==0&&s(g=>{const S=new Set(g);for(const v of h){const y=v.target.dataset.galleryLazyKey;y&&S.add(y)}return S})},{root:e,rootMargin:"200% 0px"});a.current=m;for(const p of i.current.values())m.observe(p);return()=>{m.disconnect(),a.current=null}},[e]);const c=R.useCallback((m,p)=>{const h=i.current.get(m);h&&h!==p&&a.current?.unobserve(h),p?(i.current.set(m,p),a.current?.observe(p)):i.current.delete(m)},[]);return{visibleKeys:o,register:c,supported:typeof IntersectionObserver<"u"}}function sO(){const{t:e,locale:a}=ge(),i=w(te=>te.galleryOpen),o=w(te=>te.closeGallery),s=w(te=>te.history),c=w(te=>te.selectHistory),m=w(te=>te.currentImage),p=w(te=>te.trashHistoryItem),h=w(te=>te.showToast),g=w(te=>te.toggleGalleryFavorite),S=w(te=>te.galleryScope),v=w(te=>te.setGalleryScope),y=w(te=>te.historyNextCursor),x=w(te=>te.historyLoadingOlder),E=w(te=>te.favoriteHistoryNextCursor),P=w(te=>te.favoriteHistoryLoadingOlder),I=w(te=>te.loadOlderHistory),k=w(te=>te.loadFavoriteHistory),C=w(te=>te.loadOlderFavoriteHistory),_=w(r1),[N,j]=R.useState(""),[$,L]=R.useState("date"),[J,re]=R.useState(!1),[he,V]=R.useState(()=>new Set),ee=R.useRef(new Set),[oe,Ne]=R.useState([]),[ne,H]=R.useState([]),[ae,ce]=R.useState(!1),[be,Se]=R.useState(!1),[T,F]=R.useState(!1),[W,U]=R.useState(0),[le,pe]=R.useState(null),[xe,Oe]=R.useState(()=>{try{return localStorage.getItem(iv)==="1"}catch{return!1}}),Re=R.useRef(null),Ze=R.useRef({}),[ie,lt]=R.useState(null),at=R.useRef(0),st=R.useRef({open:!1,selectedKey:null}),bt=R.useMemo(()=>hs(s.filter(mi)),[s]),se=R.useCallback(te=>{Re.current=te,lt(te)},[]),qe=lO(ie),ot=uo(i,o);R.useEffect(()=>{i||j("")},[i]),R.useEffect(()=>{if(!i)return;let te=!1;return(async()=>{try{const Te=await LT();te||pe(Te)}catch{te||pe({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{te=!0}},[i]),R.useEffect(()=>{if(!i||$!=="session")return;let te=!1;return Ne([]),H([]),ce(!0),Se(!1),F(!1),(async()=>{try{const Te=await MT({limit:500,sessionId:S==="current-session"?_:void 0});if(te)return;F(Te.nextCursor!==null||Te.total>=500);const Tt=de=>{const We=de.kind,Ft=We==="classic"||We==="edit"||We==="generate"||We==="card-news-card"||We==="card-news-set"?We:null,Ma=de.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(de.filename??"");return{image:de.url,url:de.url,filename:de.filename,thumb:de.thumb??(Ma?void 0:de.url),mediaType:de.mediaType,video:de.video??null,videoSeries:de.videoSeries??null,videoContinuity:de.videoContinuity??null,prompt:de.prompt??void 0,userPrompt:de.userPrompt??null,revisedPrompt:de.revisedPrompt??null,promptMode:de.promptMode??null,composerPrompt:de.composerPrompt??null,composerInsertedPrompts:de.composerInsertedPrompts??null,size:de.size??void 0,quality:de.quality??void 0,format:de.format,moderation:de.moderation??void 0,model:de.model??void 0,reasoningEffort:de.reasoningEffort,provider:de.provider,providerUrl:de.providerUrl??null,usage:de.usage,elapsed:de.elapsed??void 0,createdAt:de.createdAt,sessionId:de.sessionId??null,nodeId:de.nodeId??null,parentNodeId:de.parentNodeId??null,clientNodeId:de.clientNodeId??null,requestId:de.requestId??null,kind:Ft,setId:de.setId??null,cardId:de.cardId??null,cardOrder:de.cardOrder??null,headline:de.headline??null,body:de.body??null,cards:de.cards,refsCount:de.refsCount??0,webSearchCalls:de.webSearchCalls??0,sequenceId:de.sequenceId??null,sequenceIndex:de.sequenceIndex??null,sequenceTotalRequested:de.sequenceTotalRequested??null,sequenceTotalReturned:de.sequenceTotalReturned??null,sequenceStatus:de.sequenceStatus??null,isFavorite:de.isFavorite??!1}};Ne(Te.sessions.map(de=>({sessionId:de.sessionId,title:de.title??null,label:de.label??null,displayLabel:de.title||de.label||de.sessionId.slice(0,8),items:hs(de.items.filter(mi).map(Tt))})).filter(de=>de.items.length>0)),H(hs(Te.loose.filter(mi).map(Tt)))}catch{te||Se(!0)}finally{te||ce(!1)}})(),()=>{te=!0}},[i,$,S,_,W]),R.useEffect(()=>{!i||$==="session"||!J||k()},[i,$,J,k]);const St=R.useMemo(()=>{const te=N.trim().toLowerCase().normalize("NFC");return bt.filter(Te=>J&&!Te.isFavorite?!1:te?(Te.prompt??"").toLowerCase().normalize("NFC").includes(te)||(Te.filename??"").toLowerCase().normalize("NFC").includes(te):!0)},[bt,N,J]),xt=R.useMemo(()=>J?oe.map(te=>({...te,items:te.items.filter(Te=>Te.isFavorite)})).filter(te=>te.items.length>0):oe,[oe,J]),nn=R.useMemo(()=>J?ne.filter(te=>te.isFavorite):ne,[ne,J]),Yt=R.useMemo(()=>{const te=new Map;for(const Te of St){const Tt=TL(Te.createdAt,a);te.has(Tt)||te.set(Tt,[]),te.get(Tt).push(Te)}return Array.from(te.entries())},[St,a]),fn=$==="session"?xt.reduce((te,Te)=>te+Te.items.length,0)+nn.length:St.length;R.useLayoutEffect(()=>{const te=m?Ot(m):null;if(!i){st.current={open:!1,selectedKey:te};return}const Te=st.current,Tt=!Te.open||Te.selectedKey!==te;st.current={open:!0,selectedKey:te};const de=te?Ze.current[te]:null;if(Tt&&de){de.scrollIntoView({block:"center"});return}Re.current&&(Re.current.scrollTop=at.current)},[i,m?.filename,m?.image,$,fn,Yt.length,xt.length,nn.length]);async function et(te,Te){Te.stopPropagation();const Tt=Ot(te);await p(te),delete Ze.current[Tt],window.requestAnimationFrame(()=>Re.current?.focus())}async function On(te){const Te=te.filename;if(!(!Te||ee.current.has(Te))){ee.current.add(Te),V(new Set(ee.current));try{const Tt=await g(te);if(Tt===null)return;Ne(de=>de.map(We=>({...We,items:We.items.map(Ft=>Ft.filename===Te?{...Ft,isFavorite:Tt}:Ft)}))),H(de=>de.map(We=>We.filename===Te?{...We,isFavorite:Tt}:We))}finally{ee.current.delete(Te),V(new Set(ee.current))}}}async function D(){try{await OT(),h(e("toast.openGeneratedDirOpened"))}catch{h(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ae,handleCopyCardNewsSetPath:ke,handleDownloadCardNewsManifest:Qe}=CL(o,h,e);function pt(){Oe(!0);try{localStorage.setItem(iv,"1")}catch{}}if(!i)return null;const Dt=te=>te==="earlier"||te==="today"||te==="yesterday"||te==="thisWeek"?e(`gallery.${te}`):te,_a=(te,Te,Tt)=>{const de=m?.image===te.image,We=Ot(te),Ft=gn=>{Ze.current[We]=gn,qe.register(We,gn)};return(qe.supported?qe.visibleKeys.has(We):!0)?te.kind==="card-news-set"?d.jsx("div",{ref:Ft,className:"gallery__tile-wrap gallery-card-news-set",children:d.jsx(EL,{item:te,onOpen:gn=>{Ae(gn)},onCopyPath:ke,onDownloadManifest:Qe})},`${Te}-${We}`):d.jsx(jL,{item:te,active:de,itemRef:Ft,onSelect:gn=>{c(gn),o()},onDelete:et,onToggleFavorite:On,favoriteBusy:!!(te.filename&&he.has(te.filename)),t:e},`${Te}-${We}`):d.jsx("div",{ref:Ft,className:"gallery__tile-wrap","data-gallery-lazy-key":We,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Te}-${We}`)},At=$==="session",Pt=m?Ot(m):null;return d.jsx("div",{className:"gallery-backdrop",onClick:o,role:"presentation",children:d.jsxs("div",{ref:ot,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:te=>te.stopPropagation(),children:[d.jsxs("div",{className:"gallery__header",children:[d.jsxs("div",{className:"gallery__title-row",children:[d.jsx("div",{className:"gallery__title",children:e("gallery.title")}),d.jsxs("div",{className:"gallery__meta",children:[e("gallery.total",{n:fn}),N||J?e("gallery.totalFiltered",{n:bt.length}):""]}),d.jsx(ju,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:J?"favorites":"all",onChange:te=>re(te==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),d.jsx(ju,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:$,onChange:L,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),d.jsx(ju,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:S,onChange:v,tabs:[{value:"current-session",label:e("gallery.scope.current"),disabled:!_},{value:"all",label:e("gallery.scope.all")}]})]}),d.jsx("input",{type:"text",className:"gallery__search",...At?{}:{"data-modal-initial-focus":!0},placeholder:e(At?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:N,onChange:te=>j(te.target.value),disabled:At}),d.jsx("button",{type:"button",className:"gallery__close",onClick:o,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),d.jsx(iO,{status:le,dismissed:xe,onOpenFolder:D,onDismiss:pt,t:e}),d.jsx("div",{className:"gallery__scroll",ref:se,tabIndex:-1,onScroll:()=>{at.current=Re.current?.scrollTop??0},children:At?ae?d.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):be?d.jsxs("div",{className:"gallery__empty",role:"alert",children:[d.jsx("span",{children:e("gallery.sessionLoadFailed")}),d.jsx("button",{type:"button",onClick:()=>U(te=>te+1),children:e("gallery.retry")})]}):d.jsxs(d.Fragment,{children:[T?d.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,d.jsx(rO,{groups:xt,loose:nn,favoritesOnly:J,galleryScope:S,setGalleryScope:v,renderTile:_a,t:e}),d.jsx(rv,{showSessions:At,favoritesOnly:J,query:N,historyNextCursor:y,favoriteHistoryNextCursor:E,historyLoadingOlder:x,favoriteHistoryLoadingOlder:P,onLoadOlder:()=>{I()},onLoadOlderFavorites:()=>{C()},t:e})]}):St.length===0?d.jsx("div",{className:"gallery__empty",children:bt.length===0?e("gallery.emptyAll"):e(J?"gallery.emptyFavorites":"gallery.noResults")}):d.jsxs(d.Fragment,{children:[d.jsx(oO,{dateGroups:Yt,selectedKey:Pt,scrollElement:ie,localizeBucket:Dt,renderTile:_a}),d.jsx(rv,{showSessions:At,favoritesOnly:J,query:N,historyNextCursor:y,favoriteHistoryNextCursor:E,historyLoadingOlder:x,favoriteHistoryLoadingOlder:P,onLoadOlder:()=>{I()},onLoadOlderFavorites:()=>{C()},t:e})]})})]})})}function cO(e){return e.includes("ratio")?"sizeConfirm.reasonRatio":e.includes("maxPixels")||e.includes("pixels")?"sizeConfirm.reasonPixels":e.includes("minPixels")?"sizeConfirm.reasonMinPixels":e.includes("min")?"sizeConfirm.reasonMin":e.includes("maxEdge")||e.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function dO(){const e=w(p=>p.customSizeConfirm),a=w(p=>p.confirmCustomSizeAdjustment),i=w(p=>p.cancelCustomSizeAdjustment),{t:o}=ge(),s=uo(!!e,i);if(!e)return null;const c=`${e.requestedW}x${e.requestedH}`,m=`${e.adjustedW}x${e.adjustedH}`;return d.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:d.jsxs("div",{ref:s,className:"modal custom-size-confirm",role:"dialog","aria-modal":"true","aria-labelledby":"custom-size-confirm-title","aria-describedby":"custom-size-confirm-body",tabIndex:-1,children:[d.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:o("sizeConfirm.title")}),d.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[d.jsx("p",{children:o("sizeConfirm.body")}),d.jsxs("dl",{className:"size-confirm__pairs",children:[d.jsxs("div",{className:"size-confirm__pair",children:[d.jsx("dt",{children:o("sizeConfirm.requested")}),d.jsx("dd",{children:c})]}),d.jsxs("div",{className:"size-confirm__pair",children:[d.jsx("dt",{children:o("sizeConfirm.adjusted")}),d.jsx("dd",{children:m})]})]}),d.jsx("p",{className:"size-confirm__reason",children:o(cO(e.reasons))})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button","data-modal-initial-focus":!0,className:"modal__btn modal__btn--secondary",onClick:i,children:o("sizeConfirm.cancel")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{a()},children:o("sizeConfirm.approve")})]})]})})}function ls(e){return e==null||e===""?"-":String(e)}function uO(){const{t:e}=ge(),a=w(h=>h.metadataRestore),i=w(h=>h.applyMetadataRestore),o=w(h=>h.addMetadataRestoreAsReference),s=w(h=>h.cancelMetadataRestore),c=uo(!!a,s);if(!a)return null;const m=a.metadata,p=m.userPrompt||m.prompt||m.revisedPrompt||"";return d.jsx("div",{className:"modal-backdrop metadata-restore-backdrop",role:"presentation",children:d.jsxs("div",{ref:c,className:"modal metadata-restore",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-restore-title",tabIndex:-1,children:[d.jsx("div",{id:"metadata-restore-title",className:"modal__title",children:e("metadata.restoreTitle")}),d.jsxs("div",{className:"modal__body metadata-restore__body",children:[d.jsx("p",{children:e("metadata.restoreBody")}),d.jsxs("div",{className:"metadata-restore__preview",children:[d.jsx("img",{src:a.image,alt:e("metadata.imageAlt")}),d.jsxs("div",{className:"metadata-restore__details",children:[d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.prompt")}),d.jsx("strong",{title:p,children:ls(p)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.size")}),d.jsx("strong",{children:ls(m.size)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.quality")}),d.jsx("strong",{children:ls(m.quality)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.model")}),d.jsx("strong",{children:ls(m.model)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.source")}),d.jsx("strong",{children:a.source==="png-comment"?e("metadata.sourcePngComment"):e("metadata.sourceXmp")})]})]})]})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:s,"data-modal-initial-focus":!0,children:e("common.cancel")}),d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:o,children:e("metadata.useAsReferenceOnly")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:i,children:e("metadata.applySettings")})]})]})})}function mO(){const{t:e}=ge(),a=w(P=>P.readinessPopupOpen),i=w(P=>P.closeReadinessPopup),o=w(P=>P.openSettings),s=w(P=>P.provider),c=w(P=>P.imageModel),m=w(P=>P.reasoningEffort),p=w(P=>P.webSearchEnabled),h=_S(),g=s==="grok",S=Na.find(P=>P.value===c),v=uo(a,i);if(!a)return null;const y=h[s],x=y.ok,E=()=>{i(),o("providers")};return d.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:i,role:"presentation",children:d.jsxs("div",{ref:v,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:P=>P.stopPropagation(),children:[d.jsx("div",{id:"provider-readiness-title",className:"modal__title",children:e("readiness.title")}),d.jsxs("div",{className:"modal__body provider-readiness__body",children:[d.jsxs("div",{className:`provider-readiness__status${x?" is-ok":" is-blocked"}`,children:[d.jsx("span",{"aria-hidden":"true"}),d.jsx("strong",{children:e(x?"readiness.ready":"readiness.blocked")}),d.jsx("small",{children:x?e("readiness.readyBody"):y.reason})]}),y.hint?d.jsx("p",{className:"modal__hint",children:y.hint}):null,d.jsxs("dl",{className:"provider-readiness__facts",children:[d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.provider")}),d.jsx("dd",{children:s==="agy"?"Gemini":s==="grok"?"Grok OAuth":s==="oauth"?"GPT OAuth":"GPT API"})]}),d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.model")}),d.jsx("dd",{children:S?e(S.fullLabelKey):c})]}),g?d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.grokApi")}),d.jsx("dd",{children:e("readiness.grokApiBody")})]}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.reasoning")}),d.jsx("dd",{children:m})]}),d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.webSearch")}),d.jsx("dd",{children:e(p?"settings.webSearch.on":"settings.webSearch.off")})]})]})]})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:i,"data-modal-initial-focus":!0,children:e("common.close")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:E,children:e("readiness.openAccount")})]})]})})}const lv="ima2.onboardingDismissed";function pO(){const{t:e}=ge(),a=w(I=>I.openSettings),i=RS(),o=NS(),{data:s}=kS(),[c,m]=R.useState(()=>{try{return localStorage.getItem(lv)==="1"}catch{return!1}}),p=i!==null&&o!==null&&s!=null,h=i?.status==="auth_required"||i?.status==="offline",g=o?.status==="offline"||o?.status==="error",S=s?!s.gemini?.configured&&!s.vertex?.configured:!1,y=!c&&(p&&h&&g&&S),x=()=>{try{localStorage.setItem(lv,"1")}catch{}m(!0)},E=()=>{x(),a("providers")},P=uo(y,x);return y?d.jsx("div",{className:"modal-backdrop",role:"presentation",children:d.jsxs("div",{ref:P,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[d.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),d.jsx("div",{className:"modal__body",children:d.jsx("p",{children:e("onboarding.body")})}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:x,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:E,children:e("onboarding.login")})]})]})}):null}function fO(){const e=w(m=>m.trashPending),a=w(m=>m.restorePendingTrash),i=w(m=>m.clearPendingTrash),{t:o}=ge(),[s,c]=R.useState(Date.now());return R.useEffect(()=>{if(!e)return;c(Date.now());const m=window.setInterval(()=>{const p=Date.now();c(p),p>=e.expiresAt&&i()},500);return()=>window.clearInterval(m)},[i,e]),e?d.jsxs("div",{className:"trash-undo-toast",children:[d.jsx("span",{children:o("gallery.deleted",{filename:e.filename})}),d.jsx("button",{type:"button",onClick:()=>{a()},children:o("gallery.undo")}),d.jsx("span",{className:"trash-undo-toast__timer",children:o("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((e.expiresAt-s)/1e3))})})]}):null}function gO(){return d.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("line",{x1:"4",y1:"6",x2:"14",y2:"6"}),d.jsx("circle",{cx:"17",cy:"6",r:"2.2"}),d.jsx("line",{x1:"4",y1:"12",x2:"8",y2:"12"}),d.jsx("circle",{cx:"11",cy:"12",r:"2.2"}),d.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),d.jsx("line",{x1:"4",y1:"18",x2:"14",y2:"18"}),d.jsx("circle",{cx:"17",cy:"18",r:"2.2"})]})}function hO(){const e=w(g=>g.composeSheetOpen),a=w(g=>g.composeSheetTab),i=w(g=>g.openComposeSheet),o=w(g=>g.settingsOpen),s=w(g=>g.uiMode),{t:c}=ge();if(!ka()||o||s==="home"||s==="card-news"||s==="agent"||s==="assets"||s==="asset-gen")return null;const p=e&&a==="controls",h=c("sheet.controlsOpen");return d.jsx("button",{type:"button",className:"mobile-settings-toggle","aria-expanded":p,"aria-controls":"mobile-generate-sheet","aria-label":h,title:h,onClick:()=>i("controls"),children:d.jsx(gO,{})})}let ks=null;function yO(e){ks=e}function vO(){const e=ks;ks=null,e?.isConnected&&e.focus()}function sv(){ks=null}function bO(){const{t:e}=ge(),a=w(S=>S.openComposeSheet),i=w(S=>S.settingsOpen),o=w(S=>S.uiMode),s=o==="agent"&&lr?"agent":o==="node"&&ir?"node":o==="home"?"home":o==="assets"?"assets":o==="asset-gen"?"asset-gen":"classic",c=ka(),m=R.useRef(null),p=R.useRef(null),h=R.useRef(null),g=(S,v)=>{v.current&&yO(v.current),a(S==="library"?"library":S==="controls"?"controls":"prompt")};return!c||i||s!=="classic"?null:d.jsxs("header",{className:"mobile-app-bar",role:"banner",children:[d.jsxs("div",{className:"mobile-app-bar__brand",children:[d.jsx("div",{className:"logo-mark","aria-hidden":"true"}),d.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[d.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),d.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),d.jsxs("div",{className:"mobile-app-bar__actions",children:[d.jsx(AS,{compact:!0}),d.jsx("button",{ref:m,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>g("library",m),"aria-label":e("promptLibrary.title"),title:e("promptLibrary.title"),children:d.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),d.jsx("button",{ref:p,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>g("controls",p),"aria-label":e("appBar.controls"),title:e("appBar.controls"),children:d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("circle",{cx:"12",cy:"12",r:"3"}),d.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),d.jsx("button",{ref:h,type:"button",className:"mobile-app-bar__generate",onClick:()=>g("prompt",h),"aria-label":e("appBar.generateAria"),title:e("appBar.generate"),style:{width:44,padding:0},children:d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),d.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]})]})}const SO={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},cv={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function xO(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const a=SO[e];return a&&a!=="settings"?{mode:a,settings:!1}:null}function AO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),d.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),d.jsx("path",{d:"m21 15-5-5L5 21"})]})}function TO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),d.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})}function CO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"2",y:"6",width:"8",height:"6",rx:"1"}),d.jsx("rect",{x:"14",y:"12",width:"8",height:"6",rx:"1"}),d.jsx("path",{d:"M10 9h4"}),d.jsx("path",{d:"M14 15V9a2 2 0 0 1 2-2h0"})]})}function wO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[d.jsx("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}),d.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(-30 12 12)"}),d.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(30 12 12)"})]})}function IO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function EO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),d.jsx("path",{d:"M8 12h8"})]})}function RO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"3",y:"3",width:"13",height:"13",rx:"2"}),d.jsx("path",{d:"M3 12l3.5-3.5a1.4 1.4 0 0 1 2 0L13 13"}),d.jsx("path",{d:"M19 14v6"}),d.jsx("path",{d:"M16 17h6"})]})}const NO=[{id:"home",mode:"home",icon:TO,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:AO,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:CO,labelKey:"nav.node",enabled:ir},{id:"agent",mode:"agent",icon:wO,labelKey:"nav.agent",enabled:lr},{id:"assets",mode:"assets",icon:EO,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:RO,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:IO,labelKey:"nav.settings",enabled:!0,bottom:!0}];function kO(){const{t:e}=ge(),a=w(x=>x.uiMode),i=w(x=>x.setUIMode),o=w(x=>x.settingsOpen),s=w(x=>x.openSettings),c=w(x=>x.closeSettings),m=ka(),p=R.useCallback(x=>{if(x.settingsAction){o?(c(),history.replaceState(null,"",cv[a]||"#create")):(s(),history.replaceState(null,"","#settings"));return}x.mode&&(o&&c(),i(x.mode),history.replaceState(null,"",cv[x.mode]||"#create"))},[a,o,i,s,c]);R.useEffect(()=>{const x=()=>{const E=xO();E&&(E.settings?s():(o&&c(),i(E.mode)))};return x(),window.addEventListener("popstate",x),window.addEventListener("hashchange",x),()=>{window.removeEventListener("popstate",x),window.removeEventListener("hashchange",x)}},[]);const h=NO.filter(x=>x.enabled),g=h.filter(x=>!x.bottom),S=h.filter(x=>x.bottom),v=x=>x.settingsAction?o:!o&&x.mode===a,y=x=>d.jsxs("button",{type:"button",className:`nav-rail__btn${v(x)?" is-active":""}`,onClick:()=>p(x),"aria-label":e(x.labelKey),"aria-current":v(x)?"page":void 0,children:[d.jsx(x.icon,{}),d.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(x.labelKey)})]},x.id);return m?d.jsx("nav",{className:"nav-rail nav-rail--mobile","aria-label":e("nav.ariaLabel"),children:h.map(y)}):d.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[d.jsx("div",{className:"nav-rail__top",children:g.map(y)}),d.jsx("div",{className:"nav-rail__bottom",children:S.map(y)})]})}const _O=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-DCtxfzy1.js"),[]).then(e=>({default:e.PromptLibraryPanel}))),Rn=["prompt","controls","library"],ss="mobile-inflight-panel",cs=e=>`mobile-sheet-tab-${e}`,ds=e=>`mobile-sheet-panel-${e}`;function MO(){const{t:e}=ge(),a=w(N=>N.composeSheetOpen),i=w(N=>N.composeSheetTab),o=w(N=>N.setComposeSheetTab),s=w(N=>N.closeComposeSheet),c=w(N=>N.inFlight.length),m=w(N=>N.settingsOpen),p=w(N=>N.uiMode),h=p==="agent"&&lr?"agent":p==="node"&&ir?"node":p==="home"?"home":p==="assets"?"assets":"classic",g=ka(),[S,v]=R.useState(!1),y=R.useRef(c),x=R.useRef(!1),E=R.useRef(null),P=R.useRef({}),I=R.useRef(!1),k=N=>{o(N),requestAnimationFrame(()=>P.current[N]?.focus())},C=(N,j)=>{const $=Rn.indexOf(j),L=N.key==="ArrowRight"?Rn[($+1)%Rn.length]:N.key==="ArrowLeft"?Rn[($-1+Rn.length)%Rn.length]:N.key==="Home"?Rn[0]:N.key==="End"?Rn[Rn.length-1]:null;L&&(N.preventDefault(),k(L))};R.useEffect(()=>{if((!a||i!=="prompt"||!g||m||h!=="classic")&&v(!1),!a)return;const N=j=>{j.key==="Escape"&&s()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[a,i,s,g,m,h]),R.useLayoutEffect(()=>{const N=y.current>0&&c===0;y.current=c,N&&(v(!1),x.current&&E.current?.querySelector(".generate-btn")?.focus(),x.current=!1)},[c]),R.useLayoutEffect(()=>{if(a){I.current=!0;const N=requestAnimationFrame(()=>P.current[i]?.focus());return()=>cancelAnimationFrame(N)}I.current&&(I.current=!1,vO())},[a,i]);const _=g&&!m&&h==="classic";return R.useEffect(()=>{_||(I.current=!1,w.getState().composeSheetOpen&&s(),sv())},[_]),R.useEffect(()=>()=>sv(),[]),_?d.jsxs(d.Fragment,{children:[a?d.jsx("button",{type:"button",className:"compose-sheet-backdrop","aria-label":e("sheet.close"),onClick:s}):null,d.jsxs("section",{id:"mobile-generate-sheet",inert:!a,className:`compose-sheet${a?" compose-sheet--open":""}`,role:"dialog","aria-modal":a?"true":"false","aria-label":e("sheet.generate"),"aria-hidden":!a,children:[d.jsx("button",{type:"button",className:"compose-sheet__handle",onClick:s,"aria-label":e("sheet.close")}),d.jsx("div",{className:"mobile-sheet-tabs",role:"tablist","aria-label":e("sheet.generate"),children:Rn.map(N=>d.jsx("button",{ref:j=>{P.current[N]=j},id:cs(N),type:"button",role:"tab","aria-selected":i===N,"aria-controls":ds(N),tabIndex:i===N?0:-1,className:`mobile-sheet-tabs__button${i===N?" active":""}`,onClick:()=>o(N),onKeyDown:j=>C(j,N),children:e(`sheet.tabs.${N}`)},N))}),d.jsxs("div",{className:"compose-sheet__body",children:[d.jsx("div",{id:ds("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":cs("prompt"),hidden:i!=="prompt",onFocusCapture:N=>{const j=document.getElementById(ss);x.current=j?.contains(N.target)??!1},children:i==="prompt"?d.jsxs(d.Fragment,{children:[d.jsx(qm,{}),c>0?d.jsxs("section",{className:"compose-sheet__inflight",hidden:!S,children:[d.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{E.current?.querySelector(".inflight-badge")?.focus(),v(!1)},"aria-expanded":S,"aria-controls":ss,"aria-label":e("inflight.inlineCollapse",{n:c}),children:[d.jsxs("span",{children:[e("inflight.title")," (",c,")"]}),d.jsx("span",{"aria-hidden":"true",children:"−"})]}),d.jsx(Hm,{variant:"inline",panelId:ss}),d.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,d.jsxs("div",{ref:E,className:"compose-sheet__actions",children:[d.jsx(Um,{}),d.jsx(xS,{variant:"inline",panelId:ss,expanded:S,onToggle:v})]})]}):null}),d.jsx("div",{id:ds("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":cs("controls"),hidden:i!=="controls",children:i==="controls"?d.jsx(OS,{}):null}),d.jsx("div",{id:ds("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":cs("library"),hidden:i!=="library",children:i==="library"?d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:d.jsx(_O,{variant:"embedded",forceOpen:!0,onRequestClose:()=>o("prompt")})}):null})]})]})]}):null}const PO={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function LO(){const e=w(o=>o.uiMode),a=w(o=>!!o.currentImage||!!o.multimodePreviewFlightId),i=w(o=>o.selectHistoryShortcutTarget);R.useEffect(()=>{if(e!=="classic")return;const o=s=>{const c=PO[s.key];c&&(s.defaultPrevented||ys(s.target)||a&&(s.preventDefault(),i(c)))};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[a,i,e])}const us=64,DS="Image Gen";let Km=DS,tm=!1,Ia=null,$m="",nm=!1;function FS(){return navigator}function zS(){if(typeof document>"u")return null;if(Ia)return Ia;const e=document.querySelector('link[rel~="icon"]');if(e)return Ia=e,$m=e.href||e.getAttribute("href")||"",e;const a=document.createElement("link");return a.rel="icon",document.head.appendChild(a),Ia=a,nm=!0,a}function OO(e){const a=document.createElement("canvas");a.width=us,a.height=us;const i=a.getContext("2d");return i?(i.clearRect(0,0,us,us),i.fillStyle="#0a0a0a",jO(i,6,6,52,52,12),i.fill(),i.strokeStyle="#ffffff",i.lineWidth=5,i.beginPath(),i.arc(30,32,14,0,Math.PI*2),i.stroke(),i.fillStyle="#ffffff",i.beginPath(),i.arc(30,32,5,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(48,16,e>1?13:10,0,Math.PI*2),i.fillStyle="#ff335f",i.fill(),i.lineWidth=4,i.strokeStyle="#ffffff",i.stroke(),e>1&&(i.fillStyle="#ffffff",i.font="bold 15px sans-serif",i.textAlign="center",i.textBaseline="middle",i.fillText(String(Math.min(e,9)),48,17)),a.toDataURL("image/png")):$m}function jO(e,a,i,o,s,c){e.beginPath(),e.moveTo(a+c,i),e.arcTo(a+o,i,a+o,i+s,c),e.arcTo(a+o,i+s,a,i+s,c),e.arcTo(a,i+s,a,i,c),e.arcTo(a,i,a+o,i,c),e.closePath()}async function GO(e){const a=FS();if(typeof a.setAppBadge=="function")try{await a.setAppBadge(e)}catch{}}async function DO(){const e=FS();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function FO(e){document.title=`(${e}) ${Km}`;const a=zS();a&&(a.href=OO(e)),GO(e)}function dv(){document.title=Km,Ia&&(nm?(Ia.remove(),Ia=null,nm=!1):Ia.href=$m),DO()}function uv(){tm||typeof document>"u"||(tm=!0,Km=document.title||DS,zS())}function zO(e){R.useEffect(()=>(uv(),()=>{tm&&dv()}),[]),R.useEffect(()=>{uv(),e>0?FO(e):dv()},[e])}function qO(){R.useEffect(()=>{if(typeof window>"u")return;const e=window.visualViewport;if(!e)return;const a=()=>{const i=Math.round(e.height),o=Math.round(e.offsetTop);document.documentElement.style.setProperty("--vv-h",`${i}px`),document.documentElement.style.setProperty("--vv-offset-top",`${o}px`)};return a(),e.addEventListener("resize",a),e.addEventListener("scroll",a),()=>{e.removeEventListener("resize",a),e.removeEventListener("scroll",a)}},[])}const UO=R.lazy(()=>$t(()=>import("./NodeCanvas-CaFDJn_9.js"),__vite__mapDeps([0,1])).then(e=>({default:e.NodeCanvas}))),HO=R.lazy(()=>$t(()=>import("./SettingsWorkspace-aHoTeB4-.js"),[]).then(e=>({default:e.SettingsWorkspace}))),BO=R.lazy(()=>$t(()=>import("./CardNewsWorkspace-DIhk26qD.js"),[]).then(e=>({default:e.CardNewsWorkspace}))),VO=R.lazy(()=>$t(()=>import("./AgentWorkspace-DU9efUdT.js"),__vite__mapDeps([2,3])).then(e=>({default:e.AgentWorkspace}))),KO=R.lazy(()=>$t(()=>import("./AssetsWorkspace-D_kJ7dP_.js"),__vite__mapDeps([4,5,3,6])).then(e=>({default:e.AssetsWorkspace}))),$O=R.lazy(()=>$t(()=>import("./AssetGenWorkspace-ldEVBldg.js").then(e=>e.A),__vite__mapDeps([7,5,3,8])).then(e=>({default:e.AssetGenWorkspace}))),YO=R.lazy(()=>$t(()=>import("./HomeWorkspace-DwRS4Cim.js"),[]).then(e=>({default:e.HomeWorkspace}))),XO=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-DCtxfzy1.js"),[]).then(e=>({default:e.PromptLibraryPanel})));function QO(){return d.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function JO(){LO(),qO();const{locale:e}=ge(),a=w(j=>j.hydrateHistory),i=w(j=>j.loadSessions),o=w(j=>j.syncCapabilities),s=w(j=>j.startInFlightPolling),c=w(j=>j.reconcileInflight),m=w(j=>j.syncFromStorage),p=w(j=>j.settingsOpen),h=w(j=>j.unseenGeneratedCount),g=w(j=>j.historyStripLayout),S=w(j=>j.workspaceProfile),v=w(j=>j.uiMode),y=v==="agent"&&lr?"agent":v==="node"&&ir?"node":v==="home"?"home":v==="assets"?"assets":v==="asset-gen"?"asset-gen":"classic",x=y==="agent",E=y==="assets",P=y==="asset-gen",I=y==="home",k=ka(),C=Ei(S),_=!k&&y==="classic"&&C.composerPlacement==="bottom"&&C.multimodeHistoryGrouping==="sequence",N=!_&&!x&&!E&&!P&&!I;return zO(h),R.useEffect(()=>{document.documentElement.lang=e},[e]),R.useEffect(()=>{o(),a(),i(),c(),s(),lo(),CT(()=>c()),wT(j=>{j==="failed"&&console.warn("[SSE] connection failed after multiple retries")})},[a,i,c,s,o]),R.useEffect(()=>{const j=$=>{const L=$.detail?.assetId;L&&w.getState().openAssetDetail(L)};return window.addEventListener("ima2:open-assets-detail",j),()=>window.removeEventListener("ima2:open-assets-detail",j)},[]),R.useEffect(()=>{const j=$=>{$.key&&($.key==="ima2.inFlight"||$.key==="ima2.selectedFilename")&&m()};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[m]),R.useEffect(()=>{const j=()=>{o1(w.getState)};return window.addEventListener("beforeunload",j),()=>{window.removeEventListener("beforeunload",j)}},[]),d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:`app${S==="prompt-studio"?" app--prompt-studio":""}${p?" app--settings-open":""}${N&&g==="horizontal"?" app--history-horizontal":""}${N&&g==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":g,"data-mobile":k?"1":void 0,"data-ui-mode":y,children:[d.jsx(kO,{}),I?null:d.jsx(P2,{}),d.jsx(bO,{}),N?d.jsx(SL,{}):null,d.jsx(R.Suspense,{fallback:d.jsx(QO,{}),children:p?d.jsx(HO,{}):y==="classic"?_?d.jsx(bP,{}):d.jsx(em,{}):y==="node"?d.jsx(UO,{}):y==="card-news"?d.jsx(BO,{}):y==="agent"?d.jsx(VO,{}):y==="assets"?d.jsx(KO,{}):y==="asset-gen"?d.jsx($O,{}):y==="home"?d.jsx(YO,{}):d.jsx(em,{})}),y==="agent"||y==="card-news"||y==="assets"||y==="asset-gen"||y==="home"?null:d.jsx(fL,{})]}),d.jsx(dO,{}),d.jsx(fO,{}),d.jsx(xL,{}),d.jsx(AL,{}),d.jsx(sO,{}),d.jsx(uO,{}),d.jsx(mO,{}),d.jsx(pO,{}),d.jsx(MO,{}),d.jsx(hO,{}),y==="card-news"?d.jsx(R.Suspense,{fallback:null,children:d.jsx(XO,{})}):null]})}function WO(){if(window.location.protocol!=="http:"||window.location.hostname!=="localhost")return!1;const e=new URL(window.location.href);return e.hostname="127.0.0.1",window.location.replace(e.toString()),!0}WO()||cT.createRoot(document.getElementById("root")).render(d.jsx(R.StrictMode,{children:d.jsx(JO,{})}));export{ZL as $,$u as A,vs as B,Js as C,i0 as D,Cj as E,xn as F,r0 as G,cS as H,Na as I,Rj as J,Nj as K,kj as L,vt as M,gL as N,o0 as O,tR as P,Eb as Q,Hl as R,HM as S,CM as T,Tj as U,d0 as V,BM as W,Ij as X,JT as Y,bj as Z,_1 as _,R as a,vS as a0,_j as a1,Pj as a2,Mj as a3,Aj as a4,Ej as a5,im as a6,_b as a7,IL as a8,Hm as a9,ej as aA,sj as aB,aj as aC,z2 as aD,nj as aE,dP as aF,pv as aG,tj as aH,Z as aI,uj as aJ,cj as aK,mj as aL,pj as aM,dj as aN,ZO as aO,fj as aP,gj as aQ,hj as aR,yj as aS,vj as aT,$t as aa,xj as ab,io as ac,Sj as ad,Ks as ae,zm as af,yS as ag,Ot as ah,_S as ai,AO as aj,CO as ak,ir as al,wO as am,lr as an,EO as ao,cv as ap,uo as aq,TM as ar,sP as as,cP as at,Zu as au,ij as av,rj as aw,ys as ax,lj as ay,oj as az,w as b,Cv as c,ML as d,p1 as e,WE as f,eT as g,Mn as h,kn as i,d as j,ro as k,wj as l,M1 as m,u1 as n,kb as o,QT as p,ue as q,am as r,ka as s,tr as t,ge as u,RS as v,XR as w,NS as x,PP as y,kS as z};
30
+ `);function sP({imageOverride:e=null,onAfterDeleteFocus:a}){const{t:i}=ge(),o=w(se=>se.currentImage),s=w(se=>se.showToast),c=w(se=>se.insertPromptToComposer),m=w(se=>se.createRootNodeFromHistoryItem),p=w(se=>se.trashHistoryItem),h=w(se=>se.saveToAssets),g=w(se=>se.permanentlyDeleteHistoryItemByClick),S=w(se=>se.canvasOpen),v=w(se=>se.openCanvas),[y,x]=R.useState(!1),[E,P]=R.useState(!1),[I,k]=R.useState("idle"),[C,_]=R.useState(!1),[N,j]=R.useState(!1),[$,L]=R.useState(!1),[J,re]=R.useState(!1),he=R.useRef(null);R.useEffect(()=>{let se=!0;return jm().then(qe=>{se&&re(qe.some(ot=>ot.id==="runway"&&ot.status.state==="connected"))}).catch(()=>{}),()=>{se=!1}},[]);const V=async se=>{if(!ee?.filename||$)return;const qe=tP(ee.filename,se);if(!qe){s(i("result.upscaleInvalid"),!0);return}L(!0);try{await ue("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(qe)}),j(!1),s(i("result.upscaleStarted"))}catch{s(i("result.upscaleFailed"),!0)}finally{L(!1)}};R.useEffect(()=>()=>he.current?.abort(),[]);const ee=e??o;if(!ee)return null;const oe=gt(ee),Ne=oe?ee.url||ee.image:"",ne=!!ee.filename,H=!!ee.filename&&!oe,ae=oe&&!!ee.filename,be=!!((ee.provider==="grok"||ee.provider==="grok-api")&&!oe&&ee.providerUrl&&ee.createdAt&&Date.now()-ee.createdAt<$y),Se=async()=>{if(!(!ee.filename||E)){P(!0);try{await w.getState().animateImage(ee.filename,ee.prompt??void 0)&&s(i("toast.animateDone"))}catch(se){const qe=se instanceof Error?se.message:i("toast.animateFailed");s(qe,!0)}finally{P(!1)}}},T=async()=>{if(!ee.filename||I==="pending")return;const se=`vext_${crypto.randomUUID()}`,qe=new AbortController;he.current=qe,k("pending");try{const ot=await H2({requestId:se,sourceVideoId:ee.filename,prompt:ee.prompt?.trim()||void 0,provider:ee.provider==="grok-api"?"grok-api":"grok",model:ee.model??void 0},qe.signal);w.getState().addHistoryItem(q2(ot,ee)),k("idle"),s(i("toast.animateDone"))}catch(ot){const St=ot instanceof DOMException&&ot.name==="AbortError";k(St?"idle":"error"),St||s(ot instanceof Error?ot.message:i("toast.animateFailed"),!0)}finally{he.current===qe&&(he.current=null)}},F=()=>he.current?.abort(),W=()=>{const se=document.createElement("a");se.href=ee.image,se.download=ee.filename||"generated.png",se.click()},U=async se=>{const ot=await(await fetch(se)).blob();let St;if(ot.type==="image/png")St=ot;else{const xt=new Image;xt.crossOrigin="anonymous";const nn=URL.createObjectURL(ot);await new Promise((fn,et)=>{xt.onload=()=>fn(),xt.onerror=et,xt.src=nn});const Yt=document.createElement("canvas");Yt.width=xt.naturalWidth,Yt.height=xt.naturalHeight,Yt.getContext("2d").drawImage(xt,0,0),URL.revokeObjectURL(nn),St=await new Promise((fn,et)=>Yt.toBlob(On=>On?fn(On):et(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":St})])},le=async()=>{try{if(oe){const se=await cr(Ne);await U(se)}else await U(ee.image);s(i(oe?"toast.frameCopied":"toast.imageCopied"))}catch{s(i("toast.copyFailed"),!0)}},pe=async()=>{try{const se=await yb(Ne);await U(se),s(i("toast.frameCopied"))}catch{s(i("toast.copyFailed"),!0)}},xe=async()=>{try{const se=await vb(Ne);await U(se),s(i("toast.frameCopied"))}catch{s(i("toast.copyFailed"),!0)}},Oe=async()=>{if(ee.prompt)try{await navigator.clipboard.writeText(ee.prompt),s(i("toast.promptCopied"))}catch{s(i("clipboard.writeFailed"),!0)}},Re=async se=>{try{await navigator.clipboard.writeText(se),s(i("toast.metadataCopied"))}catch{s(i("clipboard.writeFailed"),!0)}},Ze=async()=>{let se={ok:!1,isVideo:!1,hasPrompt:!1};try{se=await Ws(ee)}catch{}S&&e&&c({id:rP,name:iP,text:lP});const qe=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');qe&&(qe.focus(),qe.setSelectionRange(qe.value.length,qe.value.length)),s(i(se.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ie=async()=>{if(oe||!ee.providerUrl||!ee.createdAt||Date.now()-ee.createdAt>=$y){s(i("toast.continueAsUrlExpired"),!0);return}try{await bS(ee)}catch{}const se=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');se&&(se.focus(),se.setSelectionRange(se.value.length,se.value.length)),s(i("toast.continueAsUrlStarted"))},lt=async()=>{if(!(!ee.filename||y)){x(!0);try{const se=await DT({filename:ee.filename});s(i("toast.comfyExported",{filename:se.uploadedFilename}))}catch(se){const qe=se instanceof Error?se.code:void 0;s(i(qe==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":qe==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":qe==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{x(!1)}}},at=()=>{m(ee),s(i("toast.nodeRootCreated"))},st=async()=>{try{await p(ee)}finally{a?.()}},bt=async()=>{try{await g(ee)}finally{a?.()}};return d.jsxs("div",{className:"result-actions",children:[d.jsx("button",{type:"button",className:"action-btn",onClick:W,children:i("result.download")}),d.jsx("button",{type:"button",className:`action-btn${oe?" action-btn--frame":""}`,onClick:le,children:i(oe?"result.copyLastFrame":"result.copyImage")}),oe&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:pe,children:i("result.copyFirstFrame")}),d.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:xe,children:i("result.copyMidFrame")})]}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Oe()},children:i("result.copyPrompt")}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const se=await h(ee);s(i(se?"chain.savedToAssets":"chain.saveToAssetsFailed"),!se)})()},title:i("chain.saveToAssets"),children:i("chain.saveToAssets")}),d.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:Ze,title:i("result.continueHereTitle"),children:i("result.continueHere")}),be&&d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ie()},title:i("result.continueAsUrlTitle"),children:i("result.continueAsUrl")}),H&&d.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Se()},disabled:E,title:i("result.animateTitle"),children:i(E?"result.animating":"result.animate")}),J&&ee.filename&&(oe?d.jsx("button",{type:"button",className:"action-btn",disabled:$,onClick:()=>{V({})},title:i("result.upscaleTitle"),children:i($?"inflight.streaming":"result.upscale")}):d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn",disabled:$,onClick:()=>j(se=>!se),title:i("result.upscaleTitle"),children:i("result.upscale")}),N?d.jsx(oP,{pending:$,onSubmit:se=>{V(se)},onClose:()=>j(!1)}):null]})),ae&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn",onClick:T,disabled:I==="pending","aria-busy":I==="pending",title:i("result.extendTitle")??"이어가기",children:I==="pending"?i("inflight.streaming"):I==="error"?i("gallery.retry"):i("result.extend")??"이어가기"}),I==="pending"&&d.jsx("button",{type:"button",className:"action-btn",onClick:F,children:i("common.cancel")})]}),d.jsx("button",{type:"button",className:"action-btn",onClick:at,title:i("result.firstNodeTitle"),children:i("result.firstNode")}),d.jsx("button",{type:"button",className:"action-btn",onClick:()=>_(!0),title:i("result.infoTitle"),children:i("result.info")}),!S&&d.jsx("button",{type:"button",className:"action-btn",onClick:v,title:i("canvas.open"),"aria-label":i("canvas.openAria"),children:d.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:d.jsx("path",{d:"M4 4h8v8M12 4l-8 8"})})}),ee.filename&&d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{st()},title:i("result.deleteTitle"),children:i("result.delete")}),d.jsxs("details",{className:"result-actions__more",children:[d.jsx("summary",{className:"action-btn",children:i("result.more")}),d.jsxs("div",{className:"result-actions__menu",children:[ne&&d.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{lt()},title:i("result.sendToComfyUITitle"),disabled:y,children:i("result.sendToComfyUI")}),d.jsx("button",{type:"button",className:"result-actions__menu-item result-actions__danger-item",onClick:()=>{bt()},children:i("result.permanentDelete")})]})]})]}),C&&d.jsx(Z2,{item:ee,onClose:()=>_(!1),onCopy:se=>{Re(se)}})]})}function cP({prompt:e,onCopy:a}){const{t:i}=ge(),o=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),a())};return d.jsx("div",{className:"result-prompt",onClick:a,onKeyDown:o,role:"button",tabIndex:0,title:i("result.copyPrompt"),"aria-label":i("result.copyPrompt"),children:d.jsx("span",{className:"result-prompt__text",children:e})})}function dP(){const e=w(y=>{const x=y.multimodePreviewFlightId;return x?y.multimodeSequences[x]??null:null}),a=w(y=>y.cancelMultimode),i=w(y=>{const x=y.multimodePreviewFlightId;return!!(x&&(y.activeFlightIds.has(x)||y.inFlight.some(E=>E.id===x)))}),o=w(y=>y.selectHistory),s=w(y=>y.currentImage),c=w(y=>y.openCanvas),{t:m}=ge(),p=y=>{o(y)},h=y=>{o(y),c()};if(!e)return null;const g=new Map,S=e.partials.filter(y=>y.index==null);for(const y of e.partials)y.index!=null&&g.set(y.index,y);const v=Array.from({length:e.requested},(y,x)=>{const E=e.images[x],P=g.get(x)??(E?void 0:S.shift());return{index:x,image:E,partial:P}});return d.jsxs("section",{className:"multimode-sequence","aria-live":"polite",children:[d.jsxs("div",{className:"multimode-sequence__header",children:[d.jsxs("div",{children:[d.jsx("div",{className:"multimode-sequence__title",children:m("multimode.sequenceTitle")}),d.jsx("div",{className:"multimode-sequence__meta",children:m("multimode.sequenceProgress",{returned:e.returned,requested:e.requested})})]}),i?d.jsx("button",{type:"button",className:"secondary-btn",onClick:a,children:m("multimode.cancel")}):null]}),d.jsx("div",{className:`multimode-sequence__grid count-${Math.min(e.requested,4)}`,children:v.map(({index:y,image:x,partial:E})=>{const P=x&&s?.filename&&x.filename===s.filename;return d.jsxs("article",{className:`multimode-sequence__slot${x?" done":""}${P?" active":""}`,onClick:x?()=>p(x):void 0,onDoubleClick:x?()=>h(x):void 0,role:x?"button":void 0,tabIndex:x?0:void 0,onKeyDown:x?I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),p(x))}:void 0,children:[d.jsx("div",{className:"multimode-sequence__badge",children:m("multimode.stageLabel",{index:y+1})}),x?d.jsx("img",{src:x.url??x.image,alt:m("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):E?d.jsx("img",{src:E.image,alt:m("multimode.partialAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):e.status==="pending"||e.status==="complete"?d.jsx("div",{className:"multimode-sequence__skeleton"}):d.jsx("div",{className:"multimode-sequence__empty",children:e.status==="error"?m("multimode.error"):e.status==="empty"?m("multimode.empty"):e.status==="canceled"?m("multimode.canceled"):e.status==="partial"?m("multimode.notReturned"):m("multimode.generating")})]},x?.filename??y)})})]})}function uP({zoom:e,minZoom:a,maxZoom:i,onZoomIn:o,onZoomOut:s,onReset:c,labels:m}){return d.jsxs("div",{className:"viewer-controls","aria-label":m.controls,onPointerDown:p=>p.stopPropagation(),onDoubleClick:p=>p.stopPropagation(),onWheel:p=>p.stopPropagation(),children:[d.jsx("button",{type:"button",className:"viewer-control-btn",onClick:p=>{p.stopPropagation(),s()},disabled:e<=a,"aria-label":m.zoomOut,children:"-"}),d.jsxs("button",{type:"button",className:"viewer-control-btn viewer-control-btn--label",onClick:p=>{p.stopPropagation(),c()},"aria-label":m.reset,children:[Math.round(e*100),"%"]}),d.jsx("button",{type:"button",className:"viewer-control-btn",onClick:p=>{p.stopPropagation(),o()},disabled:e>=i,"aria-label":m.zoomIn,children:"+"})]})}function ys(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function mP(e,a,i,o){if(!e)return!1;const s=a.find(c=>c.filename===e);return s?!!s.isFavorite:o!==void 0?o:i.has(e)}function _j(e,a){return a?e.filter(i=>i!=="starred"):Array.from(new Set([...e,"starred"]))}const no=1,IS=5,as=.22;function pP(e){return Math.min(IS,Math.max(no,e))}function fP(e){const[a,i]=R.useState(1),[o,s]=R.useState({x:0,y:0}),[c,m]=R.useState(null),p=R.useRef(0),h=R.useRef(null),g=R.useCallback(()=>{cancelAnimationFrame(p.current),p.current=0,h.current=null,i(1),s({x:0,y:0}),m(null)},[]);R.useEffect(()=>{g()},[g,e]),R.useEffect(()=>()=>{cancelAnimationFrame(p.current)},[]);const S=R.useCallback(I=>{i(k=>{const C=pP(k+I);return C<=no?(s({x:0,y:0}),no):Number(C.toFixed(2))})},[]),v=R.useCallback(I=>{I.preventDefault(),S(I.deltaY<0?as:-as)},[S]),y=R.useCallback(()=>{if(a>no){g();return}i(2)},[g,a]),x=R.useCallback(I=>{a<=no||I.button!==0||(I.preventDefault(),I.currentTarget.setPointerCapture(I.pointerId),m({pointerId:I.pointerId,startX:I.clientX,startY:I.clientY,baseX:o.x,baseY:o.y}))},[o.x,o.y,a]),E=R.useCallback(I=>{if(!c||c.pointerId!==I.pointerId)return;const k={x:c.baseX+I.clientX-c.startX,y:c.baseY+I.clientY-c.startY};h.current=k,cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{s(k),h.current=null})},[c]),P=R.useCallback(I=>{!c||c.pointerId!==I.pointerId||(cancelAnimationFrame(p.current),p.current=0,h.current&&(s(h.current),h.current=null),m(null),I.currentTarget.releasePointerCapture(I.pointerId))},[c]);return{zoom:a,pan:o,reset:g,zoomIn:()=>S(as),zoomOut:()=>S(-as),handleWheel:v,handleDoubleClick:y,handlePointerDown:x,handlePointerMove:E,handlePointerUp:P}}const gP=R.lazy(()=>$t(()=>import("./index-VXkP0z69.js"),[]).then(e=>({default:e.CanvasModeWorkspace})));function hP(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function yP(e){if(!e)return null;const a=e.match(/^(\d+)x\1$/);return a?`${a[1]}²`:e.replace("x","×")}function vP(e){const a=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||a.startsWith("data:"))return a;const i=a.includes("?")?"&":"?";return`${a}${i}canvasMergedAt=${e.canvasMergedAt}`}function em(){const e=w(T=>T.currentImage),a=w(T=>T.importLocalImageToHistory),i=w(T=>{const F=T.multimodePreviewFlightId;return F?T.multimodeSequences[F]??null:null}),o=w(T=>T.selectHistoryShortcutTarget),s=w(T=>T.trashHistoryItem),c=w(T=>T.permanentlyDeleteHistoryItemByShortcut),m=w(T=>T.markGeneratedResultsSeen),p=w(T=>T.activeGenerations),h=w(T=>T.canvasOpen),g=w(T=>T.openCanvas),S=w(T=>T.showToast),v=w(T=>T.history),y=w(T=>T.galleryFavorites),x=w(T=>T.toggleGalleryFavorite),{t:E}=ge(),[P,I]=R.useState(!1),[k,C]=R.useState(null),{creatingBlankCanvas:_,createBlankCanvas:N}=z2(),j=R.useRef(null),$=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,L=fP($),J=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),S(E("toast.promptCopied")))},re=T=>{if(T.key==="Delete"||T.key==="Backspace"){if(!e||T.target!==T.currentTarget||ys(T.target))return;if(T.preventDefault(),T.shiftKey){c(e);return}s(e);return}T.key!=="ArrowLeft"&&T.key!=="ArrowRight"&&T.key!=="Home"&&T.key!=="End"||T.target===T.currentTarget&&(ys(T.target)||(T.preventDefault(),T.key==="ArrowLeft"?o("previous"):T.key==="ArrowRight"?o("next"):T.key==="Home"?o("first"):T.key==="End"&&o("last")))},he=T=>{ys(T.target)||(m(),T.currentTarget.focus())},V=R.useCallback(()=>{window.requestAnimationFrame(()=>j.current?.focus())},[]),ee=async()=>{const T=e?.filename;if(!(!e||!T||k===T)){C(T);try{await x(e)}finally{C(F=>F===T?null:F)}}},oe=R.useCallback(T=>{Array.from(T.dataTransfer.types).includes("Files")&&(T.preventDefault(),I(F=>F||!0))},[]),Ne=R.useCallback(T=>{T.currentTarget.contains(T.relatedTarget)||I(!1)},[]),ne=R.useCallback(async T=>{if(!Array.from(T.dataTransfer.types).includes("Files"))return;T.preventDefault(),I(!1);const F=Array.from(T.dataTransfer.files).filter(W=>/^image\/(png|jpeg|webp)$/.test(W.type));F.length!==0&&await a(F[0])},[a]);if(h&&e)return d.jsx(R.Suspense,{fallback:d.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:d.jsx(gP,{currentImage:e})});const H=hP(e?.quality),ae=yP(e?.size),ce=Cv(e?.model,e?.provider),be=e?vP(e):null,Se=mP(e?.filename,v,y,e?.isFavorite);return d.jsxs("main",{className:`canvas${P?" canvas--drop-active":""}`,onDragOver:oe,onDragLeave:Ne,onDrop:ne,children:[P?d.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:d.jsx("span",{className:"canvas__drop-hint",children:E("canvas.drop.hint")})}):null,d.jsx("div",{className:`progress-bar${p>0?" active":""}`}),i?d.jsx(dP,{}):e&&be?d.jsxs("div",{ref:j,className:"result-container visible",tabIndex:0,onMouseDown:he,onKeyDown:re,"aria-label":E("canvas.imageViewerAria"),children:[d.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${L.zoom>no?" canvas-annotation-frame--zoomed":""}`,onWheel:L.handleWheel,onDoubleClick:L.handleDoubleClick,onPointerDown:L.handlePointerDown,onPointerMove:L.handlePointerMove,onPointerUp:L.handlePointerUp,onPointerCancel:L.handlePointerUp,children:[e.filename?d.jsx(vS,{variant:"result",active:Se,busy:k===e.filename,label:E(Se?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:ee}):null,gt(e)?d.jsxs(d.Fragment,{children:[d.jsx("video",{className:"result-img",src:be,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${L.pan.x}px, ${L.pan.y}px) scale(${L.zoom})`}},$??void 0),d.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:T=>{T.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi(e))),T.dataTransfer.effectAllowed="copy"},title:E("canvas.dragToComposer"),"aria-label":E("canvas.dragToComposer"),children:E("canvas.dragHint")})]}):d.jsxs(d.Fragment,{children:[d.jsx("img",{className:"result-img",src:be,alt:E("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${L.pan.x}px, ${L.pan.y}px) scale(${L.zoom})`},onDoubleClick:T=>{T.stopPropagation(),g()}},$??void 0),d.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:T=>{T.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),T.dataTransfer.effectAllowed="copy"},title:E("canvas.dragToComposer"),"aria-label":E("canvas.dragToComposer"),children:E("canvas.dragHint")})]}),d.jsx(uP,{zoom:L.zoom,minZoom:no,maxZoom:IS,onZoomIn:L.zoomIn,onZoomOut:L.zoomOut,onReset:L.reset,labels:{controls:E("viewer.controls"),zoomIn:E("viewer.zoomIn"),zoomOut:E("viewer.zoomOut"),reset:E("viewer.reset")}})]}),d.jsx("div",{className:"result-meta",children:(gt(e)?[e.elapsed!=null?`${e.elapsed}s`:null,e.video?.duration?`${e.video.duration}s clip`:null,e.video?.resolution??null,e.video?.aspectRatio??null,Bb(e.videoContinuity),ce]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?E("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,WE(e.reasoningEffort),H,ae,ce]).filter(T=>!!T).join(" · ")}),d.jsx(sP,{onAfterDeleteFocus:V}),e.prompt?d.jsx(cP,{prompt:e.prompt,onCopy:J}):null]}):e?null:d.jsxs("div",{className:"canvas__blank-entry",children:[d.jsx("div",{className:"canvas__blank-sheet","aria-hidden":!0}),d.jsxs("div",{className:"canvas__blank-copy",children:[d.jsx("strong",{children:E("canvas.blank.title")}),d.jsx("span",{children:E("canvas.blank.subtitle")})]}),d.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{N()},disabled:_,children:E(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function bP(){return d.jsxs("div",{className:"classic-workspace",children:[d.jsx("div",{className:"classic-workspace__stage",children:d.jsx(em,{})}),d.jsxs("div",{className:"classic-workspace__dock",children:[d.jsx(qm,{variant:"bottom"}),d.jsx(Um,{})]})]})}const ES="ima2.customSizeSlots";function SP(e){if(!e||typeof e!="object")return!1;const a=e;return typeof a.id=="string"&&typeof a.w=="number"&&typeof a.h=="number"&&typeof a.updatedAt=="number"}function xP(){try{const e=localStorage.getItem(ES);if(!e)return[];const a=JSON.parse(e);return Array.isArray(a)?Wo(a.filter(SP)):[]}catch{return[]}}function AP(e){try{localStorage.setItem(ES,JSON.stringify(Wo(e)))}catch{}}function TP(e,a,i){return Gs({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:a,ratio:i,updatedAt:Date.now()})}function ci(e){return e.map(a=>({value:a.value,label:a.label,sub:a.sub}))}function CP(){const e=w(ne=>ne.sizePreset),a=w(ne=>ne.setSizePreset),i=w(ne=>ne.customW),o=w(ne=>ne.customH),s=w(ne=>ne.setCustomSize),{t:c}=ge(),[m,p]=R.useState(String(i)),[h,g]=R.useState(String(o)),[S,v]=R.useState(e==="custom"),[y,x]=R.useState(()=>xP()),[E,P]=R.useState(null),[I,k]=R.useState("free"),C=e==="custom",_=pm(m,h,i,o),N=gR().filter(ne=>ne.value==="auto");R.useEffect(()=>{p(String(i)),g(String(o))},[i,o]),R.useEffect(()=>{C||(v(!1),P(null))},[C]);function j(ne){x(ne),AP(ne)}function $(){const ne=_n(m,i),H=_n(h,o);s(ne,H),p(String(ne)),g(String(H))}function L(ne){ne.key==="Enter"&&(ne.preventDefault(),$())}function J(){a("custom"),v(!0),P(y.length>=Jo?y[0]?.id??null:null)}function re(ne){a(ne),ne!=="custom"&&(v(!1),P(null))}function he(ne){a("custom"),s(ne.w,ne.h),p(String(ne.w)),g(String(ne.h)),v(!1),P(ne.id)}function V(ne){k(ne.id);const H=sR(ne);H&&(p(String(H.w)),g(String(H.h)))}function ee(){const ne=TP(_.w,_.h,I),H=y.length>=Jo&&E?dR(y,E,ne):cR(y,ne);j(H),a("custom"),s(_.w,_.h),p(String(_.w)),g(String(_.h)),P(ne.id),v(!1)}const oe=_.reasons.length>0?_.reasons.map(ne=>c(`size.adjustedReasons.${ne}`)).join(", "):c("size.noAdjustment"),Ne=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?c("size.squareMaxHint",{size:`${uy}×${uy}`}):null;return d.jsxs("div",{className:"option-group size-picker",children:[d.jsx("div",{className:"section-title",children:c("size.title")}),d.jsx(xn,{title:"",items:ci(uR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(mR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(pR),value:e,onChange:re}),d.jsx(xn,{title:"",items:ci(fR),value:e,onChange:re}),d.jsxs("div",{className:"option-row size-picker__quick-row",children:[ci(N).map(ne=>d.jsxs("button",{type:"button",className:`option-btn${e===ne.value?" active":""}`,onClick:()=>re(ne.value),children:[ne.label,ne.sub?d.jsxs(d.Fragment,{children:[d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:ne.sub})]}):null]},ne.value)),d.jsxs("button",{type:"button",className:`option-btn${C?" active":""}`,onClick:J,children:[c("size.customPlus"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:c("size.customSub")})]})]}),y.length>0?d.jsx("div",{className:"option-row size-picker__slot-row",children:y.map(ne=>d.jsxs("button",{type:"button",className:`option-btn size-picker__slot${C&&i===ne.w&&o===ne.h?" active":""}`,onClick:()=>he(ne),children:[ne.w,"×",ne.h,d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:ne.ratio||c("size.customSlot")})]},ne.id))}):null,S?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"size-picker__ratio-row",children:iR.map(ne=>d.jsx("button",{type:"button",className:`size-picker__ratio${I===ne.id?" active":""}`,onClick:()=>V(ne),children:ne.id==="free"?c("size.ratioFree"):ne.label},ne.id))}),d.jsxs("div",{className:"option-row size-picker__custom-row",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:m,onChange:ne=>p(ne.target.value.replace(/\D/g,"")),onBlur:$,onKeyDown:L,placeholder:c("size.width")}),d.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:h,onChange:ne=>g(ne.target.value.replace(/\D/g,"")),onBlur:$,onKeyDown:L,placeholder:c("size.height")})]}),d.jsxs("div",{className:"size-picker__preview",children:[d.jsx("span",{children:c("size.normalizedPreview")}),d.jsx("strong",{children:lR(_.w,_.h)})]}),d.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:oe}),Ne?d.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:Ne}):null,y.length>=Jo?d.jsxs("div",{className:"size-picker__replace-row",children:[d.jsx("span",{children:c("size.replaceCustomSlot")}),y.map(ne=>d.jsxs("button",{type:"button",className:`size-picker__replace${E===ne.id?" active":""}`,onClick:()=>P(ne.id),children:[ne.w,"×",ne.h]},ne.id))]}):null,d.jsx("button",{type:"button",className:"size-picker__save",onClick:ee,children:y.length>=Jo?c("size.replaceCustomSlot"):c("size.saveCustomSlot")}),d.jsx("div",{className:"size-hint",children:c("size.hint")})]}):null]})}const ku=[1,2,4];function wP(){const e=w(C=>C.count),a=w(C=>C.setCount),i=w(C=>C.uiMode),o=w(C=>C.multimode),s=w(C=>C.multimodeMaxImages),c=w(C=>C.setMultimodeMaxImages),{t:m}=ge(),p=i==="classic"&&o,h=p?s:e,g=p?c:a,[S,v]=R.useState(!ku.includes(h)),[y,x]=R.useState(String(h));R.useEffect(()=>{v(!ku.includes(h)),x(String(h))},[p,h]);function E(C=y){const _=Yu(Number.parseInt(C,10));g(_),x(String(_))}function P(C){v(!1),x(String(C)),g(C)}function I(C){const _=Yu(h+C);v(!0),x(String(_)),g(_)}function k(C){C.key==="Enter"&&(C.preventDefault(),E())}return d.jsxs("div",{className:"option-group count-picker",children:[d.jsx("div",{className:"section-title",children:m(p?"multimode.maxStages":"count.title")}),d.jsxs("div",{className:"option-row",children:[ku.map(C=>d.jsx("button",{type:"button",className:`option-btn${h===C&&!S?" active":""}`,onClick:()=>P(C),children:C},C)),d.jsx("button",{type:"button",className:`option-btn${S?" active":""}`,onClick:()=>{v(C=>!C),x(String(h))},children:m("count.customPlus")})]}),S?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"count-picker__custom",children:[d.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>I(-1),"aria-label":m("count.decrease"),children:"-"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"count-picker__input",value:y,onChange:C=>x(C.target.value.replace(/\D/g,"")),onBlur:()=>E(),onKeyDown:k,"aria-label":m("count.customLabel")}),d.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>I(1),"aria-label":m("count.increase"),children:"+"})]}),d.jsx("p",{className:"option-help",children:h>=5?m(p?"multimode.highCountHint":"count.highCountHint"):m(p?"multimode.minMaxHint":"count.minMaxHint")})]}):null]})}const IP={low:{"1024x1024":.006,"1024x1536":.005,"1536x1024":.005,"1024x1360":.005,"1360x1024":.005,"1024x1824":.006,"1824x1024":.006,"2048x2048":.012,"2048x1152":.009,"1152x2048":.009,"3840x2160":.023,"2160x3840":.023,auto:.006},medium:{"1024x1024":.053,"1024x1536":.041,"1536x1024":.041,"1024x1360":.041,"1360x1024":.041,"1024x1824":.05,"1824x1024":.05,"2048x2048":.106,"2048x1152":.08,"1152x2048":.08,"3840x2160":.2,"2160x3840":.2,auto:.053},high:{"1024x1024":.211,"1024x1536":.165,"1536x1024":.165,"1024x1360":.165,"1360x1024":.165,"1024x1824":.2,"1824x1024":.2,"2048x2048":.422,"2048x1152":.32,"1152x2048":.32,"3840x2160":.8,"2160x3840":.8,auto:.211}},EP={512:.045,"1K":.067,"2K":.101,"4K":.151},RP={512:.134,"1K":.134,"2K":.134,"4K":.24};function NP(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function kP(e,a){const i=e.match(/^(\d+)x(\d+)$/);if(!i)return .003;const o=Math.max(Number(i[1]),Number(i[2])),s=NP(o),m=a==="nano-banana-pro"?RP:EP;return m[s]??m["1K"]??.003}function _P(e,a,i,o){return i==="gemini-api"?kP(a,o):IP[e]?.[a]??0}function MP(){const{t:e}=ge(),a=w(y=>y.provider),i=w(y=>y.quality),o=w(y=>y.multimode),s=w(y=>y.multimodeMaxImages),m=w(y=>y.getResolvedSize)(),p=w(y=>y.imageModel),h=a==="oauth"||a==="grok"||a==="agy",g=_P(i,m,a,p),S=h?e("cost.free"):o?e("cost.multimodeApprox",{amount:(g*s).toFixed(3),count:s}):e("cost.approx",{amount:g.toFixed(3)}),v=h?"var(--green)":void 0;return d.jsxs("div",{className:"cost-estimate",children:[d.jsx("span",{children:e("cost.label")}),d.jsx("span",{className:"price",style:v?{color:v}:void 0,children:S})]})}function RS(){const[e,a]=R.useState(null);return R.useEffect(()=>{let i=!1,o=null;const s=async()=>{try{const c=await hT();if(i)return;a(c),c.status==="starting"&&(o=setTimeout(s,3e3))}catch{i||a(null)}};return s(),()=>{i=!0,o&&clearTimeout(o)}},[]),e}function PP(){const[e,a]=R.useState(null),[i,o]=R.useState(!1);return R.useEffect(()=>{let s=!1;return yT().then(c=>{s||a(c)}).catch(()=>{s||o(!0)}),()=>{s=!0}},[]),{data:e,error:i}}function NS(){const[e,a]=R.useState(null);return R.useEffect(()=>{let i=!1,o=null;const s=async()=>{try{const c=await fetch("/api/grok/status");if(i)return;const m=await c.json();a(m),m.status!=="ready"&&(o=setTimeout(s,1e4))}catch{i||a({status:"offline"})}};return s(),()=>{i=!0,o&&clearTimeout(o)}},[]),e}function kS(){const[e,a]=R.useState(null),[i,o]=R.useState(null),s=R.useCallback(async()=>{try{const m=await(await fetch("/api/keys/status")).json();a(m),o(null)}catch(c){o(c instanceof Error?c:new Error(String(c)))}},[]);return R.useEffect(()=>{let c=!1,m=null;return(async()=>(await s(),c||(m=setInterval(s,3e4))))(),()=>{c=!0,m&&clearInterval(m)}},[s]),{data:e,error:i,mutate:s}}function _S(){const{t:e}=ge(),a=RS(),{data:i}=PP(),o=NS(),{data:s}=kS(),c=a?.status==="ready";let m=e("provider.oauthNotReady"),p;a?.status==="auth_required"?(m=e("provider.codexLoginRequired"),p=e("provider.codexLoginHint")):a?.status==="starting"?m=e("provider.oauthStarting"):a||(m=e("provider.serverUnreachable"));const h=i?.apiKeyValid===!0,g=o?.status==="ready",S=o?o.status==="offline"?e("provider.grokOffline"):o.status==="no_image_model"?e("provider.grokNoImageModel"):o.status==="error"?e("provider.grokNotReady"):"":e("provider.grokNotReady"),v=s?.xai?.valid===!0,y=s?.gemini?.valid===!0||s?.vertex?.valid===!0,x=s?.atlascloud?.valid===!0,E=s?.minimax?.valid===!0;return{oauth:{ok:c,reason:m,hint:p},api:{ok:h,reason:h?"":e("provider.apiInvalid")},grok:{ok:g,reason:S,hint:g?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:v,reason:v?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:y,reason:y?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:x,reason:x?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:E,reason:E?"":e("provider.minimaxApiKeyRequired")}}}const LP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");function uo(e,a){const i=R.useRef(null),o=R.useRef(a);return o.current=a,R.useEffect(()=>{if(!e)return;const s=document.activeElement instanceof HTMLElement?document.activeElement:null,c=i.current,m=()=>Array.from(c?.querySelectorAll(LP)??[]).filter(h=>!h.hidden&&h.getAttribute("aria-hidden")!=="true");window.requestAnimationFrame(()=>{(c?.querySelector("[data-modal-initial-focus]")??m()[0]??c)?.focus()});const p=h=>{if(h.key==="Escape"){h.preventDefault(),o.current();return}if(h.key!=="Tab")return;const g=m();if(g.length===0){h.preventDefault(),c?.focus();return}const S=g[0],v=g[g.length-1];h.shiftKey&&document.activeElement===S?(h.preventDefault(),v.focus()):!h.shiftKey&&document.activeElement===v&&(h.preventDefault(),S.focus())};return document.addEventListener("keydown",p),()=>{document.removeEventListener("keydown",p),window.requestAnimationFrame(()=>s?.focus())}},[e]),i}function OP({open:e,providerLabel:a,reason:i,hint:o,onClose:s}){const{t:c}=ge(),m=uo(e,s);if(!e)return null;const p=c("apiDisabled.title",{provider:a});return d.jsx("div",{className:"modal-backdrop",onClick:s,role:"presentation",children:d.jsxs("div",{ref:m,className:"modal",role:"dialog","aria-modal":"true","aria-label":p,tabIndex:-1,onClick:h=>h.stopPropagation(),children:[d.jsx("div",{className:"modal__title",children:p}),d.jsxs("div",{className:"modal__body",children:[d.jsx("p",{children:i}),o?d.jsx("p",{className:"modal__hint",children:o}):null]}),d.jsx("div",{className:"modal__actions",children:d.jsx("button",{type:"button",className:"modal__btn",onClick:s,"data-modal-initial-focus":!0,children:c("common.ok")})})]})})}const os="core:",_u="mcp:",Mu=[{value:"oauth",provider:"GPT",method:"OAuth"},{value:"api",provider:"GPT",method:"API"},{value:"grok",provider:"Grok",method:"OAuth"},{value:"grok-api",provider:"Grok",method:"API"},{value:"agy",provider:"Gemini",method:"agy"},{value:"gemini-api",provider:"Gemini",method:"API"},{value:"atlascloud",provider:"Atlas Cloud",method:"API"},{value:"minimax",provider:"MiniMax",method:"API"}];function Pu(e){return e.replace(/(^|-)([a-z])/g,(a,i,o)=>`${i}${o.toUpperCase()}`)}function Lu({tone:e}){return d.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function Yy(e){return e.enabled?e.status.state==="connected"?e.executable===!1?"warn":"ok":e.status.state==="connecting"||e.status.state==="auth_required"?"warn":"bad":"bad"}function Xy({mcpProviders:e}){const{t:a}=ge(),i=w(_=>_.provider),o=w(_=>_.mcpProvider??null),s=w(_=>_.setProvider),c=_S(),[m,p]=R.useState(null),h=_=>{const N=c[_.value];return N.ok?a("provider.statusReady"):N.reason},g=_=>_.enabled?_.status.state==="connected"?_.executable===!1?`${a("provider.statusConnected")} · ${a("mcp.locked")}`:a("provider.statusConnected"):_.status.state==="connecting"?a("mcp.connecting"):_.status.state==="auth_required"?a("provider.statusAuthRequired"):a("provider.statusDisconnected"):a("mcp.disabledProvider"),S=[{label:a("mcp.coreProviders"),items:Mu.map(_=>{const N=c[_.value];return{value:`${os}${_.value}`,searchText:`${_.provider} ${_.method}`,label:d.jsxs("span",{className:"provider-option",children:[d.jsx(Lu,{tone:N.ok?"ok":"bad"}),d.jsxs("span",{children:[_.provider," ",_.method]})]}),sub:h(_)}})}],v=e.filter(_=>_.enabled).map(_=>({value:`${_u}${_.id}`,searchText:Pu(_.id),label:d.jsxs("span",{className:"provider-option",children:[d.jsx(Lu,{tone:Yy(_)}),d.jsx("span",{children:Pu(_.id)})]}),sub:g(_)}));v.length>0&&S.push({label:"MCP",items:v});const y=o?`${_u}${o}`:`${os}${i}`,x=o?null:Mu.find(_=>_.value===i)??null,E=o?e.find(_=>_.id===o)??null:null,P=x?h(x):E?g(E):a("provider.statusDisconnected"),I=x?c[x.value].ok?"ok":"bad":E?Yy(E):"bad",k=x?x.method:"MCP",C=_=>{if(_.startsWith(os)){const $=_.slice(os.length),L=Mu.find(re=>re.value===$),J=c[$];if(!J.ok){p({label:L?`${L.provider} ${L.method}`:$,reason:J.reason,hint:J.hint});return}s($);return}const N=_.slice(_u.length),j=e.find($=>$.id===N);if(!j||!j.enabled||j.status.state!=="connected"){p({label:Pu(N),reason:!j||!j.enabled?a("mcp.disabledProvider"):a("mcp.disconnectedSelection")});return}Qs(N,w.setState,w.getState)};return d.jsxs("div",{className:"option-group provider-status-select","data-testid":"provider-status-select",children:[d.jsx("div",{className:"section-title",children:a("provider.authTitle")}),d.jsx(tr,{groups:S,value:y,onChange:C,portal:!0,ariaLabel:a("provider.authTitle"),className:"provider-status-select__select"}),d.jsxs("div",{className:"provider-status-line","data-tone":I,children:[d.jsx(Lu,{tone:I}),d.jsxs("span",{className:"provider-status-line__key",children:[a("provider.statusLineTitle"),":"]}),d.jsx("span",{className:"provider-status-line__value",children:P})]}),d.jsxs("div",{className:"provider-auth-chip",title:a("provider.authMethodTitle"),children:[d.jsx("span",{children:k}),I!=="bad"?d.jsx("span",{className:"provider-auth-chip__state",children:a("provider.authActive")}):null]}),d.jsx(OP,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>p(null)})]})}const jP=[{value:"1:1",label:"1:1"},{value:"3:2",label:"3:2"},{value:"2:3",label:"2:3"},{value:"4:3",label:"4:3"},{value:"3:4",label:"3:4"},{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"2:1",label:"2:1"},{value:"1:2",label:"1:2"},{value:"auto",label:"Auto"}],GP=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function DP(){const{t:e}=ge(),a=w(c=>c.grokAspectRatio),i=w(c=>c.grokResolution),o=w(c=>c.setGrokAspectRatio),s=w(c=>c.setGrokResolution);return d.jsxs("div",{className:"option-group grok-size-picker",children:[d.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")}),d.jsx("div",{className:"grok-size-picker__aspects",children:jP.map(c=>d.jsx("button",{type:"button",className:`option-btn grok-size-picker__aspect${a===c.value?" active":""}`,onClick:()=>o(c.value),children:c.label},c.value))}),d.jsx("div",{className:"section-title",style:{marginTop:8},children:e("size.grokResolutionTitle")}),d.jsx("div",{className:"grok-size-picker__resolutions",children:GP.map(c=>d.jsx("button",{type:"button",className:`option-btn grok-size-picker__res${i===c.value?" active":""}`,onClick:()=>s(c.value),children:c.label},c.value))})]})}const FP=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function zP(){const{t:e}=ge(),a=w(o=>o.imageModel),i=w(o=>o.setImageModel);return d.jsx(xn,{title:e("quality.grokModelTitle"),items:FP,value:a,onChange:i})}function MS({values:e,value:a,defaultValue:i,onChange:o,allowAuto:s=!1,disabled:c,ariaLabel:m}){const{t:p}=ge(),h=R.useId();if(e.length===0)return null;const g=a??i??e[0],S=e.reduce((E,P,I)=>Math.abs(P-g)<Math.abs(e[E]-g)?I:E,0),v=a===null,y=e[0],x=e[e.length-1];return d.jsxs("div",{className:`ctl-duration${v?" is-auto":""}${c?" is-disabled":""}`,children:[d.jsxs("div",{className:"ctl-duration__head",children:[d.jsx("output",{htmlFor:h,className:"ctl-duration__value",children:v?`${p("size.autoLabel")} · ${e[S]}s`:`${e[S]}s`}),s?d.jsx("button",{type:"button",className:`option-btn ctl-duration__auto${v?" active":""}`,"aria-pressed":v,disabled:c,onClick:()=>o(null),children:p("size.autoLabel")}):null]}),d.jsx("input",{id:h,type:"range",className:"ctl-duration__range",min:0,max:e.length-1,step:1,value:S,disabled:c,"aria-label":m,"aria-valuetext":`${e[S]}s`,onChange:E=>o(e[Number(E.target.value)]??e[0])}),d.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[d.jsxs("span",{children:[y,"s"]}),d.jsxs("span",{children:[x,"s"]})]})]})}const qP=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],UP=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),Qy=[3,5,8,10,12,15],HP=[{value:dm,label:"Grok V",sub:"Fast"},{value:Ea,label:"Grok V1.5",sub:"HD"}];function BP(){const{t:e}=ge(),a=w(V=>V.videoModelSelected),i=w(V=>V.selectVideoModel),o=w(V=>V.activeVideoRefCount()),s=w(V=>V.videoDuration),c=w(V=>V.setVideoDuration),m=w(V=>V.videoResolution),p=w(V=>V.setVideoResolution),h=w(V=>V.videoAspectRatio),g=w(V=>V.setVideoAspectRatio),S=w(V=>V.videoTopic),v=w(V=>V.setVideoTopic),y=w(V=>V.showToast),x=w(V=>V.videoContinuityLineage),E=w(V=>V.selectedPresetIds),P=w(V=>V.removePreset),I=E.map(V=>zb(V)).filter(V=>V?.category==="camera-motion"),k=o>=2?Ev:15,C=Rv(o),_=Bb(x),N=vu(a,"1080p",C),j=vu(Ea,"1080p",C),$=qP.map(V=>V.value==="1080p"?{...V,disabled:!j}:V);R.useEffect(()=>{vu(a,m,C)||p("720p")},[C,m,p,a]);const L=V=>{if(V==="1080p"){if(!j)return;N||i(Ea)}p(V)},[J,re]=R.useState(null);R.useEffect(()=>{fetch("/api/config/grok-planner").then(V=>V.json()).then(re).catch(()=>{})},[]);const he=async V=>{const ee=J?.model;re(oe=>oe?{...oe,model:V}:null);try{const oe=await fetch("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:V})});if(!oe.ok)throw new Error(`HTTP ${oe.status}`)}catch{re(oe=>oe&&ee?{...oe,model:ee}:oe),y(e("video.plannerUpdateFailed"),!0)}};return d.jsxs("div",{className:"right-panel-settings video-controls",children:[d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")??"Model"}),d.jsx("div",{className:"option-row",children:HP.map(V=>d.jsxs("button",{type:"button",className:`option-btn${a===V.value?" active":""}`,onClick:()=>i(V.value),children:[V.label,d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:V.sub})]},V.value))})]}),d.jsxs("div",{className:"provider-compat-note",role:"note",children:[d.jsx("strong",{children:e("video.modeLabel")}),d.jsx("span",{children:e(`video.mode.${C}`,{n:o})})]}),_?d.jsxs("div",{className:"provider-compat-note",role:"note",children:[d.jsx("strong",{children:e("common.continuity")}),d.jsx("span",{children:_})]}):null,I.length>0&&d.jsx(zm,{ariaLabel:e("video.selectedCameraPresets"),children:I.map(V=>d.jsx(yS,{onRemove:()=>P(V.id),removeLabel:e("common.removeNamed",{name:V.name}),children:V.name},V.id))}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("video.seriesTopicTitle")??"시리즈 주제"}),d.jsx("input",{type:"text",className:"video-topic-input",placeholder:e("video.seriesTopicPlaceholder")??"예: 한국 여행 브이로그",value:S,onChange:V=>v(V.target.value)})]}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("video.durationTitle")}),d.jsx(MS,{values:Qy.filter(V=>V<=k),value:s,ariaLabel:e("video.durationTitle"),onChange:V=>c(V??Qy[0])})]}),d.jsx(xn,{title:e("video.resolutionTitle"),help:j?void 0:e("video.resolution1080Help"),items:$,value:m,onChange:L}),d.jsx(xn,{title:e("video.aspectTitle"),items:UP,value:h,onChange:g}),J&&d.jsx("div",{className:"video-controls__pills",children:d.jsx(tr,{className:"video-controls__pill",items:J.options.map(V=>({value:V,label:V})),value:J.model,onChange:V=>{he(V)},ariaLabel:e("video.plannerModelTitle")})}),d.jsxs("details",{className:"provider-compat-details",style:{marginTop:8},children:[d.jsx("summary",{children:e("common.activePrompt")}),d.jsx("p",{children:Ts})]})]})}const VP="",PS=3;function Jy(e,a,i,o){const s=[],c=new Set;for(const m of[a,...e])!m?.filename||c.has(m.filename)||gt(m)!==o||o&&!/\.(?:mp4|mov)$/i.test(m.filename)||(c.add(m.filename),s.push({filename:m.filename,current:m===a}));for(const m of i){const p=m.filePath,h=o?m.kind==="video":m.kind==="image"||m.kind==="element",g=o?/\.(?:mp4|mov)$/i.test(p??""):/\.(?:png|jpe?g|webp)$/i.test(p??"");!p||!h||!g||c.has(p)||(c.add(p),s.push({filename:p,current:!1,label:m.name||p,source:m.kind==="element"?"element":"asset"}))}return s}function KP(e,a){return e[a]??null}function LS(e,a,i){const o=!a||e.some(s=>s.filename===a);return[{value:VP,label:i("mcp.referenceNone")},...o?[]:[{value:a,label:a,sub:i("mcp.referenceMissing")}],...e.map(s=>({value:s.filename,label:s.label??s.filename,sub:s.current?i("mcp.referenceCurrent"):s.source?i(`mcp.referenceSource.${s.source}`):void 0}))]}function Ou({id:e,label:a,value:i,candidates:o,disabled:s,title:c,help:m,onChange:p,t:h}){return d.jsxs("div",{className:"mcp-reference-slot",children:[d.jsx("label",{className:"mcp-reference-slot__label",htmlFor:e,children:a}),d.jsx(tr,{id:e,items:LS(o,i??"",h),value:i??"",onChange:p,ariaLabel:a,placeholder:h("mcp.referenceSelect"),disabled:s,title:c,portal:!0}),m?d.jsx("p",{className:"option-help",children:m}):null]})}function $P({index:e,images:a,selection:i,disabled:o,onChange:s,t:c}){const m=KP(i.references,e),p=new Set(i.references.filter((E,P)=>P!==e).map(E=>E.filename)),h=m?.dataUrl?{filename:m.filename,current:!1,label:m.displayName??c("mcp.referenceLocalFallback"),source:"local"}:null,g=[...h?[h]:[],...a.filter(E=>!p.has(E.filename))],S=E=>{const P=[...i.references];E?P[e]={filename:E,...m?.tag?{tag:m.tag}:{}}:P.splice(e,1),s({...i,references:P})},v=E=>{if(!m)return;const P=[...i.references],{tag:I,...k}=m;P[e]={...k,...E?{tag:E}:{}},s({...i,references:P})},y=!!(m?.tag&&!fm(m.tag)),x=`mcp-reference-tag-error-${e}`;return d.jsxs("div",{className:"mcp-reference-slot__reference",children:[d.jsx(tr,{items:LS(g,m?.filename??"",c),value:m?.filename??"",onChange:S,ariaLabel:c("mcp.imageReferenceAria",{index:e+1}),placeholder:c("mcp.referenceSelect"),disabled:o,portal:!0}),d.jsxs("div",{children:[d.jsx("input",{type:"text",value:m?.tag??"",onChange:E=>v(E.target.value),"aria-label":c("mcp.referenceTagAria",{index:e+1}),placeholder:c("mcp.referenceTagPlaceholder"),"aria-invalid":y,"aria-describedby":y?x:void 0,maxLength:32,disabled:o||!m}),y?d.jsx("p",{id:x,className:"settings-row__microcopy",role:"alert",children:c("mcp.referenceTagInvalid")}):null]})]})}function YP({selection:e,disabled:a,onChange:i,t:o}){const s=R.useRef(null),[c,m]=R.useState(null),p=e.references.length>=PS,h=async g=>{const S=g.target.files?.[0];if(g.target.value="",!!S){if(!/^image\/(?:png|jpeg|webp)$/i.test(S.type)){m(o("mcp.referenceLocalInvalidType"));return}try{const v=await Tm(S),y=`local:${globalThis.crypto.randomUUID()}`;i({...e,references:[...e.references,{filename:y,displayName:S.name,dataUrl:v}]}),m(null)}catch{m(o("mcp.referenceLocalReadFailed"))}}};return d.jsxs("div",{children:[d.jsx("input",{ref:s,className:"sr-only",type:"file",accept:"image/png,image/jpeg,image/webp",onChange:g=>{h(g)},disabled:a||p}),d.jsx("button",{type:"button",className:"option-btn",onClick:()=>s.current?.click(),disabled:a||p,children:o("mcp.referenceAttachLocal")}),d.jsx("p",{className:"option-help",children:o("mcp.referenceAttachHelp")}),c?d.jsx("p",{className:"settings-row__microcopy",role:"alert",children:c}):null]})}function XP({images:e,selection:a,disabled:i,onChange:o,t:s}){return d.jsxs("div",{className:"mcp-reference-slot",children:[d.jsx("div",{className:"mcp-reference-slot__label",children:s("mcp.imageReferencesLabel")}),Array.from({length:PS},(c,m)=>d.jsx($P,{index:m,images:e,selection:a,disabled:i,onChange:o,t:s},m)),d.jsx(YP,{selection:a,disabled:i,onChange:o,t:s})]})}function QP({inputRoles:e,disabled:a}){const{t:i}=ge(),o=w(v=>v.history),s=w(v=>v.currentImage),c=w(v=>v.assets),m=w(v=>v.mcpReferenceSelection)??Tn(),p=R.useMemo(()=>Jy(o,s,c,!1),[o,s,c]),h=R.useMemo(()=>Jy(o,s,c,!0),[o,s,c]),g=v=>qk(v,w.setState,w.getState),S=m.startFrameFilename?void 0:i("mcp.endFrameNeedsStart");return d.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?d.jsx(Ou,{id:"mcp-start-frame",label:i("mcp.startFrameLabel"),value:m.startFrameFilename,candidates:p,disabled:a,t:i,onChange:v=>g({...m,startFrameFilename:v||null,...v?{}:{endFrameFilename:null}})}):null,e.includes("end_image")?d.jsx(Ou,{id:"mcp-end-frame",label:i("mcp.endFrameLabel"),value:m.endFrameFilename,candidates:p,disabled:a||!m.startFrameFilename,title:S,help:S,t:i,onChange:v=>g({...m,endFrameFilename:v||null})}):null,e.includes("image_references")?d.jsx(XP,{images:p,selection:m,disabled:a,onChange:g,t:i}):null,e.includes("video_references")?d.jsx(Ou,{id:"mcp-video-reference",label:i("mcp.videoReferenceLabel"),value:m.referenceVideoFilename,candidates:h,disabled:a,t:i,help:i("mcp.videoReferenceCostNote"),onChange:v=>g({...m,referenceVideoFilename:v||null})}):null]})}function JP(e){return Array.isArray(e)&&e.includes("image_references")}function WP(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function Mj(e,a){return a.mode!=="trained-id"||!Array.isArray(a.trainedFromRefs)?!1:a.trainedFromRefs.length!==e.length?!0:a.trainedFromRefs.some((i,o)=>e[o]!==i)}function Pj(e){return e.length>3}function ZP({inputRoles:e,disabled:a}){const{t:i}=ge(),o=w(g=>g.assets),s=w(g=>g.mcpCharacterElementId??null),c=w(g=>g.selectedElementIds??[]);if(!JP(e))return null;const m=o.filter(g=>g.kind==="element"&&g.metadata?.elementKind==="character"),p=WP({mentionElementIds:c,characterElementId:s})==="conflict",h=!!a||c.length>0;return d.jsxs("div",{className:"mcp-character-slot","data-testid":"mcp-character-slot",children:[d.jsx("div",{className:"section-title",children:i("mcp.characterSlotLabel")}),d.jsxs("select",{value:s??"",disabled:h,"aria-label":i("mcp.characterSlotLabel"),title:c.length>0?i("mcp.characterSlotConflictHint"):void 0,onChange:g=>w.setState({mcpCharacterElementId:g.target.value||null}),children:[d.jsx("option",{value:"",children:i("mcp.characterSlotNone")}),m.map(g=>d.jsx("option",{value:g.id,children:g.name},g.id))]}),p?d.jsx("p",{className:"option-help",role:"alert",children:i("mcp.characterSlotConflictHint")}):null]})}const Wy=new Set(["duration","resolution","quality","mode"]);function Zy(e){return e.filter((a,i)=>e.findIndex(o=>o===a)===i)}function Vm(e){return e.options&&e.options.length>0?Zy(e.options):e.type==="boolean"?[!0,!1]:e.type!=="number"||e.min===void 0||e.max===void 0?[]:Number.isInteger(e.min)&&Number.isInteger(e.max)&&e.max-e.min<=20?Array.from({length:e.max-e.min+1},(a,i)=>e.min+i):Zy([e.min,...e.default!==void 0?[e.default]:[],e.max])}function ev(e,a){return{duration:a("mcp.durationLabel"),resolution:a("mcp.resolutionLabel"),quality:a("mcp.qualityLabel"),mode:a("mcp.modeLabel"),generateAudio:a("mcp.audioLabel"),generate_audio:a("mcp.audioLabel"),sound:a("mcp.audioLabel")}[e]??e.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}function eL(e,a){return typeof e=="boolean"?a(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function tL(e){return[...Vm(e).filter(i=>typeof i=="number")].sort((i,o)=>i-o)}function nL({parameter:e,value:a,disabled:i,onChange:o}){const{t:s}=ge();if(e.name==="duration"&&e.type==="number"){const p=tL(e);if(p.length>1){const h=ev(e.name,s);return d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:h}),d.jsx(MS,{values:p,value:typeof a=="number"?a:null,defaultValue:typeof e.default=="number"?e.default:void 0,allowAuto:!e.required,disabled:i,ariaLabel:h,onChange:o})]})}}const c=Vm(e);if(c.length===0)return null;const m=ev(e.name,s);return d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:m}),d.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":m,children:[e.required?null:d.jsx("button",{type:"button",className:`option-btn${a===void 0?" active":""}`,"aria-pressed":a===void 0,disabled:i,onClick:()=>o(null),children:s("size.autoLabel")}),c.map(p=>d.jsx("button",{type:"button",className:`option-btn${a===p?" active":""}`,"aria-pressed":a===p,disabled:i,onClick:()=>o(p),title:e.description,children:eL(p,s)},`${typeof p}:${String(p)}`))]})]})}function tv({entries:e,parameters:a,disabled:i,onParameter:o}){return d.jsx(d.Fragment,{children:e.map(s=>d.jsx(nL,{parameter:s,value:a[s.name],disabled:i,onChange:c=>o(s.name,c)},s.name))})}function aL({entry:e,ratio:a,parameters:i,disabled:o,onRatio:s,onParameter:c}){const{t:m}=ge(),p=e.capabilities.aspectRatios.filter(y=>y!=="auto"),h=e.capabilities.parameters.filter(y=>Vm(y).length>0),g=h.filter(y=>Wy.has(y.name)),S=h.filter(y=>!Wy.has(y.name)),v=e.capabilities.inputRoles.some(y=>y==="start_image"||y==="end_image"||y==="image_references"||y==="video_references");return d.jsxs("div",{className:"mcp-model-presets","data-capability-source":e.capabilities.source,children:[p.length>0?d.jsxs("div",{className:"mcp-preset-row",children:[d.jsx("div",{className:"section-title",children:m("mcp.aspectRatioLabel")}),d.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":m("mcp.aspectRatioLabel"),children:[d.jsx("button",{type:"button",className:`option-btn${a===null?" active":""}`,"aria-pressed":a===null,disabled:o,onClick:()=>s(null),children:m("size.autoLabel")}),p.map(y=>d.jsx("button",{type:"button",className:`option-btn${a===y?" active":""}`,"aria-pressed":a===y,disabled:o,onClick:()=>s(y),children:y},y))]})]}):null,d.jsx(tv,{entries:g,parameters:i,disabled:o,onParameter:c}),v?d.jsxs("div",{className:"mcp-tool-inputs",children:[d.jsx("div",{className:"section-title",children:m("mcp.toolInputsLabel")}),d.jsx(QP,{inputRoles:e.capabilities.inputRoles,disabled:o}),d.jsx(ZP,{inputRoles:e.capabilities.inputRoles,disabled:o})]}):null,S.length>0?d.jsxs("details",{className:"mcp-advanced-presets",children:[d.jsx("summary",{children:m("mcp.advancedPresetsLabel")}),d.jsx(tv,{entries:S,parameters:i,disabled:o,onParameter:c})]}):null,p.length===0&&h.length===0?d.jsx("p",{className:"option-help",children:m("mcp.providerDefaultsHelp")}):null]})}const rs={image:[],video:[]},oL={};function rL(e){return e.replace(/(^|-)([a-z])/g,(a,i,o)=>`${i}${o.toUpperCase()}`)}function iL({record:e}){const{t:a}=ge(),i=w(_=>_.mcpProvider??null),o=w(_=>_.mcpModel??null),s=w(_=>_.mcpMediaKind??"image"),c=w(_=>_.mcpRatio??null),p=w(_=>_.mcpParameters)??oL,[h,g]=R.useState(rs),[S,v]=R.useState("idle"),[y,x]=R.useState(0),E=e?.executable===!1,P=e?.status.state==="connected";if(R.useEffect(()=>{if(!i||!P){g(rs),v("idle");return}const _=new AbortController;return g(rs),v("loading"),sS(i,_.signal).then(N=>{_.signal.aborted||(g(N),v("ready"))}).catch(N=>{N.name!=="AbortError"&&(_.signal.aborted||(g(rs),v("error")))}),()=>_.abort()},[i,P,y]),!i)return null;const I=s==="video"?h.video:h.image,k=I.find(_=>_.id===o)??null,C=_=>Dk(_,w.setState,w.getState);return d.jsxs("div",{className:"mcp-generation-controls","data-testid":"mcp-generation-controls",children:[d.jsxs("div",{className:"option-group",children:[d.jsxs("div",{className:"section-title mcp-generation-controls__header",children:[d.jsxs("span",{children:[rL(i)," · MCP"]}),d.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>Qs(null,w.setState,w.getState),children:a("mcp.exitLane")})]}),P?null:d.jsx("p",{className:"option-help",children:a("mcp.disconnectedSelection")}),E?d.jsx("p",{className:"option-help",children:a("mcp.higgsfieldLocked")}):null]}),d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"option-group",children:d.jsxs("div",{className:"option-row",children:[d.jsx("button",{type:"button",className:`option-btn${s==="image"?" active":""}`,"aria-pressed":s==="image",onClick:()=>C("image"),children:a("grokMode.image")}),d.jsx("button",{type:"button",className:`option-btn${s==="video"?" active":""}`,"aria-pressed":s==="video",onClick:()=>C("video"),children:a("grokMode.video")})]})}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:a("mcp.modelSectionTitle")}),S==="loading"?d.jsx("p",{className:"option-help",role:"status",children:a("mcp.loadingModels")}):S==="error"?d.jsxs("div",{className:"mcp-catalog-state",role:"alert",children:[d.jsx("span",{children:a("mcp.modelsLoadFailed")}),d.jsx("button",{type:"button",className:"settings-action-btn",onClick:()=>x(_=>_+1),children:a("mcp.retryModels")})]}):S==="ready"&&I.length===0?d.jsx("p",{className:"option-help",children:a("mcp.noModels")}):k?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"mcp-selected-model",children:[d.jsx("strong",{children:k.label}),k.description?d.jsx("span",{children:k.description}):null]}),d.jsx(aL,{entry:k,ratio:c,parameters:p,disabled:E,onRatio:_=>Fk(_,w.setState),onParameter:(_,N)=>zk(_,N,w.setState,w.getState)})]}):d.jsx("p",{className:"option-help",children:a(o?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}const lL=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],is=[{value:"1:1",label:"1:1"},{value:"2:3",label:"2:3"},{value:"3:2",label:"3:2"},{value:"3:4",label:"3:4"},{value:"4:3",label:"4:3"},{value:"4:5",label:"4:5"},{value:"5:4",label:"5:4"},{value:"9:16",label:"9:16"},{value:"16:9",label:"16:9"},{value:"21:9",label:"21:9"}],sL=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Is={"1:1":{512:"512x512","1K":"1024x1024","2K":"2048x2048","4K":"4096x4096"},"2:3":{512:"424x632","1K":"848x1264","2K":"1696x2528","4K":"3392x5056"},"3:2":{512:"632x424","1K":"1264x848","2K":"2528x1696","4K":"5056x3392"},"3:4":{512:"448x600","1K":"896x1200","2K":"1792x2400","4K":"3584x4800"},"4:3":{512:"600x448","1K":"1200x896","2K":"2400x1792","4K":"4800x3584"},"4:5":{512:"464x576","1K":"928x1152","2K":"1856x2304","4K":"3712x4608"},"5:4":{512:"576x464","1K":"1152x928","2K":"2304x1856","4K":"4608x3712"},"9:16":{512:"384x688","1K":"768x1376","2K":"1536x2752","4K":"3072x5504"},"16:9":{512:"688x384","1K":"1376x768","2K":"2752x1536","4K":"5504x3072"},"21:9":{512:"792x168","1K":"1584x672","2K":"3168x1344","4K":"6336x2688"}};function cL(e){for(const[a,i]of Object.entries(Is))for(const[o,s]of Object.entries(i))if(s===e)return{ratio:a,res:o};return null}function dL(e,a){const i=e/a;let o="1:1",s=1/0;const c=[...Object.keys(Is),"1:8","8:1","1:4","4:1"];for(const h of c){const[g,S]=h.split(":").map(Number),v=Math.abs(i-g/S);v<s&&(s=v,o=h)}const m=Math.max(e,a),p=m<=512?"512":m<=1024?"1K":m<=2048?"2K":"4K";return{ratio:o,res:p}}function OS(){const{t:e}=ge(),a=w(ie=>ie.provider),i=w(ie=>ie.quality),o=w(ie=>ie.setQuality),s=w(ie=>ie.format),c=w(ie=>ie.setFormat),m=w(ie=>ie.moderation),p=w(ie=>ie.setModeration),h=w(ie=>ie.multimode),g=w(ie=>ie.setMultimode),S=w(ie=>ie.imageModel),v=w(ie=>ie.setImageModel),y=w(ie=>ie.selectVideoModel),x=w(ie=>ie.sizePreset),E=w(ie=>ie.customW),P=w(ie=>ie.customH),I=w(ie=>ie.setSizePreset),k=w(ie=>ie.setCustomSize),C=w(ie=>ie.uiMode),_=w(ie=>ie.videoModelSelected),N=w(ie=>ie.mcpProvider??null),{providers:j}=cS(),$=C==="classic",L=a==="grok"||a==="grok-api",J=a==="agy",re=a==="gemini-api",he=J||re,V=L||he,ee=x==="custom"?`${E}x${P}`:"1024x1024",oe=re&&x==="auto",Ne=re&&!oe?cL(ee):null,ne=Ne??{ratio:"",res:""},H=re&&!oe&&x==="custom"&&!Ne,ae=S==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[ce,be]=R.useState(!1),[Se,T]=R.useState(String(E)),[F,W]=R.useState(String(P)),U=(ie,lt)=>{const at=Is[ie||"1:1"]?.[lt||"1K"]||"1024x1024",[st,bt]=at.split("x").map(Number);be(!1),I("custom"),k(st,bt)},le=()=>{const ie=Number(Se),lt=Number(F);!Number.isFinite(ie)||!Number.isFinite(lt)||ie<=0||lt<=0||(I("custom"),k(ie,lt),be(!1))},pe=[{value:"low",label:e("quality.lowLabel"),sub:e("quality.lowSub")},{value:"medium",label:e("quality.mediumLabel"),sub:e("quality.mediumSub")},{value:"high",label:e("quality.highLabel"),sub:e("quality.highSub")}],xe=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],Oe=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],Re=L?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:J?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:re?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},Ze=ie=>{ie==="video"?y("grok-imagine-video"):v(S)};return N?d.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[d.jsx(Xy,{mcpProviders:j}),d.jsx(iL,{record:j.find(ie=>ie.id===N)??null})]}):d.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[d.jsx(Xy,{mcpProviders:j}),d.jsxs("details",{className:"provider-compat-details",children:[d.jsx("summary",{children:Re.title}),d.jsx("p",{children:Re.body})]}),L&&d.jsx("div",{className:"option-group grok-mode-toggle",children:d.jsxs("div",{className:"option-row",children:[d.jsx("button",{type:"button",className:`option-btn${_?"":" active"}`,onClick:()=>Ze("image"),children:e("grokMode.image")}),d.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>Ze("video"),children:e("grokMode.video")})]})}),_?d.jsx(BP,{}):d.jsxs(d.Fragment,{children:[J?null:L?d.jsxs(d.Fragment,{children:[d.jsx(zP,{}),d.jsx(DP,{})]}):re?d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("quality.grokModelTitle"),items:Oe,value:ae,onChange:v}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")||"Aspect Ratio"}),[is.slice(0,3),is.slice(3,6),is.slice(6,8),is.slice(8)].map((ie,lt)=>d.jsx("div",{className:"option-row",children:ie.map(at=>d.jsx("button",{type:"button",className:`option-btn${ne.ratio===at.value?" active":""}`,onClick:()=>U(at.value,ne.res),children:at.label},at.value))},lt))]}),d.jsxs("div",{className:"option-group",children:[d.jsx("div",{className:"section-title",children:e("size.grokResolutionTitle")||"Resolution"}),d.jsx("div",{className:"gemini-resolution-grid",children:sL.map(ie=>d.jsxs("button",{type:"button",className:`option-btn${ne.res===ie.value?" active":""}`,onClick:()=>U(ne.ratio,ie.value),children:[d.jsx("span",{children:ie.label}),d.jsx("br",{}),d.jsx("small",{children:Is[ne.ratio]?.[ie.value]?.replace("x","×")||""})]},ie.value))})]}),d.jsxs("div",{className:"option-group",children:[d.jsxs("div",{className:"option-row",children:[d.jsxs("button",{type:"button",className:`option-btn${oe?" active":""}`,onClick:()=>{be(!1),I("auto")},children:[e("size.autoLabel"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:e("size.autoSub")})]}),d.jsxs("button",{type:"button",className:`option-btn${H||ce?" active":""}`,onClick:()=>be(ie=>!ie),children:[e("size.customPlus"),d.jsx("br",{}),d.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),ce?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"option-row size-picker__custom-row",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:Se,onChange:ie=>T(ie.target.value.replace(/\D/g,"")),placeholder:e("size.width")}),d.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:F,onChange:ie=>W(ie.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(Se)>0&&Number(F)>0?d.jsxs("div",{className:"size-picker__preview",children:[d.jsx("span",{children:e("size.normalizedPreview")}),d.jsx("strong",{children:(()=>{const ie=dL(Number(Se),Number(F));return`${ie.ratio} · ${ie.res}`})()})]}):null,d.jsx("button",{type:"button",className:"size-picker__save",onClick:le,children:e("settings.apiKeys.save")})]}):null]})]}):d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("quality.title"),items:pe,value:i,onChange:o}),d.jsx(CP,{})]}),V?null:d.jsxs(d.Fragment,{children:[d.jsx(xn,{title:e("format.title"),items:lL,value:s,onChange:c}),d.jsx(xn,{title:e("moderation.title"),items:xe,value:m,onChange:p}),d.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),$&&!he&&d.jsx("div",{className:"option-group multimode-toggle",children:d.jsxs("button",{type:"button",className:`multimode-toggle__button${h?" active":""}`,"aria-pressed":h,title:e("multimode.tooltip"),onClick:()=>g(!h),children:[d.jsx("span",{children:e("multimode.label")}),d.jsx("span",{children:e("multimode.shortHint")})]})}),he?null:d.jsx(wP,{}),d.jsx(MP,{})]})]})}const uL=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-BYTG-mBa.js"),[]).then(e=>({default:e.PromptLibraryPanel}))),mL=R.lazy(()=>$t(()=>import("./PromptBuilderPanel-DeSY9dl-.js"),[]).then(e=>({default:e.PromptBuilderPanel}))),pL=R.lazy(()=>$t(()=>import("./GenerationRequestLogPanel-CpyvTE6t.js"),[]).then(e=>({default:e.GenerationRequestLogPanel})));function fL(){const e=w(k=>k.rightPanelOpen),a=w(k=>k.toggleRightPanel),i=w(k=>k.promptLibraryOpen),o=w(k=>k.setPromptLibraryOpen),s=w(k=>k.promptBuilderOpen),c=w(k=>k.togglePromptBuilder),m=w(k=>k.workspaceProfile),{t:p}=ge(),[h,g]=R.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);R.useEffect(()=>{if(typeof window>"u")return;const k=window.matchMedia("(max-width: 800px)"),C=()=>g(k.matches);return k.addEventListener("change",C),()=>k.removeEventListener("change",C)},[]);const[S,v]=R.useState(!1),y=BN(m)&&!h,x=h?e:!0,E=uo(h&&e,a),P=S?"log":s&&y?"builder":i?"library":"settings",I=k=>{v(k==="log"),k==="builder"?(s||c(),i&&o(!1)):k==="library"?(s&&c(),i||o(!0)):(s&&c(),i&&o(!1))};return d.jsxs(d.Fragment,{children:[h&&e?d.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":p("panel.closeSettings"),onClick:a}):null,d.jsxs("aside",{ref:E,className:`right-panel${e?"":" collapsed"}${h&&x?" drawer-open":""}`,"aria-label":p("panel.detailSettings"),"aria-modal":h&&e?"true":void 0,role:h&&e?"dialog":void 0,tabIndex:h?-1:void 0,children:[!h&&d.jsx("button",{type:"button",className:"right-panel-toggle","aria-expanded":e,"aria-controls":"right-panel-body",onClick:a,title:p(e?"panel.toggleHide":"panel.toggleShow"),children:e?">":"<"}),d.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!e,children:[d.jsxs("div",{className:"right-panel-tabs",role:"tablist","aria-label":p("panel.detailSettings"),children:[y?d.jsx("button",{type:"button",role:"tab","aria-selected":P==="builder","aria-controls":"right-panel-tab-builder",title:p("promptBuilder.title"),className:`right-panel-tabs__button${P==="builder"?" active":""}`,onClick:()=>I("builder"),children:p("promptBuilder.title")}):null,d.jsx("button",{type:"button",role:"tab","aria-selected":P==="log","aria-controls":"right-panel-tab-log",title:p("generationLog.title"),className:`right-panel-tabs__button${y?"":" right-panel-tabs__button--full"}${P==="log"?" active":""}`,onClick:()=>I("log"),children:p("generationLog.title")}),d.jsx("button",{type:"button",role:"tab","aria-selected":P==="library","aria-controls":"right-panel-tab-library",title:p("promptLibrary.title"),className:`right-panel-tabs__button right-panel-tabs__button--full${P==="library"?" active":""}`,onClick:()=>I("library"),children:p("promptLibrary.title")}),d.jsx("button",{type:"button",role:"tab","aria-selected":P==="settings","aria-controls":"right-panel-tab-settings",title:p("panel.detailSettings"),className:`right-panel-tabs__button right-panel-tabs__button--full${P==="settings"?" active":""}`,onClick:()=>I("settings"),children:p("panel.detailSettings")})]}),P==="builder"&&y?d.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(mL,{variant:"sidebar"})})}):P==="library"?d.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(uL,{variant:"embedded"})})}):P==="log"?d.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:p("common.loading")}),children:d.jsx(pL,{})})}):d.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:d.jsx(OS,{})})]})]})]})}function gL(e){const a=e.currentTarget;if(a.scrollWidth<=a.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const o=a.scrollLeft<=0,s=a.scrollLeft+a.clientWidth>=a.scrollWidth-1,c=e.deltaY<0,m=e.deltaY>0;c&&o||m&&s||(e.preventDefault(),a.scrollLeft+=e.deltaY)}function hL({id:e}){const{t:a}=ge();return d.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":a("common.generating")},e)}function yL({id:e,count:a}){const{t:i}=ge(),o=Math.min(a,4);return d.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":i("history.generatingCollection",{count:a}),children:Array.from({length:o},(s,c)=>d.jsx("div",{className:"collection-mini collection-mini--skeleton"},c))},`coll-${e}`)}function vL({sequenceId:e,images:a}){const i=w(p=>p.showHistorySequence),s=w(p=>p.multimodePreviewFlightId)===`history:${e}`,c=a.slice(0,4),{t:m}=ge();return d.jsx("button",{type:"button",className:`history-thumb history-thumb--collection${s?" active":""}`,onClick:()=>i(e),"aria-label":m("common.imageCollection",{n:a.length}),children:c.map((p,h)=>!p.thumb&&(kn(p.url)||kn(p.image))?d.jsx(nr,{className:"collection-mini"},h):d.jsx("img",{className:"collection-mini",src:p.thumb||p.url||p.image,alt:"",loading:"lazy",decoding:"async"},h))})}function bL(e){const a=R.useRef(null),i=R.useRef(new Map),[o,s]=R.useState(()=>new Set);R.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const m=new IntersectionObserver(p=>{const h=p.filter(g=>g.isIntersecting);h.length!==0&&s(g=>{const S=new Set(g);for(const v of h){const y=v.target.dataset.historyLazyKey;y&&S.add(y)}return S})},{root:e,rootMargin:"0px 200% 0px 200%"});a.current=m;for(const p of i.current.values())m.observe(p);return()=>{m.disconnect(),a.current=null}},[e]);const c=R.useCallback((m,p)=>{const h=i.current.get(m);h&&h!==p&&a.current?.unobserve(h),p?(i.current.set(m,p),a.current?.observe(p)):i.current.delete(m)},[]);return{visibleKeys:o,register:c,supported:typeof IntersectionObserver<"u"}}function SL(){const e=w(C=>C.history),a=w(C=>C.currentImage),i=w(C=>C.historyStripLayout),o=w(C=>C.selectHistory),s=w(C=>C.openGallery),c=w(C=>C.inFlight),m=w(C=>C.multimodeSequences),p=R.useRef({}),[h,g]=R.useState(null),S=bL(h),{t:v}=ge(),y=a?Ot(a):null,x=R.useMemo(()=>hs(e.filter(mi)),[e]),E=R.useMemo(()=>{const C=[];for(const _ of c){const N=m[_.id];if(_.kind==="multimode"&&N){C.push({type:"collection-skeleton",id:_.id,count:N.requested});for(let j=0;j<N.requested;j++)N.images[j]||C.push({type:"skeleton",id:`${_.id}_${j}`,count:1})}else C.push({type:"skeleton",id:_.id,count:1})}return C},[c,m]),{completedSequences:P,sequenceFirstKeys:I}=R.useMemo(()=>{const C=new Map,_=new Set;for(const N of x)if(N.sequenceId&&(N.sequenceTotalRequested??0)>1){C.has(N.sequenceId)||_.add(Ot(N));const j=C.get(N.sequenceId)||[];j.push(N),C.set(N.sequenceId,j)}return{completedSequences:C,sequenceFirstKeys:_}},[x]);R.useEffect(()=>{y&&p.current[y]?.scrollIntoView({block:"nearest",inline:"nearest"})},[y,x]);const k=(C,_)=>{const N=S.supported?S.visibleKeys.has(C):!0;return d.jsx("div",{ref:j=>{p.current[C]=j,S.register(C,j)},className:"history-thumb","data-history-lazy-key":C,"aria-hidden":N?void 0:!0,style:{padding:0,overflow:"hidden"},children:N?_:null},C)};return d.jsxs("div",{ref:g,className:`history-strip${i==="horizontal"?" history-strip--horizontal":""}${i==="sidebar"?" history-strip--sidebar":""}`,onWheel:gL,"data-layout":i,children:[d.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:s,"aria-label":v("history.openGalleryAria"),title:v("history.openGalleryTitle"),children:d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),d.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),E.map(C=>C.type==="collection-skeleton"?d.jsx(yL,{id:C.id,count:C.count},`coll-${C.id}`):d.jsx(hL,{id:C.id},C.id)),x.map(C=>{const _=Ot(C),N=y===_;if(C.sequenceId&&P.has(C.sequenceId)&&I.has(_)){const j=P.get(C.sequenceId);return[k(`coll-${C.sequenceId}`,d.jsx(vL,{sequenceId:C.sequenceId,images:j})),...j.map($=>{const L=Ot($),J=y===L;return gt($)?k(L,d.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${J?" active":""}`,onClick:()=>o($),draggable:!0,onDragStart:re=>{re.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi($))),re.dataTransfer.effectAllowed="copy"},children:[$.thumb?d.jsx("img",{src:$.thumb,alt:"",loading:"lazy",decoding:"async"}):d.jsx(nr,{}),d.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):k(L,d.jsx("img",{src:$.thumb||$.url||$.image,alt:"",className:`history-thumb history-thumb--fade-in${J?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>o($),draggable:!0,onDragStart:re=>{re.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:$.url||$.image,filename:$.filename})),re.dataTransfer.effectAllowed="copy"}}))})]}return C.sequenceId&&P.has(C.sequenceId)&&!I.has(_)?null:gt(C)?k(_,d.jsxs("div",{className:`history-thumb history-thumb--video${N?" active":""}`,onClick:()=>o(C),draggable:!0,onDragStart:j=>{j.dataTransfer.setData("application/ima2-ref",JSON.stringify(yi(C))),j.dataTransfer.effectAllowed="copy"},children:[C.thumb?d.jsx("img",{src:C.thumb,alt:"",loading:"lazy",decoding:"async"}):d.jsx(nr,{}),d.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):k(_,d.jsx("img",{src:C.thumb||C.url||C.image,alt:"",className:`history-thumb${N?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>o(C),draggable:!0,onDragStart:j=>{j.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:C.url||C.image,filename:C.filename})),j.dataTransfer.effectAllowed="copy"}}))})]})}const nv=3e3;function xL(){const{t:e}=ge(),a=w(g=>g.toastLog),i=w(g=>g.errorCardLog),o=w(g=>g.dismissToast),s=w(g=>g.dismissErrorCard),[c,m]=R.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),p=R.useRef(new Map);R.useEffect(()=>{const g=()=>m(document.visibilityState==="visible");return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),window.addEventListener("blur",g),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g),window.removeEventListener("blur",g)}},[]),R.useEffect(()=>{const g=p.current,S=new Set([...a.map(v=>`toast-${v.id}`),...i.map(v=>`error-card-${v.id}`)]);for(const[v,y]of g)(!S.has(v)||!c)&&(clearTimeout(y),g.delete(v));if(c){for(const v of a){const y=`toast-${v.id}`;if(g.has(y))continue;const x=setTimeout(()=>{g.delete(y),o(v.id)},nv);g.set(y,x)}for(const v of i){const y=`error-card-${v.id}`;if(g.has(y))continue;const x=setTimeout(()=>{g.delete(y),s(v.id)},nv);g.set(y,x)}}},[s,o,i,c,a]),R.useEffect(()=>()=>{for(const g of p.current.values())clearTimeout(g);p.current.clear()},[]);const h=[...a.map(g=>({kind:"toast",id:g.id,key:`toast-${g.id}`,message:g.message,error:g.error,createdAt:g.createdAt,cta:void 0,cardKey:void 0})),...i.map(g=>{const S=eo[g.code],v=g.cardKey??S?.cardKey??"errorCard.unknown",y=e(`${v}.title`),x=e(`${v}.body`),E=g.cta??S?.cta;return{kind:"error-card",id:g.id,key:`error-card-${g.id}`,message:g.fallbackMessage?`${y}: ${x} ${g.fallbackMessage}`:`${y}: ${x}`,error:!0,createdAt:g.createdAt,cta:E,cardKey:v}})].sort((g,S)=>g.createdAt-S.createdAt).slice(-5);return h.length===0?null:d.jsx("div",{className:"toast-stack","aria-live":"polite","aria-relevant":"additions removals",children:h.map(g=>{const S=["toast","visible",g.error?"error":"",g.kind==="error-card"?"toast--card":""].filter(Boolean).join(" ");return d.jsxs("div",{className:S,role:g.error?"alert":"status",children:[d.jsx("span",{className:"toast__message",children:g.message}),g.kind==="error-card"&&(g.cta==="reauth"||g.cta==="reload")?d.jsx("button",{type:"button",className:"toast__cta",onClick:()=>{g.cta==="reauth"&&w.getState().openSettings("providers"),g.cta==="reload"&&window.location.reload()},children:e(`${g.cardKey??"errorCard.unknown"}.cta`)}):null,d.jsx("button",{type:"button",className:"toast__dismiss","aria-label":e("common.dismiss"),onClick:()=>g.kind==="error-card"?s(g.id):o(g.id),children:d.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:d.jsx("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round"})})})]},g.key)})})}function AL(){return null}function TL(e,a="en"){if(!e)return"earlier";const i=new Date(e);if(Number.isNaN(i.getTime()))return"earlier";const s=Math.floor((new Date().getTime()-i.getTime())/864e5);return s===0?"today":s===1?"yesterday":s<7?"thisWeek":new Intl.DateTimeFormat(a,{year:"numeric",month:"short",day:"numeric"}).format(i)}function CL(e,a,i){async function o(m){if(m.setId)try{await vt.getState().loadSet(m.setId),w.getState().setUIMode("card-news"),e()}catch{a(i("gallery.openCardNewsSetFailed"),!0)}}async function s(m,p){if(p.stopPropagation(),!m.setId)return;const h=`generated/cardnews/${m.setId}`;try{await navigator.clipboard?.writeText(h),a(i("gallery.cardNewsPathCopied"))}catch{a(i("toast.copyFailed"),!0)}}function c(m,p){p.stopPropagation(),m.setId&&window.open(b2(m.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:o,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:c}}const wL=["ArrowLeft","ArrowRight","Home","End"];function IL(){return R.useCallback(e=>{if(!wL.includes(e.key))return;const a=e.currentTarget,i=Array.from(a.querySelectorAll("[role='tab']")).filter(p=>!p.hasAttribute("disabled"));if(i.length===0)return;e.preventDefault();const o=document.activeElement,s=o?i.indexOf(o):-1,c=e.key==="Home"?0:e.key==="End"?i.length-1:s<0?0:(s+(e.key==="ArrowRight"?1:-1)+i.length)%i.length,m=i[c];m?.focus(),m?.click()},[])}function ju({className:e,ariaLabel:a,tabs:i,value:o,onChange:s}){const c=IL(),m=i.find(h=>h.value===o),p=m&&!m.disabled?m.value:i.find(h=>!h.disabled)?.value;return d.jsx("div",{className:e,role:"tablist","aria-label":a,onKeyDown:c,children:i.map(h=>d.jsx("button",{type:"button",role:"tab","aria-selected":h.value===o,tabIndex:h.value===p?0:-1,className:h.value===o?"active":"",onClick:()=>s(h.value),disabled:h.disabled,children:h.label},h.value))})}function EL({item:e,onOpen:a,onCopyPath:i,onDownloadManifest:o}){const{t:s}=ge(),m=e.cards?.find(p=>p.headline)?.headline||e.headline||s("gallery.cardNewsSet");return d.jsxs(d.Fragment,{children:[d.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>a(e),title:m,children:[e.image?d.jsx("img",{src:e.image,alt:m,loading:"lazy"}):null,d.jsxs("div",{className:"gallery__caption",children:[d.jsx("small",{children:s("gallery.cardNewsSet")}),d.jsx("span",{className:"gallery__caption-text",children:m})]}),d.jsx("div",{className:"gallery-card-news-strip",children:(e.cards||[]).slice(0,5).map((p,h)=>d.jsxs("span",{children:[p.url?d.jsx("img",{src:p.url,alt:p.headline??"",loading:"lazy"}):null,d.jsx("em",{children:p.cardOrder??h+1})]},`${p.url}-${h}`))})]}),d.jsxs("div",{className:"gallery-card-news-actions",children:[d.jsx("span",{children:s("gallery.cardNewsCount",{n:e.cards?.length??0})}),d.jsx("button",{type:"button",onClick:()=>a(e),children:s("gallery.openCardNewsSet")}),d.jsx("button",{type:"button",onClick:p=>i(e,p),children:s("gallery.copyCardNewsSetPath")}),d.jsx("button",{type:"button",onClick:p=>o(e,p),children:s("gallery.downloadCardNewsManifest")})]})]})}const RL=[{id:"animate",labelKey:"chain.animate",available:e=>!!e.filename&&!gt(e)},{id:"edit",labelKey:"chain.edit",available:e=>!!e.filename&&!gt(e)},{id:"useAsRef",labelKey:"chain.useAsRef",available:e=>!!(e.image||e.url)},{id:"rebake",labelKey:"chain.rebake",available:e=>!!(e.prompt||e.filename)},{id:"saveToAssets",labelKey:"chain.saveToAssets",available:e=>!!e.filename},{id:"saveAsElement",labelKey:"chain.saveAsElement",available:e=>!!e.filename&&!gt(e)}];async function NL(e,a,i,o){const s=i();switch(e){case"animate":{if(!a.filename)return;try{await s.animateImage(a.filename,a.prompt??void 0)&&s.showToast(o("toast.animateDone"))}catch(c){s.showToast(c instanceof Error?c.message:o("toast.animateFailed"),!0)}break}case"edit":{s.selectHistory(a),s.openCanvas();break}case"useAsRef":{const c=a.url||a.image;if(!c)return;try{const p=await(await fetch(c)).blob(),h=new File([p],a.filename||"reference.png",{type:p.type});await s.addReferences([h]),s.showToast(o("chain.refAdded"))}catch{s.showToast(o("chain.refFailed"),!0)}break}case"rebake":{try{const{continueFromItem:m}=await $t(async()=>{const{continueFromItem:h}=await Promise.resolve().then(()=>UM);return{continueFromItem:h}},void 0),p=await m(a);s.showToast(o(p.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))}catch{s.showToast(o("toast.forkFailed"),!0)}const c=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');c&&(c.focus(),c.setSelectionRange(c.value.length,c.value.length));break}case"saveToAssets":{try{const c=await s.saveToAssets(a);s.showToast(o(c?"chain.savedToAssets":"chain.saveToAssetsFailed"),!c)}catch{s.showToast(o("chain.saveToAssetsFailed"),!0)}break}case"saveAsElement":{try{const c=await s.saveAsElement?.(a);s.showToast(o(c?"chain.savedToAssets":"chain.saveToAssetsFailed"),!c)}catch{s.showToast(o("chain.saveToAssetsFailed"),!0)}break}}}function kL(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function _L(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function ML(e){return{modelLabel:Cv(e.model,e.provider),derivation:kL(e),sourceLabel:_L(e)}}function PL(e){return!e.modelLabel&&!e.derivation}function LL({view:e,size:a="sm"}){const{t:i}=ge();return PL(e)?null:d.jsxs("span",{className:`provenance-chip provenance-chip--${a}`,children:[e.modelLabel?d.jsx("span",{className:"provenance-chip__model",children:e.modelLabel}):null,e.derivation?d.jsx("span",{className:"provenance-chip__derivation",children:i(`provenance.${e.derivation}`)}):null]})}function OL({id:e}){switch(e){case"animate":return d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})});case"edit":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),d.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]});case"useAsRef":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),d.jsx("polyline",{points:"17 8 12 3 7 8"}),d.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]});case"rebake":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]});case"saveToAssets":return d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),d.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),d.jsx("path",{d:"M10 12h4"})]})}}function jL({item:e,active:a,itemRef:i,onSelect:o,onDelete:s,onToggleFavorite:c,favoriteBusy:m=!1,t:p}){const h=R.useMemo(()=>RL.filter(v=>v.available(e)),[e]),g=R.useCallback(async(v,y)=>{y.stopPropagation(),await NL(v,e,()=>{const x=w.getState();return{animateImage:x.animateImage,openCanvas:x.openCanvas,selectHistory:x.selectHistory,addReferences:x.addReferences,showToast:x.showToast,saveToAssets:x.saveToAssets}},p)},[e,p]),S=v=>{v.dataTransfer.setData("application/ima2-ref",JSON.stringify(gt(e)?yi(e):{image:e.url||e.image,filename:e.filename})),v.dataTransfer.effectAllowed="copy"};return d.jsxs("div",{ref:i,className:`gallery__tile-wrap${a?" gallery__tile-wrap--active":""}${e.isFavorite?" gallery__tile-wrap--favorite":""}`,children:[d.jsxs("button",{type:"button",className:`gallery__tile${a?" gallery__tile--active":""}`,onClick:()=>o(e),title:e.prompt??"",draggable:!0,onDragStart:S,children:[gt(e)?d.jsxs("div",{className:"gallery__tile-video-wrap",children:[e.thumb?d.jsx("img",{src:e.thumb,alt:e.prompt??p("gallery.imageAltFallback"),loading:"lazy",decoding:"async",className:"gallery__tile-video"}):d.jsx(nr,{className:"gallery__tile-video"}),d.jsx("span",{className:"gallery__play-badge","aria-hidden":"true",children:"▶"})]}):d.jsx("img",{src:e.thumb||e.image,alt:e.prompt??p("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),e.prompt&&d.jsx("div",{className:"gallery__caption",children:d.jsx("span",{className:"gallery__caption-text",children:e.prompt})})]}),h.length>0?d.jsx("div",{className:"gallery__chain-overlay",role:"group","aria-label":p("chain.ariaLabel"),children:h.map(v=>d.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:y=>{g(v.id,y)},title:p(v.labelKey),"aria-label":p(v.labelKey),children:d.jsx(OL,{id:v.id})},v.id))}):null,e.filename&&c&&d.jsx(vS,{variant:"gallery",active:!!e.isFavorite,busy:m,label:e.isFavorite?p("gallery.unfavoriteAria"):p("gallery.favoriteAria"),onToggle:()=>c(e)}),e.filename&&d.jsx("button",{type:"button",className:"gallery__delete",onClick:v=>s(e,v),title:p("gallery.deleteTitle"),"aria-label":p("gallery.deleteAria"),children:"×"}),d.jsx(LL,{view:ML(e)})]})}function GL(e,a,i){const o=new Array(e);return new Proxy(o,{get(s,c,m){if(typeof c=="string"){const p=c.charCodeAt(0);if(p>=48&&p<=57){const h=+c;if(Number.isInteger(h)&&h>=0&&h<e){let g=s[h];if(!g){const S=a[h*2];g=s[h]={index:h,key:i(h),start:S,size:a[h*2+1],end:S+a[h*2+1],lane:0}}return g}}if(c==="length")return e}return Reflect.get(s,c,m)}})}function Qo(e,a,i){let o=i.initialDeps??[],s,c=!0;function m(){const p=e();return(p.length!==o.length||p.some((g,S)=>o[S]!==g))&&(o=p,s=a(...p),i?.onChange&&!(c&&i.skipInitialOnChange)&&i.onChange(s),c=!1),s}return m.updateDeps=p=>{o=p},m}function av(e,a){if(e===void 0)throw new Error("Unexpected undefined");return e}const DL=(e,a)=>Math.abs(e-a)<1.01,FL=(e,a,i)=>{let o;return function(...s){e.clearTimeout(o),o=e.setTimeout(()=>a.apply(this,s),i)}};let di;const Gu=()=>{if(di!==void 0)return di;if(typeof navigator>"u")return di=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return di=!0;const e=navigator.maxTouchPoints;return di=navigator.platform==="MacIntel"&&e!==void 0&&e>0},ov=e=>{const{offsetWidth:a,offsetHeight:i}=e;return{width:a,height:i}},zL=e=>e,qL=e=>{const a=Math.max(e.startIndex-e.overscan,0),o=Math.min(e.endIndex+e.overscan,e.count-1)-a+1,s=new Array(o);for(let c=0;c<o;c++)s[c]=a+c;return s},UL=(e,a)=>{const i=e.scrollElement;if(!i)return;const o=e.targetWindow;if(!o)return;const s=m=>{const{width:p,height:h}=m;a({width:Math.round(p),height:Math.round(h)})};if(s(ov(i)),!o.ResizeObserver)return()=>{};const c=new o.ResizeObserver(m=>{const p=()=>{const h=m[0];if(h?.borderBoxSize){const g=h.borderBoxSize[0];if(g){s({width:g.inlineSize,height:g.blockSize});return}}s(ov(i))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(p):p()});return c.observe(i,{box:"border-box"}),()=>{c.unobserve(i)}},Es={passive:!0},HL=typeof window>"u"?!0:"onscrollend"in window,BL=(e,a,i)=>{const o=e.scrollElement;if(!o)return;const s=e.targetWindow;if(!s)return;const c=e.options.useScrollendEvent&&HL;let m=0;const p=c?null:FL(s,()=>a(m,!1),e.options.isScrollingResetDelay),h=v=>()=>{m=i(o),p?.(),a(m,v)},g=h(!0),S=h(!1);return o.addEventListener("scroll",g,Es),c&&o.addEventListener("scrollend",S,Es),()=>{o.removeEventListener("scroll",g),c&&o.removeEventListener("scrollend",S)}},VL=(e,a)=>BL(e,a,i=>{const{horizontal:o,isRtl:s}=e.options;return o?i.scrollLeft*(s&&-1||1):i.scrollTop}),KL=(e,a,i)=>{if(i.options.useCachedMeasurements){const o=i.indexFromElement(e),s=i.options.getItemKey(o);return i.itemSizeCache.get(s)??i.options.estimateSize(o)}if(a?.borderBoxSize){const o=a.borderBoxSize[0];if(o)return Math.round(o[i.options.horizontal?"inlineSize":"blockSize"])}if(!a){const o=i.indexFromElement(e),s=i.options.getItemKey(o),c=i.itemSizeCache.get(s);if(c!==void 0)return c}return e[i.options.horizontal?"offsetWidth":"offsetHeight"]},$L=(e,{adjustments:a=0,behavior:i},o)=>{var s,c;(c=(s=o.scrollElement)==null?void 0:s.scrollTo)==null||c.call(s,{[o.options.horizontal?"left":"top"]:e+a,behavior:i})},YL=$L;class XL{constructor(a){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var i,o,s;return((s=(o=(i=this.targetWindow)==null?void 0:i.performance)==null?void 0:o.now)==null?void 0:s.call(o))??Date.now()},this.observer=(()=>{let i=null;const o=()=>i||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:i=new this.targetWindow.ResizeObserver(s=>{s.forEach(c=>{const m=()=>{const p=c.target,h=this.indexFromElement(p);if(!p.isConnected){this.observer.unobserve(p);for(const[g,S]of this.elementsCache)if(S===p){this.elementsCache.delete(g);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(p,c,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()})}));return{disconnect:()=>{var s;(s=o())==null||s.disconnect(),i=null},observe:s=>{var c;return(c=o())==null?void 0:c.observe(s,{box:"border-box"})},unobserve:s=>{var c;return(c=o())==null?void 0:c.unobserve(s)}}})(),this.range=null,this.setOptions=i=>{var o,s;const c={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:zL,rangeExtractor:qL,onChange:()=>{},measureElement:KL,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const y in i){const x=i[y];x!==void 0&&(c[y]=x)}const m=this.options;let p=null,h=null,g=!1;if(m!==void 0&&m.enabled&&c.enabled&&c.anchorTo==="end"&&this.scrollElement!==null){const y=m.count,x=c.count,E=this.getMeasurements(),P=y>0?((o=E[0])==null?void 0:o.key)??m.getItemKey(0):null,I=y>0?((s=E[y-1])==null?void 0:s.key)??m.getItemKey(y-1):null;if(x!==y||y>0&&x>0&&(c.getItemKey(0)!==P||c.getItemKey(x-1)!==I)){g=!0;const _=y>0?this.getVirtualItemForOffset(this.getScrollOffset())??E[0]:null;_&&(p=[_.key,this.getScrollOffset()-_.start]);const N=c.followOnAppend===!0?"auto":c.followOnAppend||null;N&&x>y&&this.isAtEnd(m.scrollEndThreshold)&&(y===0||c.getItemKey(x-1)!==I)&&(h=N)}}this.options=c,g&&(this.pendingMin=0,this.itemSizeCacheVersion++);let S=!1,v=0;if(p&&this.scrollOffset!==null){const[y,x]=p,E=this.getMeasurements(),{count:P,getItemKey:I}=this.options;let k=0;for(;k<P&&I(k)!==y;)k++;if(k<P){const C=E[k];if(C){const _=Math.max(0,C.start+x);_!==this.scrollOffset&&(v=_-this.scrollOffset,this.scrollOffset=_,S=!0)}}}(S||h)&&(this.pendingScrollAnchor=[S?p[0]:null,S?p[1]:0,h,v])},this.notify=i=>{var o,s;(s=(o=this.options).onChange)==null||s.call(o,this,i)},this.maybeNotify=Qo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),i=>{this.notify(i)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(i=>i()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var i;const o=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==o){if(this.cleanup(),!o){this.maybeNotify();return}if(this.scrollElement=o,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((i=this.scrollElement)==null?void 0:i.window)??null,this.elementsCache.forEach(c=>{this.observer.observe(c)}),this.unsubs.push(this.options.observeElementRect(this,c=>{this.scrollRect=c,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(c,m)=>{if(m&&this._intendedScrollOffset===null&&c===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(c-this._intendedScrollOffset)<1.5&&(c=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const p=this.getScrollOffset();this.scrollDirection=m?p===c?this.scrollDirection:p<c?"forward":"backward":null,this.scrollOffset=c,this.isScrolling=m,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const c=this.scrollElement,m=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},p=()=>{this._iosTouching=!1,!(!Gu()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};c.addEventListener("touchstart",m,Es),c.addEventListener("touchend",p,Es),this.unsubs.push(()=>{c.removeEventListener("touchstart",m),c.removeEventListener("touchend",p),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[c,m,p,h]=s;c!==null&&!p&&(Gu()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),p&&this.scrollToEnd({behavior:p})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const i=this.getScrollOffset(),o=this.getMaxScrollOffset();if(i<0||i>o)return;if(this._iosDeferredAdjustment<0&&i>=o-1){this._iosDeferredAdjustment=0;return}const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(i,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Qo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(i,o,s,c,m,p,h,g)=>(this.prevLanes!==void 0&&this.prevLanes!==p&&(this.lanesChangedFlag=!0),this.prevLanes=p,this.pendingMin=null,{count:i,paddingStart:o,scrollMargin:s,getItemKey:c,enabled:m,lanes:p,laneAssignmentMode:h,gap:g}),{key:!1}),this.getMeasurements=Qo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:i,paddingStart:o,scrollMargin:s,getItemKey:c,enabled:m,lanes:p,laneAssignmentMode:h,gap:g},S)=>{const v=this.itemSizeCache;if(!m)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>i)for(const k of this.laneAssignments.keys())k>=i&&this.laneAssignments.delete(k);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(k=>{this.itemSizeCache.set(k.key,k.size)}));const y=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===i&&(this.lanesSettling=!1),p===1){const k=i*2;let C=this._flatMeasurements;if(!C||C.length<k){const j=new Float64Array(k);C&&y>0&&j.set(C.subarray(0,y*2)),C=j,this._flatMeasurements=C}let _;if(y===0)_=o+s;else{const j=y-1;_=C[j*2]+C[j*2+1]+g}for(let j=y;j<i;j++){const $=c(j),L=v.get($),J=typeof L=="number"?L:this.options.estimateSize(j);C[j*2]=_,C[j*2+1]=J,_+=J+g}const N=GL(i,C,c);return this.measurementsCache=N,N}const x=this.measurementsCache.slice(0,y),E=new Array(p).fill(void 0),P=new Float64Array(p);let I=0;for(let k=0;k<y;k++){const C=x[k];C&&(E[C.lane]===void 0&&I++,E[C.lane]=k,P[C.lane]=C.end)}for(let k=y;k<i;k++){const C=c(k),_=this.laneAssignments.get(k);let N,j;const $=h==="estimate"||v.has(C);if(_!==void 0&&this.options.lanes>1){N=_;const he=E[N],V=he!==void 0?x[he]:void 0;j=V?V.end+g:o+s}else if(I===p){let he=0,V=P[0],ee=E[0];for(let oe=1;oe<p;oe++){const Ne=P[oe];(Ne<V||Ne===V&&E[oe]<ee)&&(he=oe,V=Ne,ee=E[oe])}N=he,j=V+g,$&&this.laneAssignments.set(k,N)}else N=k%this.options.lanes,j=o+s,$&&this.laneAssignments.set(k,N);const L=v.get(C),J=typeof L=="number"?L:this.options.estimateSize(k),re=j+J;x[k]={index:k,start:j,size:J,end:re,key:C,lane:N},E[N]===void 0&&I++,E[N]=k,P[N]=re}return this.measurementsCache=x,x},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Qo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(i,o,s,c)=>i.length===0||o===0?(this.range=null,null):(this.range=JL(i,o,s,c,c===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Qo(()=>{let i=null,o=null;const s=this.calculateRange();return s&&(i=s.startIndex,o=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,i,o]),[this.options.rangeExtractor,this.options.overscan,this.options.count,i,o]},(i,o,s,c,m)=>c===null||m===null?[]:i({startIndex:c,endIndex:m,overscan:o,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=i=>{const o=this.options.indexAttribute,s=i.getAttribute(o);return s?parseInt(s,10):(console.warn(`Missing attribute name '${o}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=i=>{var o;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((o=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:o.index);if(s!==void 0&&this.range){const c=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),m=Math.max(0,s-c),p=Math.min(this.options.count-1,s+c);return i>=m&&i<=p}return!0},this.measureElement=i=>{if(!i){this.elementsCache.forEach((m,p)=>{m.isConnected||(this.observer.unobserve(m),this.elementsCache.delete(p))});return}const o=this.indexFromElement(i),s=this.options.getItemKey(o),c=this.elementsCache.get(s);c!==i&&(c&&this.observer.unobserve(c),this.observer.observe(i),this.elementsCache.set(s,i)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(o)&&this.resizeItem(o,this.options.measureElement(i,void 0,this))},this.resizeItem=(i,o)=>{var s,c;if(i<0||i>=this.options.count)return;let m,p,h;const g=this._flatMeasurements;if(this.options.lanes===1&&g!==null)h=this.options.getItemKey(i),p=g[i*2],m=g[i*2+1];else{const y=this.measurementsCache[i];if(!y)return;h=y.key,p=y.start,m=y.size}const S=this.itemSizeCache.get(h)??m,v=o-S;if(v!==0){const y=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=y?this.getTotalSize():0,E=this.getScrollOffset()+this.scrollAdjustments,I=!this.itemSizeCache.has(h)?p<E:p+S<=E&&this.scrollDirection!=="backward",k=((c=this.scrollState)==null?void 0:c.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[i]??{index:i,key:h,start:p,size:m,end:p+m,lane:0},v,this):I);(this.pendingMin===null||i<this.pendingMin)&&(this.pendingMin=i),this.itemSizeCache.set(h,o),this.itemSizeCacheVersion++;let C=!1;y?C=this.applyScrollAdjustment(this.getTotalSize()-x):k&&(C=this.applyScrollAdjustment(v)),this.notify(C)}},this.getVirtualItems=Qo(()=>[this.getVirtualIndexes(),this.getMeasurements()],(i,o)=>{const s=[];for(let c=0,m=i.length;c<m;c++){const p=i[c],h=o[p];s.push(h)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=i=>{const o=this.getMeasurements();if(o.length===0)return;const s=this._flatMeasurements,c=this.options.lanes===1&&s!=null,m=jS(0,o.length-1,c?p=>s[p*2]:p=>av(o[p]).start,i);return av(o[m])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const i=this.scrollElement.document.documentElement;return this.options.horizontal?i.scrollWidth-this.scrollElement.innerWidth:i.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(i=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=i,this.getOffsetForAlignment=(i,o,s=0)=>{if(!this.scrollElement)return 0;const c=this.getSize(),m=this.getScrollOffset();o==="auto"&&(o=i>=m+c?"end":"start"),o==="center"?i+=(s-c)/2:o==="end"&&(i-=c);const p=this.getMaxScrollOffset();return Math.max(Math.min(p,i),0)},this.getOffsetForIndex=(i,o="auto")=>{i=Math.max(0,Math.min(i,this.options.count-1));const s=this.getSize(),c=this.getScrollOffset(),m=this.measurementsCache[i];if(!m)return;if(o==="auto")if(m.end>=c+s-this.options.scrollPaddingEnd)o="end";else if(m.start<=c+this.options.scrollPaddingStart)o="start";else return[c,o];if(o==="end"&&i===this.options.count-1)return[this.getMaxScrollOffset(),o];const p=o==="end"?m.end+this.options.scrollPaddingEnd:m.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(p,o,m.size),o]},this.scrollToOffset=(i,{align:o="start",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0;const c=this.getOffsetForAlignment(i,o),m=this.now();this.scrollState={index:null,align:o,behavior:s,startedAt:m,lastTargetOffset:c,stableFrames:0},this._scrollToOffset(c,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(i,{align:o="auto",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0,i=Math.max(0,Math.min(i,this.options.count-1));const c=this.getOffsetForIndex(i,o);if(!c)return;const[m,p]=c,h=this.now();this.scrollState={index:i,align:p,behavior:s,startedAt:h,lastTargetOffset:m,stableFrames:0},this._scrollToOffset(m,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(i,{behavior:o="auto"}={})=>{const s=this.getScrollOffset()+i,c=this.now();this.scrollState={index:null,align:"start",behavior:o,startedAt:c,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:i="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:i});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:i})},this.getTotalSize=()=>{var i;const o=this.getMeasurements();let s;if(o.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const c=o.length-1,m=this._flatMeasurements;m!=null?s=m[c*2]+m[c*2+1]:s=((i=o[c])==null?void 0:i.end)??0}else{const c=Array(this.options.lanes).fill(null);let m=o.length-1;for(;m>=0&&c.some(p=>p===null);){const p=o[m];c[p.lane]===null&&(c[p.lane]=p.end),m--}s=Math.max(...c.filter(p=>p!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const i=[];if(this.itemSizeCache.size===0)return i;const o=this.getMeasurements();for(const s of o)s&&this.itemSizeCache.has(s.key)&&i.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return i},this._scrollToOffset=(i,{adjustments:o,behavior:s})=>{this._intendedScrollOffset=i+(o??0),this.options.scrollToFn(i,{behavior:s,adjustments:o},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(a)}applyScrollAdjustment(a,i){return a===0?!1:Gu()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=a,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:i}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const o=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=o?o[0]:this.scrollState.lastTargetOffset,c=1,m=s!==this.scrollState.lastTargetOffset;if(!m&&DL(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=c){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,m){const p=this.getSize()||600,h=Math.abs(s-this.getScrollOffset()),g=this.scrollState.behavior==="smooth"&&h>p;this.scrollState.lastTargetOffset=s,g||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:g?"smooth":"auto"})}this.scheduleScrollReconcile()}}const jS=(e,a,i,o)=>{for(;e<=a;){const s=(e+a)/2|0,c=i(s);if(c<o)e=s+1;else if(c>o)a=s-1;else return s}return e>0?e-1:0};function QL(e,a,i){let o=0;for(;o<=a;){const s=(o+a)/2|0,c=e[s*2];if(c<i)o=s+1;else if(c>i)a=s-1;else return s}return o>0?o-1:0}function JL(e,a,i,o,s){const c=e.length-1;if(e.length<=o)return{startIndex:0,endIndex:c};if(o===1&&s!==null){const g=QL(s,c,i);let S=g;const v=i+a;for(;S<c&&s[S*2]+s[S*2+1]<v;)S++;return{startIndex:g,endIndex:S}}let p=jS(0,c,g=>e[g].start,i),h=p;if(o===1)for(;h<c&&e[h].end<i+a;)h++;else if(o>1){const g=Array(o).fill(0);for(;h<c&&g.some(v=>v<i+a);){const v=e[h];g[v.lane]=v.end,h++}const S=Array(o).fill(i+a);for(;p>=0&&S.some(v=>v>=i);){const v=e[p];S[v.lane]=v.start,p--}p=Math.max(0,p-p%o),h=Math.min(c,h+(o-1-h%o))}return{startIndex:p,endIndex:h}}const Du=typeof document<"u"?R.useLayoutEffect:R.useEffect;function WL({useFlushSync:e=!0,directDomUpdates:a=!1,directDomUpdatesMode:i="transform",...o}){const s=R.useReducer(S=>S+1,0)[1],c=R.useRef({enabled:a,mode:i,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});c.current.enabled=a,c.current.mode=i;const m=S=>{const v=c.current;if(!v.enabled||!v.container)return;const y=S.getTotalSize();if(y!==v.lastSize){v.lastSize=y;const x=S.options.horizontal?"width":"height";v.container.style[x]=`${y}px`}},p=S=>{const v=c.current;if(!v.enabled||!v.container)return;m(S);const y=!!S.options.horizontal,x=v.mode==="transform",E=y?"left":"top",P=S.options.scrollMargin,I=S.getVirtualItems();for(const k of I){const C=k.start-P,_=S.elementsCache.get(k.key);_&&v.lastPositions.get(_)!==C&&(v.lastPositions.set(_,C),x?_.style.transform=y?`translate3d(${C}px, 0, 0)`:`translate3d(0, ${C}px, 0)`:_.style[E]=`${C}px`)}},h={...o,onChange:(S,v)=>{var y;const x=c.current;let E=!0;if(x.enabled){p(S);const P=S.range,I=x.prevRange;E=!I||I.isScrolling!==S.isScrolling||I.startIndex!==P?.startIndex||I.endIndex!==P?.endIndex,E&&(x.prevRange=P?{startIndex:P.startIndex,endIndex:P.endIndex,isScrolling:S.isScrolling}:null)}E&&(e&&v?Js.flushSync(s):s()),(y=o.onChange)==null||y.call(o,S,v)}},[g]=R.useState(()=>{const S=new XL(h);return Object.assign(S,{containerRef:v=>{const y=c.current;if(y.container=v,y.lastSize=null,v&&y.enabled){const x=S.getTotalSize();y.lastSize=x;const E=S.options.horizontal?"width":"height";v.style[E]=`${x}px`}}})});return g.setOptions(h),Du(()=>g._didMount(),[]),Du(()=>(m(g),g._willUpdate())),Du(()=>{p(g)}),g}function ZL(e){return WL({observeElementRect:UL,observeElementOffset:VL,scrollToFn:YL,...e})}const Rs=170,Ns=10,GS=36,eO=44;function tO(e){const a=Math.max(Rs,e-GS);return Math.max(1,Math.floor((a+Ns)/(Rs+Ns)))}function nO(e,a){const i=Math.max(Rs,e-GS);return Math.max(Rs,Math.floor((i-Ns*Math.max(0,a-1))/a))+Ns}function aO(e,a){const i=[];for(const[o,s]of e){i.push({type:"header",id:`h-${o}`,label:o,count:s.length});for(let c=0;c<s.length;c+=a)i.push({type:"items",id:`r-${o}-${c}`,items:s.slice(c,c+a)})}return i}function oO({dateGroups:e,selectedKey:a,scrollElement:i,localizeBucket:o,renderTile:s}){const c=R.useRef(null),[m,p]=R.useState(0),h=R.useMemo(()=>tO(m||960),[m]),g=R.useMemo(()=>nO(m||960,h),[m,h]),S=R.useMemo(()=>aO(e,h),[e,h]);R.useEffect(()=>{const y=c.current;if(!y)return;const x=()=>p(y.clientWidth);x();const E=new ResizeObserver(x);return E.observe(y),()=>E.disconnect()},[]);const v=ZL({count:S.length,getScrollElement:()=>i,estimateSize:y=>S[y]?.type==="header"?eO:g,overscan:6});return R.useEffect(()=>{if(!a)return;const y=S.findIndex(x=>x.type==="items"&&x.items.some(E=>Ot(E)===a));y>=0&&v.scrollToIndex(y,{align:"center"})},[S,a,v]),d.jsx("div",{ref:c,className:"gallery__virtual",style:{height:v.getTotalSize()},children:v.getVirtualItems().map(y=>{const x=S[y.index];return x?d.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${y.start}px)`},children:x.type==="header"?d.jsxs("header",{className:"gallery__group-header gallery__group-header--virtual",children:[d.jsx("span",{className:"gallery__group-label",children:o(x.label)}),d.jsx("span",{className:"gallery__group-count",children:x.count})]}):d.jsx("div",{className:"gallery__grid gallery__grid--virtual",children:x.items.map((E,P)=>s(E,x.id,P))})},x.id):null})})}function rv({showSessions:e,favoritesOnly:a,query:i,historyNextCursor:o,favoriteHistoryNextCursor:s,historyLoadingOlder:c,favoriteHistoryLoadingOlder:m,onLoadOlder:p,onLoadOlderFavorites:h,t:g}){return e?d.jsx("div",{className:"gallery__load-more gallery__load-more--hint",children:g("gallery.sessionPaginationHint")}):i.trim()?null:a?s?d.jsx("div",{className:"gallery__load-more",children:d.jsx("button",{type:"button",onClick:h,disabled:m,children:g(m?"gallery.loadingOlderFavorites":"gallery.loadOlderFavorites")})}):null:o?d.jsx("div",{className:"gallery__load-more",children:d.jsx("button",{type:"button",onClick:p,disabled:c,children:g(c?"gallery.loadingOlder":"gallery.loadOlder")})}):null}function rO({groups:e,loose:a,favoritesOnly:i,galleryScope:o,setGalleryScope:s,renderTile:c,t:m}){return e.length===0&&a.length===0?d.jsx("div",{className:"gallery__empty",children:i?m("gallery.emptyFavorites"):o==="current-session"?d.jsxs(d.Fragment,{children:[d.jsx("p",{children:m("gallery.empty.currentSession")}),d.jsx("button",{type:"button",onClick:()=>s("all"),children:m("gallery.scope.all")})]}):m("gallery.emptySessions")}):d.jsxs(d.Fragment,{children:[e.map(p=>d.jsxs("section",{className:"gallery__group",children:[d.jsxs("header",{className:"gallery__group-header",children:[d.jsx("span",{className:"gallery__group-label",title:p.sessionId,children:p.title?p.displayLabel:m("gallery.sessionLabel",{name:p.displayLabel})}),d.jsx("span",{className:"gallery__group-count",children:p.items.length})]}),d.jsx("div",{className:"gallery__grid",children:p.items.map((h,g)=>c(h,p.sessionId,g))})]},p.sessionId)),a.length>0&&d.jsxs("section",{className:"gallery__group",children:[d.jsxs("header",{className:"gallery__group-header",children:[d.jsx("span",{className:"gallery__group-label",children:m("gallery.standalone")}),d.jsx("span",{className:"gallery__group-count",children:a.length})]}),d.jsx("div",{className:"gallery__grid",children:a.map((p,h)=>c(p,"loose",h))})]})]})}function iO({status:e,dismissed:a,onOpenFolder:i,onDismiss:o,t:s}){const c=e!=null&&e.state!=="ok"&&!a,m=e?.state==="recoverable"?"gallery.storageNoticeRecoverable":e?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return d.jsxs("div",{className:`gallery__storage-bar${c?" gallery__storage-bar--notice":""}`,children:[c?d.jsxs("div",{className:"gallery__storage-copy",children:[d.jsx("div",{className:"gallery__storage-title",children:s("gallery.storageNoticeTitle")}),d.jsx("div",{className:"gallery__storage-text",children:s(m)})]}):d.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:e?.generatedDirLabel??"~/.ima2/generated"}),d.jsxs("div",{className:"gallery__storage-actions",children:[d.jsx("button",{type:"button",className:"gallery__storage-button",onClick:i,title:s("gallery.openGeneratedDirTitle"),children:s("gallery.openGeneratedDir")}),c&&d.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:o,children:s("common.close")})]})]})}const iv="ima2.storageNoticeDismissed.0.09.23";function lO(e){const a=R.useRef(null),i=R.useRef(new Map),[o,s]=R.useState(()=>new Set);R.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const m=new IntersectionObserver(p=>{const h=p.filter(g=>g.isIntersecting);h.length!==0&&s(g=>{const S=new Set(g);for(const v of h){const y=v.target.dataset.galleryLazyKey;y&&S.add(y)}return S})},{root:e,rootMargin:"200% 0px"});a.current=m;for(const p of i.current.values())m.observe(p);return()=>{m.disconnect(),a.current=null}},[e]);const c=R.useCallback((m,p)=>{const h=i.current.get(m);h&&h!==p&&a.current?.unobserve(h),p?(i.current.set(m,p),a.current?.observe(p)):i.current.delete(m)},[]);return{visibleKeys:o,register:c,supported:typeof IntersectionObserver<"u"}}function sO(){const{t:e,locale:a}=ge(),i=w(te=>te.galleryOpen),o=w(te=>te.closeGallery),s=w(te=>te.history),c=w(te=>te.selectHistory),m=w(te=>te.currentImage),p=w(te=>te.trashHistoryItem),h=w(te=>te.showToast),g=w(te=>te.toggleGalleryFavorite),S=w(te=>te.galleryScope),v=w(te=>te.setGalleryScope),y=w(te=>te.historyNextCursor),x=w(te=>te.historyLoadingOlder),E=w(te=>te.favoriteHistoryNextCursor),P=w(te=>te.favoriteHistoryLoadingOlder),I=w(te=>te.loadOlderHistory),k=w(te=>te.loadFavoriteHistory),C=w(te=>te.loadOlderFavoriteHistory),_=w(r1),[N,j]=R.useState(""),[$,L]=R.useState("date"),[J,re]=R.useState(!1),[he,V]=R.useState(()=>new Set),ee=R.useRef(new Set),[oe,Ne]=R.useState([]),[ne,H]=R.useState([]),[ae,ce]=R.useState(!1),[be,Se]=R.useState(!1),[T,F]=R.useState(!1),[W,U]=R.useState(0),[le,pe]=R.useState(null),[xe,Oe]=R.useState(()=>{try{return localStorage.getItem(iv)==="1"}catch{return!1}}),Re=R.useRef(null),Ze=R.useRef({}),[ie,lt]=R.useState(null),at=R.useRef(0),st=R.useRef({open:!1,selectedKey:null}),bt=R.useMemo(()=>hs(s.filter(mi)),[s]),se=R.useCallback(te=>{Re.current=te,lt(te)},[]),qe=lO(ie),ot=uo(i,o);R.useEffect(()=>{i||j("")},[i]),R.useEffect(()=>{if(!i)return;let te=!1;return(async()=>{try{const Te=await LT();te||pe(Te)}catch{te||pe({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{te=!0}},[i]),R.useEffect(()=>{if(!i||$!=="session")return;let te=!1;return Ne([]),H([]),ce(!0),Se(!1),F(!1),(async()=>{try{const Te=await MT({limit:500,sessionId:S==="current-session"?_:void 0});if(te)return;F(Te.nextCursor!==null||Te.total>=500);const Tt=de=>{const We=de.kind,Ft=We==="classic"||We==="edit"||We==="generate"||We==="card-news-card"||We==="card-news-set"?We:null,Ma=de.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(de.filename??"");return{image:de.url,url:de.url,filename:de.filename,thumb:de.thumb??(Ma?void 0:de.url),mediaType:de.mediaType,video:de.video??null,videoSeries:de.videoSeries??null,videoContinuity:de.videoContinuity??null,prompt:de.prompt??void 0,userPrompt:de.userPrompt??null,revisedPrompt:de.revisedPrompt??null,promptMode:de.promptMode??null,composerPrompt:de.composerPrompt??null,composerInsertedPrompts:de.composerInsertedPrompts??null,size:de.size??void 0,quality:de.quality??void 0,format:de.format,moderation:de.moderation??void 0,model:de.model??void 0,reasoningEffort:de.reasoningEffort,provider:de.provider,providerUrl:de.providerUrl??null,usage:de.usage,elapsed:de.elapsed??void 0,createdAt:de.createdAt,sessionId:de.sessionId??null,nodeId:de.nodeId??null,parentNodeId:de.parentNodeId??null,clientNodeId:de.clientNodeId??null,requestId:de.requestId??null,kind:Ft,setId:de.setId??null,cardId:de.cardId??null,cardOrder:de.cardOrder??null,headline:de.headline??null,body:de.body??null,cards:de.cards,refsCount:de.refsCount??0,webSearchCalls:de.webSearchCalls??0,sequenceId:de.sequenceId??null,sequenceIndex:de.sequenceIndex??null,sequenceTotalRequested:de.sequenceTotalRequested??null,sequenceTotalReturned:de.sequenceTotalReturned??null,sequenceStatus:de.sequenceStatus??null,isFavorite:de.isFavorite??!1}};Ne(Te.sessions.map(de=>({sessionId:de.sessionId,title:de.title??null,label:de.label??null,displayLabel:de.title||de.label||de.sessionId.slice(0,8),items:hs(de.items.filter(mi).map(Tt))})).filter(de=>de.items.length>0)),H(hs(Te.loose.filter(mi).map(Tt)))}catch{te||Se(!0)}finally{te||ce(!1)}})(),()=>{te=!0}},[i,$,S,_,W]),R.useEffect(()=>{!i||$==="session"||!J||k()},[i,$,J,k]);const St=R.useMemo(()=>{const te=N.trim().toLowerCase().normalize("NFC");return bt.filter(Te=>J&&!Te.isFavorite?!1:te?(Te.prompt??"").toLowerCase().normalize("NFC").includes(te)||(Te.filename??"").toLowerCase().normalize("NFC").includes(te):!0)},[bt,N,J]),xt=R.useMemo(()=>J?oe.map(te=>({...te,items:te.items.filter(Te=>Te.isFavorite)})).filter(te=>te.items.length>0):oe,[oe,J]),nn=R.useMemo(()=>J?ne.filter(te=>te.isFavorite):ne,[ne,J]),Yt=R.useMemo(()=>{const te=new Map;for(const Te of St){const Tt=TL(Te.createdAt,a);te.has(Tt)||te.set(Tt,[]),te.get(Tt).push(Te)}return Array.from(te.entries())},[St,a]),fn=$==="session"?xt.reduce((te,Te)=>te+Te.items.length,0)+nn.length:St.length;R.useLayoutEffect(()=>{const te=m?Ot(m):null;if(!i){st.current={open:!1,selectedKey:te};return}const Te=st.current,Tt=!Te.open||Te.selectedKey!==te;st.current={open:!0,selectedKey:te};const de=te?Ze.current[te]:null;if(Tt&&de){de.scrollIntoView({block:"center"});return}Re.current&&(Re.current.scrollTop=at.current)},[i,m?.filename,m?.image,$,fn,Yt.length,xt.length,nn.length]);async function et(te,Te){Te.stopPropagation();const Tt=Ot(te);await p(te),delete Ze.current[Tt],window.requestAnimationFrame(()=>Re.current?.focus())}async function On(te){const Te=te.filename;if(!(!Te||ee.current.has(Te))){ee.current.add(Te),V(new Set(ee.current));try{const Tt=await g(te);if(Tt===null)return;Ne(de=>de.map(We=>({...We,items:We.items.map(Ft=>Ft.filename===Te?{...Ft,isFavorite:Tt}:Ft)}))),H(de=>de.map(We=>We.filename===Te?{...We,isFavorite:Tt}:We))}finally{ee.current.delete(Te),V(new Set(ee.current))}}}async function D(){try{await OT(),h(e("toast.openGeneratedDirOpened"))}catch{h(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ae,handleCopyCardNewsSetPath:ke,handleDownloadCardNewsManifest:Qe}=CL(o,h,e);function pt(){Oe(!0);try{localStorage.setItem(iv,"1")}catch{}}if(!i)return null;const Dt=te=>te==="earlier"||te==="today"||te==="yesterday"||te==="thisWeek"?e(`gallery.${te}`):te,_a=(te,Te,Tt)=>{const de=m?.image===te.image,We=Ot(te),Ft=gn=>{Ze.current[We]=gn,qe.register(We,gn)};return(qe.supported?qe.visibleKeys.has(We):!0)?te.kind==="card-news-set"?d.jsx("div",{ref:Ft,className:"gallery__tile-wrap gallery-card-news-set",children:d.jsx(EL,{item:te,onOpen:gn=>{Ae(gn)},onCopyPath:ke,onDownloadManifest:Qe})},`${Te}-${We}`):d.jsx(jL,{item:te,active:de,itemRef:Ft,onSelect:gn=>{c(gn),o()},onDelete:et,onToggleFavorite:On,favoriteBusy:!!(te.filename&&he.has(te.filename)),t:e},`${Te}-${We}`):d.jsx("div",{ref:Ft,className:"gallery__tile-wrap","data-gallery-lazy-key":We,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Te}-${We}`)},At=$==="session",Pt=m?Ot(m):null;return d.jsx("div",{className:"gallery-backdrop",onClick:o,role:"presentation",children:d.jsxs("div",{ref:ot,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:te=>te.stopPropagation(),children:[d.jsxs("div",{className:"gallery__header",children:[d.jsxs("div",{className:"gallery__title-row",children:[d.jsx("div",{className:"gallery__title",children:e("gallery.title")}),d.jsxs("div",{className:"gallery__meta",children:[e("gallery.total",{n:fn}),N||J?e("gallery.totalFiltered",{n:bt.length}):""]}),d.jsx(ju,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:J?"favorites":"all",onChange:te=>re(te==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),d.jsx(ju,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:$,onChange:L,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),d.jsx(ju,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:S,onChange:v,tabs:[{value:"current-session",label:e("gallery.scope.current"),disabled:!_},{value:"all",label:e("gallery.scope.all")}]})]}),d.jsx("input",{type:"text",className:"gallery__search",...At?{}:{"data-modal-initial-focus":!0},placeholder:e(At?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:N,onChange:te=>j(te.target.value),disabled:At}),d.jsx("button",{type:"button",className:"gallery__close",onClick:o,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),d.jsx(iO,{status:le,dismissed:xe,onOpenFolder:D,onDismiss:pt,t:e}),d.jsx("div",{className:"gallery__scroll",ref:se,tabIndex:-1,onScroll:()=>{at.current=Re.current?.scrollTop??0},children:At?ae?d.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):be?d.jsxs("div",{className:"gallery__empty",role:"alert",children:[d.jsx("span",{children:e("gallery.sessionLoadFailed")}),d.jsx("button",{type:"button",onClick:()=>U(te=>te+1),children:e("gallery.retry")})]}):d.jsxs(d.Fragment,{children:[T?d.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,d.jsx(rO,{groups:xt,loose:nn,favoritesOnly:J,galleryScope:S,setGalleryScope:v,renderTile:_a,t:e}),d.jsx(rv,{showSessions:At,favoritesOnly:J,query:N,historyNextCursor:y,favoriteHistoryNextCursor:E,historyLoadingOlder:x,favoriteHistoryLoadingOlder:P,onLoadOlder:()=>{I()},onLoadOlderFavorites:()=>{C()},t:e})]}):St.length===0?d.jsx("div",{className:"gallery__empty",children:bt.length===0?e("gallery.emptyAll"):e(J?"gallery.emptyFavorites":"gallery.noResults")}):d.jsxs(d.Fragment,{children:[d.jsx(oO,{dateGroups:Yt,selectedKey:Pt,scrollElement:ie,localizeBucket:Dt,renderTile:_a}),d.jsx(rv,{showSessions:At,favoritesOnly:J,query:N,historyNextCursor:y,favoriteHistoryNextCursor:E,historyLoadingOlder:x,favoriteHistoryLoadingOlder:P,onLoadOlder:()=>{I()},onLoadOlderFavorites:()=>{C()},t:e})]})})]})})}function cO(e){return e.includes("ratio")?"sizeConfirm.reasonRatio":e.includes("maxPixels")||e.includes("pixels")?"sizeConfirm.reasonPixels":e.includes("minPixels")?"sizeConfirm.reasonMinPixels":e.includes("min")?"sizeConfirm.reasonMin":e.includes("maxEdge")||e.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function dO(){const e=w(p=>p.customSizeConfirm),a=w(p=>p.confirmCustomSizeAdjustment),i=w(p=>p.cancelCustomSizeAdjustment),{t:o}=ge(),s=uo(!!e,i);if(!e)return null;const c=`${e.requestedW}x${e.requestedH}`,m=`${e.adjustedW}x${e.adjustedH}`;return d.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:d.jsxs("div",{ref:s,className:"modal custom-size-confirm",role:"dialog","aria-modal":"true","aria-labelledby":"custom-size-confirm-title","aria-describedby":"custom-size-confirm-body",tabIndex:-1,children:[d.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:o("sizeConfirm.title")}),d.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[d.jsx("p",{children:o("sizeConfirm.body")}),d.jsxs("dl",{className:"size-confirm__pairs",children:[d.jsxs("div",{className:"size-confirm__pair",children:[d.jsx("dt",{children:o("sizeConfirm.requested")}),d.jsx("dd",{children:c})]}),d.jsxs("div",{className:"size-confirm__pair",children:[d.jsx("dt",{children:o("sizeConfirm.adjusted")}),d.jsx("dd",{children:m})]})]}),d.jsx("p",{className:"size-confirm__reason",children:o(cO(e.reasons))})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button","data-modal-initial-focus":!0,className:"modal__btn modal__btn--secondary",onClick:i,children:o("sizeConfirm.cancel")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{a()},children:o("sizeConfirm.approve")})]})]})})}function ls(e){return e==null||e===""?"-":String(e)}function uO(){const{t:e}=ge(),a=w(h=>h.metadataRestore),i=w(h=>h.applyMetadataRestore),o=w(h=>h.addMetadataRestoreAsReference),s=w(h=>h.cancelMetadataRestore),c=uo(!!a,s);if(!a)return null;const m=a.metadata,p=m.userPrompt||m.prompt||m.revisedPrompt||"";return d.jsx("div",{className:"modal-backdrop metadata-restore-backdrop",role:"presentation",children:d.jsxs("div",{ref:c,className:"modal metadata-restore",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-restore-title",tabIndex:-1,children:[d.jsx("div",{id:"metadata-restore-title",className:"modal__title",children:e("metadata.restoreTitle")}),d.jsxs("div",{className:"modal__body metadata-restore__body",children:[d.jsx("p",{children:e("metadata.restoreBody")}),d.jsxs("div",{className:"metadata-restore__preview",children:[d.jsx("img",{src:a.image,alt:e("metadata.imageAlt")}),d.jsxs("div",{className:"metadata-restore__details",children:[d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.prompt")}),d.jsx("strong",{title:p,children:ls(p)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.size")}),d.jsx("strong",{children:ls(m.size)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.quality")}),d.jsx("strong",{children:ls(m.quality)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.model")}),d.jsx("strong",{children:ls(m.model)})]}),d.jsxs("div",{children:[d.jsx("span",{children:e("metadata.source")}),d.jsx("strong",{children:a.source==="png-comment"?e("metadata.sourcePngComment"):e("metadata.sourceXmp")})]})]})]})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:s,"data-modal-initial-focus":!0,children:e("common.cancel")}),d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:o,children:e("metadata.useAsReferenceOnly")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:i,children:e("metadata.applySettings")})]})]})})}function mO(){const{t:e}=ge(),a=w(P=>P.readinessPopupOpen),i=w(P=>P.closeReadinessPopup),o=w(P=>P.openSettings),s=w(P=>P.provider),c=w(P=>P.imageModel),m=w(P=>P.reasoningEffort),p=w(P=>P.webSearchEnabled),h=_S(),g=s==="grok",S=Na.find(P=>P.value===c),v=uo(a,i);if(!a)return null;const y=h[s],x=y.ok,E=()=>{i(),o("providers")};return d.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:i,role:"presentation",children:d.jsxs("div",{ref:v,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:P=>P.stopPropagation(),children:[d.jsx("div",{id:"provider-readiness-title",className:"modal__title",children:e("readiness.title")}),d.jsxs("div",{className:"modal__body provider-readiness__body",children:[d.jsxs("div",{className:`provider-readiness__status${x?" is-ok":" is-blocked"}`,children:[d.jsx("span",{"aria-hidden":"true"}),d.jsx("strong",{children:e(x?"readiness.ready":"readiness.blocked")}),d.jsx("small",{children:x?e("readiness.readyBody"):y.reason})]}),y.hint?d.jsx("p",{className:"modal__hint",children:y.hint}):null,d.jsxs("dl",{className:"provider-readiness__facts",children:[d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.provider")}),d.jsx("dd",{children:s==="agy"?"Gemini":s==="grok"?"Grok OAuth":s==="oauth"?"GPT OAuth":"GPT API"})]}),d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.model")}),d.jsx("dd",{children:S?e(S.fullLabelKey):c})]}),g?d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.grokApi")}),d.jsx("dd",{children:e("readiness.grokApiBody")})]}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.reasoning")}),d.jsx("dd",{children:m})]}),d.jsxs("div",{children:[d.jsx("dt",{children:e("readiness.webSearch")}),d.jsx("dd",{children:e(p?"settings.webSearch.on":"settings.webSearch.off")})]})]})]})]}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:i,"data-modal-initial-focus":!0,children:e("common.close")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:E,children:e("readiness.openAccount")})]})]})})}const lv="ima2.onboardingDismissed";function pO(){const{t:e}=ge(),a=w(I=>I.openSettings),i=RS(),o=NS(),{data:s}=kS(),[c,m]=R.useState(()=>{try{return localStorage.getItem(lv)==="1"}catch{return!1}}),p=i!==null&&o!==null&&s!=null,h=i?.status==="auth_required"||i?.status==="offline",g=o?.status==="offline"||o?.status==="error",S=s?!s.gemini?.configured&&!s.vertex?.configured:!1,y=!c&&(p&&h&&g&&S),x=()=>{try{localStorage.setItem(lv,"1")}catch{}m(!0)},E=()=>{x(),a("providers")},P=uo(y,x);return y?d.jsx("div",{className:"modal-backdrop",role:"presentation",children:d.jsxs("div",{ref:P,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[d.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),d.jsx("div",{className:"modal__body",children:d.jsx("p",{children:e("onboarding.body")})}),d.jsxs("div",{className:"modal__actions",children:[d.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:x,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),d.jsx("button",{type:"button",className:"modal__btn",onClick:E,children:e("onboarding.login")})]})]})}):null}function fO(){const e=w(m=>m.trashPending),a=w(m=>m.restorePendingTrash),i=w(m=>m.clearPendingTrash),{t:o}=ge(),[s,c]=R.useState(Date.now());return R.useEffect(()=>{if(!e)return;c(Date.now());const m=window.setInterval(()=>{const p=Date.now();c(p),p>=e.expiresAt&&i()},500);return()=>window.clearInterval(m)},[i,e]),e?d.jsxs("div",{className:"trash-undo-toast",children:[d.jsx("span",{children:o("gallery.deleted",{filename:e.filename})}),d.jsx("button",{type:"button",onClick:()=>{a()},children:o("gallery.undo")}),d.jsx("span",{className:"trash-undo-toast__timer",children:o("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((e.expiresAt-s)/1e3))})})]}):null}function gO(){return d.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("line",{x1:"4",y1:"6",x2:"14",y2:"6"}),d.jsx("circle",{cx:"17",cy:"6",r:"2.2"}),d.jsx("line",{x1:"4",y1:"12",x2:"8",y2:"12"}),d.jsx("circle",{cx:"11",cy:"12",r:"2.2"}),d.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),d.jsx("line",{x1:"4",y1:"18",x2:"14",y2:"18"}),d.jsx("circle",{cx:"17",cy:"18",r:"2.2"})]})}function hO(){const e=w(g=>g.composeSheetOpen),a=w(g=>g.composeSheetTab),i=w(g=>g.openComposeSheet),o=w(g=>g.settingsOpen),s=w(g=>g.uiMode),{t:c}=ge();if(!ka()||o||s==="home"||s==="card-news"||s==="agent"||s==="assets"||s==="asset-gen")return null;const p=e&&a==="controls",h=c("sheet.controlsOpen");return d.jsx("button",{type:"button",className:"mobile-settings-toggle","aria-expanded":p,"aria-controls":"mobile-generate-sheet","aria-label":h,title:h,onClick:()=>i("controls"),children:d.jsx(gO,{})})}let ks=null;function yO(e){ks=e}function vO(){const e=ks;ks=null,e?.isConnected&&e.focus()}function sv(){ks=null}function bO(){const{t:e}=ge(),a=w(S=>S.openComposeSheet),i=w(S=>S.settingsOpen),o=w(S=>S.uiMode),s=o==="agent"&&lr?"agent":o==="node"&&ir?"node":o==="home"?"home":o==="assets"?"assets":o==="asset-gen"?"asset-gen":"classic",c=ka(),m=R.useRef(null),p=R.useRef(null),h=R.useRef(null),g=(S,v)=>{v.current&&yO(v.current),a(S==="library"?"library":S==="controls"?"controls":"prompt")};return!c||i||s!=="classic"?null:d.jsxs("header",{className:"mobile-app-bar",role:"banner",children:[d.jsxs("div",{className:"mobile-app-bar__brand",children:[d.jsx("div",{className:"logo-mark","aria-hidden":"true"}),d.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[d.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),d.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),d.jsxs("div",{className:"mobile-app-bar__actions",children:[d.jsx(AS,{compact:!0}),d.jsx("button",{ref:m,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>g("library",m),"aria-label":e("promptLibrary.title"),title:e("promptLibrary.title"),children:d.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:d.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),d.jsx("button",{ref:p,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>g("controls",p),"aria-label":e("appBar.controls"),title:e("appBar.controls"),children:d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("circle",{cx:"12",cy:"12",r:"3"}),d.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),d.jsx("button",{ref:h,type:"button",className:"mobile-app-bar__generate",onClick:()=>g("prompt",h),"aria-label":e("appBar.generateAria"),title:e("appBar.generate"),style:{width:44,padding:0},children:d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),d.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]})]})}const SO={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},cv={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function xO(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const a=SO[e];return a&&a!=="settings"?{mode:a,settings:!1}:null}function AO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),d.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),d.jsx("path",{d:"m21 15-5-5L5 21"})]})}function TO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),d.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})}function CO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"2",y:"6",width:"8",height:"6",rx:"1"}),d.jsx("rect",{x:"14",y:"12",width:"8",height:"6",rx:"1"}),d.jsx("path",{d:"M10 9h4"}),d.jsx("path",{d:"M14 15V9a2 2 0 0 1 2-2h0"})]})}function wO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[d.jsx("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}),d.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(-30 12 12)"}),d.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(30 12 12)"})]})}function IO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function EO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),d.jsx("path",{d:"M8 12h8"})]})}function RO(){return d.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("rect",{x:"3",y:"3",width:"13",height:"13",rx:"2"}),d.jsx("path",{d:"M3 12l3.5-3.5a1.4 1.4 0 0 1 2 0L13 13"}),d.jsx("path",{d:"M19 14v6"}),d.jsx("path",{d:"M16 17h6"})]})}const NO=[{id:"home",mode:"home",icon:TO,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:AO,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:CO,labelKey:"nav.node",enabled:ir},{id:"agent",mode:"agent",icon:wO,labelKey:"nav.agent",enabled:lr},{id:"assets",mode:"assets",icon:EO,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:RO,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:IO,labelKey:"nav.settings",enabled:!0,bottom:!0}];function kO(){const{t:e}=ge(),a=w(x=>x.uiMode),i=w(x=>x.setUIMode),o=w(x=>x.settingsOpen),s=w(x=>x.openSettings),c=w(x=>x.closeSettings),m=ka(),p=R.useCallback(x=>{if(x.settingsAction){o?(c(),history.replaceState(null,"",cv[a]||"#create")):(s(),history.replaceState(null,"","#settings"));return}x.mode&&(o&&c(),i(x.mode),history.replaceState(null,"",cv[x.mode]||"#create"))},[a,o,i,s,c]);R.useEffect(()=>{const x=()=>{const E=xO();E&&(E.settings?s():(o&&c(),i(E.mode)))};return x(),window.addEventListener("popstate",x),window.addEventListener("hashchange",x),()=>{window.removeEventListener("popstate",x),window.removeEventListener("hashchange",x)}},[]);const h=NO.filter(x=>x.enabled),g=h.filter(x=>!x.bottom),S=h.filter(x=>x.bottom),v=x=>x.settingsAction?o:!o&&x.mode===a,y=x=>d.jsxs("button",{type:"button",className:`nav-rail__btn${v(x)?" is-active":""}`,onClick:()=>p(x),"aria-label":e(x.labelKey),"aria-current":v(x)?"page":void 0,children:[d.jsx(x.icon,{}),d.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(x.labelKey)})]},x.id);return m?d.jsx("nav",{className:"nav-rail nav-rail--mobile","aria-label":e("nav.ariaLabel"),children:h.map(y)}):d.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[d.jsx("div",{className:"nav-rail__top",children:g.map(y)}),d.jsx("div",{className:"nav-rail__bottom",children:S.map(y)})]})}const _O=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-BYTG-mBa.js"),[]).then(e=>({default:e.PromptLibraryPanel}))),Rn=["prompt","controls","library"],ss="mobile-inflight-panel",cs=e=>`mobile-sheet-tab-${e}`,ds=e=>`mobile-sheet-panel-${e}`;function MO(){const{t:e}=ge(),a=w(N=>N.composeSheetOpen),i=w(N=>N.composeSheetTab),o=w(N=>N.setComposeSheetTab),s=w(N=>N.closeComposeSheet),c=w(N=>N.inFlight.length),m=w(N=>N.settingsOpen),p=w(N=>N.uiMode),h=p==="agent"&&lr?"agent":p==="node"&&ir?"node":p==="home"?"home":p==="assets"?"assets":"classic",g=ka(),[S,v]=R.useState(!1),y=R.useRef(c),x=R.useRef(!1),E=R.useRef(null),P=R.useRef({}),I=R.useRef(!1),k=N=>{o(N),requestAnimationFrame(()=>P.current[N]?.focus())},C=(N,j)=>{const $=Rn.indexOf(j),L=N.key==="ArrowRight"?Rn[($+1)%Rn.length]:N.key==="ArrowLeft"?Rn[($-1+Rn.length)%Rn.length]:N.key==="Home"?Rn[0]:N.key==="End"?Rn[Rn.length-1]:null;L&&(N.preventDefault(),k(L))};R.useEffect(()=>{if((!a||i!=="prompt"||!g||m||h!=="classic")&&v(!1),!a)return;const N=j=>{j.key==="Escape"&&s()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[a,i,s,g,m,h]),R.useLayoutEffect(()=>{const N=y.current>0&&c===0;y.current=c,N&&(v(!1),x.current&&E.current?.querySelector(".generate-btn")?.focus(),x.current=!1)},[c]),R.useLayoutEffect(()=>{if(a){I.current=!0;const N=requestAnimationFrame(()=>P.current[i]?.focus());return()=>cancelAnimationFrame(N)}I.current&&(I.current=!1,vO())},[a,i]);const _=g&&!m&&h==="classic";return R.useEffect(()=>{_||(I.current=!1,w.getState().composeSheetOpen&&s(),sv())},[_]),R.useEffect(()=>()=>sv(),[]),_?d.jsxs(d.Fragment,{children:[a?d.jsx("button",{type:"button",className:"compose-sheet-backdrop","aria-label":e("sheet.close"),onClick:s}):null,d.jsxs("section",{id:"mobile-generate-sheet",inert:!a,className:`compose-sheet${a?" compose-sheet--open":""}`,role:"dialog","aria-modal":a?"true":"false","aria-label":e("sheet.generate"),"aria-hidden":!a,children:[d.jsx("button",{type:"button",className:"compose-sheet__handle",onClick:s,"aria-label":e("sheet.close")}),d.jsx("div",{className:"mobile-sheet-tabs",role:"tablist","aria-label":e("sheet.generate"),children:Rn.map(N=>d.jsx("button",{ref:j=>{P.current[N]=j},id:cs(N),type:"button",role:"tab","aria-selected":i===N,"aria-controls":ds(N),tabIndex:i===N?0:-1,className:`mobile-sheet-tabs__button${i===N?" active":""}`,onClick:()=>o(N),onKeyDown:j=>C(j,N),children:e(`sheet.tabs.${N}`)},N))}),d.jsxs("div",{className:"compose-sheet__body",children:[d.jsx("div",{id:ds("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":cs("prompt"),hidden:i!=="prompt",onFocusCapture:N=>{const j=document.getElementById(ss);x.current=j?.contains(N.target)??!1},children:i==="prompt"?d.jsxs(d.Fragment,{children:[d.jsx(qm,{}),c>0?d.jsxs("section",{className:"compose-sheet__inflight",hidden:!S,children:[d.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{E.current?.querySelector(".inflight-badge")?.focus(),v(!1)},"aria-expanded":S,"aria-controls":ss,"aria-label":e("inflight.inlineCollapse",{n:c}),children:[d.jsxs("span",{children:[e("inflight.title")," (",c,")"]}),d.jsx("span",{"aria-hidden":"true",children:"−"})]}),d.jsx(Hm,{variant:"inline",panelId:ss}),d.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,d.jsxs("div",{ref:E,className:"compose-sheet__actions",children:[d.jsx(Um,{}),d.jsx(xS,{variant:"inline",panelId:ss,expanded:S,onToggle:v})]})]}):null}),d.jsx("div",{id:ds("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":cs("controls"),hidden:i!=="controls",children:i==="controls"?d.jsx(OS,{}):null}),d.jsx("div",{id:ds("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":cs("library"),hidden:i!=="library",children:i==="library"?d.jsx(R.Suspense,{fallback:d.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:d.jsx(_O,{variant:"embedded",forceOpen:!0,onRequestClose:()=>o("prompt")})}):null})]})]})]}):null}const PO={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function LO(){const e=w(o=>o.uiMode),a=w(o=>!!o.currentImage||!!o.multimodePreviewFlightId),i=w(o=>o.selectHistoryShortcutTarget);R.useEffect(()=>{if(e!=="classic")return;const o=s=>{const c=PO[s.key];c&&(s.defaultPrevented||ys(s.target)||a&&(s.preventDefault(),i(c)))};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[a,i,e])}const us=64,DS="Image Gen";let Km=DS,tm=!1,Ia=null,$m="",nm=!1;function FS(){return navigator}function zS(){if(typeof document>"u")return null;if(Ia)return Ia;const e=document.querySelector('link[rel~="icon"]');if(e)return Ia=e,$m=e.href||e.getAttribute("href")||"",e;const a=document.createElement("link");return a.rel="icon",document.head.appendChild(a),Ia=a,nm=!0,a}function OO(e){const a=document.createElement("canvas");a.width=us,a.height=us;const i=a.getContext("2d");return i?(i.clearRect(0,0,us,us),i.fillStyle="#0a0a0a",jO(i,6,6,52,52,12),i.fill(),i.strokeStyle="#ffffff",i.lineWidth=5,i.beginPath(),i.arc(30,32,14,0,Math.PI*2),i.stroke(),i.fillStyle="#ffffff",i.beginPath(),i.arc(30,32,5,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(48,16,e>1?13:10,0,Math.PI*2),i.fillStyle="#ff335f",i.fill(),i.lineWidth=4,i.strokeStyle="#ffffff",i.stroke(),e>1&&(i.fillStyle="#ffffff",i.font="bold 15px sans-serif",i.textAlign="center",i.textBaseline="middle",i.fillText(String(Math.min(e,9)),48,17)),a.toDataURL("image/png")):$m}function jO(e,a,i,o,s,c){e.beginPath(),e.moveTo(a+c,i),e.arcTo(a+o,i,a+o,i+s,c),e.arcTo(a+o,i+s,a,i+s,c),e.arcTo(a,i+s,a,i,c),e.arcTo(a,i,a+o,i,c),e.closePath()}async function GO(e){const a=FS();if(typeof a.setAppBadge=="function")try{await a.setAppBadge(e)}catch{}}async function DO(){const e=FS();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function FO(e){document.title=`(${e}) ${Km}`;const a=zS();a&&(a.href=OO(e)),GO(e)}function dv(){document.title=Km,Ia&&(nm?(Ia.remove(),Ia=null,nm=!1):Ia.href=$m),DO()}function uv(){tm||typeof document>"u"||(tm=!0,Km=document.title||DS,zS())}function zO(e){R.useEffect(()=>(uv(),()=>{tm&&dv()}),[]),R.useEffect(()=>{uv(),e>0?FO(e):dv()},[e])}function qO(){R.useEffect(()=>{if(typeof window>"u")return;const e=window.visualViewport;if(!e)return;const a=()=>{const i=Math.round(e.height),o=Math.round(e.offsetTop);document.documentElement.style.setProperty("--vv-h",`${i}px`),document.documentElement.style.setProperty("--vv-offset-top",`${o}px`)};return a(),e.addEventListener("resize",a),e.addEventListener("scroll",a),()=>{e.removeEventListener("resize",a),e.removeEventListener("scroll",a)}},[])}const UO=R.lazy(()=>$t(()=>import("./NodeCanvas-scDxt0LA.js"),__vite__mapDeps([0,1])).then(e=>({default:e.NodeCanvas}))),HO=R.lazy(()=>$t(()=>import("./SettingsWorkspace-chsddbrB.js"),[]).then(e=>({default:e.SettingsWorkspace}))),BO=R.lazy(()=>$t(()=>import("./CardNewsWorkspace-F3LrEj0b.js"),[]).then(e=>({default:e.CardNewsWorkspace}))),VO=R.lazy(()=>$t(()=>import("./AgentWorkspace-JQ0K_ndE.js"),__vite__mapDeps([2,3])).then(e=>({default:e.AgentWorkspace}))),KO=R.lazy(()=>$t(()=>import("./AssetsWorkspace-Di0BYZZW.js"),__vite__mapDeps([4,5,3,6])).then(e=>({default:e.AssetsWorkspace}))),$O=R.lazy(()=>$t(()=>import("./AssetGenWorkspace-B2d-aiIb.js").then(e=>e.A),__vite__mapDeps([7,5,3,8])).then(e=>({default:e.AssetGenWorkspace}))),YO=R.lazy(()=>$t(()=>import("./HomeWorkspace-KplbVQT9.js"),[]).then(e=>({default:e.HomeWorkspace}))),XO=R.lazy(()=>$t(()=>import("./PromptLibraryPanel-BYTG-mBa.js"),[]).then(e=>({default:e.PromptLibraryPanel})));function QO(){return d.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function JO(){LO(),qO();const{locale:e}=ge(),a=w(j=>j.hydrateHistory),i=w(j=>j.loadSessions),o=w(j=>j.syncCapabilities),s=w(j=>j.startInFlightPolling),c=w(j=>j.reconcileInflight),m=w(j=>j.syncFromStorage),p=w(j=>j.settingsOpen),h=w(j=>j.unseenGeneratedCount),g=w(j=>j.historyStripLayout),S=w(j=>j.workspaceProfile),v=w(j=>j.uiMode),y=v==="agent"&&lr?"agent":v==="node"&&ir?"node":v==="home"?"home":v==="assets"?"assets":v==="asset-gen"?"asset-gen":"classic",x=y==="agent",E=y==="assets",P=y==="asset-gen",I=y==="home",k=ka(),C=Ei(S),_=!k&&y==="classic"&&C.composerPlacement==="bottom"&&C.multimodeHistoryGrouping==="sequence",N=!_&&!x&&!E&&!P&&!I;return zO(h),R.useEffect(()=>{document.documentElement.lang=e},[e]),R.useEffect(()=>{o(),a(),i(),c(),s(),lo(),CT(()=>c()),wT(j=>{j==="failed"&&console.warn("[SSE] connection failed after multiple retries")})},[a,i,c,s,o]),R.useEffect(()=>{const j=$=>{const L=$.detail?.assetId;L&&w.getState().openAssetDetail(L)};return window.addEventListener("ima2:open-assets-detail",j),()=>window.removeEventListener("ima2:open-assets-detail",j)},[]),R.useEffect(()=>{const j=$=>{$.key&&($.key==="ima2.inFlight"||$.key==="ima2.selectedFilename")&&m()};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[m]),R.useEffect(()=>{const j=()=>{o1(w.getState)};return window.addEventListener("beforeunload",j),()=>{window.removeEventListener("beforeunload",j)}},[]),d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:`app${S==="prompt-studio"?" app--prompt-studio":""}${p?" app--settings-open":""}${N&&g==="horizontal"?" app--history-horizontal":""}${N&&g==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":g,"data-mobile":k?"1":void 0,"data-ui-mode":y,children:[d.jsx(kO,{}),I?null:d.jsx(P2,{}),d.jsx(bO,{}),N?d.jsx(SL,{}):null,d.jsx(R.Suspense,{fallback:d.jsx(QO,{}),children:p?d.jsx(HO,{}):y==="classic"?_?d.jsx(bP,{}):d.jsx(em,{}):y==="node"?d.jsx(UO,{}):y==="card-news"?d.jsx(BO,{}):y==="agent"?d.jsx(VO,{}):y==="assets"?d.jsx(KO,{}):y==="asset-gen"?d.jsx($O,{}):y==="home"?d.jsx(YO,{}):d.jsx(em,{})}),y==="agent"||y==="card-news"||y==="assets"||y==="asset-gen"||y==="home"?null:d.jsx(fL,{})]}),d.jsx(dO,{}),d.jsx(fO,{}),d.jsx(xL,{}),d.jsx(AL,{}),d.jsx(sO,{}),d.jsx(uO,{}),d.jsx(mO,{}),d.jsx(pO,{}),d.jsx(MO,{}),d.jsx(hO,{}),y==="card-news"?d.jsx(R.Suspense,{fallback:null,children:d.jsx(XO,{})}):null]})}function WO(){if(window.location.protocol!=="http:"||window.location.hostname!=="localhost")return!1;const e=new URL(window.location.href);return e.hostname="127.0.0.1",window.location.replace(e.toString()),!0}WO()||cT.createRoot(document.getElementById("root")).render(d.jsx(R.StrictMode,{children:d.jsx(JO,{})}));export{ZL as $,$u as A,vs as B,Js as C,i0 as D,Cj as E,xn as F,r0 as G,cS as H,Na as I,Rj as J,Nj as K,kj as L,vt as M,gL as N,o0 as O,tR as P,Eb as Q,Hl as R,HM as S,CM as T,Tj as U,d0 as V,BM as W,Ij as X,JT as Y,bj as Z,_1 as _,R as a,vS as a0,_j as a1,Pj as a2,Mj as a3,Aj as a4,Ej as a5,im as a6,_b as a7,IL as a8,Hm as a9,ej as aA,sj as aB,aj as aC,z2 as aD,nj as aE,dP as aF,pv as aG,tj as aH,Z as aI,uj as aJ,cj as aK,mj as aL,pj as aM,dj as aN,ZO as aO,fj as aP,gj as aQ,hj as aR,yj as aS,vj as aT,$t as aa,xj as ab,io as ac,Sj as ad,Ks as ae,zm as af,yS as ag,Ot as ah,_S as ai,AO as aj,CO as ak,ir as al,wO as am,lr as an,EO as ao,cv as ap,uo as aq,TM as ar,sP as as,cP as at,Zu as au,ij as av,rj as aw,ys as ax,lj as ay,oj as az,w as b,Cv as c,ML as d,p1 as e,WE as f,eT as g,Mn as h,kn as i,d as j,ro as k,wj as l,M1 as m,u1 as n,kb as o,QT as p,ue as q,am as r,ka as s,tr as t,ge as u,RS as v,XR as w,NS as x,PP as y,kS as z};