scenri 0.17.0 → 0.17.1
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.
|
@@ -101,6 +101,6 @@ Please change the parent <Route path="${k}"> to <Route path="${k==="/"?"*":`${k}
|
|
|
101
101
|
`)&&t.add(n+l+1);n+=i.v.length}t.add(n);const r=[...t].sort((i,l)=>i-l),a=Cf(e);return r.filter((i,l)=>l===r.length-1||!/^[ \n]*$/.test(a.slice(i,r[l+1])))}const Cf=e=>e.map(t=>t.t==="text"?t.v:"").join(""),Dv=(e,t,n)=>{const r=n<=t?e.slice(n,t):e.slice(t+1,n);return/^[ \n]*$/.test(r)};function qX(e,t){const n=Cf(e);return SN(e).filter(r=>!Dv(n,t,r))}function XX(e,t){return e.find(n=>n>=t)??(e.length?e[e.length-1]:null)}function QX(e,t){let n=null,r=1/0;for(const a of e){const i=Math.abs(a-t);i<r&&(r=i,n=a)}return n}function EN(e,t,n){if(!e||!t.parentNode)return!1;const r=ni(e,t);if(Dv(Cf(rm(e)),r,n))return!1;let a=null,i=0;for(const l of Array.from(e.childNodes)){const u=Vu(l);if(n<=i+u){if(l.nodeType===Node.TEXT_NODE){const f=n-i;f<=0?a=l:f>=u?a=l.nextSibling:a=l.splitText(Zh(l,f))}else a=n===i?l:l.nextSibling;break}i+=u}return a===t?!1:(t.remove(),e.insertBefore(t,a),no(e),!0)}function Yx(e,t,n){if(!e)return!1;const r=ni(e,t),a=qX(rm(e),r),i=n===-1?[...a].reverse().find(l=>l<r):a.find(l=>l>r+1);return i===void 0?!1:EN(e,t,i)}function JX(e,t){if(!e)return t;const n=Cf(rm(e));let r=t;for(;r>0&&(n[r-1]===" "||n[r-1]===`
|
|
102
102
|
`);)r-=1;return r}function qx(e,t,n,r){if(!e)return null;const a=ZX(e,n,r);if(!a)return null;const i=rm(e),l=ni(e,t),u=SN(i),f="beside"in a?ni(e,a.beside)+(a.side==="before"?0:1):a.node.nodeType===Node.TEXT_NODE||a.node===e?Vh(e,a.node,a.offset):null;if(f===null)return null;const h="beside"in a&&a.side==="after"?XX(u,f):QX(u,f);return h===null?null:{units:h,noop:Dv(Cf(i),l,h)}}function A6(e,t){const n=Io(t)||"the chip",r=eQ(t);if(r)return`Moved ${n} before ${r}.`;const a=tQ(t);return a?`Moved ${n} after ${a}.`:ni(e,t)===0?`Moved ${n} to the start of the brief.`:`Moved ${n} to the end of the brief.`}const CN=3;function eQ(e){for(let t=e.nextSibling;t;t=t.nextSibling){if(Vs(t))return Io(t)||null;const n=(t.textContent??"").replace(cl,"").trim();if(n)return`"${n.split(/\s+/).slice(0,CN).join(" ")}"`}return null}function tQ(e){for(let t=e.previousSibling;t;t=t.previousSibling){if(Vs(t))return Io(t)||null;const n=(t.textContent??"").replace(cl,"").trim();if(n)return`"${n.split(/\s+/).slice(-CN).join(" ")}"`}return null}function rm(e){const t=[];let n="";for(const r of Array.from(e.childNodes)){if(r.nodeType===Node.TEXT_NODE){n+=(r.textContent??"").replace(cl,"");continue}n&&(t.push({t:"text",v:n}),n=""),t.push({t:"ref",imageHash:""})}return n&&t.push({t:"text",v:n}),t}function N6(e){var n;const t=e.target;(n=t==null?void 0:t.closest)!=null&&n.call(t,'input, textarea, select, [contenteditable=""], [contenteditable="true"]')||e.preventDefault()}const Vd=e=>(e==null?void 0:e.querySelector('[data-kind="template"]'))??null,Pi=e=>{var t;return((t=e==null?void 0:e.closest)==null?void 0:t.call(e,Ef))??null};function _g(e,t,n={}){var a;if(!e)return!1;let r=!1;for(let i=0;i<32;i++){const l=rQ(e,!!n.commit);if(!l)break;const u={t:"color",hex:l.hex,name:(a=n.nameFor)==null?void 0:a.call(n,l.hex)};oQ(e,l.node,l.start,l.end,t(u)),r=!0}return r&&no(e),r}function nQ(e,t){var i;e.dataset.kind="color",e.dataset.tok=nm(t);const n=t.name??t.hex,r=e.querySelector(".sc-token-swatch");r&&(r.style.background=t.hex);const a=e.querySelector(".sc-token-label");a&&(a.textContent=n),e.getAttribute("role")==="button"&&e.setAttribute("aria-label",`colour: ${n}. Change or remove.`),(i=e.querySelector('[data-role="remove"]'))==null||i.setAttribute("aria-label",`Remove ${n}`)}function rQ(e,t){for(let n=e.childNodes.length-1;n>=0;n--){const r=e.childNodes[n];if(r.nodeType!==Node.TEXT_NODE)continue;const a=r,i=aQ(a.textContent??"",t,(u,f)=>sQ(a,f,u)),l=i[i.length-1];if(l)return{node:a,...l}}return null}function sQ(e,t,n){if(n>0)return Bh(t[n-1]);const r=e.previousSibling;if(!r||Vs(r))return!0;if(r.nodeType===Node.TEXT_NODE){const a=r.textContent??"";return!a.length||Bh(a[a.length-1]??"")}return!0}function aQ(e,t,n){const r=[];for(let a=0;a<e.length;a++){if(e[a]!=="#"||!n(a,e))continue;let i=a+1;for(;i<e.length&&/[0-9A-Fa-f]/.test(e[i]??"");)i++;const l=e.slice(a,i),u=MY(l);if(!u)continue;if(i-a-1===3){const h=e[i];if(h===void 0?!t:/[0-9A-Za-z]/.test(h))continue}r.push({start:a,end:i,hex:u})}return r}function oQ(e,t,n,r,a){const i=t.textContent??"",l=i.slice(0,n),u=i.slice(r),f=typeof window>"u"?null:window.getSelection();let h=null;f&&f.rangeCount>0&&f.getRangeAt(0).startContainer===t&&(h=f.getRangeAt(0).startOffset);const p=t.parentNode;if(p&&(t.textContent=u.length?u:" ",p.insertBefore(a,t),l&&p.insertBefore(document.createTextNode(l),a),h!=null)){if(h<=n){const g=a.previousSibling;(g==null?void 0:g.nodeType)===Node.TEXT_NODE&&lo(e,g,Math.min(h,(g.textContent??"").length));return}if(h<=r||!u.length){lo(e,t,t.length);return}lo(e,t,Math.min(h-r,t.length))}}function Mu(e){if(!e||!/^#[0-9a-f]{6}$/i.test(e))return;const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,r=parseInt(e.slice(5,7),16)/255,a=Math.max(t,n,r),i=Math.min(t,n,r),l=a-i;if(l<.02)return;let u;return a===t?u=((n-r)/l+(n<r?6:0))*60%360:a===n?u=((r-t)/l+2)*60:u=((t-n)/l+4)*60,`hsl(${Math.round(u)} 55% 55%)`}function iQ(){const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");t.setAttribute("width","9"),t.setAttribute("height","9"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2.4");const n=document.createElementNS(e,"path");return n.setAttribute("d","m6 6 12 12M18 6 6 18"),t.appendChild(n),t}const zd="data-sc-coach-inert",lQ=new Set(["SCRIPT","STYLE","LINK","META","TEMPLATE","NOSCRIPT"]);function cQ(e=document.body){let t=new Set;const n=a=>{a.hasAttribute("inert")&&!a.hasAttribute(zd)||(a.setAttribute(zd,""),a.setAttribute("inert",""))},r=a=>{a.hasAttribute(zd)&&(a.removeAttribute(zd),a.removeAttribute("inert"))};return{set(a){const i=new Set(a.filter(h=>h.isConnected&&e.contains(h)&&h!==e)),l=new Set;for(const h of i)for(let p=h.parentElement;p&&p!==e;p=p.parentElement)l.add(p);const u=new Set,f=h=>{for(const p of Array.from(h.children))i.has(p)||lQ.has(p.tagName)||(l.has(p)?f(p):u.add(p))};f(e);for(const h of t)u.has(h)||r(h);for(const h of u)t.has(h)||n(h);t=new Set([...u].filter(h=>h.hasAttribute(zd)))},release(){for(const a of t)r(a);t=new Set}}}const hh=e=>({left:e.left,top:e.top,right:e.right,bottom:e.bottom}),Yo=e=>e.right-e.left,ao=e=>e.bottom-e.top;function jN(e,t){return{left:Math.min(e.left,t.left),top:Math.min(e.top,t.top),right:Math.max(e.right,t.right),bottom:Math.max(e.bottom,t.bottom)}}function Bd(e,t){return{left:e.left-t,top:e.top-t,right:e.right+t,bottom:e.bottom+t}}function Xx(e,t=0,n=4,r=14,a=0,i=0,l=0){if(e>=4)return e+n;const u=i===0||a===0||a<=i+16;return t>=4&&u&&l<=1?t+n:r}function AN(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}function Qx(e,t){let n=e;for(const r of t)n={left:Math.max(n.left,r.left),top:Math.max(n.top,r.top),right:Math.min(n.right,r.right),bottom:Math.min(n.bottom,r.bottom)};return Yo(n)>0&&ao(n)>0?n:null}function Jx(e,t){let{top:n,bottom:r}=e;const a=(e.top+e.bottom)/2;for(const i of t)AN(i,e)&&(i.bottom<=a?n=Math.max(n,i.bottom):r=Math.min(r,i.top));return r>n?{...e,top:n,bottom:r}:null}const uQ=e=>e==="top"||e==="bottom";function dQ(e,t,n){return t?uQ(n)?{left:e.left,right:e.right,top:t.top,bottom:t.bottom}:{left:t.left,right:t.right,top:e.top,bottom:e.bottom}:e}const ek=e=>e==="top"?"bottom":e==="bottom"?"top":e==="left"?"right":"left",xs=e=>Math.round(e*2)/2;function fQ(e,t,n){const r=xs(t),a=xs(n),i=e.map(u=>{const f=Math.max(0,xs(Yo(u))),h=Math.max(0,xs(ao(u))),p=xs(Math.max(0,Math.min(u.radius,f/2,h/2)));return`<rect x='${xs(u.left)}' y='${xs(u.top)}' width='${f}' height='${h}' rx='${p}' fill='black'/>`}).join(""),l=`<svg xmlns='http://www.w3.org/2000/svg' width='${r}' height='${a}'><defs><mask id='m' maskUnits='userSpaceOnUse' x='0' y='0' width='${r}' height='${a}'><rect width='${r}' height='${a}' fill='white'/>${i}</mask></defs><rect width='${r}' height='${a}' fill='black' mask='url(#m)'/></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(l)}")`}function hQ(e,t,n,r){const a=xs(t),i=xs(n),l=e.map(p=>{const g=Math.max(0,xs(Yo(p))),v=Math.max(0,xs(ao(p))),w=xs(Math.max(0,Math.min(p.radius,g/2,v/2)));return{x:xs(p.left),y:xs(p.top),ww:g,hh:v,k:w}}),u=l.map(p=>`<rect x='${p.x}' y='${p.y}' width='${p.ww}' height='${p.hh}' rx='${p.k}' fill='black'/>`),f=l.map(p=>`<rect x='${p.x}' y='${p.y}' width='${p.ww}' height='${p.hh}' rx='${p.k}' fill='none' stroke='${r}' stroke-width='2'/>`),h=`<svg xmlns='http://www.w3.org/2000/svg' width='${a}' height='${i}'><defs><mask id='o' maskUnits='userSpaceOnUse' x='0' y='0' width='${a}' height='${i}'><rect width='${a}' height='${i}' fill='white'/>${u.join("")}</mask></defs><g mask='url(#o)'>${f.join("")}</g></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(h)}")`}function pQ(e,t,n){const r={left:Math.max(0,e.left),top:Math.max(0,e.top),right:Math.min(t,e.right),bottom:Math.min(n,e.bottom)};return[{left:0,top:0,right:t,bottom:r.top},{left:0,top:r.bottom,right:t,bottom:n},{left:0,top:r.top,right:r.left,bottom:r.bottom},{left:r.right,top:r.top,right:t,bottom:r.bottom}].filter(a=>Yo(a)>0&&ao(a)>0)}const tk=0,mQ=10,Zg=14,Ud=4,Vg="data-guide-stage",gQ="rgba(255,255,255,0.05)",M6="[data-guide-shape]",nk=[],vQ="[data-radix-popper-content-wrapper], .sc-setpop, .sc-morepop, .sc-shotsheet, .sc-note-pop",rk='input, textarea, [contenteditable]:not([contenteditable="false"])',wQ=17,U1=12,yQ=20,bQ=450,xQ=768,sk=90,kQ=8,ak=12,SQ=2e3,EQ=".sc-topbar, .sc-tabbar, .sc-filterbar, .sc-canvas-dock, .sc-help-float, .sc-pstudio-head, .sc-newdlg-head",CQ=120,jQ="[aria-live], .sc-toasts, .sc-upd-float, .sc-upd-overlay, [data-radix-popper-content-wrapper], .sc-chip-preview, .sc-swap, .sc-shotsheet, .sc-shotsheet-scrim, .sc-cmd",zg=e=>({id:e.id,title:e.title,body:e.body,canBack:e.canBack,action:e.action,count:e.at&&e.of?`${e.at} of ${e.of}`:void 0});function AQ(e){const{id:t,voice:n,target:r,live:a,side:i,container:l,onShown:u}=e,f=e.lit??nk,h=e.also??nk,p=n==="ask",g=!r,v=!!(e.title||e.body),w=s.useId(),y=s.useId(),x=s.useRef(null),k=s.useRef(null),S=s.useRef(null),E=s.useRef(null),j=s.useRef(null),N=s.useRef(null),P=s.useRef(null),$=s.useRef(null),M=s.useRef(null),C=s.useRef(null),[R,T]=s.useState("moving"),[H]=s.useState(TQ),[D,K]=s.useState(()=>zg(e)),O=s.useRef(e);O.current=e;const Z=s.useRef(!1),te=s.useRef(null),B=s.useRef([]),F=R==="shown"&&D.id===t?zg(e):D,X=Bg(a),z=Bg(h),I=Bg(f);s.useEffect(()=>{if(p)return C.current=cQ(l),()=>{var G;(G=C.current)==null||G.release(),C.current=null;for(const ne of B.current)ne.removeAttribute(Vg);B.current=[]}},[p,l]),s.useLayoutEffect(()=>{var cn,Fe,pt;const G=x.current,ne=k.current,q=S.current,le=E.current,Se=j.current,Q=N.current;if(p&&(!q||!le||!Se||!Q)||v&&(!G||!ne))return;let xe=!0,ee=0,ae=0,re=!1,_=!1,ue="",We=0,Xe=0,ze=0,tt=null,ce=null,ve=null;const Pe=window.matchMedia("(prefers-reduced-motion: reduce)").matches,de=a[0]??r??l;let je="",Ue=r?W1(r):null;T("moving");const ye=()=>{var it;return(it=C.current)==null?void 0:it.set([...G?[G]:[],...q?[q]:[],...le?[le]:[],...Se?[Se]:[],...Q?[Q]:[],...a,...h,...[...document.querySelectorAll(jQ)].filter(St=>![...a,...h].some(xt=>St.contains(xt)))])},Ee=()=>{var it,St;(it=C.current)==null||it.release(),_=!1,T("away"),(St=r??a[0])!=null&&St.isConnected&&Qe()};if(p&&C.current&&Z.current){ye(),_=!0;const it=a.find(xt=>xt.matches(rk)),St=document.activeElement;it&&!a.some(xt=>xt.contains(St))&&ok(it)}const be=async()=>{const it=++ee;if(r&&!r.isConnected||a.some(se=>!se.isConnected))return Ee(),O.current.onLost();const St=window.innerWidth,xt=window.innerHeight,At=window.visualViewport,Kt=[{left:0,top:0,right:St,bottom:xt},...At?[{left:At.offsetLeft,top:At.offsetTop,right:At.offsetLeft+At.width,bottom:At.offsetTop+At.height}]:[]],et=se=>{const oe=se===r?Ue:W1(se);return oe?[...Kt,hh(oe.getBoundingClientRect())]:Kt},mt=NQ(de,l),ot=mt.filter(se=>Yo(se)>St/3),kn=r?Qx(hh(r.getBoundingClientRect()),et(r)):null,ut=kn&&Jx(kn,ot);if(r&&!ut)return!re&&ze<ak&&(ze++,Ue=W1(r),Ug(r,Ue,Pe).then(()=>xe&&Ke())),Ee();const Gt=[],Ft=[];for(const se of[...r?[r]:[],...a,...h,...f,...ik()]){const oe=lk(se);Ft.includes(oe)||Ft.push(oe)}const en=new Set([...r?[r]:[],...a,...f,...ik()].map(lk));let Jt=null;for(const se of Ft){const oe=Qx(hh(se.getBoundingClientRect()),et(se)),we=oe&&Jx(oe,ot);if(!we)continue;const ge=ph(se);Gt.push(ge>=4||se.matches("img, video, canvas")?{...Bd(we,tk),radius:ge+tk}:{...Bd(we,mQ),radius:Zg}),en.has(se)&&(Jt=Jt?jN(Jt,we):we)}if(!g&&!ut&&!Jt)return Ee();if(_&&(a.some(se=>se.closest("[inert]"))||G!=null&&G.closest("[inert]"))&&(_=!1),p&&q&&le&&Se&&Q){if(!Gt.length&&ut){const we=r,ge=ck(we);Gt.push({...Bd(ut,Ud),radius:Xx(ph(we),ge.radius,Ud,Zg,ao(ut),ge.height,ge.count)})}for(const we of B.current)Ft.includes(we)||we.removeAttribute(Vg);for(const we of Ft)we.setAttribute(Vg,"");B.current=Ft;const oe=`${Gt.map(we=>[we.left,we.top,we.right,we.bottom,we.radius].map(Math.round).join(",")).join("|")}@${St}x${xt}`;if(oe!==je&&(je=oe,LQ(q,le,Q,Gt,H)),r&&ut){const we=OQ(r),ge=ck(r),J=we??Bd(ut,Ud);Object.assign(Se.style,{left:`${J.left}px`,top:`${J.top}px`,width:`${Yo(J)}px`,height:`${ao(J)}px`,borderRadius:`${we?HQ:Xx(ph(r),ge.radius,Ud,Zg,ao(ut),ge.height,ge.count)}px`}),Se.hidden=!1}else Se.hidden=!0}if(G&&document.documentElement.style.setProperty("--sc-coach-h",`${Math.round(G.offsetHeight)}px`),G&&g&&(G.style.right="",G.style.left=`${Math.round((St-G.offsetWidth)/2)}px`,G.style.top=`${Math.round((xt-G.offsetHeight)/2)}px`,G.dataset.side="centre",ne&&(ne.hidden=!0)),G&&ne&&r&&ut){G.style.right="";const se={top:U1+MQ(mt,xt),bottom:U1+RQ(mt,xt),left:U1,right:U1},oe=St>=xQ;ce!==oe&&(ce!==null&&r&&(Ue=W1(r),Ug(r,Ue,Pe)),tt=null,ce=oe);const we=i==="left"||i==="right"?"top":i,ge=!oe&&Yo(ut)>St*.6,J=oe?i:ge?`${we}-start`:we,Oe=(Ct,st)=>Y9(PQ(Ct,r),G,{strategy:"fixed",placement:tt??J,middleware:[W9(wQ),G9({padding:se,fallbackPlacements:st}),K9({padding:se}),V8({element:ne,padding:yQ})]}),Be=!oe&&Jt?{...ut,top:Jt.top,bottom:Jt.bottom}:ut,Ve=(Ct,st)=>AN({left:Ct,top:st,right:Ct+G.offsetWidth,bottom:st+G.offsetHeight},Bd(Be,Ud)),_e=oe&&(i==="left"||i==="right")?[ek(i),"top","bottom"]:oe?void 0:ge?["bottom-start","top-start"]:["bottom","top"],W=!p&&ao(ut)>xt*.6,pe=oe&&(e.beside||a.length>1),Ie=W?{...ut,top:ut.bottom-1}:pe?dQ(ut,Jt,i):Be;let Te=await Oe(Ie,W?["top"]:_e);if(!xe||it!==ee||!W&&Ve(Te.x,Te.y)&&(Te=await Oe(Be,void 0),!xe||it!==ee))return;if(!W&&Ve(Te.x,Te.y))return T("stowed");tt=Te.placement;const bt=Te.placement.split("-")[0];G.style.left=`${Math.round(Te.x)}px`,G.style.top=`${Math.round(Te.y)}px`,G.dataset.side=bt;const vt=Te.middlewareData.arrow;ne.dataset.edge=ek(bt),ne.style.left=(vt==null?void 0:vt.x)!=null?`${vt.x}px`:"",ne.style.top=(vt==null?void 0:vt.y)!=null?`${vt.y}px`:"",ne.hidden=!vt||Math.abs(vt.centerOffset)>1}if(p&&!_&&(ye(),_=!0),!re){if(IQ([...r?[r]:[],...a])&&++Xe<ak){window.setTimeout(Ke,sk);return}const se=[...r?[r]:[],...a,...h,...f].map(oe=>{const we=oe.getBoundingClientRect();return[we.left,we.top,we.right,we.bottom].map(Math.round).join(",")}).join("|");if(se!==ue&&(ue=se,We=0),++We<2&&We<kQ){window.setTimeout(Ke,sk);return}}T("shown"),re||(re=!0,nt(),Qe())};let Le=0;const Qe=()=>{const it=r??a[0];if(!it)return;cancelAnimationFrame(Le);let St=it.getBoundingClientRect();const xt=performance.now()+SQ,At=()=>{if(!xe)return;const Kt=it.getBoundingClientRect();(Kt.top!==St.top||Kt.left!==St.left||Kt.height!==St.height)&&(St=Kt,Ke()),performance.now()<xt&&(Le=requestAnimationFrame(At))};Le=requestAnimationFrame(At)},Ke=()=>{cancelAnimationFrame(ae),ae=requestAnimationFrame(()=>void be())},nt=()=>{Z.current=!0;let it=!1;if(p&&G){const St=Kt=>!!Kt&&a.some(et=>et.contains(Kt)),xt=document.activeElement,At=a.find(Kt=>Kt.matches(rk))??null;M.current&&St(xt)?M.current=null:M.current?(((M.current==="back"?P.current:null)??$.current??G).focus({preventScroll:!0}),M.current=null):At&&!St(xt)?ok(At):(!xt||xt===document.body||xt.closest("[inert]"))&&(G.focus({preventScroll:!0}),it=!0)}u(t,it)},gt=Z.current&&!Pe&&v&&te.current!==t?CQ:0;te.current=t,$Q(gt).then(()=>{if(xe)return Rr.flushSync(()=>K(zg(O.current))),r?Ug(r,Ue,Pe):void 0}).then(()=>{xe&&(ve=U9(de,G??q??de,Ke))});const Pt=new ResizeObserver(Ke);for(const it of a)Pt.observe(it);r&&Pt.observe(r),G&&Pt.observe(G);for(const it of[...r?[r]:[],...a]){const St=(cn=it==null?void 0:it.closest)==null?void 0:cn.call(it,M6);St&&Pt.observe(St)}(Fe=window.visualViewport)==null||Fe.addEventListener("resize",Ke),(pt=window.visualViewport)==null||pt.addEventListener("scroll",Ke);let Ut=0;const Nt=p?new MutationObserver(()=>{_&&(cancelAnimationFrame(Ut),Ut=requestAnimationFrame(ye))}):null;return Nt==null||Nt.observe(l,{childList:!0,subtree:!0}),()=>{var it,St;xe=!1,document.documentElement.style.removeProperty("--sc-coach-h"),cancelAnimationFrame(ae),cancelAnimationFrame(Le),cancelAnimationFrame(Ut),Nt==null||Nt.disconnect(),ve==null||ve(),Pt.disconnect(),(it=window.visualViewport)==null||it.removeEventListener("resize",Ke),(St=window.visualViewport)==null||St.removeEventListener("scroll",Ke)}},[t,p,v,r,X,z,I,i,l,u,H]),s.useEffect(()=>{if(!v||!r||!DQ(r))return;const G=(r.getAttribute("aria-describedby")??"").split(/\s+/).filter(Boolean);if(!G.includes(y))return r.setAttribute("aria-describedby",[...G,y].join(" ")),()=>{const ne=(r.getAttribute("aria-describedby")??"").split(/\s+/).filter(q=>q&&q!==y);ne.length?r.setAttribute("aria-describedby",ne.join(" ")):r.removeAttribute("aria-describedby")}},[v,r,y]);const{onEscape:U}=e;return s.useEffect(()=>{if(!p)return;const G=xe=>!!xe&&a.some(ee=>ee.contains(xe)),ne=xe=>{var ue;const ee=x.current,ae=xe.target instanceof Node?xe.target:null,re=G(ae),_=document.activeElement;if(xe.key==="Escape"){if(xe.defaultPrevented||_!=null&&_.closest('[role="dialog"]:not(.sc-coach):not(.sc-attachpanel)')||re&&(_!=null&&_.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="listbox"]')))return;xe.preventDefault(),xe.stopPropagation(),U(t);return}re||(!ae||ae===document.body||ae===document.documentElement||ee!=null&&ee.contains(ae)||(ue=E.current)!=null&&ue.contains(ae))&&xe.stopPropagation()};let q=0,le=!1;const Se=xe=>{le=xe.target instanceof Node&&G(xe.target)},Q=xe=>{xe.relatedTarget||le||!x.current||(cancelAnimationFrame(q),q=requestAnimationFrame(()=>{var ae;if(!document.hasFocus())return;const ee=document.activeElement;(!ee||ee===document.body||ee.closest("[inert]"))&&((ae=x.current)==null||ae.focus({preventScroll:!0}))}))};return window.addEventListener("keydown",ne,!0),window.addEventListener("pointerdown",Se,!0),document.addEventListener("focusout",Q,!0),()=>{cancelAnimationFrame(q),window.removeEventListener("keydown",ne,!0),window.removeEventListener("pointerdown",Se,!0),document.removeEventListener("focusout",Q,!0)}},[t,p,X,U]),Rr.createPortal(o.jsxs(o.Fragment,{children:[p&&o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:S,className:"sc-coach-veil","data-veil":H?"mask":"panels","data-soft":e.soft||void 0,"data-state":R,"aria-hidden":"true",children:dk.map(G=>o.jsx("div",{className:"sc-coach-panel"},G))}),o.jsx("div",{ref:E,className:"sc-coach-catch","data-guide":"catch","data-state":R,"aria-hidden":"true",onMouseDown:G=>G.preventDefault(),children:dk.map(G=>o.jsx("div",{className:"sc-coach-catch-part"},G))}),o.jsx("div",{ref:N,className:"sc-coach-rim","data-state":R,"aria-hidden":"true"}),o.jsx("div",{ref:j,className:"sc-coach-ring","data-state":R,"aria-hidden":"true",hidden:!0})]}),v&&o.jsxs("div",{ref:x,className:"sc-coach","data-guide":"card","data-voice":p?"coach":"card","data-beside":e.beside||void 0,...p?{role:"dialog","aria-labelledby":F.title?w:void 0}:{role:"note"},"aria-describedby":y,tabIndex:-1,"data-state":R,children:[o.jsx("div",{ref:k,className:"sc-coach-arrow","aria-hidden":"true",hidden:!0}),o.jsxs("div",{className:"sc-coach-head",children:[F.title?o.jsx("h2",{id:w,className:"sc-coach-title",children:F.title}):o.jsx("p",{id:y,className:"sc-coach-body","data-lead":"",children:F.body}),F.count&&o.jsxs("p",{className:"sc-coach-count",children:[o.jsx("span",{className:"sc-vh",children:"Step "}),F.count]}),o.jsx(lr,{label:e.closeLabel,children:o.jsx("button",{type:"button",className:"sc-coach-x","aria-label":e.closeLabel,onClick:()=>e.onClose(t),children:o.jsx(jn,{size:16})})})]}),F.title&&F.body&&o.jsx("p",{id:y,className:"sc-coach-body",children:F.body}),(F.canBack||F.action)&&o.jsxs("div",{className:"sc-coach-foot",children:[F.canBack&&o.jsx("button",{ref:P,type:"button",className:"sc-coach-back",onClick:()=>{M.current="back",e.onBack(t)},children:"Back"}),F.action&&o.jsx("button",{ref:$,type:"button",className:"sc-btn sc-btn-primary sc-coach-next",onClick:()=>{M.current="action",e.onAction(t)},children:F.action.label})]})]})]}),l)}function ok(e){var t,n;if(e.focus({preventScroll:!0}),!e.isContentEditable){const r=e,a=((t=r.value)==null?void 0:t.length)??0;(n=r.setSelectionRange)==null||n.call(r,a,a);return}Ol(e)}function ik(){return[...document.querySelectorAll(vQ)].filter(e=>e.getClientRects().length>0)}function Bg(e){const t=s.useRef(e);return(t.current.length!==e.length||t.current.some((n,r)=>n!==e[r]))&&(t.current=e),t.current}function NQ(e,t){const n=[];for(const r of document.querySelectorAll(EQ))t.contains(r)&&(r.contains(e)||e.contains(r)||r.getClientRects().length===0||n.push(hh(r.getBoundingClientRect())));return n}function MQ(e,t){return Math.max(0,...e.filter(n=>n.top<=0&&n.bottom<t/3).map(n=>n.bottom))}function RQ(e,t){return Math.max(0,...e.filter(n=>n.bottom>=t&&n.top>t*2/3).map(n=>t-n.top))}function PQ(e,t){const n={x:e.left,y:e.top,left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:Yo(e),height:ao(e)};return{getBoundingClientRect:()=>n,contextElement:t}}function LQ(e,t,n,r,a){const i=window.innerWidth,l=window.innerHeight,u=r.reduce((h,p)=>h?jN(h,p):p,null),f=u?pQ(u,i,l):[];if(a){const h=fQ(r,i,l),p=e.style;p.maskImage=h,p.webkitMaskImage=h,n.style.backgroundImage=hQ(r,i,l,gQ)}else uk(e,f);uk(t,f)}function ph(e){return Number.parseFloat(getComputedStyle(e).borderTopLeftRadius)||0}function lk(e){return e.closest(M6)??e.querySelector(M6)??e}function ck(e){let t=0,n=0,r=0;for(const a of e.querySelectorAll("button, a[href], .sc-chip, .sc-btn"))a.getClientRects().length&&(r+=1,t=Math.max(t,ph(a)),n=Math.max(n,a.getBoundingClientRect().height));return{radius:t,height:n,count:r}}function uk(e,t){Array.from(e.children).forEach((n,r)=>{const a=t[r],i=n.style;if(!a){i.display="none";return}Object.assign(i,{display:"block",left:`${a.left}px`,top:`${a.top}px`,width:`${Yo(a)}px`,height:`${ao(a)}px`})})}const dk=[0,1,2,3];function TQ(){return typeof CSS>"u"?!1:CSS.supports("mask-image",'url("x.svg")')||CSS.supports("-webkit-mask-image",'url("x.svg")')}function W1(e){for(let t=e.parentElement;t&&t!==document.body;t=t.parentElement){const n=getComputedStyle(t).overflowY;if((n==="auto"||n==="scroll")&&t.scrollHeight>t.clientHeight)return t}return null}function Ug(e,t,n){if(!t)return Promise.resolve();const r=e.getBoundingClientRect(),a=t.getBoundingClientRect();if(Math.max(0,Math.min(r.bottom,a.bottom,window.innerHeight)-Math.max(r.top,a.top,0))>=Math.min(120,r.height*.4))return Promise.resolve();const u=r.height>a.height*.8?r.top-a.top-16:(r.top+r.bottom)/2-(a.top+a.bottom)/2;return t.scrollBy({top:u,behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(f=>{let h=!1;const p=()=>{h||(h=!0,t.removeEventListener("scrollend",p),f())};t.addEventListener("scrollend",p),window.setTimeout(p,bQ)})}function $Q(e){return e>0?new Promise(t=>window.setTimeout(t,e)):Promise.resolve()}function DQ(e){return e.matches('button, a[href], input, select, textarea, [tabindex], [contenteditable="true"]')}const HQ=10;function OQ(e){if(!e.matches("a[href], button")||e.getBoundingClientRect().height<=48)return null;const t=document.createRange();t.selectNodeContents(e);const n=t.getBoundingClientRect();return n.width?{left:n.left-12,top:n.top-7,right:n.right+12,bottom:n.bottom+7}:null}function IQ(e){return document.getAnimations().some(t=>{var r,a;const n=(r=t.effect)==null?void 0:r.target;return!(n instanceof Element)||t.playState!=="running"||((a=t.effect)==null?void 0:a.getTiming().iterations)===Number.POSITIVE_INFINITY?!1:e.some(i=>n.contains(i))})}const er=e=>e.kind==="question"?`q:${e.question.id}`:`${e.kind}:${e.id}`,jf=320,Hv=180,FQ=28,_Q=700;function sm(e){const t=e.split(/(\s+)/).filter(a=>a.length>0),n=t.filter(a=>!/^\s+$/.test(a)).length,r=Math.min(FQ,Math.floor(_Q/Math.max(1,n)));return{words:t,step:r,total:jf+Hv+r*n+160}}function Wg(e,t){return e.every(n=>!!t[n.id])}function ZQ(e,t,n={}){const r=e.trim().toLowerCase();if(!r||r.split(/\s+/).length>6)return null;for(const i of t){const l=i.label.toLowerCase();if(r===l||r===i.id.toLowerCase())return i.id}for(const i of t){const l=n[i.id];if(l!=null&&l.test(r))return i.id}return null}function VQ(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const zQ=/^(hi|hello|hey|heya|hiya|yo|hola|shalom|sup|good (morning|afternoon|evening)|thanks|thank you|thx|cheers)\b/i,BQ=/^(ok|okay|k|kk|sure|fine|yes|yeah|yep|yup|no|nope|nah|cool|nice|great|alright|right|hmm+|hm+|uh+|um+|oh|ah|wow|haha+|hehe+|lol|lmao|omg|meh|really|seriously|interesting|whatever)[\s!.,?]*$/i,UQ=/^(how|what|what's|whats|who|who's|whos|why|where|when|which|can|could|do|does|did|are|is|will|would|should|may|have|has|am|isn't|aren't|don't|doesn't)\b/i,WQ=/^(start over|start again|restart|reset|cancel|stop|quit|exit|go back|back|undo|never ?mind|forget it|close)\b/i,KQ=/^(skip|next|continue|go|go on|proceed|generate|draw|render|build|show me|show|try|do it|let'?s go|begin|start)\b/i,fk=/^(help|help me|how does this work|what do i do|what should i (write|say|type)|instructions|\?+)[\s!.,?]*$/i,GQ=/\b(presenters?|avatars?|characters?|Scenri|create|creating|generate|generating|images?|pictures?|shoot|campaign|brand|product)\b/i,YQ=/^(test|testing|blah|lorem|ipsum|foo|bar|baz|dummy|sample|placeholder|xxx+|abc|asdf\w*|qwer\w*|zxcv\w*|hjkl|jkl|sdfg?|dfgh?|fghj?|bull\w*|shit\w*|crap|fuck\w*|damn|wtf|stfu|bs|rofl|lol+|lmao+|haha\w*|hehe\w*|meh|idk|nvm)$/i,qQ=/^[b-df-hj-np-tv-xz]{3,}$/i,XQ=/(.)\1{3,}/,QQ=/\b(like|as|resembling|resembles|similar to|looks? like|looking like)\s+([A-Z][a-z]+)(?:\s+[A-Z][a-z]+)*\b/,JQ=/^(mediterranean|asian|east|south|southeast|indian|chinese|japanese|korean|african|black|white|nordic|scandinavian|latin|latina|latino|hispanic|arab|arabic|middle|eastern|european|caucasian|israeli|jewish|irish|italian|french|spanish|greek|turkish|persian|brazilian|mexican|american|british|german|dutch|russian|polish|thai|vietnamese|filipino|filipina|nigerian|ethiopian|moroccan|egyptian|australian|canadian|swedish|norwegian|danish|finnish|portuguese|indonesian|pakistani|iranian|lebanese|slavic|celtic|west|north|central)$/i;function Vo(e,t){const n=e.trim();if(!n)return null;const r=QQ.exec(n);if(r&&!JQ.test(r[2]))return"likeness";if(t(n))return null;if(!new RegExp("\\p{L}","u").test(n))return fk.test(n)?"help":"nonsense";const a=n.split(/\s+/).filter(Boolean),i=a.length;if(fk.test(n))return"help";if(zQ.test(n)&&i<=4)return"greeting";if(BQ.test(n))return"ack";const l=u=>u.replace(/[^a-z]/gi,"");return i<=8&&a.some(u=>YQ.test(l(u))||qQ.test(l(u))||XQ.test(l(u)||u))?"nonsense":UQ.test(n)||/\?\s*$/.test(n)?"question":WQ.test(n)&&i<=4?"nav":GQ.test(n)&&i<=10?"intent":KQ.test(n)&&i<=4?"go":i===1&&/^[A-Z][a-z]+$/.test(n)?null:i<=2?"vague":null}const eJ=e=>`aside-said-${e}`,hk=e=>e.startsWith("aside-said-")?e.slice(11):null,ri=(e,t=!1,n=!1)=>[...n?[]:[{kind:"you",id:eJ(e.at),text:e.said,editable:!0,editing:t||void 0}],{kind:"scenri",id:`aside-reply-${e.at}${e.rev?`-${e.rev}`:""}`,text:e.reply}],Uh=e=>(e.kind==="you"||e.kind==="scenri")&&e.id.startsWith("aside-");function NN(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.kind==="question")return n.question.id;if(!Uh(n))return null}return null}const Wh=()=>new Date().toISOString();function tJ({options:e,picked:t,onPick:n}){return o.jsx("div",{className:"sc-convo-grid",children:e.map(r=>o.jsxs("button",{type:"button",className:"sc-convo-plate","aria-label":r.label,"aria-pressed":t===r.id,"data-on":t===r.id||void 0,onClick:()=>n(r.id),children:[o.jsx("span",{className:"sc-convo-plate-in","data-card":r.card}),o.jsx("span",{className:"sc-convo-plate-lb",children:r.label})]},r.id))})}function nJ({step:e,children:t}){const n=s.useRef(null),[r,a]=s.useState({back:!1,on:!0}),i=s.useCallback(()=>{const h=n.current;if(!h)return;const p=h.scrollWidth-h.clientWidth;a({back:h.scrollLeft>2,on:h.scrollLeft<p-2})},[]);s.useEffect(()=>{const h=n.current;if(!h)return;i(),h.addEventListener("scroll",i,{passive:!0});const p=new ResizeObserver(i);return p.observe(h),()=>{h.removeEventListener("scroll",i),p.disconnect()}},[i]);const l=h=>{const p=n.current;if(!p)return;const g=p.firstElementChild,v=Number.parseFloat(getComputedStyle(p).columnGap)||0,w=g?g.offsetWidth+v:e,y=!window.matchMedia("(prefers-reduced-motion: reduce)").matches;p.scrollBy({left:h*w,behavior:y?"smooth":"auto"})},u=r.back&&r.on?"both":r.back?"back":r.on?"on":void 0,f=r.back||r.on;return o.jsxs("div",{className:"sc-convo-strip","data-fade":u,children:[f&&o.jsx(pk,{dir:-1,live:r.back,onGo:l}),o.jsx("div",{className:"sc-convo-plates",ref:n,children:t}),f&&o.jsx(pk,{dir:1,live:r.on,onGo:l})]})}function pk({dir:e,live:t,onGo:n}){const r=e<0;return o.jsx("button",{type:"button",className:"sc-convo-strip-go","data-dir":r?"back":"on","data-spent":!t||void 0,"aria-label":r?"Show earlier":"Show more","aria-disabled":!t||void 0,tabIndex:-1,onClick:a=>{a.currentTarget.blur(),t&&n(e)},children:r?o.jsx(ga,{size:14,weight:"bold"}):o.jsx(ol,{size:14,weight:"bold"})})}const rJ=106;function mk({options:e,picked:t,onPick:n}){return o.jsx(nJ,{step:rJ,children:e.map(r=>o.jsxs("button",{type:"button",className:"sc-convo-plate","aria-label":r.label,"aria-pressed":t===r.id,"data-on":t===r.id||void 0,onClick:()=>n(r.id),children:[o.jsx("span",{className:"sc-convo-plate-in","data-card":r.card}),o.jsx("span",{className:"sc-convo-plate-lb",children:r.label})]},r.id))})}const MN=6e4,sJ=60*MN,Kg=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),aJ=e=>e.toLocaleDateString([],{day:"numeric",month:"short"});function oJ(e,t){const n=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),r=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();return Math.round((r-n)/864e5)}function iJ(e,t=Date.now()){const n=Math.max(0,t-e);if(n<45e3)return"just now";if(n<sJ)return`${Math.max(1,Math.round(n/MN))} min ago`;const r=new Date(e),a=oJ(r,new Date(t));return a===0?Kg(r):a===1?`Yesterday ${Kg(r)}`:`${aJ(r)} ${Kg(r)}`}const lJ=e=>new Date(e).toLocaleString([],{dateStyle:"medium",timeStyle:"short"});function cJ({text:e,tone:t,at:n,now:r,reveal:a,eyebrow:i=!0,delay:l=0,leave:u,turnId:f,dim:h,thumb:p,label:g,view:v,current:w,restore:y,onRestore:x,retry:k,onRetry:S,onShow:E}){const[j]=s.useState(l),N=Iv(u,j),{playing:P,thinking:$}=$N(a,e,j,N==="true");return o.jsxs("div",{className:"sc-convo-turn","data-guide-shape":"","data-who":"scenri","data-arrive":P||void 0,"data-leave":N,"data-turn":f,"data-dim":h||void 0,style:P?{...RN(j),"--sc-convo-after":`${sm(e).total}ms`}:void 0,children:[i&&o.jsx(Ov,{thinking:$,at:n,now:r}),o.jsxs("p",{className:"sc-convo-say","data-tone":t,"data-reveal":P||void 0,children:[$&&o.jsx(LN,{}),o.jsx(TN,{text:e,playing:P})]}),p&&o.jsxs("span",{className:"sc-convo-shot","data-reveal":P||void 0,"data-current":w||void 0,children:[v&&E?o.jsx("button",{type:"button",className:"sc-convo-shot-pick","aria-label":g?`Show ${g} on the stage`:"Show this on the stage",onClick:()=>E(v),children:o.jsx(gk,{thumb:p,label:g,current:w})}):o.jsx(gk,{thumb:p,label:g,current:w}),y&&x?o.jsx("button",{type:"button",className:"sc-convo-shot-do sc-convo-restore",onClick:()=>x(y.view,y.hash),children:"Put back"}):k&&S?o.jsx("button",{type:"button",className:"sc-convo-shot-do sc-convo-restore",onClick:()=>S(k),children:"Try again"}):w&&o.jsx("span",{className:"sc-convo-shot-do",children:"Active"})]})]})}const RN=e=>({"--sc-convo-start":`${e}ms`,"--sc-convo-think":`${jf}ms`});function Ov({thinking:e,at:t,now:n}){return o.jsxs("span",{className:"sc-convo-who","data-thinking":e||void 0,children:[o.jsx(cY,{className:"sc-convo-mark"}),"Scenri",t?o.jsx(PN,{at:t,now:n}):null]})}function PN({at:e,now:t}){return o.jsx("time",{className:"sc-convo-time",dateTime:new Date(e).toISOString(),title:lJ(e),children:iJ(e,t)})}function uJ({what:e="Thinking"}){return o.jsxs("div",{className:"sc-convo-turn","data-who":"scenri","data-working":"true",children:[o.jsx(Ov,{thinking:!0}),o.jsx("p",{className:"sc-convo-say",role:"status",children:o.jsxs("span",{className:"sc-convo-work",children:[e,o.jsx(dJ,{})]})})]})}function dJ(){return o.jsxs("span",{className:"sc-convo-ell","aria-hidden":"true",children:[o.jsx("i",{children:"."}),o.jsx("i",{children:"."}),o.jsx("i",{children:"."})]})}function LN(){return o.jsxs("span",{className:"sc-convo-dots","aria-hidden":"true",children:[o.jsx("i",{}),o.jsx("i",{}),o.jsx("i",{})]})}function TN({text:e,playing:t}){if(!t)return o.jsx(o.Fragment,{children:e});const{words:n,step:r}=sm(e);let a=0,i=0;return o.jsx(o.Fragment,{children:n.map(l=>{const u=i;if(i+=l.length,/^\s+$/.test(l))return l;const f=a++;return o.jsx("span",{className:"sc-convo-w",style:{"--sc-convo-word-delay":`${f*r}ms`},children:l},`${u}:${l}`)})})}function $N(e,t,n=0,r=!1){const[a,i]=s.useState(!!e),[l,u]=s.useState(!!e),f=s.useRef(!!e);return s.useEffect(()=>{e&&!f.current&&(i(!0),u(!0)),f.current=!!e},[e]),s.useEffect(()=>{if(!a)return;const h=setTimeout(()=>{u(!1),i(!1)},n+sm(t).total),p=setTimeout(()=>u(!1),n+jf);return()=>{clearTimeout(h),clearTimeout(p)}},[a,t,n]),{playing:a&&!r,thinking:a&&l&&!r}}function Iv(e,t,n=jf+Hv){const r=s.useRef(performance.now());if(e)return performance.now()-r.current<t+n?"early":"true"}function gk({thumb:e,label:t,current:n}){return o.jsx("img",{src:dn(e,"micro"),srcSet:`${dn(e,"micro")} 160w, ${dn(e,"small")} 320w, ${dn(e,"tile")} 640w`,sizes:"(max-width: 767px) 248px, 128px",alt:n&&t?`${t}, active`:t??""})}const fJ=300,hJ=e=>typeof e=="string"?e:null,pJ=e=>Array.isArray(e)?e:[],mJ=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};function gJ({question:e,reveal:t,busy:n,eyebrow:r=!0,delay:a=0,leave:i,spent:l,turnId:u,dim:f,at:h,now:p,onAnswer:g,onPick:v,onStarter:w,onDescribe:y,onAttachFiles:x,onCancel:k}){var Q,xe,ee,ae,re;const[S]=s.useState(a),E=Iv(i,S),{playing:j,thinking:N}=$N(t,e.prompt,S,E==="true"),P="given"in e?e.given:void 0,[$,M]=s.useState(()=>mJ(P)),[C,R]=s.useState(null),[T,H]=s.useState(()=>new Set(pJ(P))),D=!!l||!!n,K=s.useRef(!1);s.useEffect(()=>{K.current&&!D&&R(null),K.current=D},[D]);const O=(_,ue)=>{C||(R(_),v==null||v(e.id,{picked:_,picks:$}),g(ue))},Z=C??hJ(P),te=s.useRef(null),B=s.useRef(null),F=s.useRef(()=>{});F.current=()=>{e.kind==="pick"&&e.more&&!e.loading&&g({kind:"pick",action:{type:"more"}})};const X=e.kind==="pick"?e.items.length:0,z=e.kind==="pick"&&!!e.more;s.useEffect(()=>{const _=B.current,ue=te.current;if(!_||!ue||!z||typeof IntersectionObserver>"u")return;const We=new IntersectionObserver(Xe=>Xe.some(ze=>ze.isIntersecting)&&F.current(),{root:ue,rootMargin:"0px 0px 240px 0px"});return We.observe(_),()=>We.disconnect()},[X,z]);const I=X>0;s.useLayoutEffect(()=>{const _=te.current;if(!_||!I||typeof ResizeObserver>"u")return;const ue=()=>{const Xe=_.querySelector(".sc-convo-plate");Xe&&_.style.setProperty("--sc-pick-row",`${Xe.getBoundingClientRect().height}px`)};ue();const We=new ResizeObserver(ue);return We.observe(_),()=>We.disconnect()},[I]);const U=e.kind==="pick"?(Q=e.search)==null?void 0:Q.value:void 0;s.useEffect(()=>{te.current&&(te.current.scrollTop=0)},[U]);const G=sm(e.prompt),ne=`sc-convo-q-${e.id}`,q=s.useRef(null),le=e.reopened&&k&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost sc-convo-cancel",onClick:k,children:"Cancel"}),Se="attach"in e&&e.attach&&x&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass",onClick:()=>{var _;return(_=q.current)==null?void 0:_.click()},children:[o.jsx(GU,{size:14,weight:"bold"}),e.attach]}),o.jsx("input",{ref:q,type:"file",accept:"image/*",hidden:!0,"aria-label":e.attach,onChange:_=>{const ue=Array.from(_.target.files??[]).filter(We=>We.type.startsWith("image/"));_.target.value="",ue.length&&x(ue)}})]});return o.jsxs("div",{className:"sc-convo-turn","data-who":"scenri","data-arrive":j||void 0,"data-leave":E,"data-turn":u,"data-dim":f||void 0,"data-reopened":e.reopened||void 0,style:j?{...RN(S),"--sc-convo-after":`${G.total}ms`}:void 0,children:[!e.reopened&&r&&o.jsx(Ov,{thinking:N,at:h,now:p}),!e.reopened&&o.jsxs("p",{className:"sc-convo-say",id:ne,"data-tone":e.tone,"data-reveal":j||void 0,children:[N&&o.jsx(LN,{}),o.jsx(TN,{text:e.prompt,playing:j})]}),e.reopened&&o.jsx("span",{id:ne,hidden:!0,children:e.prompt}),!e.reopened&&e.hint&&o.jsx("p",{className:"sc-convo-hint","data-reveal":j||void 0,children:e.hint}),o.jsxs("fieldset",{className:"sc-convo-q","aria-labelledby":ne,hidden:e.kind==="text"&&!((xe=e.starters)!=null&&xe.length)&&!e.cost&&!e.note?!0:void 0,tabIndex:-1,"data-kind":e.kind,"data-reveal":j||void 0,"data-picked":!!C||void 0,disabled:n||void 0,children:[e.starters&&e.starters.length>0&&o.jsx("div",{className:"sc-convo-starters",children:e.starters.map(_=>o.jsx(lr,{label:_.text,children:o.jsx("button",{type:"button",className:"sc-convo-starter",onClick:()=>w==null?void 0:w(_.text),children:_.label})},_.text))}),e.kind==="choice"&&((ee=e.options)==null?void 0:ee.some(_=>_.card))&&o.jsx(mk,{options:e.options,picked:Z,onPick:_=>O(_,{kind:"choice",id:_})}),e.kind==="choice"&&e.options&&!e.groups&&!e.options.some(_=>_.card)&&o.jsx("div",{className:"sc-convo-choices sc-convo-ask","data-guide-shape":"",children:e.options.map(_=>o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice","aria-pressed":e.multi?T.has(_.id):void 0,"data-on":(e.multi?T.has(_.id):Z===_.id)||void 0,onClick:()=>e.multi?H(ue=>{const We=new Set(ue);return We.delete(_.id)||We.add(_.id),We}):O(_.id,{kind:"choice",id:_.id}),children:_.label},_.id))}),e.kind==="choice"&&(e.describe||e.attach||e.skip)&&o.jsxs("div",{className:"sc-convo-ways sc-convo-ask","data-guide-shape":"",children:[e.skip&&!e.multi&&!e.groups&&o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass","data-on":C==="skip"||!C&&e.skipped||void 0,onClick:()=>O("skip",{kind:"skip"}),children:e.skip}),e.describe&&y&&o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass","aria-pressed":e.saying===void 0?void 0:e.saying,"data-on":e.saying||void 0,onClick:y,children:e.describe}),Se,!e.multi&&le]}),e.kind==="choice"&&!e.groups&&!e.multi&&!e.describe&&!e.attach&&le&&o.jsx("div",{className:"sc-convo-ways sc-convo-ask","data-guide-shape":"",children:le}),e.kind==="choice"&&e.multi&&o.jsxs("div",{className:"sc-convo-decide sc-convo-ask","data-guide-shape":"",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary","data-on":C==="submit"||void 0,onClick:()=>O("submit",{kind:"choices",picks:Object.fromEntries([...T].map(_=>[_,"on"]))}),children:e.submit??"Continue"}),e.skip&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost","data-on":C==="skip"||!C&&e.skipped||void 0,onClick:()=>O("skip",{kind:"skip"}),children:e.skip}),le]}),e.kind==="choice"&&e.groups&&o.jsxs("div",{className:"sc-convo-groups",children:[e.groups.map(_=>o.jsxs("div",{className:"sc-convo-group",children:[o.jsx("span",{className:"sc-convo-group-lb",id:`sc-convo-g-${e.id}-${_.id}`,children:_.label}),o.jsx(_o,{label:_.label,value:$[_.id]??"",ids:_.options.map(ue=>ue.id),onChange:ue=>M(We=>({...We,[_.id]:ue})),className:"sc-convo-choices",children:_.options.map(ue=>o.jsx(Zo,{id:ue.id,on:$[_.id]===ue.id,label:ue.label,className:"sc-chip sc-convo-choice",onPick:()=>M(We=>({...We,[_.id]:ue.id})),children:ue.label},ue.id))})]},_.id)),o.jsxs("div",{className:"sc-convo-decide sc-convo-ask","data-guide-shape":"",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary","aria-disabled":!Wg(e.groups,$)||void 0,title:Wg(e.groups,$)?void 0:"Pick one in each row, or skip.","data-on":C==="submit"||void 0,onClick:()=>{Wg(e.groups??[],$)&&O("submit",{kind:"choices",picks:$})},children:e.submit??"Continue"}),e.skip&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost","data-on":C==="skip"||!C&&e.skipped||void 0,onClick:()=>O("skip",{kind:"skip"}),children:e.skip}),le]})]}),e.kind==="swatches"&&o.jsxs("div",{className:"sc-convo-look",children:[e.row.options.some(_=>_.card)?e.layout==="grid"?o.jsx(tJ,{options:e.row.options,picked:Z,onPick:_=>O(_,{kind:"swatches",picks:{[e.row.id]:_}})}):o.jsx(mk,{options:e.row.options,picked:Z,onPick:_=>O(_,{kind:"swatches",picks:{[e.row.id]:_}})}):o.jsx("div",{className:"sc-convo-swatches",children:e.row.options.map(_=>o.jsx(lr,{label:_.label,children:o.jsx("button",{type:"button",className:_.color?"sc-convo-swatch":"sc-chip sc-convo-choice",style:_.color?{"--sc-swatch":_.color}:void 0,"aria-label":_.label,"aria-pressed":Z===_.id,"data-on":Z===_.id||void 0,onClick:()=>O(_.id,{kind:"swatches",picks:{[e.row.id]:_.id}}),children:_.color?null:_.label})},_.id))}),(e.skip||e.describe||le)&&o.jsxs("div",{className:"sc-convo-ways sc-convo-ask","data-guide-shape":"",children:[e.skip&&o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass","aria-pressed":C==="skip"||!C&&e.skipped,"data-on":C==="skip"||!C&&e.skipped||void 0,onClick:()=>O("skip",{kind:"skip"}),children:e.skip}),e.describe&&y&&o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass","aria-pressed":e.saying===void 0?void 0:e.saying,"data-on":e.saying||void 0,onClick:y,children:e.describe}),le]})]}),e.kind==="photos"&&o.jsxs("div",{className:"sc-convo-photos-q",children:[o.jsx($A,{hashes:e.hashes,max:e.max,label:((ae=e.drop)==null?void 0:ae.label)??"Add a photo of their face",hint:((re=e.drop)==null?void 0:re.hint)??"Drop it here, or choose a file",busy:e.busy,onAdd:_=>g({kind:"photos",action:{type:"add",files:_}}),onRemove:_=>g({kind:"photos",action:{type:"remove",hash:_}}),onReject:()=>g({kind:"photos",action:{type:"reject"}})}),e.instead&&o.jsx("button",{type:"button",className:"sc-convo-other","data-on":C==="instead"||void 0,"data-waiting":e.insteadWaiting||void 0,"aria-hidden":e.insteadWaiting||void 0,tabIndex:e.insteadWaiting?-1:void 0,disabled:e.insteadWaiting||void 0,onClick:()=>O("instead",{kind:"photos",action:{type:"instead"}}),children:e.instead}),e.attest&&o.jsxs("label",{className:"sc-convo-attest",children:[o.jsx("input",{type:"checkbox",checked:e.attest.checked,onChange:_=>g({kind:"photos",action:{type:"attest",checked:_.target.checked}})}),o.jsx("span",{children:e.attest.text})]}),o.jsxs("div",{className:"sc-convo-decide sc-convo-ask","data-guide-shape":"",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary","aria-disabled":!!Gg(e)||void 0,title:Gg(e)??void 0,"data-on":C==="submit"||void 0,onClick:()=>{Gg(e)||O("submit",{kind:"photos",action:{type:"submit"}})},children:e.submit}),e.back&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost","data-on":C==="back"||void 0,onClick:()=>O("back",{kind:"photos",action:{type:"back"}}),children:e.back}),le]})]}),e.kind==="pick"&&o.jsxs("div",{className:"sc-convo-pick",children:[e.search&&o.jsx("input",{type:"search",className:"sc-convo-pick-q",value:e.search.value,placeholder:e.search.label,"aria-label":e.search.label,onChange:_=>g({kind:"pick",action:{type:"query",text:_.target.value}}),onKeyDown:_=>{var ue;_.key!=="Escape"||!((ue=e.search)!=null&&ue.value)||(_.preventDefault(),g({kind:"pick",action:{type:"query",text:""}}))}}),o.jsxs("fieldset",{ref:te,className:"sc-convo-pick-scroll","aria-labelledby":ne,"aria-busy":e.loading||void 0,children:[e.items.length===0&&e.loading&&o.jsx("div",{className:"sc-convo-grid sc-convo-pick-grid","aria-hidden":!0,children:Array.from({length:8},(_,ue)=>o.jsx("span",{className:"sc-convo-plate sc-convo-pick-wait",children:o.jsx("span",{className:"sc-convo-plate-in"})},ue))}),e.items.length>0&&o.jsx("div",{className:"sc-convo-grid sc-convo-pick-grid",children:e.items.map(_=>o.jsx("button",{type:"button",className:"sc-convo-plate","aria-label":_.alt,"aria-pressed":Z===_.id,"data-on":Z===_.id||void 0,onClick:()=>O(_.id,{kind:"pick",action:{type:"pick",id:_.id}}),children:o.jsx("span",{className:"sc-convo-plate-in",style:{backgroundImage:`url("${dn(_.hash,"small")}")`}})},_.id))}),e.items.length===0&&!e.loading&&e.empty&&o.jsx("p",{className:"sc-convo-pick-empty",children:e.empty}),e.more&&o.jsx("div",{ref:B,className:"sc-convo-pick-end","aria-hidden":!0})]}),o.jsx("p",{className:"sc-vh",role:"status",children:e.loading?"":e.status??""}),(e.back||le)&&o.jsxs("div",{className:"sc-convo-ways sc-convo-ask","data-guide-shape":"",children:[e.back&&o.jsx("button",{type:"button",className:"sc-chip sc-convo-choice sc-convo-pass","data-on":C==="back"||void 0,onClick:()=>O("back",{kind:"pick",action:{type:"back"}}),children:e.back}),le]})]}),e.kind==="confirm"&&e.quote&&o.jsx(vJ,{text:e.quote,label:e.quoteLabel}),e.kind==="confirm"&&o.jsxs("div",{className:"sc-convo-decide sc-convo-ask","data-guide-shape":"",children:[e.options.map((_,ue)=>o.jsx("button",{type:"button",className:`sc-btn ${ue===0&&!e.quiet?"sc-btn-primary":"sc-btn-ghost"}`,"data-on":C===_.id||void 0,onClick:()=>O(_.id,{kind:"confirm",id:_.id}),children:_.label},_.id)),e.describe&&y&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost","aria-pressed":e.saying===void 0?void 0:e.saying,"data-on":e.saying||void 0,onClick:y,children:e.describe}),Se,le]}),e.cost&&o.jsx("p",{className:"sc-convo-note","data-cost":!0,children:e.cost}),e.note&&o.jsx("p",{className:"sc-convo-note",children:e.note})]})]})}function vJ({text:e,label:t="The brief"}){const[n,r]=s.useState(!1);return s.useEffect(()=>{if(!n)return;const a=setTimeout(()=>r(!1),1600);return()=>clearTimeout(a)},[n]),o.jsxs("figure",{className:"sc-convo-brief",children:[o.jsxs("figcaption",{className:"sc-convo-brief-head",children:[o.jsx("span",{className:"sc-convo-brief-lb",children:t}),o.jsxs("button",{type:"button",className:"sc-convo-brief-copy","data-took":n||void 0,onClick:()=>{var a;(a=navigator.clipboard)==null||a.writeText(e).then(()=>r(!0),()=>{})},children:[n?o.jsx(Kn,{size:13,weight:"bold"}):o.jsx(Lh,{size:13,weight:"bold"}),n?"Copied":"Copy"]})]}),o.jsx("p",{className:"sc-convo-brief-text",children:e})]})}function Gg(e){return e.busy?"Still uploading.":e.hashes.length===0?"Add at least one photo.":e.attest&&!e.attest.checked?"Confirm you have permission to use their likeness.":null}function wJ({text:e,photos:t,at:n,now:r,editable:a,editing:i,arrive:l,leave:u,delay:f=0,turnId:h,dim:p,onEdit:g,onSave:v,onCancel:w}){const[y]=s.useState(!!l),[x]=s.useState(f),k=Iv(u,y?x:0,y?240:0);return o.jsxs("div",{className:"sc-convo-turn","data-guide-shape":"","data-who":"you","data-arrive":y||void 0,"data-leave":k,"data-turn":h,"data-dim":p||void 0,style:y?{"--sc-convo-start":`${x}ms`}:void 0,children:[n?o.jsx(PN,{at:n,now:r}):null,i&&v&&w?o.jsx(yJ,{text:e,onSave:v,onCancel:w}):o.jsxs("div",{className:"sc-convo-bubble",children:[a&&g&&o.jsx(lr,{label:"Change this answer",children:o.jsx("button",{type:"button",className:"sc-convo-edit","aria-label":"Change this answer",onClick:g,children:o.jsx(Ju,{size:13})})}),o.jsx("p",{children:e}),t&&t.length>0&&o.jsx("div",{className:"sc-convo-photos",children:t.map((S,E)=>o.jsx("img",{src:dn(S,"micro"),alt:`Yours, ${E+1} of ${t.length}`},S))})]})]})}function yJ({text:e,onSave:t,onCancel:n}){const[r,a]=s.useState(e),i=s.useRef(null);s.useEffect(()=>{const u=i.current;u&&(u.focus(),u.setSelectionRange(u.value.length,u.value.length))},[]);const l=()=>{const u=r.trim();u&&t(u)};return o.jsxs("div",{className:"sc-convo-bubble","data-editing":"true",children:[o.jsx("textarea",{ref:i,className:"sc-convo-rewrite","aria-label":"Your answer",rows:Math.min(6,Math.max(1,r.split(`
|
|
103
103
|
`).length)),value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Escape"&&(u.preventDefault(),n()),u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),l())}}),o.jsxs("div",{className:"sc-convo-rewrite-do",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:n,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary","aria-disabled":!r.trim()||void 0,onClick:l,children:"Save"})]})]})}const bJ=180,vk=3e3,DN=460,xJ="cubic-bezier(0.22, 1, 0.36, 1)",kJ=220,SJ=450,EJ=48;function CJ({turns:e,busy:t,working:n,memoryKey:r,resumed:a,onAnswer:i,onEdit:l,onSaveEdit:u,onCancelEdit:f,onStarter:h,onDescribe:p,onAttachFiles:g,onRestore:v,onRetry:w,onShow:y}){var Pe;const x=s.useRef(null),k=s.useRef(!0),S=s.useRef(!!a),E=s.useRef(performance.now());S.current&&performance.now()-E.current>vk&&(S.current=!1),s.useEffect(()=>{if(!S.current)return;const de=()=>{S.current=!1},je=window.setTimeout(de,vk);return window.addEventListener("pointerdown",de,{capture:!0}),window.addEventListener("keydown",de,{capture:!0}),()=>{window.clearTimeout(je),window.removeEventListener("pointerdown",de,{capture:!0}),window.removeEventListener("keydown",de,{capture:!0})}},[]);const j=VQ(),N=s.useRef(e),P=s.useRef(null),$=s.useRef(null),M=s.useRef(null),C=s.useRef(null),R=s.useRef(null),T=s.useRef([]),[,H]=s.useState(0),D=s.useRef(new Map),K=s.useRef(0),O=performance.now(),Z=s.useRef(!1),te=NJ(e);if(te!==P.current){P.current=te,Z.current=!0;const de=C.current&&O<C.current.until?C.current:null,je=de?wk(N.current,de):N.current,Ue=new Set(e.map(er)),ye=bk(e),Ee=bk(je),be=Le=>Le.startsWith("you:")&&ye.has(K1(Le))||Le.startsWith("q:")&&Ee.has(Le)&&Ue.has(K1(Le));if(T.current=je.map(er).filter(Le=>!Ue.has(Le)&&!be(Le)),ye.size&&!Ee.size){const Le=K1([...ye][0]),Qe=je.find(Ke=>er(Ke)===Le);M.current=(Qe==null?void 0:Qe.kind)==="you"?{key:Le,text:Qe.text}:null}if(Ee.size>0&&ye.size===0){const Le=M.current;M.current=null;const Qe=Le?e.find(gt=>er(gt)===Le.key):void 0,Ke=!!Le&&((Qe==null?void 0:Qe.kind)!=="you"||Qe.text!==Le.text),nt=e[e.length-1];$.current=Ke&&(nt==null?void 0:nt.kind)==="question"?er(nt):null}if(!j&&T.current.length){const Le=T.current.some(nt=>!(de!=null&&de.gone.has(nt))),Qe=de!=null&&de.look&&T.current.includes(`q:${de.look.qid}`)?de.look:null,Ke=R.current??Qe;C.current={from:je,gone:new Set(T.current),look:Ke,until:Le?O+(R.current?fJ:bJ):(de==null?void 0:de.until)??O}}else C.current=null;R.current=null,N.current=e}const B=C.current&&O<C.current.until?C.current:null;B||(C.current=null),s.useEffect(()=>{if(!B)return;const de=window.setTimeout(()=>H(je=>je+1),Math.max(0,B.until-performance.now()));return()=>window.clearTimeout(de)},[B]);const F=(de,je)=>{R.current={qid:de,look:je}},X=B?wk(e,B):e,z=s.useRef(null);if(z.current===null){const de=r?PJ(r):null;z.current=de??new Set(a||e.length>2?e.map(er):[])}const I=s.useRef(null);I.current===null&&(I.current=(r?MJ(r):null)??new Map);const[U,G]=s.useState(()=>Date.now()),ne=Math.max(0,...I.current.values()),q=U-ne<36e5;s.useEffect(()=>{if(!q)return;const de=window.setInterval(()=>G(Date.now()),3e4);return()=>window.clearInterval(de)},[q]),$.current&&(z.current.delete($.current),$.current=null);const le=new Set;for(const de of X){const je=er(de);de.kind==="question"&&de.question.reopened||z.current.has(je)||le.add(je)}if(a&&S.current&&le.size){for(const de of le)z.current.add(de);le.clear()}const Se=[];let Q=Number.POSITIVE_INFINITY;{const de=new Set(X.map(er));for(const je of[...D.current.keys()])de.has(je)||D.current.delete(je);for(const je of X){const Ue=er(je);if(!le.has(Ue)){Se.push(je);continue}let ye=D.current.get(Ue);if(ye===void 0){const Ee=je.kind==="you"||je.kind==="scenri"&&!!je.quiet;ye=Math.max(O,Ee?0:K.current,(B==null?void 0:B.until)??0),D.current.set(Ue,ye),K.current=Math.max(K.current,ye+(Ee?kJ:jf+Hv))}ye<=O?Se.push(je):Q=Math.min(Q,ye-O)}}s.useEffect(()=>{if(Q===Number.POSITIVE_INFINITY)return;const de=window.setTimeout(()=>H(je=>je+1),Q);return()=>window.clearTimeout(de)},[Q]),s.useEffect(()=>{const de=z.current;if(de){for(const je of T.current)de.delete(je);for(const je of Se){if(je.kind==="question"&&je.question.reopened)continue;const Ue=er(je);B!=null&&B.gone.has(Ue)||de.add(Ue)}r&&LJ(r,de),r&&I.current&&RJ(r,I.current)}});const xe=s.useRef(null),ee=s.useCallback(()=>{const de=x.current;if(!de)return null;const je=xe.current;return je!=null&&je.isConnected&&je.scrollHeight>je.clientHeight?je:(xe.current=R6(de),xe.current)},[]);s.useEffect(()=>{const de=()=>{const je=ee();je&&(k.current=je.scrollHeight-je.scrollTop-je.clientHeight<24)};return document.addEventListener("scroll",de,{passive:!0,capture:!0}),()=>document.removeEventListener("scroll",de,{capture:!0})},[ee]);const ae=(()=>{const de=e.find(Ue=>Ue.kind==="question"&&Ue.question.reopened);if(de)return er(de);const je=e.find(Ue=>Ue.kind==="you"&&Ue.editing);return je?er(je):null})();s.useLayoutEffect(()=>{var Ue;if(!k.current||ae)return;const de=document.activeElement;if(de instanceof HTMLInputElement&&de.type==="search"&&((Ue=x.current)!=null&&Ue.contains(de)))return;const je=ee();je&&(je.scrollTop=je.scrollHeight)});const re=s.useRef(null);s.useLayoutEffect(()=>{var be,Le,Qe,Ke;if(ae===re.current)return;const de=re.current;re.current=ae;const je=x.current;if(!je)return;const Ue=document.activeElement;if(!(!Ue||Ue===document.body||je.contains(Ue)))return;if(ae){if(k.current=!1,ae.startsWith("you:"))return;(Le=(be=Wd(je,ae))==null?void 0:be.querySelector(".sc-convo-q"))==null||Le.focus({preventScroll:!0});return}if(!de)return;const Ee=de.startsWith("q:")?K1(de):de;(Ke=(Qe=Wd(je,Ee))==null?void 0:Qe.querySelector(".sc-convo-edit"))==null||Ke.focus({preventScroll:!0})}),s.useEffect(()=>{if(!ae)return;const de=window.setTimeout(()=>{const je=Wd(x.current,ae),Ue=x.current&&R6(x.current);if(!je||!Ue)return;const ye=je.getBoundingClientRect(),Ee=Ue.getBoundingClientRect();ye.bottom-Ee.bottom>EJ&&yk(je,j)},DN);return()=>window.clearTimeout(de)},[ae,j]);const _=e.length&&e[e.length-1].kind==="question"?er(e[e.length-1]):null,ue=s.useRef(_);s.useLayoutEffect(()=>{var be,Le;const de=x.current;if(ae||!de||_===ue.current)return;const je=document.activeElement,Ue=(be=je==null?void 0:je.closest(".sc-convo-turn"))==null?void 0:be.getAttribute("data-turn"),ye=!je||je===document.body||je!==de&&je.contains(de)||!!Ue&&Ue.startsWith("q:")&&Ue!==_;if(!_||!ye){ue.current=_;return}const Ee=(Le=Wd(de,_))==null?void 0:Le.querySelector(".sc-convo-q:not([hidden])");Ee&&(ue.current=_,Ee.focus({preventScroll:!0}))});const We=s.useRef(_),Xe=s.useRef(null);s.useEffect(()=>{if(_===We.current)return;if(!_){ae&&(Xe.current=We.current),We.current=null;return}const de=Wd(x.current,_);if(!de)return;We.current=_;const je=Xe.current!==null,Ue=Xe.current===_;if(Xe.current=null,k.current||je&&Ue)return;const ye=()=>{AJ(de,x.current)||yk(de,j)};if(!je){ye();return}const Ee=window.setTimeout(ye,SJ);return()=>window.clearTimeout(Ee)},[_,ae,j]);const ze=s.useRef(new Map);s.useLayoutEffect(()=>{const de=x.current;if(!de)return;const je=new Map,Ue=Z.current;Z.current=!1;for(const ye of de.querySelectorAll(".sc-convo-turn")){const Ee=ye.dataset.turn??"",be=ye.offsetTop;je.set(Ee,be);const Le=ze.current.get(Ee);!Ue||j||Le===void 0||Math.abs(Le-be)<1||jJ(ye,Le-be)}ze.current=je});const tt=new Set;if(ae){tt.add(ae);const de=ae.slice(ae.indexOf(":")+1);tt.add(`scenri:asked-${de}`);const je=Se.findIndex(Ue=>er(Ue)===ae);if(je>=0){for(let Ue=je+1;Ue<Se.length&&Uh(Se[Ue]);Ue++)tt.add(er(Se[Ue]));for(let Ue=je-1;Ue>=0&&Uh(Se[Ue]);Ue--)tt.add(er(Se[Ue]))}}for(const de of Se){const je=er(de);I.current.has(je)||I.current.set(je,Date.now())}let ce=!1;const ve=[];for(const de of Se){const je=er(de),Ue=!!ae&&!tt.has(je),ye=I.current.get(je),Ee=!!(B!=null&&B.gone.has(je)),be=Ee&&de.kind==="question"&&((Pe=B==null?void 0:B.look)==null?void 0:Pe.qid)===de.question.id,Le=de.kind==="scenri"&&!!de.quiet,Qe=!j&&!Ee&&le.has(je)&&!Le,Ke=0,nt=ce;Ee||(ce=de.kind==="scenri"||de.kind==="question"&&!de.question.reopened),de.kind==="you"?ve.push(o.jsx(wJ,{text:de.text,photos:de.photos,editable:de.editable,editing:de.editing,arrive:Qe,leave:Ee,delay:Ke,turnId:je,dim:Ue,at:ye,now:U,onEdit:de.editable&&l?()=>l(de.id):void 0,onSave:u?gt=>u(de.id,gt):void 0,onCancel:f},je)):de.kind==="scenri"?ve.push(o.jsx(cJ,{text:de.text,tone:de.tone,reveal:Qe,leave:Ee,eyebrow:!nt,delay:Ke,turnId:je,dim:Ue,at:ye,now:U,thumb:de.thumb,label:de.label,current:de.current,restore:de.restore,onRestore:v,retry:de.retry,onRetry:w,onShow:y},je)):ve.push(o.jsx(gJ,{question:de.question,reveal:Qe,leave:Ee&&!be,spent:Ee,delay:Ke,turnId:je,dim:Ue,busy:t||Ue,eyebrow:!nt,at:ye,now:U,onAnswer:gt=>i(de.question.id,gt),onPick:F,onStarter:h,onDescribe:p,onAttachFiles:g,onCancel:f},je))}return o.jsx("div",{ref:x,className:"sc-convo-log",role:"log","aria-live":"polite","aria-relevant":"additions","data-changing":ae?"true":void 0,children:o.jsxs("div",{className:"sc-convo-turns",children:[ve,n&&o.jsx(uJ,{what:n===!0?void 0:n})]})})}function wk(e,t){const n=[],r=new Set(e.map(er));let a=0;for(const i of t.from){const l=er(i);if(t.gone.has(l)){r.has(l)||n.push(i);continue}for(;a<e.length&&er(e[a])!==l;)n.push(e[a++]);a<e.length&&n.push(e[a++])}for(;a<e.length;)n.push(e[a++]);return n}function jJ(e,t){for(const a of e.getAnimations())a.id==="slide"&&a.cancel();const n=`translateY(${t}px)`;e.style.transform=n;const r=e.animate([{transform:n},{transform:"translateY(0)"}],{duration:DN,easing:xJ,fill:"both"});r.id="slide",r.onfinish=()=>{e.style.transform="",r.cancel()}}function AJ(e,t){if(!t)return!1;const n=R6(t),r=e.getBoundingClientRect(),a=n.getBoundingClientRect();return r.top>=a.top&&r.top<=a.bottom-24}function yk(e,t){var n;(n=e==null?void 0:e.scrollIntoView)==null||n.call(e,{block:"nearest",behavior:t?"auto":"smooth"})}function Wd(e,t){if(!e)return null;for(const n of e.querySelectorAll(".sc-convo-turn"))if(n.dataset.turn===t)return n;return null}function NJ(e){const t=[];for(const n of e){const r=er(n);if(n.kind==="question"){const u=n.question,f="options"in u&&Array.isArray(u.options)?u.options.map(h=>h.id).join(","):"";t.push(`${r}~${u.reopened?1:0}~${u.prompt}~${u.hint??""}~${f}`);continue}const a="photos"in n&&Array.isArray(n.photos)?n.photos.length:0,i="thumb"in n?n.thumb??"":"",l="editing"in n&&n.editing?1:0;t.push(`${r}~${n.text??""}~${i}~${a}~${l}`)}return t.join("")}function bk(e){const t=new Set;for(const n of e)n.kind==="question"&&n.question.reopened&&t.add(er(n));return t}function K1(e){return e.startsWith("you:")?`q:${e.slice(4)}`:e.startsWith("q:")?`you:${e.slice(2)}`:""}function R6(e){let t=e;for(;t;){const{overflowY:n}=getComputedStyle(t);if((n==="auto"||n==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return e}const Fv=e=>`scenri:convo-said:${e}`;function Ii(e){try{sessionStorage.removeItem(Fv(e)),sessionStorage.removeItem(_v(e))}catch{}}const _v=e=>`scenri:convo-at:${e}`;function MJ(e){try{const t=sessionStorage.getItem(_v(e));return t?new Map(Object.entries(JSON.parse(t))):null}catch{return null}}function RJ(e,t){try{sessionStorage.setItem(_v(e),JSON.stringify(Object.fromEntries(t)))}catch{}}function PJ(e){try{const t=sessionStorage.getItem(Fv(e));return t?new Set(JSON.parse(t)):null}catch{return null}}function LJ(e,t){try{sessionStorage.setItem(Fv(e),JSON.stringify([...t]))}catch{}}function xk(e){return`${["No","One","Two","Three","Four","Five"][e]??String(e)} picture${e===1?"":"s"}`}function kk(e){const[t,...n]=e,r=[t,...n.map(a=>a.toLowerCase())];return r.length>1?`${r.slice(0,-1).join(", ")} and ${r[r.length-1]}`:r[0]??""}const Ne={title:"Create scene",editTitle:"Edit scene",intent:"Create a scene",source:"Where are we shooting? Describe the place, or start from pictures of one.",addPictures:"Add pictures",guideMe:"Guide me",photos:"Add one to four pictures of the place. The more they share, the better it reads.",photosDrop:{label:"Add pictures of the place",hint:"Drop them here, or choose files"},fromShot:"Or start from one of your shots",fromShotAnswer:"Start from one of my shots",shot:"Which shot? I'll read the place in it and leave the product and people out.",shotSearch:"Find a shot",shotNone:"No shots to start from yet.",shotNotFound:e=>`No shot matches "${e}".`,shotsFailed:"The shots could not be read just now. Try the search again.",shotCount:(e,t)=>t?`${e} shots so far, more as you scroll`:`${e} ${e===1?"shot":"shots"}`,shotAnswer:"This shot",backToPictures:"Back to pictures",shotOff:"Choose a shot above.",madeIn:e=>`This shot was made in ${e}.`,takeScene:e=>`Use ${e}`,readNew:"Read a new scene from it",reuseOff:"Choose above.",anotherShot:"Choose another shot",stopped:"That was stopped. Nothing here was changed.",stoppedRead:"Stopped before the place was read. Read it again, or say it differently.",stoppedDraw:"Stopped. Nothing was drawn.",stoppedChange:"Stopped before the picture changed. The new words are kept: draw them, or put back the last picture.",readThem:"Read them",guideInstead:"Guide me instead",skip:"Skip",describeInstead:"Describe instead",worldHint:"Choose a starting world. You'll personalise it next.",worldLightPrompt:e=>`This world is already lit ${e}. Keep it, or choose another.`,keepWorldLight:"Keep it",keepWorldSurface:"Keep the world's own",suggestOne:"Suggest one",followWorld:"You have the feel of it. What kind of place is it?",followLight:"You have the place. What light is it in?",leaveToReading:"Leave it to the reading",worldIsAStart:"Treat this as a starting direction, not a picture to reproduce: keep the material language and the character of the light, and invent a specific original arrangement.",emptyLead:"The place appears here",emptyHint:"Describe it, or add pictures of it",sourcePlaceholder:"Describe the place, or choose above",nothingSaidPlaceholder:"Tell me where we are, in your own words",rowPlaceholder:e=>`Tap one above, or describe the ${e} in your own words`,photosOff:"Add the pictures above, then read them.",addPlaceholder:"Anything to add or leave out?",keepPlaceholder:"Anything to keep or ignore in them?",keepShotPlaceholder:"Anything to keep or ignore in it?",changePlaceholder:"Say what to change. The rest stays.",namePlaceholder:"Its name",nameIt:"Name this scene",attachLabel:"Add pictures of the place",send:"Send",lineLabel:"Your answer",change:"Change",reading:"Writing what your shots are told",readingPhotos:"Reading your pictures",changing:"Changing the words",drawing:"Drawing the scene",stillReading:"Still writing what your shots are told",readingHead:"What your shots are told",placeLabel:"The place",lightLabel:"Light",cameraLabel:"Camera",figureLabel:"Built around",agree:"Here is the place, in full. Ready to draw?",agreePhotos:"Here is the place I read in your pictures. Ready to draw?",agreeShot:"Here is the place I read in your shot. Ready to draw?",agreeChanged:"Here it is with that. Ready to draw?",agreeBlind:"Here is the place, in full. Nothing here can draw yet, so it is saved as words.",readAgain:"I read the place again.",draw:"Draw the scene",saveWords:"Save scene",here:"Here is the scene.",again:"Here it is again.",changed:"Here it is, changed.",decide:e=>`Here is ${e}. Use it, or change something.`,decideEdit:e=>`Here is ${e}. Save it, or change something.`,use:"Use this scene",saveChanges:"Save changes",tryAgain:"Try again",changeSomething:"Change something",name:"While it draws: what should we call it?",editOpen:e=>`Here is ${e}, as it is saved. Change something, or draw it again.`,failed:"That did not work. Nothing standing was touched.",failedFirst:e=>`That did not go through: ${e}. Nothing was drawn.`,lost:"That work is gone: the server restarted while it ran. Try it again.",offline:"Lost touch with Scenri. Still trying.",retry:"Try again",version:e=>`Version ${e}`,saved:"Saved.",savedQuiet:"Saved. Nothing is drawn until you ask.",showInUse:(e,t)=>`Show it in use? ${xk(t.length)} with a Scenri demo ${e} in the place: ${kk(t.map(n=>n.toLowerCase()))}.`,staleSet:e=>`${xk(e)} here show${e===1?"s":""} the place as it was before. Draw ${e===1?"it":"them"} again?`,drawThem:"Draw them",drawThemAgain:"Draw them again",inUse:e=>`Saved. Now it is shown in use, with a Scenri demo ${e}. Shots are told the words, never handed these pictures.`,noLibrary:"Saved. Scenri's library has not downloaded yet, so it cannot be shown in use for now.",exampleHere:{hero:"Here is the hero.",close:"Here is a close-up.",hands:"Here it is in hands.",angle:"Here is another angle.",bold:"Here is a bold one."},exampleFailed:(e,t)=>`The ${e.toLowerCase()} did not draw: ${t.replace(/[.\s]+$/,"")}.`,more:e=>`Add ${["no","one","two","three"][e.length]??e.length} more? ${kk(e)}.`,addThem:"Add them",notNow:"Not now",ready:e=>`${e} is ready.`,readyUndrawn:e=>`${e} is ready. It can be shown in use any time, from its page.`,readyMissing:e=>`${e} is ready. Some did not draw.`,openScene:"Open scene",useInAShot:"Use in a shot",notAPlace:"That did not read as a place. Try a few words about it, like 'a quiet concrete gallery at dusk'.",greet:"Hello. Describe the place, or choose above.",greetRow:"Tap one above, or say it in a few words.",askHelp:"Describe the place in a few words, or tap one above. Everything can be changed later.",goFirst:"Choose above, or describe the place first.",startOverIsUp:"Start over is at the top of this panel.",notInAScene:"A scene holds the place and its light. Add presenters and products in Create.",usePutBack:"Step back through the versions on the picture, and Put back the one you want.",sayAChange:"Say what to change about the place, and the rest stays as it is.",renamed:e=>`Called it ${e}.`,changeIt:"Change it",changeTitle:"Change this answer?",changeBody:"The picture was drawn from the answers as they are. Changing one asks again from there, and the pictures so far go. To keep the picture and change one thing, say it in the line instead.",onlyPictures:"Only pictures can show a place.",fourPictures:"Four pictures is the most a scene is read from.",leaveTitle:"Leave this scene?",leaveBody:"Nothing has been read yet, so the answers here go.",leave:"Leave",discardTitle:"Discard the changes?",discardBody:"The scene stays as it was saved. What was drawn here is let go.",discard:"Discard changes",startOver:"Start over",startOverTitle:"Start over?",startOverBody:"This conversation begins again from the first question. Nothing here is saved yet."},TJ="part of the place itself, never a separate object that competes with the subject, and leaving the subject a clear place to stand",HN={water:{surface:[{key:"basalt",label:"Wet basalt",words:"a ledge of wet black basalt, glossy where the sea has just left it"},{key:"sand",label:"White sand",words:"rippled white sand under a few centimetres of clear water"},{key:"pebbles",label:"Sea pebbles",words:"a bed of smooth sea-worn pebbles, wet and gleaming"},{key:"awash",label:"Rock awash",words:"a flat rock just awash, a thin sheet of clear water sliding over it"}],light:[{key:"caustics",label:"Water caustics",words:"a live net of water caustics sliding across every surface"},{key:"sunset",label:"Low sun on water",words:"low sun skimming the water, long glittering reflections"},{key:"silver",label:"Silver overcast",words:"soft silver overcast light, the sea flat and pale"},{key:"backlit",label:"Backlit spray",words:"the sun behind the surf, the spray lit up like glass"}],signature:[{key:"wave",label:"Frozen wave",words:"a wave frozen mid-break behind the rock, its crest in glassy detail"},{key:"foam",label:"Foam lace",words:"a lace of sea foam drawn across the wet rock"},{key:"kelp",label:"Kelp ribbons",words:"glossy olive-gold ribbons of kelp draped over the rocks"},{key:"pool",label:"Mirror pool",words:"a still rock pool mirroring the sky"}]},stone:{surface:[{key:"travertine",label:"Travertine",words:"honed cream travertine up close, its pores and soft veins readable"},{key:"limestone",label:"Rough limestone",words:"a rough-cut block of warm limestone, chisel marks in its face"},{key:"terracotta",label:"Terracotta tile",words:"sun-baked terracotta floor tiles, worn at the edges"},{key:"marble",label:"Weathered marble",words:"weathered pale marble, its polish worn soft by years of sun"}],light:[{key:"shadow",label:"One long shadow",words:"one high hard light throwing a single long, precise shadow across the stone"},{key:"olive",label:"Olive-leaf dapple",words:"sun broken into moving dapples through olive leaves"},{key:"golden",label:"Low golden sun",words:"low golden sun raking almost flat across the stone, long warm shadows"},{key:"shade",label:"Cool shade",words:"the niche in open shade, cool bounced light and a bright sunlit world beyond"}],signature:[{key:"vines",label:"Vines taking over",words:"a vine growing down the stone, claiming its edges"},{key:"basin",label:"Water in the stone",words:"water trickling into a basin carved in the stone, glinting"},{key:"dust",label:"Dust in the sun",words:"fine dust hanging in one bright shaft of sun"},{key:"sphere",label:"A giant stone sphere",words:"one oversized stone sphere resting in the space, impossible in scale"}]},colour:{surface:[{key:"lacquer",label:"Glossy lacquer",words:"a glossy lacquered floor the same colour as the sweep, mirroring it"},{key:"paper",label:"Matte paper",words:"matte coloured paper, its fibres and one soft crease readable"},{key:"acrylic",label:"Frosted acrylic",words:"a sheet of frosted acrylic glowing softly with the colour behind it"},{key:"velvet",label:"Flocked velvet",words:"flocked velvet in the same colour, soaking up the light"}],light:[{key:"gobo",label:"Cut spotlight",words:"a hard spotlight cut into one graphic shape across the colour"},{key:"split",label:"Two-colour gels",words:"two coloured gels splitting the light, one warm and one cool edge"},{key:"wrap",label:"Soft studio wrap",words:"soft wrapping studio light, a gentle gradient across the sweep"},{key:"rim",label:"Neon rim",words:"one neon rim tracing the edges, the rest of the colour dimmed"}],signature:[{key:"shapes",label:"Floating shapes",words:"a few simple geometric shapes floating in the colour, frozen in place"},{key:"planes",label:"Cut-paper planes",words:"sharp-angled planes of cut paper converging in the colour"},{key:"block",label:"Colour-block shadow",words:"a hard shadow cut into a block of a second colour"},{key:"giant",label:"Surreal scale",words:"one oversized sphere or arch in the colour, impossible in scale"}]},citrus:{surface:[{key:"halves",label:"Cut citrus",words:"a bed of halved citrus, the flesh glistening with juice"},{key:"tile",label:"Glazed tile",words:"sun-bleached glazed tiles in white and cobalt"},{key:"ice",label:"Crushed ice",words:"crushed ice melting over the fruit"},{key:"cloth",label:"Crisp linen",words:"a crisp white linen cloth spread under the fruit"}],light:[{key:"glow",label:"Sun through fruit",words:"the sun behind the fruit, the flesh glowing like stained glass"},{key:"leaves",label:"Leaf shade",words:"sun broken into dapples through citrus leaves"},{key:"golden",label:"Late golden sun",words:"late golden sun, the sky deepening, long warm shadows"},{key:"flash",label:"Hard flash",words:"hard direct flash against the blue sky, crisp and saturated"}],signature:[{key:"blossom",label:"Blossom and leaves",words:"citrus blossom and glossy leaves threaded through the fruit"},{key:"melting",label:"Ice melting",words:"ice melting over the fruit, beads of water running down"},{key:"peel",label:"Peel spirals",words:"long spirals of peel curling across the mound"},{key:"giant",label:"Giant fruit",words:"one citrus fruit at an impossible, monumental scale on the horizon"}]},volcanic:{surface:[{key:"crust",label:"Lava crust",words:"a crust of cooled black lava, ropey and cracked"},{key:"sand",label:"Black sand",words:"fine black volcanic sand, wind-rippled"},{key:"pumice",label:"Pumice",words:"porous grey pumice, sharp and light"},{key:"obsidian",label:"Obsidian",words:"a slab of glassy black obsidian with conchoidal edges"}],light:[{key:"fissures",label:"Glow from below",words:"incandescent orange fissures lighting the rock from below"},{key:"raking",label:"Sun through haze",words:"a hard low sun raking through the orange haze"},{key:"ember",label:"Ember glow",words:"a deep ember glow, everything else falling into dark"},{key:"moon",label:"Blue moonlight",words:"cold blue moonlight on the black rock, the haze gone silver"}],signature:[{key:"lava",label:"Lava still moving",words:"lava still glowing in the cracks of the crust, cooling as it goes"},{key:"ash",label:"Ash in the air",words:"fine ash drifting through the haze"},{key:"steam",label:"Steam vents",words:"white steam rising from vents in the rock"},{key:"floating",label:"Floating rocks",words:"a few rocks hanging weightless in the haze, impossible and still"}]},dark:{surface:[{key:"mirror",label:"Black mirror",words:"black mirror glass, every reflection crisp"},{key:"steel",label:"Brushed steel",words:"brushed stainless steel with a fine directional grain"},{key:"marble",label:"Black marble",words:"polished black marble with thin white veins"},{key:"water",label:"Black water",words:"still black water, one faint ripple"}],light:[{key:"gobo",label:"Cut spotlight",words:"a hard spotlight cut into one graphic shape across the dark"},{key:"pool",label:"Pool of light",words:"one pool of light from above, the rest falling to true black"},{key:"neon",label:"Neon edge",words:"one line of coloured neon reflected in the black surface"},{key:"rim",label:"Thin rim",words:"a thin bright rim of light along every edge, nothing else lit"}],signature:[{key:"wax",label:"Wax cascading",words:"dark wax cascading down a wall into the mirror, glossy and still setting"},{key:"ripples",label:"Ripples",words:"slow concentric ripples crossing the black surface"},{key:"smoke",label:"Smoke curl",words:"one curl of smoke drifting through the light"},{key:"sphere",label:"Floating sphere",words:"a perfect sphere floating above the mirror, impossible and still"}]},plaster:{surface:[{key:"limewash",label:"Limewash floor",words:"a limewashed plaster floor, soft and chalky"},{key:"oak",label:"Pale oak",words:"pale oak boards, their grain soft in the light"},{key:"terrazzo",label:"Terrazzo",words:"pale terrazzo with small flecks of stone"},{key:"silk",label:"Silk drape",words:"a length of silk pooling on the floor in soft folds"}],light:[{key:"shadow",label:"Window shadow",words:"hard sun through the tall window, its shape laid long across the room"},{key:"leaves",label:"Leaf shadows",words:"soft moving leaf shadows thrown across the plaster"},{key:"golden",label:"Low golden sun",words:"low golden sun raking across the plaster, long warm shadows"},{key:"dusk",label:"Blue dusk",words:"cool blue dusk in the window, the room dim and quiet"}],signature:[{key:"curtain",label:"Curtain in the wind",words:"a sheer curtain lifted into the room by the wind"},{key:"plants",label:"Plants growing in",words:"green plants growing up the plaster walls, claiming the corners"},{key:"arch",label:"Arch shadow",words:"the hard shadow of an arch cut across the wall"},{key:"stair",label:"Surreal stair",words:"a plaster stair rising into the wall and going nowhere"}]},linen:{surface:[{key:"linen",label:"Raw linen",words:"raw undyed linen, its slub weave readable"},{key:"satin",label:"Silk satin",words:"heavy silk satin in deep folds, its sheen catching the light"},{key:"boucle",label:"Wool bouclé",words:"nubbly wool bouclé, soft and textured"},{key:"paper",label:"Crumpled paper",words:"large sheets of crumpled paper folded like cloth"}],light:[{key:"leaves",label:"Leaf dapple",words:"sun broken into soft dapples through leaves"},{key:"slice",label:"Slice of sun",words:"one hard slice of sun across the folds"},{key:"golden",label:"Low golden sun",words:"low golden sun raking across the folds, deep warm shadows"},{key:"through",label:"Light through cloth",words:"light glowing through the cloth from behind"}],signature:[{key:"wind",label:"Lifted by wind",words:"the cloth lifted by a gust and frozen mid-billow"},{key:"dried",label:"Dried flowers",words:"a few dried flowers and grasses caught in the folds"},{key:"thread",label:"One red thread",words:"a single red thread running through the folds"},{key:"landscape",label:"Folds as dunes",words:"the folds made vast, like a landscape of dunes"}]}};function Zv(e,t){const n=e?HN[e]:void 0;return n?n[t].map((r,a)=>({id:`${e}-${r.key}`,label:r.label,words:r.words,card:`scene-${e}-${t}-${a+1}`})):null}function $J(e){return Object.keys(HN).flatMap(t=>Zv(t,e)??[])}const DJ=["water","stone","colour","citrus","volcanic","dark","plaster","linen"],Af=["world","surface","light","signature"],na=(e,t)=>`scene-${e}-${t}`,Xi={world:{prompt:"What world?",options:[{id:"water",label:"Rock and water",words:"a shoreline of wet dark rock and shallow turquoise water",light:"in hard midday sun",card:na("world",1),cues:["water","sea","ocean","shore","shoreline","beach","wet","pool","underwater"]},{id:"stone",label:"Sunlit stone",words:"a niche of warm limestone and rough plaster",light:"in hard afternoon sun",card:na("world",2),cues:["stone","limestone","wall","niche","arch","terracotta","mediterranean","sunlit"]},{id:"colour",label:"Colour field",words:"a seamless studio sweep in one saturated colour",light:"in flat hard poster light",card:na("world",3),cues:["studio","sweep","seamless","backdrop","colour","color","paper","poster","graphic","flat"]},{id:"citrus",label:"Fruit and sky",words:"a mound of cut citrus under an open blue sky",light:"in bright direct sun",card:na("world",4),cues:["fruit","citrus","orange","lemon","sky","outdoors","outdoor","summer","juice"]},{id:"volcanic",label:"Volcanic haze",words:"dark volcanic rock in a deep orange haze",light:"with one hard low light raking across it",card:na("world",5),cues:["volcanic","lava","rock","ash","dust","haze","smoke","desert","mars"]},{id:"dark",label:"Dark mirror",words:"a near-black polished surface like a still pool",light:"in low-key light, with one bright edge",card:na("world",6),cues:["mirror","reflection","polished","still pool"]},{id:"plaster",label:"Soft plaster",words:"a bare plaster room with one tall soft window",light:"in soft overcast daylight",card:na("world",7),cues:["plaster","concrete","microcement","minimal","interior","room","window","raw","architectural","overcast"]},{id:"linen",label:"Linen fold",words:"a length of raw undyed linen folded in soft loose drapes",light:"in soft window light",card:na("world",8),cues:["linen","fabric","textile","cloth","drape","fold","woven","cotton","soft fabric"]}]},surface:{prompt:"What is it made of, up close?",options:[{id:"travertine",label:"Travertine",words:"honed cream travertine up close, its pores and soft veins readable",cues:["travertine"]},{id:"steel",label:"Brushed steel",words:"brushed stainless steel with a fine directional grain",cues:["steel","stainless","brushed metal","aluminium","aluminum"]},{id:"clay",label:"Cracked clay",words:"sun-dried terracotta clay cracked into deep fissures",cues:["clay","terracotta","cracked earth"]},{id:"silk",label:"Silk folds",words:"heavy silk gathered into deep sculptural folds",cues:["silk","satin"]},{id:"sand",label:"Wet sand",words:"rippled wet sand, glossy where the water has just drawn back",cues:["sand","wet sand"]},{id:"moss",label:"Moss and roots",words:"damp moss over exposed roots, dense and living",cues:["moss","mossy","roots"]},{id:"ice",label:"Ice",words:"clear ice with trapped bubbles and a cold blue depth",cues:["ice","icy","glacial"]},{id:"concrete",label:"Raw concrete",words:"raw board-formed concrete with timber grain printed into it",cues:["board-formed","cement"]}]},light:{prompt:"What does the light do?",options:[{id:"shadow",label:"One long shadow",words:"one high hard light throwing a single long, precise shadow across the place",cues:["long shadow","skylight","shaft of light","single shadow"]},{id:"dapple",label:"Dappled leaves",words:"sun broken into soft moving dapples through leaves",cues:["dappled","dapple","through leaves","leaf shadows","canopy"]},{id:"caustics",label:"Water caustics",words:"a live net of water caustics sliding across every surface",cues:["caustics","caustic","rippling light","underwater light"]},{id:"gobo",label:"Cut spotlight",words:"a hard spotlight cut into one graphic shape across the set",cues:["gobo","spotlight","cut light","shaped light"]},{id:"window",label:"Soft window",words:"soft daylight from one large window, falling open and shadowless on the far side",card:na("light",7),cues:["window light","side light","from a window","sidelit","window","soft","daylight","overcast","diffused"]},{id:"golden",label:"Low golden sun",words:"low golden sun raking almost flat across it, long warm shadows",card:na("light",2),cues:["golden","golden hour","sunset","sunrise","dusk","warm"]},{id:"neon",label:"Neon glow",words:"coloured neon streaking its light across glossy surfaces at night",card:na("light",4),cues:["neon","night","nocturnal","after dark"]},{id:"lowkey",label:"Pool of light",words:"one pool of light with a bright edge, the rest falling to true black",card:na("light",6),cues:["low key","lowkey","dramatic","shadowy","chiaroscuro","rim light"]}]},signature:{prompt:"What makes it unforgettable?",options:[{id:"air",label:"Mist, snow or wind",words:"the air of the place alive, such as mist lying low, snow drifting down or wind moving through fabric or grass: one, chosen for this place",cues:["mist","misty","fog","foggy","snow","snowing","wind","windswept","haze"]},{id:"change",label:"Caught mid-change",words:"the place's own material caught mid-change, such as wax cascading down a wall, sugar pulled glassy across the surface or ice melting at its edge: one, chosen for this place",cues:["melting","molten","dripping","wax","resin","mid-change"]},{id:"graphic",label:"Graphic light and shadow",words:"one bold graphic device of light and shadow shaping the set, such as a cut shadow or a hard slice of colour",cues:["graphic","geometric","cut shadow","colour block","color block"]},{id:"nature",label:"Nature taking over",words:"nature growing through the set, such as moss, blooms or roots claiming its edges: one, chosen for this place",cues:["overgrown","blooms","flowers","vines","growing"]},{id:"water",label:"Glass and water",words:"water and reflection in the place, such as a still reflecting pool or rain-beaded glass: one, chosen for this place",cues:["reflection","reflecting","rain","puddle","rain glass"]},{id:"scale",label:"Surreal scale",words:"one surreal touch of scale, an oversized natural or architectural form that makes the place feel impossible",cues:["surreal","giant","oversized","impossible","dreamlike"]}]}},HJ=new Set([...Xi.world.options.map(e=>e.card),...Xi.light.options.filter(e=>e.card).map(e=>e.card),...DJ.flatMap(e=>["surface","light","signature"].flatMap(t=>(Zv(e,t)??[]).map(n=>n.card)))]);function OJ(e,t){return e==="world"?Xi.world.options:Zv(t,e)??Xi[e].options}function IJ(e,t){const n=OJ(e,t),r=n.every(a=>!!a.card&&HJ.has(a.card));return{id:e,label:Xi[e].prompt,options:n.map(a=>({id:a.id,label:a.label,...r?{card:a.card}:{}}))}}const FJ={world:"place",surface:"surface",light:"light",signature:"idea"},Sk=e=>FJ[e],co=(e,t)=>{if(!t)return;const n=Xi[e].options.find(r=>r.id===t);return n||e==="world"?n:$J(e).find(r=>r.id===t)},_J="one signature idea that makes this place unforgettable, invented for it and never generic";function ZJ(e){const t=` ${e.toLowerCase().replace(/[^a-z0-9]+/g," ")} `,n={};for(const r of Af){let a=null;for(const i of Xi[r].options)for(const l of i.cues??[]){const u=` ${l.replace(/[^a-z0-9]+/g," ")} `;t.includes(u)&&(!a||l.length>a.len)&&(a={id:i.id,len:l.length})}a&&(n[r]=a.id)}return n}const VJ=["studio","cyclorama","cyc","seamless","sweep","backdrop","set","room","interior","exterior","beach","shore","shoreline","coast","sea","ocean","lake","river","water","pool","forest","woods","woodland","jungle","garden","park","field","meadow","desert","dune","dunes","mountain","mountains","cliff","cave","canyon","street","city","urban","rooftop","loft","warehouse","gallery","museum","hotel","lobby","kitchen","bathroom","bedroom","living room","cafe","café","bar","restaurant","shop","store","boutique","market","library","courtyard","terrace","balcony","corridor","hallway","tunnel","bridge","station","greenhouse","spa","chapel","ruin","ruins","architecture","landscape","outdoors","indoors","sky"],P6=["stone","rock","rocks","marble","travertine","limestone","granite","basalt","concrete","plaster","terrazzo","tile","tiles","wood","wooden","oak","walnut","linen","fabric","velvet","silk","satin","glass","metal","steel","chrome","brass","mirror","sand","moss","ferns","foliage","flowers","paper","colour field","color field","colour block","color block","pastel","brutalist","minimal","wall","walls","clay","terracotta","ice","aluminium","aluminum","stainless","leather","felt","slate","onyx","salt"],ON=["splash","splashing","mid air","frozen","falling","petals","confetti","smoke","mist","fog","steam","dust","drifting","bubbles","melting","molten","dripping","wax","resin","pouring","overgrown","blooms","flowers","vines","reflection","reflections","reflecting","rain","puddle","ripples","surreal","giant","oversized","levitating","impossible","dreamlike","cut shadow","gobo"],IN=["light","lit","lighting","flash","strobe","strobes","sun","sunny","sunlight","sunlit","sunshine","daylight","golden hour","sunset","sunrise","dusk","dawn","twilight","blue hour","night","neon","moonlight","moonlit","candle","candlelight","candlelit","lamp","lamplight","spotlight","spotlit","softbox","overcast","shadow","shadows","shadowless","backlit","backlight","rim light","glow","glowing","noon","midday","low key","high key","chiaroscuro","hard sun","window light"],FN=["plinth","pedestal","podium","platform","block","cube","table","tabletop","counter","countertop","shelf","ledge","tray","on the floor","on the ground","in hand","in hands","hand","hands","held","holding","resting","rests","floating","floats","suspended","hanging","leaning","propped","nestled","nested","half buried","emerging","balanced","stacked","scattered"],_N=["top down","overhead","flat lay","flatlay","birds eye","bird s eye","aerial","from above","from below","low angle","high angle","eye level","worms eye","close up","closeup","macro","wide angle","wide shot","wide","telephoto","35mm","50mm","85mm","lens","shot from","framed","framing","straight on","profile"],ZN={world:[...VJ,...P6],surface:P6,light:IN,signature:ON,stage:FN,camera:_N},zJ=e=>` ${e.toLowerCase().replace(/[^a-z0-9é]+/g," ").trim()} `,BJ=(e,t)=>e.includes(` ${t.replace(/[^a-z0-9é]+/g," ")} `);function VN(e){const t=zJ(e),n=r=>r.some(a=>BJ(t,a));return{world:n(ZN.world),surface:n(P6),light:n(IN),signature:n(ON),stage:n(FN),camera:n(_N)}}const UJ=e=>Object.keys(ZN).filter(t=>e[t]);function WJ(e){const t=["world","surface","light"].filter(r=>!e[r]),n=UJ(e).length>=3?t.filter(r=>r==="world"):t.slice(0,2);return e.signature?n:[...n,"signature"]}const qo="__passed",o0=e=>{var t;return(t=e.source)==null?void 0:t.door},KJ=e=>{var t;return o0(e)==="words"?WJ(VN(((t=e.source)==null?void 0:t.text)??"")):[]},am=[{id:"source",applies:()=>!0},{id:"photos",applies:e=>o0(e)==="photos"},{id:"shot",applies:e=>o0(e)==="shot"},{id:"reuse",applies:e=>{var t;return o0(e)==="shot"&&!!((t=e.shot)!=null&&t.scene)}},...Af.map(e=>({id:e,applies:t=>o0(t)==="guided"||KJ(t).includes(e)}))],mh=am.map(e=>e.id),Kh=e=>Af.includes(e),Ek=e=>mh.includes(e),GJ=e=>{var t;return!!e&&(!!e.pick||!!((t=e.words)!=null&&t.trim()))};function Vv(e,t){var n;return e==="source"?!!t.source:e==="photos"?!!((n=t.photos)!=null&&n.done)&&t.photos.hashes.length>0:e==="shot"?!!t.shot:e==="reuse"?t.reuse==="read":GJ(t[e])}const YJ=e=>am.filter(t=>t.applies(e)&&Vv(t.id,e)).map(t=>t.id);function zN(e){var t;return((t=am.find(n=>n.applies(e)&&!Vv(n.id,e)))==null?void 0:t.id)??null}const BN=e=>{var t,n,r,a,i;return((t=e.source)==null?void 0:t.door)==="words"?!!((n=e.source.text)!=null&&n.trim()):((r=e.source)==null?void 0:r.door)==="photos"?(((a=e.photos)==null?void 0:a.hashes.length)??0)>0:((i=e.source)==null?void 0:i.door)==="shot"?!!e.shot:Af.some(l=>Li(l,e[l])!==null)},Ck=e=>!!e.source&&zN(e)===null&&BN(e),L6=(e,t)=>JSON.stringify(e)!==JSON.stringify(t);function zv(e,t){const n={...e},r=[];for(const[a,i]of Object.entries(t))L6(e[a],i)&&(i===void 0?delete n[a]:n[a]=i,r.push(a));if(r.length){const a=Math.min(...r.map(i=>mh.indexOf(i)));for(const i of mh)mh.indexOf(i)<=a||i in t||delete n[i]}for(const a of am)n[a.id]!==void 0&&!a.applies(n)&&delete n[a.id];return n}function qJ(e,t,n){var r,a;if(e==="source")return t.kind!=="choice"?null:t.id==="photos"?{source:{door:"photos"},photos:{hashes:((r=n.photos)==null?void 0:r.hashes)??[],done:!1}}:t.id==="guided"?{source:{door:"guided"}}:null;if(e==="reuse")return t.kind==="choice"&&t.id==="read"?{reuse:"read"}:null;if(Kh(e)){const i=(a=n[e])==null?void 0:a.words,l=t.kind==="swatches"?t.picks[e]??Object.values(t.picks)[0]:t.kind==="choice"?t.id:void 0;if(l)return{[e]:{pick:l,...i?{words:i}:{}}};if(t.kind==="skip")return{[e]:{pick:qo,...i?{words:i}:{}}}}return null}function jk(e){var t;return(e==null?void 0:e.pick)===qo?[_J,(t=e.words)==null?void 0:t.trim()].filter(Boolean).join(", "):Li("signature",e)}function Li(e,t){var a,i;if(!t)return null;const n=t.pick&&t.pick!==qo?(a=co(e,t.pick))==null?void 0:a.words:void 0,r=(i=t.words)==null?void 0:i.trim();return n&&r?`${n}, ${r}`:n??r??null}const Ak=e=>e?`, ${TJ}`:"";function XJ(e){var l,u,f,h,p,g,v;if(((l=e.source)==null?void 0:l.door)==="words"){const w=(e.source.text??"").trim(),y=Li("world",e.world),x=Li("light",e.light)??(VN(w).light?null:((f=co("world",(u=e.world)==null?void 0:u.pick))==null?void 0:f.light)??null),k=jk(e.signature),S=[y,Li("surface",e.surface),x,k].filter(Boolean);return S.length?`${w.replace(/[.\s]+$/,"")}, ${S.join(", ")}${Ak(k)}.`:w}if(((h=e.source)==null?void 0:h.door)!=="guided")return"";const t=Li("world",e.world),n=Li("light",e.light)??((g=co("world",(p=e.world)==null?void 0:p.pick))==null?void 0:g.light)??null,r=jk(e.signature),i=`${[t??"a place",Li("surface",e.surface),n,r].filter(Boolean).join(", ").replace(/^./,w=>w.toUpperCase())}${Ak(r)}.`;return(v=e.world)!=null&&v.pick?`${i.slice(0,-1)}. ${Ne.worldIsAStart}`:i}function QJ(e){var t,n,r;return((t=e.source)==null?void 0:t.door)==="shot"?e.shot?[e.shot.hash]:[]:((n=e.source)==null?void 0:n.door)==="photos"&&((r=e.photos)!=null&&r.done)?e.photos.hashes:[]}const JJ={answers:{},revision:0,editing:null,held:null,asides:[]};function eee(e,t){var n;switch(t.type){case"answer":{const r=zv(e.answers,t.patch);return L6(r,e.answers)?{...e,answers:r,revision:e.revision+1,editing:null,held:null}:{...e,editing:null,held:null}}case"photos":{if(((n=e.answers.source)==null?void 0:n.door)!=="photos")return e;const r=[...new Set(t.hashes)].slice(0,4),a=e.editing==="photos";return{...e,answers:{...e.answers,photos:{hashes:r,done:a}},revision:e.revision+1}}case"edit":return Vv(t.id,e.answers)?{...e,editing:t.id,held:e.answers}:e;case"cancel-edit":return!e.held||!L6(e.held,e.answers)?{...e,editing:null,held:null}:{...e,answers:e.held,revision:e.revision+1,editing:null,held:null};case"aside":return{...e,asides:[...e.asides,t.aside].slice(-40)}}}const tee=e=>({answers:e.answers,revision:e.revision,asides:e.asides}),nee=/^[a-f0-9]{32}$/,Nk=/^[\w.:-]{1,80}$/;function ree(e){const t=e;if(!t||typeof t!="object"||typeof t.answers!="object"||!t.answers)return null;const n={},r=t.answers.source;r&&["photos","shot","guided","words"].includes(r.door)&&(n.source={door:r.door,...typeof r.text=="string"?{text:r.text.slice(0,400)}:{}});const a=t.answers.photos;a&&Array.isArray(a.hashes)&&(n.photos={hashes:a.hashes.filter(u=>typeof u=="string").slice(0,4),done:!!a.done});const i=t.answers.shot;if(i&&typeof i.id=="string"&&Nk.test(i.id)&&typeof i.hash=="string"&&nee.test(i.hash)){const u=i.scene,f=u&&typeof u.id=="string"&&Nk.test(u.id)&&typeof u.name=="string"?{id:u.id,name:u.name.slice(0,120)}:void 0;n.shot={id:i.id,hash:i.hash,...f?{scene:f}:{}}}t.answers.reuse==="read"&&(n.reuse="read");for(const u of Af){const f=t.answers[u];if(!f||typeof f!="object")continue;const h=typeof f.pick=="string"&&(f.pick===qo||co(u,f.pick))?f.pick:void 0,p=typeof f.words=="string"?f.words.slice(0,200):void 0;(h||p)&&(n[u]={...h?{pick:h}:{},...p?{words:p}:{}})}const l=Array.isArray(t.asides)?t.asides.filter(u=>u&&typeof u.said=="string"&&typeof u.reply=="string"&&typeof u.at=="string").map(u=>({said:u.said,reply:u.reply,at:u.at,q:typeof u.q=="string"?u.q:null})):[];return{answers:zv({},n),revision:Number(t.revision)||0,editing:null,held:null,asides:l}}const UN=4,WN=800,Bv=60,KN={place:"",pictures:[],inputsRev:0,readRev:null,readTried:null,versions:[],current:-1,name:"",named:!1,job:null,error:null,saved:null,moreDeclined:!1,moreAsked:!1,setDrawn:!1,setDeclined:!1};function see(e){return{...KN,place:e.place,pictures:e.pictures,readRev:0,versions:[{reading:e.reading,hash:e.hash,coverage:[],how:"read"}],current:0,name:e.name,named:!0}}const Or=e=>e.versions[e.current]??null,Mk=e=>e.versions.some(t=>!!t.hash);function aee(e,t){return!t||e.job||e.inputsRev===0||e.readRev!==null&&e.readRev===e.inputsRev||e.readTried===e.inputsRev?null:e.inputsRev}const GN=e=>e.readRev!==null&&e.readRev!==e.inputsRev;function oee(e,t){var n,r,a;switch(t.type){case"inputs":{const i=t.place.slice(0,WN),l=[...new Set(t.pictures)].slice(0,UN);return i===e.place&&l.join()===e.pictures.join()?e:{...e,place:i,pictures:l,inputsRev:e.inputsRev+1}}case"name":return{...e,name:t.text.slice(0,Bv),named:!0};case"started":return e.job?e:{...e,job:{id:t.id,kind:t.kind,ask:t.ask,inputsRev:e.inputsRev,pending:null,coverage:[],phase:t.kind==="again"?"drawing":t.kind==="change"?"changing":"reading",since:t.since},readTried:t.kind==="make"?e.inputsRev:e.readTried,error:null};case"stopping":return!e.job||e.job.id!==t.id||e.job.stopping?e:{...e,job:{...e.job,stopping:!0}};case"progress":{if(!e.job||e.job.id!==t.job.id)return e;const i={...e.job,pending:t.job.reading??e.job.pending,coverage:t.job.coverage??e.job.coverage,phase:t.job.phase,since:t.job.phaseAt??e.job.since};return Rk({...e,job:i},i.pending)}case"finished":{if(!e.job||e.job.id!==t.job.id)return e;const i=e.job,l=t.job,u={...e,job:null};if(i.kind==="make"&&i.inputsRev!==e.inputsRev)return u;const f=l.reading??(i.kind==="again"?((n=Or(e))==null?void 0:n.reading)??null:null),h=l.status==="failed"?l.error??Ne.failed:null;if(l.status==="cancelled"){if(!f)return{...u,error:i.kind==="make"?Ne.stoppedRead:Ne.stopped};if(i.kind==="again"&&!l.hash)return{...u,error:Ne.stoppedDraw}}const p=l.status==="cancelled"&&i.kind==="change"&&!l.hash;if(!f||i.kind==="again"&&!l.hash)return{...u,error:h};const g=i.kind==="make"?"read":i.kind==="change"?"change":e.versions.some(S=>S.hash)?"again":"draw",v={reading:f,hash:l.hash,ask:i.kind==="change"?i.ask:void 0,coverage:(r=l.coverage)!=null&&r.length?l.coverage:i.kind==="again"?((a=Or(e))==null?void 0:a.coverage)??[]:[],how:g},w=Or(e),y=i.kind==="make"&&!l.hash&&w&&!w.hash&&w.how==="read",x=y?e.versions.map((S,E)=>E===e.current?v:S):[...e.versions,v],k={...u,versions:x,current:y?e.current:x.length-1,readRev:i.kind==="make"?i.inputsRev:e.readRev,error:p?Ne.stoppedChange:h};return Rk(k,f)}case"lost":return!e.job||e.job.id!==t.id?e:{...e,job:null,error:t.error};case"put-back":return e.job||!e.versions[t.index]?e:{...e,current:t.index};case"forget-record":return e.job||!e.versions.length?e:{...e,versions:[],current:-1,error:null};case"edit-words":{const i=Or(e);if(e.job||!i||!t.reading.prompt.trim()||JSON.stringify(t.reading)===JSON.stringify(i.reading))return e;const l=[...e.versions,{reading:t.reading,hash:i.hash,coverage:i.coverage,how:"edit"}];return{...e,versions:l,current:l.length-1}}case"error":return{...e,error:t.text};case"saved":return{...e,saved:t.id,error:null};case"decline-more":return{...e,moreDeclined:!0};case"ask-more":return{...e,moreAsked:!0};case"set-drawn":return{...e,setDrawn:!0,setDeclined:!1};case"set-declined":return{...e,setDeclined:!0}}}function Rk(e,t){return e.named||!(t!=null&&t.name)?e:{...e,name:t.name.slice(0,Bv)}}function iee(e){var n;const t=e.job?e.job.phase==="drawing"?e.job.pending:null:((n=Or(e))==null?void 0:n.reading)??null;return t?!e.job&&GN(e)?{can:!1,why:Ne.stillReading,words:t}:e.name.trim()?{can:!0,why:null,words:t}:{can:!1,why:Ne.nameIt,words:t}:{can:!1,why:e.job?Ne.stillReading:null,words:null}}const Yg=e=>e.job?e.job.phase==="changing"?Ne.changing:e.job.phase==="drawing"?Ne.drawing:e.pictures.length?Ne.readingPhotos:Ne.reading:void 0;function lee(e){var r;const t=new Map;e.versions.forEach((a,i)=>{a.hash&&t.set(a.hash,i)});const n=((r=Or(e))==null?void 0:r.hash)??null;return[...t.entries()].sort((a,i)=>a[1]-i[1]).map(([a],i)=>({n:i+1,hash:a,current:a===n}))}const cee=(e,t)=>e.versions.slice(0,t+1).filter(n=>!!n.hash).length,uee=(e,t)=>e.versions.map(n=>n.hash).lastIndexOf(t);function dee(e){const t=[{label:Ne.placeLabel,text:e.prompt}];return e.lighting&&t.push({label:Ne.lightLabel,text:e.lighting}),e.camera&&t.push({label:Ne.cameraLabel,text:e.camera}),e.figure&&t.push({label:Ne.figureLabel,text:e.figureTreatment?`${Pk(e.figure)}, ${Pk(e.figureTreatment)}.`:e.figure}),t}const Pk=e=>e.replace(/[.\s]+$/,""),fee=/\b(presenters?|models?|influencers?|celebrit(y|ies)|actors?|actress(es)?)\b/i,hee=/\b(my|our|the|a|an)\s+(\w+\s+)?(products?|bottles?|serum|perfume|shoes?|bag|jar|packaging|package|logos?|brand|brand name|wordmark)\b/i,pee=/\b(add|put|place|include|show|feature|with|holding|wearing|sitting|standing)\b/i,mee=/\b(no|without|remove|removing|empty|nobody|none|take out|get rid of|less)\b/i,gee=/^\s*(undo|go back|revert|back to|previous|the (first|last|previous|old|earlier) (one|version))\b/i,vee=/^\s*(hi|hello|hey|thanks|thank you|ok|okay|cool|nice|great|good|wow|yes|no)\b[\s!.]*$/i,wee=/^(?:please\s+)?(?:(?:call|name)\s+(?:it|this|the\s+scene)|rename(?:\s+(?:it|this|the\s+scene))?)\s+(?:to\s+|as\s+)?["'\u201c\u2018]?(.+?)["'\u201d\u2019]?[.!]?$/i,YN=e=>{var t,n;return((n=(t=wee.exec(e.trim()))==null?void 0:t[1])==null?void 0:n.trim())||null};function yee(e){const t=e.trim(),n=YN(t);return n?{kind:"rename",name:n}:gee.test(t)?{kind:"navigate",say:Ne.usePutBack}:vee.test(t)||/\?\s*$/.test(t)&&!/\b(make|can you|could you|try)\b/i.test(t)?{kind:"chatter",say:Ne.sayAChange}:(fee.test(t)||hee.test(t))&&pee.test(t)&&!mee.test(t)?{kind:"refuse",say:Ne.notInAScene}:{kind:"change"}}const bee=(e,t)=>{var n;return!!((n=Or(e))!=null&&n.ask)&&Or(e).ask.trim().toLowerCase()===t.trim().toLowerCase()},qN=e=>!e.saved&&(e.versions.length>0||!!e.job||!!e.error),xee=(e,t)=>e.saved?!1:t?e.versions.length>t.versions.length||e.current!==t.current||e.place!==t.place||e.pictures.join()!==t.pictures.join()||e.name!==t.name||!!e.job:!!(e.place.trim()||e.pictures.length||e.versions.length||e.job),XN=1;function kee(e){return JSON.stringify({v:XN,...e})}function See(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||t.v!==XN)return null;const n=u=>Array.isArray(u)?u.filter(f=>typeof f=="string"):[],r=u=>!!u&&typeof u.prompt=="string"&&typeof u.name=="string",a=Array.isArray(t.versions)?t.versions.filter(u=>u&&r(u.reading)).map(u=>({reading:u.reading,hash:typeof u.hash=="string"?u.hash:null,ask:typeof u.ask=="string"?u.ask:void 0,coverage:n(u.coverage),how:["read","draw","again","change","edit"].includes(u.how)?u.how:u.hash?"draw":"read"})):[],i=t.job&&typeof t.job.id=="string"&&["make","again","change"].includes(t.job.kind)?{id:t.job.id,kind:t.job.kind,ask:typeof t.job.ask=="string"?t.job.ask:void 0,inputsRev:Number(t.job.inputsRev)||0,pending:r(t.job.pending)?t.job.pending:null,coverage:n(t.job.coverage),phase:["reading","changing","drawing"].includes(t.job.phase)?t.job.phase:null,since:typeof t.job.since=="string"?t.job.since:null,...t.job.stopping===!0?{stopping:!0}:{}}:null,l=Number.isInteger(t.current)&&t.current>=-1&&t.current<a.length?t.current:a.length-1;return{place:typeof t.place=="string"?t.place.slice(0,WN):"",pictures:n(t.pictures).slice(0,UN),inputsRev:Number(t.inputsRev)||0,readRev:t.readRev===null||t.readRev===void 0?null:Number(t.readRev),readTried:t.readTried===null||t.readTried===void 0?null:Number(t.readTried),versions:a,current:l,name:typeof t.name=="string"?t.name.slice(0,Bv):"",named:!!t.named,job:i,error:typeof t.error=="string"?t.error:null,saved:typeof t.saved=="string"&&t.saved?t.saved:null,moreDeclined:t.moreDeclined===!0,moreAsked:t.moreAsked===!0,setDrawn:t.setDrawn===!0,setDeclined:t.setDeclined===!0}}function Eee(e){if(!e||e.loading)return"";const t=e.items.length;return t?Ne.shotCount(t,e.more):e.error?Ne.shotsFailed:e.query.trim()?Ne.shotNotFound(e.query.trim()):Ne.shotNone}function Lk(e){var n;const t=(n=e==null?void 0:e.tokens)==null?void 0:n.find(r=>(r==null?void 0:r.t)==="template");return typeof(t==null?void 0:t.id)=="string"&&t.id?t.id:typeof(e==null?void 0:e.templateId)=="string"&&e.templateId?e.templateId:null}function Cee(e){return dee(e).map(t=>t.label===Ne.placeLabel?t.text:`${t.label}: ${t.text.replace(/[.\s]+$/,"")}.`).join(" ")}const jee=new Set([Ne.stopped,Ne.stoppedRead,Ne.stoppedDraw,Ne.stoppedChange,Ne.lost]),Tk=e=>jee.has(e)?e:Ne.failedFirst(e.replace(/[.\s]+$/,""));function $k(e,t,n,r,a){var y,x,k,S,E,j,N,P,$,M,C,R,T,H;const i=t.answers,l=n?{reopened:!0}:{};if(e==="source")return{id:e,kind:"choice",prompt:Ne.source,options:[{id:"photos",label:Ne.addPictures},{id:"guided",label:Ne.guideMe}],given:((y=i.source)==null?void 0:y.door)==="words"?void 0:((x=i.source)==null?void 0:x.door)==="shot"?"photos":(k=i.source)==null?void 0:k.door,note:((S=i.source)==null?void 0:S.door)==="words"?i.source.text:void 0,...l};if(e==="photos")return{id:e,kind:"photos",prompt:Ne.photos,hashes:((E=i.photos)==null?void 0:E.hashes)??[],max:4,busy:r>0,submit:Ne.readThem,back:Ne.guideInstead,drop:Ne.photosDrop,...l,...a&&a.any!==!1&&!((j=i.photos)!=null&&j.hashes.length)&&r===0&&!n?{instead:Ne.fromShot,...a.any===null?{insteadWaiting:!0}:{}}:{}};if(e==="shot"){const D=(a==null?void 0:a.query.trim())??"";return{id:e,kind:"pick",prompt:Ne.shot,items:(a==null?void 0:a.items)??[],given:(N=i.shot)==null?void 0:N.id,search:{label:Ne.shotSearch,value:(a==null?void 0:a.query)??""},more:(a==null?void 0:a.more)??!1,loading:(a==null?void 0:a.loading)??!1,empty:a!=null&&a.error?Ne.shotsFailed:D?Ne.shotNotFound(D):Ne.shotNone,status:Eee(a),back:n?void 0:Ne.backToPictures,...l}}if(e==="reuse"){const D=(($=(P=i.shot)==null?void 0:P.scene)==null?void 0:$.name)??"";return{id:e,kind:"choice",prompt:Ne.madeIn(D),options:[{id:"use",label:Ne.takeScene(D)},{id:"read",label:Ne.readNew}],given:i.reuse,...l}}const u=i[e],f=e==="light"?(C=co("world",(M=i.world)==null?void 0:M.pick))==null?void 0:C.light:void 0,h=e==="surface"&&!!co("world",(R=i.world)==null?void 0:R.pick),p=(u==null?void 0:u.pick)===qo||u==null?void 0:u.pick,g=(u==null?void 0:u.pick)===qo,v=u==null?void 0:u.words,w=((T=i.source)==null?void 0:T.door)==="words";return{id:e,kind:"swatches",prompt:QN(e,i),row:IJ(e,(H=i.world)==null?void 0:H.pick),layout:e==="world"?"grid":void 0,hint:e==="world"&&!w?Ne.worldHint:void 0,skip:f?Ne.keepWorldLight:h?Ne.keepWorldSurface:e==="signature"&&!w?Ne.suggestOne:w?Ne.leaveToReading:Ne.skip,describe:Ne.describeInstead,given:p,skipped:g,note:v,...l}}function QN(e,t){var r,a,i;const n=e==="light"?(a=co("world",(r=t.world)==null?void 0:r.pick))==null?void 0:a.light:void 0;if(n)return Ne.worldLightPrompt(n);if(((i=t.source)==null?void 0:i.door)==="words"){if(e==="world")return Ne.followWorld;if(e==="light")return Ne.followLight}return Xi[e].prompt}function Aee(e,t){var n,r;return e==="source"?Ne.source:e==="photos"?Ne.photos:e==="shot"?Ne.shot:e==="reuse"?Ne.madeIn(((r=(n=t.shot)==null?void 0:n.scene)==null?void 0:r.name)??""):QN(e,t)}function Nee(e,t){var f,h,p,g,v,w,y,x,k,S,E;if(e==="source")return((f=t.source)==null?void 0:f.door)==="words"?{text:t.source.text??""}:((h=t.source)==null?void 0:h.door)==="shot"?{text:Ne.fromShotAnswer}:{text:((p=t.source)==null?void 0:p.door)==="photos"?Ne.addPictures:Ne.guideMe};if(e==="shot")return{text:Ne.shotAnswer,photos:t.shot?[t.shot.hash]:[]};if(e==="reuse")return{text:Ne.readNew};if(e==="photos"){const j=((g=t.photos)==null?void 0:g.hashes.length)??0;return{text:`${j} ${j===1?"picture":"pictures"}`,photos:(v=t.photos)==null?void 0:v.hashes}}const n=t[e],r=e==="light"&&(n==null?void 0:n.pick)===qo&&((y=co("world",(w=t.world)==null?void 0:w.pick))==null?void 0:y.light),a=e==="surface"&&(n==null?void 0:n.pick)===qo&&!!co("world",(x=t.world)==null?void 0:x.pick),i=r?Ne.keepWorldLight:a?Ne.keepWorldSurface:((k=t.source)==null?void 0:k.door)==="words"?Ne.leaveToReading:e==="signature"?Ne.suggestOne:Ne.skip,l=(n==null?void 0:n.pick)===qo?i:(S=co(e,n==null?void 0:n.pick))==null?void 0:S.label,u=(E=n==null?void 0:n.words)==null?void 0:E.trim();return{text:l&&u?`${l}, ${u}`:u??l??""}}const Dk=(e,t)=>e.at<t.at?-1:e.at>t.at?1:0,Mee=e=>{const t=Or(e);return t?`${t.hash?"decide":"agree"}-${e.current}`:null};function Ree(e){var v,w,y,x;const{setup:t,studio:n,edit:r}=e,a=t.answers,i=[],l=new Set,u=k=>{for(const S of t.asides.filter(E=>E.q===k&&!l.has(E)).sort(Dk))l.add(S),i.push(...ri(S))};r?i.push({kind:"scenri",id:"edit-open",text:Ne.editOpen(r.name)}):i.push({kind:"you",id:"intent",text:Ne.intent});const f=r?null:zN(a);if(!r)for(const k of YJ(a)){if(i.push({kind:"scenri",id:`asked-${k}`,text:Aee(k,a),quiet:!0}),u(k),t.editing===k){i.push({kind:"question",question:$k(k,t,!0,e.uploading,e.shots)});continue}const S=Nee(k,a);i.push({kind:"you",id:k,text:S.text,photos:S.photos,editable:!n.job&&!n.saved})}const h=n.versions.findIndex(k=>!!k.hash);n.versions.forEach((k,S)=>{if(k.how==="read"&&S>0&&i.push({kind:"scenri",id:`reread-${S}`,text:Ne.readAgain}),k.how==="change"&&i.push({kind:"you",id:`ask-${S}`,text:k.ask??""}),k.hash&&(k.how==="draw"&&i.push({kind:"you",id:`draw-${S}`,text:Ne.draw}),k.how==="again"&&i.push({kind:"you",id:`again-${S}`,text:Ne.tryAgain}),S===h&&!r&&Hk(i,e),i.push({kind:"scenri",id:`pic-${S}`,text:k.how==="change"?Ne.changed:k.how==="again"?Ne.again:Ne.here,thumb:k.hash,label:Ne.version(cee(n,S)),view:"scene",current:S===n.current,restore:S===n.current||n.saved?void 0:{view:"scene",hash:k.hash}})),S===n.current)for(const[E,j]of k.coverage.entries())i.push({kind:"scenri",id:`cover-${S}-${E}`,text:j});u(`agree-${S}`),u(`decide-${S}`)});const p=n.job;(p==null?void 0:p.kind)==="again"&&i.push({kind:"you",id:`pending-${p.id}`,text:h<0?Ne.draw:Ne.tryAgain}),(p==null?void 0:p.kind)==="change"&&i.push({kind:"you",id:`pending-${p.id}`,text:p.ask??""}),(p==null?void 0:p.kind)==="again"&&h<0&&!r&&Hk(i,e),n.saved&&Pee(i,e);let g=null;if(f)g=$k(f,t,!1,e.uploading,e.shots);else if(p){if(p.kind==="again"&&h<0&&!n.named&&!e.editingName){const k=((w=p.pending??((v=Or(n))==null?void 0:v.reading))==null?void 0:w.name)??n.name;g={id:"name",kind:"text",prompt:Ne.name,starters:k?[{label:k,text:k}]:void 0}}}else if(n.saved)g=Lee(e);else{const k=Or(n);if(e.stale&&!r)n.error&&(g={id:"retry",kind:"confirm",tone:"alert",prompt:Tk(n.error),options:[{id:"retry",label:Ne.retry}]});else if(!k&&n.error)g={id:"retry",kind:"confirm",tone:"alert",prompt:Tk(n.error),options:[{id:"retry",label:Ne.retry}]};else if(k){n.error&&i.push({kind:"scenri",id:`error-${n.versions.length}`,text:n.error,tone:"alert"});const S=Cee(k.reading);if(k.hash)g={id:`decide-${n.current}`,kind:"confirm",prompt:(r?Ne.decideEdit:Ne.decide)(n.name.trim()||k.reading.name),quote:S,quoteLabel:Ne.readingHead,options:[{id:"use",label:r?Ne.saveChanges:Ne.use},...e.canDraw?[{id:"again",label:Ne.tryAgain}]:[]],describe:Ne.changeSomething};else{const E=!r&&((y=a.source)==null?void 0:y.door)==="photos",j=!r&&((x=a.source)==null?void 0:x.door)==="shot",N=j?[{id:"another-shot",label:Ne.anotherShot}]:[];g={id:`agree-${n.current}`,kind:"confirm",prompt:e.canDraw?k.how==="change"?Ne.agreeChanged:E?Ne.agreePhotos:j?Ne.agreeShot:Ne.agree:Ne.agreeBlind,quote:S,quoteLabel:Ne.readingHead,options:[...e.canDraw?[{id:"draw",label:Ne.draw}]:[{id:"use",label:r?Ne.saveChanges:Ne.saveWords}],...N]}}}}for(const k of t.asides.filter(S=>!l.has(S)).sort(Dk))i.push(...ri(k));return e.note&&i.push({kind:"scenri",id:`note-${e.note.length}-${e.note.slice(0,12)}`,text:e.note}),g&&i.push({kind:"question",question:g}),i}function Pee(e,t){const{studio:n,edit:r,set:a,canDraw:i}=t;if(e.push({kind:"you",id:"use",text:r?Ne.saveChanges:i?Ne.use:Ne.saveWords}),!a)return;const l=a.tiles.length>0||a.running;e.push({kind:"scenri",id:"saved",text:l?Ne.inUse(a.who):a.read&&a.noSubject&&i?Ne.noLibrary:a.read&&i&&a.first.length?Ne.savedQuiet:Ne.saved}),(n.setDrawn||n.setDeclined)&&e.push({kind:"you",id:"set-start",text:n.setDrawn?a.stale?Ne.drawThemAgain:Ne.drawThem:Ne.notNow});const u=n.moreAsked?Ne.addThem:n.moreDeclined?Ne.notNow:null;let f=!1;const h=()=>{!u||f||(f=!0,e.push({kind:"you",id:"more",text:u}))};for(const p of a.tiles)p.role!=="hero"&&p.role!=="close"&&h(),p.state==="shown"&&p.hash?e.push({kind:"scenri",id:`ex-${p.role}-${p.hash}`,text:Ne.exampleHere[p.role],thumb:p.hash,label:tc[p.role],view:p.role,...a.running||n.job?{}:{retry:p.role}}):p.state==="failed"&&e.push({kind:"scenri",id:`ex-failed-${p.role}`,text:Ne.exampleFailed(tc[p.role],p.error??Ne.failed),tone:"alert"});h()}function Lee(e){var l;const{set:t,studio:n}=e,r=n.name.trim()||((l=Or(n))==null?void 0:l.reading.name)||"The scene";if(!t||t.running||!t.read)return null;if(e.canDraw&&t.first.length&&!n.setDrawn&&!n.setDeclined)return{id:"set-start",kind:"confirm",prompt:t.stale?Ne.staleSet(t.first.length):Ne.showInUse(t.who,t.first.map(u=>tc[u])),options:[{id:"draw-set",label:t.stale?Ne.drawThemAgain:Ne.drawThem},{id:"not-now",label:Ne.notNow}]};const a=t.tiles.some(u=>u.role==="hero"&&u.state==="shown");if(e.canDraw&&a&&t.missing.length&&!n.moreDeclined&&!n.moreAsked)return{id:"set-more",kind:"confirm",prompt:Ne.more(t.missing.map(u=>tc[u])),options:[{id:"more",label:Ne.addThem},{id:"not-now",label:Ne.notNow}]};const i=t.tiles.filter(u=>u.state==="failed");return{id:"set-done",kind:"confirm",prompt:i.length?Ne.readyMissing(r):t.tiles.length?Ne.ready(r):Ne.readyUndrawn(r),options:[...i.length&&e.canDraw?[{id:"retry-failed",label:Ne.tryAgain}]:[],{id:"done",label:t.finish}]}}function Hk(e,t){if(!t.studio.named&&!t.editingName)return;e.push({kind:"scenri",id:"asked-name",text:Ne.name,quiet:!0});const n=!t.studio.saved;e.push({kind:"you",id:"name",text:t.studio.name,editable:n,editing:t.editingName||void 0})}function Tee(e,t){var l,u,f;const{setup:n,studio:r}=e,a=(h,p=!1)=>({target:{kind:"off",why:h},placeholder:"",label:Ne.lineLabel,action:Ne.send,working:p,attach:!1});if(r.saved)return a("",!!r.job||!!((l=e.set)!=null&&l.running));const i=n.editing;return i==="source"?To({kind:"source"},Ne.sourcePlaceholder,!0):i&&Kh(i)?To({kind:"row",id:i},Ne.rowPlaceholder(Sk(i))):i==="photos"?a(Ne.photosOff):i==="shot"?a(Ne.shotOff):i==="reuse"?a(Ne.reuseOff):!t&&!r.job&&n.answers.source&&!BN(n.answers)?To({kind:"source"},Ne.nothingSaidPlaceholder,!0):t?t.id==="source"?To({kind:"source"},Ne.sourcePlaceholder,!0):t.id==="photos"?{...a(Ne.photosOff),attach:!0}:t.id==="shot"?a(Ne.shotOff):t.id==="reuse"?a(Ne.reuseOff):Kh(t.id)?To({kind:"row",id:t.id},Ne.rowPlaceholder(Sk(t.id))):t.id==="name"?To({kind:"name"},Ne.namePlaceholder):t.id==="retry"?To({kind:"source"},Ne.nothingSaidPlaceholder,!0):t.id.startsWith("agree-")?e.canDraw?To({kind:"add"},e.edit?Ne.addPlaceholder:((u=n.answers.source)==null?void 0:u.door)==="photos"?Ne.keepPlaceholder:((f=n.answers.source)==null?void 0:f.door)==="shot"?Ne.keepShotPlaceholder:Ne.addPlaceholder):a(""):t.id.startsWith("decide-")?{...To({kind:"change"},Ne.changePlaceholder),action:Ne.change}:a(""):r.job?a("",!0):a("")}function To(e,t,n=!1){return{target:e,placeholder:t,label:t,action:Ne.send,working:!1,attach:n}}const $ee=/\b(studio|room|lobby|hall|beach|forest|desert|street|city|kitchen|bathroom|bedroom|office|garden|park|field|mountain|shore|sea|ocean|lake|river|cave|rooftop|roof|terrace|warehouse|loft|gallery|museum|church|hotel|restaurant|caf[eé]|bar|shop|store|market|set|stage|backdrop|wall|floor|marble|concrete|wood|stone|light|dusk|dawn|night|sun|neon|fog|rain|snow|sand|water|glass|metal|plaster|fabric|interior|outdoors?|indoors?|landscape|pool|library|station|tunnel|bridge|corridor|courtyard|balcony|window|sky|cyclorama|cyc|seamless|brutalist|minimal)\b/i,JN=e=>$ee.test(e)||e.trim().split(/\s+/).length>=5&&!/\?\s*$/.test(e);function Ok(e,t){switch(e){case"greeting":case"ack":return t==="source"?Ne.greet:Ne.greetRow;case"question":case"help":return Ne.askHelp;case"nav":return Ne.startOverIsUp;case"go":return t==="source"?Ne.goFirst:Ne.greetRow;default:return Ne.notAPlace}}function Ik(e,t){if(t==="source"){const r=Vo(e,JN);return r==="vague"?null:r}const n=Vo(e,()=>!1);return n==="vague"||n==="intent"||n==="likeness"?null:n}const eM=2;function Dee(e,t){return JSON.stringify({v:eM,setup:tee(e),studio:kee(t)})}function tM(e){if(!e)return null;try{const t=JSON.parse(e);return(t==null?void 0:t.v)!==eM?null:{setup:ree(t.setup),studio:See(typeof t.studio=="string"?t.studio:null)}}catch{return null}}const nM=e=>`scenri:scene-studio:${e}:`;function Hee(e,t){var f,h,p;if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(n!=null&&n.sceneId)return null;const r=tM(typeof(n==null?void 0:n.session)=="string"?n.session:null),a=r==null?void 0:r.studio;if(!a||!qN(a))return null;const i=[a.versions[a.current],...[...a.versions].reverse()].find(g=>g==null?void 0:g.hash),l=Or(a),u=a.place.trim().split(/\s+/).slice(0,5).join(" ");return{convo:e,name:a.name.trim()||(l==null?void 0:l.reading.name)||((h=(f=a.job)==null?void 0:f.pending)==null?void 0:h.name)||u,hash:(i==null?void 0:i.hash)??null,drawing:!!a.job,failed:!a.job&&!!a.error,read:a.versions.length>0,jobId:((p=a.job)==null?void 0:p.id)??null,at:Number(n.at)||0}}function Oee(e,t){const n=new Map(t.filter(i=>i.kind==="scene").map(i=>[i.id.slice(6),i])),r=e.map(i=>{const l=i.jobId?n.get(i.jobId):void 0;return l?i.drawing?{...i,name:i.name||l.name,hash:l.status==="done"&&l.thumb?l.thumb:i.hash,drawing:l.status==="running",failed:l.status==="failed"}:i:{...i,drawing:!1}}),a=new Set(e.map(i=>i.convo));for(const i of t)i.kind!=="scene"||i.status!=="running"||!i.conversation||i.sceneId||a.has(i.conversation)||(a.add(i.conversation),r.push({convo:i.conversation,name:i.name,hash:null,drawing:!0,failed:!1,read:!1,jobId:i.id.slice(6),at:Date.parse(i.startedAt)||0}));return r.filter(i=>i.drawing||i.hash||i.failed||i.read).sort((i,l)=>l.at-i.at)}function Iee(e){return e.drawing?"Drawing":e.failed?"Did not finish":e.hash?"Drawn, not used yet":"Not drawn yet"}function gh(e){const t=nM(e);return cs.keys(t).map(n=>Hee(n.slice(t.length),cs.get(n))).filter(n=>!!n)}function Fee(e,t){const n=`${nM(e)}${t}`;cs.del(n),Ii(n)}function _ee(e,t,n,r){const a=PX(e,n)||e==="presenter"&&!!r;switch(e){case"first-shot":case"reuse":return t.onHub?{kind:"stay"}:a?{kind:"hub"}:{kind:"head"};case"refine":return t.onShot||t.onHub?{kind:"stay"}:a?{kind:"hub"}:{kind:"head"};case"presenter":return r||n.some(i=>i==="start"||i==="face"||i==="save")?t.onStudio?{kind:"stay"}:{kind:"studio"}:t.onStudio||t.onPresenters?{kind:"stay"}:a?{kind:"presenters"}:{kind:"head"};case"product":return a&&n.includes("product")?{kind:"dialog",asset:"product"}:t.onProducts?{kind:"stay"}:a?{kind:"products"}:{kind:"head"};case"scene":return a&&n.some(i=>i==="start"||i==="words"||i==="use")?t.onSceneStudio?{kind:"stay"}:{kind:"sceneStudio"}:t.onSceneStudio||t.onScenes?{kind:"stay"}:a?{kind:"scenes"}:{kind:"head"}}}function rM(){const{brand:e,recent:t,products:n}=on(),r=Dn(),a=ll(),i=!!un(ct.hub),l=!!un(ct.hubShot),u=!!un(ct.products),f=!!un(ct.scenes),h=!!un(ct.presenters),p=!!un(ct.presenterStudio),g=!!un(ct.sceneStudio);return s.useCallback(async v=>{var j,N;const w=t.find(P=>P.kind!=="root"&&P.status==="done"&&P.images.length>0),y=v==="refine"&&!w?"first-shot":v==="reuse"&&n.length===0?"product":v,x=fh().active;(x==null?void 0:x.task)===y&&x.brandId===e.id&&!x.paused||await Tl({start:{task:y,brandId:e.id}});const k=((N=(j=fh().progress)==null?void 0:j[y])==null?void 0:N.reached)??[],S=fh().activeDraftId,E=_ee(y,{onHub:i,onShot:l,onProducts:u,onScenes:f,onPresenters:h,onStudio:p,onSceneStudio:g},k,S);switch(E.kind!=="head"&&u6(),E.kind){case"stay":try{window.localStorage.removeItem(c6(e.id,y)),(y==="first-shot"||y==="reuse")&&window.localStorage.removeItem(Dj(e.id))}catch{}return(y==="first-shot"||y==="reuse")&&i?r(mr(e)):void 0;case"head":return Hj(e.id,y);case"hub":return r(mr(e));case"products":return r(Eu(e));case"scenes":return r(_u(e));case"presenters":return r(qi(e));case"studio":return r(zi(e,S));case"sceneStudio":{const P=gh(e.id).sort(($,M)=>M.at-$.at)[0];return r(Vi(e,(P==null?void 0:P.convo)??null))}case"dialog":return a(E.asset)}},[e,t,n,r,a,i,l,u,f,h,p,g])}const Zee=Number(window.localStorage.getItem("scenri:welcome-settle-ms")??900),Vee='[role="dialog"]:not(.sc-coach):not(.sc-attachpanel):not(.sc-swap), [role="alertdialog"], .sc-lightbox',zee=["settings","setup","new","whatsnew","learn","welcome"],Bee='[data-guide="compose"] .sc-attachpanel';function Uee(){var J,Oe,Be,Ve,Ge,me,_e;const e=lv(),t=pN(),n=Rn(),{brand:r,recent:a,subscribeActivity:i,products:l,importing:u}=on(),{tasks:f,builds:h}=Za(),{push:p}=or(),g=rM(),v=Dn(),[w]=el(),y=Ns("new"),x=!!un(ct.brand),k=!!un(ct.hub),S=((J=un(ct.hubShot))==null?void 0:J.params.shotId)??null,E=!!un(ct.presenterStudio),j=!!un(ct.sceneStudio),N=!!un(ct.products),P=!!un(ct.scenes),$=!!un(ct.presenters),M=e.active,C=M&&M.brandId===r.id?M.task:null,R=C&&!(M!=null&&M.paused)?C:null,T=R==="first-shot"||R==="reuse"?"generation":R==="refine"?"edit":null,H=e.loaded&&e.eligible&&e.welcome===null,[D,K]=s.useState(e.activeNodes);s.useEffect(()=>K(e.activeNodes),[e.activeNodes]),s.useEffect(()=>{if(!(!T||!M))return i(W=>K(pe=>xX(pe,W,M.since,T)))},[T,M,i]);const O=!!((Oe=t.composer)!=null&&Oe.busy),Z=s.useRef(!1),[te,B]=s.useState(!1);s.useEffect(()=>{Z.current&&!O&&T&&(B(!0),jg().finally(()=>B(!1))),Z.current=O},[O,T]);const[,F]=s.useState(0),X=s.useRef(0),z=s.useCallback(()=>{cancelAnimationFrame(X.current),X.current=requestAnimationFrame(()=>F(W=>W+1))},[]);s.useEffect(()=>{if(!R&&!H)return;const W=new MutationObserver(z);return W.observe(document.body,{childList:!0,subtree:H}),window.addEventListener("resize",z),()=>{cancelAnimationFrame(X.current),W.disconnect(),window.removeEventListener("resize",z)}},[R,H,z]);const[I,U]=s.useState(()=>!document.hidden);s.useEffect(()=>{const W=()=>U(!document.hidden);return document.addEventListener("visibilitychange",W),()=>document.removeEventListener("visibilitychange",W)},[]);const G=!!R||H,ne=zee.some(W=>w.has(W)),q=G&&(ne||[...document.querySelectorAll(Vee)].some(W=>!W.closest("[data-radix-popper-content-wrapper], .sc-shotsheet"))),le=w.get("new"),Se=R?`scenri:guide-begun:${r.id}:${R}`:null,[Q,xe]=s.useState(!1);s.useEffect(()=>{xe(!!Se&&window.localStorage.getItem(Se)==="1")},[Se]);const ee=s.useCallback(()=>{if(Se)try{window.localStorage.setItem(Se,"1")}catch{}xe(!0)},[Se]),ae=e.heading,re=W=>!!W&&(ae==null?void 0:ae.brandId)===r.id&&ae.task===W&&!q,_=W=>W==="first-shot"||W==="reuse"||W==="refine"?k:W==="product"?N:W==="scene"?P:W==="presenter"?$||E:!1,[ue,We]=s.useState(!1);s.useEffect(()=>{let W=!1;try{W=!!R&&window.localStorage.getItem(c6(r.id,R))==="1"}catch{}We(W)},[R,r.id,ae]),s.useEffect(()=>{if(!(!ae||ae.brandId!==r.id)&&_(ae.task)){try{window.localStorage.setItem(c6(r.id,ae.task),"1")}catch{}We(!0),(ae.task==="first-shot"||ae.task==="reuse")&&ee(),u6()}},[ae,k,N,P,$,E,r.id,ee]);const Xe=s.useRef(null);s.useEffect(()=>{const W=Xe.current;!W||_(W)||(Xe.current=null,Hj(r.id,W))},[k,N,P,$,E,r.id]),s.useEffect(()=>{e.loaded&&!C&&ae&&u6()},[e.loaded,C,ae]);let ze=null;if(R==="first-shot"||R==="reuse"){const W=((Be=t.composer)==null?void 0:Be.brandId)===r.id?t.composer:null,pe=k&&re(R),Ie={here:k&&!q,heading:re(R)&&!k,composer:W&&te?{...W,busy:!0}:W,nodes:D,begun:Q||pe||D.length>0};ze=R==="reuse"?iN(Ie):oN(Ie)}else if(R==="refine"){const W=((Ve=t.composer)==null?void 0:Ve.brandId)===r.id?t.composer:null,pe=!!S;ze=fX({here:pe||k&&!q,heading:re(R)&&!k&&!pe,open:pe,armed:k&&!!(W!=null&&W.refining),nodes:D,asking:pe?!!Rl(cN):!!Rl(Ih)})}else R==="presenter"?ze=uN({heading:re(R)&&!$&&!E,onPage:$&&!E&&!q,studio:E?t.studio:null}):R==="scene"?ze=pX({heading:re(R)&&!P&&!j,onPage:P&&!j&&!q,studio:j?t.studio:null}):R==="product"&&(ze=mX({heading:re(R)&&!N,onPage:N&&!q&&le!=="product",dialogOpen:le==="product"}));const tt=((Ge=t.composer)==null?void 0:Ge.brandId)===r.id?t.composer:null,ce=R==="first-shot"&&tt?lN(tt):R==="reuse"&&tt?tt.products===0?"product":tt.scene?null:"scene":null,ve=!!((me=t.composer)!=null&&me.pickerOpen);s.useEffect(()=>{ve&&(R==="first-shot"&&!ce?window.dispatchEvent(new Event("scenri:guide-close-picker")):ce&&window.dispatchEvent(new CustomEvent("scenri:guide-picker",{detail:{tab:Hx[ce]}})))},[R,ve,ce]),s.useEffect(()=>{R==="first-shot"&&!ce&&window.dispatchEvent(new CustomEvent("scenri:guide-picker",{detail:{tab:null}}))},[R,ce]),s.useEffect(()=>{if(R)return document.documentElement.dataset.guideTask=R,()=>{delete document.documentElement.dataset.guideTask}},[R]);const Pe=(ze==null?void 0:ze.point)===Bee&&window.innerWidth<1024;if(s.useEffect(()=>{if(Pe)return document.documentElement.dataset.guidePicker="",()=>{delete document.documentElement.dataset.guidePicker}},[Pe]),R&&ze&&ze.voice!=="quiet"){const W=LX(R,ze.id);W&&(ze={...ze,...W})}const de=R&&ze&&ze.voice!=="quiet"?ze.id:null,je=s.useRef("");s.useEffect(()=>{var pe,Ie;if(!R||!de)return;const W=`${R}:${de}`;je.current!==W&&(je.current=W,!((Ie=(pe=e.progress)==null?void 0:pe[R])!=null&&Ie.reached.includes(de))&&Tl({reached:{task:R,moment:de}}))},[R,de,e.progress]);const Ue=ze,ye=s.useRef(new Set),Ee=s.useCallback(W=>{ye.current.add(W),Tl({finish:W})},[]),be=s.useCallback(W=>{Tl({dismiss:W}),p({kind:"info",title:"Guide closed",detail:"Continue it any time from Learn."})},[p]);s.useEffect(()=>{R==="first-shot"&&S&&D.some(W=>W.id===S&&W.status==="done"&&W.images>0)&&Ee("first-shot")},[R,S,D,Ee]),s.useEffect(()=>{R==="refine"&&S&&jg()},[R,S]);const Le=s.useRef(!1);s.useEffect(()=>{if(R!=="refine"){Le.current=!1;return}S?Le.current=!0:Le.current&&(Le.current=!1,Ee("refine"))},[R,S,Ee]);const Qe=C==="presenter"||C==="scene"||C==="product",Ke=h.filter(W=>!W.finished).length;s.useEffect(()=>{Qe&&jg()},[Qe,r,l.length,Ke,u]),s.useEffect(()=>{Qe&&e.counts&&vX(e,e.counts)&&Ee(M==null?void 0:M.task)},[Qe,e,M,Ee]);const nt=!!((_e=t.overlay)!=null&&_e.engaged);s.useEffect(()=>{if(!e.loaded||!e.eligible)return;const W={eligible:e.eligible,hidden:e.hidden,done:e.done,dismissed:e.dismissed,active:M},Ie=!!S&&nt&&a.some(Te=>Te.id===S&&Te.status==="done")&&B1("refine",W)?"refine":j&&B1("scene",W)?"scene":le==="product"&&B1("product",W)?"product":E&&B1("presenter",W)?"presenter":null;!Ie||ye.current.has(Ie)||(ye.current.add(Ie),Tl({start:{task:Ie,brandId:r.id}}))},[e,M,S,nt,a,le,E,j,r.id]);const[gt,Pt]=s.useState(""),Ut=s.useRef(Ue);Ut.current=Ue;const Nt=s.useCallback((W,pe)=>{if(Pt(""),pe)return;const Ie=Ut.current,Te=Ie?[Ie.title,Ie.body].filter(Boolean).join(". "):"";Te&&requestAnimationFrame(()=>Pt(Te))},[]),[cn,Fe]=s.useState(!1),pt=Ns("welcome"),it=pt.value!==null,St=x&&n.showcaseLoaded||k,xt=h.some(W=>!W.finished)||f.some(W=>W.state==="running"&&W.kind!=="catalog"),At=yX({onMainPage:x||k,eligible:e.eligible,welcome:e.welcome,ready:St&&!document.querySelector('[data-variant="skeleton"]'),visible:I,blocked:q,busy:xt});s.useEffect(()=>{if(!At)return;const W=window.setTimeout(()=>Fe(!0),Zee);return()=>window.clearTimeout(W)},[At]);const Kt=s.useMemo(()=>bX(n.showcase).map(W=>Wee(W.previewUrl)),[n.showcase]),et=n.engines.some(W=>W.available),mt=l.length>0,ot=Ue&&(Ue.voice==="ask"||Ue.voice==="note")?Ue:null,kn=ot!=null&&ot.shell?Rl(ot.shell):document.body,ut=ot!=null&&ot.point?Rl(ot.point):null,Gt=(ot==null?void 0:ot.live)??(ot!=null&&ot.point?[ot.point]:[]),Ft=Gt.map(W=>Rl(W)).filter(W=>!!W),en=((ot==null?void 0:ot.also)??[]).map(W=>Rl(W)).filter(W=>!!W),Jt=((ot==null?void 0:ot.lit)??[]).map(W=>Rl(W)).filter(W=>!!W),se=!!ot&&!!kn&&(!ot.point||!!ut)&&Ft.length===Gt.length,oe=ot&&!se?ot:null,we=cn||se;s.useEffect(()=>Zx(we),[we]),s.useEffect(()=>()=>Zx(!1),[]),s.useEffect(()=>{if(!oe)return;const W=(oe.shell?document.querySelector(oe.shell):null)??document.querySelector(".sc-feed")??document.body,pe=new MutationObserver(z);return pe.observe(W,{childList:!0,subtree:!0}),()=>pe.disconnect()},[oe==null?void 0:oe.id,oe==null?void 0:oe.shell,z]);const ge=W=>{R&&(W.done?Ee(R):be(R))};return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"sc-vh",role:"status","aria-live":"polite",children:gt}),ot&&se&&o.jsx(AQ,{id:ot.id,voice:ot.voice,target:ut,live:Ft,also:en,lit:Jt,side:ot.side??"top",beside:ot.beside,soft:ot.soft,container:kn,title:ot.title,body:ot.body,at:ot.at,of:ot.of,canBack:gX(R,ot.id,ue||!!(k&&re(R))),action:ot.start?{label:"Start"}:ot.done?{label:"Done"}:null,closeLabel:ot.done?"Close":"Close guide",onBack:()=>{const W=R?fN(R,ot.id):null;if(W){window.dispatchEvent(new CustomEvent("scenri:guide-take-back",{detail:{kind:W}})),window.dispatchEvent(new CustomEvent("scenri:guide-picker",{detail:{tab:Hx[W]}}));return}if(R==="presenter"&&(ot.id==="start"||ot.id==="face"||ot.id==="save"))return v(qi(r),{replace:!0});if((R==="product"||R==="scene")&&ot.id===R)return y.close();if(R==="refine"&&ot.id==="ask"){if(S)return v(mr(r),{replace:!0});window.dispatchEvent(new Event("scenri:guide-clear-refine"));return}if(ue&&R&&(ot.id==="new"||ot.id==="choose"||ot.id==="product"))return window.dispatchEvent(new Event("scenri:guide-close-picker")),Xe.current=R,v(mo(r))},onAction:()=>{if(ot.start)return ee();ot.done&&R&&Ee(R)},onClose:()=>ge(ot),onEscape:()=>ge(ot),onShown:Nt,onLost:z}),o.jsx($X,{open:cn||it,pictures:Kt,note:wu.note({engineReady:et,ownsProducts:mt}),onTake:()=>{const W=cn;Fe(!1),it&&pt.close(),W?Tl({welcome:"taken"}).then(()=>g("first-shot")):window.setTimeout(()=>void g("first-shot"),0)},onDecline:()=>{const W=cn;Fe(!1),it&&pt.close(),W&&Tl({welcome:"declined"})}})]})}function Rl(e){for(const t of document.querySelectorAll(e))if(t.getClientRects().length>0)return t;return null}function Wee(e){return`${e}${e.includes("?")?"&":"?"}w=320`}const Kee="lessons";function Gee(){var B;const e=Ns("learn"),t=e.value!==null,n=NX(e.value),r=wr(Ks),a=lv(),i=pN(),{brand:l,recent:u,products:f}=on(),h=rM(),[p,g]=s.useState(null);s.useEffect(()=>{t||!p||(g(null),h(p))},[t,p,h]);const v=s.useRef(!1),w=F=>{v.current=!0,g(F),e.close()},y=s.useRef(null);s.useEffect(()=>{t&&(y.current=d6.current,d6.current=null)},[t]);const x=()=>{const F=v.current;if(v.current=!1,F)return;const X=y.current==="help";requestAnimationFrame(()=>{var U;if(document.activeElement!==document.body)return;const z=X?".sc-help-btn":".sc-learn-btn",I=X?".sc-learn-btn":".sc-help-btn";(U=document.querySelector(z)??document.querySelector(I))==null||U.focus()})},k=!!un(ct.hub),S=!!un(ct.presenterStudio),E=!!un(ct.presenters),j=F=>{var X;return((X=a.heading)==null?void 0:X.brandId)===l.id&&a.heading.task===F},N=((B=a.active)==null?void 0:B.brandId)===l.id&&!a.active.paused?a.active.task:null,P=u.some(F=>F.kind!=="root"&&F.status==="done"&&F.images.length>0),$=F=>F.needs==="shot"&&!P||F.needs==="product"&&f.length===0?F.needs??null:null,M=F=>{var G,ne,q,le,Se,Q;const X=((ne=(G=a.progress)==null?void 0:G[F.id])==null?void 0:ne.reached)??[];if(N!==F.id)return Vx(F.id,X,null);const z=((q=i.composer)==null?void 0:q.brandId)===l.id?i.composer:null,I={here:k,heading:j(F.id),composer:k?z:null,nodes:a.activeNodes,begun:!0},U=F.id==="first-shot"?((le=oN(I))==null?void 0:le.id)??null:F.id==="reuse"?((Se=iN(I))==null?void 0:Se.id)??null:F.id==="presenter"?((Q=uN({heading:j("presenter"),onPage:E&&!S,studio:S?i.studio:null}))==null?void 0:Q.id)??null:null;return Vx(F.id,X,{moment:U,nodes:a.activeNodes,draft:!!a.activeDraftId})},C=F=>MX(F.id,a,l.id,M(F)),R=RX($i,C),T=n??R??$i[0],H=$i.filter(F=>C(F)==="done").length;s.useEffect(()=>{if(t)for(const F of Object.values(j6))new Image().src=F.wide},[t]);const D=s.useRef(null),K=s.useRef(new Map),O=s.useRef(null),Z=s.useRef(!1);s.useEffect(()=>{var z;const F=t&&!Z.current;if(Z.current=t,!t)return;const X=()=>{var I,U;(I=D.current)==null||I.focus({preventScroll:!0}),(U=D.current)==null||U.scrollIntoView({block:"nearest"})};r&&n?(O.current=n.id,X()):r&&O.current?(z=K.current.get(O.current))==null||z.focus({preventScroll:!0}):F&&X()},[t,r,n]);const te=(F,X)=>o.jsx(Yee,{lesson:F,state:C(F),at:M(F),blocked:$(F),describe:X,actionRef:D,onBegin:()=>w(F.id)});return o.jsx(Ts,{open:t,className:"sc-learn",maxWidth:"880px",described:!0,onDismiss:e.close,onCloseAutoFocus:x,children:r&&n?o.jsxs("div",{className:"sc-learn-level",children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx("button",{type:"button",className:"sc-newdlg-back",onClick:()=>e.set(Kee),"aria-label":"All lessons",children:o.jsx(ga,{size:15})}),o.jsx(ds,{className:"sc-newdlg-title",children:n.title}),o.jsx(Fk,{})]}),o.jsx("div",{className:"sc-newdlg-body sc-learn-body",children:te(n,!0)})]},`one-${n.id}`):o.jsxs("div",{className:"sc-learn-level",children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Learn"}),o.jsxs("span",{className:"sc-learn-count",children:[H," of ",$i.length," done"]}),o.jsx(Fk,{})]}),o.jsx(td,{className:"sc-vh",children:"Each one walks you through one real thing, a step at a time."}),o.jsxs("div",{className:"sc-newdlg-body sc-learn-body",children:[o.jsx("ul",{className:"sc-learn-list",children:$i.map(F=>o.jsx("li",{children:o.jsxs("button",{type:"button",className:"sc-learn-row","data-state":C(F),"aria-current":!r&&T.id===F.id?"true":void 0,ref:X=>{X?K.current.set(F.id,X):K.current.delete(F.id)},onClick:()=>e.set(F.id),children:[o.jsx("span",{className:"sc-learn-thumb",children:o.jsx("img",{src:j6[F.id].square,alt:"",decoding:"async"})}),o.jsxs("span",{className:"sc-learn-say",children:[o.jsx("span",{className:"sc-learn-name",children:F.title}),o.jsx(sM,{lesson:F,state:C(F),at:M(F),blocked:$(F)})]}),(R==null?void 0:R.id)===F.id&&o.jsx("span",{className:"sc-learn-next",children:"Next"})]})},F.id))}),!r&&te(T,!1)]})]},"all")})}function Yee({lesson:e,state:t,at:n,blocked:r,describe:a,actionRef:i,onBegin:l}){const u=r?C6[r].action:t==="active"?"Continue":t==="done"?"Start again":"Start",f=t==="active"?n:0,h=g=>t==="done"?"done":t==="active"?g<n?"done":g===n?"active":"todo":g===0?"active":"todo",p=a?o.jsx(td,{className:"sc-learn-summary",children:e.summary}):o.jsx("p",{className:"sc-learn-summary",children:e.summary});return o.jsxs("section",{className:"sc-learn-lesson","aria-label":e.title,children:[o.jsx("span",{className:"sc-learn-hero",children:o.jsx("img",{src:j6[e.id].wide,alt:"",decoding:"async"})}),o.jsxs("div",{className:"sc-learn-copy",children:[o.jsx("div",{className:"sc-learn-kicker",children:o.jsx(sM,{lesson:e,state:t,at:n,blocked:r})}),o.jsx("h3",{className:"sc-learn-title",children:e.title}),p,o.jsxs("div",{className:"sc-learn-do",children:[o.jsx("ol",{className:"sc-learn-steps",children:mN(e).map((g,v)=>{const w=h(v),y=o.jsx("span",{className:"sc-learn-n","aria-hidden":"true",children:w==="done"?o.jsx(Kn,{size:14,weight:"bold"}):v+1}),x=t==="active"&&v===n?"step":void 0,k=o.jsx("span",{className:"sc-learn-step-name",children:g});return o.jsx("li",{children:v===f?o.jsxs("button",{ref:i,type:"button",className:"sc-learn-step","data-state":w,"data-here":"","aria-current":x,"aria-label":`${u}: ${g}`,onClick:l,children:[y,k,o.jsxs("span",{className:"sc-learn-go","aria-hidden":"true",children:[u," ",o.jsx(Pa,{size:12,weight:"bold"})]})]}):o.jsxs("div",{className:"sc-learn-step","data-state":w,"aria-current":x,children:[y,k,w==="done"&&o.jsx("span",{className:"sc-vh",children:", done"})]})},g)})}),r&&o.jsx("p",{className:"sc-learn-note",children:C6[r].note})]})]})]})}function sM({lesson:e,state:t,at:n,blocked:r}){const a=mN(e).length;return t==="done"?o.jsxs("span",{className:"sc-learn-status","data-state":"done",children:[o.jsx("span",{className:"sc-learn-tick","aria-hidden":"true",children:o.jsx(Kn,{size:9,weight:"bold"})}),"Done"]}):t==="active"?o.jsxs("span",{className:"sc-learn-status","data-state":"active",children:["Step ",Math.min(n+1,a)," of ",a]}):r?o.jsx("span",{className:"sc-learn-status",children:C6[r].status}):o.jsxs("span",{className:"sc-learn-status",children:[a," step",a===1?"":"s"]})}function Fk(){return o.jsx(As,{children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx(jn,{size:16})})})}const aM=s.createContext(null),qee={products:[],productsLoaded:!1,importing:!1,refreshProducts:async()=>{}};function on(){const e=s.useContext(aM),t=ZA()??qee;if(!e)throw new Error("useBrand must be used inside BrandLayout");return s.useMemo(()=>({...e,...t}),[e,t])}const oM=s.createContext(null);function Xee(){const e=s.useContext(oM);if(!e)throw new Error("useAssetsPanel must be used inside BrandLayout");return e}function Qee(){const{brandSlug:e}=Bs(),{pathname:t,search:n}=Zn(),r=un({path:ct.brand,end:!1}),{brands:a,engines:i,refresh:l}=Rn(),[u,f]=s.useState(null),[h,p]=s.useState(null),[g,v]=s.useState([]),[w,y]=s.useState([]),[x,k]=s.useState({}),[S,E]=s.useState(!1),[j,N]=s.useState(0),P=s.useCallback(()=>N(Q=>Q+1),[]),$=Dn(),[M,C]=fa(Dr.assetsOpen,window.innerWidth>=1280),R=s.useCallback(()=>C(Q=>!Q),[]),T=s.useMemo(()=>({open:M,toggle:R,setOpen:C}),[M,R]);fY();const H=s.useRef(null),D=a.find(Q=>Q.slug===e)??a.find(Q=>Q.id===e)??a.find(Q=>Q.id===H.current)??null;D&&(H.current=D.id);const K=s.useRef(D==null?void 0:D.id);K.current=D==null?void 0:D.id;const O=s.useCallback(async()=>{if(!D)return;const Q=D.id,xe=await Re.workspace(Q);K.current===Q&&(f(xe.project),p(xe.root),v(xe.recent),y(xe.sets),k(xe.membership),E(!0))},[D==null?void 0:D.id]),Z=s.useRef(new Set),te=s.useCallback(Q=>(Z.current.add(Q),()=>{Z.current.delete(Q)}),[]),B=s.useCallback(Q=>{if(Q.length){v(xe=>oX(xe,Q));for(const xe of Z.current)xe(Q)}},[]),F=s.useCallback((Q,xe)=>{!D||Q!==D.id||B(xe)},[D==null?void 0:D.id,B]),X=s.useCallback(Q=>y(xe=>xe.map(ee=>ee.id===Q.id?Q:ee)),[]),z=s.useCallback(Q=>y(xe=>xe.filter(ee=>ee.id!==Q)),[]),I=s.useCallback(Q=>y(xe=>xe.some(ee=>ee.id===Q.id)?xe:[Q,...xe]),[]),U=s.useCallback((Q,xe)=>k(ee=>({...ee,[Q]:xe})),[]),G=s.useMemo(()=>D?{brand:D,workspace:u,root:h,recent:g,sets:w,membership:x,loaded:S,refresh:O,applySet:X,dropSet:z,insertSet:I,applyMembership:U,applyNodes:B,subscribeActivity:te,shotsEpoch:j,resetShots:P}:null,[D,u,h,g,w,x,S,O,X,z,I,U,B,te,j,P]);s.useEffect(()=>{E(!1),v([]),p(null)},[D==null?void 0:D.id]),s.useEffect(()=>{D&&sB(D.id)},[D==null?void 0:D.id]),s.useEffect(()=>{O()},[O]);const ne=s.useCallback(()=>{l(),O()},[l,O]),q=r?t.slice(r.pathnameBase.length):"",le=!!D&&e!==D.slug,Se=D?mo(D)+q+n:"";if(s.useEffect(()=>{le&&$(Se,{replace:!0})},[le,Se,$]),!D){const Q=nN(a),xe=!!H.current&&!a.some(re=>re.id===H.current),ee=new URLSearchParams(n);xe&&(ee.delete("settings"),ee.delete("new"));const ae=ee.toString();return o.jsx(uo,{to:Q?mo(Q)+q+(ae?`?${ae}`:""):ct.root,replace:!0})}return o.jsxs(aM.Provider,{value:G,children:[o.jsx(_q,{engines:i,brandId:D.id,onSaved:ne}),o.jsx(Qq,{engines:i,onSaved:l}),o.jsx(Wq,{}),o.jsx(GK,{brand:D,onActivity:F,children:o.jsxs(hY,{brand:D,children:[o.jsx(nte,{}),o.jsx(eY,{children:o.jsxs(oM.Provider,{value:T,children:[o.jsxs("div",{className:"sc-shell",children:[o.jsx(uY,{}),o.jsx(uc,{}),o.jsx(cG,{})]}),o.jsx(Uee,{}),o.jsx(Gee,{}),o.jsx(EX,{})]})})]})})]})}function Jee(e){return!e.unread||e.spent||e.firstUse||!e.loaded||!e.visible||e.dialogOpen?!1:e.running===0&&e.builds===0}const ete=Number(window.localStorage.getItem("scenri:whatsnew-settle-ms")??2500)||2500,iM=s.createContext(null);function om(){const e=s.useContext(iM);if(!e)throw new Error("useWhatsNew must be used inside WhatsNewProvider");return e}function tte({children:e}){const[t,n]=s.useState(null),[r,a]=s.useState(null),[i,l]=s.useState(null),[u,f]=s.useState(null),[h,p]=s.useState(null),[g,v]=s.useState("loading"),[w,y]=s.useState(!1),x=Ns("whatsnew");s.useEffect(()=>{let $=!0;return Re.releaseNotes().then(M=>{$&&(n(M.version),a(M.entry),l(M.changelogUrl),f(M.releasesUrl??null),p(M.seen),v("ready"))}).catch(()=>{$&&v("failed")}),()=>{$=!1}},[]);const k=x.open,S=s.useCallback(()=>k(t??"latest"),[k,t]),E=s.useCallback(()=>{y(!0),S()},[S]),j=s.useCallback(()=>{!t||h===t||(p(t),Re.releaseSeen(t).catch(()=>{}))},[t,h]),N=t!==null&&h!==t&&r!==null&&r.sections.length>0,P=s.useMemo(()=>({status:g,version:t,entry:r,changelogUrl:i,releasesUrl:u,unread:N,open:S,autoOpenSpent:w,autoOpen:E,markSeen:j}),[g,t,r,i,u,N,S,w,E,j]);return o.jsx(iM.Provider,{value:P,children:e})}function nte(){var k;const e=om(),{running:t,builds:n}=Za(),{loaded:r}=on(),[a]=el(),[i,l]=s.useState(()=>!document.hidden),u=s.useRef(!1),f=lv(),h=AX(),p=f.eligible&&f.welcome===null,g=p||h||((k=f.active)==null?void 0:k.task)==="first-shot"&&!f.active.paused,v=!f.loaded||g;g&&(u.current=!0);const w=s.useRef(!1),{markSeen:y}=e;s.useEffect(()=>{p?w.current=!0:w.current&&(w.current=!1,y())},[p,y]),s.useEffect(()=>{const S=()=>l(!document.hidden);return document.addEventListener("visibilitychange",S),()=>document.removeEventListener("visibilitychange",S)},[]);const x=a.has("settings")||a.has("setup")||a.has("new")||a.has("whatsnew");return s.useEffect(()=>{if(!Jee({unread:e.unread,spent:u.current||e.autoOpenSpent,loaded:r,visible:i,dialogOpen:x,running:t,builds:n.length,firstUse:v}))return;const E=window.setTimeout(()=>{u.current=!0,e.autoOpen()},ete);return()=>window.clearTimeout(E)},[e,r,i,x,t,n.length,v]),null}const lM=s.createContext(null);function Rn(){const e=s.useContext(lM);if(!e)throw new Error("useAppData must be used inside AppShell");return e}function rte(){const e=DW(),[t,n]=s.useState(null),[r,a]=s.useState([]),[i,l]=s.useState(null),u=OW(),f=FW(),h=ZW(),p=zW(),g=s.useRef(0),v=s.useRef(new Map),w=s.useRef(0),y=s.useRef(!1),x=s.useCallback(N=>{v.current.set(N.id,++g.current),n(P=>P&&aK(P,N))},[]),k=s.useCallback(async()=>{const N=++g.current;w.current=N;const P=await Re.brands();if(w.current!==N)return;const $=new Set;for(const[M,C]of v.current)C>N&&$.add(M);n(M=>oK(M,P,$))},[]),S=s.useCallback(()=>k().catch(()=>{}),[k]),E=s.useCallback(async()=>{try{await Promise.all([k(),Re.engines().then(a)]),y.current=!0}catch(N){y.current||l(String(N.message??N))}},[k]);s.useEffect(()=>{E(),jW()},[E]);const j=s.useMemo(()=>t===null?null:{brands:t,engines:r,scenes:u.scenes,collections:u.collections,verticals:u.verticals,loaded:u.loaded,error:u.error,refetch:u.refetch,presenters:f.presenters,presenterCategories:f.categories,presenterStyles:f.styles,presentersLoaded:f.loaded,presentersError:f.error,refetchPresenters:f.refetch,demoProducts:h.demoProducts,demoProductCategories:h.categories,demoProductsLoaded:h.loaded,demoProductsError:h.error,showcase:p.showcase,showcaseCategories:p.categories,showcaseLoaded:p.loaded,showcaseError:p.error,refetchShowcase:p.refetch,refresh:E,refreshBrands:S,applyBrand:x},[t,r,u.scenes,u.collections,u.verticals,u.loaded,u.error,u.refetch,f.presenters,f.categories,f.styles,f.loaded,f.error,f.refetch,h.demoProducts,h.categories,h.loaded,h.error,p.showcase,p.categories,p.loaded,p.error,p.refetch,E,S,x]);return i?o.jsx(js,{align:"center",justify:"center",height:"100vh",p:"5",children:o.jsx(uv,{failure:{kind:"unknown",title:"Scenri could not read your library.",fix:"Check that it is still running, then reload.",raw:i,retryable:!0}})}):t===null?o.jsx(js,{align:"center",justify:"center",height:"100vh",children:o.jsx(xr,{size:"3"})}):o.jsx(lM.Provider,{value:j,children:o.jsx(Oj.Provider,{value:e,children:o.jsx(eK,{children:o.jsxs(tte,{children:[o.jsx(IS,{}),o.jsx(uc,{})]})})})})}function Ns(e){const[t,n]=el(),r=t.get(e),a=s.useCallback(u=>{n(f=>{const h=new URLSearchParams(f);return h.set(e,u),h},{replace:!1})},[e,n]),i=s.useCallback(u=>{n(f=>{const h=new URLSearchParams(f);return h.set(e,u),h},{replace:!0})},[e,n]),l=s.useCallback(()=>{n(u=>{const f=new URLSearchParams(u);return f.delete(e),f},{replace:!0})},[e,n]);return{value:r,open:a,set:i,close:l}}function G1(e,t=""){const[n,r]=el(),a=n.get(e)??t,i=s.useCallback(l=>{r(u=>{const f=new URLSearchParams(u);return l===null||l===t?f.delete(e):f.set(e,l),f},{replace:!0})},[e,t,r]);return[a,i]}function _k(e,t){const n=Zk(t.name),r=Vk(t.url);return!n&&!r?null:e.find(a=>{var i,l,u,f;return!!(r&&Vk((l=(i=a.json)==null?void 0:i.meta)==null?void 0:l.website)===r||n&&Zk(((f=(u=a.json)==null?void 0:u.meta)==null?void 0:f.name)??a.slug)===n)})??null}const Zk=e=>String(e??"").trim().replace(/\s+/g," ").toLowerCase()||null,Vk=e=>{const t=String(e??"").trim();if(!t)return null;const n=/^https?:\/\//i.test(t)?t:`https://${t}`;try{return new URL(n).hostname.toLowerCase().replace(/^www\./,"")||null}catch{return null}};function ste(e){const t=e.name.source==="hostname"?{key:"name",found:!1,label:"Name",value:`taken from the address (${e.host})`}:{key:"name",found:!0,label:"Name",value:e.name.value},n=e.logo.status==="primary"?{key:"logo",found:!0,label:"Logo",value:"found on the site"}:e.logo.status==="alternate"?{key:"logo",found:!0,label:"Logo",value:"only a small mark, saved as an alternate"}:{key:"logo",found:!1,label:"Logo",value:"none found"},r=e.colors.count>0?{key:"colors",found:!0,label:"Colours",value:`${e.colors.count} taken from the site`}:{key:"colors",found:!1,label:"Colours",value:"none we could trust"};return[t,n,r]}function ate(e){return e.logo.status!=="primary"||e.colors.count===0||e.name.source==="hostname"}const Kd=(e,t=!1)=>({key:"products",found:t,label:"Products",value:e});function ote(e){switch(e.kind){case"idle":return null;case"scanning":return Kd("looking for a shop");case"timeout":return Kd("this site took too long to search");case"error":return Kd("the search did not finish");case"result":{const{scan:t}=e;if(t.verdict==="none")return null;if(t.verdict==="found"){const n=t.countSource==="sitemap"&&t.count>20;return Kd(`${n?"about ":""}${t.count.toLocaleString()} found`,!0)}return Kd("we could not load the catalogue")}}}function ite(e){return e.kind==="timeout"||e.kind==="error"?!0:e.kind==="result"&&(e.scan.verdict==="blocked"||e.scan.verdict==="likely")}function lte(e){var t;return!e||e.verdict!=="found"?!1:e.candidates.length>0||(((t=e.cards)==null?void 0:t.length)??0)>0}function cte(e,t){const n=e.trim();if(n.length<=t)return n;const r=n.slice(0,t),a=r.lastIndexOf(" ");return`${(a>t*.6?r.slice(0,a):r).replace(/[\s,;:.]+$/,"")}...`}function ute(){var Se,Q,xe,ee,ae,re;const{brands:e,refresh:t}=Rn(),n=Dn(),r=e.length>0,[a,i]=s.useState(""),[l,u]=s.useState(""),[f,h]=s.useState(!1),[p,g]=s.useState(!1),[v,w]=s.useState(null),[y,x]=s.useState(null),[k,S]=s.useState(!1),[E,j]=s.useState(!1),[N,P]=s.useState(null),[$,M]=s.useState(null),[C,R]=s.useState(null),[T,H]=s.useState(null),D=s.useRef(!1),K=s.useRef(null),O=async(_,ue)=>{D.current=!0,K.current=null,x(_),await t(),n(`${mo(_)}${ue?`?settings=${ue}`:""}`,{replace:!0})};s.useEffect(()=>{const _=()=>{const ue=K.current;!ue||D.current||(K.current=null,fetch(`/api/brands/${ue}`,{method:"DELETE",keepalive:!0}).catch(()=>{}))};return window.addEventListener("pagehide",_),()=>{window.removeEventListener("pagehide",_),_()}},[]);const Z=async(_=!1)=>{var ue,We;if(!_){const Xe=_k(e,{url:a.trim()});if(Xe){H(Xe);return}}g(!0),w(null);try{const Xe=await Re.brandFromUrl(a);x(Xe),K.current=Xe.id,P(Xe.report),M(((ue=Xe.report)==null?void 0:ue.read)===!1&&((We=Xe.warnings)==null?void 0:We.slice(0,2).join(" "))||null),g(!1)}catch(Xe){w(String(Xe.message??Xe)),g(!1)}},te=async(_=!1)=>{if(!_){const ue=_k(e,{name:l});if(ue){H(ue);return}}g(!0),w(null);try{await O(await Re.createBrand({specVersion:"0.1",meta:{name:l.trim()||"Untitled brand"}}))}catch(ue){w(String(ue.message??ue)),g(!1)}},B=()=>n("/",{replace:!0}),{scan:F,scanning:X,outcome:z,retry:I}=LA((y==null?void 0:y.id)??null),U=ote(z),G=z.kind==="timeout"||z.kind==="error",ne=async _=>{var ue,We;if(y){R(null),j(!0);try{await Re.catalogImport(y.id,String(((We=(ue=y.json)==null?void 0:ue.meta)==null?void 0:We.website)??a),_)}catch{R("That did not start. Check your connection and try again."),j(!1);return}j(!1),S(!1),await O(y)}},q=y?Zs((Se=y.json)==null?void 0:Se.palette):[],le=y?Fr((Q=JK(y.json))==null?void 0:Q.file):null;return o.jsxs("div",{className:"sc-wiz",children:[o.jsxs("div",{className:"sc-wiz-form",children:[o.jsxs("div",{className:"sc-wiz-head",children:[o.jsxs("button",{type:"button",className:"sc-wiz-back",onClick:B,style:r?void 0:{visibility:"hidden"},children:[o.jsx(ga,{size:11})," Back"]}),o.jsx("span",{}),o.jsx("span",{})]}),o.jsxs("h1",{children:["Your ",o.jsx("em",{children:"brand"})]}),o.jsx("p",{className:"sc-wiz-sub",children:y&&N?o.jsxs(o.Fragment,{children:["Built from ",N.host,". Everything here can be changed later, from Settings."]}):o.jsx(o.Fragment,{children:"Paste a website and the kit builds itself: name, logo, palette. You can also start from nothing and fill it in later from Settings."})}),o.jsxs("div",{className:"sc-wiz-fields",children:[y?o.jsx("div",{style:{textAlign:"center"},children:X?o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"sc-wiz-cta",disabled:!0,children:[o.jsx(xr,{size:"1"})," Looking for products"]}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>void O(y),children:"Skip and add the brand only"})})]}):G?o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"sc-wiz-cta",onClick:I,children:["Look for products again ",o.jsx(Pa,{size:12})]}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>void O(y),children:"Continue without products"})})]}):lte(F)?o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"sc-wiz-cta",onClick:()=>S(!0),children:["Add brand and products ",o.jsx(Pa,{size:12})]}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>void O(y),children:"Just the brand"})})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"sc-wiz-cta",onClick:()=>void O(y),children:["Looks right ",o.jsx(Pa,{size:12})]}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>void O(y,"brand"),children:N&&ate(N)?"Finish the kit first":"Edit the kit first"})})]})}):f?o.jsxs(o.Fragment,{children:[o.jsx("label",{htmlFor:"sc-wiz-name",children:"Brand name"}),o.jsx("input",{id:"sc-wiz-name",className:"sc-in",placeholder:"Brand name",value:l,onChange:_=>{u(_.target.value),H(null)},onKeyDown:_=>_.key==="Enter"&&l.trim()&&!p&&void te()}),o.jsxs("div",{style:{textAlign:"center"},children:[o.jsx("button",{type:"button",className:"sc-wiz-cta",disabled:!l.trim()||p,onClick:()=>void te(),children:p?o.jsx(xr,{size:"1"}):o.jsxs(o.Fragment,{children:["Create it ",o.jsx(Pa,{size:12})]})}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>{h(!1),H(null)},children:"Build from a website instead"})})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("label",{htmlFor:"sc-wiz-url",children:"Website"}),o.jsx("input",{id:"sc-wiz-url",className:"sc-in",placeholder:"acme.com",value:a,onChange:_=>{i(_.target.value),H(null)},onKeyDown:_=>_.key==="Enter"&&a.trim()&&!p&&void Z()}),o.jsx("p",{className:"sc-wiz-hint",children:"We only read public pages. Nothing leaves this machine."}),o.jsxs("div",{style:{textAlign:"center"},children:[o.jsx("button",{type:"button",className:"sc-wiz-cta",disabled:!a.trim()||p,onClick:()=>void Z(),children:p?o.jsx(xr,{size:"1"}):o.jsxs(o.Fragment,{children:["Build the kit ",o.jsx(Pa,{size:12})]})}),o.jsx("div",{children:o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>{h(!0),H(null)},children:"Start from scratch instead"})})]})]}),T&&o.jsxs(J8,{color:"amber",mt:"3",size:"1",children:[o.jsxs(e6,{children:["You already have ",ca(T),". Creating another makes a second workspace with its own address."]}),o.jsxs("div",{style:{display:"flex",gap:10,marginTop:4,flexWrap:"wrap"},children:[o.jsxs("button",{type:"button",className:"sc-wiz-cta",onClick:()=>n(mo(T)),children:["Open ",ca(T)," instead"]}),o.jsx("button",{type:"button",className:"sc-wiz-skip",onClick:()=>{H(null),f?te(!0):Z(!0)},children:"Create anyway"})]})]}),v&&o.jsx(J8,{color:"red",mt:"3",size:"1",children:o.jsx(e6,{children:v})})]})]}),o.jsx("div",{className:"sc-wiz-preview",children:o.jsxs("div",{className:"sc-wiz-card",children:[o.jsx("div",{className:"sc-wiz-cap",children:y?"Your kit":p?`Reading ${a||"the site"}`:"Live kit preview"}),o.jsxs("div",{className:"sc-wiz-body",children:[p&&!y&&o.jsxs("div",{className:"sc-scrape-row",children:[o.jsx(xr,{size:"1"})," Reading the site and building the kit"]}),!p&&!y&&o.jsx("p",{style:{color:"var(--sc-fg3)",fontSize:12.5,margin:0},children:"The kit appears here as it is found."}),y&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:q.length?16:0},children:[o.jsx("span",{className:"sc-kit-logo",style:{width:44,height:44,padding:7,borderRadius:12},children:le?o.jsx("img",{src:le,alt:""}):o.jsx(Ws,{size:16,color:"var(--sc-fg3)"})}),o.jsxs("span",{children:[o.jsx("b",{dir:"auto",style:{fontFamily:"var(--sc-font-display)",fontSize:16},children:(ee=(xe=y.json)==null?void 0:xe.meta)==null?void 0:ee.name}),((re=(ae=y.json)==null?void 0:ae.meta)==null?void 0:re.tagline)&&o.jsx("small",{dir:"auto",style:{display:"block",color:"var(--sc-fg3)",fontSize:11.5},children:cte(String(y.json.meta.tagline),72)})]})]}),q.length>0&&o.jsx("div",{style:{display:"flex",gap:8},children:q.slice(0,5).map(_=>o.jsx("span",{style:{flex:1,height:44,borderRadius:9,border:"1px solid var(--sc-line)",background:_.hex}},_.hex))}),N&&o.jsx("ul",{className:"sc-kit-lines",role:"status",children:[...ste(N),...U?[U]:[]].map(_=>o.jsxs("li",{"data-found":_.found?"":void 0,children:[_.key==="products"&&X?o.jsx(xr,{size:"1"}):_.found?o.jsx(Kn,{size:12,weight:"bold"}):o.jsx(UU,{size:12}),o.jsx("span",{className:"sc-kit-line-label",children:_.label}),o.jsx("span",{className:"sc-kit-line-value",children:_.value})]},_.key))}),$&&o.jsx("p",{className:"sc-kit-note",role:"status",children:$}),!X&&!G&&ite(z)&&o.jsx("button",{type:"button",className:"sc-wizpick-open",onClick:I,children:"Try the catalogue again"})]})]})]})}),k&&F&&y&&o.jsx(PA,{brandId:y.id,scan:F,busy:E,error:C,onImport:_=>void ne(_),onImportAll:()=>void ne(),onDismiss:()=>S(!1)})]})}const fu=e=>{const t=(e??"").trim();return t||null};function dte(e){const t=e;return{name:e.name,brand:fu(t.brand)??fu(t.vendor),qualifier:fu(t.format)??fu(t.subcategory)??fu(t.variant)}}function fte(e){return!e.brand||e.name.toLowerCase().startsWith(e.brand.toLowerCase())?e.name:`${e.brand} ${e.name}`}function go(e,t){const n=dte(e);if(t==="chip")return n.name;const r=fte(n);return t==="tooltip"?[r,n.qualifier].filter(Boolean).join(" · "):r}function Qi(e,t){return t==="tooltip"?[e.name,fu(e.lighting)].filter(Boolean).join(" · "):e.name}function Gh(e){return[e.name,...e.legacyNames??[],...e.keywords??[],e.description,e.lighting,e.subject].concat(e.collections??[],e.verticals??[]).filter(Boolean).join(" ")}function Uv(e){const t=e;return[e.name,...t.legacyNames??[],...t.keywords??[],t.brand,t.vendor,t.format,t.subcategory,t.variant,t.productType,...t.tags??[]].filter(Boolean).join(" ")}function Yh(e){return[e.name,e.descriptor,e.presentation,e.ageRange,e.facial,e.skin,e.hair,e.build,e.wardrobeDefault,...e.suitableCategories,...e.suitableStyles].filter(Boolean).join(" ")}function hte(e,t,n){return[e.title,e.category,n,t.product?Uv(t.product):null,t.presenter?Yh(t.presenter):null,t.scene?Gh(t.scene):null].filter(Boolean).join(" ")}function Wv(){const{brand:e}=on(),t=Dn(),n=mr(e);return s.useCallback(r=>{t(`${n}?presenter=${encodeURIComponent(r)}&compose=1`)},[n,t])}function im(){const{brand:e}=on(),t=Dn(),n=mr(e);return s.useCallback((r,a)=>{const i=a?`&setup=${encodeURIComponent(a)}`:"";t(`${n}?scene=${encodeURIComponent(r)}${i}&compose=1`)},[n,t])}function T6(e){return{...e.brief,...e.variants?{variants:e.variants}:{},...e.quality?{quality:e.quality}:{},_at:Date.now()}}function pte(){const{brand:e}=on(),t=Dn(),n=mr(e);return s.useCallback(r=>{t(`${n}?showcase=${encodeURIComponent(r)}`)},[n,t])}const vh=e=>`sc-favscenes-${e}`,mte=e=>`sc-favlooks-${e}`,gte=e=>`bt-favlooks-${e}`;function cM(e,t){return e==="presenter"?`sc-favpresenters-${t}`:e==="product"?`sc-favproducts-${t}`:vh(t)}function uM(e){try{const t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function vo(e){try{const t=localStorage.getItem(vh(e))??r6(mte(e),vh(e))??r6(gte(e),vh(e));return uM(t)}catch{return[]}}function lm(e,t){try{return e==="scene"?vo(t):uM(localStorage.getItem(cM(e,t)))}catch{return[]}}function dM(e,t,n){try{localStorage.setItem(cM(e,t),JSON.stringify(n))}catch{}}function cm(e,t,n){const r=lm(e,t),a=r.includes(n)?r.filter(i=>i!==n):[...r,n];return dM(e,t,a),a}function Kv(e,t,n,r){const a=lm(e,t),i=r?[...a,...n.filter(l=>!a.includes(l))]:a.filter(l=>!n.includes(l));return dM(e,t,i),i}const fM=[{key:"campaign",label:"Product campaign"},{key:"lifestyle",label:"Lifestyle"},{key:"editorial",label:"Fashion & editorial"},{key:"beauty",label:"Beauty"},{key:"food-drink",label:"Food & drink"},{key:"launch",label:"Tech launch"},{key:"social",label:"Social"},{key:"cinematic",label:"Cinematic"},{key:"catalog",label:"Catalog"},{key:"seasonal",label:"Seasonal"}],vte=new Map(fM.map(e=>[e.key,e]));function qg(e){var t;return e?((t=vte.get(e))==null?void 0:t.label)??e:null}function wte(e){const t=new Map(fM.map((n,r)=>[n.key,r]));return[...e].sort((n,r)=>(t.get(n)??99)-(t.get(r)??99)||n.localeCompare(r))}const Ru=14,yte=768,sc=[{px:190,label:"Compact",cells:3,cols:6,min:200},{px:320,label:"Large",cells:2,cols:5,min:280}];function bte(e){let t=sc[0];for(const n of sc)Math.abs(n.px-e)<Math.abs(t.px-e)&&(t=n);return t}const hM=320;function pM(e){const t=typeof e=="number"&&Number.isFinite(e)?e:hM;let n=sc[0].px;for(const r of sc)Math.abs(r.px-t)<Math.abs(n-t)&&(n=r.px);return n}const zu=5;function jc(e){const t=typeof e=="number"?e:zu;return t===7||t===5?t:t===6?5:zu}function xte(e){const[t,n]=s.useState(0);return s.useLayoutEffect(()=>{if(!e)return;const r=e.clientWidth;n(a=>a===r?a:r)}),s.useLayoutEffect(()=>{if(!e)return;const r=()=>{const i=e.clientWidth;n(l=>l===i?l:i)};r();const a=new ResizeObserver(r);return a.observe(e),()=>a.disconnect()},[e]),t}function kte(){const[e,t]=s.useState(()=>window.innerWidth);return s.useEffect(()=>{let n=0;const r=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>t(window.innerWidth))};return window.addEventListener("resize",r),()=>{cancelAnimationFrame(n),window.removeEventListener("resize",r)}},[]),e}function Xg(e,t){return Math.max(1,Math.floor((e-Ru*(t-1))/t))}function Ste(e,t,n){if(e<=0)return{tile:t,cols:1};if(n)return{tile:Math.floor((e-Ru)/2),cols:2};const r=sc[1],a=sc[0],i=Math.min(r.cols,Math.max(1,Math.floor((e+Ru)/(r.min+Ru))));if(bte(t).px===r.px)return{tile:Xg(e,i),cols:i};let l=Math.min(a.cols,i+1);return l>1&&Xg(e,l)<a.min&&(l=i),{tile:Xg(e,l),cols:l}}function zk(e){return Math.max(1,e)}function um(e){return jc(e)===5?"large":"compact"}const Nf=s.createContext("large");function Ete(){return s.useContext(Nf)}const Cte=[{value:7,label:"Compact",hint:"More cards per row",cells:3},{value:5,label:"Large",hint:"Fewer, larger cards",cells:2}],jte=sc.map(e=>({value:e.px,label:e.label,hint:e.label==="Compact"?"More shots per row":"Fewer, larger shots",cells:e.cells}));function dm({value:e,onChange:t}){return o.jsx(mM,{label:"Grid size",value:jc(e),options:Cte,onChange:n=>t(n)})}function Ate({value:e,onChange:t}){return o.jsx(mM,{label:"Shot size",value:pM(e),options:jte,onChange:t})}function mM({label:e,value:t,options:n,onChange:r}){const a=s.useRef(null);return s.useLayoutEffect(()=>{const i=a.current;if(!i)return;const l=()=>{const f=i.querySelector(":scope > button[data-on]");if(!f){i.style.setProperty("--sc-density-x","0px"),i.style.setProperty("--sc-density-w","0px");return}i.style.setProperty("--sc-density-x",`${f.offsetLeft}px`),i.style.setProperty("--sc-density-w",`${f.offsetWidth}px`)};l(),i.dataset.inkReady||requestAnimationFrame(()=>{i.dataset.inkReady=""});const u=new ResizeObserver(l);return u.observe(i),()=>u.disconnect()},[t]),o.jsxs("div",{ref:a,className:"sc-density",role:"radiogroup","aria-label":e,children:[o.jsx("span",{className:"sc-density-ink","aria-hidden":!0}),n.map(i=>{const l=t===i.value;return o.jsx("button",{type:"button",role:"radio",className:"sc-density-opt","aria-checked":l,"aria-label":i.label,title:i.hint,"data-on":l||void 0,onClick:()=>{l||r(i.value)},children:o.jsx(Nte,{cells:i.cells})},i.value)})]})}function Nte({cells:e}){const t=e,n=16,r=1.5,a=1.5,l=(n-r*2-a*(t-1))/t,u=Math.max(.6,l*.22),f=[];for(let h=0;h<t;h++)for(let p=0;p<t;p++)f.push({x:r+p*(l+a),y:r+h*(l+a)});return o.jsx("svg",{className:"sc-density-icon",width:n,height:n,viewBox:`0 0 ${n} ${n}`,"aria-hidden":!0,children:f.map(h=>o.jsx("rect",{x:h.x,y:h.y,width:l,height:l,rx:u,ry:u,fill:"currentColor"},`${h.x}-${h.y}`))})}function fm(e){return{"--sc-wall-cols":String(jc(e))}}function Mte(e,t){let r=null,a=null,i=null,l=null,u=null,f=null,h=null,p={dx:0,dy:0},g={w:0,h:0},v=0;const w=R=>{R.style.position="fixed",R.style.left="0",R.style.top="0",R.style.margin="0",R.style.zIndex="var(--sc-z-popover)",R.style.pointerEvents="none"},y=()=>{const R=T=>{var H,D;window.removeEventListener("click",R,!0),!((D=(H=T.target).closest)!=null&&D.call(H,'[data-role="remove"]'))&&(T.stopPropagation(),T.preventDefault())};window.addEventListener("click",R,!0),setTimeout(()=>window.removeEventListener("click",R,!0),250)},x=()=>{if(h!==null){try{e.releasePointerCapture(h)}catch{}h=null}i==null||i.remove(),l==null||l.remove(),i=null,l=null,u=null,a==null||a.removeAttribute("data-drag-src"),a=null,r=null,e.removeAttribute("data-chip-drag"),document.documentElement.style.cursor="",cancelAnimationFrame(v)},k=R=>{!e.isConnected||!e.contains(document.activeElement)||(f!==null?Ra(e,f):Vl(e,R,"after"))},S=()=>{if(!a)return;const R=a;x(),y(),k(R),t.onCancelled()},E=R=>{if(R.button!==0||R.pointerType==="touch")return;const T=R.target;if(T.closest('[data-role="remove"]'))return;const H=Pi(T);H&&(r={chip:H,x:R.clientX,y:R.clientY})},j=R=>{var H,D;if(!r)return;f=Do(e),a=r.chip,t.onDragStart(),(H=window.getSelection())==null||H.removeAllRanges(),e.setAttribute("data-chip-drag","");const T=a.getBoundingClientRect();p={dx:r.x-T.left,dy:r.y-T.top},r=null;try{e.setPointerCapture(R.pointerId),h=R.pointerId}catch{}document.documentElement.style.cursor="grabbing",i=a.cloneNode(!0),(D=i.querySelector('[data-role="remove"]'))==null||D.remove(),i.className=`${a.className} sc-chip-ghost`,i.removeAttribute("data-drag-src"),i.removeAttribute("title"),w(i),i.style.width=`${T.width}px`,i.style.height=`${T.height}px`,i.style.fontSize=getComputedStyle(a).fontSize,g={w:T.width,h:T.height},document.body.appendChild(i),a.setAttribute("data-drag-src",""),l=document.createElement("div"),l.className="sc-drop-caret",w(l),l.style.display="none",document.body.appendChild(l),N(R)},N=R=>{if(!i||!a)return;const T=Math.min(Math.max(4,R.clientX-p.dx),window.innerWidth-g.w-4),H=Math.min(Math.max(4,R.clientY-p.dy),window.innerHeight-g.h-4);i.style.transform=`translate3d(${T}px, ${H}px, 0)`;const D=qx(e,a,R.clientX,R.clientY);if(u=D,!l)return;const K=D&&!D.noop?Bk(e,D.units):null;if(!K||!D){l.style.display="none";return}const O=JX(e,D.units),Z=O<D.units?Bk(e,O):null,te=!!Z&&Math.abs(Z.top+Z.height/2-(K.top+K.height/2))<K.height/2,B=Z&&te?(Z.left+K.left)/2:K.left;l.style.display="",l.style.transform=`translate3d(${B-1.5}px, ${K.top-2}px, 0)`,l.style.height=`${K.height+4}px`},P=R=>{if(r){if(Math.hypot(R.clientX-r.x,R.clientY-r.y)<5)return;R.preventDefault(),j(R);return}if(!a)return;R.preventDefault(),cancelAnimationFrame(v);const{clientX:T,clientY:H}=R;v=requestAnimationFrame(()=>N({clientX:T,clientY:H}))},$=R=>{if(r){r=null;return}if(!a)return;const T=a;let H;try{H=qx(e,T,R.clientX,R.clientY)??u}catch{H=u}finally{x()}if(y(),H&&!H.noop&&EN(e,T,H.units)){Vl(e,T,"after"),t.onMoved(T,A6(e,T));return}k(T),t.onCancelled()},M=R=>{R.key==="Escape"&&a&&(R.stopPropagation(),S())},C=R=>{Pi(R.target)&&R.preventDefault()};return e.addEventListener("pointerdown",E),e.addEventListener("dragstart",C),e.addEventListener("lostpointercapture",S),window.addEventListener("pointermove",P),window.addEventListener("pointerup",$),window.addEventListener("pointercancel",S),window.addEventListener("blur",S),window.addEventListener("keydown",M,!0),()=>{x(),e.removeEventListener("pointerdown",E),e.removeEventListener("dragstart",C),e.removeEventListener("lostpointercapture",S),window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",$),window.removeEventListener("pointercancel",S),window.removeEventListener("blur",S),window.removeEventListener("keydown",M,!0)}}function Bk(e,t){let n=0;const r=Array.from(e.childNodes);for(let l=0;l<r.length;l++){const u=r[l],f=Vu(u),h=u.nodeType===Node.TEXT_NODE&&t===n+f&&l<r.length-1;if(t<=n+f&&!h){if(u.nodeType!==Node.TEXT_NODE){const v=u.getBoundingClientRect();return new DOMRect(t===n?v.left:v.right,v.top,0,v.height)}const p=document.createRange();p.setStart(u,Zh(u,Math.max(0,Math.min(t-n,f)))),p.collapse(!0);const g=p.getBoundingClientRect();return g.height?g:null}n+=f}const i=(e.lastElementChild??e).getBoundingClientRect();return new DOMRect(i.right,i.top,0,i.height||18)}function Rte({kind:e,label:t,thumb:n,onInspect:r,onMove:a,onRemove:i,onClose:l}){const{sheet:u,grip:f}=ed(()=>l("dismiss")),h=e==="mark"?"brand mark":"reference image";return o.jsx(fc,{open:!0,onOpenChange:p=>!p&&l("dismiss"),children:o.jsxs(hc,{children:[o.jsx(pc,{className:"sc-shotsheet-scrim"}),o.jsxs(mc,{ref:u,className:"sc-shotsheet sc-swapsheet","data-kind":e,"aria-describedby":void 0,onOpenAutoFocus:p=>{var g;p.preventDefault(),(g=u.current)==null||g.focus({preventScroll:!0})},onCloseAutoFocus:p=>p.preventDefault(),onEscapeKeyDown:p=>{p.preventDefault(),l("escape")},children:[o.jsxs("div",{className:"sc-shotsheet-grip",...f,children:[o.jsx("span",{className:"sc-shotsheet-bar","aria-hidden":!0}),o.jsxs(gc,{className:"sc-vh",children:["Move or remove ",h]})]}),o.jsxs("div",{className:"sc-movesheet-head",children:[n&&o.jsx("button",{type:"button",className:"sc-movesheet-face",onClick:r,"aria-label":`Open ${h}`,children:o.jsx("img",{src:n,alt:"",onError:p=>p.currentTarget.remove()})}),o.jsxs("span",{className:"sc-movesheet-txt",children:[o.jsx("b",{dir:"auto",children:t||h}),o.jsx("span",{children:h})]})]}),o.jsxs("div",{className:"sc-swap-foot",children:[o.jsxs("div",{className:"sc-swap-move",children:[o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>a(-1),children:[o.jsx(sv,{size:13})," Move earlier"]}),o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>a(1),children:["Move later ",o.jsx(Pa,{size:13})]})]}),i&&o.jsxs("button",{type:"button",className:"sc-swap-remove",onClick:i,children:[o.jsx(il,{size:13}),"Remove ",e==="mark"?"mark":"reference"]})]})]})]})})}const Pte=440,Lte=460,Uk=156,gM=8,wh=14,Qg=20,hr=12,vM=200,Tte=240,wM=204;function $te(e,t,n){if(e.bottom<0||e.top>t.height)return null;const r=Math.min(n==null?void 0:n.width,t.width-hr*2),i=e.right+wh+r+hr<=t.width?e.right+wh:Math.max(hr,e.left-wh-r),l=Math.max(hr,Math.min(e.top,t.height-hr-wM));return{left:i,top:l,width:r,maxHeight:Math.max(vM,t.height-l-hr),side:"beside"}}function Dte(e,t){const n=(r,a)=>Math.min(Math.max(r,Qg),Math.max(Qg,a-Qg));return t.side==="beside"?{edge:t.left>=e.right?"left":"right",x:0,y:n((e.top+e.bottom)/2-t.top,wM)}:{edge:t.side==="above"?"bottom":"top",x:n((e.left+e.right)/2-t.left,t.width),y:0}}function Hte(e,t,n,r){if(e.bottom<0||e.top>t.height)return null;const a=gM,i=Math.min(n.width,t.width-hr*2),l=n.height,u=Math.min(Math.max(e.left+(e.right-e.left)/2-i/2,hr),Math.max(hr,t.width-i-hr)),h=e.top-a-hr>=l?e.top-a-l:Math.min(e.bottom+a,Math.max(hr,t.height-l-hr));return{left:u,top:h}}function Gv(e,t,n){if(e.bottom<0||e.top>t.height)return null;const r=Math.min((n==null?void 0:n.width)??Pte,t.width-hr*2),a=(n==null?void 0:n.gap)??gM,i=e.top-a-hr,l=t.height-e.bottom-a-hr,u=i>=Tte||i>=l?"above":"below",h=Math.max(vM,Math.min(Lte,u==="above"?i:l)),p=Math.min(Math.max(e.left,hr),Math.max(hr,t.width-r-hr)),g=u==="above"?Math.max(hr,e.top-a-h):e.bottom+a;return u==="above"?{left:p,top:g,width:r,maxHeight:h,side:u,bottomEdge:e.top-a}:{left:p,top:g,width:r,maxHeight:h,side:u}}function yM(e){return e.side==="above"&&e.bottomEdge!==void 0?{left:e.left,width:e.width,maxHeight:e.maxHeight,top:"auto",bottom:window.innerHeight-e.bottomEdge}:{left:e.left,width:e.width,maxHeight:e.maxHeight,top:e.top}}const Ote=["ref","mark","product","presenter","scene","shot"],yh=e=>Ote.includes(e),bM={ref:"Reference image",mark:"Brand mark",product:"Product",presenter:"Presenter",scene:"Scene",shot:"Shot"};function Ite(e){return e.side==="below"||e.side==="beside"?{top:Math.round(e.top)}:{bottom:Math.round(window.innerHeight-(e.top+e.maxHeight))}}function ad({anchor:e,kind:t,src:n,label:r,warning:a,note:i,noun:l,side:u="auto",onOpen:f,onHoverIn:h,onHoverOut:p,onClose:g}){const[v,w]=s.useState(null),[y,x]=s.useState(!1);if(s.useEffect(()=>x(!1),[n]),s.useLayoutEffect(()=>{var E,j;const S=()=>{const N=window.visualViewport,P=e.getBoundingClientRect(),$={width:(N==null?void 0:N.width)??window.innerWidth,height:(N==null?void 0:N.height)??window.innerHeight},M=u==="beside"?$te(P,$,{width:Uk}):Gv(P,$,{width:Uk,gap:wh});if(!M){g();return}w({...M,tail:Dte(P,M)})};return S(),window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),(E=window.visualViewport)==null||E.addEventListener("resize",S),(j=window.visualViewport)==null||j.addEventListener("scroll",S),()=>{var N,P;window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0),(N=window.visualViewport)==null||N.removeEventListener("resize",S),(P=window.visualViewport)==null||P.removeEventListener("scroll",S)}},[e,u,g]),s.useEffect(()=>{const S=E=>{E.key==="Escape"&&g()};return window.addEventListener("keydown",S,!0),()=>window.removeEventListener("keydown",S,!0)},[g]),!v)return null;const k=l??bM[t];return Rr.createPortal(o.jsxs("div",{className:"sc-chip-preview","data-kind":t,"data-side":v.side,"aria-hidden":"true",style:{left:Math.round(v.left),...Ite(v),maxWidth:v.width,maxHeight:v.maxHeight},onPointerEnter:h,onPointerLeave:p,children:[o.jsx("span",{className:"sc-chip-preview-tail","data-edge":v.tail.edge,style:v.tail.edge==="left"||v.tail.edge==="right"?{top:Math.round(v.tail.y)}:{left:Math.round(v.tail.x)}}),o.jsxs("button",{type:"button",className:"sc-chip-preview-hit",tabIndex:-1,onClick:f,children:[y?o.jsxs("span",{className:"sc-chip-preview-plate sc-chip-preview-blank",children:[o.jsx(Ws,{size:20}),"Image unavailable"]}):o.jsx("img",{className:"sc-chip-preview-plate",src:n,alt:"",decoding:"async",onError:()=>x(!0)}),r&&o.jsx("b",{dir:"auto",children:r}),k&&o.jsx("span",{children:k})]}),i&&o.jsx("p",{className:"sc-chip-preview-note",children:i}),a&&o.jsx("p",{className:"sc-swap-warn",children:a})]}),document.body)}const Fte=160,_te=120;function od(){const[e,t]=s.useState(null),n=s.useRef(null),r=s.useRef(!1);r.current=e!==null;const a=s.useCallback(()=>{n.current&&clearTimeout(n.current),n.current=null},[]),i=s.useCallback(f=>{if(a(),r.current){t(f);return}n.current=setTimeout(()=>t(f),Fte)},[a]),l=s.useCallback(()=>{a(),n.current=setTimeout(()=>t(null),_te)},[a]),u=s.useCallback(()=>{a(),t(null)},[a]);return s.useEffect(()=>a,[a]),{shown:e,open:i,keep:a,close:l,closeNow:u}}const i0="sc-insert-menu";function Zte(e){var t;return!!(((t=e.nativeEvent)==null?void 0:t.isComposing)??e.isComposing)||e.keyCode===229}function Vte(e){return e==="/"?"Scenes":e==="@"?"Presenters":e==="#"?"Colors":"Products"}function zte(e){return e==="/"?"No matching scenes":e==="#"?"No matching colours":e==="@"?"No matching presenters":"No matching products"}function Bte({menuOpen:e,handled:t}){return!e&&!t}function Ute(e,t){return t||!e?{open:!1}:{open:!0,sigil:e.sigil,query:e.query}}function Wte(e,t){const n=t.trim().split(/\s+/).filter(Boolean)[0];if(!n)return[{text:e,hit:!1}];const r=e.toLocaleLowerCase().indexOf(n.toLocaleLowerCase());if(r<0)return[{text:e,hit:!1}];const a=r+n.length;return[...r>0?[{text:e.slice(0,r),hit:!1}]:[],{text:e.slice(r,a),hit:!0},...a<e.length?[{text:e.slice(a),hit:!1}]:[]]}function Kte(e,t){return{x:e.left-t.left,y:e.top-t.top,w:e.right-e.left,h:e.bottom-e.top}}function Gte(e,t){return{left:e.left+t.x,top:e.top+t.y,right:e.left+t.x+t.w,bottom:e.top+t.y+t.h}}function Yte(e,t,n){return n?t:e||t}function qte(e,t){return!t||e==null?!0:e===t?!1:!t.contains(e)}function Jg(e,t){return e===t?!0:!e||!t?!1:e.left===t.left&&e.top===t.top&&e.width===t.width&&e.maxHeight===t.maxHeight&&e.side===t.side&&e.shell===t.shell}function Xte(e,t,n){return Math.min(n,Math.max(0,e)+Math.max(0,t))}function Qte(e,t,n){return n>0&&t>0&&e!==t}function Jte(e,t){const n=t.getBoundingClientRect(),r=e.getBoundingClientRect();n.bottom>r.bottom?e.scrollTop+=n.bottom-r.bottom:n.top<r.top&&(e.scrollTop-=r.top-n.top)}const xM=320,qh=320,ene=280,Il=8,$l=12,tne=8,Wk=80,nne=120,kM=48;function SM(e,t){return!(!e||e.top===0&&e.left===0&&e.right===0&&e.bottom===0||e.bottom<0||e.top>t.height||e.right-e.left>kM)}function rne(e){return{top:e.top,bottom:Math.min(e.bottom,e.top+22),left:e.left,right:e.left+2}}function EM(e,t,n,r){return Math.min(Math.max(e,r),Math.max(r,n.width-t-r))}function $6(e,t,n,r){const a=n?tne:$l,i=n?Math.max(0,e.right-e.left):Math.min(xM,t.width-a*2),l=n?e.left:EM(e.left,i,t,a),u=n?Math.min(ene,Math.floor(t.height*.4)):qh,f=Math.min(u,r??u),h=e.top-Il-a,p=Math.max(0,Math.min(f,h)),g=Math.max(a,e.top-Il-p);return{left:l,top:g,width:i,maxHeight:p,side:"above",shell:"dock"}}function Kk(e,t,n,r){const a=Math.min(xM,n.width-$l*2),i=EM(e.left,a,n,$l),l=e.top-Il-$l,u=n.height-e.bottom-Il-$l,f=l>=nne||l>=u?"above":"below",h=Math.min(qh,r??qh),p=f==="above"?l:u,g=Math.min(h,r==null?Math.max(Wk,p):p);if(f==="above"){const w=Math.max($l,e.top-Il-Math.min(h,l)),y=Math.min(h,e.top-Il-w);return r==null&&y<Wk?$6(t,n,!1):{left:i,top:w,width:a,maxHeight:y,side:f,shell:"caret"}}const v=e.bottom+Il;return v+Math.min(g,u)>n.height-$l?$6(t,n,!1,r):{left:i,top:v,width:a,maxHeight:Math.min(h,u),side:f,shell:"caret"}}function sne(e,t,n,r={}){if(r.phone)return $6(t,n,!0,r.height);const a=r.line??t;if(SM(e,n)&&e)return Kk(e,t,n,r.height);const i=e&&e.right-e.left>kM?e:a;return Kk(rne(i),t,n,r.height)}function ane({anchor:e,composer:t,line:n,query:r,options:a,remaining:i=0,total:l=0,sigil:u,onMore:f,onActiveId:h,onClose:p}){const g=wr(Ks),[v,w]=s.useState(0),[y,x]=s.useState(null),k=s.useRef(null),S=s.useRef(null),E=s.useRef(null),j=s.useRef(null),N=`${u??""}\0${r}`,P=s.useRef({}),$=s.useRef(f);$.current=f;const M=s.useRef(i);M.current=i;const C=s.useRef(0),R=s.useCallback(()=>{var O;Qte(C.current,a.length,M.current)&&(C.current=a.length,(O=$.current)==null||O.call($))},[a.length]);s.useEffect(()=>{w(0),C.current=0},[r]),s.useEffect(()=>{w(O=>Math.min(O,Math.max(0,a.length-1)))},[a.length]),s.useEffect(()=>{j.current=null,P.current={}},[u]);const T=s.useCallback(O=>{var ne;const Z=t==null?void 0:t.getBoundingClientRect();if(!Z)return null;const te=(n==null?void 0:n.getBoundingClientRect())??Z,B=window.visualViewport,F={width:(B==null?void 0:B.width)??window.innerWidth,height:(B==null?void 0:B.height)??window.innerHeight},X=!!((ne=k.current)!=null&&ne.contains(document.activeElement)),z=X?null:yN(),I=z&&SM(z,F)?z:null;I&&(j.current=Kte(I,te));const U=j.current?Gte(te,j.current):null,G=Yte(I,U,X)??(X?null:(e==null?void 0:e.getBoundingClientRect())??null);return sne(G,Z,F,{phone:g,line:te,height:O})},[e,t,n,g]);s.useLayoutEffect(()=>{var B,F;P.current.sigil!==u&&(P.current={sigil:u});const O=()=>{const X=M.current>0?void 0:P.current.height,z=T(X);x(I=>Jg(I,z)?I:z)},Z=X=>{qte(X.target,k.current)&&O()};O();const te=requestAnimationFrame(O);return window.addEventListener("resize",O),window.addEventListener("scroll",Z,!0),(B=window.visualViewport)==null||B.addEventListener("resize",O),(F=window.visualViewport)==null||F.addEventListener("scroll",O),()=>{var X,z;cancelAnimationFrame(te),window.removeEventListener("resize",O),window.removeEventListener("scroll",Z,!0),(X=window.visualViewport)==null||X.removeEventListener("resize",O),(z=window.visualViewport)==null||z.removeEventListener("scroll",O)}},[e,t,n,g,u,T]),s.useLayoutEffect(()=>{if(!y||!k.current)return;if(i>0){if(P.current.height==null&&P.current.sigil===(u??""))return;P.current={sigil:u??""};const X=T();X&&!Jg(y,X)&&x(X);return}const O=k.current,Z=S.current,te=Z?O.offsetHeight-Z.clientHeight:O.offsetHeight,B=Xte(te,(Z==null?void 0:Z.scrollHeight)??0,qh);if(!(B>0)||P.current.height===B&&P.current.sigil===(u??""))return;P.current={sigil:u??"",height:B};const F=T(B);!F||Jg(y,F)||x(F)},[y,N,T,i,a.length,u]),s.useLayoutEffect(()=>{const O=Z=>{Z.isComposing||Z.keyCode===229||(Z.key==="ArrowDown"?(Z.preventDefault(),v>=a.length-1?R():w(te=>te+1)):Z.key==="ArrowUp"?(Z.preventDefault(),w(te=>Math.max(0,te-1))):(Z.key==="Enter"||Z.key==="Tab")&&a[v]?(Z.preventDefault(),a[v].run()):Z.key==="Escape"&&(Z.preventDefault(),p()))};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[a,v,p,R]),s.useEffect(()=>{const O=S.current,Z=O==null?void 0:O.querySelector('[data-active="true"]');O&&Z&&Jte(O,Z)},[v]),s.useEffect(()=>{const O=E.current,Z=S.current;if(!O||!Z)return;const te=new IntersectionObserver(B=>{Z.scrollTop<=0||B.some(F=>F.isIntersecting)&&R()},{root:Z,rootMargin:"0px 0px 8px 0px"});return te.observe(O),()=>te.disconnect()},[y,N,R]);const H=a[v]?`${i0}-opt-${v}`:null;if(s.useEffect(()=>(h==null||h(H),()=>h==null?void 0:h(null)),[H,h]),s.useEffect(()=>{const O=Z=>{Z.target.closest(".sc-cmd")||(N6(Z),p())};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[p]),!y)return null;const D=`${i0}-list`,K=Vte(u);return Rr.createPortal(o.jsx("div",{className:"sc-cmd",id:i0,"data-shell":y.shell,style:{left:y.left,top:y.top,width:y.width,maxHeight:y.maxHeight,height:y.side==="above"&&i>0?y.maxHeight:void 0},ref:k,children:o.jsxs("div",{className:"sc-cmd-list",ref:S,role:"listbox","aria-label":K,id:D,children:[a.length?a.map((O,Z)=>{var B;const te=Z===0||O.group!==((B=a[Z-1])==null?void 0:B.group);return o.jsxs("div",{children:[te&&o.jsx(Gk,{name:O.group,total:l}),o.jsxs("button",{type:"button",id:`${i0}-opt-${Z}`,className:"sc-cmd-row",role:"option","aria-selected":Z===v,"data-active":Z===v,onMouseEnter:()=>w(Z),onMouseDown:F=>N6(F),onClick:()=>O.run(),children:[O.thumb?o.jsx("img",{src:O.thumb,alt:"","data-crop":O.crop}):O.swatch?o.jsx("span",{className:"sc-cmd-swatch",style:{background:O.swatch}}):null,o.jsx(one,{text:O.label,query:r}),O.hint&&o.jsx("span",{className:"sc-cmd-hint",children:O.hint})]})]},O.key)}):o.jsxs(o.Fragment,{children:[o.jsx(Gk,{name:K,total:l}),o.jsx("div",{className:"sc-cmd-empty",children:zte(u)})]}),i>0&&a.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"sc-cmd-count","aria-live":"polite",children:[a.length," of ",l]}),o.jsx("div",{ref:E,className:"sc-cmd-sentinel","aria-hidden":!0})]})]})}),document.body)}function Gk({name:e,total:t}){return o.jsxs("div",{className:"sc-cmd-group",children:[e," ",o.jsx("span",{className:"sc-cmd-n",children:t})]})}function one({text:e,query:t}){return o.jsx("span",{className:"sc-cmd-label",children:Wte(e,t).map(n=>n.hit?o.jsx("b",{children:n.text},`h:${n.text}`):o.jsx("span",{children:n.text},`t:${n.text}`))})}const ine={fragrance:["Fragrance"],footwear:["Footwear"],apparel:["Apparel"],furniture:["Furniture","Home"],beauty:["Beauty"],electronics:["Electronics"],accessories:["Accessories"],beverage:["Food & drink"],jewelry:["Jewelry"],food:["Food & drink"]},lne={fragrance:["Fragrance"],footwear:["Footwear","Apparel"],apparel:["Apparel"],furniture:["Furniture","Home"],beauty:["Beauty"],electronics:["Electronics"],accessories:["Accessories"],beverage:["Food & drink"],jewelry:["Jewelry"],food:["Food & drink"]};function cne(e,t){if(!t)return!1;const n=ine[t];return!!n&&n.some(r=>e.verticals.includes(r))}function une(e,t){if(!t)return!1;const n=lne[t];return!!n&&n.some(r=>e.suitableCategories.includes(r))}function Yk(e){return e.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").replace(/[\u200e\u200f\u061c\u202a-\u202e\u2066-\u2069]/g,"").toLowerCase()}const dne=4;function wo(e,t){const n=Yk(t).trim().split(/\s+/).filter(Boolean);if(!n.length)return!0;const r=Yk(e);return n.every(a=>r.includes(a)||a.length>=dne&&a.endsWith("s")&&r.includes(a.slice(0,-1)))}function Yv(e,t){return{visible:e.slice(0,t),remaining:Math.max(0,e.length-t)}}function CM(e,t){return[...e].sort((n,r)=>Number(t(r))-Number(t(n)))}function jM(e,t){if(e.t==="product"){const n=t.products.find(a=>a.id===e.id)??null,r=n?null:t.demoProducts.find(a=>a.id===e.id)??null;return{kind:"product",product:n,demo:r}}if(e.t==="character"){const n=t.cast.find(a=>a.id===e.id)??null,r=n?null:t.presenters.find(a=>a.id===e.id)??null;return{kind:"presenter",character:n,presenter:r}}if(e.t==="template"){const n=t.scenes.find(r=>r.id===e.id)??null;return{kind:"scene",scene:n,custom:!!n&&"custom"in n&&!!n.custom}}return null}const Mf={product:"product",presenter:"presenter",scene:"scene"},Fi=48;function fne(e){return e?e.t==="product"?"product":e.t==="character"?"presenter":e.t==="template"?"scene":null:null}function hu(e){const t=fne(e);return t||((e==null?void 0:e.t)==="color"?"color":null)}function hne(e){const t=hu(e);return t||((e==null?void 0:e.t)==="ref"||(e==null?void 0:e.t)==="mark"?e.t:null)}function e8(e){return(e==null?void 0:e.t)==="ref"||(e==null?void 0:e.t)==="mark"?e.imageHash:null}const g0=e=>{const t=(e??"").trim();return t||void 0},qk=e=>(e==null?void 0:e.custom)===!0;function _i(e,t){return e==="product"?[...(t.libraryProducts.length?t.libraryProducts:t.brandProducts).map(r=>{var a,i;return Xk(r,"brand",Bp((i=(a=r.shots)==null?void 0:a[0])==null?void 0:i.file,"tile"))}),...t.demoProducts.map(r=>Xk(r,"catalog",r.previewUrl??null))]:e==="presenter"?[...t.presenters.map(n=>{const r=ti(n);return{kind:"presenter",id:n.id,label:n.name,full:[n.name,g0(n.descriptor)].filter(Boolean).join(" · "),sub:g0(n.descriptor),search:Yh(n),thumb:sr(r.src,"tile"),crop:r.crop,source:qk(n)?"brand":"catalog",recommended:une(n,t.productCategory),token:{t:"character",id:n.id}}}),...t.cast.map(n=>{const r=bv(n);return{kind:"presenter",id:n.id,label:n.name,full:n.name,search:n.name,thumb:sr(r.src,"tile"),crop:r.crop,source:"brand",token:{t:"character",id:n.id}}})]:t.scenes.map(n=>({kind:"scene",id:n.id,label:Qi(n,"card"),full:Qi(n,"tooltip"),sub:g0(n.lighting),search:Gh(n),thumb:sr(n.previewUrl??null,"tile"),tint:Mu(n.previewColor),source:qk(n)?"brand":"catalog",recommended:cne(n,t.productCategory),token:{t:"template",id:n.id}}))}function Xk(e,t,n){return{kind:"product",id:e.id,label:go(e,"chip"),full:go(e,"tooltip"),sub:pne(e),search:Uv(e),thumb:n,source:t,token:{t:"product",id:e.id}}}function pne(e){const t=e;return g0(t.brand)??g0(t.vendor)}function Pu(e,t){const n=t.trim();return n?e.filter(r=>wo(r.search,n)):e}function Qk(e,t,n){return t.source==="brand"?0:e==="scene"?n.has(t.id)?1:t.recommended?2:3:e==="presenter"?t.recommended?1:2:1}function hm(e,t,n){const r=n.currentId?t.find(h=>h.id===n.currentId)??null:null,a=r?t.filter(h=>h.id!==r.id):t,l=[...Pu(a,n.query)].sort((h,p)=>Qk(e,h,n.bookmarked)-Qk(e,p,n.bookmarked)).map(h=>n.bookmarked.has(h.id)?{...h,bookmarked:!0}:h),{visible:u,remaining:f}=Yv(l,n.shown??Fi);return{current:r,items:u,remaining:f,total:l.length}}const mne={$:"product","/":"scene","@":"presenter"},AM={Products:8,Presenters:8,Colors:16,Scenes:8},NM={$:"Products","/":"Scenes","@":"Presenters","#":"Colors"};function Gd(e){return AM[NM[e??"$"]]}function MM(e){return{key:`${e.kind}:${e.id}`,group:e.kind==="presenter"?"Presenters":e.kind==="scene"?"Scenes":"Products",label:e.label,hint:e.sub,search:e.search,thumb:e.thumb??void 0,crop:e.crop,token:e.token}}function gne(e,t,n){return hm(e,t,{currentId:null,query:"",bookmarked:n,shown:t.length}).items.map(MM)}function Jk(e,t){const{visible:n,remaining:r}=Yv(e,t);return{items:n,remaining:r,total:e.length}}function vne(e,t,n={query:""}){const r=n.query.trim(),a=n.bookmarked??new Set,i=n.shown??AM[NM[e]];if(e==="#"){const h=(t.colors??[]).map(wne),p=r?h.filter(g=>wo(g.search??g.label,r)):h;return Jk(p,i)}const l=mne[e],u=l==="product"?t.products:l==="presenter"?t.presenters:t.scenes??[],f=r?Pu(u,r).map(MM):gne(l,u,a);return Jk(f,i)}function wne(e){return{key:`color:${e.hex}`,group:"Colors",label:e.name,hint:e.hex,search:`${e.name} ${e.hex}`,swatch:e.hex,token:{t:"color",hex:e.hex,name:e.name||void 0}}}const yne="(pointer: coarse)";function bne(e){return wr(Ks)?o.jsx(Cne,{...e}):o.jsx(Ene,{...e,onMove:void 0})}function xne(){return!wr(yne)}const kne=e=>`Remove ${Mf[e]}`;function Sne(e,t,n){const r={slug:t};return e==="product"?la(r,n):e==="presenter"?ha(r,n):_r(r,n)}function RM({kind:e,currentId:t,candidates:n,brandId:r,brandSlug:a,warning:i,note:l,onPick:u,onRemove:f,onClose:h,onAttachRequest:p,onMove:g,autoFocusSearch:v}){const[w,y]=s.useState(""),[x,k]=s.useState(Fi),S=s.useRef(null),E=s.useRef(null),[j,N]=s.useState(0),P=s.useMemo(()=>e==="scene"?new Set(vo(r)):new Set,[e,r]);s.useEffect(()=>{k(Fi),N(0)},[w]);const $=s.useMemo(()=>hm(e,n,{currentId:t,query:w,bookmarked:P,shown:x}),[e,n,t,w,P,x]);s.useLayoutEffect(()=>{var D;v&&((D=S.current)==null||D.focus({preventScroll:!0}))},[v]),s.useEffect(()=>{N(D=>Math.max(0,Math.min(D,$.items.length-1)))},[$.items.length]);const M=s.useCallback(D=>{var O;const K=(O=E.current)==null?void 0:O.querySelectorAll("[data-nav]")[D];K&&(N(D),K.focus({preventScroll:!0}),K.scrollIntoView({block:"nearest"}))},[]),C=s.useCallback(()=>{const D=E.current;return D?Math.max(1,getComputedStyle(D).gridTemplateColumns.split(" ").filter(Boolean).length):1},[]),R=D=>{var te;if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),h("escape");return}const K=D.target===S.current;if(K&&D.key==="ArrowDown"){D.preventDefault(),M(0);return}if(K&&D.key==="Enter"){D.preventDefault(),$.items[0]&&u($.items[0]);return}if(K)return;const O=C(),Z=D.key==="ArrowRight"?1:D.key==="ArrowLeft"?-1:D.key==="ArrowDown"?O:D.key==="ArrowUp"?-O:0;if(Z){D.preventDefault();const B=j+Z;B<0&&Z===-O?(te=S.current)==null||te.focus():B>=0&&B<$.items.length&&M(B);return}D.key==="Home"?(D.preventDefault(),M(0)):D.key==="End"&&(D.preventDefault(),M($.items.length-1))},T=Mf[e],H=e==="product";return o.jsxs("div",{className:"sc-swap-inner",onKeyDown:R,children:[o.jsx("div",{className:"sc-swap-head",children:o.jsxs("span",{className:"sc-swap-search",children:[o.jsx(Fu,{size:13}),o.jsx("input",{ref:S,type:"text",value:w,onChange:D=>y(D.target.value),placeholder:`Search ${T}s`,"aria-label":`Search ${T}s`,autoComplete:"off",spellCheck:!1})]})}),$.current&&o.jsxs("div",{className:"sc-swap-cur",title:$.current.full,children:[o.jsx(e5,{src:$.current.thumb,tinted:!!$.current.tint,crop:$.current.crop}),o.jsxs("span",{className:"sc-swap-curtext",children:[o.jsx("b",{dir:"auto",children:$.current.label}),$.current.sub&&o.jsx("span",{dir:"auto",children:$.current.sub})]}),o.jsx("a",{className:"sc-swap-open",href:Sne(e,a,$.current.id),target:"_blank",rel:"noreferrer",title:`Open this ${T} in a new tab`,"aria-label":`Open ${$.current.label} in a new tab`,children:o.jsx(gf,{size:14})}),o.jsx("span",{className:"sc-swap-tick","aria-hidden":!0,children:o.jsx(Kn,{size:11,weight:"bold"})})]}),o.jsxs("div",{className:"sc-swap-body",children:[$.items.length===0&&o.jsx("p",{className:"sc-swap-empty",children:w.trim()?`Nothing matches “${w.trim()}”.`:`No other ${T}s.`}),o.jsx("div",{className:"sc-swap-grid",ref:E,role:"listbox","aria-label":`Choose a ${T}`,children:$.items.map((D,K)=>o.jsxs("div",{className:"sc-swap-card",role:"option","aria-selected":!1,"data-nav":K,tabIndex:K===j?0:-1,title:D.full,style:D.tint?{"--tint":D.tint}:void 0,onFocus:()=>N(K),onClick:()=>u(D),onKeyDown:O=>{O.key!=="Enter"&&O.key!==" "||(O.preventDefault(),u(D))},children:[o.jsx(e5,{src:D.thumb,tinted:!!D.tint,crop:D.crop}),o.jsxs("b",{dir:"auto",children:[D.bookmarked&&o.jsxs(o.Fragment,{children:[o.jsx(po,{className:"sc-bm-mark",size:10,weight:"fill","aria-hidden":!0}),o.jsx("span",{className:"sc-vh",children:"Kept. "})]}),D.label]}),H&&D.sub&&o.jsx("span",{dir:"auto",children:D.sub})]},D.id))}),$.remaining>0&&o.jsxs("button",{type:"button",className:"sc-swap-more",onClick:()=>k(D=>D+Fi),children:["Show ",Math.min(Fi,$.remaining)," more of ",$.total]})]}),o.jsxs("div",{className:"sc-swap-foot",children:[t&&!$.current&&o.jsxs("p",{className:"sc-swap-warn",children:["This ",T," is no longer available."]}),l&&o.jsx("p",{className:"sc-chip-preview-note",children:l}),i&&o.jsx("p",{className:"sc-swap-warn",children:i}),i&&p&&e==="scene"&&o.jsxs("div",{className:"sc-swap-attach",children:[i.includes("product")&&o.jsx("button",{type:"button",className:"sc-btn",onClick:()=>p("Products"),children:"Attach a product"}),i.includes("person")&&o.jsx("button",{type:"button",className:"sc-btn",onClick:()=>p("Presenters"),children:"Attach a presenter"})]}),g&&o.jsxs("div",{className:"sc-swap-move",children:[o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>g(-1),children:[o.jsx(sv,{size:13})," Move earlier"]}),o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>g(1),children:["Move later ",o.jsx(Pa,{size:13})]})]}),f&&o.jsxs("button",{type:"button",className:"sc-swap-remove",onClick:f,children:[o.jsx(il,{size:13}),kne(e)]})]})]})}function e5({src:e,tinted:t,crop:n}){const[r,a]=s.useState(!1);return s.useEffect(()=>a(!1),[e]),!e||r?o.jsx("span",{className:"sc-swap-thumb sc-swap-thumb-empty",children:o.jsx(Ws,{size:18})}):o.jsx("img",{className:"sc-swap-thumb","data-tinted":t||void 0,"data-crop":n,src:e,alt:"",loading:"lazy",onError:()=>a(!0)})}function Ene(e){const{anchor:t,kind:n,onClose:r}=e,a=xne(),[i,l]=s.useState(null),u=s.useRef(null);return s.useLayoutEffect(()=>{var h,p;const f=()=>{const g=window.visualViewport,v=Gv(t.getBoundingClientRect(),{width:(g==null?void 0:g.width)??window.innerWidth,height:(g==null?void 0:g.height)??window.innerHeight});if(!v){r("outside");return}l(v)};return f(),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),(h=window.visualViewport)==null||h.addEventListener("resize",f),(p=window.visualViewport)==null||p.addEventListener("scroll",f),()=>{var g,v;window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0),(g=window.visualViewport)==null||g.removeEventListener("resize",f),(v=window.visualViewport)==null||v.removeEventListener("scroll",f)}},[t,r]),s.useEffect(()=>{const f=h=>{var g;const p=h.target;(g=u.current)!=null&&g.contains(p)||t.contains(p)||r("outside")};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[r,t]),i?Rr.createPortal(o.jsx("div",{ref:u,className:"sc-swap","data-kind":n,"data-side":i.side,role:"dialog","aria-label":`Change ${Mf[n]}`,style:yM(i),children:o.jsx(RM,{...e,autoFocusSearch:a})}),document.body):null}function Cne(e){const{kind:t,onClose:n}=e,{sheet:r,grip:a}=ed(()=>n("dismiss"));return o.jsx(fc,{open:!0,onOpenChange:i=>!i&&n("dismiss"),children:o.jsxs(hc,{children:[o.jsx(pc,{className:"sc-shotsheet-scrim"}),o.jsxs(mc,{ref:r,className:"sc-shotsheet sc-swapsheet","data-kind":t,"aria-describedby":void 0,onOpenAutoFocus:i=>{var l;i.preventDefault(),(l=r.current)==null||l.focus({preventScroll:!0})},onCloseAutoFocus:i=>i.preventDefault(),onEscapeKeyDown:i=>{i.preventDefault(),n("escape")},children:[o.jsxs("div",{className:"sc-shotsheet-grip",...a,children:[o.jsx("span",{className:"sc-shotsheet-bar","aria-hidden":!0}),o.jsxs(gc,{className:"sc-vh",children:["Change ",Mf[t]]})]}),o.jsx(RM,{...e,autoFocusSearch:!1})]})]})})}const jne=260;function Ane(e){return wr(Ks)?o.jsx(Mne,{...e}):o.jsx(Nne,{...e,onMove:void 0})}function eu(e,t){const n=e?nr(e):null,r=t?nr(t):null;return!!n&&n===r}function PM({currentHex:e,currentName:t,palette:n,onPick:r,onRemove:a,onClose:i,onMove:l}){const u=s.useMemo(()=>{const S=new Set,E=[],j=P=>{const $=nr(P.hex);!$||S.has($)||(S.add($),E.push({...P,hex:$}))},N=e?nr(e):null;N&&!n.some(P=>eu(P.hex,N))&&j({hex:N,name:t||N,slot:"accent"});for(const P of n)j(P);return E},[n,e,t]),f=s.useRef(null),[h,p]=s.useState(()=>Math.max(0,u.findIndex(S=>eu(S.hex,e))));s.useEffect(()=>{p(S=>Math.max(0,Math.min(S,Math.max(0,u.length-1))))},[u.length]),s.useLayoutEffect(()=>{var E,j;const S=Math.max(0,u.findIndex(N=>eu(N.hex,e)));(j=(E=f.current)==null?void 0:E.querySelectorAll("[data-nav]")[S])==null||j.focus({preventScroll:!0})},[]);const g=s.useCallback(S=>{var j;const E=(j=f.current)==null?void 0:j.querySelectorAll("[data-nav]")[S];E&&(p(S),E.focus({preventScroll:!0}))},[]),v=S=>{if(S.key==="Escape"){S.preventDefault(),S.stopPropagation(),i("escape");return}if(S.key==="ArrowDown"||S.key==="ArrowUp"){S.preventDefault();const E=h+(S.key==="ArrowDown"?1:-1);E>=0&&E<u.length&&g(E)}},w=S=>r({t:"color",hex:S.hex,name:S.name||void 0}),y=(S,E)=>{const j=u.find(N=>eu(N.hex,S));r({t:"color",hex:S,name:(j==null?void 0:j.name)||void 0},{live:!0})},x=e?nr(e):null,k=!!x&&!n.some(S=>eu(S.hex,x));return o.jsxs("div",{className:"sc-swap-inner",onKeyDown:v,children:[o.jsx("div",{className:"sc-swap-body",children:u.length===0?o.jsx("p",{className:"sc-swap-empty",children:"No brand colours yet."}):o.jsx("div",{className:"sc-swap-swatches",ref:f,role:"listbox","aria-label":"Choose a colour",children:u.map((S,E)=>{const j=eu(S.hex,e),N=o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"sc-swap-dot",style:{background:S.hex},"aria-hidden":!0}),o.jsx("b",{dir:"auto",children:S.name}),o.jsx("span",{children:S.hex}),j&&o.jsx("span",{className:"sc-swap-tick","aria-hidden":!0,children:o.jsx(Kn,{size:11,weight:"bold"})})]});return k&&j?o.jsx(Zu,{className:"sc-swap-swatch",triggerStyle:{background:"none"},value:S.hex,presets:n.map(P=>P.hex),commitMode:"live",align:"start",label:`Edit ${S.name}`,triggerProps:{role:"option","aria-selected":!0,"data-on":"","data-nav":E,tabIndex:E===h?0:-1,title:`${S.name} ${S.hex}`,onFocus:()=>p(E)},onChange:P=>y(P),children:N},"current-custom"):o.jsx("div",{className:"sc-swap-swatch",role:"option","aria-selected":j,"data-on":j||void 0,"data-nav":E,tabIndex:E===h?0:-1,title:`${S.name} ${S.hex}`,onFocus:()=>p(E),onClick:()=>w(S),onKeyDown:P=>{P.key!=="Enter"&&P.key!==" "||(P.preventDefault(),w(S))},children:N},S.hex)})})}),o.jsxs("div",{className:"sc-swap-foot",children:[o.jsxs(Zu,{className:"sc-swap-swatch sc-swap-custom",triggerStyle:{background:"none"},value:e??Jp(n),presets:n.map(S=>S.hex),commitMode:"live",align:"start",label:"Custom colour",onChange:S=>y(S),children:[o.jsx(cr,{size:12}),o.jsx("b",{children:"Custom colour"})]}),l&&o.jsxs("div",{className:"sc-swap-move",children:[o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>l(-1),children:[o.jsx(sv,{size:13})," Move earlier"]}),o.jsxs("button",{type:"button",className:"sc-btn",onClick:()=>l(1),children:["Move later ",o.jsx(Pa,{size:13})]})]}),a&&o.jsxs("button",{type:"button",className:"sc-swap-remove",onClick:a,children:[o.jsx(il,{size:13}),"Remove colour"]})]})]})}function Nne(e){const{anchor:t,onClose:n}=e,[r,a]=s.useState(null),i=s.useRef(null);return s.useLayoutEffect(()=>{var u,f;const l=()=>{const h=window.visualViewport,p=Gv(t.getBoundingClientRect(),{width:(h==null?void 0:h.width)??window.innerWidth,height:(h==null?void 0:h.height)??window.innerHeight},{width:jne});if(!p){n("outside");return}a(p)};return l(),window.addEventListener("resize",l),window.addEventListener("scroll",l,!0),(u=window.visualViewport)==null||u.addEventListener("resize",l),(f=window.visualViewport)==null||f.addEventListener("scroll",l),()=>{var h,p;window.removeEventListener("resize",l),window.removeEventListener("scroll",l,!0),(h=window.visualViewport)==null||h.removeEventListener("resize",l),(p=window.visualViewport)==null||p.removeEventListener("scroll",l)}},[t,n]),s.useEffect(()=>{const l=u=>{var h,p;const f=u.target;(h=i.current)!=null&&h.contains(f)||t.contains(f)||(p=f.closest)!=null&&p.call(f,".sc-cp")||n("outside")};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[n,t]),r?Rr.createPortal(o.jsx("div",{ref:i,className:"sc-swap","data-kind":"color","data-side":r.side,role:"dialog","aria-label":"Change colour",style:yM(r),children:o.jsx(PM,{...e})}),document.body):null}function Mne(e){const{onClose:t}=e,{sheet:n,grip:r}=ed(()=>t("dismiss"));return o.jsx(fc,{open:!0,onOpenChange:a=>!a&&t("dismiss"),children:o.jsxs(hc,{children:[o.jsx(pc,{className:"sc-shotsheet-scrim"}),o.jsxs(mc,{ref:n,className:"sc-shotsheet sc-swapsheet","data-kind":"color","aria-describedby":void 0,onOpenAutoFocus:a=>{var i;a.preventDefault(),(i=n.current)==null||i.focus({preventScroll:!0})},onCloseAutoFocus:a=>a.preventDefault(),onEscapeKeyDown:a=>{a.preventDefault(),t("escape")},children:[o.jsxs("div",{className:"sc-shotsheet-grip",...r,children:[o.jsx("span",{className:"sc-shotsheet-bar","aria-hidden":!0}),o.jsx(gc,{className:"sc-vh",children:"Change colour"})]}),o.jsx(PM,{...e})]})]})})}function Rf(e){const{brand:t,products:n}=on(),{scenes:r,presenters:a,demoProducts:i}=Rn(),l=s.useMemo(()=>Oh(Cc(t),r),[t,r]),u=s.useMemo(()=>Oh(Sf(t),a),[t,a]),f=s.useMemo(()=>{var p;return(((p=t==null?void 0:t.json)==null?void 0:p.characters)??[]).filter(g=>(g==null?void 0:g.origin)!=="custom")},[t]),h=s.useMemo(()=>{var p;return L0(((p=t==null?void 0:t.json)==null?void 0:p.products)??[])},[t]);return s.useMemo(()=>({libraryProducts:NA(n),brandProducts:h,demoProducts:i,presenters:u,cast:f,scenes:l,productCategory:e??null}),[n,h,i,u,f,l,e])}const Yd=new Map,Rne=64;function LM(e){let t=Yd.get(e);if(!t)for(t=Lne(e).then(n=>n?Tne(n.data,4):null).catch(()=>null),Yd.set(e,t);Yd.size>Rne;)Yd.delete(Yd.keys().next().value);return t}function Pne(e,t){LM(t).then(n=>{const r=Mu(n??void 0);!r||!e.isConnected||(e.dataset.tinted="true",e.style.setProperty("--tint",r))})}async function Lne(e){const t=new Image;t.decoding="async",t.src=e;try{await t.decode()}catch{return null}const n=Math.min(1,48/Math.max(t.naturalWidth,t.naturalHeight,1)),r=Math.max(1,Math.round(t.naturalWidth*n)),a=Math.max(1,Math.round(t.naturalHeight*n)),i=document.createElement("canvas");i.width=r,i.height=a;const l=i.getContext("2d",{willReadFrequently:!0});if(!l)return null;l.drawImage(t,0,0,r,a);try{return l.getImageData(0,0,r,a)}catch{return null}}function Tne(e,t){const n=Array.from({length:24},()=>({score:0,r:0,g:0,b:0}));for(let a=0;a+t-1<e.length;a+=t){if(e[a+3]<128)continue;const i=e[a],l=e[a+1],u=e[a+2],{h:f,s:h,l:p}=$ne(i,l,u);if(h<.18||p<.12||p>.92)continue;const g=h*(1-Math.abs(p-.5)*1.2),v=n[Math.min(23,Math.floor(f/360*24))];v.score+=g,v.r+=i*g,v.g+=l*g,v.b+=u*g}const r=n.reduce((a,i)=>i.score>a.score?i:a,n[0]);return r.score<=0?null:Dne(r.r/r.score,r.g/r.score,r.b/r.score)}function $ne(e,t,n){const r=e/255,a=t/255,i=n/255,l=Math.max(r,a,i),u=Math.min(r,a,i),f=(l+u)/2;if(l===u)return{h:0,s:0,l:f};const h=l-u,p=f>.5?h/(2-l-u):h/(l+u);let g;return l===r?g=((a-i)/h+(a<i?6:0))*60:l===a?g=((i-r)/h+2)*60:g=((r-a)/h+4)*60,{h:g,s:p,l:f}}function Dne(e,t,n){const r=a=>Math.max(0,Math.min(255,Math.round(a))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`}function Hne(e){return!e||e.cap==null||e.cap<=0?null:e.cap}function One(e){const t=new Set;if(!e||e.cap==null||e.cap<=0)return t;const n=new Set(e.attachments.map(r=>Fl(r.role,r.id??r.hash)));for(const r of e.dropped){const a=Fl(r.role,r.id??r.hash);r.reason!=="missing"&&!n.has(a)&&t.add(a)}return t}const Fl=(e,t)=>`${e}:${t}`,l0=new Set(["product","character","ref","mark","template"]),Xh=12,D6=`Shot is full: ${Xh} identities. Remove one to add another.`,Xr=[{id:"square",label:"Square",hint:"1:1",w:1024,h:1024},{id:"portrait",label:"Portrait",hint:"4:5",w:1024,h:1280},{id:"story",label:"Story",hint:"9:16",w:1080,h:1920},{id:"landscape",label:"Landscape",hint:"16:9",w:1600,h:900}];function Bu(e){const t=Xr.find(n=>n.id===e);return t?t.w/t.h:1}function Ine(e,t=0){var i,l;const n=Xr.find(u=>u.id===(e==null?void 0:e.format));if(n)return n.id;const r=(l=(i=e==null?void 0:e.rendered)==null?void 0:i.sizes)==null?void 0:l[t];if(!r||!(r[0]>0)||!(r[1]>0))return;const a=Math.log(r[0]/r[1]);return Xr.reduce((u,f)=>Math.abs(Math.log(f.w/f.h)-a)<Math.abs(Math.log(u.w/u.h)-a)?f:u).id}const Y1=6,Fne=s.forwardRef(function({initialTokens:t,onChange:n,brand:r,templates:a,presenters:i,demoProducts:l,onTemplatePick:u,scenesSitOut:f,placeholder:h,placeholderSm:p,label:g="Brief",flag:v,described:w,describedNote:y,onInspect:x,activeProductCategory:k,onAttachRequest:S,onSubmit:E,onDropFiles:j},N){var bt,vt,Ct,st,$t,An;const P=s.useRef(null),$=s.useRef(null),M=s.useId(),[C,R]=s.useState(""),T=s.useCallback(Y=>{R(""),requestAnimationFrame(()=>R(Y))},[]),H=s.useRef(null),[D,K]=s.useState(null),[O,Z]=s.useState(null),te=od(),{shown:B,closeNow:F}=te,X=s.useRef(O);s.useEffect(()=>{X.current=O},[O]);const z=s.useRef(v);s.useEffect(()=>{z.current=v},[v]);const[I,U]=s.useState(""),[G,ne]=s.useState(Gd("$")),[q,le]=s.useState(null),Se=s.useRef(!1),Q=s.useRef(0),[xe,ee]=s.useState(!1),ae=s.useRef(0),{products:re}=on(),_=re.length?re:((bt=r.json)==null?void 0:bt.products)??[],ue=((vt=r.json)==null?void 0:vt.characters)??[],We=s.useMemo(()=>xf(r.json),[r]),Xe=s.useCallback((Y,he)=>{var In,Dt,On;const Me=document.createElement("span");Me.className=Hl,Me.contentEditable="false",Me.dir="ltr",Me.dataset.kind=Y.t,Me.dataset.tok=nm(Y),Me.dataset.uid=he??`u${Q.current++}`;let Ye="",dt=null,wt,Zt=null;const Ht=jM(Y,{products:_,demoProducts:l,cast:ue,presenters:i,scenes:a});if((Ht==null?void 0:Ht.kind)==="scene"){const Et=Ht.scene;Ye=Et?Qi(Et,"chip"):"missing template",dt=(Et==null?void 0:Et.previewUrl)??null;const Hn=Mu(Et==null?void 0:Et.previewColor);Hn&&(Me.dataset.tinted="true",Me.style.setProperty("--tint",Hn)),!Hn&&dt&&Ht.custom&&Pne(Me,dt)}else if((Ht==null?void 0:Ht.kind)==="product"){const Et=Ht.product??Ht.demo;Ye=Et?go(Et,"chip"):"missing product",dt=Ht.product?Bp((Dt=(In=Ht.product.shots)==null?void 0:In[0])==null?void 0:Dt.file,"micro"):((On=Ht.demo)==null?void 0:On.previewUrl)??null}else if((Ht==null?void 0:Ht.kind)==="presenter"){const{character:Et,presenter:Hn}=Ht;Ye=(Et==null?void 0:Et.name)??(Hn==null?void 0:Hn.name)??"missing person";const Ot=Et?bv(Et):Hn?ti(Hn):{src:null};dt=sr(Ot.src,"micro"),wt=Ot.crop}else if(Y.t==="color")Ye=Y.name??Y.hex,Zt=Y.hex;else if(Y.t==="ref")Ye=Y.label??"Image",dt=dn(Y.imageHash,"micro");else if(Y.t==="mark"){const Et=We.find(Hn=>Hn.hash===Y.imageHash);Ye=Et?qp(r.json,Et):"missing mark",dt=dn(Y.imageHash,"micro")}if(Ye.startsWith("missing ")&&(Me.dataset.missing=""),dt){const Et=document.createElement("img");Et.src=dt,Et.alt="",wt&&(Et.dataset.crop=wt),Et.onerror=()=>Et.remove(),Me.appendChild(Et)}else if(Zt){const Et=document.createElement("span");Et.className="sc-token-swatch",Et.style.background=Zt,Me.appendChild(Et)}const pn=document.createElement("span");pn.className="sc-token-label",pn.dir="auto",pn.textContent=Ye,Me.appendChild(pn);const Wt=(v==null?void 0:v(Y))??null;Wt&&(Me.title=Wt,Me.dataset.warn="1"),w!=null&&w(Y)&&(Me.dataset.described="1");const wn=hu(Y);if(wn){const Et=wn==="color"?"colour":Mf[wn];Me.tabIndex=0,Me.setAttribute("role","button"),Me.setAttribute("aria-haspopup","dialog"),Me.setAttribute("aria-expanded","false"),Me.setAttribute("aria-label",`${Et}: ${Ye}. Change or remove.`)}else Me.tabIndex=0,Me.setAttribute("role","button"),Me.setAttribute("aria-haspopup","dialog"),Me.setAttribute("aria-expanded","false"),Me.setAttribute("aria-label",`${Y.t==="mark"?"brand mark":"reference image"}: ${Ye}. Open, remove or move.`);Me.setAttribute("aria-keyshortcuts","Alt+ArrowLeft Alt+ArrowRight"),Me.setAttribute("aria-describedby",M),Me.setAttribute("draggable","false");const sn=document.createElement("button");return sn.type="button",sn.tabIndex=-1,sn.setAttribute("aria-hidden","true"),sn.dataset.role="remove",sn.appendChild(iQ()),Me.appendChild(sn),Me},[a,_,ue,i,l,We,r,v,w,M]),ze=s.useCallback(()=>{const Y=P.current;Y&&n(Bx(Y))},[n]);s.useEffect(()=>{const Y=P.current;Y&&(Ux(Y,t!=null&&t.length?t:Oo(),he=>Xe(he)),a0(Y))},[]);const tt=s.useCallback((Y,he)=>{var dt;const Me=P.current,Ye=Me==null?void 0:Me.querySelector(`[data-uid="${CSS.escape(Y)}"]`);if(Me&&Ye&&Yx(Me,Ye,he)){Vl(Me,Ye,"after");const wt=Do(Me);wt!==null&&(H.current=wt,((dt=X.current)==null?void 0:dt.uid)===Y&&(X.current={...X.current,caret:wt}),Z(Zt=>Zt&&Zt.uid===Y?{...Zt,caret:wt}:Zt)),ze(),T(A6(Me,Ye))}},[ze,T]);s.useEffect(()=>{const Y=P.current;if(Y)return Mte(Y,{onDragStart:()=>{K(null),U(""),F()},onMoved:(he,Me)=>{ze(),T(Me)},onCancelled:()=>T("Reorder cancelled.")})},[ze,T,F]),s.useEffect(()=>{const Y=P.current;if(Y)for(const he of Y.querySelectorAll(`.${Hl}`)){const Me=as(he.dataset.tok??"");if(!Me)continue;const Ye=(v==null?void 0:v(Me))??null;Ye?he.dataset.warn="1":delete he.dataset.warn,w!=null&&w(Me)?he.dataset.described="1":delete he.dataset.described,Ye&&!("open"in he.dataset)?he.title=Ye:he.removeAttribute("title")}},[v,w]),s.useEffect(()=>{const Y=()=>{const he=Do(P.current);he!==null&&(H.current=he)};return document.addEventListener("selectionchange",Y),()=>document.removeEventListener("selectionchange",Y)},[]);const ce=s.useCallback(Y=>{const he=P.current;if(!he)return;if(Y.t==="template"){const wt=Vd(he);if(wt){wt.replaceWith(Xe(Y,wt.dataset.uid)),no(he),ze(),K(null),U("");return}}const Me=Ta(Y);if(Me){const wt=Ig(he,Me);if(wt){K(null),U(""),T(`${Io(wt)||"That"} is already in the brief.`);return}}if(l0.has(Y.t)&&!(Y.t==="template"&&Vd(he))&&Array.from(he.querySelectorAll(`.${Hl}`)).filter(Zt=>l0.has(Zt.dataset.kind??"")).length>=Xh){K(null),U(""),T(D6);return}VX(he,Xe(Y),{eatQuery:!!D,fallbackUnits:H.current});const dt=Do(he);dt!==null&&(H.current=dt),ze(),K(null),U("")},[D,Xe,ze,T]),ve=s.useRef(ce);s.useEffect(()=>{ve.current=ce},[ce]);const Pe=s.useCallback((Y,he)=>{const Me=P.current,Ye=Me==null?void 0:Me.querySelector(`[data-uid="${CSS.escape(Y)}"]`);return!Me||!Ye?!1:(Ye.replaceWith(Xe(he,Y)),no(Me),ze(),!0)},[Xe,ze]),de=s.useCallback(Y=>{const he=P.current,Me=he==null?void 0:he.querySelector(`[data-uid="${CSS.escape(Y)}"]`);if(!he||!Me)return null;const Ye=ni(he,Me);return Fg(he,Me),ze(),Ye},[ze]),je=()=>{var Y;return document.documentElement.dataset.guideTask==="first-shot"&&!!((Y=P.current)!=null&&Y.closest('[data-guide="compose"]'))},Ue=(Y,he)=>{var wt;const Me=[...Y.querySelectorAll(".sc-token")];if(!Me.length)return!1;const[Ye]=((wt=he.getTargetRanges)==null?void 0:wt.call(he))??[];if(!Ye)return!1;const dt=document.createRange();return dt.setStart(Ye.startContainer,Ye.startOffset),dt.setEnd(Ye.endContainer,Ye.endOffset),Me.some(Zt=>dt.intersectsNode(Zt))},ye=s.useRef(de);s.useEffect(()=>{ye.current=de},[de]),s.useEffect(()=>{const Y=P.current;if(!Y)return;const he=Me=>{if(Me.inputType.startsWith("delete")&&je()&&Ue(Y,Me))return Me.preventDefault();const Ye=Me.inputType==="deleteContentBackward"?"Backspace":Me.inputType==="deleteContentForward"?"Delete":null;if(!Ye)return;const dt=Wx(Y,Ye);if(!(dt!=null&&dt.dataset.uid)){Kx(Y,Ye)&&Me.preventDefault();return}Me.preventDefault();const wt=ye.current(dt.dataset.uid);wt!=null&&Ra(Y,wt)};return Y.addEventListener("beforeinput",he),()=>Y.removeEventListener("beforeinput",he)},[]);const Ee=s.useCallback(Y=>{const he=as(Y.dataset.tok??"");if(!he||he.t!=="ref"&&he.t!=="mark")return!1;const Me=P.current,Ye=Me?Do(Me):null;return Ye!=null&&(H.current=Ye),F(),x==null||x({src:Mr(he.imageHash),kind:he.t,label:he.t==="mark"?Io(Y):null}),!0},[x,F]),be=s.useCallback((Y,he,Me,Ye)=>{const dt=Y.dataset.uid;dt&&(F(),Y.dataset.open="",Y.hasAttribute("aria-haspopup")&&Y.setAttribute("aria-expanded","true"),Y.removeAttribute("title"),K(null),U(""),Z({uid:dt,kind:he,anchor:Y,caret:Me,touch:Ye}))},[F]),Le=s.useCallback((Y,he)=>{var Zt;const Me=X.current;if(X.current=null,Z(null),!Me)return;const Ye=P.current,dt=Ye==null?void 0:Ye.querySelector(`[data-uid="${CSS.escape(Me.uid)}"]`);if(dt){delete dt.dataset.open,dt.hasAttribute("aria-haspopup")&&dt.setAttribute("aria-expanded","false");const Ht=as(dt.dataset.tok??""),pn=Ht?((Zt=z.current)==null?void 0:Zt.call(z,Ht))??null:null;pn&&(dt.title=pn)}const wt=he!==void 0?he:Me.caret;if(Me.touch){wt!=null&&(H.current=wt);return}Ye&&(Ye.focus({preventScroll:!0}),wt!=null?Ra(Ye,wt):Ol(Ye))},[]);s.useEffect(()=>{if(!O)return;const Y=P.current;Y!=null&&Y.querySelector(`[data-uid="${CSS.escape(O.uid)}"]`)||Le("outside")},[O,Le]),s.useEffect(()=>{var Y;B&&((Y=P.current)!=null&&Y.contains(B.anchor)||F())},[B,F]),s.useEffect(()=>{const Y=B==null?void 0:B.anchor;if(!Y)return;Y.dataset.open="";const he=Y.getAttribute("title");return he&&Y.removeAttribute("title"),()=>{delete Y.dataset.open,he&&Y.setAttribute("title",he)}},[B]),s.useImperativeHandle(N,()=>({insert:Y=>ve.current(Y),setTokens:Y=>{const he=P.current;he&&(Ux(he,Y.length?Y:Oo(),Me=>Xe(Me)),a0(he),n(Bx(he)))},removeTemplate:()=>{const Y=P.current,he=Y?Vd(Y):null;!Y||!he||(Fg(Y,he),ze())},remove:Y=>{const he=P.current;if(!he)return;const Me=Ig(he,Ta(Y));Me&&(Fg(he,Me),ze())},openMenu:Y=>{U(""),ne(Gd("$")),K({anchor:Y})},focus:()=>Ol(P.current),restoreCaret:()=>{const Y=P.current;if(!Y)return;Y.focus({preventScroll:!0});const he=H.current;he!=null?Ra(Y,he):Ol(Y)}}));const Qe=Rf(k),Ke=s.useCallback(Y=>_i(Y,Qe),[Qe]),nt=s.useMemo(()=>new Set(vo(r.id)),[r.id]),gt=s.useMemo(()=>{var Y;return D?vne(D.sigil??"$",{products:_i("product",Qe),presenters:_i("presenter",Qe),scenes:f?[]:_i("scene",Qe),colors:Zs((Y=r.json)==null?void 0:Y.palette)},{query:I,bookmarked:nt,shown:G}):{items:[],remaining:0,total:0}},[D,Qe,I,nt,G,f,(Ct=r.json)==null?void 0:Ct.palette]),Pt=s.useMemo(()=>gt.items.map(Y=>({...Y,run:()=>Y.token.t==="template"?u(Y.token.id):ve.current(Y.token)})),[gt.items,u]),Ut=s.useCallback(()=>{gt.remaining<=0||ne(Y=>Y+Gd(D==null?void 0:D.sigil))},[gt.remaining,D==null?void 0:D.sigil]),Nt=Y=>{const he=P.current,Me=Y.target;if(Me.closest('[data-role="remove"]')){if(Y.preventDefault(),je())return;const pn=Pi(Me);O&&(pn==null?void 0:pn.dataset.uid)===O.uid&&Le("remove"),pn!=null&&pn.dataset.uid&&de(pn.dataset.uid),K(null);return}const Ye=Pi(Me),dt=Ye==null?void 0:Ye.getBoundingClientRect();if(!(!!Ye&&!!dt&&Y.clientX-dt.left>Y1&&dt.right-Y.clientX>Y1)){if(HX(he))return;Gx(he,Y.clientX,Y.clientY);return}Gx(he,Y.clientX,Y.clientY);const Zt=Ye.dataset.uid??null;if(Zt&&(O==null?void 0:O.uid)===Zt){Y.detail!==0&&Le("outside");return}const Ht=hu(as(Ye.dataset.tok??""));if(!Ht){Ee(Ye);return}be(Ye,Ht,Do(he),!1)},cn=Y=>{if(Y.pointerType!=="mouse")return;const he=P.current;if(O||D||he&&"chipDrag"in he.dataset)return;const Me=Pi(Y.target),Ye=Me==null?void 0:Me.dataset.uid;if(!Me||!Ye||!Fe(Me)){te.close();return}if((B==null?void 0:B.uid)===Ye){te.keep();return}te.open({uid:Ye,anchor:Me})},Fe=Y=>{const he=as(Y.dataset.tok??"");if(e8(he))return!0;const Me=hu(he);return!!(Me&&Me!=="color"&&yh(Me)&&Y.querySelector("img"))},pt=Y=>{const he=Pi(Y.target),Me=he==null?void 0:he.dataset.uid;!he||!Me||O||D||Fe(he)&&Xp(he)&&te.open({uid:Me,anchor:he})},it=Y=>{if(Y.pointerType==="mouse")return;const he=Y.target;if(he.closest('[data-role="remove"]'))return;const Me=Pi(he);if(!Me)return;const Ye=Me.getBoundingClientRect();if(Y.clientX-Ye.left<=Y1||Ye.right-Y.clientX<=Y1)return;const dt=hne(as(Me.dataset.tok??""));if(!dt||Me.dataset.uid&&(O==null?void 0:O.uid)===Me.dataset.uid)return;Y.preventDefault();const wt=P.current,Zt=document.activeElement===wt,Ht=Zt?Do(wt):H.current;Zt&&(wt==null||wt.blur()),be(Me,dt,Ht,!0)},St=Y=>{const he=P.current,Me=Pi(Y.target);if(Me&&!O){const Ye=()=>{Vl(he,Me,"after"),he==null||he.focus({preventScroll:!0})};if(Y.altKey&&(Y.key==="ArrowLeft"||Y.key==="ArrowRight")){Y.preventDefault(),he&&Yx(he,Me,Y.key==="ArrowLeft"?-1:1)&&(Me.focus({preventScroll:!0}),ze(),T(A6(he,Me)));return}if(Y.key==="ArrowLeft"||Y.key==="ArrowRight"){Y.preventDefault(),Vl(he,Me,Y.key==="ArrowLeft"?"before":"after"),he==null||he.focus({preventScroll:!0});return}if(Y.key==="Tab"){Y.preventDefault(),Vl(he,Me,Y.shiftKey?"before":"after"),he==null||he.focus({preventScroll:!0});return}if(Y.key==="Enter"||Y.key===" "){Y.preventDefault();const dt=hu(as(Me.dataset.tok??""));dt&&he?be(Me,dt,ni(he,Me)+1,!1):Ee(Me);return}if(Y.key==="Backspace"||Y.key==="Delete"){if(Y.preventDefault(),je())return;const dt=Me.dataset.uid?de(Me.dataset.uid):null;he==null||he.focus({preventScroll:!0}),dt!=null&&Ra(he,dt);return}if(Y.key==="Escape"){Y.preventDefault(),Ye();return}}if(Y.key==="Escape"&&D){Y.preventDefault(),K(null),U("");return}if(Y.key==="Enter"&&!Y.shiftKey){const Ye=Y.defaultPrevented;Y.preventDefault(),Bte({menuOpen:!!D,handled:Ye})&&E();return}if(!(D||O)&&!Zte(Y)){if(!Y.shiftKey&&!Y.altKey&&!Y.metaKey&&!Y.ctrlKey){if(Y.key==="ArrowLeft"||Y.key==="ArrowRight"){_X(he,Y.key==="ArrowLeft"?"left":"right")&&Y.preventDefault();return}if(Y.key==="Backspace"||Y.key==="Delete"){const Ye=Wx(he,Y.key);if(Ye!=null&&Ye.dataset.uid){if(Y.preventDefault(),je())return;const dt=de(Ye.dataset.uid);dt!=null&&Ra(he,dt);return}if(Kx(he,Y.key)){Y.preventDefault();return}}}if((Y.key==="$"||Y.key==="/"||Y.key==="@"||Y.key==="#")&&!je()){const Ye=P.current,dt=wN(Ye),wt=dt.slice(-1);if(dt.length&&!/[\s\u00a0]/.test(wt))return;U(""),ne(Gd(Y.key)),K({anchor:{getBoundingClientRect:()=>yN()??(Ye==null?void 0:Ye.getBoundingClientRect())??new DOMRect},sigil:Y.key})}}},xt=s.useCallback(Y=>{var he,Me;return(Me=Zs((he=r.json)==null?void 0:he.palette).find(Ye=>Ye.hex===Y))==null?void 0:Me.name},[(st=r.json)==null?void 0:st.palette]),At=s.useCallback(()=>{requestAnimationFrame(()=>{const Y=$.current;if(!Y)return;Y.scrollHeight-Y.scrollTop-Y.clientHeight>1?Y.dataset.more="":delete Y.dataset.more})},[]);s.useEffect(()=>{const Y=$.current;if(!Y)return;At();const he=new ResizeObserver(At);he.observe(Y);for(const Me of Y.children)he.observe(Me);return()=>he.disconnect()},[At]);const Kt=Y=>{At();const he=P.current,Me=Y==null?void 0:Y.nativeEvent;if(Me!=null&&Me.isComposing)return;OX(he)||no(he),a0(he)&&Ol(he);const Ye=Se.current;Se.current=!1;const dt=_g(he,Zt=>Xe(Zt),{commit:Ye,nameFor:xt});dt&&(K(null),U(""));const wt=dt?{open:!1}:Ute(UX(he),Ye);wt.open?D&&(wt.query!==I&&ne(Gd(wt.sigil)),U(wt.query)):D&&(K(null),U("")),ze()},et=Y=>{const he=window.getSelection();if(!he||he.rangeCount===0||he.isCollapsed)return null;const Me=he.getRangeAt(0),{text:Ye,html:dt}=KX(Me);return Ye?(Y.clipboardData.setData("text/plain",Ye),Y.clipboardData.setData("text/html",dt),Y.preventDefault(),Me):null},mt=Y=>{et(Y)},ot=Y=>{const he=et(Y);he&&(he.deleteContents(),no(P.current),ze())},kn=s.useCallback(Y=>Y.t==="template"?a.some(he=>he.id===Y.id):Y.t==="product"?_.some(he=>he.id===Y.id)||l.some(he=>he.id===Y.id):Y.t==="character"?ue.some(he=>he.id===Y.id)||i.some(he=>he.id===Y.id):Y.t==="mark"?We.some(he=>he.hash===Y.imageHash):!0,[a,_,ue,i,l,We]);s.useEffect(()=>{const Y=P.current;if(Y)for(const he of Y.querySelectorAll(`.${Hl}[data-missing]`)){const Me=as(he.dataset.tok??"");Me&&kn(Me)&&he.replaceWith(Xe(Me,he.dataset.uid))}},[kn,Xe]);const ut=Y=>{Array.from(Y.dataTransfer.types).includes("Files")&&(Y.preventDefault(),ae.current++,ee(!0))},Gt=Y=>Y.preventDefault(),Ft=()=>{ae.current=Math.max(0,ae.current-1),ae.current===0&&ee(!1)},en=Y=>{Y.preventDefault(),ae.current=0,ee(!1),Y.dataTransfer.files.length&&(j==null||j(Y.dataTransfer.files))},Jt=Y=>{Y.preventDefault();const he=Y.clipboardData.files;if(he.length&&Array.from(he).some(dt=>dt.type.startsWith("image/"))){j==null||j(he);return}Se.current=!0;const Me=YX(Y.clipboardData.getData("text/html"));if(Me&&se(Me)){const dt=P.current;_g(dt,wt=>Xe(wt),{commit:!0,nameFor:xt})&&ze();return}const Ye=Y.clipboardData.getData("text/plain");Ye&&document.execCommand("insertText",!1,Ye)},se=Y=>{const he=P.current,Me=window.getSelection();if(!he||!Me||Me.rangeCount===0||!he.contains(Me.getRangeAt(0).startContainer))return!1;const Ye=Me.getRangeAt(0);Ye.deleteContents();let dt=!1,wt=Array.from(he.querySelectorAll(`.${Hl}`)).filter(Dt=>l0.has(Dt.dataset.kind??"")).length,Zt=!1;const Ht=new Set,pn=[];for(const Dt of Y){if(typeof Dt=="string"){pn.push(Dt);continue}if(!kn(Dt)){pn.push(Vne(Dt,a,_));continue}if(Dt.t==="template"){if(dt)continue;dt=!0}const On=Ta(Dt);if(On){if(Ht.has(On)||Ig(he,On))continue;Ht.add(On)}if(l0.has(Dt.t)&&!(Dt.t==="template"&&Vd(he))){if(wt>=Xh){Zt=!0;continue}wt+=1}pn.push(Dt)}Zt&&T(D6);const Wt=dt?Vd(he):null,wn=document.createDocumentFragment();for(const Dt of pn)wn.appendChild(typeof Dt=="string"?document.createTextNode(Dt):Xe(Dt));const sn=wn.lastChild;Ye.insertNode(wn),Wt&&Wt.remove();const In=sn?sn.nodeType===Node.TEXT_NODE?Vh(he,sn,sn.length):Vh(he,he,Array.from(he.childNodes).indexOf(sn)+1):Do(he)??0;return no(he),Ra(he,In),ze(),!0},oe=s.useCallback(()=>{requestAnimationFrame(()=>{const Y=P.current;Y&&document.activeElement===Y&&a0(Y)&&Ol(Y)})},[]),we=O?as(O.anchor.dataset.tok??""):null,ge=e8(we),J=we?(v==null?void 0:v(we))??null:null,Oe=we&&(w!=null&&w(we))?y??null:null,Be=B?as(B.anchor.dataset.tok??""):null,Ve=e8(Be),Ge=(($t=B==null?void 0:B.anchor.querySelector("img"))==null?void 0:$t.getAttribute("src"))??null,me=Ve?dn(Ve,"tile"):sr(Ge,"tile"),_e=hu(Be),W=Be&&yh(Be.t)?Be.t:_e&&_e!=="color"&&yh(_e)?_e:null,pe=Be?(v==null?void 0:v(Be))??null:null,Ie=Be&&(w!=null&&w(Be))?y??null:null,Te=je()?void 0:()=>{if(!O)return;const Y=de(O.uid);Le("remove",Y)};return o.jsxs("div",{className:"sc-brief",ref:$,onScroll:At,"data-drag-over":xe||void 0,children:[o.jsx("span",{id:M,className:"sc-vh",children:"Press Enter to open, Delete to remove, Alt plus arrow keys to move."}),o.jsx("span",{className:"sc-vh",role:"status","aria-live":"polite",children:C}),o.jsx("div",{ref:P,className:"sc-brief-line",contentEditable:!0,suppressContentEditableWarning:!0,role:"textbox","aria-multiline":"true","aria-autocomplete":"list","aria-expanded":D?!0:void 0,"aria-controls":D?i0:void 0,"aria-activedescendant":D?q??void 0:void 0,"aria-label":g,"aria-placeholder":h,tabIndex:0,dir:"auto","data-ph":h,...p?{"data-ph-sm":p}:{},onClick:Nt,onPointerDown:it,onPointerOver:cn,onPointerLeave:Y=>Y.pointerType==="mouse"&&te.close(),onFocusCapture:pt,onKeyDown:St,onInput:Kt,onCopy:mt,onCut:ot,onPaste:Jt,onDragEnter:ut,onDragOver:Gt,onDragLeave:Ft,onDrop:en,onFocus:oe,onBlur:()=>{const Y=P.current;_g(Y,he=>Xe(he),{commit:!0,nameFor:xt})&&(K(null),U("")),ze()}}),D&&o.jsx(ane,{anchor:D.anchor,composer:{getBoundingClientRect:()=>{var Y,he,Me;return((he=(Y=P.current)==null?void 0:Y.closest(".sc-promptcard"))==null?void 0:he.getBoundingClientRect())??((Me=P.current)==null?void 0:Me.getBoundingClientRect())??new DOMRect}},line:{getBoundingClientRect:()=>{var Y;return((Y=P.current)==null?void 0:Y.getBoundingClientRect())??new DOMRect}},query:I,options:Pt,remaining:gt.remaining,total:gt.total,sigil:D.sigil,onMore:Ut,onActiveId:le,onClose:()=>{K(null),U("")}}),B&&me&&W&&o.jsx(ad,{anchor:B.anchor,kind:W,src:me,label:Io(B.anchor),warning:pe,note:Ie,onOpen:()=>{const Y=B.anchor;if(Ve){Ee(Y);return}F(),x==null||x({src:me,kind:W,label:Io(Y)})},onHoverIn:te.keep,onHoverOut:te.close,onClose:F},B.uid),(O==null?void 0:O.kind)==="ref"||(O==null?void 0:O.kind)==="mark"?o.jsx(Rte,{kind:O.kind,label:Io(O.anchor),thumb:ge?dn(ge,"micro"):null,onInspect:()=>Ee(O.anchor),onMove:Y=>tt(O.uid,Y),onRemove:Te,onClose:Le},O.uid):(O==null?void 0:O.kind)==="color"?o.jsx(Ane,{anchor:O.anchor,currentHex:q1(O.anchor),currentName:_ne(O.anchor),palette:Zs((An=r.json)==null?void 0:An.palette),onPick:(Y,he)=>{var Ye;const Me=O.uid;if(he!=null&&he.live){const dt=(Ye=P.current)==null?void 0:Ye.querySelector(`[data-uid="${CSS.escape(Me)}"]`);dt&&nQ(dt,Y),ze();return}if(Zne(Y.hex,q1(O.anchor))){Le("pick");return}Pe(Me,Y),Le("pick")},onRemove:Te,onMove:Y=>tt(O.uid,Y),onClose:Le},O.uid):O?o.jsx(bne,{kind:O.kind,anchor:O.anchor,currentId:q1(O.anchor),candidates:Ke(O.kind),brandId:r.id,brandSlug:r.slug,warning:J,note:Oe,onAttachRequest:S?Y=>{Le("outside"),S(Y)}:void 0,onPick:Y=>{const he=O.uid;if(Y.id===q1(O.anchor)){Le("pick");return}Y.kind==="scene"?u(Y.id):Pe(he,Y.token),Le("pick")},onRemove:Te,onMove:Y=>tt(O.uid,Y),onClose:Le},O.uid):null]})});function q1(e){const t=as(e.dataset.tok??"");return t?t.t==="color"?t.hex:"id"in t?t.id:null:null}function _ne(e){const t=as(e.dataset.tok??"");return(t==null?void 0:t.t)==="color"?t.name:void 0}function Zne(e,t){const n=e?nr(e):null,r=t?nr(t):null;return!!n&&n===r}function Vne(e,t,n){var r,a;return e.t==="template"?((r=t.find(i=>i.id===e.id))==null?void 0:r.name)??"template":e.t==="product"?((a=n.find(i=>i.id===e.id))==null?void 0:a.name)??"product":e.t==="character"?"someone":e.t==="color"?e.name??e.hex:e.t==="mark"?"brand mark":e.t==="ref"?e.label??"Image":"reference"}function X1(e,t){return t===null?e===null:e===t}function zne(e){const t=e.closest(".sc-filterbar, .sc-toolbar"),n=t==null?void 0:t.closest("[data-page-scroll]");if(!t||!n)return;let r=t.nextElementSibling;for(;r&&r.getBoundingClientRect().height===0;)r=r.nextElementSibling;if(!r)return;const i=r.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-Number.parseFloat(getComputedStyle(t).marginBottom)-t.offsetHeight;if(n.scrollTop<=i+1)return;const l=window.matchMedia("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:i,behavior:l?"auto":"smooth"})}function qv({"aria-label":e,activeKey:t,items:n,onSelect:r}){const a=s.useRef(null),i=s.useRef(null),l=n.map(p=>`${p.value??""}:${p.count??""}`).join("|");s.useLayoutEffect(()=>{const p=a.current,g=i.current;if(!p||!g)return;let v=0;const w=()=>{const N=g.querySelector(":scope > button[data-on]");if(!N)return g.style.setProperty("--sc-ink-x","0px"),g.style.setProperty("--sc-ink-w","0px"),null;const P=N.querySelector(".sc-vlabel")??N;return g.style.setProperty("--sc-ink-x",`${N.offsetLeft+P.offsetLeft}px`),g.style.setProperty("--sc-ink-w",`${P.offsetWidth}px`),N},y=()=>{const N=g.scrollWidth-g.clientWidth;if(N<=1){delete p.dataset.overflowLeft,delete p.dataset.overflowRight;return}g.scrollLeft>2?p.dataset.overflowLeft="":delete p.dataset.overflowLeft,g.scrollLeft<N-2?p.dataset.overflowRight="":delete p.dataset.overflowRight},x=N=>{const P=g.scrollWidth-g.clientWidth;if(P<=0)return;const $=[...g.querySelectorAll(":scope > button")],M=$.indexOf(N);if(M<0)return;const C=72,R=g.scrollLeft,T=R+g.clientWidth,H=$[M-1],D=$[M+1],K=D?D.offsetLeft+Math.min(C,D.offsetWidth):N.offsetLeft+N.offsetWidth+8,O=H?Math.max(0,H.offsetLeft+H.offsetWidth-C):Math.max(0,N.offsetLeft-8);let Z=R;if(K>T)Z=Math.min(P,K-g.clientWidth);else if(O<R)Z=O;else return;if(Math.abs(Z-R)<1)return;const te=window.matchMedia("(prefers-reduced-motion: reduce)").matches;g.scrollTo({left:Z,behavior:te?"auto":"smooth"})},k=w();k&&x(k),y(),g.dataset.inkReady||requestAnimationFrame(()=>{g.dataset.inkReady=""});const S=()=>{v||(v=requestAnimationFrame(()=>{v=0,y()}))},E=N=>{if(g.scrollWidth<=g.clientWidth+1||Math.abs(N.deltaX)>Math.abs(N.deltaY)||N.deltaY===0)return;const P=g.scrollWidth-g.clientWidth,$=Math.max(0,Math.min(P,g.scrollLeft+N.deltaY));$!==g.scrollLeft&&(N.preventDefault(),g.scrollLeft=$,y())},j=new ResizeObserver(()=>{w(),y()});j.observe(g);for(const N of g.querySelectorAll(":scope > button"))j.observe(N);return g.addEventListener("scroll",S,{passive:!0}),g.addEventListener("wheel",E,{passive:!1}),()=>{v&&cancelAnimationFrame(v),j.disconnect(),g.removeEventListener("scroll",S),g.removeEventListener("wheel",E)}},[t,l]);const u=p=>{X1(t,p)||(a.current&&zne(a.current),r(p))},f=p=>{var y;if(p.key!=="ArrowLeft"&&p.key!=="ArrowRight"&&p.key!=="Home"&&p.key!=="End"||n.length===0)return;p.preventDefault();const g=Math.max(0,n.findIndex(x=>X1(t,x.value)));let v=g;if(p.key==="ArrowRight"?v=Math.min(n.length-1,g+1):p.key==="ArrowLeft"?v=Math.max(0,g-1):p.key==="Home"?v=0:p.key==="End"&&(v=n.length-1),v===g)return;u(n[v].value);const w=(y=i.current)==null?void 0:y.querySelectorAll(":scope > button")[v];w==null||w.focus()},h=n.findIndex(p=>X1(t,p.value));return o.jsx("div",{ref:a,className:"sc-verticals-shell",children:o.jsxs("div",{ref:i,className:"sc-verticals",role:"tablist","aria-label":e,onKeyDown:f,children:[o.jsx("span",{className:"sc-verticals-ink","aria-hidden":!0}),n.map((p,g)=>{const v=X1(t,p.value);return o.jsxs("button",{type:"button",role:"tab","aria-selected":v,"data-on":v?"":void 0,tabIndex:v||h<0&&g===0?0:-1,onClick:()=>u(p.value),children:[o.jsx("span",{className:"sc-vlabel",children:p.label}),p.count!==void 0&&o.jsx("span",{className:"sc-vcount",children:p.count})]},p.value??"__all__")})]})})}function id({value:e,onChange:t,noun:n,total:r,shortcut:a=!0}){const i=s.useRef(null),[l,u]=s.useState(e.trim().length>0),f=s.useCallback(()=>{var p;Rr.flushSync(()=>u(!0)),(p=i.current)==null||p.focus()},[]);s.useEffect(()=>{e.trim().length>0&&u(!0)},[e]),s.useEffect(()=>{if(!a)return;const p=g=>{if(g.key!=="/"||g.metaKey||g.ctrlKey||g.altKey)return;const v=g.target;v!=null&&v.isContentEditable||v&&/^(input|textarea|select)$/i.test(v.tagName)||(g.preventDefault(),f())};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[f,a]);const h=p=>{var g;p.key==="Escape"&&(p.stopPropagation(),e?t(""):(u(!1),(g=i.current)==null||g.blur()))};return o.jsxs("div",{className:"sc-libsearch","data-open":l?"":void 0,children:[o.jsx("button",{type:"button",className:"sc-libsearch-toggle","aria-label":`Search ${n}`,"aria-expanded":l,tabIndex:l?-1:0,onClick:f,children:o.jsx(Fu,{size:16})}),o.jsxs("div",{className:"sc-libsearch-field",children:[o.jsx(Fu,{size:15,"aria-hidden":!0}),o.jsx("input",{ref:i,type:"search",value:e,placeholder:r==null?`Search ${n}`:`Search ${r} ${n}`,"aria-label":`Search ${n}`,autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:l?0:-1,onChange:p=>t(p.target.value),onKeyDown:h,onBlur:()=>{e.trim()||u(!1)}}),o.jsx("button",{type:"button",className:"sc-libsearch-clear","aria-label":"Clear search",hidden:!e,tabIndex:e?0:-1,onMouseDown:p=>p.preventDefault(),onClick:()=>{var p;t(""),(p=i.current)==null||p.focus()},children:o.jsx(jn,{size:12,weight:"bold"})})]})]})}function TM({why:e,children:t}){return e?o.jsx(rv,{content:e,className:"sc-tip",maxWidth:"220px",children:CA(t)}):t}const Bne=["All","Products","Presenters","Scenes","Colors","Brand","Shots"],Qh=Bne.filter(e=>e!=="All"),t5={Products:"Products",Presenters:"Presenters",Scenes:"Scenes",Colors:"Brand colors",Brand:"Brand marks",Shots:"Shots"},Une={Products:"Product",Presenters:"Presenter",Scenes:"Scene",Colors:"Brand color",Brand:"Brand mark",Shots:"Reference shot"},H6={Products:"products",Presenters:"presenters",Scenes:"scenes",Colors:"brand colors",Brand:"brand marks",Shots:"shots"},Wne={Products:"square",Presenters:"square",Scenes:"square",Colors:"swatch",Brand:"square",Shots:"square"},$M={Products:132,Presenters:132,Scenes:132,Colors:132,Brand:132,Shots:132},O6={Products:96,Presenters:96,Scenes:96,Colors:96,Brand:96,Shots:96},n5=10;function Kne(e,t,n){const r=(n?O6:$M)[e];return r<=0||t<=0?1:Math.max(1,Math.floor((t+n5)/(r+n5)))}const Gne={product:"Products",presenter:"Presenters",scene:"Scenes"};function Yne(e){const t=Gne[e.kind];return{key:Ta(e.token),group:t,shape:Wne[t],label:e.label,sub:e.kind==="product"?e.sub:void 0,full:e.recommended?`${e.full} · Recommended`:e.full,search:e.search,thumb:sr(e.thumb??null,"small"),crop:e.crop,recommended:e.recommended,bookmarked:e.bookmarked,token:e.token}}function qne(e){const t=xf(e).map(r=>{const a=r.hash,i=qp(e,r);return{key:`m:${a}`,group:"Brand",shape:"square",label:i,full:`${i} · the mark itself`,search:i,thumb:dn(a,"micro"),token:{t:"mark",imageHash:a}}}),n=Zs(e==null?void 0:e.palette).map(r=>{const a={t:"color",hex:r.hex,name:r.name};return{key:Ta(a),group:"Colors",shape:"swatch",label:r.name,full:`${r.name} · ${r.hex}`,search:`${r.name} ${r.hex}`,swatch:r.hex,token:a}});return[...t,...n]}function Xne(e,t){return e.map((n,r)=>{const a=`Shot ${Math.max(1,t-r)}`;return{key:`r:${n.images[0]}`,group:"Shots",shape:"square",label:a,full:`${a} · joins the shot as a reference image`,search:a,thumb:dn(n.images[0],"micro"),token:{t:"ref",imageHash:n.images[0],label:"Shot"}}})}const r5=(e,t)=>wo(`${e.label} ${e.sub??""} ${e.search}`,t),DM=`
|
|
104
|
-
`;function Qne(e){return e.map(Ta).filter(t=>t.length>0).join(DM)}function Jne(e){return new Set(e?e.split(DM):[])}const ere=new Set(["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"]);function tre(e,t,n,r){const a=r.length?r[r.length-1].end+1:0;if(a===0)return t==="ArrowUp"?"search":null;const i=Math.max(1,n),l=r.findIndex(p=>e>=p.start&&e<=p.end),u=r[l]??{start:0,end:a-1},f=(e-u.start)%i,h=p=>p.start+Math.floor((p.end-p.start)/i)*i;switch(t){case"ArrowRight":return e+1<a?e+1:null;case"ArrowLeft":return e>0?e-1:null;case"Home":return 0;case"End":return a-1;case"ArrowDown":{if(e+i<=u.end)return e+i;if(e<h(u))return u.end;const p=r[l+1];return p?p.start+Math.min(f,p.end-p.start):null}case"ArrowUp":{if(e-i>=u.start)return e-i;const p=r[l-1];return p?Math.min(p.end,h(p)+f):"search"}}}function nre(e,t){const n=t.trim();return e==="All"?n?`Nothing matches “${n}”.`:"Nothing to add yet.":n?`No matching ${H6[e]}.`:e==="Shots"?"No finished shots yet.":`No ${H6[e]} yet.`}function rre(e){return[{value:null,label:"All",count:Qh.reduce((n,r)=>n+e[r],0)},...Qh.map(n=>({value:n,label:n,count:e[n]}))]}const sre=s.memo(function({card:t,index:n,active:r,ticked:a,why:i,onPick:l,onFocus:u}){const f=g=>{(g.key==="Enter"||g.key===" ")&&g.stopPropagation()},h=i&&!a?i:null,p=o.jsxs("button",{type:"button",className:"sc-ap-card","data-shape":t.shape,"data-group":t.group,"data-nav":n,"data-on":a?"":void 0,tabIndex:r?0:-1,"aria-disabled":h?!0:void 0,"aria-pressed":a,title:h??(a?`${t.label} is in the shot. Press to remove it.`:t.full),onClick:h?void 0:()=>l(n),onFocus:()=>u(n),onKeyDown:f,children:[t.shape==="swatch"?o.jsx("span",{className:"sc-ap-thumb sc-ap-swatch",style:{background:t.swatch},"aria-hidden":!0}):o.jsx(are,{src:t.thumb,crop:t.crop}),o.jsxs("span",{className:"sc-ap-cap",children:[o.jsxs("span",{className:"sc-vh",children:[Une[t.group],": "]}),o.jsx("b",{dir:"auto",children:t.label}),t.sub&&o.jsx("span",{dir:"auto",children:t.sub})]}),(a||!i)&&o.jsxs("span",{className:"sc-ap-puck","aria-hidden":!0,children:[o.jsx(cr,{className:"sc-ap-puck-add",size:11,weight:"bold"}),o.jsx(Kn,{className:"sc-ap-puck-on",size:11,weight:"bold"}),o.jsx(jn,{className:"sc-ap-puck-off",size:11,weight:"bold"})]}),a&&o.jsx("span",{className:"sc-vh",children:" In the shot."})]});return o.jsx(TM,{why:h,children:p})});function are({src:e,crop:t}){const[n,r]=s.useState(!1);return s.useEffect(()=>r(!1),[e]),o.jsx("span",{className:"sc-ap-thumb","data-empty":!e||n?"":void 0,children:!e||n?o.jsx(Ws,{size:16}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async","data-crop":t,onError:()=>r(!0)})})}function s5({onClick:e}){return o.jsxs("button",{type:"button",className:"sc-ap-card sc-ap-add sc-ap-upload-tile",title:"Add an image from your phone. It joins the shot as a reference.",onClick:e,children:[o.jsx("span",{className:"sc-ap-thumb",children:o.jsx(iv,{size:22,"aria-hidden":!0})}),o.jsx("span",{className:"sc-ap-cap",children:o.jsx("b",{children:"Upload image"})})]})}const ore=48,ire={items:[],total:0,hasMore:!1,loading:!1,settled:!1,error:null,loadMore:()=>{}};function Xv(e,t,n=!0){const r=t.trim(),{shotsEpoch:a,subscribeActivity:i}=on(),l=`${e}|${r}|${a}`,[u,f]=s.useState({key:"",items:[],next:null,total:0}),[h,p]=s.useState(!1),[g,v]=s.useState(null),w=s.useRef(null),y=s.useCallback(async S=>{var j;(j=w.current)==null||j.abort();const E=new AbortController;w.current=E,p(!0),v(null);try{const N=await Re.feed(e,{lens:"all",sort:"newest",q:r,limit:ore,cursor:S??void 0},E.signal);if(E.signal.aborted)return;f(P=>{var M;const $=S===null||P.key!==l;return{key:l,items:$?N.items:[...P.items,...N.items],next:N.next,total:((M=N.counts)==null?void 0:M.all)??($?N.items.length:P.total)}})}catch(N){if(E.signal.aborted)return;v(String(N.message??N))}finally{E.signal.aborted||p(!1)}},[e,r,l]);s.useEffect(()=>{if(!n)return;const S=u.key===""?0:150,E=setTimeout(()=>void y(null),S);return()=>clearTimeout(E)},[y,n]),s.useEffect(()=>()=>{var S;return(S=w.current)==null?void 0:S.abort()},[]),s.useEffect(()=>i(S=>{const E=new Map(S.map(j=>[j.id,j]));f(j=>{if(!j.items.some(P=>E.has(P.id)))return j;const N=j.items.flatMap(P=>{const $=E.get(P.id);return $?$.archived?[]:[{...P,...$}]:[P]});return{...j,items:N,total:Math.max(0,j.total-(j.items.length-N.length))}})}),[i]);const x=u.key===l?u:null,k=s.useCallback(()=>{x!=null&&x.next&&y(x.next)},[x==null?void 0:x.next,y]);return x?{items:x.items.filter(S=>S.status==="done"&&S.images.length>0),total:x.total,hasMore:x.next!==null,loading:h,settled:!0,error:g,loadMore:k}:{...ire,loading:h,error:g,loadMore:k}}const t8={Products:"product",Presenters:"presenter",Scenes:"scene"};function lre({brand:e,tab:t,onTab:n,only:r,activeProductCategory:a,refining:i,full:l,attached:u,phone:f,touch:h,onPick:p,onRemove:g,onUpload:v,onFiles:w,onClose:y}){const x=s.useRef(a).current,k=Rf(x),S=s.useMemo(()=>new Set(vo(e.id)),[e.id]),E=ll(),{applyBrand:j}=Rn(),{push:N}=or(),[P,$]=s.useState(!1),[M,C]=s.useState(""),R=s.useDeferredValue(M),[T,H]=s.useState(Fi),[D,K]=s.useState(0),[O,Z]=s.useState(f?347:696),te=s.useRef(null),B=s.useRef(null);s.useEffect(()=>{H(Fi),K(0)},[t,R]),s.useLayoutEffect(()=>{const ce=B.current;if(!ce)return;const ve=()=>Z(ce.clientWidth-2*ure(ce));ve();const Pe=new ResizeObserver(ve);return Pe.observe(ce),()=>Pe.disconnect()},[]);const F=s.useMemo(()=>({product:_i("product",k),presenter:_i("presenter",k),scene:_i("scene",k)}),[k]),X=s.useMemo(()=>qne(e.json),[e.json]),z=Xv(e.id,R),I=s.useMemo(()=>Xne(z.items,z.total),[z.items,z.total]),U=s.useMemo(()=>{const ce={};for(const ve of Qh){const Pe=t8[ve];ce[ve]=ve==="Shots"?z.total:Pe?Pu(F[Pe],R).length:X.filter(de=>de.group===ve&&r5(de,R)).length}return ce},[F,X,R,z.total]),G=s.useCallback((ce,ve)=>{const Pe=t8[ce];if(Pe){const je=hm(Pe,F[Pe],{currentId:null,query:R,bookmarked:S,shown:ve});return{group:ce,items:je.items.map(Yne),total:je.total,remaining:je.remaining}}if(ce==="Shots"){const je=I.slice(0,ve),Ue=z.hasMore?Math.max(1,z.total-I.length):Math.max(0,I.length-ve);return{group:ce,items:je,total:z.total,remaining:Ue}}const de=X.filter(je=>je.group===ce&&r5(je,R));return{group:ce,items:de.slice(0,ve),total:de.length,remaining:Math.max(0,de.length-ve)}},[F,X,R,S,I,z.hasMore,z.total]),ne=s.useMemo(()=>{if(t==="All"){const ce=[];for(const ve of Qh){const Pe=Kne(ve,O,f),de=G(ve,f&&ce.length===0?Math.max(1,Pe-1):Pe);de.items.length>0&&ce.push(de)}return ce}return[G(t,t==="Shots"?Number.MAX_SAFE_INTEGER:T)]},[t,G,T,O,f]),{flat:q,navGroups:le}=s.useMemo(()=>{const ce=[],ve=[];for(const Pe of ne)Pe.items.length&&(ve.push({start:ce.length,end:ce.length+Pe.items.length-1}),ce.push(...Pe.items));return{flat:ce,navGroups:ve}},[ne]);s.useEffect(()=>{K(ce=>Math.max(0,Math.min(ce,q.length-1)))},[q.length]);const Se=s.useCallback(ce=>{var Pe;const ve=(Pe=B.current)==null?void 0:Pe.querySelector(`[data-nav="${ce}"]`);ve&&(K(ce),ve.focus({preventScroll:!0}),ve.scrollIntoView({block:"nearest"}))},[]),Q=s.useRef(null),xe=s.useRef(()=>{});xe.current=()=>{const ce=ne[0];!ce||t==="All"||ce.remaining<=0||(ce.group==="Shots"?z.loading||z.loadMore():H(ve=>ve+Fi))},s.useEffect(()=>{const ce=Q.current,ve=B.current;if(!ce||!ve)return;const Pe=new IntersectionObserver(de=>{de.some(je=>je.isIntersecting)&&xe.current()},{root:ve,rootMargin:"0px 0px 240px 0px"});return Pe.observe(ce),()=>Pe.disconnect()},[t,ne]);const ee=s.useCallback(ce=>{var Pe,de;const ve=q[ce];ve&&(u.has(ve.key)?g(ve):p(ve),h&&((de=(Pe=document.activeElement)==null?void 0:Pe.blur)==null||de.call(Pe)))},[q,u,h,p,g]),ae=ce=>{const ve=ce.clipboardData.files;!ve.length||!Array.from(ve).some(Pe=>Pe.type.startsWith("image/"))||(ce.preventDefault(),w(ve))},re=ce=>{var Ue,ye;const ve=ce.target,Pe=ve instanceof HTMLInputElement&&!!((Ue=te.current)!=null&&Ue.contains(ve));if(ce.key==="Escape"){if(Pe)return;ce.preventDefault(),ce.stopPropagation(),y();return}if(Pe){ce.key==="ArrowDown"?(ce.preventDefault(),ce.stopPropagation(),Se(0)):ce.key==="Enter"&&(ce.preventDefault(),ce.stopPropagation(),ee(0));return}if(!ere.has(ce.key)||(ce.stopPropagation(),ve.closest('[role="tablist"]')))return;const de=ve.closest("[data-nav]");if(!de)return;ce.preventDefault();const je=tre(D,ce.key,cre(de.closest(".sc-ap-grid")),le);if(je==="search"){const Ee=te.current;(ye=(Ee==null?void 0:Ee.querySelector(".sc-libsearch[data-open] input"))??(Ee==null?void 0:Ee.querySelector(".sc-libsearch-toggle")))==null||ye.focus()}else je!=null&&Se(je)},_=async ce=>{$(!0);try{const ve=await Nj(e.id,ce);j(ve);const Pe=ve.logoHash;Pe&&p({key:`m:${Pe}`,group:"Brand",shape:"square",label:"Logo",full:"Logo",search:"",token:{t:"mark",imageHash:Pe}});const de=ve.logoEdge;de&&de<512&&N({kind:"warning",title:"Logo added, but it is small",detail:`Only ${de}px across. Fine lettering may not survive generation. Export it larger, or as SVG.`})}catch(ve){N(nn(ve,"Could not upload that logo"))}finally{$(!1)}},ue=ce=>E(ce,{onCreated:ve=>{if(ve.kind===ce){if(ve.kind==="product"){const Pe={t:"product",id:ve.id};p({key:Ta(Pe),group:"Products",shape:"square",label:"Product",full:"",search:"",token:Pe});return}if(ve.kind==="presenter"){const Pe={t:"character",id:ve.id};p({key:Ta(Pe),group:"Presenters",shape:"square",label:"Presenter",full:ve.name,search:ve.name,token:Pe});return}n("Scenes")}}}),We=async ce=>{var de;const ve=VA((de=e.json)==null?void 0:de.palette,ce);if(!ve.swatch)return;if(ve.added)try{const je=await Re.updateBrand(e.id,{...e.json??{},palette:ve.palette});j(je)}catch(je){N(nn(je,"Could not save the brand"));return}const Pe={t:"color",hex:ve.swatch.hex,name:ve.swatch.name};p({key:Ta(Pe),group:"Colors",shape:"swatch",label:ve.swatch.name,full:"",search:"",swatch:ve.swatch.hex,token:Pe})},Xe=ce=>i&&ce==="Scenes"?"Scenes set up a new shot. Press X on Refining to use one.":l&&ce!=="Colors"?l:null,ze=q.length===0;let tt=0;return o.jsxs("div",{className:"sc-ap-inner",onKeyDown:re,onPaste:ae,children:[o.jsxs("div",{className:"sc-ap-head",ref:te,children:[o.jsx("div",{className:"sc-ap-tabs",children:o.jsx(qv,{"aria-label":"What to add",activeKey:t==="All"?null:t,items:rre(U),onSelect:ce=>n(ce??"All")})}),o.jsxs("div",{className:"sc-ap-actions",children:[o.jsxs("div",{className:"sc-ap-actions-add",children:[o.jsx(id,{value:M,onChange:C,noun:t==="All"?"everything":H6[t],total:t==="All"?void 0:U[t],shortcut:!1}),!f&&o.jsxs("button",{type:"button",className:"sc-btn sc-btn-primary sc-ap-upload",onClick:v,title:"Add an image from your computer. It joins the shot as a reference.",children:[o.jsx(iv,{size:14,"aria-hidden":!0}),o.jsx("span",{children:"Upload image"})]})]}),!f&&o.jsx("button",{type:"button",className:"sc-icon-btn sc-ap-close",onClick:y,"aria-label":"Close",children:o.jsx(jn,{size:14})})]})]}),o.jsxs("div",{className:"sc-ap-body",ref:B,children:[i&&t==="Scenes"&&o.jsx("p",{className:"sc-ap-hint",children:"Scenes set up a new shot, so they sit out while you are refining. Press X on Refining to use one."}),ne.map((ce,ve)=>{var Ee,be,Le;const Pe=Xe(ce.group),de=tt;tt+=ce.items.length;const je=t8[ce.group],ye={"--ap-min":`${(f?O6:$M)[ce.group]}px`,"--ap-lines":je==="product"?2:1};return o.jsxs("section",{className:"sc-ap-group","aria-label":t5[ce.group],children:[o.jsxs("div",{className:"sc-ap-sec",children:[o.jsxs("span",{className:"sc-ap-sec-title",children:[t5[ce.group],o.jsx("span",{className:"sc-ap-sec-n",children:ce.total})]}),t==="All"&&ce.total>ce.items.length&&o.jsxs("button",{type:"button",className:"sc-ap-sec-act",onClick:()=>n(ce.group),children:["Show all ",ce.total]}),t==="Products"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("product"),children:"Add product"}),t==="Presenters"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("presenter"),children:"Create presenter"}),t==="Scenes"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("scene"),children:"Create scene"}),t==="Colors"&&o.jsx(Zu,{className:"sc-ap-sec-act sc-ap-add",triggerStyle:{background:"none"},value:Jp(Zs((Ee=e.json)==null?void 0:Ee.palette)),presets:Zs((be=e.json)==null?void 0:be.palette).map(Qe=>Qe.hex),commitMode:"close",align:"end",label:"Add color",onChange:Qe=>void We(Qe),children:"Add color"}),t==="Brand"&&o.jsxs("label",{className:"sc-ap-sec-act sc-ap-add",title:"Add your logo to the brand kit","data-busy":P||void 0,children:[o.jsx("input",{type:"file",accept:"image/*",className:"sc-vh",disabled:P,onChange:Qe=>{var nt;const Ke=(nt=Qe.target.files)==null?void 0:nt[0];Qe.target.value="",Ke&&_(Ke)}}),"Add logo"]})]}),o.jsxs("div",{className:"sc-ap-grid","data-shape":((Le=ce.items[0])==null?void 0:Le.shape)??"square",style:ye,children:[f&&ve===0&&!r&&o.jsx(s5,{onClick:v}),ce.items.map((Qe,Ke)=>o.jsx(sre,{card:Qe,index:de+Ke,active:de+Ke===D,ticked:u.has(Qe.key),why:Pe,onPick:ee,onFocus:K},Qe.key))]}),t!=="All"&&ce.remaining>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:Q,className:"sc-ap-sentinel","aria-hidden":!0}),o.jsxs("p",{className:"sc-ap-foot","aria-live":"polite",children:[ce.items.length," of ",ce.total]})]})]},ce.group)}),t==="Shots"&&z.error&&o.jsxs("p",{className:"sc-ap-empty",children:["Could not load the shots. ",z.error]}),ze&&f&&o.jsx("div",{className:"sc-ap-grid",style:{"--ap-min":`${O6.Products}px`},children:o.jsx(s5,{onClick:v})}),ze&&!(t==="Shots"&&(!z.settled||z.loading||z.error))&&o.jsx("p",{className:"sc-ap-empty",children:nre(t,M)})]})]})}function cre(e){return e?Math.max(1,getComputedStyle(e).gridTemplateColumns.split(" ").filter(Boolean).length):1}function ure(e){return Number.parseFloat(getComputedStyle(e).paddingLeft)||0}const dre="(pointer: coarse)";function fre(e){const t=wr(Ks),n=wr(dre),[r,a]=s.useState(e.initialTab??"All");s.useEffect(()=>{a(e.initialTab??"All")},[e.initialTab,e.tabNonce]);const[i]=el(),l=i.get("new")!==null;return o.jsx(hre,{id:e.id,phone:t,touch:n,creating:l,onClose:e.onClose,children:o.jsx(lre,{brand:e.brand,tab:e.only??r,onTab:a,only:e.only,activeProductCategory:e.activeProductCategory,refining:e.refining,full:e.full,attached:e.attached,phone:t,touch:n,onPick:e.onPick,onRemove:e.onRemove,onUpload:e.onUpload,onFiles:e.onFiles,onClose:()=>e.onClose({restore:!n})})})}function hre({id:e,phone:t,touch:n,creating:r,onClose:a,children:i}){const l=s.useRef(null),u=()=>{var p;return a({restore:!n&&!!((p=l.current)!=null&&p.contains(document.activeElement))})},f=s.useRef(u);f.current=u,s.useEffect(()=>{var p,g;n&&((g=(p=document.activeElement)==null?void 0:p.blur)==null||g.call(p))},[n]),s.useLayoutEffect(()=>{var y,x;const p=l.current,g=p==null?void 0:p.parentElement;if(!t||!p||!g)return;const v=()=>{const k=p.closest(".sc-shell")??document.documentElement,S=Number.parseFloat(getComputedStyle(k).getPropertyValue("--sc-topbar-h"))||0,E=g.getBoundingClientRect().top-S-16;p.style.setProperty("--ap-avail",`${Math.max(160,Math.round(E))}px`)};v();const w=new ResizeObserver(v);return w.observe(g),window.addEventListener("resize",v),(y=window.visualViewport)==null||y.addEventListener("resize",v),(x=window.visualViewport)==null||x.addEventListener("scroll",v),()=>{var k,S;w.disconnect(),window.removeEventListener("resize",v),(k=window.visualViewport)==null||k.removeEventListener("resize",v),(S=window.visualViewport)==null||S.removeEventListener("scroll",v)}},[t]),s.useEffect(()=>{const p=g=>{var w;if(g.key!=="Escape"||r)return;const v=document.activeElement;v instanceof HTMLInputElement&&((w=l.current)!=null&&w.contains(v))||(g.preventDefault(),g.stopPropagation(),f.current())};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[r]);const h=p=>{var w;const g=document.activeElement,v=p.target;g instanceof HTMLInputElement&&((w=l.current)!=null&&w.contains(g))&&!v.closest("input")&&g.blur(),N6(p)};return s.useEffect(()=>{const p=g=>{if(r)return;const v=g.target;v.closest('[data-guide="catch"], [data-guide="card"], [data-guide="inline"]')||document.querySelector('[data-guide="catch"]')||v.closest(".sc-attachpanel, .sc-attach-toggle, [data-attach-opener]")||f.current()};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[r]),o.jsx("div",{ref:l,className:"sc-attachpanel","data-guide-shape":"",role:"dialog",id:e,"aria-label":"Add to shot",onMouseDownCapture:h,children:i})}function pre({target:e,onOpenImage:t,onClear:n}){var f;const r=od(),a=e.images[0],l=(((f=e.brief)==null?void 0:f.tokens)??[]).filter(h=>h.t==="text"&&typeof h.v=="string").map(h=>h.v.trim()).join(" ").trim()||Sr(e),u=s.useCallback(()=>{a&&(r.closeNow(),t())},[a,r.closeNow,t]);return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"sc-token sc-target-chip",role:"button",tabIndex:0,"aria-haspopup":"dialog","aria-label":n?`Version being refined: ${l}. Open the image, or remove to make a new shot.`:`Version being refined: ${l}. Open the image.`,onPointerEnter:h=>{h.pointerType==="mouse"&&a&&r.open({anchor:h.currentTarget})},onPointerLeave:h=>h.pointerType==="mouse"&&r.close(),onClick:u,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[a?o.jsx("img",{src:dn(a,"micro"),alt:""}):o.jsx("span",{className:"sc-target-thumb sc-shimmer"}),"Refining",n&&o.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),r.closeNow(),n()},"aria-label":"Make a new shot instead",children:o.jsx(jn,{size:12})})]}),r.shown&&a&&o.jsx(ad,{anchor:r.shown.anchor,kind:"shot",src:dn(a,"tile"),label:l,noun:"Refining this shot",onOpen:u,onHoverIn:r.keep,onHoverOut:r.close,onClose:r.closeNow})]})}function Uu({src:e,kind:t,label:n,noun:r,actions:a,onRestoreFocus:i,onClose:l}){const[u,f]=s.useState(!1),h=r??bM[t],p=s.useRef(null);return o.jsxs(Ts,{className:"sc-lightbox",maxWidth:"min(880px, 92vw)",onOpenAutoFocus:()=>{p.current=document.activeElement},onCloseAutoFocus:g=>{var v;if(g.preventDefault(),i)return i();(v=p.current)!=null&&v.isConnected&&p.current.focus()},onDismiss:l,children:[o.jsx("div",{className:"sc-lightbox-frame","data-kind":t,children:u?o.jsxs("span",{className:"sc-lightbox-blank",children:[o.jsx(Ws,{size:28}),"Image unavailable"]}):o.jsx("img",{src:e,alt:n?`${n}, ${h.toLowerCase()}`:h,onError:()=>f(!0)})}),o.jsxs("p",{className:"sc-lightbox-cap",children:[n&&o.jsx("b",{dir:"auto",children:n}),o.jsx("span",{children:h})]}),a&&o.jsx("div",{className:"sc-lightbox-acts",children:a})]})}const mre={"codex-cli":{sizing:"advisory"},openrouter:{sizing:"ratio"},replicate:{sizing:"ratio",formats:["square","story","landscape"]},fal:{sizing:"exact"},demo:{sizing:"exact"}},gre={sizing:"exact"},HM=e=>mre[e]??gre;function vre(e,t){const n=HM(e).formats;return!n||n.includes(t)}const Qv=e=>HM(e).sizing,Zi=[{id:"draft",label:"Draft",edge:768,note:"quick checks"},{id:"standard",label:"Standard",edge:1024,note:"everyday shots"},{id:"high",label:"High",edge:1536,note:"hero and print"}],Jh=[1,2,3,4],OM=e=>Xr.filter(t=>!vre(e,t.id)).map(t=>t.id),I6=(e,t)=>t.length===0?void 0:`${e} cannot make ${Xr.filter(n=>t.includes(n.id)).map(n=>n.hint).join(" or ")}.`,Jv=e=>{var n;e.preventDefault();const t=e.currentTarget??e.target;(n=t==null?void 0:t.querySelector('[role="radiogroup"]'))==null||n.focus()};function n8({aria:e,width:t,trigger:n,open:r,onOpenChange:a,children:i,onCloseAutoFocus:l,guide:u}){const f=s.useRef(null);return s.useEffect(()=>{var p;const h=(p=f.current)==null?void 0:p.parentElement;h&&(h.style.pointerEvents=r?"":"none")},[r]),o.jsxs(Hu,{open:r,onOpenChange:a,children:[o.jsx(Ou,{children:o.jsx("button",{type:"button",className:"sc-var","aria-label":e,"data-guide":u,children:n})}),o.jsx(Iu,{ref:f,className:"sc-setpop",align:"end",sideOffset:8,width:t,onOpenAutoFocus:Jv,onCloseAutoFocus:l,onInteractOutside:h=>{var p;(p=h.target)!=null&&p.closest(".sc-prompt-pills")&&h.preventDefault()},children:i(()=>a(!1))})]})}function wre({mode:e,engineId:t,engineName:n,formatId:r,onFormat:a,count:i,onCount:l,quality:u,onQuality:f,onCloseAutoFocus:h,guided:p=!1,onSettle:g}){const v=Xr.find($=>$.id===r)??Xr[0],w=Zi.find($=>$.id===u)??Zi[1],y=OM(t),x=Qv(t),[k,S]=s.useState(null),E=s.useRef(null);E.current=k;const j=$=>{$.preventDefault(),E.current===null&&(h==null||h($))},N={aspect:"shape",variants:"count",resolution:"quality"},P=$=>({open:k===$,onCloseAutoFocus:j,guide:p?`compose.${N[$]}`:void 0,onOpenChange:M=>{!M&&E.current===$&&(g==null||g(N[$])),S(C=>M?$:C===$?null:C)}});return o.jsxs("div",{className:"sc-prompt-pills","data-guide":p?"compose.settings-row":void 0,children:[o.jsx(n8,{...P("aspect"),aria:`Aspect ${v.label}, ${v.hint}`,width:"178px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(v6,{w:v.w,h:v.h,slot:15,box:13}),v.label]}),children:$=>o.jsxs(o.Fragment,{children:[o.jsx(_o,{label:"Aspect ratio",className:"sc-setpop-list",value:r,ids:Xr.map(M=>M.id),unavailable:y,onChange:a,children:Xr.map(M=>o.jsxs(Zo,{id:M.id,className:"sc-setrow",on:M.id===r,unavailable:y.includes(M.id),label:`${M.label}, ${M.hint}`,onPick:()=>{a(M.id),$()},children:[o.jsx(v6,{w:M.w,h:M.h,slot:20,box:17}),o.jsx("span",{className:"sc-setrow-n",children:M.label}),o.jsx("span",{className:"sc-setrow-v",children:M.hint}),o.jsx(kx,{})]},M.id))}),I6(n,y)&&o.jsx(gY,{children:I6(n,y)})]})}),e==="generation"&&o.jsx(n8,{...P("variants"),aria:`${i} shot${i===1?"":"s"}`,width:"156px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(dj,{size:14}),i]}),children:$=>o.jsx(o.Fragment,{children:o.jsx(_o,{label:"Shots",className:"sc-seg",value:String(i),ids:Jh.map(String),onChange:M=>l(Number(M)),children:Jh.map(M=>o.jsx(Zo,{id:String(M),className:"sc-seg-o",on:M===i,label:`${M} shot${M===1?"":"s"}`,onPick:()=>{l(M),$()},children:M},M))})})}),e==="generation"&&x!=="ratio"&&o.jsx(n8,{...P("resolution"),aria:`Resolution ${w.label}, ${w.edge} px`,width:"192px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(TC,{size:14}),w.label]}),children:$=>o.jsx(o.Fragment,{children:o.jsx(_o,{label:"Resolution",className:"sc-setpop-list",value:u,ids:Zi.map(M=>M.id),onChange:M=>f(M),children:Zi.map(M=>o.jsxs(Zo,{id:M.id,className:"sc-setrow",on:M.id===u,label:`${M.label}, ${M.edge} px, ${M.note}`,onPick:()=>{f(M.id),$()},children:[o.jsx("span",{className:"sc-setrow-n",children:M.label}),o.jsxs("span",{className:"sc-setrow-v",children:[M.edge," px"]}),o.jsx(kx,{})]},M.id))})})})]})}function IM({mode:e,engineId:t,engineName:n,formatId:r,onFormat:a,count:i,onCount:l,quality:u,onQuality:f,engineChoices:h,onEngine:p}){const g=OM(t),v=Qv(t);return o.jsxs(o.Fragment,{children:[h&&p&&h.length>1&&o.jsx(Q1,{label:"Engine",children:o.jsx(_o,{label:"Engine",className:"sc-seg",value:t,ids:h.map(w=>w.id),onChange:p,children:h.map(w=>o.jsx(Zo,{id:w.id,className:"sc-seg-o",on:w.id===t,label:w.displayName,onPick:()=>p(w.id),children:w.displayName},w.id))})}),o.jsx(Q1,{label:"Aspect ratio",note:I6(n,g),children:o.jsx(_o,{label:"Aspect ratio",className:"sc-seg",value:r,ids:Xr.map(w=>w.id),unavailable:g,onChange:a,children:Xr.map(w=>o.jsxs(Zo,{id:w.id,className:"sc-seg-o sc-seg-ratio",on:w.id===r,unavailable:g.includes(w.id),label:`${w.label}, ${w.hint}`,onPick:()=>a(w.id),children:[o.jsx(v6,{w:w.w,h:w.h,slot:17,box:14}),w.hint]},w.id))})}),e==="generation"&&o.jsx(Q1,{label:"Shots",children:o.jsx(_o,{label:"Shots",className:"sc-seg",value:String(i),ids:Jh.map(String),onChange:w=>l(Number(w)),children:Jh.map(w=>o.jsx(Zo,{id:String(w),className:"sc-seg-o",on:w===i,label:`${w} shot${w===1?"":"s"}`,onPick:()=>l(w),children:w},w))})}),e==="generation"&&v!=="ratio"&&o.jsx(Q1,{label:"Resolution",note:v==="advisory"?"This engine renders at its own size, so this is a request rather than a guarantee.":void 0,children:o.jsx(_o,{label:"Resolution",className:"sc-seg",value:u,ids:Zi.map(w=>w.id),onChange:w=>f(w),children:Zi.map(w=>o.jsx(Zo,{id:w.id,className:"sc-seg-o",on:w.id===u,label:v==="advisory"?`${w.label}, asks for ${w.edge} px, ${w.note}`:`${w.label}, ${w.edge} px, ${w.note}`,onPick:()=>f(w.id),children:w.label},w.id))})})]})}function Q1({label:e,note:t,children:n}){return o.jsxs("div",{className:"sc-shotfield",children:[o.jsx("span",{className:"sc-shotfield-lb",children:e}),n,t&&o.jsx("p",{className:"sc-shotfield-note",children:t})]})}function yre({guide:e,onSettle:t,...n}){const[r,a]=s.useState(!1),i=f=>{!f&&r&&(t==null||t()),a(f)},{sheet:l,grip:u}=ed(()=>i(!1));return o.jsxs(fc,{open:r,onOpenChange:i,children:[o.jsx(g4,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-var sc-shotset","aria-label":"Shot settings",title:"Shot settings","data-guide":e,children:o.jsx(ov,{size:16})})}),o.jsxs(hc,{children:[o.jsx(pc,{className:"sc-shotsheet-scrim"}),o.jsxs(mc,{ref:l,className:"sc-shotsheet","aria-describedby":void 0,onOpenAutoFocus:Jv,onCloseAutoFocus:f=>f.preventDefault(),children:[o.jsxs("div",{className:"sc-shotsheet-grip",...u,children:[o.jsx("span",{className:"sc-shotsheet-bar","aria-hidden":!0}),o.jsx(gc,{className:"sc-vh",children:"Shot settings"})]}),o.jsx(IM,{...n})]})]})]})}const yu=e=>`scenri:draft-${e}`,bre=e=>cs.get(e),xre=(e,t)=>cs.set(e,t),bh=e=>cs.del(e);function a5(e,t){return e.some(n=>n.t==="text"?!!n.v.trim():n.t!=="template")||Object.values(t).some(n=>!!n.trim())}function kre(e){const t=bre(yu(e));if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null)return null;const r=n;if(r.v!==1||r.brandId!==e||!Array.isArray(r.tokens)||typeof r.tplFields!="object"||!r.tplFields||r.branchId)return bh(yu(e)),null;const a=Date.now()-Date.parse(r.updatedAt??"");return!Number.isFinite(a)||a>zj?(bh(yu(e)),null):{v:1,brandId:e,updatedAt:r.updatedAt,tokens:r.tokens,tplFields:r.tplFields,setSlug:r.setSlug??null}}function FM(e,t){const n={v:1,brandId:e,updatedAt:new Date().toISOString(),tokens:t.tokens,tplFields:t.tplFields,setSlug:t.setSlug??null};xre(yu(e),JSON.stringify(n))}function o5(e){bh(yu(e))}function i5(e,t,n,r,a){if(e===t)return{changed:!1,toast:null};const i=!!r;return e===null&&!i?{changed:!0,toast:null}:{changed:!0,toast:{title:i?`Switched to ${n}. This starts a new shot instead of refining ${a??"that shot"}.`:`Switched to ${n}.`,prevSceneId:e,branchWasCleared:i}}}function Sre(e,t){return e>0&&t>0&&Math.abs(Math.log(t))<Math.abs(Math.log(e))-.01?"crop":"extend"}const r8=2,Ere=.15;function Cre(e,t){if(Sre(e,t)==="crop")return"crop";if(!(e>0&&t>0))return"extend";const n=t>e?t/e:e/t;return(n>r8?Math.max(r8,n*(1-Ere)):n)>r8+1e-9?"crop":"extend"}const F6=4,ep=24,v0=24,_M={product:[],presenter:[],scene:null,ref:[],color:[]};function jre(e){const t=[],n=[],r=[],a=[];let i=null;const l=(u,f)=>{u.includes(f)||u.push(f)};for(const u of e)u.t==="product"?l(t,u.id):u.t==="character"?l(n,u.id):u.t==="template"?i=u.id:u.t==="ref"?l(r,u.imageHash):u.t==="color"&&l(a,u.hex.toLowerCase());return{product:t,presenter:n,scene:i,ref:r,color:a}}function Are(e){return`${e.product.join(",")}|${e.presenter.join(",")}|${e.scene??""}|${e.ref.join(",")}|${e.color.join(",")}`}function Nre(e,t,n){const r=e.slice(0,n);return{visible:r,more:Math.max(0,e.length-r.length)}}const ew=s.forwardRef(function({projectId:t,brand:n,engines:r,parentId:a,initialBrief:i,suppressDraftRestore:l,startScene:u,startSetup:f,startPresenter:h,startProduct:p,onSeedsSpent:g,openAttachTab:v,onQueued:w,onSending:y,onAttached:x,onCeiling:k,target:S,onClearTarget:E,sourceImage:j,onRestoreBranchId:N,setSlug:P,persistDraft:$=!0,variant:M="dock",guided:C=!1},R){var dd,hl;const{products:T,productsLoaded:H}=on(),{demoProducts:D,demoProductsLoaded:K,loaded:O}=Rn(),Z=Rf(),te=Z.scenes,B=Z.presenters,F=vf(),X=Ec(),{push:z}=or(),I=r.filter(Ce=>Ce.available),[U,G]=fa(Dr.engine,H0);s.useEffect(()=>{const Ce=QY(I,U);Ce!==U&&G(Ce)},[I,U,G]);const ne=I.length===0&&r.some(Ce=>Ce.code==="not-installed"||Ce.code==="not-authenticated"),q=I.length===0,le=q?ne?{icon:o.jsx(KA,{}),title:"Image generation is not set up yet",detail:"About a minute, using the ChatGPT account you already have.",action:"Set up",onAct:()=>X(),info:!0}:{icon:o.jsx(R0,{size:15}),title:"No image provider connected",detail:"Add a provider key and this prompt is ready to run.",action:"Open settings",onAct:()=>F("engines"),info:!1}:null,[Se,Q]=s.useState(Oo()),[xe,ee]=s.useState(void 0),[ae,re,_]=kg(Dr.format,"square"),[ue,We]=s.useState({}),Xe=S&&S.kind!=="root"?S:null,ze=Xe?Ine(Xe.brief):void 0,tt=Xe?ue[Xe.id]??ze??ae:ae,ce=Ce=>{Xe?We(ht=>({...ht,[Xe.id]:Ce})):re(Ce)},[ve,Pe]=s.useState({}),[de,je,Ue]=kg(Dr.count,2),[ye,Ee]=s.useState(!1),[be,Le]=s.useState(null),[Qe,Ke]=s.useState(null),[nt,gt]=s.useState(!1),[Pt,Ut]=s.useState("All"),[Nt,cn]=s.useState(0),[Fe,pt]=s.useState(null),[it,St,xt]=kg(Dr.quality,"standard"),[At,Kt]=s.useState(!1),[et,mt]=s.useState(!1),ot=Ce=>mt(Ce);wr("(hover: hover) and (min-width: 1024px)");const kn=wr("(max-width: 767px)"),ut=s.useRef(null),Gt=s.useRef(null),Ft=s.useRef(null),en=s.useId(),Jt=s.useRef({tokens:Se,tplFields:ve,branchId:(S==null?void 0:S.id)??null});Jt.current={tokens:Se,tplFields:ve,branchId:(S==null?void 0:S.id)??null};const se=s.useRef(null),oe=s.useRef(null),we=s.useRef(void 0),ge=s.useRef(void 0),J=s.useRef(void 0),Oe=s.useCallback(Ce=>{if(oe.current&&(clearTimeout(oe.current),oe.current=null),!$)return;const ht=Jt.current;ht.branchId||(a5(ht.tokens,ht.tplFields)?FM(Ce,{tokens:ht.tokens,tplFields:ht.tplFields,setSlug:P}):o5(Ce))},[P,$]);s.useEffect(()=>{v&&(Ut(v),gt(!0))},[v]),s.useEffect(()=>{if(!i)return;const Ce=(i.tokens??[]).find(ht=>ht.t==="format");Ce&&_(Ce.id),i.variants&&Ue(i.variants),i.quality&&xt(i.quality),ee(Tv(i)),Pe(i.templateFields??{})},[i]),s.useEffect(()=>{var ps;const Ce=se.current;Ce&&Ce!==n.id&&Oe(Ce);const ht=!!i||!!l||!$,It=Ce!==n.id;let qt=null,fn=null;if(!ht&&It){const Xt=kre(n.id);Xt&&a5(Xt.tokens,Xt.tplFields)&&(qt=Xt.tokens,fn=Xt.tplFields)}let mn=!1;if(u&&u!==we.current){we.current=u,mn=!0;const Xt=qt??Oo(),Fn=Xt.find(xa=>xa.t==="template"),Tn=(Fn==null?void 0:Fn.id)??null,Ua=((ps=te.find(xa=>xa.id===u))==null?void 0:ps.name)??"this scene",Mc=i5(Tn,u,Ua,null,null);if(Mc.changed&&(qt=[{t:"template",id:u,...f?{setup:f}:{}},...Xt.filter(xa=>xa.t!=="template")],Mc.toast)){const xa=Mc.toast;z({kind:"info",title:xa.title,action:{label:"Undo",onClick:()=>{var Tf,$f;xa.prevSceneId?(Tf=ut.current)==null||Tf.insert({t:"template",id:xa.prevSceneId}):($f=ut.current)==null||$f.removeTemplate()}}})}}if(h&&h!==ge.current){ge.current=h,mn=!0;const Xt=qt??Oo();Xt.some(Tn=>Tn.t==="character"&&Tn.id===h)||(qt=[...Xt,{t:"character",id:h}])}if(p&&p!==J.current){J.current=p,mn=!0;const Xt=qt??Oo();Xt.some(Tn=>Tn.t==="product"&&Tn.id===p)||(qt=[...Xt,{t:"product",id:p}])}qt&&(ee(qt),Pe(fn??{})),mn&&(g==null||g()),se.current=n.id},[n.id,u,h,p]),s.useEffect(()=>{var Ce;xe&&((Ce=ut.current)==null||Ce.setTokens(xe),ee(void 0))},[xe]);const Be=s.useMemo(()=>{var fn;const Ce=Xr.find(mn=>mn.id===tt)??Xr[0],It=(((fn=Zi.find(mn=>mn.id===it))==null?void 0:fn.edge)??1024)/Math.max(Ce.w,Ce.h),qt=mn=>Math.max(256,Math.round(mn*It/8)*8);return{t:"format",id:Ce.id,w:qt(Ce.w),h:qt(Ce.h)}},[tt,it]),Ve=s.useMemo(()=>[Be,...Se],[Be,Se]),Ge=s.useMemo(()=>({tokens:Ve,templateFields:ve,variants:de,quality:it,format:tt}),[Ve,ve,de,it,tt]),me=Se.some(Ce=>Ce.t==="text"?!!Ce.v.trim():!0),_e=s.useMemo(()=>{const Ce=Se.find(ht=>ht.t==="template");return Ce?te.find(ht=>ht.id===Ce.id)??null:null},[Se,te]),W=s.useMemo(()=>{const Ce=Se.find(ht=>ht.t==="template");return(Ce==null?void 0:Ce.id)??null},[Se]),pe=s.useCallback(Ce=>{var mn,ps;const ht=(_e==null?void 0:_e.id)??null,It=(S==null?void 0:S.id)??null,qt=((mn=te.find(Xt=>Xt.id===Ce))==null?void 0:mn.name)??"this scene",fn=i5(ht,Ce,qt,It,S?Sr(S):null);if(fn.changed&&((ps=ut.current)==null||ps.insert({t:"template",id:Ce}),fn.toast)){const Xt=fn.toast;z({kind:"info",title:Xt.title,action:{label:"Undo",onClick:()=>{var Fn,Tn;Xt.prevSceneId?(Fn=ut.current)==null||Fn.insert({t:"template",id:Xt.prevSceneId}):(Tn=ut.current)==null||Tn.removeTemplate(),Xt.branchWasCleared&&It&&(N==null||N(It))}}})}},[_e,S,te,z,N]);s.useImperativeHandle(R,()=>({insertToken:Ce=>{var ht;return(ht=ut.current)==null?void 0:ht.insert(Ce)},removeToken:Ce=>{var ht;return(ht=ut.current)==null?void 0:ht.remove(Ce)},applyScene:Ce=>pe(Ce),removeTemplate:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.removeTemplate()},openAttach:Ce=>wa(Ce),showAttach:()=>{Eo.current||wa("All")},focus:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.focus()},submit:()=>{ui()}}));const Ie=s.useMemo(()=>jre(Se),[Se]),Te=Are(Ie),bt=Qne(Se),vt=s.useMemo(()=>Jne(bt),[bt]),Ct=s.useRef(Ie);Ct.current=Ie,s.useEffect(()=>{x==null||x(Ct.current)},[Te,x]),s.useEffect(()=>{var Ce;!O||!W||_e||((Ce=ut.current)==null||Ce.removeTemplate(),z({kind:"warning",title:"That scene is no longer available",detail:"Removed from the brief."}))},[O,W,_e,z]);const st=s.useRef(null);s.useEffect(()=>(oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>Oe(se.current??n.id),500),()=>{oe.current&&clearTimeout(oe.current)}),[Se,ve,S==null?void 0:S.id,n.id,Oe]),s.useEffect(()=>()=>Oe(se.current??n.id),[Oe]),s.useEffect(()=>{const Ce=()=>Oe(se.current??n.id);return window.addEventListener("beforeunload",Ce),()=>window.removeEventListener("beforeunload",Ce)},[Oe,n.id]);const $t=r.find(Ce=>Ce.id===U),An=$t?Bi($t.displayName):"This engine",Y=!!S&&S.kind!=="root"&&S.status==="running",he=S&&S.kind!=="root"&&S.status==="done"&&S.images.length>0||Y,Me=!!($t!=null&&$t.supportsEdit),dt=!!Xe&&!!ze&&ze!==tt&&he&&!_e,wt=dt?Cre(Bu(ze),Bu(tt)):null,Zt=wt==="crop",Ht=wt==="extend"&&Me,pn=Xr.find(Ce=>Ce.id===tt),Wt=pn?`${pn.label} ${pn.hint}`:tt,[wn,sn]=s.useState(null),In=()=>{S!=null&&S.images[0]&&sn({src:Mr(S.images[0]),kind:"shot",label:Sr(S),noun:"Refining this shot"})},Dt=he&&!_e&&(Me||Zt||Ht)?"edit":"generation",On=Dt==="edit"&&!!S&&M!=="overlay",Et=he?_e?"A scene starts a new shot.":Zt||Ht||Me?null:`${($t==null?void 0:$t.displayName)??"This engine"} cannot edit. This makes a new shot.`:null,Hn=s.useMemo(()=>{const Ce=Xr.find(mn=>mn.id===tt)??Xr[0],ht=`Aspect ${Ce.label} ${Ce.hint}`;if(Dt==="edit")return ht;const It=Zi.find(mn=>mn.id===it),qt=Qv(U),fn=qt==="ratio"||!It?null:qt==="advisory"?`${It.label}, asking for ${It.edge} px`:`${It.label} ${It.edge} px`;return[ht,`${de} shot${de===1?"":"s"}`,fn&&`resolution ${fn}`].filter(Boolean).join(", ")},[Dt,tt,de,it,U]),Ot=s.useRef(void 0),tn=s.useRef(void 0);s.useEffect(()=>{var qt;const Ce=he?(S==null?void 0:S.id)??null:null,ht=Ce!==Ot.current&&Ot.current!==void 0;Ot.current=Ce;const It=W!==tn.current;tn.current=W,!(!_e||!he)&&(ht&&!It&&Ce?(qt=ut.current)==null||qt.removeTemplate():E==null||E())},[_e,W,he,S,E]);const Vn=(Qe==null?void 0:Qe.warnings.filter(Ce=>Ce.includes("built around a product")))??[],ur=dt&&!me,Zr=Zt&&me,zn=!ye&&(me||ur)&&!Zr&&!!t&&!Y&&(Zt||!q),yn=q&&!Zt?"Image generation is not set up yet":ye?"Working on the last one":t?Y?"Wait for this version to finish, or press X to start a new shot":Zr?"This shape is reached by cropping, and a crop uses no words. Clear the prompt, or keep the current shape.":!me&&!ur?"Write a prompt first":null:"Still opening this brand";s.useEffect(()=>{const Ce=Dt==="edit"&&!!S;if(Zt||!me&&!Ce){Ke(null);return}st.current&&clearTimeout(st.current);const ht=Ge;return st.current=setTimeout(()=>{Re.previewBrief(Ge,U,n.id,Ce?S.id:void 0).then(It=>Ke({...It,forBrief:ht})).catch(()=>Ke(null))},280),()=>{st.current&&clearTimeout(st.current)}},[Ge,U,n.id,me,Dt,S,Zt]);const Va=Ce=>{var ht;ce(Ce),(ht=ut.current)==null||ht.focus()},ko=Ce=>{var ht;St(Ce),(ht=ut.current)==null||ht.focus()},So=Ce=>{var ht;je(Ce),(ht=ut.current)==null||ht.focus()},ul=Ce=>{var ht;Ce.preventDefault(),(ht=ut.current)==null||ht.focus()},wa=Ce=>{Ut(Ce),cn(ht=>ht+1),gt(!0)},Eo=s.useRef(!1);Eo.current=nt;const ya=s.useRef(wa);ya.current=wa;const ba=s.useCallback(({restore:Ce})=>{var ht;Eo.current&&(Eo.current=!1,gt(!1),Ce&&((ht=ut.current)==null||ht.restoreCaret()))},[]),Vr=s.useRef(pe);Vr.current=pe;const ts=s.useRef(Se);ts.current=Se;const Gs=s.useCallback(Ce=>{var It;const ht=Ce.token;ht.t==="template"?Vr.current(ht.id):(It=ut.current)==null||It.insert(ht)},[]),za=s.useCallback(Ce=>{var It,qt;const ht=Ce.token;ht.t==="template"?(It=ut.current)==null||It.removeTemplate():(qt=ut.current)==null||qt.remove(ht)},[]),Pr=async Ce=>{var It;if(!(Ce!=null&&Ce.length))return;const ht=Array.from(Ce).filter(qt=>qt.type.startsWith("image/"));if(!ht.length){z({kind:"warning",title:"Only images can be attached here"});return}Kt(!0),Le(null);try{for(const qt of ht.slice(0,4)){const fn=await P0(qt);(It=ut.current)==null||It.insert({t:"ref",imageHash:fn,label:Mre(qt.name)})}ht.length>4&&z({kind:"warning",title:"Only the first 4 images were attached",detail:`${ht.length-4} more ${ht.length-4===1?"was":"were"} skipped. Attach ${ht.length-4===1?"it":"them"} in another pick.`})}catch(qt){Le(String(qt.message??qt)),z(nn(qt,"Could not attach that image"))}finally{Kt(!1),Ft.current&&(Ft.current.value="")}},Lr=Qe&&Qe.forBrief===Ge?Qe:null,Ba=s.useMemo(()=>Se.filter(Ce=>l0.has(Ce.t)).length,[Se]),ci=s.useRef(null),ie=s.useMemo(()=>Ba===0?(ci.current=null,null):(Lr&&(ci.current={cap:Hne(Lr),described:One(Lr),preview:Lr}),ci.current),[Lr,Ba]),De=(ie==null?void 0:ie.cap)??null,Je=(ie==null?void 0:ie.preview)??null,Vt=($t==null?void 0:$t.displayName)??"This engine",Yt=Ba>=Xh?D6:null;s.useEffect(()=>{k==null||k(Yt)},[Yt,k]);const Bn=Ce=>{const ht=ie==null?void 0:ie.described;return!ht||ht.size===0?!1:Ce.t==="product"?ht.has(Fl("product",Ce.id)):Ce.t==="character"?ht.has(Fl("character",Ce.id)):Ce.t==="template"?ht.has(Fl("scene",Ce.id)):Ce.t==="ref"?ht.has(Fl("reference",Ce.imageHash)):Ce.t==="mark"?ht.has(Fl("brand",Ce.imageHash)):!1},Nn=De!=null?`Described in words: ${Vt} pictures ${De} per shot. Drag it earlier to picture it.`:null,xn=_e?Vn.length>0?"This scene builds around a product. Attach one.":(Je==null?void 0:Je.warnings.some(Ce=>Ce.includes("built around a person")))??!1?"This scene builds around a person. Without a presenter, only the set renders.":null:null,Sn=Ce=>{var mn,ps;if(Ce.t==="template")return xn;if(Ce.t==="product"&&H&&K&&!((T.length?T:((mn=n.json)==null?void 0:mn.products)??[]).some(Tn=>Tn.id===Ce.id)||D.some(Tn=>Tn.id===Ce.id)))return"This product is no longer in your library. Remove it from the brief.";if(Ce.t==="mark"&&!xf(n.json).some(Xt=>Xt.hash===Ce.imageHash))return"This mark is no longer in your brand kit. Remove it from the brief.";if(!Je)return null;const ht=($t==null?void 0:$t.displayName)??"this engine",It=Je.cap,qt=Xt=>`${Xt} won't reach ${ht} this time.`,fn=(Xt,Fn)=>{var Tn;return((Tn=Je.dropped)==null?void 0:Tn.some(Ua=>Ua.role===Xt&&Ua.id===Fn&&Ua.reason==="missing"))??!1};if(Ce.t==="ref"&&!Je.attachments.some(Xt=>Xt.hash===Ce.imageHash))return It===0?`This reference won't reach ${ht}. Choose an engine that reads images, or remove it.`:It==null?qt("This reference"):null;if(Ce.t==="mark"&&!Je.attachments.some(Xt=>Xt.role==="brand"&&Xt.hash===Ce.imageHash))return It===0?`The brand mark won't reach ${ht}, so the logo can't be drawn from it. Choose an engine that reads images.`:It==null?`${qt("The brand mark")} The logo can't be drawn from it.`:null;if(Ce.t==="mark"){const Xt=Je.warnings.find(Fn=>Fn.includes("px across"));if(Xt)return Xt}if(Ce.t==="product"){const Fn=(T.length?T:((ps=n.json)==null?void 0:ps.products)??[]).find(Tn=>Tn.id===Ce.id)??D.find(Tn=>Tn.id===Ce.id);if(Fn&&!Je.attachments.some(Tn=>Tn.role==="product"&&Tn.id===Fn.id))return fn("product",Fn.id)?`${Fn.name} has no usable photo. Re-add one, or remove this.`:null}if(Ce.t==="character"){const Xt=B.find(Fn=>Fn.id===Ce.id);if(!Xt&&B.length>0)return"This presenter is no longer in your roster. Remove them from the brief.";if(Xt&&!Je.attachments.some(Fn=>Fn.role==="character"&&Fn.id===Xt.id))return fn("character",Xt.id)?`${Xt.name} has no usable photo. Re-add one, or remove this.`:null}return null},hs=s.useCallback(Sn,[Je,$t==null?void 0:$t.displayName,xn,T,H,n.json,D,K,B]),cd=s.useCallback(Bn,[ie]),ui=async()=>{var ht,It,qt;if(!zn)return;Ee(!0),Le(null);const Ce=Se.flatMap(fn=>fn.t==="text"?[fn.v]:[]).join(" ").replace(/\s+/g," ").trim();y==null||y({said:Ce||"Your shot",count:Dt==="generation"?de:1});try{if(!t)throw new Error("the workspace is still loading");const fn=await Re.addNode({projectId:t,parentId:Dt==="edit"&&S?S.id:a,kind:Dt,engineId:U,count:de,brief:Ge,...Dt==="edit"&&j?{sourceImage:j}:{},...Dt==="edit"&&wt?{reshape:wt}:{}}),mn=fn.warnings??[];mn.length===1?z({kind:"warning",title:"Sent, with one thing to know",detail:mn[0]}):mn.length>1&&z({kind:"warning",title:`Sent, with ${mn.length} things to know`,detail:mn.join(" ")}),(ht=ut.current)==null||ht.setTokens(Oo()),Pe({}),_(null),We({}),Ue(null),xt(null),$&&o5(n.id),w(fn.id,Dt,(It=fn.siblings)==null?void 0:It.map(ps=>ps.id),(qt=fn.siblings)!=null&&qt.length?fn.siblings:[fn])}catch(fn){const mn=String(fn.message??fn);Le(mn),z(nn(fn,"That did not send",$t==null?void 0:$t.displayName)),y==null||y(null)}finally{Ee(!1)}},di=(dd=Se.find(Ce=>Ce.t==="product"))==null?void 0:dd.id,dl=di?T.find(Ce=>Ce.id===di)??(((hl=n.json)==null?void 0:hl.products)??[]).find(Ce=>Ce.id===di)??D.find(Ce=>Ce.id===di)??null:null,Ac=dl?Cv(dl):null,ud=C?{brandId:n.id,products:Se.filter(Ce=>Ce.t==="product").length,presenters:Se.filter(Ce=>Ce.t==="character").length,scene:!!_e,others:Se.filter(Ce=>Ce.t==="color"||Ce.t==="ref"||Ce.t==="mark").length,words:Se.some(Ce=>Ce.t==="text"&&!!Ce.v.trim()),busy:ye,pickerOpen:nt,refining:Dt==="edit"&&!!S,engine:q?ne?"setup":"settings":"ready"}:null;s.useEffect(()=>{ud&&Fx(ud)}),s.useEffect(()=>{if(C)return()=>Fx(null)},[C]),s.useEffect(()=>{if(!C||!nt)return;const Ce=()=>ba({restore:!0});return window.addEventListener("scenri:guide-close-picker",Ce),()=>window.removeEventListener("scenri:guide-close-picker",Ce)},[C,nt,ba]),s.useEffect(()=>{if(!C)return;const Ce=ht=>{var mn;const{kind:It}=ht.detail,qt=It==="presenter"?"character":It==="scene"?"template":"product",fn=[...ts.current].reverse().find(ps=>ps.t===qt);fn&&((mn=ut.current)==null||mn.remove(fn))};return window.addEventListener("scenri:guide-take-back",Ce),()=>window.removeEventListener("scenri:guide-take-back",Ce)},[C]),s.useEffect(()=>{if(!E)return;const Ce=()=>E();return window.addEventListener("scenri:guide-clear-refine",Ce),()=>window.removeEventListener("scenri:guide-clear-refine",Ce)},[E]),s.useEffect(()=>{if(!C)return;const Ce=ht=>{const{tab:It}=ht.detail;pt(It??null),It&&ya.current(It)};return window.addEventListener("scenri:guide-picker",Ce),()=>{window.removeEventListener("scenri:guide-picker",Ce),pt(null)}},[C]);const[Ys,Nc]=s.useState(!1),fl=M==="overlay"&&(Ys||Se.some(Ce=>Ce.t==="text"&&!!Ce.v.trim()));return s.useEffect(()=>{M==="overlay"&&_x({engaged:fl})},[M,fl]),s.useEffect(()=>{if(M==="overlay")return()=>_x(null)},[M]),o.jsxs("div",{className:"sc-composer","data-guide":C?"compose":void 0,onPointerDownCapture:M==="overlay"&&!Ys?()=>Nc(!0):void 0,onKeyDownCapture:M==="overlay"&&!Ys?()=>Nc(!0):void 0,children:[o.jsx("input",{ref:Ft,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Ce=>void Pr(Ce.target.files)}),wn&&o.jsx(Uu,{src:wn.src,kind:wn.kind,label:wn.label,noun:wn.noun,onRestoreFocus:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.restoreCaret()},onClose:()=>sn(null)}),nt&&o.jsx(fre,{brand:n,activeProductCategory:Ac,refining:On,full:Yt,initialTab:Pt,tabNonce:Nt,only:Fe,id:en,attached:vt,onUpload:()=>{var Ce;return(Ce=Ft.current)==null?void 0:Ce.click()},onFiles:Ce=>void Pr(Ce),onPick:Gs,onRemove:za,onClose:ba}),le&&o.jsx("div",{className:"sc-notes","data-guide-shape":C?"":void 0,children:le&&o.jsxs("div",{className:"sc-banner","data-tone":"action",children:[o.jsx("span",{className:"sc-banner-ic",children:le.icon}),o.jsxs("span",{className:"sc-banner-txt",children:[o.jsx("b",{children:le.title}),o.jsxs("small",{children:[le.detail,le.info&&o.jsxs(Hu,{children:[o.jsx(Ou,{children:o.jsx("button",{type:"button",className:"sc-note-info","aria-label":"What a ChatGPT account has to do with this",children:o.jsx(_p,{size:13})})}),o.jsxs(Iu,{className:"sc-note-pop",align:"start",sideOffset:8,width:"300px",children:[o.jsx("p",{children:"Codex CLI signs in with your ChatGPT account and makes the images there. Every plan includes some Codex usage, so how many images you get depends on the plan you are on."}),o.jsx("p",{children:"No ChatGPT account, or run out for now? Use your own key from an image provider instead."}),o.jsx("p",{className:"sc-note-pop-fine",children:"Scenri never sees your password or token. The sign-in happens in your browser and stays with Codex."}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>F("engines"),children:"Use a provider key instead"})]})]})]})]}),o.jsx("button",{type:"button",className:"sc-banner-act","data-primary":"","data-guide":C?"compose.engine":void 0,onClick:le.onAct,children:le.action})]})}),o.jsxs("div",{className:"sc-promptcard","data-guide-shape":C?"":void 0,children:[he&&(E||M==="overlay"&&Dt==="edit")&&o.jsxs("div",{className:"sc-target","data-note":Et?"":void 0,children:[o.jsx(pre,{target:S,onOpenImage:In,onClear:E}),Et&&o.jsx("small",{className:"sc-target-note",children:Et})]}),he&&!E&&Et&&!(M==="overlay"&&Dt==="edit")&&o.jsx("small",{className:"sc-target-note sc-target-note-alone",children:Et}),dt&&(Zt||Ht)&&o.jsxs("small",{className:"sc-reshape-hint","aria-live":"polite",children:[Zt?"Will crop to":"Will extend to"," ",Wt]}),o.jsx(Fne,{ref:ut,onChange:Q,brand:n,templates:te,presenters:B,demoProducts:D,onTemplatePick:pe,scenesSitOut:On,flag:hs,described:cd,describedNote:Nn,onInspect:Ce=>sn(Ce),onAttachRequest:Ce=>wa(Ce),activeProductCategory:Ac,placeholder:_e?"Add art direction, or run it as written":Dt==="edit"?"Say what to change about this shot":"What should we shoot? (use $ / @ #)",placeholderSm:_e||Dt==="edit"?void 0:"What should we shoot? ($ / @ #)",label:_e?"Art direction":Dt==="edit"?"What to change":"Shot brief",onSubmit:()=>void ui(),onDropFiles:Ce=>void Pr(Ce)}),o.jsxs("div",{className:"sc-prompt-row",children:[o.jsxs("div",{className:"sc-prompt-left",children:[o.jsx("button",{type:"button",ref:Gt,className:"sc-icon-btn sc-attach-toggle","data-guide":C?"compose.add":void 0,"aria-expanded":nt,"aria-controls":nt?en:void 0,"aria-label":"Add to shot",title:"Add a product, a presenter, a scene, a colour or an image",onClick:()=>nt?ba({restore:!1}):wa("All"),children:At?o.jsx(xr,{size:"1"}):o.jsx(cr,{size:16})}),I.length>1&&o.jsxs(Z7,{value:U,onValueChange:G,children:[o.jsxs(V7,{variant:"ghost",className:"sc-mini-sel",children:[o.jsx(R0,{size:14}),o.jsx("span",{className:"sc-mini-sel-t",children:$t?Bi($t.displayName):"Demo"})]}),o.jsx(z7,{children:I.map(Ce=>o.jsx(B7,{value:Ce.id,children:Bi(Ce.displayName)},Ce.id))})]})]}),o.jsxs("div",{className:"sc-prompt-right",children:[o.jsx(wre,{mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko,onCloseAutoFocus:ul,guided:C}),o.jsxs(Hu,{open:et,onOpenChange:ot,children:[o.jsx(Ou,{children:o.jsxs("button",{type:"button",className:"sc-var sc-more","aria-label":`Shot settings. ${Hn}`,"data-guide":C&&!kn?"compose.settings":void 0,children:[o.jsx(ov,{size:14}),"More"]})}),o.jsx(Iu,{className:"sc-morepop",align:"end",sideOffset:8,width:"300px",onOpenAutoFocus:Jv,onCloseAutoFocus:ul,children:o.jsx(IM,{mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko})})]}),o.jsx(yre,{guide:C&&kn?"compose.settings":void 0,mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko}),o.jsxs("button",{type:"button",className:"sc-send","data-guide":C?"compose.send":void 0,"aria-disabled":!zn||void 0,onClick:()=>void ui(),"aria-label":Dt==="edit"?"Refine":"Generate",title:be??xn??yn??`${Dt==="edit"?"Refine":"Generate"} (enter)`,children:[o.jsx("span",{className:"sc-send-ico",children:ye?o.jsx(xr,{size:"1"}):o.jsx(iC,{size:17,weight:"bold"})}),o.jsx("span",{className:"sc-send-lb",children:Dt==="edit"?"Refine":"Generate"})]})]})]})]})]})});function Mre(e){return e.replace(/\.[a-z0-9]{2,5}$/i,"").trim()||"Image"}function tw(e,t){s.useLayoutEffect(()=>{if(!e||typeof ResizeObserver>"u")return;const n=document.documentElement,r=()=>n.style.setProperty(t,`${Math.round(e.offsetHeight)}px`);r();const a=new ResizeObserver(r);return a.observe(e),()=>{a.disconnect(),n.style.removeProperty(t)}},[e,t])}function ZM({full:e=!0,children:t}){const[n,r]=s.useState(null);return tw(n,"--sc-dock-h"),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-dock-fade","data-full":e,"aria-hidden":!0}),o.jsx("div",{className:"sc-canvas-dock","data-full":e,ref:r,children:t})]})}function nw(){const{brand:e}=on(),{tasks:t}=Za(),[n,r]=s.useState(null),[a,i]=s.useState(null),[l,u]=s.useState(()=>Date.now()),f=s.useRef({id:"",pct:0}),h=t.find(y=>y.kind==="catalog"&&y.state==="running");if(s.useEffect(()=>{if(!h)return;const y=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(y)},[h]),!h&&!a)return null;const p=h!=null&&h.id.startsWith("catalog:")?h.id.slice(8):null,g=h!=null&&n===h.id,v=eG(e.json),w=Fr(v==null?void 0:v.file);return h&&(f.current.id!==h.id&&(f.current={id:h.id,pct:0}),f.current.pct=Math.max(f.current.pct,h.percent??0)),o.jsxs(o.Fragment,{children:[h&&o.jsxs("div",{className:"sc-impbar",role:"status",style:{"--sc-impbar-p":`${f.current.pct}%`},children:[o.jsx("span",{className:"sc-impbar-fill","aria-hidden":!0}),o.jsxs("button",{type:"button",className:"sc-impbar-open",onClick:()=>p&&i(p),disabled:!p,"aria-label":"Show import details",children:[o.jsx("span",{className:"sc-impbar-mark","aria-hidden":!0,children:w?o.jsx("img",{src:w,alt:"",className:(v==null?void 0:v.role)==="mark"?"sc-impbar-badge":void 0}):o.jsx(pj,{size:13,weight:"regular"})}),o.jsx("span",{className:"sc-impbar-count",children:h.subtitle}),o.jsx("span",{className:"sc-impbar-clock",children:rc(h.startedAt,l)})]}),p&&o.jsxs("button",{type:"button",className:"sc-impbar-stop",disabled:g,"aria-label":"Stop importing",onClick:()=>{r(h.id),Re.cancelCatalogJob(e.id,p).catch(()=>r(null))},children:[o.jsx(jn,{size:12,weight:"bold"}),g?"Stopping":"Stop"]})]}),a&&o.jsx(p6,{brandId:e.id,jobId:a,onDismiss:()=>i(null)})]})}const Rre={presenter:"Presenter",product:"Product",scene:"Scene"};function VM({entry:e,productName:t,productPreviewUrl:n,productId:r,presenterName:a,presenterPreviewUrl:i,presenterId:l,sceneName:u,scenePreviewUrl:f,sceneId:h,onOpen:p,productHref:g,presenterHref:v,sceneHref:w,active:y,hideRecipe:x,decorative:k,size:S="grid"}){const E=[t,a,u].filter(Boolean).join(" · "),j=a?{key:"presenter",name:a,previewUrl:i,linked:!!(v&&l),href:v&&l?v(l):void 0}:null,N=n&&t?{key:"product",name:t,previewUrl:n,linked:!!(g&&r),href:g&&r?g(r):void 0}:null,P=f&&u?{key:"scene",name:u,previewUrl:f,linked:!!(w&&h),href:w&&h?w(h):void 0}:null;return o.jsxs("div",{className:"sc-showcase-tile","data-active":y||void 0,"aria-hidden":k||void 0,...k?{inert:""}:{},children:[o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.title,primary:e.title,secondary:x?"":E,useLabel:"Recreate this",variant:"use",onOpen:p,onUse:p,size:S}),(j||N||P)&&o.jsx(Lre,{presenter:j,product:N,scene:P})]})}function Pre(e){return o.jsx(Qp,{...e,caption:!1})}function Lre({presenter:e,product:t,scene:n}){const[r,a]=s.useState(null),i=[t,n].filter(Boolean),l=i.length+(e?1:0)+Math.max(0,i.length-1);let u=0;const f=()=>({"--i":u++});return o.jsxs("div",{className:"sc-showcase-chips",onMouseLeave:()=>a(null),children:[e&&o.jsx(l5,{credit:e,open:r==="presenter",onEnter:()=>a("presenter"),children:$re(e)}),i.length>0&&o.jsxs("div",{className:"sc-showcase-recipe",style:{"--n":l},children:[e&&o.jsx("span",{className:"sc-showcase-join",style:f(),"aria-hidden":!0}),i.map((h,p)=>o.jsxs(s.Fragment,{children:[p>0&&o.jsx("span",{className:"sc-showcase-join",style:f(),"aria-hidden":!0}),o.jsx(l5,{credit:h,open:r===h.key,onEnter:()=>a(h.key),style:f(),children:Tre({credit:h,step:p===0?1:2})})]},h.key))]})]})}function l5({credit:e,open:t,onEnter:n,children:r,style:a}){const i=s.useRef(null),l=s.useRef(null),[u,f]=s.useState(null),h=Ete(),p=h==="large"?144:88,g=h==="large"?168:112;if(s.useLayoutEffect(()=>{var S,E;if(!t||!e.previewUrl){f(null);return}const w=()=>{const j=i.current;if(!j)return;const N=j.getBoundingClientRect(),P=l.current,$=(P==null?void 0:P.offsetWidth)||p,M=(P==null?void 0:P.offsetHeight)||g,C=window.visualViewport,R=Hte(N,{width:(C==null?void 0:C.width)??window.innerWidth,height:(C==null?void 0:C.height)??window.innerHeight},{width:$,height:M});if(!R){f(null);return}f({left:Math.round(R.left),top:Math.round(R.top)})};w();const y=requestAnimationFrame(w),x=i.current,k=x?new ResizeObserver(w):null;return x&&k&&k.observe(x),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),(S=window.visualViewport)==null||S.addEventListener("resize",w),(E=window.visualViewport)==null||E.addEventListener("scroll",w),()=>{var j,N;cancelAnimationFrame(y),k==null||k.disconnect(),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w),(j=window.visualViewport)==null||j.removeEventListener("resize",w),(N=window.visualViewport)==null||N.removeEventListener("scroll",w)}},[t,e.previewUrl,e.key,p,g]),!e.previewUrl)return o.jsx("span",{ref:i,className:"sc-credit-tip",onPointerEnter:n,style:a,children:r});const v=Rre[e.key];return o.jsxs("span",{ref:i,className:"sc-credit-tip","data-open":t||void 0,onPointerEnter:n,style:a,children:[r,t&&Rr.createPortal(o.jsx("span",{ref:l,className:"sc-credit-tip-pop","data-size":h,style:u?{left:u.left,top:u.top}:{left:-9999,top:0},role:"tooltip","aria-label":`${v}: ${e.name}`,children:o.jsxs("span",{className:"sc-credit-tip-card",children:[o.jsx("img",{src:e.previewUrl,alt:""}),o.jsx("span",{className:"sc-credit-tip-name",children:e.name}),o.jsx("span",{className:"sc-credit-tip-role",children:v})]})}),document.body)]})}function Tre({credit:e,step:t}){const{name:n,previewUrl:r,linked:a,href:i}=e;return a&&i?o.jsx(_n,{className:"sc-showcase-chip",to:i,"data-link":!0,"data-step":t,"aria-label":`See ${n}`,onClick:l=>l.stopPropagation(),children:r?o.jsx("img",{src:r,alt:""}):null}):o.jsx("span",{className:"sc-showcase-chip","data-step":t,children:r?o.jsx("img",{src:r,alt:n}):o.jsx("span",{className:"sc-vh",children:n})})}function $re(e){const{name:t,previewUrl:n,linked:r,href:a}=e;return r&&a?o.jsxs(_n,{className:"sc-showcase-badge",to:a,"data-link":!0,"aria-label":`See ${t}`,onClick:i=>i.stopPropagation(),children:[n?o.jsx("img",{src:n,alt:""}):null,o.jsx("span",{className:"sc-showcase-badge-name",children:t})]}):o.jsxs("span",{className:"sc-showcase-badge","aria-hidden":!0,children:[n?o.jsx("img",{src:n,alt:""}):null,o.jsx("span",{className:"sc-showcase-badge-name",children:t})]})}function c5(e){return{key:"open-tab",icon:"open-tab",label:"Open in new tab",onSelect:()=>window.open(e,"_blank")}}function u5(e){return{key:"select",icon:"select",label:"Select",onSelect:e}}function Ji(e){if(e.only)return[{key:"only",icon:"use",label:e.only.label,onSelect:e.only.run}];if(e.draft){const n=[{key:"continue",icon:"continue",label:"Continue",onSelect:e.draft.onContinue}];return e.draft.href&&n.push(c5(e.draft.href)),e.select&&n.push(u5(e.select.run)),n.push({key:"discard",icon:"discard",label:"Discard",onSelect:e.draft.onDiscard,danger:!0,separated:!0}),n}const t=[];return e.onOpen&&t.push({key:"open",icon:"open",label:"Open",onSelect:e.onOpen}),e.href&&t.push(c5(e.href)),e.use&&t.push({key:"use",icon:"use",label:e.use.label,onSelect:e.use.run}),e.select&&t.push(u5(e.select.run)),e.keep&&t.push({key:"keep",icon:e.keep.on?"kept":"keep",label:e.keep.on?"Remove from Keepers":"Add to Keepers",onSelect:e.keep.run}),e.onRename&&t.push({key:"rename",icon:"rename",label:"Rename",onSelect:e.onRename}),e.onDuplicate&&t.push({key:"duplicate",icon:"duplicate",label:"Duplicate presenter",onSelect:e.onDuplicate}),e.onEdit&&t.push({key:"edit",icon:"edit",label:"Edit presenter",onSelect:e.onEdit}),e.remove&&t.push({key:"delete",icon:"delete",label:e.remove.label,onSelect:e.remove.run,danger:!0,separated:!0}),t}function qr(e,t){if(e==="draft")return{tool:"Discard",menu:t>1?`Discard ${t} drafts`:"Discard",icon:"discard",danger:!0};const n=e==="presenter"?"Delete presenter":e==="product"?"Delete product":"Delete scene",r=e==="presenter"?"presenters":e==="product"?"products":"scenes";return{tool:"Delete",menu:t>1?`Delete ${t} ${r}`:n,icon:"delete",danger:!0}}function pm(e,t,n){return{tool:t?"Remove from keepers":"Keep",menu:e>1?t?`Remove ${e} ${n} from Keepers`:`Add ${e} ${n} to Keepers`:t?"Remove from Keepers":"Add to Keepers",icon:t?"kept":"keep"}}function mm({kind:e,count:t,openLabel:n,onOpen:r,href:a,onDeselect:i,onAct:l,onKeep:u,allKept:f}){const h=qr(e,t),p=[{key:"open",icon:n==="Continue"?"continue":"open",label:n,onSelect:r}];if(a&&p.push({key:"open-tab",icon:"open-tab",label:"Open in new tab",onSelect:()=>window.open(a,"_blank")}),p.push({key:"deselect",icon:"select",label:t>1?"Deselect this":"Deselect",onSelect:i}),u&&e!=="draft"){const v=pm(t,!!f,e==="presenter"?"presenters":e==="product"?"products":"scenes");p.push({key:"keep",icon:v.icon,label:v.menu,onSelect:u})}return p.push({key:e==="draft"?"discard":"delete",icon:h.icon,label:h.menu,onSelect:l,danger:h.danger||void 0,separated:!0}),p}async function tp(e,t){const n=[];let r;for(const a of e)try{await t(a)}catch(i){if((i==null?void 0:i.status)===404)continue;n.push(a),r??(r=i)}return{failed:n,error:r}}function _6({presenter:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,onDuplicate:u,onEdit:f,onDelete:h,onRename:p,bookmarked:g,onBookmark:v,fresh:w,chosen:y,batching:x,onPick:k,batch:S,size:E="grid"}){const N=S?mm({kind:"presenter",count:S.count,openLabel:"Open",onOpen:()=>n==null?void 0:n(e.id),href:a,onDeselect:()=>k==null?void 0:k(e.id),onAct:S.onAct,onKeep:S.onKeep,allKept:S.allKept}):Ji(!a&&!r&&!!n?{only:{label:"Use in a shot",run:()=>n(e.id)}}:{onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,select:k?{run:()=>k(e.id)}:void 0,keep:v?{on:!!g,run:()=>v(e.id)}:void 0,onRename:p?()=>p(e.id):void 0,onDuplicate:u?()=>u(e.id):void 0,onEdit:f?()=>f(e.id):void 0,remove:h?{label:"Delete presenter",run:()=>h(e.id)}:void 0});return o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.descriptor||e.name,primary:e.name,secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,menu:N,bookmarked:g,onBookmark:v,fresh:w,chosen:y,batching:x,onPick:k,size:E})}function zM(e){return o.jsx(Qp,{...e})}function I0({scene:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,bookmarked:u,onBookmark:f,onDelete:h,onRename:p,chosen:g,batching:v,onPick:w,batch:y,size:x="grid"}){const S=y&&h?mm({kind:"owned-scene",count:y.count,openLabel:"Open",onOpen:()=>n==null?void 0:n(e.id),href:a,onDeselect:()=>w==null?void 0:w(e.id),onAct:y.onAct,onKeep:y.onKeep,allKept:y.allKept}):Ji(!a&&!r&&!!n?{only:{label:"Use in a shot",run:()=>n(e.id)}}:{onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,select:w?{run:()=>w(e.id)}:void 0,keep:f?{on:!!u,run:()=>f(e.id)}:void 0,onRename:p?()=>p(e.id):void 0,remove:h?{label:"Delete scene",run:()=>h(e.id)}:void 0});return o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.description||Qi(e,"tooltip"),primary:Qi(e,"card"),secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,bookmarked:u,onBookmark:f,menu:S,chosen:g,batching:v,onPick:w,size:x})}function BM(e){return o.jsx(Qp,{...e})}const pu=new Map,Dre=50;function Hre(e,t){for(pu.delete(e),pu.set(e,t);pu.size>Dre;)pu.delete(pu.keys().next().value)}function Ore(e){return pu.get(e)}const Ire=1e3;function is({className:e="sc-home",children:t}){const n=s.useRef(null),{key:r}=Zn(),a=s.useRef(!1);return s.useLayoutEffect(()=>{const i=n.current,l=Ore(r);if(!i||!l)return;let u=!1;const f=()=>{u||(u=!0,a.current=!1,p.disconnect(),clearTimeout(g),i.removeEventListener("wheel",f),i.removeEventListener("touchstart",f))},h=()=>{u||(i.scrollTop=l,Math.abs(i.scrollTop-l)<1&&f())};a.current=!0;const p=new ResizeObserver(h),g=setTimeout(f,Ire);return i.addEventListener("wheel",f,{passive:!0}),i.addEventListener("touchstart",f,{passive:!0}),h(),p.observe(i),i.firstElementChild&&p.observe(i.firstElementChild),f},[r]),s.useEffect(()=>{const i=n.current;if(!i)return;const l=()=>{a.current||Hre(r,i.scrollTop)};return i.addEventListener("scroll",l,{passive:!0}),()=>i.removeEventListener("scroll",l)},[r]),o.jsx("div",{ref:n,className:e,"data-page-scroll":"",children:t})}function gm({title:e,filters:t,active:n,summary:r,onClear:a,density:i,search:l,action:u}){return o.jsxs("div",{className:"sc-filterbar",children:[e?o.jsx("h1",{className:"sc-vh",children:e}):null,t,o.jsxs("div",{className:"sc-filterbar-actions",children:[n&&o.jsxs("span",{className:"sc-lib-count",children:[r,a&&o.jsx("button",{type:"button",className:"sc-lib-clear",onClick:a,children:"Clear"})]}),l,i,u?o.jsx("span",{className:"sc-filterbar-cta",children:u}):null]})]})}function vm({mode:e,group:t}){if(e==="none"||!t)return null;const n=[{value:null,label:t.everyLabel,count:t.everyCount},...t.options.map(r=>({value:r.value,label:r.label,count:r.count}))];return o.jsx(qv,{"aria-label":t.label,activeKey:t.selected,items:n,onSelect:t.onSelect})}function oo({shape:e,title:t,body:n,action:r,onRetry:a}){return e==="error"?o.jsxs(o.Fragment,{children:[o.jsx("h1",{children:t??"Couldn't load this library"}),o.jsx("p",{className:"sc-lookpage-lede",children:n}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:a,children:"Retry"})})]}):e==="cold"?o.jsxs("div",{className:"sc-canvas-empty",children:[t&&o.jsx("h3",{children:t}),o.jsx("p",{children:n}),r&&o.jsx("div",{className:"sc-lookpage-acts",children:r})]}):o.jsxs("div",{className:"sc-lib-zero",children:[o.jsx("p",{children:n}),r]})}function wm({noun:e,q:t,facet:n,onClearSearch:r,onClearAll:a}){const i=t.trim(),l=i?o.jsxs(o.Fragment,{children:["No ",e," found for ",o.jsxs("em",{children:["“",i,"”"]}),n?` in ${n}`:""]}):o.jsxs(o.Fragment,{children:["No ",e," in ",n]});return o.jsx(oo,{shape:"zero",body:l,action:o.jsxs("span",{className:"sc-lib-zero-acts",children:[i&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:r,children:"Clear search"}),i&&n&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Clear all"}),!i&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Clear filter"})]})})}const Fre=150;function Pf(e){const[t,n]=el(),r=t.get("q")??"",a=e.join(","),i=s.useMemo(()=>{const E={};for(const j of a.split(",").filter(Boolean))E[j]=t.get(j)||null;return E},[t,a]),l=s.useCallback(E=>{n(j=>{const N=new URLSearchParams(j);for(const[P,$]of Object.entries(E))$===null||$===""?N.delete(P):N.set(P,$);return N},{replace:!0})},[n]),[u,f]=s.useState(r),h=s.useRef(r),p=s.useRef(null),g=s.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]);s.useEffect(()=>{r!==h.current&&(h.current=r,g(),f(r))},[r,g]),s.useEffect(()=>g,[g]);const v=s.useCallback(E=>{f(E),g(),p.current=setTimeout(()=>{p.current=null,h.current=E,l({q:E||null})},Fre)},[l,g]),w=s.useCallback((E,j)=>l({[E]:j}),[l]),y=l,x=u.trim().length>0||Object.values(i).some(Boolean),k=s.useCallback(()=>{g(),f(""),h.current="",l({q:null})},[l,g]),S=s.useCallback(()=>{g(),f(""),h.current="";const E={q:null};for(const j of a.split(",").filter(Boolean))E[j]=null;l(E)},[l,g,a]);return{q:u,setQ:v,facets:i,setFacet:w,setFacets:y,active:x,clearSearch:k,clear:S}}const _re=8;function Zre(){var tt;const{engines:e,scenes:t,loaded:n,presenters:r,presentersLoaded:a,demoProducts:i,showcase:l,showcaseCategories:u,showcaseLoaded:f,showcaseError:h,refetchShowcase:p}=Rn(),{brand:g,workspace:v,root:w,products:y,applyNodes:x}=on(),{poke:k}=Za(),S=ll(),E=Dn(),{push:j}=or(),N=Wv(),P=im(),$=pte(),M=wr(Ks),{q:C,setQ:R,facets:T,setFacet:H,clearSearch:D,clear:K}=Pf(["category"]),O=T.category,Z=ce=>H("category",ce),te=C.trim().length>0,[B,F]=fa(Dr.wallDensity,zu),X=jc(B),z=ce=>F(ce),I=fm(X),U=um(X),G=ce=>{const ve=new URLSearchParams(ce??{}).toString();E(`${mr(g)}${ve?`?${ve}`:""}`)},ne=y.length?y:((tt=g.json)==null?void 0:tt.products)??[],q=ce=>{var je,Ue,ye;const ve=(je=ce.brief.tokens.find(Ee=>Ee.t==="product"))==null?void 0:je.id,Pe=(Ue=ce.brief.tokens.find(Ee=>Ee.t==="character"))==null?void 0:Ue.id,de=(ye=ce.brief.tokens.find(Ee=>Ee.t==="template"))==null?void 0:ye.id;return{product:ve?i.find(Ee=>Ee.id===ve):void 0,presenter:Pe?r.find(Ee=>Ee.id===Pe):void 0,scene:de?t.find(Ee=>Ee.id===de):void 0}},le=s.useMemo(()=>{const ce=new Map;for(const ve of l){const{product:Pe,presenter:de,scene:je}=q(ve);ce.set(ve.id,hte(ve,{product:Pe,presenter:de,scene:je},qg(ve.category)))}return ce},[l,i,r,t]),Se=s.useMemo(()=>(O?l.filter(ve=>ve.category===O):l).filter(ve=>wo(le.get(ve.id)??ve.title,C)),[l,O,C,le]),Q=s.useMemo(()=>{const ce=wte(u);return{key:"category",label:"Categories",everyLabel:"All examples",everyCount:l.length,selected:O,onSelect:Z,options:ce.map(ve=>({value:ve,label:qg(ve)??ve,count:l.filter(Pe=>Pe.category===ve).length}))}},[l,u,O,Z]),xe=ce=>{const{product:ve,presenter:Pe,scene:de}=q(ce);return{productName:ve?go(ve,"chip"):null,productPreviewUrl:(ve==null?void 0:ve.previewUrl)??null,productId:(ve==null?void 0:ve.id)??null,presenterName:(Pe==null?void 0:Pe.name)??null,presenterPreviewUrl:Pe?ti(Pe).src:null,presenterId:(Pe==null?void 0:Pe.id)??null,sceneName:de?Qi(de,"chip"):null,scenePreviewUrl:(de==null?void 0:de.previewUrl)??null,sceneId:(de==null?void 0:de.id)??null}},[ee,ae]=s.useState(null),_=M?$:ce=>{const ve=l.find(Pe=>Pe.id===ce);ve&&(ae(T6(ve)),j({kind:"info",title:`Starting from "${ve.title}"`}))},ue=()=>{const ve=[...vo(g.id)].reverse().find(Pe=>t.some(de=>de.id===Pe));G(ve?{scene:ve,attach:"products",compose:"1"}:{attach:"products",compose:"1"})},We=s.useMemo(()=>Oh(Sf(g),r).slice(0,8),[g,r]),Xe=s.useMemo(()=>{const ce=vo(g.id);return Oh(Cc(g),CM(t,ve=>ce.includes(ve.id))).slice(0,8)},[t,g]),ze=s.useMemo(()=>{var ye,Ee,be,Le,Qe;const ce=new Set,ve=Ke=>!Ke||ce.has(Ke)?null:(ce.add(Ke),sr(Ke,"tile")),Pe=Ke=>{for(const nt of Ke){const gt=l.find(Ut=>Ut.id===nt&&Ut.previewUrl),Pt=ve(gt==null?void 0:gt.previewUrl);if(Pt)return Pt}return null},de=Ke=>{for(const nt of Ke){const gt=t.find(Ut=>Ut.id===nt&&Ut.previewUrl),Pt=ve(gt==null?void 0:gt.previewUrl);if(Pt)return Pt}return null},je=Ke=>{for(const nt of l)if(!(!nt.previewUrl||ce.has(nt.previewUrl))&&!(Ke&&!nt.brief.tokens.some(gt=>gt.t===Ke)))return ve(nt.previewUrl);return null},Ue=ne.find(Ke=>{var nt,gt;return Fr((gt=(nt=Ke==null?void 0:Ke.shots)==null?void 0:nt[0])==null?void 0:gt.file)});return{compose:ve(Ue?Fr((Ee=(ye=Ue.shots)==null?void 0:ye[0])==null?void 0:Ee.file):null)??Pe(["aurelia-serum-succulent-dew","verity-pearls-suspended-silk","solstice-aviators-screen-print"])??ve((be=i.find(Ke=>Ke.id==="aurelia-amber-serum"))==null?void 0:be.previewUrl)??ve((Le=i.find(Ke=>Ke.previewUrl))==null?void 0:Le.previewUrl)??je("product"),product:Pe(["voss-rowe-runner-volcanic-ash","birchwood-salt-flat","voss-rowe-dune-slip-face"])??ve((Qe=i.find(Ke=>Ke.id==="voss-rowe-trail-runner"))==null?void 0:Qe.previewUrl)??je("product"),presenter:ve(ti(r.find(Ke=>Ke.id==="maren")??r.find(Ke=>Ke.avatarUrl)??r[0]??{}).src)??je("character"),scene:de(["furniture-travertine-atrium","wide-establishing-environment","studio-soft-horizon","studio-volcanic-ash-field","furniture-lamplight-hours"])??Pe(["moss-larkin-chair-travertine-atrium","calder-snow-loft","basalt-snells-window"])??je("template")}},[t,r,ne,i,l]);return o.jsx(Nf.Provider,{value:U,children:o.jsxs(is,{children:[o.jsxs("main",{className:"sc-main",id:"main","data-no-dock":M||void 0,children:[o.jsxs("h1",{className:"sc-greet",children:["Compose a shot ",o.jsx("em",{children:"on brand"})]}),o.jsxs("div",{className:"sc-create-grid",children:[o.jsxs("button",{type:"button",className:"sc-create-card","data-tone":"compose","data-main":"",onClick:ue,children:[o.jsx(UM,{thumbUrl:ze.compose,fallback:o.jsx(Y7,{size:22,weight:"fill"})}),o.jsx("b",{children:"Create an image"})]}),o.jsx(s8,{tone:"product",title:"Add a product",count:ne.length,thumbUrl:ze.product,icon:o.jsx(Zp,{size:22,weight:"fill"}),onClick:()=>S("product")}),o.jsx(s8,{tone:"presenter",title:"Create a presenter",thumbUrl:ze.presenter,icon:o.jsx(eW,{size:22,weight:"fill"}),onClick:()=>S("presenter")}),o.jsx(s8,{tone:"scene",title:"Create a scene",thumbUrl:ze.scene,icon:o.jsx(WU,{size:22,weight:"fill"}),onClick:()=>S("scene")})]}),!f&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":U,style:I,"aria-hidden":!0,children:o.jsx(Pre,{size:"grid",count:8})}),f&&h&&o.jsxs("p",{className:"sc-feed-empty",children:["Couldn't load the showcase gallery."," ",o.jsx("button",{type:"button",className:"sc-sec-more",onClick:()=>p(),children:"Retry"})]}),f&&!h&&l.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(gm,{filters:o.jsx(vm,{mode:"tabs",group:Q}),search:l.length>=_re&&o.jsx(id,{value:C,onChange:R,noun:"examples",total:l.length}),density:o.jsx(dm,{value:X,onChange:z})}),Se.length>0&&o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":U,style:I,children:Se.map(ce=>o.jsx(VM,{entry:ce,size:"grid",hideRecipe:!0,onOpen:_,productHref:ve=>la(g,ve),presenterHref:ve=>ha(g,ve),sceneHref:ve=>_r(g,ve),...xe(ce)},ce.id))}),Se.length===0&&(te?o.jsx(wm,{noun:"examples",q:C,facet:O?qg(O):null,onClearSearch:D,onClearAll:K}):o.jsx("p",{className:"sc-looks-empty",children:"No example carries that category yet."}))]}),!a&&o.jsx("div",{className:"sc-masonry","aria-hidden":!0,children:o.jsx(zM,{size:"grid",count:8})}),a&&We.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"sc-sec-head",children:[o.jsx("span",{className:"sc-sec-title",children:"Presenters"}),o.jsx(_n,{className:"sc-sec-more",to:qi(g),children:"Browse presenters"})]}),o.jsx("div",{className:"sc-masonry",children:We.map(ce=>o.jsx(_6,{presenter:ce,variant:"navigate",size:"grid",onOpen:N},ce.id))})]}),!n&&o.jsx("div",{className:"sc-masonry","aria-hidden":!0,children:o.jsx(BM,{size:"grid",count:8})}),n&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"sc-sec-head",children:[o.jsx("span",{className:"sc-sec-title",children:"Scenes"}),o.jsx(_n,{className:"sc-sec-more",to:_u(g),children:"Browse scenes"})]}),o.jsx("div",{className:"sc-masonry",children:Xe.map(ce=>o.jsx(I0,{scene:ce,variant:"navigate",size:"grid",onOpen:P},ce.id))})]})]}),!M&&o.jsxs(ZM,{children:[o.jsx(nw,{}),o.jsx(ew,{projectId:(v==null?void 0:v.id)||null,brand:g,engines:e,parentId:w,initialBrief:ee,onQueued:(ce,ve,Pe,de)=>{de!=null&&de.length&&x(de),k(),E(mr(g))}})]})]})})}function s8({tone:e,title:t,icon:n,count:r,thumbUrl:a,onClick:i}){return o.jsxs("button",{type:"button",className:"sc-create-card","data-tone":e,onClick:i,children:[o.jsx(UM,{thumbUrl:a,fallback:n}),o.jsxs("b",{children:[t,r?o.jsx(M7,{variant:"soft",radius:"full",size:"1",children:r}):null]})]})}function UM({thumbUrl:e,fallback:t}){return o.jsx("span",{className:"sc-glyph","data-photo":e?"":void 0,"aria-hidden":!0,children:e?o.jsx("span",{className:"sc-glyph-shot",children:o.jsx("img",{src:e,alt:"",loading:"lazy"})}):t})}function WM({id:e,name:t,hash:n,drawing:r,state:a,href:i,blank:l,onDiscard:u,chosen:f,batching:h,onPick:p,batch:g}){const v=Dn(),w=yv(),y=g?mm({kind:"draft",count:g.count,openLabel:"Continue",onOpen:()=>v(i),href:i,onDeselect:()=>p==null?void 0:p(e),onAct:g.onAct}):Ji(u?{draft:{onContinue:()=>v(i),href:i,onDiscard:()=>u(e)},select:p?{run:()=>p(e)}:void 0}:{onOpen:()=>v(i),href:i}),x=o.jsxs("div",{className:"sc-lookcard","data-variant":"plain","data-size":"grid","data-build":!0,"data-building":r||void 0,"data-picked":f||void 0,"data-batching":h||void 0,children:[o.jsxs(_n,{className:"sc-lookcard-media",to:i,"aria-label":h?`${f?"Deselect":"Select"} ${t}`:`Continue ${t}`,onClick:k=>{h&&p&&(k.preventDefault(),p(e))},children:[n?o.jsx("img",{src:dn(n,"tile"),alt:""}):o.jsx("span",{className:"sc-lookcard-blank",children:l}),r&&o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}),o.jsx("span",{className:"sc-draftmark",children:"Draft"})]}),p&&o.jsx("button",{type:"button",className:"sc-cell-ctl sc-lookcard-pick","data-on":f||void 0,"aria-pressed":!!f,"aria-label":f?`Deselect ${t}`:`Select ${t}`,onClick:k=>{k.preventDefault(),k.stopPropagation(),p(e)},children:o.jsx(Kn,{size:13,weight:"bold"})}),u&&!h&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Discard ${t}`,onClick:()=>u(e),children:o.jsx(jn,{size:13})}),o.jsxs("span",{className:"sc-lookcard-cap",children:[o.jsx("b",{dir:"auto",children:t}),o.jsx("span",{children:a})]})]});return w?x:o.jsxs(ff,{children:[o.jsx(hf,{children:x}),o.jsx(pf,{children:y.map(k=>o.jsxs("span",{style:{display:"contents"},children:[k.separated&&o.jsx(Hp,{}),o.jsxs(mf,{color:k.danger?"red":void 0,onSelect:k.onSelect,children:[o.jsx(Sv,{name:k.icon}),k.label]})]},k.key))})]})}function rw({title:e,name:t,maxLength:n,busy:r,error:a,onConfirm:i,onDismiss:l}){const[u,f]=s.useState(t),h=s.useRef(null),p=s.useRef(!1),g=u.trim(),v=g.length>0,w=x=>{x&&(x.style.height="auto",x.style.height=`${x.scrollHeight}px`)};s.useEffect(()=>{p.current=!1,w(h.current)},[t]),s.useEffect(()=>{r||(p.current=!1)},[r]);const y=()=>{if(!(!v||r||p.current)){if(g===t.trim())return l();p.current=!0,i(g)}};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(420px, 94vw)",onDismiss:l,onOpenAutoFocus:x=>{x.preventDefault();const k=h.current;k&&(k.focus(),k.select(),w(k))},children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:e}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("textarea",{ref:h,className:"sc-pdetails-field",value:u,dir:"auto",rows:1,maxLength:n,"aria-label":"Name",onChange:x=>{f(x.target.value),w(x.currentTarget)},onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),y())}})]}),a&&o.jsx("p",{className:"sc-assetform-err",children:a})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:l,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!v||r,"data-busy":r||void 0,onClick:y,children:r?"Saving":"Save"})]})]})}function KM({since:e}){const[t,n]=s.useState(Date.now());return s.useEffect(()=>{const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[]),o.jsx("span",{className:"sc-cell-tag",role:"status","aria-label":`${gv(e,t)}, ${rc(e,t)}`,children:rc(e,t)})}function Vre({build:e,onCancel:t,onRetry:n,onDismiss:r}){const a=e.stage==="failed",i=a?kf(e.error):null;return o.jsxs("div",{className:"sc-lookcard","data-variant":"plain","data-size":"grid","data-build":a||void 0,"data-building":!a||void 0,children:[o.jsxs("div",{className:"sc-lookcard-media",children:[o.jsx("span",{className:"sc-lookcard-blank"}),!a&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"sc-shimmer"}),o.jsx(KM,{since:e.startedAt})]}),!a&&t&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Stop building ${e.name}`,onClick:()=>t(e.id),children:o.jsx(jn,{size:13})}),a&&r&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Dismiss ${e.name}`,onClick:()=>r(e.id),children:o.jsx(jn,{size:13})}),a&&n&&o.jsxs("button",{type:"button",className:"sc-lookcard-use",onClick:()=>n(e),children:[o.jsx(eC,{size:12})," Try again"]})]}),i?o.jsxs("span",{className:"sc-lookcard-cap",title:i.raw,children:[o.jsx("b",{dir:"auto",children:e.name}),o.jsx("span",{children:i.title})]}):null]})}function sw({count:e,loaded:t,tool:n,icon:r,danger:a,onAct:i,keep:l,onClear:u,onSelectAll:f}){return o.jsxs("div",{className:"sc-picked",role:"toolbar","aria-label":"Selection",children:[o.jsxs("span",{className:"sc-picked-meta",children:[o.jsxs("span",{className:"sc-picked-n",role:"status",children:[e,o.jsx("span",{className:"sc-vh",children:" selected"})]}),t>1&&o.jsx("button",{type:"button",className:"sc-picked-all",onClick:e<t?f:u,children:e<t?"Select all":"Deselect all"})]}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsxs("span",{className:"sc-picked-tools",children:[l&&o.jsx(a8,{label:l.label,onClick:l.onAct,children:o.jsx(po,{size:17,weight:l.filled?"fill":"regular"})}),o.jsx(a8,{label:n,tone:a?"danger":void 0,onClick:i,children:o.jsx(zre,{name:r})})]}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsx("span",{className:"sc-picked-exit",children:o.jsx(a8,{label:"Done",onClick:u,children:o.jsx(jn,{size:16,weight:"bold"})})})]})}function zre(e){return o.jsx(il,{size:17})}function a8({label:e,tone:t,onClick:n,children:r}){return o.jsx(lr,{label:e,children:o.jsx("button",{type:"button",className:"sc-picked-tool","data-tone":t,"aria-label":e,onClick:n,children:r})})}const qd=()=>({kind:null,ids:new Set});function aw(e){const[t,n]=s.useState(qd),r=s.useCallback(()=>n(qd()),[]);s.useEffect(()=>{r()},[e,r]),s.useEffect(()=>{if(t.ids.size===0)return;const p=g=>{g.defaultPrevented||g.key!=="Escape"||r()};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[t.ids.size,r]);const a=s.useCallback((p,g)=>{n(v=>{if(v.kind&&v.kind!==p)return v;const w=new Set(v.ids);return w.has(g)?w.delete(g):w.add(g),w.size?{kind:v.kind??p,ids:w}:qd()})},[]),i=s.useCallback((p,g)=>{n({kind:p,ids:new Set(g)})},[]),l=s.useCallback(p=>{const g=new Set(p);n(v=>{const w=new Set([...v.ids].filter(y=>g.has(y)));return w.size?{kind:v.kind,ids:w}:qd()})},[]),u=s.useCallback(p=>{n(g=>{if(!g.ids.has(p))return g;const v=new Set(g.ids);return v.delete(p),v.size?{kind:g.kind,ids:v}:qd()})},[]),f=s.useCallback(p=>{t.ids.size===0||p.target.closest(".sc-lookcard, .sc-picked, button, a, input, select, textarea, label, [role], [contenteditable]")||r()},[t.ids.size,r]),h=s.useCallback(p=>t.kind===null||t.kind===p,[t.kind]);return{kind:t.kind,ids:t.ids,toggle:a,selectAll:i,clear:r,retain:l,forget:u,onBlank:f,picking:h,batching:t.kind}}function ow({label:e}){return o.jsx("div",{className:"sc-starter-rule",children:o.jsx("span",{children:e})})}const o8=60;function iw(e,t){const[n,r]=s.useState(o8);s.useEffect(()=>{r(o8)},[t]);const{visible:a,remaining:i}=Yv(e,n),l=s.useCallback(()=>r(u=>u+o8),[]);return{visible:a,remaining:i,showMore:l}}const Bre=24,Ure=8,i8="__bookmarked";function Wre(){const{scenes:e,collections:t,verticals:n,loaded:r,error:a,refetch:i,applyBrand:l,refreshBrands:u}=Rn(),{brand:f}=on(),{push:h}=or(),p=Dn(),[g,v]=s.useState(()=>vo(f.id)),w=J=>v(cm("scene",f.id,J)),y=im(),{builds:x,poke:k,studio:S}=Za(),E=ll(),j=s.useMemo(()=>Cc(f),[f]),N=x.filter(J=>J.kind==="scene"&&(!J.finished||J.stage==="failed")),P=!!un({path:ct.sceneStudio}),[$,M]=s.useState(()=>gh(f.id)),C=S.filter(J=>J.kind==="scene").map(J=>`${J.id}:${J.status}`).join("|");s.useEffect(()=>{P||M(gh(f.id))},[P,f.id,C]);const R=s.useMemo(()=>Oee($,S),[$,S]),[T,H]=s.useState(null),D=J=>{J.drawing&&J.jobId&&Re.cancelSceneStudioJob(f.id,J.jobId).catch(()=>{}),Fee(f.id,J.convo),M(gh(f.id))},K=J=>{const Oe=R.find(Be=>Be.convo===J);Oe&&(Oe.hash||Oe.drawing?H(Oe):D(Oe))},{q:O,setQ:Z,facets:te,setFacets:B,clearSearch:F,clear:X}=Pf(["vertical","bookmarked"]),z=te.vertical,I=te.bookmarked==="1",U=aw(`${f.id}|${O}|${z??""}|${I?"1":""}`),G=O.trim().length>0,[ne,q]=fa(Dr.wallDensity,zu),le=jc(ne),Se=J=>q(J),Q=fm(le),xe=um(le),ee=J=>p(_r(f,J)),[ae,re]=s.useState(null),[_,ue]=s.useState(!1),[We,Xe]=s.useState(null),[ze,tt]=s.useState(!1),[ce,ve]=s.useState(null),[Pe,de]=s.useState(!1),je=s.useCallback(J=>{const Oe=j.find(Be=>Be.id===J);Oe&&re(Oe)},[j]),Ue=s.useCallback(J=>{const Oe=j.find(Be=>Be.id===J);Oe&&(ve(null),Xe(Oe))},[j]),ye=async J=>{if(!(!We||ze)){tt(!0),ve(null);try{l((await Re.updateScene(f.id,We.id,{name:J})).brand),Xe(null)}catch(Oe){const Be=nn(Oe,"Could not rename this scene");ve([Be.title,Be.detail].filter(Boolean).join(" "))}finally{tt(!1)}}},Ee=async()=>{if(!(!ae||_)){ue(!0);try{l((await Re.deleteScene(f.id,ae.id)).brand),U.forget(ae.id),re(null)}catch(J){(J==null?void 0:J.status)===404?(await u(),U.forget(ae.id),re(null)):h(nn(J,"Could not delete this scene"))}finally{ue(!1)}}},be=s.useMemo(()=>I?e.filter(J=>g.includes(J.id)):z?e.filter(J=>J.verticals.includes(z)):e,[e,z,I,g]),Qe=!(j.length>0||N.length>0||R.length>0),Ke=[...e,...j].reduce((J,Oe)=>J+(g.includes(Oe.id)?1:0),0),nt=I&&Ke===0,gt=nt&&Qe,Pt=nt&&!Qe,Ut=G||I&&!gt,Nt=s.useMemo(()=>gt?e:be,[gt,e,be]),cn=s.useMemo(()=>Nt.filter(J=>wo(Gh(J),O)),[Nt,O]),[Fe,pt]=s.useState(()=>new Set),{visible:it,remaining:St,showMore:xt}=iw(cn,`${z??""}|${I?"bookmarked":""}|${gt?"browse":""}|${O}`),At=J=>[...j,...e].filter(Oe=>!Oe.verticals.length||Oe.verticals.includes(J)).length,Kt=[{value:i8,label:"Keepers",count:Ke},...n.map(J=>({value:J,label:J,count:At(J)}))],et=e.length>0?"tabs":"none",mt={key:"vertical",label:"Vertical",everyLabel:"All scenes",everyCount:e.length+j.length,selected:I?i8:z,onSelect:J=>B(J===i8?{bookmarked:"1",vertical:null}:{bookmarked:null,vertical:J}),options:Kt},ot=s.useMemo(()=>j.filter(J=>z?!J.verticals.length||J.verticals.includes(z):!0).filter(J=>wo(Gh(J),O)).filter(J=>I?g.includes(J.id):!0),[j,z,O,I,g]),kn=I?ot.length>0:R.length>0||N.length>0||ot.length>0,ut=()=>{U.ids.size===1?je([...U.ids][0]):de(!0)},Gt=[...U.ids],Ft=Gt.length>0&&Gt.every(J=>g.includes(J)),en=()=>v(Kv("scene",f.id,Gt,!Ft)),Jt=pm(U.ids.size,Ft,"scenes"),se=async()=>{if(_)return;const J=[...U.ids];ue(!0);try{const{failed:Oe,error:Be}=await tp(J,Ve=>Re.deleteScene(f.id,Ve));await u(),U.retain(Oe),de(!1),Be&&h(nn(Be,"Could not delete these scenes"))}finally{ue(!1)}},oe=o.jsxs("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>E("scene"),children:[o.jsx(cr,{size:12})," Create scene"]}),we=(J,Oe=!1)=>o.jsx("div",{className:"sc-masonry","data-wall":Oe||void 0,"data-density":!0,"data-density-size":xe,style:Q,children:J.map(Be=>o.jsx(I0,{scene:Be,variant:"use",size:"grid",onOpen:ee,href:_r(f,Be.id),onUse:y,bookmarked:g.includes(Be.id),onBookmark:w},Be.id))}),ge=o.jsx(gm,{title:"Scenes",filters:o.jsx(vm,{mode:et,group:mt}),density:o.jsx(dm,{value:le,onChange:Se}),search:e.length>=Ure&&o.jsx(id,{value:O,onChange:Z,noun:"scenes",total:e.length})});return o.jsxs(Nf.Provider,{value:xe,children:[o.jsx(is,{children:o.jsxs("main",{className:"sc-looks sc-scenes",id:"main","data-hero":Qe||void 0,onClick:U.onBlank,children:[!Qe&&ge,kn&&o.jsxs("section",{className:"sc-owned",children:[o.jsx("div",{className:"sc-sec-head",children:o.jsx("h2",{className:"sc-sec-title",children:"Your scenes"})}),o.jsxs("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":xe,style:Q,children:[!I&&R.map(J=>o.jsx(WM,{id:J.convo,name:J.name||"Untitled scene",hash:J.hash,drawing:J.drawing,state:Iee(J),href:Vi(f,J.convo),blank:o.jsx(gj,{size:44,weight:"thin"}),onDiscard:K},J.convo)),T&&o.jsx(Wn,{label:"Discard",title:`Discard ${T.name||"this unfinished scene"}?`,body:T.drawing?"The picture being drawn is stopped, and what was drawn here is thrown away. Nothing was saved to the library.":"What was drawn here is thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:J=>{J||H(null)},onConfirm:()=>{D(T),H(null)}}),!I&&N.map(J=>o.jsx(Vre,{build:J,onCancel:Oe=>void Re.cancelAssetBuild(f.id,Oe).then(k),onDismiss:Oe=>void Re.deleteAssetBuild(f.id,Oe).then(k),onRetry:()=>E("scene")},J.id)),ot.map(J=>o.jsx(I0,{scene:J,variant:"use",size:"grid",onOpen:ee,href:_r(f,J.id),onUse:y,bookmarked:g.includes(J.id),onBookmark:w,onDelete:je,onRename:Ue,chosen:U.ids.has(J.id),batching:U.batching==="owned-scene",onPick:U.picking("owned-scene")?Oe=>U.toggle("owned-scene",Oe):void 0,batch:U.kind==="owned-scene"&&U.ids.has(J.id)?{count:U.ids.size,onAct:ut,onKeep:en,allKept:Ft}:null},J.id))]}),We&&o.jsx(rw,{title:"Rename scene",name:We.name,maxLength:60,busy:ze,error:ce,onConfirm:J=>void ye(J),onDismiss:()=>{ze||Xe(null)}}),ae&&o.jsx(Wn,{label:"Delete scene",title:`Delete ${ae.name}?`,body:"Shots already made here keep their images and their recipe. Only future shots lose it.",open:!0,busy:_,onOpenChange:J=>{!J&&!_&&re(null)},onConfirm:()=>void Ee()}),Pe&&o.jsx(Wn,{label:qr("owned-scene",U.ids.size).menu,title:`${qr("owned-scene",U.ids.size).menu}?`,body:"Shots already made here keep their images and their recipe. Only future shots lose it.",open:!0,busy:_,onOpenChange:J=>{!J&&!_&&de(!1)},onConfirm:()=>void se()})]}),Qe&&r&&!a&&e.length>0&&o.jsx(oo,{shape:"cold",title:o.jsxs(o.Fragment,{children:["Build your own ",o.jsx("em",{children:"scene"})]}),body:"Upload a few references of a place, or describe it, and its light and materials carry into every image you make.",action:oe}),kn&&r&&!a&&be.length>0&&o.jsx("div",{className:"sc-sec-head sc-owned-divider",children:o.jsx("h2",{className:"sc-sec-title",children:"Scenri scenes"})}),Qe&&r&&!a&&e.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(ow,{label:"Or start from one of ours"}),ge]}),!r&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":xe,style:Q,"aria-hidden":!0,children:o.jsx(BM,{size:"grid",count:8})}),r&&a&&o.jsx(oo,{shape:"error",title:"Couldn't load this library",body:"Something went wrong reaching the catalog.",onRetry:()=>i()}),r&&!a&&!Ut&&t.map(J=>{const Oe=Nt.filter(Ge=>Ge.collections.includes(J));if(!Oe.length)return null;const Ve=Fe.has(J)?Oe:Oe.slice(0,Bre);return o.jsxs("section",{className:"sc-coll",children:[o.jsx("h2",{children:J}),we(Ve),Ve.length<Oe.length&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>pt(Ge=>new Set(Ge).add(J)),children:["Show all ",Oe.length]})})]},J)}),r&&!a&&Ut&&it.length>0&&we(it,!0),r&&!a&&Pt&&o.jsx(oo,{shape:"zero",body:"Nothing in Keepers yet. Add a scene to Keepers from its card and it stays here.",action:o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>B({bookmarked:null}),children:"Browse every scene"})}),r&&!a&&e.length>0&&!Pt&&cn.length===0&&ot.length===0&&o.jsx(wm,{noun:"scenes",q:O,facet:gt?null:I?"Keepers":z,onClearSearch:F,onClearAll:X}),Ut&&St>0&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:xt,children:["Show ",Math.min(St,60)," more"]})})]})}),o.jsx(uc,{}),U.kind==="owned-scene"&&U.ids.size>0&&o.jsx("div",{className:"sc-wall-dock",children:o.jsx(sw,{count:U.ids.size,loaded:ot.length,tool:qr("owned-scene",U.ids.size).tool,icon:qr("owned-scene",U.ids.size).icon,danger:!0,onAct:ut,keep:{label:Jt.tool,filled:Ft,onAct:en},onClear:U.clear,onSelectAll:()=>U.selectAll("owned-scene",ot.map(J=>J.id))})})]})}function lw(e,t,n=12){const r=t.filter(Boolean).join(","),[a,i]=s.useState({key:"",items:[]});return s.useEffect(()=>{if(!r)return;const l=new AbortController;return Re.feed(e,{token:r,limit:n},l.signal).then(u=>{l.signal.aborted||i({key:r,items:u.items.filter(f=>f.status==="done"&&f.images.length>0)})}).catch(()=>{}),()=>l.abort()},[e,r,n]),a.key===r?a.items:[]}const Z6=[{id:"top-down",label:"Top down",camera:"Directly overhead, looking straight down, the subject centred, deep focus"},{id:"eye-level",label:"Eye level",camera:"Eye level, the subject at a natural three-quarter angle, medium depth"},{id:"ground",label:"Ground level",camera:"Ground level, camera low, the subject close and large in frame, the place rising behind it"},{id:"wide",label:"Wide",camera:"A wide view, the subject small in the frame, the place around it doing the talking"},{id:"close",label:"Close",camera:"Close in on the subject, its surface, edge and material filling the frame"}],GM=4;function Kre(e,t=""){var u,f;const n=[],r=((u=e.refs)==null?void 0:u.length)??0;r>0&&n.push(`read from ${r} ${r===1?"photograph":"photographs"}`);const a=((f=e.setups)==null?void 0:f.length)??0;a>0&&n.push(`${a} ${a===1?"way":"ways"} to shoot it`);const i=n.join(" · "),l=i?`${i.charAt(0).toUpperCase()}${i.slice(1)}.`:"";return[t.trim(),l].filter(Boolean).join(" ")}function Gre({items:e,placeholder:t,open:n,hit:r,onRemove:a,onOpen:i}){return o.jsxs("div",{className:"sc-chipfield","data-state":n?"open":void 0,children:[r,o.jsxs("span",{className:"sc-chipfield-row",children:[e.length===0&&t?o.jsx("span",{className:"sc-chipfield-ph",children:t}):null,e.map(l=>o.jsxs("span",{className:"sc-chipfield-chip",onClick:()=>i==null?void 0:i(),children:[l,a&&o.jsx("button",{type:"button","data-role":"remove","aria-label":`Remove ${l}`,onPointerDown:u=>u.stopPropagation(),onClick:u=>{u.preventDefault(),u.stopPropagation(),a(l)},children:o.jsx(jn,{size:10,weight:"bold"})})]},l))]}),o.jsx(Yi,{size:13,className:"sc-chipfield-caret","aria-hidden":!0})]})}function Yre({value:e,onChange:t,options:n,label:r,placeholder:a="Any",findPlaceholder:i="Find or add",emptyNote:l="Nothing by that name.",max:u=12,maxLength:f=40}){const[h,p]=s.useState(!1),[g,v]=s.useState(""),w=s.useRef(null),y=[...n,...e.filter(P=>!n.some($=>tu($,P)))],x=g.trim(),k=x?y.filter(P=>P.toLowerCase().includes(x.toLowerCase())):y,S=e.length>=u,E=x.length>0&&!y.some(P=>tu(P,x))&&!S,j=P=>{const $=e.some(M=>tu(M,P));!$&&S||t($?e.filter(M=>!tu(M,P)):[...e,P])},N=()=>{var P;E&&(t([...e,x.slice(0,f)]),v(""),(P=w.current)==null||P.focus())};return s.useEffect(()=>{if(!h)return;const P=setTimeout(()=>{var $;return($=w.current)==null?void 0:$.focus()},0);return()=>clearTimeout(P)},[h]),o.jsxs(Ss,{open:h,onOpenChange:P=>{p(P),P||v("")},children:[o.jsx(Gre,{items:e,placeholder:a,open:h,onOpen:()=>p(!0),onRemove:P=>t(e.filter($=>!tu($,P))),hit:o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-chipfield-hit","aria-label":r})})}),o.jsxs(Cs,{align:"start",sideOffset:6,className:"sc-menu sc-chippick-menu",children:[o.jsx("input",{ref:w,className:"sc-chippick-find",type:"text",value:g,maxLength:f,placeholder:i,"aria-label":i,onChange:P=>v(P.target.value),onKeyDown:P=>{P.stopPropagation(),P.key==="Enter"?(P.preventDefault(),E?N():k.length===1&&j(k[0])):P.key==="Escape"&&p(!1)}}),o.jsxs("div",{className:"sc-chippick-list",children:[k.map(P=>{const $=e.some(M=>tu(M,P));return o.jsxs(tr,{className:"sc-menu-item","data-on":$||void 0,"data-off":!$&&S?"":void 0,onSelect:M=>{M.preventDefault(),j(P)},children:[o.jsx("span",{className:"sc-menu-lb",children:P}),$&&o.jsx(Kn,{size:14,className:"sc-menu-check","aria-hidden":"true"})]},P)}),!k.length&&!E&&o.jsx("p",{className:"sc-chippick-none",children:l})]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-menu-sep"}),o.jsxs(tr,{className:"sc-menu-item",onSelect:P=>{P.preventDefault(),N()},children:[o.jsx(cr,{size:16,className:"sc-menu-ic"}),o.jsxs("span",{className:"sc-menu-lb",children:['Add "',x,'"']})]})]}),S&&o.jsx("p",{className:"sc-chippick-none",children:"That is as many as this holds."})]})]})}const tu=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();function YM({name:e,categories:t,known:n,hint:r,ways:a,wayChoices:i,wayMax:l,busy:u,error:f,onSave:h,onDismiss:p}){const[g,v]=s.useState(e),[w,y]=s.useState(t),[x,k]=s.useState(()=>[...a??[]]),S=g.trim(),E=S.length>0,j=M=>M.map(C=>C.id).join(" "),N=S!==e.trim()||w.join(" ")!==t.join(" ")||!!a&&j(x)!==j(a),P=x.length>=(l??Number.POSITIVE_INFINITY)?[]:(i??[]).filter(M=>!x.some(C=>C.id===M.id)),$=()=>{if(!(!E||u)){if(!N)return p();h({name:S,categories:w,...a?{ways:x}:{}})}};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(460px, 94vw)",onDismiss:p,children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Details"}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("input",{className:"sc-pdetails-field",value:g,dir:"auto",onChange:M=>v(M.target.value),onKeyDown:M=>M.key==="Enter"&&$()})]}),o.jsxs("div",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Categories"}),o.jsx(Yre,{value:w,onChange:y,options:n,label:"Categories",placeholder:"Any",findPlaceholder:"Find or add a category",emptyNote:"Nothing by that name.",maxLength:30}),o.jsx("span",{className:"sc-pdetails-hint",children:r})]}),a&&o.jsxs("div",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Ways to shoot it"}),o.jsxs("div",{className:"sc-pdetails-ways",children:[x.map(M=>o.jsxs("div",{className:"sc-pdetails-way",children:[o.jsx("span",{className:"sc-pdetails-way-lb",children:M.label}),o.jsx("span",{className:"sc-pdetails-way-sub",children:M.camera}),o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":`Remove ${M.label}`,onClick:()=>k(x.filter(C=>C.id!==M.id)),children:o.jsx(jn,{size:13,weight:"bold","aria-hidden":!0})})]},M.id)),P.length>0&&o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost","aria-label":"Add a way to shoot it",children:[o.jsx(cr,{size:12,weight:"bold","aria-hidden":!0}),o.jsx("span",{children:"Add a way"})]})}),o.jsx(Cs,{children:P.map(M=>o.jsx(tr,{onSelect:()=>k([...x,M]),children:M.label},M.id))})]})]}),o.jsxs("span",{className:"sc-pdetails-hint",children:["A way moves the camera and leaves the world alone.",l?` ${l} at most.`:""]})]}),f&&o.jsx("p",{className:"sc-assetform-err",children:f})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:p,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!E,"data-busy":u||void 0,onClick:$,children:u?"Saving":"Save"})]})]})}function zl({src:e,crop:t}){const[n,r]=s.useState(!1);return n?o.jsx("span",{className:"sc-lookpage-ref-blank","aria-hidden":!0,children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async",...t?{"data-crop":t}:{},onError:()=>r(!0)})}function cw(){return o.jsx("div",{className:"sc-lookpage-refs",children:o.jsx("div",{className:"sc-lookpage-ref",children:o.jsx("span",{className:"sc-lookpage-ref-blank",children:o.jsx(Ws,{size:20})})})})}function uw({node:e,to:t}){const[n,r]=s.useState(!1);return o.jsx(_n,{className:"sc-lookcard","aria-label":`Open ${Sr(e)}`,to:t,children:n?o.jsx("span",{className:"sc-lookcard-blank",children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:dn(e.images[0],"tile"),alt:"",loading:"lazy",onError:()=>r(!0)})})}function Lu({label:e,children:t}){const n=s.useRef(null),r=s.useRef(null),a=s.useRef(!1),i=s.useRef(()=>{});s.useLayoutEffect(()=>{const u=n.current,f=r.current;if(!u||!f)return;let h=0;const p=()=>{const w=f.scrollWidth-f.clientWidth;if(w<=1){delete u.dataset.overflowLeft,delete u.dataset.overflowRight;return}f.scrollLeft>2?u.dataset.overflowLeft="":delete u.dataset.overflowLeft,f.scrollLeft<w-2?u.dataset.overflowRight="":delete u.dataset.overflowRight};i.current=p,p();const g=()=>{h||(h=requestAnimationFrame(()=>{h=0,p()}))},v=new ResizeObserver(()=>p());return v.observe(f),f.addEventListener("scroll",g,{passive:!0}),()=>{h&&cancelAnimationFrame(h),i.current=()=>{},v.disconnect(),f.removeEventListener("scroll",g)}},[]);const l=u=>{const f=r.current;if(!(f!=null&&f.firstElementChild)||a.current)return;const h=f.firstElementChild.getBoundingClientRect().width+16,p=f.scrollWidth/2;u<0&&f.scrollLeft<h&&(f.scrollLeft+=p);const g=f.scrollLeft,v=u*h,w=performance.now();a.current=!0;const y=x=>{const k=Math.min(1,(x-w)/420);f.scrollLeft=g+v*(1-(1-k)**3),i.current(),k<1?requestAnimationFrame(y):(a.current=!1,f.scrollLeft>=p&&(f.scrollLeft-=p),i.current())};requestAnimationFrame(y)};return o.jsxs("section",{className:"sc-lookpage-band",children:[o.jsx("p",{className:"sc-bandhead",children:e}),o.jsxs("div",{className:"sc-slider",ref:n,children:[o.jsx("button",{type:"button",className:"sc-slider-arrow prev","aria-label":"Previous",onClick:()=>l(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-slider-arrow next","aria-label":"Next",onClick:()=>l(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsxs("div",{className:"sc-slider-track",ref:r,children:[t,t]})]})]})}function qM(e){const t=s.useRef(null),n=s.useRef(null);s.useLayoutEffect(()=>{const a=t.current,i=n.current;if(!a||!i)return;let l=0;const u=()=>{const p=i.scrollWidth-i.clientWidth;if(p<=1){delete a.dataset.overflowLeft,delete a.dataset.overflowRight;return}i.scrollLeft>2?a.dataset.overflowLeft="":delete a.dataset.overflowLeft,i.scrollLeft<p-2?a.dataset.overflowRight="":delete a.dataset.overflowRight},f=()=>{l||(l=requestAnimationFrame(()=>{l=0,u()}))};u();const h=new ResizeObserver(()=>u());h.observe(i);for(const p of i.children)h.observe(p);return i.addEventListener("scroll",f,{passive:!0}),()=>{l&&cancelAnimationFrame(l),h.disconnect(),i.removeEventListener("scroll",f)}},[e]);const r=s.useCallback(a=>{const i=n.current;if(!(i!=null&&i.firstElementChild))return;const l=i.firstElementChild.getBoundingClientRect().width,u=Number.parseFloat(getComputedStyle(i).columnGap)||0,f=window.matchMedia("(prefers-reduced-motion: reduce)").matches;i.scrollBy({left:a*(l+u),behavior:f?"auto":"smooth"})},[]);return{shellRef:t,railRef:n,page:r}}function dw({count:e,label:t,className:n,trackClassName:r,style:a,children:i}){const{shellRef:l,railRef:u,page:f}=qM(e);return o.jsxs("div",{className:n?`sc-rail ${n}`:"sc-rail",ref:l,style:{"--sc-rail-count":e},children:[o.jsx("button",{type:"button",className:"sc-rail-arrow prev","aria-label":`${t}, earlier`,onClick:()=>f(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-rail-arrow next","aria-label":`${t}, later`,onClick:()=>f(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsx("ol",{className:r?`sc-rail-track ${r}`:"sc-rail-track","aria-label":t,ref:u,style:a,children:i})]})}function ym(){const e=s.useRef(!1);return s.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),s.useCallback(()=>{const t=window.location.pathname;return()=>e.current&&window.location.pathname===t},[])}const qre=1500;function XM(e,t,n){const{refreshBrands:r}=Rn(),[a,i]=s.useState(null),[l,u]=s.useState([]),[f,h]=s.useState([]),[p,g]=s.useState(!1),[v,w]=s.useState(0),y=s.useRef(void 0),x=s.useRef(r);x.current=r,s.useEffect(()=>{if(!t)return;let S=!0,E=null;const j=async()=>{var N;try{const P=await Re.sceneExamples(e,t);if(!S)return;const $=P.job?`${P.job.id}:${P.job.done.length}:${P.job.status}`:null;if($&&y.current!==void 0&&$!==y.current&&await x.current(),!S)return;y.current=$,i(P.job),u(P.first),h(P.more),g(!0),((N=P.job)==null?void 0:N.status)==="running"&&(E=setTimeout(j,qre))}catch{}};return j(),()=>{S=!1,E&&clearTimeout(E)}},[e,t,n,v]);const k=s.useCallback(()=>w(S=>S+1),[]);return{job:a,first:l,more:f,read:p,again:k}}const Xre=["no","one","two","three","four","five"];function Qre({brandId:e,scene:t,onError:n}){const{applyBrand:r}=Rn(),a=im(),i=ym(),{job:l,first:u,again:f}=XM(e,t.id,t.previewUrl??null),[h,p]=s.useState(!1),[g,v]=s.useState(!1),[w,y]=s.useState(null),x=iA(t.examples,l),k=(l==null?void 0:l.status)==="running",S=$K(t.examples),E=async()=>{if(g||!u.length)return;const T=i();v(!0),n(null);try{await Re.drawSceneExamples(e,t.id,{first:!0}),f()}catch(H){T()&&n(String((H==null?void 0:H.message)??H))}finally{T()&&v(!1)}},j=u.length&&(l==null?void 0:l.status)!=="running"?o.jsx("p",{className:"sc-scenepage-examples-ask",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",disabled:g,onClick:()=>void E(),children:[S.length?"Draw them again":"Draw it in use",`, ${Xre[u.length]??u.length} picture${u.length===1?"":"s"}`]})}):null,N=async T=>{const H=Z6.find(K=>K.id===T);if(!H||h)return;const D=i();p(!0),n(null);try{const K=t.setups??[];if(!K.some(O=>O.id===H.id)){const O=await Re.updateScene(e,t.id,{setups:[...K,H]});r(O.brand)}a(t.id,H.id)}catch(K){D()&&n(String((K==null?void 0:K.message)??K))}finally{D()&&p(!1)}},P=t.previewUrl?{src:t.previewUrl,label:"The place"}:null;if(!x.length&&!P)return o.jsx(cw,{});if(!x.length&&P)return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-scenepage-place",children:o.jsx("button",{type:"button","aria-label":`${P.label}, open`,onClick:()=>y(P),children:o.jsx(zl,{src:sr(P.src,"tile")})})}),j,w&&o.jsx(Uu,{src:w.src,kind:"scene",label:w.label,noun:t.name,onClose:()=>y(null)})]});const $=w==null?void 0:w.tile,M=$!=null&&$.setup?Z6.find(T=>T.id===$.setup):void 0,C=!!M&&((t.setups??[]).some(T=>T.id===M.id)||(t.setups??[]).length<GM),R=k&&l?mv({status:l.status,step:l.current,done:l.done.length,total:l.roles.length,error:l.error}):S.length>0?`${S.length===1?`The ${tc[S[0]].toLowerCase()} shows`:"These show"} an earlier picture of this place.`:null;return o.jsxs(o.Fragment,{children:[o.jsxs(dw,{count:x.length+(P?1:0),label:"Pictures of this place",className:"sc-refset-rail",trackClassName:"sc-refset",children:[P&&o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":"The place, open",onClick:()=>y(P),children:o.jsx(zl,{src:sr(P.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:"The place"})]}),x.map(T=>{const H=tc[T.role];return o.jsxs("li",{children:[T.state==="drawing"?o.jsxs("span",{className:"sc-refset-tile","data-state":"drawing",role:"img","aria-label":`${H}, drawing`,children:[T.url&&o.jsx(zl,{src:sr(T.url,"small")}),o.jsx("span",{className:"sc-shimmer","aria-hidden":!0})]}):T.state==="failed"?o.jsxs("span",{className:"sc-refset-tile","data-state":"failed",role:"img","aria-label":`${H} did not draw`,title:T.error,children:[o.jsx(kc,{size:20,"aria-hidden":!0}),o.jsx("span",{children:"Did not draw"})]}):o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":`${H}, open`,onClick:()=>y({src:T.url,label:H,tile:T}),children:o.jsx(zl,{src:sr(T.url,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:H})]},T.role)})]}),R&&o.jsx("p",{className:"sc-scenepage-examples-state","aria-live":"polite",children:R}),j,w&&o.jsx(Uu,{src:w.src,kind:"scene",label:w.label,noun:t.name,onClose:()=>y(null),actions:M&&C?o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:h,onClick:()=>void N(M.id),children:"Shoot it this way"}):void 0})]})}function Jre(){var xe,ee,ae,re;const{sceneId:e}=Bs(),{scenes:t,loaded:n,error:r,refetch:a,applyBrand:i,refreshBrands:l}=Rn(),{brand:u}=on(),f=Dn(),h=im(),p=u.id,[g,v]=s.useState([]),[w,y]=s.useState(()=>vo(p)),[x,k]=s.useState(null),S=_=>f(_r(u,_)),E=Hh(u,e??""),j=E??t.find(_=>_.id===e);Sc(j==null?void 0:j.name);const N=!!E;s.useEffect(()=>{let _=!0;if(v([]),!N)return Re.sceneFrames(e??"").then(ue=>{_&&v(ue.frames)}).catch(()=>{_&&v([])}),()=>{_=!1}},[e,N]);const P=lw(u.id,[e??""]),$=s.useMemo(()=>{if(!j||N)return[];return t.filter(We=>We.id!==j.id).sort((We,Xe)=>ue(Xe)-ue(We)).slice(0,8);function ue(We){const Xe=We.lighting.split(/[ ,]+/).some(tt=>tt.length>3&&j.lighting.toLowerCase().includes(tt.toLowerCase())),ze=We.collections.some(tt=>j.collections.includes(tt));return(Xe?2:0)+(ze?1:0)}},[t,j,N]),M=s.useMemo(()=>{if(j||!n||r)return[];const _=vo(p);return CM(t,ue=>_.includes(ue.id)).slice(0,6)},[j,n,r,t,p]),[C,R]=s.useState(null),[T,H]=s.useState(!1),[D,K]=s.useState(!1),[O,Z]=s.useState(!1),te=s.useRef(!1),B=ym(),F=s.useMemo(()=>[...new Set([...t.flatMap(_=>_.verticals),...Cc(u).flatMap(_=>_.verticals)])].sort((_,ue)=>_.localeCompare(ue)),[t,u]),X=async _=>{if(E){K(!0),R(null);try{const ue=await Re.updateScene(u.id,E.id,{name:_.name,verticals:_.categories,..._.ways?{setups:_.ways}:{}});i(ue.brand),Z(!1)}catch(ue){R(String(ue.message??ue))}finally{K(!1)}}},z=async()=>{if(!E||te.current)return;te.current=!0;const _=B(),ue=_u(u);H(!0);try{const We=await Re.deleteScene(u.id,E.id);i(We.brand)}catch(We){if((We==null?void 0:We.status)!==404){te.current=!1,_()&&(R(String(We.message??We)),H(!1));return}await l()}_()&&f(ue,{replace:!0})};if(!n&&!E)return o.jsx(is,{children:o.jsx("main",{className:"sc-lookpage sc-scenepage",id:"main",children:o.jsx("div",{className:"sc-tplrow","aria-hidden":!0})})});if(r&&!E)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:"Couldn't load this scene"}),o.jsx("p",{className:"sc-lookpage-lede",children:"Something went wrong reaching the catalog."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>a(),children:"Retry"})})]})});if(!j)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:"This scene isn't here anymore"}),o.jsx("p",{className:"sc-lookpage-lede",children:"It may have been removed from the catalog, or the link is out of date."}),o.jsxs("div",{className:"sc-lookpage-acts",children:[o.jsx(_n,{className:"sc-btn sc-btn-primary",to:`${mr(u)}?compose=1`,children:"Start from scratch"}),o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:_u(u),children:"Browse all scenes"})]}),M.length>0&&o.jsx(Lu,{label:"You might like",children:M.map(_=>o.jsx(I0,{scene:_,variant:"navigate",size:"slider",onOpen:S,href:_r(u,_.id)},_.id))})]})});const I=g.length?g.map((_,ue)=>({src:_,label:`Example ${ue+1}`})):j.previewUrl?[{src:j.previewUrl,label:"The place"}]:[],U=j.subject!=="person"&&I.length>0?"Shown with a demo product for reference. Yours replaces it.":"",G=!E&&w.includes(j.id),ne=(E==null?void 0:E.setups)??[],q=((E==null?void 0:E.refs)??[]).filter(_=>_!==(E==null?void 0:E.previewUrl)),le=((ee=(xe=E==null?void 0:E.examples)==null?void 0:xe.find(_=>!_.earlier))==null?void 0:ee.with)??((re=(ae=E==null?void 0:E.examples)==null?void 0:ae[0])==null?void 0:re.with),Se=E?E.figure?"The person in it is a stand-in: with a presenter attached, the picture goes with the shot and they take the role.":le?`Shown in use with a Scenri demo ${le}. Shots are told the words, never handed these pictures.`:E.previewUrl?"Shots are told the words, never handed this picture.":"":"",Q=E?Kre({refs:q,setups:E.setups},Se):"";return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:j.name}),j.verticals.length>0&&o.jsx("ul",{className:"sc-lookpage-cats","aria-label":"Filed under",children:j.verticals.map(_=>o.jsx("li",{className:"sc-chip","data-static":!0,children:_},_))}),o.jsx("p",{className:"sc-lookpage-lede",children:j.description}),o.jsxs("div",{className:"sc-lookpage-acts",children:[ne.length>0?o.jsxs("span",{className:"sc-splitbtn",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary sc-splitbtn-go",onClick:()=>void h(j.id),children:"Use in a shot"}),o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary sc-splitbtn-more","aria-label":"Use it a way",children:o.jsx(Yi,{size:12,weight:"bold","aria-hidden":!0})})}),o.jsx(Cs,{children:ne.map(_=>o.jsx(tr,{onSelect:()=>void h(j.id,_.id),children:_.label},_.id))})]})]}):o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>void h(j.id),children:"Use in a shot"}),E?o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:cv(u,E.id),children:"Edit scene"}):o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost","aria-pressed":G,onClick:()=>y(cm("scene",p,j.id)),children:[o.jsx(po,{size:13,weight:G?"fill":"regular"}),o.jsx("span",{children:G?"Remove from Keepers":"Add to Keepers"})]}),E&&o.jsx(lr,{label:"Edit name, filing and ways",children:o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":"Edit name, filing and ways","aria-haspopup":"dialog",onClick:()=>Z(!0),children:o.jsx(Ju,{size:17})})})]}),C&&o.jsx("p",{className:"sc-assetform-err",children:C}),E?o.jsx(Qre,{brandId:u.id,scene:E,onError:R},E.id):I.length>1?o.jsx(dw,{count:I.length,label:"Pictures of this place",className:"sc-refset-rail",trackClassName:"sc-refset",children:I.map(_=>o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":`${_.label}, open`,onClick:()=>k(_),children:o.jsx(zl,{src:sr(_.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:_.label})]},_.src))}):I.length===1?o.jsx("div",{className:"sc-scenepage-place",children:o.jsx("button",{type:"button","aria-label":`${I[0].label}, open`,onClick:()=>k(I[0]),children:o.jsx(zl,{src:sr(I[0].src,"tile")})})}):o.jsx(cw,{}),!E&&U&&o.jsx("p",{className:"sc-lookpage-note",children:U}),E&&o.jsxs("section",{className:"sc-scenepage-told",children:[o.jsxs("dl",{className:"sc-lookpage-told",children:[o.jsxs("div",{children:[o.jsx("dt",{children:Ne.lightLabel}),o.jsx("dd",{dir:"auto",children:E.lighting})]}),E.camera&&o.jsxs("div",{children:[o.jsx("dt",{children:Ne.cameraLabel}),o.jsx("dd",{dir:"auto",children:E.camera})]}),E.figure&&o.jsxs("div",{children:[o.jsx("dt",{children:Ne.figureLabel}),o.jsx("dd",{dir:"auto",children:E.figure})]})]}),o.jsx("p",{className:"sc-lookpage-note",children:"Every shot made here is told this. Anything you write in the shot wins."})]}),q.length>0&&o.jsxs("section",{className:"sc-presenterpage-sources",children:[o.jsx("p",{className:"sc-presenterpage-sources-lb",children:"What it was read from"}),o.jsx("div",{className:"sc-presenterpage-sources-row",children:q.map((_,ue)=>o.jsx("button",{type:"button",className:"sc-presenterpage-source","aria-label":`Source photo ${ue+1}, open`,onClick:()=>k({src:_,label:`Source photo ${ue+1}`}),children:o.jsx(zl,{src:sr(_,"micro")})},_))})]}),E&&o.jsxs("div",{className:"sc-prec",children:[Q&&o.jsx("p",{className:"sc-prec-note",children:Q}),o.jsx(Wn,{label:"Delete scene",title:`Delete ${E.name}?`,body:"Shots already made here keep their images. Their recipe will say this scene is gone, and building from one again will miss it.",busy:T,onConfirm:()=>void z()})]}),P.length>0&&o.jsx(Lu,{label:`Shots made in ${j.name}`,children:P.map(_=>o.jsx(uw,{node:_,to:Wp(u,null,_.id)},_.id))}),$.length>0&&o.jsx(Lu,{label:"Other scenes, similar light",children:$.map(_=>o.jsx(I0,{scene:_,variant:"navigate",size:"slider",onOpen:S,href:_r(u,_.id)},_.id))}),O&&E&&o.jsx(YM,{name:E.name,categories:E.verticals,known:F,hint:"The verticals this place suits, so it surfaces where you work.",ways:ne,wayChoices:Z6,wayMax:GM,busy:D,error:C,onSave:_=>void X(_),onDismiss:()=>Z(!1)}),x&&o.jsx(Uu,{src:x.src,kind:"scene",label:x.label,noun:j.name,onClose:()=>k(null)})]})})}function ese({draft:e,href:t,onDiscard:n,chosen:r,batching:a,onPick:i,batch:l}){return o.jsx(WM,{id:e.id,name:e.name.trim()||"Untitled presenter",hash:e.hash,drawing:!!e.drawing,state:tse(e),href:t,blank:o.jsx(tW,{size:44,weight:"thin"}),onDiscard:n,chosen:r,batching:a,onPick:i,batch:l})}function tse(e){return e.drawing?"Drawing":e.approved?e.approved===1?"Face ready":e.approved>=e.of?"Ready to save":`${e.approved} of ${e.of} views ready`:e.hash?"A face to decide":e.source==="photos"?"Photos added":"Not drawn yet"}function nse({suggested:e,busy:t,error:n,onConfirm:r,onDismiss:a}){const[i,l]=s.useState(e),u=s.useRef(null),f=s.useRef(!1),h=i.trim(),p=h.length>0;s.useEffect(()=>{f.current=!1},[e]),s.useEffect(()=>{t||(f.current=!1)},[t]);const g=()=>{!p||t||f.current||(f.current=!0,r(h))};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(420px, 94vw)",onDismiss:a,onOpenAutoFocus:v=>{v.preventDefault();const w=u.current;w&&(w.focus(),w.select())},children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Duplicate presenter"}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("input",{ref:u,className:"sc-pdetails-field",value:i,dir:"auto",maxLength:60,onChange:v=>l(v.target.value),onKeyDown:v=>v.key==="Enter"&&g()})]}),n&&o.jsx("p",{className:"sc-assetform-err",children:n})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!p||t,"data-busy":t||void 0,onClick:g,children:t?"Duplicating":"Duplicate"})]})]})}const rse=60;function sse(e,t,n=rse){var l;const r=e.trim(),a=(((l=r.match(/^(.*?)(?: copy(?: \d+)?)?$/i))==null?void 0:l[1])??r).trim()||r,i=new Set(t.map(u=>u.trim().toLowerCase()).filter(Boolean));for(let u=1;u<1e4;u++){const f=u===1?" copy":` copy ${u}`,h=Math.max(1,n-f.length),p=`${a.slice(0,h).trimEnd()}${f}`;if(!i.has(p.toLowerCase()))return p}return`${a.slice(0,Math.max(1,n-5)).trimEnd()} copy`}const ase=8,l8="__bookmarked";function ose(){const{presenters:e,presenterCategories:t,presentersLoaded:n,presentersError:r,refetchPresenters:a,applyBrand:i,refreshBrands:l}=Rn(),{brand:u}=on(),f=Dn(),h=Wv(),{push:p}=or(),{q:g,setQ:v,facets:w,setFacets:y,clearSearch:x,clear:k}=Pf(["category","bookmarked"]),S=w.category,E=w.bookmarked==="1",[j,N]=s.useState(()=>lm("presenter",u.id)),P=me=>N(cm("presenter",u.id,me)),$=aw(`${u.id}|${g}|${S??""}|${E?"1":""}`),M=ll(),C=s.useMemo(()=>Sf(u),[u]),[R,T]=fa(Dr.wallDensity,zu),H=jc(R),D=me=>T(me),K=fm(H),O=um(H),Z=me=>f(ha(u,me)),te=me=>f(Up(u,me)),B=s.useMemo(()=>S?e.filter(me=>me.suitableCategories.includes(S)):e,[e,S]),F=s.useMemo(()=>B.filter(me=>wo(Yh(me),g)),[B,g]),X=s.useRef(null),z=s.useRef(null),I=o.jsxs("button",{ref:z,type:"button",className:"sc-btn sc-btn-primary",onClick:()=>M("presenter"),children:[o.jsx(cr,{size:12})," Create presenter"]}),[U,G]=s.useState([]),ne=s.useRef(0),q=s.useCallback(()=>{const me=++ne.current;return Re.presenterDrafts(u.id).then(_e=>{me===ne.current&&G(_e.drafts.filter(W=>!W.presenterId))}).catch(()=>{}),()=>{me===ne.current&&ne.current++}},[u.id]),le=!!un({path:ct.presenterStudio}),{tasks:Se}=Za(),Q=Se.filter(me=>me.id.startsWith("presenter:")).map(me=>`${me.id}:${me.state}:${me.percent??""}`).join("|");s.useEffect(()=>{if(!le)return q()},[le,q,Q]);const xe=s.useCallback(me=>{const _e=Math.max(0,U.findIndex(W=>W.id===me));ee.current=_e,$.forget(me),G(W=>W.filter(pe=>pe.id!==me)),Re.deletePresenterDraft(u.id,me).finally(()=>q())},[u.id,U,q,$.forget]),ee=s.useRef(null);s.useEffect(()=>{var pe;const me=ee.current;if(me===null)return;ee.current=null;const _e=(pe=X.current)==null?void 0:pe.querySelectorAll("[data-build] .sc-cardpuck"),W=_e!=null&&_e.length?_e[Math.min(me,_e.length-1)]:z.current??document.querySelector(".sc-new-go");W==null||W.focus()},[U]);const[ae,re]=s.useState(null),[_,ue]=s.useState(!1),[We,Xe]=s.useState(!1),ze=s.useCallback(me=>{const _e=U.find(W=>W.id===me);_e!=null&&_e.drawn?re(_e):xe(me)},[U,xe]),[tt,ce]=s.useState(null),[ve,Pe]=s.useState(null),[de,je]=s.useState(null),[Ue,ye]=s.useState(!1),[Ee,be]=s.useState(null),[Le,Qe]=s.useState(null),Ke=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&(be(null),ce(_e))},[C]),nt=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&(be(null),Pe(_e))},[C]),gt=async me=>{if(!(!ve||Ue)){ye(!0),be(null);try{i((await Re.updatePresenter(u.id,ve.id,{name:me})).brand),Pe(null)}catch(_e){const W=nn(_e,"Could not rename this presenter");be([W.title,W.detail].filter(Boolean).join(" "))}finally{ye(!1)}}},Pt=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&je(_e)},[C]),Ut=s.useRef(null);s.useEffect(()=>{var pe;const me=Ut.current;if(me===null)return;Ut.current=null;const _e=(pe=X.current)==null?void 0:pe.querySelectorAll(".sc-lookcard:not([data-build]) .sc-lookcard-more"),W=_e!=null&&_e.length?_e[Math.min(me,_e.length-1)]:z.current??document.querySelector(".sc-new-go");W==null||W.focus()},[e,u]);const Nt=async me=>{if(!(!tt||Ue)){ye(!0),be(null);try{const _e=await Re.duplicatePresenter(u.id,tt.id,me);i(_e.brand),ce(null),Qe(_e.presenter.id)}catch(_e){const W=nn(_e,"Could not duplicate this presenter");be([W.title,W.detail].filter(Boolean).join(" "))}finally{ye(!1)}}},cn=async()=>{if(!(!de||Ue)){Ut.current=Math.max(0,Fe.findIndex(me=>me.id===de.id)),ye(!0);try{const me=await Re.deletePresenter(u.id,de.id);i(me.brand),$.forget(de.id),je(null)}catch(me){(me==null?void 0:me.status)===404?(await l(),$.forget(de.id),je(null)):p(nn(me,"Could not delete this presenter"))}finally{ye(!1)}}};s.useEffect(()=>{var _e,W;if(!Le)return;(W=(_e=X.current)==null?void 0:_e.querySelector(".sc-lookcard[data-just-added]"))==null||W.scrollIntoView({block:"nearest"});const me=window.setTimeout(()=>Qe(null),1800);return()=>window.clearTimeout(me)},[Le]);const Fe=s.useMemo(()=>C.filter(me=>S?!me.suitableCategories.length||me.suitableCategories.includes(S):!0).filter(me=>wo(Yh(me),g)).filter(me=>E?j.includes(me.id):!0),[C,S,g,E,j]),it=!(C.length>0||U.length>0),St=[...C,...e].reduce((me,_e)=>me+(j.includes(_e.id)?1:0),0),xt=E&&St===0,At=xt&&it,Kt=xt&&!it,et=!E||At,mt=Fe.filter(me=>!E||At||j.includes(me.id)),ot=et&&U.length>0||mt.length>0,kn=s.useMemo(()=>!E||At?F:F.filter(me=>j.includes(me.id)),[F,E,At,j]),{visible:ut,remaining:Gt,showMore:Ft}=iw(kn,`${S??""}|${E?"keepers":""}|${At?"browse":""}|${g}`),en=e.length+C.length>0?"tabs":"none",Jt=s.useCallback(async me=>{const{failed:_e,error:W}=await tp(me,pe=>Re.deletePresenterDraft(u.id,pe));G(pe=>pe.filter(Ie=>_e.includes(Ie.id)||!me.includes(Ie.id))),$.retain(_e),q(),W&&p(nn(W,"Could not discard these drafts"))},[u.id,q,$.retain,p]),se=()=>{const me=U.filter(_e=>$.ids.has(_e.id));me.some(_e=>_e.drawn)?me.length===1?re(me[0]):ue(!0):Jt(me.map(_e=>_e.id))},oe=()=>{const me=[...$.ids];me.length===1?Pt(me[0]):Xe(!0)},we=[...$.ids],ge=$.kind==="presenter"&&we.length>0&&we.every(me=>j.includes(me)),J=()=>N(Kv("presenter",u.id,we,!ge)),Oe=pm($.ids.size,ge,"presenters"),Be=async()=>{if(Ue)return;const me=[...$.ids];ye(!0);try{const{failed:_e,error:W}=await tp(me,pe=>Re.deletePresenter(u.id,pe));await l(),$.retain(_e),Xe(!1),W&&p(nn(W,"Could not delete these presenters"))}finally{ye(!1)}},Ve={key:"category",label:"Category",everyLabel:"All presenters",everyCount:e.length+C.length,selected:E?l8:S,onSelect:me=>y(me===l8?{bookmarked:"1",category:null}:{bookmarked:null,category:me}),options:[{value:l8,label:"Keepers",count:St},...t.map(me=>({value:me,label:me,count:[...C,...e].filter(_e=>!_e.suitableCategories.length||_e.suitableCategories.includes(me)).length}))]},Ge=o.jsx(gm,{title:"Presenters",filters:o.jsx(vm,{mode:en,group:Ve}),density:o.jsx(dm,{value:H,onChange:D}),search:e.length>=ase&&o.jsx(id,{value:g,onChange:v,noun:"presenters",total:e.length})});return o.jsxs(Nf.Provider,{value:O,children:[o.jsx(is,{children:o.jsxs("main",{className:"sc-looks sc-presenters",id:"main","data-hero":it||void 0,onClick:$.onBlank,children:[!it&&Ge,ot&&o.jsxs("section",{className:"sc-owned",children:[o.jsx("div",{className:"sc-sec-head",children:o.jsx("h2",{className:"sc-sec-title",children:"Your presenters"})}),o.jsxs("div",{ref:X,className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:[et&&U.map(me=>o.jsx(ese,{draft:me,href:zi(u,me.id),onDiscard:ze,chosen:$.ids.has(me.id),batching:$.batching==="draft",onPick:$.picking("draft")?_e=>$.toggle("draft",_e):void 0,batch:$.kind==="draft"&&$.ids.has(me.id)?{count:$.ids.size,onAct:se}:null},me.id)),ae&&o.jsx(Wn,{label:"Discard",title:`Discard ${ae.name.trim()||"this unfinished presenter"}?`,body:"The views drawn so far are thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:me=>{me||re(null)},onConfirm:()=>{xe(ae.id),re(null)}}),mt.map(me=>o.jsx(_6,{presenter:me,variant:"use",size:"grid",onOpen:Z,href:ha(u,me.id),onUse:h,onDuplicate:Ke,onEdit:te,onDelete:Pt,onRename:nt,bookmarked:j.includes(me.id),onBookmark:P,fresh:me.id===Le,chosen:$.ids.has(me.id),batching:$.batching==="presenter",onPick:$.picking("presenter")?_e=>$.toggle("presenter",_e):void 0,batch:$.kind==="presenter"&&$.ids.has(me.id)?{count:$.ids.size,onAct:oe,onKeep:J,allKept:ge}:null},me.id)),ve&&o.jsx(rw,{title:"Rename presenter",name:ve.name,maxLength:60,busy:Ue,error:Ee,onConfirm:me=>void gt(me),onDismiss:()=>{Ue||Pe(null)}}),tt&&o.jsx(nse,{suggested:sse(tt.name,C.map(me=>me.name)),busy:Ue,error:Ee,onConfirm:me=>void Nt(me),onDismiss:()=>{Ue||ce(null)}}),de&&o.jsx(Wn,{label:"Delete presenter",title:`Delete ${de.name}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",open:!0,busy:Ue,onOpenChange:me=>{!me&&!Ue&&je(null)},onConfirm:()=>void cn()}),We&&o.jsx(Wn,{label:qr("presenter",$.ids.size).menu,title:`${qr("presenter",$.ids.size).menu}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",open:!0,busy:Ue,onOpenChange:me=>{!me&&!Ue&&Xe(!1)},onConfirm:()=>void Be()}),_&&o.jsx(Wn,{label:qr("draft",$.ids.size).menu,title:`${qr("draft",$.ids.size).menu}?`,body:"The views drawn so far are thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:me=>{me||ue(!1)},onConfirm:()=>{const me=[...$.ids];ue(!1),Jt(me)}})]})]}),it&&n&&!r&&e.length>0&&o.jsx(oo,{shape:"cold",title:o.jsxs(o.Fragment,{children:["Cast your own ",o.jsx("em",{children:"presenter"})]}),body:"Describe someone new, or add photos of a real person. They stay the same person in every image you make.",action:I}),ot&&n&&!r&&ut.length>0&&o.jsx("div",{className:"sc-sec-head sc-owned-divider",children:o.jsx("h2",{className:"sc-sec-title",children:"Scenri presenters"})}),!n&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":O,style:K,"aria-hidden":!0,children:o.jsx(zM,{size:"grid",count:8})}),n&&r&&o.jsx(oo,{shape:"error",title:"Couldn't load the presenter library",body:"Something went wrong reaching the catalog.",onRetry:()=>a()}),it&&n&&!r&&e.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(ow,{label:"Or cast someone from ours"}),Ge]}),n&&!r&&ut.length>0&&o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:ut.map(me=>o.jsx(_6,{presenter:me,variant:"use",size:"grid",onOpen:Z,href:ha(u,me.id),onUse:h,bookmarked:j.includes(me.id),onBookmark:P},me.id))}),n&&!r&&Kt&&o.jsx(oo,{shape:"zero",body:"Nothing in Keepers yet. Add a presenter to Keepers from its card and it stays here.",action:o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>y({bookmarked:null}),children:"Browse every presenter"})}),n&&!r&&!Kt&&!kn.length&&e.length>0&&o.jsx(wm,{noun:"presenters",q:g,facet:E?"Keepers":S,onClearSearch:x,onClearAll:k}),n&&!r&&!e.length&&o.jsx(oo,{shape:"zero",body:"The presenter library is still being cast. Check back soon."}),Gt>0&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:Ft,children:["Show ",Math.min(Gt,60)," more"]})})]})}),$.ids.size>0&&($.kind==="draft"||$.kind==="presenter")&&o.jsx("div",{className:"sc-wall-dock",children:o.jsx(sw,{count:$.ids.size,loaded:$.kind==="draft"?U.length:mt.length,tool:qr($.kind,$.ids.size).tool,icon:qr($.kind,$.ids.size).icon,danger:qr($.kind,$.ids.size).danger,onAct:$.kind==="draft"?se:oe,keep:$.kind==="presenter"?{label:Oe.tool,filled:ge,onAct:J}:null,onClear:$.clear,onSelectAll:()=>$.selectAll($.kind==="draft"?"draft":"presenter",($.kind==="draft"?U:mt).map(me=>me.id))})}),o.jsx(uc,{})]})}const ise={portrait:"Face",identity:"Face",front:"Full body","three-quarter":"Three-quarter",back:"Back",left:"Left",right:"Right","left-profile":"Left","right-profile":"Right"},lse=["Front","Left","Right","Back"];function cse(){var ne;const{presenterId:e=""}=Bs(),{presenters:t,presentersLoaded:n,presentersError:r,refetchPresenters:a,applyBrand:i,refreshBrands:l,presenterCategories:u}=Rn(),{brand:f}=on(),h=Dn(),p=ym(),g=s.useRef(!1),v=Wv(),[w,y]=s.useState([]),[x,k]=s.useState(null),[S,E]=s.useState(null),j=LG(f,e),N=j??t.find(q=>q.id===e);Sc(N==null?void 0:N.name);const P=!!j;s.useEffect(()=>{let q=!0;if(y([]),!P)return Re.presenterFrames(e).then(le=>{q&&y(le.frames)}).catch(()=>{q&&y([])}),()=>{q=!1}},[e,P]);const $=!!un({path:ct.presenterEdit});s.useEffect(()=>{let q=!0;if(E(null),!(!P||$))return Re.presenterDrafts(f.id).then(le=>{if(!q)return;const Se=le.drafts.find(Q=>Q.presenterId===e);E((Se==null?void 0:Se.id)??null)}).catch(()=>{}),()=>{q=!1}},[f.id,e,P,$]);const M=((ne=f.json)==null?void 0:ne.characters)??[],C=M.find(q=>q.presenterId===e),R=M.find(q=>q.id===e),T=lw(f.id,[e??"",(C==null?void 0:C.id)??""]),[H,D]=s.useState(null),[K,O]=s.useState(!1),[Z,te]=s.useState(!1),B=async q=>{if(j){O(!0),D(null);try{const le=await Re.updatePresenter(f.id,j.id,q);i(le.brand),te(!1)}catch(le){D(String(le.message??le))}finally{O(!1)}}},F=async()=>{if(!j||g.current)return;g.current=!0;const q=p(),le=qi(f);O(!0);try{const Se=await Re.deletePresenter(f.id,j.id);i(Se.brand)}catch(Se){if((Se==null?void 0:Se.status)!==404){g.current=!1,q()&&(D(String(Se.message??Se)),O(!1));return}await l()}q()&&h(le,{replace:!0})},X=kv(f,e);if(X!==e)return o.jsx(uo,{to:ha(f,X),replace:!0});if(!n&&!j)return o.jsx(is,{children:o.jsx("main",{className:"sc-lookpage",id:"main",children:o.jsx("div",{className:"sc-tplrow","aria-hidden":!0})})});if(r&&!j)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage",id:"main",children:[o.jsx("h1",{children:"Couldn't load this presenter"}),o.jsx("p",{className:"sc-lookpage-lede",children:"Something went wrong reaching the catalog."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>a(),children:"Retry"})})]})});if(!N)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage",id:"main",children:[o.jsx("h1",{children:"This presenter isn't here anymore"}),o.jsx("p",{className:"sc-lookpage-lede",children:"They may have been removed from the catalog, or the link is out of date."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx(_n,{className:"sc-btn sc-btn-primary",to:qi(f),children:"Browse presenters"})})]})});const z=j?(Array.isArray(R==null?void 0:R.shots)?R.shots:[]).map((q,le)=>({src:Fr(q==null?void 0:q.file),label:ise[(q==null?void 0:q.angle)??""]??`Reference ${le+1}`,angle:typeof(q==null?void 0:q.angle)=="string"?q.angle:void 0})).filter(q=>!!q.src):w.length?w.map((q,le)=>({src:q,label:lse[le]??`Reference ${le+1}`})):N.previewUrl?[{src:N.previewUrl,label:"Preview"}]:[],I=Up(f,e),U=ti(j??N),G=[...new Set([...u,...Sf(f).flatMap(q=>q.suitableCategories??[])])].sort((q,le)=>q.localeCompare(le));return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-presenterpage",id:"main",children:[U.src&&o.jsx("div",{className:"sc-presenterpage-avatar",children:o.jsx(c8,{src:sr(U.src,"small"),crop:U.crop})}),o.jsx("h1",{children:N.name}),N.suitableCategories.length>0&&o.jsx("ul",{className:"sc-lookpage-cats","aria-label":"Filed under",children:N.suitableCategories.map(q=>o.jsx("li",{className:"sc-chip","data-static":!0,children:q},q))}),N.descriptor&&o.jsx("p",{className:"sc-lookpage-lede",children:N.descriptor}),o.jsxs("div",{className:"sc-lookpage-acts",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>v(e),children:"Use in a shot"}),j&&o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:I,children:S?"Continue editing":"Edit presenter"}),j&&o.jsx(lr,{label:"Edit name and details",children:o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":"Edit name and details","aria-haspopup":"dialog",onClick:()=>te(!0),children:o.jsx(Ju,{size:17})})})]}),H&&o.jsx("p",{className:"sc-assetform-err",children:H}),z.length>0?o.jsx(dw,{count:z.length,label:"Reference set",className:"sc-refset-rail",trackClassName:"sc-refset",children:z.map(q=>o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","data-role":q.angle,"aria-label":`${q.label}, open`,onClick:()=>k(q),children:o.jsx(c8,{src:sr(q.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:q.label})]},q.label))}):o.jsx(cw,{}),j&&j.sourceRefs.length>0&&o.jsxs("section",{className:"sc-presenterpage-sources",children:[o.jsx("p",{className:"sc-presenterpage-sources-lb",children:"From your photos"}),o.jsx("div",{className:"sc-presenterpage-sources-row",children:j.sourceRefs.map((q,le)=>o.jsx("button",{type:"button",className:"sc-presenterpage-source","aria-label":`Source photo ${le+1}, open`,onClick:()=>k({src:q,label:`Source photo ${le+1}`}),children:o.jsx(c8,{src:sr(q,"micro")})},q))})]}),j&&o.jsxs("div",{className:"sc-prec",children:[o.jsxs("p",{className:"sc-prec-note",children:[N.ageRange?`${N.ageRange} · `:"",j.source==="synthetic"?"Created in Scenri. Not a real person.":j.source==="photos"?"Built from your photographs.":"Saved in Scenri.",j.likeness?` Likeness confirmed ${new Date(j.likeness.attestedAt).toLocaleDateString()}.`:""]}),o.jsx(Wn,{label:"Delete presenter",title:`Delete ${j.name}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",busy:K,onConfirm:()=>void F()})]}),T.length>0&&o.jsx(Lu,{label:`Shots featuring ${N.name}`,children:T.map(q=>o.jsx(uw,{node:q,to:Wp(f,null,q.id)},q.id))}),Z&&j&&o.jsx(YM,{name:j.name,categories:N.suitableCategories,known:G,hint:"The verticals they suit, so they surface where you work.",busy:K,error:H,onSave:q=>void B({name:q.name,suitableCategories:q.categories}),onDismiss:()=>te(!1)}),x&&o.jsx(Uu,{src:x.src,kind:"presenter",label:x.label,noun:N.name,onClose:()=>k(null)})]})})}function c8({src:e,crop:t}){const[n,r]=s.useState(!1);return n?o.jsx("span",{className:"sc-lookpage-ref-blank","aria-hidden":!0,children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async",...t?{"data-crop":t}:{},onError:()=>r(!0)})}function use({placeholder:e,label:t,action:n="Send",scope:r,hint:a,value:i,onValue:l,allowEmpty:u,disabled:f,why:h,quiet:p,working:g,error:v,focusKey:w,onStop:y,stopping:x,onAttach:k,onAttachFiles:S,attachLabel:E,colour:j,refs:N,onSend:P}){const $=s.useRef(null),M=s.useRef(null),[C,R]=s.useState(void 0);s.useLayoutEffect(()=>{const I=$.current;if(!I)return;I.style.height="auto";const U=Number.parseFloat(getComputedStyle(I).maxHeight)||Number.POSITIVE_INFINITY;I.style.height=`${Math.min(I.scrollHeight,U)}px`,I.style.overflowY=I.scrollHeight>U?"auto":"hidden"},[i]);const[T,H]=s.useState(!1),D=wr(Ks);s.useEffect(()=>{if(!w||w===C||f||(R(w),D))return;const I=$.current;if(I==null||I.focus({preventScroll:!0}),I!=null&&I.value){I.select(),H(!0);const U=setTimeout(()=>H(!1),700);return()=>clearTimeout(U)}},[w,C,f,D]);const K=f||g,O=!!(j!=null&&j.hex)||!!(N!=null&&N.some(I=>!I.busy)),Z=!i.trim()&&!u&&!O,te=()=>{K||Z||P(i)},B=v?{text:v,tone:"alert"}:{text:(r==null?void 0:r.hint)??a??"",tone:r==null?void 0:r.tone},F=!!y&&(g||!i.trim()&&!O),X=g||F?null:f&&h?h:Z&&!f?"Nothing typed yet.":null,z=o.jsxs("button",{type:"button",className:"sc-convo-send","aria-disabled":(F?!!x:g||K||Z)||void 0,"aria-busy":g||F||void 0,"data-stop":F||void 0,onClick:F?x?void 0:y:g?void 0:te,children:[o.jsx("span",{className:"sc-convo-send-ico",children:g||F?o.jsx("span",{className:"sc-convo-spin","aria-hidden":"true"}):o.jsx(iC,{size:17,weight:"bold"})}),F?x?"Stopping":"Stop":g?"Working":n]});return o.jsxs("div",{className:"sc-convo-composer",children:[o.jsxs("div",{className:"sc-convo-card","data-quiet":p||void 0,"data-flash":T||void 0,children:[(r==null?void 0:r.chip)&&o.jsx("div",{className:"sc-convo-scope-row",children:o.jsxs("span",{className:"sc-convo-scope",children:[r.chip.thumb?o.jsx("img",{src:r.chip.thumb,alt:""}):null,r.chip.label]})}),o.jsxs("div",{className:"sc-convo-field",children:[N==null?void 0:N.map(I=>o.jsxs("span",{className:"sc-token","data-kind":"image","data-busy":I.busy||void 0,dir:"ltr",children:[o.jsx("img",{src:I.src,alt:""}),o.jsx("span",{className:"sc-token-label",children:I.label}),o.jsx("button",{type:"button",className:"sc-convo-chip-x","aria-label":`Remove ${I.label}`,onClick:I.onRemove,children:o.jsx(jn,{size:11,weight:"bold"})})]},I.key)),j&&o.jsxs("span",{className:"sc-token","data-kind":"color","data-empty":j.hex?void 0:"",dir:"ltr",children:[o.jsxs(Zu,{className:"sc-convo-chip",triggerStyle:{background:"none"},value:j.hex??j.seed??"#808080",commitMode:"live",align:"start",label:j.hex?`${j.label}. Change the colour.`:"Pick a colour",onChange:j.onPick,children:[o.jsx("span",{className:"sc-token-swatch",style:j.hex?{background:j.hex}:void 0}),o.jsx("span",{className:"sc-token-label",children:j.label})]}),j.hex&&o.jsx("button",{type:"button",className:"sc-convo-chip-x","aria-label":"Remove colour",onClick:j.onClear,children:o.jsx(jn,{size:11,weight:"bold"})})]}),o.jsx("textarea",{ref:$,className:"sc-in",rows:1,maxLength:400,"aria-label":t,placeholder:j!=null&&j.hex&&!i?"":f&&h?h:e,value:i,disabled:f,onChange:I=>l(I.target.value),onKeyDown:I=>{I.key!=="Enter"||I.shiftKey||(I.preventDefault(),te())}})]}),o.jsxs("div",{className:"sc-convo-row",children:[(k||S)&&o.jsxs(o.Fragment,{children:[o.jsx(lr,{label:K&&h?h:E??"Add photos",children:o.jsx("button",{type:"button",className:"sc-convo-attach","aria-label":E??"Add photos","aria-disabled":K||void 0,onClick:K?void 0:S?()=>{var I;return(I=M.current)==null?void 0:I.click()}:k,children:o.jsx(cr,{size:16,weight:"bold"})})}),S&&o.jsx("input",{ref:M,type:"file",accept:"image/*",hidden:!0,"aria-label":E??"Add a picture",onChange:I=>{const U=Array.from(I.target.files??[]).filter(G=>G.type.startsWith("image/"));I.target.value="",U.length&&S(U)}})]}),X?o.jsx(lr,{label:X,children:z}):z]})]}),B.text?o.jsx("small",{className:"sc-convo-line",role:B.tone==="alert"?"alert":void 0,"data-tone":B.tone,children:B.text}):null]})}function QM({glyph:e,lead:t,hint:n}){return o.jsxs("div",{className:"sc-pstudio-empty",children:[o.jsxs("span",{className:"sc-pstudio-empty-mark","aria-hidden":!0,children:[o.jsx("span",{className:"sc-pstudio-empty-ring","data-at":"far"}),o.jsx("span",{className:"sc-pstudio-empty-ring","data-at":"near"}),e]}),t&&o.jsxs("span",{className:"sc-pstudio-empty-say",children:[o.jsx("span",{children:t}),n&&o.jsx("span",{children:n})]})]})}const d5=500,JM=400,eR=760,nu=e=>Math.min(eR,Math.max(JM,Math.round(e)));function dse({title:e,headAction:t,stage:n,body:r,bodyProps:a,foot:i,overlay:l,kind:u,resizeLabel:f,onPaste:h,onDropFiles:p,onClose:g}){const v=s.useRef(null),[w,y]=s.useState(null);tw(w,"--sc-pstudio-dock-h"),s.useEffect(()=>{const j=N=>{N.key!=="Escape"||N.defaultPrevented||(N.preventDefault(),g())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[g]);const[x,k]=fa(Dr.pstudioRailW,d5),S=s.useRef(0),E=s.useRef(0);return Rr.createPortal(o.jsx(Gu,{trapped:!0,loop:!0,asChild:!0,onMountAutoFocus:j=>{var N;j.preventDefault(),(N=v.current)==null||N.focus({preventScroll:!0})},children:o.jsxs("div",{ref:v,tabIndex:-1,className:"sc-pstudio","data-kind":u,style:{"--sc-pstudio-rail-set":`${nu(x)}px`},role:"dialog","aria-modal":"true","aria-labelledby":"sc-pstudio-title",onDragOver:j=>{p&&Array.from(j.dataTransfer.types).includes("Files")&&j.preventDefault()},onDrop:j=>{var P;if(!p||j.defaultPrevented)return;const N=Array.from(((P=j.dataTransfer)==null?void 0:P.files)??[]);N.length&&(j.preventDefault(),p(N))},onPaste:j=>{var P;if(!h)return;const N=Array.from(((P=j.clipboardData)==null?void 0:P.files)??[]).filter($=>$.type.startsWith("image/"));N.length&&(j.preventDefault(),h(N))},children:[o.jsxs("div",{className:"sc-pstudio-grid",children:[o.jsx("div",{className:"sc-pstudio-resize",role:"separator","aria-orientation":"vertical","aria-label":f,"aria-valuemin":JM,"aria-valuemax":eR,"aria-valuenow":nu(x),tabIndex:0,onPointerDown:j=>{j.button===0&&(j.preventDefault(),j.stopPropagation(),j.currentTarget.setPointerCapture(j.pointerId))},onPointerMove:j=>{if(!j.currentTarget.hasPointerCapture(j.pointerId))return;const N=j.currentTarget.closest(".sc-pstudio");S.current=j.clientX,!E.current&&(E.current=requestAnimationFrame(()=>{E.current=0,N==null||N.style.setProperty("--sc-pstudio-rail-set",`${nu(window.innerWidth-S.current)}px`)}))},onPointerUp:j=>{j.currentTarget.releasePointerCapture(j.pointerId),E.current&&(cancelAnimationFrame(E.current),E.current=0),k(nu(window.innerWidth-j.clientX))},onDoubleClick:()=>k(d5),onKeyDown:j=>{if(j.key==="ArrowLeft")k(N=>nu(N+16));else if(j.key==="ArrowRight")k(N=>nu(N-16));else return;j.preventDefault()}}),o.jsx(lr,{label:"Close (esc)",children:o.jsx("button",{type:"button",className:"sc-pstudio-close",onClick:g,"aria-label":"Close",children:o.jsx(jn,{size:13})})}),o.jsxs("div",{className:"sc-pstudio-head sc-newdlg-head",children:[o.jsx("h2",{id:"sc-pstudio-title",className:"sc-newdlg-title",children:e}),t,o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close",onClick:g,"aria-label":"Close",children:o.jsx(jn,{size:16})})]}),o.jsxs("div",{className:"sc-pstudio-scroll",children:[n,o.jsx("div",{className:"sc-pstudio-body",...a,children:r})]}),o.jsx("div",{className:"sc-pstudio-foot sc-dock",ref:y,children:i})]}),l]})}),document.body)}function fse({hash:e,alt:t,drawing:n,since:r,items:a,onPick:i,compare:l,doing:u,takes:f,onTake:h,empty:p,glyph:g}){const v=hse(n),[w,y]=s.useState(null),x=f??[],k=Math.max(0,x.findIndex(R=>w?R.hash===w:R.current)),S=x[k];s.useEffect(()=>y(null),[e]);const E=pse(w&&x.some(R=>R.hash===w)?w:e),[j,N]=s.useState(void 0);s.useEffect(()=>N(void 0),[e]);const P=R=>{const T=x[k+R];T&&y(T.hash)},$=s.useRef(null),[M,C]=s.useState(!1);return s.useLayoutEffect(()=>{const R=$.current;C(!(R!=null&&R.complete&&R.naturalWidth))},[E]),o.jsxs("div",{className:"sc-pstudio-stage",children:[o.jsx("div",{className:"sc-pstudio-wrap",children:o.jsxs("div",{className:"sc-pstudio-well","data-drawing":n||void 0,"data-empty":!e||void 0,style:j?{"--sc-well-ar":j}:void 0,children:[e&&E?o.jsx("img",{ref:$,src:Mr(E),srcSet:`${dn(E,"tile")} 640w, ${Mr(E)} 1024w`,sizes:"(max-width: 767px) 92vw, 44vw",alt:t,decoding:"async","data-waiting":M||void 0,onLoad:R=>{const T=R.currentTarget;C(!1),T.naturalWidth&&T.naturalHeight&&N(T.naturalWidth/T.naturalHeight)}}):o.jsx("span",{className:"sc-pstudio-well-blank",children:!n&&o.jsx(QM,{glyph:g,lead:p==null?void 0:p.lead,hint:p==null?void 0:p.hint})}),n&&!e&&o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}),n&&e&&o.jsx("span",{className:"sc-pstudio-veil","aria-hidden":!0}),n&&o.jsxs("span",{className:"sc-pstudio-doing",role:"status",children:[o.jsx("span",{className:"sc-pstudio-ring","aria-hidden":!0}),o.jsx("span",{children:u??"Drawing"}),r&&o.jsx("time",{children:rc(r,v)})]}),x.length>1&&!n&&!(l!=null&&l.on)&&o.jsxs("div",{className:"sc-pstudio-vers",children:[o.jsx("button",{type:"button",className:"sc-pstudio-vers-step","aria-label":"The version before","aria-disabled":k===0||void 0,onClick:()=>k>0&&P(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsxs("span",{className:"sc-pstudio-vers-n","aria-live":"polite",children:["Version ",(S==null?void 0:S.n)??1," of ",x.length]}),o.jsx("button",{type:"button",className:"sc-pstudio-vers-step","aria-label":"The version after","aria-disabled":k===x.length-1||void 0,onClick:()=>k<x.length-1&&P(1),children:o.jsx(ol,{size:13,weight:"bold"})}),S&&!S.current&&h&&o.jsx("button",{type:"button",className:"sc-pstudio-vers-put",onClick:()=>h(S.hash),children:"Put back"}),(S==null?void 0:S.current)&&o.jsx("span",{className:"sc-pstudio-vers-on",children:"Active"})]}),l&&!n&&o.jsx("button",{type:"button",className:"sc-pstudio-compare","aria-pressed":l.on,onClick:l.toggle,children:l.on?"Showing current":"Compare"})]})}),a.length>0&&o.jsx("ol",{className:"sc-pstudio-strip","aria-label":"Views",children:a.map(R=>{const T=R.label+(R.approved?", used":R.state==="stale"?", to be drawn again":"")+(R.photo?", your photo":"")+(R.drawing?", drawing":"")+(R.error?", failed":"");return o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-pstudio-slot","data-state":R.state,"data-view":R.view,"aria-current":R.state==="current"?"step":void 0,"aria-label":T,disabled:!i,onClick:()=>i==null?void 0:i(R.view),children:o.jsxs("span",{className:"sc-pstudio-slot-inner",children:[R.hash?o.jsx("img",{src:dn(R.hash,"micro"),alt:""}):null,R.drawing&&!R.hash?o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}):null,R.drawing&&R.hash?o.jsx("span",{className:"sc-pstudio-slot-work sc-pstudio-ring","aria-hidden":!0}):null,R.approved&&!R.drawing?o.jsx("span",{className:"sc-pstudio-slot-mark","aria-hidden":!0,children:o.jsx(Kn,{size:11,weight:"bold"})}):null,R.error&&!R.drawing?o.jsx("span",{className:"sc-pstudio-slot-mark","data-tone":"alert","aria-hidden":!0,children:o.jsx(zp,{size:11,weight:"bold"})}):null]})}),o.jsx("span",{className:"sc-pstudio-slot-lb","data-on":R.state==="current"||void 0,"aria-hidden":!0,children:R.label})]},R.view)})})]})}function hse(e){const[t,n]=s.useState(()=>Date.now());return s.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}function pse(e){const[t,n]=s.useState(e);return s.useEffect(()=>{if(!e||e===t){e||n(void 0);return}let r=!0;const a=()=>{r&&n(e)},i=new Image;i.srcset=`${dn(e,"tile")} 640w, ${Mr(e)} 1024w`,i.sizes="(max-width: 767px) 92vw, 44vw",i.src=Mr(e),i.decode?i.decode().then(a,a):(i.onload=a,i.onerror=a);const l=window.setTimeout(a,3e3);return()=>{r=!1,window.clearTimeout(l)}},[e,t]),t}function fw({surface:e,onClose:t}){var p,g,v;const n=wr(Ks),r=e,a=(p=r.stage)==null?void 0:p.onPick,i=a?w=>a(w):void 0,l=r.turns[r.turns.length-1],u=(l==null?void 0:l.kind)==="question"&&l.question.kind==="confirm"&&!l.question.quiet?l.question:null;s.useEffect(()=>{if(!u||r.busy)return;let w=!1;const y=x=>{if(x.key!=="Enter"||x.shiftKey||x.defaultPrevented||w)return;const k=x.target;k&&(k.tagName==="INPUT"||k.tagName==="TEXTAREA"||k.tagName==="BUTTON"||k.isContentEditable)||(x.preventDefault(),w=!0,r.onAnswer(u.id,{kind:"confirm",id:u.options[0].id}))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[u,r.busy,r.onAnswer]);const f=r.glyph??o.jsx(nW,{size:32}),h=n?null:r.stage?o.jsx(fse,{hash:r.stage.hash,alt:r.stage.alt,drawing:r.stage.drawing,since:r.stage.since,doing:r.stage.doing,takes:r.stage.takes,onTake:r.stage.onTake,items:r.stage.items,onPick:r.stage.onPick,compare:r.stage.compare,empty:r.stageEmpty,glyph:f}):o.jsx("div",{className:"sc-pstudio-stage","data-reserve":!0,children:o.jsx("div",{className:"sc-pstudio-wrap",children:o.jsx("div",{className:"sc-pstudio-well","data-empty":!0,children:o.jsx("span",{className:"sc-pstudio-well-blank",children:o.jsx(QM,{glyph:f,lead:(g=r.stageEmpty)==null?void 0:g.lead,hint:(v=r.stageEmpty)==null?void 0:v.hint})})})})});return o.jsx(dse,{kind:r.kind??"presenter",title:r.title,headAction:r.headAction,resizeLabel:"Resize the conversation",onPaste:r.onPaste,onClose:t,overlay:r.overlay,stage:h,bodyProps:{"data-convo":!0},body:o.jsx(CJ,{turns:r.turns,busy:r.busy,working:r.working,memoryKey:r.memoryKey,resumed:r.resumed,onAnswer:r.onAnswer,onEdit:r.onEdit,onSaveEdit:r.onSaveEdit,onCancelEdit:r.onCancelEdit,onRestore:r.onRestore,onRetry:r.onRetry,onShow:i,onStarter:w=>(r.onStarter??r.onText)(w),onDescribe:r.onDescribe,onAttachFiles:r.onAttachRef}),foot:o.jsxs(o.Fragment,{children:[r.dock,r.composer&&o.jsx(use,{quiet:!!r.composer.disabled&&!r.composer.working,placeholder:r.composer.placeholder,label:r.composer.label,action:r.composer.action,scope:r.composer.scope,hint:r.composer.hint,value:r.text,onValue:r.onText,allowEmpty:r.composer.allowEmpty,disabled:r.composer.disabled,why:r.composer.why,working:r.composer.working,error:r.composer.error,focusKey:r.composer.focusKey,onAttach:r.composer.onAttach,onAttachFiles:r.composer.onAttachFiles,attachLabel:r.composer.attachLabel,colour:r.composer.colour,refs:r.composer.refs,onStop:r.composer.onStop,stopping:r.composer.stopping,onSend:r.onSend})]})})}const ld=[{id:"glasses",label:"Glasses",ask:"What glasses do they wear?",options:[{id:"thin black rectangular metal frames",label:"Thin black",card:"glasses-1"},{id:"round thin gold metal frames",label:"Round metal",card:"glasses-2"},{id:"clear transparent acetate frames",label:"Clear acetate",card:"glasses-3"},{id:"bold thick black rectangular acetate frames",label:"Bold rectangular",card:"glasses-4"},{id:"tortoiseshell acetate frames",label:"Tortoiseshell",card:"glasses-5"},{id:"rimless frames with thin temples",label:"Rimless",card:"glasses-6"}],saying:"Describe the glasses",refHint:"A clear front or three-quarter view of the frames."},{id:"freckles",label:"Freckles or marks",ask:"What marks their skin?",options:[{id:"light freckles across the nose and cheeks",label:"Light freckles",card:"freckles-1"},{id:"dense freckles across the whole face",label:"Dense freckles",card:"freckles-2"},{id:"freckles across the face and shoulders",label:"Face and shoulders",card:"freckles-3"},{id:"a small birthmark on one cheek",label:"Birthmark",card:"freckles-4"},{id:"a beauty mark above the lip",label:"Beauty mark",card:"freckles-5"}],saying:"Describe it",refHint:"A clear, close photograph of it."},{id:"makeup",label:"Makeup",ask:"What makeup do they wear?",options:[{id:"natural, barely-there makeup",label:"Natural",card:"makeup-1"},{id:"black winged eyeliner",label:"Winged liner",card:"makeup-2"},{id:"a soft smoky eye",label:"Smoky eye",card:"makeup-3"},{id:"a bold red lip",label:"Bold red lip",card:"makeup-4"},{id:"soft glamorous makeup with a warm shimmer",label:"Soft glam",card:"makeup-5"},{id:"strong defined brows and a nude lip",label:"Strong brows",card:"makeup-6"}],saying:"Describe the makeup",refHint:"A clear face photograph showing the look."},{id:"scar",label:"Scar",ask:"What scar do they have?",options:[{id:"a thin pale scar through one eyebrow",label:"Through an eyebrow",card:"scar-1"},{id:"a small pale scar on one cheek",label:"On a cheek",card:"scar-2"},{id:"a small scar on the chin",label:"On the chin",card:"scar-3"},{id:"a fine scar along the jaw",label:"Along the jaw",card:"scar-4"},{id:"a small scar beside one eye",label:"Beside an eye",card:"scar-5"},{id:"a faded scar across the bridge of the nose",label:"Across the nose",card:"scar-6"}],saying:"Describe the scar",refHint:"A clear, close photograph of it."},{id:"piercing",label:"Piercing",ask:"What piercing do they wear?",options:[{id:"a small silver nose stud",label:"Nose stud",card:"piercing-1"},{id:"a silver septum ring",label:"Septum ring",card:"piercing-2"},{id:"a small silver hoop through one eyebrow",label:"Eyebrow hoop",card:"piercing-3"},{id:"several small silver hoops in one ear",label:"Ear hoops",card:"piercing-4"},{id:"a small silver lip ring",label:"Lip ring",card:"piercing-5"},{id:"a row of small silver studs up one ear",label:"Ear studs",card:"piercing-6"}],saying:"Describe the piercing",refHint:"A clear photograph of the jewellery."},{id:"tattoo",label:"Tattoo",ask:"What is their tattoo?",options:[{id:"a fine-line botanical tattoo",label:"Fine line",card:"tattoo-1"},{id:"a small geometric line tattoo",label:"Geometric",card:"tattoo-2"},{id:"a floral tattoo in soft grey shading",label:"Floral",card:"tattoo-3"},{id:"a bold traditional red rose tattoo with heavy black linework",label:"Traditional",card:"tattoo-4"},{id:"a solid blackwork snake tattoo in heavy black ink",label:"Blackwork",card:"tattoo-5"},{id:"a small script tattoo in thin lettering",label:"Script",card:"tattoo-6"}],saying:"Describe the tattoo",refHint:"A clear photograph of the design itself.",where:{ask:"And where is it?",options:[{id:"on their right forearm",label:"Right forearm"},{id:"on their left forearm",label:"Left forearm"},{id:"on their right upper arm",label:"Right upper arm"},{id:"on their left upper arm",label:"Left upper arm"},{id:"on one shoulder",label:"Shoulder"},{id:"on the side of their neck",label:"Neck"},{id:"on their hand",label:"Hand"},{id:"on their back",label:"Back"}]}},{id:"prosthetic",label:"Prosthetic limb",ask:"What does their limb look like?",options:[{id:"a matte black mechanical prosthetic limb with dark articulated joints",label:"Matte black",card:"prosthetic-1"},{id:"a brushed steel mechanical prosthetic limb with dark articulated joints",label:"Brushed steel",card:"prosthetic-2"},{id:"a woven carbon fibre mechanical prosthetic limb with dark articulated joints",label:"Carbon fibre",card:"prosthetic-3"},{id:"a skin-tone mechanical prosthetic limb with dark articulated joints",label:"Skin tone",card:"prosthetic-4"},{id:"a glossy bright red mechanical prosthetic limb with dark articulated joints",label:"Red",card:"prosthetic-5"},{id:"a matte white mechanical prosthetic limb with dark articulated joints",label:"Matte white",card:"prosthetic-6"}],saying:"Describe it",refHint:"A clear photograph showing its shape and finish.",where:{ask:"And which limb?",options:[{id:"in place of their left arm",label:"Left arm"},{id:"in place of their right arm",label:"Right arm"},{id:"in place of their left leg",label:"Left leg"},{id:"in place of their right leg",label:"Right leg"},{id:"in place of their left hand",label:"Left hand"},{id:"in place of their right hand",label:"Right hand"}]}}],va=e=>ld.find(t=>t.id===e),mse=/\b(forearm|upper arm|arm|shoulder|neck|throat|hand|wrist|back|chest|ribs|thigh|leg|calf|ankle|foot|cheek|eyebrow|brow|chin|lip|nose|ear|temple|jaw|collarbone)\b/i;function tR(e){return mse.test(e??"")}function gse(e,t){var a,i,l;const n=((a=t.words)==null?void 0:a.trim())??"",r=((i=t.where)==null?void 0:i.trim())??"";return n?r&&!tR(n)?`${n} ${r}`:n:r?`${((l=va(e))==null?void 0:l.label.toLowerCase())??e} ${r}`:""}function f5(e,t){const n=(t??[]).filter(r=>/\b(left|right)\b/i.test(r.words)&&(e==="front"||!vse.has(r.id)));if(n.length)return`Check the side: ${n.map(r=>r.words).join("; ")}. Facing you, their right is on your left.`}const vse=new Set(["tattoo","prosthetic"]),bm=["who","age","heritage","skin","hair","length","facial","eyes","build","height"],ac="either",oc=e=>{var t,n;return[(e==null?void 0:e.pick)===ac?"":(t=e==null?void 0:e.pick)==null?void 0:t.trim(),(n=e==null?void 0:e.words)==null?void 0:n.trim()].filter(Boolean).join(", ")},nR=e=>{var t;return!!(e!=null&&e.pick||(t=e==null?void 0:e.words)!=null&&t.trim())},xm=e=>{var t;return((t=e.source)==null?void 0:t.door)==="scratch"},V6=e=>{var t;return xm(e)&&((t=e.source)==null?void 0:t.via)==="taps"},km=e=>{var t;return xm(e)&&((t=e.source)==null?void 0:t.via)!=="taps"},Sm=e=>{var t;return((t=e.source)==null?void 0:t.door)==="photos"},wse=/\b(slim|slender|athletic|average|fuller|curvy|broad|lean|muscular|petite|stocky|heavy|thin|plus.size)\b/i;function hw(e){const t=e.trim(),n=t.split(/\s+/).filter(Boolean).length,r=[];return $h.test(t)||r.push("who"),hv.test(t)||r.push("age"),r.length&&!wse.test(t)&&n<8&&r.push("build"),r}const yse=(e,t)=>bm.every(n=>!cR(`look-${n}`,e,t)||e[`look-${n}`]!==void 0),rR=e=>km(e)&&e.describe!==void 0&&hw(e.describe).length>0,bse=e=>km(e)&&e.describe!==void 0&&(!rR(e)||e.gaps!==void 0),xse=(e,t)=>{var n;return Sm(e)&&!!t.draft&&t.draft.source==="photos"&&t.canGenerate&&t.draft.stage!=="analyzing"&&(e.traits!==void 0||!((n=t.draft.keep)!=null&&n.trim()))},sR=(e,t)=>V6(e)?yse(e,t):km(e)?bse(e):xse(e,t),kse=(e,t)=>xm(e)||Sm(e)&&!!t.draft,aR=e=>t=>{var n;return!!((n=t.traits)!=null&&n.includes(e))},oR=e=>t=>nR(t[`trait-${e}`]),iR=e=>t=>{var n;return aR(e)(t)&&oR(e)(t)&&!!((n=va(e))!=null&&n.where)&&!tR(oc(t[`trait-${e}`]))},J1=(e,t)=>Array.isArray(e)&&e.includes(t),Sse=(e,t)=>{var n;return sR(e,t)&&(((n=e.traits)==null?void 0:n.every(r=>oR(r)(e)&&(!iR(r)(e)||e[`trait-${r}-where`]!==void 0)))??!1)},Ese=(e,t)=>JSON.stringify(e)!==JSON.stringify(t),Cse=(e,t)=>{var r;if(!Sm(e)||!t.draft||t.draft.stage==="analyzing"||t.draft.views.portrait.status!=="empty")return!1;const n=((r=t.draft.analysis)==null?void 0:r.photos)??[];return n.length>0&&n.every(a=>a.usable===!1)},Xo=[{id:"source",applies:()=>!0},{id:"photos",applies:Sm},{id:"weakphotos",applies:Cse},...bm.map(e=>({id:`look-${e}`,applies:e==="facial"?t=>{var n;return V6(t)&&((n=t["look-who"])==null?void 0:n.pick)!=="woman"}:V6})),{id:"describe",applies:km},{id:"gaps",applies:rR,dependsOn:[{on:"describe"}]},{id:"traits",applies:kse,ready:sR},...ld.flatMap(e=>[{id:`trait-${e.id}`,applies:aR(e.id),dependsOn:[{on:"traits",changed:(t,n)=>J1(t,e.id)!==J1(n,e.id)}]},{id:`trait-${e.id}-where`,applies:iR(e.id),dependsOn:[{on:`trait-${e.id}`,changed:(t,n)=>oc(t)!==oc(n)},{on:"traits",changed:(t,n)=>J1(t,e.id)!==J1(n,e.id)}]}]),{id:"keep",applies:xm,ready:Sse,optional:!0,sticky:!0}],lR=new Map(Xo.map(e=>[e.id,e])),jse=Xo.map(e=>e.id),F0=e=>{const t=Xo.findIndex(n=>n.id===e);return t<0?Xo.length:t},Ase=e=>lR.get(e);function cR(e,t,n){return Ase(e).applies(t,n)}function uR(e,t,n){if(e==="photos")return!!n.draft&&n.draft.source==="photos";const r=t[e];return r===void 0?!1:rr(e)||Mse(e)?nR(r):!0}function dR(e,t){return Xo.filter(n=>n.applies(e,t)&&uR(n.id,e,t)).map(n=>n.id)}function Em(e,t){var n;return((n=Xo.find(r=>{var a;return!r.optional&&r.applies(e,t)&&(((a=r.ready)==null?void 0:a.call(r,e,t))??!0)&&!uR(r.id,e,t)}))==null?void 0:n.id)??null}function h5(e,t,n){const r={...e},a=new Set,i=new Set(Object.keys(t));for(const[u,f]of Object.entries(t))Ese(e[u],f)&&(f===void 0?delete r[u]:r[u]=f,a.add(u));if(a.size){const u=Xo.map(g=>g.id),f=Math.min(...[...a].map(g=>u.indexOf(g))),h=new Set(a),p=g=>(g.dependsOn??[]).some(v=>h.has(v.on));for(const g of Xo)u.indexOf(g.id)<=f||i.has(g.id)||r[g.id]===void 0||g.sticky||p(g)||(delete r[g.id],a.add(g.id))}let l=!0;for(;l;){l=!1;for(const u of Xo){if(r[u.id]===void 0)continue;(!i.has(u.id)&&(u.dependsOn??[]).some(h=>a.has(h.on)&&(h.changed?h.changed(e[h.on],r[h.on]):!0))||!u.applies(r,n))&&(delete r[u.id],a.add(u.id),l=!0)}}return r}function Nse(e){const t={};for(const n of e.traits??[]){const r=e[`trait-${n}`];r&&(t[n]={words:oc(r)||void 0,where:oc(e[`trait-${n}-where`])||void 0,refs:r.refs.length?r.refs:void 0})}return t}function fR(e){const t={};for(const n of bm){const r=e[`look-${n}`];r!==void 0&&(t[n]=r)}return t}const hR=e=>ld.map(t=>t.id).filter(t=>e.includes(t)),rr=e=>e.startsWith("look-"),Mse=e=>e.startsWith("trait-"),_s=e=>lR.has(e);function Jr(e){if(!e.startsWith("trait-"))return null;const t=e.endsWith("-where"),n=t?e.slice(6,-6):e.slice(6);return va(n)?{id:n,part:t?"where":"what"}:null}const Rse=[{to:8,name:"red"},{to:16,name:"scarlet"},{to:30,name:"orange"},{to:36,name:"amber"},{to:46,name:"gold"},{to:64,name:"yellow"},{to:80,name:"lime"},{to:95,name:"yellow-green"},{to:158,name:"green"},{to:172,name:"sea green"},{to:183,name:"teal"},{to:196,name:"cyan"},{to:205,name:"sky blue"},{to:215,name:"azure"},{to:240,name:"blue"},{to:252,name:"indigo"},{to:268,name:"violet"},{to:285,name:"purple"},{to:300,name:"orchid"},{to:318,name:"magenta"},{to:330,name:"fuchsia"},{to:342,name:"pink"},{to:352,name:"rose"},{to:360,name:"red"}],Pse=[{to:.05,name:"black"},{to:.16,name:"charcoal"},{to:.32,name:"dark grey"},{to:.62,name:"grey"},{to:.76,name:"light grey"},{to:.88,name:"silver"},{to:.96,name:"off-white"},{to:1.01,name:"white"}],Lse=new Set(["black","charcoal","dark grey","grey","light grey","silver","off-white","white","dark brown","brown","chestnut","auburn","copper","tan","beige","cream","amber","gold","blonde"]),Tse=e=>{const t=String(e??"").replace("#","").trim();return(t.length===3?t.split("").map(r=>r+r):[t.slice(0,2),t.slice(2,4),t.slice(4,6)]).map(r=>{const a=Number.parseInt(r,16);return Number.isFinite(a)?a:0})};function $se(e){const[t,n,r]=Tse(e),a=t/255,i=n/255,l=r/255,u=Math.max(a,i,l),f=Math.min(a,i,l),h=(u+f)/2,p=u-f;if(p===0)return{h:0,s:0,l:h};const g=p/(1-Math.abs(2*h-1));return{h:((u===a?60*((i-l)/p%6):u===i?60*((l-a)/p+2):60*((a-i)/p+4))+360)%360,s:g,l:h}}const Dse=e=>{var t;return((t=Rse.find(n=>e<n.to))==null?void 0:t.name)??"red"};function Hse(e,t,n){return e==="orange"||e==="amber"||e==="scarlet"?n<.2?"dark brown":n<.32?e==="scarlet"?"chestnut":"brown":n>=.86&&t<.6?"cream":n>=.72&&t<.6?"beige":n<.44&&t<.7?"brown":n<.62&&t<.55?"tan":null:(e==="gold"||e==="yellow")&&n<.42?"olive":(e==="indigo"||e==="violet"||e==="purple")&&n>=.72&&t<.7?"lavender":(e==="blue"||e==="azure"||e==="indigo")&&n<.22?"navy":e==="red"&&n<.34?t<.55?"burgundy":"maroon":e==="rose"&&n<.34?"burgundy":null}function Ose(e){return e<.18?"deep":e<.34?"dark":e>=.88?"pale":e>=.74?"light":""}function pR(e){var u;const{h:t,s:n,l:r}=$se(e);if(n<.09){const f=((u=Pse.find(h=>r<h.to))==null?void 0:u.name)??"grey";return{name:f,family:f,h:t,s:n,l:r}}const a=Dse(t),i=Hse(a,n,r);if(i){const f=r<.12?"deep":r>=.93?"pale":"";return{name:f?`${f} ${i}`:i,family:i,h:t,s:n,l:r}}const l=Ose(r);return l?{name:`${l} ${a}`,family:a,h:t,s:n,l:r}:n<.22?{name:`muted ${a}`,family:a,h:t,s:n,l:r}:n>.85&&r>.4&&r<.65?{name:`vivid ${a}`,family:a,h:t,s:n,l:r}:{name:a,family:a,h:t,s:n,l:r}}function Ise(e){const{family:t,h:n,s:r,l:a}=pR(e);return Lse.has(t)?!0:n>=16&&n<=60&&a>=.7&&r<.7||r<.09}const pw=[{id:"black",label:"Black",color:"#15120f"},{id:"dark brown",label:"Dark brown",color:"#3b2418"},{id:"brown",label:"Brown",color:"#6b4630"},{id:"auburn",label:"Auburn",color:"#8c3b26"},{id:"ginger",label:"Ginger",color:"#c2622a"},{id:"blonde",label:"Blonde",color:"#d8ac63"},{id:"platinum blonde",label:"Platinum",color:"#e9e1d0"},{id:"grey",label:"Grey",color:"#9b9b99"},{id:"white",label:"White",color:"#f0efed"}],mR=[{id:"buzzed",label:"Buzzed",card:"length-1"},{id:"cropped",label:"Cropped",card:"length-2"},{id:"short",label:"Short",card:"length-3"},{id:"chin-length",label:"Chin",card:"length-4"},{id:"shoulder-length",label:"Shoulder",card:"length-5"},{id:"long",label:"Long",card:"length-6"}],mw=[{id:"porcelain",label:"Porcelain",color:"#f4e0d4"},{id:"fair",label:"Fair",color:"#edcdb6"},{id:"light olive",label:"Light olive",color:"#ddb894"},{id:"olive",label:"Olive",color:"#c2935f"},{id:"tan",label:"Tan",color:"#a9713f"},{id:"brown",label:"Brown",color:"#7c4f2c"},{id:"deep brown",label:"Deep brown",color:"#57351d"},{id:"deep",label:"Deep",color:"#3a2114"}],gR=[{id:"slight",label:"Slight",card:"build-1"},{id:"lean",label:"Lean",card:"build-2"},{id:"average",label:"Average",card:"build-3"},{id:"solid",label:"Solid",card:"build-4"},{id:"full",label:"Full",card:"build-5"}],Fse=[{id:"East Asian",label:"East Asian"},{id:"South Asian",label:"South Asian"},{id:"Southeast Asian",label:"Southeast Asian"},{id:"Middle Eastern",label:"Middle Eastern"},{id:"Mediterranean",label:"Mediterranean"},{id:"North African",label:"North African"},{id:"West African",label:"West African"},{id:"East African",label:"East African"},{id:"Northern European",label:"Northern European"},{id:"Eastern European",label:"Eastern European"},{id:"Latin American",label:"Latin American"},{id:"Caribbean",label:"Caribbean"},{id:"mixed heritage",label:"Mixed"}],gw=[{id:"dark brown",label:"Dark brown",color:"#3b2a1d"},{id:"brown",label:"Brown",color:"#6b4423"},{id:"hazel",label:"Hazel",color:"#8a7340"},{id:"amber",label:"Amber",color:"#b07d1a"},{id:"green",label:"Green",color:"#5b7a4b"},{id:"blue",label:"Blue",color:"#4a7ba7"},{id:"grey",label:"Grey",color:"#8b949c"}],vR=[{id:"clean-shaven",label:"Clean shaven",card:"facial-1"},{id:"light stubble",label:"Stubble",card:"facial-2"},{id:"a moustache",label:"Moustache",card:"facial-3"},{id:"a goatee",label:"Goatee",card:"facial-4"},{id:"a short beard",label:"Short beard",card:"facial-5"},{id:"a full beard",label:"Full beard",card:"facial-6"}],wR=[{id:"very short",label:"Very short",card:"height-1"},{id:"short",label:"Short",card:"height-2"},{id:"average height",label:"Average",card:"height-3"},{id:"tall",label:"Tall",card:"height-4"},{id:"very tall",label:"Very tall",card:"height-5"}],_se={},yR=[{id:"woman",label:"Woman"},{id:"man",label:"Man"},{id:"androgynous",label:"Androgynous"}],bR=["20s","30s","40s","50s","60+"].map(e=>({id:e,label:e})),Lf={who:{row:{id:"who",label:"Who",options:yR},prompt:"Who are they?"},age:{row:{id:"age",label:"Age",options:bR},prompt:"Roughly how old?"},heritage:{row:{id:"heritage",label:"Heritage",options:Fse},prompt:"Where are they from?"},skin:{row:{id:"skin",label:"Skin",options:mw},prompt:"And their skin?"},eyes:{row:{id:"eyes",label:"Eyes",options:gw},prompt:"What colour are their eyes?"},facial:{row:{id:"facial",label:"Facial hair",options:vR},prompt:"Any facial hair?"},hair:{row:{id:"hair",label:"Hair",options:pw},prompt:"What colour is their hair?"},length:{row:{id:"length",label:"Length",options:mR},prompt:"And the length?"},build:{row:{id:"build",label:"Build",options:gR},prompt:"And their build?"},height:{row:{id:"height",label:"Height",options:wR},prompt:"And how tall?"}};bm.map(e=>Lf[e]);const p5=new Set(["hair","skin","eyes"]),Zse={who:"Who they are, in your words",age:"Their age, in words or a number",heritage:"Where they are from, in your words",hair:"Their hair colour, in words or a swatch",length:"Their cut, in your words",facial:"Their facial hair, in your words",eyes:"Their eye colour, in words or a swatch",skin:"Their skin, in words or a swatch",build:"Their build, in your words",height:"How tall they are, in your words"},Vse=e=>e==="man"?"man":e==="woman"?"woman":"androgynous",zse=new Set(["length","height","build"]),Bse=900;function vw(e,t,n){const r=Use(e,t);if(r.far<Bse)return r.id;const a=pR(e).name;return n==="hair"&&!Ise(e)?`dyed ${a}`:a}function Use(e,t,n){const r=h=>{const p=h.replace("#","");return(p.length===3?p.split("").map(v=>v+v):[p.slice(0,2),p.slice(2,4),p.slice(4,6)]).map(v=>Number.parseInt(v,16)||0)},[a,i,l]=r(e);let u=t[0],f=Number.POSITIVE_INFINITY;for(const h of t){if(!h.color)continue;const[p,g,v]=r(h.color),w=(a-p)**2+(i-g)**2+(l-v)**2;w<f&&(f=w,u=h)}return{id:u.id,far:f}}const m5=e=>e==="skin"?mw:e==="eyes"?gw:pw,xh=e=>e.charAt(0).toUpperCase()+e.slice(1);function xR(e){const t=H=>H!=null&&H.pick&&H.pick!==ac?H.pick:"",n=(H,D,K)=>{var Z;const O=t(H);return O?O.startsWith("#")?vw(O,D,K):O:((Z=H==null?void 0:H.words)==null?void 0:Z.trim())??""},r=H=>{var D;return t(H)?((D=H==null?void 0:H.words)==null?void 0:D.trim())??"":""},a=(H,...D)=>[H,...D.filter(Boolean)].join(" "),i=(H,D,K)=>n(H,D,K).toLowerCase(),l={androgynous:"androgynous person",man:"man",woman:"woman"},u=i(e.who,[]),f=l[u]??u,p=[n(e.heritage,[]),f].filter(Boolean).join(" "),v=[p?/^(a|an|the)\s/i.test(p)?p:`${/^[aeiou]/i.test(p)?"an":"a"} ${p}`:"a person"],w=i(e.age,[]),y=w==="60+"?"in their 60s or older":/^\d{1,3}$/.test(w)?`aged ${w}`:`in their ${w}`;w&&v.push(a(y,r(e.age)));const x=[],k=i(e.length,mR),S=i(e.hair,pw,"hair"),E=[k,S].filter(Boolean).join(" ");E&&x.push(a(`${E} hair`,r(e.length),r(e.hair)));const j=i(e.facial,vR);j&&x.push(a(j,r(e.facial)));const N=i(e.eyes,gw);N&&x.push(a(`${N} eyes`,r(e.eyes)));const P=i(e.skin,mw,"skin");P&&x.push(a(`${P} skin`,r(e.skin)));const $=i(e.height,wR),M=i(e.build,gR),C=$?a(_se[$]??$,r(e.height)):"",R=M?a(`${/^[aeiou]/.test(M)?"an":"a"} ${M} build`,r(e.build)):"",T=[C,R&&(C?`with ${R}`:R)].filter(Boolean).join(" ");return T&&x.push(T),x.length&&v.push(`with ${x.join(", ")}`),a(v.join(" "),r(e.who))}function Wse(e,t){var i,l;const n=t.pick,r=n===ac?"Either way":n!=null&&n.startsWith("#")?xh(vw(n,e.options,e.id)):n?((i=e.options.find(u=>u.id===n))==null?void 0:i.label)??xh(n):"",a=((l=t.words)==null?void 0:l.trim())??"";return r?a?`${r}, ${a}`:r:xh(a)}function Kse(e){return xh(xR(e))}const _0=e=>typeof e=="string"&&e.startsWith("aside:"),Gse=e=>e.slice(6),np={answers:{},revision:0,editing:null,saying:null,says:0,text:"",colour:null,composing:null,asides:[],unsure:null,extrasDeclined:!1,uploading:0},Yse="That did not read as a description of someone.",kR=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qse(e){if(!e||e==="name")return null;if(e==="keep")return"keep";const t=Jr(e);return t&&t.part==="what"?`trait-${t.id}`:null}function g5(e,t){var r;const n=qse(t);return n?{id:n,refs:((r=e.answers[n])==null?void 0:r.refs)??[]}:null}function u8(e){const t=e.composing;if(!t)return e.answers;const n=e.answers[t.id];if(!n||kR(n.refs,t.refs))return e.answers;if(!oc(n)&&!t.refs.length){const r={...e.answers};return delete r[t.id],r}return{...e.answers,[t.id]:{...n,refs:t.refs}}}function Xse(e,t){var r;if(!rr(t)&&!Jr(t))return;const n=e.answers[t];if(n)return{saying:t,text:n.words??"",colour:(r=n.pick)!=null&&r.startsWith("#")?{step:t,hex:n.pick}:null}}function z6(e,t,n,r){return e.filter(a=>!a.q||!_s(a.q)?!0:!cR(a.q,t,n)||a.edit&&t[a.q]!==void 0?!1:r===void 0||F0(a.q)<=r)}function Qse(e){const t=Object.keys(e).filter(n=>_s(n));return t.length?Math.min(...t.map(F0)):void 0}function SR(e,t){if(!e.some(r=>r.at===t.at))return t;let n=1;for(;e.some(r=>r.at===`${t.at}#${n}`);)n+=1;return{...t,at:`${t.at}#${n}`}}function d8(e,t){const n=e.unsure;if(!n)return e;const r=Em(e.answers,t),a=u=>u&&(u===r||_s(u)&&e.answers[u]!==void 0)?u:null,i=e.asides.map(u=>u.q==="unsure"?{...u,q:a(n.q)}:u),l=SR(i,{said:n.said,reply:Yse,q:a(n.q),at:n.at});return{...e,unsure:null,asides:z6([...i,l],e.answers,t)}}function Jse(e,t){var n,r,a;switch(t.type){case"answer":{const i=h5(e.answers,t.patch,t.ctx),l=!kR(i,e.answers),u=d8(e,t.ctx);return{...u,answers:i,revision:l?e.revision+1:e.revision,asides:z6(u.asides,i,t.ctx,Qse(t.patch)),editing:null,saying:null,colour:null,composing:null,text:""}}case"edit":{const i=_0(t.id)||t.id==="name"?void 0:Xse(e,t.id);return{...e,answers:u8(e),composing:_0(t.id)?null:g5(e,t.id),editing:t.id,saying:(i==null?void 0:i.saying)??null,says:i?e.says+1:e.says,colour:(i==null?void 0:i.colour)??null,text:(i==null?void 0:i.text)??""}}case"amend-aside":{const i=e.asides.find(h=>h.at===t.at),l=i!=null&&i.q&&_s(i.q)?i.q:null,u=l&&e.answers[l]!==void 0?h5(e.answers,{[l]:void 0},t.ctx):e.answers,f=z6(e.asides.filter(h=>h.at<=t.at),u,t.ctx,l?F0(l):void 0);return{...e,answers:u,revision:u===e.answers?e.revision:e.revision+1,editing:null,asides:f.map(h=>h.at===t.at?{...h,said:t.said,reply:t.reply,kind:t.kind,rev:(h.rev??0)+1}:h)}}case"drop-aside":return{...e,editing:null,asides:e.asides.filter(i=>i.at<t.at)};case"cancel-edit":return{...e,answers:u8(e),composing:null,editing:null,saying:null,colour:null,text:""};case"say":{const i=e.saying===t.id?null:t.id;return{...e,answers:u8(e),composing:g5(e,i),saying:i,says:e.says+1,colour:null,text:""}}case"text":return e.text===t.text?e:{...e,text:t.text};case"colour":return t.hex?t.step&&t.step!=="keep"?{...e,colour:{step:t.step,hex:t.hex}}:e:{...e,colour:null};case"aside":{if(!t.aside.said.trim()||!t.aside.reply.trim())return{...e,text:""};const l=!!t.aside.q&&_s(t.aside.q)&&e.answers[t.aside.q]!==void 0?{...t.aside,after:!0}:t.aside;return{...e,asides:[...e.asides,SR(e.asides,l)],text:""}}case"unsure":return{...d8(e,t.ctx),unsure:t.unsure,text:""};case"settle-unsure":return d8(e,t.ctx);case"upload-begin":return{...e,uploading:e.uploading+1};case"upload-end":return{...e,uploading:Math.max(0,e.uploading-1)};case"uploaded":{if(((n=e.answers.source)==null?void 0:n.door)!=="photos")return e;const i=e.answers.photos??{hashes:[],attested:!1};return i.hashes.includes(t.hash)||i.hashes.length>=t.max?e:{...e,answers:{...e.answers,photos:{...i,hashes:[...i.hashes,t.hash]}},revision:e.revision+1}}case"remove-photo":{const i=e.answers.photos;if(!(i!=null&&i.hashes.includes(t.hash)))return e;const l=i.hashes.filter(u=>u!==t.hash);return{...e,answers:{...e.answers,photos:{hashes:l,attested:l.length?i.attested:!1}},revision:e.revision+1}}case"attest":{if(((r=e.answers.source)==null?void 0:r.door)!=="photos")return e;const i=e.answers.photos??{hashes:[],attested:!1};return i.attested===t.checked?e:{...e,answers:{...e.answers,photos:{...i,attested:t.checked}},revision:e.revision+1}}case"ref":{if(t.id!=="keep"){const u=t.id.slice(6);if(!((a=e.answers.traits)!=null&&a.includes(u)))return e}const i=e.answers[t.id]??{refs:[]},l=t.remove?i.refs.filter(u=>u!==t.hash):t.id==="keep"?[...i.refs.filter(u=>u!==t.hash),t.hash].slice(-4):[t.hash];return l.join()===i.refs.join()?e:{...e,answers:{...e.answers,[t.id]:{...i,refs:l}},revision:e.revision+1}}case"extras-declined":return{...e,extrasDeclined:!0};case"start-over":return{...np,revision:e.revision+1,text:t.text??""};case"restore":return{...np,answers:t.answers,revision:t.revision,asides:t.asides??[]}}}function B6(e,t){return Em(e.answers,t)===null&&!e.editing&&!e.saying}const ER=5,CR=40;function eae(e){return JSON.stringify({v:ER,answers:e.answers,revision:e.revision,asides:e.asides.slice(-CR)})}function tae(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.said!="string"||typeof t.reply!="string"||typeof t.at!="string"||!t.said.trim()||!t.reply.trim())return null;const n=typeof t.q=="string"?t.q:null,r=typeof t.rev=="number"&&t.rev>0?t.rev:void 0,a=typeof t.kind=="string"?t.kind:void 0,i=t.after===!0?!0:void 0,l=t.edit===!0?!0:void 0;return{said:t.said,reply:t.reply,q:n,at:t.at,...r?{rev:r}:{},...a?{kind:a}:{},...i?{after:i}:{},...l?{edit:l}:{}}}function nae(e){var r;if(rr(e))return Lf[e.slice(5)].row.options;const t=Jr(e),n=t&&va(t.id);return n?t.part==="where"?((r=n.where)==null?void 0:r.options)??[]:n.options:[]}function v5(e,t){return t===ac||/^#[0-9a-f]{6}$/i.test(t)?{pick:t}:nae(e).some(n=>n.id===t)?{pick:t}:{words:t}}function rae(e,t){if(e==="keep")return typeof t=="string"?{words:t,refs:[]}:t;if(typeof t=="string"&&(rr(e)||Jr(e)))return v5(e,t);const n=Jr(e);if((n==null?void 0:n.part)==="what"&&t&&typeof t=="object"){const r=t,a=Array.isArray(r.refs)?r.refs:[];return r.pick!==void 0||typeof r.words!="string"?{...r,refs:a}:{...v5(e,r.words),refs:a}}return t}function rp(e){if(!e)return null;try{const t=JSON.parse(e);if(t.v!==ER&&t.v!==4&&t.v!==3&&t.v!==2||!t.answers||typeof t.answers!="object")return null;const n={};for(const[a,i]of Object.entries(t.answers))_s(a)&&(n[a]=rae(a,i));const r=(Array.isArray(t.asides)?t.asides:[]).map(tae).filter(a=>a!==null).slice(-CR);return{answers:n,revision:typeof t.revision=="number"?t.revision:0,asides:r}}catch{return null}}const Pn={source:"Who are we making? Describe someone new, or add photos of a real person.",describe:"Describe them. Age, hair, build, skin and presence all help; one or two sentences is enough.",lookHint:"Skip anything you would rather leave to us.",photos:"Add one clear photo of their face. Up to three more angles hold the likeness better.",weakPhotos:"I cannot read a face in any of those photos, so anything I draw now would be a stranger rather than them.",name:"What should we call them?",nameWhileDrawing:"While it draws: what should we call them?",nameWhileReading:"While I read them: what should we call them?",traits:"Anything else that is always true of them?",traitsPhotos:"Anything in these photos that is always true of them?",keep:"Anything else about them?",agree:"Here is the presenter, in full. Ready to draw?",identity:e=>`Here is ${e==="them"?"the face":e}. Use this person, or change something.`,change:"What should change?",landed:e=>`Here is the ${e}. Use it, or try again.`,extras:"Add back and profile views? They help shots from behind or in profile."},jR=e=>e==="photos"?"the photos":"the face",AR=[{id:"photos",label:"Add photos"},{id:"scratch",label:"Describe someone"}],sae={photos:/\b(photos?|pictures?|pics?|upload|images?|selfies?)\b/,scratch:/\b(scratch|describe|description|invent|make (someone|one|them) up|imagine|new person)\b/},aae=[{label:"Late 30s, warm",text:"A woman in her late 30s, Mediterranean, olive skin, dark shoulder-length hair, slim build, warm and composed."},{label:"Early 20s, bright",text:"A man in his early 20s, fair skin with freckles, short blond hair, athletic build, bright and easygoing."},{label:"Mid 40s, quiet",text:"A man in his mid 40s, East Asian, close-cropped black hair, lean build, quietly confident."},{label:"Late 20s, easy",text:"A woman in her late 20s, deep brown skin, natural curls, tall and graceful, with an easy laugh."},{label:"Sixties, calm",text:"A woman in her early sixties, light skin, silver hair in a soft bob, broad build, calm and assured."}],oae="I have permission to use this person's likeness.";function iae(e){const t=[];return e.over>0&&t.push(e.over===1?`That is one more than ${e.max} photos, so the last one was not added.`:`That is ${e.over} more than ${e.max} photos, so the last ${e.over} were not added.`),e.same>0&&t.push(e.same===1?"One of those is already here.":`${e.same} of those are already here.`),e.failed.length&&t.push(e.failed.join(" ")),t.length?t.join(" "):null}const lae=(e,t)=>`${e} is larger than ${Math.round(t/1024/1024)}MB. Choose a smaller copy of it.`,cae=e=>`${e} could not be read as a photograph. JPEG, PNG, WebP and HEIC all work.`,uae="First portrait appears here",dae=(e,t)=>!e||e==="portrait"||!t?uae:`The ${t} appears here`;function fae(e){return e==="agree"?"Ready when you are":e==="photos"?"Add their photos":"Keep describing your presenter"}const NR=e=>e===1?"One thing I cannot tell yet.":e===2?"Two things I cannot tell yet.":"A few things I cannot tell yet.";function hae(e){return e===1?"One photo":`${e} photos`}function pae(e,t){return e===0?"The same person, face clear. Add the clearest one first.":e===1?"One photo works. Two to four, from different angles, hold the likeness better.":e<t?`${e} photos. More angles hold the likeness better.`:"Four angles. The reference set comes from these, the first one leading."}const mae="That does not read as a description yet. Draw from it anyway, or describe them: age, hair, build, skin, presence.",gae=e=>e===0?void 0:e===1?"Changing this asks the one after it again.":`Changing this asks the ${e} after it again.`,vae="Change this answer?",wae="The face is drawn again from the change, and the views built on it follow. Nothing already saved changes.",yae="The views drawn from the photos are drawn again with the change. The photos themselves stay as they are.",bae={source:"describe them in a sentence, or pick one",describe:"a few words about them is enough: age, hair, build, skin, presence",look:"tap one, or say it in your own words",name:"a name, so the rest of the conversation can use it",refine:"say what should change: hair, age or build change the person; anything else changes the view on the stage",detail:"tap one, or say what it looks like"},xae={who:{thing:"a person",how:"tap who they are"},age:{thing:"an age",how:"tap an age, or type one: Scenri draws adults"},hair:{thing:"a hair colour",how:"tap a colour, or say it: dark auburn, salt and pepper"},length:{thing:"a length",how:"tap a length, or say it: a chin-length bob"},skin:{thing:"a skin tone",how:"tap a tone, or say it: warm olive"},build:{thing:"a build",how:"tap a build, or say it: lean and tall"}},ss=e=>e.charAt(0).toUpperCase()+e.slice(1);function Pl(e,t,n,r="",a,i=!1){const l=t==="look"?xae[a??""]??null:null,u=(l==null?void 0:l.how)??bae[t],f=i?"":` ${ss(u)}.`;if(n>=2&&e!=="likeness"){const h=t==="look"||t==="detail"?"Or Skip it and we will choose.":"";return i?h||`${ss(u)}.`:`${ss(u)}.${h?` ${h}`:""}`}switch(e){case"likeness":return"Describe them by looks. Scenri does not draw a named person.";case"help":return l?`${ss(u)}.`:t==="refine"?"Select a view and say what is wrong with it, or say what should change about them: hair, age, build, skin.":t==="name"?"Any name will do; it can be changed later.":t==="detail"?`${ss(u)}.`:"Describe the person in a sentence: age, hair, build, skin, presence. Or add photos of a real person.";case"question":return l?`This step asks for ${l.thing}: ${u}.`:t==="refine"?`This is where the picture is changed: ${u}.`:t==="name"?`This is where they get a name: ${u}.`:t==="detail"?`This asks what the detail looks like: ${u}.`:`This is where the person is described: ${u}.`;case"nav":return"To begin again, use Start over at the top. Close keeps the draft where it is.";case"go":return t==="refine"?"Try again redraws it as it is; a sentence says what should change.":`Nothing to draw yet. ${ss(u)}.`;case"intent":return l?`${ss(u)}.`:t==="refine"?`Nothing changes until it is said what: ${u}.`:`That is what we are here for. Who are they? ${ss(u)}.`;case"nonsense":return l?`That is not ${l.thing}.${f}`:t==="name"?`That is not a name. ${ss(u)}.`:t==="refine"?`That does not say what should change. ${ss(u)}.`:t==="detail"?`That does not say what it looks like. ${ss(u)}.`:`That does not describe anyone. ${ss(u)}.`;case"greeting":return n?`Still here.${f}`:/^(hi|hello|hey|heya|hiya|yo|hola|shalom|good)\b/i.test(r.trim())?`Hi.${f}`:`${ss(u)}.`;case"ack":return n?`Still here.${f}`:i?"Go ahead.":`Go ahead: ${u}.`;case"vague":return n?`Still here. ${ss(u)}.`:`${ss(u)}.`}}const Z0=e=>e.trim().replace(/[.\s]+$/,"");function w5(e,t){const n=e==="portrait"?"face":bn[e];return t==="cancelled"?{id:"retry",kind:"confirm",quiet:!0,prompt:`Stopped drawing the ${n}. Nothing finished was touched.`,options:[{id:"retry",label:"Draw it again"}]}:{id:"retry",kind:"confirm",tone:"alert",prompt:`The ${n} could not be drawn: ${Z0(t)}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}}function kae(e){var r;const t=(((r=e.analysis)==null?void 0:r.suitableCategories)??[]).filter(Boolean);return t.length?` Filed under ${t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}; that can change on their page.`:""}function Sae(e){if(!e)return"";const t=[...e.asks??[],...e.results??[],...e.decisions??[]].map(n=>n.at);return t.length?t.reduce((n,r)=>r>n?r:n):""}const Eae=e=>e.charAt(0).toUpperCase()+e.slice(1);function Cae({draft:e,canGenerate:t,ui:n,afterCoverage:r,asides:a,openId:i,placed:l}){var Se;const u=[],f=(Q,xe,ee)=>u.push({kind:"scenri",id:Q,text:xe,tone:ee}),h=Q=>u.push({kind:"question",question:Q}),p=((Se=e.name)==null?void 0:Se.trim())??"",g=p||"them",v=()=>{p&&(u.push({kind:"scenri",id:"asked-name",text:Pn.name,quiet:!0}),u.push({kind:"you",id:"name",text:p,editable:!0,editing:n.editingName||void 0}))},w=Q=>h({id:"name",kind:"text",prompt:Q});if(e.stage==="analyzing")return f("reading",`Reading ${jR(e.source)}.`),p?v():w(Pn.nameWhileReading),u;const y=RK(e,t);if(y&&f("coverage",y.text,y.tone),u.push(...r),!t&&e.source==="photos")return p&&v(),p?(h({id:"blind",kind:"confirm",prompt:"No engine here can draw the other views. Save them from the photos as they are?",options:[{id:"save",label:"Save with photos"},{id:"setup",label:"Set up"}]}),u):(w(Pn.name),u);const x=e.views.portrait,k=e.activeView,S=e.asks??[],E=S[S.length-1],j=E?e.views[E.view]:null,N=!!E&&!!j&&(j.status==="generating"&&e.activeView===E.view||j.status==="candidate"&&j.adjustment===E.text||!!j.error),P=Q=>Q==="portrait"&&!Ko(e)?Pn.identity(g):Pn.change,$=(e.results??[]).filter(Q=>Q.how!=="restored"),M=e.decisions??[],C=!e.activeView&&e.stage==="idle",R=new Map,T=new Map,H=new Map;for(const Q of $){const xe=`${Q.view}:${Q.hash}`;if(H.set(xe,Q),R.has(xe))continue;const ee=(T.get(Q.view)??0)+1;T.set(Q.view,ee),R.set(xe,ee)}const D=Q=>R.get(`${Q.view}:${Q.hash}`)??1,K=(Q,xe)=>{const ee=D(Q),ae=e.views[Q.view].hash===Q.hash,re=(T.get(Q.view)??0)>1;return{kind:"scenri",id:xe,text:`Here is ${bn[Q.view]} ${ee}.`,thumb:Q.hash,view:Q.view,label:`${Jl[Q.view]} ${ee}`,current:re&&ae&&H.get(`${Q.view}:${Q.hash}`)===Q,restore:C&&!ae&&!pv(e,Q.view)?{view:Q.view,hash:Q.hash}:void 0}},O=new Set,Z=new Map(S.map(Q=>{const xe=$.find(ee=>!O.has(ee)&&ee.how==="drawn"&&ee.view===Q.view&&ee.ask===Q.text&&ee.at>=Q.at);return xe&&O.add(xe),[Q,xe]})),te=new Map;for(const Q of M)Q.what==="use"&&!te.has(Q.view)&&te.set(Q.view,Q);const B=Q=>Q==="portrait"?`Here is ${g} with the change. Use this, or keep the previous one. Using it redraws the views built on the face.`:`Redrew the ${bn[Q]}. Use it, or keep the previous one.`,F=Q=>{const xe=Q===te.get(Q.view),ee=Q.view==="portrait"&&xe,ae=Q.what==="again"?"Try again":Q.what==="keep"?"Keep previous":ee?"Use this person":Q.view==="portrait"?"Use this":"Use it";return[{kind:"scenri",id:`asked-decided-${Q.at}`,text:ee?Pn.identity(g):xe?Pn.landed(bn[Q.view]):B(Q.view),quiet:!0},{kind:"you",id:`decided-${Q.at}`,text:ae,editable:!1}]},X=()=>{const Q=N?S.slice(0,-1):S,xe=Sae(e),ee=a.filter(_=>!l.has(_)&&(_.q!==i||_.at<=xe));for(const _ of ee)l.add(_);const ae=$.find(_=>fK.includes(_.view)),re=[...Q.map(_=>{const ue=Z.get(_);return{at:_.at,turns:[{kind:"scenri",id:`asked-ask-${_.at}`,text:P(_.view),quiet:!0},{kind:"you",id:`ask-${_.at}`,text:_.text,editable:!1},...ue?[K(ue,`redrew-${_.at}`)]:[]]}}),...$.filter(_=>!O.has(_)).map(_=>({at:_.at,turns:[K(_,`result-${_.at}`)]})),...M.map(_=>({at:_.at,turns:F(_)})),...ee.map(_=>({at:_.at,turns:ri(_)})),...Ko(e)&&(e.extras||n.extrasDeclined)?[{at:ae?ae.at.slice(0,-1):"~",turns:[{kind:"scenri",id:"asked-extras",text:Pn.extras,quiet:!0},{kind:"you",id:"extras",text:e.extras?"Add them":"Not now",editable:!1}]}]:[]];re.sort((_,ue)=>_.at<ue.at?-1:_.at>ue.at?1:0);for(const _ of re)u.push(..._.turns)},z=()=>{!N||!E||(u.push({kind:"scenri",id:`asked-ask-${E.at}`,text:P(E.view),quiet:!0}),u.push({kind:"you",id:`ask-${E.at}`,text:E.text,editable:!1}))};if(!Ko(e)){const Q=x.status==="generating"||k==="portrait"&&x.status!=="candidate";return Q&&!S.length?(f("drawing-face","Drawing their face."),p?v():w(Pn.nameWhileDrawing),u):(v(),X(),Q?(z(),f("drawing-face",N?"Adjusting the face. Everything else stays.":"Drawing their face."),p||w(Pn.nameWhileDrawing),u):n.failed?(h({id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${Z0(n.failed??"")}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}),u):x.error?(z(),h(w5("portrait",x.error)),u):(x.status==="candidate"&&(z(),h({id:"identity",kind:"confirm",prompt:N?"Adjusted. Use this person, or try again.":Pn.identity(g),hint:f5("portrait",e.keepItems),options:[{id:"use",label:"Use this person"},{id:"again",label:"Try again"},{id:"change",label:"Change something"}]})),u))}v(),X();const I=Object.keys(e.views),U=Wo(e),G=[...U].reverse().find(Q=>f6.has(Q)),ne=U.find(Q=>!f6.has(Q)),q=I.find(Q=>e.views[Q].status==="candidate"),le=I.find(Q=>!!e.views[Q].error);if(n.failed&&!k)return h({id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${Z0(n.failed??"")}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}),u;if(k)return z(),f(`drawing-${k}`,N&&(E==null?void 0:E.view)===k?`Redrawing the ${bn[k]}.`:k===G&&!e.views[k].hash?`Drawing the ${bn[k]} from this face.`:k===ne&&!e.views[k].hash&&G?`Building the rest of the set from the ${bn[G]}.`:`Drawing the ${bn[k]}.`),p||w(Pn.nameWhileDrawing),u;if(q){z();const Q=e.views[q],xe=!!Q.prior,ee=re=>re?R.get(`${q}:${re}`)??0:0,ae=!!Q.hash&&!!Q.prior&&ee(Q.hash)<ee(Q.prior);return Q.hash&&u.push({kind:"scenri",id:`candidate-${q}-${Q.hash}`,text:ae?`Here is ${bn[q]} ${ee(Q.hash)} again.`:xe?q==="portrait"?`Here is ${g} with the change.`:`Redrew the ${bn[q]}.`:`Here is the ${bn[q]}.`,thumb:Q.hash,label:Jl[q],view:q,current:!0}),h({id:q==="portrait"?"revision":"view-revision",kind:"confirm",prompt:xe?q==="portrait"?`Use this, or keep the previous one.${PK(e,q)?" Using it redraws the views built on the face.":""}`:"Use it, or keep the previous one.":"Use it, or try again.",hint:q==="portrait"||q==="front"?f5(q,e.keepItems):void 0,options:[{id:"use",label:q==="portrait"?"Use this":"Use it"},...xe?[{id:"keep",label:"Keep previous"}]:[],{id:"again",label:"Try again"}]}),u}return le?(z(),h(w5(le,e.views[le].error??"")),u):hK(e)?!e.extras&&!n.extrasDeclined?(f("set-ready","The set is ready. Select a view and say what is wrong to redraw it."),h({id:"extras",kind:"confirm",prompt:Pn.extras,options:[{id:"add",label:"Add them"},{id:"save",label:"Not now"}]}),u):p?(h({id:"save",kind:"confirm",prompt:`${Eae(g)} is ready.${kae(e)}`,options:[{id:"save",label:"Save presenter"}]}),u):(w(Pn.name),u):(p||w(Pn.nameWhileDrawing),u)}const jae={who:{label:"Who",options:yR},age:{label:"Age",options:bR},build:{label:"Build",options:["slender","average","athletic","fuller"].map(e=>({id:e,label:e.charAt(0).toUpperCase()+e.slice(1)}))}},sp=e=>e.charAt(0).toUpperCase()+e.slice(1);function Aae(e){return!e||e==="skipped"?"Draw as is":Object.values(e).map(t=>sp(t)).join(", ")}function Nae(e){const t=e.map(n=>{var r;return((r=va(n))==null?void 0:r.label)??n});return t.length?t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`:"Nothing distinctive"}const Mae=e=>ZQ(e,AR,sae);function Cm(e){var a;if(((a=e.source)==null?void 0:a.via)==="taps"){const i=fR(e),l=oc(i.who);return xR(l&&!ra(l)?{...i,who:void 0}:i)}const t=(e.describe??"").trim(),n=e.gaps&&e.gaps!=="skipped"?e.gaps:{},r=n.build?`${t.replace(/[.\s]+$/,"")}, ${n.build} build`:t;return jK({steer:n.who??null,age:n.age??null},r)}function Rae(e){return jm(e).map(t=>t.words)}const Pae=200,Lae=12;function jm(e){var i,l;const t=Nse(e),n=(u,f,h)=>({id:u,words:f.slice(0,Pae),...h!=null&&h.length?{refs:h.slice(0,4)}:{}}),r=[];for(const u of hR(e.traits??[])){const f=t[u],h=f?gse(u,f):"";h&&r.push(n(u,h,f==null?void 0:f.refs))}const a=(((i=e.keep)==null?void 0:i.words)??"").trim();return a&&r.push(n("said",a,(l=e.keep)==null?void 0:l.refs)),r.slice(0,Lae)}function y5(e){const t=Rae(e);return t.length<2?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Tae(e){const t=e.trim().replace(/[.\s]+$/,""),n=t.replace(/^(?:but|and|also|plus|though|although|however)\b[\s,]*/i,"");return n.replace(/^(?:he|she|they|it)\s+(?:has|have|had|has got|have got|is|are|wears?|carries)\s+/i,"")||n||t}function $ae(e,t,n,r){const a=r.toLowerCase().split(/[^a-z0-9]+/).filter(l=>l.length>2);if(!a.length)return!0;const i=Cm({...e,[t]:n}).toLowerCase();return a.every(l=>i.includes(l))}function Dae(e){const t=rp(e.setup??null);return t&&Object.keys(t.answers).length?{answers:t.answers,asides:t.asides}:{answers:Hae(e),asides:[]}}function Hae(e){const t=rp(e.setup??null);return t&&Object.keys(t.answers).length?t.answers:e.source==="photos"?{source:{door:"photos",via:"taps"},photos:{hashes:e.sources??[],attested:!0},...b5(e)}:{source:{door:"scratch",via:"typed"},describe:e.direction??"",gaps:"skipped",traits:[],...b5(e)}}function b5(e){const t=e.keepItems??[];if(!t.length)return{};const n={},r=[];let a;for(const i of t){const l=ld.find(u=>u.id===i.id);if(l){r.push(l.id),n[`trait-${l.id}`]={words:i.words,refs:i.refs??[]};continue}a={words:[a==null?void 0:a.words,i.words].filter(Boolean).join(", "),refs:[...(a==null?void 0:a.refs)??[],...i.refs??[]]}}return n.traits=r,a&&(n.keep=a),n}const MR=(e,t)=>({draft:e?{source:e.source,stage:e.stage,keep:e.keep,views:{portrait:{status:e.views.portrait.status}},analysis:e.analysis?{photos:e.analysis.photos}:void 0}:null,canGenerate:t});function Oae(e,t,n){var a,i;if(e==="source")return t.kind==="choice"?{source:{door:t.id,via:"taps"}}:null;if(rr(e)){const l=(a=n[e])==null?void 0:a.words,u=l?{words:l}:{};return t.kind==="swatches"?{[e]:{pick:t.picks[e.slice(5)]??Object.values(t.picks)[0],...u}}:t.kind==="skip"?{[e]:{pick:ac,...u}}:null}if(e==="gaps")return t.kind==="choices"?{gaps:t.picks}:t.kind==="skip"?{gaps:"skipped"}:null;if(e==="traits")return t.kind==="choices"?{traits:ld.map(l=>l.id).filter(l=>t.picks[l])}:t.kind==="skip"?{traits:[]}:null;const r=Jr(e);if(r&&t.kind==="choice"){if(r.part==="where"){const u=(i=n[e])==null?void 0:i.words;return{[e]:{pick:t.id,...u?{words:u}:{}}}}const l=n[`trait-${r.id}`];return{[e]:{pick:t.id,...l!=null&&l.words?{words:l.words}:{},refs:(l==null?void 0:l.refs)??[]}}}return null}function Iae(e,t){var r;return`the ${((r=va(e))==null?void 0:r.label.toLowerCase())??"detail"} in the attached ${t===1?"picture":"pictures"}`}const x5="A scar, a ring, anything we missed",Fae=new Set(["describe","keep"]),_ae=new Set(["likeness","help","question","greeting","ack","nav","intent","go","nonsense"]);function k5(e,t){const n=(t==null?void 0:t.trim())??"";return e?n?`${e}, ${n}`:e:sp(n)}const Zae=/^(?:but|and|though|although|only|just|except(?: that)?|with|without|plus)\s+/i,S5=e=>Zae.test(e.trim());function f8(e){return e.trim().replace(/[.\s]+$/,"").replace(/^(?:but|and|though|although|only|just|except(?: that)?)\s+/i,"").trim()}function V0(e,t){if(!e)return!1;if(Fae.has(e))return!0;if(!rr(e)&&!Jr(e))return!1;const n=t[e];return!!n&&!n.pick&&!!n.words}function eh(e,t,n){const r=t.trim();return r?e==="look-age"&&bK(r)?null:e!=="look-who"&&(rr(e)||e.startsWith("trait-"))&&vK(r)?"nonsense":rr(e)||e.startsWith("trait-")||e==="keep"?zae(r,n):e==="describe"||e==="source"?Vo(r,n):null:"vague"}function h8(e,t,n){if(e&&rr(e))return"look";if(e==="keep"||e!=null&&e.startsWith("trait-"))return"detail";const r=e??t;if(r&&rr(r))return"look";if(r!=null&&r.startsWith("trait-"))return"detail";switch(r){case"source":return"source";case"describe":case"gaps":return"describe";case"name":return"name";case"traits":return"detail";default:return n?"refine":"describe"}}const E5=new Set(["who","age","hair","colour","color","length","cut","skin","build","body","name","look","style","face","person","presenter","glasses","scar","scars","tattoo","piercing","makeup","freckles","prosthetic"]),Vae=/^[a-z]{1,10}\d+$/i,zae=(e,t)=>{const n=e.trim(),r=n.toLowerCase().replace(/[^a-z ]/g,"");if(E5.has(r)||E5.has(r.replace(/^(the|their|its|his|her)\s+/,"")))return"nonsense";const a=n.split(/\s+/).filter(Boolean);if(a.length<=2&&a.some(l=>Vae.test(l)))return"nonsense";const i=Vo(e,t);return i&&_ae.has(i)?i:null};function Bae(e,t){return e==="name"?"metadata":t?e==="source"||e==="photos"?"start-over":"redraw":"plain"}function C5(e,t,n,r){var f,h,p,g,v,w,y,x,k;const a=t.answers,i=r?{reopened:!0,cost:gae(dR(a,n).filter(S=>S!=="keep"&&F0(S)>F0(e)).length)}:{};switch(e){case"source":return{id:e,kind:"choice",prompt:Pn.source,options:AR,given:(f=a.source)==null?void 0:f.door,...i};case"weakphotos":return{id:e,kind:"confirm",prompt:Pn.weakPhotos,options:[{id:"again",label:"Use different photos"},{id:"anyway",label:"Draw from these anyway"}]};case"photos":{const S=a.photos??{hashes:[],attested:!1};return{id:e,kind:"photos",prompt:Pn.photos,hint:pae(S.hashes.length,h0),hashes:S.hashes,max:h0,busy:t.uploading>0,attest:{text:oae,checked:S.attested},submit:"Continue",back:"Describe someone instead"}}case"describe":return{id:e,kind:"text",prompt:Pn.describe,starters:aae};case"gaps":{const S=hw(a.describe??"");return{id:e,kind:"choice",prompt:NR(S.length),groups:S.map(E=>({id:E,...jae[E]})),submit:"Continue",skip:"Skip, draw as is",given:a.gaps&&a.gaps!=="skipped"?a.gaps:void 0,...i}}case"traits":{const S=((h=a.source)==null?void 0:h.door)==="photos";return{id:e,kind:"choice",prompt:S?Pn.traitsPhotos:Pn.traits,multi:!0,options:ld.map(E=>({id:E.id,label:E.label})),submit:"Continue",skip:S?"Nothing to add":"Nothing else",given:a.traits,...i}}case"keep":return{id:e,kind:"text",prompt:Pn.keep}}if(rr(e)){const S=e.slice(5),{row:E,prompt:j}=Lf[S],N=Vse((p=a["look-who"])==null?void 0:p.pick),P=zse.has(S)?{...E,options:E.options.map($=>$.card?{...$,card:`${$.card}-${N}`}:$)}:E;return{id:e,kind:"swatches",prompt:j,hint:S==="who"?Pn.lookHint:void 0,row:P,skip:"Skip",describe:S==="who"?"Describe them instead":void 0,saying:t.saying===e,given:((g=a[e])==null?void 0:g.pick)===ac||(v=a[e])==null?void 0:v.pick,skipped:((w=a[e])==null?void 0:w.pick)===ac,note:(y=a[e])==null?void 0:y.words,...i}}const l=Jr(e),u=l?va(l.id):void 0;if(l&&u&&l.part==="where"&&u.where)return{id:e,kind:"choice",prompt:u.where.ask,options:u.where.options.map(S=>({id:S.id,label:S.label})),saying:t.saying===e,given:(x=a[e])==null?void 0:x.pick,note:(k=a[e])==null?void 0:k.words,...i};if(l&&u){const S=a[`trait-${l.id}`];return{id:e,kind:"choice",prompt:u.ask,hint:u.hint,options:u.options.map(E=>({id:E.id,label:E.label,card:E.card})),attach:S!=null&&S.refs.length?"Replace the reference":"Add a reference",saying:t.saying===e,given:S==null?void 0:S.pick,note:S==null?void 0:S.words,...i}}return{id:e,kind:"text",prompt:""}}function j5(e,t){var a,i,l;switch(e){case"source":return Pn.source;case"photos":return Pn.photos;case"describe":return((a=t.source)==null?void 0:a.via)==="typed"?Pn.source:Pn.describe;case"gaps":return NR(hw(t.describe??"").length);case"traits":return((i=t.source)==null?void 0:i.door)==="photos"?Pn.traitsPhotos:Pn.traits;case"keep":return Pn.keep}if(rr(e))return Lf[e.slice(5)].prompt;const n=Jr(e),r=n?va(n.id):void 0;return!n||!r?"":n.part==="where"?((l=r.where)==null?void 0:l.ask)??"":r.ask}function Uae(e,t,n){var u,f,h,p,g,v,w;switch(e){case"source":return{text:((u=t.source)==null?void 0:u.door)==="photos"?"Add photos":"Describe someone"};case"photos":{const y=(n==null?void 0:n.sources)??((f=t.photos)==null?void 0:f.hashes)??[];return{text:hae(y.length),photos:y}}case"describe":return{text:(t.describe??"").trim()};case"gaps":return{text:Aae(t.gaps)};case"traits":return{text:Nae(hR(t.traits??[]))};case"keep":return{text:(((h=t.keep)==null?void 0:h.words)??"").trim(),photos:(p=t.keep)==null?void 0:p.refs}}if(rr(e)){const y=e.slice(5);return{text:Wse(Lf[y].row,t[e]??{})}}const r=Jr(e),a=r?va(r.id):void 0;if(!r||!a)return{text:""};if(r.part==="where"){const y=t[e]??{},x=y.pick?((v=(g=a.where)==null?void 0:g.options.find(k=>k.id===y.pick))==null?void 0:v.label)??sp(y.pick):"";return{text:k5(x,y.words)}}const i=t[`trait-${r.id}`],l=i!=null&&i.pick?((w=a.options.find(y=>y.id===i.pick))==null?void 0:w.label)??sp(i.pick):"";return{text:k5(l,i==null?void 0:i.words),photos:i!=null&&i.refs.length?i.refs:void 0}}function Wae(e){const t=e.state.asides,n=t.length?NN(A5(e,[],null)):null;return A5(e,t,n)}const RR=(e,t)=>e.at<t.at?-1:e.at>t.at?1:0,ap=(e,t)=>_0(e.editing)&&Gse(e.editing)===t.at;function A5(e,t,n){const r=new Set,a=Kae(e,t,n,r),i=a.length&&a[a.length-1].kind==="question"?a.pop():null,l=t.filter(f=>!r.has(f)).sort(RR),u=e.state.unsure;for(const f of l)(!u||f.at<u.at)&&a.push(...ri(f,ap(e.state,f)));if(i&&a.push(i),u){a.push({kind:"you",id:`unsure-${u.at}`,text:u.said,editable:!1}),a.push({kind:"question",question:{id:"unsure",kind:"confirm",quiet:!0,prompt:mae,options:[{id:"use",label:"Use it anyway"}]}});for(const f of l)f.at>=u.at&&a.push(...ri(f,ap(e.state,f)))}return a}function Kae({state:e,draft:t,canGenerate:n,failed:r,awaiting:a},i,l,u){var P,$,M,C,R;const f=MR(t,n),h=e.answers,p=[{kind:"you",id:"intent",text:"Create a presenter"}],g=[],v=((P=h.source)==null?void 0:P.door)==="photos",w=(T,H,D=!1)=>{const K=i.filter(O=>!u.has(O)&&!!O.q&&O.q!==l&&H.includes(O.q)&&!!O.after===D).sort(RR);for(const O of K)u.add(O),T.push(...ri(O,ap(e,O)))},y=T=>i.find(H=>H.edit&&H.q===T&&!u.has(H)),x=(T,H,D=!0)=>{var O;if(T.push({kind:"scenri",id:`asked-${H}`,text:j5(H,h),quiet:!0}),w(T,H==="describe"&&((O=h.source)==null?void 0:O.via)==="typed"?["source","describe"]:[H]),!D){const Z=y(H);Z&&(u.add(Z),T.push({kind:"you",id:H,text:Z.said}),T.push(...ri(Z,ap(e,Z),!0))),w(T,[H],!0);return}const K=Uae(H,h,t);T.push({kind:"you",id:H,text:K.text,photos:K.photos,editable:!0,editing:e.editing===H&&V0(H,h)||void 0}),w(T,[H],!0)},k=new Set(dR(h,f)),S=jse.filter(T=>k.has(T)||i.some(H=>H.edit&&H.q===T));for(const T of S){const H=v&&t&&T!=="source"&&T!=="photos"?g:p;if(e.editing===T&&!V0(T,h)){H.push({kind:"scenri",id:`asked-${T}`,text:j5(T,h),quiet:!0}),w(H,[T]),H.push({kind:"question",question:C5(T,e,f,!0)}),w(H,[T],!0);continue}T==="source"&&(($=h.source)==null?void 0:$.via)==="typed"||x(H,T,k.has(T))}let E=null;if(((M=h.source)==null?void 0:M.door)==="scratch"&&!n&&!t)E={id:"noengine",kind:"confirm",quiet:!0,prompt:"Describing someone needs image generation, which is not set up yet.",options:[{id:"setup",label:"Set up"},{id:"photos",label:"Add photos instead"}]};else{const T=Em(h,f);T?E=C5(T,e,f,!1):!t&&((C=h.source)==null?void 0:C.door)==="scratch"&&(h.source.via==="taps"?E={id:"agree",kind:"confirm",prompt:Pn.agree,quote:`${Kse(fR(h))}${y5(h)?`, and always ${y5(h)}`:""}.`,options:[{id:"draw",label:"Draw the presenter"}]}:r&&(E={id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${r}. Nothing was drawn.`,options:[{id:"retry",label:"Retry"}]}))}if(a&&(E=null),!t)return E&&p.push({kind:"question",question:E}),p;const j=Cae({draft:t,canGenerate:n,ui:{extrasDeclined:e.extrasDeclined,failed:r,editingName:e.editing==="name"},afterCoverage:g,asides:i,openId:l,placed:u}),N=[...p,...j];return E&&((R=N[N.length-1])==null?void 0:R.kind)==="question"&&N.pop(),E&&N.push({kind:"question",question:E}),N}function PR(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.kind==="question")return n.question;if(!Uh(n))return null}return null}const Ja={placeholder:"Nothing to type yet",label:"Message",action:"Send"},N5=(e,t)=>({placeholder:t?Zse[e]??"In your words":p5.has(e)?"Tap a swatch above, or say the colour":"Tap one above, or describe it",label:"Describe it",action:"Send",color:p5.has(e)});function M5(e,t){const n=Jr(e),r=n?va(n.id):void 0,a=(n==null?void 0:n.part)==="where"?"Where it is, in your words":(r==null?void 0:r.saying)??"What it looks like",i=(n==null?void 0:n.part)==="where"?"Tap one above, or say where it is":`Tap one above, or ${((r==null?void 0:r.saying)??"describe it").toLowerCase()}`;return{placeholder:t?a:i,label:(r==null?void 0:r.saying)??"Describe it",action:"Send"}}function Gae(e,t,n,r){if(t.editing!==null&&(t.editing==="name"||_0(t.editing)||V0(t.editing,t.answers)))return{...Ja,off:"Finish the change above."};if(t.saying==="keep")return{placeholder:x5,label:"What should stay the same about them",action:"Send"};if(t.saying&&rr(t.saying))return N5(t.saying.slice(5),!0);if(t.saying)return M5(t.saying,!0);if(t.editing!==null)return{...Ja,off:"Finish the change above."};if(e){if(rr(e.id))return N5(e.id.slice(5),!1);if(e.id.startsWith("trait-"))return M5(e.id,!1);switch(e.id){case"source":return{placeholder:"Describe them, or choose above",label:"Describe them",action:"Send"};case"describe":case"unsure":return{placeholder:"Describe them",label:"Describe them",action:"Send"};case"name":return{placeholder:"Their name",label:"Their name",action:"Send"};case"identity":return{placeholder:"What should change? Shorter hair, older",label:"What should change",action:"Refine"};case"agree":return{placeholder:x5,label:"Anything else that is always true of them",action:"Send"};case"traits":return{placeholder:"Tap any above, or say it in your own words",label:"Anything else that is always true of them",action:"Send"};case"gaps":return{placeholder:"Tap one above, or say it in your own words",label:"Fill in what is missing",action:"Send"};case"photos":return{...Ja,off:"Add their photos above."};case"noengine":return{...Ja,off:"Set up image generation, or add photos."};case"blind":return{...Ja,off:"Decide above."};case"retry":return{...Ja,off:"Retry above."}}}return n?n.stage==="analyzing"?{...Ja,off:`Reading ${n.source==="photos"?"the photos":"the face"}.`}:ec(n)?Ko(n)?{placeholder:R5(r,n),label:"What should change",action:"Refine",off:""}:{...Ja,off:""}:Ko(n)?{placeholder:R5(r,n),label:"What should change",action:"Refine"}:{...Ja,off:"The face comes first."}:{...Ja,off:"Starting the draft."}}function R5(e,t){var r;const n=((r=t.name)==null?void 0:r.trim())||"them";return e==="portrait"?`What should change about ${n}?`:`Change this view: ${bn[e]}`}function P5(e,t){return e.saying?e.saying:t&&_s(t.id)&&(t.id==="source"||t.id==="describe")||t&&_s(t.id)&&(rr(t.id)||t.id.startsWith("trait-"))?t.id:(t==null?void 0:t.id)==="agree"?"keep":(t==null?void 0:t.id)==="name"?"name":null}const Yae=/\b(here|in this (view|one|picture|image|frame)|this (view|one|picture|image|frame))\b/i,qae=/\b(looks? like|doesn'?t look|does not look|not (her|him|them)|drift(s|ed|ing)?|wrong|\boff\b|different person|someone else|regenerate|redraw|again)\b/i,Xae=/\b(dress|gown|outfit|wearing|wear|jacket|coat|suit|shirt|t-shirt|tee|hoodie|jeans|trousers|skirt|shoes|heels|sneakers|boots|hat|cap|sunglasses|jewell?ery|necklace|earrings|watch|holding|holds?|product|bottle|perfume|bag|handbag|phone|laptop|scene|beach|paris|london|tokyo|street|rooftop|office|kitchen|cafe|city|forest|desert|snow|rain|sunset|sunrise|golden hour|background|backdrop|lighting|campaign|shoot)\b/i,Qae=/\b(simpler|plainer|plain|neutral|cleaner|tidier)\b/i,Jae=/\b(outfit|clothes|clothing|top|wardrobe|wearing)\b/i;function LR(e,t,n){const r=e.trim();if(!r)return{blocked:"Say what should change."};if(Xae.test(r)&&!(Qae.test(r)&&Jae.test(r)))return{scope:"out-of-scope"};const a=eA.test(r),i=qae.test(r),l=Yae.test(r),u=n.source==="photos";if(t==="portrait")return u?{blocked:"Their photos define who they are. Change a drawn view instead."}:{scope:"identity",view:"portrait"};if(a&&i&&!l)return u?{scope:"view",view:t}:{scope:"ambiguous"};if(a&&!l)return u?{blocked:"Their photos define who they are. Change a drawn view instead."}:{scope:"identity",view:"portrait"};const f=n.views[t];return f.origin==="photo"?{blocked:"Your photo stands as it is. Pick a drawn view to change."}:f.status!=="approved"&&f.status!=="candidate"?{blocked:`Nothing drawn for the ${bn[t]} yet.`}:{scope:"view",view:t}}const TR=e=>`Use Create for wardrobe, products and scenes. Edits here change who ${e} is.`;function eoe(e,t,n,r){const a=e.trim(),i=t==="portrait"?"Describe a change to who they are.":"Say what is wrong with this view, or describe a change to who they are.";if(!a){const u=n.views[t];return t!=="portrait"&&u.origin==="photo"?{chip:null,hint:"Your photo stands as it is. Pick a drawn view to change."}:{chip:null,hint:i}}const l=LR(a,t,n);return"blocked"in l?{chip:null,hint:l.blocked,tone:"alert"}:l.scope==="out-of-scope"?{chip:null,hint:TR(r),tone:"alert"}:l.scope==="ambiguous"?{chip:null,hint:"This reads as the view or the person. Send it and I will ask which."}:l.scope==="identity"?{chip:{view:"portrait",label:"Changing the person"},hint:"Changes the person. The other views are redrawn after you use it."}:{chip:{view:l.view,label:`Refining the ${bn[l.view]}`},hint:"Changes this view only. Hair, skin, age or build change the person."}}const toe=e=>e.replace(/^asset:/,"");function $R(e,t){if((e.identityEdits??[]).join(`
|
|
104
|
+
`;function Qne(e){return e.map(Ta).filter(t=>t.length>0).join(DM)}function Jne(e){return new Set(e?e.split(DM):[])}const ere=new Set(["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"]);function tre(e,t,n,r){const a=r.length?r[r.length-1].end+1:0;if(a===0)return t==="ArrowUp"?"search":null;const i=Math.max(1,n),l=r.findIndex(p=>e>=p.start&&e<=p.end),u=r[l]??{start:0,end:a-1},f=(e-u.start)%i,h=p=>p.start+Math.floor((p.end-p.start)/i)*i;switch(t){case"ArrowRight":return e+1<a?e+1:null;case"ArrowLeft":return e>0?e-1:null;case"Home":return 0;case"End":return a-1;case"ArrowDown":{if(e+i<=u.end)return e+i;if(e<h(u))return u.end;const p=r[l+1];return p?p.start+Math.min(f,p.end-p.start):null}case"ArrowUp":{if(e-i>=u.start)return e-i;const p=r[l-1];return p?Math.min(p.end,h(p)+f):"search"}}}function nre(e,t){const n=t.trim();return e==="All"?n?`Nothing matches “${n}”.`:"Nothing to add yet.":n?`No matching ${H6[e]}.`:e==="Shots"?"No finished shots yet.":`No ${H6[e]} yet.`}function rre(e){return[{value:null,label:"All",count:Qh.reduce((n,r)=>n+e[r],0)},...Qh.map(n=>({value:n,label:n,count:e[n]}))]}const sre=s.memo(function({card:t,index:n,active:r,ticked:a,why:i,onPick:l,onFocus:u}){const f=g=>{(g.key==="Enter"||g.key===" ")&&g.stopPropagation()},h=i&&!a?i:null,p=o.jsxs("button",{type:"button",className:"sc-ap-card","data-shape":t.shape,"data-group":t.group,"data-nav":n,"data-on":a?"":void 0,tabIndex:r?0:-1,"aria-disabled":h?!0:void 0,"aria-pressed":a,title:h??(a?`${t.label} is in the shot. Press to remove it.`:t.full),onClick:h?void 0:()=>l(n),onFocus:()=>u(n),onKeyDown:f,children:[t.shape==="swatch"?o.jsx("span",{className:"sc-ap-thumb sc-ap-swatch",style:{background:t.swatch},"aria-hidden":!0}):o.jsx(are,{src:t.thumb,crop:t.crop}),o.jsxs("span",{className:"sc-ap-cap",children:[o.jsxs("span",{className:"sc-vh",children:[Une[t.group],": "]}),o.jsx("b",{dir:"auto",children:t.label}),t.sub&&o.jsx("span",{dir:"auto",children:t.sub})]}),(a||!i)&&o.jsxs("span",{className:"sc-ap-puck","aria-hidden":!0,children:[o.jsx(cr,{className:"sc-ap-puck-add",size:11,weight:"bold"}),o.jsx(Kn,{className:"sc-ap-puck-on",size:11,weight:"bold"}),o.jsx(jn,{className:"sc-ap-puck-off",size:11,weight:"bold"})]}),a&&o.jsx("span",{className:"sc-vh",children:" In the shot."})]});return o.jsx(TM,{why:h,children:p})});function are({src:e,crop:t}){const[n,r]=s.useState(!1);return s.useEffect(()=>r(!1),[e]),o.jsx("span",{className:"sc-ap-thumb","data-empty":!e||n?"":void 0,children:!e||n?o.jsx(Ws,{size:16}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async","data-crop":t,onError:()=>r(!0)})})}function s5({onClick:e}){return o.jsxs("button",{type:"button",className:"sc-ap-card sc-ap-add sc-ap-upload-tile",title:"Add an image from your phone. It joins the shot as a reference.",onClick:e,children:[o.jsx("span",{className:"sc-ap-thumb",children:o.jsx(iv,{size:22,"aria-hidden":!0})}),o.jsx("span",{className:"sc-ap-cap",children:o.jsx("b",{children:"Upload image"})})]})}const ore=48,ire={items:[],total:0,hasMore:!1,loading:!1,settled:!1,error:null,loadMore:()=>{}};function Xv(e,t,n=!0){const r=t.trim(),{shotsEpoch:a,subscribeActivity:i}=on(),l=`${e}|${r}|${a}`,[u,f]=s.useState({key:"",items:[],next:null,total:0}),[h,p]=s.useState(!1),[g,v]=s.useState(null),w=s.useRef(null),y=s.useCallback(async S=>{var j;(j=w.current)==null||j.abort();const E=new AbortController;w.current=E,p(!0),v(null);try{const N=await Re.feed(e,{lens:"all",sort:"newest",q:r,limit:ore,cursor:S??void 0},E.signal);if(E.signal.aborted)return;f(P=>{var M;const $=S===null||P.key!==l;return{key:l,items:$?N.items:[...P.items,...N.items],next:N.next,total:((M=N.counts)==null?void 0:M.all)??($?N.items.length:P.total)}})}catch(N){if(E.signal.aborted)return;v(String(N.message??N))}finally{E.signal.aborted||p(!1)}},[e,r,l]);s.useEffect(()=>{if(!n)return;const S=u.key===""?0:150,E=setTimeout(()=>void y(null),S);return()=>clearTimeout(E)},[y,n]),s.useEffect(()=>()=>{var S;return(S=w.current)==null?void 0:S.abort()},[]),s.useEffect(()=>i(S=>{const E=new Map(S.map(j=>[j.id,j]));f(j=>{if(!j.items.some(P=>E.has(P.id)))return j;const N=j.items.flatMap(P=>{const $=E.get(P.id);return $?$.archived?[]:[{...P,...$}]:[P]});return{...j,items:N,total:Math.max(0,j.total-(j.items.length-N.length))}})}),[i]);const x=u.key===l?u:null,k=s.useCallback(()=>{x!=null&&x.next&&y(x.next)},[x==null?void 0:x.next,y]);return x?{items:x.items.filter(S=>S.status==="done"&&S.images.length>0),total:x.total,hasMore:x.next!==null,loading:h,settled:!0,error:g,loadMore:k}:{...ire,loading:h,error:g,loadMore:k}}const t8={Products:"product",Presenters:"presenter",Scenes:"scene"};function lre({brand:e,tab:t,onTab:n,only:r,activeProductCategory:a,refining:i,full:l,attached:u,phone:f,touch:h,onPick:p,onRemove:g,onUpload:v,onFiles:w,onClose:y}){const x=s.useRef(a).current,k=Rf(x),S=s.useMemo(()=>new Set(vo(e.id)),[e.id]),E=ll(),{applyBrand:j}=Rn(),{push:N}=or(),[P,$]=s.useState(!1),[M,C]=s.useState(""),R=s.useDeferredValue(M),[T,H]=s.useState(Fi),[D,K]=s.useState(0),[O,Z]=s.useState(f?347:696),te=s.useRef(null),B=s.useRef(null);s.useEffect(()=>{H(Fi),K(0)},[t,R]),s.useLayoutEffect(()=>{const ce=B.current;if(!ce)return;const ve=()=>Z(ce.clientWidth-2*ure(ce));ve();const Pe=new ResizeObserver(ve);return Pe.observe(ce),()=>Pe.disconnect()},[]);const F=s.useMemo(()=>({product:_i("product",k),presenter:_i("presenter",k),scene:_i("scene",k)}),[k]),X=s.useMemo(()=>qne(e.json),[e.json]),z=Xv(e.id,R),I=s.useMemo(()=>Xne(z.items,z.total),[z.items,z.total]),U=s.useMemo(()=>{const ce={};for(const ve of Qh){const Pe=t8[ve];ce[ve]=ve==="Shots"?z.total:Pe?Pu(F[Pe],R).length:X.filter(de=>de.group===ve&&r5(de,R)).length}return ce},[F,X,R,z.total]),G=s.useCallback((ce,ve)=>{const Pe=t8[ce];if(Pe){const je=hm(Pe,F[Pe],{currentId:null,query:R,bookmarked:S,shown:ve});return{group:ce,items:je.items.map(Yne),total:je.total,remaining:je.remaining}}if(ce==="Shots"){const je=I.slice(0,ve),Ue=z.hasMore?Math.max(1,z.total-I.length):Math.max(0,I.length-ve);return{group:ce,items:je,total:z.total,remaining:Ue}}const de=X.filter(je=>je.group===ce&&r5(je,R));return{group:ce,items:de.slice(0,ve),total:de.length,remaining:Math.max(0,de.length-ve)}},[F,X,R,S,I,z.hasMore,z.total]),ne=s.useMemo(()=>{if(t==="All"){const ce=[];for(const ve of Qh){const Pe=Kne(ve,O,f),de=G(ve,f&&ce.length===0?Math.max(1,Pe-1):Pe);de.items.length>0&&ce.push(de)}return ce}return[G(t,t==="Shots"?Number.MAX_SAFE_INTEGER:T)]},[t,G,T,O,f]),{flat:q,navGroups:le}=s.useMemo(()=>{const ce=[],ve=[];for(const Pe of ne)Pe.items.length&&(ve.push({start:ce.length,end:ce.length+Pe.items.length-1}),ce.push(...Pe.items));return{flat:ce,navGroups:ve}},[ne]);s.useEffect(()=>{K(ce=>Math.max(0,Math.min(ce,q.length-1)))},[q.length]);const Se=s.useCallback(ce=>{var Pe;const ve=(Pe=B.current)==null?void 0:Pe.querySelector(`[data-nav="${ce}"]`);ve&&(K(ce),ve.focus({preventScroll:!0}),ve.scrollIntoView({block:"nearest"}))},[]),Q=s.useRef(null),xe=s.useRef(()=>{});xe.current=()=>{const ce=ne[0];!ce||t==="All"||ce.remaining<=0||(ce.group==="Shots"?z.loading||z.loadMore():H(ve=>ve+Fi))},s.useEffect(()=>{const ce=Q.current,ve=B.current;if(!ce||!ve)return;const Pe=new IntersectionObserver(de=>{de.some(je=>je.isIntersecting)&&xe.current()},{root:ve,rootMargin:"0px 0px 240px 0px"});return Pe.observe(ce),()=>Pe.disconnect()},[t,ne]);const ee=s.useCallback(ce=>{var Pe,de;const ve=q[ce];ve&&(u.has(ve.key)?g(ve):p(ve),h&&((de=(Pe=document.activeElement)==null?void 0:Pe.blur)==null||de.call(Pe)))},[q,u,h,p,g]),ae=ce=>{const ve=ce.clipboardData.files;!ve.length||!Array.from(ve).some(Pe=>Pe.type.startsWith("image/"))||(ce.preventDefault(),w(ve))},re=ce=>{var Ue,ye;const ve=ce.target,Pe=ve instanceof HTMLInputElement&&!!((Ue=te.current)!=null&&Ue.contains(ve));if(ce.key==="Escape"){if(Pe)return;ce.preventDefault(),ce.stopPropagation(),y();return}if(Pe){ce.key==="ArrowDown"?(ce.preventDefault(),ce.stopPropagation(),Se(0)):ce.key==="Enter"&&(ce.preventDefault(),ce.stopPropagation(),ee(0));return}if(!ere.has(ce.key)||(ce.stopPropagation(),ve.closest('[role="tablist"]')))return;const de=ve.closest("[data-nav]");if(!de)return;ce.preventDefault();const je=tre(D,ce.key,cre(de.closest(".sc-ap-grid")),le);if(je==="search"){const Ee=te.current;(ye=(Ee==null?void 0:Ee.querySelector(".sc-libsearch[data-open] input"))??(Ee==null?void 0:Ee.querySelector(".sc-libsearch-toggle")))==null||ye.focus()}else je!=null&&Se(je)},_=async ce=>{$(!0);try{const ve=await Nj(e.id,ce);j(ve);const Pe=ve.logoHash;Pe&&p({key:`m:${Pe}`,group:"Brand",shape:"square",label:"Logo",full:"Logo",search:"",token:{t:"mark",imageHash:Pe}});const de=ve.logoEdge;de&&de<512&&N({kind:"warning",title:"Logo added, but it is small",detail:`Only ${de}px across. Fine lettering may not survive generation. Export it larger, or as SVG.`})}catch(ve){N(nn(ve,"Could not upload that logo"))}finally{$(!1)}},ue=ce=>E(ce,{onCreated:ve=>{if(ve.kind===ce){if(ve.kind==="product"){const Pe={t:"product",id:ve.id};p({key:Ta(Pe),group:"Products",shape:"square",label:"Product",full:"",search:"",token:Pe});return}if(ve.kind==="presenter"){const Pe={t:"character",id:ve.id};p({key:Ta(Pe),group:"Presenters",shape:"square",label:"Presenter",full:ve.name,search:ve.name,token:Pe});return}n("Scenes")}}}),We=async ce=>{var de;const ve=VA((de=e.json)==null?void 0:de.palette,ce);if(!ve.swatch)return;if(ve.added)try{const je=await Re.updateBrand(e.id,{...e.json??{},palette:ve.palette});j(je)}catch(je){N(nn(je,"Could not save the brand"));return}const Pe={t:"color",hex:ve.swatch.hex,name:ve.swatch.name};p({key:Ta(Pe),group:"Colors",shape:"swatch",label:ve.swatch.name,full:"",search:"",swatch:ve.swatch.hex,token:Pe})},Xe=ce=>i&&ce==="Scenes"?"Scenes set up a new shot. Press X on Refining to use one.":l&&ce!=="Colors"?l:null,ze=q.length===0;let tt=0;return o.jsxs("div",{className:"sc-ap-inner",onKeyDown:re,onPaste:ae,children:[o.jsxs("div",{className:"sc-ap-head",ref:te,children:[o.jsx("div",{className:"sc-ap-tabs",children:o.jsx(qv,{"aria-label":"What to add",activeKey:t==="All"?null:t,items:rre(U),onSelect:ce=>n(ce??"All")})}),o.jsxs("div",{className:"sc-ap-actions",children:[o.jsxs("div",{className:"sc-ap-actions-add",children:[o.jsx(id,{value:M,onChange:C,noun:t==="All"?"everything":H6[t],total:t==="All"?void 0:U[t],shortcut:!1}),!f&&o.jsxs("button",{type:"button",className:"sc-btn sc-btn-primary sc-ap-upload",onClick:v,title:"Add an image from your computer. It joins the shot as a reference.",children:[o.jsx(iv,{size:14,"aria-hidden":!0}),o.jsx("span",{children:"Upload image"})]})]}),!f&&o.jsx("button",{type:"button",className:"sc-icon-btn sc-ap-close",onClick:y,"aria-label":"Close",children:o.jsx(jn,{size:14})})]})]}),o.jsxs("div",{className:"sc-ap-body",ref:B,children:[i&&t==="Scenes"&&o.jsx("p",{className:"sc-ap-hint",children:"Scenes set up a new shot, so they sit out while you are refining. Press X on Refining to use one."}),ne.map((ce,ve)=>{var Ee,be,Le;const Pe=Xe(ce.group),de=tt;tt+=ce.items.length;const je=t8[ce.group],ye={"--ap-min":`${(f?O6:$M)[ce.group]}px`,"--ap-lines":je==="product"?2:1};return o.jsxs("section",{className:"sc-ap-group","aria-label":t5[ce.group],children:[o.jsxs("div",{className:"sc-ap-sec",children:[o.jsxs("span",{className:"sc-ap-sec-title",children:[t5[ce.group],o.jsx("span",{className:"sc-ap-sec-n",children:ce.total})]}),t==="All"&&ce.total>ce.items.length&&o.jsxs("button",{type:"button",className:"sc-ap-sec-act",onClick:()=>n(ce.group),children:["Show all ",ce.total]}),t==="Products"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("product"),children:"Add product"}),t==="Presenters"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("presenter"),children:"Create presenter"}),t==="Scenes"&&!r&&o.jsx("button",{type:"button",className:"sc-ap-sec-act sc-ap-add",onClick:()=>ue("scene"),children:"Create scene"}),t==="Colors"&&o.jsx(Zu,{className:"sc-ap-sec-act sc-ap-add",triggerStyle:{background:"none"},value:Jp(Zs((Ee=e.json)==null?void 0:Ee.palette)),presets:Zs((be=e.json)==null?void 0:be.palette).map(Qe=>Qe.hex),commitMode:"close",align:"end",label:"Add color",onChange:Qe=>void We(Qe),children:"Add color"}),t==="Brand"&&o.jsxs("label",{className:"sc-ap-sec-act sc-ap-add",title:"Add your logo to the brand kit","data-busy":P||void 0,children:[o.jsx("input",{type:"file",accept:"image/*",className:"sc-vh",disabled:P,onChange:Qe=>{var nt;const Ke=(nt=Qe.target.files)==null?void 0:nt[0];Qe.target.value="",Ke&&_(Ke)}}),"Add logo"]})]}),o.jsxs("div",{className:"sc-ap-grid","data-shape":((Le=ce.items[0])==null?void 0:Le.shape)??"square",style:ye,children:[f&&ve===0&&!r&&o.jsx(s5,{onClick:v}),ce.items.map((Qe,Ke)=>o.jsx(sre,{card:Qe,index:de+Ke,active:de+Ke===D,ticked:u.has(Qe.key),why:Pe,onPick:ee,onFocus:K},Qe.key))]}),t!=="All"&&ce.remaining>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:Q,className:"sc-ap-sentinel","aria-hidden":!0}),o.jsxs("p",{className:"sc-ap-foot","aria-live":"polite",children:[ce.items.length," of ",ce.total]})]})]},ce.group)}),t==="Shots"&&z.error&&o.jsxs("p",{className:"sc-ap-empty",children:["Could not load the shots. ",z.error]}),ze&&f&&o.jsx("div",{className:"sc-ap-grid",style:{"--ap-min":`${O6.Products}px`},children:o.jsx(s5,{onClick:v})}),ze&&!(t==="Shots"&&(!z.settled||z.loading||z.error))&&o.jsx("p",{className:"sc-ap-empty",children:nre(t,M)})]})]})}function cre(e){return e?Math.max(1,getComputedStyle(e).gridTemplateColumns.split(" ").filter(Boolean).length):1}function ure(e){return Number.parseFloat(getComputedStyle(e).paddingLeft)||0}const dre="(pointer: coarse)";function fre(e){const t=wr(Ks),n=wr(dre),[r,a]=s.useState(e.initialTab??"All");s.useEffect(()=>{a(e.initialTab??"All")},[e.initialTab,e.tabNonce]);const[i]=el(),l=i.get("new")!==null;return o.jsx(hre,{id:e.id,phone:t,touch:n,creating:l,onClose:e.onClose,children:o.jsx(lre,{brand:e.brand,tab:e.only??r,onTab:a,only:e.only,activeProductCategory:e.activeProductCategory,refining:e.refining,full:e.full,attached:e.attached,phone:t,touch:n,onPick:e.onPick,onRemove:e.onRemove,onUpload:e.onUpload,onFiles:e.onFiles,onClose:()=>e.onClose({restore:!n})})})}function hre({id:e,phone:t,touch:n,creating:r,onClose:a,children:i}){const l=s.useRef(null),u=()=>{var p;return a({restore:!n&&!!((p=l.current)!=null&&p.contains(document.activeElement))})},f=s.useRef(u);f.current=u,s.useEffect(()=>{var p,g;n&&((g=(p=document.activeElement)==null?void 0:p.blur)==null||g.call(p))},[n]),s.useLayoutEffect(()=>{var y,x;const p=l.current,g=p==null?void 0:p.parentElement;if(!t||!p||!g)return;const v=()=>{const k=p.closest(".sc-shell")??document.documentElement,S=Number.parseFloat(getComputedStyle(k).getPropertyValue("--sc-topbar-h"))||0,E=g.getBoundingClientRect().top-S-16;p.style.setProperty("--ap-avail",`${Math.max(160,Math.round(E))}px`)};v();const w=new ResizeObserver(v);return w.observe(g),window.addEventListener("resize",v),(y=window.visualViewport)==null||y.addEventListener("resize",v),(x=window.visualViewport)==null||x.addEventListener("scroll",v),()=>{var k,S;w.disconnect(),window.removeEventListener("resize",v),(k=window.visualViewport)==null||k.removeEventListener("resize",v),(S=window.visualViewport)==null||S.removeEventListener("scroll",v)}},[t]),s.useEffect(()=>{const p=g=>{var w;if(g.key!=="Escape"||r)return;const v=document.activeElement;v instanceof HTMLInputElement&&((w=l.current)!=null&&w.contains(v))||(g.preventDefault(),g.stopPropagation(),f.current())};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[r]);const h=p=>{var w;const g=document.activeElement,v=p.target;g instanceof HTMLInputElement&&((w=l.current)!=null&&w.contains(g))&&!v.closest("input")&&g.blur(),N6(p)};return s.useEffect(()=>{const p=g=>{if(r)return;const v=g.target;v.closest('[data-guide="catch"], [data-guide="card"], [data-guide="inline"]')||document.querySelector('[data-guide="catch"]')||v.closest(".sc-attachpanel, .sc-attach-toggle, [data-attach-opener]")||f.current()};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[r]),o.jsx("div",{ref:l,className:"sc-attachpanel","data-guide-shape":"",role:"dialog",id:e,"aria-label":"Add to shot",onMouseDownCapture:h,children:i})}function pre({target:e,onOpenImage:t,onClear:n}){var f;const r=od(),a=e.images[0],l=(((f=e.brief)==null?void 0:f.tokens)??[]).filter(h=>h.t==="text"&&typeof h.v=="string").map(h=>h.v.trim()).join(" ").trim()||Sr(e),u=s.useCallback(()=>{a&&(r.closeNow(),t())},[a,r.closeNow,t]);return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"sc-token sc-target-chip",role:"button",tabIndex:0,"aria-haspopup":"dialog","aria-label":n?`Version being refined: ${l}. Open the image, or remove to make a new shot.`:`Version being refined: ${l}. Open the image.`,onPointerEnter:h=>{h.pointerType==="mouse"&&a&&r.open({anchor:h.currentTarget})},onPointerLeave:h=>h.pointerType==="mouse"&&r.close(),onClick:u,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[a?o.jsx("img",{src:dn(a,"micro"),alt:""}):o.jsx("span",{className:"sc-target-thumb sc-shimmer"}),"Refining",n&&o.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),r.closeNow(),n()},"aria-label":"Make a new shot instead",children:o.jsx(jn,{size:12})})]}),r.shown&&a&&o.jsx(ad,{anchor:r.shown.anchor,kind:"shot",src:dn(a,"tile"),label:l,noun:"Refining this shot",onOpen:u,onHoverIn:r.keep,onHoverOut:r.close,onClose:r.closeNow})]})}function Uu({src:e,kind:t,label:n,noun:r,actions:a,onRestoreFocus:i,onClose:l}){const[u,f]=s.useState(!1),h=r??bM[t],p=s.useRef(null);return o.jsxs(Ts,{className:"sc-lightbox",maxWidth:"min(880px, 92vw)",onOpenAutoFocus:()=>{p.current=document.activeElement},onCloseAutoFocus:g=>{var v;if(g.preventDefault(),i)return i();(v=p.current)!=null&&v.isConnected&&p.current.focus()},onDismiss:l,children:[o.jsx("div",{className:"sc-lightbox-frame","data-kind":t,children:u?o.jsxs("span",{className:"sc-lightbox-blank",children:[o.jsx(Ws,{size:28}),"Image unavailable"]}):o.jsx("img",{src:e,alt:n?`${n}, ${h.toLowerCase()}`:h,onError:()=>f(!0)})}),o.jsxs("p",{className:"sc-lightbox-cap",children:[n&&o.jsx("b",{dir:"auto",children:n}),o.jsx("span",{children:h})]}),a&&o.jsx("div",{className:"sc-lightbox-acts",children:a})]})}const mre={"codex-cli":{sizing:"advisory"},openrouter:{sizing:"ratio"},replicate:{sizing:"ratio",formats:["square","story","landscape"]},fal:{sizing:"exact"},demo:{sizing:"exact"}},gre={sizing:"exact"},HM=e=>mre[e]??gre;function vre(e,t){const n=HM(e).formats;return!n||n.includes(t)}const Qv=e=>HM(e).sizing,Zi=[{id:"draft",label:"Draft",edge:768,note:"quick checks"},{id:"standard",label:"Standard",edge:1024,note:"everyday shots"},{id:"high",label:"High",edge:1536,note:"hero and print"}],Jh=[1,2,3,4],OM=e=>Xr.filter(t=>!vre(e,t.id)).map(t=>t.id),I6=(e,t)=>t.length===0?void 0:`${e} cannot make ${Xr.filter(n=>t.includes(n.id)).map(n=>n.hint).join(" or ")}.`,Jv=e=>{var n;e.preventDefault();const t=e.currentTarget??e.target;(n=t==null?void 0:t.querySelector('[role="radiogroup"]'))==null||n.focus()};function n8({aria:e,width:t,trigger:n,open:r,onOpenChange:a,children:i,onCloseAutoFocus:l,guide:u}){const f=s.useRef(null);return s.useEffect(()=>{var p;const h=(p=f.current)==null?void 0:p.parentElement;h&&(h.style.pointerEvents=r?"":"none")},[r]),o.jsxs(Hu,{open:r,onOpenChange:a,children:[o.jsx(Ou,{children:o.jsx("button",{type:"button",className:"sc-var","aria-label":e,"data-guide":u,children:n})}),o.jsx(Iu,{ref:f,className:"sc-setpop",align:"end",sideOffset:8,width:t,onOpenAutoFocus:Jv,onCloseAutoFocus:l,onInteractOutside:h=>{var p;(p=h.target)!=null&&p.closest(".sc-prompt-pills")&&h.preventDefault()},children:i(()=>a(!1))})]})}function wre({mode:e,engineId:t,engineName:n,formatId:r,onFormat:a,count:i,onCount:l,quality:u,onQuality:f,onCloseAutoFocus:h,guided:p=!1,onSettle:g}){const v=Xr.find($=>$.id===r)??Xr[0],w=Zi.find($=>$.id===u)??Zi[1],y=OM(t),x=Qv(t),[k,S]=s.useState(null),E=s.useRef(null);E.current=k;const j=$=>{$.preventDefault(),E.current===null&&(h==null||h($))},N={aspect:"shape",variants:"count",resolution:"quality"},P=$=>({open:k===$,onCloseAutoFocus:j,guide:p?`compose.${N[$]}`:void 0,onOpenChange:M=>{!M&&E.current===$&&(g==null||g(N[$])),S(C=>M?$:C===$?null:C)}});return o.jsxs("div",{className:"sc-prompt-pills","data-guide":p?"compose.settings-row":void 0,children:[o.jsx(n8,{...P("aspect"),aria:`Aspect ${v.label}, ${v.hint}`,width:"178px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(v6,{w:v.w,h:v.h,slot:15,box:13}),v.label]}),children:$=>o.jsxs(o.Fragment,{children:[o.jsx(_o,{label:"Aspect ratio",className:"sc-setpop-list",value:r,ids:Xr.map(M=>M.id),unavailable:y,onChange:a,children:Xr.map(M=>o.jsxs(Zo,{id:M.id,className:"sc-setrow",on:M.id===r,unavailable:y.includes(M.id),label:`${M.label}, ${M.hint}`,onPick:()=>{a(M.id),$()},children:[o.jsx(v6,{w:M.w,h:M.h,slot:20,box:17}),o.jsx("span",{className:"sc-setrow-n",children:M.label}),o.jsx("span",{className:"sc-setrow-v",children:M.hint}),o.jsx(kx,{})]},M.id))}),I6(n,y)&&o.jsx(gY,{children:I6(n,y)})]})}),e==="generation"&&o.jsx(n8,{...P("variants"),aria:`${i} shot${i===1?"":"s"}`,width:"156px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(dj,{size:14}),i]}),children:$=>o.jsx(o.Fragment,{children:o.jsx(_o,{label:"Shots",className:"sc-seg",value:String(i),ids:Jh.map(String),onChange:M=>l(Number(M)),children:Jh.map(M=>o.jsx(Zo,{id:String(M),className:"sc-seg-o",on:M===i,label:`${M} shot${M===1?"":"s"}`,onPick:()=>{l(M),$()},children:M},M))})})}),e==="generation"&&x!=="ratio"&&o.jsx(n8,{...P("resolution"),aria:`Resolution ${w.label}, ${w.edge} px`,width:"192px",trigger:o.jsxs(o.Fragment,{children:[o.jsx(TC,{size:14}),w.label]}),children:$=>o.jsx(o.Fragment,{children:o.jsx(_o,{label:"Resolution",className:"sc-setpop-list",value:u,ids:Zi.map(M=>M.id),onChange:M=>f(M),children:Zi.map(M=>o.jsxs(Zo,{id:M.id,className:"sc-setrow",on:M.id===u,label:`${M.label}, ${M.edge} px, ${M.note}`,onPick:()=>{f(M.id),$()},children:[o.jsx("span",{className:"sc-setrow-n",children:M.label}),o.jsxs("span",{className:"sc-setrow-v",children:[M.edge," px"]}),o.jsx(kx,{})]},M.id))})})})]})}function IM({mode:e,engineId:t,engineName:n,formatId:r,onFormat:a,count:i,onCount:l,quality:u,onQuality:f,engineChoices:h,onEngine:p}){const g=OM(t),v=Qv(t);return o.jsxs(o.Fragment,{children:[h&&p&&h.length>1&&o.jsx(Q1,{label:"Engine",children:o.jsx(_o,{label:"Engine",className:"sc-seg",value:t,ids:h.map(w=>w.id),onChange:p,children:h.map(w=>o.jsx(Zo,{id:w.id,className:"sc-seg-o",on:w.id===t,label:w.displayName,onPick:()=>p(w.id),children:w.displayName},w.id))})}),o.jsx(Q1,{label:"Aspect ratio",note:I6(n,g),children:o.jsx(_o,{label:"Aspect ratio",className:"sc-seg",value:r,ids:Xr.map(w=>w.id),unavailable:g,onChange:a,children:Xr.map(w=>o.jsxs(Zo,{id:w.id,className:"sc-seg-o sc-seg-ratio",on:w.id===r,unavailable:g.includes(w.id),label:`${w.label}, ${w.hint}`,onPick:()=>a(w.id),children:[o.jsx(v6,{w:w.w,h:w.h,slot:17,box:14}),w.hint]},w.id))})}),e==="generation"&&o.jsx(Q1,{label:"Shots",children:o.jsx(_o,{label:"Shots",className:"sc-seg",value:String(i),ids:Jh.map(String),onChange:w=>l(Number(w)),children:Jh.map(w=>o.jsx(Zo,{id:String(w),className:"sc-seg-o",on:w===i,label:`${w} shot${w===1?"":"s"}`,onPick:()=>l(w),children:w},w))})}),e==="generation"&&v!=="ratio"&&o.jsx(Q1,{label:"Resolution",note:v==="advisory"?"This engine renders at its own size, so this is a request rather than a guarantee.":void 0,children:o.jsx(_o,{label:"Resolution",className:"sc-seg",value:u,ids:Zi.map(w=>w.id),onChange:w=>f(w),children:Zi.map(w=>o.jsx(Zo,{id:w.id,className:"sc-seg-o",on:w.id===u,label:v==="advisory"?`${w.label}, asks for ${w.edge} px, ${w.note}`:`${w.label}, ${w.edge} px, ${w.note}`,onPick:()=>f(w.id),children:w.label},w.id))})})]})}function Q1({label:e,note:t,children:n}){return o.jsxs("div",{className:"sc-shotfield",children:[o.jsx("span",{className:"sc-shotfield-lb",children:e}),n,t&&o.jsx("p",{className:"sc-shotfield-note",children:t})]})}function yre({guide:e,onSettle:t,...n}){const[r,a]=s.useState(!1),i=f=>{!f&&r&&(t==null||t()),a(f)},{sheet:l,grip:u}=ed(()=>i(!1));return o.jsxs(fc,{open:r,onOpenChange:i,children:[o.jsx(g4,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-var sc-shotset","aria-label":"Shot settings",title:"Shot settings","data-guide":e,children:o.jsx(ov,{size:16})})}),o.jsxs(hc,{children:[o.jsx(pc,{className:"sc-shotsheet-scrim"}),o.jsxs(mc,{ref:l,className:"sc-shotsheet","aria-describedby":void 0,onOpenAutoFocus:Jv,onCloseAutoFocus:f=>f.preventDefault(),children:[o.jsxs("div",{className:"sc-shotsheet-grip",...u,children:[o.jsx("span",{className:"sc-shotsheet-bar","aria-hidden":!0}),o.jsx(gc,{className:"sc-vh",children:"Shot settings"})]}),o.jsx(IM,{...n})]})]})]})}const yu=e=>`scenri:draft-${e}`,bre=e=>cs.get(e),xre=(e,t)=>cs.set(e,t),bh=e=>cs.del(e);function a5(e,t){return e.some(n=>n.t==="text"?!!n.v.trim():n.t!=="template")||Object.values(t).some(n=>!!n.trim())}function kre(e){const t=bre(yu(e));if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null)return null;const r=n;if(r.v!==1||r.brandId!==e||!Array.isArray(r.tokens)||typeof r.tplFields!="object"||!r.tplFields||r.branchId)return bh(yu(e)),null;const a=Date.now()-Date.parse(r.updatedAt??"");return!Number.isFinite(a)||a>zj?(bh(yu(e)),null):{v:1,brandId:e,updatedAt:r.updatedAt,tokens:r.tokens,tplFields:r.tplFields,setSlug:r.setSlug??null}}function FM(e,t){const n={v:1,brandId:e,updatedAt:new Date().toISOString(),tokens:t.tokens,tplFields:t.tplFields,setSlug:t.setSlug??null};xre(yu(e),JSON.stringify(n))}function o5(e){bh(yu(e))}function i5(e,t,n,r,a){if(e===t)return{changed:!1,toast:null};const i=!!r;return e===null&&!i?{changed:!0,toast:null}:{changed:!0,toast:{title:i?`Switched to ${n}. This starts a new shot instead of refining ${a??"that shot"}.`:`Switched to ${n}.`,prevSceneId:e,branchWasCleared:i}}}function Sre(e,t){return e>0&&t>0&&Math.abs(Math.log(t))<Math.abs(Math.log(e))-.01?"crop":"extend"}const r8=2,Ere=.15;function Cre(e,t){if(Sre(e,t)==="crop")return"crop";if(!(e>0&&t>0))return"extend";const n=t>e?t/e:e/t;return(n>r8?Math.max(r8,n*(1-Ere)):n)>r8+1e-9?"crop":"extend"}const F6=4,ep=24,v0=24,_M={product:[],presenter:[],scene:null,ref:[],color:[]};function jre(e){const t=[],n=[],r=[],a=[];let i=null;const l=(u,f)=>{u.includes(f)||u.push(f)};for(const u of e)u.t==="product"?l(t,u.id):u.t==="character"?l(n,u.id):u.t==="template"?i=u.id:u.t==="ref"?l(r,u.imageHash):u.t==="color"&&l(a,u.hex.toLowerCase());return{product:t,presenter:n,scene:i,ref:r,color:a}}function Are(e){return`${e.product.join(",")}|${e.presenter.join(",")}|${e.scene??""}|${e.ref.join(",")}|${e.color.join(",")}`}function Nre(e,t,n){const r=e.slice(0,n);return{visible:r,more:Math.max(0,e.length-r.length)}}const ew=s.forwardRef(function({projectId:t,brand:n,engines:r,parentId:a,initialBrief:i,suppressDraftRestore:l,startScene:u,startSetup:f,startPresenter:h,startProduct:p,onSeedsSpent:g,openAttachTab:v,onQueued:w,onSending:y,onAttached:x,onCeiling:k,target:S,onClearTarget:E,sourceImage:j,onRestoreBranchId:N,setSlug:P,persistDraft:$=!0,variant:M="dock",guided:C=!1},R){var dd,hl;const{products:T,productsLoaded:H}=on(),{demoProducts:D,demoProductsLoaded:K,loaded:O}=Rn(),Z=Rf(),te=Z.scenes,B=Z.presenters,F=vf(),X=Ec(),{push:z}=or(),I=r.filter(Ce=>Ce.available),[U,G]=fa(Dr.engine,H0);s.useEffect(()=>{const Ce=QY(I,U);Ce!==U&&G(Ce)},[I,U,G]);const ne=I.length===0&&r.some(Ce=>Ce.code==="not-installed"||Ce.code==="not-authenticated"),q=I.length===0,le=q?ne?{icon:o.jsx(KA,{}),title:"Image generation is not set up yet",detail:"About a minute, using the ChatGPT account you already have.",action:"Set up",onAct:()=>X(),info:!0}:{icon:o.jsx(R0,{size:15}),title:"No image provider connected",detail:"Add a provider key and this prompt is ready to run.",action:"Open settings",onAct:()=>F("engines"),info:!1}:null,[Se,Q]=s.useState(Oo()),[xe,ee]=s.useState(void 0),[ae,re,_]=kg(Dr.format,"square"),[ue,We]=s.useState({}),Xe=S&&S.kind!=="root"?S:null,ze=Xe?Ine(Xe.brief):void 0,tt=Xe?ue[Xe.id]??ze??ae:ae,ce=Ce=>{Xe?We(ht=>({...ht,[Xe.id]:Ce})):re(Ce)},[ve,Pe]=s.useState({}),[de,je,Ue]=kg(Dr.count,2),[ye,Ee]=s.useState(!1),[be,Le]=s.useState(null),[Qe,Ke]=s.useState(null),[nt,gt]=s.useState(!1),[Pt,Ut]=s.useState("All"),[Nt,cn]=s.useState(0),[Fe,pt]=s.useState(null),[it,St,xt]=kg(Dr.quality,"standard"),[At,Kt]=s.useState(!1),[et,mt]=s.useState(!1),ot=Ce=>mt(Ce);wr("(hover: hover) and (min-width: 1024px)");const kn=wr("(max-width: 767px)"),ut=s.useRef(null),Gt=s.useRef(null),Ft=s.useRef(null),en=s.useId(),Jt=s.useRef({tokens:Se,tplFields:ve,branchId:(S==null?void 0:S.id)??null});Jt.current={tokens:Se,tplFields:ve,branchId:(S==null?void 0:S.id)??null};const se=s.useRef(null),oe=s.useRef(null),we=s.useRef(void 0),ge=s.useRef(void 0),J=s.useRef(void 0),Oe=s.useCallback(Ce=>{if(oe.current&&(clearTimeout(oe.current),oe.current=null),!$)return;const ht=Jt.current;ht.branchId||(a5(ht.tokens,ht.tplFields)?FM(Ce,{tokens:ht.tokens,tplFields:ht.tplFields,setSlug:P}):o5(Ce))},[P,$]);s.useEffect(()=>{v&&(Ut(v),gt(!0))},[v]),s.useEffect(()=>{if(!i)return;const Ce=(i.tokens??[]).find(ht=>ht.t==="format");Ce&&_(Ce.id),i.variants&&Ue(i.variants),i.quality&&xt(i.quality),ee(Tv(i)),Pe(i.templateFields??{})},[i]),s.useEffect(()=>{var ps;const Ce=se.current;Ce&&Ce!==n.id&&Oe(Ce);const ht=!!i||!!l||!$,It=Ce!==n.id;let qt=null,fn=null;if(!ht&&It){const Xt=kre(n.id);Xt&&a5(Xt.tokens,Xt.tplFields)&&(qt=Xt.tokens,fn=Xt.tplFields)}let mn=!1;if(u&&u!==we.current){we.current=u,mn=!0;const Xt=qt??Oo(),Fn=Xt.find(xa=>xa.t==="template"),Tn=(Fn==null?void 0:Fn.id)??null,Ua=((ps=te.find(xa=>xa.id===u))==null?void 0:ps.name)??"this scene",Mc=i5(Tn,u,Ua,null,null);if(Mc.changed&&(qt=[{t:"template",id:u,...f?{setup:f}:{}},...Xt.filter(xa=>xa.t!=="template")],Mc.toast)){const xa=Mc.toast;z({kind:"info",title:xa.title,action:{label:"Undo",onClick:()=>{var Tf,$f;xa.prevSceneId?(Tf=ut.current)==null||Tf.insert({t:"template",id:xa.prevSceneId}):($f=ut.current)==null||$f.removeTemplate()}}})}}if(h&&h!==ge.current){ge.current=h,mn=!0;const Xt=qt??Oo();Xt.some(Tn=>Tn.t==="character"&&Tn.id===h)||(qt=[...Xt,{t:"character",id:h}])}if(p&&p!==J.current){J.current=p,mn=!0;const Xt=qt??Oo();Xt.some(Tn=>Tn.t==="product"&&Tn.id===p)||(qt=[...Xt,{t:"product",id:p}])}qt&&(ee(qt),Pe(fn??{})),mn&&(g==null||g()),se.current=n.id},[n.id,u,h,p]),s.useEffect(()=>{var Ce;xe&&((Ce=ut.current)==null||Ce.setTokens(xe),ee(void 0))},[xe]);const Be=s.useMemo(()=>{var fn;const Ce=Xr.find(mn=>mn.id===tt)??Xr[0],It=(((fn=Zi.find(mn=>mn.id===it))==null?void 0:fn.edge)??1024)/Math.max(Ce.w,Ce.h),qt=mn=>Math.max(256,Math.round(mn*It/8)*8);return{t:"format",id:Ce.id,w:qt(Ce.w),h:qt(Ce.h)}},[tt,it]),Ve=s.useMemo(()=>[Be,...Se],[Be,Se]),Ge=s.useMemo(()=>({tokens:Ve,templateFields:ve,variants:de,quality:it,format:tt}),[Ve,ve,de,it,tt]),me=Se.some(Ce=>Ce.t==="text"?!!Ce.v.trim():!0),_e=s.useMemo(()=>{const Ce=Se.find(ht=>ht.t==="template");return Ce?te.find(ht=>ht.id===Ce.id)??null:null},[Se,te]),W=s.useMemo(()=>{const Ce=Se.find(ht=>ht.t==="template");return(Ce==null?void 0:Ce.id)??null},[Se]),pe=s.useCallback(Ce=>{var mn,ps;const ht=(_e==null?void 0:_e.id)??null,It=(S==null?void 0:S.id)??null,qt=((mn=te.find(Xt=>Xt.id===Ce))==null?void 0:mn.name)??"this scene",fn=i5(ht,Ce,qt,It,S?Sr(S):null);if(fn.changed&&((ps=ut.current)==null||ps.insert({t:"template",id:Ce}),fn.toast)){const Xt=fn.toast;z({kind:"info",title:Xt.title,action:{label:"Undo",onClick:()=>{var Fn,Tn;Xt.prevSceneId?(Fn=ut.current)==null||Fn.insert({t:"template",id:Xt.prevSceneId}):(Tn=ut.current)==null||Tn.removeTemplate(),Xt.branchWasCleared&&It&&(N==null||N(It))}}})}},[_e,S,te,z,N]);s.useImperativeHandle(R,()=>({insertToken:Ce=>{var ht;return(ht=ut.current)==null?void 0:ht.insert(Ce)},removeToken:Ce=>{var ht;return(ht=ut.current)==null?void 0:ht.remove(Ce)},applyScene:Ce=>pe(Ce),removeTemplate:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.removeTemplate()},openAttach:Ce=>wa(Ce),showAttach:()=>{Eo.current||wa("All")},focus:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.focus()},submit:()=>{ui()}}));const Ie=s.useMemo(()=>jre(Se),[Se]),Te=Are(Ie),bt=Qne(Se),vt=s.useMemo(()=>Jne(bt),[bt]),Ct=s.useRef(Ie);Ct.current=Ie,s.useEffect(()=>{x==null||x(Ct.current)},[Te,x]),s.useEffect(()=>{var Ce;!O||!W||_e||((Ce=ut.current)==null||Ce.removeTemplate(),z({kind:"warning",title:"That scene is no longer available",detail:"Removed from the brief."}))},[O,W,_e,z]);const st=s.useRef(null);s.useEffect(()=>(oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>Oe(se.current??n.id),500),()=>{oe.current&&clearTimeout(oe.current)}),[Se,ve,S==null?void 0:S.id,n.id,Oe]),s.useEffect(()=>()=>Oe(se.current??n.id),[Oe]),s.useEffect(()=>{const Ce=()=>Oe(se.current??n.id);return window.addEventListener("beforeunload",Ce),()=>window.removeEventListener("beforeunload",Ce)},[Oe,n.id]);const $t=r.find(Ce=>Ce.id===U),An=$t?Bi($t.displayName):"This engine",Y=!!S&&S.kind!=="root"&&S.status==="running",he=S&&S.kind!=="root"&&S.status==="done"&&S.images.length>0||Y,Me=!!($t!=null&&$t.supportsEdit),dt=!!Xe&&!!ze&&ze!==tt&&he&&!_e,wt=dt?Cre(Bu(ze),Bu(tt)):null,Zt=wt==="crop",Ht=wt==="extend"&&Me,pn=Xr.find(Ce=>Ce.id===tt),Wt=pn?`${pn.label} ${pn.hint}`:tt,[wn,sn]=s.useState(null),In=()=>{S!=null&&S.images[0]&&sn({src:Mr(S.images[0]),kind:"shot",label:Sr(S),noun:"Refining this shot"})},Dt=he&&!_e&&(Me||Zt||Ht)?"edit":"generation",On=Dt==="edit"&&!!S&&M!=="overlay",Et=he?_e?"A scene starts a new shot.":Zt||Ht||Me?null:`${($t==null?void 0:$t.displayName)??"This engine"} cannot edit. This makes a new shot.`:null,Hn=s.useMemo(()=>{const Ce=Xr.find(mn=>mn.id===tt)??Xr[0],ht=`Aspect ${Ce.label} ${Ce.hint}`;if(Dt==="edit")return ht;const It=Zi.find(mn=>mn.id===it),qt=Qv(U),fn=qt==="ratio"||!It?null:qt==="advisory"?`${It.label}, asking for ${It.edge} px`:`${It.label} ${It.edge} px`;return[ht,`${de} shot${de===1?"":"s"}`,fn&&`resolution ${fn}`].filter(Boolean).join(", ")},[Dt,tt,de,it,U]),Ot=s.useRef(void 0),tn=s.useRef(void 0);s.useEffect(()=>{var qt;const Ce=he?(S==null?void 0:S.id)??null:null,ht=Ce!==Ot.current&&Ot.current!==void 0;Ot.current=Ce;const It=W!==tn.current;tn.current=W,!(!_e||!he)&&(ht&&!It&&Ce?(qt=ut.current)==null||qt.removeTemplate():E==null||E())},[_e,W,he,S,E]);const Vn=(Qe==null?void 0:Qe.warnings.filter(Ce=>Ce.includes("built around a product")))??[],ur=dt&&!me,Zr=Zt&&me,zn=!ye&&(me||ur)&&!Zr&&!!t&&!Y&&(Zt||!q),yn=q&&!Zt?"Image generation is not set up yet":ye?"Working on the last one":t?Y?"Wait for this version to finish, or press X to start a new shot":Zr?"This shape is reached by cropping, and a crop uses no words. Clear the prompt, or keep the current shape.":!me&&!ur?"Write a prompt first":null:"Still opening this brand";s.useEffect(()=>{const Ce=Dt==="edit"&&!!S;if(Zt||!me&&!Ce){Ke(null);return}st.current&&clearTimeout(st.current);const ht=Ge;return st.current=setTimeout(()=>{Re.previewBrief(Ge,U,n.id,Ce?S.id:void 0).then(It=>Ke({...It,forBrief:ht})).catch(()=>Ke(null))},280),()=>{st.current&&clearTimeout(st.current)}},[Ge,U,n.id,me,Dt,S,Zt]);const Va=Ce=>{var ht;ce(Ce),(ht=ut.current)==null||ht.focus()},ko=Ce=>{var ht;St(Ce),(ht=ut.current)==null||ht.focus()},So=Ce=>{var ht;je(Ce),(ht=ut.current)==null||ht.focus()},ul=Ce=>{var ht;Ce.preventDefault(),(ht=ut.current)==null||ht.focus()},wa=Ce=>{Ut(Ce),cn(ht=>ht+1),gt(!0)},Eo=s.useRef(!1);Eo.current=nt;const ya=s.useRef(wa);ya.current=wa;const ba=s.useCallback(({restore:Ce})=>{var ht;Eo.current&&(Eo.current=!1,gt(!1),Ce&&((ht=ut.current)==null||ht.restoreCaret()))},[]),Vr=s.useRef(pe);Vr.current=pe;const ts=s.useRef(Se);ts.current=Se;const Gs=s.useCallback(Ce=>{var It;const ht=Ce.token;ht.t==="template"?Vr.current(ht.id):(It=ut.current)==null||It.insert(ht)},[]),za=s.useCallback(Ce=>{var It,qt;const ht=Ce.token;ht.t==="template"?(It=ut.current)==null||It.removeTemplate():(qt=ut.current)==null||qt.remove(ht)},[]),Pr=async Ce=>{var It;if(!(Ce!=null&&Ce.length))return;const ht=Array.from(Ce).filter(qt=>qt.type.startsWith("image/"));if(!ht.length){z({kind:"warning",title:"Only images can be attached here"});return}Kt(!0),Le(null);try{for(const qt of ht.slice(0,4)){const fn=await P0(qt);(It=ut.current)==null||It.insert({t:"ref",imageHash:fn,label:Mre(qt.name)})}ht.length>4&&z({kind:"warning",title:"Only the first 4 images were attached",detail:`${ht.length-4} more ${ht.length-4===1?"was":"were"} skipped. Attach ${ht.length-4===1?"it":"them"} in another pick.`})}catch(qt){Le(String(qt.message??qt)),z(nn(qt,"Could not attach that image"))}finally{Kt(!1),Ft.current&&(Ft.current.value="")}},Lr=Qe&&Qe.forBrief===Ge?Qe:null,Ba=s.useMemo(()=>Se.filter(Ce=>l0.has(Ce.t)).length,[Se]),ci=s.useRef(null),ie=s.useMemo(()=>Ba===0?(ci.current=null,null):(Lr&&(ci.current={cap:Hne(Lr),described:One(Lr),preview:Lr}),ci.current),[Lr,Ba]),De=(ie==null?void 0:ie.cap)??null,Je=(ie==null?void 0:ie.preview)??null,Vt=($t==null?void 0:$t.displayName)??"This engine",Yt=Ba>=Xh?D6:null;s.useEffect(()=>{k==null||k(Yt)},[Yt,k]);const Bn=Ce=>{const ht=ie==null?void 0:ie.described;return!ht||ht.size===0?!1:Ce.t==="product"?ht.has(Fl("product",Ce.id)):Ce.t==="character"?ht.has(Fl("character",Ce.id)):Ce.t==="template"?ht.has(Fl("scene",Ce.id)):Ce.t==="ref"?ht.has(Fl("reference",Ce.imageHash)):Ce.t==="mark"?ht.has(Fl("brand",Ce.imageHash)):!1},Nn=De!=null?`Described in words: ${Vt} pictures ${De} per shot, products and presenters first. Drag it earlier to picture it.`:null,xn=_e?Vn.length>0?"This scene builds around a product. Attach one.":(Je==null?void 0:Je.warnings.some(Ce=>Ce.includes("built around a person")))??!1?"This scene builds around a person. Without a presenter, only the set renders.":null:null,Sn=Ce=>{var mn,ps;if(Ce.t==="template")return xn;if(Ce.t==="product"&&H&&K&&!((T.length?T:((mn=n.json)==null?void 0:mn.products)??[]).some(Tn=>Tn.id===Ce.id)||D.some(Tn=>Tn.id===Ce.id)))return"This product is no longer in your library. Remove it from the brief.";if(Ce.t==="mark"&&!xf(n.json).some(Xt=>Xt.hash===Ce.imageHash))return"This mark is no longer in your brand kit. Remove it from the brief.";if(!Je)return null;const ht=($t==null?void 0:$t.displayName)??"this engine",It=Je.cap,qt=Xt=>`${Xt} won't reach ${ht} this time.`,fn=(Xt,Fn)=>{var Tn;return((Tn=Je.dropped)==null?void 0:Tn.some(Ua=>Ua.role===Xt&&Ua.id===Fn&&Ua.reason==="missing"))??!1};if(Ce.t==="ref"&&!Je.attachments.some(Xt=>Xt.hash===Ce.imageHash))return It===0?`This reference won't reach ${ht}. Choose an engine that reads images, or remove it.`:It==null?qt("This reference"):null;if(Ce.t==="mark"&&!Je.attachments.some(Xt=>Xt.role==="brand"&&Xt.hash===Ce.imageHash))return It===0?`The brand mark won't reach ${ht}, so the logo can't be drawn from it. Choose an engine that reads images.`:It==null?`${qt("The brand mark")} The logo can't be drawn from it.`:null;if(Ce.t==="mark"){const Xt=Je.warnings.find(Fn=>Fn.includes("px across"));if(Xt)return Xt}if(Ce.t==="product"){const Fn=(T.length?T:((ps=n.json)==null?void 0:ps.products)??[]).find(Tn=>Tn.id===Ce.id)??D.find(Tn=>Tn.id===Ce.id);if(Fn&&!Je.attachments.some(Tn=>Tn.role==="product"&&Tn.id===Fn.id))return fn("product",Fn.id)?`${Fn.name} has no usable photo. Re-add one, or remove this.`:null}if(Ce.t==="character"){const Xt=B.find(Fn=>Fn.id===Ce.id);if(!Xt&&B.length>0)return"This presenter is no longer in your roster. Remove them from the brief.";if(Xt&&!Je.attachments.some(Fn=>Fn.role==="character"&&Fn.id===Xt.id))return fn("character",Xt.id)?`${Xt.name} has no usable photo. Re-add one, or remove this.`:null}return null},hs=s.useCallback(Sn,[Je,$t==null?void 0:$t.displayName,xn,T,H,n.json,D,K,B]),cd=s.useCallback(Bn,[ie]),ui=async()=>{var ht,It,qt;if(!zn)return;Ee(!0),Le(null);const Ce=Se.flatMap(fn=>fn.t==="text"?[fn.v]:[]).join(" ").replace(/\s+/g," ").trim();y==null||y({said:Ce||"Your shot",count:Dt==="generation"?de:1});try{if(!t)throw new Error("the workspace is still loading");const fn=await Re.addNode({projectId:t,parentId:Dt==="edit"&&S?S.id:a,kind:Dt,engineId:U,count:de,brief:Ge,...Dt==="edit"&&j?{sourceImage:j}:{},...Dt==="edit"&&wt?{reshape:wt}:{}}),mn=fn.warnings??[];mn.length===1?z({kind:"warning",title:"Sent, with one thing to know",detail:mn[0]}):mn.length>1&&z({kind:"warning",title:`Sent, with ${mn.length} things to know`,detail:mn.join(" ")}),(ht=ut.current)==null||ht.setTokens(Oo()),Pe({}),_(null),We({}),Ue(null),xt(null),$&&o5(n.id),w(fn.id,Dt,(It=fn.siblings)==null?void 0:It.map(ps=>ps.id),(qt=fn.siblings)!=null&&qt.length?fn.siblings:[fn])}catch(fn){const mn=String(fn.message??fn);Le(mn),z(nn(fn,"That did not send",$t==null?void 0:$t.displayName)),y==null||y(null)}finally{Ee(!1)}},di=(dd=Se.find(Ce=>Ce.t==="product"))==null?void 0:dd.id,dl=di?T.find(Ce=>Ce.id===di)??(((hl=n.json)==null?void 0:hl.products)??[]).find(Ce=>Ce.id===di)??D.find(Ce=>Ce.id===di)??null:null,Ac=dl?Cv(dl):null,ud=C?{brandId:n.id,products:Se.filter(Ce=>Ce.t==="product").length,presenters:Se.filter(Ce=>Ce.t==="character").length,scene:!!_e,others:Se.filter(Ce=>Ce.t==="color"||Ce.t==="ref"||Ce.t==="mark").length,words:Se.some(Ce=>Ce.t==="text"&&!!Ce.v.trim()),busy:ye,pickerOpen:nt,refining:Dt==="edit"&&!!S,engine:q?ne?"setup":"settings":"ready"}:null;s.useEffect(()=>{ud&&Fx(ud)}),s.useEffect(()=>{if(C)return()=>Fx(null)},[C]),s.useEffect(()=>{if(!C||!nt)return;const Ce=()=>ba({restore:!0});return window.addEventListener("scenri:guide-close-picker",Ce),()=>window.removeEventListener("scenri:guide-close-picker",Ce)},[C,nt,ba]),s.useEffect(()=>{if(!C)return;const Ce=ht=>{var mn;const{kind:It}=ht.detail,qt=It==="presenter"?"character":It==="scene"?"template":"product",fn=[...ts.current].reverse().find(ps=>ps.t===qt);fn&&((mn=ut.current)==null||mn.remove(fn))};return window.addEventListener("scenri:guide-take-back",Ce),()=>window.removeEventListener("scenri:guide-take-back",Ce)},[C]),s.useEffect(()=>{if(!E)return;const Ce=()=>E();return window.addEventListener("scenri:guide-clear-refine",Ce),()=>window.removeEventListener("scenri:guide-clear-refine",Ce)},[E]),s.useEffect(()=>{if(!C)return;const Ce=ht=>{const{tab:It}=ht.detail;pt(It??null),It&&ya.current(It)};return window.addEventListener("scenri:guide-picker",Ce),()=>{window.removeEventListener("scenri:guide-picker",Ce),pt(null)}},[C]);const[Ys,Nc]=s.useState(!1),fl=M==="overlay"&&(Ys||Se.some(Ce=>Ce.t==="text"&&!!Ce.v.trim()));return s.useEffect(()=>{M==="overlay"&&_x({engaged:fl})},[M,fl]),s.useEffect(()=>{if(M==="overlay")return()=>_x(null)},[M]),o.jsxs("div",{className:"sc-composer","data-guide":C?"compose":void 0,onPointerDownCapture:M==="overlay"&&!Ys?()=>Nc(!0):void 0,onKeyDownCapture:M==="overlay"&&!Ys?()=>Nc(!0):void 0,children:[o.jsx("input",{ref:Ft,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Ce=>void Pr(Ce.target.files)}),wn&&o.jsx(Uu,{src:wn.src,kind:wn.kind,label:wn.label,noun:wn.noun,onRestoreFocus:()=>{var Ce;return(Ce=ut.current)==null?void 0:Ce.restoreCaret()},onClose:()=>sn(null)}),nt&&o.jsx(fre,{brand:n,activeProductCategory:Ac,refining:On,full:Yt,initialTab:Pt,tabNonce:Nt,only:Fe,id:en,attached:vt,onUpload:()=>{var Ce;return(Ce=Ft.current)==null?void 0:Ce.click()},onFiles:Ce=>void Pr(Ce),onPick:Gs,onRemove:za,onClose:ba}),le&&o.jsx("div",{className:"sc-notes","data-guide-shape":C?"":void 0,children:le&&o.jsxs("div",{className:"sc-banner","data-tone":"action",children:[o.jsx("span",{className:"sc-banner-ic",children:le.icon}),o.jsxs("span",{className:"sc-banner-txt",children:[o.jsx("b",{children:le.title}),o.jsxs("small",{children:[le.detail,le.info&&o.jsxs(Hu,{children:[o.jsx(Ou,{children:o.jsx("button",{type:"button",className:"sc-note-info","aria-label":"What a ChatGPT account has to do with this",children:o.jsx(_p,{size:13})})}),o.jsxs(Iu,{className:"sc-note-pop",align:"start",sideOffset:8,width:"300px",children:[o.jsx("p",{children:"Codex CLI signs in with your ChatGPT account and makes the images there. Every plan includes some Codex usage, so how many images you get depends on the plan you are on."}),o.jsx("p",{children:"No ChatGPT account, or run out for now? Use your own key from an image provider instead."}),o.jsx("p",{className:"sc-note-pop-fine",children:"Scenri never sees your password or token. The sign-in happens in your browser and stays with Codex."}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>F("engines"),children:"Use a provider key instead"})]})]})]})]}),o.jsx("button",{type:"button",className:"sc-banner-act","data-primary":"","data-guide":C?"compose.engine":void 0,onClick:le.onAct,children:le.action})]})}),o.jsxs("div",{className:"sc-promptcard","data-guide-shape":C?"":void 0,children:[he&&(E||M==="overlay"&&Dt==="edit")&&o.jsxs("div",{className:"sc-target","data-note":Et?"":void 0,children:[o.jsx(pre,{target:S,onOpenImage:In,onClear:E}),Et&&o.jsx("small",{className:"sc-target-note",children:Et})]}),he&&!E&&Et&&!(M==="overlay"&&Dt==="edit")&&o.jsx("small",{className:"sc-target-note sc-target-note-alone",children:Et}),dt&&(Zt||Ht)&&o.jsxs("small",{className:"sc-reshape-hint","aria-live":"polite",children:[Zt?"Will crop to":"Will extend to"," ",Wt]}),o.jsx(Fne,{ref:ut,onChange:Q,brand:n,templates:te,presenters:B,demoProducts:D,onTemplatePick:pe,scenesSitOut:On,flag:hs,described:cd,describedNote:Nn,onInspect:Ce=>sn(Ce),onAttachRequest:Ce=>wa(Ce),activeProductCategory:Ac,placeholder:_e?"Add art direction, or run it as written":Dt==="edit"?"Say what to change about this shot":"What should we shoot? (use $ / @ #)",placeholderSm:_e||Dt==="edit"?void 0:"What should we shoot? ($ / @ #)",label:_e?"Art direction":Dt==="edit"?"What to change":"Shot brief",onSubmit:()=>void ui(),onDropFiles:Ce=>void Pr(Ce)}),o.jsxs("div",{className:"sc-prompt-row",children:[o.jsxs("div",{className:"sc-prompt-left",children:[o.jsx("button",{type:"button",ref:Gt,className:"sc-icon-btn sc-attach-toggle","data-guide":C?"compose.add":void 0,"aria-expanded":nt,"aria-controls":nt?en:void 0,"aria-label":"Add to shot",title:"Add a product, a presenter, a scene, a colour or an image",onClick:()=>nt?ba({restore:!1}):wa("All"),children:At?o.jsx(xr,{size:"1"}):o.jsx(cr,{size:16})}),I.length>1&&o.jsxs(Z7,{value:U,onValueChange:G,children:[o.jsxs(V7,{variant:"ghost",className:"sc-mini-sel",children:[o.jsx(R0,{size:14}),o.jsx("span",{className:"sc-mini-sel-t",children:$t?Bi($t.displayName):"Demo"})]}),o.jsx(z7,{children:I.map(Ce=>o.jsx(B7,{value:Ce.id,children:Bi(Ce.displayName)},Ce.id))})]})]}),o.jsxs("div",{className:"sc-prompt-right",children:[o.jsx(wre,{mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko,onCloseAutoFocus:ul,guided:C}),o.jsxs(Hu,{open:et,onOpenChange:ot,children:[o.jsx(Ou,{children:o.jsxs("button",{type:"button",className:"sc-var sc-more","aria-label":`Shot settings. ${Hn}`,"data-guide":C&&!kn?"compose.settings":void 0,children:[o.jsx(ov,{size:14}),"More"]})}),o.jsx(Iu,{className:"sc-morepop",align:"end",sideOffset:8,width:"300px",onOpenAutoFocus:Jv,onCloseAutoFocus:ul,children:o.jsx(IM,{mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko})})]}),o.jsx(yre,{guide:C&&kn?"compose.settings":void 0,mode:Dt,engineId:U,engineName:An,formatId:tt,onFormat:Va,count:de,onCount:So,quality:it,onQuality:ko}),o.jsxs("button",{type:"button",className:"sc-send","data-guide":C?"compose.send":void 0,"aria-disabled":!zn||void 0,onClick:()=>void ui(),"aria-label":Dt==="edit"?"Refine":"Generate",title:be??xn??yn??`${Dt==="edit"?"Refine":"Generate"} (enter)`,children:[o.jsx("span",{className:"sc-send-ico",children:ye?o.jsx(xr,{size:"1"}):o.jsx(iC,{size:17,weight:"bold"})}),o.jsx("span",{className:"sc-send-lb",children:Dt==="edit"?"Refine":"Generate"})]})]})]})]})]})});function Mre(e){return e.replace(/\.[a-z0-9]{2,5}$/i,"").trim()||"Image"}function tw(e,t){s.useLayoutEffect(()=>{if(!e||typeof ResizeObserver>"u")return;const n=document.documentElement,r=()=>n.style.setProperty(t,`${Math.round(e.offsetHeight)}px`);r();const a=new ResizeObserver(r);return a.observe(e),()=>{a.disconnect(),n.style.removeProperty(t)}},[e,t])}function ZM({full:e=!0,children:t}){const[n,r]=s.useState(null);return tw(n,"--sc-dock-h"),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-dock-fade","data-full":e,"aria-hidden":!0}),o.jsx("div",{className:"sc-canvas-dock","data-full":e,ref:r,children:t})]})}function nw(){const{brand:e}=on(),{tasks:t}=Za(),[n,r]=s.useState(null),[a,i]=s.useState(null),[l,u]=s.useState(()=>Date.now()),f=s.useRef({id:"",pct:0}),h=t.find(y=>y.kind==="catalog"&&y.state==="running");if(s.useEffect(()=>{if(!h)return;const y=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(y)},[h]),!h&&!a)return null;const p=h!=null&&h.id.startsWith("catalog:")?h.id.slice(8):null,g=h!=null&&n===h.id,v=eG(e.json),w=Fr(v==null?void 0:v.file);return h&&(f.current.id!==h.id&&(f.current={id:h.id,pct:0}),f.current.pct=Math.max(f.current.pct,h.percent??0)),o.jsxs(o.Fragment,{children:[h&&o.jsxs("div",{className:"sc-impbar",role:"status",style:{"--sc-impbar-p":`${f.current.pct}%`},children:[o.jsx("span",{className:"sc-impbar-fill","aria-hidden":!0}),o.jsxs("button",{type:"button",className:"sc-impbar-open",onClick:()=>p&&i(p),disabled:!p,"aria-label":"Show import details",children:[o.jsx("span",{className:"sc-impbar-mark","aria-hidden":!0,children:w?o.jsx("img",{src:w,alt:"",className:(v==null?void 0:v.role)==="mark"?"sc-impbar-badge":void 0}):o.jsx(pj,{size:13,weight:"regular"})}),o.jsx("span",{className:"sc-impbar-count",children:h.subtitle}),o.jsx("span",{className:"sc-impbar-clock",children:rc(h.startedAt,l)})]}),p&&o.jsxs("button",{type:"button",className:"sc-impbar-stop",disabled:g,"aria-label":"Stop importing",onClick:()=>{r(h.id),Re.cancelCatalogJob(e.id,p).catch(()=>r(null))},children:[o.jsx(jn,{size:12,weight:"bold"}),g?"Stopping":"Stop"]})]}),a&&o.jsx(p6,{brandId:e.id,jobId:a,onDismiss:()=>i(null)})]})}const Rre={presenter:"Presenter",product:"Product",scene:"Scene"};function VM({entry:e,productName:t,productPreviewUrl:n,productId:r,presenterName:a,presenterPreviewUrl:i,presenterId:l,sceneName:u,scenePreviewUrl:f,sceneId:h,onOpen:p,productHref:g,presenterHref:v,sceneHref:w,active:y,hideRecipe:x,decorative:k,size:S="grid"}){const E=[t,a,u].filter(Boolean).join(" · "),j=a?{key:"presenter",name:a,previewUrl:i,linked:!!(v&&l),href:v&&l?v(l):void 0}:null,N=n&&t?{key:"product",name:t,previewUrl:n,linked:!!(g&&r),href:g&&r?g(r):void 0}:null,P=f&&u?{key:"scene",name:u,previewUrl:f,linked:!!(w&&h),href:w&&h?w(h):void 0}:null;return o.jsxs("div",{className:"sc-showcase-tile","data-active":y||void 0,"aria-hidden":k||void 0,...k?{inert:""}:{},children:[o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.title,primary:e.title,secondary:x?"":E,useLabel:"Recreate this",variant:"use",onOpen:p,onUse:p,size:S}),(j||N||P)&&o.jsx(Lre,{presenter:j,product:N,scene:P})]})}function Pre(e){return o.jsx(Qp,{...e,caption:!1})}function Lre({presenter:e,product:t,scene:n}){const[r,a]=s.useState(null),i=[t,n].filter(Boolean),l=i.length+(e?1:0)+Math.max(0,i.length-1);let u=0;const f=()=>({"--i":u++});return o.jsxs("div",{className:"sc-showcase-chips",onMouseLeave:()=>a(null),children:[e&&o.jsx(l5,{credit:e,open:r==="presenter",onEnter:()=>a("presenter"),children:$re(e)}),i.length>0&&o.jsxs("div",{className:"sc-showcase-recipe",style:{"--n":l},children:[e&&o.jsx("span",{className:"sc-showcase-join",style:f(),"aria-hidden":!0}),i.map((h,p)=>o.jsxs(s.Fragment,{children:[p>0&&o.jsx("span",{className:"sc-showcase-join",style:f(),"aria-hidden":!0}),o.jsx(l5,{credit:h,open:r===h.key,onEnter:()=>a(h.key),style:f(),children:Tre({credit:h,step:p===0?1:2})})]},h.key))]})]})}function l5({credit:e,open:t,onEnter:n,children:r,style:a}){const i=s.useRef(null),l=s.useRef(null),[u,f]=s.useState(null),h=Ete(),p=h==="large"?144:88,g=h==="large"?168:112;if(s.useLayoutEffect(()=>{var S,E;if(!t||!e.previewUrl){f(null);return}const w=()=>{const j=i.current;if(!j)return;const N=j.getBoundingClientRect(),P=l.current,$=(P==null?void 0:P.offsetWidth)||p,M=(P==null?void 0:P.offsetHeight)||g,C=window.visualViewport,R=Hte(N,{width:(C==null?void 0:C.width)??window.innerWidth,height:(C==null?void 0:C.height)??window.innerHeight},{width:$,height:M});if(!R){f(null);return}f({left:Math.round(R.left),top:Math.round(R.top)})};w();const y=requestAnimationFrame(w),x=i.current,k=x?new ResizeObserver(w):null;return x&&k&&k.observe(x),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),(S=window.visualViewport)==null||S.addEventListener("resize",w),(E=window.visualViewport)==null||E.addEventListener("scroll",w),()=>{var j,N;cancelAnimationFrame(y),k==null||k.disconnect(),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w),(j=window.visualViewport)==null||j.removeEventListener("resize",w),(N=window.visualViewport)==null||N.removeEventListener("scroll",w)}},[t,e.previewUrl,e.key,p,g]),!e.previewUrl)return o.jsx("span",{ref:i,className:"sc-credit-tip",onPointerEnter:n,style:a,children:r});const v=Rre[e.key];return o.jsxs("span",{ref:i,className:"sc-credit-tip","data-open":t||void 0,onPointerEnter:n,style:a,children:[r,t&&Rr.createPortal(o.jsx("span",{ref:l,className:"sc-credit-tip-pop","data-size":h,style:u?{left:u.left,top:u.top}:{left:-9999,top:0},role:"tooltip","aria-label":`${v}: ${e.name}`,children:o.jsxs("span",{className:"sc-credit-tip-card",children:[o.jsx("img",{src:e.previewUrl,alt:""}),o.jsx("span",{className:"sc-credit-tip-name",children:e.name}),o.jsx("span",{className:"sc-credit-tip-role",children:v})]})}),document.body)]})}function Tre({credit:e,step:t}){const{name:n,previewUrl:r,linked:a,href:i}=e;return a&&i?o.jsx(_n,{className:"sc-showcase-chip",to:i,"data-link":!0,"data-step":t,"aria-label":`See ${n}`,onClick:l=>l.stopPropagation(),children:r?o.jsx("img",{src:r,alt:""}):null}):o.jsx("span",{className:"sc-showcase-chip","data-step":t,children:r?o.jsx("img",{src:r,alt:n}):o.jsx("span",{className:"sc-vh",children:n})})}function $re(e){const{name:t,previewUrl:n,linked:r,href:a}=e;return r&&a?o.jsxs(_n,{className:"sc-showcase-badge",to:a,"data-link":!0,"aria-label":`See ${t}`,onClick:i=>i.stopPropagation(),children:[n?o.jsx("img",{src:n,alt:""}):null,o.jsx("span",{className:"sc-showcase-badge-name",children:t})]}):o.jsxs("span",{className:"sc-showcase-badge","aria-hidden":!0,children:[n?o.jsx("img",{src:n,alt:""}):null,o.jsx("span",{className:"sc-showcase-badge-name",children:t})]})}function c5(e){return{key:"open-tab",icon:"open-tab",label:"Open in new tab",onSelect:()=>window.open(e,"_blank")}}function u5(e){return{key:"select",icon:"select",label:"Select",onSelect:e}}function Ji(e){if(e.only)return[{key:"only",icon:"use",label:e.only.label,onSelect:e.only.run}];if(e.draft){const n=[{key:"continue",icon:"continue",label:"Continue",onSelect:e.draft.onContinue}];return e.draft.href&&n.push(c5(e.draft.href)),e.select&&n.push(u5(e.select.run)),n.push({key:"discard",icon:"discard",label:"Discard",onSelect:e.draft.onDiscard,danger:!0,separated:!0}),n}const t=[];return e.onOpen&&t.push({key:"open",icon:"open",label:"Open",onSelect:e.onOpen}),e.href&&t.push(c5(e.href)),e.use&&t.push({key:"use",icon:"use",label:e.use.label,onSelect:e.use.run}),e.select&&t.push(u5(e.select.run)),e.keep&&t.push({key:"keep",icon:e.keep.on?"kept":"keep",label:e.keep.on?"Remove from Keepers":"Add to Keepers",onSelect:e.keep.run}),e.onRename&&t.push({key:"rename",icon:"rename",label:"Rename",onSelect:e.onRename}),e.onDuplicate&&t.push({key:"duplicate",icon:"duplicate",label:"Duplicate presenter",onSelect:e.onDuplicate}),e.onEdit&&t.push({key:"edit",icon:"edit",label:"Edit presenter",onSelect:e.onEdit}),e.remove&&t.push({key:"delete",icon:"delete",label:e.remove.label,onSelect:e.remove.run,danger:!0,separated:!0}),t}function qr(e,t){if(e==="draft")return{tool:"Discard",menu:t>1?`Discard ${t} drafts`:"Discard",icon:"discard",danger:!0};const n=e==="presenter"?"Delete presenter":e==="product"?"Delete product":"Delete scene",r=e==="presenter"?"presenters":e==="product"?"products":"scenes";return{tool:"Delete",menu:t>1?`Delete ${t} ${r}`:n,icon:"delete",danger:!0}}function pm(e,t,n){return{tool:t?"Remove from keepers":"Keep",menu:e>1?t?`Remove ${e} ${n} from Keepers`:`Add ${e} ${n} to Keepers`:t?"Remove from Keepers":"Add to Keepers",icon:t?"kept":"keep"}}function mm({kind:e,count:t,openLabel:n,onOpen:r,href:a,onDeselect:i,onAct:l,onKeep:u,allKept:f}){const h=qr(e,t),p=[{key:"open",icon:n==="Continue"?"continue":"open",label:n,onSelect:r}];if(a&&p.push({key:"open-tab",icon:"open-tab",label:"Open in new tab",onSelect:()=>window.open(a,"_blank")}),p.push({key:"deselect",icon:"select",label:t>1?"Deselect this":"Deselect",onSelect:i}),u&&e!=="draft"){const v=pm(t,!!f,e==="presenter"?"presenters":e==="product"?"products":"scenes");p.push({key:"keep",icon:v.icon,label:v.menu,onSelect:u})}return p.push({key:e==="draft"?"discard":"delete",icon:h.icon,label:h.menu,onSelect:l,danger:h.danger||void 0,separated:!0}),p}async function tp(e,t){const n=[];let r;for(const a of e)try{await t(a)}catch(i){if((i==null?void 0:i.status)===404)continue;n.push(a),r??(r=i)}return{failed:n,error:r}}function _6({presenter:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,onDuplicate:u,onEdit:f,onDelete:h,onRename:p,bookmarked:g,onBookmark:v,fresh:w,chosen:y,batching:x,onPick:k,batch:S,size:E="grid"}){const N=S?mm({kind:"presenter",count:S.count,openLabel:"Open",onOpen:()=>n==null?void 0:n(e.id),href:a,onDeselect:()=>k==null?void 0:k(e.id),onAct:S.onAct,onKeep:S.onKeep,allKept:S.allKept}):Ji(!a&&!r&&!!n?{only:{label:"Use in a shot",run:()=>n(e.id)}}:{onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,select:k?{run:()=>k(e.id)}:void 0,keep:v?{on:!!g,run:()=>v(e.id)}:void 0,onRename:p?()=>p(e.id):void 0,onDuplicate:u?()=>u(e.id):void 0,onEdit:f?()=>f(e.id):void 0,remove:h?{label:"Delete presenter",run:()=>h(e.id)}:void 0});return o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.descriptor||e.name,primary:e.name,secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,menu:N,bookmarked:g,onBookmark:v,fresh:w,chosen:y,batching:x,onPick:k,size:E})}function zM(e){return o.jsx(Qp,{...e})}function I0({scene:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,bookmarked:u,onBookmark:f,onDelete:h,onRename:p,chosen:g,batching:v,onPick:w,batch:y,size:x="grid"}){const S=y&&h?mm({kind:"owned-scene",count:y.count,openLabel:"Open",onOpen:()=>n==null?void 0:n(e.id),href:a,onDeselect:()=>w==null?void 0:w(e.id),onAct:y.onAct,onKeep:y.onKeep,allKept:y.allKept}):Ji(!a&&!r&&!!n?{only:{label:"Use in a shot",run:()=>n(e.id)}}:{onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,select:w?{run:()=>w(e.id)}:void 0,keep:f?{on:!!u,run:()=>f(e.id)}:void 0,onRename:p?()=>p(e.id):void 0,remove:h?{label:"Delete scene",run:()=>h(e.id)}:void 0});return o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:e.description||Qi(e,"tooltip"),primary:Qi(e,"card"),secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,bookmarked:u,onBookmark:f,menu:S,chosen:g,batching:v,onPick:w,size:x})}function BM(e){return o.jsx(Qp,{...e})}const pu=new Map,Dre=50;function Hre(e,t){for(pu.delete(e),pu.set(e,t);pu.size>Dre;)pu.delete(pu.keys().next().value)}function Ore(e){return pu.get(e)}const Ire=1e3;function is({className:e="sc-home",children:t}){const n=s.useRef(null),{key:r}=Zn(),a=s.useRef(!1);return s.useLayoutEffect(()=>{const i=n.current,l=Ore(r);if(!i||!l)return;let u=!1;const f=()=>{u||(u=!0,a.current=!1,p.disconnect(),clearTimeout(g),i.removeEventListener("wheel",f),i.removeEventListener("touchstart",f))},h=()=>{u||(i.scrollTop=l,Math.abs(i.scrollTop-l)<1&&f())};a.current=!0;const p=new ResizeObserver(h),g=setTimeout(f,Ire);return i.addEventListener("wheel",f,{passive:!0}),i.addEventListener("touchstart",f,{passive:!0}),h(),p.observe(i),i.firstElementChild&&p.observe(i.firstElementChild),f},[r]),s.useEffect(()=>{const i=n.current;if(!i)return;const l=()=>{a.current||Hre(r,i.scrollTop)};return i.addEventListener("scroll",l,{passive:!0}),()=>i.removeEventListener("scroll",l)},[r]),o.jsx("div",{ref:n,className:e,"data-page-scroll":"",children:t})}function gm({title:e,filters:t,active:n,summary:r,onClear:a,density:i,search:l,action:u}){return o.jsxs("div",{className:"sc-filterbar",children:[e?o.jsx("h1",{className:"sc-vh",children:e}):null,t,o.jsxs("div",{className:"sc-filterbar-actions",children:[n&&o.jsxs("span",{className:"sc-lib-count",children:[r,a&&o.jsx("button",{type:"button",className:"sc-lib-clear",onClick:a,children:"Clear"})]}),l,i,u?o.jsx("span",{className:"sc-filterbar-cta",children:u}):null]})]})}function vm({mode:e,group:t}){if(e==="none"||!t)return null;const n=[{value:null,label:t.everyLabel,count:t.everyCount},...t.options.map(r=>({value:r.value,label:r.label,count:r.count}))];return o.jsx(qv,{"aria-label":t.label,activeKey:t.selected,items:n,onSelect:t.onSelect})}function oo({shape:e,title:t,body:n,action:r,onRetry:a}){return e==="error"?o.jsxs(o.Fragment,{children:[o.jsx("h1",{children:t??"Couldn't load this library"}),o.jsx("p",{className:"sc-lookpage-lede",children:n}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:a,children:"Retry"})})]}):e==="cold"?o.jsxs("div",{className:"sc-canvas-empty",children:[t&&o.jsx("h3",{children:t}),o.jsx("p",{children:n}),r&&o.jsx("div",{className:"sc-lookpage-acts",children:r})]}):o.jsxs("div",{className:"sc-lib-zero",children:[o.jsx("p",{children:n}),r]})}function wm({noun:e,q:t,facet:n,onClearSearch:r,onClearAll:a}){const i=t.trim(),l=i?o.jsxs(o.Fragment,{children:["No ",e," found for ",o.jsxs("em",{children:["“",i,"”"]}),n?` in ${n}`:""]}):o.jsxs(o.Fragment,{children:["No ",e," in ",n]});return o.jsx(oo,{shape:"zero",body:l,action:o.jsxs("span",{className:"sc-lib-zero-acts",children:[i&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:r,children:"Clear search"}),i&&n&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Clear all"}),!i&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Clear filter"})]})})}const Fre=150;function Pf(e){const[t,n]=el(),r=t.get("q")??"",a=e.join(","),i=s.useMemo(()=>{const E={};for(const j of a.split(",").filter(Boolean))E[j]=t.get(j)||null;return E},[t,a]),l=s.useCallback(E=>{n(j=>{const N=new URLSearchParams(j);for(const[P,$]of Object.entries(E))$===null||$===""?N.delete(P):N.set(P,$);return N},{replace:!0})},[n]),[u,f]=s.useState(r),h=s.useRef(r),p=s.useRef(null),g=s.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]);s.useEffect(()=>{r!==h.current&&(h.current=r,g(),f(r))},[r,g]),s.useEffect(()=>g,[g]);const v=s.useCallback(E=>{f(E),g(),p.current=setTimeout(()=>{p.current=null,h.current=E,l({q:E||null})},Fre)},[l,g]),w=s.useCallback((E,j)=>l({[E]:j}),[l]),y=l,x=u.trim().length>0||Object.values(i).some(Boolean),k=s.useCallback(()=>{g(),f(""),h.current="",l({q:null})},[l,g]),S=s.useCallback(()=>{g(),f(""),h.current="";const E={q:null};for(const j of a.split(",").filter(Boolean))E[j]=null;l(E)},[l,g,a]);return{q:u,setQ:v,facets:i,setFacet:w,setFacets:y,active:x,clearSearch:k,clear:S}}const _re=8;function Zre(){var tt;const{engines:e,scenes:t,loaded:n,presenters:r,presentersLoaded:a,demoProducts:i,showcase:l,showcaseCategories:u,showcaseLoaded:f,showcaseError:h,refetchShowcase:p}=Rn(),{brand:g,workspace:v,root:w,products:y,applyNodes:x}=on(),{poke:k}=Za(),S=ll(),E=Dn(),{push:j}=or(),N=Wv(),P=im(),$=pte(),M=wr(Ks),{q:C,setQ:R,facets:T,setFacet:H,clearSearch:D,clear:K}=Pf(["category"]),O=T.category,Z=ce=>H("category",ce),te=C.trim().length>0,[B,F]=fa(Dr.wallDensity,zu),X=jc(B),z=ce=>F(ce),I=fm(X),U=um(X),G=ce=>{const ve=new URLSearchParams(ce??{}).toString();E(`${mr(g)}${ve?`?${ve}`:""}`)},ne=y.length?y:((tt=g.json)==null?void 0:tt.products)??[],q=ce=>{var je,Ue,ye;const ve=(je=ce.brief.tokens.find(Ee=>Ee.t==="product"))==null?void 0:je.id,Pe=(Ue=ce.brief.tokens.find(Ee=>Ee.t==="character"))==null?void 0:Ue.id,de=(ye=ce.brief.tokens.find(Ee=>Ee.t==="template"))==null?void 0:ye.id;return{product:ve?i.find(Ee=>Ee.id===ve):void 0,presenter:Pe?r.find(Ee=>Ee.id===Pe):void 0,scene:de?t.find(Ee=>Ee.id===de):void 0}},le=s.useMemo(()=>{const ce=new Map;for(const ve of l){const{product:Pe,presenter:de,scene:je}=q(ve);ce.set(ve.id,hte(ve,{product:Pe,presenter:de,scene:je},qg(ve.category)))}return ce},[l,i,r,t]),Se=s.useMemo(()=>(O?l.filter(ve=>ve.category===O):l).filter(ve=>wo(le.get(ve.id)??ve.title,C)),[l,O,C,le]),Q=s.useMemo(()=>{const ce=wte(u);return{key:"category",label:"Categories",everyLabel:"All examples",everyCount:l.length,selected:O,onSelect:Z,options:ce.map(ve=>({value:ve,label:qg(ve)??ve,count:l.filter(Pe=>Pe.category===ve).length}))}},[l,u,O,Z]),xe=ce=>{const{product:ve,presenter:Pe,scene:de}=q(ce);return{productName:ve?go(ve,"chip"):null,productPreviewUrl:(ve==null?void 0:ve.previewUrl)??null,productId:(ve==null?void 0:ve.id)??null,presenterName:(Pe==null?void 0:Pe.name)??null,presenterPreviewUrl:Pe?ti(Pe).src:null,presenterId:(Pe==null?void 0:Pe.id)??null,sceneName:de?Qi(de,"chip"):null,scenePreviewUrl:(de==null?void 0:de.previewUrl)??null,sceneId:(de==null?void 0:de.id)??null}},[ee,ae]=s.useState(null),_=M?$:ce=>{const ve=l.find(Pe=>Pe.id===ce);ve&&(ae(T6(ve)),j({kind:"info",title:`Starting from "${ve.title}"`}))},ue=()=>{const ve=[...vo(g.id)].reverse().find(Pe=>t.some(de=>de.id===Pe));G(ve?{scene:ve,attach:"products",compose:"1"}:{attach:"products",compose:"1"})},We=s.useMemo(()=>Oh(Sf(g),r).slice(0,8),[g,r]),Xe=s.useMemo(()=>{const ce=vo(g.id);return Oh(Cc(g),CM(t,ve=>ce.includes(ve.id))).slice(0,8)},[t,g]),ze=s.useMemo(()=>{var ye,Ee,be,Le,Qe;const ce=new Set,ve=Ke=>!Ke||ce.has(Ke)?null:(ce.add(Ke),sr(Ke,"tile")),Pe=Ke=>{for(const nt of Ke){const gt=l.find(Ut=>Ut.id===nt&&Ut.previewUrl),Pt=ve(gt==null?void 0:gt.previewUrl);if(Pt)return Pt}return null},de=Ke=>{for(const nt of Ke){const gt=t.find(Ut=>Ut.id===nt&&Ut.previewUrl),Pt=ve(gt==null?void 0:gt.previewUrl);if(Pt)return Pt}return null},je=Ke=>{for(const nt of l)if(!(!nt.previewUrl||ce.has(nt.previewUrl))&&!(Ke&&!nt.brief.tokens.some(gt=>gt.t===Ke)))return ve(nt.previewUrl);return null},Ue=ne.find(Ke=>{var nt,gt;return Fr((gt=(nt=Ke==null?void 0:Ke.shots)==null?void 0:nt[0])==null?void 0:gt.file)});return{compose:ve(Ue?Fr((Ee=(ye=Ue.shots)==null?void 0:ye[0])==null?void 0:Ee.file):null)??Pe(["aurelia-serum-succulent-dew","verity-pearls-suspended-silk","solstice-aviators-screen-print"])??ve((be=i.find(Ke=>Ke.id==="aurelia-amber-serum"))==null?void 0:be.previewUrl)??ve((Le=i.find(Ke=>Ke.previewUrl))==null?void 0:Le.previewUrl)??je("product"),product:Pe(["voss-rowe-runner-volcanic-ash","birchwood-salt-flat","voss-rowe-dune-slip-face"])??ve((Qe=i.find(Ke=>Ke.id==="voss-rowe-trail-runner"))==null?void 0:Qe.previewUrl)??je("product"),presenter:ve(ti(r.find(Ke=>Ke.id==="maren")??r.find(Ke=>Ke.avatarUrl)??r[0]??{}).src)??je("character"),scene:de(["furniture-travertine-atrium","wide-establishing-environment","studio-soft-horizon","studio-volcanic-ash-field","furniture-lamplight-hours"])??Pe(["moss-larkin-chair-travertine-atrium","calder-snow-loft","basalt-snells-window"])??je("template")}},[t,r,ne,i,l]);return o.jsx(Nf.Provider,{value:U,children:o.jsxs(is,{children:[o.jsxs("main",{className:"sc-main",id:"main","data-no-dock":M||void 0,children:[o.jsxs("h1",{className:"sc-greet",children:["Compose a shot ",o.jsx("em",{children:"on brand"})]}),o.jsxs("div",{className:"sc-create-grid",children:[o.jsxs("button",{type:"button",className:"sc-create-card","data-tone":"compose","data-main":"",onClick:ue,children:[o.jsx(UM,{thumbUrl:ze.compose,fallback:o.jsx(Y7,{size:22,weight:"fill"})}),o.jsx("b",{children:"Create an image"})]}),o.jsx(s8,{tone:"product",title:"Add a product",count:ne.length,thumbUrl:ze.product,icon:o.jsx(Zp,{size:22,weight:"fill"}),onClick:()=>S("product")}),o.jsx(s8,{tone:"presenter",title:"Create a presenter",thumbUrl:ze.presenter,icon:o.jsx(eW,{size:22,weight:"fill"}),onClick:()=>S("presenter")}),o.jsx(s8,{tone:"scene",title:"Create a scene",thumbUrl:ze.scene,icon:o.jsx(WU,{size:22,weight:"fill"}),onClick:()=>S("scene")})]}),!f&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":U,style:I,"aria-hidden":!0,children:o.jsx(Pre,{size:"grid",count:8})}),f&&h&&o.jsxs("p",{className:"sc-feed-empty",children:["Couldn't load the showcase gallery."," ",o.jsx("button",{type:"button",className:"sc-sec-more",onClick:()=>p(),children:"Retry"})]}),f&&!h&&l.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(gm,{filters:o.jsx(vm,{mode:"tabs",group:Q}),search:l.length>=_re&&o.jsx(id,{value:C,onChange:R,noun:"examples",total:l.length}),density:o.jsx(dm,{value:X,onChange:z})}),Se.length>0&&o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":U,style:I,children:Se.map(ce=>o.jsx(VM,{entry:ce,size:"grid",hideRecipe:!0,onOpen:_,productHref:ve=>la(g,ve),presenterHref:ve=>ha(g,ve),sceneHref:ve=>_r(g,ve),...xe(ce)},ce.id))}),Se.length===0&&(te?o.jsx(wm,{noun:"examples",q:C,facet:O?qg(O):null,onClearSearch:D,onClearAll:K}):o.jsx("p",{className:"sc-looks-empty",children:"No example carries that category yet."}))]}),!a&&o.jsx("div",{className:"sc-masonry","aria-hidden":!0,children:o.jsx(zM,{size:"grid",count:8})}),a&&We.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"sc-sec-head",children:[o.jsx("span",{className:"sc-sec-title",children:"Presenters"}),o.jsx(_n,{className:"sc-sec-more",to:qi(g),children:"Browse presenters"})]}),o.jsx("div",{className:"sc-masonry",children:We.map(ce=>o.jsx(_6,{presenter:ce,variant:"navigate",size:"grid",onOpen:N},ce.id))})]}),!n&&o.jsx("div",{className:"sc-masonry","aria-hidden":!0,children:o.jsx(BM,{size:"grid",count:8})}),n&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"sc-sec-head",children:[o.jsx("span",{className:"sc-sec-title",children:"Scenes"}),o.jsx(_n,{className:"sc-sec-more",to:_u(g),children:"Browse scenes"})]}),o.jsx("div",{className:"sc-masonry",children:Xe.map(ce=>o.jsx(I0,{scene:ce,variant:"navigate",size:"grid",onOpen:P},ce.id))})]})]}),!M&&o.jsxs(ZM,{children:[o.jsx(nw,{}),o.jsx(ew,{projectId:(v==null?void 0:v.id)||null,brand:g,engines:e,parentId:w,initialBrief:ee,onQueued:(ce,ve,Pe,de)=>{de!=null&&de.length&&x(de),k(),E(mr(g))}})]})]})})}function s8({tone:e,title:t,icon:n,count:r,thumbUrl:a,onClick:i}){return o.jsxs("button",{type:"button",className:"sc-create-card","data-tone":e,onClick:i,children:[o.jsx(UM,{thumbUrl:a,fallback:n}),o.jsxs("b",{children:[t,r?o.jsx(M7,{variant:"soft",radius:"full",size:"1",children:r}):null]})]})}function UM({thumbUrl:e,fallback:t}){return o.jsx("span",{className:"sc-glyph","data-photo":e?"":void 0,"aria-hidden":!0,children:e?o.jsx("span",{className:"sc-glyph-shot",children:o.jsx("img",{src:e,alt:"",loading:"lazy"})}):t})}function WM({id:e,name:t,hash:n,drawing:r,state:a,href:i,blank:l,onDiscard:u,chosen:f,batching:h,onPick:p,batch:g}){const v=Dn(),w=yv(),y=g?mm({kind:"draft",count:g.count,openLabel:"Continue",onOpen:()=>v(i),href:i,onDeselect:()=>p==null?void 0:p(e),onAct:g.onAct}):Ji(u?{draft:{onContinue:()=>v(i),href:i,onDiscard:()=>u(e)},select:p?{run:()=>p(e)}:void 0}:{onOpen:()=>v(i),href:i}),x=o.jsxs("div",{className:"sc-lookcard","data-variant":"plain","data-size":"grid","data-build":!0,"data-building":r||void 0,"data-picked":f||void 0,"data-batching":h||void 0,children:[o.jsxs(_n,{className:"sc-lookcard-media",to:i,"aria-label":h?`${f?"Deselect":"Select"} ${t}`:`Continue ${t}`,onClick:k=>{h&&p&&(k.preventDefault(),p(e))},children:[n?o.jsx("img",{src:dn(n,"tile"),alt:""}):o.jsx("span",{className:"sc-lookcard-blank",children:l}),r&&o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}),o.jsx("span",{className:"sc-draftmark",children:"Draft"})]}),p&&o.jsx("button",{type:"button",className:"sc-cell-ctl sc-lookcard-pick","data-on":f||void 0,"aria-pressed":!!f,"aria-label":f?`Deselect ${t}`:`Select ${t}`,onClick:k=>{k.preventDefault(),k.stopPropagation(),p(e)},children:o.jsx(Kn,{size:13,weight:"bold"})}),u&&!h&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Discard ${t}`,onClick:()=>u(e),children:o.jsx(jn,{size:13})}),o.jsxs("span",{className:"sc-lookcard-cap",children:[o.jsx("b",{dir:"auto",children:t}),o.jsx("span",{children:a})]})]});return w?x:o.jsxs(ff,{children:[o.jsx(hf,{children:x}),o.jsx(pf,{children:y.map(k=>o.jsxs("span",{style:{display:"contents"},children:[k.separated&&o.jsx(Hp,{}),o.jsxs(mf,{color:k.danger?"red":void 0,onSelect:k.onSelect,children:[o.jsx(Sv,{name:k.icon}),k.label]})]},k.key))})]})}function rw({title:e,name:t,maxLength:n,busy:r,error:a,onConfirm:i,onDismiss:l}){const[u,f]=s.useState(t),h=s.useRef(null),p=s.useRef(!1),g=u.trim(),v=g.length>0,w=x=>{x&&(x.style.height="auto",x.style.height=`${x.scrollHeight}px`)};s.useEffect(()=>{p.current=!1,w(h.current)},[t]),s.useEffect(()=>{r||(p.current=!1)},[r]);const y=()=>{if(!(!v||r||p.current)){if(g===t.trim())return l();p.current=!0,i(g)}};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(420px, 94vw)",onDismiss:l,onOpenAutoFocus:x=>{x.preventDefault();const k=h.current;k&&(k.focus(),k.select(),w(k))},children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:e}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("textarea",{ref:h,className:"sc-pdetails-field",value:u,dir:"auto",rows:1,maxLength:n,"aria-label":"Name",onChange:x=>{f(x.target.value),w(x.currentTarget)},onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),y())}})]}),a&&o.jsx("p",{className:"sc-assetform-err",children:a})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:l,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!v||r,"data-busy":r||void 0,onClick:y,children:r?"Saving":"Save"})]})]})}function KM({since:e}){const[t,n]=s.useState(Date.now());return s.useEffect(()=>{const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[]),o.jsx("span",{className:"sc-cell-tag",role:"status","aria-label":`${gv(e,t)}, ${rc(e,t)}`,children:rc(e,t)})}function Vre({build:e,onCancel:t,onRetry:n,onDismiss:r}){const a=e.stage==="failed",i=a?kf(e.error):null;return o.jsxs("div",{className:"sc-lookcard","data-variant":"plain","data-size":"grid","data-build":a||void 0,"data-building":!a||void 0,children:[o.jsxs("div",{className:"sc-lookcard-media",children:[o.jsx("span",{className:"sc-lookcard-blank"}),!a&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"sc-shimmer"}),o.jsx(KM,{since:e.startedAt})]}),!a&&t&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Stop building ${e.name}`,onClick:()=>t(e.id),children:o.jsx(jn,{size:13})}),a&&r&&o.jsx("button",{type:"button",className:"sc-cardpuck","aria-label":`Dismiss ${e.name}`,onClick:()=>r(e.id),children:o.jsx(jn,{size:13})}),a&&n&&o.jsxs("button",{type:"button",className:"sc-lookcard-use",onClick:()=>n(e),children:[o.jsx(eC,{size:12})," Try again"]})]}),i?o.jsxs("span",{className:"sc-lookcard-cap",title:i.raw,children:[o.jsx("b",{dir:"auto",children:e.name}),o.jsx("span",{children:i.title})]}):null]})}function sw({count:e,loaded:t,tool:n,icon:r,danger:a,onAct:i,keep:l,onClear:u,onSelectAll:f}){return o.jsxs("div",{className:"sc-picked",role:"toolbar","aria-label":"Selection",children:[o.jsxs("span",{className:"sc-picked-meta",children:[o.jsxs("span",{className:"sc-picked-n",role:"status",children:[e,o.jsx("span",{className:"sc-vh",children:" selected"})]}),t>1&&o.jsx("button",{type:"button",className:"sc-picked-all",onClick:e<t?f:u,children:e<t?"Select all":"Deselect all"})]}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsxs("span",{className:"sc-picked-tools",children:[l&&o.jsx(a8,{label:l.label,onClick:l.onAct,children:o.jsx(po,{size:17,weight:l.filled?"fill":"regular"})}),o.jsx(a8,{label:n,tone:a?"danger":void 0,onClick:i,children:o.jsx(zre,{name:r})})]}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsx("span",{className:"sc-picked-exit",children:o.jsx(a8,{label:"Done",onClick:u,children:o.jsx(jn,{size:16,weight:"bold"})})})]})}function zre(e){return o.jsx(il,{size:17})}function a8({label:e,tone:t,onClick:n,children:r}){return o.jsx(lr,{label:e,children:o.jsx("button",{type:"button",className:"sc-picked-tool","data-tone":t,"aria-label":e,onClick:n,children:r})})}const qd=()=>({kind:null,ids:new Set});function aw(e){const[t,n]=s.useState(qd),r=s.useCallback(()=>n(qd()),[]);s.useEffect(()=>{r()},[e,r]),s.useEffect(()=>{if(t.ids.size===0)return;const p=g=>{g.defaultPrevented||g.key!=="Escape"||r()};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[t.ids.size,r]);const a=s.useCallback((p,g)=>{n(v=>{if(v.kind&&v.kind!==p)return v;const w=new Set(v.ids);return w.has(g)?w.delete(g):w.add(g),w.size?{kind:v.kind??p,ids:w}:qd()})},[]),i=s.useCallback((p,g)=>{n({kind:p,ids:new Set(g)})},[]),l=s.useCallback(p=>{const g=new Set(p);n(v=>{const w=new Set([...v.ids].filter(y=>g.has(y)));return w.size?{kind:v.kind,ids:w}:qd()})},[]),u=s.useCallback(p=>{n(g=>{if(!g.ids.has(p))return g;const v=new Set(g.ids);return v.delete(p),v.size?{kind:g.kind,ids:v}:qd()})},[]),f=s.useCallback(p=>{t.ids.size===0||p.target.closest(".sc-lookcard, .sc-picked, button, a, input, select, textarea, label, [role], [contenteditable]")||r()},[t.ids.size,r]),h=s.useCallback(p=>t.kind===null||t.kind===p,[t.kind]);return{kind:t.kind,ids:t.ids,toggle:a,selectAll:i,clear:r,retain:l,forget:u,onBlank:f,picking:h,batching:t.kind}}function ow({label:e}){return o.jsx("div",{className:"sc-starter-rule",children:o.jsx("span",{children:e})})}const o8=60;function iw(e,t){const[n,r]=s.useState(o8);s.useEffect(()=>{r(o8)},[t]);const{visible:a,remaining:i}=Yv(e,n),l=s.useCallback(()=>r(u=>u+o8),[]);return{visible:a,remaining:i,showMore:l}}const Bre=24,Ure=8,i8="__bookmarked";function Wre(){const{scenes:e,collections:t,verticals:n,loaded:r,error:a,refetch:i,applyBrand:l,refreshBrands:u}=Rn(),{brand:f}=on(),{push:h}=or(),p=Dn(),[g,v]=s.useState(()=>vo(f.id)),w=J=>v(cm("scene",f.id,J)),y=im(),{builds:x,poke:k,studio:S}=Za(),E=ll(),j=s.useMemo(()=>Cc(f),[f]),N=x.filter(J=>J.kind==="scene"&&(!J.finished||J.stage==="failed")),P=!!un({path:ct.sceneStudio}),[$,M]=s.useState(()=>gh(f.id)),C=S.filter(J=>J.kind==="scene").map(J=>`${J.id}:${J.status}`).join("|");s.useEffect(()=>{P||M(gh(f.id))},[P,f.id,C]);const R=s.useMemo(()=>Oee($,S),[$,S]),[T,H]=s.useState(null),D=J=>{J.drawing&&J.jobId&&Re.cancelSceneStudioJob(f.id,J.jobId).catch(()=>{}),Fee(f.id,J.convo),M(gh(f.id))},K=J=>{const Oe=R.find(Be=>Be.convo===J);Oe&&(Oe.hash||Oe.drawing?H(Oe):D(Oe))},{q:O,setQ:Z,facets:te,setFacets:B,clearSearch:F,clear:X}=Pf(["vertical","bookmarked"]),z=te.vertical,I=te.bookmarked==="1",U=aw(`${f.id}|${O}|${z??""}|${I?"1":""}`),G=O.trim().length>0,[ne,q]=fa(Dr.wallDensity,zu),le=jc(ne),Se=J=>q(J),Q=fm(le),xe=um(le),ee=J=>p(_r(f,J)),[ae,re]=s.useState(null),[_,ue]=s.useState(!1),[We,Xe]=s.useState(null),[ze,tt]=s.useState(!1),[ce,ve]=s.useState(null),[Pe,de]=s.useState(!1),je=s.useCallback(J=>{const Oe=j.find(Be=>Be.id===J);Oe&&re(Oe)},[j]),Ue=s.useCallback(J=>{const Oe=j.find(Be=>Be.id===J);Oe&&(ve(null),Xe(Oe))},[j]),ye=async J=>{if(!(!We||ze)){tt(!0),ve(null);try{l((await Re.updateScene(f.id,We.id,{name:J})).brand),Xe(null)}catch(Oe){const Be=nn(Oe,"Could not rename this scene");ve([Be.title,Be.detail].filter(Boolean).join(" "))}finally{tt(!1)}}},Ee=async()=>{if(!(!ae||_)){ue(!0);try{l((await Re.deleteScene(f.id,ae.id)).brand),U.forget(ae.id),re(null)}catch(J){(J==null?void 0:J.status)===404?(await u(),U.forget(ae.id),re(null)):h(nn(J,"Could not delete this scene"))}finally{ue(!1)}}},be=s.useMemo(()=>I?e.filter(J=>g.includes(J.id)):z?e.filter(J=>J.verticals.includes(z)):e,[e,z,I,g]),Qe=!(j.length>0||N.length>0||R.length>0),Ke=[...e,...j].reduce((J,Oe)=>J+(g.includes(Oe.id)?1:0),0),nt=I&&Ke===0,gt=nt&&Qe,Pt=nt&&!Qe,Ut=G||I&&!gt,Nt=s.useMemo(()=>gt?e:be,[gt,e,be]),cn=s.useMemo(()=>Nt.filter(J=>wo(Gh(J),O)),[Nt,O]),[Fe,pt]=s.useState(()=>new Set),{visible:it,remaining:St,showMore:xt}=iw(cn,`${z??""}|${I?"bookmarked":""}|${gt?"browse":""}|${O}`),At=J=>[...j,...e].filter(Oe=>!Oe.verticals.length||Oe.verticals.includes(J)).length,Kt=[{value:i8,label:"Keepers",count:Ke},...n.map(J=>({value:J,label:J,count:At(J)}))],et=e.length>0?"tabs":"none",mt={key:"vertical",label:"Vertical",everyLabel:"All scenes",everyCount:e.length+j.length,selected:I?i8:z,onSelect:J=>B(J===i8?{bookmarked:"1",vertical:null}:{bookmarked:null,vertical:J}),options:Kt},ot=s.useMemo(()=>j.filter(J=>z?!J.verticals.length||J.verticals.includes(z):!0).filter(J=>wo(Gh(J),O)).filter(J=>I?g.includes(J.id):!0),[j,z,O,I,g]),kn=I?ot.length>0:R.length>0||N.length>0||ot.length>0,ut=()=>{U.ids.size===1?je([...U.ids][0]):de(!0)},Gt=[...U.ids],Ft=Gt.length>0&&Gt.every(J=>g.includes(J)),en=()=>v(Kv("scene",f.id,Gt,!Ft)),Jt=pm(U.ids.size,Ft,"scenes"),se=async()=>{if(_)return;const J=[...U.ids];ue(!0);try{const{failed:Oe,error:Be}=await tp(J,Ve=>Re.deleteScene(f.id,Ve));await u(),U.retain(Oe),de(!1),Be&&h(nn(Be,"Could not delete these scenes"))}finally{ue(!1)}},oe=o.jsxs("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>E("scene"),children:[o.jsx(cr,{size:12})," Create scene"]}),we=(J,Oe=!1)=>o.jsx("div",{className:"sc-masonry","data-wall":Oe||void 0,"data-density":!0,"data-density-size":xe,style:Q,children:J.map(Be=>o.jsx(I0,{scene:Be,variant:"use",size:"grid",onOpen:ee,href:_r(f,Be.id),onUse:y,bookmarked:g.includes(Be.id),onBookmark:w},Be.id))}),ge=o.jsx(gm,{title:"Scenes",filters:o.jsx(vm,{mode:et,group:mt}),density:o.jsx(dm,{value:le,onChange:Se}),search:e.length>=Ure&&o.jsx(id,{value:O,onChange:Z,noun:"scenes",total:e.length})});return o.jsxs(Nf.Provider,{value:xe,children:[o.jsx(is,{children:o.jsxs("main",{className:"sc-looks sc-scenes",id:"main","data-hero":Qe||void 0,onClick:U.onBlank,children:[!Qe&&ge,kn&&o.jsxs("section",{className:"sc-owned",children:[o.jsx("div",{className:"sc-sec-head",children:o.jsx("h2",{className:"sc-sec-title",children:"Your scenes"})}),o.jsxs("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":xe,style:Q,children:[!I&&R.map(J=>o.jsx(WM,{id:J.convo,name:J.name||"Untitled scene",hash:J.hash,drawing:J.drawing,state:Iee(J),href:Vi(f,J.convo),blank:o.jsx(gj,{size:44,weight:"thin"}),onDiscard:K},J.convo)),T&&o.jsx(Wn,{label:"Discard",title:`Discard ${T.name||"this unfinished scene"}?`,body:T.drawing?"The picture being drawn is stopped, and what was drawn here is thrown away. Nothing was saved to the library.":"What was drawn here is thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:J=>{J||H(null)},onConfirm:()=>{D(T),H(null)}}),!I&&N.map(J=>o.jsx(Vre,{build:J,onCancel:Oe=>void Re.cancelAssetBuild(f.id,Oe).then(k),onDismiss:Oe=>void Re.deleteAssetBuild(f.id,Oe).then(k),onRetry:()=>E("scene")},J.id)),ot.map(J=>o.jsx(I0,{scene:J,variant:"use",size:"grid",onOpen:ee,href:_r(f,J.id),onUse:y,bookmarked:g.includes(J.id),onBookmark:w,onDelete:je,onRename:Ue,chosen:U.ids.has(J.id),batching:U.batching==="owned-scene",onPick:U.picking("owned-scene")?Oe=>U.toggle("owned-scene",Oe):void 0,batch:U.kind==="owned-scene"&&U.ids.has(J.id)?{count:U.ids.size,onAct:ut,onKeep:en,allKept:Ft}:null},J.id))]}),We&&o.jsx(rw,{title:"Rename scene",name:We.name,maxLength:60,busy:ze,error:ce,onConfirm:J=>void ye(J),onDismiss:()=>{ze||Xe(null)}}),ae&&o.jsx(Wn,{label:"Delete scene",title:`Delete ${ae.name}?`,body:"Shots already made here keep their images and their recipe. Only future shots lose it.",open:!0,busy:_,onOpenChange:J=>{!J&&!_&&re(null)},onConfirm:()=>void Ee()}),Pe&&o.jsx(Wn,{label:qr("owned-scene",U.ids.size).menu,title:`${qr("owned-scene",U.ids.size).menu}?`,body:"Shots already made here keep their images and their recipe. Only future shots lose it.",open:!0,busy:_,onOpenChange:J=>{!J&&!_&&de(!1)},onConfirm:()=>void se()})]}),Qe&&r&&!a&&e.length>0&&o.jsx(oo,{shape:"cold",title:o.jsxs(o.Fragment,{children:["Build your own ",o.jsx("em",{children:"scene"})]}),body:"Upload a few references of a place, or describe it, and its light and materials carry into every image you make.",action:oe}),kn&&r&&!a&&be.length>0&&o.jsx("div",{className:"sc-sec-head sc-owned-divider",children:o.jsx("h2",{className:"sc-sec-title",children:"Scenri scenes"})}),Qe&&r&&!a&&e.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(ow,{label:"Or start from one of ours"}),ge]}),!r&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":xe,style:Q,"aria-hidden":!0,children:o.jsx(BM,{size:"grid",count:8})}),r&&a&&o.jsx(oo,{shape:"error",title:"Couldn't load this library",body:"Something went wrong reaching the catalog.",onRetry:()=>i()}),r&&!a&&!Ut&&t.map(J=>{const Oe=Nt.filter(Ge=>Ge.collections.includes(J));if(!Oe.length)return null;const Ve=Fe.has(J)?Oe:Oe.slice(0,Bre);return o.jsxs("section",{className:"sc-coll",children:[o.jsx("h2",{children:J}),we(Ve),Ve.length<Oe.length&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>pt(Ge=>new Set(Ge).add(J)),children:["Show all ",Oe.length]})})]},J)}),r&&!a&&Ut&&it.length>0&&we(it,!0),r&&!a&&Pt&&o.jsx(oo,{shape:"zero",body:"Nothing in Keepers yet. Add a scene to Keepers from its card and it stays here.",action:o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>B({bookmarked:null}),children:"Browse every scene"})}),r&&!a&&e.length>0&&!Pt&&cn.length===0&&ot.length===0&&o.jsx(wm,{noun:"scenes",q:O,facet:gt?null:I?"Keepers":z,onClearSearch:F,onClearAll:X}),Ut&&St>0&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:xt,children:["Show ",Math.min(St,60)," more"]})})]})}),o.jsx(uc,{}),U.kind==="owned-scene"&&U.ids.size>0&&o.jsx("div",{className:"sc-wall-dock",children:o.jsx(sw,{count:U.ids.size,loaded:ot.length,tool:qr("owned-scene",U.ids.size).tool,icon:qr("owned-scene",U.ids.size).icon,danger:!0,onAct:ut,keep:{label:Jt.tool,filled:Ft,onAct:en},onClear:U.clear,onSelectAll:()=>U.selectAll("owned-scene",ot.map(J=>J.id))})})]})}function lw(e,t,n=12){const r=t.filter(Boolean).join(","),[a,i]=s.useState({key:"",items:[]});return s.useEffect(()=>{if(!r)return;const l=new AbortController;return Re.feed(e,{token:r,limit:n},l.signal).then(u=>{l.signal.aborted||i({key:r,items:u.items.filter(f=>f.status==="done"&&f.images.length>0)})}).catch(()=>{}),()=>l.abort()},[e,r,n]),a.key===r?a.items:[]}const Z6=[{id:"top-down",label:"Top down",camera:"Directly overhead, looking straight down, the subject centred, deep focus"},{id:"eye-level",label:"Eye level",camera:"Eye level, the subject at a natural three-quarter angle, medium depth"},{id:"ground",label:"Ground level",camera:"Ground level, camera low, the subject close and large in frame, the place rising behind it"},{id:"wide",label:"Wide",camera:"A wide view, the subject small in the frame, the place around it doing the talking"},{id:"close",label:"Close",camera:"Close in on the subject, its surface, edge and material filling the frame"}],GM=4;function Kre(e,t=""){var u,f;const n=[],r=((u=e.refs)==null?void 0:u.length)??0;r>0&&n.push(`read from ${r} ${r===1?"photograph":"photographs"}`);const a=((f=e.setups)==null?void 0:f.length)??0;a>0&&n.push(`${a} ${a===1?"way":"ways"} to shoot it`);const i=n.join(" · "),l=i?`${i.charAt(0).toUpperCase()}${i.slice(1)}.`:"";return[t.trim(),l].filter(Boolean).join(" ")}function Gre({items:e,placeholder:t,open:n,hit:r,onRemove:a,onOpen:i}){return o.jsxs("div",{className:"sc-chipfield","data-state":n?"open":void 0,children:[r,o.jsxs("span",{className:"sc-chipfield-row",children:[e.length===0&&t?o.jsx("span",{className:"sc-chipfield-ph",children:t}):null,e.map(l=>o.jsxs("span",{className:"sc-chipfield-chip",onClick:()=>i==null?void 0:i(),children:[l,a&&o.jsx("button",{type:"button","data-role":"remove","aria-label":`Remove ${l}`,onPointerDown:u=>u.stopPropagation(),onClick:u=>{u.preventDefault(),u.stopPropagation(),a(l)},children:o.jsx(jn,{size:10,weight:"bold"})})]},l))]}),o.jsx(Yi,{size:13,className:"sc-chipfield-caret","aria-hidden":!0})]})}function Yre({value:e,onChange:t,options:n,label:r,placeholder:a="Any",findPlaceholder:i="Find or add",emptyNote:l="Nothing by that name.",max:u=12,maxLength:f=40}){const[h,p]=s.useState(!1),[g,v]=s.useState(""),w=s.useRef(null),y=[...n,...e.filter(P=>!n.some($=>tu($,P)))],x=g.trim(),k=x?y.filter(P=>P.toLowerCase().includes(x.toLowerCase())):y,S=e.length>=u,E=x.length>0&&!y.some(P=>tu(P,x))&&!S,j=P=>{const $=e.some(M=>tu(M,P));!$&&S||t($?e.filter(M=>!tu(M,P)):[...e,P])},N=()=>{var P;E&&(t([...e,x.slice(0,f)]),v(""),(P=w.current)==null||P.focus())};return s.useEffect(()=>{if(!h)return;const P=setTimeout(()=>{var $;return($=w.current)==null?void 0:$.focus()},0);return()=>clearTimeout(P)},[h]),o.jsxs(Ss,{open:h,onOpenChange:P=>{p(P),P||v("")},children:[o.jsx(Gre,{items:e,placeholder:a,open:h,onOpen:()=>p(!0),onRemove:P=>t(e.filter($=>!tu($,P))),hit:o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-chipfield-hit","aria-label":r})})}),o.jsxs(Cs,{align:"start",sideOffset:6,className:"sc-menu sc-chippick-menu",children:[o.jsx("input",{ref:w,className:"sc-chippick-find",type:"text",value:g,maxLength:f,placeholder:i,"aria-label":i,onChange:P=>v(P.target.value),onKeyDown:P=>{P.stopPropagation(),P.key==="Enter"?(P.preventDefault(),E?N():k.length===1&&j(k[0])):P.key==="Escape"&&p(!1)}}),o.jsxs("div",{className:"sc-chippick-list",children:[k.map(P=>{const $=e.some(M=>tu(M,P));return o.jsxs(tr,{className:"sc-menu-item","data-on":$||void 0,"data-off":!$&&S?"":void 0,onSelect:M=>{M.preventDefault(),j(P)},children:[o.jsx("span",{className:"sc-menu-lb",children:P}),$&&o.jsx(Kn,{size:14,className:"sc-menu-check","aria-hidden":"true"})]},P)}),!k.length&&!E&&o.jsx("p",{className:"sc-chippick-none",children:l})]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-menu-sep"}),o.jsxs(tr,{className:"sc-menu-item",onSelect:P=>{P.preventDefault(),N()},children:[o.jsx(cr,{size:16,className:"sc-menu-ic"}),o.jsxs("span",{className:"sc-menu-lb",children:['Add "',x,'"']})]})]}),S&&o.jsx("p",{className:"sc-chippick-none",children:"That is as many as this holds."})]})]})}const tu=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();function YM({name:e,categories:t,known:n,hint:r,ways:a,wayChoices:i,wayMax:l,busy:u,error:f,onSave:h,onDismiss:p}){const[g,v]=s.useState(e),[w,y]=s.useState(t),[x,k]=s.useState(()=>[...a??[]]),S=g.trim(),E=S.length>0,j=M=>M.map(C=>C.id).join(" "),N=S!==e.trim()||w.join(" ")!==t.join(" ")||!!a&&j(x)!==j(a),P=x.length>=(l??Number.POSITIVE_INFINITY)?[]:(i??[]).filter(M=>!x.some(C=>C.id===M.id)),$=()=>{if(!(!E||u)){if(!N)return p();h({name:S,categories:w,...a?{ways:x}:{}})}};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(460px, 94vw)",onDismiss:p,children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Details"}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("input",{className:"sc-pdetails-field",value:g,dir:"auto",onChange:M=>v(M.target.value),onKeyDown:M=>M.key==="Enter"&&$()})]}),o.jsxs("div",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Categories"}),o.jsx(Yre,{value:w,onChange:y,options:n,label:"Categories",placeholder:"Any",findPlaceholder:"Find or add a category",emptyNote:"Nothing by that name.",maxLength:30}),o.jsx("span",{className:"sc-pdetails-hint",children:r})]}),a&&o.jsxs("div",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Ways to shoot it"}),o.jsxs("div",{className:"sc-pdetails-ways",children:[x.map(M=>o.jsxs("div",{className:"sc-pdetails-way",children:[o.jsx("span",{className:"sc-pdetails-way-lb",children:M.label}),o.jsx("span",{className:"sc-pdetails-way-sub",children:M.camera}),o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":`Remove ${M.label}`,onClick:()=>k(x.filter(C=>C.id!==M.id)),children:o.jsx(jn,{size:13,weight:"bold","aria-hidden":!0})})]},M.id)),P.length>0&&o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost","aria-label":"Add a way to shoot it",children:[o.jsx(cr,{size:12,weight:"bold","aria-hidden":!0}),o.jsx("span",{children:"Add a way"})]})}),o.jsx(Cs,{children:P.map(M=>o.jsx(tr,{onSelect:()=>k([...x,M]),children:M.label},M.id))})]})]}),o.jsxs("span",{className:"sc-pdetails-hint",children:["A way moves the camera and leaves the world alone.",l?` ${l} at most.`:""]})]}),f&&o.jsx("p",{className:"sc-assetform-err",children:f})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:p,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!E,"data-busy":u||void 0,onClick:$,children:u?"Saving":"Save"})]})]})}function zl({src:e,crop:t}){const[n,r]=s.useState(!1);return n?o.jsx("span",{className:"sc-lookpage-ref-blank","aria-hidden":!0,children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async",...t?{"data-crop":t}:{},onError:()=>r(!0)})}function cw(){return o.jsx("div",{className:"sc-lookpage-refs",children:o.jsx("div",{className:"sc-lookpage-ref",children:o.jsx("span",{className:"sc-lookpage-ref-blank",children:o.jsx(Ws,{size:20})})})})}function uw({node:e,to:t}){const[n,r]=s.useState(!1);return o.jsx(_n,{className:"sc-lookcard","aria-label":`Open ${Sr(e)}`,to:t,children:n?o.jsx("span",{className:"sc-lookcard-blank",children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:dn(e.images[0],"tile"),alt:"",loading:"lazy",onError:()=>r(!0)})})}function Lu({label:e,children:t}){const n=s.useRef(null),r=s.useRef(null),a=s.useRef(!1),i=s.useRef(()=>{});s.useLayoutEffect(()=>{const u=n.current,f=r.current;if(!u||!f)return;let h=0;const p=()=>{const w=f.scrollWidth-f.clientWidth;if(w<=1){delete u.dataset.overflowLeft,delete u.dataset.overflowRight;return}f.scrollLeft>2?u.dataset.overflowLeft="":delete u.dataset.overflowLeft,f.scrollLeft<w-2?u.dataset.overflowRight="":delete u.dataset.overflowRight};i.current=p,p();const g=()=>{h||(h=requestAnimationFrame(()=>{h=0,p()}))},v=new ResizeObserver(()=>p());return v.observe(f),f.addEventListener("scroll",g,{passive:!0}),()=>{h&&cancelAnimationFrame(h),i.current=()=>{},v.disconnect(),f.removeEventListener("scroll",g)}},[]);const l=u=>{const f=r.current;if(!(f!=null&&f.firstElementChild)||a.current)return;const h=f.firstElementChild.getBoundingClientRect().width+16,p=f.scrollWidth/2;u<0&&f.scrollLeft<h&&(f.scrollLeft+=p);const g=f.scrollLeft,v=u*h,w=performance.now();a.current=!0;const y=x=>{const k=Math.min(1,(x-w)/420);f.scrollLeft=g+v*(1-(1-k)**3),i.current(),k<1?requestAnimationFrame(y):(a.current=!1,f.scrollLeft>=p&&(f.scrollLeft-=p),i.current())};requestAnimationFrame(y)};return o.jsxs("section",{className:"sc-lookpage-band",children:[o.jsx("p",{className:"sc-bandhead",children:e}),o.jsxs("div",{className:"sc-slider",ref:n,children:[o.jsx("button",{type:"button",className:"sc-slider-arrow prev","aria-label":"Previous",onClick:()=>l(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-slider-arrow next","aria-label":"Next",onClick:()=>l(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsxs("div",{className:"sc-slider-track",ref:r,children:[t,t]})]})]})}function qM(e){const t=s.useRef(null),n=s.useRef(null);s.useLayoutEffect(()=>{const a=t.current,i=n.current;if(!a||!i)return;let l=0;const u=()=>{const p=i.scrollWidth-i.clientWidth;if(p<=1){delete a.dataset.overflowLeft,delete a.dataset.overflowRight;return}i.scrollLeft>2?a.dataset.overflowLeft="":delete a.dataset.overflowLeft,i.scrollLeft<p-2?a.dataset.overflowRight="":delete a.dataset.overflowRight},f=()=>{l||(l=requestAnimationFrame(()=>{l=0,u()}))};u();const h=new ResizeObserver(()=>u());h.observe(i);for(const p of i.children)h.observe(p);return i.addEventListener("scroll",f,{passive:!0}),()=>{l&&cancelAnimationFrame(l),h.disconnect(),i.removeEventListener("scroll",f)}},[e]);const r=s.useCallback(a=>{const i=n.current;if(!(i!=null&&i.firstElementChild))return;const l=i.firstElementChild.getBoundingClientRect().width,u=Number.parseFloat(getComputedStyle(i).columnGap)||0,f=window.matchMedia("(prefers-reduced-motion: reduce)").matches;i.scrollBy({left:a*(l+u),behavior:f?"auto":"smooth"})},[]);return{shellRef:t,railRef:n,page:r}}function dw({count:e,label:t,className:n,trackClassName:r,style:a,children:i}){const{shellRef:l,railRef:u,page:f}=qM(e);return o.jsxs("div",{className:n?`sc-rail ${n}`:"sc-rail",ref:l,style:{"--sc-rail-count":e},children:[o.jsx("button",{type:"button",className:"sc-rail-arrow prev","aria-label":`${t}, earlier`,onClick:()=>f(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-rail-arrow next","aria-label":`${t}, later`,onClick:()=>f(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsx("ol",{className:r?`sc-rail-track ${r}`:"sc-rail-track","aria-label":t,ref:u,style:a,children:i})]})}function ym(){const e=s.useRef(!1);return s.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),s.useCallback(()=>{const t=window.location.pathname;return()=>e.current&&window.location.pathname===t},[])}const qre=1500;function XM(e,t,n){const{refreshBrands:r}=Rn(),[a,i]=s.useState(null),[l,u]=s.useState([]),[f,h]=s.useState([]),[p,g]=s.useState(!1),[v,w]=s.useState(0),y=s.useRef(void 0),x=s.useRef(r);x.current=r,s.useEffect(()=>{if(!t)return;let S=!0,E=null;const j=async()=>{var N;try{const P=await Re.sceneExamples(e,t);if(!S)return;const $=P.job?`${P.job.id}:${P.job.done.length}:${P.job.status}`:null;if($&&y.current!==void 0&&$!==y.current&&await x.current(),!S)return;y.current=$,i(P.job),u(P.first),h(P.more),g(!0),((N=P.job)==null?void 0:N.status)==="running"&&(E=setTimeout(j,qre))}catch{}};return j(),()=>{S=!1,E&&clearTimeout(E)}},[e,t,n,v]);const k=s.useCallback(()=>w(S=>S+1),[]);return{job:a,first:l,more:f,read:p,again:k}}const Xre=["no","one","two","three","four","five"];function Qre({brandId:e,scene:t,onError:n}){const{applyBrand:r}=Rn(),a=im(),i=ym(),{job:l,first:u,again:f}=XM(e,t.id,t.previewUrl??null),[h,p]=s.useState(!1),[g,v]=s.useState(!1),[w,y]=s.useState(null),x=iA(t.examples,l),k=(l==null?void 0:l.status)==="running",S=$K(t.examples),E=async()=>{if(g||!u.length)return;const T=i();v(!0),n(null);try{await Re.drawSceneExamples(e,t.id,{first:!0}),f()}catch(H){T()&&n(String((H==null?void 0:H.message)??H))}finally{T()&&v(!1)}},j=u.length&&(l==null?void 0:l.status)!=="running"?o.jsx("p",{className:"sc-scenepage-examples-ask",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",disabled:g,onClick:()=>void E(),children:[S.length?"Draw them again":"Draw it in use",`, ${Xre[u.length]??u.length} picture${u.length===1?"":"s"}`]})}):null,N=async T=>{const H=Z6.find(K=>K.id===T);if(!H||h)return;const D=i();p(!0),n(null);try{const K=t.setups??[];if(!K.some(O=>O.id===H.id)){const O=await Re.updateScene(e,t.id,{setups:[...K,H]});r(O.brand)}a(t.id,H.id)}catch(K){D()&&n(String((K==null?void 0:K.message)??K))}finally{D()&&p(!1)}},P=t.previewUrl?{src:t.previewUrl,label:"The place"}:null;if(!x.length&&!P)return o.jsx(cw,{});if(!x.length&&P)return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-scenepage-place",children:o.jsx("button",{type:"button","aria-label":`${P.label}, open`,onClick:()=>y(P),children:o.jsx(zl,{src:sr(P.src,"tile")})})}),j,w&&o.jsx(Uu,{src:w.src,kind:"scene",label:w.label,noun:t.name,onClose:()=>y(null)})]});const $=w==null?void 0:w.tile,M=$!=null&&$.setup?Z6.find(T=>T.id===$.setup):void 0,C=!!M&&((t.setups??[]).some(T=>T.id===M.id)||(t.setups??[]).length<GM),R=k&&l?mv({status:l.status,step:l.current,done:l.done.length,total:l.roles.length,error:l.error}):S.length>0?`${S.length===1?`The ${tc[S[0]].toLowerCase()} shows`:"These show"} an earlier picture of this place.`:null;return o.jsxs(o.Fragment,{children:[o.jsxs(dw,{count:x.length+(P?1:0),label:"Pictures of this place",className:"sc-refset-rail",trackClassName:"sc-refset",children:[P&&o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":"The place, open",onClick:()=>y(P),children:o.jsx(zl,{src:sr(P.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:"The place"})]}),x.map(T=>{const H=tc[T.role];return o.jsxs("li",{children:[T.state==="drawing"?o.jsxs("span",{className:"sc-refset-tile","data-state":"drawing",role:"img","aria-label":`${H}, drawing`,children:[T.url&&o.jsx(zl,{src:sr(T.url,"small")}),o.jsx("span",{className:"sc-shimmer","aria-hidden":!0})]}):T.state==="failed"?o.jsxs("span",{className:"sc-refset-tile","data-state":"failed",role:"img","aria-label":`${H} did not draw`,title:T.error,children:[o.jsx(kc,{size:20,"aria-hidden":!0}),o.jsx("span",{children:"Did not draw"})]}):o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":`${H}, open`,onClick:()=>y({src:T.url,label:H,tile:T}),children:o.jsx(zl,{src:sr(T.url,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:H})]},T.role)})]}),R&&o.jsx("p",{className:"sc-scenepage-examples-state","aria-live":"polite",children:R}),j,w&&o.jsx(Uu,{src:w.src,kind:"scene",label:w.label,noun:t.name,onClose:()=>y(null),actions:M&&C?o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:h,onClick:()=>void N(M.id),children:"Shoot it this way"}):void 0})]})}function Jre(){var xe,ee,ae,re;const{sceneId:e}=Bs(),{scenes:t,loaded:n,error:r,refetch:a,applyBrand:i,refreshBrands:l}=Rn(),{brand:u}=on(),f=Dn(),h=im(),p=u.id,[g,v]=s.useState([]),[w,y]=s.useState(()=>vo(p)),[x,k]=s.useState(null),S=_=>f(_r(u,_)),E=Hh(u,e??""),j=E??t.find(_=>_.id===e);Sc(j==null?void 0:j.name);const N=!!E;s.useEffect(()=>{let _=!0;if(v([]),!N)return Re.sceneFrames(e??"").then(ue=>{_&&v(ue.frames)}).catch(()=>{_&&v([])}),()=>{_=!1}},[e,N]);const P=lw(u.id,[e??""]),$=s.useMemo(()=>{if(!j||N)return[];return t.filter(We=>We.id!==j.id).sort((We,Xe)=>ue(Xe)-ue(We)).slice(0,8);function ue(We){const Xe=We.lighting.split(/[ ,]+/).some(tt=>tt.length>3&&j.lighting.toLowerCase().includes(tt.toLowerCase())),ze=We.collections.some(tt=>j.collections.includes(tt));return(Xe?2:0)+(ze?1:0)}},[t,j,N]),M=s.useMemo(()=>{if(j||!n||r)return[];const _=vo(p);return CM(t,ue=>_.includes(ue.id)).slice(0,6)},[j,n,r,t,p]),[C,R]=s.useState(null),[T,H]=s.useState(!1),[D,K]=s.useState(!1),[O,Z]=s.useState(!1),te=s.useRef(!1),B=ym(),F=s.useMemo(()=>[...new Set([...t.flatMap(_=>_.verticals),...Cc(u).flatMap(_=>_.verticals)])].sort((_,ue)=>_.localeCompare(ue)),[t,u]),X=async _=>{if(E){K(!0),R(null);try{const ue=await Re.updateScene(u.id,E.id,{name:_.name,verticals:_.categories,..._.ways?{setups:_.ways}:{}});i(ue.brand),Z(!1)}catch(ue){R(String(ue.message??ue))}finally{K(!1)}}},z=async()=>{if(!E||te.current)return;te.current=!0;const _=B(),ue=_u(u);H(!0);try{const We=await Re.deleteScene(u.id,E.id);i(We.brand)}catch(We){if((We==null?void 0:We.status)!==404){te.current=!1,_()&&(R(String(We.message??We)),H(!1));return}await l()}_()&&f(ue,{replace:!0})};if(!n&&!E)return o.jsx(is,{children:o.jsx("main",{className:"sc-lookpage sc-scenepage",id:"main",children:o.jsx("div",{className:"sc-tplrow","aria-hidden":!0})})});if(r&&!E)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:"Couldn't load this scene"}),o.jsx("p",{className:"sc-lookpage-lede",children:"Something went wrong reaching the catalog."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>a(),children:"Retry"})})]})});if(!j)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:"This scene isn't here anymore"}),o.jsx("p",{className:"sc-lookpage-lede",children:"It may have been removed from the catalog, or the link is out of date."}),o.jsxs("div",{className:"sc-lookpage-acts",children:[o.jsx(_n,{className:"sc-btn sc-btn-primary",to:`${mr(u)}?compose=1`,children:"Start from scratch"}),o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:_u(u),children:"Browse all scenes"})]}),M.length>0&&o.jsx(Lu,{label:"You might like",children:M.map(_=>o.jsx(I0,{scene:_,variant:"navigate",size:"slider",onOpen:S,href:_r(u,_.id)},_.id))})]})});const I=g.length?g.map((_,ue)=>({src:_,label:`Example ${ue+1}`})):j.previewUrl?[{src:j.previewUrl,label:"The place"}]:[],U=j.subject!=="person"&&I.length>0?"Shown with a demo product for reference. Yours replaces it.":"",G=!E&&w.includes(j.id),ne=(E==null?void 0:E.setups)??[],q=((E==null?void 0:E.refs)??[]).filter(_=>_!==(E==null?void 0:E.previewUrl)),le=((ee=(xe=E==null?void 0:E.examples)==null?void 0:xe.find(_=>!_.earlier))==null?void 0:ee.with)??((re=(ae=E==null?void 0:E.examples)==null?void 0:ae[0])==null?void 0:re.with),Se=E?E.figure?"The person in it is a stand-in: with a presenter attached, the picture goes with the shot and they take the role.":le?`Shown in use with a Scenri demo ${le}. Shots are told the words, never handed these pictures.`:E.previewUrl?"Shots are told the words, never handed this picture.":"":"",Q=E?Kre({refs:q,setups:E.setups},Se):"";return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-scenepage",id:"main",children:[o.jsx("h1",{children:j.name}),j.verticals.length>0&&o.jsx("ul",{className:"sc-lookpage-cats","aria-label":"Filed under",children:j.verticals.map(_=>o.jsx("li",{className:"sc-chip","data-static":!0,children:_},_))}),o.jsx("p",{className:"sc-lookpage-lede",children:j.description}),o.jsxs("div",{className:"sc-lookpage-acts",children:[ne.length>0?o.jsxs("span",{className:"sc-splitbtn",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary sc-splitbtn-go",onClick:()=>void h(j.id),children:"Use in a shot"}),o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary sc-splitbtn-more","aria-label":"Use it a way",children:o.jsx(Yi,{size:12,weight:"bold","aria-hidden":!0})})}),o.jsx(Cs,{children:ne.map(_=>o.jsx(tr,{onSelect:()=>void h(j.id,_.id),children:_.label},_.id))})]})]}):o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>void h(j.id),children:"Use in a shot"}),E?o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:cv(u,E.id),children:"Edit scene"}):o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost","aria-pressed":G,onClick:()=>y(cm("scene",p,j.id)),children:[o.jsx(po,{size:13,weight:G?"fill":"regular"}),o.jsx("span",{children:G?"Remove from Keepers":"Add to Keepers"})]}),E&&o.jsx(lr,{label:"Edit name, filing and ways",children:o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":"Edit name, filing and ways","aria-haspopup":"dialog",onClick:()=>Z(!0),children:o.jsx(Ju,{size:17})})})]}),C&&o.jsx("p",{className:"sc-assetform-err",children:C}),E?o.jsx(Qre,{brandId:u.id,scene:E,onError:R},E.id):I.length>1?o.jsx(dw,{count:I.length,label:"Pictures of this place",className:"sc-refset-rail",trackClassName:"sc-refset",children:I.map(_=>o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","aria-label":`${_.label}, open`,onClick:()=>k(_),children:o.jsx(zl,{src:sr(_.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:_.label})]},_.src))}):I.length===1?o.jsx("div",{className:"sc-scenepage-place",children:o.jsx("button",{type:"button","aria-label":`${I[0].label}, open`,onClick:()=>k(I[0]),children:o.jsx(zl,{src:sr(I[0].src,"tile")})})}):o.jsx(cw,{}),!E&&U&&o.jsx("p",{className:"sc-lookpage-note",children:U}),E&&o.jsxs("section",{className:"sc-scenepage-told",children:[o.jsxs("dl",{className:"sc-lookpage-told",children:[o.jsxs("div",{children:[o.jsx("dt",{children:Ne.lightLabel}),o.jsx("dd",{dir:"auto",children:E.lighting})]}),E.camera&&o.jsxs("div",{children:[o.jsx("dt",{children:Ne.cameraLabel}),o.jsx("dd",{dir:"auto",children:E.camera})]}),E.figure&&o.jsxs("div",{children:[o.jsx("dt",{children:Ne.figureLabel}),o.jsx("dd",{dir:"auto",children:E.figure})]})]}),o.jsx("p",{className:"sc-lookpage-note",children:"Every shot made here is told this. Anything you write in the shot wins."})]}),q.length>0&&o.jsxs("section",{className:"sc-presenterpage-sources",children:[o.jsx("p",{className:"sc-presenterpage-sources-lb",children:"What it was read from"}),o.jsx("div",{className:"sc-presenterpage-sources-row",children:q.map((_,ue)=>o.jsx("button",{type:"button",className:"sc-presenterpage-source","aria-label":`Source photo ${ue+1}, open`,onClick:()=>k({src:_,label:`Source photo ${ue+1}`}),children:o.jsx(zl,{src:sr(_,"micro")})},_))})]}),E&&o.jsxs("div",{className:"sc-prec",children:[Q&&o.jsx("p",{className:"sc-prec-note",children:Q}),o.jsx(Wn,{label:"Delete scene",title:`Delete ${E.name}?`,body:"Shots already made here keep their images. Their recipe will say this scene is gone, and building from one again will miss it.",busy:T,onConfirm:()=>void z()})]}),P.length>0&&o.jsx(Lu,{label:`Shots made in ${j.name}`,children:P.map(_=>o.jsx(uw,{node:_,to:Wp(u,null,_.id)},_.id))}),$.length>0&&o.jsx(Lu,{label:"Other scenes, similar light",children:$.map(_=>o.jsx(I0,{scene:_,variant:"navigate",size:"slider",onOpen:S,href:_r(u,_.id)},_.id))}),O&&E&&o.jsx(YM,{name:E.name,categories:E.verticals,known:F,hint:"The verticals this place suits, so it surfaces where you work.",ways:ne,wayChoices:Z6,wayMax:GM,busy:D,error:C,onSave:_=>void X(_),onDismiss:()=>Z(!1)}),x&&o.jsx(Uu,{src:x.src,kind:"scene",label:x.label,noun:j.name,onClose:()=>k(null)})]})})}function ese({draft:e,href:t,onDiscard:n,chosen:r,batching:a,onPick:i,batch:l}){return o.jsx(WM,{id:e.id,name:e.name.trim()||"Untitled presenter",hash:e.hash,drawing:!!e.drawing,state:tse(e),href:t,blank:o.jsx(tW,{size:44,weight:"thin"}),onDiscard:n,chosen:r,batching:a,onPick:i,batch:l})}function tse(e){return e.drawing?"Drawing":e.approved?e.approved===1?"Face ready":e.approved>=e.of?"Ready to save":`${e.approved} of ${e.of} views ready`:e.hash?"A face to decide":e.source==="photos"?"Photos added":"Not drawn yet"}function nse({suggested:e,busy:t,error:n,onConfirm:r,onDismiss:a}){const[i,l]=s.useState(e),u=s.useRef(null),f=s.useRef(!1),h=i.trim(),p=h.length>0;s.useEffect(()=>{f.current=!1},[e]),s.useEffect(()=>{t||(f.current=!1)},[t]);const g=()=>{!p||t||f.current||(f.current=!0,r(h))};return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(420px, 94vw)",onDismiss:a,onOpenAutoFocus:v=>{v.preventDefault();const w=u.current;w&&(w.focus(),w.select())},children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Duplicate presenter"}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Name"}),o.jsx("input",{ref:u,className:"sc-pdetails-field",value:i,dir:"auto",maxLength:60,onChange:v=>l(v.target.value),onKeyDown:v=>v.key==="Enter"&&g()})]}),n&&o.jsx("p",{className:"sc-assetform-err",children:n})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:!p||t,"data-busy":t||void 0,onClick:g,children:t?"Duplicating":"Duplicate"})]})]})}const rse=60;function sse(e,t,n=rse){var l;const r=e.trim(),a=(((l=r.match(/^(.*?)(?: copy(?: \d+)?)?$/i))==null?void 0:l[1])??r).trim()||r,i=new Set(t.map(u=>u.trim().toLowerCase()).filter(Boolean));for(let u=1;u<1e4;u++){const f=u===1?" copy":` copy ${u}`,h=Math.max(1,n-f.length),p=`${a.slice(0,h).trimEnd()}${f}`;if(!i.has(p.toLowerCase()))return p}return`${a.slice(0,Math.max(1,n-5)).trimEnd()} copy`}const ase=8,l8="__bookmarked";function ose(){const{presenters:e,presenterCategories:t,presentersLoaded:n,presentersError:r,refetchPresenters:a,applyBrand:i,refreshBrands:l}=Rn(),{brand:u}=on(),f=Dn(),h=Wv(),{push:p}=or(),{q:g,setQ:v,facets:w,setFacets:y,clearSearch:x,clear:k}=Pf(["category","bookmarked"]),S=w.category,E=w.bookmarked==="1",[j,N]=s.useState(()=>lm("presenter",u.id)),P=me=>N(cm("presenter",u.id,me)),$=aw(`${u.id}|${g}|${S??""}|${E?"1":""}`),M=ll(),C=s.useMemo(()=>Sf(u),[u]),[R,T]=fa(Dr.wallDensity,zu),H=jc(R),D=me=>T(me),K=fm(H),O=um(H),Z=me=>f(ha(u,me)),te=me=>f(Up(u,me)),B=s.useMemo(()=>S?e.filter(me=>me.suitableCategories.includes(S)):e,[e,S]),F=s.useMemo(()=>B.filter(me=>wo(Yh(me),g)),[B,g]),X=s.useRef(null),z=s.useRef(null),I=o.jsxs("button",{ref:z,type:"button",className:"sc-btn sc-btn-primary",onClick:()=>M("presenter"),children:[o.jsx(cr,{size:12})," Create presenter"]}),[U,G]=s.useState([]),ne=s.useRef(0),q=s.useCallback(()=>{const me=++ne.current;return Re.presenterDrafts(u.id).then(_e=>{me===ne.current&&G(_e.drafts.filter(W=>!W.presenterId))}).catch(()=>{}),()=>{me===ne.current&&ne.current++}},[u.id]),le=!!un({path:ct.presenterStudio}),{tasks:Se}=Za(),Q=Se.filter(me=>me.id.startsWith("presenter:")).map(me=>`${me.id}:${me.state}:${me.percent??""}`).join("|");s.useEffect(()=>{if(!le)return q()},[le,q,Q]);const xe=s.useCallback(me=>{const _e=Math.max(0,U.findIndex(W=>W.id===me));ee.current=_e,$.forget(me),G(W=>W.filter(pe=>pe.id!==me)),Re.deletePresenterDraft(u.id,me).finally(()=>q())},[u.id,U,q,$.forget]),ee=s.useRef(null);s.useEffect(()=>{var pe;const me=ee.current;if(me===null)return;ee.current=null;const _e=(pe=X.current)==null?void 0:pe.querySelectorAll("[data-build] .sc-cardpuck"),W=_e!=null&&_e.length?_e[Math.min(me,_e.length-1)]:z.current??document.querySelector(".sc-new-go");W==null||W.focus()},[U]);const[ae,re]=s.useState(null),[_,ue]=s.useState(!1),[We,Xe]=s.useState(!1),ze=s.useCallback(me=>{const _e=U.find(W=>W.id===me);_e!=null&&_e.drawn?re(_e):xe(me)},[U,xe]),[tt,ce]=s.useState(null),[ve,Pe]=s.useState(null),[de,je]=s.useState(null),[Ue,ye]=s.useState(!1),[Ee,be]=s.useState(null),[Le,Qe]=s.useState(null),Ke=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&(be(null),ce(_e))},[C]),nt=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&(be(null),Pe(_e))},[C]),gt=async me=>{if(!(!ve||Ue)){ye(!0),be(null);try{i((await Re.updatePresenter(u.id,ve.id,{name:me})).brand),Pe(null)}catch(_e){const W=nn(_e,"Could not rename this presenter");be([W.title,W.detail].filter(Boolean).join(" "))}finally{ye(!1)}}},Pt=s.useCallback(me=>{const _e=C.find(W=>W.id===me);_e&&je(_e)},[C]),Ut=s.useRef(null);s.useEffect(()=>{var pe;const me=Ut.current;if(me===null)return;Ut.current=null;const _e=(pe=X.current)==null?void 0:pe.querySelectorAll(".sc-lookcard:not([data-build]) .sc-lookcard-more"),W=_e!=null&&_e.length?_e[Math.min(me,_e.length-1)]:z.current??document.querySelector(".sc-new-go");W==null||W.focus()},[e,u]);const Nt=async me=>{if(!(!tt||Ue)){ye(!0),be(null);try{const _e=await Re.duplicatePresenter(u.id,tt.id,me);i(_e.brand),ce(null),Qe(_e.presenter.id)}catch(_e){const W=nn(_e,"Could not duplicate this presenter");be([W.title,W.detail].filter(Boolean).join(" "))}finally{ye(!1)}}},cn=async()=>{if(!(!de||Ue)){Ut.current=Math.max(0,Fe.findIndex(me=>me.id===de.id)),ye(!0);try{const me=await Re.deletePresenter(u.id,de.id);i(me.brand),$.forget(de.id),je(null)}catch(me){(me==null?void 0:me.status)===404?(await l(),$.forget(de.id),je(null)):p(nn(me,"Could not delete this presenter"))}finally{ye(!1)}}};s.useEffect(()=>{var _e,W;if(!Le)return;(W=(_e=X.current)==null?void 0:_e.querySelector(".sc-lookcard[data-just-added]"))==null||W.scrollIntoView({block:"nearest"});const me=window.setTimeout(()=>Qe(null),1800);return()=>window.clearTimeout(me)},[Le]);const Fe=s.useMemo(()=>C.filter(me=>S?!me.suitableCategories.length||me.suitableCategories.includes(S):!0).filter(me=>wo(Yh(me),g)).filter(me=>E?j.includes(me.id):!0),[C,S,g,E,j]),it=!(C.length>0||U.length>0),St=[...C,...e].reduce((me,_e)=>me+(j.includes(_e.id)?1:0),0),xt=E&&St===0,At=xt&&it,Kt=xt&&!it,et=!E||At,mt=Fe.filter(me=>!E||At||j.includes(me.id)),ot=et&&U.length>0||mt.length>0,kn=s.useMemo(()=>!E||At?F:F.filter(me=>j.includes(me.id)),[F,E,At,j]),{visible:ut,remaining:Gt,showMore:Ft}=iw(kn,`${S??""}|${E?"keepers":""}|${At?"browse":""}|${g}`),en=e.length+C.length>0?"tabs":"none",Jt=s.useCallback(async me=>{const{failed:_e,error:W}=await tp(me,pe=>Re.deletePresenterDraft(u.id,pe));G(pe=>pe.filter(Ie=>_e.includes(Ie.id)||!me.includes(Ie.id))),$.retain(_e),q(),W&&p(nn(W,"Could not discard these drafts"))},[u.id,q,$.retain,p]),se=()=>{const me=U.filter(_e=>$.ids.has(_e.id));me.some(_e=>_e.drawn)?me.length===1?re(me[0]):ue(!0):Jt(me.map(_e=>_e.id))},oe=()=>{const me=[...$.ids];me.length===1?Pt(me[0]):Xe(!0)},we=[...$.ids],ge=$.kind==="presenter"&&we.length>0&&we.every(me=>j.includes(me)),J=()=>N(Kv("presenter",u.id,we,!ge)),Oe=pm($.ids.size,ge,"presenters"),Be=async()=>{if(Ue)return;const me=[...$.ids];ye(!0);try{const{failed:_e,error:W}=await tp(me,pe=>Re.deletePresenter(u.id,pe));await l(),$.retain(_e),Xe(!1),W&&p(nn(W,"Could not delete these presenters"))}finally{ye(!1)}},Ve={key:"category",label:"Category",everyLabel:"All presenters",everyCount:e.length+C.length,selected:E?l8:S,onSelect:me=>y(me===l8?{bookmarked:"1",category:null}:{bookmarked:null,category:me}),options:[{value:l8,label:"Keepers",count:St},...t.map(me=>({value:me,label:me,count:[...C,...e].filter(_e=>!_e.suitableCategories.length||_e.suitableCategories.includes(me)).length}))]},Ge=o.jsx(gm,{title:"Presenters",filters:o.jsx(vm,{mode:en,group:Ve}),density:o.jsx(dm,{value:H,onChange:D}),search:e.length>=ase&&o.jsx(id,{value:g,onChange:v,noun:"presenters",total:e.length})});return o.jsxs(Nf.Provider,{value:O,children:[o.jsx(is,{children:o.jsxs("main",{className:"sc-looks sc-presenters",id:"main","data-hero":it||void 0,onClick:$.onBlank,children:[!it&&Ge,ot&&o.jsxs("section",{className:"sc-owned",children:[o.jsx("div",{className:"sc-sec-head",children:o.jsx("h2",{className:"sc-sec-title",children:"Your presenters"})}),o.jsxs("div",{ref:X,className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:[et&&U.map(me=>o.jsx(ese,{draft:me,href:zi(u,me.id),onDiscard:ze,chosen:$.ids.has(me.id),batching:$.batching==="draft",onPick:$.picking("draft")?_e=>$.toggle("draft",_e):void 0,batch:$.kind==="draft"&&$.ids.has(me.id)?{count:$.ids.size,onAct:se}:null},me.id)),ae&&o.jsx(Wn,{label:"Discard",title:`Discard ${ae.name.trim()||"this unfinished presenter"}?`,body:"The views drawn so far are thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:me=>{me||re(null)},onConfirm:()=>{xe(ae.id),re(null)}}),mt.map(me=>o.jsx(_6,{presenter:me,variant:"use",size:"grid",onOpen:Z,href:ha(u,me.id),onUse:h,onDuplicate:Ke,onEdit:te,onDelete:Pt,onRename:nt,bookmarked:j.includes(me.id),onBookmark:P,fresh:me.id===Le,chosen:$.ids.has(me.id),batching:$.batching==="presenter",onPick:$.picking("presenter")?_e=>$.toggle("presenter",_e):void 0,batch:$.kind==="presenter"&&$.ids.has(me.id)?{count:$.ids.size,onAct:oe,onKeep:J,allKept:ge}:null},me.id)),ve&&o.jsx(rw,{title:"Rename presenter",name:ve.name,maxLength:60,busy:Ue,error:Ee,onConfirm:me=>void gt(me),onDismiss:()=>{Ue||Pe(null)}}),tt&&o.jsx(nse,{suggested:sse(tt.name,C.map(me=>me.name)),busy:Ue,error:Ee,onConfirm:me=>void Nt(me),onDismiss:()=>{Ue||ce(null)}}),de&&o.jsx(Wn,{label:"Delete presenter",title:`Delete ${de.name}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",open:!0,busy:Ue,onOpenChange:me=>{!me&&!Ue&&je(null)},onConfirm:()=>void cn()}),We&&o.jsx(Wn,{label:qr("presenter",$.ids.size).menu,title:`${qr("presenter",$.ids.size).menu}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",open:!0,busy:Ue,onOpenChange:me=>{!me&&!Ue&&Xe(!1)},onConfirm:()=>void Be()}),_&&o.jsx(Wn,{label:qr("draft",$.ids.size).menu,title:`${qr("draft",$.ids.size).menu}?`,body:"The views drawn so far are thrown away. Nothing was saved to the library.",open:!0,busy:!1,onOpenChange:me=>{me||ue(!1)},onConfirm:()=>{const me=[...$.ids];ue(!1),Jt(me)}})]})]}),it&&n&&!r&&e.length>0&&o.jsx(oo,{shape:"cold",title:o.jsxs(o.Fragment,{children:["Cast your own ",o.jsx("em",{children:"presenter"})]}),body:"Describe someone new, or add photos of a real person. They stay the same person in every image you make.",action:I}),ot&&n&&!r&&ut.length>0&&o.jsx("div",{className:"sc-sec-head sc-owned-divider",children:o.jsx("h2",{className:"sc-sec-title",children:"Scenri presenters"})}),!n&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":O,style:K,"aria-hidden":!0,children:o.jsx(zM,{size:"grid",count:8})}),n&&r&&o.jsx(oo,{shape:"error",title:"Couldn't load the presenter library",body:"Something went wrong reaching the catalog.",onRetry:()=>a()}),it&&n&&!r&&e.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(ow,{label:"Or cast someone from ours"}),Ge]}),n&&!r&&ut.length>0&&o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:ut.map(me=>o.jsx(_6,{presenter:me,variant:"use",size:"grid",onOpen:Z,href:ha(u,me.id),onUse:h,bookmarked:j.includes(me.id),onBookmark:P},me.id))}),n&&!r&&Kt&&o.jsx(oo,{shape:"zero",body:"Nothing in Keepers yet. Add a presenter to Keepers from its card and it stays here.",action:o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>y({bookmarked:null}),children:"Browse every presenter"})}),n&&!r&&!Kt&&!kn.length&&e.length>0&&o.jsx(wm,{noun:"presenters",q:g,facet:E?"Keepers":S,onClearSearch:x,onClearAll:k}),n&&!r&&!e.length&&o.jsx(oo,{shape:"zero",body:"The presenter library is still being cast. Check back soon."}),Gt>0&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:Ft,children:["Show ",Math.min(Gt,60)," more"]})})]})}),$.ids.size>0&&($.kind==="draft"||$.kind==="presenter")&&o.jsx("div",{className:"sc-wall-dock",children:o.jsx(sw,{count:$.ids.size,loaded:$.kind==="draft"?U.length:mt.length,tool:qr($.kind,$.ids.size).tool,icon:qr($.kind,$.ids.size).icon,danger:qr($.kind,$.ids.size).danger,onAct:$.kind==="draft"?se:oe,keep:$.kind==="presenter"?{label:Oe.tool,filled:ge,onAct:J}:null,onClear:$.clear,onSelectAll:()=>$.selectAll($.kind==="draft"?"draft":"presenter",($.kind==="draft"?U:mt).map(me=>me.id))})}),o.jsx(uc,{})]})}const ise={portrait:"Face",identity:"Face",front:"Full body","three-quarter":"Three-quarter",back:"Back",left:"Left",right:"Right","left-profile":"Left","right-profile":"Right"},lse=["Front","Left","Right","Back"];function cse(){var ne;const{presenterId:e=""}=Bs(),{presenters:t,presentersLoaded:n,presentersError:r,refetchPresenters:a,applyBrand:i,refreshBrands:l,presenterCategories:u}=Rn(),{brand:f}=on(),h=Dn(),p=ym(),g=s.useRef(!1),v=Wv(),[w,y]=s.useState([]),[x,k]=s.useState(null),[S,E]=s.useState(null),j=LG(f,e),N=j??t.find(q=>q.id===e);Sc(N==null?void 0:N.name);const P=!!j;s.useEffect(()=>{let q=!0;if(y([]),!P)return Re.presenterFrames(e).then(le=>{q&&y(le.frames)}).catch(()=>{q&&y([])}),()=>{q=!1}},[e,P]);const $=!!un({path:ct.presenterEdit});s.useEffect(()=>{let q=!0;if(E(null),!(!P||$))return Re.presenterDrafts(f.id).then(le=>{if(!q)return;const Se=le.drafts.find(Q=>Q.presenterId===e);E((Se==null?void 0:Se.id)??null)}).catch(()=>{}),()=>{q=!1}},[f.id,e,P,$]);const M=((ne=f.json)==null?void 0:ne.characters)??[],C=M.find(q=>q.presenterId===e),R=M.find(q=>q.id===e),T=lw(f.id,[e??"",(C==null?void 0:C.id)??""]),[H,D]=s.useState(null),[K,O]=s.useState(!1),[Z,te]=s.useState(!1),B=async q=>{if(j){O(!0),D(null);try{const le=await Re.updatePresenter(f.id,j.id,q);i(le.brand),te(!1)}catch(le){D(String(le.message??le))}finally{O(!1)}}},F=async()=>{if(!j||g.current)return;g.current=!0;const q=p(),le=qi(f);O(!0);try{const Se=await Re.deletePresenter(f.id,j.id);i(Se.brand)}catch(Se){if((Se==null?void 0:Se.status)!==404){g.current=!1,q()&&(D(String(Se.message??Se)),O(!1));return}await l()}q()&&h(le,{replace:!0})},X=kv(f,e);if(X!==e)return o.jsx(uo,{to:ha(f,X),replace:!0});if(!n&&!j)return o.jsx(is,{children:o.jsx("main",{className:"sc-lookpage",id:"main",children:o.jsx("div",{className:"sc-tplrow","aria-hidden":!0})})});if(r&&!j)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage",id:"main",children:[o.jsx("h1",{children:"Couldn't load this presenter"}),o.jsx("p",{className:"sc-lookpage-lede",children:"Something went wrong reaching the catalog."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>a(),children:"Retry"})})]})});if(!N)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage",id:"main",children:[o.jsx("h1",{children:"This presenter isn't here anymore"}),o.jsx("p",{className:"sc-lookpage-lede",children:"They may have been removed from the catalog, or the link is out of date."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx(_n,{className:"sc-btn sc-btn-primary",to:qi(f),children:"Browse presenters"})})]})});const z=j?(Array.isArray(R==null?void 0:R.shots)?R.shots:[]).map((q,le)=>({src:Fr(q==null?void 0:q.file),label:ise[(q==null?void 0:q.angle)??""]??`Reference ${le+1}`,angle:typeof(q==null?void 0:q.angle)=="string"?q.angle:void 0})).filter(q=>!!q.src):w.length?w.map((q,le)=>({src:q,label:lse[le]??`Reference ${le+1}`})):N.previewUrl?[{src:N.previewUrl,label:"Preview"}]:[],I=Up(f,e),U=ti(j??N),G=[...new Set([...u,...Sf(f).flatMap(q=>q.suitableCategories??[])])].sort((q,le)=>q.localeCompare(le));return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-presenterpage",id:"main",children:[U.src&&o.jsx("div",{className:"sc-presenterpage-avatar",children:o.jsx(c8,{src:sr(U.src,"small"),crop:U.crop})}),o.jsx("h1",{children:N.name}),N.suitableCategories.length>0&&o.jsx("ul",{className:"sc-lookpage-cats","aria-label":"Filed under",children:N.suitableCategories.map(q=>o.jsx("li",{className:"sc-chip","data-static":!0,children:q},q))}),N.descriptor&&o.jsx("p",{className:"sc-lookpage-lede",children:N.descriptor}),o.jsxs("div",{className:"sc-lookpage-acts",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>v(e),children:"Use in a shot"}),j&&o.jsx(_n,{className:"sc-btn sc-btn-ghost",to:I,children:S?"Continue editing":"Edit presenter"}),j&&o.jsx(lr,{label:"Edit name and details",children:o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":"Edit name and details","aria-haspopup":"dialog",onClick:()=>te(!0),children:o.jsx(Ju,{size:17})})})]}),H&&o.jsx("p",{className:"sc-assetform-err",children:H}),z.length>0?o.jsx(dw,{count:z.length,label:"Reference set",className:"sc-refset-rail",trackClassName:"sc-refset",children:z.map(q=>o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-refset-tile","data-role":q.angle,"aria-label":`${q.label}, open`,onClick:()=>k(q),children:o.jsx(c8,{src:sr(q.src,"small")})}),o.jsx("span",{className:"sc-refset-lb","aria-hidden":!0,children:q.label})]},q.label))}):o.jsx(cw,{}),j&&j.sourceRefs.length>0&&o.jsxs("section",{className:"sc-presenterpage-sources",children:[o.jsx("p",{className:"sc-presenterpage-sources-lb",children:"From your photos"}),o.jsx("div",{className:"sc-presenterpage-sources-row",children:j.sourceRefs.map((q,le)=>o.jsx("button",{type:"button",className:"sc-presenterpage-source","aria-label":`Source photo ${le+1}, open`,onClick:()=>k({src:q,label:`Source photo ${le+1}`}),children:o.jsx(c8,{src:sr(q,"micro")})},q))})]}),j&&o.jsxs("div",{className:"sc-prec",children:[o.jsxs("p",{className:"sc-prec-note",children:[N.ageRange?`${N.ageRange} · `:"",j.source==="synthetic"?"Created in Scenri. Not a real person.":j.source==="photos"?"Built from your photographs.":"Saved in Scenri.",j.likeness?` Likeness confirmed ${new Date(j.likeness.attestedAt).toLocaleDateString()}.`:""]}),o.jsx(Wn,{label:"Delete presenter",title:`Delete ${j.name}?`,body:"Shots already made with them keep their images and their recipe. Only future shots lose them.",busy:K,onConfirm:()=>void F()})]}),T.length>0&&o.jsx(Lu,{label:`Shots featuring ${N.name}`,children:T.map(q=>o.jsx(uw,{node:q,to:Wp(f,null,q.id)},q.id))}),Z&&j&&o.jsx(YM,{name:j.name,categories:N.suitableCategories,known:G,hint:"The verticals they suit, so they surface where you work.",busy:K,error:H,onSave:q=>void B({name:q.name,suitableCategories:q.categories}),onDismiss:()=>te(!1)}),x&&o.jsx(Uu,{src:x.src,kind:"presenter",label:x.label,noun:N.name,onClose:()=>k(null)})]})})}function c8({src:e,crop:t}){const[n,r]=s.useState(!1);return n?o.jsx("span",{className:"sc-lookpage-ref-blank","aria-hidden":!0,children:o.jsx(Ws,{size:20})}):o.jsx("img",{src:e,alt:"",loading:"lazy",decoding:"async",...t?{"data-crop":t}:{},onError:()=>r(!0)})}function use({placeholder:e,label:t,action:n="Send",scope:r,hint:a,value:i,onValue:l,allowEmpty:u,disabled:f,why:h,quiet:p,working:g,error:v,focusKey:w,onStop:y,stopping:x,onAttach:k,onAttachFiles:S,attachLabel:E,colour:j,refs:N,onSend:P}){const $=s.useRef(null),M=s.useRef(null),[C,R]=s.useState(void 0);s.useLayoutEffect(()=>{const I=$.current;if(!I)return;I.style.height="auto";const U=Number.parseFloat(getComputedStyle(I).maxHeight)||Number.POSITIVE_INFINITY;I.style.height=`${Math.min(I.scrollHeight,U)}px`,I.style.overflowY=I.scrollHeight>U?"auto":"hidden"},[i]);const[T,H]=s.useState(!1),D=wr(Ks);s.useEffect(()=>{if(!w||w===C||f||(R(w),D))return;const I=$.current;if(I==null||I.focus({preventScroll:!0}),I!=null&&I.value){I.select(),H(!0);const U=setTimeout(()=>H(!1),700);return()=>clearTimeout(U)}},[w,C,f,D]);const K=f||g,O=!!(j!=null&&j.hex)||!!(N!=null&&N.some(I=>!I.busy)),Z=!i.trim()&&!u&&!O,te=()=>{K||Z||P(i)},B=v?{text:v,tone:"alert"}:{text:(r==null?void 0:r.hint)??a??"",tone:r==null?void 0:r.tone},F=!!y&&(g||!i.trim()&&!O),X=g||F?null:f&&h?h:Z&&!f?"Nothing typed yet.":null,z=o.jsxs("button",{type:"button",className:"sc-convo-send","aria-disabled":(F?!!x:g||K||Z)||void 0,"aria-busy":g||F||void 0,"data-stop":F||void 0,onClick:F?x?void 0:y:g?void 0:te,children:[o.jsx("span",{className:"sc-convo-send-ico",children:g||F?o.jsx("span",{className:"sc-convo-spin","aria-hidden":"true"}):o.jsx(iC,{size:17,weight:"bold"})}),F?x?"Stopping":"Stop":g?"Working":n]});return o.jsxs("div",{className:"sc-convo-composer",children:[o.jsxs("div",{className:"sc-convo-card","data-quiet":p||void 0,"data-flash":T||void 0,children:[(r==null?void 0:r.chip)&&o.jsx("div",{className:"sc-convo-scope-row",children:o.jsxs("span",{className:"sc-convo-scope",children:[r.chip.thumb?o.jsx("img",{src:r.chip.thumb,alt:""}):null,r.chip.label]})}),o.jsxs("div",{className:"sc-convo-field",children:[N==null?void 0:N.map(I=>o.jsxs("span",{className:"sc-token","data-kind":"image","data-busy":I.busy||void 0,dir:"ltr",children:[o.jsx("img",{src:I.src,alt:""}),o.jsx("span",{className:"sc-token-label",children:I.label}),o.jsx("button",{type:"button",className:"sc-convo-chip-x","aria-label":`Remove ${I.label}`,onClick:I.onRemove,children:o.jsx(jn,{size:11,weight:"bold"})})]},I.key)),j&&o.jsxs("span",{className:"sc-token","data-kind":"color","data-empty":j.hex?void 0:"",dir:"ltr",children:[o.jsxs(Zu,{className:"sc-convo-chip",triggerStyle:{background:"none"},value:j.hex??j.seed??"#808080",commitMode:"live",align:"start",label:j.hex?`${j.label}. Change the colour.`:"Pick a colour",onChange:j.onPick,children:[o.jsx("span",{className:"sc-token-swatch",style:j.hex?{background:j.hex}:void 0}),o.jsx("span",{className:"sc-token-label",children:j.label})]}),j.hex&&o.jsx("button",{type:"button",className:"sc-convo-chip-x","aria-label":"Remove colour",onClick:j.onClear,children:o.jsx(jn,{size:11,weight:"bold"})})]}),o.jsx("textarea",{ref:$,className:"sc-in",rows:1,maxLength:400,"aria-label":t,placeholder:j!=null&&j.hex&&!i?"":f&&h?h:e,value:i,disabled:f,onChange:I=>l(I.target.value),onKeyDown:I=>{I.key!=="Enter"||I.shiftKey||(I.preventDefault(),te())}})]}),o.jsxs("div",{className:"sc-convo-row",children:[(k||S)&&o.jsxs(o.Fragment,{children:[o.jsx(lr,{label:K&&h?h:E??"Add photos",children:o.jsx("button",{type:"button",className:"sc-convo-attach","aria-label":E??"Add photos","aria-disabled":K||void 0,onClick:K?void 0:S?()=>{var I;return(I=M.current)==null?void 0:I.click()}:k,children:o.jsx(cr,{size:16,weight:"bold"})})}),S&&o.jsx("input",{ref:M,type:"file",accept:"image/*",hidden:!0,"aria-label":E??"Add a picture",onChange:I=>{const U=Array.from(I.target.files??[]).filter(G=>G.type.startsWith("image/"));I.target.value="",U.length&&S(U)}})]}),X?o.jsx(lr,{label:X,children:z}):z]})]}),B.text?o.jsx("small",{className:"sc-convo-line",role:B.tone==="alert"?"alert":void 0,"data-tone":B.tone,children:B.text}):null]})}function QM({glyph:e,lead:t,hint:n}){return o.jsxs("div",{className:"sc-pstudio-empty",children:[o.jsxs("span",{className:"sc-pstudio-empty-mark","aria-hidden":!0,children:[o.jsx("span",{className:"sc-pstudio-empty-ring","data-at":"far"}),o.jsx("span",{className:"sc-pstudio-empty-ring","data-at":"near"}),e]}),t&&o.jsxs("span",{className:"sc-pstudio-empty-say",children:[o.jsx("span",{children:t}),n&&o.jsx("span",{children:n})]})]})}const d5=500,JM=400,eR=760,nu=e=>Math.min(eR,Math.max(JM,Math.round(e)));function dse({title:e,headAction:t,stage:n,body:r,bodyProps:a,foot:i,overlay:l,kind:u,resizeLabel:f,onPaste:h,onDropFiles:p,onClose:g}){const v=s.useRef(null),[w,y]=s.useState(null);tw(w,"--sc-pstudio-dock-h"),s.useEffect(()=>{const j=N=>{N.key!=="Escape"||N.defaultPrevented||(N.preventDefault(),g())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[g]);const[x,k]=fa(Dr.pstudioRailW,d5),S=s.useRef(0),E=s.useRef(0);return Rr.createPortal(o.jsx(Gu,{trapped:!0,loop:!0,asChild:!0,onMountAutoFocus:j=>{var N;j.preventDefault(),(N=v.current)==null||N.focus({preventScroll:!0})},children:o.jsxs("div",{ref:v,tabIndex:-1,className:"sc-pstudio","data-kind":u,style:{"--sc-pstudio-rail-set":`${nu(x)}px`},role:"dialog","aria-modal":"true","aria-labelledby":"sc-pstudio-title",onDragOver:j=>{p&&Array.from(j.dataTransfer.types).includes("Files")&&j.preventDefault()},onDrop:j=>{var P;if(!p||j.defaultPrevented)return;const N=Array.from(((P=j.dataTransfer)==null?void 0:P.files)??[]);N.length&&(j.preventDefault(),p(N))},onPaste:j=>{var P;if(!h)return;const N=Array.from(((P=j.clipboardData)==null?void 0:P.files)??[]).filter($=>$.type.startsWith("image/"));N.length&&(j.preventDefault(),h(N))},children:[o.jsxs("div",{className:"sc-pstudio-grid",children:[o.jsx("div",{className:"sc-pstudio-resize",role:"separator","aria-orientation":"vertical","aria-label":f,"aria-valuemin":JM,"aria-valuemax":eR,"aria-valuenow":nu(x),tabIndex:0,onPointerDown:j=>{j.button===0&&(j.preventDefault(),j.stopPropagation(),j.currentTarget.setPointerCapture(j.pointerId))},onPointerMove:j=>{if(!j.currentTarget.hasPointerCapture(j.pointerId))return;const N=j.currentTarget.closest(".sc-pstudio");S.current=j.clientX,!E.current&&(E.current=requestAnimationFrame(()=>{E.current=0,N==null||N.style.setProperty("--sc-pstudio-rail-set",`${nu(window.innerWidth-S.current)}px`)}))},onPointerUp:j=>{j.currentTarget.releasePointerCapture(j.pointerId),E.current&&(cancelAnimationFrame(E.current),E.current=0),k(nu(window.innerWidth-j.clientX))},onDoubleClick:()=>k(d5),onKeyDown:j=>{if(j.key==="ArrowLeft")k(N=>nu(N+16));else if(j.key==="ArrowRight")k(N=>nu(N-16));else return;j.preventDefault()}}),o.jsx(lr,{label:"Close (esc)",children:o.jsx("button",{type:"button",className:"sc-pstudio-close",onClick:g,"aria-label":"Close",children:o.jsx(jn,{size:13})})}),o.jsxs("div",{className:"sc-pstudio-head sc-newdlg-head",children:[o.jsx("h2",{id:"sc-pstudio-title",className:"sc-newdlg-title",children:e}),t,o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close",onClick:g,"aria-label":"Close",children:o.jsx(jn,{size:16})})]}),o.jsxs("div",{className:"sc-pstudio-scroll",children:[n,o.jsx("div",{className:"sc-pstudio-body",...a,children:r})]}),o.jsx("div",{className:"sc-pstudio-foot sc-dock",ref:y,children:i})]}),l]})}),document.body)}function fse({hash:e,alt:t,drawing:n,since:r,items:a,onPick:i,compare:l,doing:u,takes:f,onTake:h,empty:p,glyph:g}){const v=hse(n),[w,y]=s.useState(null),x=f??[],k=Math.max(0,x.findIndex(R=>w?R.hash===w:R.current)),S=x[k];s.useEffect(()=>y(null),[e]);const E=pse(w&&x.some(R=>R.hash===w)?w:e),[j,N]=s.useState(void 0);s.useEffect(()=>N(void 0),[e]);const P=R=>{const T=x[k+R];T&&y(T.hash)},$=s.useRef(null),[M,C]=s.useState(!1);return s.useLayoutEffect(()=>{const R=$.current;C(!(R!=null&&R.complete&&R.naturalWidth))},[E]),o.jsxs("div",{className:"sc-pstudio-stage",children:[o.jsx("div",{className:"sc-pstudio-wrap",children:o.jsxs("div",{className:"sc-pstudio-well","data-drawing":n||void 0,"data-empty":!e||void 0,style:j?{"--sc-well-ar":j}:void 0,children:[e&&E?o.jsx("img",{ref:$,src:Mr(E),srcSet:`${dn(E,"tile")} 640w, ${Mr(E)} 1024w`,sizes:"(max-width: 767px) 92vw, 44vw",alt:t,decoding:"async","data-waiting":M||void 0,onLoad:R=>{const T=R.currentTarget;C(!1),T.naturalWidth&&T.naturalHeight&&N(T.naturalWidth/T.naturalHeight)}}):o.jsx("span",{className:"sc-pstudio-well-blank",children:!n&&o.jsx(QM,{glyph:g,lead:p==null?void 0:p.lead,hint:p==null?void 0:p.hint})}),n&&!e&&o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}),n&&e&&o.jsx("span",{className:"sc-pstudio-veil","aria-hidden":!0}),n&&o.jsxs("span",{className:"sc-pstudio-doing",role:"status",children:[o.jsx("span",{className:"sc-pstudio-ring","aria-hidden":!0}),o.jsx("span",{children:u??"Drawing"}),r&&o.jsx("time",{children:rc(r,v)})]}),x.length>1&&!n&&!(l!=null&&l.on)&&o.jsxs("div",{className:"sc-pstudio-vers",children:[o.jsx("button",{type:"button",className:"sc-pstudio-vers-step","aria-label":"The version before","aria-disabled":k===0||void 0,onClick:()=>k>0&&P(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsxs("span",{className:"sc-pstudio-vers-n","aria-live":"polite",children:["Version ",(S==null?void 0:S.n)??1," of ",x.length]}),o.jsx("button",{type:"button",className:"sc-pstudio-vers-step","aria-label":"The version after","aria-disabled":k===x.length-1||void 0,onClick:()=>k<x.length-1&&P(1),children:o.jsx(ol,{size:13,weight:"bold"})}),S&&!S.current&&h&&o.jsx("button",{type:"button",className:"sc-pstudio-vers-put",onClick:()=>h(S.hash),children:"Put back"}),(S==null?void 0:S.current)&&o.jsx("span",{className:"sc-pstudio-vers-on",children:"Active"})]}),l&&!n&&o.jsx("button",{type:"button",className:"sc-pstudio-compare","aria-pressed":l.on,onClick:l.toggle,children:l.on?"Showing current":"Compare"})]})}),a.length>0&&o.jsx("ol",{className:"sc-pstudio-strip","aria-label":"Views",children:a.map(R=>{const T=R.label+(R.approved?", used":R.state==="stale"?", to be drawn again":"")+(R.photo?", your photo":"")+(R.drawing?", drawing":"")+(R.error?", failed":"");return o.jsxs("li",{children:[o.jsx("button",{type:"button",className:"sc-pstudio-slot","data-state":R.state,"data-view":R.view,"aria-current":R.state==="current"?"step":void 0,"aria-label":T,disabled:!i,onClick:()=>i==null?void 0:i(R.view),children:o.jsxs("span",{className:"sc-pstudio-slot-inner",children:[R.hash?o.jsx("img",{src:dn(R.hash,"micro"),alt:""}):null,R.drawing&&!R.hash?o.jsx("span",{className:"sc-shimmer","aria-hidden":!0}):null,R.drawing&&R.hash?o.jsx("span",{className:"sc-pstudio-slot-work sc-pstudio-ring","aria-hidden":!0}):null,R.approved&&!R.drawing?o.jsx("span",{className:"sc-pstudio-slot-mark","aria-hidden":!0,children:o.jsx(Kn,{size:11,weight:"bold"})}):null,R.error&&!R.drawing?o.jsx("span",{className:"sc-pstudio-slot-mark","data-tone":"alert","aria-hidden":!0,children:o.jsx(zp,{size:11,weight:"bold"})}):null]})}),o.jsx("span",{className:"sc-pstudio-slot-lb","data-on":R.state==="current"||void 0,"aria-hidden":!0,children:R.label})]},R.view)})})]})}function hse(e){const[t,n]=s.useState(()=>Date.now());return s.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}function pse(e){const[t,n]=s.useState(e);return s.useEffect(()=>{if(!e||e===t){e||n(void 0);return}let r=!0;const a=()=>{r&&n(e)},i=new Image;i.srcset=`${dn(e,"tile")} 640w, ${Mr(e)} 1024w`,i.sizes="(max-width: 767px) 92vw, 44vw",i.src=Mr(e),i.decode?i.decode().then(a,a):(i.onload=a,i.onerror=a);const l=window.setTimeout(a,3e3);return()=>{r=!1,window.clearTimeout(l)}},[e,t]),t}function fw({surface:e,onClose:t}){var p,g,v;const n=wr(Ks),r=e,a=(p=r.stage)==null?void 0:p.onPick,i=a?w=>a(w):void 0,l=r.turns[r.turns.length-1],u=(l==null?void 0:l.kind)==="question"&&l.question.kind==="confirm"&&!l.question.quiet?l.question:null;s.useEffect(()=>{if(!u||r.busy)return;let w=!1;const y=x=>{if(x.key!=="Enter"||x.shiftKey||x.defaultPrevented||w)return;const k=x.target;k&&(k.tagName==="INPUT"||k.tagName==="TEXTAREA"||k.tagName==="BUTTON"||k.isContentEditable)||(x.preventDefault(),w=!0,r.onAnswer(u.id,{kind:"confirm",id:u.options[0].id}))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[u,r.busy,r.onAnswer]);const f=r.glyph??o.jsx(nW,{size:32}),h=n?null:r.stage?o.jsx(fse,{hash:r.stage.hash,alt:r.stage.alt,drawing:r.stage.drawing,since:r.stage.since,doing:r.stage.doing,takes:r.stage.takes,onTake:r.stage.onTake,items:r.stage.items,onPick:r.stage.onPick,compare:r.stage.compare,empty:r.stageEmpty,glyph:f}):o.jsx("div",{className:"sc-pstudio-stage","data-reserve":!0,children:o.jsx("div",{className:"sc-pstudio-wrap",children:o.jsx("div",{className:"sc-pstudio-well","data-empty":!0,children:o.jsx("span",{className:"sc-pstudio-well-blank",children:o.jsx(QM,{glyph:f,lead:(g=r.stageEmpty)==null?void 0:g.lead,hint:(v=r.stageEmpty)==null?void 0:v.hint})})})})});return o.jsx(dse,{kind:r.kind??"presenter",title:r.title,headAction:r.headAction,resizeLabel:"Resize the conversation",onPaste:r.onPaste,onClose:t,overlay:r.overlay,stage:h,bodyProps:{"data-convo":!0},body:o.jsx(CJ,{turns:r.turns,busy:r.busy,working:r.working,memoryKey:r.memoryKey,resumed:r.resumed,onAnswer:r.onAnswer,onEdit:r.onEdit,onSaveEdit:r.onSaveEdit,onCancelEdit:r.onCancelEdit,onRestore:r.onRestore,onRetry:r.onRetry,onShow:i,onStarter:w=>(r.onStarter??r.onText)(w),onDescribe:r.onDescribe,onAttachFiles:r.onAttachRef}),foot:o.jsxs(o.Fragment,{children:[r.dock,r.composer&&o.jsx(use,{quiet:!!r.composer.disabled&&!r.composer.working,placeholder:r.composer.placeholder,label:r.composer.label,action:r.composer.action,scope:r.composer.scope,hint:r.composer.hint,value:r.text,onValue:r.onText,allowEmpty:r.composer.allowEmpty,disabled:r.composer.disabled,why:r.composer.why,working:r.composer.working,error:r.composer.error,focusKey:r.composer.focusKey,onAttach:r.composer.onAttach,onAttachFiles:r.composer.onAttachFiles,attachLabel:r.composer.attachLabel,colour:r.composer.colour,refs:r.composer.refs,onStop:r.composer.onStop,stopping:r.composer.stopping,onSend:r.onSend})]})})}const ld=[{id:"glasses",label:"Glasses",ask:"What glasses do they wear?",options:[{id:"thin black rectangular metal frames",label:"Thin black",card:"glasses-1"},{id:"round thin gold metal frames",label:"Round metal",card:"glasses-2"},{id:"clear transparent acetate frames",label:"Clear acetate",card:"glasses-3"},{id:"bold thick black rectangular acetate frames",label:"Bold rectangular",card:"glasses-4"},{id:"tortoiseshell acetate frames",label:"Tortoiseshell",card:"glasses-5"},{id:"rimless frames with thin temples",label:"Rimless",card:"glasses-6"}],saying:"Describe the glasses",refHint:"A clear front or three-quarter view of the frames."},{id:"freckles",label:"Freckles or marks",ask:"What marks their skin?",options:[{id:"light freckles across the nose and cheeks",label:"Light freckles",card:"freckles-1"},{id:"dense freckles across the whole face",label:"Dense freckles",card:"freckles-2"},{id:"freckles across the face and shoulders",label:"Face and shoulders",card:"freckles-3"},{id:"a small birthmark on one cheek",label:"Birthmark",card:"freckles-4"},{id:"a beauty mark above the lip",label:"Beauty mark",card:"freckles-5"}],saying:"Describe it",refHint:"A clear, close photograph of it."},{id:"makeup",label:"Makeup",ask:"What makeup do they wear?",options:[{id:"natural, barely-there makeup",label:"Natural",card:"makeup-1"},{id:"black winged eyeliner",label:"Winged liner",card:"makeup-2"},{id:"a soft smoky eye",label:"Smoky eye",card:"makeup-3"},{id:"a bold red lip",label:"Bold red lip",card:"makeup-4"},{id:"soft glamorous makeup with a warm shimmer",label:"Soft glam",card:"makeup-5"},{id:"strong defined brows and a nude lip",label:"Strong brows",card:"makeup-6"}],saying:"Describe the makeup",refHint:"A clear face photograph showing the look."},{id:"scar",label:"Scar",ask:"What scar do they have?",options:[{id:"a thin pale scar through one eyebrow",label:"Through an eyebrow",card:"scar-1"},{id:"a small pale scar on one cheek",label:"On a cheek",card:"scar-2"},{id:"a small scar on the chin",label:"On the chin",card:"scar-3"},{id:"a fine scar along the jaw",label:"Along the jaw",card:"scar-4"},{id:"a small scar beside one eye",label:"Beside an eye",card:"scar-5"},{id:"a faded scar across the bridge of the nose",label:"Across the nose",card:"scar-6"}],saying:"Describe the scar",refHint:"A clear, close photograph of it."},{id:"piercing",label:"Piercing",ask:"What piercing do they wear?",options:[{id:"a small silver nose stud",label:"Nose stud",card:"piercing-1"},{id:"a silver septum ring",label:"Septum ring",card:"piercing-2"},{id:"a small silver hoop through one eyebrow",label:"Eyebrow hoop",card:"piercing-3"},{id:"several small silver hoops in one ear",label:"Ear hoops",card:"piercing-4"},{id:"a small silver lip ring",label:"Lip ring",card:"piercing-5"},{id:"a row of small silver studs up one ear",label:"Ear studs",card:"piercing-6"}],saying:"Describe the piercing",refHint:"A clear photograph of the jewellery."},{id:"tattoo",label:"Tattoo",ask:"What is their tattoo?",options:[{id:"a fine-line botanical tattoo",label:"Fine line",card:"tattoo-1"},{id:"a small geometric line tattoo",label:"Geometric",card:"tattoo-2"},{id:"a floral tattoo in soft grey shading",label:"Floral",card:"tattoo-3"},{id:"a bold traditional red rose tattoo with heavy black linework",label:"Traditional",card:"tattoo-4"},{id:"a solid blackwork snake tattoo in heavy black ink",label:"Blackwork",card:"tattoo-5"},{id:"a small script tattoo in thin lettering",label:"Script",card:"tattoo-6"}],saying:"Describe the tattoo",refHint:"A clear photograph of the design itself.",where:{ask:"And where is it?",options:[{id:"on their right forearm",label:"Right forearm"},{id:"on their left forearm",label:"Left forearm"},{id:"on their right upper arm",label:"Right upper arm"},{id:"on their left upper arm",label:"Left upper arm"},{id:"on one shoulder",label:"Shoulder"},{id:"on the side of their neck",label:"Neck"},{id:"on their hand",label:"Hand"},{id:"on their back",label:"Back"}]}},{id:"prosthetic",label:"Prosthetic limb",ask:"What does their limb look like?",options:[{id:"a matte black mechanical prosthetic limb with dark articulated joints",label:"Matte black",card:"prosthetic-1"},{id:"a brushed steel mechanical prosthetic limb with dark articulated joints",label:"Brushed steel",card:"prosthetic-2"},{id:"a woven carbon fibre mechanical prosthetic limb with dark articulated joints",label:"Carbon fibre",card:"prosthetic-3"},{id:"a skin-tone mechanical prosthetic limb with dark articulated joints",label:"Skin tone",card:"prosthetic-4"},{id:"a glossy bright red mechanical prosthetic limb with dark articulated joints",label:"Red",card:"prosthetic-5"},{id:"a matte white mechanical prosthetic limb with dark articulated joints",label:"Matte white",card:"prosthetic-6"}],saying:"Describe it",refHint:"A clear photograph showing its shape and finish.",where:{ask:"And which limb?",options:[{id:"in place of their left arm",label:"Left arm"},{id:"in place of their right arm",label:"Right arm"},{id:"in place of their left leg",label:"Left leg"},{id:"in place of their right leg",label:"Right leg"},{id:"in place of their left hand",label:"Left hand"},{id:"in place of their right hand",label:"Right hand"}]}}],va=e=>ld.find(t=>t.id===e),mse=/\b(forearm|upper arm|arm|shoulder|neck|throat|hand|wrist|back|chest|ribs|thigh|leg|calf|ankle|foot|cheek|eyebrow|brow|chin|lip|nose|ear|temple|jaw|collarbone)\b/i;function tR(e){return mse.test(e??"")}function gse(e,t){var a,i,l;const n=((a=t.words)==null?void 0:a.trim())??"",r=((i=t.where)==null?void 0:i.trim())??"";return n?r&&!tR(n)?`${n} ${r}`:n:r?`${((l=va(e))==null?void 0:l.label.toLowerCase())??e} ${r}`:""}function f5(e,t){const n=(t??[]).filter(r=>/\b(left|right)\b/i.test(r.words)&&(e==="front"||!vse.has(r.id)));if(n.length)return`Check the side: ${n.map(r=>r.words).join("; ")}. Facing you, their right is on your left.`}const vse=new Set(["tattoo","prosthetic"]),bm=["who","age","heritage","skin","hair","length","facial","eyes","build","height"],ac="either",oc=e=>{var t,n;return[(e==null?void 0:e.pick)===ac?"":(t=e==null?void 0:e.pick)==null?void 0:t.trim(),(n=e==null?void 0:e.words)==null?void 0:n.trim()].filter(Boolean).join(", ")},nR=e=>{var t;return!!(e!=null&&e.pick||(t=e==null?void 0:e.words)!=null&&t.trim())},xm=e=>{var t;return((t=e.source)==null?void 0:t.door)==="scratch"},V6=e=>{var t;return xm(e)&&((t=e.source)==null?void 0:t.via)==="taps"},km=e=>{var t;return xm(e)&&((t=e.source)==null?void 0:t.via)!=="taps"},Sm=e=>{var t;return((t=e.source)==null?void 0:t.door)==="photos"},wse=/\b(slim|slender|athletic|average|fuller|curvy|broad|lean|muscular|petite|stocky|heavy|thin|plus.size)\b/i;function hw(e){const t=e.trim(),n=t.split(/\s+/).filter(Boolean).length,r=[];return $h.test(t)||r.push("who"),hv.test(t)||r.push("age"),r.length&&!wse.test(t)&&n<8&&r.push("build"),r}const yse=(e,t)=>bm.every(n=>!cR(`look-${n}`,e,t)||e[`look-${n}`]!==void 0),rR=e=>km(e)&&e.describe!==void 0&&hw(e.describe).length>0,bse=e=>km(e)&&e.describe!==void 0&&(!rR(e)||e.gaps!==void 0),xse=(e,t)=>{var n;return Sm(e)&&!!t.draft&&t.draft.source==="photos"&&t.canGenerate&&t.draft.stage!=="analyzing"&&(e.traits!==void 0||!((n=t.draft.keep)!=null&&n.trim()))},sR=(e,t)=>V6(e)?yse(e,t):km(e)?bse(e):xse(e,t),kse=(e,t)=>xm(e)||Sm(e)&&!!t.draft,aR=e=>t=>{var n;return!!((n=t.traits)!=null&&n.includes(e))},oR=e=>t=>nR(t[`trait-${e}`]),iR=e=>t=>{var n;return aR(e)(t)&&oR(e)(t)&&!!((n=va(e))!=null&&n.where)&&!tR(oc(t[`trait-${e}`]))},J1=(e,t)=>Array.isArray(e)&&e.includes(t),Sse=(e,t)=>{var n;return sR(e,t)&&(((n=e.traits)==null?void 0:n.every(r=>oR(r)(e)&&(!iR(r)(e)||e[`trait-${r}-where`]!==void 0)))??!1)},Ese=(e,t)=>JSON.stringify(e)!==JSON.stringify(t),Cse=(e,t)=>{var r;if(!Sm(e)||!t.draft||t.draft.stage==="analyzing"||t.draft.views.portrait.status!=="empty")return!1;const n=((r=t.draft.analysis)==null?void 0:r.photos)??[];return n.length>0&&n.every(a=>a.usable===!1)},Xo=[{id:"source",applies:()=>!0},{id:"photos",applies:Sm},{id:"weakphotos",applies:Cse},...bm.map(e=>({id:`look-${e}`,applies:e==="facial"?t=>{var n;return V6(t)&&((n=t["look-who"])==null?void 0:n.pick)!=="woman"}:V6})),{id:"describe",applies:km},{id:"gaps",applies:rR,dependsOn:[{on:"describe"}]},{id:"traits",applies:kse,ready:sR},...ld.flatMap(e=>[{id:`trait-${e.id}`,applies:aR(e.id),dependsOn:[{on:"traits",changed:(t,n)=>J1(t,e.id)!==J1(n,e.id)}]},{id:`trait-${e.id}-where`,applies:iR(e.id),dependsOn:[{on:`trait-${e.id}`,changed:(t,n)=>oc(t)!==oc(n)},{on:"traits",changed:(t,n)=>J1(t,e.id)!==J1(n,e.id)}]}]),{id:"keep",applies:xm,ready:Sse,optional:!0,sticky:!0}],lR=new Map(Xo.map(e=>[e.id,e])),jse=Xo.map(e=>e.id),F0=e=>{const t=Xo.findIndex(n=>n.id===e);return t<0?Xo.length:t},Ase=e=>lR.get(e);function cR(e,t,n){return Ase(e).applies(t,n)}function uR(e,t,n){if(e==="photos")return!!n.draft&&n.draft.source==="photos";const r=t[e];return r===void 0?!1:rr(e)||Mse(e)?nR(r):!0}function dR(e,t){return Xo.filter(n=>n.applies(e,t)&&uR(n.id,e,t)).map(n=>n.id)}function Em(e,t){var n;return((n=Xo.find(r=>{var a;return!r.optional&&r.applies(e,t)&&(((a=r.ready)==null?void 0:a.call(r,e,t))??!0)&&!uR(r.id,e,t)}))==null?void 0:n.id)??null}function h5(e,t,n){const r={...e},a=new Set,i=new Set(Object.keys(t));for(const[u,f]of Object.entries(t))Ese(e[u],f)&&(f===void 0?delete r[u]:r[u]=f,a.add(u));if(a.size){const u=Xo.map(g=>g.id),f=Math.min(...[...a].map(g=>u.indexOf(g))),h=new Set(a),p=g=>(g.dependsOn??[]).some(v=>h.has(v.on));for(const g of Xo)u.indexOf(g.id)<=f||i.has(g.id)||r[g.id]===void 0||g.sticky||p(g)||(delete r[g.id],a.add(g.id))}let l=!0;for(;l;){l=!1;for(const u of Xo){if(r[u.id]===void 0)continue;(!i.has(u.id)&&(u.dependsOn??[]).some(h=>a.has(h.on)&&(h.changed?h.changed(e[h.on],r[h.on]):!0))||!u.applies(r,n))&&(delete r[u.id],a.add(u.id),l=!0)}}return r}function Nse(e){const t={};for(const n of e.traits??[]){const r=e[`trait-${n}`];r&&(t[n]={words:oc(r)||void 0,where:oc(e[`trait-${n}-where`])||void 0,refs:r.refs.length?r.refs:void 0})}return t}function fR(e){const t={};for(const n of bm){const r=e[`look-${n}`];r!==void 0&&(t[n]=r)}return t}const hR=e=>ld.map(t=>t.id).filter(t=>e.includes(t)),rr=e=>e.startsWith("look-"),Mse=e=>e.startsWith("trait-"),_s=e=>lR.has(e);function Jr(e){if(!e.startsWith("trait-"))return null;const t=e.endsWith("-where"),n=t?e.slice(6,-6):e.slice(6);return va(n)?{id:n,part:t?"where":"what"}:null}const Rse=[{to:8,name:"red"},{to:16,name:"scarlet"},{to:30,name:"orange"},{to:36,name:"amber"},{to:46,name:"gold"},{to:64,name:"yellow"},{to:80,name:"lime"},{to:95,name:"yellow-green"},{to:158,name:"green"},{to:172,name:"sea green"},{to:183,name:"teal"},{to:196,name:"cyan"},{to:205,name:"sky blue"},{to:215,name:"azure"},{to:240,name:"blue"},{to:252,name:"indigo"},{to:268,name:"violet"},{to:285,name:"purple"},{to:300,name:"orchid"},{to:318,name:"magenta"},{to:330,name:"fuchsia"},{to:342,name:"pink"},{to:352,name:"rose"},{to:360,name:"red"}],Pse=[{to:.05,name:"black"},{to:.16,name:"charcoal"},{to:.32,name:"dark grey"},{to:.62,name:"grey"},{to:.76,name:"light grey"},{to:.88,name:"silver"},{to:.96,name:"off-white"},{to:1.01,name:"white"}],Lse=new Set(["black","charcoal","dark grey","grey","light grey","silver","off-white","white","dark brown","brown","chestnut","auburn","copper","tan","beige","cream","amber","gold","blonde"]),Tse=e=>{const t=String(e??"").replace("#","").trim();return(t.length===3?t.split("").map(r=>r+r):[t.slice(0,2),t.slice(2,4),t.slice(4,6)]).map(r=>{const a=Number.parseInt(r,16);return Number.isFinite(a)?a:0})};function $se(e){const[t,n,r]=Tse(e),a=t/255,i=n/255,l=r/255,u=Math.max(a,i,l),f=Math.min(a,i,l),h=(u+f)/2,p=u-f;if(p===0)return{h:0,s:0,l:h};const g=p/(1-Math.abs(2*h-1));return{h:((u===a?60*((i-l)/p%6):u===i?60*((l-a)/p+2):60*((a-i)/p+4))+360)%360,s:g,l:h}}const Dse=e=>{var t;return((t=Rse.find(n=>e<n.to))==null?void 0:t.name)??"red"};function Hse(e,t,n){return e==="orange"||e==="amber"||e==="scarlet"?n<.2?"dark brown":n<.32?e==="scarlet"?"chestnut":"brown":n>=.86&&t<.6?"cream":n>=.72&&t<.6?"beige":n<.44&&t<.7?"brown":n<.62&&t<.55?"tan":null:(e==="gold"||e==="yellow")&&n<.42?"olive":(e==="indigo"||e==="violet"||e==="purple")&&n>=.72&&t<.7?"lavender":(e==="blue"||e==="azure"||e==="indigo")&&n<.22?"navy":e==="red"&&n<.34?t<.55?"burgundy":"maroon":e==="rose"&&n<.34?"burgundy":null}function Ose(e){return e<.18?"deep":e<.34?"dark":e>=.88?"pale":e>=.74?"light":""}function pR(e){var u;const{h:t,s:n,l:r}=$se(e);if(n<.09){const f=((u=Pse.find(h=>r<h.to))==null?void 0:u.name)??"grey";return{name:f,family:f,h:t,s:n,l:r}}const a=Dse(t),i=Hse(a,n,r);if(i){const f=r<.12?"deep":r>=.93?"pale":"";return{name:f?`${f} ${i}`:i,family:i,h:t,s:n,l:r}}const l=Ose(r);return l?{name:`${l} ${a}`,family:a,h:t,s:n,l:r}:n<.22?{name:`muted ${a}`,family:a,h:t,s:n,l:r}:n>.85&&r>.4&&r<.65?{name:`vivid ${a}`,family:a,h:t,s:n,l:r}:{name:a,family:a,h:t,s:n,l:r}}function Ise(e){const{family:t,h:n,s:r,l:a}=pR(e);return Lse.has(t)?!0:n>=16&&n<=60&&a>=.7&&r<.7||r<.09}const pw=[{id:"black",label:"Black",color:"#15120f"},{id:"dark brown",label:"Dark brown",color:"#3b2418"},{id:"brown",label:"Brown",color:"#6b4630"},{id:"auburn",label:"Auburn",color:"#8c3b26"},{id:"ginger",label:"Ginger",color:"#c2622a"},{id:"blonde",label:"Blonde",color:"#d8ac63"},{id:"platinum blonde",label:"Platinum",color:"#e9e1d0"},{id:"grey",label:"Grey",color:"#9b9b99"},{id:"white",label:"White",color:"#f0efed"}],mR=[{id:"buzzed",label:"Buzzed",card:"length-1"},{id:"cropped",label:"Cropped",card:"length-2"},{id:"short",label:"Short",card:"length-3"},{id:"chin-length",label:"Chin",card:"length-4"},{id:"shoulder-length",label:"Shoulder",card:"length-5"},{id:"long",label:"Long",card:"length-6"}],mw=[{id:"porcelain",label:"Porcelain",color:"#f4e0d4"},{id:"fair",label:"Fair",color:"#edcdb6"},{id:"light olive",label:"Light olive",color:"#ddb894"},{id:"olive",label:"Olive",color:"#c2935f"},{id:"tan",label:"Tan",color:"#a9713f"},{id:"brown",label:"Brown",color:"#7c4f2c"},{id:"deep brown",label:"Deep brown",color:"#57351d"},{id:"deep",label:"Deep",color:"#3a2114"}],gR=[{id:"slight",label:"Slight",card:"build-1"},{id:"lean",label:"Lean",card:"build-2"},{id:"average",label:"Average",card:"build-3"},{id:"solid",label:"Solid",card:"build-4"},{id:"full",label:"Full",card:"build-5"}],Fse=[{id:"East Asian",label:"East Asian"},{id:"South Asian",label:"South Asian"},{id:"Southeast Asian",label:"Southeast Asian"},{id:"Middle Eastern",label:"Middle Eastern"},{id:"Mediterranean",label:"Mediterranean"},{id:"North African",label:"North African"},{id:"West African",label:"West African"},{id:"East African",label:"East African"},{id:"Northern European",label:"Northern European"},{id:"Eastern European",label:"Eastern European"},{id:"Latin American",label:"Latin American"},{id:"Caribbean",label:"Caribbean"},{id:"mixed heritage",label:"Mixed"}],gw=[{id:"dark brown",label:"Dark brown",color:"#3b2a1d"},{id:"brown",label:"Brown",color:"#6b4423"},{id:"hazel",label:"Hazel",color:"#8a7340"},{id:"amber",label:"Amber",color:"#b07d1a"},{id:"green",label:"Green",color:"#5b7a4b"},{id:"blue",label:"Blue",color:"#4a7ba7"},{id:"grey",label:"Grey",color:"#8b949c"}],vR=[{id:"clean-shaven",label:"Clean shaven",card:"facial-1"},{id:"light stubble",label:"Stubble",card:"facial-2"},{id:"a moustache",label:"Moustache",card:"facial-3"},{id:"a goatee",label:"Goatee",card:"facial-4"},{id:"a short beard",label:"Short beard",card:"facial-5"},{id:"a full beard",label:"Full beard",card:"facial-6"}],wR=[{id:"very short",label:"Very short",card:"height-1"},{id:"short",label:"Short",card:"height-2"},{id:"average height",label:"Average",card:"height-3"},{id:"tall",label:"Tall",card:"height-4"},{id:"very tall",label:"Very tall",card:"height-5"}],_se={},yR=[{id:"woman",label:"Woman"},{id:"man",label:"Man"},{id:"androgynous",label:"Androgynous"}],bR=["20s","30s","40s","50s","60+"].map(e=>({id:e,label:e})),Lf={who:{row:{id:"who",label:"Who",options:yR},prompt:"Who are they?"},age:{row:{id:"age",label:"Age",options:bR},prompt:"Roughly how old?"},heritage:{row:{id:"heritage",label:"Heritage",options:Fse},prompt:"Where are they from?"},skin:{row:{id:"skin",label:"Skin",options:mw},prompt:"And their skin?"},eyes:{row:{id:"eyes",label:"Eyes",options:gw},prompt:"What colour are their eyes?"},facial:{row:{id:"facial",label:"Facial hair",options:vR},prompt:"Any facial hair?"},hair:{row:{id:"hair",label:"Hair",options:pw},prompt:"What colour is their hair?"},length:{row:{id:"length",label:"Length",options:mR},prompt:"And the length?"},build:{row:{id:"build",label:"Build",options:gR},prompt:"And their build?"},height:{row:{id:"height",label:"Height",options:wR},prompt:"And how tall?"}};bm.map(e=>Lf[e]);const p5=new Set(["hair","skin","eyes"]),Zse={who:"Who they are, in your words",age:"Their age, in words or a number",heritage:"Where they are from, in your words",hair:"Their hair colour, in words or a swatch",length:"Their cut, in your words",facial:"Their facial hair, in your words",eyes:"Their eye colour, in words or a swatch",skin:"Their skin, in words or a swatch",build:"Their build, in your words",height:"How tall they are, in your words"},Vse=e=>e==="man"?"man":e==="woman"?"woman":"androgynous",zse=new Set(["length","height","build"]),Bse=900;function vw(e,t,n){const r=Use(e,t);if(r.far<Bse)return r.id;const a=pR(e).name;return n==="hair"&&!Ise(e)?`dyed ${a}`:a}function Use(e,t,n){const r=h=>{const p=h.replace("#","");return(p.length===3?p.split("").map(v=>v+v):[p.slice(0,2),p.slice(2,4),p.slice(4,6)]).map(v=>Number.parseInt(v,16)||0)},[a,i,l]=r(e);let u=t[0],f=Number.POSITIVE_INFINITY;for(const h of t){if(!h.color)continue;const[p,g,v]=r(h.color),w=(a-p)**2+(i-g)**2+(l-v)**2;w<f&&(f=w,u=h)}return{id:u.id,far:f}}const m5=e=>e==="skin"?mw:e==="eyes"?gw:pw,xh=e=>e.charAt(0).toUpperCase()+e.slice(1);function xR(e){const t=H=>H!=null&&H.pick&&H.pick!==ac?H.pick:"",n=(H,D,K)=>{var Z;const O=t(H);return O?O.startsWith("#")?vw(O,D,K):O:((Z=H==null?void 0:H.words)==null?void 0:Z.trim())??""},r=H=>{var D;return t(H)?((D=H==null?void 0:H.words)==null?void 0:D.trim())??"":""},a=(H,...D)=>[H,...D.filter(Boolean)].join(" "),i=(H,D,K)=>n(H,D,K).toLowerCase(),l={androgynous:"androgynous person",man:"man",woman:"woman"},u=i(e.who,[]),f=l[u]??u,p=[n(e.heritage,[]),f].filter(Boolean).join(" "),v=[p?/^(a|an|the)\s/i.test(p)?p:`${/^[aeiou]/i.test(p)?"an":"a"} ${p}`:"a person"],w=i(e.age,[]),y=w==="60+"?"in their 60s or older":/^\d{1,3}$/.test(w)?`aged ${w}`:`in their ${w}`;w&&v.push(a(y,r(e.age)));const x=[],k=i(e.length,mR),S=i(e.hair,pw,"hair"),E=[k,S].filter(Boolean).join(" ");E&&x.push(a(`${E} hair`,r(e.length),r(e.hair)));const j=i(e.facial,vR);j&&x.push(a(j,r(e.facial)));const N=i(e.eyes,gw);N&&x.push(a(`${N} eyes`,r(e.eyes)));const P=i(e.skin,mw,"skin");P&&x.push(a(`${P} skin`,r(e.skin)));const $=i(e.height,wR),M=i(e.build,gR),C=$?a(_se[$]??$,r(e.height)):"",R=M?a(`${/^[aeiou]/.test(M)?"an":"a"} ${M} build`,r(e.build)):"",T=[C,R&&(C?`with ${R}`:R)].filter(Boolean).join(" ");return T&&x.push(T),x.length&&v.push(`with ${x.join(", ")}`),a(v.join(" "),r(e.who))}function Wse(e,t){var i,l;const n=t.pick,r=n===ac?"Either way":n!=null&&n.startsWith("#")?xh(vw(n,e.options,e.id)):n?((i=e.options.find(u=>u.id===n))==null?void 0:i.label)??xh(n):"",a=((l=t.words)==null?void 0:l.trim())??"";return r?a?`${r}, ${a}`:r:xh(a)}function Kse(e){return xh(xR(e))}const _0=e=>typeof e=="string"&&e.startsWith("aside:"),Gse=e=>e.slice(6),np={answers:{},revision:0,editing:null,saying:null,says:0,text:"",colour:null,composing:null,asides:[],unsure:null,extrasDeclined:!1,uploading:0},Yse="That did not read as a description of someone.",kR=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qse(e){if(!e||e==="name")return null;if(e==="keep")return"keep";const t=Jr(e);return t&&t.part==="what"?`trait-${t.id}`:null}function g5(e,t){var r;const n=qse(t);return n?{id:n,refs:((r=e.answers[n])==null?void 0:r.refs)??[]}:null}function u8(e){const t=e.composing;if(!t)return e.answers;const n=e.answers[t.id];if(!n||kR(n.refs,t.refs))return e.answers;if(!oc(n)&&!t.refs.length){const r={...e.answers};return delete r[t.id],r}return{...e.answers,[t.id]:{...n,refs:t.refs}}}function Xse(e,t){var r;if(!rr(t)&&!Jr(t))return;const n=e.answers[t];if(n)return{saying:t,text:n.words??"",colour:(r=n.pick)!=null&&r.startsWith("#")?{step:t,hex:n.pick}:null}}function z6(e,t,n,r){return e.filter(a=>!a.q||!_s(a.q)?!0:!cR(a.q,t,n)||a.edit&&t[a.q]!==void 0?!1:r===void 0||F0(a.q)<=r)}function Qse(e){const t=Object.keys(e).filter(n=>_s(n));return t.length?Math.min(...t.map(F0)):void 0}function SR(e,t){if(!e.some(r=>r.at===t.at))return t;let n=1;for(;e.some(r=>r.at===`${t.at}#${n}`);)n+=1;return{...t,at:`${t.at}#${n}`}}function d8(e,t){const n=e.unsure;if(!n)return e;const r=Em(e.answers,t),a=u=>u&&(u===r||_s(u)&&e.answers[u]!==void 0)?u:null,i=e.asides.map(u=>u.q==="unsure"?{...u,q:a(n.q)}:u),l=SR(i,{said:n.said,reply:Yse,q:a(n.q),at:n.at});return{...e,unsure:null,asides:z6([...i,l],e.answers,t)}}function Jse(e,t){var n,r,a;switch(t.type){case"answer":{const i=h5(e.answers,t.patch,t.ctx),l=!kR(i,e.answers),u=d8(e,t.ctx);return{...u,answers:i,revision:l?e.revision+1:e.revision,asides:z6(u.asides,i,t.ctx,Qse(t.patch)),editing:null,saying:null,colour:null,composing:null,text:""}}case"edit":{const i=_0(t.id)||t.id==="name"?void 0:Xse(e,t.id);return{...e,answers:u8(e),composing:_0(t.id)?null:g5(e,t.id),editing:t.id,saying:(i==null?void 0:i.saying)??null,says:i?e.says+1:e.says,colour:(i==null?void 0:i.colour)??null,text:(i==null?void 0:i.text)??""}}case"amend-aside":{const i=e.asides.find(h=>h.at===t.at),l=i!=null&&i.q&&_s(i.q)?i.q:null,u=l&&e.answers[l]!==void 0?h5(e.answers,{[l]:void 0},t.ctx):e.answers,f=z6(e.asides.filter(h=>h.at<=t.at),u,t.ctx,l?F0(l):void 0);return{...e,answers:u,revision:u===e.answers?e.revision:e.revision+1,editing:null,asides:f.map(h=>h.at===t.at?{...h,said:t.said,reply:t.reply,kind:t.kind,rev:(h.rev??0)+1}:h)}}case"drop-aside":return{...e,editing:null,asides:e.asides.filter(i=>i.at<t.at)};case"cancel-edit":return{...e,answers:u8(e),composing:null,editing:null,saying:null,colour:null,text:""};case"say":{const i=e.saying===t.id?null:t.id;return{...e,answers:u8(e),composing:g5(e,i),saying:i,says:e.says+1,colour:null,text:""}}case"text":return e.text===t.text?e:{...e,text:t.text};case"colour":return t.hex?t.step&&t.step!=="keep"?{...e,colour:{step:t.step,hex:t.hex}}:e:{...e,colour:null};case"aside":{if(!t.aside.said.trim()||!t.aside.reply.trim())return{...e,text:""};const l=!!t.aside.q&&_s(t.aside.q)&&e.answers[t.aside.q]!==void 0?{...t.aside,after:!0}:t.aside;return{...e,asides:[...e.asides,SR(e.asides,l)],text:""}}case"unsure":return{...d8(e,t.ctx),unsure:t.unsure,text:""};case"settle-unsure":return d8(e,t.ctx);case"upload-begin":return{...e,uploading:e.uploading+1};case"upload-end":return{...e,uploading:Math.max(0,e.uploading-1)};case"uploaded":{if(((n=e.answers.source)==null?void 0:n.door)!=="photos")return e;const i=e.answers.photos??{hashes:[],attested:!1};return i.hashes.includes(t.hash)||i.hashes.length>=t.max?e:{...e,answers:{...e.answers,photos:{...i,hashes:[...i.hashes,t.hash]}},revision:e.revision+1}}case"remove-photo":{const i=e.answers.photos;if(!(i!=null&&i.hashes.includes(t.hash)))return e;const l=i.hashes.filter(u=>u!==t.hash);return{...e,answers:{...e.answers,photos:{hashes:l,attested:l.length?i.attested:!1}},revision:e.revision+1}}case"attest":{if(((r=e.answers.source)==null?void 0:r.door)!=="photos")return e;const i=e.answers.photos??{hashes:[],attested:!1};return i.attested===t.checked?e:{...e,answers:{...e.answers,photos:{...i,attested:t.checked}},revision:e.revision+1}}case"ref":{if(t.id!=="keep"){const u=t.id.slice(6);if(!((a=e.answers.traits)!=null&&a.includes(u)))return e}const i=e.answers[t.id]??{refs:[]},l=t.remove?i.refs.filter(u=>u!==t.hash):t.id==="keep"?[...i.refs.filter(u=>u!==t.hash),t.hash].slice(-4):[t.hash];return l.join()===i.refs.join()?e:{...e,answers:{...e.answers,[t.id]:{...i,refs:l}},revision:e.revision+1}}case"extras-declined":return{...e,extrasDeclined:!0};case"start-over":return{...np,revision:e.revision+1,text:t.text??""};case"restore":return{...np,answers:t.answers,revision:t.revision,asides:t.asides??[]}}}function B6(e,t){return Em(e.answers,t)===null&&!e.editing&&!e.saying}const ER=5,CR=40;function eae(e){return JSON.stringify({v:ER,answers:e.answers,revision:e.revision,asides:e.asides.slice(-CR)})}function tae(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.said!="string"||typeof t.reply!="string"||typeof t.at!="string"||!t.said.trim()||!t.reply.trim())return null;const n=typeof t.q=="string"?t.q:null,r=typeof t.rev=="number"&&t.rev>0?t.rev:void 0,a=typeof t.kind=="string"?t.kind:void 0,i=t.after===!0?!0:void 0,l=t.edit===!0?!0:void 0;return{said:t.said,reply:t.reply,q:n,at:t.at,...r?{rev:r}:{},...a?{kind:a}:{},...i?{after:i}:{},...l?{edit:l}:{}}}function nae(e){var r;if(rr(e))return Lf[e.slice(5)].row.options;const t=Jr(e),n=t&&va(t.id);return n?t.part==="where"?((r=n.where)==null?void 0:r.options)??[]:n.options:[]}function v5(e,t){return t===ac||/^#[0-9a-f]{6}$/i.test(t)?{pick:t}:nae(e).some(n=>n.id===t)?{pick:t}:{words:t}}function rae(e,t){if(e==="keep")return typeof t=="string"?{words:t,refs:[]}:t;if(typeof t=="string"&&(rr(e)||Jr(e)))return v5(e,t);const n=Jr(e);if((n==null?void 0:n.part)==="what"&&t&&typeof t=="object"){const r=t,a=Array.isArray(r.refs)?r.refs:[];return r.pick!==void 0||typeof r.words!="string"?{...r,refs:a}:{...v5(e,r.words),refs:a}}return t}function rp(e){if(!e)return null;try{const t=JSON.parse(e);if(t.v!==ER&&t.v!==4&&t.v!==3&&t.v!==2||!t.answers||typeof t.answers!="object")return null;const n={};for(const[a,i]of Object.entries(t.answers))_s(a)&&(n[a]=rae(a,i));const r=(Array.isArray(t.asides)?t.asides:[]).map(tae).filter(a=>a!==null).slice(-CR);return{answers:n,revision:typeof t.revision=="number"?t.revision:0,asides:r}}catch{return null}}const Pn={source:"Who are we making? Describe someone new, or add photos of a real person.",describe:"Describe them. Age, hair, build, skin and presence all help; one or two sentences is enough.",lookHint:"Skip anything you would rather leave to us.",photos:"Add one clear photo of their face. Up to three more angles hold the likeness better.",weakPhotos:"I cannot read a face in any of those photos, so anything I draw now would be a stranger rather than them.",name:"What should we call them?",nameWhileDrawing:"While it draws: what should we call them?",nameWhileReading:"While I read them: what should we call them?",traits:"Anything else that is always true of them?",traitsPhotos:"Anything in these photos that is always true of them?",keep:"Anything else about them?",agree:"Here is the presenter, in full. Ready to draw?",identity:e=>`Here is ${e==="them"?"the face":e}. Use this person, or change something.`,change:"What should change?",landed:e=>`Here is the ${e}. Use it, or try again.`,extras:"Add back and profile views? They help shots from behind or in profile."},jR=e=>e==="photos"?"the photos":"the face",AR=[{id:"photos",label:"Add photos"},{id:"scratch",label:"Describe someone"}],sae={photos:/\b(photos?|pictures?|pics?|upload|images?|selfies?)\b/,scratch:/\b(scratch|describe|description|invent|make (someone|one|them) up|imagine|new person)\b/},aae=[{label:"Late 30s, warm",text:"A woman in her late 30s, Mediterranean, olive skin, dark shoulder-length hair, slim build, warm and composed."},{label:"Early 20s, bright",text:"A man in his early 20s, fair skin with freckles, short blond hair, athletic build, bright and easygoing."},{label:"Mid 40s, quiet",text:"A man in his mid 40s, East Asian, close-cropped black hair, lean build, quietly confident."},{label:"Late 20s, easy",text:"A woman in her late 20s, deep brown skin, natural curls, tall and graceful, with an easy laugh."},{label:"Sixties, calm",text:"A woman in her early sixties, light skin, silver hair in a soft bob, broad build, calm and assured."}],oae="I have permission to use this person's likeness.";function iae(e){const t=[];return e.over>0&&t.push(e.over===1?`That is one more than ${e.max} photos, so the last one was not added.`:`That is ${e.over} more than ${e.max} photos, so the last ${e.over} were not added.`),e.same>0&&t.push(e.same===1?"One of those is already here.":`${e.same} of those are already here.`),e.failed.length&&t.push(e.failed.join(" ")),t.length?t.join(" "):null}const lae=(e,t)=>`${e} is larger than ${Math.round(t/1024/1024)}MB. Choose a smaller copy of it.`,cae=e=>`${e} could not be read as a photograph. JPEG, PNG, WebP and HEIC all work.`,uae="First portrait appears here",dae=(e,t)=>!e||e==="portrait"||!t?uae:`The ${t} appears here`;function fae(e){return e==="agree"?"Ready when you are":e==="photos"?"Add their photos":"Keep describing your presenter"}const NR=e=>e===1?"One thing I cannot tell yet.":e===2?"Two things I cannot tell yet.":"A few things I cannot tell yet.";function hae(e){return e===1?"One photo":`${e} photos`}function pae(e,t){return e===0?"The same person, face clear. Add the clearest one first.":e===1?"One photo works. Two to four, from different angles, hold the likeness better.":e<t?`${e} photos. More angles hold the likeness better.`:"Four angles. The reference set comes from these, the first one leading."}const mae="That does not read as a description yet. Draw from it anyway, or describe them: age, hair, build, skin, presence.",gae=e=>e===0?void 0:e===1?"Changing this asks the one after it again.":`Changing this asks the ${e} after it again.`,vae="Change this answer?",wae="The face is drawn again from the change, and the views built on it follow. Nothing already saved changes.",yae="The views drawn from the photos are drawn again with the change. The photos themselves stay as they are.",bae={source:"describe them in a sentence, or pick one",describe:"a few words about them is enough: age, hair, build, skin, presence",look:"tap one, or say it in your own words",name:"a name, so the rest of the conversation can use it",refine:"say what should change: hair, age or build change the person; anything else changes the view on the stage",detail:"tap one, or say what it looks like"},xae={who:{thing:"a person",how:"tap who they are"},age:{thing:"an age",how:"tap an age, or type one: Scenri draws adults"},hair:{thing:"a hair colour",how:"tap a colour, or say it: dark auburn, salt and pepper"},length:{thing:"a length",how:"tap a length, or say it: a chin-length bob"},skin:{thing:"a skin tone",how:"tap a tone, or say it: warm olive"},build:{thing:"a build",how:"tap a build, or say it: lean and tall"}},ss=e=>e.charAt(0).toUpperCase()+e.slice(1);function Pl(e,t,n,r="",a,i=!1){const l=t==="look"?xae[a??""]??null:null,u=(l==null?void 0:l.how)??bae[t],f=i?"":` ${ss(u)}.`;if(n>=2&&e!=="likeness"){const h=t==="look"||t==="detail"?"Or Skip it and we will choose.":"";return i?h||`${ss(u)}.`:`${ss(u)}.${h?` ${h}`:""}`}switch(e){case"likeness":return"Describe them by looks. Scenri does not draw a named person.";case"help":return l?`${ss(u)}.`:t==="refine"?"Select a view and say what is wrong with it, or say what should change about them: hair, age, build, skin.":t==="name"?"Any name will do; it can be changed later.":t==="detail"?`${ss(u)}.`:"Describe the person in a sentence: age, hair, build, skin, presence. Or add photos of a real person.";case"question":return l?`This step asks for ${l.thing}: ${u}.`:t==="refine"?`This is where the picture is changed: ${u}.`:t==="name"?`This is where they get a name: ${u}.`:t==="detail"?`This asks what the detail looks like: ${u}.`:`This is where the person is described: ${u}.`;case"nav":return"To begin again, use Start over at the top. Close keeps the draft where it is.";case"go":return t==="refine"?"Try again redraws it as it is; a sentence says what should change.":`Nothing to draw yet. ${ss(u)}.`;case"intent":return l?`${ss(u)}.`:t==="refine"?`Nothing changes until it is said what: ${u}.`:`That is what we are here for. Who are they? ${ss(u)}.`;case"nonsense":return l?`That is not ${l.thing}.${f}`:t==="name"?`That is not a name. ${ss(u)}.`:t==="refine"?`That does not say what should change. ${ss(u)}.`:t==="detail"?`That does not say what it looks like. ${ss(u)}.`:`That does not describe anyone. ${ss(u)}.`;case"greeting":return n?`Still here.${f}`:/^(hi|hello|hey|heya|hiya|yo|hola|shalom|good)\b/i.test(r.trim())?`Hi.${f}`:`${ss(u)}.`;case"ack":return n?`Still here.${f}`:i?"Go ahead.":`Go ahead: ${u}.`;case"vague":return n?`Still here. ${ss(u)}.`:`${ss(u)}.`}}const Z0=e=>e.trim().replace(/[.\s]+$/,"");function w5(e,t){const n=e==="portrait"?"face":bn[e];return t==="cancelled"?{id:"retry",kind:"confirm",quiet:!0,prompt:`Stopped drawing the ${n}. Nothing finished was touched.`,options:[{id:"retry",label:"Draw it again"}]}:{id:"retry",kind:"confirm",tone:"alert",prompt:`The ${n} could not be drawn: ${Z0(t)}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}}function kae(e){var r;const t=(((r=e.analysis)==null?void 0:r.suitableCategories)??[]).filter(Boolean);return t.length?` Filed under ${t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}; that can change on their page.`:""}function Sae(e){if(!e)return"";const t=[...e.asks??[],...e.results??[],...e.decisions??[]].map(n=>n.at);return t.length?t.reduce((n,r)=>r>n?r:n):""}const Eae=e=>e.charAt(0).toUpperCase()+e.slice(1);function Cae({draft:e,canGenerate:t,ui:n,afterCoverage:r,asides:a,openId:i,placed:l}){var Se;const u=[],f=(Q,xe,ee)=>u.push({kind:"scenri",id:Q,text:xe,tone:ee}),h=Q=>u.push({kind:"question",question:Q}),p=((Se=e.name)==null?void 0:Se.trim())??"",g=p||"them",v=()=>{p&&(u.push({kind:"scenri",id:"asked-name",text:Pn.name,quiet:!0}),u.push({kind:"you",id:"name",text:p,editable:!0,editing:n.editingName||void 0}))},w=Q=>h({id:"name",kind:"text",prompt:Q});if(e.stage==="analyzing")return f("reading",`Reading ${jR(e.source)}.`),p?v():w(Pn.nameWhileReading),u;const y=RK(e,t);if(y&&f("coverage",y.text,y.tone),u.push(...r),!t&&e.source==="photos")return p&&v(),p?(h({id:"blind",kind:"confirm",prompt:"No engine here can draw the other views. Save them from the photos as they are?",options:[{id:"save",label:"Save with photos"},{id:"setup",label:"Set up"}]}),u):(w(Pn.name),u);const x=e.views.portrait,k=e.activeView,S=e.asks??[],E=S[S.length-1],j=E?e.views[E.view]:null,N=!!E&&!!j&&(j.status==="generating"&&e.activeView===E.view||j.status==="candidate"&&j.adjustment===E.text||!!j.error),P=Q=>Q==="portrait"&&!Ko(e)?Pn.identity(g):Pn.change,$=(e.results??[]).filter(Q=>Q.how!=="restored"),M=e.decisions??[],C=!e.activeView&&e.stage==="idle",R=new Map,T=new Map,H=new Map;for(const Q of $){const xe=`${Q.view}:${Q.hash}`;if(H.set(xe,Q),R.has(xe))continue;const ee=(T.get(Q.view)??0)+1;T.set(Q.view,ee),R.set(xe,ee)}const D=Q=>R.get(`${Q.view}:${Q.hash}`)??1,K=(Q,xe)=>{const ee=D(Q),ae=e.views[Q.view].hash===Q.hash,re=(T.get(Q.view)??0)>1;return{kind:"scenri",id:xe,text:`Here is ${bn[Q.view]} ${ee}.`,thumb:Q.hash,view:Q.view,label:`${Jl[Q.view]} ${ee}`,current:re&&ae&&H.get(`${Q.view}:${Q.hash}`)===Q,restore:C&&!ae&&!pv(e,Q.view)?{view:Q.view,hash:Q.hash}:void 0}},O=new Set,Z=new Map(S.map(Q=>{const xe=$.find(ee=>!O.has(ee)&&ee.how==="drawn"&&ee.view===Q.view&&ee.ask===Q.text&&ee.at>=Q.at);return xe&&O.add(xe),[Q,xe]})),te=new Map;for(const Q of M)Q.what==="use"&&!te.has(Q.view)&&te.set(Q.view,Q);const B=Q=>Q==="portrait"?`Here is ${g} with the change. Use this, or keep the previous one. Using it redraws the views built on the face.`:`Redrew the ${bn[Q]}. Use it, or keep the previous one.`,F=Q=>{const xe=Q===te.get(Q.view),ee=Q.view==="portrait"&&xe,ae=Q.what==="again"?"Try again":Q.what==="keep"?"Keep previous":ee?"Use this person":Q.view==="portrait"?"Use this":"Use it";return[{kind:"scenri",id:`asked-decided-${Q.at}`,text:ee?Pn.identity(g):xe?Pn.landed(bn[Q.view]):B(Q.view),quiet:!0},{kind:"you",id:`decided-${Q.at}`,text:ae,editable:!1}]},X=()=>{const Q=N?S.slice(0,-1):S,xe=Sae(e),ee=a.filter(_=>!l.has(_)&&(_.q!==i||_.at<=xe));for(const _ of ee)l.add(_);const ae=$.find(_=>fK.includes(_.view)),re=[...Q.map(_=>{const ue=Z.get(_);return{at:_.at,turns:[{kind:"scenri",id:`asked-ask-${_.at}`,text:P(_.view),quiet:!0},{kind:"you",id:`ask-${_.at}`,text:_.text,editable:!1},...ue?[K(ue,`redrew-${_.at}`)]:[]]}}),...$.filter(_=>!O.has(_)).map(_=>({at:_.at,turns:[K(_,`result-${_.at}`)]})),...M.map(_=>({at:_.at,turns:F(_)})),...ee.map(_=>({at:_.at,turns:ri(_)})),...Ko(e)&&(e.extras||n.extrasDeclined)?[{at:ae?ae.at.slice(0,-1):"~",turns:[{kind:"scenri",id:"asked-extras",text:Pn.extras,quiet:!0},{kind:"you",id:"extras",text:e.extras?"Add them":"Not now",editable:!1}]}]:[]];re.sort((_,ue)=>_.at<ue.at?-1:_.at>ue.at?1:0);for(const _ of re)u.push(..._.turns)},z=()=>{!N||!E||(u.push({kind:"scenri",id:`asked-ask-${E.at}`,text:P(E.view),quiet:!0}),u.push({kind:"you",id:`ask-${E.at}`,text:E.text,editable:!1}))};if(!Ko(e)){const Q=x.status==="generating"||k==="portrait"&&x.status!=="candidate";return Q&&!S.length?(f("drawing-face","Drawing their face."),p?v():w(Pn.nameWhileDrawing),u):(v(),X(),Q?(z(),f("drawing-face",N?"Adjusting the face. Everything else stays.":"Drawing their face."),p||w(Pn.nameWhileDrawing),u):n.failed?(h({id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${Z0(n.failed??"")}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}),u):x.error?(z(),h(w5("portrait",x.error)),u):(x.status==="candidate"&&(z(),h({id:"identity",kind:"confirm",prompt:N?"Adjusted. Use this person, or try again.":Pn.identity(g),hint:f5("portrait",e.keepItems),options:[{id:"use",label:"Use this person"},{id:"again",label:"Try again"},{id:"change",label:"Change something"}]})),u))}v(),X();const I=Object.keys(e.views),U=Wo(e),G=[...U].reverse().find(Q=>f6.has(Q)),ne=U.find(Q=>!f6.has(Q)),q=I.find(Q=>e.views[Q].status==="candidate"),le=I.find(Q=>!!e.views[Q].error);if(n.failed&&!k)return h({id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${Z0(n.failed??"")}. Nothing finished was touched.`,options:[{id:"retry",label:"Retry"}]}),u;if(k)return z(),f(`drawing-${k}`,N&&(E==null?void 0:E.view)===k?`Redrawing the ${bn[k]}.`:k===G&&!e.views[k].hash?`Drawing the ${bn[k]} from this face.`:k===ne&&!e.views[k].hash&&G?`Building the rest of the set from the ${bn[G]}.`:`Drawing the ${bn[k]}.`),p||w(Pn.nameWhileDrawing),u;if(q){z();const Q=e.views[q],xe=!!Q.prior,ee=re=>re?R.get(`${q}:${re}`)??0:0,ae=!!Q.hash&&!!Q.prior&&ee(Q.hash)<ee(Q.prior);return Q.hash&&u.push({kind:"scenri",id:`candidate-${q}-${Q.hash}`,text:ae?`Here is ${bn[q]} ${ee(Q.hash)} again.`:xe?q==="portrait"?`Here is ${g} with the change.`:`Redrew the ${bn[q]}.`:`Here is the ${bn[q]}.`,thumb:Q.hash,label:Jl[q],view:q,current:!0}),h({id:q==="portrait"?"revision":"view-revision",kind:"confirm",prompt:xe?q==="portrait"?`Use this, or keep the previous one.${PK(e,q)?" Using it redraws the views built on the face.":""}`:"Use it, or keep the previous one.":"Use it, or try again.",hint:q==="portrait"||q==="front"?f5(q,e.keepItems):void 0,options:[{id:"use",label:q==="portrait"?"Use this":"Use it"},...xe?[{id:"keep",label:"Keep previous"}]:[],{id:"again",label:"Try again"}]}),u}return le?(z(),h(w5(le,e.views[le].error??"")),u):hK(e)?!e.extras&&!n.extrasDeclined?(f("set-ready","The set is ready. Select a view and say what is wrong to redraw it."),h({id:"extras",kind:"confirm",prompt:Pn.extras,options:[{id:"add",label:"Add them"},{id:"save",label:"Not now"}]}),u):p?(h({id:"save",kind:"confirm",prompt:`${Eae(g)} is ready.${kae(e)}`,options:[{id:"save",label:"Save presenter"}]}),u):(w(Pn.name),u):(p||w(Pn.nameWhileDrawing),u)}const jae={who:{label:"Who",options:yR},age:{label:"Age",options:bR},build:{label:"Build",options:["slender","average","athletic","fuller"].map(e=>({id:e,label:e.charAt(0).toUpperCase()+e.slice(1)}))}},sp=e=>e.charAt(0).toUpperCase()+e.slice(1);function Aae(e){return!e||e==="skipped"?"Draw as is":Object.values(e).map(t=>sp(t)).join(", ")}function Nae(e){const t=e.map(n=>{var r;return((r=va(n))==null?void 0:r.label)??n});return t.length?t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`:"Nothing distinctive"}const Mae=e=>ZQ(e,AR,sae);function Cm(e){var a;if(((a=e.source)==null?void 0:a.via)==="taps"){const i=fR(e),l=oc(i.who);return xR(l&&!ra(l)?{...i,who:void 0}:i)}const t=(e.describe??"").trim(),n=e.gaps&&e.gaps!=="skipped"?e.gaps:{},r=n.build?`${t.replace(/[.\s]+$/,"")}, ${n.build} build`:t;return jK({steer:n.who??null,age:n.age??null},r)}function Rae(e){return jm(e).map(t=>t.words)}const Pae=200,Lae=12;function jm(e){var i,l;const t=Nse(e),n=(u,f,h)=>({id:u,words:f.slice(0,Pae),...h!=null&&h.length?{refs:h.slice(0,4)}:{}}),r=[];for(const u of hR(e.traits??[])){const f=t[u],h=f?gse(u,f):"";h&&r.push(n(u,h,f==null?void 0:f.refs))}const a=(((i=e.keep)==null?void 0:i.words)??"").trim();return a&&r.push(n("said",a,(l=e.keep)==null?void 0:l.refs)),r.slice(0,Lae)}function y5(e){const t=Rae(e);return t.length<2?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Tae(e){const t=e.trim().replace(/[.\s]+$/,""),n=t.replace(/^(?:but|and|also|plus|though|although|however)\b[\s,]*/i,"");return n.replace(/^(?:he|she|they|it)\s+(?:has|have|had|has got|have got|is|are|wears?|carries)\s+/i,"")||n||t}function $ae(e,t,n,r){const a=r.toLowerCase().split(/[^a-z0-9]+/).filter(l=>l.length>2);if(!a.length)return!0;const i=Cm({...e,[t]:n}).toLowerCase();return a.every(l=>i.includes(l))}function Dae(e){const t=rp(e.setup??null);return t&&Object.keys(t.answers).length?{answers:t.answers,asides:t.asides}:{answers:Hae(e),asides:[]}}function Hae(e){const t=rp(e.setup??null);return t&&Object.keys(t.answers).length?t.answers:e.source==="photos"?{source:{door:"photos",via:"taps"},photos:{hashes:e.sources??[],attested:!0},...b5(e)}:{source:{door:"scratch",via:"typed"},describe:e.direction??"",gaps:"skipped",traits:[],...b5(e)}}function b5(e){const t=e.keepItems??[];if(!t.length)return{};const n={},r=[];let a;for(const i of t){const l=ld.find(u=>u.id===i.id);if(l){r.push(l.id),n[`trait-${l.id}`]={words:i.words,refs:i.refs??[]};continue}a={words:[a==null?void 0:a.words,i.words].filter(Boolean).join(", "),refs:[...(a==null?void 0:a.refs)??[],...i.refs??[]]}}return n.traits=r,a&&(n.keep=a),n}const MR=(e,t)=>({draft:e?{source:e.source,stage:e.stage,keep:e.keep,views:{portrait:{status:e.views.portrait.status}},analysis:e.analysis?{photos:e.analysis.photos}:void 0}:null,canGenerate:t});function Oae(e,t,n){var a,i;if(e==="source")return t.kind==="choice"?{source:{door:t.id,via:"taps"}}:null;if(rr(e)){const l=(a=n[e])==null?void 0:a.words,u=l?{words:l}:{};return t.kind==="swatches"?{[e]:{pick:t.picks[e.slice(5)]??Object.values(t.picks)[0],...u}}:t.kind==="skip"?{[e]:{pick:ac,...u}}:null}if(e==="gaps")return t.kind==="choices"?{gaps:t.picks}:t.kind==="skip"?{gaps:"skipped"}:null;if(e==="traits")return t.kind==="choices"?{traits:ld.map(l=>l.id).filter(l=>t.picks[l])}:t.kind==="skip"?{traits:[]}:null;const r=Jr(e);if(r&&t.kind==="choice"){if(r.part==="where"){const u=(i=n[e])==null?void 0:i.words;return{[e]:{pick:t.id,...u?{words:u}:{}}}}const l=n[`trait-${r.id}`];return{[e]:{pick:t.id,...l!=null&&l.words?{words:l.words}:{},refs:(l==null?void 0:l.refs)??[]}}}return null}function Iae(e,t){var r;return`the ${((r=va(e))==null?void 0:r.label.toLowerCase())??"detail"} in the attached ${t===1?"picture":"pictures"}`}const x5="A scar, a ring, anything we missed",Fae=new Set(["describe","keep"]),_ae=new Set(["likeness","help","question","greeting","ack","nav","intent","go","nonsense"]);function k5(e,t){const n=(t==null?void 0:t.trim())??"";return e?n?`${e}, ${n}`:e:sp(n)}const Zae=/^(?:but|and|though|although|only|just|except(?: that)?|with|without|plus)\s+/i,S5=e=>Zae.test(e.trim());function f8(e){return e.trim().replace(/[.\s]+$/,"").replace(/^(?:but|and|though|although|only|just|except(?: that)?)\s+/i,"").trim()}function V0(e,t){if(!e)return!1;if(Fae.has(e))return!0;if(!rr(e)&&!Jr(e))return!1;const n=t[e];return!!n&&!n.pick&&!!n.words}function eh(e,t,n){const r=t.trim();return r?e==="look-age"&&bK(r)?null:e!=="look-who"&&(rr(e)||e.startsWith("trait-"))&&vK(r)?"nonsense":rr(e)||e.startsWith("trait-")||e==="keep"?zae(r,n):e==="describe"||e==="source"?Vo(r,n):null:"vague"}function h8(e,t,n){if(e&&rr(e))return"look";if(e==="keep"||e!=null&&e.startsWith("trait-"))return"detail";const r=e??t;if(r&&rr(r))return"look";if(r!=null&&r.startsWith("trait-"))return"detail";switch(r){case"source":return"source";case"describe":case"gaps":return"describe";case"name":return"name";case"traits":return"detail";default:return n?"refine":"describe"}}const E5=new Set(["who","age","hair","colour","color","length","cut","skin","build","body","name","look","style","face","person","presenter","glasses","scar","scars","tattoo","piercing","makeup","freckles","prosthetic"]),Vae=/^[a-z]{1,10}\d+$/i,zae=(e,t)=>{const n=e.trim(),r=n.toLowerCase().replace(/[^a-z ]/g,"");if(E5.has(r)||E5.has(r.replace(/^(the|their|its|his|her)\s+/,"")))return"nonsense";const a=n.split(/\s+/).filter(Boolean);if(a.length<=2&&a.some(l=>Vae.test(l)))return"nonsense";const i=Vo(e,t);return i&&_ae.has(i)?i:null};function Bae(e,t){return e==="name"?"metadata":t?e==="source"||e==="photos"?"start-over":"redraw":"plain"}function C5(e,t,n,r){var f,h,p,g,v,w,y,x,k;const a=t.answers,i=r?{reopened:!0,cost:gae(dR(a,n).filter(S=>S!=="keep"&&F0(S)>F0(e)).length)}:{};switch(e){case"source":return{id:e,kind:"choice",prompt:Pn.source,options:AR,given:(f=a.source)==null?void 0:f.door,...i};case"weakphotos":return{id:e,kind:"confirm",prompt:Pn.weakPhotos,options:[{id:"again",label:"Use different photos"},{id:"anyway",label:"Draw from these anyway"}]};case"photos":{const S=a.photos??{hashes:[],attested:!1};return{id:e,kind:"photos",prompt:Pn.photos,hint:pae(S.hashes.length,h0),hashes:S.hashes,max:h0,busy:t.uploading>0,attest:{text:oae,checked:S.attested},submit:"Continue",back:"Describe someone instead"}}case"describe":return{id:e,kind:"text",prompt:Pn.describe,starters:aae};case"gaps":{const S=hw(a.describe??"");return{id:e,kind:"choice",prompt:NR(S.length),groups:S.map(E=>({id:E,...jae[E]})),submit:"Continue",skip:"Skip, draw as is",given:a.gaps&&a.gaps!=="skipped"?a.gaps:void 0,...i}}case"traits":{const S=((h=a.source)==null?void 0:h.door)==="photos";return{id:e,kind:"choice",prompt:S?Pn.traitsPhotos:Pn.traits,multi:!0,options:ld.map(E=>({id:E.id,label:E.label})),submit:"Continue",skip:S?"Nothing to add":"Nothing else",given:a.traits,...i}}case"keep":return{id:e,kind:"text",prompt:Pn.keep}}if(rr(e)){const S=e.slice(5),{row:E,prompt:j}=Lf[S],N=Vse((p=a["look-who"])==null?void 0:p.pick),P=zse.has(S)?{...E,options:E.options.map($=>$.card?{...$,card:`${$.card}-${N}`}:$)}:E;return{id:e,kind:"swatches",prompt:j,hint:S==="who"?Pn.lookHint:void 0,row:P,skip:"Skip",describe:S==="who"?"Describe them instead":void 0,saying:t.saying===e,given:((g=a[e])==null?void 0:g.pick)===ac||(v=a[e])==null?void 0:v.pick,skipped:((w=a[e])==null?void 0:w.pick)===ac,note:(y=a[e])==null?void 0:y.words,...i}}const l=Jr(e),u=l?va(l.id):void 0;if(l&&u&&l.part==="where"&&u.where)return{id:e,kind:"choice",prompt:u.where.ask,options:u.where.options.map(S=>({id:S.id,label:S.label})),saying:t.saying===e,given:(x=a[e])==null?void 0:x.pick,note:(k=a[e])==null?void 0:k.words,...i};if(l&&u){const S=a[`trait-${l.id}`];return{id:e,kind:"choice",prompt:u.ask,hint:u.hint,options:u.options.map(E=>({id:E.id,label:E.label,card:E.card})),attach:S!=null&&S.refs.length?"Replace the reference":"Add a reference",saying:t.saying===e,given:S==null?void 0:S.pick,note:S==null?void 0:S.words,...i}}return{id:e,kind:"text",prompt:""}}function j5(e,t){var a,i,l;switch(e){case"source":return Pn.source;case"photos":return Pn.photos;case"describe":return((a=t.source)==null?void 0:a.via)==="typed"?Pn.source:Pn.describe;case"gaps":return NR(hw(t.describe??"").length);case"traits":return((i=t.source)==null?void 0:i.door)==="photos"?Pn.traitsPhotos:Pn.traits;case"keep":return Pn.keep}if(rr(e))return Lf[e.slice(5)].prompt;const n=Jr(e),r=n?va(n.id):void 0;return!n||!r?"":n.part==="where"?((l=r.where)==null?void 0:l.ask)??"":r.ask}function Uae(e,t,n){var u,f,h,p,g,v,w;switch(e){case"source":return{text:((u=t.source)==null?void 0:u.door)==="photos"?"Add photos":"Describe someone"};case"photos":{const y=(n==null?void 0:n.sources)??((f=t.photos)==null?void 0:f.hashes)??[];return{text:hae(y.length),photos:y}}case"describe":return{text:(t.describe??"").trim()};case"gaps":return{text:Aae(t.gaps)};case"traits":return{text:Nae(hR(t.traits??[]))};case"keep":return{text:(((h=t.keep)==null?void 0:h.words)??"").trim(),photos:(p=t.keep)==null?void 0:p.refs}}if(rr(e)){const y=e.slice(5);return{text:Wse(Lf[y].row,t[e]??{})}}const r=Jr(e),a=r?va(r.id):void 0;if(!r||!a)return{text:""};if(r.part==="where"){const y=t[e]??{},x=y.pick?((v=(g=a.where)==null?void 0:g.options.find(k=>k.id===y.pick))==null?void 0:v.label)??sp(y.pick):"";return{text:k5(x,y.words)}}const i=t[`trait-${r.id}`],l=i!=null&&i.pick?((w=a.options.find(y=>y.id===i.pick))==null?void 0:w.label)??sp(i.pick):"";return{text:k5(l,i==null?void 0:i.words),photos:i!=null&&i.refs.length?i.refs:void 0}}function Wae(e){const t=e.state.asides,n=t.length?NN(A5(e,[],null)):null;return A5(e,t,n)}const RR=(e,t)=>e.at<t.at?-1:e.at>t.at?1:0,ap=(e,t)=>_0(e.editing)&&Gse(e.editing)===t.at;function A5(e,t,n){const r=new Set,a=Kae(e,t,n,r),i=a.length&&a[a.length-1].kind==="question"?a.pop():null,l=t.filter(f=>!r.has(f)).sort(RR),u=e.state.unsure;for(const f of l)(!u||f.at<u.at)&&a.push(...ri(f,ap(e.state,f)));if(i&&a.push(i),u){a.push({kind:"you",id:`unsure-${u.at}`,text:u.said,editable:!1}),a.push({kind:"question",question:{id:"unsure",kind:"confirm",quiet:!0,prompt:mae,options:[{id:"use",label:"Use it anyway"}]}});for(const f of l)f.at>=u.at&&a.push(...ri(f,ap(e.state,f)))}return a}function Kae({state:e,draft:t,canGenerate:n,failed:r,awaiting:a},i,l,u){var P,$,M,C,R;const f=MR(t,n),h=e.answers,p=[{kind:"you",id:"intent",text:"Create a presenter"}],g=[],v=((P=h.source)==null?void 0:P.door)==="photos",w=(T,H,D=!1)=>{const K=i.filter(O=>!u.has(O)&&!!O.q&&O.q!==l&&H.includes(O.q)&&!!O.after===D).sort(RR);for(const O of K)u.add(O),T.push(...ri(O,ap(e,O)))},y=T=>i.find(H=>H.edit&&H.q===T&&!u.has(H)),x=(T,H,D=!0)=>{var O;if(T.push({kind:"scenri",id:`asked-${H}`,text:j5(H,h),quiet:!0}),w(T,H==="describe"&&((O=h.source)==null?void 0:O.via)==="typed"?["source","describe"]:[H]),!D){const Z=y(H);Z&&(u.add(Z),T.push({kind:"you",id:H,text:Z.said}),T.push(...ri(Z,ap(e,Z),!0))),w(T,[H],!0);return}const K=Uae(H,h,t);T.push({kind:"you",id:H,text:K.text,photos:K.photos,editable:!0,editing:e.editing===H&&V0(H,h)||void 0}),w(T,[H],!0)},k=new Set(dR(h,f)),S=jse.filter(T=>k.has(T)||i.some(H=>H.edit&&H.q===T));for(const T of S){const H=v&&t&&T!=="source"&&T!=="photos"?g:p;if(e.editing===T&&!V0(T,h)){H.push({kind:"scenri",id:`asked-${T}`,text:j5(T,h),quiet:!0}),w(H,[T]),H.push({kind:"question",question:C5(T,e,f,!0)}),w(H,[T],!0);continue}T==="source"&&(($=h.source)==null?void 0:$.via)==="typed"||x(H,T,k.has(T))}let E=null;if(((M=h.source)==null?void 0:M.door)==="scratch"&&!n&&!t)E={id:"noengine",kind:"confirm",quiet:!0,prompt:"Describing someone needs image generation, which is not set up yet.",options:[{id:"setup",label:"Set up"},{id:"photos",label:"Add photos instead"}]};else{const T=Em(h,f);T?E=C5(T,e,f,!1):!t&&((C=h.source)==null?void 0:C.door)==="scratch"&&(h.source.via==="taps"?E={id:"agree",kind:"confirm",prompt:Pn.agree,quote:`${Kse(fR(h))}${y5(h)?`, and always ${y5(h)}`:""}.`,options:[{id:"draw",label:"Draw the presenter"}]}:r&&(E={id:"retry",kind:"confirm",tone:"alert",prompt:`That did not go through: ${r}. Nothing was drawn.`,options:[{id:"retry",label:"Retry"}]}))}if(a&&(E=null),!t)return E&&p.push({kind:"question",question:E}),p;const j=Cae({draft:t,canGenerate:n,ui:{extrasDeclined:e.extrasDeclined,failed:r,editingName:e.editing==="name"},afterCoverage:g,asides:i,openId:l,placed:u}),N=[...p,...j];return E&&((R=N[N.length-1])==null?void 0:R.kind)==="question"&&N.pop(),E&&N.push({kind:"question",question:E}),N}function PR(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.kind==="question")return n.question;if(!Uh(n))return null}return null}const Ja={placeholder:"Nothing to type yet",label:"Message",action:"Send"},N5=(e,t)=>({placeholder:t?Zse[e]??"In your words":p5.has(e)?"Tap a swatch above, or say the colour":"Tap one above, or describe it",label:"Describe it",action:"Send",color:p5.has(e)});function M5(e,t){const n=Jr(e),r=n?va(n.id):void 0,a=(n==null?void 0:n.part)==="where"?"Where it is, in your words":(r==null?void 0:r.saying)??"What it looks like",i=(n==null?void 0:n.part)==="where"?"Tap one above, or say where it is":`Tap one above, or ${((r==null?void 0:r.saying)??"describe it").toLowerCase()}`;return{placeholder:t?a:i,label:(r==null?void 0:r.saying)??"Describe it",action:"Send"}}function Gae(e,t,n,r){if(t.editing!==null&&(t.editing==="name"||_0(t.editing)||V0(t.editing,t.answers)))return{...Ja,off:"Finish the change above."};if(t.saying==="keep")return{placeholder:x5,label:"What should stay the same about them",action:"Send"};if(t.saying&&rr(t.saying))return N5(t.saying.slice(5),!0);if(t.saying)return M5(t.saying,!0);if(t.editing!==null)return{...Ja,off:"Finish the change above."};if(e){if(rr(e.id))return N5(e.id.slice(5),!1);if(e.id.startsWith("trait-"))return M5(e.id,!1);switch(e.id){case"source":return{placeholder:"Describe them, or choose above",label:"Describe them",action:"Send"};case"describe":case"unsure":return{placeholder:"Describe them",label:"Describe them",action:"Send"};case"name":return{placeholder:"Their name",label:"Their name",action:"Send"};case"identity":return{placeholder:"What should change? Shorter hair, older",label:"What should change",action:"Refine"};case"agree":return{placeholder:x5,label:"Anything else that is always true of them",action:"Send"};case"traits":return{placeholder:"Tap any above, or say it in your own words",label:"Anything else that is always true of them",action:"Send"};case"gaps":return{placeholder:"Tap one above, or say it in your own words",label:"Fill in what is missing",action:"Send"};case"photos":return{...Ja,off:"Add their photos above."};case"noengine":return{...Ja,off:"Set up image generation, or add photos."};case"blind":return{...Ja,off:"Decide above."};case"retry":return{...Ja,off:"Retry above."}}}return n?n.stage==="analyzing"?{...Ja,off:`Reading ${n.source==="photos"?"the photos":"the face"}.`}:ec(n)?Ko(n)?{placeholder:R5(r,n),label:"What should change",action:"Refine",off:""}:{...Ja,off:""}:Ko(n)?{placeholder:R5(r,n),label:"What should change",action:"Refine"}:{...Ja,off:"The face comes first."}:{...Ja,off:"Starting the draft."}}function R5(e,t){var r;const n=((r=t.name)==null?void 0:r.trim())||"them";return e==="portrait"?`What should change about ${n}?`:`Change this view: ${bn[e]}`}function P5(e,t){return e.saying?e.saying:t&&_s(t.id)&&(t.id==="source"||t.id==="describe")||t&&_s(t.id)&&(rr(t.id)||t.id.startsWith("trait-"))?t.id:(t==null?void 0:t.id)==="agree"?"keep":(t==null?void 0:t.id)==="name"?"name":null}const Yae=/\b(here|in this (view|one|picture|image|frame)|this (view|one|picture|image|frame))\b/i,qae=/\b(looks? like|doesn'?t look|does not look|not (her|him|them)|drift(s|ed|ing)?|wrong|\boff\b|different person|someone else|regenerate|redraw|again)\b/i,Xae=/\b(dress|gown|outfit|wearing|wear|jacket|coat|suit|shirt|t-shirt|tee|hoodie|jeans|trousers|skirt|shoes|heels|sneakers|boots|hat|cap|sunglasses|jewell?ery|necklace|earrings|watch|holding|holds?|product|bottle|perfume|bag|handbag|phone|laptop|scene|beach|paris|london|tokyo|street|rooftop|office|kitchen|cafe|city|forest|desert|snow|rain|sunset|sunrise|golden hour|background|backdrop|lighting|campaign|shoot)\b/i,Qae=/\b(simpler|plainer|plain|neutral|cleaner|tidier)\b/i,Jae=/\b(outfit|clothes|clothing|top|wardrobe|wearing)\b/i;function LR(e,t,n){const r=e.trim();if(!r)return{blocked:"Say what should change."};if(Xae.test(r)&&!(Qae.test(r)&&Jae.test(r)))return{scope:"out-of-scope"};const a=eA.test(r),i=qae.test(r),l=Yae.test(r),u=n.source==="photos";if(t==="portrait")return u?{blocked:"Their photos define who they are. Change a drawn view instead."}:{scope:"identity",view:"portrait"};if(a&&i&&!l)return u?{scope:"view",view:t}:{scope:"ambiguous"};if(a&&!l)return u?{blocked:"Their photos define who they are. Change a drawn view instead."}:{scope:"identity",view:"portrait"};const f=n.views[t];return f.origin==="photo"?{blocked:"Your photo stands as it is. Pick a drawn view to change."}:f.status!=="approved"&&f.status!=="candidate"?{blocked:`Nothing drawn for the ${bn[t]} yet.`}:{scope:"view",view:t}}const TR=e=>`Use Create for wardrobe, products and scenes. Edits here change who ${e} is.`;function eoe(e,t,n,r){const a=e.trim(),i=t==="portrait"?"Describe a change to who they are.":"Say what is wrong with this view, or describe a change to who they are.";if(!a){const u=n.views[t];return t!=="portrait"&&u.origin==="photo"?{chip:null,hint:"Your photo stands as it is. Pick a drawn view to change."}:{chip:null,hint:i}}const l=LR(a,t,n);return"blocked"in l?{chip:null,hint:l.blocked,tone:"alert"}:l.scope==="out-of-scope"?{chip:null,hint:TR(r),tone:"alert"}:l.scope==="ambiguous"?{chip:null,hint:"This reads as the view or the person. Send it and I will ask which."}:l.scope==="identity"?{chip:{view:"portrait",label:"Changing the person"},hint:"Changes the person. The other views are redrawn after you use it."}:{chip:{view:l.view,label:`Refining the ${bn[l.view]}`},hint:"Changes this view only. Hair, skin, age or build change the person."}}const toe=e=>e.replace(/^asset:/,"");function $R(e,t){if((e.identityEdits??[]).join(`
|
|
105
105
|
`)!==(t.identityEdits??[]).join(`
|
|
106
106
|
`))return!0;const r=t.shots.some(i=>i.angle==="portrait"&&i.file),a=new Map(t.shots.map((i,l)=>[!r&&l===0?"portrait":i.angle??"",toe(i.file)]));for(const i of Wo(e)){const l=e.views[i];if(l.status==="candidate"||l.status==="stale"||l.prior)return!0;const u=a.get(i);if(l.status==="approved"&&l.hash&&l.hash!==u||l.status==="empty"&&u)return!0}return!1}const noe=e=>dK.filter(t=>e.views[t].status==="empty"&&t!=="portrait"),roe=e=>e.length<=2?e.map(t=>bn[t]).join(" and "):`${e.slice(0,-1).map(t=>bn[t]).join(", ")} and ${bn[e[e.length-1]]}`,soe={building:!1,buildDeclined:!1,scopeAsk:null,failed:null,conflict:null},aoe="Say what should change: hair, age or build change the person; anything else changes the view on the stage.",ooe="Still here. Select a view and say what is wrong with it, or say what should change about them.";function ioe(e,t,n){const r=`select a view and say what is wrong with it, or say what should change about ${t}`;switch(e){case"likeness":return"Describe the change by looks. Scenri does not draw a named person.";case"help":case"question":return`This is where ${t} is changed: ${r}.`;case"nav":return"Discard changes is at the top, and Save changes keeps what you did.";case"go":case"intent":return`Nothing changes until it is said what: ${r}.`;case"nonsense":return`That does not say what should change. ${r.charAt(0).toUpperCase()}${r.slice(1)}.`;default:return n?ooe:aoe}}const Dl={opening:e=>`What would you like to change about ${e}? Select a view to work on it, or describe a change to who they are.`,scope:"Apply this to:",change:"What should change?",saved:"Save changes when you are done."};function loe(e){const t=e.ui.asides??[],n=t.length?NN(L5(e,[],null)):null;return L5(e,t,n)}function L5({draft:e,base:t,name:n,selected:r,canGenerate:a,ui:i},l,u){var xe;const f=[{kind:"scenri",id:"opening",text:Dl.opening(n)}],h=new Set,p=()=>{for(const ee of l)h.has(ee)||f.push(...ri(ee));return f},g=(ee,ae,re)=>{re&&f.push({kind:"scenri",id:`asked-${ee}`,text:re}),f.push({kind:"you",id:ee,text:ae,editable:!1})},v=(ee,ae,re)=>f.push({kind:"scenri",id:ee,text:ae,tone:re}),w=ee=>f.push({kind:"question",question:ee});if(!e)return p();const y=noe(e),x=e.source!=="synthetic"||!!((xe=e.direction)!=null&&xe.trim()),k=Wo(e).some(ee=>e.views[ee].status==="candidate");if(y.length&&x&&!k&&!i.building&&!i.buildDeclined&&!ec(e)&&a){const ee=Wo(e).filter(ae=>e.views[ae].status==="approved").length;return w({id:"legacy",kind:"confirm",prompt:`${n} has ${ee===1?"one reference":`${ee} references`}. Build the ${roe(y)} from it?`,options:[{id:"build",label:"Build them"},{id:"not",label:"Not now"}]}),p()}const S=Wo(e),E=e.activeView,j=S.find(ee=>e.views[ee].status==="candidate"),N=S.find(ee=>!!e.views[ee].error),P=(t==null?void 0:t.identityEdits)??[];(e.identityEdits??[]).filter(ee=>!P.includes(ee)).forEach((ee,ae)=>{g(`edit-${ae}`,ee,Dl.change),v(`changed-${ae}`,`Changed ${n}. The views built on the face were redrawn.`)});const M=e.asks??[],C=M[M.length-1],R=C?e.views[C.view]:null,T=!!C&&!!R&&(R.status==="generating"&&e.activeView===C.view||R.status==="candidate"&&R.adjustment===C.text||!!R.error),H=new Set((e.identityEdits??[]).map(ee=>ee.toLowerCase())),D=(T?M.slice(0,-1):M).filter(ee=>!(ee.view==="portrait"&&H.has(ee.text.replace(/\s+/g," ").toLowerCase()))),K=[...M,...e.results??[],...e.decisions??[]].map(ee=>ee.at).reduce((ee,ae)=>ae>ee?ae:ee,""),O=l.filter(ee=>!h.has(ee)&&(ee.q!==u||ee.at<=K));for(const ee of O)h.add(ee);const Z=(e.results??[]).filter(ee=>ee.how!=="restored"),te=!e.activeView&&e.stage==="idle",B=new Map,F=new Map,X=new Map;for(const ee of Z){const ae=`${ee.view}:${ee.hash}`;if(X.set(ae,ee),B.has(ae))continue;const re=(F.get(ee.view)??0)+1;F.set(ee.view,re),B.set(ae,re)}const z=ee=>B.get(`${ee.view}:${ee.hash}`)??1,I=(ee,ae)=>{const re=z(ee),_=e.views[ee.view].hash===ee.hash,ue=(F.get(ee.view)??0)>1;return{kind:"scenri",id:ae,text:`Here is ${bn[ee.view]} ${re}.`,thumb:ee.hash,view:ee.view,label:`${Jl[ee.view]} ${re}`,current:ue&&_&&X.get(`${ee.view}:${ee.hash}`)===ee,restore:te&&!_?{view:ee.view,hash:ee.hash}:void 0}},U=new Set,G=new Map(M.map(ee=>{const ae=Z.find(re=>!U.has(re)&&re.how==="drawn"&&re.view===ee.view&&re.ask===ee.text&&re.at>=ee.at);return ae&&U.add(ae),[ee,ae]})),ne=(e.decisions??[]).filter(ee=>!(ee.view==="portrait"&&ee.what==="use")),q=ee=>[{kind:"scenri",id:`asked-decided-${ee.at}`,text:ee.view==="portrait"?`Here is ${n} with the change. Use this, or keep the previous one. Using it redraws the views built on the face.`:`Redrew the ${bn[ee.view]}. Use it, or keep the previous one.`},{kind:"you",id:`decided-${ee.at}`,text:ee.what==="again"?"Try again":ee.what==="keep"?"Keep previous":"Use it",editable:!1}],le=[...D.map(ee=>{const ae=G.get(ee);return{at:ee.at,turns:[{kind:"scenri",id:`asked-ask-${ee.at}`,text:Dl.change},{kind:"you",id:`ask-${ee.at}`,text:ee.text,editable:!1},...ae?[I(ae,`redrew-${ee.at}`)]:[]]}}),...Z.filter(ee=>!U.has(ee)).map(ee=>({at:ee.at,turns:[I(ee,`result-${ee.at}`)]})),...ne.map(ee=>({at:ee.at,turns:q(ee)})),...O.map(ee=>({at:ee.at,turns:ri(ee)}))];le.sort((ee,ae)=>ee.at<ae.at?-1:ee.at>ae.at?1:0);for(const ee of le)f.push(...ee.turns);if(i.scopeAsk)return g("scope-ask",i.scopeAsk.said),w({id:"scope",kind:"choice",prompt:Dl.scope,options:[{id:"view",label:`This view (the ${bn[r]})`},{id:"identity",label:"The presenter"}]}),p();const Se=()=>{T&&C&&g(`ask-${C.at}`,C.text,Dl.change)};if(E){const ee=e.views[E];return Se(),v(`drawing-${E}`,T&&(C==null?void 0:C.view)===E?E==="portrait"?`Changing ${n}. Everything else stays.`:`Redrawing the ${bn[E]}.`:ee.status==="stale"||S.some(ae=>e.views[ae].status==="stale")?`Redrawing the views built on the face. The ${bn[E]} first.`:`Drawing the ${bn[E]}.`),p()}if(j){Se();const ee=e.views[j];return ee.hash&&f.push({kind:"scenri",id:`candidate-${j}-${ee.hash}`,text:j==="portrait"?`Here is ${n} with the change.`:`Redrew the ${bn[j]}.`,thumb:ee.hash,label:Jl[j],view:j,current:!0}),w({id:j==="portrait"?"revision":"view-revision",kind:"confirm",prompt:j==="portrait"?"Use this, or keep the previous one. Using it redraws the views built on the face.":"Use it, or keep the previous one.",options:[{id:"use",label:j==="portrait"?"Use this":"Use it"},{id:"keep",label:"Keep previous"},{id:"again",label:"Try again"}]}),p()}if(i.failed||N){Se();const ee=!!N&&e.views[N].error==="cancelled";return w({id:"retry",kind:"confirm",...ee?{quiet:!0}:{tone:"alert"},prompt:ee?`Stopped drawing the ${bn[N]}. Nothing finished was touched.`:N?`The ${bn[N]} could not be drawn: ${Z0(e.views[N].error??"")}. Nothing finished was touched.`:`That did not go through: ${Z0(i.failed??"")}. Nothing finished was touched.`,options:[{id:"retry",label:ee?"Draw it again":"Retry"}]}),p()}if(i.conflict)return w({id:"conflict",kind:"confirm",tone:"alert",prompt:`${n} changed in another tab. Reload to continue.`,options:[{id:"reload",label:"Reload"}]}),p();const Q=S.find(ee=>e.views[ee].status==="stale");return Q?(v(`drawing-${Q}`,`Redrawing the views built on the face. The ${bn[Q]} first.`),p()):(t&&$R(e,t)&&w({id:"save",kind:"confirm",prompt:`The set is coherent. ${Dl.saved}`,options:[{id:"save",label:"Save changes"}]}),p())}function coe(e,t,n){return!(!n||t.id!==n||e&&e.id===t.id&&t.updatedAt<e.updatedAt)}function DR(e,t){const[n,r]=s.useState(null),[a,i]=s.useState(!1),[l,u]=s.useState(null),[f,h]=s.useState(!1),p=s.useRef(!0);s.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);const g=s.useRef(t);g.current=t;const v=s.useCallback(H=>{p.current&&r(D=>coe(D,H,g.current)?H:D)},[]);s.useEffect(()=>{r(null),i(!1),u(null),h(!1)},[t]);const w=s.useCallback(async()=>{if(!t)return;const H=t;try{v(await Re.presenterDraft(e,H))}catch(D){if(!p.current||g.current!==H)return;/HTTP 404|not found/i.test(String((D==null?void 0:D.message)??D))?i(!0):u(String((D==null?void 0:D.message)??D))}},[e,t,v]);s.useEffect(()=>{w()},[w]);const y=!!n&&(n.stage!=="idle"||!!n.activeView);s.useEffect(()=>{if(!y)return;const H=setInterval(()=>void w(),1500);return()=>clearInterval(H)},[y,w]);const x=s.useCallback(async H=>{const D=g.current;h(!0),u(null);try{return v(await H()),!0}catch(K){return!p.current||g.current!==D?!1:(K==null?void 0:K.status)===409?(w(),!1):(u(String((K==null?void 0:K.message)??K)),!1)}finally{p.current&&h(!1)}},[v,w]),k=s.useCallback((H,D,K)=>x(async()=>(await Re.generateDraftView(e,t??"",H,{...D?{adjustment:D}:{},...K?{decide:K}:{}})).draft),[x,e,t]),S=s.useCallback(H=>x(()=>Re.approveDraftView(e,t??"",H)),[x,e,t]),E=s.useCallback(H=>x(()=>Re.redoDraftView(e,t??"",H)),[x,e,t]),j=s.useCallback(H=>x(()=>Re.revertDraftView(e,t??"",H)),[x,e,t]),[N,P]=s.useState(!1),$=s.useCallback(async()=>{P(!0);try{return await x(()=>Re.stopDraft(e,t??""))}finally{p.current&&P(!1)}},[x,e,t]),M=s.useCallback((H,D)=>x(()=>Re.restoreDraftView(e,t??"",H,D)),[x,e,t]),C=s.useCallback((H,D)=>x(()=>Re.placeDraftPhoto(e,t??"",H,D)),[x,e,t]),R=s.useCallback(H=>x(()=>Re.updatePresenterDraft(e,t??"",H)),[x,e,t]),T=s.useCallback(()=>u(null),[]);return{draft:n,gone:a,err:l,busy:f,drawing:y,reload:w,generate:k,approve:S,redo:E,revert:j,stop:$,stopping:N,restore:M,placePhoto:C,update:R,clearErr:T}}function uoe({presenterId:e,onLeave:t,caps:n}){var ze,tt;const{brand:r}=on(),{applyBrand:a,refreshBrands:i}=Rn(),l=Ec(),u=!!(n!=null&&n.canGenerate),[f,h]=s.useState(null),[p,g]=s.useState(null),[v,w]=s.useState(soe),[y,x]=s.useState(""),[k,S]=s.useState(null),[E,j]=s.useState(!1),[N,P]=s.useState(null),[$,M]=s.useState(!1),[C,R]=s.useState(!1),T=s.useRef(new Set),H=(((ze=r.json)==null?void 0:ze.characters)??[]).find(ce=>ce.id===e),D=((tt=H==null?void 0:H.name)==null?void 0:tt.trim())||"them",K=H?{shots:H.shots??[],identityEdits:H.identityEdits??[]}:null;s.useEffect(()=>{let ce=!0;return h(null),g(null),Re.editPresenter(r.id,e).then(ve=>{ce&&h(ve.id)}).catch(ve=>{ce&&g(String((ve==null?void 0:ve.message)??ve))}),()=>{ce=!1}},[r.id,e]);const O=DR(r.id,f),Z=O.draft,te=Z?`presenter-edit:${r.id}:${e}:${Z.id}`:void 0,B=!0;s.useEffect(()=>{if(!Z||O.busy||!u||O.err)return;const ce=qj(Z);if(!ce||Z.views[ce].status==="empty"&&!v.building)return;const ve=`${ce}:${Z.views[ce].attempts}:${Z.generations}:${Z.views[ce].status}`;T.current.has(ve)||(T.current.add(ve),O.generate(ce,void 0,Ho(ce)))},[Z,O.busy,O.generate,u,O.err,v.building]);const F=Z?Xj(Z,k):"portrait",X=Z?Z.views[F]:null,z=!!Z&&(Z.activeView===F||Z.stage==="analyzing"),I=!!Z&&!Z.activeView&&Z.stage==="idle",U=O.err&&Z&&!Z.activeView?O.err:null,G=s.useMemo(()=>loe({draft:Z,base:K,name:D,selected:F,canGenerate:u,ui:{...v,failed:U}}),[Z,K,D,F,u,v,U]),ne=PR(G),q=!!Z&&!!K&&$R(Z,K),le=s.useCallback(ce=>{te&&Ii(te),t(ce)},[te,t]),Se=s.useCallback(async()=>{if(!(!Z||$)){M(!0),P(null);try{const ce=await Re.savePresenterDraft(r.id,Z.id);le(ce.presenter.id),a(ce.brand)}catch(ce){M(!1);const ve=String((ce==null?void 0:ce.message)??ce);/changed elsewhere|HTTP 409/i.test(ve)?w(Pe=>({...Pe,conflict:ve})):P(ve)}}},[Z,$,r.id,a,le]),Q=s.useCallback(async()=>{R(!0);try{Z&&await Re.deletePresenterDraft(r.id,Z.id)}catch{}le(e)},[Z,r.id,e,le]),xe=s.useCallback(async()=>{R(!0);try{const ce=await Re.revertPresenter(r.id,e);Z&&await Re.deletePresenterDraft(r.id,Z.id).catch(()=>{}),le(ce.presenter.id),a(ce.brand)}catch(ce){R(!1),P(String((ce==null?void 0:ce.message)??ce))}},[r.id,e,Z,a,le]),ee=s.useCallback((ce,ve)=>{var Pe;if(P(null),!!Z)switch(ce){case"legacy":if(ve.kind!=="confirm")return;w(de=>({...de,building:ve.id==="build",buildDeclined:ve.id!=="build"}));return;case"scope":{if(ve.kind!=="choice")return;const de=((Pe=v.scopeAsk)==null?void 0:Pe.said)??"";w(je=>({...je,scopeAsk:null})),ve.id==="identity"?O.generate("portrait",de):O.generate(F,de,Ho(F)),S(ve.id==="identity"?"portrait":F);return}case"revision":case"view-revision":{if(ve.kind!=="confirm")return;const de=Object.keys(Z.views).find(je=>Z.views[je].status==="candidate")??F;ve.id==="use"&&O.approve(de),ve.id==="keep"&&O.revert(de),ve.id==="again"&&O.generate(de,Z.views[de].adjustment,Ho(de)),j(!1);return}case"retry":{if(O.err){O.clearErr(),T.current=new Set;return}const de=Object.keys(Z.views).find(je=>!!Z.views[je].error);de&&O.generate(de,Z.views[de].adjustment,Ho(de));return}case"conflict":w(de=>({...de,conflict:null})),R(!0),i().finally(()=>le(e));return;case"save":Se();return}},[Z,v.scopeAsk,O,F,Se,i,le,e]),ae=s.useCallback(ce=>{const ve=ce.trim();if(!ve||!Z)return!1;P(null);const Pe=(ne==null?void 0:ne.id)??null,de=Wh(),je=(be,Le)=>({...be,asides:[...be.asides??[],{said:ve,reply:Le,q:Pe,at:de}]}),Ue=be=>be.scopeAsk?{...be,scopeAsk:null,asides:[...be.asides??[],{said:be.scopeAsk.said,reply:Dl.scope,q:"scope",at:be.scopeAsk.at}]}:be,ye=Vo(ve,ra);if(ye&&ye!=="vague")return w(be=>je(be,ioe(ye,D,(be.asides??[]).some(Le=>Le.q===Pe)))),x(""),!0;if(!u)return P("Image generation is not set up, so nothing can be redrawn yet."),!1;const Ee=LR(ve,F,Z);return"blocked"in Ee?(P(Ee.blocked),!1):Ee.scope==="out-of-scope"?(w(be=>je(Ue(be),TR(D))),x(""),!0):Ee.scope==="ambiguous"?(w(be=>({...Ue(be),scopeAsk:{said:ve,at:de}})),x(""),!0):(w(be=>Ue(be)),S(Ee.view),j(!1),O.generate(Ee.view,ve,Ee.scope==="view"?Ho(Ee.view):void 0),x(""),!0)},[Z,u,F,O,ne==null?void 0:ne.id,D]),re=Z?eoe(y,F,Z,D):null,_=re?{chip:re.chip?{label:re.chip.label,thumb:Z!=null&&Z.views[re.chip.view].hash?dn(Z.views[re.chip.view].hash,"micro"):void 0}:null,hint:re.hint,tone:re.tone}:null,ue=E&&(X!=null&&X.prior)?X.prior:X==null?void 0:X.hash,We=Z?(ne==null?void 0:ne.id)==="legacy"?"Decide above.":(ne==null?void 0:ne.id)==="conflict"?"Reload to continue.":(ne==null?void 0:ne.id)==="scope"?"Pick above.":(ne==null?void 0:ne.id)==="retry"?"Retry above.":Z.stage==="analyzing"?"Reading the photos.":Z.activeView?"":null:null,Xe=!!Z;return{d:Z,record:H,name:D,view:F,slot:X,dirty:q,saving:$,leaving:C,openErr:p,canRevert:!!(H!=null&&H.revisionOf),discard:Q,revert:xe,keepPrevious:X&&X.status==="approved"&&X.prior&&!z&&!(Z!=null&&Z.activeView)&&(Z==null?void 0:Z.stage)==="idle"?()=>void O.revert(F):null,surface:{title:"Edit presenter",memoryKey:te,resumed:B,turns:G,busy:O.busy||$||C,stage:Z?{hash:ue,alt:`${Jl[F]}${(X==null?void 0:X.status)==="candidate"?", candidate":""}`,drawing:z,since:nA(Z),doing:rA(Z),takes:pv(Z,F)?[]:aA(Z,F),onTake:I?ce=>void O.restore(F,ce):void 0,items:Qj(Z,F),onPick:ce=>{S(ce),j(!1)},compare:X&&X.status==="candidate"&&X.prior?{on:E,toggle:()=>j(ce=>!ce)}:void 0}:null,composer:Xe?{placeholder:F==="portrait"?`What should change about ${D}?`:`Change this view: ${bn[F]}`,label:"What should change",action:"Refine",scope:We?null:_,hint:null,why:We??void 0,error:N,disabled:O.busy||$||C||!!We,working:!!(Z!=null&&Z.activeView),onStop:Z!=null&&Z.activeView?()=>void O.stop():void 0,stopping:O.stopping,focusKey:`${(ne==null?void 0:ne.id)??"open"}:${(Z==null?void 0:Z.id)??""}`}:null,text:y,onText:x,onSend:ae,onAnswer:ee,onRestore:(ce,ve)=>{S(ce),O.restore(ce,ve)}},setupNeeded:u?null:l}}function doe({onClose:e,...t}){const n=uoe(t),r=o.jsxs(o.Fragment,{children:[n.canRevert&&o.jsx(Wn,{label:"Revert last change",tone:"quiet",title:"Revert the last saved change?",body:`${n.name} goes back to the pictures and the person before the last save. Shots already made keep what they were made with.`,busy:n.leaving,onConfirm:()=>void n.revert()}),n.dirty&&o.jsx(Wn,{label:"Discard changes",tone:"quiet",title:"Discard the changes?",body:"The views redrawn in this session are thrown away. The saved presenter stays as it was.",busy:n.leaving,onConfirm:()=>void n.discard()})]}),a=n.keepPrevious?o.jsxs("div",{className:"sc-pstudio-offer",children:[o.jsxs("span",{children:["Redrew the ",bn[n.view],"."]}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:n.keepPrevious,children:"Keep previous"})]}):n.openErr?o.jsx("p",{className:"sc-newdlg-err",role:"alert",children:n.openErr}):null;return o.jsx(fw,{surface:{...n.surface,headAction:r,dock:a},onClose:e})}function foe(){const{presenterId:e=""}=Bs(),{brand:t}=on(),n=Dn(),{caps:r}=jv();Sc("Edit presenter");const[a]=s.useState(()=>kv(t,e)),i=s.useCallback(u=>n(ha(t,u),{replace:!0}),[n,t]),l=s.useCallback(()=>n(ha(t,e),{replace:!0}),[n,t,e]);return a!==e?o.jsx(uo,{to:Up(t,a),replace:!0}):o.jsx(doe,{presenterId:e,onLeave:i,onClose:l,caps:r})}function hoe(e,t){return(t.source!=="synthetic"||(t.direction??"")===Cm(e.answers))&&poe(t.keepItems,jm(e.answers))}function poe(e,t){const n=e??[];return n.length!==t.length?!1:t.every((r,a)=>{const i=n[a];return!i||i.id!==r.id||i.words!==r.words?!1:(i.refs??[]).every(l=>(r.refs??[]).includes(l))})}function moe(e,t){return{...t.source==="synthetic"?{direction:Cm(e.answers)}:{},keepItems:jm(e.answers)}}const goe=e=>e.source==="photos"?e.views.front.hash?"front":null:e.views.portrait.hash?"portrait":null;function HR(e){if(!e.draftId)return!1;const t=e.draft;return t?e.seededFor!==t.id&&(!e.state.answers.source||!B6(e.state,e.ctx)):!0}function voe(e){const{state:t,draft:n,ctx:r}=e;if(e.busy||e.err)return[];if(n){if(HR(e))return[{kind:"seed",...Dae(n)}];if(!B6(t,r))return[];const i=[];hoe(t,n)||i.push({kind:"sync",patch:moe(t,n),redo:goe(n)});const l=e.canDraw?qj(n):null;return l&&i.push({kind:"draw",view:l,decide:Ho(l)}),i}if(e.draftId)return[];if(!e.canDraw||!B6(t,r))return[];const a=t.answers.source;return(a==null?void 0:a.door)==="scratch"&&a.via!=="taps"?[{kind:"start"}]:[]}function woe(e){for(const t of voe(e))if(!e.done.has(OR(t,e)))return t;return null}function OR(e,t){const n=t.draft;switch(e.kind){case"seed":return`seed:${n==null?void 0:n.id}`;case"start":return`start:${t.state.revision}`;case"sync":return`sync:${n==null?void 0:n.id}:${JSON.stringify(e.patch)}:${e.redo??""}`;case"draw":{const r=n==null?void 0:n.views[e.view];return`draw:${n==null?void 0:n.id}:${e.view}:${(r==null?void 0:r.attempts)??0}:${(n==null?void 0:n.generations)??0}:${(r==null?void 0:r.status)??""}`}}}const ru=(e,t)=>`scenri:presenter-setup:${e}:${t}`,su={read(e){try{return sessionStorage.getItem(e)}catch{return null}},write(e,t){try{sessionStorage.setItem(e,t)}catch{}},remove(e){try{sessionStorage.removeItem(e)}catch{}}};function yoe(e,t){var r,a,i;const n=t==="keep"?"detail":((a=va(((r=Jr(t))==null?void 0:r.id)??"glasses"))==null?void 0:a.label.toLowerCase())??"detail";return`${(i=e.answers[t])!=null&&i.refs.length?"Replace":"Add"} the picture of the ${n}`}function T5(e,t,n){const r=e.editing&&e.editing!=="name"?e.editing:e.saying??Em(e.answers,t);if(r==="keep"||!r&&n==="agree")return"keep";if(!r)return null;const a=Jr(r);return a&&a.part==="what"?`trait-${a.id}`:null}function boe({draftId:e,convoKey:t,onOpenDraft:n,onLeaveDraft:r,onStarted:a,caps:i}){var me,_e;const{brand:l}=on(),{presenterCategories:u,applyBrand:f}=Rn(),h=Ec(),p=!!(i!=null&&i.canGenerate),[g,v]=s.useReducer(Jse,{brandId:l.id,convoKey:t},W=>{const pe=rp(su.read(ru(W.brandId,W.convoKey)));return pe?{...np,answers:pe.answers,revision:pe.revision,asides:pe.asides}:np}),w=s.useRef(g);w.current=g;const y=eae(g),x=Object.keys(g.answers).length>0||g.asides.length>0,k=s.useRef(t);s.useEffect(()=>{x?su.write(ru(l.id,t),y):su.remove(ru(l.id,t));const W=k.current;k.current=t,W!==t&&e&&t===e&&(su.remove(ru(l.id,W)),Ii(`presenter-create:${l.id}:${W}`))},[l.id,t,e,y,x]);const S=s.useRef(null);s.useEffect(()=>{if(!e||S.current===y)return;const W=setTimeout(()=>{S.current=y,Re.updatePresenterDraft(l.id,e,{setup:y}).catch(()=>{S.current=null})},800);return()=>clearTimeout(W)},[l.id,e,y]);const[E,j]=s.useState(null),[N,P]=s.useState(!1),[$,M]=s.useState(null),[C,R]=s.useState([]),[T,H]=s.useState(!1),[D,K]=s.useState(null),[O,Z]=s.useState(!1),[te,B]=s.useState(null),[F,X]=s.useState(null),[z,I]=s.useState(0),[U,G]=s.useState([]),ne=s.useRef(new Map),[q]=s.useState(()=>!!e||!!rp(su.read(ru(l.id,t))));s.useEffect(()=>()=>{for(const W of ne.current.values())URL.revokeObjectURL(W)},[]);const le=s.useRef(!1),Se=s.useRef(new Set),Q=s.useRef(!1),xe=s.useRef(null),ee=s.useRef(!1),ae=DR(l.id,e),re=ae.draft,_=s.useMemo(()=>MR(re,p),[re,p]);s.useEffect(()=>{Se.current=new Set,le.current=!1,R([]),S.current=null,e||(ee.current=!1)},[e]),s.useEffect(()=>{if(le.current||!re)return;const W=AK(re,C);W&&(le.current=!0,R(W))},[re,C]),s.useEffect(()=>{ae.gone&&r()},[ae.gone,r]);const ue=s.useCallback(()=>{su.remove(ru(l.id,t)),Ii(`presenter-create:${l.id}:${t}`)},[l.id,t]),We=s.useCallback(W=>n(W,!0),[n]),Xe=s.useCallback(async()=>{const W=w.current;if(!p||O)return;const pe=W.revision;Z(!0),M(null);try{const Ie=jm(W.answers),Te=await Re.createPresenterDraft(l.id,{source:"synthetic",direction:Cm(W.answers),...Ie.length?{keepItems:Ie}:{}});if(w.current.revision!==pe){Re.deletePresenterDraft(l.id,Te.id).catch(()=>{});return}We(Te.id)}catch(Ie){M(String((Ie==null?void 0:Ie.message)??Ie))}finally{Z(!1)}},[l.id,p,O,We]),ze=s.useCallback(async()=>{const W=w.current,pe=W.answers.photos;if(!(pe!=null&&pe.hashes.length)||!pe.attested||O)return;const Ie=W.revision;Z(!0),M(null);try{const Te=await Re.createPresenterDraft(l.id,{source:"photos",imageHashes:pe.hashes,attestation:!0});if(w.current.revision!==Ie){Re.deletePresenterDraft(l.id,Te.id).catch(()=>{});return}We(Te.id)}catch(Te){M(String((Te==null?void 0:Te.message)??Te))}finally{Z(!1)}},[l.id,O,We]),tt=s.useCallback(async W=>{M(null);const pe=()=>{var vt;return((vt=w.current.answers.photos)==null?void 0:vt.hashes)??[]},Ie=W.slice(0,Math.max(0,h0-pe().length)),Te=[];let bt=0;v({type:"upload-begin"});try{for(const vt of Ie){if(vt.size>rx){Te.push(lae(vt.name,rx));continue}try{const Ct=await P0(vt);pe().includes(Ct)&&(bt+=1),v({type:"uploaded",hash:Ct,max:h0})}catch{Te.push(cae(vt.name))}}}finally{v({type:"upload-end"})}M(iae({over:W.length-Ie.length,same:bt,failed:Te,max:h0}))},[]),ce=s.useCallback(W=>{v({type:"answer",patch:W,ctx:_})},[_]),ve=s.useCallback(async W=>{const pe=W??re;if(!pe||T)return;const Ie=NK(pe,pe.name,p);if(Ie){K(Ie);return}H(!0),K(null);try{await Re.updatePresenterDraft(l.id,pe.id,{facets:C});const Te=await Re.savePresenterDraft(l.id,pe.id);f(Te.brand),ue(),v({type:"start-over"}),a({kind:"presenter",id:Te.presenter.id,name:Te.presenter.name})}catch(Te){H(!1),K(String((Te==null?void 0:Te.message)??Te))}},[re,T,p,l.id,C,ue,a,f]),Pe=s.useCallback(async()=>{var pe;if(!re||T)return;const W=(pe=re.sources)==null?void 0:pe[0];if(!W||re.views.portrait.status==="approved"){ve();return}H(!0),K(null);try{const Ie=await Re.placeDraftPhoto(l.id,re.id,"portrait",W);H(!1),await ve(Ie)}catch(Ie){H(!1),K(String((Ie==null?void 0:Ie.message)??Ie))}},[re,T,l.id,ve]),de=s.useCallback(async()=>{const pe=w.current.answers.describe||(re==null?void 0:re.direction)||"";ee.current=!0,ue(),v({type:"start-over",text:pe}),M(null),B(null),X(null),Se.current=new Set,re&&!Jj(re)&&await Re.deletePresenterDraft(l.id,re.id).catch(()=>{}),r()},[re,l.id,ue,r]),je=re?ae.err&&!ec(re)?ae.err:null:$,Ue=s.useMemo(()=>Wae({state:g,draft:re,canGenerate:p,failed:je,awaiting:HR({state:g,draft:re,ctx:_,draftId:e,seededFor:xe.current})}),[g,re,p,je,e,_]),ye=PR(Ue),Ee=s.useRef(null);Ee.current=(ye==null?void 0:ye.id)??null;const be=re?Xj(re,E):"portrait",Le=re?re.views[be]:null,Qe=!!re&&(re.activeView===be||re.stage==="analyzing"),Ke=!!re&&!re.activeView&&re.stage==="idle",nt={state:g,draft:re,ctx:_,canDraw:p,busy:ae.busy||O||Q.current||ee.current||(re?ec(re):!1),err:!!ae.err||!!$,draftId:e,seededFor:xe.current,done:Se.current},gt=woe(nt),Pt=s.useRef(gt);Pt.current=gt;const Ut=gt?OR(gt,nt):"";s.useEffect(()=>{var pe;re&&xe.current!==re.id&&!nt.busy&&!nt.err&&((pe=Pt.current)==null?void 0:pe.kind)!=="seed"&&(xe.current=re.id);const W=Pt.current;if(!(!W||Se.current.has(Ut)))switch(Se.current.add(Ut),W.kind){case"seed":xe.current=(re==null?void 0:re.id)??null,v({type:"restore",answers:W.answers,revision:w.current.revision+1,asides:W.asides});return;case"start":Xe();return;case"sync":Q.current=!0,(async()=>{await ae.update(W.patch),W.redo&&await ae.redo(W.redo)})().finally(()=>{Q.current=!1});return;case"draw":ae.generate(W.view,void 0,W.decide);return}},[Ut,re,Xe,ae.update,ae.redo,ae.generate]);const Nt=s.useCallback((W,pe,Ie,Te,bt=!1)=>{v({type:"aside",aside:{said:W,reply:pe,q:Ie,at:Wh(),kind:Te,...bt?{edit:!0}:{}}})},[]),cn=s.useCallback((W,pe)=>{M(null);const Ie=w.current;if(_s(W)){if(W==="weakphotos"&&pe.kind==="confirm"){pe.id==="again"&&de(),pe.id==="anyway"&&ce({weakphotos:{pick:"anyway"}});return}const Te=Oae(W,pe,Ie.answers);if(Te){const bt=Ie.text.trim(),vt=Te[W],Ct=(rr(W)||!!Jr(W))&&vt&&typeof vt=="object"&&!vt.words;ce(Ct&&bt?{...Te,[W]:{...vt,words:f8(bt)}}:Te);return}if(W==="photos"&&pe.kind==="photos"){const bt=pe.action;bt.type==="add"&&tt(bt.files),bt.type==="remove"&&v({type:"remove-photo",hash:bt.hash}),bt.type==="attest"&&v({type:"attest",checked:bt.checked}),bt.type==="reject"&&M("That was not an image. Drop a photo, or choose a file."),bt.type==="submit"&&ze(),bt.type==="back"&&ce({source:{door:"scratch",via:"taps"}})}return}switch(W){case"unsure":{if(pe.kind!=="confirm"||pe.id!=="use"||!Ie.unsure)return;const Te=Ie.unsure.said,bt=Ie.unsure.q==="describe"?"describe":"source";v({type:"settle-unsure",ctx:_}),ce(bt==="describe"?{describe:Te}:{source:{door:"scratch",via:"typed"},describe:Te});return}case"noengine":pe.kind==="confirm"&&pe.id==="setup"&&h(),pe.kind==="confirm"&&pe.id==="photos"&&ce({source:{door:"photos",via:"taps"}});return;case"agree":{if(pe.kind!=="confirm")return;pe.id==="draw"&&Xe();return}case"identity":if(pe.kind!=="confirm"||!re)return;pe.id==="use"&&(ae.approve("portrait"),j(null)),pe.id==="again"&&ae.generate("portrait"),pe.id==="change"&&I(Te=>Te+1);return;case"revision":case"view-revision":{if(pe.kind!=="confirm"||!re)return;const Te=W==="revision"?"portrait":Object.keys(re.views).find(bt=>re.views[bt].status==="candidate")??be;pe.id==="use"&&ae.approve(Te),pe.id==="keep"&&ae.revert(Te),pe.id==="again"&&ae.generate(Te,re.views[Te].adjustment,Ho(Te)),P(!1);return}case"retry":{if(!re){Se.current=new Set,M(null);return}if(ae.err){ae.clearErr(),Se.current=new Set;return}const Te=Object.keys(re.views).find(bt=>!!re.views[bt].error);Te&&ae.generate(Te,re.views[Te].adjustment,Ho(Te));return}case"extras":if(pe.kind!=="confirm")return;pe.id==="add"&&ae.update({extras:!0}),pe.id==="save"&&v({type:"extras-declined"});return;case"blind":if(pe.kind!=="confirm")return;pe.id==="save"&&Pe(),pe.id==="setup"&&h();return;case"save":ve();return}},[ce,tt,ze,Xe,h,re,ae,be,ve]),Fe=s.useCallback(W=>{var Ht,pn,Wt,wn,sn,In,Dt,On,Et,Hn;const pe=W.trim(),Ie=w.current,Te=P5(Ie,ye),bt=Te&&((Ht=Ie.colour)==null?void 0:Ht.step)===Te?Ie.colour.hex:null,vt=Te&&rr(Te)?Te.slice(5):null,Ct=Te==="keep"?(((pn=Ie.answers.keep)==null?void 0:pn.refs)??[]).length:Te!=null&&Te.startsWith("trait-")?(((Wt=Ie.answers[Te])==null?void 0:Wt.refs)??[]).length:0,st=pe||bt||"";if(!st&&!Ct)return!1;if(M(null),Te==="name"){const Ot=st.replace(/^(?:(?:her|his|their|the|my)\s+name\s+is|call\s+(?:her|him|them)|name:)\s*/i,"").trim()||st;return re&&ae.update({name:Ot.slice(0,60)}),v({type:"text",text:""}),!0}const $t=(Ot,tn)=>Ie.asides.filter(Vn=>Vn.q===Ot&&Vn.kind===tn).length,An=(Ot,tn=null)=>h8(Ot,tn,!!(re!=null&&re.views.portrait.hash)),Y=(Ot,tn,Vn,ur)=>{const Zr=Vn!==null&&Ie.editing===Vn;Zr&&ce({[Vn]:void 0}),Nt(Ot,tn,Vn,ur,Zr)};if(Te&&Te!=="keep"&&Te.startsWith("trait-")){const Ot=Jr(Te);if(!Ot)return!1;const tn=Ot.part==="what"?((wn=Ie.answers[Te])==null?void 0:wn.refs)??[]:[];if(!pe&&tn.length)return ce({[Te]:{pick:(sn=Ie.answers[Te])==null?void 0:sn.pick,words:Iae(Ot.id,tn.length),refs:tn}}),!0;const Vn=eh(Te,pe,ra);if(!pe||Vn)return Y(pe,Pl(Vn??"vague",An(Te),$t(Te,Vn??"vague"),pe,void 0,!0),Te,Vn??"vague"),!0;const ur=S5(pe),Zr=ur?f8(pe):pe;if(Ot.part==="where"){const zn=Ie.answers[Te];ce({[Te]:{pick:ur?zn==null?void 0:zn.pick:void 0,words:Zr}})}else{const zn=Ie.answers[Te];ce({[Te]:{pick:ur?zn==null?void 0:zn.pick:void 0,words:Zr,refs:(zn==null?void 0:zn.refs)??[]}})}return!0}if(Te==="keep"){const Ot=Ie.answers.keep,tn=(Ot==null?void 0:Ot.refs)??[],Vn=pe||(tn.length&&!(Ot!=null&&Ot.words)?"the detail in the attached picture":"");return Vn?(ce({keep:{words:[(In=Ot==null?void 0:Ot.words)==null?void 0:In.trim(),Vn].filter(Boolean).join(", "),refs:tn}}),!0):!1}if(Te&&rr(Te)&&vt){const Ot=pe&&!/^#[0-9a-f]{6}$/i.test(pe)?eh(Te,pe,ra):null;if(Ot)return Y(pe,Pl(Ot,An(Te),$t(Te,Ot),pe,vt,!0),Te,Ot),!0;const tn=Ie.answers[Te],Vn=!pe||S5(pe),ur=bt??(Vn?tn==null?void 0:tn.pick:void 0),Zr={pick:ur,words:pe?Vn?f8(pe):pe:tn==null?void 0:tn.words};if(pe&&!ur&&!$ae(Ie.answers,Te,Zr,pe)){const zn=Ie.answers.keep;return ce({keep:{words:[(Dt=zn==null?void 0:zn.words)==null?void 0:Dt.trim(),Tae(pe)].filter(Boolean).join(", "),refs:(zn==null?void 0:zn.refs)??[]}}),!0}return ce({[Te]:Zr}),!0}const he=(ye==null?void 0:ye.id)??null,Me=he==="unsure"?((On=Ie.unsure)==null?void 0:On.q)??"source":he;if(he==="traits"){const Ot=Vo(st,ra);if(Ot)return Nt(st,Pl(Ot,An(null,he),$t(he,Ot),st),he,Ot),!0;const tn=Ie.answers.keep;return ce({traits:[],keep:{words:[(Et=tn==null?void 0:tn.words)==null?void 0:Et.trim(),st].filter(Boolean).join(", "),refs:(tn==null?void 0:tn.refs)??[]}}),!0}if(he==="gaps"){const Ot=Vo(st,ra);if(Ot)return Nt(st,Pl(Ot,An(null,he),$t(he,Ot),st),he,Ot),!0;const tn=(Ie.answers.describe??"").trim().replace(/[.\s]+$/,"");return ce({describe:tn?`${tn}, ${st}`:st}),!0}const Ye=An(null,Me),dt=Me==="source"?Mae(st):null,wt=dt?null:Vo(st,ra);if(wt&&(Ye==="source"||Ye==="describe"||wt!=="vague"))return Nt(st,Pl(wt,Ye,$t(he,wt),st),he,wt),!0;if((Me==="source"||Me==="describe")&&!dt&&!ra(st))return v({type:"unsure",unsure:{said:st,q:he,at:Wh()},ctx:_}),!0;if((Me==="source"||Me==="describe")&&v({type:"settle-unsure",ctx:_}),Me==="source")return dt?(ce({source:{door:dt,via:"taps"}}),!0):(ce({source:{door:"scratch",via:"typed"},describe:st}),!0);if(Me==="describe")return ce({describe:st}),!0;if(re&&!((Hn=re.name)!=null&&Hn.trim())&&Me!=="name"&&/^[A-Z][a-z]+(?:\s[A-Z][a-z]+)?$/.test(st)&&!ra(st))return ae.update({name:st.slice(0,60)}),v({type:"text",text:""}),!0;if(Me==="name"){const Ot=st.replace(/^(?:(?:her|his|their|the|my)\s+name\s+is|call\s+(?:her|him|them)|name:)\s*/i,"").trim()||st;return re&&ae.update({name:Ot.slice(0,60)}),v({type:"text",text:""}),!0}if(!re)return!1;if(Me==="identity")return ae.generate("portrait",st),v({type:"text",text:""}),!0;const Zt=tA(st,be,re);return"blocked"in Zt?(M(Zt.blocked),!1):(j(Zt.view),P(!1),ae.generate(Zt.view,st,Zt.scope==="view"?Ho(Zt.view):void 0),v({type:"text",text:""}),!0)},[ye,ce,Nt,re,ae,be]),pt=s.useCallback(W=>{if(W==="name"){v({type:"edit",id:"name"});return}const pe=hk(W);if(pe){v({type:"edit",id:`aside:${pe}`});return}if(!_s(W))return;const Ie=Bae(W,re);if(Ie==="start-over"){B("start-over");return}if(Ie==="redraw"){X(W),B("redraw");return}v({type:"edit",id:W})},[re]),it=s.useCallback(()=>{B(null),F&&v({type:"edit",id:F}),X(null)},[F]),St=s.useCallback((W,pe)=>{const Ie=w.current.answers;if(W==="keep"||W.startsWith("trait-")&&!W.endsWith("-where")){const Te=Ie[W];ce({[W]:{pick:W==="keep"||Te==null?void 0:Te.pick,words:pe,refs:(Te==null?void 0:Te.refs)??[]}});return}if(rr(W)||W.startsWith("trait-")){const Te=Ie[W];ce({[W]:{pick:Te==null?void 0:Te.pick,words:pe}});return}ce({[W]:pe})},[ce]),xt=s.useCallback((W,pe)=>{const Ie=pe.trim();if(!Ie)return;if(W==="name"){v({type:"cancel-edit"}),re&&ae.update({name:Ie.slice(0,60)});return}const Te=hk(W);if(Te){const vt=w.current,Ct=vt.asides.find(Ye=>Ye.at===Te);if(!Ct)return;const st=Ct.q&&_s(Ct.q)?Ct.q:null,$t=st?eh(st,Ie,ra):Vo(Ie,ra);if(!$t&&st){v({type:"drop-aside",at:Te}),St(st,Ie);return}const An=h8(st,Ct.q,!!(re!=null&&re.views.portrait.hash)),Y=st&&rr(st)?st.slice(5):void 0,he=$t??"vague",Me=vt.asides.filter(Ye=>Ye.q===Ct.q&&Ye.at<Ct.at&&Ye.kind===he).length;v({type:"amend-aside",at:Te,said:Ie,reply:Pl(he,An,Me,Ie,Y),kind:he,ctx:_});return}if(!_s(W)||!V0(W,w.current.answers))return;const bt=eh(W,Ie,ra);if(bt){const vt=w.current,Ct=h8(W,W,!!(re!=null&&re.views.portrait.hash)),st=rr(W)?W.slice(5):void 0,$t=vt.asides.filter(An=>An.q===W&&An.kind===bt).length;ce({[W]:void 0}),Nt(Ie,Pl(bt,Ct,$t,Ie,st),W,bt);return}St(W,Ie)},[re,ae.update,ce,St,Fe,ye,_]),At=s.useCallback(()=>v({type:"cancel-edit"}),[]),Kt=s.useCallback(()=>{const W=w.current,pe=W.editing&&W.editing!=="name"&&!_0(W.editing)?W.editing:null,Ie=pe&&!V0(pe,W.answers)?pe:ye==null?void 0:ye.id;if(Ie==="agree"){v({type:"say",id:"keep"});return}if(!(!Ie||!_s(Ie))){if(Ie==="look-who"){ce({source:{door:"scratch",via:"words"}});return}v({type:"say",id:Ie})}},[ye==null?void 0:ye.id,ce]),et=s.useCallback(()=>T5(w.current,_,Ee.current),[_]),mt=s.useCallback(W=>{const pe=et();if(pe){M(null),w.current.saying!==pe&&v({type:"say",id:pe});for(const Ie of W.slice(0,1)){const Te=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,bt=URL.createObjectURL(Ie);G(vt=>[...vt,{key:Te,id:pe,url:bt}]),P0(Ie).then(vt=>{ne.current.set(vt,bt),v({type:"ref",id:pe,hash:vt}),G(Ct=>Ct.filter(st=>st.key!==Te))}).catch(vt=>{M(String((vt==null?void 0:vt.message)??vt)),G(Ct=>Ct.filter(st=>st.key!==Te)),URL.revokeObjectURL(bt)})}}},[et]),ot=(W,pe,Ie)=>{const Te=vw(W,pe,Ie);return Te.charAt(0).toUpperCase()+Te.slice(1)},kn=W=>m5(W).flatMap(pe=>{const Ie=pe.color?nr(pe.color):null;return Ie?[{hex:Ie,name:pe.label,slot:"accent"}]:[]}),ut=T5(g,_,(ye==null?void 0:ye.id)??null),Gt=(()=>{var $t,An,Y;if(!ut)return;const W=(($t=g.answers[ut])==null?void 0:$t.refs)??[],pe=ut==="keep"?W.slice(((An=g.composing)==null?void 0:An.id)==="keep"?g.composing.refs.length:W.length):W,Ie=U.filter(he=>he.id===ut);if(!pe.length&&!Ie.length)return;const Te=ut==="keep"?null:Jr(ut),bt=Te&&((Y=va(Te.id))==null?void 0:Y.label)||"Detail",vt=pe.length+Ie.length>1;let Ct=0;const st=()=>vt?`${bt} ${++Ct}`:bt;return[...pe.map(he=>({key:he,src:ne.current.get(he)??dn(he,"micro"),label:st(),onRemove:()=>v({type:"ref",id:ut,hash:he,remove:!0})})),...Ie.map(he=>({key:he.key,src:he.url,label:st(),busy:!0,onRemove:()=>G(Me=>Me.filter(Ye=>Ye.key!==he.key))}))]})(),Ft=Gae(ye,g,re,be),en=ae.busy||O||!!Ft.off,Jt=ut,se=P5(g,ye),oe=se==="name"?null:se,we=oe&&rr(oe)?oe.slice(5):null,ge=Ft.color&&we?kn(we):null,J=oe&&((me=g.colour)==null?void 0:me.step)===oe?g.colour.hex:null,Oe=re&&Ko(re)&&!Ft.off&&!(ye!=null&&ye.id.match(/^(name|describe)$/))?(()=>{const W=MK(g.text,be,re),pe=W.chip?re.views[W.chip.view].hash:void 0;return{chip:W.chip?{label:W.chip.label,thumb:pe?dn(pe,"micro"):void 0}:null,hint:W.hint,tone:W.tone}})():null,Be=re?Qj(re,be):[],Ve=(Le==null?void 0:Le.hash)??((re==null?void 0:re.stage)==="analyzing"?re.sources[0]:void 0),Ge=N&&(Le!=null&&Le.prior)?Le.prior:Ve;return{d:re,view:be,slot:Le,facets:C,setFacets:R,presenterCategories:u,saving:T,saveErr:D,confirming:te,setConfirming:B,confirmEdit:it,pendingEdit:F,startOver:de,begun:Object.keys(g.answers).length>0||!!re,unsaved:!re&&Object.keys(g.answers).length>0,leave:()=>{ue(),v({type:"start-over"})},revision:g.revision,open:(ye==null?void 0:ye.id)??null,keepPrevious:Le&&Le.status==="approved"&&Le.prior&&!Qe&&!(re!=null&&re.activeView)&&(re==null?void 0:re.stage)==="idle"?()=>void ae.revert(be):null,surface:{title:"Create presenter",memoryKey:`presenter-create:${l.id}:${t}`,resumed:q,turns:Ue,busy:ae.busy||O,working:(re==null?void 0:re.stage)==="analyzing"?`Reading ${jR(re.source)}`:re!=null&&re.activeView?"Drawing":O||ae.busy,stageEmpty:{lead:dae(re?be:void 0,bn[be]),hint:fae((ye==null?void 0:ye.id)??null)},stage:re?{hash:Ge,alt:`${Jl[be]}${(Le==null?void 0:Le.status)==="candidate"?", candidate":""}`,drawing:Qe,since:nA(re),doing:rA(re),takes:pv(re,be)?[]:aA(re,be),onTake:Ke?W=>void ae.restore(be,W):void 0,items:Be,onPick:W=>{j(W),P(!1)},compare:Le&&Le.status==="candidate"&&Le.prior?{on:N,toggle:()=>P(W=>!W)}:void 0}:null,composer:{placeholder:Ft.placeholder,label:Ft.label,action:Ft.action,scope:Oe,hint:null,why:Ft.off??void 0,error:$??D,disabled:en,working:!!re&&!!re.activeView&&(ye==null?void 0:ye.id)!=="name",onStop:re!=null&&re.activeView?()=>void ae.stop():void 0,stopping:ae.stopping,focusKey:ye&&!(ye.id==="agree"&&!g.saying)?`${ye.id}:${(re==null?void 0:re.id)??"setup"}:${z}:${g.saying??""}:${g.says}`:void 0,onAttach:!Jt&&!re&&(ye==null?void 0:ye.id)==="source"?()=>ce({source:{door:"photos",via:"taps"}}):void 0,onAttachFiles:Jt?mt:void 0,attachLabel:Jt?yoe(g,Jt):"Add photos",refs:Gt,colour:ge&&we?{hex:J,label:J?ot(J,m5(we),we):"Pick a colour",seed:(_e=ge[Math.floor(ge.length/2)])==null?void 0:_e.hex,onPick:W=>v({type:"colour",hex:W,step:oe}),onClear:()=>v({type:"colour",hex:null,step:oe})}:null},text:g.text,onText:W=>v({type:"text",text:W}),onSend:Fe,onAnswer:cn,onRestore:(W,pe)=>{j(W),ae.restore(W,pe)},onEdit:pt,onSaveEdit:xt,onCancelEdit:At,onDescribe:Kt,onAttachRef:mt,onStarter:W=>{(ye==null?void 0:ye.id)==="agree"&&v({type:"say",id:"keep"}),v({type:"text",text:W})},onPaste:re?void 0:W=>void tt(W)}}}function xoe({onClose:e,...t}){const n=boe(t),r=n.d;s.useEffect(()=>_h({open:n.open}),[n.open]),s.useEffect(()=>()=>_h(null),[]);const[a,i]=s.useState(!1),l=()=>{if(n.unsaved){i(!0);return}e()},u=n.begun?r?o.jsx(Wn,{label:"Start over",tone:"quiet",title:"Start over?",body:`This conversation begins again from the first question. ${Jj(r)?"The views drawn so far are kept: the unfinished presenter stays on your wall.":"Nothing has been drawn yet, so nothing is kept."}`,open:n.confirming==="start-over"||void 0,busy:!1,onOpenChange:g=>{g||n.setConfirming(null)},onConfirm:()=>void n.startOver()}):o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>void n.startOver(),children:"Start over"}):null,f=o.jsx(o.Fragment,{children:n.keepPrevious&&n.slot&&o.jsxs("div",{className:"sc-pstudio-offer",children:[o.jsxs("span",{children:["Redrew the ",bn[n.view],"."]}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:n.keepPrevious,children:"Keep previous"})]})}),h=o.jsx(Wn,{label:"Change it",title:vae,body:(r==null?void 0:r.source)==="photos"?yae:wae,busy:!1,open:n.confirming==="redraw",onOpenChange:g=>{g||n.setConfirming(null)},onConfirm:n.confirmEdit}),p=o.jsxs(o.Fragment,{children:[h,o.jsx(Wn,{label:"Leave",title:"Leave without drawing them?",body:"Nothing has been drawn yet, so the answers are not kept. Starting again starts from the first question.",busy:!1,open:a,onOpenChange:g=>{g||i(!1)},onConfirm:()=>{i(!1),n.leave(),e()}})]});return o.jsx(fw,{surface:{...n.surface,headAction:u,dock:f,overlay:p},onClose:l})}function koe(){const{draftId:e=null}=Bs(),{key:t}=Zn(),{brand:n}=on(),r=Dn(),{announce:a,caps:i}=jv();Sc("Create presenter");const l=s.useRef(!1);s.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const u=s.useCallback((p,g=!1)=>r(zi(n,p),{replace:g}),[r,n]),f=s.useCallback(()=>r(zi(n),{replace:!0}),[r,n]),h=s.useCallback(()=>r(qi(n),{replace:!0}),[r,n]);return o.jsx(xoe,{draftId:e,convoKey:e??t,onOpenDraft:u,onLeaveDraft:f,onClose:h,onStarted:p=>{a(p),l.current&&r(p.kind==="presenter"?ha(n,p.id):qi(n),{replace:!0})},caps:i})}const $5=1e3,Soe=3;function Eoe(e,t,n){return{name:e.name.trim()||t.name,prompt:t.prompt,lighting:t.lighting,description:t.description,subject:t.subject,camera:t.camera??"",figure:t.figure??"",figureTreatment:t.figureTreatment??"",keywords:t.keywords??[],collections:t.collections??[],verticals:t.verticals??[],...t.promptName?{promptName:t.promptName}:{},instruction:e.place.trim(),refHashes:e.pictures,...n?{previewHash:n}:{}}}function Coe(e){var P,$;const{s:t,dispatch:n,brandId:r,sceneId:a,conversation:i,applyBrand:l}=e,[u,f]=s.useState(!1),[h,p]=s.useState(!1),g=s.useRef(t);g.current=t;const v=s.useRef(!1),w=s.useRef(e.onSaved);w.current=e.onSaved;const y=s.useCallback(async(M,C={})=>{if(!(v.current||g.current.job)){v.current=!0;try{const R=g.current,T=Or(R),H=M==="make"?{kind:M,instruction:R.place,imageHashes:R.pictures,draw:C.draw??!1,...C.shot?{shot:!0}:{}}:M==="again"?{kind:M,reading:T==null?void 0:T.reading,imageHashes:R.pictures}:{kind:M,reading:T==null?void 0:T.reading,ask:C.ask,from:(T==null?void 0:T.hash)??void 0,imageHashes:R.pictures,draw:C.draw},D=R.name.trim()||(T==null?void 0:T.reading.name)||void 0,{jobId:K,job:O}=await Re.startSceneStudioJob(r,{...H,conversation:i,...a?{sceneId:a}:{},...D?{label:D}:{}});n({type:"started",id:K,kind:O.kind,ask:O.kind===M?C.ask:void 0,since:O.phaseAt})}catch(R){n({type:"error",text:String((R==null?void 0:R.message)??R)})}finally{v.current=!1}}},[r,n]),x=t.named?t.name.trim():"",k=((P=t.job)==null?void 0:P.id)??null;s.useEffect(()=>{!k||!x||Re.labelSceneStudioJob(r,k,x).catch(()=>{})},[k,x,r]);const S=(($=t.job)==null?void 0:$.id)??null;s.useEffect(()=>{if(!S)return;let M=!0,C=0,R;const T=async()=>{try{const H=await Re.sceneStudioJob(r,S);if(!M)return;C=0,f(!1),H.status==="running"?(n({type:"progress",job:H}),R=setTimeout(T,$5)):n({type:"finished",job:H})}catch(H){if(!M)return;if((H==null?void 0:H.status)===404){n({type:"lost",id:S,error:Ne.lost});return}C++,C>=Soe&&f(!0),R=setTimeout(T,Math.min($5*2**Math.min(C,3),8e3))}};return T(),()=>{M=!1,clearTimeout(R)}},[S,r,n]);const E=s.useCallback(()=>{const M=g.current.job;!M||M.stopping||(n({type:"stopping",id:M.id}),Re.cancelSceneStudioJob(r,M.id).catch(()=>{}))},[r,n]),j=s.useCallback(M=>{const C=uee(g.current,M);C>=0&&n({type:"put-back",index:C})},[n]),N=s.useCallback(async(M={})=>{var D,K,O,Z,te;const C=g.current,R=((D=Or(C))==null?void 0:D.reading.name)||((O=(K=C.job)==null?void 0:K.pending)==null?void 0:O.name)||"",T={...C,name:C.name.trim()||R},H=iee(T);if(!(!H.can||!H.words||v.current)){v.current=!0,p(!0);try{const B=((Z=C.job)==null?void 0:Z.phase)==="drawing"?C.job.id:null,F=B?null:((te=Or(C))==null?void 0:te.hash)??null,X=Eoe(T,H.words,F),z=a&&!M.asNew?await Re.updateScene(r,a,X):await Re.createScene(r,X);l(z.brand);const I=z.scene;if(B){const U=await Re.attachSceneStudioJob(r,B,I.id).catch(()=>null);(U==null?void 0:U.state)==="landed"&&l(U.brand)}n({type:"saved",id:I.id}),w.current({id:I.id,name:I.name,verticals:I.verticals??[]},!!M.asNew)}catch(B){n({type:"error",text:String((B==null?void 0:B.message)??B)})}finally{v.current=!1,p(!1)}}},[r,a,l,n]);return{offline:u,saving:h,start:y,stop:E,putBack:j,use:N}}const joe="scenri:scene-studio:",Aoe=10080*60*1e3;function Noe(e){const t=cs.get(e);if(!t)return null;try{const n=JSON.parse(t);return tM(typeof(n==null?void 0:n.session)=="string"?n.session:null)}catch{return null}}function Moe(e,t,n){cs.set(e,JSON.stringify({at:Date.now(),sceneId:n,session:t}))}function Roe(e){const t=e.trim();if(!t)return"A shot";if(t.length<=60)return t;const n=t.slice(0,60);return`${n.slice(0,Math.max(n.lastIndexOf(" "),40)).trim()}…`}function p8(e){cs.del(e)}function Poe(e=Date.now()){var t;for(const n of cs.keys(joe)){let r=0;try{r=Number((t=JSON.parse(cs.get(n)??"null"))==null?void 0:t.at)||0}catch{}e-r>Aoe&&cs.del(n)}}function Loe(e){var en,Jt,se,oe,we;const{brand:t,applyBrand:n,sceneId:r,seed:a,conversation:i,storageKey:l,caps:u}=e,f=r&&a?{name:a.name}:null,[h]=s.useState(()=>{Poe();const ge=Noe(l);return ge||Ii(l),ge}),[p,g]=s.useReducer(eee,null,()=>(h==null?void 0:h.setup)??JJ),[v,w]=s.useReducer(oee,null,()=>(h==null?void 0:h.studio)??a??KN),[y,x]=s.useState(0),[k,S]=s.useState(""),E=s.useRef(null),[j,N]=s.useState(!1),[P,$]=s.useState(void 0),[M,C]=s.useState(null),R=s.useRef(!1),T=s.useRef(p);T.current=p;const H=s.useRef(v);H.current=v;const[D,K]=s.useState(null),O=s.useRef(e.onSaved);O.current=e.onSaved;const Z=Coe({s:v,dispatch:w,brandId:t.id,sceneId:r,conversation:i,applyBrand:n,onSaved:(ge,J)=>O.current(ge,r&&!J?"updated":"created")});s.useEffect(()=>{R.current||Moe(l,Dee(p,v),r??v.saved)},[p,v,l,r]);const te=v.saved,B=te?Hh(t,te):void 0,F=XM(t.id,te,(B==null?void 0:B.previewUrl)??null),X=((en=F.job)==null?void 0:en.status)==="running",[z,I]=s.useState(!1);s.useEffect(()=>{X||I(!1)},[X]);const U=s.useMemo(()=>iA(B==null?void 0:B.examples,F.job),[B==null?void 0:B.examples,F.job]),G=s.useRef(e.onDone);G.current=e.onDone;const ne=s.useMemo(()=>{var J,Oe;if(!te)return;const ge=(B==null?void 0:B.examples)??[];return{tiles:U,running:X,read:F.read,who:((J=ge[0])==null?void 0:J.with)??((Oe=F.job)==null?void 0:Oe.subject.kind)??((B==null?void 0:B.subject)==="person"||B!=null&&B.figure?"presenter":"product"),noSubject:F.read&&!F.job&&!ge.length&&F.more.length===0,missing:TK(F.more,ge,F.job),first:F.first,stale:F.first.length>0&&ge.length>0,finish:e.finish}},[te,B,U,X,F.read,F.job,F.first,F.more,e.finish]),q=s.useCallback(ge=>{te&&(C(null),Re.drawSceneExamples(t.id,te,ge).then(()=>F.again()).catch(J=>C(String((J==null?void 0:J.message)??J))))},[t.id,te,F.again]),le=s.useCallback(()=>{te&&(R.current=!0,p8(l),Ii(l),G.current(te))},[te,l]),[Se,Q]=s.useState(null);s.useEffect(()=>{f||p.editing||!Ck(p.answers)||w({type:"inputs",place:XJ(p.answers),pictures:QJ(p.answers)})},[p.answers,p.editing,f]);const xe=s.useRef(new Set),ee=aee(v,!f&&Ck(p.answers));s.useEffect(()=>{var ge;ee===null||xe.current.has(ee)||(xe.current.add(ee),Z.start("make",{draw:!1,shot:((ge=T.current.answers.source)==null?void 0:ge.door)==="shot"}))},[ee,Z.start]);const[ae,re]=s.useState(""),_=Xv(t.id,ae,!f),ue=s.useRef(_);ue.current=_;const We=s.useRef([]);_.settled&&!_.error&&(We.current=_.items);const Xe=_.settled?_.items:We.current,ze=!_.error&&(!_.settled||_.loading),{recent:tt,loaded:ce}=on(),[ve,Pe]=s.useState(null);s.useEffect(()=>{!ae.trim()&&_.settled&&!_.error&&Pe(_.items.length>0)},[ae,_.settled,_.error,_.items.length]);const de=ve??(tt.length>0?!0:ce?!1:null),je=s.useMemo(()=>({any:de,items:Xe.map(ge=>({id:ge.id,hash:ge.images[0],alt:Roe(ge.promptHead)})),query:ae,more:_.settled&&_.hasMore,loading:ze,error:_.error}),[de,Xe,ae,_.settled,_.hasMore,ze,_.error]),Ue=Rn().scenes,ye=s.useCallback(async ge=>{var Ge,me,_e;const J=We.current.find(W=>W.id===ge)??_.items.find(W=>W.id===ge);if(!(J!=null&&J.images[0]))return;const Oe=T.current.revision;let Be=Lk(J.brief);if(!Be&&J.kind==="edit"){const W=await Re.lineage(J.id).catch(()=>null);if(Be=Lk((Ge=W==null?void 0:W.ancestors.find(pe=>pe.kind==="generation"))==null?void 0:Ge.brief),T.current.revision!==Oe)return}const Ve=Be?((me=Hh(t,Be))==null?void 0:me.name)??((_e=Ue.find(W=>W.id===Be))==null?void 0:_e.name):void 0;Nt({shot:{id:J.id,hash:J.images[0],...Be&&Ve?{scene:{id:Be,name:Ve}}:{}},reuse:void 0})},[t,Ue,_.items]),Ee=s.useCallback(()=>{var J;const ge=(J=T.current.answers.shot)==null?void 0:J.scene;ge&&(R.current=!0,p8(l),Ii(l),G.current(ge.id,{existing:!0}))},[l]),be=(u==null?void 0:u.canDraw)??!0,Le=Z.offline?Ne.offline:M,Qe={setup:p,studio:v,canDraw:be,uploading:y,edit:f,editingName:j,note:Le,stale:GN(v),shots:je,set:ne},Ke=s.useMemo(()=>Ree(Qe),[p,v,be,y,j,Le,f,je,ne]),nt=(()=>{const ge=Ke[Ke.length-1];return(ge==null?void 0:ge.kind)==="question"?ge.question:null})(),gt=Tee(Qe,nt),Pt=s.useCallback(async ge=>{var Ge,me,_e;const J=ge.filter(W=>W.type.startsWith("image/")||/\.(heic|heif)$/i.test(W.name));if(!J.length){C(Ne.onlyPictures);return}((Ge=T.current.answers.source)==null?void 0:Ge.door)!=="photos"&&g({type:"answer",patch:{source:{door:"photos"}}});const Ve=4-(((me=T.current.answers.photos)==null?void 0:me.hashes)??[]).length;if(Ve<=0){C(Ne.fourPictures);return}C(J.length>Ve?Ne.fourPictures:null),x(W=>W+1);try{for(const W of J.slice(0,Ve))try{const pe=await P0(W),Ie=((_e=T.current.answers.photos)==null?void 0:_e.hashes)??[];g({type:"photos",hashes:[...Ie,pe]})}catch(pe){C(`${W.name} could not be added: ${String((pe==null?void 0:pe.message)??pe)}`)}}finally{x(W=>W-1)}},[]),Ut=(ge,J,Oe)=>g({type:"aside",aside:{said:ge,reply:J,q:Oe,at:Wh()}}),Nt=s.useCallback(ge=>{const J=T.current,Oe=J.held??J.answers;J.editing&&Mk(H.current)&&JSON.stringify(zv(Oe,ge))!==JSON.stringify(Oe)&&w({type:"forget-record"}),g({type:"answer",patch:ge})},[]),cn=s.useRef(U);cn.current=U;const Fe=s.useCallback((ge,J)=>{var Oe,Be;if(C(null),ge==="photos"&&J.kind==="photos"){const Ve=J.action,Ge=((Oe=T.current.answers.photos)==null?void 0:Oe.hashes)??[];Ve.type==="add"?Pt(Ve.files):Ve.type==="instead"?Nt({source:{door:"shot"}}):Ve.type==="remove"?g({type:"photos",hashes:Ge.filter(me=>me!==Ve.hash)}):Ve.type==="reject"?C(Ne.onlyPictures):Ve.type==="submit"&&Ge.length?Nt({photos:{hashes:Ge,done:!0}}):Ve.type==="back"&&Nt({source:{door:"guided"}});return}if(ge==="shot"&&J.kind==="pick"){const Ve=J.action;Ve.type==="pick"?ye(Ve.id):Ve.type==="query"?re(Ve.text):Ve.type==="more"?ue.current.loading||ue.current.loadMore():Ve.type==="back"&&(re(""),Nt({source:{door:"photos"},photos:{hashes:[],done:!1}}));return}if(ge==="reuse"&&J.kind==="choice"&&J.id==="use"){Ee();return}if(Ek(ge)){const Ve=qJ(ge,J,T.current.answers);Ve&&Nt(Ve);return}if(ge==="retry"){Z.start("make",{draw:!1,shot:((Be=T.current.answers.source)==null?void 0:Be.door)==="shot"});return}if(J.kind==="confirm"){if(ge==="set-start"){J.id==="draw-set"?(w({type:"set-drawn"}),q({first:!0})):w({type:"set-declined"});return}if(ge==="set-more"){J.id==="more"?(w({type:"ask-more"}),q({more:!0})):w({type:"decline-more"});return}if(ge==="set-done"){J.id==="retry-failed"?q({roles:cn.current.filter(Ve=>Ve.state==="failed").map(Ve=>Ve.role)}):le();return}J.id==="draw"||J.id==="again"?Z.start("again"):J.id==="use"?Z.use():J.id==="another-shot"&&At.current("shot")}},[Pt,Nt,Z.start,Z.use,q,le,ye,Ee]),pt=ge=>{ge.trim()?!E.current&>.target.kind!=="off"&&(E.current=gt.target):E.current=null,S(ge)},it=ge=>{const J=St(ge);return J&&(E.current=null,S("")),J};function St(ge){var J;{const Oe=ge.trim();if(!Oe)return!1;C(null);const Be=E.current??gt.target;if(Be.kind==="source"){if(JN(Oe))return Nt({source:{door:"words",text:Oe.slice(0,400)}}),!0;const Ve=ZJ(Oe),Ge=Object.keys(Ve);return Ge.length>0?(Nt({source:{door:"guided"},...Object.fromEntries(Ge.map(me=>[me,{pick:Ve[me]}]))}),!0):(Ut(Oe,Ok(Ik(Oe,"source")??"vague","source"),"source"),!0)}if(Be.kind==="row"&&Kh(Be.id)){const Ve=Ik(Oe,"row");if(Ve)return Ut(Oe,Ok(Ve,"row"),Be.id),!0;const Ge=(J=T.current.answers[Be.id])==null?void 0:J.pick;return Nt({[Be.id]:{...Ge?{pick:Ge}:{},words:Oe.slice(0,200)}}),!0}if(Be.kind==="name")return w({type:"name",text:YN(Oe)??Oe}),!0;if(Be.kind==="add"||Be.kind==="change"){if(v.job)return!1;const Ve=yee(Oe),Ge=Mee(v);return Ve.kind==="rename"?(w({type:"name",text:Ve.name}),Ut(Oe,Ne.renamed(Ve.name),Ge),!0):Ve.kind!=="change"?(Ut(Oe,Ve.say,Ge),Ve.kind!=="refuse"):(Be.kind==="add"?Z.start("change",{ask:Oe,draw:!1}):bee(v,Oe)?Z.start("again"):Z.start("change",{ask:Oe}),!0)}return!1}}const xt=s.useCallback(ge=>{v.job||(ge==="name"?N(!0):Ek(ge)&&(ge==="shot"&&re(""),Mk(v)?K(ge):g({type:"edit",id:ge})))},[v]),At=s.useRef(xt);At.current=xt;const Kt=s.useCallback((ge,J)=>{ge==="name"&&(J.trim()&&w({type:"name",text:J.trim()}),N(!1))},[]),et=s.useCallback(()=>{N(!1),g({type:"cancel-edit"})},[]),mt=Or(v),ot=X&&F.job?mv({status:F.job.status,step:F.job.current,done:F.job.done.length,total:F.job.roles.length,error:F.job.error}):void 0,kn=v.job?Yg(v):Z.saving?"Saving":ot,ut=[];let Gt=null;if(te){const ge=X?(Jt=F.job)==null?void 0:Jt.current:null,J=((se=[...U].reverse().find(Ve=>Ve.state==="shown"))==null?void 0:se.role)??null,Oe=Se??ge??J??"place";ut.push({view:"place",label:"The place",state:Oe==="place"?"current":"approved",hash:(mt==null?void 0:mt.hash)??void 0,photo:!1,drawing:!1,approved:!0,error:!1});for(const Ve of U)ut.push({view:Ve.role,label:tc[Ve.role],state:Oe===Ve.role?"current":Ve.state==="shown"?"approved":"todo",hash:Ve.hash,photo:!1,drawing:Ve.state==="drawing",approved:Ve.state==="shown",error:Ve.state==="failed"});const Be=ut.find(Ve=>Ve.view===Oe)??ut[0];Gt={hash:Be.hash,drawing:Be.drawing}}const Ft=!f&&(!!p.answers.source||v.versions.length>0);return{title:f?Ne.editTitle:Ne.title,turns:Ke,working:kn,busy:Z.saving,resumed:!!h,memoryKey:l,stage:Gt?{hash:Gt.hash,alt:`${v.name.trim()||(mt==null?void 0:mt.reading.name)||"The scene"}, in use`,drawing:Gt.drawing||!!v.job&&v.job.phase==="drawing",doing:ot??Yg(v),items:ut,onPick:ge=>Q(ge)}:{hash:(mt==null?void 0:mt.hash)??void 0,alt:`Preview of ${v.name.trim()||(mt==null?void 0:mt.reading.name)||"the scene"}`,drawing:!!v.job&&v.job.phase==="drawing",since:((oe=v.job)==null?void 0:oe.since)??void 0,doing:Yg(v),takes:v.job?void 0:lee(v),onTake:Z.putBack,items:[]},composer:{placeholder:gt.placeholder,label:gt.label,action:gt.action,disabled:gt.target.kind==="off",why:gt.target.kind==="off"&>.target.why||null,working:gt.working,onStop:v.job?Z.stop:X&&te?()=>{I(!0),Re.stopSceneExamples(t.id,te).then(()=>F.again()).catch(()=>{})}:void 0,stopping:!!((we=v.job)!=null&&we.stopping)||z,focusKey:P,onAttachFiles:gt.attach?ge=>void Pt(ge):void 0,attachLabel:Ne.attachLabel},text:k,onText:pt,onSend:it,onAnswer:Fe,onEdit:xt,onSaveEdit:Kt,onCancelEdit:et,confirmingEdit:D!==null,confirmEdit:()=>{D&&g({type:"edit",id:D}),K(null)},cancelConfirm:()=>K(null),onRestore:(ge,J)=>Z.putBack(J),onRetry:ge=>q({roles:[ge]}),onDescribe:()=>$(String(Date.now())),onStarter:ge=>{pt(ge),$(String(Date.now()))},onPaste:(nt==null?void 0:nt.id)==="source"||(nt==null?void 0:nt.id)==="photos"?ge=>void Pt(ge):void 0,canDraw:be,begun:Ft,unsaved:v.saved?!1:f?xee(v,a):Ft,running:!!v.job||X,saved:!!te,finish:le,keptAsDraft:!f&&qN(v),leave:()=>{Z.stop(),R.current=!0,p8(l),Ii(l)}}}function Toe({brand:e,applyBrand:t,sceneId:n,seed:r,conversation:a,storageKey:i,caps:l,onClose:u,onStartOver:f,onSaved:h,onDone:p,finish:g}){const v=Loe({brand:e,applyBrand:t,sceneId:n,seed:r,conversation:a,storageKey:i,caps:l,onSaved:h,onDone:p,finish:g}),[w,y]=s.useState(!1),x=v.turns[v.turns.length-1],k=(x==null?void 0:x.kind)==="question"?x.question.id:null;s.useEffect(()=>_h({open:k}),[k]),s.useEffect(()=>()=>_h(null),[]);const S=!!n,E=()=>{if(v.saved){v.finish();return}if(v.running||v.keptAsDraft){u();return}if(v.unsaved){y(!0);return}v.leave(),u()},j=!S&&v.begun&&!v.saved?o.jsx(Wn,{label:Ne.startOver,tone:"quiet",title:Ne.startOverTitle,body:Ne.startOverBody,busy:!1,onConfirm:()=>{v.leave(),f()}}):null;return o.jsx(fw,{onClose:E,surface:{kind:"scene",glyph:o.jsx(gj,{size:32}),title:v.title,turns:v.turns,busy:v.busy,working:v.working,memoryKey:v.memoryKey,resumed:v.resumed,stage:v.stage,stageEmpty:{lead:Ne.emptyLead,hint:Ne.emptyHint},composer:v.composer,text:v.text,onText:v.onText,onSend:v.onSend,onAnswer:v.onAnswer,onEdit:v.onEdit,onSaveEdit:v.onSaveEdit,onCancelEdit:v.onCancelEdit,onRestore:v.onRestore,onRetry:v.onRetry,onDescribe:v.onDescribe,onStarter:v.onStarter,onPaste:v.onPaste,headAction:j,overlay:o.jsxs(o.Fragment,{children:[o.jsx(Wn,{label:Ne.changeIt,title:Ne.changeTitle,body:Ne.changeBody,busy:!1,open:v.confirmingEdit,onOpenChange:N=>{N||v.cancelConfirm()},onConfirm:v.confirmEdit}),o.jsx(Wn,{label:S?Ne.discard:Ne.leave,title:S?Ne.discardTitle:Ne.leaveTitle,body:S?Ne.discardBody:Ne.leaveBody,busy:!1,open:w,onOpenChange:N=>{N||y(!1)},onConfirm:()=>{y(!1),v.leave(),u()}})]})}})}const D5=e=>{const t=/^asset:([a-f0-9]{32})$/.exec(String(e??""));return t?t[1]:null};function $oe(e,t){var l;const r=(((l=e.json)==null?void 0:l.scenes)??[]).find(u=>(u==null?void 0:u.id)===t);if(!r)return null;const a={name:String(r.name??""),prompt:String(r.prompt??""),lighting:String(r.lighting??""),subject:r.subject==="product"||r.subject==="person"?r.subject:"either",description:String(r.description??""),...r.promptName?{promptName:String(r.promptName)}:{},...r.camera?{camera:String(r.camera)}:{},...r.figure?{figure:String(r.figure)}:{},...r.figure&&r.figureTreatment?{figureTreatment:String(r.figureTreatment)}:{},...Array.isArray(r.keywords)?{keywords:r.keywords.map(String)}:{},...Array.isArray(r.collections)?{collections:r.collections.map(String)}:{},...Array.isArray(r.verticals)?{verticals:r.verticals.map(String)}:{}},i=(Array.isArray(r.refs)?r.refs:[]).map(u=>D5(u==null?void 0:u.file)).filter(Boolean);return see({place:String(r.instruction??""),pictures:i.slice(0,4),reading:a,hash:D5(r.preview)??null,name:a.name})}function Doe(){return[...crypto.getRandomValues(new Uint8Array(6))].map(t=>t.toString(16).padStart(2,"0")).join("")}function H5(){const{sceneId:e=null,convoId:t=null}=Bs(),{key:n,state:r}=Zn(),{brand:a}=on(),{applyBrand:i}=Rn(),l=Dn(),{announce:u,caps:f}=jv();Sc(e?"Edit scene":"Create scene");const[h]=s.useState(()=>e?$oe(a,e):null),p=typeof(r==null?void 0:r.from)=="string"?r.from:null,g=p&&(Wi(ct.hub,p.split("?")[0])||Wi(ct.set,p.split("?")[0])),v=s.useCallback(()=>l(p??(e?_r(a,e):_u(a)),{replace:!0}),[l,p,e,a]),w=s.useMemo(()=>t??Doe(),[t,n]);s.useEffect(()=>{t||e&&!h||l(e?cv(a,e,w):Vi(a,w),{replace:!0,state:r})},[t,w,e,h,a,l,r]);const y=s.useRef(null);return e&&!h?o.jsx(uo,{to:_r(a,e),replace:!0}):o.jsx(Toe,{brand:a,applyBrand:i,sceneId:e,seed:h,conversation:w,storageKey:`scenri:scene-studio:${a.id}:${w}`,caps:f?{canRead:f.canAnalyze,canDraw:f.canGenerate}:null,onClose:v,onStartOver:()=>l(Vi(a),{replace:!0,state:r}),onSaved:(x,k)=>{y.current={made:x,how:k}},finish:g?Ne.useInAShot:Ne.openScene,onDone:(x,k)=>{var S,E;if(!(k!=null&&k.existing)){const j=Hh(a,x),N=((S=y.current)==null?void 0:S.made.id)===x?y.current.made:null;u({kind:"scene",id:x,name:(N==null?void 0:N.name)??(j==null?void 0:j.name)??"",verticals:(N==null?void 0:N.verticals)??(j==null?void 0:j.verticals)??[],how:((E=y.current)==null?void 0:E.how)??(e===x?"updated":"created")})}g&&p?l(`${p.split("?")[0]}?scene=${encodeURIComponent(x)}&compose=1`,{replace:!0}):l(_r(a,x),{replace:!0})}},w)}function IR(){const{brand:e}=on(),t=Dn(),n=mr(e);return s.useCallback(r=>{t(`${n}?product=${encodeURIComponent(r)}&compose=1`)},[n,t])}function Hoe({product:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,onDelete:u,onRename:f,bookmarked:h,onBookmark:p,chosen:g,batching:v,onPick:w,batch:y,size:x="grid"}){var S,E;const k=s.useMemo(()=>y?mm({kind:"product",count:y.count,openLabel:"Open",onOpen:()=>n==null?void 0:n(e.id),href:a,onDeselect:()=>w==null?void 0:w(e.id),onAct:y.onAct,onKeep:y.onKeep,allKept:y.allKept}):Ji({onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,select:w?{run:()=>w(e.id)}:void 0,keep:p?{on:!!h,run:()=>p(e.id)}:void 0,onRename:f?()=>f(e.id):void 0,remove:u?{label:"Delete product",run:()=>u(e.id)}:void 0}),[n,r,u,f,w,p,h,a,e.id,y]);return o.jsx(nd,{id:e.id,previewUrl:Fr((E=(S=e.shots)==null?void 0:S[0])==null?void 0:E.file),title:go(e,"tooltip"),primary:go(e,"card"),secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,menu:k,bookmarked:h,onBookmark:p,chosen:g,batching:v,onPick:w,size:x})}function Ooe(e){return o.jsx(Qp,{...e})}const FR=s.memo(Hoe);function Ioe({product:e,variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,bookmarked:u,onBookmark:f,size:h="grid"}){const p=$0(e.category)??e.category,g=s.useMemo(()=>Ji({onOpen:n?()=>n(e.id):void 0,href:a,use:r?{label:"Use in a shot",run:()=>r(e.id)}:void 0,keep:f?{on:!!u,run:()=>f(e.id)}:void 0}),[n,r,f,u,a,e.id]);return o.jsx(nd,{id:e.id,previewUrl:e.previewUrl,title:`${go(e,"tooltip")} · ${p}`,primary:go(e,"card"),secondary:"",useLabel:"Use in a shot",variant:t,onOpen:n,onUse:r,href:a,selected:i,onToggle:l,menu:g,bookmarked:u,onBookmark:f,size:h})}const _R=s.memo(Ioe),Foe=8,m8="__bookmarked";function _oe(){var Kt;const{brand:e,products:t,productsLoaded:n,refreshProducts:r}=on(),a=((Kt=ZA())==null?void 0:Kt.importing)??!1,{demoProducts:i,applyBrand:l,refreshBrands:u}=Rn(),{push:f}=or(),h=n&&t.length===0,p=Dn(),g=IR(),v=ll(),{q:w,setQ:y,facets:x,setFacets:k,clearSearch:S,clear:E}=Pf(["category","bookmarked"]),j=x.category,N=x.bookmarked==="1",[P,$]=s.useState(()=>lm("product",e.id)),M=et=>$(cm("product",e.id,et)),C=aw(`${e.id}|${w}|${j??""}|${N?"1":""}`),[R,T]=fa(Dr.wallDensity,zu),H=jc(R),D=s.useCallback(et=>T(et),[T]),K=s.useMemo(()=>fm(H),[H]),O=um(H),Z=s.useMemo(()=>{const et=a?t.filter(mt=>{var ot;return(((ot=mt.shots)==null?void 0:ot.length)??0)>0}):t;return NA(et).map(mt=>({product:mt,category:Cv(mt),own:!0}))},[t,a]),te=s.useMemo(()=>i.map(et=>({product:et,category:et.category,own:!1})),[i]),B=s.useMemo(()=>[...Z,...te],[Z,te]),F=s.useMemo(()=>B.reduce((et,mt)=>et+(P.includes(mt.product.id)?1:0),0),[B,P]),X=N&&F===0,z=X&&h,I=X&&!h,U=s.useMemo(()=>{const et=new Map;for(const{category:mt}of B)mt&&et.set(mt,(et.get(mt)??0)+1);return et},[B]),G=s.useMemo(()=>T0.filter(et=>U.has(et.key)),[U]),ne=B.length>0?"tabs":"none",q=s.useCallback(et=>p(la(e,et)),[p,e]),[le,Se]=s.useState(null),[Q,xe]=s.useState(!1),[ee,ae]=s.useState(null),[re,_]=s.useState(!1),[ue,We]=s.useState(null),[Xe,ze]=s.useState(!1),tt=s.useCallback(et=>{const mt=t.find(ot=>ot.id===et);mt&&Se(mt)},[t]),ce=et=>et.origin==="catalog"||et.id.startsWith("cat-"),ve=s.useCallback(et=>{const mt=t.find(ot=>ot.id===et);!mt||ce(mt)||(We(null),ae(mt))},[t]),Pe=async et=>{if(!(!ee||re)){_(!0),We(null);try{l(await Re.updateProduct(e.id,ee.id,{name:et})),ae(null)}catch(mt){const ot=nn(mt,"Could not rename this product");We([ot.title,ot.detail].filter(Boolean).join(" "))}finally{_(!1)}}},de=async()=>{if(!le||Q)return;xe(!0);const et=le.origin==="catalog"||le.id.startsWith("cat-");try{et?(await Re.deleteCatalogProduct(e.id,le.id),await r()):l(await a6(e.id,le.id)),C.forget(le.id),Se(null)}catch(mt){(mt==null?void 0:mt.status)===404?(await Promise.all([u(),r()]),C.forget(le.id),Se(null)):f(nn(mt,"Could not delete this product"))}finally{xe(!1)}},je=s.useCallback(et=>et.filter(({product:mt})=>z||!N||P.includes(mt.id)).filter(({category:mt})=>!j||mt===j).filter(({product:mt,category:ot})=>wo([Uv(mt),$0(ot)].filter(Boolean).join(" "),w)).map(({product:mt})=>mt),[j,w,N,P,z]),Ue=s.useMemo(()=>je(Z),[je,Z]),ye=s.useMemo(()=>je(te),[je,te]),{visible:Ee,remaining:be,showMore:Le}=iw(Ue,`${j??""}|${N?"keepers":""}|${w}`),[Qe,Ke]=s.useState(null);s.useEffect(()=>{if(!Qe||be<=0)return;const et=Qe.closest(".sc-home"),mt=new IntersectionObserver(ot=>{ot.some(kn=>kn.isIntersecting)&&Le()},{root:et,rootMargin:"200% 0px"});return mt.observe(Qe),()=>mt.disconnect()},[Qe,be,Le]);const nt={key:"category",label:"Category",everyLabel:"All products",everyCount:B.length,selected:N?m8:j,onSelect:et=>k(et===m8?{bookmarked:"1",category:null}:{bookmarked:null,category:et}),options:[{value:m8,label:"Keepers",count:F},...G.map(et=>({value:et.key,label:et.label,count:U.get(et.key)??0}))]},gt=o.jsxs("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>v("product"),children:[o.jsx(cr,{size:12})," Add product"]}),Pt=h,Ut=t.length>0,Nt=o.jsx(gm,{title:"Products",filters:o.jsx(vm,{mode:ne,group:nt}),density:o.jsx(dm,{value:H,onChange:D}),search:B.length>=Foe&&o.jsx(id,{value:w,onChange:y,noun:"products",total:B.length})}),cn=et=>{const mt=t.find(kn=>kn.id===et);return mt&&mt.origin==="catalog"||et.startsWith("cat-")?Re.deleteCatalogProduct(e.id,et):a6(e.id,et)},Fe=()=>{const et=[...C.ids];et.length===1?tt(et[0]):ze(!0)},pt=[...C.ids],it=pt.length>0&&pt.every(et=>P.includes(et)),St=()=>$(Kv("product",e.id,pt,!it)),xt=pm(C.ids.size,it,"products"),At=async()=>{if(Q)return;const et=[...C.ids];xe(!0);try{const{failed:mt,error:ot}=await tp(et,cn);await Promise.all([u(),r()]),C.retain(mt),ze(!1),ot&&f(nn(ot,"Could not delete these products"))}finally{xe(!1)}};return o.jsx(Nf.Provider,{value:O,children:o.jsxs(is,{children:[o.jsxs("main",{className:"sc-looks sc-products",id:"main","data-hero":Pt||void 0,onClick:C.onBlank,children:[!Pt&&Nt,!n&&o.jsx("div",{className:"sc-masonry","data-density":!0,"data-density-size":O,style:K,"aria-hidden":!0,children:o.jsx(Ooe,{size:"grid",count:8})}),Ut&&Ee.length>0&&o.jsxs("section",{className:"sc-owned",children:[o.jsx("div",{className:"sc-sec-head",children:o.jsx("h2",{className:"sc-sec-title",children:"Your products"})}),o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:Ee.map(et=>o.jsx(FR,{product:et,variant:"use",size:"grid",onOpen:q,href:la(e,et.id),onUse:g,bookmarked:P.includes(et.id),onBookmark:M,onDelete:tt,onRename:ce(et)?void 0:ve,chosen:C.ids.has(et.id),batching:C.batching==="product",onPick:C.picking("product")?mt=>C.toggle("product",mt):void 0,batch:C.kind==="product"&&C.ids.has(et.id)?{count:C.ids.size,onAct:Fe,onKeep:St,allKept:it}:null},et.id))}),be>0&&o.jsx("div",{ref:Ke,"aria-hidden":!0}),be>0&&o.jsx("div",{className:"sc-lib-more",children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:Le,children:["Show ",Math.min(be,60)," more"]})}),ee&&o.jsx(rw,{title:"Rename product",name:ee.name,maxLength:500,busy:re,error:ue,onConfirm:et=>void Pe(et),onDismiss:()=>{re||ae(null)}}),le&&o.jsx(Wn,{label:"Delete product",title:`Delete ${le.name}?`,body:"Shots already made with it keep their images and their recipe. Only future shots lose it.",open:!0,busy:Q,onOpenChange:et=>{!et&&!Q&&Se(null)},onConfirm:()=>void de()}),Xe&&o.jsx(Wn,{label:qr("product",C.ids.size).menu,title:`${qr("product",C.ids.size).menu}?`,body:"Shots already made with it keep their images and their recipe. Only future shots lose it.",open:!0,busy:Q,onOpenChange:et=>{!et&&!Q&&ze(!1)},onConfirm:()=>void At()})]}),Pt&&o.jsx(oo,{shape:"cold",title:o.jsxs(o.Fragment,{children:["Bring in a ",o.jsx("em",{children:"product"})]}),body:"Upload a few clean shots, or import your store, and it stays exact in every image you make.",action:gt}),Ut&&Ee.length>0&&ye.length>0&&o.jsx("div",{className:"sc-sec-head sc-owned-divider",children:o.jsx("h2",{className:"sc-sec-title",children:"Scenri products"})}),Pt&&te.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(ow,{label:"Or borrow one of ours"}),Nt]}),ye.length>0&&o.jsx("div",{className:"sc-masonry","data-wall":!0,"data-density":!0,"data-density-size":O,style:K,children:ye.map(et=>o.jsx(_R,{product:et,variant:"use",size:"grid",onUse:g,onOpen:q,href:la(e,et.id),bookmarked:P.includes(et.id),onBookmark:M},et.id))}),n&&I&&o.jsx(oo,{shape:"zero",body:"Nothing in Keepers yet. Add a product to Keepers from its card and it stays here.",action:o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:()=>k({bookmarked:null}),children:"Browse every product"})}),n&&!I&&Ue.length===0&&ye.length===0&&o.jsx(wm,{noun:"products",q:w,facet:N?"Keepers":j?$0(j):null,onClearSearch:S,onClearAll:E})]}),o.jsxs("div",{className:"sc-wall-dock",children:[C.kind==="product"&&C.ids.size>0&&o.jsx(sw,{count:C.ids.size,loaded:Ee.length,tool:qr("product",C.ids.size).tool,icon:qr("product",C.ids.size).icon,danger:!0,onAct:Fe,keep:{label:xt.tool,filled:it,onAct:St},onClear:C.clear,onSelectAll:()=>C.selectAll("product",Ee.map(et=>et.id))}),o.jsx(nw,{})]})]})})}function Zoe({value:e,onChange:t}){const n=$0(e)??"Other",r=e&&T0.some(a=>a.key===e)?e:"other";return o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-btn sc-btn-ghost sc-catpick","aria-label":`Category: ${n}`,children:[n,o.jsx(Yi,{size:11,weight:"bold"})]})}),o.jsx(Cs,{align:"center",sideOffset:8,children:o.jsx(Rh,{value:r,children:T0.map(a=>o.jsx(gu,{value:a.key,onSelect:()=>t(a.key),children:a.label},a.key))})})]})}function Voe({refs:e,cap:t,note:n,addLabel:r,busy:a,onAdd:i,onPromote:l,onRemove:u}){const[f,h]=s.useState(null),p=s.useMemo(()=>e.find(N=>N.file===f)??e[0],[e,f]);s.useEffect(()=>{var N;e.length&&!e.some(P=>P.file===f)&&h(((N=e[0])==null?void 0:N.file)??null)},[e,f]);const g=p?e.findIndex(N=>N.file===p.file):-1,v=!!l&&g>0,w=!!u&&!!p&&e.length>1,y=!!(r&&i&&e.length>0),x=e.length>1||y,{shellRef:k,railRef:S,page:E}=qM(e.length),j=N=>{const P=N==null?void 0:N[0];P&&(i==null||i(P))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-refstage",children:p?o.jsx("div",{className:"sc-refstage-frame",children:o.jsx("img",{src:p.url,alt:""})}):i?o.jsxs("label",{className:"sc-refstage-blank sc-refstage-drop","data-busy":a||void 0,onDragOver:N=>{N.preventDefault(),N.dataTransfer.dropEffect="copy"},onDrop:N=>{N.preventDefault(),j(N.dataTransfer.files)},children:[o.jsx("input",{type:"file",accept:"image/*",hidden:!0,disabled:a,onChange:N=>{j(N.target.files),N.target.value=""}}),a?o.jsx(xr,{size:"2"}):o.jsx(cr,{size:22,weight:"bold"}),o.jsx("span",{children:"Add a reference"})]}):o.jsx("span",{className:"sc-refstage-blank",children:o.jsx(Ws,{size:22})})}),x&&o.jsxs("div",{className:"sc-refrail-shell",ref:k,children:[o.jsxs("div",{className:"sc-refrail-track",children:[o.jsx("button",{type:"button",className:"sc-refrail-arrow prev","aria-label":"Previous references",onClick:()=>E(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-refrail-arrow next","aria-label":"Next references",onClick:()=>E(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsx("div",{className:"sc-refrail",ref:S,children:e.map((N,P)=>o.jsx("button",{type:"button",className:"sc-refrail-item","data-on":(p==null?void 0:p.file)===N.file?"":void 0,"data-spare":P>=t?"":void 0,"aria-label":`Reference ${P+1}`,"aria-pressed":(p==null?void 0:p.file)===N.file,onClick:()=>h(N.file),children:o.jsx("img",{src:N.url,alt:"",loading:"lazy"})},N.file))})]}),y&&o.jsxs("label",{className:"sc-refrail-item sc-refrail-add","data-busy":a||void 0,children:[o.jsx("input",{type:"file",accept:"image/*",hidden:!0,disabled:a,onChange:N=>{j(N.target.files),N.target.value=""}}),a?o.jsx(xr,{size:"1"}):o.jsx(cr,{size:16,weight:"bold"}),o.jsx("span",{className:"sc-vh",children:r})]})]}),(v||w)&&o.jsx("div",{className:"sc-refacts",children:o.jsxs("span",{className:"sc-refacts-pair",children:[v&&o.jsxs("button",{type:"button",className:"sc-refact sc-refact-lead",onClick:()=>l==null?void 0:l(p.file),children:[o.jsx(RU,{size:14,weight:"bold"}),"Use first"]}),w&&o.jsx("button",{type:"button",className:"sc-refact sc-refact-aside",onClick:()=>u==null?void 0:u(p.file),children:"Remove"})]})}),o.jsx("p",{className:"sc-lookpage-note",children:n})]})}function zoe({value:e,onChange:t,onBlur:n,label:r,placeholder:a,className:i="sc-lookpage-titleedit"}){const l=s.useRef(null),u=f=>{f&&(f.style.height="auto",f.style.height=`${f.scrollHeight}px`)};return s.useEffect(()=>u(l.current),[e]),o.jsx("textarea",{ref:l,className:i,rows:1,dir:"auto","aria-label":r,placeholder:a,value:e,onChange:f=>{u(f.currentTarget),t(f.target.value)},onBlur:n,onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),f.currentTarget.blur())}})}function Boe({size:e,busy:t,error:n,onSave:r,onDismiss:a}){const i=(e==null?void 0:e.by)==="person"?e.text:"",[l,u]=s.useState(i),f=l.trim(),h=()=>{if(!t){if(f===i)return a();r(f)}},p=(e==null?void 0:e.by)==="person"?"Yours. Leave it empty to go back to the size read from its photo.":(e==null?void 0:e.by)==="record"?"From your store's listing. Write another to use yours instead.":e?"Read from its photo, so a shot keeps it at its real size. Correct it if it is off.":"Not read yet. Write it the way a shop lists it.";return o.jsxs(Ts,{className:"sc-newdlg sc-pdetails",maxWidth:"min(460px, 94vw)",onDismiss:a,children:[o.jsxs("div",{className:"sc-newdlg-head",children:[o.jsx(ds,{className:"sc-newdlg-title",children:"Details"}),o.jsx(As,{asChild:!0,children:o.jsx("button",{type:"button",className:"sc-set-close sc-newdlg-close","aria-label":"Close",children:o.jsx("span",{"aria-hidden":!0,children:"×"})})})]}),o.jsxs("div",{className:"sc-newdlg-body",children:[o.jsxs("label",{className:"sc-pdetails-row",children:[o.jsx("span",{className:"sc-pdetails-lb",children:"Size"}),o.jsx("input",{className:"sc-pdetails-field",value:l,placeholder:e&&e.by!=="person"?e.text:"About 2 cm across, or 30 x 20 cm",onChange:g=>u(g.target.value),onKeyDown:g=>g.key==="Enter"&&h()}),o.jsx("span",{className:"sc-pdetails-hint",children:p})]}),n&&o.jsx("p",{className:"sc-assetform-err",children:n})]}),o.jsxs("div",{className:"sc-newdlg-foot",children:[o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost",onClick:a,children:"Cancel"}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary","data-busy":t||void 0,onClick:h,children:t?"Saving":"Save"})]})]})}const Uoe=3;function Woe(e){const t=e,n=(t.brand??t.vendor??"").trim();return!n||e.name.toLowerCase().startsWith(n.toLowerCase())?null:n}function Koe(e){return e.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim()}function Goe(e,t){if(e.length<=t)return e;const n=e.slice(0,t+1).search(/[.!?](\s|$)/);if(n>40)return e.slice(0,n+1);const r=e.lastIndexOf(" ",t);return`${e.slice(0,r>40?r:t).trimEnd()}…`}function Yoe(){var Ee;const{productId:e=""}=Bs(),{brand:t,products:n,refreshProducts:r}=on(),{demoProducts:a,demoProductsLoaded:i,applyBrand:l,refreshBrands:u}=Rn(),f=Dn(),h=IR(),{push:p}=or(),[g,v]=s.useState(!1),[w,y]=s.useState(!1),[x,k]=s.useState(null),S=s.useRef(null),E=s.useRef({}),j=s.useRef(!1),N=ym(),P=n.find(be=>be.id===e),[$,M]=s.useState(null);s.useEffect(()=>{if((P==null?void 0:P.origin)!=="catalog"){M(null);return}let be=!0;return Re.libraryProduct(t.id,P.id).then(Le=>{be&&M(Le.product)}).catch(()=>{}),()=>{be=!1}},[t.id,P]);const C=$&&P&&$.id===P.id?{...$,...P,shots:$.shots}:P,R=s.useMemo(()=>C?void 0:a.find(be=>be.id===e),[C,a,e]);Sc((Ee=C??R)==null?void 0:Ee.name);const[T,H]=s.useState([]);s.useEffect(()=>{if(!R){H([]);return}let be=!0;return Re.demoProductFrames(R.id).then(Le=>{be&&H(Le.frames)}).catch(()=>{be&&H([])}),()=>{be=!1}},[R==null?void 0:R.id]);const[D,K]=s.useState((C==null?void 0:C.name)??"");s.useEffect(()=>{K((C==null?void 0:C.name)??"")},[C==null?void 0:C.id]);const O=lw(t.id,[e??""]),[Z,te]=s.useState(null),[B,F]=s.useState(!1),[X,z]=s.useState(!1),[I,U]=s.useState(null),G=!!(C??R);s.useEffect(()=>{if(te(null),!G||!e)return;let be=!0;return Re.productSize(t.id,e).then(Le=>{be&&te(Le.size)}).catch(()=>{}),()=>{be=!1}},[t.id,e,G]);const ne=async be=>{if(!e)return;const Le=N();z(!0),U(null);try{const Qe=await Re.setProductSize(t.id,e,be);Le()&&(te(Qe.size),F(!1))}catch(Qe){U(String(Qe.message??Qe))}finally{z(!1)}},q=((C==null?void 0:C.origin)??"manual")==="manual",le=async(be,Le)=>{Le&&be&&typeof be=="object"&&"json"in be?l(be):await r()},Se=be=>{if(!C||j.current)return;E.current={...E.current,...be},S.current&&clearTimeout(S.current);const Le=t.id,Qe=C.id,Ke=q;S.current=setTimeout(()=>{S.current=null;const nt=E.current;E.current={},(Ke?Re.updateProduct(Le,Qe,nt):Re.updateCatalogProduct(Le,Qe,nt)).then(Pt=>le(Pt,Ke)).catch(Pt=>k(String(Pt.message??Pt)))},500)},Q=async be=>{const Le=q;v(!0),k(null);try{await le(await be,Le)}catch(Qe){k(String(Qe.message??Qe))}finally{v(!1)}},xe=async()=>{if(!C||j.current)return;j.current=!0,S.current&&clearTimeout(S.current),S.current=null,E.current={};const be=N(),Le=Eu(t),Qe=C.origin==="catalog"||C.id.startsWith("cat-");y(!0),k(null);try{Qe?(await Re.deleteCatalogProduct(t.id,C.id),await r()):l(await a6(t.id,C.id))}catch(Ke){if((Ke==null?void 0:Ke.status)!==404){j.current=!1,be()&&(k(String(Ke.message??Ke)),y(!1));return}await Promise.all([u(),r()])}be()&&f(Le,{replace:!0})};if(!C&&!R&&!i)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-productpage",id:"main",children:[o.jsxs("div",{className:"sc-refskeleton","aria-hidden":!0,children:[o.jsx("span",{className:"sc-refskeleton-title"}),o.jsx("span",{className:"sc-refskeleton-stage"}),o.jsxs("span",{className:"sc-refskeleton-rail",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]}),o.jsx("p",{className:"sc-vh",role:"status",children:"Loading this product"})]})});if(!C&&!R)return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage",id:"main",children:[o.jsx("h1",{children:"This product isn't here anymore"}),o.jsx("p",{className:"sc-lookpage-lede",children:"It may have been removed, or the link is out of date."}),o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx(_n,{className:"sc-btn sc-btn-primary",to:Eu(t),children:"Browse products"})})]})});const ee=R?"none":q?"full":"fields",ae=C??R,re=(C==null?void 0:C.id)??R.id,_=C?Cv(C):(R==null?void 0:R.category)??null,ue=Woe(ae),We=be=>{const Le=Fr(be.file);return Le?[{file:be.file,url:Le,angle:be.angle}]:[]},Xe=R?T.map(be=>({file:be.angle,url:be.url,angle:be.angle})):((C==null?void 0:C.shots)??[]).flatMap(We),ze=be=>{const Le=Xe.map(Ke=>Ke.file),Qe=Le.indexOf(be)+1;Q(Re.setProductShots(t.id,re,Le.filter(Ke=>Ke!==be))).then(()=>p({kind:"success",title:"Reference removed",detail:`Reference ${Qe} of ${Le.length}`,action:{label:"Undo",onClick:()=>void Q(Re.setProductShots(t.id,re,Le))}}))},tt=R?"Our reference set. Yours replaces it.":Xe.length===0?q?"No reference yet.":"No reference yet. Images from your store are still arriving.":Xe.length===1?"One angle. A shot has to guess at every side it can't see.":Xe.length===2?"Two angles. A third pins the shape.":"The first three build every shot. Remove any that show a different colour or version.",ce=ee==="none"?null:"Add image",ve=C!=null&&C.descriptionHtml?Goe(Koe(C.descriptionHtml),200):"",Pe=(R==null?void 0:R.description)||ve||null,de=Z?Z.text.charAt(0).toUpperCase()+Z.text.slice(1):null,je=R?[R.subcategory,de]:[C==null?void 0:C.variant,C==null?void 0:C.material,de??(C==null?void 0:C.dimensions)],Ue=[ee==="none"?$0(_):null,...je].filter(Boolean),ye=R?a.filter(be=>be.id!==re).slice(0,8):n.filter(be=>be.id!==re).slice(0,8);return o.jsx(is,{children:o.jsxs("main",{className:"sc-lookpage sc-productpage",id:"main",children:[o.jsxs("div",{className:"sc-lookpage-crumb",children:[o.jsx(_n,{to:Eu(t),children:"Products"}),o.jsx("span",{children:"/"}),o.jsx("span",{children:R?"Scenri library":q?"Yours":"From your store"})]}),ue&&o.jsx("p",{className:"sc-lookpage-house",children:o.jsx("em",{className:"sc-accent",children:ue})}),ee==="full"?o.jsx(zoe,{label:"Product name",value:D,onChange:be=>{K(be),Se({name:be})}}):o.jsx("h1",{dir:"auto",children:ae.name}),Pe&&o.jsx("p",{className:"sc-lookpage-lede",children:Pe}),Ue.length>0&&o.jsx("p",{className:"sc-lookpage-facts",children:Ue.join(" · ")}),o.jsxs("div",{className:"sc-lookpage-acts",children:[ee!=="none"&&o.jsx(Zoe,{value:_,onChange:be=>Se({category:be})}),o.jsx("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>h(re),children:"Use in a shot"}),ee!=="none"&&o.jsx(lr,{label:"Edit details",children:o.jsx("button",{type:"button",className:"sc-icon-btn","aria-label":"Edit details","aria-haspopup":"dialog",onClick:()=>{U(null),F(!0)},children:o.jsx(Ju,{size:17})})})]}),x&&o.jsx("p",{className:"sc-assetform-err",children:x}),o.jsx(Voe,{refs:Xe,cap:Uoe,note:tt,addLabel:ce,busy:g,onAdd:ee==="none"?void 0:be=>void Q(hW(t.id,re,be)),onPromote:ee==="none"?void 0:be=>void Q(Re.setProductShots(t.id,re,[be,...Xe.map(Le=>Le.file).filter(Le=>Le!==be)])),onRemove:ee==="none"?void 0:ze}),O.length>0&&o.jsx(Lu,{label:`Shots featuring ${ae.name}`,children:O.map(be=>o.jsx(uw,{node:be,to:Wp(t,null,be.id)},be.id))}),ye.length>0&&o.jsx(Lu,{label:R?"Other products in the library":"Other products",children:ye.map(be=>R?o.jsx(_R,{product:be,variant:"navigate",size:"slider",onOpen:Le=>f(la(t,Le)),href:la(t,be.id)},be.id):o.jsx(FR,{product:be,variant:"navigate",size:"slider",onOpen:Le=>f(la(t,Le)),href:la(t,be.id)},be.id))}),B&&o.jsx(Boe,{size:Z,busy:X,error:I,onSave:be=>void ne(be),onDismiss:()=>F(!1)}),C&&o.jsx("div",{className:"sc-ownedbits",children:o.jsx("div",{className:"sc-lookpage-acts",children:o.jsx(Wn,{label:"Delete product",title:`Delete ${C.name}?`,body:"Shots already made with it keep their images and their recipe. Only future shots lose it.",busy:w,onConfirm:()=>void xe()})})})]})})}function qoe(e,t){const n=new Map,r=[];for(const a of t){n.set(a.id,a.status);const i=e.get(a.id);if(i!==a.status){if(i===void 0){a.status==="running"&&r.push("Generating shot.");continue}a.status==="done"?r.push("Shot ready."):a.status==="error"?r.push(`Shot failed${a.error?`: ${a.error}`:"."}`):a.status==="cancelled"&&r.push("Shot cancelled.")}}return{messages:r,next:n}}const Xoe=[{label:"Generate",keys:["cmd","enter"]},{label:"Jump to the prompt",keys:["/"]},{label:"Product menu",keys:["$"]},{label:"Scene menu",keys:["/"]},{label:"Presenter menu",keys:["@"]},{label:"Colour menu",keys:["#"]},{label:"Previous or next shot",keys:["←","→"]},{label:"Previous or next in the history",keys:["↑","↓"]},{label:"Refine this shot",keys:["b"]},{label:"Keep or unkeep",keys:["k"]},{label:"Open the shot",keys:["enter"]},{label:"Close, or stop refining",keys:["esc"]},{label:"Assets panel",keys:["."]},{label:"This list",keys:["?"]}];function Qoe({open:e,onOpenChange:t}){return o.jsx(Q4,{open:e,onOpenChange:t,children:o.jsxs(J4,{maxWidth:"360px","aria-describedby":void 0,children:[o.jsx(ev,{children:"Shortcuts"}),o.jsx("div",{className:"sc-keys",children:Xoe.map(n=>o.jsxs("div",{className:"sc-krow",children:[o.jsx("span",{children:n.label}),o.jsx("span",{className:"sc-ksp"}),n.keys.map(r=>o.jsx("kbd",{children:r},r))]},n.label))})]})})}const ZR=new Set;function Joe(e){return ZR.has(e)}function eie(e){e&&ZR.add(e)}function tie({src:e,fallback:t,alt:n="",aspect:r,guess:a=!0}){const[i,l]=s.useState(!1),u=i&&t?t:e,[f,h]=s.useState(!1),[p,g]=s.useState(u);u!==p&&(g(u),h(!1));const v=s.useRef(null),w=s.useCallback(()=>{eie(u),h(!0)},[u]),y=s.useCallback(k=>{v.current=k,k!=null&&k.complete&&k.naturalWidth&&w()},[w]);s.useLayoutEffect(()=>{const k=v.current;k!=null&&k.complete&&k.naturalWidth&&w()},[w]);const x=Joe(u);return o.jsxs("span",{className:"sc-cellimg","data-loaded":f||void 0,"data-cached":x||void 0,"data-guess":a||void 0,style:r?{"--sc-cell-ar":r}:void 0,children:[!f&&!x&&o.jsx("span",{className:"sc-shimmer"}),o.jsx("img",{ref:y,src:u,alt:n,loading:x?"eager":"lazy",decoding:x?"sync":"async",onLoad:()=>w(),onError:()=>{t&&!i?l(!0):w()}})]})}function VR({name:e}){return o.jsx(Sv,{name:e})}function nie({node:e,chosen:t,picking:n,batching:r,armed:a,menu:i,onPick:l,onBranch:u,onToggleKeep:f,onArchive:h,onDelete:p}){const g=Sr(e),v=yv(),w=(x,k)=>EA(x,k,v),y=()=>{const x=e.images[0];if(!x)return;const k=e.promptHead.slice(0,40).replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"")||"shot",S=document.createElement("a");S.href=Mr(x),S.download=`${k}.png`,S.click()};return o.jsxs(o.Fragment,{children:[!r&&o.jsx("span",{className:"sc-cell-veil","aria-hidden":!0}),n&&w(t?"Deselect":"Select",o.jsx("button",{type:"button",className:"sc-cell-ctl sc-cell-pick","data-on":t||void 0,"aria-pressed":t,"aria-label":t?"Deselect shot":"Select shot",onClick:()=>l==null?void 0:l(e.id),children:o.jsx(Kn,{size:13,weight:"bold"})})),a&&!n&&o.jsxs("span",{className:"sc-cell-ctl sc-cell-pick","data-on":!0,title:"Being refined",children:[o.jsx(Kn,{size:13,weight:"bold"}),o.jsx("span",{className:"sc-vh",children:"Being refined"})]}),o.jsx("div",{className:"sc-shot-tools",children:f&&o.jsxs("div",{className:"sc-corner",children:[i.length>0&&o.jsxs(Ss,{children:[w("More",o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-cell-ctl sc-cell-more","aria-label":`More for ${g}`,children:o.jsx(CC,{size:16,weight:"bold"})})})),o.jsx(Cs,{align:"end",sideOffset:4,collisionPadding:12,children:i.map(x=>o.jsxs("span",{style:{display:"contents"},children:[x.separated&&o.jsx(Bl,{}),o.jsxs(tr,{color:x.danger?"red":void 0,onSelect:x.onSelect,children:[o.jsx(VR,{name:x.icon}),x.label]})]},x.key))})]}),u&&!r&&w("Refine",o.jsx("button",{type:"button",className:"sc-cell-ctl sc-cell-branch","data-on":a||void 0,"aria-label":`Refine ${g}`,onClick:()=>u(e.id),children:o.jsx(zC,{size:15,weight:"bold"})})),e.archived?p&&w("Delete permanently",o.jsx("button",{type:"button",className:"sc-cell-ctl","aria-label":`Delete ${g} permanently`,onClick:()=>p(e),children:o.jsx(il,{size:15})})):h&&w("Archive",o.jsx("button",{type:"button",className:"sc-cell-ctl","aria-label":`Archive ${g}`,onClick:()=>h(e),children:o.jsx(Op,{size:15})})),e.images[0]&&w("Download",o.jsx("button",{type:"button",className:"sc-cell-ctl","aria-label":`Download ${g}`,onClick:y,children:o.jsx(AC,{size:15})})),w(e.kept?"Remove from Keepers":"Add to Keepers",o.jsx("button",{type:"button",className:`sc-cell-ctl sc-cell-keep${e.kept?" sc-cell-star":""}`,"data-on":e.kept||void 0,"aria-pressed":e.kept,"aria-label":e.kept?`Remove ${g} from Keepers`:`Add ${g} to Keepers`,onClick:()=>f(e),children:o.jsx(po,{size:15,weight:e.kept?"fill":"regular"})}))]})})]})}function zR(e,t){return e>1?`Remove ${e} shots from ${t}`:`Remove from ${t}`}function th(e,t,n){return e>1?n(e):t}function rie(e,{chosen:t,batching:n,versions:r,onOpen:a,onBranch:i,onPick:l,onVersions:u,onToggleKeep:f,onArchive:h,onDeletePermanently:p,shotHref:g,inSet:v,filedIn:w,onRemoveFromSet:y,batch:x}){const k=[{key:"open",icon:"open",label:"Open",onSelect:()=>a(e.id)}];g&&k.push({key:"open-tab",icon:"open-tab",label:"Open in new tab",onSelect:()=>window.open(g(e.id),"_blank")}),i&&!n&&k.push({key:"branch",icon:"refine",label:"Refine",onSelect:()=>i(e.id)});const S=!!(n&&t&&x&&x.count>0),E=!!(S&&x&&x.count>1);l&&k.push({key:"pick",icon:"select",label:t?E?"Deselect this shot":"Deselect":"Select",onSelect:()=>l(e.id)});const j=M=>M?"Remove from Keepers":"Add to Keepers",N=(M,C)=>M?`Remove ${C} shots from Keepers`:`Add ${C} shots to Keepers`;S&&x?k.push({key:"keep",icon:x.allKept?"kept":"keep",label:th(x.count,j(x.allKept),M=>N(x.allKept,M)),onSelect:x.onKeep,separated:E}):f&&k.push({key:"keep",icon:e.kept?"kept":"keep",label:j(e.kept),onSelect:()=>f(e)});const P=S?x==null?void 0:x.onRemoveFromSet:y,$=S?v?[v]:[]:v?[v]:w??[];if(P)for(const M of $)k.push({key:`unset-${M.id}`,icon:"unset",label:zR(S&&x?x.count:1,M.name),onSelect:()=>P(M)});return r>0&&u&&!n&&k.push({key:"versions",icon:"versions",label:`Show ${r} version${r===1?"":"s"}`,onSelect:()=>u(e.id)}),S&&x?(k.push({key:"archive",icon:x.archived?"restore":"archive",label:x.archived?th(x.count,"Restore",M=>`Restore ${M} shots`):th(x.count,"Archive",M=>`Archive ${M} shots`),onSelect:x.archived?x.onRestore:x.onArchive,danger:!x.archived,separated:!0}),x.archived&&k.push({key:"delete",icon:"delete",label:th(x.count,"Delete permanently",M=>`Delete ${M} shots permanently`),onSelect:x.onDelete,danger:!0,separated:!0})):(h&&k.push({key:"archive",icon:e.archived?"restore":"archive",label:e.archived?"Restore":"Archive",onSelect:()=>h(e),danger:!e.archived,separated:!0}),p&&e.archived&&k.push({key:"delete",icon:"delete",label:"Delete permanently",onSelect:()=>p(e),danger:!0,separated:!0})),k}function BR(e,t){var r,a,i,l;const n=(i=(a=(r=e.brief)==null?void 0:r.rendered)==null?void 0:a.sizes)==null?void 0:i[t];return n&&n[0]>0&&n[1]>0?{aspect:n[0]/n[1],guess:!1}:{aspect:Bu((l=e.brief)==null?void 0:l.format),guess:!0}}const sie=s.memo(function({node:t,selected:n,armed:r,chosen:a,picking:i,batching:l,versions:u,handlers:f,inSet:h,filedIn:p,pickedMeta:g}){const v=rie(t,{chosen:a,batching:l,versions:u,onOpen:f.onOpen,shotHref:f.shotHref,onBranch:f.onBranch,onPick:f.onPick,onVersions:f.onVersions,onToggleKeep:f.onToggleKeep,onArchive:f.onArchive,onDeletePermanently:f.onDeleteAsk,inSet:h,filedIn:p,onRemoveFromSet:f.onRemoveFromSet?w=>{var y;return(y=f.onRemoveFromSet)==null?void 0:y.call(f,t,w)}:void 0,batch:l&&a&&g&&f.onKeepPicked?{...g,onKeep:f.onKeepPicked,onArchive:f.onArchivePicked??(()=>{}),onRestore:f.onRestorePicked??(()=>{}),onDelete:f.onDeletePickedAsk??(()=>{}),onRemoveFromSet:f.onRemovePickedFromSet}:null});return o.jsxs(ff,{children:[o.jsx(hf,{children:o.jsxs("div",{className:"sc-cell","data-fb-node":t.id,"data-selected":n,"data-armed":r||void 0,"data-batching":l||void 0,"data-picked":a||void 0,children:[o.jsx(_n,{className:"sc-cell-open",to:f.shotHref(t.id),"aria-label":l?`${a?"Deselect":"Select"} ${Sr(t)}`:`Open ${Sr(t)}`,onClick:w=>{var y;l&&(w.preventDefault(),(y=f.onPick)==null||y.call(f,t.id))},children:o.jsx(tie,{src:dn(t.images[0],"tile"),fallback:Mr(t.images[0]),...BR(t,0)})}),o.jsx(nie,{node:t,chosen:a,picking:i,batching:l,armed:r,menu:v,onPick:f.onPick,onBranch:f.onBranch,onToggleKeep:f.onToggleKeep,onArchive:f.onArchive,onDelete:f.onDeleteAsk})]})}),o.jsx(pf,{children:v.map(w=>o.jsxs("span",{style:{display:"contents"},children:[w.separated&&o.jsx(Hp,{}),o.jsxs(mf,{color:w.danger?"red":void 0,onSelect:w.onSelect,children:[o.jsx(VR,{name:w.icon}),w.label]})]},w.key))})]})}),aie=s.memo(function({node:t,selected:n,shotHref:r,onCancel:a}){var i;return o.jsxs("div",{className:"sc-cell","data-running":"true","data-fb-node":t.id,"data-selected":n,style:{"--sc-cell-ar":Bu((i=t.brief)==null?void 0:i.format)},children:[o.jsxs(_n,{className:"sc-cell-open",to:r(t.id),"aria-label":`Open ${Sr(t)}, still rendering`,children:[o.jsx("span",{className:"sc-shimmer"}),o.jsx(KM,{since:Oi(t)})]}),a&&o.jsx("button",{type:"button",className:"sc-cell-ctl sc-cell-cancel","data-urgent":nc(Oi(t))>=60||void 0,onClick:()=>a(t),children:"Cancel"})]})}),oie=s.memo(function({node:t,selected:n,shotHref:r,engineName:a,onRetry:i,onArchive:l}){const u=t.status==="cancelled",f=u?bA():kf(t.error,a==null?void 0:a(t.engineId));return o.jsxs("div",{className:"sc-cell","data-fb-node":t.id,"data-cancelled":u||void 0,"data-failed":!u||void 0,"data-selected":n,children:[o.jsx(_n,{className:"sc-cell-open",to:r(t.id),"aria-label":`Open ${Sr(t)}`}),o.jsx("span",{className:"sc-cell-failed",children:o.jsx(Zj,{failure:f,density:"tile",onRetry:()=>i(t),dismiss:l?{label:t.archived?"Restore":"Dismiss",onClick:()=>l(t)}:void 0})})]})}),iie=40,lie=1,O5=64,cie=e=>e>iie,uie=e=>Math.floor(e/O5)*O5;function nh(e,t,n){const r=Math.max(0,n-2),a=e!=="failed"&&t&&t>0?t:4/5;return Math.round(r/a)+2+Ru}function I5(e){const t=new Array(e.length+1);let n=0;for(let r=0;r<e.length;r++)t[r]=n,n+=e[r];return t[e.length]=n,t}function die(e,t,n){const r=e.length-1;if(r<=0||n<=t)return[0,0];let a=0,i=r;for(;a<i;){const u=a+i>>1;e[u+1]<=t?a=u+1:i=u}const l=a;for(a=l,i=r;a<i;){const u=a+i>>1;e[u]<n?a=u+1:i=u}return[l,a]}function F5(e,t){const n=Array.from({length:Math.max(1,t)},()=>[]);for(let r=0;r<e;r++)n[r%n.length].push(r);return n}function fie(e,t){const n=t*lie;return[e-n,e+t+n]}function ww(e){const t=e.getBoundingClientRect().top,n=e.querySelector(".sc-toolbar");return n?Math.max(t,n.getBoundingClientRect().bottom):t}function hie(e,t){const[n,r]=s.useState(()=>({top:0,height:typeof window>"u"?0:window.innerHeight})),a=s.useRef(null),i=s.useRef(null),l=s.useRef((h,p=0)=>{i.current=h?{anchor:h,until:p}:null}).current,u=s.useRef(()=>{}),f=s.useRef(()=>u.current()).current;return s.useLayoutEffect(()=>{if(!e)return;const h=e.closest(".sc-canvas");if(!h)return;let p=0,g=0;const v=()=>{var S;const k=i.current;if(k&&performance.now()<k.until){a.current=k.anchor;return}i.current=null,a.current=h.scrollTop>0?pie(e,ww(h),(S=a.current)==null?void 0:S.id):null},w=()=>{if(p=0,t){const k=e.getBoundingClientRect().top-h.getBoundingClientRect().top+h.scrollTop,S={top:uie(h.scrollTop-k),height:h.clientHeight};r(E=>E.top===S.top&&E.height===S.height?E:S)}v(),cancelAnimationFrame(g),g=requestAnimationFrame(v)},y=()=>{p||(p=requestAnimationFrame(w))};u.current=w,w(),h.addEventListener("scroll",y,{passive:!0});const x=new ResizeObserver(y);return x.observe(h),x.observe(e),()=>{cancelAnimationFrame(p),cancelAnimationFrame(g),u.current=()=>{},h.removeEventListener("scroll",y),x.disconnect()}},[e,t]),{...n,anchor:a,resync:f,hold:l}}function pie(e,t,n){let r=null,a=null;for(const l of e.querySelectorAll(".sc-cell[data-fb-node]")){const u=l.getBoundingClientRect();if(u.bottom<=t||u.height===0)continue;const f=l.getAttribute("data-fb-node");if(!f)continue;const h={id:f,top:u.top,left:u.left};if(u.top>=t-1){const p=!!r&&Math.abs(u.top-r.top)<=1;(!r||u.top<r.top-1||p&&r.id!==n&&(f===n||u.left<r.left))&&(r=h)}else(!a||u.left<a.left)&&(a=h)}const i=r??a;return i?{id:i.id,offset:i.top-t}:null}function mie(e,t,n){const r=s.useRef(new Map),[,a]=s.useState(0),i=s.useRef(null),l=s.useRef(new Set);return s.useLayoutEffect(()=>{if(!t)return;let u=0;const f=new ResizeObserver(h=>{let p=!1;for(const g of h){const v=g.target.getAttribute("data-fb-node");if(!v)continue;const w=g.target;if(w.offsetHeight<=2||w.offsetWidth<=2)continue;const y=(w.offsetHeight-2)/(w.offsetWidth-2),x=r.current.get(v);(x===void 0||Math.abs(x-y)>.004)&&(r.current.set(v,y),p=!0)}p&&!u&&(u=requestAnimationFrame(()=>{u=0,a(g=>g+1)}))});return i.current=f,()=>{cancelAnimationFrame(u),f.disconnect(),i.current=null,l.current=new Set}},[t]),s.useLayoutEffect(()=>{const u=i.current;if(!(!t||!u||!e)){for(const f of l.current)f.isConnected||(u.unobserve(f),l.current.delete(f));for(const f of e.querySelectorAll(".sc-cell[data-fb-node]"))l.current.has(f)||(l.current.add(f),u.observe(f))}}),s.useCallback(u=>{const f=r.current.get(u);return f===void 0?void 0:Math.round(f*Math.max(0,n-2))+2+Ru},[n])}function gie({nodes:e,selectedId:t,onOpen:n,shotHref:r,onRetry:a,onCancel:i,onToggleKeep:l,onArchive:u,onDeletePermanently:f,picked:h,onPick:p,empty:g,sending:v,onBranch:w,branchingFrom:y,onVersions:x,engineName:k,tile:S,pending:E,onNearEnd:j,inSet:N,setsFor:P,onRemoveFromSet:$,onKeepPicked:M,onArchivePicked:C,onRestorePicked:R,onDeletePicked:T,onRemovePickedFromSet:H}){const D=e.filter(ye=>ye.kind!=="root"),K=!!p,O=K&&((h==null?void 0:h.size)??0)>0,Z=s.useMemo(()=>{if(!h||h.size===0)return null;let ye=0,Ee=0,be=0;for(const Le of e)!h.has(Le.id)||Le.kind==="root"||(ye+=1,Le.kept&&(Ee+=1),Le.archived&&(be+=1));return{count:h.size,allKept:ye>0&&Ee===ye,archived:ye>0&&be===ye}},[e,h]),[te,B]=s.useState(null),[F,X]=s.useState(!1),[z,I]=s.useState(null),{tile:U,cols:G}=Ste(xte(z),S,kte()<yte),[ne,q]=s.useState(null);s.useEffect(()=>{if(!ne||!j)return;const ye=ne.closest(".sc-canvas"),Ee=new IntersectionObserver(be=>{be.some(Le=>Le.isIntersecting)&&j()},{root:ye,rootMargin:"200% 0px"});return Ee.observe(ne),()=>Ee.disconnect()},[ne,j]);const le=s.useRef({onOpen:n,shotHref:r,onRetry:a,onCancel:i,onToggleKeep:l,onArchive:u,onBranch:w,onPick:p,onVersions:x,engineName:k,onRemoveFromSet:$,onKeepPicked:M,onArchivePicked:C,onRestorePicked:R,onDeletePicked:T,onRemovePickedFromSet:H});le.current={onOpen:n,shotHref:r,onRetry:a,onCancel:i,onToggleKeep:l,onArchive:u,onBranch:w,onPick:p,onVersions:x,engineName:k,onRemoveFromSet:$,onKeepPicked:M,onArchivePicked:C,onRestorePicked:R,onDeletePicked:T,onRemovePickedFromSet:H};const Se=!!f,Q=!!T,xe=s.useMemo(()=>({onOpen:ye=>le.current.onOpen(ye),shotHref:ye=>le.current.shotHref(ye),onRetry:ye=>le.current.onRetry(ye),onCancel:i?ye=>{var Ee,be;return(be=(Ee=le.current).onCancel)==null?void 0:be.call(Ee,ye)}:void 0,onToggleKeep:l?ye=>{var Ee,be;return(be=(Ee=le.current).onToggleKeep)==null?void 0:be.call(Ee,ye)}:void 0,onArchive:u?ye=>{var Ee,be;return(be=(Ee=le.current).onArchive)==null?void 0:be.call(Ee,ye)}:void 0,onBranch:w?ye=>{var Ee,be;return(be=(Ee=le.current).onBranch)==null?void 0:be.call(Ee,ye)}:void 0,onPick:p?ye=>{var Ee,be;return(be=(Ee=le.current).onPick)==null?void 0:be.call(Ee,ye)}:void 0,onVersions:x?ye=>{var Ee,be;return(be=(Ee=le.current).onVersions)==null?void 0:be.call(Ee,ye)}:void 0,onDeleteAsk:Se?ye=>B(ye):void 0,engineName:k?ye=>{var Ee,be;return(be=(Ee=le.current).engineName)==null?void 0:be.call(Ee,ye)}:void 0,onRemoveFromSet:$?(ye,Ee)=>{var be,Le;return(Le=(be=le.current).onRemoveFromSet)==null?void 0:Le.call(be,ye,Ee)}:void 0,onKeepPicked:M?()=>{var ye,Ee;return(Ee=(ye=le.current).onKeepPicked)==null?void 0:Ee.call(ye)}:void 0,onArchivePicked:C?()=>{var ye,Ee;return(Ee=(ye=le.current).onArchivePicked)==null?void 0:Ee.call(ye)}:void 0,onRestorePicked:R?()=>{var ye,Ee;return(Ee=(ye=le.current).onRestorePicked)==null?void 0:Ee.call(ye)}:void 0,onDeletePickedAsk:Q?()=>X(!0):void 0,onRemovePickedFromSet:H?ye=>{var Ee,be;return(be=(Ee=le.current).onRemovePickedFromSet)==null?void 0:be.call(Ee,ye)}:void 0}),[!!i,!!l,!!u,!!w,!!p,!!x,Se,Q,!!k,!!$,!!M,!!C,!!R,!!H]),ee=[...v?Array.from({length:Math.max(1,v.count)},(ye,Ee)=>({key:`sending-${Ee}`,node:null,said:v.said})):[],...D.map(ye=>({key:ye.id,node:ye}))],ae=ye=>ye.status==="cancelled"||ye.status==="error"||ye.images.length===0,re=ye=>{const Ee=ye.node;return Ee?Ee.status==="running"?o.jsx(aie,{node:Ee,selected:Ee.id===t,shotHref:xe.shotHref,onCancel:xe.onCancel},Ee.id):ae(Ee)?o.jsx(oie,{node:Ee,selected:Ee.id===t,shotHref:xe.shotHref,engineName:xe.engineName,onRetry:xe.onRetry,onArchive:xe.onArchive},Ee.id):o.jsx(sie,{node:Ee,selected:Ee.id===t,armed:Ee.id===y,chosen:(h==null?void 0:h.has(Ee.id))??!1,picking:K,batching:O,versions:Ee.childCount,handlers:xe,inSet:N,filedIn:P==null?void 0:P(Ee.id),pickedMeta:Z},Ee.id):o.jsxs("div",{className:"sc-cell","data-running":"true","data-sending":"true",children:[o.jsx("span",{className:"sc-shimmer"}),o.jsx("span",{className:"sc-cell-tag",children:"sending"}),o.jsx("span",{className:"sc-cell-said",dir:"auto",children:ye.said})]},ye.key)},_=ye=>{var be;const Ee=ye.node;return Ee?Ee.status==="running"?nh("running",Bu((be=Ee.brief)==null?void 0:be.format),U):ae(Ee)?nh("failed",void 0,U):nh("done",BR(Ee,0).aspect,U):nh("sending",void 0,U)},ue=cie(ee.length),We=hie(z,ue),Xe=mie(z,ue,U),ze=zk(G),tt=`${ze}:${U}`,ce=s.useRef(tt),ve=s.useRef({items:ee,heightOf:Xe,estimate:_});ve.current={items:ee,heightOf:Xe,estimate:_};const Pe=s.useRef(null);if(s.useLayoutEffect(()=>{const ye=ce.current;ce.current=tt;const Ee=We.anchor.current,be=z==null?void 0:z.closest(".sc-canvas");if(!(ye===tt||!Ee||!z||!be)){if(Pe.current={anchor:Ee,until:performance.now()+vie},We.hold(Ee,Pe.current.until),!_5(z,be,Ee)){const{items:Le,heightOf:Qe,estimate:Ke}=ve.current,nt=Le.findIndex(Nt=>{var cn;return((cn=Nt.node)==null?void 0:cn.id)===Ee.id});if(nt<0)return;const gt=F5(Le.length,ze)[nt%ze],Pt=I5(gt.map(Nt=>(Le[Nt].node&&Qe(Le[Nt].node.id))??Ke(Le[Nt]))),Ut=z.getBoundingClientRect().top+Pt[Math.floor(nt/ze)];be.scrollTop+=Ut-ww(be)-Ee.offset}We.resync()}},[tt,ze,z,We.anchor,We.resync,We.hold]),s.useLayoutEffect(()=>{const ye=Pe.current,Ee=z==null?void 0:z.closest(".sc-canvas");if(!(!ye||!z||!Ee)){if(performance.now()>ye.until){Pe.current=null;return}_5(z,Ee,ye.anchor)}}),s.useEffect(()=>{const ye=z==null?void 0:z.closest(".sc-canvas");if(!ye)return;const Ee=()=>{Pe.current=null,We.hold(null)},be=["wheel","touchstart","keydown","pointerdown"];for(const Le of be)ye.addEventListener(Le,Ee,{passive:!0});return()=>{for(const Le of be)ye.removeEventListener(Le,Ee)}},[z,We.hold]),E&&Y3(D)&&!v){const ye=Math.max(1,Math.min(G,8));return o.jsx("div",{className:"sc-feed",ref:I,style:{"--sc-tile":`${U}px`,"--sc-cols":ye},children:Array.from({length:ye},(Ee,be)=>o.jsx("div",{className:"sc-feed-col",children:Array.from({length:2},(Le,Qe)=>o.jsx("div",{className:"sc-cell","data-running":"true","data-sending":"true",children:o.jsx("span",{className:"sc-shimmer"})},`pending-${be}-${Qe}`))},`col-${ye}-${be}`))})}if(Y3(D)&&!v)return o.jsx(o.Fragment,{children:g??o.jsx("p",{className:"sc-feed-empty",children:"Nothing here yet."})});const de=zk(G),je=F5(ee.length,de),Ue=ue?fie(We.top,We.height):null;return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sc-feed",ref:I,style:{"--sc-tile":`${U}px`,"--sc-cols":de},children:je.map((ye,Ee)=>{const be=`col-${de}-${Ee}`;if(!Ue)return o.jsx("div",{className:"sc-feed-col",children:ye.map(gt=>re(ee[gt]))},be);const Le=ye.map(gt=>(ee[gt].node&&Xe(ee[gt].node.id))??_(ee[gt])),Qe=I5(Le),[Ke,nt]=die(Qe,Ue[0],Ue[1]);return o.jsxs("div",{className:"sc-feed-col",children:[Ke>0&&o.jsx("div",{className:"sc-feed-pad",style:{height:Qe[Ke]},"aria-hidden":!0}),ye.slice(Ke,nt).map(gt=>re(ee[gt])),nt<ye.length&&o.jsx("div",{className:"sc-feed-pad",style:{height:Qe[ye.length]-Qe[nt]},"aria-hidden":!0})]},be)})}),j&&o.jsx("div",{className:"sc-feed-end",ref:q,"aria-hidden":!0}),o.jsx(sf,{open:!!te||F,onOpenChange:ye=>{ye||(B(null),X(!1))},children:o.jsxs(af,{maxWidth:"420px",children:[o.jsx(of,{children:F?`Delete ${(Z==null?void 0:Z.count)??0} shot${((Z==null?void 0:Z.count)??0)===1?"":"s"} permanently?`:"Delete this shot permanently?"}),o.jsx(lf,{size:"2",children:"This cannot be undone."}),o.jsxs(js,{gap:"3",mt:"4",justify:"end",children:[o.jsx(uf,{children:o.jsx(ia,{variant:"soft",color:"gray",children:"Cancel"})}),o.jsx(cf,{children:o.jsx(ia,{color:"red",onClick:()=>{F?T==null||T():te&&(f==null||f(te)),B(null),X(!1)},children:"Delete permanently"})})]})]})})]})}const vie=800;function _5(e,t,n){const r=e.querySelector(`.sc-cell[data-fb-node="${CSS.escape(n.id)}"]`);if(!r)return!1;const a=r.getBoundingClientRect().top-ww(t)-n.offset;return Math.abs(a)>=1&&(t.scrollTop+=a),!0}function wie(e){return e==="open"||e==="result"?"open":"compact"}function U6({name:e,kind:t,count:n,mode:r,onToggle:a,action:i,children:l}){const u=wie(r);return o.jsxs("div",{className:"sc-agroup","data-mode":r,"data-kind":t,children:[o.jsxs("div",{className:"sc-agroup-h",children:[o.jsxs("button",{type:"button",className:"sc-agroup-t","aria-expanded":r==="open",onClick:a,children:[o.jsx("b",{children:e}),n!==void 0&&n>0&&o.jsx("span",{className:"sc-agroup-n",children:n}),o.jsx(Yi,{size:11,className:"sc-agroup-caret","aria-hidden":"true"})]}),i]}),o.jsx("div",{className:"sc-agroup-body",children:o.jsx("div",{className:"sc-agroup-content",children:o.jsx("div",{className:"sc-agroup-layer",children:l(u)},u)})})]})}function UR({candidate:e,on:t,named:n,disabled:r,title:a,onClick:i}){const l=o.jsxs("button",{type:"button",className:"sc-acard","data-on":t||void 0,"aria-label":e.full,"aria-pressed":t,"aria-disabled":r||void 0,title:r?void 0:e.full,onClick:r?void 0:i,children:[o.jsxs("span",{className:"sc-acard-thumb",children:[e.thumb?o.jsx("img",{src:e.thumb,alt:"",loading:"lazy","data-crop":e.crop}):o.jsx("span",{className:"sc-aswatch",style:{display:"grid",placeItems:"center"},children:o.jsx(Ws,{size:14})}),o.jsx("span",{className:"sc-acard-tick","aria-hidden":!0,children:o.jsx(Kn,{size:10,weight:"bold"})})]}),n&&o.jsxs("span",{className:"sc-acard-label",children:[e.bookmarked&&o.jsxs(o.Fragment,{children:[o.jsx(po,{className:"sc-bm-mark",size:10,weight:"fill","aria-hidden":!0}),o.jsx("span",{className:"sc-vh",children:"Kept. "})]}),e.label]})]});return o.jsx(TM,{why:r?a:null,children:l})}function g8({kind:e,title:t,items:n,attached:r,mode:a,onToggle:i,onPick:l,onUnpick:u,full:f,moreLabel:h,createLabel:p,onCreate:g}){const v=s.useMemo(()=>new Set(r),[r]),[w,y]=s.useState(ep);return s.useEffect(()=>{a!=="open"&&y(ep)},[a]),a==="result"&&n.length===0?null:o.jsx(U6,{name:t,kind:e,count:n.length,mode:a,onToggle:()=>i(e),action:o.jsx("button",{type:"button",className:"sc-aadd",title:p,"aria-label":p,onClick:g,children:o.jsx(cr,{size:10})}),children:x=>{const{visible:k,more:S}=Nre(n,v,x==="open"?w:F6);return o.jsxs("div",{className:x==="open"?"sc-acard-grid":"sc-arow",children:[k.map(E=>o.jsx(UR,{candidate:E,on:v.has(E.id),named:x==="open",disabled:!!f&&!v.has(E.id),title:f??void 0,onClick:()=>v.has(E.id)?u(E.id):l(E.id)},E.id)),x==="open"&&S>0&&o.jsxs("button",{type:"button",className:"sc-amore-tile",onClick:()=>y(E=>E+v0),"aria-label":`Show ${Math.min(S,v0)} more ${h}`,children:[o.jsxs("span",{className:"sc-amore-n",children:["+",S]}),o.jsx("span",{className:"sc-amore-t",children:"more"})]})]})}})}const Z5=220,V5="cubic-bezier(0.32, 0.72, 0, 1)";function v8(e){const t=[];for(const n of e.querySelectorAll(".sc-agroup")){const r=n.querySelector(":scope > .sc-agroup-body");r&&t.push({group:n,body:r,height:r.getBoundingClientRect().height,marginBottom:Number.parseFloat(getComputedStyle(n).marginBottom)||0})}return t}function yie(e,t){const n=s.useRef(null),r=()=>{const a=e.current;if(!(!a||window.matchMedia("(prefers-reduced-motion: reduce)").matches)){for(const i of v8(a))for(const l of[...i.body.getAnimations(),...i.group.getAnimations()])l.finish();n.current=v8(a)}};return s.useLayoutEffect(()=>{const a=n.current;n.current=null;const i=e.current;if(!(!a||!i))for(const l of v8(i)){const u=a.find(f=>f.group===l.group);if(u){if(Math.abs(u.height-l.height)>.5){const{body:f}=l;f.style.overflow="hidden";const h=f.animate([{height:`${u.height}px`},{height:`${l.height}px`}],{duration:Z5,easing:V5}),p=()=>{f.style.overflow=""};h.onfinish=p,h.oncancel=p}Math.abs(u.marginBottom-l.marginBottom)>.5&&l.group.animate([{marginBottom:`${u.marginBottom}px`},{marginBottom:`${l.marginBottom}px`}],{duration:Z5,easing:V5})}}},[t]),r}function bie({brand:e,shots:t,shotsTotal:n,attached:r=_M,full:a,onToken:i,offToken:l,onTemplate:u,offTemplate:f,onClose:h}){const p=Rf(),g=ll(),{applyBrand:v}=Rn(),{push:w}=or(),[y,x]=nB(Dr.assetsExpanded,null),k=s.useRef(null),S=yie(k,y),E=G=>{S(),x(ne=>ne===G?null:G)},[j,N]=s.useState(""),P=j.trim().length>0,$=G=>{S(),N(""),x(G)},M=G=>P?"result":y===null?"idle":y===G?"open":"collapsed",C=s.useMemo(()=>new Set(vo(e.id)),[e.id]),R=s.useMemo(()=>{const G=ne=>{const q=_i(ne,p);return hm(ne,q,{currentId:null,query:"",bookmarked:C,shown:q.length}).items};return{product:G("product"),presenter:G("presenter"),scene:G("scene")}},[p,C]),T=s.useMemo(()=>({product:Pu(R.product,j),presenter:Pu(R.presenter,j),scene:Pu(R.scene,j)}),[R,j]),H=s.useMemo(()=>{var G;return Zs((G=e.json)==null?void 0:G.palette)},[e]),D=s.useMemo(()=>P?H.filter(G=>wo(`${G.name} ${G.hex}`,j)):H,[H,j,P]),K=G=>{(async()=>{var q;const ne=VA((q=e.json)==null?void 0:q.palette,G);if(ne.swatch){if(ne.added)try{const le=await Re.updateBrand(e.id,{...e.json??{},palette:ne.palette});v(le)}catch(le){w(nn(le,"Could not save the brand"));return}$("colors")}})()},O=G=>{(async()=>{var q;const ne=RY((q=e.json)==null?void 0:q.palette,G);if(ne.removed)try{const le=await Re.updateBrand(e.id,{...e.json??{},palette:ne.palette});v(le)}catch(le){w(nn(le,"Could not save the brand"))}})()},Z=M("shots")==="open",te=Xv(e.id,"",Z),B=s.useMemo(()=>{const G=new Set,ne=[];for(const q of[...t,...te.items])q.status!=="done"||q.images.length===0||G.has(q.id)||(G.add(q.id),ne.push(q));return ne},[t,te.items]),F=Math.max(n??0,te.total,B.length),[X,z]=s.useState(ep);s.useEffect(()=>{Z||z(ep)},[Z]);const I=()=>{z(G=>G+v0),te.hasMore&&B.length<X+2*v0&&te.loadMore()},U=P&&!T.product.length&&!T.presenter.length&&!T.scene.length&&!D.length;return o.jsxs("aside",{ref:k,className:"sc-assets","aria-label":"Assets",children:[o.jsxs("div",{className:"sc-assets-head",children:[o.jsx("b",{children:"Assets"}),o.jsx("button",{type:"button",className:"sc-icon-btn",onClick:h,"aria-label":"Close assets",style:{width:28,height:28},children:o.jsx(jn,{size:12})})]}),o.jsx("div",{className:"sc-assets-searchbar",children:o.jsxs("div",{className:"sc-assets-search",children:[o.jsx(Fu,{size:12}),o.jsx("input",{value:j,onChange:G=>N(G.target.value),onKeyDown:G=>{G.key==="Escape"&&j&&(G.stopPropagation(),N(""))},placeholder:"Search assets","aria-label":"Search assets in this panel"}),P&&o.jsx("button",{type:"button",className:"sc-assets-clear",onClick:()=>N(""),"aria-label":"Clear search",children:o.jsx(jn,{size:11})})]})}),U&&o.jsxs("p",{className:"sc-assets-zero",children:["Nothing here matches “",j.trim(),"”."]}),o.jsx(g8,{kind:"product",title:"Products",items:T.product,attached:r.product,mode:M("product"),onToggle:E,onPick:G=>i({t:"product",id:G}),onUnpick:G=>l({t:"product",id:G}),full:a,moreLabel:"products",createLabel:"Add product",onCreate:()=>g("product",{onCreated:G=>{G.kind==="product"&&($("product"),i({t:"product",id:G.id}))}})}),o.jsx(g8,{kind:"presenter",title:"Presenters",items:T.presenter,attached:r.presenter,mode:M("presenter"),onToggle:E,onPick:G=>i({t:"character",id:G}),onUnpick:G=>l({t:"character",id:G}),full:a,moreLabel:"presenters",createLabel:"Create presenter",onCreate:()=>g("presenter",{onCreated:()=>$("presenter")})}),o.jsx(g8,{kind:"scene",title:"Scenes",items:T.scene,attached:r.scene?[r.scene]:[],mode:M("scene"),onToggle:E,onPick:u,onUnpick:()=>f(),full:a,moreLabel:"scenes",createLabel:"Create scene",onCreate:()=>g("scene",{onCreated:G=>{G.kind==="scene"&&$("scene")}})}),!(P&&D.length===0)&&o.jsx(U6,{name:"Brand colors",count:D.length,mode:M("colors"),onToggle:()=>E("colors"),action:o.jsx(Zu,{className:"sc-aadd",triggerStyle:{background:"none"},value:Jp(H),presets:H.map(G=>G.hex),commitMode:"close",align:"end",label:"Add colour",onChange:K,children:o.jsx(cr,{size:10})}),children:G=>o.jsx("div",{className:"sc-arow",children:(G==="open"?D:D.slice(0,F6)).map(ne=>{const q=r.color.includes(ne.hex.toLowerCase());return o.jsxs("div",{className:"sc-aswatch-tile","data-on":q||void 0,children:[o.jsxs("button",{type:"button",title:`${ne.name} ${ne.hex}`,"aria-pressed":q,onClick:()=>q?l({t:"color",hex:ne.hex,name:ne.name}):i({t:"color",hex:ne.hex,name:ne.name}),children:[o.jsx("span",{className:"sc-aswatch",style:{background:ne.hex}}),o.jsx("span",{className:"sc-acard-tick","aria-hidden":!0,children:o.jsx(Kn,{size:10,weight:"bold"})})]}),G==="open"&&o.jsx("button",{type:"button",className:"sc-aswatch-x","aria-label":`Remove ${ne.name}`,title:"Remove",onClick:()=>O(ne.hex),children:o.jsx(jn,{size:10,weight:"bold"})})]},ne.hex)})})}),B.length>0&&!P&&o.jsx(U6,{name:"Recent shots",count:F,mode:M("shots"),onToggle:()=>E("shots"),children:G=>o.jsxs("div",{className:G==="open"?"sc-acard-grid":"sc-arow",children:[B.slice(0,G==="open"?X:F6).map((ne,q)=>{const le=ne.images[0],Se=r.ref.includes(le);return o.jsx(UR,{candidate:{label:`Shot ${F-q}`,full:`Shot ${F-q} · as reference`,thumb:dn(le,"micro")},on:Se,named:G==="open",disabled:!!a&&!Se,title:a??void 0,onClick:()=>Se?l({t:"ref",imageHash:le}):i({t:"ref",imageHash:le,label:"Shot"})},ne.id)}),G==="open"&&(B.length>X||te.hasMore)&&o.jsxs("button",{type:"button",className:"sc-amore-tile",onClick:I,"aria-label":`Show ${v0} more shots`,"aria-busy":te.loading||void 0,children:[o.jsxs("span",{className:"sc-amore-n",children:["+",Math.max(1,F-Math.min(B.length,X))]}),o.jsx("span",{className:"sc-amore-t",children:"more"})]})]})})]})}function xie({sets:e,active:t,ungrouped:n,ungroupedCount:r,onPlaceAll:a,onPlaceUngrouped:i,onOpenSet:l,onNewSet:u,onResetNewSet:f,onRenameSet:h,onDeleteSet:p,askCreate:g,lens:v,lensCounts:w,onLens:y,q:x,onQ:k,searchTotal:S,sort:E,onSort:j,tile:N,onTile:P,assets:$,onAssets:M,showAssets:C}){const R=t?t.id:n?"__ungrouped__":"__all__",T=t?t.name:n?"Not in a set":"All shots",H=!!t||n,D=wr(Ks),[K,O]=s.useState(!1),[Z,te]=s.useState(!1),[B,F]=s.useState(!1),[X,z]=s.useState(""),I=s.useRef(null),U=s.useRef(!1),G=()=>{U.current=!0,te(!0),z(""),O(!0)},ne=()=>{t&&(U.current=!1,te(!1),z(t.name),O(!0))};s.useEffect(()=>{g&&G()},[g]);const q=()=>{const ae=X.trim();if(!ae)return;const re=U.current;U.current=!1,te(!1),O(!1),re?u(ae):h==null||h(ae)},le=ae=>{if(ae){O(!0);return}const re=U.current;U.current=!1,te(!1),O(!1),re&&(f==null||f())},Se=Lj.map(ae=>({value:ae.id==="all"?null:ae.id,label:ae.label,count:w==null?void 0:w[ae.id]})),Q=o.jsxs(o.Fragment,{children:[o.jsxs(Rh,{value:R,children:[o.jsx(gu,{value:"__all__",onSelect:a,children:"All shots"}),o.jsxs(gu,{value:"__ungrouped__",onSelect:i,children:["Not in a set",r>0?` · ${r}`:""]}),e.length>0&&o.jsx(Bl,{}),e.map(ae=>o.jsx(gu,{value:ae.id,onSelect:()=>l(ae),children:ae.name},ae.id))]}),o.jsx(Bl,{}),o.jsx(tr,{onSelect:()=>{f==null||f(),G()},children:"New set"}),t&&h&&o.jsx(tr,{onSelect:ne,children:"Rename"}),t&&p&&o.jsx(tr,{color:"red",onSelect:()=>F(!0),children:"Delete set"})]}),xe=o.jsx(Rh,{value:E,onValueChange:ae=>j(ae),children:Pj.map(ae=>o.jsx(gu,{value:ae.id,children:ae.label},ae.id))}),ee=H||E!=="newest";return o.jsxs("div",{className:"sc-toolbar",children:[o.jsxs("div",{className:"sc-toolbar-scope",children:[!D&&o.jsxs("div",{className:"sc-toolbar-where",children:[H&&o.jsx("button",{type:"button",className:"sc-toolbar-back","aria-label":"All shots",onClick:a,children:o.jsx(ga,{size:16})}),o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-toolbar-place","data-on":H||void 0,"aria-label":T,children:[o.jsx(av,{className:"sc-toolbar-place-ic",size:16}),o.jsx("span",{className:"sc-toolbar-place-t",children:T}),o.jsx(Yi,{size:10,className:"sc-caret"})]})}),o.jsx(Cs,{align:"start",children:Q})]})]}),o.jsx(Q4,{open:K,onOpenChange:le,children:o.jsxs(J4,{maxWidth:"360px","aria-describedby":void 0,onOpenAutoFocus:ae=>{ae.preventDefault();const re=I.current;re&&(re.focus(),re.select())},children:[o.jsx(ev,{children:Z?"Name this set":"Rename set"}),o.jsx("input",{ref:I,className:"sc-in",style:{width:"100%",marginTop:8},value:X,"aria-label":"Set name",onChange:ae=>z(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&q()}}),o.jsxs(js,{gap:"3",mt:"4",justify:"end",children:[o.jsx(ia,{variant:"soft",color:"gray",onClick:()=>le(!1),children:"Cancel"}),o.jsx(ia,{onClick:q,disabled:!X.trim(),children:"Save"})]})]})}),o.jsx(sf,{open:B,onOpenChange:F,children:o.jsxs(af,{maxWidth:"420px",children:[o.jsx(of,{children:"Delete this set?"}),o.jsx(lf,{size:"2",children:"Shots stay in the library. Only the set goes."}),o.jsxs(js,{gap:"3",mt:"4",justify:"end",children:[o.jsx(uf,{children:o.jsx(ia,{variant:"soft",color:"gray",children:"Cancel"})}),o.jsx(cf,{children:o.jsx(ia,{color:"red",onClick:()=>{p==null||p(),F(!1)},children:"Delete set"})})]})]})}),o.jsx(qv,{"aria-label":"Shot lenses",activeKey:v==="all"?null:v,items:Se,onSelect:ae=>y(ae??"all")})]}),o.jsxs("div",{className:"sc-toolbar-actions",children:[o.jsx(id,{value:x,onChange:k,noun:"shots",total:S}),D?o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-toolbar-btn sc-toolbar-view","data-on":ee||void 0,"aria-label":`Set and sort: ${T}`,children:[o.jsx(ov,{size:15}),ee&&o.jsx("span",{className:"sc-toolbar-view-dot","aria-hidden":!0})]})}),o.jsxs(Cs,{align:"end",children:[o.jsx(t6,{children:"Set"}),Q,o.jsx(Bl,{}),o.jsx(t6,{children:"Sort"}),xe]})]}):o.jsxs(Ss,{children:[o.jsx(Es,{children:o.jsxs("button",{type:"button",className:"sc-toolbar-btn","aria-label":"Sort shots",children:[o.jsx(PU,{size:14}),o.jsx("span",{className:"sc-toolbar-btn-t",children:"Sort"}),o.jsx(Yi,{size:10})]})}),o.jsx(Cs,{align:"end",children:xe})]}),o.jsx(Ate,{value:N,onChange:P}),C&&o.jsx("button",{type:"button",className:"sc-icon-btn sc-toolbar-assets","data-on":$||void 0,onClick:M,"aria-label":"Assets panel","aria-pressed":$,title:"Assets panel (.)",children:o.jsx(JU,{size:15,mirrored:!0})})]})]})}function kie(e){const{push:t}=or(),n=s.useCallback(l=>Re.archiveNode(l.id,!0).then(u=>(e(u),t({kind:"success",title:"Archived",detail:Sr(l),action:{label:"Undo",onClick:()=>void Re.archiveNode(l.id,!1).then(e)}}),!0)).catch(u=>(t(nn(u,"Could not archive this shot")),!1)),[e,t]),r=s.useCallback(l=>Re.archiveNode(l.id,!1).then(u=>(e(u),!0)).catch(u=>(t(nn(u,"Could not restore this shot")),!1)),[e,t]),a=s.useCallback(l=>Promise.all(l.map(u=>Re.archiveNode(u,!0))).then(u=>{for(const f of u)e(f);return t({kind:"success",title:`Archived ${u.length} shot${u.length===1?"":"s"}`,action:{label:"Undo",onClick:()=>{Promise.all(u.map(f=>Re.archiveNode(f.id,!1))).then(f=>{for(const h of f)e(h)})}}}),!0}).catch(u=>(t(nn(u,"Could not archive these shots")),!1)),[e,t]),i=s.useCallback(l=>Promise.all(l.map(u=>Re.archiveNode(u,!1))).then(u=>{for(const f of u)e(f);return!0}).catch(u=>(t(nn(u,"Could not restore these shots")),!1)),[e,t]);return{archive:n,archiveBatch:a,unarchive:r,unarchiveBatch:i}}function Sie(e){const{push:t}=or(),n=s.useCallback(a=>Re.deleteNode(a.id).then(()=>e([a.id])).catch(i=>t(nn(i,"Could not delete this shot"))),[e,t]),r=s.useCallback(a=>Re.deleteNodesBatch(a).then(()=>e(a)).catch(i=>t(nn(i,"Could not delete these shots"))),[e,t]);return{remove:n,removeBatch:r}}function Eie(e,{demoProducts:t,presenters:n,scenes:r}){var f,h,p,g;const a=((f=e.brief)==null?void 0:f.tokens)??[],i=(h=a.find(v=>(v==null?void 0:v.t)==="product"))==null?void 0:h.id,l=(p=a.find(v=>(v==null?void 0:v.t)==="character"))==null?void 0:p.id,u=(g=a.find(v=>(v==null?void 0:v.t)==="template"))==null?void 0:g.id;return{product:i?t.find(v=>v.id===i):void 0,presenter:l?n.find(v=>v.id===l):void 0,scene:u?r.find(v=>v.id===u):void 0}}function Cie(e,t){const{product:n,presenter:r,scene:a}=Eie(e,t);return{productName:n?go(n,"chip"):null,productPreviewUrl:(n==null?void 0:n.previewUrl)??null,productId:(n==null?void 0:n.id)??null,presenterName:(r==null?void 0:r.name)??null,presenterPreviewUrl:r?ti(r).src:null,presenterId:(r==null?void 0:r.id)??null,sceneName:a?Qi(a,"chip"):null,scenePreviewUrl:(a==null?void 0:a.previewUrl)??null,sceneId:(a==null?void 0:a.id)??null}}function jie(e){const t=s.useRef(null),n=s.useRef(0),r=s.useRef(null),a=s.useRef(0),i=s.useCallback(()=>{const h=t.current;h&&(n.current=h.scrollWidth/3)},[]);s.useEffect(()=>{const h=t.current;if(!h||!e)return;i(),h.scrollLeft=n.current;const p=new ResizeObserver(()=>{const g=n.current;i(),g<=0&&n.current>0&&(h.scrollLeft=n.current)});p.observe(h);for(const g of h.children)p.observe(g);return()=>p.disconnect()},[e,i]);const l=s.useCallback(()=>{const h=t.current,p=n.current;!h||p<=0||(h.scrollLeft<p*.5?(h.scrollLeft+=p,r.current!==null&&(r.current+=p)):h.scrollLeft>p*1.5&&(h.scrollLeft-=p,r.current!==null&&(r.current-=p)))},[]),u=s.useCallback(()=>{r.current=null,cancelAnimationFrame(a.current)},[]);s.useEffect(()=>{const h=t.current;if(!h)return;let p=0;const g=()=>{p||(p=requestAnimationFrame(()=>{p=0,l()}))},v=y=>{Math.abs(y.deltaY)<=Math.abs(y.deltaX)||(y.preventDefault(),u(),h.scrollLeft+=y.deltaY)},w=y=>{y.target.closest(".sc-shelf-arrow")||u()};return h.addEventListener("scroll",g,{passive:!0}),h.addEventListener("wheel",v,{passive:!1}),h.addEventListener("pointerdown",w),()=>{p&&cancelAnimationFrame(p),u(),h.removeEventListener("scroll",g),h.removeEventListener("wheel",v),h.removeEventListener("pointerdown",w)}},[u,l]);const f=s.useCallback(h=>{const p=t.current,g=p==null?void 0:p.firstElementChild;if(!p||!g)return;const v=g.offsetWidth||232,w=Number.parseFloat(getComputedStyle(p).columnGap)||0,y=v+w,x=r.current??p.scrollLeft;r.current=x+y*h;const k=()=>{u()};if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){p.scrollLeft=r.current,k(),l();return}cancelAnimationFrame(a.current);let S=0;const E=()=>{const j=r.current;if(j===null)return;const N=j-p.scrollLeft;if(S+=1,Math.abs(N)<.5||S>45){p.scrollLeft=j,k(),l();return}p.scrollLeft+=N*.16,a.current=requestAnimationFrame(E)};a.current=requestAnimationFrame(E)},[u,l]);return{ref:t,page:f}}function Aie(e){const t=[...e];for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}function Nie({entries:e,catalogs:t,stagedId:n,onUse:r,productHref:a,presenterHref:i,sceneHref:l}){const u=s.useMemo(()=>Aie(e).slice(0,10),[e]),{ref:f,page:h}=jie(u.length);return o.jsxs("div",{className:"sc-canvas-empty",children:[o.jsxs("h3",{children:["Your first ",o.jsx("em",{children:"shot"})]}),o.jsx("p",{children:"Describe what you want in the prompt below, or open one of these."}),u.length>0&&o.jsxs("div",{className:"sc-shelf",children:[o.jsx("button",{type:"button",className:"sc-shelf-arrow prev","aria-label":"Previous examples",onClick:()=>h(-1),children:o.jsx(ga,{size:13,weight:"bold"})}),o.jsx("button",{type:"button",className:"sc-shelf-arrow next","aria-label":"More examples",onClick:()=>h(1),children:o.jsx(ol,{size:13,weight:"bold"})}),o.jsx("div",{className:"sc-shelf-row",ref:f,children:[0,1,2].map(p=>u.map(g=>o.jsx(VM,{entry:g,size:"grid",hideRecipe:!0,decorative:p!==1,active:n===g.id,onOpen:()=>r(g),productHref:a,presenterHref:i,sceneHref:l,...Cie(g,t)},`${p}-${g.id}`)))})]})]})}function Xd({text:e,onAll:t,actionLabel:n="Show all shots"}){return o.jsxs("div",{className:"sc-feed-empty",children:[o.jsx("p",{children:e}),t&&o.jsx("button",{type:"button",className:"sc-btn",onClick:t,children:n})]})}function Mie({count:e,sets:t,activeSet:n,onAdd:r,onRemove:a,onNew:i,onClear:l,onKeep:u,onArchiveBatch:f,allKept:h,archivedLens:p,pickedIds:g,onRestoreBatch:v,onDeleteBatch:w,loaded:y,onSelectAll:x}){const[k,S]=s.useState(!1);return o.jsxs("div",{className:"sc-picked","data-lens":p?"archived":void 0,role:"toolbar","aria-label":"Selection",children:[o.jsxs("span",{className:"sc-picked-meta",children:[o.jsxs("span",{className:"sc-picked-n",role:"status",children:[e,o.jsx("span",{className:"sc-vh",children:" selected"})]}),y>1&&o.jsx("button",{type:"button",className:"sc-picked-all",onClick:e<y?x:l,children:e<y?"Select all":"Deselect all"})]}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsx("span",{className:"sc-picked-tools",children:p?o.jsxs(o.Fragment,{children:[o.jsx(au,{label:"Restore",onClick:()=>v(g),children:o.jsx(M0,{size:17})}),o.jsx(au,{label:`Delete ${e} permanently`,tone:"danger",onClick:()=>S(!0),children:o.jsx(il,{size:17})})]}):o.jsxs(o.Fragment,{children:[o.jsx(au,{label:h?"Remove from keepers":"Keep",onClick:u,children:o.jsx(po,{size:17,weight:h?"fill":"regular"})}),o.jsxs(Ss,{children:[o.jsx(lr,{label:"Add to set",children:o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-picked-tool","aria-label":"Add to set",children:o.jsx(av,{size:17})})})}),o.jsxs(Cs,{children:[t.filter(E=>E.id!==(n==null?void 0:n.id)).map(E=>o.jsx(tr,{onSelect:()=>r(E),children:E.name},E.id)),t.some(E=>E.id!==(n==null?void 0:n.id))&&o.jsx(Bl,{}),o.jsx(tr,{onSelect:i,children:"New set…"})]})]}),n&&a&&o.jsx(au,{label:zR(e,n.name),onClick:a,children:o.jsx(PC,{size:17})}),o.jsx(au,{label:"Archive",tone:"danger",onClick:()=>f(g),children:o.jsx(Op,{size:17})})]})}),o.jsx("span",{className:"sc-picked-rule","aria-hidden":!0}),o.jsx("span",{className:"sc-picked-exit",children:o.jsx(au,{label:"Done",onClick:l,children:o.jsx(jn,{size:16,weight:"bold"})})}),p&&o.jsx(Wn,{label:`Delete ${e} permanently`,title:`Delete ${e} shot${e===1?"":"s"} permanently?`,body:"This cannot be undone.",busy:!1,open:k,onOpenChange:S,onConfirm:()=>w(g)})]})}function au({label:e,tone:t,onClick:n,children:r}){return o.jsx(lr,{label:e,children:o.jsx("button",{type:"button",className:"sc-picked-tool","data-tone":t,"aria-label":e,onClick:n,children:r})})}function Rie(e,t){return[e,t.lens??"all",t.set??"",t.ungrouped?"ungrouped":"",t.lineage??"",t.token??"",(t.q??"").trim(),t.sort??"newest",t.limit??""].join("|")}function Pie(e){switch(e){case"oldest":return(t,n)=>vu(n,t);case"cost":return(t,n)=>n.costUsd-t.costUsd||vu(t,n);case"keepers":return(t,n)=>Number(n.kept)-Number(t.kept)||vu(t,n);default:return vu}}function WR(e,t,n){return e.kind==="root"?!1:t.lineage?n.inLineage?n.inLineage(e):!1:t.set?n.inSet?n.inSet(e.id):!1:t.ungrouped?n.inAnySet?!n.inAnySet(e.id):!1:!0}function Lie(e,t){return t==="archived"?e.archived:t==="keepers"?!e.archived&&e.kept:!e.archived}function z5(e,t,n){var r;return(r=t.q)!=null&&r.trim()?null:WR(e,t,n)&&Lie(e,t.lens)}function B5(e){return!e||e.kind==="root"?{all:0,keepers:0,archived:0}:{all:e.archived?0:1,keepers:!e.archived&&e.kept?1:0,archived:e.archived?1:0}}function w8(e,t,n,r){if(!r)return e;const a=B5(t),i=B5(n),l={...e,all:e.all+i.all-a.all,keepers:e.keepers+i.keepers-a.keepers,archived:e.archived+i.archived-a.archived};return l.all===e.all&&l.keepers===e.keepers&&l.archived===e.archived?e:l}function W6(e,t){const n=e.findIndex(a=>a.id===t.id);if(n===-1||e[n]===t)return e;const r=[...e];return r[n]=t,r}function U5(e,t){const n=new Set(t);return e.some(r=>n.has(r.id))?e.filter(r=>!n.has(r.id)):e}function Tie(e,t,n,r){if(e.some(u=>u.id===t.id))return W6(e,t);const a=Pie(n);let i=0;for(;i<e.length&&a(e[i],t)<=0;)i++;if(i===e.length&&!r)return e;const l=[...e];return l.splice(i,0,t),l}function $ie(e,t){const n=new Set(e.map(a=>a.id)),r=t.filter(a=>!n.has(a.id));return r.length?[...e,...r]:e}function Die(e,t){const n=new Set(t.map(r=>r.id));return[...t,...e.filter(r=>!n.has(r.id))]}const y8=60;function Hie(e,t,n){const{shotsEpoch:r}=on(),a=`${Rie(e,t)}#${r}`,[i,l]=s.useState({brandId:e,key:"",items:[],next:null,counts:null,error:null}),[u,f]=s.useState(!1),h=s.useRef(i);h.current=i;const p=s.useRef(t);p.current=t;const g=s.useRef(n);g.current=n;const v=s.useRef(!1);s.useEffect(()=>{const N=new AbortController;return f(!0),Re.feed(e,{...p.current,limit:y8},N.signal).then(P=>{N.signal.aborted||l({brandId:e,key:a,items:P.items,next:P.next,counts:P.counts??null,error:null})}).catch(P=>{if(N.signal.aborted)return;const $=String((P==null?void 0:P.message)??P);l(M=>({...M,brandId:e,key:a,error:$}))}).finally(()=>{N.signal.aborted||f(!1)}),()=>N.abort()},[e,a]);const w=s.useCallback(()=>{const N=h.current;if(N.key!==a||!N.next||v.current)return;v.current=!0,f(!0);const P=N.next;Re.feed(e,{...p.current,limit:y8,cursor:P}).then($=>{l(M=>M.key!==a?M:{...M,items:$ie(M.items,$.items),next:$.next,counts:$.counts??M.counts})}).catch(()=>{}).finally(()=>{v.current=!1,f(!1)})},[e,a]),y=s.useCallback(async()=>{const N=await Re.feed(e,{...p.current,limit:y8});l(P=>P.key!==a?P:{...P,items:Die(P.items,N.items),next:P.items.length?P.next:N.next,counts:N.counts??P.counts,error:null})},[e,a]),x=s.useCallback(N=>{l(P=>{const $=P.items.find(H=>H.id===N.id);if(!$)return P;const M=p.current,R=z5(N,M,g.current)===!1?U5(P.items,[N.id]):W6(P.items,N),T=P.counts?w8(P.counts,$,N,!0):P.counts;return R===P.items&&T===P.counts?P:{...P,items:R,counts:T}})},[]),k=s.useCallback((N,P)=>{let $=!1;l(M=>{let C=M.items,R=M.counts;const T=p.current;for(const H of N){if(C.some(Z=>Z.id===H.id)){C=W6(C,H);continue}const D=z5(H,T,g.current);if(D===null){$=!0;continue}const K=WR(H,T,g.current);D&&(C=Tie(C,H,T.sort,M.next===null));const O=(P==null?void 0:P.get(H.id))??null;R&&(R=w8(R,O,H,K))}return C===M.items&&R===M.counts?M:{...M,items:C,counts:R}}),$&&y().catch(()=>{})},[y]),S=s.useCallback(N=>{l(P=>{const $=P.items.filter(C=>N.includes(C.id));if(!$.length)return P;let M=P.counts;if(M)for(const C of $)M=w8(M,C,null,!0);return{...P,items:U5(P.items,N),counts:M}})},[]),E=i.brandId===e?i.items:[],j=s.useMemo(()=>new Map(E.map(N=>[N.id,N])),[E]);return{items:E,byId:j,counts:i.brandId===e?i.counts:null,ready:i.key===a&&!i.error,loading:u,complete:i.key===a&&i.next===null,error:i.key===a?i.error:null,loadMore:w,patch:x,insert:k,drop:S,refresh:y}}function Oie(){const e=un(ct.hubShot),t=un(ct.setShot);return(e==null?void 0:e.params.shotId)??(t==null?void 0:t.params.shotId)??null}function W5(e,t){const n=e?t.get(e)??null:null,[r,a]=s.useState(null);return s.useEffect(()=>{if(!e||n)return;let i=!0;return Re.node(e).then(l=>i&&a({id:e,node:l})).catch(()=>i&&a({id:e,node:null})),()=>{i=!1}},[e,n]),e?n?{node:n,missing:!1}:(r==null?void 0:r.id)===e?{node:r.node,missing:r.node===null}:{node:null,missing:!1}:{node:null,missing:!1}}function KR({set:e}){const{engines:t,scenes:n,presenters:r,demoProducts:a,showcase:i,showcaseLoaded:l}=Rn(),{brand:u,workspace:f,root:h,recent:p,sets:g,membership:v,loaded:w,refresh:y,applySet:x,dropSet:k,insertSet:S,applyMembership:E,applyNodes:j,subscribeActivity:N,products:P}=on(),$=Rf(),M=Dn(),[C,R]=el(),T=Oie(),[H,D]=s.useState(null),[K,O]=s.useState(!1);s.useEffect(()=>{const ie=()=>O(!0);return window.addEventListener("scenri:shortcuts",ie),()=>window.removeEventListener("scenri:shortcuts",ie)},[]);const{open:Z,toggle:te,setOpen:B}=Xee(),F=wr("(min-width: 1280px)"),X=F&&Z,[z,I]=s.useState(null),[U,G]=s.useState(_M),[ne,q]=s.useState(null),[le,Se]=s.useState(null),Q=s.useRef(!1);s.useEffect(()=>{if(!Q.current||T)return;Q.current=!1;const ie=requestAnimationFrame(()=>{var De;return(De=Ke.current)==null?void 0:De.focus()});return()=>cancelAnimationFrame(ie)},[T,le]);const[xe,ee]=s.useState(null),[ae,re]=s.useState(new Set),[_,ue]=G1("tab","all"),[We,Xe]=G1("in",""),[ze,tt]=G1("branch",""),[ce,ve]=G1("lineage",""),[Pe,de]=fa(Dr.tileSize,hM),je=pM(Pe),{q:Ue,setQ:ye,clearSearch:Ee}=Pf([]),[be,Le]=fa(Dr.feedSort,"newest"),Qe=yW(be)?be:"newest",Ke=s.useRef(null),{push:nt}=or(),{poke:gt}=Za(),[Pt,Ut]=s.useState(null),Nt=(f==null?void 0:f.id)??"",cn=e?t0(u,e):mr(u),Fe=s.useCallback(ie=>{const De=C.toString();return`${cn}/shots/${ie}${De?`?${De}`:""}`},[cn,C]),pt=s.useCallback((ie,De=!1)=>M(Fe(ie),{replace:De}),[M,Fe]),it=s.useCallback(()=>{const ie=new URLSearchParams(C);ie.delete("panel");const De=ie.toString();M(`${cn}${De?`?${De}`:""}`,{replace:!0})},[cn,M,C]),St=bW(_)?_:"all",xt=!e&&We==="ungrouped";s.useEffect(()=>{_==="ungrouped"&&(ue(null),Xe("ungrouped"))},[_,ue,Xe]);const At=s.useMemo(()=>{const ie=new Map;for(const De of g)for(const Je of v[De.id]??[])ie.has(Je)||ie.set(Je,[]),ie.get(Je).push(De);return ie},[g,v]),Kt=s.useMemo(()=>({lens:St,set:e==null?void 0:e.id,ungrouped:xt||void 0,lineage:ce||void 0,q:Ue.trim()||void 0,sort:Qe}),[St,e==null?void 0:e.id,xt,ce,Ue,Qe]),et=s.useRef(v);et.current=v;const mt=s.useRef(At);mt.current=At;const ot=s.useRef(new Set),kn=s.useMemo(()=>({inSet:ie=>e?(et.current[e.id]??[]).includes(ie):!1,inAnySet:ie=>mt.current.has(ie),inLineage:ie=>ie.id===ce||ie.parentId!==null&&ot.current.has(ie.parentId)}),[e==null?void 0:e.id,ce]),ut=Hie(u.id,Kt,kn),{items:Gt,byId:Ft,counts:en}=ut,Jt=s.useRef(ut);Jt.current=ut,ot.current=s.useMemo(()=>new Set(Gt.map(ie=>ie.id)),[Gt]);const se=s.useRef(new Map);s.useEffect(()=>{for(const ie of Gt)se.current.set(ie.id,ie)},[Gt]);const oe=s.useRef(null),[we,ge]=s.useState("");s.useEffect(()=>N(ie=>{const{messages:De,next:Je}=qoe(oe.current??new Map,ie),Vt=oe.current===null;oe.current=Je,!Vt&&De.length&&ge(De.join(" "));const Yt=Jt.current;let Bn=!1;const Nn=[],xn=new Map;for(const Sn of ie){if(Yt.byId.has(Sn.id))Yt.patch(Sn);else if(se.current.has(Sn.id)){const hs=se.current.get(Sn.id);hs&&xn.set(Sn.id,hs),Nn.push(Sn)}else Sn.kind!=="root"&&(Bn=!0);se.current.set(Sn.id,Sn)}Nn.length&&Yt.insert(Nn,xn),Bn&&Yt.ready&&Yt.refresh().catch(()=>{})}),[N]);const J=w&&ut.ready,Oe=W5(ce||null,Ft);s.useEffect(()=>{!ce||!Oe.missing||(ve(null),nt({kind:"info",title:"That shot is no longer available",detail:"Showing everything instead."}))},[ce,Oe.missing,ve,nt]);const Be=s.useMemo(()=>{var Vt,Yt;const ie=P.length?P:((Vt=u.json)==null?void 0:Vt.products)??[],De=((Yt=u.json)==null?void 0:Yt.characters)??[],Je=$.scenes;return{product:Bn=>{const Nn=ie.find(xn=>xn.id===Bn)??a.find(xn=>xn.id===Bn);return Nn?go(Nn,"chip"):null},person:Bn=>{var Nn,xn;return((Nn=De.find(Sn=>Sn.id===Bn))==null?void 0:Nn.name)??((xn=r.find(Sn=>Sn.id===Bn))==null?void 0:xn.name)??null},scene:Bn=>{const Nn=Je.find(xn=>xn.id===Bn);return Nn?Qi(Nn,"chip"):null}}},[P,a,u,r,$.scenes]),Ve=s.useMemo(()=>{const ie=H?Ft.get(H):void 0;return ie||(Gt.find(De=>De.status!=="error")??Gt[0]??null)},[Ft,Gt,H]),Ge=W5(ze||null,Ft),me=s.useMemo(()=>{const ie=Ge.node;return!ie||ie.kind==="root"?null:ie.status==="running"||ie.status==="done"&&ie.images.length>0?ie:null},[Ge.node]),_e=(me==null?void 0:me.images[0])??null,W=s.useCallback(()=>tt(null),[tt]),pe=s.useRef(null),Ie=s.useCallback((...ie)=>{if(pe.current){for(const Je of ie)pe.current.add(Je);return}const De=new Set(ie);pe.current=De,queueMicrotask(()=>{pe.current=null,R(Je=>{const Vt=new URLSearchParams(Je);for(const Yt of De)Vt.delete(Yt);return Vt},{replace:!0})})},[R]),Te=s.useCallback(()=>Ie("scene","setup","presenter","product"),[Ie]);s.useEffect(()=>{!ze||!J||(Ge.node&&!me?(W(),nt({kind:"info",title:"That shot is no longer available to refine",detail:"Making a new shot."})):Ge.missing&&(W(),nt({kind:"info",title:"That shot is no longer available to refine",detail:"Making a new shot."})))},[ze,Ge.node,Ge.missing,me,J,W,nt]);const bt=s.useCallback(ie=>{var De;tt(ie),(De=Ke.current)==null||De.focus()},[tt]),vt=ie=>D(ie),Ct=ie=>T||/\/shots\//.test(window.location.pathname)?pt(ie,!0):vt(ie),st=s.useCallback(ie=>{for(const De of ie)se.current.set(De.id,De);Jt.current.insert(ie),j(ie),gt()},[j,gt]),$t=s.useCallback(async()=>{try{await y(),await Jt.current.refresh(),I(null)}catch(ie){I(String(ie.message??ie))}},[y]),An=s.useCallback(ie=>j([ie]),[j]),{archive:Y,archiveBatch:he,unarchive:Me,unarchiveBatch:Ye}=kie(An),dt=s.useCallback(ie=>Jt.current.drop(ie),[]),{remove:wt,removeBatch:Zt}=Sie(dt);s.useEffect(()=>{T&&D(T)},[T]);const Ht=s.useRef(new Set),pn=async ie=>{var De,Je;if(ie.status==="running"||Ht.current.has(ie.id))return ie.id;if(ie.status==="error"||ie.status==="cancelled"){Ht.current.add(ie.id);try{const Vt=await Re.retryNode(ie.id);return j([Vt]),gt(),Vt.id}catch(Vt){return nt(nn(Vt,"Could not run this again")),null}finally{Ht.current.delete(ie.id)}}try{const Vt=await Re.node(ie.id),Yt=await Re.addNode({projectId:Nt,parentId:ie.parentId,kind:ie.kind==="edit"?"edit":"generation",prompt:Vt.prompt,engineId:ie.engineId,count:1,brief:ie.brief,...ie.kind==="edit"&&((De=ie.brief)!=null&&De.sourceImage)?{sourceImage:ie.brief.sourceImage}:{}});return st((Je=Yt.siblings)!=null&&Je.length?Yt.siblings:[Yt]),(Yt==null?void 0:Yt.id)??null}catch(Vt){return nt(nn(Vt,"Could not run this again")),null}},Wt=async ie=>{try{await Re.cancelNode(ie.id),j([{...ie,status:"cancelled"}]),gt()}catch(De){nt(nn(De,"Could not cancel this shot"))}},wn=s.useCallback(ie=>{var De,Je,Vt;ie!=null&&ie.scene&&((De=Ke.current)==null||De.applyScene(ie.scene)),ie!=null&&ie.scenesPanel&&((Je=Ke.current)==null||Je.openAttach("Scenes")),(Vt=Ke.current)==null||Vt.focus()},[]);s.useEffect(()=>{var De;if(C.get("compose")===null)return;const ie=C.get("attach")==="all";wn(),ie&&((De=Ke.current)==null||De.showAttach()),Ie("compose",...ie?["attach"]:[])},[C,wn,Ie]);const sn=C.get("showcase"),In=s.useRef(null);s.useEffect(()=>{if(!sn||!l||In.current===sn)return;In.current=sn;const ie=i.find(De=>De.id===sn);ie?(Se(T6(ie)),nt({kind:"info",title:`Starting from "${ie.title}"`})):nt({kind:"info",title:"That example is no longer available",detail:"Starting from scratch instead."}),R(De=>{const Je=new URLSearchParams(De);return Je.delete("showcase"),Je},{replace:!0})},[sn,l,i,R,nt]);const Dt=async(ie,De=!ie.kept)=>{j([{...ie,kept:De}]);try{j([await Re.keep(ie.id,De)])}catch(Je){j([ie]),nt(nn(Je,"Could not update keeper status"))}},On=s.useMemo(()=>[...ae].map(ie=>Ft.get(ie)).filter(ie=>!!ie),[Ft,ae]),Et=async()=>{const ie=!(On.length>0&&On.every(Je=>Je.kept)),De=On.filter(Je=>Je.kept!==ie);j(De.map(Je=>({...Je,kept:ie})));try{j(await Promise.all(De.map(Je=>Re.keep(Je.id,ie))))}catch(Je){j(De),nt(nn(Je,"Could not update keeper status"))}},Hn=ie=>{const De=ie.map(Je=>Ft.get(Je)).filter(Je=>!!Je&&!Je.archived);De.length&&j(De.map(Je=>({...Je,archived:!0}))),re(new Set),he(ie).then(Je=>{Je||j(De)})},Ot=ie=>{const De=ie.map(Je=>Ft.get(Je)).filter(Je=>!!Je&&Je.archived);De.length&&j(De.map(Je=>({...Je,archived:!1}))),re(new Set),Ye(ie).then(Je=>{Je||j(De)})},tn=s.useCallback((ie,De)=>{et.current={...et.current,[ie]:De},E(ie,De)},[E]),Vn=async ie=>{try{const De=await Re.addToSet(ie.id,[...ae]);tn(ie.id,De.nodeIds),re(new Set),(e||xt)&&Jt.current.refresh()}catch(De){nt(nn(De,"Could not add to the set"))}},ur=async(ie,De)=>{const Je=et.current[ie.id]??[],Vt=Je.filter(Yt=>!De.includes(Yt));tn(ie.id,Vt),re(Yt=>{if(!De.some(Nn=>Yt.has(Nn)))return Yt;const Bn=new Set(Yt);for(const Nn of De)Bn.delete(Nn);return Bn}),(e==null?void 0:e.id)===ie.id&&Jt.current.drop(De);try{const Yt=await Re.removeFromSet(ie.id,De);tn(ie.id,Yt.nodeIds),xt&&Jt.current.refresh()}catch(Yt){tn(ie.id,Je),((e==null?void 0:e.id)===ie.id||xt)&&Jt.current.refresh(),nt(nn(Yt,"Could not remove from the set"))}},Zr=ie=>ur(ie,[...ae]),zn=(ie,De)=>ur(De,[ie.id]),yn=s.useRef([]),[Va,ko]=s.useState(!1);s.useEffect(()=>{Va&&ko(!1)},[Va]);const So=async(ie,De)=>{const Je=De.trim();if(Je)try{const Vt=await Re.createSet(u.id,Je);if(S(Vt),ie.length>0){const Yt=await Re.addToSet(Vt.id,ie);tn(Vt.id,Yt.nodeIds)}re(new Set),M(t0(u,Vt))}catch(Vt){nt(nn(Vt,"Could not create the set"))}},ul=()=>{const ie=yn.current;return yn.current=[],ie},wa=async ie=>{if(!e)return;const De=ie.trim();if(!(!De||De===e.name))try{const Je=await Re.renameSet(e.id,De);x(Je),M(t0(u,Je),{replace:!0}),y()}catch(Je){nt(nn(Je,"Could not rename the set"))}},Eo=async()=>{if(e)try{await Re.deleteSet(e.id),k(e.id),M(mr(u),{replace:!0}),y()}catch(ie){nt(nn(ie,"Could not delete the set"))}},ya=async ie=>{var Sn;const De=((Sn=/\/shots\/([^/?#]+)/.exec(window.location.pathname))==null?void 0:Sn[1])??null,Je=De?Ft.get(De)??null:Ve;if(!Je)return;if(ie==="left"||ie==="right"){const{prev:hs,next:cd}=o6(Gt,Je.id),ui=ie==="left"?hs:cd;ui&&Ct(ui.id);return}const Vt=await Re.lineage(Je.id).catch(()=>null);if(!Vt)return;const Yt=Vt.history??[...Vt.ancestors,Je,...Vt.children.slice(0,1)],{prev:Bn,next:Nn}=o6(Yt.filter(hs=>hs.id===Je.id||hs.images[0]),Je.id),xn=ie==="up"?Bn:Nn;xn&&Ct(xn.id)};s.useEffect(()=>{const ie=De=>{var Nn,xn;if(De.defaultPrevented)return;const Je=document.activeElement,Vt=((Je==null?void 0:Je.tagName)??"").toUpperCase(),Yt=Vt==="INPUT"||Vt==="TEXTAREA"||Vt==="SELECT"||!!(Je!=null&&Je.closest('[contenteditable="true"]'))||!!(Je!=null&&Je.closest('[role="separator"]')),Bn=!!(Je!=null&&Je.closest('button, a[href], [role="button"], [role="tab"], [role="menuitem"]'));if(De.key==="Enter"&&(De.metaKey||De.ctrlKey)){(Nn=Ke.current)==null||Nn.submit(),De.preventDefault();return}if(!Yt){if(De.key==="?"){O(!0),De.preventDefault();return}if(De.key==="/"&&!T){(xn=Ke.current)==null||xn.focus(),De.preventDefault();return}if(De.key==="Escape"&&K){O(!1),De.preventDefault();return}if(De.key==="Escape"&&T){it(),De.preventDefault();return}if(De.key==="Escape"&&ae.size>0){re(new Set),De.preventDefault();return}if(De.key==="Escape"&&ze){W(),De.preventDefault();return}if(Ve){if(De.key==="b"&&Ve.kind!=="root"&&Ve.status==="done"&&Ve.images.length>0){bt(Ve.id),De.preventDefault();return}if(De.key==="k"&&Ve.kind!=="root"&&Ve.status==="done"){Dt(Ve),De.preventDefault();return}De.key==="ArrowLeft"?(ya("left"),De.preventDefault()):De.key==="ArrowRight"?(ya("right"),De.preventDefault()):De.key==="ArrowUp"?(ya("up"),De.preventDefault()):De.key==="ArrowDown"?(ya("down"),De.preventDefault()):De.key==="Enter"&&!T&&Ve.kind!=="root"&&!Bn?pt(Ve.id):De.key==="."&&!T&&F&&te()}}};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ve,T,K,ae.size,ze,bt,tt,h,F]);const ba=ie=>re(De=>{const Je=new Set(De);return Je.delete(ie)||Je.add(ie),Je}),Vr=J&&en!==null&&en.total===0,ts=X||Vr&&F,Gs=Vr?o.jsx(Nie,{entries:i,catalogs:{demoProducts:a,presenters:r,scenes:n},stagedId:xe,productHref:ie=>la(u,ie),presenterHref:ie=>ha(u,ie),sceneHref:ie=>_r(u,ie),onUse:ie=>{ee(ie.id),Se(T6(ie))}}):Ue.trim()?o.jsx(Xd,{text:`No shots match “${Ue.trim()}”.`,onAll:Ee,actionLabel:"Clear search"}):St==="keepers"?o.jsx(Xd,{text:"No keepers yet. Star a shot and it lands here.",onAll:()=>ue(null)}):St==="archived"?o.jsx(Xd,{text:"Nothing archived.",onAll:()=>ue(null)}):e?o.jsx(Xd,{text:"Nothing in this set yet. Pick shots on All, then add them here."}):xt?o.jsx(Xd,{text:"Every shot is already in a set.",onAll:()=>Xe(null)}):null,za=s.useRef(0);!Ue.trim()&&en&&(za.current=en[St]);const[Pr,Lr]=fa(Dr.feedCounts,null);s.useEffect(()=>{if(!en)return;const ie={brandId:u.id,all:en.all,keepers:en.keepers,archived:en.archived};Lr(De=>De&&De.brandId===ie.brandId&&De.all===ie.all&&De.keepers===ie.keepers&&De.archived===ie.archived?De:ie)},[u.id,en,Lr]);const Ba=s.useMemo(()=>en?{all:en.all,keepers:en.keepers,archived:en.archived}:(Pr==null?void 0:Pr.brandId)===u.id?{all:Pr.all,keepers:Pr.keepers,archived:Pr.archived}:null,[en,Pr,u.id]),ci={byId:Ft,items:Gt,loadMore:ut.loadMore,complete:ut.complete,rootId:h,recent:p,loaded:J,setsFor:ie=>At.get(ie)??[],brand:u,engines:t,projectId:Nt,close:it,select:Ct,retry:ie=>{pn(ie).then(De=>{De&&Ct(De)})},cancel:ie=>void Wt(ie),keep:ie=>void Dt(ie),reload:$t,remix:ie=>{var Bn;const De=(Bn=ie.brief)==null?void 0:Bn.tokens,Je=ie.prompt??ie.promptHead,Vt=De!=null&&De.length||!Je?ie.brief:{...ie.brief,tokens:[{t:"text",v:Je}]},Yt=Vt!=null&&Vt.tokens?{...Vt,tokens:$G(u,Vt.tokens)}:Vt;Se({...Yt,_at:Date.now()}),Yt&&FM(u.id,{tokens:Tv(Yt),tplFields:Yt.templateFields??{}}),it(),nt({kind:"info",title:"Starting from this shot",detail:"Its prompt, chips and settings are in the composer. Change anything, then Generate."}),Q.current=!0},branch:ie=>{bt(ie.id),it()},archive:ie=>Y(ie).then(De=>{De&&it()}),unarchive:ie=>Me(ie).then(()=>{}),delete:ie=>void wt(ie).then(()=>it()),landed:st,refined:(ie,De)=>{De==="edit"&&tt(ie)},subscribeActivity:N,tokenNames:Be};return o.jsxs("div",{className:"sc-work","data-assets":ts,children:[o.jsxs("main",{className:"sc-canvas",id:"main","data-page-scroll":"","data-firstrun":Vr||void 0,onClick:ie=>{if(ae.size===0&&!H)return;const De=ie.target;De.closest(".sc-cell")||De.closest("button, a, input, select, textarea, label, [role], [contenteditable]")||(re(new Set),D(null))},children:[o.jsx("span",{className:"sc-vh",role:"status","aria-live":"polite",children:we}),(z||ut.error)&&o.jsx("div",{className:"sc-canvas-alert",children:o.jsx(uv,{failure:kf(z??ut.error??"")})}),(!Vr||e)&&o.jsx(xie,{sets:g,active:e,ungrouped:xt,ungroupedCount:(en==null?void 0:en.ungrouped)??0,onPlaceAll:()=>e?M(mr(u)):Xe(null),onPlaceUngrouped:()=>e?M(`${mr(u)}?in=ungrouped`):Xe("ungrouped"),onOpenSet:ie=>M(t0(u,ie)),onNewSet:ie=>void So(ul(),ie),onResetNewSet:()=>{yn.current=[]},onRenameSet:ie=>void wa(ie),onDeleteSet:()=>void Eo(),askCreate:Va,lens:St,lensCounts:Ba,onLens:ie=>ue(ie==="all"?null:ie),q:Ue,onQ:ye,searchTotal:Ue.trim()?za.current:(en==null?void 0:en[St])??0,sort:Qe,onSort:Le,tile:je,onTile:de,assets:X,onAssets:te,showAssets:F}),ce&&Oe.node&&o.jsxs("div",{className:"sc-lineage-bar",children:[o.jsx("button",{type:"button",className:"sc-crumb-back",onClick:()=>ve(null),children:"All shots"}),o.jsx("span",{className:"sc-crumb-sep",children:"›"}),o.jsx("b",{dir:"auto",children:Sr(Oe.node)}),o.jsx("span",{className:"sc-crumb-sep",children:"›"}),o.jsx("span",{className:"sc-crumb-here",children:"versions"})]}),o.jsx(gie,{nodes:Gt,selectedId:H,onOpen:pt,shotHref:Fe,onRetry:ie=>void pn(ie),onCancel:ie=>void Wt(ie),onToggleKeep:ie=>void Dt(ie),onArchive:ie=>ie.archived?Me(ie):Y(ie),onDeletePermanently:wt,engineName:ie=>{var De;return(De=t.find(Je=>Je.id===ie))==null?void 0:De.displayName},picked:ae,onPick:ba,sending:Pt,onBranch:bt,branchingFrom:(me==null?void 0:me.id)??null,onVersions:ve,tile:je,empty:J?Gs:null,pending:!J,onNearEnd:ut.complete?void 0:ut.loadMore,inSet:e,setsFor:ie=>At.get(ie)??[],onRemoveFromSet:(ie,De)=>void zn(ie,De),onKeepPicked:()=>void Et(),onArchivePicked:()=>Hn([...ae]),onRestorePicked:()=>Ot([...ae]),onDeletePicked:()=>void Zt([...ae]).then(()=>re(new Set)),onRemovePickedFromSet:ie=>void Zr(ie)})]}),ts&&o.jsx("div",{className:"sc-assets-backdrop",onClick:()=>B(!1),"aria-hidden":!0}),o.jsx(Qoe,{open:K,onOpenChange:O}),F&&o.jsx(bie,{brand:u,shots:p,shotsTotal:(Ba==null?void 0:Ba.all)??0,attached:U,full:ne,onToken:ie=>{var De;return(De=Ke.current)==null?void 0:De.insertToken(ie)},offToken:ie=>{var De;return(De=Ke.current)==null?void 0:De.removeToken(ie)},onTemplate:ie=>{var De;return(De=Ke.current)==null?void 0:De.applyScene(ie)},offTemplate:()=>{var ie;return(ie=Ke.current)==null?void 0:ie.removeTemplate()},onClose:()=>B(!1)}),o.jsxs(ZM,{full:!ts,children:[o.jsx(nw,{}),ae.size>0&&o.jsx(Mie,{count:ae.size,sets:g,activeSet:e,onAdd:ie=>void Vn(ie),onRemove:e?()=>void Zr(e):void 0,onNew:()=>{yn.current=[...ae],ko(!0)},onClear:()=>re(new Set),onKeep:()=>void Et(),onArchiveBatch:ie=>Hn(ie),allKept:On.length>0&&On.every(ie=>ie.kept),archivedLens:St==="archived",pickedIds:[...ae],onRestoreBatch:ie=>Ot(ie),onDeleteBatch:ie=>void Zt(ie).then(()=>re(new Set)),loaded:Gt.length,onSelectAll:()=>re(new Set(Gt.map(ie=>ie.id)))}),o.jsx(ew,{ref:Ke,projectId:Nt||null,brand:u,engines:t,parentId:h,initialBrief:le,suppressDraftRestore:sn!==null,startScene:C.get("scene")??void 0,startSetup:C.get("setup")??void 0,startPresenter:C.get("presenter")??void 0,startProduct:C.get("product")??void 0,onSeedsSpent:Te,openAttachTab:C.get("attach")==="scenes"?"Scenes":C.get("attach")==="products"?"Products":void 0,target:me,onClearTarget:W,onRestoreBranchId:tt,guided:!0,setSlug:(e==null?void 0:e.slug)??null,onSending:Ut,onAttached:G,onCeiling:q,sourceImage:_e??void 0,onQueued:(ie,De,Je,Vt)=>{Se(null),R(xn=>{const Sn=new URLSearchParams(xn);return Sn.delete("scene"),Sn.delete("attach"),Sn.delete("presenter"),Sn.delete("product"),Sn},{replace:!0});const Yt=()=>Ut(null),Bn=()=>{De!=="edit"||!ie||R(xn=>{const Sn=new URLSearchParams(xn);return Sn.set("branch",ie),Sn},{replace:!0})},Nn=()=>{st(Vt??[]),Bn(),Yt()};e&&ie?Re.addToSet(e.id,Je!=null&&Je.length?Je:[ie]).then(xn=>tn(e.id,xn.nodeIds)).catch(xn=>nt(nn(xn,"Could not add to the set"))).finally(Nn):Nn()}})]}),o.jsx(uc,{context:ci})]})}function Iie(e){var t;return Bu((t=e.brief)==null?void 0:t.format)}function Fie(e){var n,r,a;const t=(a=(r=(n=e.brief)==null?void 0:n.rendered)==null?void 0:r.sizes)==null?void 0:a[0];return t&&t[0]>0&&t[1]>0?t:null}const _ie=e=>({"--sc-pic-ar":e[0]/e[1],"--sc-pic-w":`${e[0]}px`});function Zie({node:e,onRetry:t,onCancel:n,engineName:r,menu:a}){const[i,l]=s.useState(null),[,u]=s.useState(0);if(s.useEffect(()=>{if(e.status!=="running")return;const g=setInterval(()=>u(v=>v+1),1e3);return()=>clearInterval(g)},[e.status]),e.kind==="root")return o.jsx(d0,{className:"sc-frame",p:"8",children:o.jsxs(js,{direction:"column",align:"center",gap:"2",py:"6",children:[o.jsx(Ql,{className:"sc-display",size:"7",align:"center",children:"Blank canvas, full brand."}),o.jsx(Ql,{color:"gray",size:"2",align:"center",children:"Pick a Template below (engineered briefs, your product attached) or describe a visual."})]})});if(e.status==="running")return o.jsxs("div",{className:"sc-stage-wait",style:{"--sc-wait-ar":Iie(e)},children:[o.jsx("span",{className:"sc-shimmer"}),o.jsxs("div",{className:"sc-stage-wait-say",children:[o.jsx("span",{className:"sc-stage-wait-t",role:"status","aria-label":`${gv(Oi(e))}, ${nc(Oi(e))} seconds`,children:rc(Oi(e))}),n&&o.jsx("button",{type:"button",className:"sc-btn sc-btn-ghost","data-urgent":nc(Oi(e))>=60||void 0,onClick:n,children:"Cancel"})]})]});if(e.status==="cancelled"||e.status==="error"){const v=e.status==="cancelled"?bA():kf(e.error,r);return o.jsx(Zj,{failure:v,density:"stage",onRetry:t})}const f=e.status==="done"?e.images[0]:void 0,h=f?Fie(e)??(i==null?void 0:i.size)??null:null,p=f?o.jsx(d0,{className:h?"sc-frame sc-stage-pic":"sc-frame sc-stage-free",style:h?_ie(h):void 0,children:o.jsx(Vie,{hash:f,alt:e.promptHead,onPainted:(g,v,w)=>l({hash:g,size:[v,w]})})}):o.jsx(js,{justify:"center",children:o.jsx(d0,{className:"sc-frame",style:{display:"inline-block",maxWidth:"100%"}})});return a?o.jsxs(ff,{children:[o.jsx(hf,{children:p}),a]}):p}function Vie({hash:e,alt:t,onPainted:n}){const[r,a]=s.useState(null),i=s.useRef(null),l=r===e,u=h=>{!(h!=null&&h.complete)||!h.naturalWidth||h.src!==new URL(Mr(e),location.href).href||i.current!==e&&(i.current=e,a(e),n==null||n(e,h.naturalWidth,h.naturalHeight))},f=i.current&&i.current!==e?Mr(i.current):dn(e,"tile");return o.jsxs(d0,{position:"relative",style:{lineHeight:0},children:[!l&&o.jsx("img",{className:"sc-stage-under",src:f,alt:"","aria-hidden":!0,decoding:"async"}),o.jsx("img",{ref:u,src:Mr(e),alt:t,className:"sc-stage-img","data-ready":l||void 0,onLoad:h=>u(h.currentTarget)})]})}const zie=e=>((e==null?void 0:e.tokens)??[]).filter(t=>t&&typeof t.t=="string");function GR(e,t){return zie(e.brief).map(r=>{var a;switch(r.t){case"text":return typeof r.v=="string"?r.v:"";case"product":return t.product(String(r.id))??"a product";case"character":return t.person(String(r.id))??"a presenter";case"template":return t.scene(String(r.id))??"a scene";case"color":return String(r.name??r.hex??"");case"ref":return"the attached reference";case"mark":return((a=t.mark)==null?void 0:a.call(t,String(r.imageHash)))??"the brand mark";default:return""}}).join(" ").replace(/\s+/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()||e.prompt||e.promptHead||""}const Bie=e=>e===0?"Original":`Refinement ${e}`,Uie=e=>e===0?"the original":`Refinement ${e}`,Wie=(e,t)=>e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);function Kie(e,t,n){const r=new Set(e.map(g=>g.id)),a=n.filter(g=>!r.has(g.id)&&g.parentId!==null&&r.has(g.parentId)),i=a.length?[...e,...a].sort(Wie):e,u=(i.some(g=>g.id===t.id)?i:[...i,t]).map(g=>g.id===t.id?t:g).filter(g=>g.id===t.id||g.images[0]);let f=0;const h=u.map(g=>{const v=g.kind==="edit"?++f:0;return{node:g,index:v,label:Bie(v),from:null,state:g.images[0]?"ready":g.status==="running"?"pending":"failed"}}),p=new Map(h.map((g,v)=>[g.node.id,v]));return h.map((g,v)=>{if(v===0||!g.node.parentId||g.node.parentId===h[v-1].node.id)return g;const w=p.get(g.node.parentId);return w===void 0?g:{...g,from:Uie(h[w].index)}})}function YR(e,t){var a;const n=e.find(i=>i.node.id===t);if(!n)return"";const r=((a=e[e.length-1])==null?void 0:a.index)??0;return n.index===0?"Original":`Refinement ${n.index} of ${r}`}const rh=28;function Gie({trail:e,activeId:t,names:n,onSelect:r}){var w;const a=s.useRef(null),i=s.useMemo(()=>e.map(y=>GR(y.node,n)),[e,n]),l=od(),u=(y,x,k)=>l.open({key:y.node.id,src:dn(y.node.images[0],"tile"),label:y.label,said:i[x],from:y.from,el:k,id:y.node.id});s.useEffect(()=>{var y,x;(x=(y=a.current)==null?void 0:y.querySelector('[aria-pressed="true"]'))==null||x.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[t]);const[f,h]=s.useState(null);s.useEffect(()=>{const y=a.current;if(!y)return;const x=()=>{const E=y.scrollWidth-y.clientWidth;if(E<=1)return h(null);const j=y.scrollLeft;h(j<=1?"end":j>=E-1?"start":"both")},k=()=>{const E=y.querySelector('[aria-pressed="true"]');if(!E)return;const j=E.getBoundingClientRect(),N=y.getBoundingClientRect();j.left<N.left+rh?y.scrollLeft-=N.left+rh-j.left:j.right>N.right-rh&&(y.scrollLeft+=j.right-(N.right-rh))};x(),y.addEventListener("scroll",x,{passive:!0});const S=new ResizeObserver(()=>{k(),x()});return S.observe(y),()=>{y.removeEventListener("scroll",x),S.disconnect()}},[e.length]),s.useEffect(()=>{const y=a.current;if(!y)return;const x=k=>{y.scrollWidth<=y.clientWidth||Math.abs(k.deltaY)<=Math.abs(k.deltaX)||(k.preventDefault(),y.scrollLeft+=k.deltaY)};return y.addEventListener("wheel",x,{passive:!1}),()=>y.removeEventListener("wheel",x)},[]);const p=y=>{var E,j;const x=[...((E=a.current)==null?void 0:E.querySelectorAll(".sc-trail-tile:not([aria-disabled])"))??[]],k=x.indexOf(document.activeElement);let S=-1;if(y.key==="ArrowRight")S=Math.min(x.length-1,k+1);else if(y.key==="ArrowLeft")S=Math.max(0,k-1);else if(y.key==="Home")S=0;else if(y.key==="End")S=x.length-1;else return;y.preventDefault(),y.stopPropagation(),(j=x[S])==null||j.focus()},g=e.some(y=>y.node.id===t)?t:(w=e[0])==null?void 0:w.node.id,v=YR(e,t);return o.jsxs("div",{className:"sc-trail",children:[v&&o.jsx("span",{className:"sc-trail-say",children:v}),o.jsx("nav",{ref:a,className:"sc-thumbs","aria-label":"History of this shot","data-more":f??void 0,onKeyDown:p,children:e.map((y,x)=>{const k=y.node,S=k.id===t,E=y.state==="pending";return o.jsx("button",{type:"button",className:"sc-thumb-btn sc-trail-tile","data-original":y.index===0&&e.length>1?"":void 0,"aria-label":i[x]?`${y.label}: ${i[x]}`:y.label,"aria-pressed":S,"aria-disabled":E||void 0,tabIndex:k.id===g?0:-1,onClick:()=>{E||(l.closeNow(),r(k.id))},onPointerEnter:j=>j.pointerType==="mouse"&&y.state==="ready"&&u(y,x,j.currentTarget),onPointerLeave:j=>j.pointerType==="mouse"&&l.close(),onFocus:j=>Xp(j.currentTarget)&&y.state==="ready"&&u(y,x,j.currentTarget),children:y.state==="ready"?o.jsx("img",{src:dn(k.images[0],"micro"),alt:"",className:"sc-thumb",loading:"lazy",decoding:"async","data-active":S,width:52,height:52}):E?o.jsx("span",{className:"sc-thumb sc-thumb-wait","data-active":S,children:o.jsx("span",{className:"sc-shimmer"})}):o.jsx("span",{className:"sc-thumb sc-thumb-failed","data-active":S,children:o.jsx(kc,{size:14})})},k.id)})}),l.shown&&o.jsx(ad,{anchor:l.shown.el,kind:"shot",src:l.shown.src,label:l.shown.label,noun:l.shown.said,note:l.shown.from?`From ${l.shown.from}`:null,onOpen:()=>{var x;const y=(x=l.shown)==null?void 0:x.id;l.closeNow(),y&&r(y)},onHoverIn:l.keep,onHoverOut:l.close,onClose:l.closeNow},l.shown.key)]})}const Yie=200,K5=32;function qie({shots:e,activeId:t,onSelect:n,onEndReached:r,complete:a}){var y;const i=s.useRef(null),l=od(),u=(x,k)=>l.open({key:x.id,src:dn(x.images[0],"tile"),label:Sr(x),el:k,id:x.id}),f=s.useRef(!1);s.useLayoutEffect(()=>{var k;const x=(k=i.current)==null?void 0:k.querySelector('[aria-pressed="true"]');x&&(x.scrollIntoView({block:"center",behavior:f.current?"smooth":"auto"}),f.current=!0)},[t]);const h=s.useRef(null),p=()=>{const x=i.current,k=h.current;if(!x||!k)return;const S=x.scrollHeight-x.clientHeight,E=x.scrollTop;k.style.setProperty("--sc-shotrail-start",S>1?Math.min(1,E/K5).toFixed(3):"0"),k.style.setProperty("--sc-shotrail-end",S>1?Math.min(1,(S-E)/K5).toFixed(3):"0")};s.useLayoutEffect(()=>{const x=i.current;if(!x)return;p();const k=new ResizeObserver(p);return k.observe(x),()=>k.disconnect()},[e.length]);const g=()=>{p();const x=i.current;!x||a||x.scrollTop+x.clientHeight>=x.scrollHeight-Yie&&r()},v=x=>{var j,N;const k=[...((j=i.current)==null?void 0:j.querySelectorAll(".sc-shotrail-tile:not([aria-disabled])"))??[]],S=k.indexOf(document.activeElement);let E=-1;if(x.key==="ArrowDown")E=Math.min(k.length-1,S+1);else if(x.key==="ArrowUp")E=Math.max(0,S-1);else if(x.key==="Home")E=0;else if(x.key==="End")E=k.length-1;else return;x.preventDefault(),x.stopPropagation(),(N=k[E])==null||N.focus()},w=e.some(x=>x.id===t)?t:(y=e[0])==null?void 0:y.id;return o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:h,className:"sc-shotrail-shell",children:o.jsx("nav",{ref:i,className:"sc-shotrail","aria-label":"Shots in this view",onScroll:g,onKeyDown:v,children:e.map(x=>{const k=x.id===t,S=x.status==="running",E=x.status==="done"&&!!x.images[0];return o.jsx("button",{type:"button",className:"sc-thumb-btn sc-shotrail-tile","aria-label":S?`${Sr(x)}, still rendering`:Sr(x),"aria-pressed":k,"aria-disabled":S||void 0,tabIndex:x.id===w?0:-1,onClick:()=>{S||(l.closeNow(),n(x.id))},onPointerEnter:j=>j.pointerType==="mouse"&&E&&u(x,j.currentTarget),onPointerLeave:j=>j.pointerType==="mouse"&&l.close(),onFocus:j=>Xp(j.currentTarget)&&E&&u(x,j.currentTarget),children:E?o.jsx("img",{src:dn(x.images[0],"micro"),alt:"",className:"sc-thumb",loading:"lazy",decoding:"async","data-active":k,width:52,height:52}):S?o.jsx("span",{className:"sc-thumb sc-thumb-wait","data-active":k,children:o.jsx("span",{className:"sc-shimmer"})}):o.jsx("span",{className:"sc-thumb sc-thumb-failed","data-active":k,children:o.jsx(kc,{size:14})})},x.id)})})}),l.shown&&o.jsx(ad,{anchor:l.shown.el,kind:"shot",noun:"Shot",side:"beside",src:l.shown.src,label:l.shown.label,onOpen:()=>{var k;const x=(k=l.shown)==null?void 0:k.id;l.closeNow(),x&&n(x)},onHoverIn:l.keep,onHoverOut:l.close,onClose:l.closeNow},l.shown.key)]})}const Xie=60;function Qie({onLeft:e,onRight:t}){const n=s.useRef(null);return{onPointerDown:r=>{r.pointerType!=="mouse"&&(n.current={id:r.pointerId,x:r.clientX,y:r.clientY})},onPointerUp:r=>{const a=n.current;if(n.current=null,!a||a.id!==r.pointerId)return;const i=r.clientX-a.x,l=r.clientY-a.y;Math.abs(i)<Xie||Math.abs(i)<2*Math.abs(l)||(i<0?e():t())},onPointerCancel:()=>{n.current=null}}}function Jie(e){const t=Dn(),n=od(),{shown:r,closeNow:a}=n,[i,l]=s.useState(null),u=i??r,f=()=>{l(null),a()};s.useEffect(()=>{if(!i)return;const w=y=>{const x=y.target;x!=null&&x.closest(".sc-chip-preview")||x!=null&&x.closest(e)||l(null)};return document.addEventListener("pointerdown",w,!0),()=>document.removeEventListener("pointerdown",w,!0)},[i,e]);const[h,p]=s.useState(null),g=w=>({"data-open":(u==null?void 0:u.key)===w.key||void 0,"aria-haspopup":"dialog",onPointerEnter:y=>y.pointerType==="mouse"&&!i&&n.open({...w,el:y.currentTarget}),onPointerLeave:y=>y.pointerType==="mouse"&&n.close(),onFocus:y=>Xp(y.currentTarget)&&!i&&n.open({...w,el:y.currentTarget}),onClick:y=>{if((i==null?void 0:i.key)===w.key){f();return}a(),l({...w,el:y.currentTarget})}}),v=o.jsxs(o.Fragment,{children:[u&&o.jsx(ad,{anchor:u.el,kind:u.kind,src:sr(u.src,"tile"),label:u.label,onOpen:()=>{const w=u;f(),w.to?t(w.to):p({src:sr(w.src,"full"),kind:w.kind,label:w.label})},onHoverIn:n.keep,onHoverOut:()=>!i&&n.close(),onClose:f},u.key),h&&o.jsx(Uu,{src:h.src,kind:h.kind,label:h.label,onClose:()=>p(null)})]});return{bind:g,isOpen:w=>(u==null?void 0:u.key)===w,surface:v}}function ele({brief:e,prompt:t,brand:n,saidRef:r,expanded:a,clamped:i}){var $,M;const{scenes:l,presenters:u,demoProducts:f}=Rn(),h=Jie(".sc-ingredient"),p=(e==null?void 0:e.tokens)??[],g=(($=n==null?void 0:n.json)==null?void 0:$.products)??[],v=((M=n==null?void 0:n.json)==null?void 0:M.characters)??[],w=Cc(n),y=xf(n==null?void 0:n.json),[x,k]=s.useState({});s.useEffect(()=>{for(const C of p){if((C==null?void 0:C.t)!=="template")continue;const R=w.find(H=>H.id===C.id);if(!(R!=null&&R.previewUrl)||Mu(R.previewColor))continue;const T=`t${C.id}`;LM(R.previewUrl).then(H=>{const D=Mu(H??void 0);D&&k(K=>K[T]?K:{...K,[T]:D})})}});const S={products:g,demoProducts:f,cast:v,presenters:u,scenes:[...w,...l]},E=C=>{var T,H;const R=jM(C,S);if((R==null?void 0:R.kind)==="product"){const{product:D,demo:K}=R;return{key:`p${C.id}`,kind:"product",label:(D==null?void 0:D.name)??(K==null?void 0:K.name)??"product",thumb:D?Bp((H=(T=D==null?void 0:D.shots)==null?void 0:T[0])==null?void 0:H.file,"micro"):(K==null?void 0:K.previewUrl)??null,to:n&&(D||K)?la(n,C.id):void 0}}if((R==null?void 0:R.kind)==="presenter"){const{character:D,presenter:K}=R,O=(K==null?void 0:K.id)??(D==null?void 0:D.presenterId)??((D==null?void 0:D.origin)==="custom"?D.id:void 0),Z=D?bv(D):K?ti(K):{src:null};return{key:`h${C.id}`,kind:"presenter",label:D!=null&&D.supersededBy?`${D.name}, edited since`:(D==null?void 0:D.name)??(K==null?void 0:K.name)??"someone",thumb:Z.src,crop:Z.crop,to:n&&O?ha(n,O):void 0}}if((R==null?void 0:R.kind)==="scene"){const D=R.scene;return{key:`t${C.id}`,kind:"scene",label:(D==null?void 0:D.name)??"a scene no longer in the catalog",thumb:(D==null?void 0:D.previewUrl)??null,to:n&&D?_r(n,D.id):void 0,tint:Mu(D==null?void 0:D.previewColor),custom:R.custom}}if((C==null?void 0:C.t)==="color")return{key:`c${C.hex}`,kind:"color",label:C.name??C.hex,swatch:C.hex};if((C==null?void 0:C.t)==="ref")return{key:`r${C.imageHash}`,kind:"ref",label:C.label??"reference image",thumb:dn(C.imageHash,"micro"),previewHash:C.imageHash};if((C==null?void 0:C.t)==="mark"){const D=y.find(K=>K.hash===C.imageHash);return{key:`m${C.imageHash}`,kind:"mark",label:D?qp(n==null?void 0:n.json,D):"brand mark",thumb:dn(C.imageHash,"micro"),previewHash:C.imageHash}}return null},j=C=>{const R=o.jsxs(o.Fragment,{children:[C.thumb?o.jsx("img",{src:C.thumb,alt:"","data-crop":C.crop}):C.swatch?o.jsx("i",{style:{background:C.swatch}}):null,C.label]}),T=C.tint??(C.custom?x[C.key]:void 0),H=T?{"--tint":T}:void 0,D=(C.previewHash?dn(C.previewHash,"tile"):sr(C.thumb,"tile"))??(C.to?"":null);if(D!==null&&yh(C.kind)){const K=C.kind,O=h.isOpen(C.key),Z={key:C.key,src:D,kind:K,label:C.label,to:C.to};return o.jsx("button",{type:"button",className:"sc-ingredient","data-kind":C.kind,"data-tinted":T?"":void 0,style:H,title:O?void 0:`${C.label}. Preview.`,"aria-label":`${C.label}. Preview.`,...h.bind(Z),children:R},C.key)}return o.jsx("span",{className:"sc-ingredient","data-kind":C.kind,"data-tinted":T?"":void 0,style:H,title:`${C.kind}: ${C.label}`,children:R},C.key)},N=[];for(const C of p){if(C.t==="text"){const T=C.v.trim();T&&N.push(T);continue}const R=E(C);R&&N.push(j(R))}if(!N.length&&!t)return null;const P=N.flatMap((C,R)=>R?[" ",C]:[C]);return o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:r,className:"sc-brief-said","data-expanded":a||void 0,"data-clamped":i||void 0,dir:"auto",children:P.length?P:t||""}),h.surface]})}const tle=256,_l=new Map;function G5(e,t){for(_l.delete(e),_l.set(e,t);_l.size>tle;)_l.delete(_l.keys().next().value)}function nle(e,t){const n=new Map(e.map(a=>[a.id,a])),r=[];for(let a=t.parentId?n.get(t.parentId):void 0;a;a=a.parentId?n.get(a.parentId):void 0)r.unshift(a);return{ancestors:r,siblings:e.filter(a=>a.parentId===t.parentId),children:e.filter(a=>a.parentId===t.id),history:e}}function rle(e,t){G5(e,t);for(const n of t.history??[])n.id!==e&&G5(n.id,nle(t.history??[],n))}function sle(e){var i;const[t,n]=s.useState(()=>{const l=_l.get(e.id);return l?{id:e.id,lineage:l}:null});s.useEffect(()=>{let l=!0;return Re.lineage(e.id).then(u=>{l&&(rle(e.id,u),n({id:e.id,lineage:u}))}).catch(()=>{}),()=>{l=!1}},[e.id,e.childCount,e.status,e.parentId]);const r=(t==null?void 0:t.id)===e.id?t.lineage:_l.get(e.id)??null;if(!r)return{ancestors:[],children:[],siblings:[e],sibIndex:0,parentShot:null,history:null,rootId:e.id,loaded:!1};const a=r.siblings.some(l=>l.id===e.id)?r.siblings:[e,...r.siblings];return{ancestors:r.ancestors,children:r.children,siblings:a,sibIndex:a.findIndex(l=>l.id===e.id),parentShot:r.ancestors[r.ancestors.length-1]??null,history:r.history??null,rootId:((i=r.ancestors[0])==null?void 0:i.id)??e.id,loaded:!0}}const ale=32,Di=new Map;function ole(e){for(Di.delete(e.id),Di.set(e.id,e);Di.size>ale;)Di.delete(Di.keys().next().value)}function ile(e){const[t,n]=s.useState(()=>Di.get(e.id)??null);return s.useEffect(()=>{const r=Di.get(e.id);if(r){n(r);return}let a=!0;return Re.node(e.id).then(i=>{a&&(ole(i),n(i))}).catch(()=>{}),()=>{a=!1}},[e.id]),(t==null?void 0:t.id)===e.id?t:Di.get(e.id)??null}const lle="(max-width: 1023px)",qR=380,XR=480,Y5=380,ou=e=>Math.min(XR,Math.max(qR,Math.round(e)));function cle({node:e,rootId:t,items:n,loadMore:r,complete:a,brand:i,engines:l,projectId:u,onClose:f,onSelect:h,onRetry:p,onCancel:g,onKeep:v,onLanded:w,onRemix:y,onArchive:x,onUnarchive:k,onDelete:S,onRefined:E,tokenNames:j}){const{ancestors:N,children:P,history:$}=sle(e),M=ile(e),C=s.useMemo(()=>l.find(Fe=>Fe.id===e.engineId),[l,e.engineId]),{push:R}=or(),[T,H]=fa(Dr.ovlPanelW,Y5),D=s.useRef(0),K=s.useRef(0),O=s.useRef(null),Z=s.useMemo(()=>{var Fe;return(((Fe=e.brief)==null?void 0:Fe.tokens)??[]).some(pt=>(pt==null?void 0:pt.t)&&pt.t!=="text"&&pt.t!=="format")},[e.brief]),te=s.useMemo(()=>{const Fe=xf(i.json);return{...j,mark:pt=>{const it=Fe.find(St=>St.hash===pt);return it?qp(i.json,it):null}}},[j,i]),B=s.useMemo(()=>GR(M??e,te),[M,e,te]),[F,X]=s.useState(!1),[z,I]=s.useState(!1),[U,G]=s.useState(!1),[ne,q]=s.useState(!1),[le,Se]=s.useState(!1),[Q,xe]=s.useState(!1);s.useEffect(()=>{G(!1),xe(!1),q(!1)},[e.id]),s.useEffect(()=>{if(!U)return;const Fe=setTimeout(()=>G(!1),1400);return()=>clearTimeout(Fe)},[U]),s.useEffect(()=>{if(!Q)return;const Fe=setTimeout(()=>xe(!1),1400);return()=>clearTimeout(Fe)},[Q]);const[ee,ae]=s.useState(null);tw(ee,"--sc-ovl-dock-h");const re=s.useRef(null),[_,ue]=s.useState(!1),[We,Xe]=s.useState(!1);s.useEffect(()=>ue(!1),[e.id]),s.useLayoutEffect(()=>{const Fe=re.current;if(!Fe||_)return;const pt=()=>Xe(Fe.scrollHeight>Fe.clientHeight+1);pt();const it=new ResizeObserver(pt);return it.observe(Fe),()=>it.disconnect()},[B,_]);const ze=s.useMemo(()=>Kie($??[...N,e,...P.slice(0,6)],e,n),[$,N,e,P,n]),tt=s.useMemo(()=>ze.find(Fe=>Fe.node.id===e.id)??null,[ze,e.id]),ce=wr(lle),ve=ze.length>1&&ce?YR(ze,e.id):e.kind!=="edit"?"Shot":$&&tt?tt.label:"Refinement",Pe=s.useMemo(()=>o6(n,e.id),[n,e.id]);s.useEffect(()=>{Pe.at>=0&&!a&&n.length-Pe.at<=6&&r()},[Pe.at,n.length,a,r]);const de=Fe=>{const pt=Fe>0?Pe.next:Pe.prev;pt&&h(pt.id)},je=od(),Ue=(Fe,pt)=>Fe!=null&&Fe.images[0]?{onPointerEnter:it=>{it.pointerType==="mouse"&&je.open({key:Fe.id,src:dn(Fe.images[0],"tile"),label:Sr(Fe),noun:pt,el:it.currentTarget,id:Fe.id})},onPointerLeave:it=>{it.pointerType==="mouse"&&je.close()}}:{},ye=Qie({onLeft:()=>de(1),onRight:()=>de(-1)});s.useEffect(()=>{const Fe=je.shown;if(!Fe)return;const pt=Fe.noun==="Next shot"?Pe.next:Pe.prev;pt!=null&&pt.images[0]?je.open({key:pt.id,src:dn(pt.images[0],"tile"),label:Sr(pt),noun:Fe.noun,el:Fe.el,id:pt.id}):je.closeNow()},[e.id]),s.useEffect(()=>{var St,xt;const Fe=ze.findIndex(At=>At.node.id===e.id),it=[(St=ze[Fe-1])==null?void 0:St.node,(xt=ze[Fe+1])==null?void 0:xt.node,Pe.prev,Pe.next].filter(At=>!!(At!=null&&At.images[0])).map(At=>{var et;const Kt=new Image;return Kt.decoding="async",Kt.src=dn(At.images[0],"tile"),(et=Kt.decode)==null||et.call(Kt).catch(()=>{}),Kt});return()=>{for(const At of it)At.src=""}},[ze,e.id,Pe.prev,Pe.next]);const Ee=e.images[0],be=e.promptHead.slice(0,40).replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"")||"shot",Le=async(Fe=!1)=>{if(!z){I(!0);try{const pt=fetch(Mr(Ee)).then(it=>{if(!it.ok)throw new Error(`HTTP ${it.status}`);return it.blob()});await navigator.clipboard.write([new ClipboardItem({"image/png":pt})]),Fe?R({kind:"success",title:"Copied to clipboard"}):G(!0)}catch(pt){R(nn(pt,"Copy failed"))}finally{I(!1)}}},Qe=async()=>{if(!ne){q(!0);try{await(e.archived?k(e):x(e))}finally{q(!1)}}},Ke=async()=>{if(!le){Se(!0);try{const Fe=e.brief?Tv(e.brief):null;if(!Fe||Fe.every(pt=>pt.t==="text"&&!pt.v.trim()))await navigator.clipboard.writeText(B);else{const pt=xt=>{var At;switch(xt.t){case"text":return xt.v;case"product":return te.product(xt.id)??"a product";case"character":return te.person(xt.id)??"a presenter";case"template":return te.scene(xt.id)??"a scene";case"color":return xt.name??xt.hex;case"ref":return"reference image";case"mark":return((At=te.mark)==null?void 0:At.call(te,xt.imageHash))??"brand mark"}},{text:it,html:St}=GX(Fe,pt);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([it],{type:"text/plain"}),"text/html":new Blob([St],{type:"text/html"})})])}xe(!0)}catch(Fe){R(nn(Fe,"Copy failed"))}finally{Se(!1)}}};s.useEffect(()=>{const Fe=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=Fe}},[]);const nt=[{key:"download",label:"Download",icon:o.jsx(AC,{size:14}),onClick:()=>{const Fe=document.createElement("a");Fe.href=Mr(Ee),Fe.download=`${be}.png`,Fe.click()}},{key:"keep",label:e.kept?"Remove from keepers":"Keep",icon:o.jsx(po,{size:14,weight:e.kept?"fill":"regular"}),onClick:()=>v(e),tint:e.kept?"var(--sc-star)":void 0,on:e.kept},{key:"copy",label:"Copy image",icon:U?o.jsx(Kn,{size:14,weight:"bold"}):o.jsx(K3,{size:14}),onClick:()=>void Le(),onMenu:()=>void Le(!0),busy:z,said:U?"Copied":void 0}],gt=[{key:"archive",label:e.archived?"Restore":"Archive",icon:e.archived?o.jsx(M0,{size:14}):o.jsx(Op,{size:14}),onClick:()=>void Qe(),busy:ne},...e.archived?[{key:"delete",label:"Delete permanently",icon:o.jsx(Vp,{size:14}),onClick:()=>X(!0),tint:"var(--sc-red)",dialog:!0}]:[]],Pt=e.status==="done"&&e.images.length>0,Ut=!Pt&&e.kind!=="edit"&&!!e.brief,Nt=Pt?[...nt,...gt]:gt,cn=Pt?o.jsx(pf,{children:Nt.map(Fe=>o.jsxs(mf,{onSelect:Fe.onMenu??Fe.onClick,disabled:Fe.busy,color:Fe.tint?"red":void 0,children:[Fe.icon,Fe.label]},Fe.key))}):void 0;return Rr.createPortal(o.jsx(Gu,{trapped:!0,loop:!0,asChild:!0,onMountAutoFocus:Fe=>{var pt;Fe.preventDefault(),(pt=O.current)==null||pt.focus({preventScroll:!0})},children:o.jsxs("div",{ref:O,tabIndex:-1,className:"sc-ovl","data-fb":"shot-overlay","data-fb-node":e.id,role:"dialog","aria-modal":"true","aria-label":Sr(e),"data-rail":n.length>1?"":void 0,style:{"--sc-ovl-panel-w":`${ou(T)}px`},children:[n.length>1&&o.jsx(qie,{shots:n,activeId:e.id,onSelect:h,onEndReached:r,complete:a}),o.jsxs("header",{className:"sc-ovl-bar",children:[o.jsxs("div",{className:"sc-ovl-bar-l",children:[o.jsx(lr,{label:"Close (esc)",children:o.jsx("button",{type:"button",className:"sc-icon-btn",onClick:f,"aria-label":"Close",children:o.jsx(jn,{size:13})})}),Pe.at>=0&&n.length>1&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"sc-icon-btn",disabled:!Pe.prev,onClick:()=>Pe.prev&&h(Pe.prev.id),"aria-label":"Previous shot",...Ue(Pe.prev,"Previous shot"),children:o.jsx(ga,{size:13})}),o.jsx("button",{type:"button",className:"sc-icon-btn",disabled:!Pe.next,onClick:()=>Pe.next&&h(Pe.next.id),"aria-label":"Next shot",...Ue(Pe.next,"Next shot"),children:o.jsx(ol,{size:13})})]})]}),Nt.length>0&&o.jsxs("div",{className:"sc-ovl-bar-r",children:[o.jsx("div",{className:"sc-ovl-acts",children:Nt.map(Fe=>o.jsx(lr,{label:Fe.said??Fe.label,open:!!Fe.said,children:o.jsx("button",{type:"button",className:"sc-icon-btn",onClick:Fe.onClick,"aria-label":Fe.label,"aria-pressed":Fe.on===void 0?void 0:Fe.on,"data-on":Fe.on||void 0,"aria-haspopup":Fe.dialog?"dialog":void 0,"aria-busy":Fe.busy||void 0,"data-busy":Fe.busy||void 0,style:Fe.tint?{color:Fe.tint}:void 0,children:Fe.icon})},Fe.key))}),o.jsxs(Ss,{children:[o.jsx(lr,{label:"More actions",children:o.jsx(Es,{children:o.jsx("button",{type:"button",className:"sc-icon-btn sc-ovl-overflow","aria-label":"More actions",children:o.jsx(SC,{size:18,weight:"bold"})})})}),o.jsx(Cs,{align:"end",sideOffset:6,children:Nt.map(Fe=>o.jsxs(tr,{onSelect:Fe.onMenu??Fe.onClick,disabled:Fe.busy,color:Fe.tint?"red":void 0,children:[Fe.icon,Fe.label]},Fe.key))})]})]})]}),o.jsx(sf,{open:F,onOpenChange:X,children:o.jsxs(af,{maxWidth:"420px",children:[o.jsx(of,{children:"Delete this shot permanently?"}),o.jsx(lf,{size:"2",children:"This cannot be undone."}),o.jsxs(js,{gap:"3",mt:"4",justify:"end",children:[o.jsx(uf,{children:o.jsx(ia,{variant:"soft",color:"gray",children:"Cancel"})}),o.jsx(cf,{children:o.jsx(ia,{color:"red",onClick:()=>S(e),children:"Delete permanently"})})]})]})}),je.shown&&o.jsx(ad,{anchor:je.shown.el,kind:"shot",noun:je.shown.noun,src:je.shown.src,label:je.shown.label,onOpen:()=>{var pt;const Fe=(pt=je.shown)==null?void 0:pt.id;je.closeNow(),Fe&&h(Fe)},onHoverIn:je.keep,onHoverOut:je.close,onClose:je.closeNow},je.shown.key),o.jsxs("div",{className:"sc-ovl-stage","data-takes":ze.length>1?"":void 0,...ye,children:[o.jsx(Zie,{node:e,onRetry:()=>p(e),onCancel:()=>g(e),engineName:C==null?void 0:C.displayName,menu:cn}),ze.length>1?o.jsx(Gie,{trail:ze,activeId:e.id,names:te,onSelect:h}):o.jsx("div",{className:"sc-trail sc-trail-empty","aria-hidden":!0})]}),o.jsx("div",{className:"sc-ovl-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize the details panel","aria-valuemin":qR,"aria-valuemax":XR,"aria-valuenow":ou(T),tabIndex:0,onPointerDown:Fe=>{Fe.button===0&&(Fe.preventDefault(),Fe.stopPropagation(),Fe.currentTarget.setPointerCapture(Fe.pointerId))},onPointerMove:Fe=>{if(!Fe.currentTarget.hasPointerCapture(Fe.pointerId))return;const pt=Fe.currentTarget.closest(".sc-ovl");D.current=Fe.clientX,!K.current&&(K.current=requestAnimationFrame(()=>{K.current=0,pt==null||pt.style.setProperty("--sc-ovl-panel-w",`${ou(window.innerWidth-D.current)}px`)}))},onPointerUp:Fe=>{Fe.currentTarget.hasPointerCapture(Fe.pointerId)&&(Fe.currentTarget.releasePointerCapture(Fe.pointerId),H(ou(window.innerWidth-Fe.clientX)))},onDoubleClick:Fe=>{Fe.stopPropagation(),H(Y5)},onKeyDown:Fe=>{Fe.key==="ArrowLeft"?H(pt=>ou(pt+16)):Fe.key==="ArrowRight"&&H(pt=>ou(pt-16))}}),o.jsxs("aside",{className:"sc-ovl-meta",children:[o.jsxs("div",{className:"sc-ovl-scroll",children:[o.jsxs("div",{className:"sc-ovl-head",children:[o.jsx("b",{children:ve}),e.archived&&o.jsx("small",{className:"sc-ovl-flag",children:"archived"}),Pt&&e.costUsd>0&&o.jsxs("small",{className:"sc-ovl-spend",title:"Of your API budget",children:["$",e.costUsd.toFixed(2)]})]}),e.kind!=="root"&&(B||Z)&&o.jsxs("div",{className:"sc-ovl-sec sc-ovl-brief",children:[o.jsxs("div",{className:"sc-ovl-brief-head",children:[o.jsx("span",{className:"sc-eyebrow",children:"Prompt"}),o.jsx(lr,{label:Q?"Copied":"Copy the prompt",open:Q||void 0,children:o.jsx("button",{type:"button",className:"sc-icon-btn sc-ovl-copy","aria-label":"Copy the prompt","aria-busy":le||void 0,"data-busy":le?"":void 0,onClick:()=>void Ke(),children:Q?o.jsx(Kn,{size:14,weight:"bold"}):o.jsx(K3,{size:14})})})]}),o.jsx("div",{className:"sc-brief-record",children:o.jsx(ele,{brief:e.brief,prompt:(M==null?void 0:M.prompt)??e.promptHead,brand:i,saidRef:re,expanded:_,clamped:We&&!_})}),(We||_)&&o.jsx("button",{type:"button",className:"sc-s sc-ovl-more","aria-expanded":_,onClick:()=>ue(Fe=>!Fe),children:_?o.jsxs(o.Fragment,{children:[o.jsx(LU,{size:12})," Show less"]}):o.jsxs(o.Fragment,{children:[o.jsx(Yi,{size:12})," Show more"]})})]}),(Pt||Ut)&&o.jsxs("div",{className:"sc-sugg",children:[Ut&&o.jsxs("button",{type:"button",className:"sc-s",onClick:()=>y(e),title:"Put this prompt back in the composer, to change and run again",children:[o.jsx(Ju,{size:12})," Edit the prompt"]}),Pt&&o.jsxs("button",{type:"button",className:"sc-s",onClick:()=>p(e),title:"Run the same setup again for a different take",children:[o.jsx(M0,{size:12})," Try again"]}),Pt&&o.jsxs("button",{type:"button",className:"sc-s",onClick:()=>y(e),title:"Start a new shot from this setup: same prompt, chips, shape and count, ready to change",children:[o.jsx(Ph,{size:12})," Reuse setup"]})]})]}),(Pt||e.status==="running")&&o.jsx("div",{className:"sc-ovl-edit sc-dock",ref:ae,children:o.jsx(ew,{variant:"overlay",projectId:u,brand:i,engines:l,parentId:t,target:e,sourceImage:Ee,persistDraft:!1,onQueued:(Fe,pt,it,St)=>{w(St??[]),Fe&&h(Fe),Fe&&(E==null||E(Fe,pt))}})})]})]})}),document.body)}function q5(){const{shotId:e}=Bs(),t=KT(),{push:n}=or(),r=e?t.byId.get(e)??null:null,[a,i]=s.useState(null);s.useEffect(()=>{if(!e||r)return;let f=!0;return Re.node(e).then(h=>f&&i({id:e,node:h.kind==="root"?null:h})).catch(()=>f&&i({id:e,node:null})),()=>{f=!1}},[e,r]),s.useEffect(()=>{if(!(!e||r))return t.subscribeActivity(f=>{const h=f.find(p=>p.id===e);h&&i({id:e,node:h})})},[e,r,t.subscribeActivity]);const l=r??(a!==null&&a.id===e?a.node:null),u=!r&&a!==null&&a.id===e&&a.node===null;return s.useEffect(()=>{u&&(n({kind:"info",title:"That shot is no longer available",detail:"Back to the feed."}),t.close())},[u,t.close,n]),l?o.jsx(cle,{node:l,rootId:t.rootId,items:t.items,loadMore:t.loadMore,complete:t.complete,brand:t.brand,engines:t.engines,projectId:t.projectId,onClose:t.close,onSelect:t.select,onRetry:t.retry,onCancel:t.cancel,onKeep:t.keep,onLanded:t.landed,onRefined:t.refined,tokenNames:t.tokenNames,onRemix:t.remix,onArchive:()=>t.archive(l),onUnarchive:()=>t.unarchive(l),onDelete:()=>t.delete(l)}):u?null:o.jsx("div",{className:"sc-ovl-wait",role:"status","aria-label":"Loading",children:o.jsx(xr,{size:"3"})})}function ule(){const e=DS();return o.jsx(js,{align:"center",justify:"center",height:"100vh",p:"5",children:o.jsx(uv,{failure:{kind:"unknown",title:"This page could not be shown.",fix:"Reloading usually brings it back.",raw:String((e==null?void 0:e.message)??e??""),retryable:!0},action:o.jsx(ia,{size:"1",variant:"soft",color:"gray",onClick:()=>window.location.reload(),children:"Reload"})})})}function dle(){const{setSlug:e=""}=Bs(),{pathname:t,search:n}=Zn(),{brand:r,sets:a,loaded:i,refresh:l}=on(),u=Dn(),f=un({path:ct.set,end:!1}),h=a.find(v=>v.slug===e)??a.find(v=>v.id===e)??null;Sc(h==null?void 0:h.name);const[p,g]=s.useState(null);if(s.useEffect(()=>{if(!i||h)return;if(p===e){u(mr(r),{replace:!0});return}let v=!0;return l().finally(()=>v&&g(e)),()=>{v=!1}},[i,h,e,p,r,u,l]),s.useEffect(()=>{h&&g(null)},[h]),!i||!h)return null;if(h.slug!==e){const v=f?t.slice(f.pathnameBase.length):"";return o.jsx(uo,{to:t0(r,h)+v+n,replace:!0})}return o.jsx(KR,{set:h},h.id)}function fle(){const{pathname:e,search:t}=Zn();return o.jsx(uo,{to:MW(e,t),replace:!0})}function hle(){const{brandSlug:e}=Bs();return o.jsx(uo,{to:`/${e}?settings=brand`,replace:!0})}function ple(){const{sceneId:e}=Bs();return o.jsxs(o.Fragment,{children:[o.jsx(Jre,{},e),o.jsx(uc,{})]})}function mle(){const{presenterId:e}=Bs();return o.jsxs(o.Fragment,{children:[o.jsx(cse,{},e),o.jsx(uc,{})]})}function gle(){const{productId:e}=Bs();return o.jsx(Yoe,{},e)}const vle=V$([{element:o.jsx(rte,{}),errorElement:o.jsx(ule,{}),children:[{index:!0,element:o.jsx(sX,{})},{path:ct.setup,element:o.jsx(ute,{})},{path:ct.legacy,element:o.jsx(fle,{})},{path:ct.brand,element:o.jsx(Qee,{}),children:[{index:!0,element:o.jsx(Zre,{})},{path:ct.hub,element:o.jsx(KR,{set:null}),children:[{path:ct.hubShot,element:o.jsx(q5,{})}]},{path:ct.set,element:o.jsx(dle,{}),children:[{path:ct.setShot,element:o.jsx(q5,{})}]},{path:ct.kit,element:o.jsx(hle,{})},{path:ct.products,element:o.jsx(_oe,{})},{path:ct.product,element:o.jsx(gle,{})},{path:ct.scenes,element:o.jsx(Wre,{}),children:[{path:ct.sceneStudio,element:o.jsx(H5,{})}]},{path:ct.scene,element:o.jsx(ple,{}),children:[{path:ct.sceneEdit,element:o.jsx(H5,{})}]},{path:ct.presenters,element:o.jsx(ose,{}),children:[{path:ct.presenterStudio,element:o.jsx(koe,{})}]},{path:ct.presenter,element:o.jsx(mle,{}),children:[{path:ct.presenterEdit,element:o.jsx(foe,{})}]}]},{path:ct.notFound,element:o.jsx(uo,{to:ct.root,replace:!0})}]}]),b8=localStorage.getItem("sc-theme")??localStorage.getItem("bt-theme");document.documentElement.dataset.theme=b8==="light"||b8==="dark"?b8:window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark";yG();ML.createRoot(document.getElementById("root")).render(o.jsx($n.StrictMode,{children:o.jsx(cB,{children:o.jsx(uW,{children:o.jsx(f$,{router:vle})})})}));
|