1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/workflow-satellite-C1f0GxAr.css"])))=>i.map(i=>d[i]); 2import{H as Xy,cx as Jy,V as un,bG as us,at as Qy,E as H,ay as qo,az as sf,P as nf,aA as Xx,g as Jx,_ as Xl,bd as tn,cy as Qx,ca as of,ap as Zx}from"./workflow-shell-C4E2GvqD.js";import{j as s,r as c,a as Ps}from"./vendor-react-BmRvYVPE.js";import{Q as eb,c2 as Bs,c3 as vs,c4 as Br,c5 as tb,c6 as ea,J as Ml,i as Bt,c7 as rb,az as sb,bw as nb,b8 as ob,bx as af,bD as lf,c8 as cf,c9 as df,ca as uf,cb as On,cc as ln,cd as vr,ce as $d,cf as pf,bv as mf,cg as ib,ch as ab,ci as lb,cj as cb,ck as ff,u as db,a2 as ub,be as pb,cl as yf,cm as hf,cn as mb,co as fb,cp as yb,cq as gf,cr as hb,cs as gb,ct as xb,cu as bb}from"./workflow-gemini-service-B7L3EbA_.js";import{gt as Ho,gu as ws,cp as Zy,c1 as on,aw as wb,gv as xu,gw as Sb,gx as eh,gy as kb,gz as vb,bJ as th,L as Go,b8 as Yo,ao as Cb,ap as zi,b7 as rh,aW as Nb,gA as Eb,gB as Tb,E as sh,bX as Rb,bk as jb,gC as xf,gD as bf,gE as wf,bV as Ki,gF as Ab,gG as Ib,gH as Pb,gI as _b,cb as Bb,gJ as Mb,d8 as Lb,aV as Ob,bW as $b,bY as Fb,gK as Db,gL as Ub,gM as Wb,gN as Hb,gO as Sf,gP as zb,cn as Kb,gQ as nh,gR as qb,gS as Gb,gT as Oo,gU as Yb,gV as kf,gW as Fd,gX as Vb,gY as Xb,gZ as Dd,g_ as Ud,g$ as Wd,h0 as $n,h1 as vf,h2 as Jb,h3 as Qb,h4 as Zb,h5 as qi,h6 as ew,h7 as tw,h8 as rw,h9 as Cf,ha as sw,hb as bl,hc as nw,hd as wl,cl as $o,he as Nf,hf as Hd,cx as Ef,hg as Tf,hh as Rf,hi as jf,cG as ow,cJ as iw,hj as aw,cf as lw,hk as cw,hl as dw,hm as uw,hn as pw,ho as mw,hp as fw,hq as yw}from"./workflow-satellite-D7p5FKVD.js";import{c as oh,$ as ih,Y as hw,an as gw,G as Af,ay as If}from"./edge-functions-CM-SJXPL.js";import"./CreativeBrainDashboard-CpyC_hvR.js";import{B as xw,a as bw,b as ww}from"./bloomBotFilmStyleGate-BB7GntuJ.js";import{FilmStylePreviewThumb as cn}from"./FilmStylePreviewThumb-DHlnajJY.js";import{S as Pf,U as _f,V as Bf,W as Sw,X as kw,Y as vw}from"./App-2Pk0_OyV.js";import{p as Cw}from"./parseBloomBotOptionsFromReply-CXxDIYme.js";import{i as Mf}from"./storyflowDescriptiveScriptRollout-ZLAfVava.js";import{u as ah}from"./useBrowserSpeechRecognition-CWbMrvXv.js";import{be as bu,A as Nw,a5 as Ew}from"./workflow-model-config-CPwFoR5W.js";import{h as Tw,i as Rw,S as jw,A as Lf,c as Aw,j as Sl,k as rn,l as Of,g as $f,s as zd,m as kl,n as Iw}from"./AddToProjectAssetLibraryWizard-BoYAolzM.js";import{w as wu}from"./workflow-i18n-C_CpSd25.js";import{u as Pw,E as Ff,i as _w,m as Bw,a as Mw,r as Lw,A as Kd,b as qd,c as Ow,g as $w,P as Fw,d as Df,e as Uf,f as Wf,h as Dw,j as Uw,k as Ww,l as Hw,n as zw,o as Kw}from"./approvedAssetLibraryMiniTabs-DevQk7yo.js";import{E as qw,m as Gw,A as Yw,a as Vw}from"./ApprovedAssetLibrarySelectionNotice-D9wFOY9h.js";import{D as Xw}from"./DeleteConfirmModal-Dgec03mi.js";import"./vendor-idb-CDJY9-SS.js";import"./director-studio-MzEqiD7r.js";import"./vendor-three-core-Chshme8x.js";import"./vendor-r3f-8y4YuVqN.js";import"./vendor-three-stdlib-RSnVEo6I.js";import"./vendor-drei-H6OlvgBO.js";import"./vendor-hls-B5xTr0nO.js";import"./workflow-controls-C5YAwnbY.js";import"./workflow-longvideo-parser-Ca6lU5fA.js";import"./vendor-api-CbM-anGD.js";import"./vendor-query-EuS0FA8-.js";import"./index-BkxxQQUg.js";import"./appSaveBeforeReload-ESW1ZqJ2.js";import"./passwordRecoveryIntent-Dfn41MYr.js";import"./AvatarWithBadge-BqXSALuG.js";import"./phoneAuth-CgLTI989.js";import"./vendor-driver-blTudzU6.js";import"./SubmitApprovedAssetWizard-DROKP_gj.js";import"./AssetLibraryModal-CQUQPGS2.js";const Jw={discovery:"Lead with logline, stakes, genre, and premise; keep world detail light unless asked.",world_bible:"Lead with rules, geography, timeline, culture, and core conflict; tie back to plot.",season_arc:"Lead with season-wide % pacing, act turns, and cross-episode payoffs per templates.",episodes:"Lead with per-episode summaries, end hooks, and template compliance.",polish:"Lead with canon checks, open seed payoffs, Dashboard conflicts, and tight dialogue."};function Qw(r){return typeof r=="string"&&["discovery","world_bible","season_arc","episodes","polish"].includes(r)}function Pr(r,t){const i=r.replace(/\s+/g," ").trim();return i.length<=t?i:`${i.slice(0,t-1)}â¦`}const Zw=8500,Hf=`## Reply discipline (this turn) 3- Honor the project state above for canon; if the user contradicts it on purpose, confirm and list side effects. 4- Prefer concrete beats, hooks, and [[OPTIONS: ...]] at major forks. 5- Mention open seeds or Dashboard conflicts when relevant; suggest payoff timing by episode range.`;function eS(r){if(r.mode==="compact")return!0;
5if(r.mode==="full")return!1;const t=r.sendTurnIndex,i=r.fullContextEveryNTurns;return t==null||t<1?!1:(t-1)%i!==0}function tS(r,t,i){return i?r===0?520:r===1?280:r===2?140:0:r===0?Math.min(1200,t<=6?900:750):r===1?t<=8?650:520:r===2?t<=12?420:320:t<=10?300:t<=24?220:110}function rS(r){var z,Z,Ee,Ie,ne,Pe,xe;const t=r.maxChars??Zw,i=eS(r),a=[];a.push("The following is the userâs current Creative Brain project state. Treat it as authoritative for canon, continuity, and seed/payoff unless the userâs latest message explicitly overrides a specific item (then acknowledge the override and list what else may need updating)."),i&&a.push("(Context mode: **compact** â distant episodes may be title-only; ask if you need a specific episode expanded.)");const u=r.narrativePhase;u&&(a.push("## User narrative phase"),a.push(`Phase: **${u}** â ${Jw[u]}`));const p=r.seriesVisualStyle;if((z=p==null?void 0:p.label)!=null&&z.trim()){const ae=(p.presetKeywords||"").trim();a.push("## Series visual style (user selection)"),a.push(`Preset: **${p.label.trim()}**${(Z=p.id)!=null&&Z.trim()?` (id: ${p.id.trim()})`:""}. Honor this look when describing imagery, storyboard beats, or production-facing language.`),ae&&a.push(`Keywords: ${Pr(ae,i?360:640)}`)}const{logline:f,synopsis:x}=r.storyOutline,S=i?720:2600;(f.trim()||x.trim())&&(a.push("## Global story arc"),f.trim()&&a.push(`Logline: ${Pr(f,i?320:420)}`),x.trim()&&a.push(`Synopsis: ${Pr(x,S)}`));const k=r.dashboardData;if((Ee=k==null?void 0:k.characterShare)!=null&&Ee.length){const ae=[...k.characterShare].sort((de,me)=>me.sharePercent-de.sharePercent).slice(0,6).map(de=>`${de.name} (${de.role} ~${Math.round(de.sharePercent)}%)`).join("; ");ae&&a.push(`## Character presence (Dashboard): ${ae}`)}if((Ie=r.characterProfiles)!=null&&Ie.length){const ae=r.characterProfiles.slice(0,i?6:12).map(de=>{const me=Pr(de.name||"",48),Te=Pr(de.backstory||"",i?120:220);return Te?`- ${me}: ${Te}`:`- ${me}`}).filter(Boolean);ae.length&&(a.push("## Character bible notes"),a.push(ae.join(` 6`)))}const v=i?380:580,I=[];for(const[ae,de]of Object.entries(r.worldDimensionLabels)){const me=(r.worldBible[ae]||"").trim();me&&I.push(`- **${de}**: ${Pr(me,v)}`)}I.length&&(a.push("## World Bible (non-empty dimensions only)"),a.push(I.join(` 7`)));const $=r.editFocus;$&&(a.push("## User UI focus (prioritize suggestions here)"),$.type==="story_arc"?a.push("- Editing: **Global Story Arc** (logline / synopsis)."):$.type==="world_bible"?a.push(`- Editing: **World Bible â ${$.dimensionLabel}** (dimension id: ${$.dimensionId}).`):a.push(`- Editing: **Episode outline Ep ${$.episodeIndex+1}** (0-based index ${$.episodeIndex}).`));const O=r.seasonEpisodes.length;if(O>0){const ae=Math.min(Math.max(0,r.selectedEpisodeIndex),Math.max(0,O-1));a.push(`## Episode board (${O} episodes, narrative focus: Ep ${ae+1}; summaries weighted by distance from focus)`),r.seasonEpisodes.forEach((de,me)=>{var ve;const Te=Math.abs(me-ae),nt=me===ae?" â focus":"",je=tS(Te,O,i),ue=(ve=de.characterNames)!=null&&ve.filter(Boolean).length?` [chars: ${de.characterNames.slice(0,8).join(", ")}${(de.characterNames.length||0)>8?"â¦":""}]`:"";je<=0?a.push(`E${me+1}${nt}: **${Pr(de.title,90)}**${ue} _(summary omitted in compact band)_`):a.push(`E${me+1}${nt}: **${Pr(de.title,90)}**${ue} â ${Pr(de.summary,je)}`)})}if(k){const ae=k.seeds.filter(me=>!me.paidOff);if(ae.length){a.push("## Open seeds (Dashboard â pay off when pacing allows)");for(const me of ae.slice(0,14))a.push(`- ${Pr(me.label,130)} (planted E${me.plantedInEpisode})`)}const de=k.seeds.filter(me=>me.paidOff&&me.paidOffInEpisode!=null).sort((me,Te)=>(Te.paidOffInEpisode??0)-(me.paidOffInEpisode??0)).slice(0,8);if(de.length&&!i){a.push("## Recent payoffs (continuity reference)");for(const me of de)a.push(`- ${Pr(me.label,100)} (E${me.plantedInEpisode} â E${me.paidOffInEpisode})`)}if(!k.logic.consistent&&k.logic.conflicts.length){a.push("## Consistency flags (Dashboard â resolve or mention in reply)");for(const me of k.logic.conflicts.slice(0,8))a.push(`- ${Pr(me.description,220)}${me.episodeIndex!=null?` (Ep ${me.episodeIndex})`:""}`)}}r.includePrinciplesReminder!==!1&&a.push(Hf);let D=a.join(` 8 9`);if(D.length>t){const ae=D.match(/Synopsis: ([\s\S]*?)(?=\n\n## |$)/);if(ae){const de=Pr(ae[1],i?400:700);D=D.replace(ae[0],`Synopsis: ${de}`)}}if(D.length>t){const ae=` 10 11`+Hf,de=D.replace(/\n\n## Reply discipline \(this turn\)[\s\S]*$/,"");de.length<D.length&&de.length+ae.length<=t&&(D=de+ae)}return D.length>t&&(D=`${D.slice(0,t-28)} 12 13â¦(truncated)`),!!u||!!((ne=p==null?void 0:p.label)!=null&&ne.trim())||f.trim()||x.trim()||I.length>0||!!((Pe=r.characterProfiles)!=null&&Pe.length)||O>0||k&&(k.seeds.length>0||((xe=k.characterShare)==null?void 0:xe.length)||!k.logic.consistent)?D:""}const Gd={};function Fl(){const r=(Gd==null?void 0:Gd.VITE_STORYFLOW_RAG)??"1";
13return r==="0"||r==="false"?!1:r==="1"||r==="true"}function sS(r){const t=[],i=[`Logline: ${r.storyOutline.logline}`,`Synopsis: ${r.storyOutline.synopsis}`].map(p=>p.trim()).filter(Boolean).join(` 14 15`);i.trim()&&t.push({sourceType:"story_outline",sourceKey:"main",text:i});for(const[p,f]of Object.entries(r.worldBible)){const x=typeof f=="string"?f.trim():"";if(!x)continue;const S=r.worldDimensionLabels[p]||p;t.push({sourceType:"world_bible",sourceKey:p.slice(0,120),text:`${S} 16 17${x}`})}r.seasonEpisodes.forEach((p,f)=>{var v;const x=(v=p.characterNames)==null?void 0:v.filter(Boolean).join(", "),k=[`Episode ${f+1}: ${p.title||""}`.trim(),p.summary||"",x?`Characters: ${x}`:""].filter(Boolean).join(` 18 19`).trim();k&&t.push({sourceType:"episode",sourceKey:String(f),text:k})});const a=(r.characterProfiles||[]).map(p=>{const f=String((p==null?void 0:p.name)||"").trim();if(!f)return"";const x=String((p==null?void 0:p.backstory)||"").trim();return x?`${f}: ${x}`:f}).filter(Boolean);a.length&&t.push({sourceType:"story_outline",sourceKey:"character_profiles",text:`Character bible notes 20 21${a.join(` 22`)}`});const u=(r.openSeeds||[]).filter(p=>!p.paidOff).slice(0,60).map(p=>`${String(p.label||"").trim()} (planted E${p.plantedInEpisode})`).filter(Boolean);return u.length&&t.push({sourceType:"story_outline",sourceKey:"seed_ledger",text:`Open seeds ledger 23 24${u.join(` 25`)}`}),t}async function nS(r,t){if(!(!r||!Fl()))try{await oh("creative-brain-rag",{action:"sync",workspaceId:r,documents:t})}catch(i){Xy("[CbRAG] sync failed:",i instanceof Error?i.message:i)}}async function oS(r,t,i=6,a=2400){if(!r||!Fl()||!t.trim())return"";try{const u=await oh("creative-brain-rag",{action:"query",workspaceId:r,query:t.trim(),topK:i}),p=u&&typeof u=="object"?u.context:null,f=typeof p=="string"?p.trim():"";if(!f)return"";if(f.length<=a)return f;const x=Math.max(16,Math.floor(a*.65)),S=Math.max(16,a-x-30);return`${f.slice(0,x)} 26 27...(RAG truncated)... 28 29${f.slice(-S)}`}catch(u){return Xy("[CbRAG] query failed:",u instanceof Error?u.message:u),""}}const iS=`You write ultra-short episode loglines for a series bible. 30Return ONLY valid JSON (no markdown). Schema: 31{"episodes":[{"i":0,"s":"one sentence"}]} 32Rules: 33- Keys: i = 0-based index matching the input order, s = one concise storyline sentence (max ~220 chars). 34- Same language as the series context (logline/synopsis). 35- Do not add episodes; only fill indices you receive. 36- If an episode title is a placeholder with no story yet, still infer a plausible beat from the season arc. 37- If a "Locked entities" section exists, do NOT rename, add, remove, or replace any character, relationship, scene, or prop entities listed there. 38- Do NOT use role labels like 主è§/é è§/æ£æ´¾/åæ´¾ or protagonist/supporting/hero/villain/antagonist in output sentences. 39- Never output marker syntax such as [[CHAR:...]], [[SCENE:...]], [[PROP:...]], or @@Name in final sentences. 40- Use complete explicit names in narration; avoid vague role references like "对æ¹é¦é¢".`;function zf(r){const t=String(r||"").trim();if(!t)throw new Error("EMPTY");const i=new Set;i.add(t);const a=t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);a!=null&&a[1]&&i.add(a[1].trim());const u=t.match(/\{[\s\S]*\}/);u!=null&&u[0]&&i.add(u[0].trim());for(const p of i)try{return JSON.parse(p)}catch{}throw new Error("PARSE_FAILED")}async function vl(r){const{logline:t,synopsis:i,worldExcerpt:a,episodes:u,lockedEntitiesText:p,chatContextText:f}=r;if(u.length===0)return[];const x=$=>{const O=$.map(D=>`${D.index}: ${(D.title||"").trim()||`Episode ${D.index+1}`}`).join(` 41`);return`## Series context 42Logline: 43${t.trim()||"â"} 44 45Synopsis: 46${i.trim()||"â"} 47 48World (excerpt): 49${a.trim()||"â"}${f!=null&&f.trim()?` 50 51## Homepage BloomBot dialogue context (must follow) 52${f.trim()}`:""}${p!=null&&p.trim()?` 53 54## Locked entities (must remain unchanged) 55${p.trim()}`:""} 56 57## Episodes (index: title) 58${O} 59 60Produce JSON only.`},S=$=>{const O=$==null?void 0:$.episodes;if(!Array.isArray(O))throw new Error("Invalid episode summary response.");const D=[];for(const n of O){if(!n||typeof n!="object")continue;const z=n.i,Z=n.s;typeof z!="number"||z<0||!Number.isFinite(z)||typeof Z!="string"||!Z.trim()||D.push({index:Math.floor(z),summary:Z.trim()})}return D},k=async $=>{const O=x($),D=()=>eb(O,"google/gemini-3.1-pro-preview",iS,2048,.35,void 0,void 0,void 0,"SCRIPT");try{const n=await D(),z=zf(n);return S(z)}catch{try{const n=await D(),z=zf(n);return S(z)}catch{throw new Error("Could not parse episode summaries. Please retry.")}}},v=16,I=new Map;for(let $=0;$<u.length;$+=v){const O=u.slice($,$+v),D=new Set(O.map(z=>z.index)),n=await k(O);for(const z of n)D.has(z.index)&&z.summary.trim()&&I.set(z.index,z.summary.trim())}return[...I.entries()].map(([$,O])=>({index:$,summary:O})).sort(($,O)=>$.index-O.index)}const aS=56;function lS(r){const t=r.map(p=>
60p.trim()).filter(Boolean);if(t.length===0)return{variant:"text",items:[]};const i=t.some(p=>p.length>aS),a=t.every(p=>/^\d+[\s.ï¼ã:ï¼\)ï¼]\s*\S/.test(p));return i||t.length>=2&&a?{variant:"numbered",items:t.map((p,f)=>{const x=p.match(/^(\d+)[\s.ï¼ã:ï¼\)ï¼]\s*(.*)$/s),S=x?x[1]:String(f+1),k=(x?x[2]:p).trim();return{sendText:p,label:S,title:k||p}})}:{variant:"text",items:t.map(p=>({sendText:p,label:p}))}}const Wn="[[STORYFLOW_STRUCTURE_JSON]]",zn="[[/STORYFLOW_STRUCTURE_JSON]]",cS="[[GREENLIGHT_STRUCTURE_JSON]]",dS="[[/GREENLIGHT_STRUCTURE_JSON]]";function uS(r){if(!r)return null;const t=r;return!String(t.seriesTitle||"").trim()&&String(t.serieTitle||"").trim()&&(t.seriesTitle=String(t.serieTitle).trim()),r}function lh(r){const t=r.trim();if(!t)return null;const i=t.replace(/^```(?:json)?\s*/i,"").replace(/```$/i,"").trim(),a=[i],u=i.indexOf("{"),p=i.lastIndexOf("}");u>=0&&p>u&&a.push(i.slice(u,p+1));for(const f of a)try{const x=JSON.parse(f);if(x&&typeof x=="object")return uS(x)}catch{}return null}function pS(r,t,i){const a=r.indexOf(t);if(a===-1)return null;const u=r.indexOf(i,a+t.length);if(u===-1)return null;const p=r.slice(a+t.length,u).trim(),f=lh(p);return{cleanedText:`${r.slice(0,a).trim()} 61${r.slice(u+i.length).trim()}`.trim(),payload:f}}function mS(r,t){const i=r.indexOf(t);if(i===-1)return null;const a=r.slice(i+t.length).trim(),u=lh(a);return{cleanedText:r.slice(0,i).trim(),payload:u}}function Cl(r){for(const[t,i]of[[Wn,zn],[cS,dS]]){const a=pS(r,t,i);if(a)return a;const u=mS(r,t);if(u)return u}return{cleanedText:r.trim(),payload:null}}function Kf(r,t){if(!(r!=null&&r.length)||!t)return null;for(const i of r){const a=String(i||"").trim();if(!a)continue;const u=t[a];if(typeof u=="string"&&/^https?:\/\//i.test(u.trim()))return u.trim()}return null}function fS(r){const t=Kf(r.scenes,r.sceneMediaByName);return t||Kf(r.characterNames,r.characterMediaByName)}const an=!0;function yS(r){return"workspace"}function hS(r){return an}const gS=12,xS=40,bS=15,wS=1,SS=20,kS=2,oa=[{id:"modern_urban",label:"Modern urban",labelZh:"ç°ä»£é½å¸"},{id:"period",label:"Period / historical",labelZh:"å¤ä»£ / åå²"},{id:"fantasy",label:"Fantasy",labelZh:"å¥å¹»"},{id:"thriller",label:"Thriller / suspense",labelZh:"æ¬ç / ææ"},{id:"comedy",label:"Comedy",labelZh:"åå§"},{id:"rural_era",label:"Rural / historical era",labelZh:"乡æ / 年代"},{id:"sci_fi",label:"Sci-fi",labelZh:"ç§å¹»"},{id:"other_professions",label:"Other (legal, medical, militaryâ¦)",labelZh:"å ¶ä»ï¼æ³å¾ãå»çãåäºâ¦ï¼"},{id:"custom",label:"Custom",labelZh:"èªå®ä¹"}];function Yd(r,t="en"){const i=oa.find(a=>a.id===r);return i?t==="zh"?i.labelZh:i.label:""}function aa(r){const t=String(r||"").trim();if(!t)return"";const i=t.toLowerCase();return/乡æ|年代|æ°å½|ç¥é|æé©|ä¸ä¹¡|æé|rural/i.test(t)?"rural_era":/æ¬ç|ææ|æ¨ç|ç¯ç½ª|thriller|suspense|mystery|crime/i.test(t)?"thriller":/åå§|æç¬|comedy|funny/i.test(t)?"comedy":/ç§å¹»|æªæ¥|èµå|空é´ç«|轨é|æé |æç|sci[\s-]?fi|science fiction|cyber/i.test(t)?"sci_fi":/å¤ä»£|å¤è£ |æä»£|宫廷|period drama|dynasty|ancient/i.test(t)?"period":/å¥å¹»|çå¹»|ä»ä¾ |éæ³|fantasy|magic/i.test(t)?"fantasy":/ç°ä»£|é½å¸|èåº|豪é¨|å®¶æå ¬å¸|urban|city|corporate|office/i.test(t)?"modern_urban":/æ³å¾|å»ç|åäº|å¾å¸|å»ç|æ³åº|hospital|military|legal|medical/i.test(t)?"other_professions":/æ¥ç³»|æ¥å¼|åé£|japanese|anime/i.test(i)?"custom":""}function qf(r){const t=(r.storyOutline.logline||"").trim().length>=gS&&(r.storyOutline.synopsis||"").trim().length>=xS,i=Ho.every(v=>(r.worldBible[v]||"").trim().length>=bS),a=r.seriesBibleCharacters.length>0&&r.seriesBibleCharacters.every(v=>(v.name||"").trim().length>=wS&&(v.backstory||"").trim().length>=SS),u=(r.seriesTitle||"").trim(),p=u.length>=kS&&!ws(u),f=typeof r.plannedEpisodeCount=="number"&&Number.isFinite(r.plannedEpisodeCount)&&r.plannedEpisodeCount>=1&&r.plannedEpisodeCount<=100,x=!!r.dramaCategoryId&&(r.dramaCategoryId!=="custom"||(r.dramaCustomNote||"").trim().length>=8),S=!!r.styleLocked;return{storyArcReady:t,worldBibleReady:i,charactersReady:a,titleReady:p,episodePlanReady:f,dramaReady:x,styleLocked:S,allFoundationReady:t&&i&&a&&p&&f&&x&&S}}const vS={script:"å§æ¬",storyboard:"èªå¨åé",imageGen:"å¾åçæ",image:"å¾ç",videoGen:"è§é¢çæ",video:"è§é¢",promptOptimizer:"æç¤ºè¯ä¼å",referenceUpload:"åèä¸ä¼ ",assetLibrary:"èµäº§åº",textShotList:"æååéå表",music:"声é³",avatar:"æ°å人",render:"渲æ",generate:"çæ"},CS={script:"Script",storyboard:"Storyboard",imageGen:"Image Gen",image:"Image",videoGen:"Video Gen",video:"Video",promptOptimizer:"Prompt Opt.",referenceUpload:"Reference Upload",assetLibrary:"Asset Library",textShotList:"Text Shot List",music:"Audio",avatar:"Avatar",render:"Render",generate:"Generate"};function Nl(r,t){return`${vS[r]}ï¼${CS[r]}ï¼`}function Dl(r,t){return r==="storyflow"?t==="zh"?"ç¼å§å°":"SCRIPT":t==="zh"?"å·¥ä½å°":"WORKFLOW"}const ch=/å|çæ|åä½|æ¹å|æ©å|润è²|ææ|å®å|è¡¥é½|è¡¥å ¨|设计è§è²|è§è²è®¾å®|ä¸çè§|大纲|åé|å§æ¬|å°è¯|åé|æ äº|synopsis|logline|write|generate|create|rewrite|polish|expand|brainstorm|refine|complete|character|world|episode|script|screenplay|outline|story/i,NS=/ä¸ä¸æ¥|æ¥ä¸æ¥|ç¶åå¢|ç°å¨åä»ä¹|该åä
61»ä¹|æä¹ç»§ç»|next step|what next|continue/i,ES=/缺ä»ä¹|è¿ç¼º|æ²¡å®æ|éè¦è¡¥|åªäºæ²¡å¥½|missing|incomplete|what.*missing/i,TS=/story workspace|æ
äºå·¥ä½åº|è¿å
¥å·¥ä½åº|continue to story workspace|workspace/i,RS=/workflow|工使µ|å·¥ä½å°|å»çæ|å¼å§å¶ä½|start production|go to workflow|ç产/i,jS=/ç¶æ|è¿åº¦|宿äºå|åå¤å¥½äºå|å½å|status|progress|ready/i,AS=/æé®|åºå«|为ä»ä¹|ç¹åªä¸ª|æä¹é|button|difference|which|choose/i,IS=/^(ä½ å¥½|æ¨å¥½|å¼å§|å¼å§å§|帮æå¼å§|hello|hi|start|let'?s start)$/i,PS=/^(请)?(帮æ)?(å建|æå»º|å¼å§).*æ
äºå¤§çº²|^å建æ
äºå¤§çº²[:ï¼]?$|story outline starter/i,_S=/^(æå»ºä¸çè§|build\s+world\s+bible|请帮ææå»º(?:è¿ä¸ª)?æ
äºçä¸çè§)\s*$/i,BS=/ä¸çè§\s*(?:æ¯|为|å¨|å°±|åºè¯¥|叿|åºäº|æç
§)|(?:æ¶ä»£|å°ç¹|è§å|éå¶|大æ|æå|å¹´å|æ«ä¸|åµå°¸|æ²æµ·|è®°å¿|ç¬¬ä¸æ¬¡)/i,MS=/帮æ(å®å|宿|è¡¥é½|è¡¥å
¨|ææ)|䏿¬¡æ§|å
¨é¨|ä¸èµ·|åæ¶.*(大纲|ä¸çè§|è§è²)|(?:大纲|ä¸çè§|è§è²).*(?:å|ä¸|å).*(?:大纲|ä¸çè§|è§è²)|complete\s+(?:all|everything)|refine\s+(?:all|everything)|fill\s+(?:all|everything)/i,dh=/(?:请)?帮æ(å|çæ|åä½|ææ)|åä¸(?:个|é¨)|çæ.*æ
äº|æ«ä¸|åµå°¸|zombie|apocal
61ypse/i,LS=/ä¼å.*å£|ä¼åæ´å£|å£èå¥|season structure|episode order|narrative role|tension curve/i,OS=/èµäº§åº|è§è²èµäº§|åºæ¯èµäº§|éå ·èµäº§|asset library|character assets|scene assets|prop assets/i,$S=/æ äº|å ³äº|è¦æ±|飿 ¼|æ¥ç³»|éå¿|è®°å¿|å¤é|èå¹´|çå§|é½å¸|ç±æ |æ¬ç|ææ|åå§|乡æ|年代|ç§å¹»|å¥å¹»|æ¦ä¾ |ä»ä¾ |å¤ä»|éè¢|豪é¨|ååé|çåé|å®¶æ|å ¬å¸|ç·ä¸»|女主|主è§|protagonist|heroine|hero|story|about|style|memory|forget|forgotten|romance|thriller|comedy|sci-fi|fantasy|revenge|rival/i,FS=/\d+\s*é|\d+\s*(?:ç§|s|sec|seconds)|\d+\s*episodes?/i,DS=/ç·ä¸»|女主|主è§|ç®æ |æ³è¦|å¤é|protagonist|heroine|hero|goal|wants?/i,uh=/å·²æäº¤(?:æ äºæµ|ç¼å§å°)填空|StoryFlow fill card submitted|SCRIPT fill card submitted/i,ph=/宿´|详ç»|æ¯é(?:å§æ |大纲|å§æ¬|åé|详æ )|ä¸å¹|对ç½|åé表|ç´æ¥çæ|è¶å®æ´è¶å¥½|full|detailed|episode-by-episode|dialogue|storyboard/i,US={styleLocked:{zh:"è§è§é£æ ¼ï¼Visual styleï¼",en:"Visual style"},dramaReady:{zh:"å§éç±»åï¼Drama categoryï¼",en:"Drama category"},storyArcReady:{zh:"æ äºä¸»çº¿ï¼Story outlineï¼",en:"Story outline"},titleReady:{zh:"å§éæ é¢ï¼Series titleï¼",en:"Series title"},worldBibleReady:{zh:"ä¸çè§è®¾å®ï¼World bibleï¼",en:"World bible"},charactersReady:{zh:"è§è²è®¾å®ï¼Charactersï¼",en:"Characters"},episodePlanReady:{zh:"éæ°ä¸åéæ¶é¿ï¼Episode count & durationï¼",en:"Episode count and duration"},allFoundationReady:{zh:"å ¨é¨åºç¡å段ï¼All foundation fieldsï¼",en:"All foundation fields"}},WS={zh:"å ¨çæ¶é¿ï¼Full film runtimeï¼",en:"Full film runtime"},HS=["styleLocked","dramaReady","storyArcReady","titleReady","worldBibleReady","charactersReady","episodePlanReady"];function Ms(r){return r.standaloneFilmMode===!0}function zS(r,t){const i=r.locale==="zh"?"zh":"en";return t==="episodePlanReady"&&Ms(r)?WS[i]:US[t][i]}function _u(r){return HS.filter(t=>!r.readiness[t]).map(t=>zS(r,t))}function mh(r){return _u(r)[0]||""}function ks(r){return r.map(t=>`- ${t}`).join(` 62`)}function fh(r){return r.readiness.styleLocked===!1&&r.readiness.storyArcReady&&r.readiness.worldBibleReady&&r.readiness.charactersReady&&r.readiness.titleReady&&r.readiness.episodePlanReady&&r.readiness.dramaReady}function yh(r){const t=String(r||"").trim();return t?!!(MS.test(t)||BS.test(t)||dh.test(t)||t.length>=220||t.length>=80&&/[ï¼ãï¼ï¼ï¼,.!?]/.test(t)||t.includes(` 63`)||/@@|%%|\$\$|\[\[/.test(t)||ph.test(t)):!1}function KS(r){const t=r.trim();return yh(t)?null:IS.test(t)?"starter":uh.test(t)?"next_step":LS.test(t)?"season_optimize_starter":OS.test(t)?"assets_starter":_S.test(t)?"world_bible_starter":PS.test(t)?"outline_starter":$S.test(t)&&(FS.test(t)||DS.test(t))&&!dh.test(t)&&!ch.test(t)&&!ph.test(t)&&t.length<=120?null:RS.test(r)?"workflow_gate":TS.test(r)?"workspace_gate":ES.test(r)?"missing_foundation":AS.test(r)?"button_difference":jS.test(r)?"status":NS.test(r)?"next_step":null}function qS(r,t){const i=_u(r),a=mh(r),u=Dl("storyflow","zh"),p=Dl("workflow","zh"),f=Nl("script"),x=Nl("assetLibrary"),S=`åå¾${p}ï¼Go to WORKFLOWï¼`;if(!r.talkExtractActive&&fh(r)&&t!=="button_difference")return"ä½ ç°å¨åªå·®ãè§è§é£æ ¼ï¼Visual styleï¼ãè¿ä¸é¡¹ãå 宿飿 ¼éæ©ï¼ç¶åç»§ç»å¨å¯¹è¯ä¸å®å大纲ä¸åéï¼å¾ç请ç¨åå¨å³ä¾§ Tab ç¹å»å¡ç设计ã";if(r.talkExtractActive&&(t==="next_step"||t==="status"))return r.readiness.allFoundationReady?"åºç¡è®¾å®ï¼å¤§çº²+ä¸çè§ï¼å·²é½ã请å¨ãåéååºãTab ååºåºå表ï¼å¨ãèµäº§åºãTab å @@ / åºæ¯ / éå ·ï¼è天éä¸å追é®ç»ææ«èã":"ç»§ç»å¨å¯¹è¯éæ¹ç¨¿å³å¯ã空æ ä¼å¨åå°è¡¥ä¸ï¼æ¹æªäºç´æ¥æ¹å³ä¾§è§åæ ã";if(t==="missing_foundation")return r.bloomBotMode==="episode_unit"?r.readiness.allFoundationReady?"ä½ å·²å¨ãåéååºã模å¼ã请éä¸å·¦ä¾§æ äºæ éçä¸åºï¼æåè¯æãå第 N é第 M åºãï¼æä¼åºäºå¤§çº²åä¸çè§è¡¥è¯¦ç»å 容ã":"åéååºåä½éè¦å æå¤§çº²åä¸çè§ã请ååãå§æ 大纲 / ä¸çè§ãTab ä¸ BloomBot è¡¥å ¨åºç¡è
63®¾å®ã":i.length?`è¿ç¼ºè¿äºåºç¡åæ®µï¼ 64${ks(i)} 65 66建议å è¡¥ã${a}ããè¡¥é½ååç»ååéæ´ç¨³å¦¥ã`:`åºç¡å段已é½å ¨ã请继ç»å¨å¯¹è¯ä¸ç»ååéï¼å¹¶åå¤è¡æ¥${p}ã`;if(t==="workspace_gate")return r.readiness.allFoundationReady?"åºç¡è®¾å®å·²é½ã请åå°ãåéååºãååºåºããèµäº§åºãåè§è§èµäº§ï¼ä¸è¦å¨è天éå夿 大纲/ä¸çè§ç»èã":`请å è¡¥ã${a}ãï¼é¿å åéä¸${Nl("assetLibrary")}è¿å·¥ã`;if(t==="workflow_gate")return r.hasEpisodes?r.readiness.allFoundationReady?`å¯ä»åéå¡çè¿å ¥${p}ã建议第 ${r.selectedEpisodeNumber} éï¼ç¹å»ã${S}ãï¼è¿å ¥åå æ£æ¥${f}ä¸${x}èç¹ã`:`请å å«è¿å ¥${p}ã建议补ã${a}ãï¼å¦åèç¹é¾è·¯æç¼ºè§è²ãä¸çè§ææ¶é¿ä¿¡æ¯ã`:`æä¸è½ç¨³å®è¿å ¥${p}ã请å çææç¡®è®¤è³å°ä¸éåéå¡çã`;if(t==="status")return r.readiness.allFoundationReady?`å½åç¶æï¼åºç¡è®¾å®å·²å°±ç»ªã 67${ks([Ms(r)?"æ ¼å¼ï¼åççµå½±ï¼1 é¨ï¼":`计åéæ°ï¼${r.episodeCount}`,r.hasEpisodes?Ms(r)?"详ç»å§æ¬ï¼å·²æ":"åéå¡çï¼å·²æ":Ms(r)?"详ç»å§æ¬ï¼å°æ ":"åéå¡çï¼å°æ ",r.hasDashboard?"æ»è§åæï¼Overviewï¼ï¼å·²æ":"æ»è§åæï¼Overviewï¼ï¼æªçæ"])}`:`åºç¡è®¾å®å°æªå®æã 68è¿ç¼ºï¼ 69${ks(i)} 70 71ä¸ä¸æ¥å å¤çã${a}ãã`;if(t==="button_difference")return`ç®åå¤æï¼ 72- 左侧对è¯ï¼æ´çæ äºãä¸çè§ä¸åé大纲ã 73- ã${S}ãï¼æä¸éå·²å®ç¨¿åï¼ç»èç¹é¾è·¯å¶ä½è§é¢ã 74 75åºç¡å段æªé½æ¶ä¼å çå¨${u}ï¼æä¸éå®ç¨¿ååè¿${p}ã`;if(t==="starter")return r.talkExtractActive?r.readiness.allFoundationReady?"ä½ å¥½ãåºç¡å·²é½ï¼ç»§ç»å¨å¯¹è¯éæ¹ç¨¿å³å¯ï¼æ¹æªäºç´æ¥æ¹å³ä¾§è§åæ ã":"ä½ å¥½ãç´æ¥åä¸ä¸ªæ äºæ³æ³ï¼é¢æã主è§ãå²çªï¼ï¼æä¼å¸®ä½ èµ·è并忥å°å³ä¾§è§åæ ã":r.readiness.allFoundationReady?"å¯ä»¥ç»§ç»ã大纲åä¸çè§å·²é½ï¼è¯·åå°ãåéååºãååºåºï¼ãèµäº§åºãå
75è§è²/åºæ¯/éå ·ï¼ä¸è¦å¨è天éå夿 ç»èã":`å¯ä»¥ï¼æä»¬å è¡¥é½${u}åºç¡è®¾å®ãç¬¬ä¸æ¥å»ºè®®ã${a}ããä¹å¯ç´æ¥åä¸å¥æ äºæ³æ³ï¼æä¼æ´çææ äºä¸»çº¿ï¼Story outlineï¼ã`;if(t==="outline_starter")return["å¯ä»¥ï¼å 仿 äºå¤§çº²ï¼Story outlineï¼å¼å§ã为é¿å é¦è½®è·åï¼è¯·å ç»ä¸å¥æç颿æçµæï¼",ks(["ä¸»è§æ¯è°ï¼","ä»/她æ³è¦ä»ä¹ï¼","æå¤§é»ç¢æ¯ä»ä¹ï¼","ææé¢æææ 绪ï¼"]),"示ä¾ï¼ç°ä»£é½å¸ç±æ çå§ï¼å¥³ä¸»ä¸ºååéï¼ç®æ æ¯å¤ºåå®¶æå ¬å¸ï¼ç·ä¸»èµ·å为对æã"].join(` 76 77`);if(t==="premise_starter"){const k=Ms(r)?"å ¨çæ¶é¿ï¼å¦ 90 / 120 åéï¼æä½ ææççé¿ï¼":"鿰䏿¶é¿ï¼å¦ 6 / 12 / 24 éï¼æ¯é 60 / 120 / 180 ç§";return[`æ¶å°ï¼è¯¥é¢æå¯å æ´ç为${u}åºç¡è®¾å®ãç´æ¥å¨å¯¹è¯éè¡¥å å³å¯ï¼æä¼åæ¥å°å³ä¾§è§åæ ï¼`,ks(["æ äºä¸»çº¿ï¼ä¸»è§ç®æ ãæå¤§é»ç¢ãç»å±èµ°å","ä¸çè§ï¼æ¶ä»£/å°ç¹ãè§å䏿 ¸å¿å²çª","è§è²ï¼ä¸»è§ã对ææçåçä¸å¥è¯è®¾å®",k]),"ä½ å¯ä»¥ä¸æ¬¡è¯´å®ï¼ä¹å¯ä»¥åå æ¡æ¶æ¯è¡¥å ï¼ä¸å¿ 填表ã"].join(` 78 79`)}if(t==="world_bible_starter")return"å¯ä»¥ï¼å æä¸çè§ï¼World bibleï¼ã请ç¨ä¸ä¸¤å¥è¯è¯´ææ¶ä»£/å°ç¹ä¸ä¸æ¡æ ¸å¿è§åï¼è¥ä½ å·²å¨å¯¹è¯éåè¿è®¾å®ï¼ç´æ¥ç²è´´æè¡¥å å³å¯ï¼æä¼æ´ç为å°çãåå²ãè§åãæå䏿 ¸å¿å²çªå¹¶åæ¥å°å³ä¾§è§åææ¡£ã";if(t==="season_optimize_starter")return r.hasEpisodes?`å¯ä»¥ä¼åæ´å£ç»æãå½å计å ${r.episodeCount} éãè¯·è¯´æææ å¿çé®é¢ï¼èå¥åå¹³ã髿½®åæãè§è²çº¿æ··ä¹±ï¼æåé顺åºã`:"ææ æ³ä¼åæ´å£ç»æï¼å°æ åéå¡çã请å 宿æ äºå¤§çº²ä¸åéå表ã";if(t==="assets_starter"){const k=Nl("assetLibrary");return r.hasEpisodes?`å¯ä»¥å¼å§${k}è§åã请å éä¼å æ¹åï¼è§è²åèãåºæ¯åèæå ³é®éå ·ï¼æä¼æå¶ä½ä¼å 级æ´çæ¸ åã`:`${k}建议å¨åéå表确å®åååã请å 宿æ äºå¤§çº²ãä¸çè§ä¸åéå¡çï¼åå°è§è²/åºæ¯/éå ·è¿å·¥ã`}return r.readiness.allFoundationReady?r.bloomBotMode==="episode_unit"?"ä¸ä¸æ¥ï¼æ©åå½åéä¸åºç beat æè¦ææè¿°å¼åºæ£æï¼å¤§çº²ä¸ä¸çè§ä¿æéå®ï¼é¤éååå ¶ä» Tabã":"ä¸ä¸æ¥ï¼å¨ãåéååºãTab è¾åºåºåºå表ï¼å¨ãèµäº§åºãTab è¡¥ @@ / åºæ¯ / éå ·ãè天éä¸å追é®å¤§çº²/ä¸çè§ç»èã":`ä¸ä¸æ¥åªåä¸ä»¶äºï¼è¡¥ã${a}ãã宿åç»§ç»å®ååé大纲ã`}function GS(r,t){const i=_u(r),a=mh(r),u=Dl("storyflow","en"),p=Dl("workflow","en");if(!r.talkExtractActive&&fh(r)&&t!=="button_difference")return"You are only missing one item now: visual style. Finish style selection, then keep refining the outline and episodes in chat. Design images later from the right-hand tabs.";if(r.talkExtractActive&&(t==="next_step"||t==="status"))return r.readiness.allFoundationReady?"Foundation (outline + world bible) is ready. Use the Episodes tab for scene beat lists and the Assets tab for @@ / scenes / props â stop micro-plot interview loops in chat.":"Keep editing the draft in chat. Empty notebook fields fill in quietly â change anything that looks off on the right panel.";if(t==="missing_foundation")return r.bloomBotMode==="episode_unit"?r.readiness.allFoundationReady?"You are in Episodes & sequences mode. Select a scene in the story tree, or ask for âEpisode N Scene Mâ, and I will expand beats using the locked outline and world bible.":"Scene-level writing needs plot outline and world bible first. Switch to Plot outline or World bible tabs to finish foundation with BloomBot.":i.length?`These foundation fields are still missing: 80${ks(i)} 81 82Start with "${a}" first. Once these are ready, ${u} can refine episodes safely.`:`All foundation fields are ready. Next, refine episodes in chat and prepare the ${p} handoff.`;if(t==="workspace_gate")return r.readiness.allFoundationReady?"Foundation is ready. Keep refining episode outlines in chat; open the design window from the right tabs for images.":`Complete "${a}" first to avoid rework in episodes and assets.`;if(t==="workflow_gate")return r.hasEpisodes?r.readiness.allFoundationReady?`You can enter ${p} from an episode card. I recommend Episode ${r.selectedEpisodeNumber}; after opening it, check the Script and Asset Library nodes first.`:`Do not jump to ${p} yet. Complete "${a}" first, otherwise the node chain may miss character, world, or duration context.`:`${p} is not ready yet. Create or confirm at least one episode card first.`;if(t==="status")return r.readiness.allFoundationReady?`Current status: foundation is ready. 83${ks([Ms(r)?"Format: standalone film (1 film)":`Planned episodes: ${r.episodeCount}`,r.hasEpisodes?Ms(r)?"Detailed script: available":"Episode cards: available":Ms(r)?"Detailed script: not yet":"Episode cards: not created yet",r.hasDashboard?"Overview anal
83ysis: available":"Overview analysis: not generated yet"])}`:`The foundation is not complete yet. 84Missing: 85${ks(i)} 86 87Next, handle "${a}" first.`;if(t==="button_difference")return`Simple rule: 88- Left chat: organize story, world bible, and episode outlines. 89- âGo to ${p}â: produce one confirmed episode through the node chain. 90 91If the foundation is incomplete, stay in ${u}. If one episode is locked, go to ${p}.`;if(t==="starter")return r.talkExtractActive?r.readiness.allFoundationReady?"Hi. Foundation is ready â keep editing the draft in chat; fix anything off on the right panel.":"Hi. Send a story idea (genre, lead, conflict) and I will draft it and sync the right-hand plan.":r.readiness.allFoundationReady?"We can continue. Foundation is ready â keep refining episode outlines in chat.":`Sure. Let us complete the ${u} foundation first. I recommend starting with "${a}". You can also send one story idea, and I will help shape it into the story outline.`;if(t==="outline_starter")return["Sure. Let us start with the story outline. To avoid a drifting first draft, send one short premise first:",ks(["Who is the protagonist?","What do they want?","What is the main obstacle?","What genre or mood do you want?"]),"Example: a modern urban romance where the heroine is a false heiress trying to reclaim the family company, and the male lead starts as her rival."].join(` 92 93`);if(t==="premise_starter"){const f=Ms(r)?"Full film runtime: e.g. 90 or 120 minutes":"Episode plan: confirm 6, 12, or 24 episodes; 60s / 120s / 180s each";return[`Got it. We can shape this into ${u} foundation fields through chat â I will sync the board quietly:`,ks(["Story outline: protagonist goal, main obstacle, ending direction","World bible: era/place, rules, core conflict","Characters: leads and key rivals in one line each",f]),"Send one message or several; no form card needed."].join(` 94 95`)}return t==="world_bible_starter"?"Sure. Let us build the world bible. Share era/location and one core rule in one or two sentencesâor paste what you already wrote in chat. I will organize geography, history, rules, culture, and core conflict and sync to the planning doc.":t==="season_optimize_starter"?r.hasEpisodes?`We can optimize the season structure. Current plan: ${r.episodeCount} episodes. Tell me the main concern: flat pacing, climax too late, messy character arcs, or episode order.`:"Season optimization is not ready yet because there are no episode cards. Finish the outline and episode list first, then come back for pacing optimization.":t==="assets_starter"?r.hasEpisodes?"We can start asset planning. Pick one priority: character references, scene references, or key props. I will organize the asset list by production priority.":"Asset planning works best after the episode list is set. Finish the outline, world bible, and episode cards first so character, scene, and prop assets do not churn.":r.readiness.allFoundationReady?r.bloomBotMode==="episode_unit"?"Next: expand the selected sceneâs beat summary or descriptive unit script. Outline and world bible stay locked unless you switch tabs.":"Next: scene beat lists in the Episodes tab; @@ / scene / prop work in the Assets tab. Do not keep drilling outline/world micro-details in chat.":`Next step: do one thing first â complete "${a}". After that, continue refining episode outlines.`}function Gf(r){const t=String(r.message||"").trim();if(!t)return null;const i=KS(t);if(!i||r.bloomBotMode==="episode_unit"&&(i==="outline_starter"||i==="world_bible_starter"||i==="assets_starter")||r.talkExtractActive&&(i==="premise_starter"||i==="outline_starter"||i==="world_bible_starter"||i==="missing_foundation")||ch.test(t)&&!uh.test(t)&&i!=="outline_starter"&&i!=="premise_starter"&&i!=="world_bible_starter"&&i!=="season_optimize_starter"&&i!=="assets_starter")return null;const a=r.locale==="zh"?"zh":"en";return{intent:i,text:a==="zh"?qS(r,i):GS(r,i)}}function bs(r){return r==="episodes"?"episode_unit":"foundation"}function YS(r){switch(r){case"world":return"world_bible";case"episodes":return"episode_board";case"assets":return"assets";case"outline":default:return"outline"}}function VS(r){return r.uiPhase==="immersive"?"all":r.uiPhase==="workspace"?YS(r.layoutTab):r.isBeginnerGuidedMode?r.guidedStep:"all"}function Vd(r){return r.inEpisodeScriptContext?r.missingFoundationCount>0:r.bloomBotMode==="episode_unit"}function XS(r){const t=`Tab: ${r.layoutTab}`,i=`Selected hierarchy node: ${r.hierarchySelectedId||"(none)"}`,a=r.mode==="foundation"?`## BloomBot mode: FOUNDATION (åºç¡è®¾å®) 96Scope: plot outline, world bible, and asset library (@@ characters, [[SCENE:]], [[PROP:]]). 97Do NOT draft full episode/scene scripts or long beat-by-beat screenplay here unless the user explicitly asks. 98**Until synopsis + all five world-bible fields are filled on the board:** do NOT output a full N-episode storyline board (åéå§æ æ¿). Prefer completing missing foundation + [[OPTIONS]] next steps; at most 1â2 sample episode rows if the user insists. 99Honor the active Layout tab: 100- outline â logline, synopsis, theme, season/film shape 101- world â five world-bible dimensions consistent with the outline 102- assets â visual bible markers only; no episode list rewrites`:`## BloomBot mode: EPISODE / SCENE (åéååº) 103Scope: expand **one episode or scene at a time** using the locked plot outline + world bible as canon. 104Do NOT rewrite title, logline, synopsis, world bible, or restart foundation interview unless the user explicitly asks. 105Output target: 106${r.sequenceBeatSyncEnabled?"- Scene beat rows: `episodes[i].sequences[]` or prose `åºN | one-line beat` (not full screenplay)\n- Optional `actId` 1â3 for film acts\n- No Shot N / dialogue script lists unless user explicitly requests script mode":`- Episode summaries, sequence labels, beat summaries, and descriptive unit scripts for the selected scene 107- Honor existing hierarchy; fill empty units before inventing new episodes`}`;let u="";if(r.mode==="episode_unit"&&r.selectedUnit){const p=r.selectedUnit;u=` 108Focus unit: Episode ${p.episodeIndex+1} · ${p.unitLabel}${p.episodeTitle?` (${p.episodeTitle})`:""}${p.beatSummary?` 109Current beat summary: ${p.beatSummary}`:""} 110Write or refine **this unit only** unless the user names another scene. This chat is keyed to the selected story-tree node.`}else r.mode==="episode_unit"&&(u=` 111No scene selected in the story tree â default **BREAKDOWN** mode: help split the film/series into acts, episodes, and sequences (compact beat list / hierarchy). Do NOT draft a full descriptive script for one unit until the user selects that unit in the story tree.`);return`${a} 112 113## Active Storyflow layout 114${t} 115${i}${u}`}function JS(r){if(r.mode==="foundation"){const i=r.layoutTab==="outline"?"Work on plot outline fields only.":r.layoutTab==="world"?"Work on world bible dimensions only.":"Work on asset visual bible (@@ / [[SCENE:]] / [[PROP:]]) only.";return`Storyflow BloomBot is in FOUNDATION mode (${r.layoutTab} tab). ${i}
115 Do not output episode-by-episode screenplay, scene shot lists, or a full N-episode åéå§æ
æ¿ until synopsis + world bible are on the board. If length-limited, stop on a whole-episode boundary and offer a Continue chip.`}return`Storyflow BloomBot is in EPISODE/SCENE mode. ${r.selectedUnit?`Focus on Episode ${r.selectedUnit.episodeIndex+1} · ${r.selectedUnit.unitLabel}. Expand beat summary / descriptive unit content for this scene only.`:"No story-tree unit selected â BREAKDOWN mode: structure acts/episodes/sequences and beat lists only; do not write full unit scripts until a tree node is selected. Do not rewrite foundation fields."} Treat plot outline and world bible as locked canon.`}const Ul=3,Wl=8,Su=5;function la(r){return Math.min(Wl,Math.max(Ul,Math.round(r*10)/10))}function Yf(r=90){const t=Math.max(Ul,Math.round(Number(r)||90)),i=la(t/3);return[1,2,3].map((a,u)=>({index:u,label:"",targetMinutes:i,actId:a}))}function Vf(r,t,i){const a=Math.max(1,Math.round(Number(i)||0));return[{index:0,episodeIndex:r,label:"",targetMinutes:la(Math.min(a,Wl))}]}function QS(r){const t=Math.max(Ul,Math.round(Number(r)||0));if(t<=Wl)return[{index:0,label:"Sequence 1",targetMinutes:la(t),actId:1}];let i=Math.max(2,Math.round(t/Su)),a=t/i;for(;a>Wl&&i<24;)i+=1,a=t/i;for(;a<Ul&&i>2;)i-=1,a=t/i;const u=[];let p=t;for(let f=0;f<i;f+=1){const x=i-f,S=f===i-1?p:la(p/x);p=Math.max(0,Math.round((p-S)*10)/10);const k=(f+.5)/i,v=k<=.25?1:k<=.75?2:3;u.push({index:f,label:`Sequence ${f+1}`,targetMinutes:S,actId:v})}return u}const ZS=24;function Hl(r){const t=Number(r);
115if(t===2)return 2;if(t===3)return 3;if(t===1)return 1}function e0(r,t){let i=String(r||"").trim();return!i||t&&Bs(i)?"":i}function t0(r){let t=String(r||"").trim();return t?(t=t.replace(/^[-*â¢]\s+/,""),t=t.replace(/^\d+[.)]\s+/,""),t=t.replace(/^\*\*([^*]+)\*\*\s*/,"$1").trim(),t):""}function r0(r){const t=t0(r);if(!t)return null;const i=t.match(/^第\s*([123])\s*å¹[^|·\-ââ:]*[·\-ââ:]\s*åº\s*\d+(?:\.\d+)?\s*[|ï½:ï¼\-ââ]\s*(.+)$/i)||t.match(/^Act\s*([123])\s*[-ââ:]\s*Scene\s*\d+(?:\.\d+)?\s*[|ï½:ï¼\-ââ]\s*(.+)$/i);if(i){const p=Hl(i[1]),f=i[2].trim(),x=f.split(/[|ï½]/),S=(x[0]||f).trim(),k=x.length>1?x.slice(1).join("|").trim():void 0;return S?{label:S,beatSummary:k,actId:p}:null}const a=t.match(/^åº\s*(\d+)\.(\d+)\s*[|ï½:ï¼\-ââ]\s*(.+)$/i)||t.match(/^Scene\s*(\d+)\.(\d+)\s*[|ï½:ï¼\-ââ]\s*(.+)$/i);if(a){const p=Hl(a[1]),f=a[3].trim(),x=f.split(/[|ï½]/),S=(x[0]||f).trim(),k=x.length>1?x.slice(1).join("|").trim():S;return S?{label:S,beatSummary:k,actId:p}:null}const u=t.match(/^åº\s*\d+(?:\.\d+)?\s*[|ï½:ï¼\-ââ]\s*(.+)$/i)||t.match(/^Scene\s*\d+(?:\.\d+)?\s*[|ï½:ï¼\-ââ]\s*(.+)$/i);if(u){const p=u[1].trim(),f=p.split(/[|ï½]/),x=(f[0]||p).trim(),S=f.length>1?f.slice(1).join("|").trim():void 0;return x?{label:x,beatSummary:S}:null}return null}function Jl(r){const t=String(r||"").split(/\n/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of t){const u=r0(a);u&&i.push(u)}return i}function s0(r){const t=[];for(let i=0;i<r;i+=1){const a=(i+.5)/r;t.push(a<=.25?1:a<=.75?2:3)}return t}function n0(r,t){const i=e0(String(r.label||""),t);if(!i)return null;const a=String(r.beatSummary||"").trim()||void 0,u=Hl(r.actId);return{label:i,beatSummary:a,actId:u}}function ku(r){const t=r.standaloneFilmMode===!0,i=[];if(Array.isArray(r.jsonBeats))for(const u of r.jsonBeats){const p=n0(u,t);p&&i.push(p)}i.length===0&&r.text&&i.push(...Jl(r.text));const a=i.slice(0,ZS);if(t){const u=s0(a.length);return a.map((p,f)=>({...p,actId:p.actId??u[f]}))}return a.map(u=>({...u,actId:u.actId?Hl(u.actId):void 0}))}function Xo(r){return r.map((t,i)=>({...t,index:i}))}function o0(r,t){const i=Math.max(Su,Math.round(Number(t)||r*Su));return la(i/Math.max(1,r))}function i0(r,t={}){const i=o0(r.length,t.totalMinutes);return Xo(r.map((a,u)=>({index:u,label:a.label,beatSummary:a.beatSummary,actId:t.standaloneFilmMode?a.actId??1:a.actId,episodeIndex:t.episodeIndex,targetMinutes:i,status:"pending"})))}function vu(r){return String(r.descriptiveScript||"").trim().length>0}function hh(r,t){return String(r.label||"").trim()===String(t.label||"").trim()&&String(r.beatSummary||"").trim()===String(t.beatSummary||"").trim()&&(r.actId??1)===(t.actId??1)}function El(r,t,i){const a={...t,descriptiveScript:r.descriptiveScript,status:r.status,canonStale:r.canonStale};return i&&vu(r)&&!hh(r,t)&&(a.canonStale=!0),a}function a0(r,t){const i=new Map,a=new Set;for(let u=0;u<t.length;u+=1){const p=t[u],f=String(p.label||"").trim().toLowerCase();let x=r.findIndex((S,k)=>!a.has(k)&&String(S.label||"").trim().toLowerCase()===f);x<0&&u<r.length&&!a.has(u)&&(x=u),x>=0&&(a.add(x),i.set(u,r[x]))}return i}function l0(r,t){const i=a0(r,t),a=new Set;for(const S of i.values())a.add(S);const u=[],p=[],f=[];for(let S=0;S<t.length;S+=1){const k=t[S],v=i.get(S);if(!v){f.push({...k});continue}vu(v)?hh(v,k)?f.push(El(v,k,!0)):(p.push({index:S,before:v,after:El(v,k,!1)}),f.push({...v,index:S})):f.push(El(v,k,!1))}for(const S of r)a.has(S)||vu(S)&&u.push(S);const x=Xo(t.map((S,k)=>{const v=i.get(k);return v?El(v,S,!0):{...S}}));return{safeUnits:Xo(f),proposedFull:x,needsConfirm:{removeWithScript:u,overwriteWithScript:p}}}function c0(r,t,i={}){const a=i0(t,i);return l0(r,a)}function Xf(r){return r.needsConfirm.removeWithScript.length>0||r.needsConfirm.overwriteWithScript.length>0}function Jf(r,t,i,a){const u=String(r||"").trim();if(u&&a(u))return u;const p=i[0];return p?`ep:${t}:seq:${p.index}`:`ep:${t}:seq:0`}function Qf(r,t,i={}){const a=Array.isArray(r)?r:[],u=c0(a,t,i);return{units:Xf(u)?u.safeUnits:u.proposedFull,diff:u,needsConfirm:Xf(u)}}function d0(r){const t=String(r||"").trim();if(!t)return null;const i=[],a=t.match(/```(?:json)?\s*([\s\S]*?)```/i);a!=null&&a[1]&&i.push(a[1].trim()),i.push(t);const u=t.indexOf("{"),p=t.lastIndexOf("}");u>=0&&p>u&&i.push(t.slice(u,p+1));for(const f of i)try{const x=JSON.parse(f);if(x&&typeof x=="object")return x}catch{}return null}function Cu(r){var t,i,a,u,p,f;return r?!!((t=r.logline)!=null&&t.trim()||(i=r.synopsis)!=null&&i.trim()||r.worldBible&&Object.values(r.worldBible).some(x=>
115String(x||"").trim())||Array.isArray(r.episodes)&&r.episodes.length>0||Array.isArray(r.characters)&&r.characters.length>0||(a=r.seriesTitle)!=null&&a.trim()||(u=r.title)!=null&&u.trim()||typeof r.plannedEpisodes=="number"&&Number.isFinite(r.plannedEpisodes)||typeof r.episodeDurationSeconds=="number"&&Number.isFinite(r.episodeDurationSeconds)||(p=r.dramaCategory)!=null&&p.trim()||(f=r.dramaCustomNote)!=null&&f.trim()):!1}function Nr(r,t){var u;const i=r.match(t);return((u=i==null?void 0:i[1])==null?void 0:u.trim())||void 0}const u0=[{key:"geography",re:/^(?:#{1,3}\s*)?(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)?(?:\*\*)?(?:geography|å°çç¯å¢|å°çä¸ç©ç|主è¦å°ç¹|å°ç¹|å°ç|ä¸çç®è¿°|ä¸çèå¾|world\s*sketch|world\s*brief)(?:\*\*)?(?:\s*[ä¸\/].{0,16})?\s*[:ï¼]?\s*(.*)$/i},{key:"timeline",re:/^(?:#{1,3}\s*)?(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)?(?:\*\*)?(?:timeline|æ¶ä»£èæ¯|æ¶é´çº¿(?:ä¸åå²)?|æ¶ä»£(?:ä¸åå²)?|年代|æ¶ä»£)(?:\*\*)?(?:\s*[ä¸\/].{0,16})?\s*[:ï¼]?\s*(.*)$/i},{key:"rules",re:/^(?:#{1,3}\s*)?(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)?(?:\*\*)?(?:rules?|è§å|éå¶|è§åä¸éå¶)(?:\*\*)?(?:\s*[ä¸\/].{0,16})?\s*[:ï¼]?\s*(.*)$/i},{key:"culture",re:/^(?:#{1,3}\s*)?(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)?(?:\*\*)?(?:culture|æå|æ¥å¸¸çæ´»|æåä¸ç¤¾ä¼)(?:\*\*)?(?:\s*[ä¸\/].{0,16})?\s*[:ï¼]?\s*(.*)$/i},{key:"coreConflict",re:/^(?:#{1,3}\s*)?(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)?(?:\*\*)?(?:core\s*conflict|æ ¸å¿å²çª|æ ¸å¿çç¾)(?:\*\*)?(?:\s*[ä¸\/].{0,16})?\s*[:ï¼]?\s*(.*)$/i}],p0=4e3;function m0(r){const t=r.trim().replace(/\r\n/g,` 116`).replace(/\n{3,}/g,` 117 118`).slice(0,p0);return t.length>=4?t:void 0}function f0(r){const i={...Bu(r)};return i.geography=Nr(r,/(?:geography|å°ç(?:ä¸ç©ç)?)\s*[:ï¼]\s*([^\n]{4,4000})/i)||i.geography,i.timeline=Nr(r,/(?:timeline|æ¶é´çº¿(?:ä¸åå²)?|æ¶ä»£(?:ä¸åå²)?)\s*[:ï¼]\s*([^\n]{4,4000})/i)||i.timeline,i.rules=Nr(r,/(?:rules|è§å(?:ä¸éå¶)?)\s*[:ï¼]\s*([^\n]{4,4000})/i)||i.rules,i.culture=Nr(r,/(?:culture|æå(?:ä¸ç¤¾ä¼)?)\s*[:ï¼]\s*([^\n]{4,4000})/i)||i.culture,i.coreConflict=Nr(r,/(?:core\s*conflict|æ ¸å¿å²çª)\s*[:ï¼]\s*([^\n]{4,4000})/i)||i.coreConflict,Object.values(i).some(a=>String(a||"").trim().length>=4)?i:void 0}function y0(r){return/^#{1,3}\s/.test(r)||/^\*\*.+\*\*/.test(r)||/^(?:[ä¸äºä¸åäºå ä¸å «ä¹å]+[ã.]|[0-9]+[.ãï¼)]\s*)/.test(r)}function h0(r,t){const i=r.match(t.re);if(!i)return!1;const a=String(i[1]||"").trim();return y0(r)?a.length<=80:/[:ï¼]/.test(r)?!(a.length>80||/[ãï¼ï¼!?]/.test(a)&&a.length>40):a.length===0}function g0(r){return/^(?:#{0,3}\s*)?(?:第\s*\d+\s*é|E(?:p(?:isode)?)?\s*\d+)/i.test(r)}function Bu(r){var f,x;const t={},i=String(r||"").split(/\n/);let a=null,u=[];const p=()=>{if(!a)return;const S=m0(u.join(` 119`));S&&!t[a]&&(t[a]=S),u=[]};for(const S of i){const k=S.trim(),v=u0.find(I=>I.re.test(k)&&h0(k,I));if(v){p(),a=v.key;const I=(x=(f=k.match(v.re))==null?void 0:f[1])==null?void 0:x.trim();I&&u.push(I);continue}if(a&&(/\*\*[^*]{2,16}\*\*\s*[:ï¼]/.test(k)||g0(k)||/^\[\[OPTIONS/i.test(k))){p(),a=null;continue}a&&u.push(S)}return p(),t}const Fo={ä¸:1,äº:2,两:2,ä¸:3,å:4,äº:5,å :6,ä¸:7,å «:8,ä¹:9};function x0(r){const t=String(r||"").trim();if(t){if(t==="å")return 10;if(t==="äºå")return 20;if(/^å[ä¸äºä¸åäºå ä¸å «ä¹]$/.test(t))return 10+Fo[t.slice(1)];if(/^[äºä¸åäºå ä¸å «ä¹]å$/.test(t))return Fo[t[0]]*10;if(/^[äºä¸åäºå ä¸å «ä¹]å[ä¸äºä¸åäºå ä¸å «ä¹]$/.test(t))return Fo[t[0]]*10+Fo[t.slice(-1)];if(t.length===1&&Fo[t])return Fo[t]}}function gh(r){const t=r.match(/(?:æ»éæ°|planned\s*episodes?|episodes?\s*planned)\s*[:ï¼]?\s*(\d{1,3})/i)||r.match(new RegExp("(?<!第)(?<![0-9\\-ââ])(\\d{1,3})\\s*é"))||r.match(new RegExp("(?<!第)(?<![0-9])(\\d{1,3})\\s*話"))||r.match(new RegExp("(?<!ì )(?<![0-9])(\\d{1,3})\\s*í¸"))||r.match(/(\d{1,3})[-ââ]\s*episodes?\b/i)||r.match(/(\d{1,3})\s+(?:[\w.-]+\s+){0,3}episodes?\b/i)||r.match(/(\d{1,3})[-ââ]\s*eps?\b/i)||r.match(/(\d{1,3})\s+(?:[\w.-]+\s+){0,3}eps?\b/i);if(t){const u=Number(t[1]);if(Number.isFinite(u)&&u>0)return u}const i=r.match(new RegExp("(?<!第)(?:ä¸å ±|å ±|约)?\\s*([ä¸äºä¸¤ä¸åäºå ä¸å «ä¹å]{1,3})\\s*é")),a=i?x0(i[1]):void 0;return a&&a>0?a:void 0}const Mu=Br,Vo=tb;function ta(r,t,i=30){if(!(!Number.isFinite(r)||r<i||r>t))return Math.round(r)}function ca(r){const t=String(r||"").trim();if(!t)return;const i=t.match(/^(\d{1,3})\s*åé/u);
119if(i){const f=ta(Number(i[1])*60,Vo,ea);if(f!=null)return f}const a=t.match(/(?:^|[^\d])(\d{1,3})\s*åé(?:ç)?(?:çµå½±|å½±ç|é¿ç|åç|feature)/u)||t.match(/(?:^|[^\d])(\d{1,3})\s*minutes?\s*(?:feature\s*)?(?:film|movie)/i)||t.match(/ä¸é¨\s*(\d{1,3})\s*åé/u)||t.match(/(?:film\s*runtime|çé¿|å
¨çæ¶é¿|çµå½±æ¶é¿)\s*[:ï¼]?\s*(\d{1,3})\s*(?:åé|min(?:ute)?s?\b)/iu);if(a){const f=ta(Number(a[1])*60,Vo,ea);if(f!=null)return f}const u=t.match(/^(?:å°±|é|大约|约|大æ¦)?\s*(\d{1,3})\s*åé\s*$/u);if(u&&vs(t))return ta(Number(u[1])*60,Vo,ea);const p=t.match(/(?:film\s*runtime|çé¿|å
¨çæ¶é¿)\s*[:ï¼]?\s*(\d{3,5})\s*(?:ç§|s\b)?/iu)||t.match(/(?:^|[^\d])(\d{3,5})\s*ç§(?:ç)?(?:çµå½±|é¿ç|å
¨ç)/u);if(p)return ta(Number(p[1]),Vo,ea)}function xh(r,t=Mu){const i=t<=Br;let a;if(/æ¯é\s*约?\s*ä¸\s*å\s*å(?:é)?/.test(r))a=90;else if(/æ¯é\s*约?\s*两\s*(?:åé|min(?:ute)?s?\b)/i.test(r))a=120;else if(/æ¯é\s*约?\s*ä¸\s*(?:åé|min(?:ute)?s?\b)/i.test(r))a=60;else{const u=r.match(new RegExp("(?<!第)(?<![0-9])\\d{1,3}\\s*é\\s*[Ãx*\\/ï¼]\\s*(\\d{1,3}(?:\\.\\d)?)\\s*(?:åé|min(?:ute)?s?\\b)","i"))||r.match(/\d{1,3}\s*(?:episodes?|eps?)\s*[Ãx*\/]\s*(\d{1,3}(?:\.\d)?)\s*min(?:ute)?s?\b/i);if(u)a=Math.round(Number(u[1])*60);else{const p=r.match(new RegExp("(?<!第)(?<![0-9])\\d{1,3}\\s*é\\s*[Ãx*\\/ï¼]\\s*(\\d{1,4})\\s*(?:ç§|s\\b)","i"))||r.match(/\d{1,3}\s*(?:episodes?|eps?)\s*[Ãx*\/]\s*(\d{1,4})\s*(?:seconds?|s)\b/i);if(p)a=Number(p[1]);else{const f=r.match(/æ¯é\s*约?\s*(\d{1,3})\s*(?:ç§|s\b)/i)||r.match(/매í¸\s*(\d{1,3})\s*ì´/)||r.match(/(\d{2,3})\s*(?:ç§|s)\s*(?:ä¸é|\/é|per\s*episode)/i)||r.match(/(\d{2,3})\s*seconds?\s+each/i)||r.match(/each(?:\s+episode)?\s*(?:is\s+|of\s+)?(\d{2,3})\s*seconds?/i);if(f)a=Number(f[1]);else{const x=r.match(/æ¯é\s*约?\s*(\d{1,2}(?:\.\d)?)\s*(?:åé|min(?:ute)?s?\b)/i)||r.match(/(\d{1,2}(?:\.\d)?)\s*(?:åé|min(?:ute)?s?)\s*(?:ä¸é|per\s*episode)/i);if(x)a=Math.round(Number(x[1])*60);else{const S=r.match(/(?:åéæ¶é¿|duration\s*per\s*episode|episode\s*duration)\s*[:ï¼]?\s*(\d{2,4})\s*(?:ç§|s|sec)?/i)||r.match(/(\d{2,4})\s*(?:ç§\/é|s\s*per\s*episode)/i),k=S?Number(S[1]):NaN;a=Number.isFinite(k)?k:void 0}}}}}if(!(a==null||!Number.isFinite(a)||a<=0))return i?Br:ta(a,t,ea)}function Kn(r,t){const i=String(r||"").trim();if(!i)return null;const a={},u=vs(i);u&&(a.plannedEpisodes=1);const p=gh(i);p&&!u&&(a.plannedEpisodes=p);const f=ca(i);if(f&&(u||!p))a.plannedEpisodes=1,a.episodeDurationSeconds=f;else{const x=xh(i,u?Vo:Mu);x?a.episodeDurationSeconds=x:p&&(t!=null&&t.defaultDurationSeconds)&&(a.episodeDurationSeconds=t.defaultDurationSeconds)}return Cu(a)?a:null}function b0(r){const t=r.split(/\n+/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of t){const u=a.match(/^E(?:p(?:isode)?)?\.?\s*0*(\d{1,3})\s*[|ï½\-ââ:ï¼]\s*(.+)$/i)||a.match(/^第\s*0*(\d{1,3})\s*é\s*[|ï½\-ââ:ï¼]?\s*(.+)$/i)||a.match(/^Episode\s*0*(\d{1,3})\s*[|ï½\-ââ:ï¼]\s*(.+)$/i);if(!u)continue;const p=Number(u[1]),f=String(u[2]||"").trim();if(!(!Number.isFinite(p)||!f)&&(i.push({title:`Episode ${p}`,summary:f}),i.length>=120))break}return i.length>0?i:void 0}function zo(r){var v,I,$,O,D,n,z,Z,Ee,Ie;const t=String(r||"").trim();if(t.length<16)return null;const i=d0(t);if(Cu(i))return i;const a={};a.logline=Nr(t,/(?:logline|one[- ]line|ä¸å¥è¯æ
äº|ä¸å¥è¯æ¢æ¦|æ¢æ¦|íì¤(?:ì´ì¼ê¸°)?|ãã°ã©ã¤ã³)\s*[:ï¼]\s*([^\n]{8,400})/i),a.synopsis=Nr(t,/(?:synopsis|å§æ
ç®ä»|æ
äºç®ä»|ìëìì¤|ãããã)\s*[:ï¼]\s*([\s\S]{8,4000}?)(?=\n(?:#{1,3}\s|logline|synopsis|ä¸å¥è¯|å§å|ì 목|ã¿ã¤ãã«|ä¸çè§|world|$))/i),a.synopsis||(a.synopsis=Nr(t,/(?:synopsis|å§æ
ç®ä»|æ
äºç®ä»|ìëìì¤|ãããã)\s*[:ï¼]\s*([^\n]{8,4000})/i));const u=Nr(t,/(?:series\s*title|\btitle\b|å§å|çå|æ é¢|ì 목|ã¿ã¤ãã«)\s*[:ï¼]\s*[â"ã]?([^"\nãâ]{2,80})[ãâ"]?/i);u&&(a.seriesTitle=u),vs(t)?a.plannedEpisodes=1:a.plannedEpisodes=gh(t);const p=ca(t);p?(a.plannedEpisodes=1,a.episodeDurationSeconds=p):a.episodeDurationSeconds=xh(t,vs(t)?Vo:Mu),a.episodes=b0(t);const f=Jl(t);if(f.length>
1190){const ne=((v=a.episodes)==null?void 0:v[0])??{title:vs(t)?"Film":"Episode 1",summary:""};a.episodes=[{...ne,sequences:f.map(Pe=>({label:Pe.label,beatSummary:Pe.beatSummary,actId:Pe.actId}))},...((I=a.episodes)==null?void 0:I.slice(1))??[]]}const x=Bu(t),k=Object.values(x).filter(ne=>String(ne||"").trim()).length>=1?{...x}:{};if(k.geography=Nr(t,/(?:geography|å°ç(?:ä¸ç©ç)?)\s*[:ï¼]\s*([^\n]{4,240})/i)||k.geography,k.timeline=Nr(t,/(?:timeline|æ¶é´çº¿(?:ä¸åå²)?)\s*[:ï¼]\s*([^\n]{4,240})/i)||k.timeline,k.rules=Nr(t,/(?:rules|è§å(?:ä¸éå¶)?)\s*[:ï¼]\s*([^\n]{4,240})/i)||k.rules,k.culture=Nr(t,/(?:culture|æå(?:ä¸ç¤¾ä¼)?)\s*[:ï¼]\s*([^\n]{4,240})/i)||k.culture,k.coreConflict=Nr(t,/(?:core\s*conflict|æ ¸å¿å²çª)\s*[:ï¼]\s*([^\n]{4,240})/i)||k.coreConflict,t.length<400){if(!k.timeline){const ne=((O=($=t.match(/ä¸çè§\s*(?:æ¯|为|å¨|å°±|åºè¯¥|叿|åºäº|æç §)\s*([^\nãï¼ï¼!?]{4,400})/i))==null?void 0:$[1])==null?void 0:O.trim())||((n=(D=t.match(/(?:æ¶ä»£|æ¶é´çº¿)\s*(?:æ¯|为|å¨)\s*([^\nãï¼ï¼!?]{4,400})/i))==null?void 0:D[1])==null?void 0:n.trim());ne&&(k.timeline=ne)}if(!k.geography){const ne=((Z=(z=t.match(/(?:å°ç¹|åºæ¯|åçå¨)\s*(?:æ¯|为|å¨)?\s*([^\nãï¼ï¼!?]{4,200})/i))==null?void 0:z[1])==null?void 0:Z.trim())||((Ie=(Ee=t.match(/æ äºåçå¨\s*([^\nãï¼ï¼!?]{4,200})/i))==null?void 0:Ee[1])==null?void 0:Ie.trim());ne&&(k.geography=ne)}}return Object.values(k).some(ne=>String(ne||"").trim())&&(a.worldBible=k),Cu(a)?a:null}function w0(){try{const r="1".trim().toLowerCase();return r==="1"||r==="true"||r==="on"}catch{return!1}}function qr(r){return!w0()||r.inEpisodeScriptContext?!1:r.uiPhase==="immersive"||r.uiPhase==="workspace"}const S0=12,k0=12e3,v0="[[GREENLIGHT_STRUCTURE_JSON]]",C0="[[/GREENLIGHT_STRUCTURE_JSON]]",N0=`You are a strict JSON extractor for STORYFLOW board sync. 120 121Input is a conversation excerpt (user + assistant) from a screenplay/series planning chat. Convert it into a concise JSON object for board fields. 122 123Return ONLY valid JSON (no markdown, no commentary). 124 125Schema: 126{ 127 "logline": string, 128 "synopsis": string, 129 "title": string, 130 "worldBible": { 131 "geography": string, 132 "timeline": string, 133 "rules": string, 134 "culture": string, 135 "coreConflict": string 136 }, 137 "episodes": [ 138 { 139 "title": string, 140 "summary": string, 141 "durationMin": number, 142 "sceneCount": number, 143 "scenes": string[], 144 "sequences": [{ "label": string, "beatSummary": string, "actId": number }], 145 "props": string[], 146 "characterRefs": [{ "name": string }] 147 } 148 ], 149 "characters": [{ "name": string, "note": string }], 150 "seriesTitle": string, 151 "plannedEpisodes": number, 152 "episodeDurationSeconds": number, 153 "dramaCategory": string, 154 "dramaCustomNote": string 155} 156 157Rules: 158- Keep user language as-is. 159- Fill logline/synopsis/title only from Title / Logline / Synopsis labels (å§å / ä¸å¥è¯æ äº / æ äºç®ä» and locale aliases). Do not copy character-rewrite, "what's missing", or duration-ack replies into those fields. 160- logline must be the story itself. Never copy meta openings such as "ä¸é¢æ¯ä¸ç大纲", "å ç»ä½ ä¸ç", "Here's a draft", or "确认æ¹è®¾å®". 161- worldBible: copy å°ç / æ¶ä»£ / è§å / æå / æ ¸å¿å²çª (Geography / Timeline / Rules / Culture / Core conflict). On a first story draft those five headings should all be filled. Also accept ä¸çç®è¿° / ä¸çèå¾ / World sketch as geography when a heading is missing. Copy labeled world sections whenever they are present, even if the user did not say æå»ºä¸çè§.
162- characters: ONLY **Name**ï¼note lines and @@Nameãnoteã with a **real character name** (e.g. å¨é, Maya). Never use role slots alone (主è§, 女主, ç·ä¸», é è§, åºä¸», ç·å©, protagonist, heroine). Omit characters when those markers are missing. Never invent names from repeated words (ç»å°¾é©, 空é´ç«, 循ç¯, å¶åº¦, â¦). 163- Fill seriesTitle when the draft names the show, or when Title / å§å / ì 목 / ã¿ã¤ãã« / ãâ¦ã refers to THIS project (not a cited other work in ãã or quotes). 164- Logline labels include Logline / ä¸å¥è¯æ äº / íì¤ / ãã°ã©ã¤ã³. Synopsis labels include Synopsis / æ äºç®ä» / ìëìì¤ / ãããã. 165- Omit remaining unknown fields or leave empty strings. Do not return {} just because labels are missing. 166- If the user only stated episode count or duration and gave no story, omit logline, synopsis, title, characters, and worldBible. Keep plannedEpisodes / episodeDurationSeconds only. 167- If the user asked æå»ºä¸çè§ / build the world, you MUST fill worldBible from the assistant's å°ç/æ¶ä»£/è§å/æå/æ ¸å¿å²çª (or Geography/Timeline/Rules/Culture/Core conflict) sections. Do not omit worldBible when those sections are present. 168- Prefer precision over guessing on world bible, characters, and episode rows; still always try logline + synopsis from a real draft. 169- **sequences** (åºåº beat list) are NOT full scripts. When the user asks to split acts/episodes into scenes/beats, fill \`episodes[i].sequences[]\` with \`label\` + optional \`beatSummary\` + optional \`actId\` (1â3 for film acts). Do NOT write Shot N / é头 / screenplay pages inside sequences. 170- Prose beat lines like \`åº1 | â¦\` or \`第1å¹Â·åº2 | â¦\` may appear in assistant replies; mirror them into sequences when present. 171- Use seriesTitle as the primary field for title; title is allowed as legacy alias. 172- dramaCategory MUST be one of: modern_urban, period, fantasy, thriller, comedy, rural_era, sci_fi, other_professions, custom (or omit). 173- If dramaCategory is custom and user provided a custom category note, put it in dramaCustomNote. 174- plannedEpisodes is the season length the user agreed on (integer ⥠1). 175- episodeDurationSeconds is the unified per-episode length in seconds. For short-drama / series mode the product length is fixed at 300 seconds (5 minutes) per episode â always use 300 when filling this field for multi-episode seasons. Do not invent other per-episode lengths. 176- seriesTitle is the show title in the user's language (not the project folder name). 177- Do not put **other works** (films/games cited only for visual style) into seriesTitle; those belong in synopsis/logline prose with ãcorner quotesã or quotes, not as seriesTitle. 178- If the excerpt has no story content at all, return {}.`,Tl=N0,E0=new Set(["title","logline","synopsis","geography","timeline","rules","culture","coreConflict","dramaCategory"]);function Lu(r){const t=r.trim();if(!t)return null;const i=t.replace(/^```(?:json)?\s*/i,"").replace(/```$/i,"").trim(),a=[i],u=i.indexOf("{"),p=i.lastIndexOf("}");u>=0&&p>u&&a.push(i.slice(u,p+1));for(const f of a)try{const x=JSON.parse(f);if(x&&typeof x=="object")return x}catch{}return null}function tr(r){var t,i,a,u,p,f;return r?!!((t=r.logline)!=null&&t.trim()||(i=r.synopsis)!=null&&i.trim()||r.worldBible&&Object.values(r.worldBible).some(x=>
178String(x||"").trim())||Ou(r)||Array.isArray(r.episodes)&&r.episodes.length>0||Array.isArray(r.characters)&&r.characters.length>0||(a=r.seriesTitle)!=null&&a.trim()||(u=r.title)!=null&&u.trim()||typeof r.plannedEpisodes=="number"&&Number.isFinite(r.plannedEpisodes)||typeof r.episodeDurationSeconds=="number"&&Number.isFinite(r.episodeDurationSeconds)||(p=r.dramaCategory)!=null&&p.trim()||(f=r.dramaCustomNote)!=null&&f.trim()):!1}function Ou(r){return!r||!Array.isArray(r.episodes)?!1:r.episodes.some(t=>Array.isArray(t.sequences)&&t.sequences.some(i=>String((i==null?void 0:i.label)||"").trim()))}function T0(r){return/ååº|åºåº|åºå表|ææ\s*\d+\s*åº|å¤åº|scene\s*list|beat\s*list|sequences/i.test(String(r||""))}function R0(r){return Jl(String(r||"")).length>0}function j0(r,t){if(!Array.isArray(r.episodes)||r.episodes.length===0)return r;const i=(t==null?void 0:t.standaloneFilmMode)===!0,a=r.episodes.map(u=>{if(!Array.isArray(u.sequences)||u.sequences.length===0)return u;const p=ku({jsonBeats:u.sequences,standaloneFilmMode:i});if(p.length===0){const{sequences:f,...x}=u;return x}return{...u,sequences:p.map(f=>({label:f.label,beatSummary:f.beatSummary,actId:f.actId}))}});return{...r,episodes:a}}function Ql(r){let t=String(r||"");const i=(a,u)=>{for(;;){const p=t.indexOf(a);if(p===-1)break;const f=t.indexOf(u,p+a.length);if(f===-1){t=`${t.slice(0,p).trim()}`;break}t=`${t.slice(0,p).trim()} 179${t.slice(f+u.length).trim()}`.trim()}};return i(Wn,zn),i(v0,C0),t.trim()}function A0(r,t){const i=S0,a=k0;let f=r.filter(x=>x.role==="user"||x.role==="assistant").slice(-Math.max(1,i)).map(x=>`${x.role==="user"?"User":"Assistant"}: ${Ql(String(x.text||""))}`).join(` 180 181`).trim();return f.length>a&&(f=f.slice(-a)),f}function I0(r,t){const i=String(r||"").trim(),a="You MUST include logline and synopsis whenever the assistant drafted a story. Infer from unlabeled prose if headings are missing. If the assistant only asked a clarifying question, omit logline and synopsis. Return JSON only.";return t?`Extract board fields from this conversation excerpt. ${a} 182 183--- 184${i} 185---`:`Extract board fields from this reply. ${a} 186 187--- 188${i} 189---`}const P0=/^(?:#{1,3}\s+|(?:logline|one[- ]line|synopsis|title|å§å|çå|æ é¢|ì 목|ã¿ã¤ãã«|ä¸å¥è¯æ äº|ä¸å¥è¯æ¢æ¦|æ¢æ¦|íì¤(?:ì´ì¼ê¸°)?|ãã°ã©ã¤ã³|æ äºç®ä»|å§æ ç®ä»|ìëìì¤|ãããã)\s*[:ï¼])/i,_0=/请é®|å åè¯æ|ä½ æ³è¦|å·²ç»ç¡®è®¤æ¯\d+\s*é|å·²ç»æç¡®äºæ¨çéæ±|æ¨çéæ±|æ¯éæ¶é¿|å¤§æ¦æ¯å¤ä¹ |which duration|how long(?: is)? each|how many episodes|I(?:'ve| have) (?:noted|understood|confirmed)/i,B0=/^(好ç[ï¼,]|okay[,.]|got it[,.]|understood[,.])/i,M0=/^(?:ä¸é¢æ¯ä¸ç|å ç»ä½ ä¸ç|å¯ä»¥[ãï¼.ï¼,]?\s*(?:åºäº|ä¸é¢)|确认æ¹è®¾å®|好ç[ï¼,]?\s*ç®å|here(?:'|â)s a (?:draft|outline)|based on (?:your|the)|i(?:'|â)ll (?:outline|draft)|i will (?:outline|draft))/i,L0=/^(?:å§å|æ é¢|çå|å°ç|å°ç¹|æ¶ä»£|æ¶é´çº¿|è§å|æå|æ ¸å¿å²çª|æ ¸å¿çç¾|ç§å|åæ¶|人ç©|è§è²|主è§|女主|ç·ä¸»|女主è§|ç·ä¸»è§|é è§|æ£æ´¾|åæ´¾|ä¸»äººå ¬|åºä¸»|èæ¿|ç·å©|女å©|路人|群æ¼|ä¸çè§|大纲|åé|åé骨æ¶|骨æ¶|ç»å°¾|ç®ä»|ä¼ç¹|缺ç¹|身份|已确å®|已确认|确认|主è§è§|è§è§|èä¸|å¤è²|å¹´é¾|æ§æ ¼|èæ¯|设å®|title|logline|synopsis|geography|timeline|rules|culture|advantage|ethnic|group|setup|escalation|reveal|reversal|climax|aftermath|pilot|finale|midpoint|hook|beat|scene|act|identity|confirmed|confirmation|pov|occupation|appearance|age|personality|background|protagonist|heroine|antagonist|villain|hero|supporting)$/i,O0=/^(?:ç¥é|æ¯ä¹¦|éé¿|åé¢|家书|åå|ä»ç»ä¿¡|ä¿¡ä»¶|ç»å°¾|é©å|ç»å°¾é©|å°¾é©å|é»å塬|å ¬ç¤¾|çªæ´|æé©|æ¶æ|西å|åå¸|女å©|ç·å©|主è§|女主|ç·ä¸»|女主è§|ç·ä¸»è§|é è§|æ£æ´¾|åæ´¾|ä¸»äººå ¬|åºä¸»|èæ¿|路人|群æ¼|æ¥å¤©|ç°åº|æ°æ°|æ§æ¡|æ§ææ|æ¨è|审æ¥|å¡è½¦|ç°å|循ç¯|空é´ç«|è¿å|ä¸ä¹¡|è½é|平衡|å·¥å|å¶åº¦|ç©èµ|çç£|åé骨æ¶|骨æ¶|ä¼å¿|å£å¿|ä¼ç¹|缺ç¹|æç¾¤|ç§æ|æå§|ææ|å²çª|æç¤º|å转|髿½®|éºå«|使³¢|å级|å¼åº|ç»å±|䏿®µ|å£ç»|é¦é|å·²é|éå®|ä¸å¹|èæ|åå¹|å¹ä¸|å¹äº|å¹ä¸|身份|已确å®|已确认|确认|主è§è§|è§è§|èä¸|å¤è²|å¹´é¾|æ§æ ¼|èæ¯|设å®)$/,$0=/(?:å¶åº¦|å²çª|è§å|é©å|ç»å°¾|循ç¯|空é´ç«|è½é|平衡|å·¥å|ç©èµ|çç£|ä¸ä¹¡|è¿å|åé¢|ç¯å¢|èæ¯|æ°æ°|ç°åº|ä»ç»ä¿¡|ç°å|骨æ¶|大纲|ä¸|ä¼å¿|å£å¿|ä¼ç¹|缺ç¹|æç¾¤|æå§|ææ|éå®|å¹|èæ|å£ç»|é¦é|å¼åº|ç»å±|ç§æ|身份|已确å®|已确认|确认|主è§è§|èä¸|å¤è²|å¹´é¾|æ§æ ¼|设å®)/,F0=/^(?:act\s*\d+|scene\s*\d+|beat\s*\d+|episode\s*\d+|season\s*\d+|advantage|ethnic(?:\s*group)?|setup|escalation|reveal|reversal|climax|aftermath|pilot|finale|midpoint|hook|turning\s*point|第[0-9ä¸äºä¸åäºå ä¸å «ä¹å]+[å¹éåº]|å¹\s*[0-9ä¸äºä¸å]|ä¼å¿|å£å¿|ä¼ç¹|缺ç¹|æç¾¤|ç§æ|æå§(?:ææ)?|ææ|å·²é(?:å®)?|éå®|ä¸å¹|åå¹|å¼åº|ç»å±|䏿®µ|å£ç»|é¦é|使³¢|éºå«|å级|æç¤º|å转|髿½®)$/i,D0=/^(?:act|scene|beat|episode|season|advantage|ethnic|setup|climax|reversal|aftermath|hook|turning|midpoint|finale|pilot|第[0-9ä¸äºä¸å]|å¹[0-9ä¸äºä¸å])/i;function bh(r){const t=vt(String(r||"").replace(/\s+/g," "));return!!(!t||F0.test(t)||D0.test(t)||/^(?:第[0-9ä¸äºä¸åäºå ä¸å «ä¹å]+[å¹éåºè]|å¹[0-9ä¸äºä¸åäºå ä¸å «ä¹å])/.test(t))}function vt(r){let t=String(r||"").trim();return t=t.replace(/^#{1,6}\s+/,""),t=t.replace(/\*\*(.+?)\*\*/g,"$1"),t=t.replace(/\*+/g,""),t=t.replace(/^_{1,3}(.+?)_{1,3}$/g,"$1"),t=t.replace(/^["â'`ã]+|[ã"â'`]+$/g,""),t.trim()}function Ss(r){const t=vt(String(r||"").replace(/\s+/g," "));if(!t||t.length<2||t.length>24||bh(t)||L0.test(t)||O0.test(t))return!1;const i=t.replace(/[·â¢ï¼.]/g,"");return/^[\u4e00-\u9fff]+$/.test(i)?!(i.length<2||i.length>4||$0.test(i)):!!(/^[A-Za-z][A-Za-z .'-]{0,22}[A-Za-z]$/.test(t)||/^[A-Za-z]{2,24}$/.test(t))}function U0(r,t){if(!Ss(r))return!1;const i=String(t||"").trim();return i?!(/^(?:Act\s*\d|Scene\s*\d|Episode\s*\d|Season|Fits best|Advantage|Ethnic|第[0-9ä¸äºä¸å]+å¹)/i.test(i)||/^(?:ä¸.*ç»å°¾|fits best with|awakening and|reverse judgment)/i.test(i)):!0}function wh(r){const t=String(r||"").trim();let i;if(/æå»ºä¸çè§|build (?:the )?world(?:\s*bible)?|world bible/i.test(t))i={kind:"world_build",allowStoryFields:!1,allowSeasonShape:!0,allowWorldBible:!0,allowCharacters:!0};else{const a=!!Kn(t);let u=J0(t);!u&&a&&Fu($u(t))&&(u=!0),a&&!u?i={kind:"shape_only",allowStoryFields:!1,allowSeasonShape:!0,allowWorldBible:!1,allowCharacters:!1}:u?i={kind:"premise",allowStoryFields:!0,allowSeasonShape:!0,allowWorldBible:!1,allowCharacters:!0}:i={kind:"other",allowStoryFields:!1,allowSeasonShape:!!a,allowWorldBible:!1,allowCharacters:!1}}return!i.allowCharacters&&ec(t).length>0?{...i,allowCharacters:!0}:i}function Nu(r){if(String(r.logline||"").trim().length>=8)return!0;const i=String(r.projectName||"").trim();return!i||/untitled|æªå½å|æ æ é¢/i.test(i)?!1:i.length>=2}function W0(r){return/(?:logline|ä¸å¥è¯æ äº|æ äºç®ä»|synopsis|å§å|ì 목|íì¤|ã¿ã¤ãã«|ãããã|ãã°ã©ã¤ã³|ìëìì¤)\s*[:ï¼]/i.test(String(r||""))}function Sh(r){const t=Bu(r);return Object.values(t).some(i=>String(i||"").trim().length>=4)}function kh(r){const t=String(r||"").trim();return t?/(?:缩ç|ç²¾ç®|æ¹ç|çä¸ç¹|ä¸è¦æ´å£|ä¸è¦éå|å±é¨|åªæ¹|rewrite|shorter|trim|shorten|keep the rest|don'?t rewrite the season)/i.test(t):!1}function H0(r){const t=String(r||"").trim();return t?/(?:æ äºç®ä»|synopsis|å§æ ç®ä»)\s*[:ï¼]/i.test(t)?!0:/(?:缩ç为|å¯ç¼©ç为|shortened to|trimmed to|replace the synopsis)/i.test(t):!1}function vh(r){if(r.userTurnKind==="shape_only"||r.userTurnKind==="world_build")return!1;const t=String(r.assistantText||"").trim();return t?r.userTurnKind==="other"?Zl(t)?!1:!!(W0(t)||r.userText&&kh(r.userText)&&H0(t)):X0(t):!1}function Ch(r){return Ko(r).length>0}function Nh(r){const t=Zy(String(r||"")),i=[],a=new Set;for(const f of t.characters){const x=vt(String(f.name||"")),S=vt(String(f.desc||""));if(!x||!Ss(x))continue;
189const k=x.toLowerCase();a.has(k)||(a.add(k),i.push({name:x,note:S||void 0}))}const u=t.scenes.map(f=>vt(String(f.name||""))).filter(f=>f.length>=2&&f.length<=48),p=t.props.map(f=>vt(String(f.name||""))).filter(f=>f.length>=2&&f.length<=48);return{characters:i,scenes:u,props:p}}function Ko(r){const t=String(r||""),i={out:[],seen:new Set};for(const a of Nh(t).characters)qn(i,a.name||"",a.note||"");for(const a of z0(t))qn(i,a.name||"",a.note||"");return i.out.slice(0,12)}function z0(r){const t=String(r||""),i={out:[],seen:new Set};for(const a of t.matchAll(/(?:^|\n)\s*([^\s\n*]{1,16})è§è²å½¢è±¡è®¾è®¡\s*(?=\n|$)/gm))qn(i,a[1],"");for(const a of t.matchAll(/\*\*([^*\n]{2,24})\s*[ââ-]\s*Character visual design\*\*/gi))qn(i,a[1],"");return i.out}function Zf(r){const{scenes:t,props:i}=Nh(r);return{scenes:t,props:i}}function Xd(r,t){let i=Ql(String(r||"")).trim();return!i||K0(i)?t==="zh"?"已忥å°å³ä¾§ç¼å§å°ã":"Synced to the script desk on the right.":(t==="zh"?i=i.replace(/##\s*Updated\s+Logline/gi,"## æ´æ°åä¸å¥è¯æ¢æ¦").replace(/##\s*Updated\s+Synopsis/gi,"## æ´æ°åå§æ ç®ä»").replace(/##\s*Next\s*Step/gi,"## ä¸ä¸æ¥").replace(/##\s*Episode\s*Board/gi,"## åé颿¿").replace(/(?:^|\n)\s*Title\s*[:ï¼]/gi,` 190å§åï¼`).replace(/(?:^|\n)\s*Logline\s*[:ï¼]/gi,` 191ä¸å¥è¯æ äºï¼`).replace(/(?:^|\n)\s*Synopsis\s*[:ï¼]/gi,` 192æ äºç®ä»ï¼`).replace(/(?:^|\n)\s*Geography\s*[:ï¼]/gi,` 193å°çï¼`).replace(/(?:^|\n)\s*Timeline\s*[:ï¼]/gi,` 194æ¶ä»£ï¼`).replace(/(?:^|\n)\s*Rules\s*[:ï¼]/gi,` 195è§åï¼`).replace(/(?:^|\n)\s*Culture\s*[:ï¼]/gi,` 196æåï¼`).replace(/(?:^|\n)\s*Core conflict\s*[:ï¼]/gi,` 197æ ¸å¿å²çªï¼`):i=i.replace(/(?:^|\n)\s*å§å\s*[:ï¼]/g,` 198Title:`).replace(/(?:^|\n)\s*ä¸å¥è¯æ äº\s*[:ï¼]/g,` 199Logline:`).replace(/(?:^|\n)\s*ä¸å¥è¯æ¢æ¦\s*[:ï¼]/g,` 200Logline:`).replace(/(?:^|\n)\s*æ äºç®ä»\s*[:ï¼]/g,` 201Synopsis:`).replace(/(?:^|\n)\s*å§æ ç®ä»\s*[:ï¼]/g,` 202Synopsis:`).replace(/(?:^|\n)\s*å°ç\s*[:ï¼]/g,` 203Geography:`).replace(/(?:^|\n)\s*æ¶ä»£\s*[:ï¼]/g,` 204Timeline:`).replace(/(?:^|\n)\s*è§å\s*[:ï¼]/g,` 205Rules:`).replace(/(?:^|\n)\s*æå\s*[:ï¼]/g,` 206Culture:`).replace(/(?:^|\n)\s*æ ¸å¿å²çª\s*[:ï¼]/g,` 207Core conflict:`),i.trim())}function K0(r){const t=String(r||"").trim();if(!t)return!1;const i=Lu(t);return tr(i)}function q0(r){return r.flagActive?r.userTurnKind==="shape_only"?!1:Sh(r.assistantText)||Ch(r.assistantText)||R0(r.assistantText)||r.userTurnKind==="world_build"?!0:vh({userTurnKind:r.userTurnKind,assistantText:r.assistantText}):!0}function G0(r,t,i){const a=wh(t),u=a.allowStoryFields||!!(i!=null&&i.fromAssistantDraft)&&a.kind==="other"&&!!(i!=null&&i.keepLabeledStory),p=a.allowCharacters||!!(i!=null&&i.keepCast),f={...r},x=Ou(r)&&(u||T0(t)||!!(i!=null&&i.keepSequenceBeats));u||(delete f.logline,delete f.synopsis,delete f.seriesTitle,delete f.title,delete f.dramaCustomNote,Array.isArray(f.episodes)&&!x?delete f.episodes:Array.isArray(f.episodes)&&x&&(f.episodes=f.episodes.map(v=>({sequences:v.sequences}))));const S=aa(t);if(S?f.dramaCategory=S:u||(delete f.dramaCategory,delete f.dramaCustomNote),a.allowWorldBible||!!(i!=null&&i.keepWorldFromDraft)?!(i!=null&&i.keepWorldFromDraft)&&!a.allowWorldBible&&a.kind!=="world_build"&&!Nu({projectName:i==null?void 0:i.projectName,logline:i==null?void 0:i.logline})&&delete f.worldBible:delete f.worldBible,p&&a.kind==="world_build"&&!Nu({projectName:i==null?void 0:i.projectName,logline:i==null?void 0:i.logline})&&ec(t).length===0?delete f.characters:p?Array.isArray(f.characters)&&(f.characters=f.characters.filter(v=>Ss((v==null?void 0:v.name)||"")),f.characters.length===0&&delete f.characters):delete f.characters,!a.allowSeasonShape)delete f.plannedEpisodes,delete f.episodeDurationSeconds;else{const v=Kn(t);v!=null&&v.plannedEpisodes?f.plannedEpisodes=v.plannedEpisodes:delete f.plannedEpisodes,v!=null&&v.episodeDurationSeconds?f.episodeDurationSeconds=v.episodeDurationSeconds:v!=null&&v.plannedEpisodes&&((i==null?void 0:i.currentEpisodeDurationSeconds)==null||i.currentEpisodeDurationSeconds===180||i.currentEpisodeDurationSeconds===Br)?f.episodeDurationSeconds=Br:delete f.episodeDurationSeconds}return f}function Zl(r){const t=String(r||"").trim();
207return!!(!t||M0.test(t)||/å ç»ä½ ä¸ç/.test(t)||/ä¸é¢æå»º/.test(t)&&t.length<90||/éå.{0,24}(?:çå§)?大纲/.test(t)&&t.length<90||/å¯ç´æ¥å±å¼/.test(t)&&t.length<90)}function $u(r){return String(r||"").replace(/(?:æ»éæ°|planned\s*episodes?)\s*[:ï¼]?\s*\d{1,3}/gi," ").replace(new RegExp("(?<!第)(?<![0-9\\-ââ])\\d{1,3}\\s*é","g")," ").replace(/[ä¸äºä¸¤ä¸åäºå ä¸å «ä¹å]{1,3}\s*é/g," ").replace(new RegExp("(?<!第)\\d{1,3}\\s*話","g")," ").replace(/\d{1,3}\s*í¸/g," ").replace(/\d{1,3}[-ââ]?\s*episodes?\b/gi," ").replace(/\d{1,3}[-ââ]?\s*eps?\b/gi," ").replace(/æ¯é\s*约?\s*(?:\d+[ç§åé]|ä¸\s*å\s*å(?:é)?)/g," ").replace(/\d{2,3}\s*seconds?\s+each/gi," ").replace(/매í¸\s*\d{1,3}\s*ì´/g," ").replace(/ä¸å ±|å ±çº¦|大约|约/g," ").replace(/[,ï¼ãã.\s]+/g," ").trim()}function Fu(r){const t=String(r||"").trim();return t.length>=16||t.length>=8&&/女主|ç·ä¸»|女修|ç·ä¿®|修士|女å®|太å|天å«|æè°|宫廷|ä»ä¾ |å¤ä»|侦æ¢|失踪|黿¢|æåº|循ç¯|空é´ç«|女é«|ç·é«|è®°å¿|ç¯å¡|å§å¦¹|ç§å¯|é产|åå®¶|ä¸ä¹¡|ç¥é|ç©¿è¶|æ»è£|æ«ä¸|便å©åº|é»å®¢|å¾å¸|ç¿»æ¡|ç»§æ¿|éç|豪é¨|空é´/.test(t)?!0:t.length>=5&&/女主|ç·ä¸»|åå®¶|ç¯å¡|å§å¦¹|ç§å¯|é产/.test(t)}function Y0(r){const t=String(r||"").trim();return!(!t||t.length<8||Zl(t)||P0.test(t)||/^\[\[OPTIONS/i.test(t)||/^E(?:p(?:isode)?)?\s*\d+/i.test(t)||/^第\s*\d+\s*é/.test(t)||/[ï¼?]\s*$/.test(t)&&t.length<40||Kn(t)&&!Fu($u(t))||/^(?:å°ç|æ¶ä»£|æ¶é´çº¿|è§å|æå|æ ¸å¿å²çª|geography|timeline|rules|culture|core conflict)/i.test(t)||/^\*\*[^*]{2,16}\*\*\s*[:ï¼]/.test(t))}function qn(r,t,i){const a=vt(String(t||"").replace(/\s+/g," "));if(!U0(a,i))return;const u=a.toLowerCase();if(r.seen.has(u))return;r.seen.add(u);const p=vt(String(i||"")).slice(0,200);r.out.push({name:a,note:p||void 0})}function ec(r){const t=String(r||""),i={out:[],seen:new Set};for(const a of t.matchAll(/\*\*([^*]{2,24})\*\*\s*[:ï¼]\s*([^\n]*?)(?=\s*\*\*[^*]{2,24}\*\*\s*[:ï¼]|$)/g))qn(i,a[1],a[2]);for(const a of t.matchAll(/@@([^\sã\]]{1,20})ã([^ã]{0,200})ã/g))qn(i,a[1],a[2]);return i.out.slice(0,8)}function Eh(r){const t=String(r||""),i=ec(t),a={out:[...i],seen:new Set(i.map(p=>p.name.toLowerCase()))},u=/^(?:å§å|çå|æ é¢|ì 목|ã¿ã¤ãã«|ä¸å¥è¯æ äº|æ äºç®ä»|ç®ä»|íì¤|ãã°ã©ã¤ã³|ìëìì¤|ãããã|å°ç|æ¶ä»£|æ¶é´çº¿|è§å|æå|æ ¸å¿å²çª|æ ¸å¿çç¾|主è¦äººç©|主è¦è§è²|è§è²å®äº|è§è²|ä¸çè§|ä¸çç®è¿°|ä¸çèå¾|åé骨æ¶|logline|synopsis|title|geography|timeline|rules|culture|advantage|ethnic|setup|escalation|reveal|reversal|climax|aftermath|pilot|finale|midpoint|hook|beat|scene|act|ä¼å¿|å£å¿|ä¼ç¹|缺ç¹|æç¾¤|æå§|ææ|ä¸å¹|åå¹|å¼åº|ç»å±|䏿®µ|å£ç»|é¦é)$/i;for(const p of t.split(` 208`)){const f=p.trim().match(/^\*{0,2}([^\s*:ï¼*]{2,16})\*{0,2}\s*[:ï¼]\s*(.{1,200})$/);if(!f)continue;const x=f[1].replace(/\*/g,"");u.test(x)||bh(x)||/^第?\d+/.test(x)||/^E(?:p(?:isode)?)?\s*\d+/i.test(x)||/^Act\s*\d/i.test(x)||qn(a,x,f[2])}return a.out.slice(0,8)}function V0(r){var u;const t=r.match(/(?:series\s*title|\btitle\b|å§å|çå|æ é¢|ì 목|ã¿ã¤ãã«)\s*[:ï¼]\s*[â"ã]?([^"\nãâ]{2,80})[ãâ"]?/i);if((u=t==null?void 0:t[1])!=null&&u.trim())return vt(t[1]);const i=r.match(/(?:å§å|çå|æå»º|大纲|æ¬å§|该å§|å®å(?:为)?|å°±å«)\s*[:ï¼]?\s*ã([^ã\n]{2,40})ã/)||r.match(/ã([^ã\n]{2,40})ã/),a=vt((i==null?void 0:i[1])||"");return a&&!Zl(a)?a:void 0}function Th(r){const t=String(r||"").trim();return t?/(?:logline|ä¸å¥è¯æ äº|æ äºç®ä»|synopsis|å§å|ì 목|íì¤|ã¿ã¤ãã«|ãããã|ãã°ã©ã¤ã³|ìëìì¤)\s*[:ï¼]/i.test(t)?!1:_0.test(t)||B0.test(t)?!0:(t.match(/[ï¼?]/g)||[]).length>=1&&t.length<320:!0}function X0(r){const t=String(r||"").trim();if(!t)return!1;if(Eh(t).length>0||/(?:logline|ä¸å¥è¯æ äº|æ äºç®ä»|synopsis|å§å|ì 목|íì¤|ã¿ã¤ãã«|ãããã|ãã°ã©ã¤ã³|ìëìì¤)\s*[:ï¼]/i.test(t))return!0;
208if(Th(t))return!1;const i=(t.match(/[ï¼?]/g)||[]).length;return t.length>=80&&i===0}function J0(r){const t=String(r||"").trim();return t.length<16?!!(aa(t)&&/(?:çå§|å¾®çå§|series|show)/i.test(t)||/^(?:女主|ç·ä¸»)/.test(t)&&/å¤ä»|éè¢|åå®¶|ä¸ä¹¡|è§é|ç¿»ç|revenge|comeback/i.test(t)):/^(?:æ¯é|ä¸å ±|å ±|æ¹æ|æ¹ä¸º)\s*\d/.test(t)&&t.length<28||/[ï¼?]\s*$/.test(t)&&t.length<40?!1:/æ äº|åä¸ä¸ª|帮æå|女主|ç·ä¸»|åçå¨|ä¸ä¹¡|ç¥é|ç©¿è¶|æ»è£|æ«ä¸|女é«ä¸ç|女åé«ç|è®°å¿|è¨æ¶|å¦å|å¸å|íì|ì¬ê³ ì|ç¯å¡|å§å¦¹|ç§å¯|é产|æµ·è¾¹|ç»§æ¿|éç|失å¿|便å©åº|write (?:me |a )?|story about|set in/i.test(t)||t.length>=40}function ey(r,t){var u,p,f,x,S;const i=String(r||"").trim();if(i.length<12)return null;const a={...zo(i)||{}};if(Th(i))return delete a.logline,delete a.synopsis,tr(a)?a:null;if(a.seriesTitle&&(a.seriesTitle=vt(a.seriesTitle)),a.logline&&(a.logline=vt(a.logline)),a.synopsis&&(a.synopsis=vt(a.synopsis)),a.logline&&Zl(a.logline)&&delete a.logline,!((u=a.seriesTitle)!=null&&u.trim())){const k=V0(i);k&&(a.seriesTitle=k)}if(!((p=a.characters)!=null&&p.length)){const k=Eh(i);k.length&&(a.characters=k)}if((t==null?void 0:t.proseFallback)!==!1&&!((f=a.logline)!=null&&f.trim())){const k=i.split(/\n\s*\n/).map(O=>O.replace(/^#{1,3}\s+/,"").trim()).filter(O=>O&&Y0(O)),v=((x=k[0])==null?void 0:x.trim())||"",I=$u(v),$=Fu(I)?I:Kn(v)?"":v;if($.length>=5&&(a.logline=vt($).slice(0,400)),!((S=a.synopsis)!=null&&S.trim())&&k.length>=2){const O=k.slice(1).join(` 209 210`).trim();O.length>=20&&(a.synopsis=vt(O).slice(0,800))}}return tr(a)?a:null}function Q0(r){return r.skipBecauseWatchdogOrFailed?!1:r.flagActive?!0:!r.structureAppliedThisTurn}function ty(r,t){return r==null?!0:r===t}function Z0(r){const t=Number(r);return Number.isFinite(t)&&t>=0?t+1:1}function Gi(r,t,i,a){const u=aa(t)||aa(String((a==null?void 0:a.assistantText)||""));if(String(i||"").trim()&&!(a!=null&&a.allowReplace)){const f={...r};return delete f.dramaCategory,f}return u?{...r,dramaCategory:u}:r}function ek(){if(typeof document>"u")return null;const r=document.activeElement;if(!(r instanceof HTMLElement))return null;const t=r.getAttribute("data-storyflow-board-field")||"";return E0.has(t)?t:null}const tk=/\[\[OPTIONS[^\]]*\]\][\s\S]*$/i,ry=/^(?:åº\s*\d+|第\s*\d+\s*å¹\s*[·â¢]\s*åº\s*\d+|Seq\.?\s*\d+)\s*[|ï½]/im,sy=/^(?:ãå 容ç®è¿°ã|ã\/å 容ç®è¿°ã|\[Scene brief\]|\[\/Scene brief\]|@@\S|â³â³|ââ|\[\[SCENE:|\[\[PROP:|%%|\$\$)/i,rk=/```(?:markdown|md|text|script|plaintext)?\s*\n([\s\S]*?)```/i;function sk(r){const t=r.split(` 211`).map(a=>a.trim()).filter(Boolean);if(t.length===0||t.length===1&&ry.test(t[0])&&t[0].length<120)return!0;const i=t.filter(a=>ry.test(a));return i.length>=2&&i.length===t.length||i.length>=3&&i.length/t.length>=.85}function nk(r){const t=String(r||"").trim();if(!t)return"";const i=t.search(/ãå 容ç®è¿°ã|\[Scene brief\]/i);if(i>=0)return t.slice(i).trim();const a=t.split(` 212`),u=a.findIndex(f=>sy.test(f.trim()));if(u>0)return a.slice(u).join(` 213`).trim();let p=-1;for(let f=0;f<Math.min(a.length,5);f+=1)if(!a[f].trim()){p=f;break}if(p>=0&&p<=3){const f=a.slice(0,p).join(" ").trim(),x=a.slice(p+1).join(` 214`).trim();if(x.length>=40&&f.length<=160&&!sy.test(f))return x}return t}function Du(r){var p;let t=Ql(String(r||"")).trim();if(t=t.replace(tk,"").trim(),!t)return null;const i=rk.exec(t);if((p=i==null?void 0:i[1])!=null&&p.trim()&&(t=i[1].trim()),t=nk(t),!t||/^\s*[\[{]/.test(t)||sk(t))return null;const u=/ãå 容ç®è¿°ã|\[Scene brief\]/i.test(t)||/@@\S|â³â³|ââ|\[\[SCENE:|\[\[PROP:|%%|\$\$/.test(t)?24:48;return t.length<u?null:t}function ra(r){const t=/^ep:(\d+):seq:(\d+)$/.exec(String(r||"").trim());if(!t)return null;const i=Number(t[1]),a=Number(t[2]);return!Number.isFinite(i)||!Number.isFinite(a)||i<0||a<0?null:{episodeIndex:i,unitIndex:a}}function ok(r){return r.bloomBotMode!=="episode_unit"||r.inEpisodeScriptContext||!ra(r.hierarchySelectedId)?!1:!!Du(r.assistantText)}function ik(r){const t=String(r||"").trim().toLowerCase();return t?!!(t==="åå ¥å·¦ä¾§"||t==="åå ¥å·¦ä¾§ç¼è¾å¨"||t==="å¡«å ¥å·¦ä¾§"||t==="apply to board"||t==="apply to left"||t==="apply chat draft to left panel"||t.includes("åå ¥å·¦ä¾§")||t.includes("apply to board")||t.includes("apply to left")):!1}function ny(r){const t=Array.isArray(r)?r:[];for(let i=t.length-1;i>=0;i-=1){const a=t[i];if((a==null?void 0:a.role)!=="assistant")continue;const u=String(a.rawAssistantReply||a.text||"").trim();if(!u||u.length<80&&/å·²å°|å·²åå ¥|åå ¥å·¦ä¾§|applied to (the )?left/i.test(u))continue;const p=Du(u);if(p)return p}return null}const ak=2,lk=20,ck=2,dk=8;function oy(r){return String(r.label||"").trim().length>=ck||String(r.beatSummary||"").trim().length>=dk}function iy(r,t){const i=Array.isArray(r)?r:[];if(t.standaloneFilmMode){const f=i[0];return f?(Array.isArray(f.generationUnits)?f.generationUnits:[]).some(oy):!1}const a=Math.max(1,Math.min(100,Math.floor(t.plannedEpisodeCount)||1)),u=i.slice(0,a);return u.length<1||!u.every(f=>String(f.title||"").trim().length>
214=ak&&String(f.summary||"").trim().length>=lk)?!1:u.some(f=>(Array.isArray(f.generationUnits)?f.generationUnits:[]).some(oy))}const _r="root";function Eu(r){return r.status?r.status:String(r.descriptiveScript||"").trim()?"generated":"empty"}function tc(r,t,i){let a=String(r||"").trim();if(!a)return"";a=a.replace(/^Sequence\s*\d+\s*[·\-ââ:]?\s*/i,"").trim(),a=a.replace(/^åº\s*\d+(?:\.\d+)?\s*[·\-ââ:]?\s*/i,"").trim();const u=String(i||"").trim();return u&&(a===u||a===`Episode ${t+1}`||/^Episode\s+\d+$/i.test(a))||/^Episode\s+\d+$/i.test(a)?"":a}const Rh=48;function Jd(r,t=Rh){const i=String(r||"").replace(/\s+/g," ").trim();return i?i.length<=t?i:`${i.slice(0,Math.max(1,t-1)).trimEnd()}â¦`:""}function uk(r,t,i=Rh){var S,k;const a=tc(String(r.label||""),r.index,t);if(a)return Jd(a,i);const u=String(r.beatSummary||"").trim();if(u)return Jd(u,i);const p=String(r.descriptiveScript||"").trim();if(!p)return"";const f=((S=p.split(/\n/)[0])==null?void 0:S.replace(/^#+\s*/,"").trim())||"";if(!f)return"";const x=((k=f.split(/[ã.!ï¼?]/)[0])==null?void 0:k.trim())||f;return Jd(x,i)}function ay(r,t,i,a){var S;const u=t.index+1,p=String(t.label||"").trim()||`Sequence ${u}`,f=tc(p,t.index,a),x=uk(t,a);return{id:`ep:${r}:seq:${t.index}`,kind:"sequence",label:((S=i==null?void 0:i.sequence)==null?void 0:S.call(i,u,""))??`Seq. ${u}`,title:f||p,summary:x,episodeIndex:r,actId:t.actId,unitIndex:t.index,status:Eu(t)}}function Qd(r,t,i,a){var p;const u=t+1;return{id:`ep:${r}:seq:${t}`,kind:"sequence",label:((p=i==null?void 0:i.sequence)==null?void 0:p.call(i,u,""))??`Seq. ${u}`,title:"",summary:"",episodeIndex:r,actId:a,unitIndex:t,status:"empty"}}function Yi(r,t){return!t.has(r)}function pk(r){var f;
214const t=Array.isArray(r.episodes)?r.episodes:[],i=r.collapsedIds??new Set,a=r.labels,u=String(r.projectTitle||"").trim();if(r.standaloneFilmMode){const x=t[0],S=Array.isArray(x==null?void 0:x.generationUnits)?[...x.generationUnits]:[],k=new Map;for(const $ of S){const O=$.actId===2||$.actId===3?$.actId:1,D=k.get(O)||[];D.push($),k.set(O,D)}const I=[1,2,3].map($=>{var z;const O=`act:${$}`,D=k.get($)||[],n=D.length>0?D.map(Z=>ay(0,Z,a,x==null?void 0:x.title)):[Qd(0,$-1,a,$)];return{id:O,kind:"act",label:((z=a==null?void 0:a.act)==null?void 0:z.call(a,$))??`Act ${$}`,actId:$,expanded:Yi(O,i),children:n,status:D.some(Z=>Eu(Z)==="generated")?"generated":D.length>0?"pending":"empty"}});return{id:_r,kind:"root",label:(a==null?void 0:a.structureRoot)??(a==null?void 0:a.rootFilm)??(u||"Film"),title:u,expanded:Yi(_r,i),children:I}}const p=t.map((x,S)=>{var O;const k=`episode:${S}`,v=String(x.title||"").trim()||`Episode ${S+1}`,I=Array.isArray(x.generationUnits)?x.generationUnits:[],$=I.length>0?I.map(D=>ay(S,D,a,v)):[Qd(S,0,a)];return{id:k,kind:"episode",label:((O=a==null?void 0:a.episode)==null?void 0:O.call(a,S+1,v))??`Ep. ${S+1} ${v}`,title:v,episodeIndex:S,expanded:Yi(k,i),children:$,status:I.some(D=>Eu(D)==="generated")?"generated":String(x.summary||"").trim()?"pending":"empty"}});if(p.length===0){const x="episode:0";p.push({id:x,kind:"episode",label:((f=a==null?void 0:a.episode)==null?void 0:f.call(a,1,"Episode 1"))??"Ep. 1 Episode 1",title:"Episode 1",episodeIndex:0,expanded:Yi(x,i),children:[Qd(0,0,a)],status:"empty"})}return{id:_r,kind:"root",label:(a==null?void 0:a.structureRoot)??(a==null?void 0:a.rootSeries)??(u||"Series"),title:u,expanded:Yi(_r,i),children:p}}function jh(r,t){if(r.id===t)return r;for(const i of r.children||[]){const a=jh(i,t);if(a)return a}return null}function Tu(r){if(!r)return null;if(r.kind==="sequence")return r;for(const t of r.children||[]){const i=Tu(t);if(i)return i}return null}const mk=220;function Ah(r){return String(r||"").trim().length>=mk}function fk(r){const t=[];return r.forEach((i,a)=>{const u=Array.isArray(i.generationUnits)?i.generationUnits:[];for(const p of u){const f=typeof p.index=="number"?p.index:t.length;t.push({id:`ep:${a}:seq:${f}`,episodeIndex:a,unitIndex:f,script:String(p.descriptiveScript||"")})}}),t}function yk(r){const t=String(r||"").trim();return!t||t===_r?!1:/^ep:\d+:seq:\d+$/.test(t)}function ly(r){return r.length===0?null:r.find(t=>!Ah(t.script))||r[0]||null}function hk(r){const t=r.layoutTab,i=r.sequences;if(t==="outline")return r.storyArcReady?{kind:"set_tab",useGoToWorkflowLabel:!1,tab:"world"}:{kind:"focus_field",useGoToWorkflowLabel:!1,focusField:r.loglineIncomplete===!1?"outline-synopsis":"outline-logline"};if(t==="world")return r.worldBibleReady?{kind:"set_tab",useGoToWorkflowLabel:!1,tab:"assets"}:{kind:"focus_field",useGoToWorkflowLabel:!1,focusField:"world-dimension",worldDimensionId:String(r.firstEmptyWorldDimensionId||"").trim()||void 0};if(t==="assets"){if(i.length===0)return{kind:"start_breakdown",useGoToWorkflowLabel:!1,tab:"episodes"};const x=ly(i);return{kind:"select_sequence",useGoToWorkflowLabel:!1,tab:"episodes",sequenceId:x.id,episodeIndex:x.episodeIndex,unitIndex:x.unitIndex}}if(i.length===0)return{kind:"start_breakdown",useGoToWorkflowLabel:!1,tab:"episodes"};const a=String(r.hierarchySelectedId||"").trim(),u=yk(a)&&i.find(x=>x.id===a)||null;if(!u){const x=ly(i);return{kind:"select_sequence",useGoToWorkflowLabel:!1,tab:"episodes",sequenceId:x.id,episodeIndex:x.episodeIndex,unitIndex:x.unitIndex}}if(!Ah(u.script))return{kind:"focus_sequence_editor",useGoToWorkflowLabel:!1,sequenceId:u.id,episodeIndex:u.episodeIndex,unitIndex:u.unitIndex};const p=i.findIndex(x=>x.id===u.id),f=p>=0?i[p+1]:void 0;return f?{kind:"select_sequence",useGoToWorkflowLabel:!1,tab:"episodes",sequenceId:f.id,episodeIndex:f.episodeIndex,unitIndex:f.unitIndex}:{kind:"open_workflow",useGoToWorkflowLabel:!0,sequenceId:u.id,episodeIndex:u.episodeIndex,unitIndex:u.unitIndex}}function cy(r){if(typeof document>"u")return;const t=()=>{let i="";if(r.kind==="focus_field"&&r.focusField==="world-dimension"&&r.worldDimensionId)i=`[data-storyflow-focus="world-dimension"][data-world-dimension="${r.worldDimensionId}"]`;else if(r.kind==="focus_field"&&r.focusField)i=`[data-storyflow-focus="${r.focusField}"]`;else if(r.kind==="focus_sequence_editor")i='[data-storyflow-focus="sequence-editor"]';else return;const a=document.querySelector(i);if(a){try{a.focus({preventScroll:!0})}catch{a.focus()}a.scrollIntoView({block:"nearest",behavior:"smooth"})}};window.requestAnimationFrame(()=>window.setTimeout(t,0))}function gk(r){const t=String(r||"").trim();return t?!!(/^https?:\/\//i.test(t)||/^data:image\//i.test(t)||/^blob:/i.test(t)||t.startsWith("/")||t.startsWith("./")):!1}function xk(r,t,i){if(!gk(r))return!1;const a=String(t||"").trim(),u=String(i||"").trim();return!a||!u?!1:a!==u}function Do(){return!0}const Ih="storyflow-bloombot-history-",bk=80;function dy(r,t){try{return new Intl.DateTimeFormat(t==="zh"?"zh-CN":"en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(r))}catch{return""}}function Ph(r){var p;const t=r.find(f=>f.role==="user"&&(f.text||"").trim()),i=((t==null?void 0:t.text)||"").trim()||(((p=r.find(f=>f.role==="assistant"&&(f.text||"").trim()))==null?void 0:p.text)||"").trim()||"Chat",a=(i.split(/\n/)[0]||i).trim(),u=[...a];return u.length<=10?a:`${u.slice(0,10).join("")}â¦`}function _h(r){return r.some(t=>t.role==="user"&&(t.text||"").trim().length>0)}function Ll(r){if(!r||typeof window>"u")return[];try{const t=localStorage.getItem(Ih+r);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(a=>{if(!a||typeof a!="object")return!1;const u=a;return typeof u.id=="string"&&typeof u.savedAt=="number"&&typeof u.summary=="string"&&Array.isArray(u.messages)}):[]}catch{return[]}}function wk(r,t){if(!r||typeof window>"u"||!_h(t))return Ll(r);const u=[{id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,savedAt:Date.now(),summary:Ph(t),messages:JSON.parse(JSON.stringify(t))},...Ll(r)].slice(0,bk);try{localStorage.setItem(Ih+r,JSON.stringify(u))}catch{}return u}const Sk=/\[\[OPTIONS:[^\]]*\]\]/gi,kk=/(?:æ»å ±\s*å¤å°\s*é|ä¸å ±æ\s*å¤å°\s*é|æ¯é\s*叿\s*æå¤é¿|how\s+many\s+episodes|episodes?\s+in\s+total|per[- ]episode\s+duration)/iu,uy=/(?:第[ä¸äºä¸123]\s*å¹|ä¸å¹ç»æ|Act\s+(?:I|II|III|1|2|3)\b|SCREENPLAY|å§æ¬|åºæ¯[ä¸äºä¸å\d]|INT\.|EXT\.|Shot\s+\d+|é头\s*\d+|%%.+%%|@@.+ã|â³â³|ââ|\[\[SCENE:|\[\[PROP:|EPISODE\s+BLUEPRINT|åº\s*\d+)/iu;function Bh(r){let t=String(r||"").trim();if(!t)return"";t=t.replace(Sk,"").trim();const i=t.indexOf(Wn);if(i>=0){const a=t.indexOf(zn,i);a>=0&&(t=(t.slice(0,i)+t.slice(a+zn.length)).trim())}return t.replace(/\n{3,}/g,` 215 216`).trim()}function vk(r){const t=Bh(r);return t.length<24||kk.test(t)&&!uy.test(t)?!1:uy.test(t)?!0:t.length>=220&&/(?:å¼åº|转æ|髿½®|ç»å±|climax|midpoint|opening)/iu.test(t)}function Ck(r){const t=Bh(r);return vk(t)?t:null}function Nk(r){const t=r.map(a=>
216String(a||"").trim()).filter(Boolean);if(t.length===0)return"";if(t.length===1)return t[0];const i=[];for(const a of t){const u=i[i.length-1];if(!u){i.push(a);continue}if(u.includes(a)||a.includes(u)){i[i.length-1]=a.length>u.length?a:u;continue}i.push(a)}return i.join(` 217 218`).trim()}function py(r){const t=[];for(const i of r){if(i.role!=="assistant")continue;const a=String(i.rawAssistantReply||i.text||"").trim(),u=Ck(a);u&&t.push(u)}return Nk(t)}function Ek(r){const t=i=>({name:i.name,desc:i.desc,key:on(i.name)});return{characters:r.characters.filter(i=>Ss(i.name)).map(t),scenes:r.scenes.map(t),props:r.props.map(t)}}function Tk(r){const t=new Set,i=[];for(const a of r){const u=String(a||"").trim();!u||t.has(u)||(t.add(u),i.push(u))}return i.join(` 219 220`)}function Rk(r){return Ek(Zy(r))}function jk(r){var i,a,u;const t=[];for(const p of r.episodes||[]){(i=p.detailedScript)!=null&&i.trim()&&t.push(p.detailedScript),(a=p.detailedScriptBloomDraft)!=null&&a.trim()&&t.push(p.detailedScriptBloomDraft);for(const f of p.generationUnits||[])(u=f.descriptiveScript)!=null&&u.trim()&&t.push(f.descriptiveScript)}return t.push(...r.bibleCharacterMarkerLines||[]),t.push(...r.extraTexts||[]),Tk(t)}function Ak(r){return(r==null?void 0:r.storyflow_pro_simple_ux)!==!1}function Ik(r){if(!r.setupComplete)return"setup_modal";if(!(!!r.foundationLockedAt||r.hasEpisodes))return"foundation";const i=String(r.hierarchySelectedId||"").trim();return/^ep:\d+:seq:\d+$/.test(i)?"detail_script":"episode_wall"}function Pk(r){return!!r.foundationLockedAt||r.hasEpisodes}function _k(r){const t=r.loglineMinChars??12,i=[];return String(r.logline||"").trim().length<t&&i.push("logline"),r.worldBibleReady||i.push("world"),r.characterCount>0||i.push("character"),{ready:i.length===0,missing:i}}function Bk(r){return r.includes("world")?"world":r.includes("character")?"assets":r.includes("logline")?"outline":null}function Mk(r){return r.plannedEpisodeCount<1?!1:!r.hasEpisodes}function Lk(r){switch(r){case"setup_modal":return{nowKey:"pathNowSetup",nextKey:"pathNextFoundation"};
220case"foundation":return{nowKey:"pathNowFoundation",nextKey:"pathNextWall"};case"episode_wall":return{nowKey:"pathNowWall",nextKey:"pathNextWrite"};case"detail_script":return{nowKey:"pathNowWrite",nextKey:"pathNextHandoff"}}}const Mh=["setup_modal","foundation","episode_wall","detail_script"];function Qo(r){const t=Mh.indexOf(r);return t>=0?t:0}function Ok(r,t){const i=Qo(r),a=Qo((t==null?void 0:t.unlockedThrough)??r),u=(t==null?void 0:t.filmMode)===!0;return Mh.map((p,f)=>{const x=f===i?"current":f<=a?"done":"locked";let S="proSimpleStepSetup";return p==="foundation"?S="proSimpleStepFoundation":p==="episode_wall"?S=u?"proSimpleStepWallFilm":"proSimpleStepWall":p==="detail_script"&&(S="proSimpleStepWrite"),{id:p,tone:x,labelKey:S}})}function $k(r){const t=r.unlockedThrough??r.current;if(!t)return!1;const i=Qo(r.target),a=Qo(t);return!(i>a||r.target==="setup_modal")}function Fk(r,t){const i=String(t||"").trim(),a=String(r||"").trim();return i?/^(ä¸ä¸æ¥\s*[ï¼:]|Next:\s*)/i.test(i)||!a?i:/[ï¼:]$/.test(a)?`${a}${i}`:`${a} ${i}`:a}function Dk(r){return r.foundationLockedAt?String(r.foundationLockedAt):r.hasEpisodes?r.nowIso||new Date().toISOString():null}function my(r){return r.detailConfirmed?"done":r.hasEditedContent?"editing":"editable"}function fy(r){return String(r||"").trim().length>0}function yy(r){return!(r.storyArcReady&&r.worldBibleReady)}function zl(r){const t=String(r||"");if(!t.trim())return!1;if(/##\s*.{0,24}(åéå§æ æ¿|åé颿¿|Episode\s*Board|episode\s*board)/i.test(t))return!0;const i=t.match(/\|\s*第\s*\d+\s*é\s*\|/g);if(i&&i.length>=2)return!0;const a=t.match(/\|\s*(?:Ep\.?\s*|Episode\s*)\d+\s*\|/gi);return!!(a&&a.length>=2)}function Uu(r){const t=String(r||""),i=t.match(/\|\s*第\s*\d+\s*é\s*\|/g);if(i!=null&&i.length)return i.length;const a=t.match(/\|\s*(?:Ep\.?\s*|Episode\s*)\d+\s*\|/gi);return(a==null?void 0:a.length)??0}function Wu(r){const t=String(r||""),i=t.match(/##\s*(\d+)\s*é/)||t.match(/(\d+)\s*é\s*åé/)||t.match(/##\s*(\d+)[-\s]*[Ee]pisode/)||t.match(/\b(\d+)\s*[Ee]pisodes?\b/);if(!i)return null;const a=Number(i[1]);return Number.isFinite(a)&&a>=2&&a<=100?a:null}function Ru(r){const t=String(r||"").trimEnd();if(!zl(t))return!1;const i=Wu(t),a=Uu(t);if(i!=null&&a>0&&a<i||/[\uFFFD]$/.test(t)||/第\s*\d+\s*é[^\n|]*$/u.test(t)&&a>=1&&(i==null||a<i)||/(?:Ep\.?\s*|Episode\s*)\d+[^\n|]*$/i.test(t)&&!/\|\s*$/.test(t)&&a>=1)return!0;const u=(t.split(` 221`).pop()||"").trim();if(/^[|ï½]/.test(u)){const p=(u.match(/[|ï½]/g)||[]).length;if(p>0&&p<3)return!0}return!1}function Uk(r){return r==="zh"?`## FOUNDATION GATE (required) 222å§æ ç®ä»ï¼synopsisï¼ä¸äºç»´ä¸çè§å°æªåé½å°å·¦ä¾§çæ¿æ¶ï¼ 223- **ç¦æ¢**è¾åºå®æ´ãNéåéå§æ æ¿ã大表æééåæ»¡ 6â12 éã 224- æ¬åååªè¡¥ï¼å§æ ç®ä»ãä¸çè§äºç»´ãè§è²å½¢è±¡ï¼å¯ç¨ @@åãæè¿°ãï¼ï¼å¹¶å¨ææ«ç¨ [[OPTIONS: â¦]] ç»åºä¸ä¸æ¥ã 225- è¥ç¨æ·ç¡¬è¦åéï¼å 说æãå åé½ä¸çè§ä¸ç®ä»ååéæ´ç¨³ãï¼æå¤ç» **1â2 é示æ**ï¼å¹¶æä¾è¯çï¼è¡¥é½ä¸çè§ / è¡¥é½ç®ä» / ç¨ååååéã 226ä¸çè§ + å§æ ç®ä»é½å°±ç»ªåï¼æå è®¸å®æ´åéå§æ æ¿ï¼ä¸æ¬¡åä¸å®å°±å卿´éè¾¹çï¼å¹¶ç»ãç»§ç»åå®å©ä½åéãè¯çã`:`## FOUNDATION GATE (required) 227Until synopsis + all five world-bible dimensions are on the board: 228- Do **NOT** output a full N-episode storyline board (6â12 rows). 229- This turn: finish synopsis, world bible, and character looks (@@Nameãlookã), then [[OPTIONS: â¦]] for next step. 230- If the user insists on episodes, warn briefly, give at most **1â2 sample episodes**, and chip: fill worldview / fill synopsis / defer episode board. 231Only after synopsis + world bible are ready may you output a full episode board; if length-limited, stop on a whole-episode boundary and chip "Continue remaining episodes".`}function Wk(r){const t=String(r.reply||"");if(!t.trim()||/\[\[OPTIONS:/i.test(t)&&!r.truncated&&!Ru(t)&&(!yy(r)||!zl(t)))return t;const i=yy(r),a=!!r.truncated||Ru(t),u=i&&zl(t);if(!a&&!u)return t;const p=r.locale==="zh",f=[t.trimEnd()];return u&&!a?(f.push(p?` 232 233[ä¸ä¸æ¥æç¤º] 234ä¸çè§æå§æ ç®ä»å°æªåé½å°å·¦ä¾§çæ¿ã宿´åéæ¿å®¹æåå°ä¸åè¢«æªæï¼å»ºè®®å è¡¥é½è®¾å®ï¼åçæåéã`:` 235 236[NEXT STEP HINT] 237Synopsis or worldview is still incomplete on the board. Full episode boards often truncate mid-way â finish foundation first, then generate episodes.`),f.push(p?` 238[[OPTIONS: 帮æåé½äºç»´ä¸çè§, 帮æè¡¥å ¨å§æ ç®ä», ç»§ç»åå®å©ä½åé]]`:` 239[[OPTIONS: Fill worldview (5 fields), Complete synopsis, Continue remaining episodes]]`),f.join("")):(f.push(p?` 240 241[ä¸ä¸æ¥æç¤º] 242åå¤å é¿åº¦è¢«æªæï¼åéæ¿æªåå®ã请ç¹ä¸æ¹è¯çç»§ç»ï¼æå åå»è¡¥é½ä¸çè§/ç®ä»ã`:` 243 244[NEXT STEP HINT] 245Reply was truncated â the episode board is incomplete. Use a chip below to continue, or finish worldview/synopsis first.`),i?f.push(p?` 246[[OPTIONS: ç»§ç»åå®å©ä½åé, å è¡¥é½äºç»´ä¸çè§, å è¡¥å ¨å§æ ç®ä»]]`:` 247[[OPTIONS: Continue remaining episodes, Fill worldview first, Complete synopsis first]]`):f.push(p?` 248[[OPTIONS: ç»§ç»åå®å©ä½åé, 仿ªæå¤æ¥çå, å å
248缩æçå§æ æ¿]]`:` 249[[OPTIONS: Continue remaining episodes, Resume from cutoff, Shorter episode board]]`),f.join(""))}function Hk(r){const t=String(r||"");return t.trim()?Ru(t):!1}function zk(r){return zl(String(r||""))}function Kk(r){const t=r.lockMissing,i=r.lastAssistantText;if(r.stage==="foundation"){if(Hk(i)){const a=Uu(String(i||"")),u=Wu(String(i||"")),p=!r.storyArcReady||!r.worldBibleReady;return{id:"incomplete_episode_board_chat",titleKey:"proSimpleSitIncompleteBoardTitle",bodyKey:p?"proSimpleSitIncompleteBoardBodyWithGaps":u!=null&&a>0?"proSimpleSitIncompleteBoardBodyProgress":"proSimpleSitIncompleteBoardBody",actions:[{kind:"ask_bloombot",labelKey:"proSimpleSitActionContinueBoard",bloombotPromptKey:"proSimpleSitPromptContinueBoard",primary:!0,testId:"storyflow-sit-continue-board"},...p?[{kind:"sync_board",labelKey:"proSimpleSitActionSyncBoard",testId:"storyflow-sit-sync-board"},{kind:"open_tab",labelKey:"proSimpleSitActionOpenWorld",tab:"world",testId:"storyflow-sit-open-world"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskFillFoundation",bloombotPromptKey:"proSimpleSitPromptFillFoundation",testId:"storyflow-sit-ask-foundation"}]:[]]}}return zk(i)&&(!r.storyArcReady||!r.worldBibleReady||t.includes("character"))?{id:"early_episode_board_missing_foundation",titleKey:"proSimpleSitEarlyBoardTitle",bodyKey:"proSimpleSitEarlyBoardBody",actions:[{kind:"sync_board",labelKey:"proSimpleSitActionSyncBoard",primary:!0,testId:"storyflow-sit-sync-board"},{kind:"open_tab",labelKey:t.includes("world")?"proSimpleSitActionOpenWorld":t.includes("character")?"proSimpleSitActionOpenAssets":"proSimpleSitActionOpenOutline",tab:t.includes("world")?"world":t.includes("character")?"assets":"outline",testId:"storyflow-sit-open-gap-tab"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskFillFoundation",bloombotPromptKey:"proSimpleSitPromptFillFoundation",testId:"storyflow-sit-ask-foundation"}]}:r.lockReady?{id:"ready_to_lock",titleKey:"proSimpleSitReadyLockTitle",bodyKey:"proSimpleSitReadyLockBody",actions:[]}:t.includes("world")?{id:"missing_world",titleKey:"proSimpleSitMissingWorldTitle",bodyKey:"proSimpleSitMissingWorldBody",actions:[{kind:"open_tab",labelKey:"proSimpleSitActionOpenWorld",tab:"world",primary:!0,testId:"storyflow-sit-open-world"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskWorld",bloombotPromptKey:"proSimpleSitPromptFillWorld",testId:"storyflow-sit-ask-world"}]}:t.includes("logline")||!r.storyArcReady?{id:"missing_synopsis_or_logline",titleKey:"proSimpleSitMissingOutlineTitle",bodyKey:"proSimpleSitMissingOutlineBody",actions:[{kind:"open_tab",labelKey:"proSimpleSitActionOpenOutline",tab:"outline",primary:!0,testId:"storyflow-sit-open-outline"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskOutline",bloombotPromptKey:"proSimpleSitPromptFillOutline",testId:"storyflow-sit-ask-outline"}]}:t.includes("character")?{id:"missing_character",titleKey:"proSimpleSitMissingRoleTitle",bodyKey:"proSimpleSitMissingRoleBody",actions:[{kind:"open_tab",labelKey:"proSimpleSitActionOpenAssets",tab:"assets",primary:!0,testId:"storyflow-sit-open-assets"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskRole",bloombotPromptKey:"proSimpleSitPromptFillRole",testId:"storyflow-sit-ask-role"}]}:{id:"generic_foundation",titleKey:"proSimpleSitGenericFoundationTitle",bodyKey:"proSimpleSitGenericFoundationBody",actions:[{kind:"open_tab",labelKey:"proSimpleSitActionOpenWorld",tab:r.layoutTab==="outline"?"world":r.layoutTab==="world"?"assets":"outline",primary:!0}]}}if(r.stage==="episode_wall")return r.hasEpisodes?{id:"episode_wall_pick_card",titleKey:"proSimpleSitWallPickTitle",bodyKey:"proSimpleSitWallPickBody",actions:[{kind:"none",labelKey:"proSimpleSitActionClickCard"}]}:{id:"episode_wall_empty",titleKey:"proSimpleSitWallEmptyTitle",bodyKey:"proSimpleSitWallEmptyBody",actions:[{kind:"none",labelKey:"proSimpleSitActionWaitCards"}]};if(r.stage==="detail_script"){const a=!r.detailScriptHasBody;return a&&r.lastAssistantLooksLikeUnitScript?{id:"detail_script_empty_with_chat",titleKey:"proSimpleSitWriteApplyChatTitle",bodyKey:"proSimpleSitWriteApplyChatBody",actions:[{kind:"apply_chat_script",labelKey:"proSimpleSitActionApplyChatScript",primary:!0,testId:"storyflow-sit-apply-chat-script"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskExpandScript",bloombotPromptKey:"proSimpleSitPromptExpandScript",testId:"storyflow-sit-ask-expand-script"}]}:a?{id:"detail_script_empty",titleKey:"proSimpleSitWriteEmptyTitle",bodyKey:"proSimpleSitWriteEmptyBody",actions:[{kind:"open_fab",labelKey:"proSimpleSitActionOpenFab",primary:!0,testId:"storyflow-sit-open-fab"},{kind:"ask_bloombot",labelKey:"proSimpleSitActionAskExpandScript",bloombotPromptKey:"proSimpleSitPromptExpandScript",testId:"storyflow-sit-ask-expand-script"}]}:{id:"detail_script_write",titleKey:"proSimpleSitWriteTitle",bodyKey:"proSimpleSitWriteBody",actions:[{kind:"none",labelKey:"proSimpleSitActionSaveOrWorkflow"}]}}return{id:"generic_foundation",titleKey:"proSimpleSitGenericFoundationTitle",bodyKey:"proSimpleSitGenericFoundationBody",actions:[]}}function qk(r){return r?r!=="ready_to_lock"&&r!=="episode_wall_pick_card"&&r!=="episode_wall_empty":!1}function Gk(r){const t=String(r||""),i=Uu(t),a=Wu(t);return i<=0||a==null?null:{rows:i,claimed:a}}const Yk=({cards:r,emptyLabel:t,hintLabel:i,onSelect:a,synopsisFallbackLabel:u=""})=>r.length?s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3","data-testid":"storyflow-episode-wall",children:[s.jsx("p",{className:"shrink-0 text-center text-xs text-neutral-500",children:i}),s.jsx("div",{className:"grid min-h-0 flex-1 auto-rows-min grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-2.5 overflow-y-auto custom-scrollbar",children:r.map(p=>{const x=String(p.synopsis||"").trim()||u;return s.jsxs("button",{type:"button","data-testid":`storyflow-episode-wall-card-${p.hierarchyId}`,"aria-describedby":x?`storyflow-episode-wall-tip-${p.hierarchyId}`:void 0,onClick:()=>a(p.hierarchyId),className:"group relative flex min-h-[110px] flex-col gap-1.5 rounded-xl border border-white/10 bg-[#12151a] p-3 text-left transition-colors hover:border-primary/40 hover:z-10",children:[s.jsx("span",{className:"text-[10px] font-extrabold uppercase tracking-wide text-neutral-500",children:p.subtitle}),s.jsx("span",{className:"text-sm font-extrabold text-white",children:p.title}),s.jsx("span",{className:`mt-auto text-[11px] font-extrabold ${p.statusTone==="done"?"text-emerald-400":p.statusTone==="ready"?"text-primary":p.statusTone==="writing"?"text-amber-300":"text-neutral-500"}`,children:p.statusLabel}),x?s.jsx("span",{id:`storyflow-episode-wall-tip-${p.hierarchyId}`,className:"pointer-events-none absolute left-1/2 top-full z-20 mt-1.5 hidden w-[min(280px,70vw)] -translate-x-1/2 roun
249ded-lg border border-white/15 bg-[#0d1117] px-2.5 py-2 text-left text-[11px] leading-snug text-neutral-200 shadow-xl group-hover:block","data-testid":`storyflow-episode-wall-card-tip-${p.hierarchyId}`,role:"tooltip",children:x}):null]},p.hierarchyId)})})]}):s.jsx("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-white/15 p-8 text-center","data-testid":"storyflow-episode-wall-empty",children:s.jsx("p",{className:"text-sm text-neutral-400",children:t})}),hy=({open:r,showFab:t,fabLabel:i,onOpen:a,onClose:u,children:p,closeLabel:f,titleLabel:x})=>s.jsxs(s.Fragment,{children:[r?s.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col overflow-hidden bg-[#0d0f12]","data-testid":"storyflow-bloombot-fab-dock",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-white/10 px-3 py-2",children:[s.jsx("span",{className:"text-xs font-extrabold text-white",children:x}),s.jsx("span",{className:"grow"}),s.jsx("button",{type:"button",className:"rounded-md px-2 py-1 text-[11px] font-bold text-neutral-400 hover:text-white",onClick:u,"data-testid":"storyflow-bloombot-fab-close",children:f})]}),s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:p})]}):null,t&&!r?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"absolute bottom-[22px] right-[22px] z-[8] flex h-[52px] w-[52px] items-center justify-center rounded-full border border-primary/45 bg-[radial-gradient(circle_at_35%_30%,#1f2937_0%,#0a0c0e_70%)] shadow-[0_8px_28px_rgba(0,0,0,0.55),0_0_0_3px_rgba(163,230,53,0.12)] transition-transform hover:scale-105",onClick:a,title:i,"aria-label":i,"data-testid":"storyflow-bloombot-fab",children:[s.jsx("img",{src:Jy,alt:"",className:"pointer-events-none h-7 w-7"}),s.jsx("span",{className:"absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-primary shadow-[0_0_0_2px_#0a0c0e]","aria-hidden":!0})]}),s.jsx("div",{className:"pointer-events-none absolute bottom-[34px] right-[82px] z-[8] rounded-full border border-primary/35 bg-black/90 px-2 py-1 text-[11px] font-extrabold text-[#d9f99d]","data-testid":"storyflow-bloombot-fab-label",children:i})]}):null]});function Vk({steps:r,nextHint:t,ariaLabel:i,onSelectStep:a,primaryCtaLabel:u,primaryCtaTestId:p="storyflow-pro-simple-lock-cta",onPrimaryCta:f,primaryCtaHighlight:x=!1,primaryCtaReady:S=!0,readinessChips:k=null,readinessWarn:v=null,situationGuide:I=null}){const $=!!(u&&f),O=!!(I!=null&&I.title&&(I!=null&&I.body));return s.jsx("div",{className:`mb-3 shrink-0 rounded-xl border bg-gradient-to-b from-primary/10 to-black/30 px-3 py-2.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ${x?"border-red-400/50":"border-primary/35"}`,"data-testid":"storyflow-pro-simple-path-bar","data-tour":"gl-pro-simple-progress",role:"navigation","aria-label":i,children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("ol",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:r.map((D,n)=>{const z=D.tone==="done",Z="inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-bold transition-colors sm:text-xs",Ee=D.tone==="current"?"border-primary bg-primary text-black shadow-[0_0_0_1px_rgba(94,225,197,0.35)]":D.tone==="done"?"border-primary/50 bg-primary/15 text-primary hover:bg-primary/25":"border-white/10 bg-white/[0.03] text-neutral-500 cursor-not-allowed opacity-70";return s.jsxs("li",{className:"flex items-center gap-1.5 sm:gap-2",children:[n>0?s.jsx("span",{className:`hidden h-px w-4 sm:block sm:w-6 ${D.tone==="locked"?"bg-white/10":"bg-primary/40"}`,"aria-hidden":!0}):null,s.jsxs("button",{type:"button",disabled:!z,"data-testid":`storyflow-pro-simple-step-${D.id}`,"data-tone":D.tone,"aria-current":D.tone==="current"?"step":void 0,onClick:()=>{z&&a(D.id)},className:`${Z} ${Ee} ${z?"cursor-pointer":""}`,children:[D.tone==="done"?s.jsx("span",{className:"text-[10px] leading-none","aria-hidden":!0,children:"â"}):null,s.jsx("span",{children:D.label})]})]},D.id)})}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[11px]",children:[s.jsx("span",{className:"font-semibold text-neutral-300",children:t}),k&&k.length>0?k.map(D=>{const n=!D.ok&&typeof D.onClick=="function",z=`rounded-full px-2 py-0.5 text-[10px] font-bold ${D.ok?"bg-primary/15 text-primary":n?"cursor-pointer bg-red-500/15 text-red-300 underline-offset-2 hover:bg-red-500/25 hover:underline":"bg-red-500/15 text-red-300"}`;return n?s.jsx("button",{type:"button",className:z,"data-testid":D.testId,onClick:D.onClick,children:D.label},D.label):s.jsx("span",{className:z,"data-testid":D.testId,children:D.label},D.label)}):null,v&&!O?s.jsx("span",{className:"w-full text-[11px] font-semibold text-amber-200/90",children:v}):null]})]}),O&&I?s.jsxs("div",{className:"max-w-[min(100%,320px)] shrink-0 rounded-lg border border-amber-400/35 bg-amber-500/10 px-2.5 py-2 sm:max-w-[360px]","data-testid":"storyflow-pro-simple-situation-guide",role:"status",children:[s.jsx("p",{className:"text-[11px] font-bold text-amber-100 sm:text-xs",children:I.title}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-snug text-amber-50/90",children:I.body}),I.actions.length>0?s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:I.actions.map(D=>s.jsx("button",{type:"button","data-testid":D.testId,onClick:D.onClick,className:D.primary?"rounded-md bg-primary px-2.5 py-1 text-[10px] font-bold text-black hover:brightness-110 sm:text-[11px]":"rounded-md border border-white/20 bg-black/30 px-2.5 py-1 text-[10px] font-bold text-neutral-200 hover:border-primary/40 hover:text-primary sm:text-[11px]",children:D.label},`${D.label}-${D.testId||""}`))}):null]}):null,$?s.jsx("button",{type:"button",className:`shrink-0 self-center rounded-lg px-3 py-1.5 text-[11px] font-bold sm:text-xs ${S?"bg-primary text-black hover:brightness-110":"cursor-pointer border border-white/15 bg-white/5 text-neutral-400 hover:border-red-400/40 hover:text-red-200"}`,"data-testid":p,"data-ready":S?"1":"0","aria-disabled":!S,onClick:f,children:u}):null]})})}const gy=`# Role 250You are BloomBot compiling a **literary descriptive screenplay** for Storyflow (not a shot list). 251 252# Output rules (strict) 253- Write **scene-level descriptive prose** with Workflow parse markers only. 254- **Forbidden:** Shot N, SHOT 01, é头01, Shot-by-Shot, storyboard tables, camera shot lists, director shot maps. 255- Use ${wb} 256- Dialogue only in %%Speaker: line%% ; narration only in $$...$$. 257- Do not invent new plot beats beyond the provided facts; expand visually and emotionally only. 258 259# Structure 2601) Optional short heading line for the unit (sequence or episode segment). 2612) Visual Bible lines for any **new** @@ / [[SCENE:]] / [[PROP:]] introduced in this unit. 2623) Flowing scene blocks (INT./EXT. or labeled scenes) with action and marked dialogue. 263 264Return **only** the screenplay text â no meta commentary.`.trim();function xy(r){const t=[],i=(a,u)=>{const p=String(u||"").trim();p&&t.push(`## ${a} 265${p}`)};return i("Project title",r.projectTitle),i("Logline",r.logline),i("Synopsis",r.synopsis),i("World bible",r.w
265orldBibleExcerpt),i("Episode title",r.episodeTitle),i("Episode summary",r.episodeSummary),i("Prior compiled units",r.priorUnitsExcerpt),i("Recent discussion",r.chatExcerpt),t.join(` 266 267`).slice(0,48e3)}function Xk(r){const{unit:t,facts:i,locale:a,unitIndex:u,unitTotal:p}=r,f=a==="zh"?"Write the screenplay in Simplified Chinese (marker syntax stays as specified).":a==="ja"?"Write in Japanese where appropriate; keep marker tokens in ASCII form.":a==="ko"?"Write in Korean where appropriate; keep marker tokens in ASCII form.":"Write in English.";return[`# Compile unit ${u+1} / ${p}`,`- Label: ${t.label}`,`- Target duration: ~${t.targetMinutes} minutes`,t.actId?`- Act: ${t.actId}`:"",f,"","# Facts (do not contradict)",i.trim()||"(none)","","# Task",`Write the descriptive screenplay for this unit only (~${t.targetMinutes} min of story time).`].filter(Boolean).join(` 268`)}function Lh(r){const t=String(r||"").trim();if(t.length<120)return{ok:!1,reason:"Compiled unit is too short."};const i=Sb(t);if(i.ok===!1)return{ok:!1,reason:i.reason};const a=eh(t);return a==="legacy_shot"?{ok:!1,reason:"Output looks like a legacy shot list."}:{ok:!0,format:a==="unknown"?"descriptive":a}}function Jk(r){return QS(r).map(t=>({...t,status:"pending"}))}function Qk(r,t,i){return r.map((a,u)=>u===t?{...a,descriptiveScript:i.trim(),status:"generated",canonStale:!1}:a)}function Zk(r,t){return r.map((i,a)=>a===t?{...i,status:"failed"}:i)}function by(r){return xu(r)}function ev(r){const t=[],i=String(r||"").trim();i||t.push("empty");const a=Lh(i);return a.ok===!1&&t.push(a.reason),{pass:t.length===0,reasons:t}}function sa(r){return ev(r).pass}function tv(r){const t=r.episodeIndex,i=r.durationSeconds;return`Continue the **descriptive literary screenplay** for Ep. ${String(t+1).padStart(2,"0")}: "${r.episodeTitle}". 269 270${r.baseContext} 271 272${r.characterLockContext} 273 274Duration target: 275- Episode duration: ${i}s (~${Math.round(i/60)} min of story time) 276- **Do NOT** write Shot N / é头 / storyboard rows â scene-level prose only. 277 278Continuity anchors: 279- Previous episode: ${r.prevEp?`${r.prevEp.title} â ${(r.prevEp.summary||"").trim()||"(empty)"}`:"(none)"} 280- Current episode summary (locked): ${r.episodeSummary.trim()||"(empty)"} 281- Next episode: ${r.nextEp?`${r.nextEp.title} â ${(r.nextEp.summary||"").trim()||"(empty)"}`:"(none)"} 282 283Use Workflow markers (@@ / [[SCENE:]] / [[PROP:]] / %% / $$). Run an internal editor pass for continuity before final output. 284 285Scope lock: 286- Write ONLY this episode. 287- Do NOT draft Episode ${t+2} or any other episode content now. 288 289If this episode descriptive script feels complete for the duration target, add: 290EPISODE COMPLETE. You can close this modal and click GO TO Workflow. 291`}function rv(r){const t=r.episodeIndex,i=r.durationSeconds;return`Create a **descriptive literary screenplay** for Ep. ${String(t+1).padStart(2,"0")}: "${r.episodeTitle}". 292 293${r.baseContext} 294 295${r.characterLockContext} 296 297Duration target: 298- Episode duration: ${i}s 299- Scene-level prose with Workflow markers â **no** Shot N / é头 lists. 300 301Continuity anchors: 302- Previous episode: ${r.prevEp?`${r.prevEp.title} â ${(r.prevEp.summary||"").trim()||"(empty)"}`:"(none)"} 303- Current episode summary (locked): ${r.episodeSummary.trim()||"(empty)"} 304- Next episode: ${r.nextEp?`${r.nextEp.title} â ${(r.nextEp.summary||"").trim()||"(empty)"}`:"(none)"} 305 306Write Visual Bible marker lines for main cast/scenes/props, then flowing scenes. Do not output shot tables. 307 308Scope lock: ONLY Ep. ${String(t+1).padStart(2,"0")}. 309`}async function sv(r){var f,x;const t=r.units.length;let i=r.units.map(S=>({...S}));const a=[],u=Math.max(0,r.maxRetriesPerUnit??1),p=xy(r.facts);for(let S=0;S<i.length;S+=1){const k=i[S];(f=r.onProgress)==null||f.call(r,{done:S,total:t,label:k.label});let v="",I="";for(let $=0;$<=u;$+=1)try{const O=by(i.slice(0,S)),D=xy({...r.facts,priorUnitsExcerpt:O.slice(-12e3)}),n=Ml(gy,void 0,"STORYFLOW_EPISODE_SCRIPT",{resolvedSystemOverride:gy}),z=Xk({unit:k,facts:D||p,locale:r.locale,unitIndex:S,unitTotal:t}),{text:Z}=await n.sendMessage(z),Ee=String(Z||"").trim(),Ie=Lh(Ee);if(Ie.ok===!1){I=Ie.reason;continue}v=Ee;break}catch(O){I=Bt(O instanceof Error?O.message:String(O))}v?i=Qk(i,S,v):(i=Zk(i,S),a.push(`${k.label}: ${I||"Generation failed."}`))}return(x=r.onProgress)==null||x.call(r,{done:t,total:t,label:""}),{units:i,mergedScript:by(i),errors:a}}const Oh="ãå 容ç®è¿°ã",$h="ã/å 容ç®è¿°ã",nv="[Scene brief]",ov="[/Scene brief]",Fh=new RegExp(`^(?:${Rl(Oh)}|${Rl(nv)})\\s*\\n([\\s\\S]*?)\\n(?:${Rl($h)}|${Rl(ov)}
309)\\s*(?:\\n+|$)`,"i");function Rl(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wy(r){const t=r.unit,i=typeof r.displayIndex=="number"?r.displayIndex:t.index+1,u=r.standaloneFilmMode===!0?`åº ${i}`:`åº ${i}`,p=tc(String(t.label||""),t.index,r.episodeTitle),f=String(t.beatSummary||"").trim(),x=String(r.episodeSummary||"").trim(),S=[];if(p?S.push(`${u} · ${p}`):S.push(u),f?S.push(f):x&&S.push(x),S.length===1){const v=Kl(String(t.descriptiveScript||"")).split(/\n/).map(I=>I.trim()).find(I=>I&&!/^#+\s/.test(I));v&&S.push(v)}return S.join(` 310`).trim()}function iv(r){const t=String(r||"").trim();return t?`${Oh} 311${t} 312${$h} 313 314`:""}function Kl(r){const t=String(r||"");if(!t.trim())return"";const i=Fh.exec(t);return i?t.slice(i[0].length).replace(/^\n+/,""):t.replace(/^\uFEFF/,"")}function av(r){const t=Fh.exec(String(r||""));return t&&String(t[1]||"").trim()||null}function Zd(r,t){const i=Kl(r),a=iv(t);return a?i.trim()?a+i.replace(/^\n+/,""):a.trimEnd()+` 315`:i}function lv(r,t){const i=String(t||"").replace(/\s+/g," ").trim();if(!i)return!0;const a=av(r);return a?a.replace(/\s+/g," ").trim()===i:!1}const Dh=({value:r,onChange:t,readOnly:i=!1,maxHeightClass:a="max-h-[min(40vh,420px)]",minHeightClass:u="min-h-[12rem]",testId:p,emptyText:f,ariaLabel:x,storyflowFocusAttr:S})=>{const k=String(r||"").trim();return!!t&&!i?s.jsx("textarea",{"data-testid":p,"data-storyflow-focus":S||void 0,"aria-label":x,className:`block w-full ${u} ${a}
315 overflow-y-auto custom-scrollbar rounded-lg border border-white/10 bg-black/20 p-3 text-xs leading-relaxed text-neutral-200 outline-none focus-visible:ring-2 focus-visible:ring-primary/40 resize-y`,value:r,onChange:I=>t==null?void 0:t(I.target.value)}):k?s.jsx("pre",{"data-testid":p,className:`${u} ${a} overflow-y-auto custom-scrollbar whitespace-pre-wrap rounded-lg border border-white/10 bg-black/20 p-3 text-xs leading-relaxed text-neutral-300`,children:kb(k.slice(0,12e4))}):s.jsx("p",{className:"text-xs text-neutral-500","data-testid":p,children:f||""})},cv="text-[10px] uppercase font-bold tracking-widest text-zinc-500",eu="text-[11px] uppercase font-bold tracking-wider text-primary",dv="min-w-0 flex-1 rounded border px-1 py-0.5 text-[10px] font-bold tabular-nums transition-colors";function uv(r){const{value:t,onChange:i,ratioLabel:a,categoryClassName:u=cv,size:p="comfortable",disabled:f,testIdPrefix:x="script-aspect"}=r;return p==="compact"?s.jsxs("div",{className:"min-w-0 flex flex-col gap-1",children:[s.jsx("span",{className:u,children:a}),s.jsx("div",{className:"flex items-center gap-1",children:["16:9","9:16"].map(S=>s.jsx("button",{type:"button",disabled:f,"aria-pressed":t===S,title:S,"data-testid":`${x}-${S.replace(":","-")}`,className:`${dv} ${t===S?"border-primary/60 bg-primary/15 text-primary":"border-white/15 text-zinc-400 hover:border-primary/40 hover:text-primary"} disabled:cursor-not-allowed disabled:opacity-40`,onClick:()=>{t!==S&&i(S)},children:S},S))})]}):s.jsxs("div",{className:"min-w-0 flex flex-col gap-1.5",children:[s.jsx("span",{className:u,children:a}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:["16:9","9:16"].map(S=>{const k=t===S;return s.jsxs("button",{type:"button",disabled:f,"aria-pressed":k,title:S,"data-testid":`${x}-${S.replace(":","-")}`,className:`flex min-h-[3.25rem] flex-col items-center justify-center gap-1 rounded-lg border px-2 py-2 transition-all ${k?"border-primary bg-primary/20 text-primary ring-1 ring-primary/30":"border-white/15 bg-black/25 text-zinc-200 hover:border-primary/50 hover:text-primary"} disabled:cursor-not-allowed disabled:opacity-40`,onClick:()=>{t!==S&&i(S)},children:[s.jsx(vb,{ratio:S,className:"h-5 w-5 flex-shrink-0 text-current"}),s.jsx("span",{className:"text-[12px] font-bold tabular-nums leading-none",children:S})]},S)})})]})}function pv(r){const{value:t,onChange:i,locale:a,noPreviewLabel:u,customUpload:p,size:f="comfortable",disabled:x,testIdPrefix:S="script-style"}=r,k=c.useRef(null),v=un.filter(n=>n.id!=="Custom (Upload Ref)"),I="Custom (Upload Ref)",$=f==="comfortable"?"truncate bg-black/70 px-1 py-1.5 text-[10px] font-semibold text-white":"truncate bg-black/70 px-1 py-1 text-[9px] font-medium text-white",O=f==="comfortable"?"text-[10px] font-medium":"text-[9px]",D=()=>{var n;x||p!=null&&p.analyzing||(p!=null&&p.imageUrl?p.onSelectCustom():(n=k.current)==null||n.click())};return s.jsxs(s.Fragment,{children:[p?s.jsx("input",{ref:k,type:"file",accept:"image/*",className:"hidden","data-testid":`${S}-custom-upload-input`,onChange:n=>{var Z;const z=(Z=n.target.files)==null?void 0:Z[0];n.target.value="",z&&p.onPickFile(z)}}):null,s.jsxs("div",{className:"grid grid-cols-5 gap-1.5",children:[v.map(n=>{const z=t===n.id;return s.jsxs("button",{type:"button",disabled:x,"data-testid":`${S}-${n.id}`,onClick:()=>i(n.id),className:`group relative flex flex-col rounded-lg overflow-hidden border-2 transition-all text-left hover:scale-[1.05] ${z?"border-primary ring-2 ring-primary/30":"border-white/10 hover:border-primary hover:shadow-[0_0_8px_rgba(163,230,53,0.2)]"} disabled:cursor-not-allowed disabled:opacity-40`,children:[s.jsx("div",{className:"relative shrink-0 overflow-hidden",children:n.preview?s.jsx(cn,{src:n.preview,alt:us(n.id,a),className:"aspect-video w-full"}):s.jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-black/50",children:s.jsx("span",{className:"text-white/40 text-[10px]",children:u})})}),s.jsx("div",{className:$,children:us(n.id,a)})]},n.id)}),p?(()=>{const n=t===I,{imageUrl:z,prompt:Z,analyzing:Ee,labels:Ie}=p;return s.jsxs("div",{role:"button",tabIndex:x?-1:0,"data-testid":`${S}-custom-upload`,onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),D())},onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),D()},className:`group relative flex flex-col rounded-lg overflow-hidden border-2 transition-all text-left hover:scale-[1.05] border-white/10 hover:border-primary hover:shadow-[0_0_8px_rgba(163,230,53,0.2)] cursor-pointer ${n?"border-primary ring-2 ring-primary/30":""} ${x?"cursor-not-allowed opacity-40 pointer-events-none":""}`,children:[s.jsxs("div",{className:"relative shrink-0 overflow-hidden",children:[z?s.jsx(cn,{src:z,alt:Ie.customRefAlt,className:"aspect-video w-full"}):s.jsxs("div",{className:"flex aspect-video w-full flex-col items-center justify-center bg-black/30 text-white/50",children:[s.jsx("span",{className:"material-symbols-outlined text-xl mb-0.5",children:"upload_file"}),s.jsx("span",{className:O,children:Ie.uploadShort})]}),Ee?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/70",children:s.jsx("span",{className:"material-symbols-outlined animate-spin text-primary text-lg",children:"sync"})}):null,z&&!Ee&&!x?s.jsxs("div",{className:"absolute inset-0 flex items-center justify-center gap-1 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity wf-touch-always-show",onClick:ne=>ne.stopPropagation(),children:[s.jsx("button",{type:"button",title:Ie.changeReference,onClick:ne=>{var Pe;ne.preventDefault(),ne.stopPropagation(),(Pe=k.current)==null||Pe.click()},className:"p-1 rounded bg-white/20 hover:bg-white/30 text-white text-[10px]",children:s.jsx("span",{className:"material-symbols-outlined text-sm",children:"edit"})}),s.jsx("button",{type:"button",title:Ie.remove,onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),p.onClearCustom()},className:"p-1 rounded bg-red-500/80 hover:bg-red-500 text-white text-[10px]",children:s.jsx("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]}):null]}
315),s.jsx("div",{className:$,title:Z||void 0,children:Ie.tileCaption})]})})():null]})]})}const mv="Untitled SCRIPT";function fv(r){const t=String(r??"").trim().slice(0,30);return t||mv}function Uh(r){const t=String(r??"").trim();return t==="9:16"||t==="16:9"?t:"16:9"}function Sy(r){var p,f;if(!r||typeof r!="object")return!1;if(r.storyflowProjectSetupComplete===!0)return!0;const t=!ws(r.projectName),i=r.seriesVisualStylePickerDismissed===!0||typeof r.seriesVisualStyleId=="string"&&r.seriesVisualStyleId.trim().length>0,a=!!String(((p=r.storyOutline)==null?void 0:p.logline)||"").trim()||!!String(((f=r.storyOutline)==null?void 0:f.synopsis)||"").trim(),u=Array.isArray(r.seasonEpisodes)&&r.seasonEpisodes.some(x=>!!String((x==null?void 0:x.summary)||"").trim()||!!String((x==null?void 0:x.detailedScript)||"").trim()||Array.isArray(x==null?void 0:x.generationUnits)&&x.generationUnits.length>0);return!!(t&&i||a&&i||u&&i)}function yv(r){const t=fv(r.title),i=String(r.visualStyleId||"").trim(),a=i==="Custom (Upload Ref)"?String(r.customStylePrompt||"").trim():"",u=String(r.synopsis||"").trim(),p=Array.isArray(r.collaboratorUserIds)?r.collaboratorUserIds.map(f=>String(f||"").trim()).filter(Boolean):[];return{storyflowProjectSetupComplete:!0,projectName:t,storyflowStandaloneFilmMode:r.standaloneFilmMode===!0,plannedEpisodeCount:r.standaloneFilmMode===!0?1:6,storyflowAspectRatio:Uh(r.aspectRatio),seriesVisualStyleId:i,seriesCustomStylePrompt:a,seriesVisualStylePickerDismissed:!0,storyOutlineSynopsis:u,setupCollaboratorUserIds:p}}function hv(r){return String(r.title||"").trim().length>30?"title_too_long":String(r.visualStyleId||"").trim()?String(r.visualStyleId||"").trim()==="Custom (Upload Ref)"&&!String(r.customStylePrompt||"").trim()?"style_custom_pending":null:"style_required"}const Uo="Custom (Upload Ref)",gv="pr-3",xv="bottom-3 right-3",ky={speechErrorNotAllowed:"canvas.node.promptSpeechErrorNotAllowed",speechErrorNetwork:"canvas.node.promptSpeechErrorNetwork",speechErrorAudioCapture:"canvas.node.promptSpeechErrorAudioCapture",speechErrorGeneric:"canvas.node.promptSpeechErrorGeneric"};function tu(r,t){const i=String(r||"").trimEnd(),a=String(t||"").trim();return a?i?`${i} ${a}`:a:i}function bv(r){const{initialTitle:t,onSubmit:i,onClose:a,t:u,locale:p}=r,f=p==="zh"?"zh":"en",x=c.useMemo(()=>un.filter(ie=>ie.id!==Uo),[]),[S,k]=c.useState(!0),[v,I]=c.useState("16:9"),[$,O]=c.useState(()=>{var ie;return((ie=x[0])==null?void 0:ie.id)??"Cinematic"}),[D,n]=c.useState(null),[z,Z]=c.useState(""),[Ee,Ie]=c.useState(!1),[ne,Pe]=c.useState(""),[xe,ae]=c.useState(null),[de,me]=c.useState(!1),Te=c.useRef(null),nt=c.useRef(!1),je=c.useRef(ne);je.current=ne;const ue=c.useRef(""),{supported:ve,listening:be,interimText:tt,userErrorKey:mr,toggleListening:ye,stopListening:rr}=ah({language:f==="zh"?"zh-CN":"en-US",scope:"storyflow_project_setup_speech",onFinalText:ie=>{nt.current=!0,Pe(dt=>{const Ft=String(dt||"").trimEnd(),ft=Ft?`${Ft} ${ie}`:ie;return je.current=ft,ft}),queueMicrotask(()=>{nt.current=!1})}});ue.current=tt;const Lt=c.useCallback(()=>{const ie=tu(je.current,ue.current);ie!==je.current&&(nt.current=!0,je.current=ie,Pe(ie),queueMicrotask(()=>{nt.current=!1})),rr()},[rr]),Ls=c.useCallback(ie=>{be&&!nt.current&&rr(),je.current=ie,Pe(ie)},[be,rr]),jt=c.useCallback(()=>{be?Lt():ye()},[be,Lt,ye]),Ot=be?tu(ne,tt):ne,it=c.useMemo(()=>{const ie=String(Ot||"").trim();return ie?rb(ie):null},[Ot]),qe=mr?u(ky[mr]||ky.speechErrorGeneric):null,$t=c.useMemo(()=>{if($===Uo){const ie=z.trim();return ie?ie.length>42?`${ie.slice(0,39)}â¦`:ie:u("canvas.node.scriptStylePickerCustomTileCaption")}return us($,f)},[$,z,f,u]),wt=xe?u(xe==="style_required"?"page.storyflow.projectSetup.errorStyleRequired":xe==="style_custom_pending"?"page.storyflow.projectSetup.errorStyleCustomPending":"page.storyflow.projectSetup.errorGeneric"):null,Mr=c.useCallback(ie=>{O(ie),ie!==Uo&&(n(null),Z(""))},[]),At=c.useCallback(async ie=>{const dt=new FileReader;dt.onloadend=async()=>{const Ft=dt.result;n(Ft),O(Uo),Ie(!0);try{const ft=await Qy(Ft),fr=await ih(ft);fr.success&&fr.styleKeywords?Z(fr.styleKeywords):(H.warning(u("page.storyflow.styleAnalysisTitle"),u("page.storyflow.styleNoKeywordsBody")),Z(""))}catch(ft){H.warning(u("page.storyflow.styleAnalysisTitle"),Bt(ft instanceof Error?ft.message:String(ft))),Z("")}finally{Ie(!1)}}
315,dt.readAsDataURL(ie)},[u]),fe=c.useCallback(()=>{var ie;n(null),Z(""),$===Uo&&O(((ie=x[0])==null?void 0:ie.id)??"Cinematic")},[x,$]),Re=c.useCallback(async ie=>{var ft;const dt=(ft=ie.target.files)==null?void 0:ft[0];if(ie.target&&(ie.target.value=""),!dt)return;const Ft=dt.name.toLowerCase();if(!/\.(txt|docx|md)$/i.test(Ft)){H.warning(u("page.scriptDocument.documentParseFailedTitle"),u("page.storyflow.projectSetup.synopsisUploadTitle"));return}me(!0);try{const fr=await th(dt);if(fr.ok===!1){fr.code==="legacy_binary_doc"?H.info(u("page.scriptDocument.legacyBinaryDocTitle"),u("page.scriptDocument.legacyBinaryDocBody")):H.warning(u("page.scriptDocument.documentParseFailedTitle"),u("page.scriptDocument.documentParseFailedBody"));return}const Lr=String(fr.text||"").trim();if(!Lr){H.warning(u("page.scriptDocument.documentParseFailedTitle"),u("page.scriptDocument.documentParseFailedBody"));return}Pe(cr=>{const ps=String(cr||"").trim();return ps?`${ps} 316 317${Lr}`:Lr})}finally{me(!1)}},[u]),J=()=>{const ie=be?tu(ne,tt):ne,dt={title:String(t||"").trim(),standaloneFilmMode:S,aspectRatio:v,visualStyleId:$,customStylePrompt:z,customStyleImage:D,synopsis:ie},Ft=hv(dt);if(Ft){ae(Ft);return}ae(null),be&&(je.current=ie,Pe(ie),rr()),i(dt)};return s.jsx("div",{className:"fixed inset-0 z-[10060] flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm","data-testid":"storyflow-project-setup-modal",role:"dialog","aria-modal":"true","aria-labelledby":"storyflow-project-setup-title",children:s.jsxs("div",{className:"flex max-h-[min(92vh,840px)] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-white/10 bg-[#12151a] shadow-2xl",children:[s.jsxs("div",{className:"relative shrink-0 border-b border-white/10 px-5 py-4 sm:px-6",children:[a?s.jsx("button",{type:"button",onClick:a,className:"absolute right-3 top-3 flex h-9 w-9 items-center justify-center rounded-lg border border-white/10 text-slate-300 transition-colors hover:border-white/25 hover:bg-white/5 hover:text-white sm:right-4 sm:top-4","aria-label":u("page.storyflow.projectSetup.closeAria"),"data-testid":"storyflow-setup-close",children:s.jsx("span",{className:"material-symbols-outlined text-[20px]","aria-hidden":!0,children:"close"})}):null,s.jsx("h1",{id:"storyflow-project-setup-title",className:"pr-10 text-lg font-bold text-white sm:text-xl",children:u("page.storyflow.projectSetup.title")}),s.jsx("p",{className:"mt-1 pr-10 text-[12px] leading-relaxed text-slate-400",children:u("page.storyflow.projectSetup.subtitle")})]}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto custom-scrollbar px-5 py-4 sm:px-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:`flex items-end justify-between gap-2 ${gv}`,children:[s.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-primary",children:u("page.storyflow.projectSetup.synopsisLabel")}),ve?s.jsx("button",{type:"button","data-testid":"storyflow-setup-speech-mic",disabled:de||Ee,"aria-pressed":be,title:u(be?"canvas.node.promptSpeechStopTitle":"canvas.node.promptSpeechStartTitle"),"aria-label":u(be?"canvas.node.promptSpeechStopAria":"canvas.node.promptSpeechStartAria"),onClick:jt,className:`flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded-lg border transition-all duration-150 disabled:pointer-events-none disabled:opacity-50 ${be?"border-primary/70 bg-primary/20 text-primary":"border-white/10 bg-zinc-800 text-zinc-500 hover:border-primary/40 hover:text-primary"}`,children:s.jsx(Go,{name:be?"mic_off":"mic",size:"inline",className:"!text-lg leading-none"})}):null]}),s.jsxs("div",{className:"relative",children:[s.jsx("textarea",{value:Ot,onChange:ie=>Ls(ie.target.value),rows:4,placeholder:u("page.storyflow.projectSetup.synopsisPlaceholder"),className:"w-full resize-none rounded-lg border border-white/10 bg-black/40 px-3 py-2.5 pr-12 pb-11 text-sm leading-relaxed text-white outline-none placeholder:text-slate-500 focus:border-primary/50 focus:ring-1 focus:ring-primary/40","data-testid":"storyflow-setup-synopsis"}),s.jsx("button",{type:"button","data-testid":"storyflow-setup-script-upload",disabled:de||Ee,title:u("page.storyflow.projectSetup.synopsisUploadTitle"),"aria-label":u("page.storyflow.projectSetup.synopsisUploadAria"),onClick:()=>{var ie;return(ie=Te.current)==null?void 0:ie.click()},className:`absolute ${xv} flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg border border-white/10 bg-zinc-800 text-zinc-400 transition-colors hover:border-primary/40 hover:text-primary disabled:pointer-events-none disabled:opacity-50`,children:s.jsx(Go,{name:de?"progress_activity":"add",size:"inline",className:`!text-lg leading-none ${de?"animate-spin":""}`})}),s.jsx("input",{ref:Te,type:"file",accept:".txt,.md,.docx,text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document",className:"hidden","data-testid":"storyflow-setup-script-file-input",onChange:ie=>void Re(ie)})]}),be?s.jsx("p",{className:"text-[10px] leading-snug text-zinc-500","data-testid":"storyflow-setup-speech-listening","aria-live":"polite",children:u("canvas.node.promptSpeechSpeakNow")}):null,qe?s.jsx("p",{className:"text-[11px] text-amber-400/90",role:"status",children:qe}):null,de?s.jsx("p",{className:"text-[11px] text-slate-500",children:u("page.storyflow.projectSetup.synopsisUploading")}):null,it?s.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-2.5 py-2 text-[11px] leading-relaxed text-slate-300","data-testid":"storyflow-setup-upload-cost-estimate",role:"status",children:[s.jsx("p",{children:u("page.storyflow.projectSetup.synopsisCostEstimate",{chars:it.chars,tokens:it.tokens,sparks:it.sparksAfterQuota,tier:it.tierId||""})}),it.truncatedForModel?s.jsx("p",{className:"mt-1 text-amber-300/90",children:u("page.storyflow.projectSetup.synopsisCostEstimateTruncated",{modelChars:it.modelInputChars})}):null]}):null]}),s.jsx("div",{className:"my-5",children:s.jsxs("div",{className:"grid grid-cols-3 gap-x-3 gap-y-2",children:[s.jsxs("div",{className:"min-w-0 flex flex-col gap-1",children:[s.jsx("span",{className:eu,children:u("page.storyflow.projectSetup.typeLabel")}),s.jsx("div",{className:"flex items-center gap-1",role:"group","aria-label":u("page.storyflow.projectSetup.typeLabel"),children:[{film:!0,label:u("page.storyflow.projectSetup.typeFilm"),testId:"storyflow-setup-type-film"},{film:!1,label:u("page.storyflow.projectSetup.typeSeries"),testId:"storyflow-setup-type-series"}].map(ie=>{const dt=S===ie.film;return s.jsx("button",{type:"button",onClick:()=>k(ie.film),className:`min-w-0 flex-1 rounded border px-1 py-0.5 text-[10px] font-bold transition-colors ${dt?"border-primary/60 bg-primary/15 text-primary":"border-white/15 text-zinc-400 hover:border-primary/40 hover:text-primary"}`,"data-testid":ie.testId,"aria-pressed":dt,children:ie.label},ie.testId)})})]}
317),s.jsx(uv,{value:v,onChange:I,ratioLabel:u("canvas.node.ratio"),categoryClassName:eu,size:"compact",testIdPrefix:"storyflow-setup-aspect"}),s.jsxs("div",{className:"min-w-0 flex flex-col items-end justify-end gap-1 text-right",children:[s.jsx("span",{className:eu,children:u("canvas.node.style")}),s.jsx("span",{className:"max-w-full truncate text-[13px] font-bold leading-snug text-white","data-testid":"storyflow-setup-style-current",title:$t,children:$t})]})]})}),s.jsx(pv,{value:$,onChange:Mr,locale:f,noPreviewLabel:u("canvas.node.noPreview"),testIdPrefix:"storyflow-setup-style",size:"comfortable",disabled:Ee,customUpload:{imageUrl:D,prompt:z,analyzing:Ee,labels:{customRefAlt:u("canvas.node.scriptStylePickerCustomRefAlt"),uploadShort:u("canvas.node.scriptStylePickerUploadRefShort"),tileCaption:u("canvas.node.scriptStylePickerCustomTileCaption"),changeReference:u("page.workflow.changeReference"),remove:u("page.tools.common.remove")},onPickFile:At,onSelectCustom:()=>O(Uo),onClearCustom:fe}})]}),s.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2.5",children:[s.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wider text-slate-400",children:u("page.storyflow.projectSetup.collabLabel")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-slate-500",children:u("page.storyflow.projectSetup.collabHint")})]}),wt?s.jsx("p",{className:"text-[12px] font-medium text-red-400",role:"alert",children:wt}):null]}),s.jsx("div",{className:"shrink-0 border-t border-white/10 px-5 py-4 sm:px-6",children:s.jsx("button",{type:"button",onClick:J,disabled:Ee||de,"data-testid":"storyflow-setup-submit",className:"w-full rounded-xl bg-primary px-4 py-3 text-sm font-bold text-black transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50",children:u("page.storyflow.projectSetup.submit")})})]})})}const Jo="gpt-image-2-text-to-image",wv="2K",Wh="16:9";function Sv(r){return String(r||"").trim()||Jo}function kv(r){const t=String(r.characterName||"").trim()||"Character",i=Yo(String(r.description||"").trim()||`${t}. ${jw}`),a=String(r.styleInstruction||"").trim();return(r.hasReference?qo.characterImageWithRef:qo.characterImage).replace(/\{\{descEn\}\}/g,i).replace(/\{\{styleInstruction\}\}/g,a).replace(/\s{2,}/g," ").trim()}function vv(r){const t=String(r.description||"").trim()||String(r.assetName||"").trim()||(r.kind==="SCENES"?"Environment concept":"Prop design"),i=String(r.styleInstruction||"").trim(),a=String(r.aspectRatio).trim(),u=sf[a]??sf["16:9"];if(r.kind==="SCENES")return(r.hasReference?qo.sceneImageWithRef:qo.sceneImage).replace(/\{\{descEn\}\}/g,t).replace(/\{\{styleInstruction\}\}/g,i).replace(/\{\{aspectRatioDescription\}\}/g,u)+" SINGLE FRAME ONLY: one cinematic environment plate â not a character design sheet, not a turn-around, not multi-panel."+nf;const p=r.hasReference?qo.propsImageWithRef:qo.propsImage;return Xx(p.replace(/\{\{descEn\}\}/g,t).replace(/\{\{styleInstruction\}\}/g,i)+nf)}function Vi(r){if(r.kind==="CHARACTERS"){const i=Tw({styleId:r.styleId||r.styleLabel,styleLabel:r.styleLabel,styleKeywords:r.styleKeywords,periodLock:r.periodLock,characterStyleHint:r.characterStyleHint});return kv({characterName:r.name,description:r.description,hasReference:r.hasReference,styleInstruction:i})}const t=Rw({styleId:r.styleId||r.styleLabel,styleLabel:r.styleLabel,styleKeywords:r.styleKeywords,periodLock:r.periodLock});return vv({kind:r.kind,description:Yo(r.description),assetName:r.name,hasReference:r.hasReference,styleInstruction:t,aspectRatio:Wh})}function na(r){const t=String(r||"").trim().toLowerCase();return t?!(t.includes("midjourney")||t==="google/gemini-3.1-flash-image-preview"||t==="seedream/5-lite-text-to-image"||t==="seedream/5-lite-image-to-image"):!0}const Xi=`${Cb} disabled:hover:bg-zinc-900/95 disabled:hover:text-white`,Cv="max-w-full text-left text-[13px] font-semibold text-primary border-b border-zinc-500/60 pb-0.5 hover:border-primary transition-colors truncate tabular-nums",ru="text-[10px] uppercase font-bold tracking-widest text-zinc-500";function Nv(r,t=20){const i=String(r||"").trim();return i.length<=t?i:`${i.slice(0,Math.max(1,t-1))}â¦`}function Ev(r){const t=String(r||"").trim().toLowerCase();return t==="midjourney/relaxed"||t==="midjourney/v8.1"||t.startsWith("midjourney/")}function Tv(r){const t=String(r||"").trim()||Jo;return Nw(t,"2K")}
317function Rv(r){const{kind:t,name:i,draft:a,onDraftChange:u,previewUrl:p,generating:f,errorText:x,mjVariants:S,sparks:k,t:v,libraryT:I,onClose:$,onGenerate:O,onUploadToProjectLibrary:D,onUploadToApprovedLibrary:n,onOpenMjPicker:z,onOpenPreview:Z,onUploadDesign:Ee,onUploadRef:Ie,onRebuildImagePrompt:ne,generateDisabled:Pe,libraryBusy:xe,uploadBusy:ae=!1,projectUploaded:de,approvedUploaded:me,showApprovedUpload:Te}=r,nt=c.useRef(null),je=c.useRef(null),ue=c.useRef(null),ve=c.useRef(null),[be,tt]=c.useState(!1),[mr,ye]=c.useState(null),[rr,Lt]=c.useState(!1),Ls=Ev(a.imageModelId),jt=na(a.imageModelId),Ot=!!String(a.conceptRefImage||"").trim(),it=!!String(p||"").trim(),qe=xe||ae||rr||f,$t=fe=>new Promise((Re,J)=>{if(fe.size>2e6){J(new Error("Image is too large. Use a file under 2 MB."));return}const ie=new FileReader;ie.onload=()=>Re(String(ie.result||"")),ie.onerror=()=>J(new Error("Could not read file.")),ie.readAsDataURL(fe)}),wt=async(fe,Re)=>{if(!(!fe||qe)){Lt(!0);try{const J=await $t(fe);if(!J)return;Re==="design"?await Ee(J):await Ie(J)}catch{}finally{Lt(!1)}}},Mr=c.useMemo(()=>{const fe=String(a.imageModelId||"").trim()||Jo;return bu(fe)},[a.imageModelId]),At=v(t==="CHARACTERS"?"page.storyflow.entityCharacter":t==="SCENES"?"page.storyflow.entityScene":"page.storyflow.entityProp");return c.useEffect(()=>{if(!be)return;const fe=()=>{var J;const Re=(J=ve.current)==null?void 0:J.getBoundingClientRect();if(!Re){ye(null);return}ye({left:Math.min(Re.left,window.innerWidth-320),top:Math.min(Re.bottom+8,window.innerHeight-280)})};return fe(),window.addEventListener("resize",fe),window.addEventListener("scroll",fe,!0),()=>{window.removeEventListener("resize",fe),window.removeEventListener("scroll",fe,!0)}},[be]),s.jsxs("div",{className:"fixed inset-0 z-[10020] flex items-center justify-center p-4 bg-black/65",role:"presentation",onClick:fe=>{fe.target===fe.currentTarget&&$()},children:[s.jsxs("div",{className:"relative flex w-full max-w-[860px] max-h-[min(92vh,calc(100dvh-2rem))] flex-col overflow-hidden rounded-xl border border-white/10 bg-surface-dark shadow-xl",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-asset-modal-title","data-testid":"storyflow-asset-design-modal",onClick:fe=>fe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2.5 border-b border-white/10 shrink-0",children:[s.jsxs("h2",{id:"workspace-asset-modal-title",className:"truncate pr-2 font-display text-sm font-bold text-white",children:[At," â ",i]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[s.jsx("button",{type:"button",disabled:xe||!it,className:Xi,title:I("canvas.library.quickActionProjectTitle"),"aria-label":I("canvas.library.quickActionProjectTitle"),"data-testid":"storyflow-design-quick-project-library",onClick:fe=>{fe.stopPropagation(),D()},children:s.jsx("span",{className:`${zi}${de?" opacity-70":""}`,children:de?"folder_check":"folder"})}),Te?s.jsx("button",{type:"button",disabled:xe||!it,className:Xi,title:I("canvas.library.quickActionApprovedTitle"),"aria-label":I("canvas.library.quickActionApprovedTitle"),"data-testid":"storyflow-design-quick-approved-library",onClick:fe=>{fe.stopPropagation(),n()},children:s.jsx("span",{className:`${zi}${me?" opacity-70":""}`,children:me?"gpp_good":"shield"})}
317):null,s.jsx("button",{type:"button",onClick:$,className:Xi,"aria-label":v("page.storyflow.closeAria"),"data-testid":"storyflow-design-close",children:s.jsx("span",{className:zi,children:"close"})})]})]}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto custom-scrollbar p-3","data-testid":"storyflow-design-window",children:[s.jsxs("div",{className:"flex items-end justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex flex-col gap-1",children:[s.jsx("span",{className:ru,children:I("canvas.node.model")}),s.jsx("button",{ref:ve,type:"button",title:I("canvas.node.modelWithSparksCost",{label:Mr.label,sparks:String(k||Mr.costPerImage)}),className:`block w-fit min-w-0 ${Cv}`,"data-testid":"storyflow-design-model-pick","aria-expanded":be,onClick:fe=>{fe.stopPropagation(),tt(Re=>!Re)},children:Nv(Mr.label,20)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 pb-0.5",children:[s.jsx("button",{type:"button",disabled:!it,className:Xi,title:I("canvas.node.zoom"),"aria-label":I("canvas.node.zoom"),"data-testid":"storyflow-design-zoom",onClick:fe=>{fe.stopPropagation(),it&&Z(p)},children:s.jsx("span",{className:zi,children:"zoom_in"})}),s.jsx("button",{type:"button",disabled:!it,className:Xi,title:I("canvas.media.download"),"aria-label":I("canvas.media.download"),"data-testid":"storyflow-design-download",onClick:fe=>{if(fe.stopPropagation(),!it)return;const Re=String(i||"asset").trim().replace(/[^\w\-]+/g,"_").slice(0,48);rh(p,`${Re||"asset"}-${Date.now()}.png`)},children:s.jsx("span",{className:zi,children:"download"})})]})]}),s.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/25 px-3 py-2.5","data-testid":"storyflow-design-upload-actions",children:[s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest text-zinc-500",children:v("page.storyflow.assetImageSourceLabel")}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx("input",{ref:je,type:"file",accept:"image/*",className:"hidden","aria-hidden":!0,"data-testid":"storyflow-design-local-upload-input",onChange:fe=>{var J;const Re=(J=fe.target.files)==null?void 0:J[0];fe.target.value="",wt(Re,"design")}}),s.jsx("input",{ref:ue,type:"file",accept:"image/*",className:"hidden","aria-hidden":!0,"data-testid":"storyflow-design-ref-upload-input",onChange:fe=>{var J;const Re=(J=fe.target.files)==null?void 0:J[0];fe.target.value="",wt(Re,"ref")}}),s.jsxs("button",{type:"button",disabled:qe,onClick:()=>{var fe;return(fe=je.current)==null?void 0:fe.click()},className:"inline-flex items-center gap-1.5 rounded-lg border border-white/15 bg-white/5 px-3 py-1.5 text-[11px] font-bold text-slate-100 hover:border-primary/40 hover:text-primary disabled:cursor-not-allowed disabled:opacity-50","data-testid":"storyflow-design-local-upload",title:v("page.storyflow.uploadLocalImageHint"),children:[s.jsx("span",{className:"material-symbols-outlined text-[16px]","aria-hidden":!0,children:"photo_library"}),v("page.storyflow.uploadLocalImage")]}),s.jsxs("button",{type:"button",disabled:qe,onClick:()=>{var fe;return(fe=ue.current)==null?void 0:fe.click()},className:"inline-flex items-center gap-1.5 rounded-lg border border-primary/35 bg-primary/10 px-3 py-1.5 text-[11px] font-bold text-primary hover:bg-primary/20 disabled:cursor-not-allowed disabled:opacity-50","data-testid":"storyflow-design-ref-upload",title:v("page.storyflow.uploadReferenceImageHint"),children:[s.jsx("span",{className:"material-symbols-outlined text-[16px]","aria-hidden":!0,children:"image_search"}),v("page.storyflow.uploadReferenceImage")]}),Ot?s.jsxs("button",{type:"button",onClick:()=>Z(a.conceptRefImage),className:"inline-flex items-center gap-1.5 rounded-lg border border-white/15 bg-black/40 px-2 py-1 text-[11px] font-semibold text-slate-200",title:v("page.storyflow.designWindowReferenceLabel"),children:[s.jsx("span",{className:"relative h-6 w-6 shrink-0 overflow-hidden rounded border border-white/15",children:s.jsx("img",{src:a.conceptRefImage,alt:"",className:"h-full w-full object-cover"})}),v("page.storyflow.designWindowReferenceLabel")]}):null]}),s.jsx("p",{className:"mt-1.5 text-[10px] leading-snug text-neutral-500",children:v(Ot?"page.storyflow.uploadReferenceReadyHint":"page.storyflow.designWindowReferenceOptional")})]}),s.jsxs("div",{className:"flex min-h-0 flex-col gap-3 sm:flex-row sm:items-stretch",children:[s.jsxs("div",{ref:nt,className:"relative aspect-video w-full shrink-0 overflow-hidden rounded-lg border border-white/10 bg-black/40 sm:aspect-auto sm:min-h-[min(280px,36vh)] sm:w-[52%] sm:flex-none",children:[s.jsx("div",{className:"flex h-full min-h-[140px] w-full items-center justify-center sm:min-h-[min(280px,36vh)]",children:it?s.jsx("img",{src:p,alt:"",className:"max-h-full max-w-full object-contain"}):s.jsx("span",{className:"px-2 text-center text-xs text-neutral-500",children:v("page.storyflow.noImageYet")})}),Ls&&S.length>1?s.jsx("button",{type:"button",onClick:fe=>{var J;fe.stopPropagation();const Re=((J=nt.current)==null?void 0:J.getBoundingClientRect())??null;z(Re)},className:"absolute top-2 right-2 z-10 flex h-[22px] w-[22px] items-center justify-center rounded-full border border-white/15 bg-primary text-[12px] font-extrabold text-zinc-900 shadow-lg transition-transform duration-200 hover:scale-110",title:v("page.storyflow.chooseVariant"),"aria-label":v("page.storyflow.chooseMidjourneyVariantAria"),"data-testid":"storyflow-design-mj-quad-picker",children:"4"}):null,!f&&x?s.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-black/65 px-3 text-center text-[12px] font-semibold text-white",children:x}):null,f?s.jsx("div",{className:"absolute bottom-2 left-1/2 z-30 inline-flex -translate-x-1/2 items-center rounded-full border border-primary/45 bg-black/70 px-2 py-0.5 text-[10px] font-semibold tracking-wide text-primary backdrop-blur-sm",children:s.jsx("span",{className:"animate-pulse",children:v("page.storyflow.generatingImage")})}):null]}),s.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx("span",{className:ru,children:v("page.storyflow.assetModalDescriptionAria")}),s.jsx("textarea",{className:`w-full resize-y rounded-lg border border-white/10 bg-black/30 px-3 py-2.5 text-[13px] leading-relaxed text-neutral-100 placeholder:text-neutral-500 outline-none focus:border-primary/40 ${jt?"min-h-[72px] sm:min-h-[min(100px,14vh)]":"min-h-[140px] flex-1 sm:min-h-[min(280px,36vh)]"}`,value:a.description,onChange:fe=>u({description:fe.target.value,...jt&&a.imagePromptDirty?{}:{imagePromptDirty:!1}}),placeholder:v("page.storyflow.assetModalDescriptionPlaceholder"),"aria-label":v("page.storyflow.assetModalDescriptionAria"),"data-testid":"storyflow-design-description"}),jt?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2",children:[s.jsx("span",{className:ru,children:v("page.storyflow.assetModalImagePromptAria")}),s.jsx("button",{type:"button",disabled:f||qe,onClick:()=>ne==null?void 0:ne(),className:"shrink-0 rounded-md border border-white/15 bg-white/5 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-300 hover:border-primary/40 hover:text-primary disabled:cursor-not-allowed disabled:opacity-50","data-testid":"storyflow-design-rebuild-prompt",title:v("page.storyflow.assetModalRebuildPromptHint"),children:v("page.storyflow.assetModalRebuildPrompt")})]}),s.jsx("textarea",{className:"min-h-[120px] w-full flex-1 resize-y rounded-lg border border-primary/25 bg-black/40 px-3 py-2.5 text-[12px] leading-relaxed text-neutral-100 placeholder:text-neutral-500 outline-none focus:border-primary/50 sm:min-h-[min(200px,22vh)]",value:a.imagePrompt,onChange:fe=>u({imagePrompt:fe.target.value,imagePromptDirty:!0}),placeholder:v("page.storyflow.assetModalImagePromptPlaceholder"),"aria-label":v("page.storyflow.assetModalImagePromptAria"),"data-testid":"storyflow-design-image-prompt"}),s.jsx("p",{className:"text-[10px] leading-snug text-slate-500",children:a.imagePromptDirty?v("page.storyflow.assetModalImagePromptDirtyHint"):v("page.storyflow.assetModalImagePromptHint")})]}):s.jsx("p",{className:"text-[10px] leading-snug text-slate-500",children:v(t==="CHARACTERS"?"page.storyflow.assetModalTriViewHint":t==="SCENES"||t==="PROPS"?"page.storyflow.assetModalPhase2ScenePropHint":"page.storyflow.assetModalEditHint")})]})]}),s.jsx(Nb,{nodeId:"storyflow-asset-design",fullWidth:!0,disabled:Pe||f||qe,sparks:k,primaryLabel:v(f?"page.storyflow.generatingImage":it?Ot?"page.storyflow.regenerateWithReferenceAction":"page.storyflow.regenerateAction":Ot?"page.storyflow.generateWithReferenceAction":"page.storyflow.generateAction"),onClick:O})]})]}),be&&typeof document<"u"?Ps.createPortal(s.jsxs("div",{className:"contents","data-testid":"storyflow-design-model-picker-portal",children:[s.jsx("div",{className:"fixed inset-0 z-[10040]","aria-hidden":!0,onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),tt(!1)}}),s.jsx("div",{className:"fixed z-[10050] rounded-xl shadow-xl overflow-hidden",style:mr?{left:mr.left,top:mr.top}:{left:"50%",top:"50%",transform:"translate(-50%, -50%)"},onClick:fe=>fe.stopPropagation(),children:s.jsx(Eb,{hasRefImages:Ot,selectedModelId:String(a.imageModelId||"").trim(),onSelect:fe=>{Tb(fe),u({imageModelId:fe}),tt(!1)}})})]}),document.body):null]})}function jv(r){return r.kind==="episode"?String(r.title||"").trim():String(r.title||r.summary||"").trim()}function Hh(r){const{node:t,labels:i,canDelete:a,selected:u=!1,onRename:p,onDelete:f}=r,[x,S]=c.useState(!1),k=c.useRef(null),v=t.kind==="episode"?i.menuAriaEpisode:i.menuAriaSequence;return c.useEffect(()=>{if(!x)return;const I=$=>{var O;(O=k.current)!=null&&O.contains($.target)||S(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[x]),s.jsxs("div",{ref:k,className:"relative shrink-0 self-start",children:[s.jsx("button",{type:"button","aria-label":v,"aria-expanded":x,"data-testid":`storyflow-hierarchy-menu-${t.id}`,onClick:I=>{I.stopPropagation(),S($=>!$)},className:`mt-0.5 flex h-6 w-6 items-center justify-center rounded-md text-slate-500 transition-colors hover:bg-white/10 hover:text-slate-200 ${x||u?"bg-white/10 text-slate-200 opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"}`,children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"more_horiz"})}),x?s.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-40 mt-0.5 min-w-[132px] rounded-md border border-white/10 bg-[#15181c] py-0.5 shadow-lg",children:[s.jsxs("button",{type:"button",role:"menuitem","data-testid":`storyflow-hierarchy-rename-${t.id}`,onClick:I=>{I.stopPropagation(),S(!1),p()},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-slate-200 hover:bg-white/8",children:[s.jsx("span",{className:"material-symbols-outlined text-[14px] text-slate-400",children:"edit"}),i.menuRename]}),s.jsxs("button",{type:"button",role:"menuitem","data-testid":`storyflow-hierarchy-delete-${t.id}`,disabled:!a,onClick:I=>{I.stopPropagation(),a&&(S(!1),f())},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-red-300/90 hover:bg-red-500/10 disabled:pointer-events-none disabled:opacity-35",children:[s.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"delete"}),i.menuDelete]})]}):null]})}function vy(r){const{node:t,selected:i,isLast:a,nestedUnderParent:u=!1,menuLabels:p,canDeleteNode:f,onRenameNode:x,onDeleteNode:S,onRequestRename:k,onRequestDelete:v,onSelect:I,onInsertAfter:$,emptySequenceSummary:O,insertSequenceAriaLabel:D}=r,n=String(t.summary||"").trim()||String(O||"").trim(),z=!!(p&&x&&S),Z=f?f(t):!0;return s.jsxs("div",{className:`relative ${u?"pl-3":"pl-2"}`,children:[u?s.jsx("div",{className:"absolute left-0 top-[13px] h-px w-3 bg-white/15","aria-hidden":!0}
317):null,s.jsx("div",{className:`absolute top-0 bottom-0 w-px bg-white/15 ${u?"left-0":"left-[7px]"}`,"aria-hidden":!0}),s.jsxs("div",{className:`group relative mb-0.5 flex w-full items-start gap-0.5 rounded-md transition-colors ${u?"ml-1":""} ${i?"bg-primary/15":"hover:bg-white/5"}`,children:[s.jsxs("button",{type:"button","data-testid":`storyflow-hierarchy-seq-${t.id}`,onClick:I,className:`flex min-w-0 flex-1 items-start gap-2 px-2 py-1.5 text-left ${i?"text-white":"text-slate-300"}`,children:[s.jsx("span",{className:`relative z-[1] mt-1 shrink-0 rounded-full border ${u?"h-2 w-2":"h-2.5 w-2.5"} ${i||t.status==="generated"?"border-primary bg-primary":"border-white/30 bg-background-dark"}`,"aria-hidden":!0}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:`block truncate leading-snug ${u?"text-[11px] font-medium text-slate-300":"text-[12px] font-medium"}`,children:t.label}),n?s.jsx("span",{className:`mt-0.5 block line-clamp-2 text-[10px] leading-snug ${i?"text-slate-300/80":"text-slate-500"}`,children:n}):null]})]}),z?s.jsx(Hh,{node:t,labels:p,canDelete:Z,selected:i,onRename:()=>k==null?void 0:k(t),onDelete:()=>v==null?void 0:v(t)}):null]}),!a&&$?s.jsx("div",{className:"relative z-[1] -my-0.5 flex justify-start py-0.5 pl-0.5",children:s.jsx("button",{type:"button","aria-label":D||"Insert sequence","data-testid":`storyflow-hierarchy-insert-after-${t.id}`,onClick:Ee=>{Ee.stopPropagation(),$()},className:"flex h-4 w-4 items-center justify-center rounded-full border border-white/20 bg-background-dark text-[10px] text-slate-400 hover:border-primary/50 hover:text-primary",children:"+"})}):null]})}function Av(r){const{node:t,selected:i,onSelect:a,onToggle:u}=r,p=t.expanded!==!1;return s.jsxs("div",{className:"mb-1 flex items-center gap-0.5",children:[s.jsx("button",{type:"button","aria-expanded":p,onClick:u,className:"flex h-7 w-6 shrink-0 items-center justify-center text-slate-500 hover:text-slate-300",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:p?"expand_more":"chevron_right"})}),s.jsxs("button",{type:"button","data-testid":"storyflow-hierarchy-root",onClick:a,className:`flex min-w-0 flex-1 items-center gap-2.5 rounded-md px-1.5 py-1.5 text-left ${i?"bg-primary/15 text-white":"text-slate-100 hover:bg-white/5"}`,children:[s.jsx("span",{className:`h-3 w-3 shrink-0 rounded-full ring-2 ring-white/5 ${i?"bg-primary":"bg-white/25"}`,"aria-hidden":!0}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-bold tracking-tight",children:t.label})]})]})}function Iv(r){const{node:t,selected:i,menuLabels:a,canDeleteNode:u,onRequestRename:p,onRequestDelete:f,onSelect:x,onToggle:S}=r,k=t.expanded===!0,v=t.kind==="episode"&&a&&p&&f,I=u?u(t):!0;return s.jsxs("div",{className:"mb-0.5 flex items-center gap-0.5",children:[s.jsx("button",{type:"button","aria-expanded":k,onClick:S,className:"flex h-7 w-6 shrink-0 items-center justify-center text-slate-500 hover:text-slate-300",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:k?"expand_more":"chevron_right"})}),s.jsxs("div",{className:`group flex min-w-0 flex-1 items-center gap-0.5 rounded-md ${i?"bg-primary/10":"hover:bg-white/5"}`,children:[s.jsxs("button",{type:"button","data-testid":`storyflow-hierarchy-parent-${t.id}`,onClick:x,className:`flex min-w-0 flex-1 items-center gap-2.5 px-1.5 py-1.5 text-left ${i?"text-white":"text-slate-100"} ${k?"text-white":""}`,children:[s.jsx("span",{className:`h-3 w-3 shrink-0 rounded-full ring-2 ring-white/5 ${t.status==="generated"||k?"bg-primary":"bg-white/25"}`,"aria-hidden":!0}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-bold tracking-tight",children:t.label})]}
317),v?s.jsx(Hh,{node:t,labels:a,canDelete:I,selected:i,onRename:()=>p(t),onDelete:()=>f(t)}):null]})]})}function Pv(r){const{root:t,selectedId:i,modeLabel:a,standaloneFilmMode:u=!1,newEpisodeLabel:p,onSelect:f,onToggleExpand:x,onAddEpisode:S,onInsertSequence:k,showAddEpisode:v=!0,emptySequenceSummary:I,insertSequenceAriaLabel:$,menuLabels:O,onRenameNode:D,onDeleteNode:n,canDeleteNode:z}=r,Z=c.useMemo(()=>t.children||[],[t.children]),Ee=u?"movie":"live_tv",Ie=t.expanded!==!1,[ne,Pe]=c.useState(null),[xe,ae]=c.useState(""),de=ue=>{Pe(ue),ae(jv(ue))},me=()=>{Pe(null),ae("")},Te=()=>{if(!ne||!D)return;const ue=xe.trim();ue&&(D(ne,ue),me())},je=O&&D&&n?{menuLabels:O,canDeleteNode:z,onRenameNode:D,onDeleteNode:n,onRequestRename:de,onRequestDelete:ue=>{if(!n||!O)return;const ve=ue.kind==="episode"?O.deleteConfirmEpisode:O.deleteConfirmSequence;window.confirm(ve)&&n(ue)}}:{};return s.jsxs("aside",{className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden border-r border-white/10 bg-[#0d0f12]","data-testid":"storyflow-hierarchy-rail","data-tour":"gl-hierarchy-rail",children:[s.jsx("div",{className:"shrink-0 border-b border-white/10 px-3 py-3",children:s.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-md border border-primary/35 bg-primary/10 px-2 py-1 text-[10px] font-bold uppercase tracking-wide text-primary",children:[s.jsx("span",{className:"material-symbols-outlined text-[14px]","aria-hidden":!0,children:Ee}),a]})}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto custom-scrollbar px-2 py-2",children:[s.jsx(Av,{node:t,selected:i===t.id,onSelect:()=>f(t),onToggle:()=>x(t.id)}),Ie&&Z.length===0?s.jsx("p",{className:"px-2 py-2 text-[11px] text-slate-500",children:"â"}):Ie?Z.map(ue=>{if(ue.kind==="sequence")return s.jsx(vy,{node:ue,selected:i===ue.id,isLast:!0,onSelect:()=>f(ue),emptySequenceSummary:I,insertSequenceAriaLabel:$,...je},ue.id);const ve=ue.children||[],be=ue.expanded===!0;return s.jsxs("div",{className:"mb-2 ml-[26px]",children:[s.jsx(Iv,{node:ue,selected:i===ue.id,onSelect:()=>f(ue),onToggle:()=>x(ue.id),...je}),be&&ve.length>0?s.jsx("div",{className:"ml-[26px] border-l border-white/15 pl-3.5 pt-0.5","data-testid":`storyflow-hierarchy-children-${ue.id}`,children:ve.map((tt,mr)=>s.jsx(vy,{node:tt,nestedUnderParent:!0,selected:i===tt.id,isLast:mr===ve.length-1,onSelect:()=>f(tt),emptySequenceSummary:I,onInsertAfter:k&&typeof tt.episodeIndex=="number"?()=>k({episodeIndex:tt.episodeIndex,unitIndex:typeof tt.unitIndex=="number"?tt.unitIndex:null}):void 0,insertSequenceAriaLabel:$,...je},tt.id))}):null]},ue.id)}):null]}),v&&S?s.jsx("div",{className:"shrink-0 border-t border-white/10 p-3",children:s.jsx("button",{type:"button","data-testid":"storyflow-hierarchy-add-episode",onClick:S,className:"flex w-full items-center justify-center gap-1 rounded-lg border border-primary/40 bg-primary/15 px-3 py-2.5 text-[12px] font-bold text-primary transition-colors hover:bg-primary/25",children:p})}):null,ne&&O?s.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/65 p-4","data-testid":"storyflow-hierarchy-rename-dialog",children:s.jsxs("div",{className:"w-full max-w-[280px] rounded-lg border border-white/10 bg-[#15181c] p-3 shadow-xl",children:[s.jsx("h3",{className:"text-[12px] font-bold text-white",children:ne.kind==="episode"?O.renameTitleEpisode:O.renameTitleSequence}),s.jsx("input",{type:"text",value:xe,onChange:ue=>ae(ue.target.value),placeholder:ne.kind==="episode"?O.renamePlaceholderEpisode:O.renamePlaceholderSequence,className:"mt-2 w-full rounded-md border border-white/15 bg-black/40 px-2.5 py-2 text-[12px] text-white outline-none focus:border-primary/50","data-testid":"storyflow-hierarchy-rename-input",onKeyDown:ue=>{ue.key==="Enter"&&Te(),ue.key==="Escape"&&me()}}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{type:"button",className:"rounded-md px-2.5 py-1.5 text-[11px] text-slate-400 hover:text-white",onClick:me,children:O.renameCancel}),s.jsx("button",{type:"button",className:"rounded-md bg-primary/20 px-2.5 py-1.5 text-[11px] font-semibold text-primary hover:bg-primary/30","data-testid":"storyflow-hierarchy-rename-save",onClick:Te,children:O.renameSave})]})]})}):null]})}const _v=({title:r,indexLabel:t,unitTitle:i,summary:a,value:u,onChange:p,emptyText:f,readOnly:x,testId:S="storyflow-selected-sequence-panel",indexFieldLabel:k,titleFieldLabel:v,synopsisFieldLabel:I,alwaysShowSynopsis:$=!1,summaryPlaceholder:O,refineWithBloomBotLabel:D,onRefineWithBloomBot:n,refineWithBloomBotDisabled:z,goToWorkflowLabel:Z,onGoToWorkflow:Ee,goToWorkflowDisabled:Ie})=>{const ne=String(a||"").trim(),Pe=String(t||"").trim(),xe=String(i||"").trim(),ae=!!(Pe||xe||ne||$),de=!!(n&&D),me=!!(Ee&&Z);return s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-2","data-testid":S,children:[s.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h4",{className:"text-sm font-bold text-white",children:r}),ae?s.jsxs("dl",{className:"mt-2 space-y-1.5 rounded-lg border border-white/10 bg-black/25 px-2.5 py-2","data-testid":`${S}-meta`,children:[Pe?s.jsxs("div",{className:"flex gap-2 text-[11px] leading-snug",children:[s.jsx("dt",{className:"shrink-0 font-bold text-neutral-500",children:k||"No."}),s.jsx("dd",{className:"min-w-0 font-semibold text-neutral-100","data-testid":`${S}-index`,children:Pe})]}):null,xe?s.jsxs("div",{className:"flex gap-2 text-[11px] leading-snug",children:[s.jsx("dt",{className:"shrink-0 font-bold text-neutral-500",children:v||"Title"}),s.jsx("dd",{className:"min-w-0 font-semibold text-white","data-testid":`${S}-title`,children:xe})]}):null,ne||$?s.jsxs("div",{className:"flex gap-2 text-[11px] leading-snug",children:[s.jsx("dt",{className:"shrink-0 font-bold text-neutral-500",children:I||"Synopsis"}
317),s.jsx("dd",{className:`min-w-0 whitespace-pre-wrap ${ne?"text-slate-300":"text-neutral-500"}`,"data-testid":`${S}-brief`,children:ne||O||"â"})]}):null]}):ne?s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-slate-300","data-testid":`${S}-brief`,children:ne}):null]}),s.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1.5",children:[me?s.jsxs("button",{type:"button",disabled:Ie,onClick:Te=>{Te.stopPropagation(),Ee==null||Ee()},className:"inline-flex items-center gap-1 rounded-lg border border-emerald-400/40 bg-emerald-400/10 px-2.5 py-1.5 text-[11px] font-semibold text-emerald-300 transition-colors hover:bg-emerald-400/20 disabled:cursor-not-allowed disabled:opacity-45","data-testid":`${S}-go-workflow`,children:[s.jsx("span",{className:"material-symbols-outlined text-sm leading-none",children:"arrow_forward"}),Z]}):null,de?s.jsxs("button",{type:"button",disabled:z,onClick:()=>n==null?void 0:n(),className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-primary/40 bg-primary/15 px-2.5 py-1.5 text-[11px] font-semibold text-primary transition-colors hover:bg-primary/25 disabled:cursor-not-allowed disabled:opacity-50","data-testid":`${S}-refine-bloombot`,children:[s.jsx("span",{className:"material-symbols-outlined text-sm leading-none",children:"auto_awesome"}),D]}):null]})]}),s.jsx(Dh,{value:u,onChange:p,readOnly:x,maxHeightClass:"max-h-[min(78vh,920px)]",minHeightClass:"min-h-[min(62vh,720px)]",emptyText:f,testId:`${S}-editor`,ariaLabel:r,storyflowFocusAttr:"sequence-editor"})]})},zh="bloomway_storyflow_column_widths_v1",Ol=240,$l=360,ju=180,Cy=420,Ny=260,Ey=560,Kh=280,Hu=6;function ql(r,t,i){return Math.min(i,Math.max(t,r))}function qh(r,t){const{containerPx:i,rightPx:a}=t;let u=ql(r,ju,Cy);if(i>0){const p=i-a-Kh-2*Hu;u=ql(u,ju,Math.min(Cy,p))}return u}function Au(r,t){const{containerPx:i,leftPx:a}=t;let u=ql(r,Ny,Ey);if(i>0){const p=i-a-Kh-2*Hu;u=ql(u,Ny,Math.min(Ey,p))}return u}function Gh(r,t=0){const i=typeof(r==null?void 0:r.leftPx)=="number"&&Number.isFinite(r.leftPx)?r.leftPx:Ol,a=typeof(r==null?void 0:r.rightPx)=="number"&&Number.isFinite(r.rightPx)?r.rightPx:$l,u=Au(a,{containerPx:t,leftPx:ju}),p=qh(i,{containerPx:t,rightPx:u});return{leftPx:p,rightPx:Au(u,{containerPx:t,leftPx:p})}}function Ty(){if(typeof window>"u")return{leftPx:Ol,rightPx:$l};try{const r=localStorage.getItem(zh);if(!r)return{leftPx:Ol,rightPx:$l};const t=JSON.parse(r);return Gh(t,0)}catch{return{leftPx:Ol,rightPx:$l}}}function Bv(r){if(!(typeof window>"u"))try{const t=Gh(r,0);localStorage.setItem(zh,JSON.stringify(t))}catch{}}function Ry({side:r,ariaLabel:t,onResizeDelta:i,onResizeEnd:a,testId:u}){const p=c.useRef(null),f=c.useCallback(k=>{k.button===0&&(k.preventDefault(),p.current={pointerId:k.pointerId,lastX:k.clientX},k.currentTarget.setPointerCapture(k.pointerId))},[]),x=c.useCallback(k=>{const v=p.current;if(!v||v.pointerId!==k.pointerId)return;const I=k.clientX-v.lastX;I!==0&&(v.lastX=k.clientX,i(r==="left"?I:-I))},[i,r]),S=c.useCallback(k=>{const v=p.current;if(!(!v||v.pointerId!==k.pointerId)){p.current=null;try{k.currentTarget.releasePointerCapture(k.pointerId)}catch{}a==null||a()}},[a]);return s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":t,"data-testid":u,"data-tour":`gl-col-splitter-${r}`,className:"group relative z-20 hidden shrink-0 cursor-col-resize items-stretch justify-center bg-transparent max-lg:hidden lg:flex",style:{width:Hu},onPointerDown:f,onPointerMove:x,onPointerUp:S,onPointerCancel:S,children:s.jsx("span",{className:"my-auto h-10 w-0.5 rounded-full bg-white/20 transition group-hover:bg-primary/70 group-active:bg-primary","aria-hidden":!0})})}function jy(r){return[r.label,r.beatSummary??"",String(r.descriptiveScript??"").slice(0,256),String(r.actId??"")].join("�")}function Mv(r,t,i,a){const u={...r},p=`ep:${t}:seq:`,f=i.map(S=>u[`${p}${S.index}`]);for(const S of Object.keys(u))S.startsWith(p)&&delete u[S];const x=new Set;return a.forEach(S=>{const k=S.index;let v=i.findIndex((I,$)=>!x.has($)&&jy(I)===jy(S));if(v<0){const I=i.findIndex(($,O)=>!x.has(O)&&$.index===k);I>=0&&(v=I)}if(v>=0){x.add(v);const I=f[v];I!=null&&I.length&&(u[`${p}${k}`]=I)}}),u}function Lv(r,t){const i={};for(const[a,u]of Object.entries(r)){const p=/^ep:(\d+):seq:(\d+)$/.exec(a);if(!p){i[a]=u;continue}const f=Number(p[1]),x=Number(p[2]);if(f===t)continue;const S=f>t?f-1:f;i[`ep:${S}:seq:${x}`]=u}return i}function Ov(r,t){const i={};for(const[a,u]of Object.entries(r)){const p=Number(a);if(!Number.isFinite(p)||p===t)continue;const f=p>t?p-1:p;i[f]=u}return i}const Gl="[[STORYFLOW_FOUNDATION_READY]]",ia="[[HIGHLIGHT]]",Yl=(r,t)=>{const i=t.split(".");let a=wu[r];for(const u of i){if(typeof a!="object"||a===null||!(u in a))return"";a=a[u]}
317return typeof a=="string"?a:""};function $v(){const r=new Set,t=ia;for(const i of["en","zh"]){const a=Yl(i,"page.storyflow.foundationReadyHighlight"),u=Yl(i,"page.storyflow.foundationReadyBody");r.add(`${t}${a} 318${u}`.trim())}return r}const Fv=$v();function zu(r){const t=String(r||"").trim();return t===Gl?!0:Fv.has(t)}function Ay(r,t,i){if(!zu(r))return r;const a=i!=null&&i.unifiedShell?"page.storyflow.foundationReadyUnifiedHighlight":"page.storyflow.foundationReadyHighlight",u=i!=null&&i.unifiedShell?"page.storyflow.foundationReadyUnifiedBody":"page.storyflow.foundationReadyBody",p=Yl(t,a),f=Yl(t,u);return`${ia}${p} 319${f}`}function Dv(r){return zu(r)?Gl:r}function Uv(r,t){const i=t.split(".");let a=wu[r]??wu.en;for(const u of i){if(typeof a!="object"||a===null||!(u in a))return"";a=a[u]}return typeof a=="string"?a:""}const Wv=/^(Category:|Total episodes:|Duration per episode:|Protagonist goal:|Main obstacle:|颿ï¼|æ»éæ°ï¼|åéæ¶é¿ï¼|主è§ç®æ ï¼|æå¤§é»ç¢ï¼)/m;function Hv(r,t){const i=String(r||"").trim();return/[\u4e00-\u9fff]/.test(i)?"zh":/[A-Za-z]/.test(i)?"en":t==="zh"?"zh":"en"}function zv(r,t){for(let i=r.length-1;i>=0;i-=1){const a=r[i];if((a==null?void 0:a.role)!=="user")continue;const u=String(a.text||"").trim();if(u&&!Wv.test(u)){if(/[\u4e00-\u9fff]/.test(u))return"zh";if(/[A-Za-z]/.test(u))return"en"}}return t==="zh"?"zh":"en"}function Kv(r){const{locale:t,hasCategory:i,categoryLabel:a,isCustomCategory:u,customNote:p,totalEpisodes:f,durationSeconds:x,draft:S}=r,k=String(S.protagonistGoal||"").trim(),v=String(S.mainObstacle||"").trim();return t==="zh"?[i?`颿ï¼${a}${u&&p?`ï¼${p}ï¼`:""}`:"颿ï¼è¯·ä½ å æ ¹æ®å½åæ äºæ¹åèªå¨ææä¸ä¸ªæå¹é é¢æï¼æåç»å¯åæ¹ï¼ã",`æ»éæ°ï¼${f} é`,`åéæ¶é¿ï¼${x} ç§`,`主è§ç®æ ï¼${k||"è¯·ä½ å èªå¨ææä¸ä¸ªæ¸ æ°ã坿§è¡ç主è§ç®æ ã"}`,`æå¤§é»ç¢ï¼${v||"è¯·ä½ å èªå¨ææä¸ä¸ªå¼ºå²çªç主è¦é»ç¢ã"}`,"è¯·å¨æå·²å¡«åå 容åºç¡ä¸ï¼èªå¨ææå©ä½å 容并继ç»è¡¥é½ç¼å§å°è¡¨åï¼ç¶ååè¯æä¸ä¸æ¥ã"].join(` 320`):[i?`Category: ${a}${u&&p?` (${p})`:""}`:"Category: Please auto-propose the best-fit category from the current story direction (I can adjust later).",`Total episodes: ${f}`,`Duration per episode: ${x} seconds`,`Protagonist goal: ${k||"Please auto-propose a clear and actionable protagonist goal."}`,`Main obstacle: ${v||"Please auto-propose one strong primary obstacle."}`,"Based on the fields I already filled, ideate the remaining content and continue filling the SCRIPT form, then give me the next step."].join(` 321`)}const qv={outline:{zh:"å建æ äºå¤§çº²",en:"Create story outline"},world_bible:{zh:"æå»ºä¸çè§",en:"Build world bible"},episode_board:{zh:"ä¼åæ´å£ç»æ",en:"Optimize season structure"},assets:{zh:"è§åèµäº§åº",en:"Plan asset library"}};function Gv(r,t){return qv[r][t]}function Yv(r){const t=r.protagonistGoal.trim(),i=r.mainObstacle.trim(),a=t&&i?r.locale==="zh"?`主è§ç®æ ï¼${t}ï¼ä¸»è¦é»ç¢ï¼${i}`:`Protagonist goal: ${t}; main obstacle: ${i}`:t||i||void 0;return{plannedEpisodes:r.totalEpisodes,episodeDurationSeconds:r.durationSeconds,dramaCategory:r.dramaCategoryId||void 0,dramaCustomNote:r.dramaCustomNote.trim()||void 0,logline:a}}const Vv={zh:"å·²æäº¤æ äºæµå¡«ç©ºå¡",en:"StoryFlow fill card submitted"};function Xv(r,t){if(r==="custom")return(t||"").trim()||"original story";const i=oa.find(a=>a.id===r);return(i==null?void 0:i.label)??""}function Yh(r){return r==="outline"?"16:9":"3:4"}function Iy(r,t,i){const a=(i==null?void 0:i.aspectRatio)??Yh(r),u=Xv(t.dramaCategoryId,t.dramaCustomNote),p=(t.seriesTitle||"Untitled").trim(),f=[t.visualStyleLabel,t.visualStyleKeywords].filter(Boolean).join(", "),x=r==="outline"?`Story logline: ${t.logline.trim()} 322Story synopsis (excerpt): ${t.synopsisExcerpt.trim().slice(0,1200)}`:`World / lore (excerpt): ${t.worldExcerpt.trim().slice(0,1200)}`;return[a==="16:9"?"Professional cinematic movie poster, widescreen 16:9 landscape key art, streaming hero / horizontal one-sheet quality.":"Professional cinematic movie poster, vertical 3:4 one-sheet composition, theatrical key art qual
322ity.",`Display the series title prominently and legibly, exactly as given (do not translate): "${p}".`,`Genre mood: ${u}.`,`Visual style: ${f||"high-end cinematic"} â consistent lighting, color grade, and production design.`,x,"No watermark, no UI frames, no collage of panels â single cohesive poster illustration.","High detail, film marketing quality, dramatic lighting, strong focal subject and readable title treatment."].join(` 323`)}const Jv="gpt-image-2-text-to-image",Qv=10;async function Py(r){var k;if(!r.projectId||!/^[0-9a-f-]{36}$/i.test(r.projectId))throw new Error("Invalid project");const t=await sb.getCurrentUser();if(!(t!=null&&t.id))throw new Error("User not authenticated");const i=r.aspectRatio??Yh(r.kind),a=r.billing??"auto_free",u=r.model??(r.kind==="outline"?Jv:"google/gemini-3.1-flash-image-preview"),p=await hw({prompt:r.prompt,model:u,size:"2K",aspectRatio:i,project_id:r.projectId,node_id:r.kind==="outline"?"storyflow-poster-outline":"storyflow-poster-world",storyflowInternalPoster:!0,storyflowPosterKind:r.kind,storyflowPosterRegen:a==="user_regen",edgeCallOptions:{silent401:!0}}),f=p==null?void 0:p.data;if(f!=null&&f.taskId&&(f==null?void 0:f.status)==="pending"){const $=Date.now();for(;Date.now()-$<6e5;){const O=await gw(f.taskId);if(O.status==="success"&&O.url)return typeof window<"u"&&window.dispatchEvent(new CustomEvent("credits-changed")),O.url;if(O.status==="failed")throw new Error(O.error||"Generation failed");await new Promise(D=>setTimeout(D,2500))}throw new Error("Image generation timed out. Please try again.")}const x=f==null?void 0:f.image,S=(k=f==null?void 0:f.image_metadata)==null?void 0:k.gcs_url;if(typeof x=="string"&&(x.startsWith("http://")||x.startsWith("https://")))return x;if(typeof S=="string"&&S.length>0)return S;throw new Error("No image URL returned")}function Zv({posterUrl:r,placeholderSrc:t,busy:i,titleStale:a,editorOpen:u,promptDraft:p,sparksLabel:f,clickToEditHint:x,promptLabel:S,promptPlaceholder:k,staleBadge:v,staleHint:I,remakeLabel:$,keepLabel:O,onOpenEditor:D,onCloseEditor:n,onPromptChange:z,onGenerate:Z,onRemakeWithTitle:Ee,onKeepCurrentTitle:Ie}){const ne=c.useRef(null),Pe=c.useRef(null);return c.useEffect(()=>{if(!u)return;const xe=ae=>{var me,Te;const de=ae.target;(me=ne.current)!=null&&me.contains(de)||(Te=Pe.current)!=null&&Te.contains(de)||n()};return document.addEventListener("pointerdown",xe),()=>document.removeEventListener("pointerdown",xe)},[u,n]),s.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-2 lg:w-[min(320px,38%)]","data-testid":"storyflow-outline-poster-panel",children:[s.jsxs("button",{ref:ne,type:"button",className:"group relative aspect-video w-full overflow-hidden rounded-lg border border-white/10 bg-black text-left","data-testid":"storyflow-outline-poster-frame",onClick:()=>{u||D()},"aria-expanded":u,"aria-label":x,children:[i?s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/50",children:s.jsx("span",{className:"material-symbols-outlined animate-spin text-2xl text-primary",children:"progress_activity"})}):null,s.jsx("img",{src:r||t,alt:"",className:"h-full w-full object-cover transition-opacity group-hover:opacity-90"}),!i&&!u?s.jsx("span",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent px-2.5 pb-2 pt-6 text-[10px] text-neutral-300",children:x}):null,a&&r?s.jsxs("div",{className:"absolute inset-x-0 top-0 z-[11] flex flex-col gap-1.5 bg-gradient-to-b from-black/90 via-black/70 to-transparent px-2.5 pb-2 pt-2","data-testid":"storyflow-poster-stale",onClick:xe=>xe.stopPropagation(),children:[s.jsx("span",{className:"inline-flex w-fit items-center rounded border border-amber-500/40 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-amber-200",children:v}),s.jsx("p",{className:"text-[10px] leading-snug text-slate-300",children:I}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[s.jsx("button",{type:"button","data-testid":"storyflow-poster-remake",disabled:i,className:"cursor-pointer rounded-md border border-primary/50 bg-primary/20 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-primary hover:bg-primary/30 disabled:cursor-not-allowed disabled:opacity-50",onClick:Ee,children:$}),s.jsx("button",{type:"button","data-testid":"storyflow-poster-keep",className:"cursor-pointer rounded-md border border-white/15 bg-black/30 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-slate-400 hover:border-white/30 hover:text-slate-200",onClick:Ie,children:O})]})]}):null]}),u?s.jsxs("div",{ref:Pe,className:"flex flex-col gap-2 rounded-lg border border-white/10 bg-black/30 p-3","data-testid":"storyflow-outline-poster-editor",children:[s.jsx("label",{className:"text-[10px] font-semibold uppercase tracking-wider text-neutral-400",children:S}),s.jsx("textarea",{className:"min-h-[7rem] w-full resize-y rounded-md border border-white/10 bg-surface-dark px-2.5 py-2 text-xs leading-relaxed text-neutral-200 outline-none focus:border-primary/40",value:p,onChange:xe=>z(xe.target.value),placeholder:k,"data-testid":"storyflow-outline-poster-prompt"}),s.jsx("button",{type:"button",disabled:i||!p.trim(),className:"inline-flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-xs font-bold uppercase tracking-wide text-black transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50","data-testid":"storyflow-outline-poster-generate",onClick:Z,children:f})]}):null]})}async function eC(r,t){var f;if(!(t!=null&&t.bypassCache)){const x=$b(r);if((f=x==null?void 0:x.rows)!=null&&f.length)return x.rows}const{supabase:i}=await Xl(async()=>{const{supabase:x}=await import("./edge-functions-CM-SJXPL.js").then(S=>S.aJ);return{supabase:x}},__vite__mapDeps([0])),a=200,u=20,p=[];for(let x=0;x<u;x+=1){const{data:S,error:k}=await i.rpc("list_user_asset_index",{p_asset_type:null,p_search:null,p_limit:a,p_offset:x*a,p_project_id:null});if(k)throw k;const v=Array.isArray(S)?S:[];if(p.push(...v),v.length<a)break}return Fb(r,p),p}const tC=({open:r,onClose:t,characters:i,scenes:a,props:u,getThumbSrc:p,onPickProjectAsset:f,seedanceApprovedEnabled:x,greenlightProjectId:S,userId:k,approvedTargetCharacterName:v=null,approvedTargetCharacterLocalId:I=null,onApprovedRefApplied:$,onDeleteLocalWorkspaceAsset:O,initialEntityTab:D="CHARACTERS"})=>{var ni,oc;const{t:n}=sh(),{enabled:z,showSegmentControls:Z}=Pw(r),[Ee,Ie]=c.useState({left:0,top:0}),ne=c.useRef({active:!1,offsetX:0,offsetY:0}),[Pe,xe]=c.useState(null),[ae,de]=c.useState(null),[me,Te]=c.useState(D),[nt,je]=c.useState("project");c.useEffect(()=>{Z||nt!=="approved"||je("project")},[Z,nt]),c.useEffect(()=>{nt==="approved"&&me!=="CHARACTERS"&&Te("CHARACTERS")},[me,nt]);const[ue,ve]=c.useState(""),[be,tt]=c.useState([]),[mr,ye]=c.useState(!1),[rr,Lt]=c.useState([]),[Ls,jt]=c.useState(!1),[Ot,it]=c.useState(()=>new Set),[qe,$t]=c.useState(null),[wt,Mr]=c.useState(!1),[At,fe]=c.useState(qw),[Re,J]=c.useState(Ff),[ie,dt]=c.useState({}),[Ft,ft]=c.useState(!1),[fr,Lr]=c.useState(!1),cr=c.useCallback(async N=>{var ee,re;let K=String(k||"").trim();if(!K){const He=await Af(5e3).catch(()=>({session:null}));K=String(((re=(ee=He==null?void 0:He.session)==null?void 0:ee.user)==null?void 0:re.id)||"").trim()}if(!K){tt([]);return}N!=null&&N.bypassCache&&Rb(K),ye(!0);try{const He=await eC(K,{bypassCache:N==null?void 0:N.bypassCache});tt(He)}catch{tt([])}finally{ye(!1)}},[k]),ps=c.useCallback(async(N=()=>!0)=>
323{if(!z){N()&&Lt([]);return}N()&&jt(!0);try{await jb({page:1,pageSize:60,onCached:K=>{N()&&(Lt(K),jt(!1))},onFresh:K=>{N()&&(Lt(K),jt(!1))}})}catch{N()&&Lt([])}finally{N()&&jt(!1)}},[z]);c.useEffect(()=>{if(!r){xe(null),de(null);return}Te(D),je("project"),ve(""),it(new Set),$t(null),fe({gender:null,eras:new Set}),J(Ff),dt({}),xf(),cr();let N=!1;return ps(()=>!N),()=>{N=!0}},[r,D,cr,ps]),c.useEffect(()=>{if(!r)return;const N=new Set,K=String(S||"").trim();K&&N.add(K);for(const re of be){const He=String(re.project_id||"").trim();He&&N.add(He)}let ee=!1;return ft(!0),xf(),bf([...N]).then(re=>{ee||(dt(re),ft(!1))}),()=>{ee=!0}},[r,S,be]),c.useEffect(()=>{if(!r||typeof window>"u")return;const N=()=>{const yt=new Set,ht=String(S||"").trim();ht&&yt.add(ht);for(const ze of be){const Fs=String(ze.project_id||"").trim();Fs&&yt.add(Fs)}return[...yt]},K=()=>{const yt=N();yt.length!==0&&(Db(yt),ft(!0),bf(yt).then(ht=>{dt(ht),ft(!1)}))},ee=yt=>{const ht=String(yt||"").trim();ht&&Ub([ht]).then(ze=>{const Fs=ze[ht]??{};dt(Vn=>{const ya=Vn[ht];return ya?{...Vn,[ht]:Wb(ya,Fs)}:Vn})})},re=()=>K(),He=yt=>{const ht=yt.detail,ze=String((ht==null?void 0:ht.projectId)||"").trim();ze?ee(ze):K()};return window.addEventListener("workflow-project-assets-refresh",re),window.addEventListener(wf,He),()=>{window.removeEventListener("workflow-project-assets-refresh",re),window.removeEventListener(wf,He)}},[r,S,be]),c.useEffect(()=>{if(!r||typeof window>"u")return;const N=window.innerWidth/3,K=Math.max(8,Math.round(N-qd/2)),ee=Math.max(8,Math.round((window.innerHeight-Kd)/2));Ie({left:K,top:ee})},[r]),c.useEffect(()=>{if(!r||typeof window>"u")return;const N=ee=>{if(!ne.current.active)return;const re=Math.max(8,window.innerWidth-qd-8),He=Math.max(8,window.innerHeight-Kd-8),yt=ee.clientX-ne.current.offsetX,ht=ee.clientY-ne.current.offsetY,ze=Math.max(8,Math.min(re,yt)),Fs=Math.max(8,Math.min(He,ht));Ie({left:ze,top:Fs})},K=()=>{ne.current.active&&(ne.current.active=!1,document.body.style.userSelect="",document.body.style.cursor="")};return window.addEventListener("mousemove",N),window.addEventListener("mouseup",K),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",K),K()}},[r]),c.useEffect(()=>{if(!r)return;const N=K=>{K.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[r,t]);const It=ue.trim().toLowerCase(),ua=c.useMemo(()=>({CHARACTERS:be.filter(N=>N.asset_type==="CHARACTERS"&&Ki(N.image_url)).filter(N=>!It||[N.name,N.desc,N.project_name].some(K=>String(K||"").toLowerCase().includes(It))).sort((N,K)=>Date.parse(String(K.updated_at||""))-Date.parse(String(N.updated_at||""))),SCENES:be.filter(N=>N.asset_type==="SCENES"&&Ki(N.image_url)).filter(N=>!It||[N.name,N.desc,N.project_name].some(K=>String(K||"").toLowerCase().includes(It))).sort((N,K)=>Date.parse(String(K.updated_at||""))-Date.parse(String(N.updated_at||""))),PROPS:be.filter(N=>N.asset_type==="PROPS"&&Ki(N.image_url)).filter(N=>!It||[N.name,N.desc,N.project_name].some(K=>String(K||"").toLowerCase().includes(It))).sort((N,K)=>Date.parse(String(K.updated_at||""))-Date.parse(String(N.updated_at||"")))}),[be,It]),Ye=c.useMemo(()=>{const N=i.map(re=>({key:`local:char:${re.id}`,thumb:p("CHARACTERS",re.id,re.name),pick:{kind:"CHARACTERS",characterId:re.id,name:re.name},name:re.name})).filter(re=>String(re.thumb||"").trim()).filter(re=>!It||re.name.toLowerCase().includes(It)),K=a.map(re=>({key:`local:scene:${re}`,thumb:p("SCENES",void 0,re),pick:{kind:"SCENES",name:re},name:re})).filter(re=>String(re.thumb||"").trim()).filter(re=>!It||re.name.toLowerCase().includes(It)),ee=u.map(re=>({key:`local:prop:${re}`,thumb:p("PROPS",void 0,re),pick:{kind:"PROPS",name:re},name:re})).filter(re=>String(re.thumb||"").trim()).filter(re=>!It||re.name.toLowerCase().includes(It));return{CHARACTERS:N,SCENES:K,PROPS:ee}},[i,a,u,p,It]),pa=c.useMemo(()=>({CHARACTERS:rr.filter(N=>_w(N.tags)).filter(N=>!It||String(N.name||"").toLowerCase().includes(It)).filter(N=>Gw(N.tags,At)),SCENES:[],PROPS:[]}),[rr,It,At]),pn=ua[me],mn=Ye[me],fn=pn.filter(N=>Bw(N,me,Re,ie)),Zo=S?((ni=ie[String(S).trim()])==null?void 0:ni.effectiveMedium)??((oc=ie[String(S).trim()])==null?void 0:oc.medium)??"unknown":"unknown",ei=mn.filter(N=>{var K;if(Re.medium!=null&&!Mw(Zo,Re))return!1;if(me==="CHARACTERS"&&Re.gender!=null){const ee=S?ie[String(S).trim()]:void 0;if(Lw(void 0,N.name,void 0,ee==null?void 0:ee.genderByCharacterName,ee==null?void 0:ee.scriptText,(K=ee==null?void 0:ee.assetLlmClassificationByLocalId)==null?void 0:K[String(N.pick.kind==="CHARACTERS"?N.pick.characterId:"")])!==Re.gender)return!1}return!0}),Cs=pa[me],ti=pn.length===0&&mn.length>0,Gn=fn.length>0||ti&&ei.length>0,Ku=Re.medium!=null||me==="CHARACTERS"&&Re.gender!=null,Yn=c.useMemo(()=>({moreMenuAriaLabel:n("canvas.library.moreActions"),zoomAriaLabel:n("canvas.library.zoomImage"),downloadAriaLabel:n("canvas.library.downloadImage"),renameAriaLabel:n("canvas.library.renameAsset"),deleteAriaLabel:n("canvas.library.deleteAsset")}),[n]),Os=c.useCallback(N=>{if(N.indexedRowId){const K=`indexed:${N.indexedRowId}`;it(re=>{if(!re.has(K))return re;const He=new Set(re);return He.delete(K),He}),tt(re=>re.filter(He=>!Ab(He,{indexedRowId:N.indexedRowId,projectId:N.projectId,assetLocalId:Number(N.assetId)})));const ee=String(k||"").trim();ee&&Ib(ee,{indexedRowId:N.indexedRowId,projectId:N.projectId,assetLocalId:Number(N.assetId)})}N.localSelectionKey&&it(K=>{if(!K.has(N.localSelectionKey))return K;const ee=new Set(K);return ee.delete(N.localSelectionKey),ee}),qe&&(N.indexedRowId&&qe.selectionKey===`indexed:${N.indexedRowId}`||N.localSelectionKey&&qe.selectionKey===N.localSelectionKey)&&$t(null)},[qe,k]),ma=c.useCallback(N=>{xe(N)},[]),fa=c.useCallback((N,K,ee,re)=>{const He=ee.trim();He&&(re&&tt(yt=>yt.map(ht=>
323ht.id===re?{...ht,name:He}:ht)),qe&&qe.selectionKey===`indexed:${re}`&&$t(yt=>yt&&{...yt,name:He}))},[qe]),rc=c.useCallback(N=>{de({...N,draft:N.name})},[]),sc=c.useCallback(async N=>{const K=N.draft.trim();if(!K){H.warning(n("page.workflowAssetLibrary.nameRequiredTitle"),n("page.workflowAssetLibrary.nameRequiredBody"));return}if(K===N.name.trim()){de(null);return}de(null),fa(N.projectId,N.assetId,K,N.indexedRowId),(await Pb(N.projectId,N.assetId,K)).ok||(H.warning(n("canvas.library.renameAssetFailedTitle"),n("canvas.library.renameAssetFailedBody")),cr({bypassCache:!0}))},[fa,cr,n]),nc=c.useCallback(async N=>{if(xe(null),N.localPick){if(!O)return;O(N.localPick),Os(N);return}const K=String(N.projectId||"").trim(),ee=Number(N.assetId);if(!K||!Number.isFinite(ee))return;Os(N),(await _b(K,ee)).ok||(H.warning(n("canvas.library.deleteAssetFailedTitle"),n("canvas.library.deleteAssetFailedBody")),cr({bypassCache:!0}))},[Os,O,cr,n]),Le=c.useCallback(N=>{$t({...N,selected:Ot.has(N.selectionKey)})},[Ot]),$s=c.useCallback((N,K)=>{const ee=Jx(N)||N;ee&&rh(ee,`${String(K||"asset").trim()||"asset"}-${Date.now()}.png`)},[]),Oe=c.useCallback((N,K)=>{it(ee=>{const re=new Set(ee);return re.has(N)?re.delete(N):re.add(N),$t({...K,selectionKey:N,selected:re.has(N)}),re})},[]),Or=c.useMemo(()=>{const N=new Map;for(const K of Ye.CHARACTERS)N.set(K.key,K.pick);for(const K of Ye.SCENES)N.set(K.key,K.pick);for(const K of Ye.PROPS)N.set(K.key,K.pick);return N},[Ye]),sr=c.useCallback(async N=>{var ee;if(!S||I==null){H.info(n("page.workflowAssetLibrary.approvedUseSelectAssetTitle"),n("page.workflowAssetLibrary.approvedUseSelectAssetBody"));return}const K=await Af(5e3).catch(()=>({session:null}));if(!((ee=K==null?void 0:K.session)!=null&&ee.access_token)){H.warning(n("canvas.library.approvedUseSessionExpiredTitle"),n("canvas.library.approvedUseSessionExpiredBody"));return}Mr(!0);try{const re=await Bb({atlasAssetId:String(N.atlasAssetId||"").trim(),projectId:S,assetLocalId:I});$==null||$(re.url),H.success(n("page.workflowAssetLibrary.approvedUseSelectionSuccessTitle"),n("page.workflowAssetLibrary.approvedUseSelectionSuccessBody",{name:v||""}))}catch(re){H.warning(n("page.workflowAssetLibrary.approvedUseFailedTitle"),Bt(re))}finally{Mr(!1)}},[I,v,S,$,n]),ri=N=>{const K=Ki(N.image_url);if(!K)return;const ee=`indexed:${N.id}`;Oe(ee,{selectionKey:ee,name:String(N.name||"Asset").trim()||"Asset",imageUrl:K,sourceLabel:String(N.project_name||n("canvas.library.project")),selected:!1})},yr=N=>{Oe(N.key,{selectionKey:N.key,name:N.name,imageUrl:N.thumb,sourceLabel:n("canvas.library.currentProject"),selected:!1})},Er=N=>{const K=String(N.atlasAssetId||"").trim();if(!K)return;const ee=String(N.previewUrl||"").trim(),re=`approved:${K}`,He=Ot.has(re);Oe(re,{selectionKey:re,name:String(N.name||"Character").trim()||"Character",imageUrl:ee,sourceLabel:n("page.workflowAssetLibrary.approvedPaneTitle"),selected:!1}),!He&&I!=null&&S&&me==="CHARACTERS"&&sr(N)},si=N=>{N!==me&&(Te(N),$t(null),it(new Set))};if(!r||typeof document>"u")return null;const Tr=z&&nt==="approved",St=!z||nt==="project",hr=Tr?Ls:mr,Ns=qe&&Or.get(qe.selectionKey)?Or.get(qe.selectionKey):null;return Ps.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[10030] bg-black/72 backdrop-blur-sm",role:"presentation",onClick:t,children:s.jsxs("div",{className:"absolute rounded-2xl border border-white/10 bg-[#121418] shadow-2xl overflow-visible",style:{width:qd,height:Kd,left:`${Ee.left}px`,top:`${Ee.top}px`},role:"dialog","aria-modal":"true","aria-labelledby":"storyflow-asset-library-mini-title",onClick:N=>N.stopPropagation(),children:[s.jsx("div",{className:"h-full overflow-hidden rounded-2xl",children:s.jsxs("div",{className:"custom-scrollbar h-full overflow-y-auto",children:[s.jsxs("div",{className:"flex cursor-move items-center justify-between border-b border-white/10 px-5 py-4",onMouseDown:N=>{N.button!==0||N.target.closest("button")||(ne.current.active=!0,ne.current.offsetX=N.clientX-Ee.left,ne.current.offsetY=N.clientY-Ee.top,document.body.style.userSelect="none",document.body.style.cursor="move")},children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:"storyflow-asset-library-mini-title",className:"text-xs font-bold uppercase tracking-wider text-white",children:n("canvas.library.openLibrary")}),s.jsx("p",{className:"mt-0.5 text-[11px] text-zinc-500",children:n(Z?"canvas.library.approvedLibraryMiniHint":"canvas.library.miniAssetLibrary")})]}),s.jsx("button",{type:"button",onClick:t,className:"rounded-lg p-1.5 text-zinc-400 hover:bg-white/10 hover:text-white","aria-label":n("page.storyflow.closeAria"),children:s.jsx("span",{className:"material-symbols-outlined",children:"close"})})]}),s.jsxs("div",{className:"p-5 pb-6",children:[s.jsxs("div",{className:"mb-3 flex flex-col gap-2.5",children:[Z?s.jsxs("div",{className:"flex flex-wrap items-end gap-2 border-b border-white/10",children:[s.jsx("div",{className:"flex items-end gap-5",role:"tablist","aria-label":n("canvas.library.openLibrary"),children:["project","approved"].map(N=>s.jsx("button",{type:"button",role:"tab","aria-selected":nt===N,onClick:()=>{je(N),N==="approved"&&Te("CHARACTERS"),$t(null)},className:`-mb-px border-b-2 pb-2 text-[11px] font-semibold tracking-wide transition-colors ${nt===N?"border-primary text-white":"border-transparent text-zinc-500 hover:text-zinc-300"}`,children:n(N==="project"?"canvas.library.segmentProject":"canvas.library.segmentApproved")},N))}),s.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2 pb-2",children:[St?s.jsx(Lf,{projectId:String(S||"").trim(),disabled:hr||wt||!S,onClick:()=>Lr(!0)}):null,Tr?s.jsx(Ow,{projectId:String(S||"").trim(),disabled:hr||wt,onSubmitted:()=>{ps(),cr({bypassCache:!0})}}):null]})]}):St?s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:s.jsx(Lf,{projectId:String(S||"").trim(),disabled:hr||wt||!S,onClick:()=>Lr(!0)})}):null,St?s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[$w("project").map(N=>s.jsx("button",{type:"button",onClick:()=>si(N),className:`rounded-lg px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider transition-colors ${me===N?"bg-primary text-black":"border border-white/10 bg-white/5 text-zinc-300 hover:border-primary/50 hover:text-white"}`,children:n(N==="CHARACTERS"?"page.workflowAssetLibrary.tabCharacters":N==="SCENES"?"page.workflowAssetLibrary.tabScenes":"page.workflowAssetLibrary.tabProps")},N)),s.jsx("button",{type:"button",onClick:()=>void cr(),disabled:hr||wt,className:"ml-auto rounded-lg border border-white/15 bg-white/5 px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider text-zinc-200 hover:border-primary/50 hover:text-white disabled:pointer-events-none disabled:opacity-50",children:n("canvas.library.refresh")})]}):Tr?s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:"text-[10px] text-zinc-500",children:n("canvas.library.approvedCharactersOnlyHint")}),s.jsx("button",{type:"button",onClick:()=>void ps(),disabled:hr||wt,className:"ml-auto rounded-lg border border-white/15 bg-white/5 px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider text-zinc-200 hover:border-primary/50 hover:text-white disabled:pointer-events-none disabled:opacity-50",children:n("canvas.library.refresh")})]}):null]}),Tr?s.jsx(Yw,{}):null,s.jsx("div",{className:"mb-2",children:s.jsx("input",{value:ue,onChange:N=>ve(N.target.value),placeholder:n("canvas.library.searchAssetsPlaceholder"),className:"w-full rounded-lg border border-white/10 bg-white/[0.03] px-2.5 py-1.5 text-[11px] text-white/90 outline-none placeholder:text-zinc-500 focus:border-primary/50"})}),s.jsx("p",{className:"mb-2 text-[10px] text-zinc-500",children:n("canvas.library.selectionHint",{max:Mb})}),Tr?s.jsx(Vw,{className:"mb-3",value:At,onChange:fe}):St?s.jsx(Fw,{entityTab:me,value:Re,onChange:J,className:"mb-3"}):null,s.jsx("div",{children:hr&&!(St&&Gn)?s.jsx(Df,{children:n("canvas.library.loadingAssets")}):St&&Ku&&Ft?s.jsx(Df,{children:n("canvas.library.loadingAssets")}):Tr?Cs.length===0?s.jsx(Uf,{children:n("canvas.library.noImagesInTab")}):s.jsx(Wf,{children:Cs.map(N=>{const K=String(N.atlasAssetId||"").trim(),ee=`approved:${K}`,re=Lb(K),He=Ot.has(ee)||I!=null&&re===I;return s.jsx(Dw,{active:He,thumb:String(N.previewUrl||""),approvedLabel:n("page.workflowAssetLibrary.approvedPaneTitle"),missingLabel:n("canvas.library.missing"),selectedLabel:n("canvas.library.selected"),onClick:()=>Er(N),...Yn,onZoom:()=>Le({selectionKey:ee,name:String(N.name||"Character").trim()||"Character",imageUrl:String(N.previewUrl||"").trim(),sourceLabel:n("page.workflowAssetLibrary.approvedPaneTitle")}),onDownload:()=>$s(String(N.previewUrl||"").trim(),String(N.name||"Character"))},ee)})}):St&&!Gn?s.jsx(Uf,{children:n("canvas.library.noImagesInTab")}):St&&Gn?s.jsx(Wf,{children:ti?ei.map(N=>s.jsx(Uw,{active:Ot.has(N.key),thumb:N.thumb,currentLabel:n("canvas.library.current"),assetName:N.name,missingLabel:n("canvas.library.missing"),selectedLabel:n("canvas.library.selected"),onClick:()=>yr(N),...Yn,onZoom:()=>Le({selectionKey:N.key,name:N.name,imageUrl:N.thumb,sourceLabel:n("canvas.library.currentProject")}),onDownload:()=>$s(N.thumb,N.name),onDelete:O?()=>ma({name:N.name,localPick:N.pick,localSelectionKey:N.key}):void 0},N.key)):fn.map(N=>{const K=Ki(N.image_url),ee=K?Ob(K)||K:"";return s.jsx(Ww,{active:Ot.has(`indexed:${N.id}`),thumb:ee,projectLabel:N.project_name||n("canvas.library.project"),assetName:String(N.name||"Asset").trim()||"Asset",missingLabel:n("canvas.library.missing"),selectedLabel:n("canvas.library.selected"),onClick:()=>ri(N),...Yn,onZoom:()=>{K&&Le({selectionKey:`indexed:${N.id}`,name:String(N.name||"Asset").trim()||"Asset",imageUrl:K,sourceLabel:String(N.project_name||n("canvas.library.project"))})},onDownload:()=>$s(ee||K||"",String(N.name||"Asset")),onDelete:()=>{const re=Number(String(N.asset_local_id||"").trim()),He=String(N.project_id||"").trim();!He||!Number.isFinite(re)||ma({projectId:He,assetId:re,name:String(N.name||"Asset").trim()||"Asset",indexedRowId:N.id})},onRename:()=>{const re=Number(String(N.asset_local_id||"").trim()),He=String(N.project_id||"").trim();!He||!Number.isFinite(re)||rc({projectId:He,assetId:re,name:String(N.name||"Asset").trim()||"Asset",indexedRowId:N.id})}},N.id)})}):null})]})]})}),s.jsx("div",{className:`absolute top-3 bottom-3 left-full h-auto overflow-hidden rounded-r-2xl transition-transform duration-300 will-change-transform -z-10 ${qe?"translate-x-0 border border-white/10 bg-[#15181c]":"-translate-x-full pointer-events-none border border-transparent bg-transparent"}`,style:{width:Hw},children:qe?s.jsx(zw,{candidate:{...qe,selected:Ot.has(qe.selectionKey)},previewTitle:n("canvas.library.imagePreview"),closeLabel:n("canvas.library.close"),selectedHint:n("canvas.library.selectedClickToRemove"),notSelectedHint:n("canvas.library.notSelectedClickToSelect"),onClose:()=>$t(null),extraFooter:Ns?s.jsx("button",{type:"button",onClick:()=>{f(Ns),t()},className:"rounded-md bg-primary px-3 py-2 text-[10px] font-semibold text-black hover:brightness-105",children:n("page.storyflow.openAssetEditor")}):null}):null})]})}),s.jsx(Xw,{isOpen:!!Pe,onClose:()=>xe(null),onConfirm:()=>{const N=Pe;N&&nc(N)},title:n("canvas.library.deleteAsset"),message:n("canvas.library.deleteAssetConfirm",{name:(Pe==null?void 0:Pe.name)??""})}),s.jsx(Kw,{open:!!ae,title:n("canvas.library.renameAssetTitle"),draft:(ae==null?void 0:ae.draft)??"",cancelLabel:n("canvas.library.cancel"),saveLabel:n("canvas.library.renameSave"),nameInputAriaLabel:n("canvas.library.renameAssetInput"),onDraftChange:N=>de(K=>K&&{...K,draft:N}),onClose:()=>de(null),onSave:()=>{const N=ae;N&&sc(N)}}),s.jsx(Aw,{open:fr,onClose:()=>Lr(!1),projectId:String(S||"").trim(),onAdded:async N=>{Te(N.type),$t(null),it(new Set),cr({bypassCache:!0})},elevatedStack:!0})]}),document.body)},rC=c.lazy(()=>Xl(()=>import("./MjVariantPickerModal-DfDZ617z.js"),__vite__mapDeps([0])).then(r=>({default:r.MjVariantPickerModal})));let su=null;const sC=6e4,nC=165e3,oC=()=>(su||(su=Xl(()=>import("./MjVariantPickerModal-DfDZ617z.js"),__vite__mapDeps([0]))),su),nu=`# Role
324ä½ æ¯ä¸ä½ç¡¬æ ¸å¥½è±å导æ¼ï¼æ é¿å°æå转å为æå ·å·¥ä¸è´¨æãæ åºè¯ã纯è§è§åäºçâ导æ¼è§è§ç½ç®ä¹¦âä¸âåéèæ¬âãä½ å´å°ãé临ã(Arrival) ä¸ãè¾¹å¢ææã(Sicario) çå·å³»ç¾å¦ã 325 326# Task 327è¯·å°ææä¾çæ··ä¹±èæ¬éæ°æ´ç为ä¸ä»½ã导æ¼åéèæ¬ãã 328 329# Rules (æ ¸å¿çº¦æ) 3301. **严ç¦åå¹¶ä¸å å**ï¼åå§èæ¬ä¸æå¤å°ä¸ªé头ï¼è¾åºå¿ 须对åºç¸åæ°éç Shotãå¿ é¡»ä¸¥æ ¼è¯å«å¹¶æ 注 [Shot 01] å° [Shot 28]ï¼ä¸¥ç¦è·³å·ï¼ä¸¥ç¦ä¸ºäºå¨ä½è¿è´¯èåå¹¶é头ã 3312. **å 餿æç ½æ æç½**ï¼ä¸¥ç¦åºç°ä»»ä½ææ§ç大忥æå å¿ç¬ç½ãåäºå¿ é¡»å®å ¨éè¿ç©ä½è¿å¨ãå 影对æ¯ãè§è²è¡ä¸ºåç©ç鳿ä½ç°ã 3323. **ææ¯æ¯è¯åµå ¥**ï¼æ¯ä¸ç»åéæè¿°å¿ é¡»å å«ï¼Realperson photo, IMAX film camera, Cinematic lighting, dramatic shadows, film grain, Cooke anamorphic lens, 16:9 æ¯ä¾, anamorphic lens flareã 3334. **æ ¼å¼è§è**ï¼ 334 - 第ä¸é¨åï¼è§è§ç½ç®ä¹¦ï¼é£æ ¼æ»è§ãæ ¸å¿åºæ¯è´¨æã主è§è§è§è®¾å®ï¼ã 335 - 第äºé¨åï¼åéèæ¬ï¼ä¸¥æ ¼æç §ä¸è¿° [Shot æ ¼å¼] æ§è¡ï¼ã 336 337# Shot æ ¼å¼æ å (ä¸¥æ ¼æ§è¡) 338Shot [æ°å] | [[SCENE:åºæ¯å]] | [æ¯å«ï¼å¦ ECU/CU/MS/LS/ELS] 339- é头å¨ä½ (Movement)ï¼[æè¿°æ¨ææç§»ãåæ ¼/æ ¢å¨ä½ãæææçä¸ä¸è°åº¦]
340- è§è§ç»é¢ (Visuals)ï¼[åºäºææ¯æ¯è¯çè§è§æè¿°ï¼å¼ºè°å å½±ãæè´¨ãå¾®è§ç»è] 341- 鳿 (Audio)ï¼[ä» éç©ç鳿ï¼é屿å»ã龿¯ãç¢è£å£°ãç¯å¢ç½åªé³] 342 343# Input Data 344æ¥èªEpisode bloombotçèæ¬åé头姿¬å 容`;function iC(r){return String(r||"").replace(/```[\s\S]*?```/g,t=>t.replace(/```/g,"").trim()).trim()}function aC(r){return(r||[]).map(i=>{const a=i.role==="assistant"?"BloomBot":"User",u=String(i.text||"").trim();return u?`${a}: ${u}`:""}).filter(Boolean).join(` 345`)}function cs(r,t,i=30){const a=new Set,u=[],p=f=>{const x=String(f||"").trim();!x||a.has(x)||(a.add(x),u.push(x))};return(r||[]).forEach(p),t.forEach(f=>p(String(f||"").trim())),u.length>i?u.slice(u.length-i):u}const lC="Cinematic",jl=1,cC=ln,Ji=Br,dC=1,uC=Br,dn=1,pr=100,ou=6,iu=10,_y=3e3,pC=5e3,au=6,mC=4,fC=36;function We(r,t=!1){return fb({seconds:r,standaloneFilmMode:t})}function Al(r,t=!1){return Math.round(We(r,t)/60)}function lu(r,t=!1){const i=r.trim();if(!i)return null;const a=Number(i);return!Number.isFinite(a)||a<=0?null:t?mb(a):ln}function cu(r,t=!1){return We(r*60,t)}function du(r,t){var S,k,v;const i=String(r||"").trim();if(!i)return;const a=Kn(i),u=ca(i);if(vs(i)||u||(a==null?void 0:a.plannedEpisodes)===1)t.setStoryflowStandaloneFilmMode(!0),t.setPlannedEpisodeCount(1),t.setPlannedEpisodeCountDraft(null),t.setStoryflowPlanAck(I=>({...I,episodeCount:!0}));else if(typeof(a==null?void 0:a.plannedEpisodes)=="number"&&a.plannedEpisodes>1){const I=Math.max(dn,Math.min(pr,Math.floor(a.plannedEpisodes)));t.setStoryflowStandaloneFilmMode(!1),t.setPlannedEpisodeCount(I),t.setPlannedEpisodeCountDraft(null),t.setStoryflowPlanAck($=>({...$,episodeCount:!0}))}const p=u||(typeof(a==null?void 0:a.episodeDurationSeconds)=="number"?a.episodeDurationSeconds:void 0),f=vs(i)||!!u||(a==null?void 0:a.plannedEpisodes)===1,x=typeof(a==null?void 0:a.plannedEpisodes)=="number"&&a.plannedEpisodes>1;f&&typeof p=="number"?(t.setEpisodeDurationSeconds(We(p,!0)),(S=t.setEpisodeDurationMinutesDraft)==null||S.call(t,null),t.setStoryflowPlanAck(I=>({...I,episodeDuration:!0}))):x?(t.setEpisodeDurationSeconds(Br),(k=t.setEpisodeDurationMinutesDraft)==null||k.call(t,null),t.setStoryflowPlanAck(I=>({...I,episodeDuration:!0}))):typeof p=="number"&&(t.setEpisodeDurationSeconds(We(p,!!u)),(v=t.setEpisodeDurationMinutesDraft)==null||v.call(t,null),t.setStoryflowPlanAck(I=>({...I,episodeDuration:!0})))}function sn(r){const t=Math.floor(Number.isFinite(r)?r:dn);return Math.max(dn,Math.min(pr,t))}function Ut(r){const t=We(r),i=Math.round(t/60*14);return Math.max(10,i)}function yC(r){return/(?:^|\n)\s*EPISODE\s+BLUEPRINT\b/i.test(String(r||""))}function Il(r){return`dc-${r.trim().toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`}const By="bloomway_cb_rag_workspace_id",My="bloomway_cb_guided_completed_v1",uu="bloomway_cb_dashboard_toggle_demo_v1";function hC(){if(typeof window>"u")return"";try{let r=localStorage.getItem(By);return(!r||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r))&&(r=crypto.randomUUID(),localStorage.setItem(By,r)),r}catch{return crypto.randomUUID()}}const Pl={dramaCategoryId:"",dramaCustomNote:"",totalEpisodes:"",durationSeconds:"",protagonistGoal:"",mainObstacle:""},gC={dramaCategory:"å¡«å颿",totalEpisodes:"填忻鿰",durationSeconds:"å¡«ååéæ¶é¿ï¼åéï¼",protagonistGoal:"å¡«å主è§ç®æ ",mainObstacle:"å¡«åæå¤§é»ç¢"},xC={dramaCategory:"Fill category",totalEpisodes:"Fill total episodes",durationSeconds:"Fill duration (minutes)",protagonistGoal:"Fill protagonist goal",mainObstacle:"Fill main obstacle"},bC={dramaCategory:"颿",totalEpisodes:"æ»éæ°",durationSeconds:"åéæ¶é¿ï¼åéï¼",protagonistGoal:"主è§ç®æ ",mainObstacle:"æå¤§é»ç¢"},wC={dramaCategory:"category",totalEpisodes:"total episodes",durationSeconds:"duration (minutes)",protagonistGoal:"protagonist goal",mainObstacle:"main obstacle"};function SC(r){return!r.styleLocked&&r.storyArcReady&&r.worldBibleReady&&r.charactersReady&&r.titleReady&&r.episodePlanReady&&r.dramaReady}function _s(r){if(!Array.isArray(r))return[];const t=[];for(const i of r){if(!i||typeof i!="object")continue;const a=i.role,u=i.text;if(a!=="user"&&a!=="assistant"||typeof u!="string")continue;const p=i.rawAssistantReply,f=i.optionChips;t.push({role:a,text:Dv(u.slice(0,2e4)),rawAssistantReply:typeof p=="string"?p.slice(0,4e4):void 0,optionChips:Array.isArray(f)?f.filter(x=>
345typeof x=="string").slice(0,12):void 0})}return t.slice(-120)}const Qi=[];function kC(r){if(!r||typeof r!="object"||Array.isArray(r))return{};const t={};for(const[i,a]of Object.entries(r)){const u=Number(i);!Number.isFinite(u)||u<0||(t[u]=_s(a))}return t}function vC(r){if(!r||typeof r!="object"||Array.isArray(r))return{};const t={};for(const[i,a]of Object.entries(r)){const u=String(i||"").trim();!u||u.length>120||(t[u]=_s(a))}return t}function Cr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ep-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Ly(r){const t=String(r||"").trim();if(!t)return!1;const i=Lu(t);return tr(i)}function CC(r){const t=String(r||"");return t.includes(Wn)||t.includes(zn)||t.includes("[[GREENLIGHT_STRUCTURE_JSON]]")||t.includes("[[/GREENLIGHT_STRUCTURE_JSON]]")}function NC(r,t,i){const a=r.slice(Math.max(0,t-44),t).trimEnd(),u=r.slice(i,Math.min(r.length,i+36));return!!(/^\s*[è¬å¼]/.test(u)||/^\s*ç(?:ç°æ|ç°é¾|é´é|åæ|æ¦è§|ç§å¹»|æ¬ç|å·é
·|ç¾å¦|æ°å´|é头|è²è°|è´¨æ|è§è§|ç»é£|æ«ä¸|åºå|å²è¯|浪漫|ç¡¬æ ¸|åè¿«|åé|空å¯|诡å¼)/.test(u)||/^\s*飿 ¼/.test(u)||/(?:å¦
345å|类似|åè|åé´|对æ |è´æ¬|å»¶ç»|å ä¸|èå|ææ|碰æ|æ¯æ|对æ äº).{0,10}$/i.test(a)||/^\s*ç[^ï¼ã\n]{1,14}(?:æ|æ°å´|ç¾å¦|åè¿«|å¼ å|æ°è´¨|对æ¯|ææ|è°æ§)/.test(u)||/(?:飿 ¼|ç»é£|è´¨æ|è²è°|å å½±|é头|å½±å|è§è§|ç»é¢|è§æ)(?:ä¸|é|ä¸)?\s*$/i.test(a)||/\b(?:like|reminiscent|similar to|in the vein of|references?)\s*$/i.test(a))}function Oy(r,t){const i=mw(t,r);return fw(r,{namingAssistantText:i})}function EC(r){const t=r.trim();if(!t)return null;const i=t.match(/(?:series\s*title|title|å§å|çå|æ é¢)\s*[:ï¼]\s*[â"ã]?([^"\nãâ]{2,80})[ãâ"]?/i);if(i!=null&&i[1]){const S=i[1].trim();if(S&&!Bs(S))return S}const a=t.match(/(?:å§å|çå|ç³»åå|æ¬å§|该å§|å®å(?:为)?|å½å(?:为)?|é¢ä¸º|å°±å«|åå)\s*[:ï¼]?\s*ã([^ã\n]{2,60})ã/i);if(a!=null&&a[1]){const S=a[1].trim();if(S&&!Bs(S))return S}const u=/ã([^ã\n]{2,60})ã/g;let p,f=null,x=0;for(;(p=u.exec(t))!==null;){const S=p[0],k=p[1].trim();if(!k||Bs(k))continue;const v=p.index,I=v+S.length;if(NC(t,v,I))continue;const $=t.slice(Math.max(0,v-24),v),O=/(?:å°±å«|称为|èµ·å|æä»¬çå§|è¿é¨å§|æ¬ç³»å)\s*$/i.test($)?3:/(?:ç³»å|壿|å§é)\s*$/i.test($)?2:1;O>=x&&(x=O,f=k)}return f}function Hn(r){const t=String(r||"").replace(/^[-*â¢\d.\s]+/,"").replace(/^["'ââââãããã\[\]()ï¼ï¼]+|["'ââââãããã\[\]()ï¼ï¼]+$/g,"").trim();return!t||t.length<2||t.length>20||/[ãï¼ï¼!?]/.test(t)?null:t}function Mt(r){const t=String(r||"").trim();if(!t)return"";const i=t.match(/(?:主è§|é è§|æ£æ´¾|åæ´¾)\s*[ï¼(]\s*代å·\s*[:ï¼]\s*([^ï¼)]+)\s*[ï¼)]/);if(i!=null&&i[1]){const u=Hn(String(i[1]||""));if(u)return u}const a=t.replace(/代å·\s*[:ï¼]\s*/g,"").replace(/\b(?:主è§|é è§|æ£æ´¾|åæ´¾|protagonist|supporting|hero|villain|antagonist)\b/gi,"").replace(/[ï¼(][^ï¼)]*[ï¼)]/g," ").replace(/\s{2,}/g," ").trim();return Hn(a)||Hn(t)||t}function $y(r){const t=String(r||"").trim();if(!t)return"?";const i=t.split(/\s+/).filter(Boolean);return i.length>=2?`${i[0][0]||""}${i[1][0]||""}`.toUpperCase():t.slice(0,1).toUpperCase()}function Un(r){const t=String(r||"").trim();if(!t)return[];const i=[],a=new Set,u=S=>{const k=Hn(S);if(!k)return;const v=k.toLowerCase();a.has(v)||(a.add(v),i.push(k))},p=Mt(t);p&&u(p);const f=t.replace(/代å·\s*[:ï¼]\s*/g,"").replace(/\b(?:主è§|é è§|æ£æ´¾|åæ´¾|protagonist|supporting|hero|villain|antagonist)\b/gi,"").replace(/[ï¼(][^ï¼)]*[ï¼)]/g," ").trim();u(f);const x=[...t.matchAll(/[ï¼(ã\[]([^ï¼)ã\]]+)[ï¼)ã\]]/g)];for(const S of x)u(String(S[1]||""));return u(t),i}function Wo(r,t){const i=String(r||"");if(!i.trim())return[];if(t==="CHAR")return nh(i);const a=[],u=new Set,p=new RegExp(`\\[\\[${t}\\s*:\\s*([^\\]]+)\\]\\]`,"ig");let f;for(;f=p.exec(i);){const x=Hn(String(f[1]||""));if(!x)continue;const S=x.toLowerCase();u.has(S)||(u.add(S),a.push(x))}return a}function TC(r){const t=[],i=String(r.summary||"").trim();i&&t.push(i);const a=String(r.detailedScript||"").trim();a&&t.push(a);const u=String(r.detailedScriptBloomDraft||"").trim();u&&t.push(u);for(const p of r.generationUnits||[]){const f=String(p.descriptiveScript||"").trim();f&&t.push(f)}return t.join(` 346 347`)}function pu(r,t){const i=String(r||"");if(!i.trim())return[];const a=[],u=new Set;for(const p of t){const f=new RegExp(`(?:^|\\n)\\s*(?:${p})\\s*[:ï¼]\\s*([^\\n]+)`,"ig");let x;for(;x=f.exec(i);){const S=String(x[1]||"").split(/[ï¼,ã;ï¼|/]+/).map(k=>k.trim()).filter(Boolean);for(const k of S){const v=Hn(k);if(!v)continue;const I=v.toLowerCase();u.has(I)||(u.add(I),a.push(v))}}}return a}function Fy(r){const t=String(r||"").trim();if(!t)return[];const i=t.split(/[ï¼,ã;ï¼|/ï¼:\-â]/).map(f=>f.trim()).filter(Boolean),a=/(å|é|æ|宫|殿|楼|è¡|å··|港|å²|å±±|è°·|æ|é¦|å |é¢|ç«|å|åºå°|妿 ¡|å»é¢|åå ¬å®¤|é å§|æ é¦|å§é¢|å®éªå®¤|è¥å°|market|city|town|street|office|school|hospital|station|harbor|port|base|lab)$/i,u=[],p=new Set;for(const f of i){const x=Hn(f);if(!x||!a.test(x))continue;const S=x.toLowerCase();p.has(S)||(p.add(S),u.push(x))}return u}function RC(r){const t=String(r||"").trim();
347return t?t.replace(/^\s*第\s*\d+\s*(?:é|è¯|ç« )\s*[:ï¼\-â.]?\s*/i,"").replace(/^\s*(?:episode|ep|e)\.?\s*0*\d+\s*[:ï¼\-â.]?\s*/i,"").replace(/^\s*\(\s*第\s*\d+\s*(?:é|è¯|ç« )\s*\)\s*/i,"").replace(/^\s*\[\s*第\s*\d+\s*(?:é|è¯|ç« )\s*\]\s*/i,"").trim()||t:""}function da(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vh(r){return String(r||"").replace(/^(?:BloomBot|User)\s*:\s*/i,"").trim()}function Dy(r,t){const i=String(t||"").trim();if(!i||!r.trim())return"";const a=new Set,u=v=>{const I=v.trim();I.length>=1&&I.length<=64&&a.add(I)};u(i);const p=Mt(i);p&&u(p);for(const v of Un(i))u(v);const f=r.split(/\n/),x=v=>Vh(v).replace(/^#{1,6}\s+/,"").replace(/^\*{1,2}\s*/,"").replace(/\*{1,2}\s*$/g,"").trim(),S=v=>{const I=x(v);return!I||I.length>140?!1:!!(/è§è²å½¢è±¡è®¾è®¡\s*$/.test(I)||/\bCharacter visual design\s*$/i.test(I)||/形象设计\s*$/.test(I)&&/^[^\n*â¢\-]{1,50}形象设计\s*$/.test(I))},k=v=>{const I=x(v);if(!I)return!1;for(const $ of a){const O=da($);if(new RegExp(`^${O}\\s*è§è²å½¢è±¡è®¾è®¡`).test(I)||new RegExp(`^${O}\\s*形象设计`).test(I)||new RegExp(`^${O}\\s*[â\\-]\\s*Character visual design`,"i").test(I))return!0}return!1};for(let v=0;v<f.length;v++){if(!k(f[v])||!S(f[v]))continue;const I=[];for(let O=v+1;O<f.length;O++){const D=f[O];if(S(D))break;I.push(D)}const $=I.join(` 348`).trim();if($.length>=8)return $.slice(0,12e3)}return""}function jC(r,t){const i=String(t||"").trim();if(!i||!r.trim())return"";const a=new Set;a.add(i);const u=Mt(i);u&&a.add(u);for(const p of Un(i))a.add(p);for(const p of a){const f=da(p.trim());if(!f)continue;const x=new RegExp(`@@${f}\\s*ã([\\s\\S]*?)ã`,"i"),S=r.match(x),k=String((S==null?void 0:S[1])||"").trim();if(k.length>=8)return k.slice(0,12e3)}return""}function AC(r,t){const i=String(t||"").trim();if(!i||!r.trim())return"";const a=new Set;(k=>{const v=k.trim();v.length>=1&&v.length<=64&&a.add(v)})(i);const p=r.split(/\n/),f=k=>Vh(k).replace(/^#{1,6}\s+/,"").replace(/^\*{1,2}\s*/,"").replace(/\*{1,2}\s*$/g,"").trim(),x=k=>{const v=f(k);return!v||v.length>140?!1:!!(/éå ·å½¢è±¡è®¾è®¡\s*$/.test(v)||/éå ·è®¾è®¡\s*$/.test(v)||/\bProp visual design\s*$/i.test(v))},S=k=>{const v=f(k);if(!v)return!1;for(const I of a){const $=da(I);if(new RegExp(`^${$}\\s*éå ·å½¢è±¡è®¾è®¡`).test(v)||new RegExp(`^${$}\\s*éå ·è®¾è®¡`).test(v)||new RegExp(`^${$}\\s*[â\\-]\\s*Prop visual design`,"i").test(v))return!0}return!1};for(let k=0;k<p.length;k++){if(!S(p[k])||!x(p[k]))continue;const v=[];for(let $=k+1;$<p.length;$++){const O=p[$];if(x(O))break;v.push(O)}const I=v.join(` 349`).trim();if(I.length>=8)return I.slice(0,12e3)}return""}function IC(r,t,i){const a=String(i||"").trim();if(!a)return"";const u=String(r||"").trim();if(!u)return`${a} ${t==="CHARACTERS"?"character":t==="SCENES"?"scene":"prop"} notes inferred from BloomBot chat: 350- BloomBot homepage chat is empty. Start a chat to generate richer notes.`;const p=new Set;if(p.add(a),t==="CHARACTERS"){const O=Mt(a);O&&p.add(O);for(const D of Un(a))p.add(D)}const f=[...p].map(O=>O.trim()).filter(Boolean).map(O=>da(O)).join("|");if(!f)return"";const x=t==="CHARACTERS"?"CHAR":t==="SCENES"?"SCENE":"PROP",S=new RegExp(`(?:(${f})|\\[\\[${x}\\s*:\\s*[^\\]]*(${f})[^\\]]*\\]\\])`,"i"),k=u.split(/\n+/).map(O=>O.trim()).filter(Boolean),v=[],I=new Set;for(const O of k){if(!S.test(O))continue;const D=O.replace(/^(?:User|BloomBot)\s*:\s*/i,"").replace(/\s+/g," ").trim();if(!D)continue;const n=D.toLowerCase();if(!I.has(n)&&(I.add(n),v.push(D.length>180?`${D.slice(0,177)}...`:D),v.length>=6))break}return v.length===0?`${a} ${t==="CHARACTERS"?"character":t==="SCENES"?"scene":"prop"} notes inferred from BloomBot chat: 351- No direct mention was found in current homepage chat history yet.`:`${t==="CHARACTERS"?`${a} character notes inferred from BloomBot chat:`:t==="SCENES"?`${a} scene notes inferred from BloomBot chat:`:`${a} prop notes inferred from BloomBot chat:`} 352${v.map(O=>`- ${O}`).join(` 353`)}`.trim()}function PC(r){let t=0;for(let i=0;i<r.length;i+=1)t=(t<<5)-t+r.charCodeAt(i),t|=0;return Math.max(1,Math.abs(t))}function _C(r){if(Array.isArray(r)){const t=r.map(i=>
353String(i||"").trim()).filter(Boolean);return t[t.length-1]||t[0]||""}return String(r||"").trim()}const Uy=un.filter(r=>r.id!=="Custom (Upload Ref)");function ds(r,t){const i=un.find(a=>a.id===r);return i?r==="Custom (Upload Ref)"&&(t!=null&&t.trim())?{id:i.id,label:i.label,presetKeywords:t.trim()}:{id:i.id,label:i.label,presetKeywords:""}:{id:r,label:r,presetKeywords:""}}function BC(r,t){if(!t||typeof t!="object"||Array.isArray(t))return r;const i=t,a=(u,p)=>{const f=typeof p=="string"?p:"";return f.trim().length>=u.trim().length?f:u};return{logline:a(r.logline,i.logline),synopsis:a(r.synopsis,i.synopsis)}}const er=[{id:"geography",label:"Geography & Physics"},{id:"timeline",label:"Timeline & History"},{id:"rules",label:"Rules & Limitations"},{id:"culture",label:"Culture & Daily Life"},{id:"coreConflict",label:"Core Conflict"}];function MC(r,t){if(!t||typeof t!="object"||Array.isArray(t))return r;const i=t,a={...r};for(const u of er){const p=(r[u.id]||"").trim(),f=i[u.id];(typeof f=="string"?f.trim():"").length>=p.length&&(a[u.id]=typeof f=="string"?f:r[u.id])}return a}const Iu=Object.fromEntries(er.map(r=>[r.id,r.label]));function mu(r){if(!r)return null;if(r.type==="story_arc")return{type:"story_arc"};if(r.type==="world_bible"){const t=Iu[r.dimensionId]??r.dimensionId;return{type:"world_bible",dimensionId:r.dimensionId,dimensionLabel:t}}return{type:"episode_outline",episodeIndex:r.episodeIndex}}function fu(r,t,i){return VS({uiPhase:r.storyflowUiPhase,layoutTab:r.storyflowLayoutTab,isBeginnerGuidedMode:i,guidedStep:t})}function LC(r){const t=r.trim(),i=t.match(/(?:^|\n)\s*(?:logline|one[- ]line)\s*:\s*(.+?)(?=\n\s*(?:synopsis|plot)\s*:|$)/is),a=t.match(/(?:^|\n)\s*(?:synopsis|plot\s*overview|story)\s*:\s*([\s\S]+)$/is);if(i&&a)return{logline:i[1].trim(),synopsis:a[1].trim()};const u=t.split(/\n\s*\n/);return u.length>=2?{logline:u[0].replace(/^[-*]\s*/,"").trim(),synopsis:u.slice(1).join(` 354 355`).trim()}:t.length<=280?{logline:t,synopsis:""}:{logline:"",synopsis:t}}function Gr(r){return Math.max(1,Math.min(5,Math.round(r)))}function Wy(r){const t=Gr(r);return`${"â ".repeat(t)}${"â".repeat(5-t)}`}function OC(r){const t=String(r||"");if(!t)return 0;const i=t.match(/(^|\n)\s*(SCENE\s*[:ï¼#-]?\s*\d+|Scene\s*[:ï¼#-]?\s*\d+)/g)||[],a=t.match(/(^|\n)\s*(INT\.|EXT\.)/g)||[],u=t.match(/(^|\n)\s*(?:[-*â¢>]+\s*)?(?:#{1,6}\s*)?(?:\*\*|__)?\s*(SHOT|Shot|é头)\s*[:ï¼#-]?\s*0*\d+\b/g)||[];return i.length+a.length+u.length}function Hy(r){return r.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(a=>a.trim())}function zy(r){const t=r.trim();if(!t.startsWith("|"))return!1;const i=t.replace(/\|/g,"").trim();return i.length>0&&/^[-:\s]+$/.test(i)}function Ky(r){const t=String(r||"");if(!t.trim())return t;const u=t.replace(/```[a-zA-Z0-9_-]*\n([\s\S]*?)```/g,(I,$)=>String($||"").trim()).replace(/\[TEXT_SHOT_LIST_JSON\][\s\S]*?\[\/TEXT_SHOT_LIST_JSON\]/gi,"").replace(/\{[\s\S]*?"tables"\s*:\s*\[[\s\S]*?\][\s\S]*?\}/gi,"").replace(/\{[\s\S]*?"v"\s*:\s*1[\s\S]*?\}/gi,"").split(` 356`),p=[];let f=0;for(;f<u.length;){const I=u[f];if(!(I.trim().startsWith("|")&&I.includes("|"))){p.push(I),f+=1;continue}const O=f;let D=f;for(;D<u.length;){const xe=u[D].trim();if(!(xe.startsWith("|")&&xe.includes("|")))break;D+=1}const n=u.slice(O,D),z=n.findIndex(xe=>!zy(xe));if(z<0){p.push(...n),f=D;continue}const Z=Hy(n[z]).map(xe=>xe.toLowerCase()),Ee=Z.findIndex(xe=>/(shot|é头)/i.test(xe)),Ie=Z.findIndex(xe=>/(visual|ç»é¢|framing|action|description)/i.test(xe)),ne=Z.findIndex(xe=>/(dialogue|对ç½|å°è¯)/i.test(xe));if(Ee<0||Ie<0){p.push(...n),f=D;continue}const Pe=n.filter((xe,ae)=>ae>z&&!zy(xe)&&xe.trim().startsWith("|")&&xe.includes("|"));if(Pe.length===0){p.push(...n),f=D;continue}for(const xe of Pe){const ae=Hy(xe),de=(ae[Ee]||"").replace(/`/g,"").trim(),me=(ae[Ie]||"").replace(/`/g,"").trim(),Te=ne>=0?(ae[ne]||"").replace(/`/g,"").trim():"";if(!de&&!me&&!Te)continue;p.push(de||"SHOT"),p.push("Visual:");const nt=me.split(/<br\s*\/?>/i).map(je=>je.trim()).filter(Boolean);if(nt.length>0)for(const je of nt)p.push(`- ${je}`);else p.push("- (to be filled)");if(Te){p.push("Dialogue:");const je=Te.split(/<br\s*\/?>/i).map(ue=>
356ue.trim()).filter(Boolean);for(const ue of je)p.push(`- ${ue}`)}p.push("")}f=D}const x=p.join(` 357`).replace(/\n{3,}/g,` 358 359`).trim();if(!x)return x;const S=x.split(` 360`),k=S.findIndex(I=>/(äº¤ä»æ ¸å¯¹æ¸ å|delivery footer|æ¬å¿µç±»å|æ°å¢éºå«|å¾ åæ¶éºå«|è¿è´¯æ§è¯´æ|æ¬é(?:å·²)?å ¨é¨å®æ|æ¬éç»æ|you can close this modal and click go to workflow|妿æ¨ç¡®è®¤ç¬¬\d+éå 容æ 误)/i.test(I.trim()));return(k>=0?S.slice(0,k):S).join(` 361`).replace(/\n{3,}/g,` 362 363`).trim()}function qy(r){return yw(r)}function $C(r){const t=String(r.scriptBody||""),i=r.ledger,{t:a}=r,u=t.toLowerCase(),p=OC(t),f=/%%.+?%%/s.test(t),x=(t.match(/@@/g)||[]).length,S=String((i==null?void 0:i.continuityNotes)||"").trim().length,k=String((i==null?void 0:i.hookType)||"").trim().length,v=String((i==null?void 0:i.editorPass)||"").trim().toUpperCase(),I=String((i==null?void 0:i.newSeeds)||"").trim().length,$=String((i==null?void 0:i.pendingPayoffs)||"").trim().length,O=Gr(2+(k>=10?1:0)+(/(cliff|reveal|twist|hook|suspense|æ¬å¿µ)/i.test(String((i==null?void 0:i.hookType)||""))?1:0)+(/(NEXT EPISODE|next episode|to be continued)/i.test(t)?1:0)),D=Gr(2+(p>=2?1:0)+(p>=4?1:0)+(/(but|however|instead|fails|cost|betray|å²çª|代价|å转)/i.test(u)?1:0)),n=Gr(2+(S>=12?1:0)+(S>=40?1:0)+(/(previous|next|canon|world|continuity|åé|ä¸é|ä¸çè§)/i.test(String((i==null?void 0:i.continuityNotes)||""))?1:0)),z=Gr(2+(x>=2?1:0)+(f?1:0)+(/(motivation|goal|trait|backstory|人ç©|卿º|设å®)/i.test(t)?1:0)),Z=Gr(2+(I>0?1:0)+($>0?1:0)+(/(seed|payoff|foreshadow|ä¼ç¬|åæ¶)/i.test(`${(i==null?void 0:i.newSeeds)||""} ${(i==null?void 0:i.pendingPayoffs)||""}`)?1:0)),Ee=v==="PASS"?1:0,Ie=[{key:"hook",label:a("page.storyflow.qualityRadarHookLabel"),stars:Gr(O+Ee*.3),note:O>=4?a("page.storyflow.qualityRadarHookNoteGood"):a("page.storyflow.qualityRadarHookNoteImprove")},{key:"conflict",label:a("page.storyflow.qualityRadarConflictLabel"),stars:Gr(D+Ee*.2),note:D>=4?a("page.storyflow.qualityRadarConflictNoteGood"):a("page.storyflow.qualityRadarConflictNoteImprove")},{key:"continuity",label:a("page.storyflow.qualityRadarContinuityLabel"),stars:Gr(n+Ee*.2),note:n>=4?a("page.storyflow.qualityRadarContinuityNoteGood"):a("page.storyflow.qualityRadarContinuityNoteImprove")},{key:"character",label:a("page.storyflow.qualityRadarCharacterLabel"),stars:Gr(z+Ee*.2),note:z>=4?a("page.storyflow.qualityRadarCharacterNoteGood"):a("page.storyflow.qualityRadarCharacterNoteImprove")},{key:"seedPayoff",label:a("page.storyflow.qualityRadarSeedPayoffLabel"),stars:Gr(Z+Ee*.2),note:Z>=4?a("page.storyflow.qualityRadarSeedPayoffNoteGood"):a("page.storyflow.qualityRadarSeedPayoffNoteImprove")}];return{overallStars:Gr(Ie.reduce((Pe,xe)=>Pe+xe.stars,0)/Math.max(1,Ie.length)),dimensions:Ie}}function FC(r){const t=String(r.detailedScript||"").trim(),i=r.parsed,a=[],u=Math.max(0,Math.round(Number(r.targetShots||0))),p=Math.max(0,Math.round(Number(r.writtenShots||0))),f=i.scriptBody.trim()||t;return f||a.push(r.t("page.storyflow.episodeQaDraftEmpty")),r.descriptiveScriptV1?f&&!sa(f)&&a.push(r.t("page.storyflow.episodeQaDescriptiveIncomplete")):u>0&&p<u&&a.push(r.t("page.storyflow.episodeQaNeedMoreShots",{count:u-p})),{ready:a.length===0,missing:a,radar:$C({scriptBody:i.scriptBody,ledger:i.ledger,t:r.t})}}function zt(r){const t=String(r||"").trim();if(!t)return{scriptBody:"",ledger:null,nextStep:""};const i=t.split(` 364`),a=S=>{const k=i.find(v=>v.toUpperCase().startsWith(`${S}:`));return k?k.slice(S.length+1).trim():""},u={hookType:a("HOOK TYPE"),newSeeds:a("NEW SEEDS"),pendingPayoffs:a("PENDING PAYOFFS"),continuityNotes:a("CONTINUITY NOTES"),editorPass:a("EDITOR PASS"),editorNotes:a("EDITOR NOTES")},p=!!(u.hookType||u.newSeeds||u.pendingPayoffs||u.continuityNotes||u.editorPass||u.editorNotes),f=a("NEXT STEP");return!p&&!f?{scriptBody:t,ledger:null,nextStep:""}:{scriptBody:i.filter(S=>{const k=S.toUpperCase();return!(k.startsWith("HOOK TYPE:")||k.startsWith("NEW SEEDS:")||k.startsWith("PENDING PAYOFFS:")||k.startsWith("CONTINUITY NOTES:")||k.startsWith("EDITOR PASS:")||k.startsWith("EDITOR NOTES:")||k.startsWith("NEXT STEP:")||k.startsWith("[NEXT STEP HINT]")||k.startsWith("OUTPUT WAS TRUNCATED BY LENGTH."))}).join(` 365`).trim(),ledger:p?u:null,nextStep:f}}const DC=/^\s*(?:\|\s*)?(?:[-*â¢>]+\s*)?(?:#{1,6}
365\s*)?(?:\*\*|__)?\s*(?:(?:SHOT|é头)\s*[:ï¼#-]?\s*|Shot\s+)0*(\d+)\b/i;function UC(r){const t=String(r||"");if(!t.trim())return[];const i=[],a=x=>{const S=Number(x);Number.isFinite(S)&&S>0&&S<500&&i.push(S)},u=/\|\s*Shot\s+0*(\d+)\s*\|/gi;let p;for(;(p=u.exec(t))!==null;)a(p[1]);const f=/(?:^|[\r\n])\s*第\s*0*(\d+)\s*é\b/gi;for(;(p=f.exec(t))!==null;)a(p[1]);return[...new Set(i)]}function WC(r){const t=String(r||"");if(!t.trim())return[];const i=[],a=/(^|\n)\s*(?:[-*â¢>]+\s*)?(?:#{1,6}\s*)?(?:\*\*|__)?\s*(?:(?:SHOT|é头)\s*[:ï¼#-]?\s*|Shot\s+)0*(\d+)\b/gi;let u=a.exec(t);for(;u;){const f=Number(u[2]);Number.isFinite(f)&&f>0&&i.push(f),u=a.exec(t)}const p=UC(t);return[...new Set([...i,...p])]}function _l(r){const t=String(r||"");if(!t.trim())return[];const i=t.split(` 366`),a=[],u=new Set,p=f=>{const x=f.trim().toLowerCase();!x||u.has(x)||(u.add(x),a.push(f.trimRight()))};for(const f of i){const x=f.trim();x&&/^(HOOK TYPE:|NEW SEEDS:|PENDING PAYOFFS:|CONTINUITY NOTES:|EDITOR PASS:|EDITOR NOTES:|NEXT STEP:|\[NEXT STEP HINT\]|OUTPUT WAS TRUNCATED BY LENGTH\.)/i.test(x)&&p(x)}return a}function Xh(r){const t=String(r||"");if(!t.trim())return[];const i=t.split(` 367`),a=[];for(let p=0;p<i.length;p+=1){const f=i[p].match(DC);if(!f)continue;const x=Number(f[1]);Number.isFinite(x)&&x>0&&a.push({line:p,shot:x})}if(!a.length)return[];const u=[];for(let p=0;p<a.length;p+=1){const f=a[p].line,x=p+1<a.length?a[p+1].line:i.length,S=i.slice(f,x).join(` 368`).trim();S&&u.push({shot:a[p].shot,block:S})}return u}function Vl(r){const t=String(r||"");if(!t.trim())return[];const i=Xh(t);if(i.length>0){const a=i.filter(({block:p})=>{const f=String(p||""),x=/(^|\n)\s*(Visual|Action|Dialogue|Camera|Environment|Entry|Exit|Sound)\s*:/i.test(f),S=f.split(` 369`).map($=>$.trim()).filter(Boolean),v=(f.match(/\|/g)||[]).length>=2&&f.length>80,I=/%%/.test(f)||/\$\$/.test(f)||/\[\[(SCENE|PROP|CHAR):/i.test(f);return x||S.length>=3||v||I}),u=a.length>0?a:i;return[...new Set(u.map(p=>p.shot))]}return[...new Set(WC(t))]}function Pu(r){return Vl(r).length}function Fn(r){const t=Vl(String(r||"")),i=t.length,a=i>0?Math.max(...t):0;return{count:i,lastMax:a}}function Jh(r){return String(r||"").trim().length>=220}function yu(r){const t=String(r||"");return t.trim()?t.replace(/^\s*EPISODE COMPLETE\.[^\n]*$/gim,"").replace(/^\s*æ¬éç»æ[^\n]*$/gim,"").replace(/^\s*æ¬é(?:å·²)?å ¨é¨å®æ[^\n]*$/gim,"").replace(/\n{3,}/g,` 370 371`).trim():t}function HC(r){const t=String(r||"");return t.trim()?!!(/\[TEXT_SHOT_LIST_JSON\]|\[\/TEXT_SHOT_LIST_JSON\]/i.test(t)||/```(?:json|yaml|yml|xml)?\s*[\s\S]*```/i.test(t)&&/[\{\}\[\]":]/.test(t)||/"tables"\s*:|"v"\s*:\s*1|"rows"\s*:|"shot"\s*:/i.test(t)&&/\{[\s\S]*\}/.test(t)):!1}function zC(r){const t=String(r||"");if(!t.trim())return t;let i=t.search(/\n\*\*F\./i);if(i<0){const a=t.match(/^\*\*F\./im);i=a&&a.index!=null?a.index:-1}return i<0&&(i=t.search(/\nF\.\s*(?:è¿ç»æ§|Continuity)/i)),i<0?t:t.slice(0,i).replace(/\s+$/,"").trimEnd()}function hu(r){const t=String(r||"").trim();if(!t)return!1;const i=zt(t).scriptBody;return!!(Pu(i)>0||yC(t)||/\*\*E\.\s*[^\n]*(åé头姿¬|å§æ¬åé表|åé表|Shot\s*Map)/i.test(t)||/\(Shot Map\)/i.test(t)||/\*\*E\./i.test(t)&&/(^|\n)Shot\s+\d+\s*\|/im.test(t)||/(^|\n)Shot\s+\d+\s*\|/im.test(t)&&t.length>200||Jh(t))}function KC(r,t){const i=String(r||"").trim(),a=String(t||"").trim();if(!a)return i;if(!i)return a;const u=Vl(i),p=Vl(a),f=u.length>0?Math.max(...u):0,x=p.length>0?Math.min(...p):0,S=p.length>0?Math.max(...p):0;if(f<=0)return a;if(p.length===0){const k=zt(i),v=_l(a);return v.length===0?i:[k.scriptBody.trim(),v.join(` 372`)].filter(Boolean).join(` 373 374`).trim()}if(x>f){const k=zt(i),v=zt(a),I=[k.scriptBody.trim(),v.scriptBody.trim()].filter(Boolean).join(` 375 376`).trim(),$=_l(a);return[I,$.join(` 377`)].filter(Boolean).join(` 378 379`).trim()}if(S>f){const k=zt(i),v=zt(a),I=Xh(v.scriptBody).filter(z=>z.shot>f).map(z=>z.block.trim()).filter(Boolean);if(I.length>0){const z=[k.scriptBody.trim(),I.join(` 380 381`)].filter(Boolean).join(` 382 383`).trim(),Z=_l(a);return[z,Z.join(` 384`)].filter(Boolean).join(` 385 386`).trim()}const $=zt(i),O=zt(a),D=[$.scriptBody.trim(),O.scriptBody.trim()].filter(
386Boolean).join(` 387 388`).trim(),n=_l(a);return[D,n.join(` 389`)].filter(Boolean).join(` 390 391`).trim()}return x<=f,i}function qC(r,t){const i=String(r||"");if(!i.trim()||t.length===0)return i;let a=i;const u=[...t].map(p=>String(p||"").trim()).filter(Boolean).sort((p,f)=>f.length-p.length);for(const p of u){const f=da(p);a=a.replace(new RegExp(`(^|\\n)\\s*(?:@@)?(${f})\\s*(说\\s*[:ï¼]|[:ï¼])`,"g"),(x,S,k,v)=>`${S}@@${k}${v}`),a=a.replace(new RegExp(`%%\\s*(?:@@)?(${f})\\s*(说\\s*[:ï¼]|[:ï¼])`,"g"),(x,S,k)=>`%%@@${S}${k}`)}return a}function GC(r,t,i,a,u){var f,x,S;const p=[];p.push(`# ${(r||"").trim()||"STORYFLOW project"}`),p.push(""),p.push("# Story Outline"),p.push(""),p.push("## Logline"),p.push(t.logline.trim()||"(empty)"),p.push(""),p.push("## Synopsis"),p.push(t.synopsis.trim()||"(empty)"),p.push(""),p.push("---"),p.push("# World Bible");for(const k of er)p.push(""),p.push(`## ${k.label}`),p.push((i[k.id]||"").trim()||"(empty)");if(p.push(""),p.push("---"),p.push("# Character Profiles"),u.length===0)p.push("(empty)");else for(const k of u)p.push(""),p.push(`## ${k.name||"(Unnamed character)"}`),p.push((k.backstory||"").trim()||"(empty)");p.push(""),p.push("---"),p.push("# Episode List");for(let k=0;k<a.length;k++){const v=a[k];p.push(""),p.push(`## Ep. ${String(k+1).padStart(2,"0")}: ${v.title}`),(f=v.characterRefs)!=null&&f.length&&(p.push(""),p.push("**Characters:** "+v.characterRefs.map(I=>I.name).join(", "))),(x=v.scenes)!=null&&x.length&&p.push("**Scenes:** "+v.scenes.join(", ")),(S=v.props)!=null&&S.length&&p.push("**Props:** "+v.props.join(", ")),p.push(""),p.push(v.summary.trim()||"(no summary)"),p.push(""),p.push("### Detailed script"),p.push(Rt(v).trim()||"(no detailed script)")}return p.join(` 392`)}function YC(r){return String(r||"").replace(/\r\n/g,` 393`).replace(/^---$/gm,` 394`).replace(/^#{1,6}\s*/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\n{3,}/g,` 395 396`).trim()}const nn=24,Dn=12;function Gy({className:r}){return s.jsxs("svg",{className:r,viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:[s.jsx("path",{d:"M7.75 2.25h4.5M10 2.25V1",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round"}),s.jsx("rect",{x:"4.75",y:"4.25",width:"10.5",height:"8.25",rx:"2.6",stroke:"currentColor",strokeWidth:"1.1"}
396),s.jsx("circle",{cx:"8.1",cy:"7.85",r:"0.8",fill:"currentColor"}),s.jsx("circle",{cx:"11.9",cy:"7.85",r:"0.8",fill:"currentColor"}),s.jsx("path",{d:"M8.15 10.35h3.7",stroke:"currentColor",strokeWidth:"0.85",strokeLinecap:"round"}),s.jsx("rect",{x:"6.35",y:"12.85",width:"7.3",height:"3.35",rx:"1.05",stroke:"currentColor",strokeWidth:"1"})]})}function Yy(r,t,i,a){const u=r.left+r.width/2,p=r.top+r.height/2,f=t.left+t.width/2,x=t.top+t.height/2,S=u-nn/2,k=p-nn/2,v=f-nn/2,I=x-nn/2,$=v-S,O=I-k,D=Math.min(100,Math.max(48,Math.hypot($,O)*.38)),n=$*.52,z=O*.52-D,Z=-$*.52,Ee=-O*.52+D,Ie=document.createElement("div");Ie.setAttribute("data-bloom-fly","1");const ne=i==="forward"?S:v,Pe=i==="forward"?k:I;Ie.style.cssText=`position:fixed;left:${ne}px;top:${Pe}px;width:${nn}px;height:${nn}px;z-index:99999;pointer-events:none;will-change:transform,filter`;const xe=document.createElement("img");xe.src=Jy,xe.alt="",xe.width=nn,xe.height=nn,xe.style.cssText="width:100%;height:100%;object-fit:contain;display:block",Ie.appendChild(xe),document.body.appendChild(Ie);const ae=i==="forward"?[{transform:"translate(0,0) scale(1)",filter:"blur(0px)"},{transform:`translate(${n}px,${z}px) scale(1.22)`,filter:"blur(2px)"},{transform:`translate(${$}px,${O}px) scale(1)`,filter:"blur(0px)"}]:[{transform:"translate(0,0) scale(1)",filter:"blur(0px)"},{transform:`translate(${Z}px,${Ee}px) scale(1.2)`,filter:"blur(1.5px)"},{transform:`translate(${-$}px,${-O}px) scale(1)`,filter:"blur(0px)"}],de=Ie.animate(ae,{duration:560,easing:"cubic-bezier(0.33, 1, 0.52, 1)",fill:"forwards"}),me=()=>{try{de.cancel()}catch{}Ie.remove()};return de.onfinish=()=>{me(),a()},me}const VC=["outline","world_bible","assets","episode_board"],XC=["guided_enter","guided_step_advanced","guided_step_prompt","guided_mode_toggle","guided_create_workflow"],JC=1,Vy=1;function Bl(...r){const t=new Set,i=[];for(const a of r)for(const u of a){const p=String(u||"").trim();if(!p)continue;const f=p.toLowerCase();t.has(f)||(t.add(f),i.push(p))}return i.sort((a,u)=>a.localeCompare(u))}function QC(r){return r.storyArcReady?r.worldBibleReady?r.episodeListReady?"episode_board":"assets":"world_bible":"outline"}function Rt(r){return r?String(r.detailedScript||"").trim()?String(r.detailedScript||""):String(r.detailedScriptBloomDraft||"").trim()?String(r.detailedScriptBloomDraft||""):"":""}const ZC=48;function e1(r){return(r.summary||"").trim().length>=ZC}function t1(r){const t=String(r||"");if(!t.trim())return[];const i=new Map,a=t.split(/\r?\n/);for(const u of a){const p=u.trim();if(!p)continue;const f=p.match(/^\s*(?:E|EP(?:ISODE)?\.?\s*|Episode\s*|第\s*)0*(\d{1,3})(?:\s*[éè¯å])?\s*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|\s*(.+)\s*$/i)||p.match(/^\s*(?:Episode|EP|第)\s*0*(\d{1,3})(?:\s*[éè¯å])?\s*[:ï¼-]\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|\s*(.+)\s*$/i);if(f){const S=Number(f[1]),k=String(f[2]||"").trim(),v=String(f[3]||"").trim(),I=String(f[4]||"").trim();if(!Number.isFinite(S)||S<1||S>200||!I)continue;const $=[k?`Role: ${k}`:"",v?`Hook: ${v}`:"",I].filter(Boolean).join(" · ");i.set(S,$);continue}const x=p.match(/^(?:E|EP(?:ISODE)?|第)\s*0*(\d{1,3})(?:\s*[éè¯å])?\s*[:ï¼\-]\s*(.+)$/i);if(x){const S=Number(x[1]),k=String(x[2]||"").trim();if(!Number.isFinite(S)||S<1||S>200||!k)continue;i.set(S,k)}}return[...i.entries()].sort((u,p)=>u[0]-p[0]).map(([u,p])=>({episodeNo:u,summary:p}))}const r1=1,s1=[],gu="bloombot-cb-skill-text-table",Zi=`Visual writing requirements for each shot: 397- Framing & composition: specify shot size (CU/MS/LS/ELS), composition position, camera angle, and first visual focus. 398- Action & state: describe precise action/state with clear start/end beats, using strong verbs. 399- Camera movement: one concise sentence only (pan/tilt/push/pull/track/follow), high-level direction for later motion execution. 400- Environment & atmosphere: lighting, art/set details, weather/particles/fx, and mood tone. 401- Entry & exit: specify in/out actions or transition cue when relevant (enter frame, exit frame, cut, fade). 402- Output must be plain text only. Do NOT use markdown tables (|) and do NOT wrap output in code fences. 403- Character naming: keep canonical names; dialogue speaker names must use @@ prefix. 404 405Shot block format (strict): 406SHOT XX 407Visual: 408- Framing & Composition (exactly 1 sentence): ... 409- Action & State (1-2 sentences): ... 410- Camera Movement (exactly 1 sentence): ... 411- Environment & Atmosphere (exactly 1 sentence; max 2 only for key shots): ... 412Dialogue/SFX (optional): ... 413Entry/Exit (optional, exactly 1 sentence when used): ... 414`;function n1(r){let t=0;for(let i=0;i<r.length;i+=1)t=Math.imul(31,t)+r.charCodeAt(i)>>>0;return t%9e5+1}const Z1=({setPhase:r,greenlightProjectId:t=null,userDisplayName:i,onCreateWorkflowFromEpisode:a,onOpenAssetLibrary:u,onGreenlightCloudPersist:p,canonicalProjectName:f,onGreenlightProjectTitleChange:x,onRegisterHeaderSave:S,onRegisterHeaderExport:k,onStoryflowHeaderSlotChange:v,onStoryflowSetupClose:I,onStoryflowSetupComplete:$,userPlan:O=null,userPlanPrepaidUntil:D=null})=>{var Um,Wm,Hm,zm,Km,qm,Gm,Ym,Vm,Xm,Jm,Qm,Zm,ef;const{t:n,locale:z}=sh();c.useMemo(()=>[{id:"hybrid",label:n("page.storyflow.generationConceptDesign"),hint:n("page.storyflow.generationConceptDesignHint")},{id:"banana2_only",label:n("page.storyflow.workspaceModalImageDesignTitle"),hint:n("page.storyflow.generationReferenceMatchHint")}],[n]),c.useMemo(()=>[{id:"consistent",label:n("page.storyflow.styleConsistent")},{id:"reference_led",label:n("page.storyflow.styleReferenceLed")},{id:"exploratory",label:n("page.storyflow.styleExploratory")}
414],[n]),c.useEffect(()=>{const e=()=>{oC().catch(()=>{})};typeof window<"u"&&typeof window.requestIdleCallback=="function"?window.requestIdleCallback(e,{timeout:3e3}):window.setTimeout(e,1200)},[]);const Z=i&&i.trim()||"Tom",Ee=nb(O,D),Ie=c.useCallback((e,o)=>{const l=String(e||"").trim();if(!l)return n("page.storyflow.episodeTitleWithNumber",{number:o});const d=l.match(/^Episode\s*(\d+)$/i);if(d){const y=Number(d[1]),h=Number.isFinite(y)&&y>0?y:o;return n("page.storyflow.episodeTitleWithNumber",{number:h})}const m=l.match(/^第\s*(\d+)\s*é\s*$/);if(m){const y=Number(m[1]),h=Number.isFinite(y)&&y>0?y:o;return n("page.storyflow.episodeTitleWithNumber",{number:h})}return l},[n]),ne=c.useCallback(e=>n("page.storyflow.episodeBadgeWithNumber",{number:e}),[n]),Pe=c.useCallback(e=>n(e==="geography"?"page.storyflow.worldDimensionGeography":e==="timeline"?"page.storyflow.worldDimensionTimeline":e==="rules"?"page.storyflow.worldDimensionRules":e==="culture"?"page.storyflow.worldDimensionCulture":"page.storyflow.worldDimensionCoreConflict"),[n]),xe=c.useCallback(e=>n(e==="geography"?"page.storyflow.worldDimensionGeographyPlaceholder":e==="timeline"?"page.storyflow.worldDimensionTimelinePlaceholder":e==="rules"?"page.storyflow.worldDimensionRulesPlaceholder":e==="culture"?"page.storyflow.worldDimensionCulturePlaceholder":"page.storyflow.worldDimensionCoreConflictPlaceholder"),[n]);c.useCallback(e=>n(e==="outline"?"page.storyflow.storyOutlineStarterPrompt":e==="world_bible"?"page.storyflow.worldBibleStarterPrompt":e==="episode_board"?"page.storyflow.optimizeSeasonPrompt":"page.storyflow.assetsStarterPrompt"),[n]);const ae=c.useMemo(()=>Hb(t,f),[t,f]),[de,me]=c.useState(0),Te=c.useRef(!1),nt=c.useRef(-1);c.useEffect(()=>{if(typeof window>"u")return;const e=typeof t=="string"?t.trim():"";if(!e)return;const o=l=>{const d=l.detail;(d==null?void 0:d.projectId)===e&&(Te.current=!1,ao.current=!1,$a.current=!1,me(m=>m+1))};return window.addEventListener(Sf,o),()=>window.removeEventListener(Sf,o)},[t]),c.useEffect(()=>{const e=typeof t=="string"?t.trim():"";if(!e){cr([]);return}cr(Ll(e))},[t]);const[je,ue]=c.useState("outline"),[ve,be]=c.useState(_r),[tt,mr]=c.useState(null),[ye]=c.useState(()=>Ak(ob())),[rr,Lt]=c.useState(null),[Ls,jt]=c.useState(!1),[Ot,it]=c.useState(!1),[qe,$t]=c.useState([]),[wt,Mr]=c.useState([]),[At,fe]=c.useState({}),Re=c.useMemo(()=>ye?/^ep:\d+:seq:\d+$/.test(String(ve||"").trim())?"episode_unit":"foundation":bs(je),[ye,ve,je]),J=c.useMemo(()=>Re!=="episode_unit"?qe:ve?At[ve]??Qi:wt,[Re,ve,At,wt,qe]),ie=c.useCallback(e=>{if(Re!=="episode_unit"){$t(e);return}if(ve){const o=ve;fe(l=>{const d=l[o]??Qi,m=typeof e=="function"?e(d):e;return{...l,[o]:m}});return}Mr(e)},[Re,ve]),[dt,Ft]=c.useState(!1),[ft,fr]=c.useState(null),[Lr,cr]=c.useState([]),ps=c.useRef(null);ps.current=ft;const It=c.useRef(null),ua=c.useRef(null);c.useEffect(()=>{if(!dt)return;const e=l=>{var m,y;const d=l.target;d instanceof Node&&((m=It.current)!=null&&m.contains(d)||(y=ua.current)!=null&&y.contains(d)||Ft(!1))},o=l=>{l.key==="Escape"&&Ft(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",o)}},[dt]);const Ye=c.useMemo(()=>zv(J,z),[J,z]),[pa,pn]=c.useState(!1),[mn,fn]=c.useState(Pl),[Zo,ei]=c.useState(null),Cs=c.useRef(null),[ti,Gn]=c.useState(()=>new Set),[Ku,Yn]=c.useState(!1),Os=c.useRef(null),ma=c.useRef(null),fa=c.useRef(null),rc=c.useRef(null),sc=c.useRef(null),nc=c.useRef(null),[Le,$s]=c.useState(()=>{var e;return((e=un[0])==null?void 0:e.id)??"Cinematic"}),[Oe,Or]=c.useState(""),[sr,ri]=c.useState(null),[yr,Er]=c.useState(!1),[si,Tr]=c.useState(!1),[St,hr]=c.useState(null),[Ns,ni]=c.useState(!1),[oc,N]=c.useState(null),K=c.useRef(null),[ee,re]=c.useState(!1),He=c.useRef(!1),yt=c.useRef(!1),ht=c.useRef(!1),[ze,Fs]=c.useState(!1),[Vn,ya]=c.useState(""),[qu,Qh]=c.useState(""),[ha,Ds]=c.useState(null),ga=c.useRef(null),[U,Rr]=c.useState({logline:"",synopsis:""}),Yr=c.useRef({}),ms=(e,o)=>{Yr.current={...Yr.current,[e]:o}},nr=e=>ms(e,"user"),[oe,Xn]=c.useState(null),[Vr,xa]=c.useState("edit"),[ba,wa]=c.useState("synced"),Gu=c.useRef(0),[Sa,Jn]=c.useState(null),[Zh,ka]=c.useState(!1),[pe,Us]=c.useState({geography:"",timeline:"",rules:"",culture:"",coreConflict:""}),[o1,i1]=c.useState(null),[P,Fe]=c.useState(()=>
414s1),[Kt,$r]=c.useState(0),[_e,oi]=c.useState(null),[at,yn]=c.useState({}),Yu=_e??Kt??0,va=c.useMemo(()=>at[Yu]??Qi,[at,Yu]),Ca=c.useRef(Qi),Na=c.useRef(null),[ii,Vu]=c.useState(!1),[hn,fs]=c.useState("idle"),[Pt,or]=c.useState(null),[ic,qt]=c.useState(null),Xu=c.useRef(null),Ju=c.useRef(null),ac=c.useRef(null),ir=c.useRef(null),lc=c.useRef(null),cc=320,dc=240,Qu=520,Zu=400,ep=Math.round(Zu*1.7),tp=28,rp=1200,eg=40,Qn=c.useCallback(()=>typeof window>"u"?Math.min(rp,Qu*2):Math.min(rp,Math.max(cc,window.innerWidth-eg)),[cc]),[Fr,Zn]=c.useState({left:24,top:100,width:Qu,height:Zu}),[sp,np]=c.useState(!1),[op,ip]=c.useState(!1),ai=c.useRef({x:0,y:0,left:0,top:0}),li=c.useRef({x:0,y:0,w:0,h:0}),ap=c.useRef(null),[lp,tg]=c.useState(0),eo=c.useCallback(()=>typeof window>"u"?ep:Math.max(dc,Math.floor(window.innerHeight-tp*2)),[ep,dc,tp]),Ea=c.useCallback(()=>{tg(e=>e+1)},[]);c.useEffect(()=>{if(lp<=0)return;const e=ap.current;if(!e||typeof e.animate!="function")return;const o=e.animate([{opacity:1},{opacity:.42,offset:.25},{opacity:1,offset:.5},{opacity:.42,offset:.75},{opacity:1}],{duration:2600,easing:"ease-in-out",fill:"both"});return()=>o.cancel()},[lp]),c.useEffect(()=>{if(!oe)return;const e=l=>{if(sp){const d=l.clientX-ai.current.x,m=l.clientY-ai.current.y;Zn(y=>({...y,left:Math.max(0,ai.current.left+d),top:Math.max(0,ai.current.top+m)}))}if(op){const d=l.clientX-li.current.x,m=l.clientY-li.current.y;Zn(y=>({...y,width:Math.max(cc,li.current.w+d),height:Math.max(dc,li.current.h+m)}))}},o=()=>{np(!1),ip(!1)};return window.addEventListener("pointermove",e),window.addEventListener("pointerup",o),window.addEventListener("pointerleave",o),()=>{window.removeEventListener("pointermove",e),window.removeEventListener("pointerup",o),window.removeEventListener("pointerleave",o)}},[oe,sp,op]);const ci=c.useCallback(()=>{const e=lc.current;if(!e)return;const o=e.getBoundingClientRect();Zn(l=>{const d=l.width,m=l.height;let y=o.left+(o.width-d)/2,h=o.top+(o.height-m)/2;const b=8;return y=Math.max(b,Math.min(y,window.innerWidth-d-b)),h=Math.max(b,Math.min(h,window.innerHeight-m-b)),{...l,left:y,top:h}})},[]);c.useLayoutEffect(()=>{if(!oe)return;ci();const e=requestAnimationFrame(()=>ci());return()=>cancelAnimationFrame(e)},[oe,ci]),c.useEffect(()=>{if(oe!=="episode")return;const e=()=>{const o=eo(),l=Qn();Zn(d=>{const m=Math.min(d.width,l),y=o;return d.width===m&&d.height===y?d:{...d,width:m,height:y}})};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[oe,eo,Qn]),c.useEffect(()=>{if(typeof window>"u")return;const e=window.matchMedia("(min-width: 1024px)"),o=()=>yg(e.matches);return o(),e.addEventListener("change",o),()=>e.removeEventListener("change",o)},[]),c.useEffect(()=>{if(!oe)return;const e=lc.current,o=()=>ci();window.addEventListener("resize",o);let l;return e&&typeof ResizeObserver<"u"&&(l=new ResizeObserver(o),l.observe(e)),()=>{window.removeEventListener("resize",o),l==null||l.disconnect()}},[oe,ci]);const[l1,gn]=c.useState(!0),[rg,Ta]=c.useState(!1),[Wt,uc]=c.useState(!0),[Gt,Ws]=c.useState("outline"),[Q,pc]=c.useState(null),[ge,Xr]=c.useState("Untitled project"),[cp,Ra]=c.useState(!1),[c1,mc]=c.useState(!1),[ja,sg]=c.useState("episodes"),[Be,Aa]=c.useState("workspace"),[rt,di]=c.useState(""),[Yt,to]=c.useState("");c.useEffect(()=>{pa&&fn(e=>{const o=rt==="custom"?Yt:"";return e.dramaCategoryId===rt&&e.dramaCustomNote===o?e:{...e,dramaCategoryId:rt,dramaCustomNote:o}})},[rt,Yt,pa]);const[Ce,Nt]=c.useState(jl),[ke,Jr]=c.useState(!1),[fc,Dt]=c.useState(null),[te,ar]=c.useState(Ji),[yc,gr]=c.useState(null),[Hs,dp]=c.useState("fill_empty"),[ui,up]=c.useState(1),[pi,pp]=c.useState(20),[Dr,kt]=c.useState({episodeCount:!1,episodeDuration:!1}),[we,xn]=c.useState([]),[hc,mp]=c.useState([]),[gc,fp]=c.useState([]),[ro,zs]=c.useState(null),[Ks,Ia]=c.useState(null),[xc,Pa]=c.useState(null),[gt,Ht]=c.useState("outline"),[Qr,bc]=c.useState(!1),[yp,ng]=c.useState(!1),[hp,gp]=c.useState("16:9"),[xp,bp]=c.useState([]),wc=c.useCallback(e=>n(e?"page.storyflow.tabEpisodesFilm":"page.storyflow.tabEpisodesSeries"),[n]),Es=c.useMemo(()=>wc(ke),[wc,ke]),wp=c.useMemo(()=>Be!=="workspace"?"":n(Re!=="episode_unit"?"page.storyflow.bloomBotModeFoundation":ke?"page.storyflow.bloomBotModeEpisodeUnitFilm":"page.storyflow.bloomBotModeEpisodeUnitSeries"),[Re,ke,Be,n]),og=c.useMemo(()=>n(Be==="workspace"?Re==="episode_unit"?"page.storyflow.bloomBotComposerEpisodeUnit":"page.storyflow.bloomBotComposerFoundation":"page.bloomBotCard.composerShellPlaceholder"),[Re,Be,n]),Sp=c.useMemo(()=>iy(P,{standaloneFilmMode:ke,plannedEpisodeCount:Ce}),[P,ke,Ce]),ig=c.useMemo(()=>Be==="workspace"&&Re==="episode_unit"?ve&&Sp?n(ke?"page.storyflow.welcomeCardBodyEpisodeUnitScriptFilm":"page.storyflow.welcomeCardBodyEpisodeUnitScriptSeries",{episodesTab:Es}):n(ke?"page.storyflow.welcomeCardBodyEpisodeUnitBreakdownFilm":"page.storyflow.welcomeCardBodyEpisodeUnitBreakdownSeries",{episodesTab:Es}):n("page.storyflow.welcomeCardBody"),[Be,Re,ve,Sp,ke,Es,n]),[kp,so]=c.useState(()=>new Set),xr=c.useRef(!1),[Sc,ag]=c.useState(()=>Ty().leftPx),[_a,lg]=c.useState(()=>Ty().rightPx),mi=c.useRef(Sc),fi=c.useRef(_a);mi.current=Sc,fi.current=_a;const kc=c.useRef(null),[d1,u1]=c.useState(!1),[Vt,vp]=c.useState(null),[yi,hi]=c.useState(null),[bn,Ba]=c.useState(""),[cg,Cp]=c.useState(!1),[Zr,Np]=c.useState(null),[es,Ep]=c.useState(!1),[wn,Tp]=c.useState(!1),no=c.useRef({outline:0,world:0}),oo=c.useRef({outline:!1,world:!1}),ts=c.useRef({outline:null,world:null}),[Rp,dg]=c.useState(0),vc=c.useCallback(()=>{Dt(e=>{if(e===null)return null;const o=e.trim(),l=o===""?dn:Math.floor(Number(o));return Nt(sn(l)),kt(d=>({...d,episodeCount:!0})),null}),window.setTimeout(()=>Ze.current({silent:!0}),0)},[]),Cc=c.useCallback(e=>{if(e!==""&&!/^\d*$/.test(e))return;const o=e.slice(0,3);Dt(o),o!==""&&Number(o)>pr&&(Nt(pr),Dt(String(pr)),kt(l=>({...l,episodeCount:!0})))},[]),Nc=c.useCallback(()=>{Dt(e=>e??String(Ce))},[Ce]),Ec=c.useCallback(()=>{gr(e=>{if(e===null)return null;if(!ke)return ar(Br),kt(l=>({...l,episodeDuration:!0})),null;const o=lu(e,!0);return o!=null&&(ar(cu(o,!0)),kt(l=>({...l,episodeDuration:!0}))),null})},[ke]),Tc=c.useCallback(e=>{ke&&(e!==""&&!/^\d*$/.test(e)||gr(e.slice(0,3)))},[ke]),Rc=c.useCallback(()=>{ke&&gr(e=>e??String(Al(te,!0)))},[te,ke]);c.useEffect(()=>{ke||(ar(e=>e===Br?e:Br),gr(null))},[ke]);const Ma=c.useCallback((e,o)=>{if(typeof window>"u")return;const l=ts.current[e];l!=null&&window.clearTimeout(l),ts.current[e]=window.setTimeout(()=>{ts.current[e]=null,dg(d=>d+1)},Math.max(1e3,o))},[]);c.useEffect(()=>()=>{if(typeof window>"u")return;const e=ts.current.outline,o=ts.current.world;e!=null&&window.clearTimeout(e),o!=null&&window.clearTimeout(o)},[]);const[La,jp]=c.useState(!1),[Oa,jc]=c.useState(af),[Ur,Ap]=c.useState(!1),[Ts,Ip]=c.useState(!1),[Pp,_p]=c.useState(!1),[Bp,Ac]=c.useState(0),[p1,io]=c.useState(""),$a=c.useRef(!1),ao=c.useRef(!1);c.useEffect(()=>{let e=!1;return(async()=>{try{const o=await lf({force:!0});e||jc(o)}catch{e||jc(af())}})(),()=>{e=!0}},[]),c.useEffect(()=>{if(!La)return;let e=!1;return(async()=>{const o=await lf({force:!0});e||jc(o)})(),()=>{e=!0}},[La]),c.useEffect(()=>{Oa&&zb(100)},[Oa]);const Ze=c.useRef(()=>!0),dr=c.useMemo(()=>{const e=J.filter(o=>o.role==="user"||o.role==="assistant").map(o=>`${o.role==="assistant"?"BloomBot":"User"}: ${String(o.text||"").trim()}`).filter(o=>o.length>0);return e.length===0?"":e.slice(-60).join(` 415`).slice(0,6e3)},[J]);c.useEffect(()=>{wi.current=P},[P]),c.useEffect(()=>{Ca.current=at[_e??Kt??0]??Qi},[at,_e,Kt]),c.useEffect(()=>{yo.current=ze,Ga.current=ze?Ga.current??Date.now():null},[ze]),c.useEffect(()=>{He.current=ee},[ee]);const lo=c.useMemo(()=>Wo(dr,"CHAR"),[dr]),co=c.useMemo(()=>Wo(dr,"SCENE"),[dr]),uo=c.useMemo(()=>Wo(dr,"PROP"),[dr]);c.useEffect(()=>{Fe(e=>{let o=!1;const l=e.map(d=>{if(!d.characterRefs||d.characterRefs.length===0)return d;const m=d.characterRefs.map(y=>{const h=Mt(String(y.name||""));return h&&h!==y.name?(o=!0,{...y,name:h}):y});return o?{...d,characterRefs:m}:d});return o?l:e})},[]);const[st,rs]=c.useState({}
415),[E,Mp]=c.useState(null),[L,lr]=c.useState({description:"",imagePrompt:"",imagePromptDirty:!1,conceptUrl:"",conceptRefImage:"",designUrl:"",generationPath:"hybrid",styleStrategy:"reference_led",characterStyleId:"",characterStyleCustomPrompt:"",imageModelId:Jo,approvedGender:"neutral",characterConfirmed:!1}),[m1,Lp]=c.useState(!1),[f1,Fa]=c.useState(!1),[Ic,Pc]=c.useState(!1),[_c,Bc]=c.useState(!1),[ug,Da]=c.useState(""),[pg,gi]=c.useState(""),[Op,Ua]=c.useState(""),[po,Wa]=c.useState(""),[Sn,qs]=c.useState(""),mo=c.useRef({home:{targetText:"",displayedText:"",timerId:null},episode:{targetText:"",displayedText:"",timerId:null}}),[mg,fg]=c.useState(0),[fo,Ha]=c.useState(!1),[Mc,za]=c.useState(!0),[Ka,Lc]=c.useState("write"),[xi,yg]=c.useState(!1),[Oc,$p]=c.useState(!1),Fp=c.useRef(-1),$c=c.useRef(!1),[xt,qa]=c.useState(!1),bi=ee||ze,Gs=c.useRef(!1),yo=c.useRef(!1),Ga=c.useRef(null),ys=c.useRef(!1),Wr=c.useCallback(e=>{yo.current=e,Fs(e)},[]),hg=c.useRef(!1),wi=c.useRef(P),ur=c.useRef({episodeIndex:-1,written:0,target:0});c.useEffect(()=>{hg.current=xt},[xt]);const ut=c.useRef({concept:null,design:null}),Ya=c.useRef(!1),Va=c.useRef(!1),Dp=2,Si=c.useRef(0),ki=c.useRef(0),pt=c.useRef({key:"",conceptPrompt:"",designPrompt:""});c.useRef(null),c.useRef(null);const gg=c.useRef(null),xg=c.useRef(null),[bg,kn]=c.useState(!1),[wg,ho]=c.useState(null),[Fc,vi]=c.useState("concept"),[Sg,Ci]=c.useState([]),[Ni,Ei]=c.useState(!1),[kg,Xa]=c.useState(!1),[Dc,Ja]=c.useState(!1),[vg,go]=c.useState(!1),Ve=c.useCallback((e,o,l)=>{if(e==="CHARACTERS"&&o)return`c:${o}`;const d=encodeURIComponent(l);return e==="SCENES"?`s:${d}`:`p:${d}`},[]);c.useCallback((e,o=2e6)=>new Promise((l,d)=>{if(e.size>o){d(new Error("Image is too large. Use a file under 2 MB."));return}const m=new FileReader;m.onload=()=>l(String(m.result||"")),m.onerror=()=>d(new Error("Could not read file.")),m.readAsDataURL(e)}),[]);const Rs=c.useMemo(()=>{const e=J.filter(l=>l.role==="user"||l.role==="assistant").map(l=>`${l.role==="assistant"?"BloomBot":"User"}: ${String(l.text||"").trim()}`).filter(l=>l.length>0);if(e.length===0)return"";const o=e.join(` 416`);return o.length<=12e4?o:`${o.slice(0,6e4)} 417...(middle omitted for length)... 418${o.slice(-6e4)}`},[J]),Ys=c.useMemo(()=>{const e=ds(Le,Oe),o=e.presetKeywords?`Series visual style (${e.label}): ${e.presetKeywords}`:`Series visual style: ${e.label}`,l=er.map(d=>`${d.label}: ${(pe[d.id]||"").trim()}`).join(` 419`);return`${o} 420Series title: ${(ge||"").trim()} 421Logline: ${(U.logline||"").trim()} 422Synopsis: ${(U.synopsis||"").trim()} 423${l}`.trim()},[ge,U.logline,U.synopsis,pe,Le,Oe]),ss=c.useMemo(()=>{const e=String(Le||"").trim();return!e||e==="Custom (Upload Ref)"?lC:e},[Le]),Ti=c.useMemo(()=>Kb(ss),[ss]),Hr=c.useMemo(()=>Sv(L.imageModelId),[L.imageModelId]);c.useMemo(()=>bu(Hr).costPerImage,[Hr]),c.useMemo(()=>bu("google/gemini-3.1-flash-image-preview").costPerImage,[]),c.useEffect(()=>()=>{ut.current.concept!=null&&(window.clearTimeout(ut.current.concept),ut.current.concept=null),ut.current.design!=null&&(window.clearTimeout(ut.current.design),ut.current.design=null)},[]),c.useMemo(()=>P.map((e,o)=>({episodeIndex:o+1,title:e.title,summary:e.summary})),[P]);const vn=c.useMemo(()=>qf({storyOutline:U,worldBible:pe,seriesTitle:ge,plannedEpisodeCount:Ce,dramaCategoryId:rt,dramaCustomNote:Yt,seriesBibleCharacters:we,styleLocked:yr}),[U,pe,ge,Ce,rt,Yt,we,yr]),Se=c.useMemo(()=>{const e=Ho.every(w=>String(pe[w]||"").trim().length>0),o=!!rt&&(rt!=="custom"||(Yt||"").trim().length>0),l=!ws(ge),d=cf({standaloneFilmMode:ke,plannedEpisodeCount:Ce,defaultPlannedEpisodeCount:jl,episodeCountAck:Dr.episodeCount}),m=df({standaloneFilmMode:ke,episodeDurationSeconds:te,episodeDurationAck:Dr.episodeDuration,normalizeDuration:w=>We(w,ke)}),y=vn.titleReady&&l,h=vn.episodePlanReady&&d&&m,b=vn.storyArcReady&&e&&vn.charactersReady&&y&&h&&o&&vn.styleLocked;return{...vn,worldBibleReady:e,dramaReady:o,titleReady:y,episodePlanReady:h,allFoundationReady:b}},[ge,Ce,te,Dr,vn,pe,rt,Yt]);c.useMemo(()=>{if(Be!=="immersive")return"";const e=Se;return e.styleLocked?e.dramaReady?e.storyArcReady?e.titleReady?e.worldBibleReady?e.charactersReady?e.episodePlanReady?"":ke?"Full film runtime is set at project setup â adjust in chat only if you want a different length.":"Confirm planned episode count and per-episode duration (chat or panel below).":"Add at least one character with a backstory (via the assistant or paste).":"Fill every world bible section with the assistant.":"Set a real series title (project header or ask the assistant).":"Build the story outline (logline + synopsis) with the assistant.":"Choose a drama category (or Custom with a short note).":"Pick a visual style below â it stays locked until you tap Change."},[Be,Se]),c.useMemo(()=>{const e=Se.storyArcReady&&Se.worldBibleReady&&Se.titleReady,o=+!!Vt+ +!!Zr;return e?es||wn?{icon:"sync",iconClass:"animate-spin text-primary",tooltip:"Posters are generating in the background."}:o===2?{icon:"cloud_done",iconClass:"text-primary",tooltip:"Both posters are ready and synced."}:o===1?{icon:"cloud_sync",iconClass:"text-primary",tooltip:"One poster is ready. The other will c
423ontinue in background."}:{icon:"cloud_upload",iconClass:"text-slate-400",tooltip:"Posters will retry automatically in the background."}:{icon:"hourglass_top",iconClass:"text-slate-400",tooltip:"Posters start automatically after Story outline, World bible, and Title are ready."}},[Se.storyArcReady,Se.worldBibleReady,Se.titleReady,Vt,Zr,es,wn]);const Up=c.useMemo(()=>{var m;const e=new Map,o=new Set,l=new Map,d=y=>{const h=Un(y);if(h.length===0)return;const b=h[0],w=b.toLowerCase();o.add(b);const g=l.get(w)||[],A=new Set([...g,...h]);l.set(w,[...A])};for(const y of we)d(String(y.name||"").trim());for(const y of((m=Q==null?void 0:Q.assets)==null?void 0:m.characters)??[])d(String(y||"").trim());for(const y of(Q==null?void 0:Q.characterShare)??[])d(String((y==null?void 0:y.name)||"").trim());for(const y of P){const h=new Map,b=String(y.title||"");for(const C of y.characterRefs||[]){const R=Un(String((C==null?void 0:C.name)||""));if(!R.length)continue;const T=R[0],M=T.toLowerCase();h.has(M)||h.set(M,T)}const w=String(y.summary||""),g=TC(y);for(const C of nh(g)){const R=Un(C);if(!R.length)continue;const T=R[0],M=T.toLowerCase();h.has(M)||h.set(M,T)}const A=w.toLowerCase(),j=b.toLowerCase();for(const C of we){const R=Un(String(C.name||"").trim());if(!R.length)continue;const T=R[0];if(!R.some(q=>A.includes(q.toLowerCase())||j.includes(q.toLowerCase())))continue;const W=T.toLowerCase();h.has(W)||h.set(W,T)}for(const C of o){const R=String(C||"").trim();if(!R)continue;const T=R.toLowerCase();(l.get(T)||[R]).some(q=>A.includes(q.toLowerCase())||j.includes(q.toLowerCase()))&&(h.has(T)||h.set(T,R))}const B=["é¦é¢","éé¿","å士","å°å","è¦é¿","导å¸","æé¿","ç»é¢"],_=`${b} 424${w}`;for(const C of B){if(!_.includes(C))continue;const R=[...l.entries()].filter(([,M])=>M.some(W=>W.includes(C))).map(([M,W])=>({key:M,canonical:W[0]}));if(R.length!==1)continue;const T=R[0];h.has(T.key)||h.set(T.key,T.canonical)}for(const[C,R]of h.entries()){const T=e.get(C);e.set(C,{count:((T==null?void 0:T.count)||0)+1,displayName:(T==null?void 0:T.displayName)||R})}}return e},[P,we,(Um=Q==null?void 0:Q.assets)==null?void 0:Um.characters,Q==null?void 0:Q.characterShare]),Wp=c.useMemo(()=>{var l;const e=new Map,o=(((l=Q==null?void 0:Q.assets)==null?void 0:l.scenes)??[]).map(d=>String(d||"").trim()).filter(Boolean);for(const d of P){const m=new Map,y=String(d.title||"");for(const w of d.scenes||[]){const g=String(w||"").trim();if(!g)continue;const A=g.toLowerCase();m.has(A)||m.set(A,g)}const h=String(d.summary||"");for(const w of Wo(h,"SCENE")){const g=w.toLowerCase();m.has(g)||m.set(g,w)}for(const w of pu(h,["scenes","scene","åºæ¯"])){const g=w.toLowerCase();m.has(g)||m.set(g,w)}for(const w of Fy(y)){const g=w.toLowerCase();m.has(g)||m.set(g,w)}const b=`${y} 425${h}`.toLowerCase();for(const w of o){const g=w.toLowerCase();b.includes(g)&&(m.has(g)||m.set(g,w))}for(const[w,g]of m.entries()){const A=e.get(w);e.set(w,{count:((A==null?void 0:A.count)||0)+1,displayName:(A==null?void 0:A.displayName)||g})}}return e},[P,(Wm=Q==null?void 0:Q.assets)==null?void 0:Wm.scenes]),Hp=c.useMemo(()=>{var l;const e=new Map,o=(((l=Q==null?void 0:Q.assets)==null?void 0:l.props)??[]).map(d=>String(d||"").trim()).filter(Boolean);for(const d of P){const m=new Map,y=String(d.title||"");for(const w of d.props||[]){const g=String(w||"").trim();if(!g)continue;const A=g.toLowerCase();m.has(A)||m.set(A,g)}const h=String(d.summary||"");for(const w of Wo(h,"PROP")){const g=w.toLowerCase();m.has(g)||m.set(g,w)}for(const w of pu(h,["props","prop","éå ·","å ³é®éå ·"])){const g=w.toLowerCase();m.has(g)||m.set(g,w)}const b=`${y} 426${h}`.toLowerCase();for(const w of o){const g=w.toLowerCase();b.includes(g)&&(m.has(g)||m.set(g,w))}for(const[w,g]of m.entries()){const A=e.get(w);e.set(w,{count:((A==null?void 0:A.count)||0)+1,displayName:(A==null?void 0:A.displayName)||g})}}return e},[P,(Hm=Q==null?void 0:Q.assets)==null?void 0:Hm.props]),xo=c.useCallback((e,o)=>{e.length>0&&mp(l=>Bl(l,e)),o.length>0&&fp(l=>Bl(l,o))},[]),Xe=Mf(),[y1,Uc]=c.useState(null),Wc=c.useRef(!1),zp=c.useMemo(()=>jk({episodes:P,bibleCharacterMarkerLines:we.map(e=>
426qb(e.name,e.backstory)),extraTexts:J.map(e=>String(e.text||e.rawAssistantReply||"").trim()).filter(Boolean)}),[P,we,J]),hs=c.useMemo(()=>Rk(zp),[zp]),bo=c.useMemo(()=>{const e=new Map;for(const o of hs.scenes)o.desc.trim()&&e.set(o.key,o.desc.trim());return e},[hs.scenes]),wo=c.useMemo(()=>{const e=new Map;for(const o of hs.props)o.desc.trim()&&e.set(o.key,o.desc.trim());return e},[hs.props]),Kp=c.useMemo(()=>{const e=new Map;for(const o of we){if(!Ss(o.name))continue;const l=o.name.trim().toLowerCase();l&&e.set(l,o)}for(const o of Up.values()){if(o.count<JC||!Ss(o.displayName))continue;const l=o.displayName.trim().toLowerCase();!l||e.get(l)||e.set(l,{id:Il(o.displayName),name:o.displayName,backstory:""})}return[...e.values()].sort((o,l)=>o.name.localeCompare(l.name))},[Up,we]),Et=c.useMemo(()=>Xe?hs.characters.filter(e=>Ss(e.name)).map(e=>({id:Il(e.name),name:e.name,backstory:e.desc.trim()})).sort((e,o)=>e.name.localeCompare(o.name)):Kp,[Xe,Kp,hs.characters]),qp=c.useMemo(()=>{var l;const e=[...Wp.values()].filter(d=>d.count>=Vy).map(d=>d.displayName),o=(((l=Q==null?void 0:Q.assets)==null?void 0:l.scenes)??[]).map(d=>String(d||"").trim()).filter(Boolean);return Bl(e,o,hc)},[Wp,(zm=Q==null?void 0:Q.assets)==null?void 0:zm.scenes,hc]),Xt=c.useMemo(()=>Xe?hs.scenes.map(e=>e.name).sort((e,o)=>e.localeCompare(o)):qp,[Xe,qp,hs.scenes]),Gp=c.useMemo(()=>{var l;const e=[...Hp.values()].filter(d=>d.count>=Vy).map(d=>d.displayName),o=(((l=Q==null?void 0:Q.assets)==null?void 0:l.props)??[]).map(d=>String(d||"").trim()).filter(Boolean);return Bl(e,o,gc)},[Hp,(Km=Q==null?void 0:Q.assets)==null?void 0:Km.props,gc]),br=c.useMemo(()=>Xe?hs.props.map(e=>e.name).sort((e,o)=>e.localeCompare(o)):Gp,[Xe,Gp,hs.props]),ns=c.useMemo(()=>Gb(U,pe,P,{assetLibrary:{characters:Et.map(e=>({id:e.id,name:e.name})),scenes:Xt,props:br,workspaceAssetMedia:st,bibleCharacters:we}}),[U,pe,P,Et,Xt,br,st,we]),Vs=c.useMemo(()=>{if(Be==="workspace"){const e=ns.assetsReady||Et.length>0||Xt.length>0||br.length>0;return Se.storyArcReady&&Se.worldBibleReady&&Se.titleReady&&Se.dramaReady&&Se.styleLocked&&Se.charactersReady&&e}return Se.allFoundationReady},[Se,ns.assetsReady,Et.length,Xt.length,br.length,Be]),Cg=c.useMemo(()=>{var d;const e=[],o=new Set,l=m=>{const y=Mt(String(m||"").trim());if(!y)return;const h=y.toLowerCase();o.has(h)||(o.add(h),e.push(y))};for(const m of we)l(m.name);for(const m of Et)l(m.name);for(const m of((d=Q==null?void 0:Q.assets)==null?void 0:d.characters)??[])l(String(m||""));for(const m of(Q==null?void 0:Q.characterShare)??[])l(String((m==null?void 0:m.name)||""));return e},[we,Et,(qm=Q==null?void 0:Q.assets)==null?void 0:qm.characters,Q==null?void 0:Q.characterShare]),Ng=c.useMemo(()=>{var d;const e=[],o=new Set,l=m=>{const y=String(m||"").trim();if(!y)return;const h=y.toLowerCase();o.has(h)||(o.add(h),e.push(y))};for(const m of Xt)l(m);for(const m of((d=Q==null?void 0:Q.assets)==null?void 0:d.scenes)??[])l(String(m||""));for(const m of P)for(const y of m.scenes||[])l(String(y||""));return e},[Xt,(Gm=Q==null?void 0:Q.assets)==null?void 0:Gm.scenes,P]),Hc=c.useMemo(()=>{var F,V,X,ce,he,se,Ke,De,Je,bt,Sr,Zs,Mn,Qe;const e=Q,o=Math.max(1,P.length||Ce||1),l=P.length?P:Array.from({length:o},(Ae,Ue)=>({id:`e-${Ue+1}`,title:`Episode ${Ue+1}`,summary:"",attribution:{userName:"User",withBloomBot:!0}})),d=Ae=>[...new Set(Ae.map(Ue=>String(Ue||"").trim()).filter(Boolean))],m={characters:d([...((F=e==null?void 0:e.assets)==null?void 0:F.characters)||[],...Et.map(Ae=>Ae.name)]),scenes:d([...((V=e==null?void 0:e.assets)==null?void 0:V.scenes)||[],...Xt]),props:d([...((X=e==null?void 0:e.assets)==null?void 0:X.props)||[],...br])};if(!!e&&((((ce=e.pacing)==null?void 0:ce.length)||0)>0||(((he=e.characterShare)==null?void 0:he.length)||0)>0||(((Ke=(se=e.relationship)==null?void 0:se.nodes)==null?void 0:Ke.length)||0)>0||(((Je=(De=e.relationship)==null?void 0:De.edges)==null?void 0:Je.length)||0)>0)&&e)return{...e,assets:m};const h=l.map((Ae,Ue)=>{const mt=String(Ae.summary||"").trim().length,Jt=Ue/Math.max(1,l.length-1),Qt=/(battle|fight|chase|war|escape|attack|å²çª|大æ|追é)/i.test(Ae.summary||"")?"action":/(reveal|twist|truth|betray|å转|çç¸|ææ)/i.test(Ae.summary||"")?"climax":/(travel|setup|daily|arrive|å¯ç¨|éºå«|è¿æ¸¡)/i.test(Ae.summary||"")?"transition":"dialogue",xs=Jt<.2?"transition":Jt<.5?"dialogue":Jt<.8?"action":"climax",en=Math.max(20,Math.min(95,28+Math.round(Jt*46)+Math.min(24,Math.round(mt/10))));return{episodeIndex:Ue+1,label:mt>0?Qt:xs,intensity:en}}),b=[...new Set([0,Math.floor((l.length-1)/2),l.length-1])].filter(Ae=>Ae>=0),w=b.map((Ae,Ue)=>{var mt;return{episodeIndex:Ae+1,label:String(((mt=l[Ae])==null?void 0:mt.title)||"").trim()||(Ue===0?"Start":Ue===b.length-1?"Ending":"Turning point")}}),g=new Map;for(const Ae of P)for(const Ue of Ae.characterRefs||[]){const mt=Mt(String(Ue.name||"").trim());mt&&g.set(mt,(g.get(mt)||0)+1)}for(const Ae of Et){const Ue=Mt(String(Ae.name||"").trim());Ue&&(g.has(Ue)||g.set(Ue,1))}const A=[...g.entries()].sort((Ae,Ue)=>Ue[1]-Ae[1]).slice(0,8),j=Math.max(1,A.reduce((Ae,[,Ue])=>Ae+Ue,0)),B=A.map(([Ae,Ue],mt)=>{const Jt=mt===0?"protagonist":/(villain|enemy|antagon|åæ´¾|宿æ|boss)/i.test(Ae)?"antagonist":"supporting";return{name:Ae,role:Jt,sharePercent:Math.max(1,Math.round(Ue/j*100))}}),_=new Map;for(const Ae of P)for(const Ue of Ae.props||[]){const mt=String(Ue||"").trim();if(!mt)continue;const Jt=_.get(mt)||[],Qt=Math.max(1,P.indexOf(Ae)+1);Jt.includes(Qt)||Jt.push(Qt),_.set(mt,Jt)}const C=br.slice(0,4).map((Ae,Ue)=>{const mt=(_.get(Ae)||[]).sort((en,_d)=>en-_d),Jt=mt[0]??Math.min(Ue+1,o),Qt=mt.length>1,xs=Qt?mt[mt.length-1]:null;return{id:`seed-${Ue+1}-${encodeURIComponent(Ae)}`,label:Ae,plantedInEpisode:Jt,paidOff:Qt,paidOffInEpisode:xs}}),R=Ho.filter(Ae=>String(pe[Ae]||"").trim().length===0),T={consistent:R.length===0,conflicts:R.slice(0,2).map(Ae=>{var Ue;return{description:`World bible section needs content: ${((Ue=er.find(mt=>mt.id===Ae))==null?void 0:Ue.label)||Ae}`,episodeIndex:null,worldBibleDimension:Ae}})},M=B.slice(0,6).map(Ae=>({id:Il(Ae.name),name:Ae.name})),W=M.length>=2?M.slice(1).map((Ae,Ue)=>{var mt,Jt;return{from:M[0].id,to:Ae.id,relation:((mt=B[Ue+1])==null?void 0:mt.role)==="antagonist"?"hostile":((Jt=B[Ue+1])==null?void 0:Jt.role)==="supporting"?"friendly":"neutral",lineStyle:Ue%2===0?"solid":"dashed"}}):[],q=Et.map(Ae=>
426Ae.name).filter(Boolean),G={pacing:h.length>0?h:(e==null?void 0:e.pacing)||[],pacingHighlights:w,characterShare:B.length>0?B:(e==null?void 0:e.characterShare)||[],seeds:C.length>0?C:(e==null?void 0:e.seeds)||[],logic:T,assets:{characters:q.length?q:((bt=e==null?void 0:e.assets)==null?void 0:bt.characters)||[],scenes:Xt.length?Xt:((Sr=e==null?void 0:e.assets)==null?void 0:Sr.scenes)||[],props:br.length?br:((Zs=e==null?void 0:e.assets)==null?void 0:Zs.props)||[]},relationship:{nodes:M.length>0?M:((Mn=e==null?void 0:e.relationship)==null?void 0:Mn.nodes)||[],edges:W.length>0?W:((Qe=e==null?void 0:e.relationship)==null?void 0:Qe.edges)||[]}};return G.pacing.length>0||G.characterShare.length>0||G.assets.characters.length>0||G.assets.scenes.length>0||G.assets.props.length>0?G:e},[Q,P,Ce,Et,Xt,br,pe]);c.useMemo(()=>{if(!Hc)return null;const e=Math.max(1,P.length||Ce||1),o=Math.max(0,...(Hc.pacing||[]).map(l=>{const d=Number(l==null?void 0:l.episodeIndex);return Number.isFinite(d)?Math.floor(d):0}));return o<=0||o>=e?null:n("page.storyflow.creativeBrainDashboard.coverageOnlyRange",{end:o})},[Hc,P.length,Ce,n]);const os=c.useCallback((e,o)=>{if(!(typeof window>"u"))try{const l=XC.includes(e)?e:"guided_enter";window.dispatchEvent(new CustomEvent("cb-guided-metric",{detail:{event:l,step:Gt,guidedMode:Wt,ts:Date.now(),...o||{}}}))}catch{}},[Gt,Wt]);c.useEffect(()=>{var e,o,l,d;Te.current=!1;try{const m=Oo(ae);if(!m)return;const y=JSON.parse(m),{state:h}=Yb(y),b=String(h.greenlightProjectId??"").trim(),w=typeof t=="string"?t.trim():"";if(b&&w&&b!==w)return;const g=h;typeof g.projectName=="string"&&g.projectName.trim()&&Xr(g.projectName.trim()),gp(Uh(g.storyflowAspectRatio));{const C=kf(g.projectName,f),R=Sy({storyflowProjectSetupComplete:g.storyflowProjectSetupComplete,projectName:C,seriesVisualStyleId:g.seriesVisualStyleId,seriesVisualStylePickerDismissed:g.seriesVisualStylePickerDismissed,storyOutline:g.storyOutline,seasonEpisodes:g.seasonEpisodes,messages:g.messages,storyflowAspectRatio:g.storyflowAspectRatio});bc(R)}{const C=g.setupCollaboratorUserIds;Array.isArray(C)&&bp(C.map(R=>String(R||"").trim()).filter(Boolean))}{const C=g.storyflowLayoutTab,R=w||(typeof t=="string"?t.trim():""),T=Pf();T&&T.parentProjectId===R&&T.tab?(_f(R),ue(T.tab),T.tab==="episodes"&&(xr.current=!1,be(null),Lt(null))):(C==="outline"||C==="world"||C==="episodes"||C==="assets")&&ue(C)}{const C=g.selectedHierarchyNodeId,R=g.storyflowLayoutTab;typeof C=="string"&&C.trim()?be(C.trim()):(R==="outline"||R==="world"||R==="assets"||!R)&&be(_r)}{const C=g.foundationLockedAt,R=Array.isArray(g.seasonEpisodes)&&g.seasonEpisodes.length>0,T=Dk({foundationLockedAt:typeof C=="string"&&C.trim()?C.trim():null,hasEpisodes:R});if(mr(T),ye&&T){const M=g.selectedHierarchyNodeId;typeof M=="string"&&/^ep:\d+:seq:\d+$/.test(M.trim())||(xr.current=!1,be(null),ue("episodes"))}}g.storyOutline&&typeof g.storyOutline=="object"&&Rr(C=>BC(C,g.storyOutline)),g.worldBible&&typeof g.worldBible=="object"&&Us(C=>MC(C,g.worldBible)),Array.isArray(g.seasonEpisodes)&&g.seasonEpisodes.length>0&&Fe(C=>C.length===0?g.seasonEpisodes:Fd(C,g.seasonEpisodes)),g.dashboardSnapshot&&typeof g.dashboardSnapshot=="object"&&pc(g.dashboardSnapshot),Qw(g.narrativePhase)&&sg(g.narrativePhase);const A=typeof g.seriesVisualStyleId=="string"?g.seriesVisualStyleId.trim():"";A&&un.some(C=>C.id===A)&&$s(A),typeof g.seriesCustomStylePrompt=="string"&&Or(g.seriesCustomStylePrompt);const j=!!((o=(e=g.storyOutline)==null?void 0:e.logline)!=null&&o.trim())||!!((d=(l=g.storyOutline)==null?void 0:l.synopsis)!=null&&d.trim())||!!(g.worldBible&&Object.values(g.worldBible).some(C=>typeof C=="string"&&C.trim().length>0))||!!(Array.isArray(g.seasonEpisodes)&&g.seasonEpisodes.some(C=>typeof(C==null?void 0:C.summary)=="string"&&C.summary.trim().length>0)),B=!!(g.worldBible&&Object.values(g.worldBible).some(C=>typeof C=="string"&&C.trim().length>0))||!!(Array.isArray(g.seasonEpisodes)&&g.seasonEpisodes.some(C=>typeof(C==null?void 0:C.summary)=="string"&&C.summary.trim().length>0))||!!(g.dashboardSnapshot&&typeof g.dashboardSnapshot=="object")||!!(g.workspaceAssetMedia&&typeof g.workspaceAssetMedia=="object"&&!Array.isArray(g.workspaceAssetMedia)&&Object.keys(g.workspaceAssetMedia).length>0);if(A?Er(!0):typeof g.seriesVisualStylePickerDismissed=="boolean"?Er(g.seriesVisualStylePickerDismissed):Er(!!j),typeof window<"u"&&t&&(sessionStorage.removeItem(`${Vb}:${t}`),sessionStorage.removeItem(`${Xb}:${t}`)),Aa(an?yS(g.storyflowUiPhase):g.storyflowUiPhase==="workspace"?"workspace":"immersive"),typeof g.plannedEpisodeCount=="number"&&g.plannedEpisodeCount>=1&&(Nt(sn(g.plannedEpisodeCount)),Dt(null)),typeof g.episodeDurationSeconds=="number"){const C=g.storyflowStandaloneFilmMode===!0;
426let R=We(g.episodeDurationSeconds,C);uf(R,C)&&(R=On),ar(R),gr(String(Al(R,C)))}else g.storyflowStandaloneFilmMode===!0?(ar(On),gr(String(On/60))):(ar(Br),gr(String(ln)));if((g.skeletonApplyMode==="fill_empty"||g.skeletonApplyMode==="overwrite_all"||g.skeletonApplyMode==="overwrite_range")&&dp(g.skeletonApplyMode),typeof g.skeletonApplyRangeStart=="number"&&up(Math.max(1,Math.min(pr,Math.floor(g.skeletonApplyRangeStart)))),typeof g.skeletonApplyRangeEnd=="number"&&pp(Math.max(1,Math.min(pr,Math.floor(g.skeletonApplyRangeEnd)))),g.storyflowPlanAck&&typeof g.storyflowPlanAck=="object"){const C=g.storyflowPlanAck;kt({episodeCount:!!C.episodeCount,episodeDuration:!!C.episodeDuration})}if(g.storyflowStandaloneFilmMode===!0)Jr(!0),Nt(1),Dt(null),kt(C=>{var R;return{episodeCount:!0,episodeDuration:C.episodeDuration||!!((R=g.storyflowPlanAck)!=null&&R.episodeDuration)||typeof g.episodeDurationSeconds=="number"}});else if(Array.isArray(g.messages)){const C=g.messages.filter(R=>R.role==="user").map(R=>String(R.text||"")).filter(Boolean);(vr({recentUserTexts:C,plannedEpisodeCount:typeof g.plannedEpisodeCount=="number"?g.plannedEpisodeCount:void 0})||$d({descriptiveScriptV1:Mf(),storyflowStandaloneFilmMode:g.storyflowStandaloneFilmMode,plannedEpisodeCount:typeof g.plannedEpisodeCount=="number"?g.plannedEpisodeCount:void 0,recentUserTexts:C}))&&(Jr(!0),Nt(1),Dt(null))}if(Array.isArray(g.seriesBibleCharacters)&&g.seriesBibleCharacters.length>0&&xn(g.seriesBibleCharacters.filter(C=>Ss(String((C==null?void 0:C.name)||"")))),Array.isArray(g.storyflowChatDerivedScenes)&&mp(g.storyflowChatDerivedScenes.map(C=>String(C||"").trim()).filter(Boolean)),Array.isArray(g.storyflowChatDerivedProps)&&fp(g.storyflowChatDerivedProps.map(C=>String(C||"").trim()).filter(Boolean)),typeof g.dramaCategoryId=="string"&&g.dramaCategoryId){const C=g.dramaCategoryId;oa.some(R=>R.id===C)&&di(C)}if(typeof g.dramaCustomNote=="string"&&to(g.dramaCustomNote),typeof g.outlinePosterUrl=="string"&&g.outlinePosterUrl.startsWith("http")&&(vp(g.outlinePosterUrl),typeof g.outlinePosterSeriesTitle=="string"&&g.outlinePosterSeriesTitle.trim()?hi(g.outlinePosterSeriesTitle.trim()):typeof g.projectName=="string"&&g.projectName.trim()&&hi(g.projectName.trim())),typeof g.worldPosterUrl=="string"&&g.worldPosterUrl.startsWith("http")&&Np(g.worldPosterUrl),typeof g.outlinePosterPrompt=="string"&&g.outlinePosterPrompt.trim()&&Ba(g.outlinePosterPrompt.trim()),g.workspaceMainTab==="outline"||g.workspaceMainTab==="world"||g.workspaceMainTab==="characters"||g.workspaceMainTab==="scenes"||g.workspaceMainTab==="props"?Ht(g.workspaceMainTab):(g.workspaceMainTab==="assets"||g.workspaceMainTab==="overview")&&Ht(an?"characters":g.workspaceMainTab==="overview"?"overview":"assets"),g.workspaceAssetMedia&&typeof g.workspaceAssetMedia=="object"&&rs(g.workspaceAssetMedia),Array.isArray(g.messages)){const C=_s(g.messages);$t(C)}{const C=g.messagesEpisodeUnit;Array.isArray(C)&&Mr(_s(C))}{const C=vC(g.messagesEpisodeUnitByHierarchyId);Object.keys(C).length>0&&fe(C)}const _=kC(g.messagesEpisodeByIndex);if(Object.keys(_).length>0)yn(_);else if(Array.isArray(g.messagesEpisode)){const C=_s(g.messagesEpisode);C.length&&yn({0:C})}typeof g.guidedMode=="boolean"?uc(g.guidedMode):uc(!B),g.guidedStep&&VC.includes(g.guidedStep)&&Ws(g.guidedStep)}catch{}finally{const m=kf(f);Sy({projectName:m})&&bc(!0),nt.current=de,Te.current=!0,ng(!0)}},[ae,t,de,f]),c.useEffect(()=>{const e=typeof t=="string"?t.trim():"";if(!e||!Pf())return;const o=_f(e);o!=null&&o.tab&&(ue(o.tab),o.tab==="episodes"&&(xr.current=!1,be(null),Lt(null)))},[t,de]),c.useEffect(()=>{if(typeof window>"u"||!Te.current)return;const e=window.setTimeout(()=>{Ze.current({silent:!0})},120);return()=>window.clearTimeout(e)},[qe,wt,At,at]),c.useEffect(()=>{if(typeof window>"u"||!Te.current)return;const e=window.setTimeout(()=>{Ze.current({silent:!0})},280);return()=>window.clearTimeout(e)},[U,pe,P,Ce,te,Dr]),c.useEffect(()=>{if(typeof window>"u")return;const e=()=>{Te.current&&Ze.current({silent:!0})};window.addEventListener("pagehide",e);const o=()=>{document.visibilityState==="hidden"&&e()};return document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("pagehide",e),document.removeEventListener("visibilitychange",o)}},[]),c.useEffect(()=>{if(typeof window>"u")return;if(!Wt){Ra(!1);return}let e=!1;try{e=localStorage.getItem(uu)==="1"}catch{e=!1}if(e)return;const o=[],l=(d,m)=>{o.push(window.setTimeout(m,d))};return gn(!0),Ra(!0),l(650,()=>
426gn(!1)),l(1300,()=>gn(!0)),l(1950,()=>gn(!1)),l(2600,()=>gn(!0)),l(2900,()=>{Ra(!1);try{localStorage.setItem(uu,"1")}catch{}}),()=>{o.forEach(d=>window.clearTimeout(d))}},[Wt]),c.useEffect(()=>{if(!(typeof window>"u"||!Q)&&Te.current)try{const e=Oo(ae),o=e?JSON.parse(e):{},l=Dd(o.dashboardSnapshot,Q)||Q;localStorage.setItem(ae,JSON.stringify({...o,dashboardSnapshot:l}))}catch{}},[ae,Q]),c.useEffect(()=>{if(typeof window>"u"||!Te.current)return;const e=window.setTimeout(()=>{if(Te.current)try{const o=Oo(ae),l=o?JSON.parse(o):{};localStorage.setItem(ae,JSON.stringify({...l,projectName:ge}))}catch{}},400);return()=>window.clearTimeout(e)},[ae,ge,de]),c.useEffect(()=>{if(typeof window>"u"||!Te.current||nt.current!==de)return;const e=window.setTimeout(()=>{var o;if(Te.current&&nt.current===de)try{const l=Oo(ae),d=l?JSON.parse(l):{},m=typeof d.seriesVisualStyleId=="string"?d.seriesVisualStyleId.trim():"";if(d.seriesVisualStylePickerDismissed===!0&&m&&!yr&&Le===(((o=un[0])==null?void 0:o.id)??"Cinematic"))return;localStorage.setItem(ae,JSON.stringify({...d,seriesVisualStyleId:Le,seriesCustomStylePrompt:Oe,seriesVisualStylePickerDismissed:yr}))}catch{}},400);return()=>window.clearTimeout(e)},[ae,Le,Oe,yr,de]),c.useEffect(()=>{if(typeof window>"u"||!Te.current)return;const e=window.setTimeout(()=>{if(Te.current)try{const o=Oo(ae),l=o?JSON.parse(o):{};localStorage.setItem(ae,JSON.stringify({...l,guidedMode:Wt,guidedStep:Gt}))}catch{}},280);return()=>window.clearTimeout(e)},[ae,Wt,Gt,de]),c.useEffect(()=>{if(typeof window>"u"||!Te.current)return;const e=window.setTimeout(()=>{Te.current&&Ze.current({silent:!0})},280);return()=>{if(window.clearTimeout(e),!!Te.current)try{Ze.current({silent:!0})}catch{}}},[ae,Wt,Gt,Be,Ce,te,Dr,Hs,ui,pi,we,hc,gc,rt,Yt,Vt,Zr,gt,st,qe,wt,At,at]),c.useEffect(()=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("workflow-project-assets-refresh"))},[st]),c.useEffect(()=>{Bf()||Ta(!0)},[]),c.useEffect(()=>()=>{Sw()},[]),c.useEffect(()=>{typeof window>"u"||os("guided_enter",{completedBefore:localStorage.getItem(My)==="1"})},[]),c.useEffect(()=>{if(!Wt)return;const e=QC(ns);if(e!==Gt&&(Ws(e),os("guided_step_advanced",{to:e})),ns.allReady&&typeof window<"u")try{localStorage.setItem(My,"1")}catch{}},[Wt,ns,Gt,os]);const Cn=c.useRef(null),Nn=c.useRef(null),zc=c.useRef(null),Kc=c.useRef(null),Ri=c.useRef(null),Qa=c.useRef("");typeof window<"u"&&!Qa.current&&(Qa.current=hC());const[Za,qc]=c.useState(!1),Gc=c.useRef(!1);c.useEffect(()=>{Gc.current=Za},[Za]),c.useEffect(()=>{try{if(typeof window>"u")return;qc(localStorage.getItem(gu)==="1")}catch{qc(!1)}},[]),c.useEffect(()=>{if(!Fl()||typeof window>"u")return;const e=Qa.current;if(!e)return;const o=sS({storyOutline:U,worldBible:pe,worldDimensionLabels:Iu,seasonEpisodes:P,characterProfiles:we.map(d=>({name:d.name,backstory:d.backstory})),openSeeds:(Q==null?void 0:Q.seeds)||[]}),l=window.setTimeout(()=>{nS(e,o)},2800);return()=>window.clearTimeout(l)},[U,pe,P,we,Q==null?void 0:Q.seeds]);const Eg=c.useCallback(()=>{qc(e=>{const o=!e;try{typeof window<"u"&&(o?localStorage.setItem(gu,"1"):localStorage.removeItem(gu))}catch{}return Cn.current=null,Nn.current=null,H.info(n("page.storyflow.toastTitleBloomBot"),n(o?"page.storyflow.textTableModeOnBody":"page.storyflow.textTableModeOffBody")),o})},[n]),ji=c.useRef(0),Ai=c.useRef(0),Xs=c.useRef({storyOutline:U,worldBible:pe,seasonEpisodes:P,selectedEpisodeIndex:Kt,dashboardData:Q,narrativePhase:ja,bloomEditContext:Pt,episodeOutlineEditingIndex:_e,openFullView:null,textTableSkillOn:!1,cbVisualStyleId:((Ym=un[0])==null?void 0:Ym.id)??"Cinematic",cbCustomStylePrompt:"",storyflowUiPhase:"immersive",projectName:"",plannedEpisodeCount:jl,storyflowStandaloneFilmMode:!1,recentHomeUserTexts:[],episodeDurationSeconds:Ji,storyflowPlanAck:{episodeCount:!1,episodeDuration:!1},dramaCategoryId:"",dramaCustomNote:"",cbSeriesStylePickerDismissed:!1,storyflowLayoutTab:"outline",hierarchySelectedId:null,cbPipelineReadiness:{storyArcReady:!1,worldBibleReady:!1,assetsReady:!1,episodeListReady:!1,allReady:!1}});Xs.current={storyOutline:U,worldBible:pe,seasonEpisodes:P,selectedEpisodeIndex:Kt,dashboardData:Q,narrativePhase:ja,bloomEditContext:Pt,episodeOutlineEditingIndex:_e,openFullView:oe,textTableSkillOn:Gc.current,cbVisualStyleId:Le,cbCustomStylePrompt:Oe,storyflowUiPhase:Be,projectName:ge,plannedEpisodeCount:Ce,storyflowStandaloneFilmMode:ke,recentHomeUserTexts:J.filter(e=>e.role==="user").slice(-5).map(e=>e.text),episodeDurationSeconds:te,storyflowPlanAck:Dr,dramaCategoryId:rt,dramaCustomNote:Yt,cbSeriesStylePickerDismissed:yr,storyflowLayoutTab:je,hierarchySelectedId:ve,cbPipelineReadiness:ns},c.useEffect(()=>{if(Re!=="episode_unit")return;const e=ve?`unit:${ve}`:"breakdown";if(Kc.current===e)return;Kc.current=e,Cn.current=null,ji.current=0;const o=ve?(At[ve]??[]).length:wt.length;qt(o)},[Re,ve,At,wt]),c.useEffect(()=>{if(!(oe==="episode"||(Pt==null?void 0:Pt.type)==="episode_outline"))return;const o=_e??((Pt==null?void 0:Pt.type)==="episode_outline"?Pt.episodeIndex:void 0)??Kt??0,l=String(o);if(zc.current!==l){Nn.current=null,Ai.current=0;const d=Number(l);qt((at[d]??[]).length),zc.current=l}},[oe,Pt,_e,Kt,at]);const Ii=c.useRef(null),Yp=c.useRef(null),Vp=c.useRef(null),[So,ko]=c.useState(""),[Xp,Yc]=c.useState(!1),Jp=c.useRef(null),Vc=c.useRef(!1),Xc=c.useMemo(()=>pf(So),[So]),Tg=Ye==="zh"?"zh-CN":"en-US",{supported:Jc,listening:En,interimText:Rg,userErrorKey:Qp,toggleListening:jg,stopListening:Zp}=ah({language:Tg,scope:"storyflow_immersive_speech",onFinalText:e=>{Vc.current=!0,ko(o=>{const l=String(o||"").trimEnd();return l?`${l} ${e}`:e}),queueMicrotask(()=>{Vc.current=!1})}}),em=Qp?n(`page.bloomBotCard.${Qp}`):null,Ag=c.useCallback(e=>
426{En&&!Vc.current&&Zp(),ko(e)},[En,Zp]),Ig=c.useCallback(e=>{Yc(!1);const o=Vp.current;o&&(e==="image"?o.accept="image/*":e==="video"?o.accept="video/*":o.accept=".txt,.md,text/plain,.docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document",o.click())},[]),Pg=J.length>0,tm=c.useMemo(()=>pf(po),[po]),el=c.useRef(!1),tl=c.useRef(!1),rm=(e,o,l)=>{const d=Ay(e,Ye),m=o==="assistant"?Xd(d,Ye):d;if(o!=="assistant"||!m.includes(ia))return s.jsx("p",{className:l,children:m});const y=m.split(` 427`);return s.jsx("div",{className:l,children:y.map((h,b)=>{const w=h.trim().startsWith(ia),g=w?h.replace(ia,"").trim():h;return s.jsx("span",{className:w?"block font-bold text-primary":"block",children:g||" "},`${b}-${g.slice(0,16)}`)})})},_g=14,[Qc,Bg]=c.useState(33.333),[Zc,Mg]=c.useState(66.667),sm=c.useRef(null),ed=c.useRef(null),[nm,om]=c.useState(!1);c.useEffect(()=>{if(!nm)return;const e=l=>{const d=ed.current,m=sm.current;if(!d||!m)return;const y=m.getBoundingClientRect().width;if(y<1)return;const h=(l.clientX-d.startX)/y*100,b=_g,w=d.startL+d.startM;let g=d.startL+h;g=Math.max(b,Math.min(g,w-b));const A=w-g;Bg(g),Mg(A)},o=()=>{ed.current=null,om(!1)};return window.addEventListener("pointermove",e),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",e),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o)}},[nm]);const Lg=c.useCallback(e=>{e.preventDefault(),ed.current={startX:e.clientX,startL:Qc,startM:Zc},om(!0),e.currentTarget.setPointerCapture(e.pointerId)},[Qc,Zc]),Og=`minmax(0,${Qc}fr) 6px minmax(0,${Zc}fr)`,im=c.useCallback(e=>{const o=l=>({getProjectContext:()=>{var he,se;const d=Xs.current,m=d.episodeOutlineEditingIndex!=null?d.episodeOutlineEditingIndex:d.selectedEpisodeIndex,y=Ho.every(Ke=>String(d.worldBible[Ke]||"").trim().length>0),h=!!d.dramaCategoryId&&(d.dramaCategoryId!=="custom"||(d.dramaCustomNote||"").trim().length>0),b=!ws(d.projectName),w=d.storyflowStandaloneFilmMode===!0||vr({standaloneFilmMode:d.storyflowStandaloneFilmMode,plannedEpisodeCount:d.plannedEpisodeCount,episodeDurationSeconds:d.episodeDurationSeconds,recentUserTexts:d.recentHomeUserTexts}),g=cf({standaloneFilmMode:w,plannedEpisodeCount:d.plannedEpisodeCount,defaultPlannedEpisodeCount:jl,episodeCountAck:d.storyflowPlanAck.episodeCount}),A=df({standaloneFilmMode:w,episodeDurationSeconds:d.episodeDurationSeconds,episodeDurationAck:d.storyflowPlanAck.episodeDuration,normalizeDuration:Ke=>We(Ke,w)}),j=qf({storyOutline:d.storyOutline,worldBible:d.worldBible,seriesTitle:d.projectName,plannedEpisodeCount:d.plannedEpisodeCount,dramaCategoryId:d.dramaCategoryId,dramaCustomNote:d.dramaCustomNote,seriesBibleCharacters:we,styleLocked:d.cbSeriesStylePickerDismissed}),B={storyArcReady:j.storyArcReady,worldBibleReady:y,charactersReady:j.charactersReady,titleReady:j.titleReady&&b,episodePlanReady:j.episodePlanReady&&g&&A,dramaReady:h,styleLocked:j.styleLocked},_=[B.storyArcReady?"":"Story outline",B.worldBibleReady?"":"World bible",B.charactersReady?"":"Characters",B.titleReady?"":"Title (must be user-confirmed, not default)",!w&&!g?"Episode count (confirm with user)":"",!w&&!A?"Per-episode duration (confirm with user)":"",w&&!A?"Full film runtime (confirm with user)":"",B.dramaReady?"":"Category (Custom needs note)",B.styleLocked?"":"Style"].filter(Boolean),C=qr({uiPhase:d.storyflowUiPhase,inEpisodeScriptContext:d.openFullView==="episode"||((he=d.bloomEditContext)==null?void 0:he.type)==="episode_outline"}),R=rS({storyOutline:d.storyOutline,worldBible:d.worldBible,worldDimensionLabels:Iu,seasonEpisodes:d.storyflowUiPhase==="immersive"?[]:d.seasonEpisodes.map(Ke=>{var bt;const De=String(Ke.title||"").trim();return{title:w&&(!De||Bs(De))?d.projectName.trim()||"This film":De,summary:Ke.summary,characterNames:(bt=Ke.characterRefs)==null?void 0:bt.map(Sr=>Sr.name).filter(Boolean)}}),characterProfiles:we.map(Ke=>({name:Ke.name,backstory:Ke.backstory})),selectedEpisodeIndex:m,dashboardData:d.dashboardData,narrativePhase:d.narrativePhase,sendTurnIndex:l.current,fullContextEveryNTurns:3,editFocus:mu(d.bloomEditContext),seriesVisualStyle:ds(d.cbVisualStyleId,d.cbCustomStylePrompt)}),T=w?` 428 429${hb(Ye==="zh"?"zh":"en")}`:"",M=w?`## STORYFLOW setup state (homepage â STANDALONE FILM) 430Film title: ${d.projectName.trim()||"(not set)"} 431Full film runtime: ${We(d.episodeDurationSeconds)}s 432Category: ${d.dramaCategoryId||"(not selected)"}${d.dramaCategoryId==="custom"?` 433Category note: ${(d.dramaCustomNote||"").trim()||"(empty)"}`:""} 434 435Behavior rules: 436- Project setup already locked **standalone film (1 film)** â never ask å é, æ¯éå¤é¿, or offer "NéÃMåé" chips. 437- **Never** ask åé¨çµå½± vs çå§/å§é or offer "åé¨çµå½±" / "çå§å§é" format chips â the user already chose **çµå½±æ¨¡å¼** at setup. 438- This is **one complete film**, not a TV season. Never say 第1é, 第ä¸é, ã第ä¸éã, Episode 1, pilot, å£ç», or ask how many episodes. Never propose those as the film title â use a real title or say æ¬ç / å¼åº / 第ä¸å¹. 439- Discuss **full film runtime** (minutes), not per-episode length. 440- When runtime is confirmed, include \`plannedEpisodes: 1\` and \`episodeDurationSeconds\` (full film seconds) in ${Wn} ⦠${zn}. 441- Build act structure / detailed script for **this film only**; option chips must use æ¬ç / act beats, not serialized episode slots. 442- Use @@ / %% / $$ / [[SCENE:]] / [[PROP:]] markers as in series mode.`:`## STORYFLOW setup state (homepage) 443Series title: ${d.projectName.trim()||"(not set)"} 444Planned episodes: ${d.plannedEpisodeCount} 445Unified episode duration: ${We(d.episodeDurationSeconds)}s 446Category: ${d.dramaCategoryId||"(not selected)"}${d.dramaCategoryId==="custom"?` 447Category note: ${(d.dramaCustomNote||"").trim()||"(empty)"}`:""} 448 449Checklist: 450- Story outline: ${B.storyArcReady?"done":"missing"} 451- World bible: ${B.worldBibleReady?"done":"missing"} 452- Title: ${B.titleReady?"done":"missing"} 453- Characters: ${B.charactersReady?"done":"missing"} 454- Episode count: ${g?"done":"missing"} 455- Episode duration: ${A?"done":"missing"} 456- Category: ${B.dramaReady?"done":"missing"} 457- Style: ${B.styleLocked?"done":"missing"} 458 459Missing now: ${_.length?_.join(", "):"none"} 460 461Behavior rules: 462- While user is on homepage immersive chat, do NOT draft episode-by-episode scripts or split detailed episode cards. 463- Focus only on completing missing foundation items above. 464- **If Story outline or World bible is missing: do NOT output a full N-episode åéå§æ æ¿ / Episode Board table** (truncation leaves users stuck mid-table with no next step). Finish synopsis + five world-bible fields first; at most 1â2 sample episode rows if the user insists; always end with [[OPTIONS: â¦]] next steps. 465- If you start an episode board and hit length limits, stop on a **whole-episode boundary** and offer [[OPTIONS: Continue remaining episodes, â¦]] â never end mid-row with
465no next-step chips. 466- **Every story character** you introduce or refine MUST include a dedicated **visual design** subsection: no character is complete without it. 467- Use this **exact subsection title pattern** per character (one block per character): 468 - Chinese replies: a single heading line \`{è§è²åå}形象设计\` or \`{è§è²åå}è§è²å½¢è±¡è®¾è®¡\` (è§è²åå = the characterâs name as used in the story). 469 - English replies: \`**{Name} â Character visual design**\` (same {Name} as in the story). 470- Under that heading, always cover (in the reply language): ethnicity/group, age, face/build, costume look, and key props carried or worn. 471- Symbol protocol is mandatory for downstream parsing: 472 - Character names must use @@ format: @@è§è²åã形象æè¿°ã. 473 - Dialogue must use %%说è¯è 说ï¼å¯¹ç½%% (or %%Name: "dialogue"%%). 474 - Narration must use $$æç½å 容$$. 475 - Scene and prop tags must use [[SCENE:Name]] and [[PROP:Name]]. 476 - Do not output role names, dialogue, scene names, or props in free-form formats that break these markers. 477- You MUST discuss **total episode count** and **unified per-episode duration** with the user before treating the season shape as settled. Offer clear options (e.g. 6 vs 12 episodes; 60s vs 120s vs 180s per episode) when helpful. 478- When the user confirms count and duration, end your reply with ${Wn} ⦠${zn} (JSON between the tags) including numeric \`plannedEpisodes\` and \`episodeDurationSeconds\` (30â300, step 30) so the homepage controls sync automatically. Legacy tag [[GREENLIGHT_STRUCTURE_JSON]] is still accepted. 479- During script communication, explicitly tag assets using markers so Asset library can parse them: 480 - Scene marker: [[SCENE:Scene Name]] 481 - Key prop marker: [[PROP:Prop Name]] 482 - Use short noun names only (2-20 chars), no full sentences. 483- If the only remaining missing item is Style, do not continue discussing plot content. Only ask user to complete style selection, then guide them to click "Continue to story workspace".
484- For short series pacing (around 10 episodes), keep active seeds lean (target 3-4), and prioritize payoff clarity over quantity. 485- Enforce visible rhythm: every 2-3 episodes should include a meaningful escalation, reversal, or cost. 486- Once all items are done, explicitly tell the user to click the bottom button "Continue to story workspace".`,W=bs(d.storyflowLayoutTab);let q=null;const G=/^ep:(\d+):seq:(\d+)$/.exec(String(d.hierarchySelectedId||""));if(G){const Ke=Number(G[1]),De=Number(G[2]),Je=d.seasonEpisodes[Ke],bt=(se=Je==null?void 0:Je.generationUnits)==null?void 0:se.find(Sr=>Sr.index===De);bt&&(q={episodeIndex:Ke,unitIndex:De,unitLabel:String(bt.label||"").trim()||`Seq ${De+1}`,beatSummary:bt.beatSummary,episodeTitle:Je==null?void 0:Je.title})}const Y=W==="foundation"&&B.storyArcReady&&B.worldBibleReady?` 487 488Post-foundation phase (outline + world bible are DONE on the board): 489- Stop asking micro plot checkpoints (single props, hook variants, "what form is the last message", etc.). 490- Do NOT rewrite title, logline, synopsis, or world bible unless the user explicitly asks. 491- Default next work: ${w?"**ååº / act beats / æ¬çå ³é®åºæ¯** tab for scene beats; use **Assets** tab for @@ / [[SCENE:]] / [[PROP:]] visual bible. **Never** ask å§éå½¢æ / å é / æ¯éå¤é¿.":"switch to **Episodes & sequences** tab for scene beats; use **Assets** tab for @@ / [[SCENE:]] / [[PROP:]] visual bible."} 492- Keep replies short; one deliverable per turn when the user asks to continue.`:"",F=C?`${gf} 493 494## Board snapshot (extractor fills empty fields in the background) 495Series title: ${d.projectName.trim()||"(not set)"} 496Project format: ${w?"STANDALONE FILM (1 complete movie â NOT a series)":"Series / short drama"} 497Planned episodes: ${w?"1 (standalone film â locked at project setup; NEVER ask again)":g?String(d.plannedEpisodeCount):"unspecified (draft as 10 for series unless the user stated otherwise)"} 498Unified episode duration: ${w?`${We(d.episodeDurationSeconds)}s (full film runtime â locked; NEVER ask per-episode length)`:A?`${We(d.episodeDurationSeconds)}s`:"unspecified (draft as 90s for series unless the user stated otherwise)"} 499Category: ${d.dramaCategoryId||"(not selected)"} 500Outline ready: ${B.storyArcReady?"yes":"no"} 501World bible ready: ${B.worldBibleReady?"yes":"no"} 502Characters on board: ${we.length} 503Write the next story draft. Do not nag missing checklist items or force @@ / visual-design subsections.${Y}${T}`:`${M}${Y}${T}`,V=d.storyflowLayoutTab==="outline"?"Focus on logline, synopsis, theme, and series/film structure. Do not draft full episode scripts unless asked.":d.storyflowLayoutTab==="world"?"Focus on world bible (geography, timeline, rules, culture, core conflict). Keep it consistent with the plot outline; do not draft full episode scripts unless asked.":d.storyflowLayoutTab==="episodes"?Do()?"Focus on scene beat lists (episodes[i].sequences or lines like åº1 | â¦). Beat list â full screenplay. Honor plot outline + world bible. Include actId 1â3 for film acts. No Shot N lists.":"Focus on episode/sequence breakdown, beats, and descriptive unit scripts (åºåº). Honor both plot outline and world bible. Do not invent Shot N lists.":"Focus on character / scene / prop visual bible using @@ / â³â³ / ââ markers.",X=d.storyflowUiPhase==="workspace"?` 504 505${XS({mode:W,layoutTab:d.storyflowLayoutTab,hierarchySelectedId:d.hierarchySelectedId,selectedUnit:q,sequenceBeatSyncEnabled:Do()})} 506 507${W==="foundation"?xb+(!B.storyArcReady||!B.worldBibleReady?` 508 509${Uk(Ye==="zh"?"zh":"en")}`:""):gb}`:` 510 511## Active Storyflow Layout B tab 512Tab: ${d.storyflowLayoutTab} 513Selected hierarchy node: ${d.hierarchySelectedId||"(none)"} 514Guidance: ${V}`;return`${w?`## CRITICAL â çµå½±æ¨¡å¼å·²éå®ï¼ç«é¡¹æ¶éå®ï¼ 515æ ¼å¼ = **åé¨å®æ´çµå½±**ï¼1 é¨ï¼å ¨çæ¶é¿å·²å¨é¢æ¿æ¾ç¤ºï¼ã**ç¦æ¢**å¨å夿 [[OPTIONS]] ä¸åºç°ï¼å§éãåéãæ¯éãå£ãå§éå½¢æãå éãæ¯éå¤é¿ãNéÃMåéãçå§/é¿å§èå¥å¯¹æ¯ã 516 517`:""}${R} 518 519${F}${X}`},getCbSkillRoutingSnapshot:()=>{var y;const d=Xs.current,m=d.storyflowStandaloneFilmMode===!0||vr({standaloneFilmMode:d.storyflowStandaloneFilmMode,plannedEpisodeCount:d.plannedEpisodeCount,episodeDurationSeconds:d.episodeDurationSeconds,recentUserTexts:d.recentHomeUserTexts});return{narrativePhase:d.narrativePhase,editFocus:mu(d.bloomEditContext),openFullView:d.openFullView,textTableSkillOn:d.textTableSkillOn,homepageTalkExtract:qr({uiPhase:d.storyflowUiPhase,inEpisodeScriptContext:d.openFullView==="episode"||((y=d.bloomEditContext)==null?void 0:y.type)==="episode_outline"}),storyflowBloomBotMode:d.storyflowUiPhase==="workspace"?bs(d.storyflowLayoutTab):void 0,standaloneFilmMode:m}},...!e&&(()=>{var w;const d=Xs.current,m=qr({uiPhase:d.storyflowUiPhase,inEpisodeScriptContext:d.openFullView==="episode"||((w=d.bloomEditContext)==null?void 0:w.type)==="episode_outline"}),y=d.storyflowStandaloneFilmMode===!0||vr({standaloneFilmMode:d.storyflowStandaloneFilmMode,plannedEpisodeCount:d.plannedEpisodeCount,episodeDurationSeconds:d.episodeDurationSeconds,recentUserTexts:d.recentHomeUserTexts});if(!m&&!y)return{};const h={narrativePhase:d.narrativePhase,editFocus:mu(d.bloomEditContext),openFullView:d.openFullView,textTableSkillOn:d.textTableSkillOn,homepageTalkExtract:m,storyflowBloomBotMode:d.storyflowUiPhase==="workspace"?bs(d.storyflowLayoutTab):void 0,standaloneFilmMode:y},b=[yb(h)];return m&&(b.push(gf),b.push(bb)),{resolvedSystemOverride:b.filter(Boolean).join(` 520 521`)}})(),...Fl()?{getRetrievedContext:d=>oS(Qa.current,d,6)}:{},...ib(Gc.current)});return e?(Nn.current||(Nn.current=mf(void 0,{...o(Ai),operationType:"STORYFLOW_EPISODE_SCRIPT"})),Nn.current):(Cn.current||(Cn.current=mf(void 0,o(ji))),Cn.current)},[]),am=c.useCallback(()=>(Ri.current||(Ri.current=Ml(Tl,void 0,"STORYFLOW_ASSISTANT",{resolvedSystemOverride:Tl})),Ri.current),[]),lm=c.useCallback(()=>(Na.current||(Na.current=Ml(nu,void 0,"STORYFLOW_EPISODE_SCRIPT",{resolvedSystemOverride:nu})),Na.current),[]),td=c.useCallback(async e=>{const o=String(e||"").trim();if(!o)return null;try{const l=lm(),d=o.length>36e3?o.slice(o.length-36e3):o,{text:m}=await l.sendMessage(`${nu} 522 523# Input Data 524${d}`),y=iC(m);return y||null}catch{return null}},[lm]),rd=c.useCallback(e=>{const o=[...new Set(e.filter(Boolean))];o.length===0||typeof window>"u"||(Gn(new Set(o)),Os.current!=null&&window.clearTimeout(Os.current),Os.current=window.setTimeout(()=>{Gn(new Set),Os.current=null},900))},[]),Tt=c.useCallback((e,o="all",l)=>{const d=Xs.current,m=qr({uiPhase:d.storyflowUiPhase}),y=vr({standaloneFilmMode:d.storyflowStandaloneFilmMode,plannedEpisodeCount:d.plannedEpisodeCount,episodeDurationSeconds:d.episodeDurationSeconds}),h=m&&(l!=null&&l.userTextForIntent)&&!(l!=null&&l.manualChatBackfill)?G0(e,l.userTextForIntent,{currentEpisodeDurationSeconds:d.episodeDurationSeconds,projectName:d.projectName,logline:d.storyOutline.logline,fromAssistantDraft:(l==null?void 0:l.fromAssistantDraft)===!0,keepLabeledStory:(l==null?void 0:l.keepLabeledStory)===!0,keepCast:(l==null?void 0:l.keepCast)===!0,keepWorldFromDraft:(l==null?void 0:l.keepWorldFromDraft)===!0,keepSequenceBeats:Ou(e)}):e;if(!tr(h))return;const b=o==="all"||o==="outline",w=o==="all"||o==="world_bible",g=o==="all"||o==="assets",A=(o==="all"||o==="episode_board")&&(l==null?void 0:l.applyEpisodes)!==!1,j=[];let B=null;const _=h,C=ek();let R=te;if(o==="all"||b){const Y=vt(_.seriesTitle||_.title||"");if(Y&&!Bs(Y)&&C!=="title"){const ce=Y,he=m?Ud(ge,Yr.current.title):Wd(ge);ce!==ge&&he?(Xr(ce),ms("title","auto"),zs(null),j.push("title"),x&&t&&x(ce)):ce!==ge&&$n()&&!he&&ws(ge)&&zs(ce)}const F=m?Kn((l==null?void 0:l.userTextForIntent)||""):null,V=!!(F!=null&&F.plannedEpisodes),X=!!(F!=null&&F.episodeDurationSeconds);!y&&typeof _.plannedEpisodes=="number"&&_.plannedEpisodes>=1&&_.plannedEpisodes<=pr&&(m?V:!$n()||!Dr.episodeCount)&&(Nt(sn(_.plannedEpisodes)),Dt(null),j.push("episodes"),$n()||kt(he=>({...he,episodeCount:!0}))),!y&&typeof _.episodeDurationSeconds=="number"&&Number.isFinite(_.episodeDurationSeconds)&&(m?X||V&&te===Ji:!$n()||!Dr.episodeDuration)&&(R=We(_.episodeDurationSeconds),ar(R),gr(null),j.push("episodes"),$n()||kt(he=>({...he,episodeDuration:!0}))),_.dramaCategory&&oa.some(ce=>ce.id===_.dramaCategory)&&C!=="dramaCategory"&&(m?vf(rt,Yr.current.dramaCategory):!String(rt||"").trim())&&(di(_.dramaCategory),ms("dramaCategory","auto"),j.push("dramaCategory")),typeof _.dramaCustomNote=="string"&&_.dramaCustomNote.trim()&&!String(Yt||"").trim()&&to(_.dramaCustomNote.trim())}const T=(Y,F)=>m?vf(Y,Yr.current[F]):Jb(Y);let M=!1;if(b){const Y=vt(h.logline??""),F=vt(h.synopsis??""),V=C!=="logline"&&!!Y&&T(d.storyOutline.logline,"logline"),X=C!=="synopsis"&&!!F&&T(d.storyOutline.synopsis,"synopsis");M=m&&V&&String(d.storyOutline.logline||"").trim().length>=8&&Y!==String(d.storyOutline.logline||"").trim(),V&&(j.push("logline"),ms("logline","auto")),X&&(j.push("synopsis"),ms("synopsis","auto")),Rr(ce=>({logline:V?Y:ce.logline,synopsis:X?F:ce.synopsis}))}if(w){const Y=h.worldBible||{},F=["geography","timeline","rules","culture","coreConflict"],V={};for(const X of F){const ce=vt(String(Y[X]??""));
524C!==X&&ce&&T(String(d.worldBible[X]||""),X)&&(V[X]=ce,j.push(X),ms(X,"auto"))}Object.keys(V).length>0&&Us(X=>({geography:V.geography??X.geography,timeline:V.timeline??X.timeline,rules:V.rules??X.rules,culture:V.culture??X.culture,coreConflict:V.coreConflict??X.coreConflict}))}const W=h.characters||[];if(W.length>0&&(o==="all"||b||g)){const Y=W.map(F=>({name:vt(String((F==null?void 0:F.name)||"")),note:vt(String((F==null?void 0:F.note)||""))})).filter(F=>F.name&&Ss(F.name));if(Y.length!==0){const F=m&&Qb({existingCount:we.length,incomingCount:Y.length,source:Yr.current.characters,storySwitch:M,userSpecifiedCast:(l==null?void 0:l.userSpecifiedCast)===!0});!m&&!F&&Zb(we.map(X=>X.name),Y.map(X=>X.name))?Ia(Y):(Ia(null),xn(X=>F?qi([],Y):qi(X,Y)),B="characters",m&&ms("characters","auto"),j.push("characters"),Fe(X=>{if(!X.length)return X;const ce=Y.map(se=>({name:se.name,imgUrl:void 0}));if(!ce.length)return X;const he=[...X];return(!he[0].characterRefs||he[0].characterRefs.length===0)&&(he[0]={...he[0],characterRefs:ce}),he}))}}const q=h.episodes;if(Array.isArray(q)){const Y=q.flatMap(V=>(Array.isArray(V.scenes)?V.scenes:[]).map(X=>vt(String(X||""))).filter(Boolean)),F=q.flatMap(V=>(Array.isArray(V.props)?V.props:[]).map(X=>vt(String(X||""))).filter(Boolean));(Y.length||F.length)&&(xo(Y,F),Y.length&&B!=="characters"?B="scenes":F.length&&!B&&(B="props"))}if(m&&rd(j),B&&Ht(B),!A)return;if(Do()&&Array.isArray(h.episodes)&&h.episodes.some(F=>Array.isArray(F.sequences)&&F.sequences.some(V=>String((V==null?void 0:V.label)||"").trim()))){const F=j0(h,{standaloneFilmMode:y});let V=null,X=0,ce=[];if(Fe(he=>{var De;const se=[...he],Ke=Je=>{for(;se.length<=Je;)se.push({id:Cr(),title:y?"Film":`Episode ${se.length+1}`,summary:"",attribution:{userName:Z,withBloomBot:!0},durationMin:We(R)/60});return se[Je]};for(let Je=0;Je<(((De=F.episodes)==null?void 0:De.length)??0);Je+=1){const bt=F.episodes[Je];if(!Array.isArray(bt.sequences)||bt.sequences.length===0)continue;const Sr=y?0:Je,Zs=Ke(Sr),Mn=ku({jsonBeats:bt.sequences,standaloneFilmMode:y});if(Mn.length===0)continue;const Qe=Qf(Zs.generationUnits,Mn,{standaloneFilmMode:y,episodeIndex:Sr,totalMinutes:Zs.durationMin??R/60});se[Sr]={...Zs,generationUnits:Qe.units},X=Sr,ce=Qe.units,Qe.needsConfirm&&!V&&(V={episodeIndex:Sr,diff:Qe.diff})}return se}),Pa(V||null),be(he=>Jf(he,X,ce,se=>{const Ke=/^ep:(\d+):seq:(\d+)$/.exec(se);if(!Ke||Number(Ke[1])!==X)return null;const De=Number(Ke[2]);return ce.some(Je=>Je.index===De)?{id:se}:null})),j.push("episodes"),m&&rd(j),y)return}if(y)return;const G=h.episodes;if(Array.isArray(G)&&G.length>0){const Y=G.map((F,V)=>{const X=String(F.title||`Episode ${V+1}`).trim()||`Episode ${V+1}`,ce=String(F.summary||"").trim();if(!X&&!ce)return null;let he=Array.isArray(F.characterRefs)?F.characterRefs.map(se=>({name:String((se==null?void 0:se.name)||"").trim(),imgUrl:typeof(se==null?void 0:se.imgUrl)=="string"?se.imgUrl:void 0})).filter(se=>se.name):void 0;return(!he||he.length===0)&&V===0&&W.length>0&&(he=W.map(se=>({name:String((se==null?void 0:se.name)||"").trim(),imgUrl:void 0})).filter(se=>se.name)),{id:Cr(),title:X,summary:ce,attribution:{userName:Z,withBloomBot:!0},durationMin:We(R)/60,sceneCount:Ut(R),scenes:Array.isArray(F.scenes)?F.scenes.map(se=>String(se).trim()).filter(Boolean):void 0,props:Array.isArray(F.props)?F.props.map(se=>String(se).trim()).filter(Boolean):void 0,characterRefs:he!=null&&he.length?he:void 0}}).filter(Boolean);Y.length>0&&(Fe(F=>$n()?ew(F,Y,Cr):Fd(F,Y,Cr)),$r(0))}else W.length>0&&Fe(Y=>{if(!Y.length)return Y;const F=W.map(X=>({name:String((X==null?void 0:X.name)||"").trim(),imgUrl:void 0})).filter(X=>X.name);if(!F.length)return Y;const V=[...Y];return V[0]={...V[0],characterRefs:F},V})},[Z,ge,x,t,te,we,U.logline,Dr.episodeCount,Dr.episodeDuration,rt,Yt,n,rd,xo]),vo=c.useRef(0),rl=c.useCallback(async(e,o="all",l,d)=>{const m=e.trim();if(!(m.length<24))try{const y=l!=null&&l.stateless?Ml(Tl,void 0,"STORYFLOW_ASSISTANT",{resolvedSystemOverride:Tl}):am(),{text:h}=await y.sendMessage(I0(m,!!(l!=null&&l.stateless)));if(!ty(d,vo.current))return;const b=Lu(h);if(!tr(b)||!b||!ty(d,vo.current))return;const w=Gi(b,(l==null?void 0:l.userTextForCategory)||m,rt,{allowReplace:!!(l!=null&&l.stateless)&&Yr.current.dramaCategory!=="user",assistantText:m});if(!tr(w))return;Tt(w,o,{...l,userTextForIntent:l==null?void 0:l.userTextForCategory,fromAssistantDraft:(l==null?void 0:l.fromAssistantDraft)===!0,manualChatBackfill:(l==null?void 0:l.manualChatBackfill)===!0})}catch{}},[Tt,rt,am]),is=c.useCallback(e=>{requestAnimationFrame(()=>{const o=e==="home"?Ii.current:Yp.current;o&&(o.scrollTop=o.scrollHeight)})},[]),sl=c.useCallback((e,o)=>{e==="home"?ya(o):Qh(o)},[]),jr=c.useCallback(e=>{const o=mo.current[e];o.timerId!=null&&window.clearInterval(o.timerId),mo.current[e]={targetText:"",displayedText:"",timerId:null},sl(e,"")},[sl]);c.useEffect(()=>{if(!(ee||ze)||typeof window>"u")return;const o=ee?sC+5e3:nC,l=window.setTimeout(()=>{if(He.current=!1,re(!1),Wr(!1),ys.current=!1,qs(""),jr("home"),jr("episode"),ee){ht.current=!0;const d=qr({uiPhase:Be});ie(m=>[...m,{role:"assistant",text:d?Ye==="zh"?"è¿è½®çå¾
æ¶é´è¿é¿ï¼æå
å¸®ä½ è§£é¤è¾å
¥éå®ãä½ å¯ä»¥æ¥çææ
äºåæ¥ã":"This turn took too long, so I unlocked the input. You can keep sending the story.":Ye==="zh"?"è¿è½®çå¾
æ¶é´è¿é¿ï¼æå
å¸®ä½ è§£é¤è¾å
¥éå®ãè¯·ææ³æ³ç¼©çæä¸å¥é¢æ/主è§/ç®æ åå䏿¬¡ï¼BloomBot ä¼ç»§ç»å¸®ä½ æ´çã":"This turn took too long, so I unlocked the input. Please resend a shorter premise with genre, protagonist, and goal, and BloomBot will continue from there."}])}qr({uiPhase:Be})||H.warning(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.bloomBotLoadingWatchdogBody"))},o);return()=>window.clearTimeout(l)},[ee,ze,jr,n,Wr,Ye,Be]);const sd=c.useCallback(e=>{const o=mo.current[e];if(o){if(o.displayedText.length<o.targetText.length){const l=Math.min(o.targetText.length,o.displayedText.length+mC);o.displayedText=o.targetText.slice(0,l),sl(e,o.displayedText)}o.displayedText.length>=o.targetText.length&&o.timerId!=null&&(window.clearInterval(o.timerId),o.timerId=null)}},[sl]),nd=c.useCallback((e,o)=>{if(!o)return;const l=mo.current[e];l.targetText=o,l.timerId==null&&(l.timerId=window.setInterval(()=>
524sd(e),fC)),sd(e)},[sd]),cm=c.useRef(Re);c.useEffect(()=>{cm.current!==Re&&(cm.current=Re,Cn.current=null,Ri.current=null,ji.current=0,jr("home"),ko(""))},[Re,jr]);const Tn=c.useCallback((e,o,l)=>{Fe(d=>{const m=d[e];if(!m)return d;const y=Array.isArray(m.generationUnits)?m.generationUnits:[],w=(y.some(j=>j.index===o)?y:[...y,{index:o,label:String(m.title||"").trim()||(ke?`Scene ${o+1}`:`Sequence ${o+1}`),targetMinutes:Math.max(1,Math.round(We(te)/60)||1),beatSummary:String(m.summary||"").trim()||void 0,status:"pending"}]).map(j=>{if(j.index!==o)return j;const B=wy({unit:{...j,descriptiveScript:l},episodeTitle:m.title,episodeSummary:m.summary,standaloneFilmMode:ke}),_=B?Zd(l,B):l,R=String(j.descriptiveScript||"").trim()!==String(_||"").trim();return{...j,descriptiveScript:_,status:"generated",canonStale:!1,detailConfirmed:R?!1:!!j.detailConfirmed}}),g=xu(w),A=[...d];return A[e]={...m,generationUnits:w,detailedScript:g,detailedScriptBloomDraft:void 0,scriptFormat:"descriptive"},A}),Ze.current({silent:!0})},[ke,te]),nl=c.useCallback(()=>{const e=ra(ve),o=ny(J);return!e||!o?(H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.proSimpleSitApplyChatFailed")),!1):(Tn(e.episodeIndex,e.unitIndex,o),H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.proSimpleSitApplyChatSuccess")),!0)},[ve,J,Tn,n]),od=c.useCallback(()=>{const e=ra(ve);if(!e)return;const o=P[e.episodeIndex];if(!o)return;const d=(Array.isArray(o.generationUnits)?o.generationUnits:[]).find(y=>y.index===e.unitIndex),m=String((d==null?void 0:d.descriptiveScript)||o.descriptiveScript||o.detailedScript||"").trim();if(!m){H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.proSimpleConfirmNeedScript"));return}Fe(y=>{const h=y[e.episodeIndex];if(!h)return y;const b=Array.isArray(h.generationUnits)?h.generationUnits:[],g=b.some(j=>j.index===e.unitIndex)?b.map(j=>j.index===e.unitIndex?{...j,descriptiveScript:String(j.descriptiveScript||m),detailConfirmed:!0,status:"generated"}:j):[...b,{index:e.unitIndex,label:String(h.title||"").trim()||(ke?`Scene ${e.unitIndex+1}`:`Sequence ${e.unitIndex+1}`),targetMinutes:Math.max(1,Math.round(We(te)/60)||1),beatSummary:String(h.summary||"").trim()||void 0,descriptiveScript:m,detailConfirmed:!0,status:"generated"}],A=[...y];return A[e.episodeIndex]={...h,generationUnits:g,detailedScript:xu(g),scriptFormat:"descriptive"},A}),Ze.current({silent:!1}),p==null||p().catch(()=>{}),H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.proSimpleConfirmSuccess"))},[ve,P,ke,te,p,n]);c.useEffect(()=>()=>{const e=mo.current.home.timerId,o=mo.current.episode.timerId;e!=null&&window.clearInterval(e),o!=null&&window.clearInterval(o),Cs.current!=null&&(window.clearTimeout(Cs.current),Cs.current=null)},[]);const lt=c.useCallback(async(e,o)=>{var M,W;yt.current=!1;const l=e.trim();if(!l)return;const d=typeof(o==null?void 0:o.storyflowSetupScriptChars)=="number"&&Number.isFinite(o.storyflowSetupScriptChars)&&o.storyflowSetupScriptChars>0?Math.floor(o.storyflowSetupScriptChars):null,m=Xs.current,y=m.openFullView==="episode"||((M=m.bloomEditContext)==null?void 0:M.type)==="episode_outline";if(!y&&ps.current)return;y||(ht.current=!1);const h=((W=m.bloomEditContext)==null?void 0:W.type)==="episode_outline"?m.bloomEditContext.episodeIndex:m.episodeOutlineEditingIndex??m.selectedEpisodeIndex??0;if(y?yo.current||ys.current:He.current)return;if(y||(vo.current=Z0(vo.current)),!y){const q=Oy(l,J);q&&q!==ge&&(Xr(q),ms("title","user"),zs(null),x&&t&&x(q))}const b=[],w=Hv(l,z),g=y?w==="zh"?"Reply in Simplified Chinese for every assistant response in this modal (shot blocks, blueprint prose, and any ledger lines you output). Do not mix in English headings or paragraphs unless the user explicitly requests bilingual output.":"Reply in English for every assistant response in this modal (shot blocks, blueprint prose, and any ledger lines you output). Do not mix in Chinese headings or paragraphs unless the user explicitly requests bilingual output.":"",A=y?"":w==="zh"?"Reply in Simplified Chinese for this turn unless the user explicitly asks for another language. Keep the whole answer in Chinese only;
524 do not mix English section headings.":"Reply in English for this turn unless the user explicitly asks for another language. Keep the whole answer in English only; do not mix Chinese section headings.",j=m.storyflowUiPhase==="workspace"&&!y?bs(m.storyflowLayoutTab):null,B=j&&!y?JS({mode:j,layoutTab:m.storyflowLayoutTab,selectedUnit:(()=>{var X;const q=/^ep:(\d+):seq:(\d+)$/.exec(String(m.hierarchySelectedId||""));if(!q)return null;const G=Number(q[1]),Y=Number(q[2]),F=m.seasonEpisodes[G],V=(X=F==null?void 0:F.generationUnits)==null?void 0:X.find(ce=>ce.index===Y);return V?{episodeIndex:G,unitIndex:Y,unitLabel:String(V.label||"").trim()||`Seq ${Y+1}`,beatSummary:V.beatSummary,episodeTitle:F==null?void 0:F.title}:null})()}):"",_=b.length>0?`Before writing detailed episode screenplay, fill missing STORYFLOW foundations in this turn. 525Missing now: 526- ${b.join(` 527- `)} 528 529Return practical updates that can be mapped into story outline, world bible, episode list, and character profiles when relevant.`:"",C=(()=>{if(!y)return"";const q=m.seasonEpisodes[h]||wi.current[h];if(!q)return"";const G=Rt(q),Y=zt(G),F=Fn(Y.scriptBody),X=[...G.matchAll(/\bSHOT\s*0*(\d{1,3})\b/gi)].reduce((De,Je)=>{const bt=Number(Je[1]||0);return Number.isFinite(bt)?Math.max(De,bt):De},0),ce=Math.max(F.lastMax,F.count,X,ur.current.episodeIndex===h?ur.current.written:0),he=We(typeof q.durationMin=="number"&&q.durationMin>0?Math.round(q.durationMin*60):te),se=typeof q.sceneCount=="number"&&q.sceneCount>0?Math.round(q.sceneCount):Ut(he),Ke=Math.max(1,ce+1);return ur.current={episodeIndex:h,written:ce,target:se},`Continuation anchor (must follow before writing): 530- Current episode: Ep. ${String(h+1).padStart(2,"0")} "${q.title||"(untitled)"}" 531- Written shots now: ${ce}/${se>0?se:"?"} 532- Continue strictly from SHOT ${String(Ke).padStart(2,"0")} 533- Never restart from SHOT 01 or switch to another episode`})(),T=[y?`You are replying inside the Episode edit modal (not homepage). 534Do NOT mention unavailable UI/actions such as "Continue to story workspace" or homepage buttons. 535Scope lock: write ONLY the current episode in this modal. Do NOT draft next episode or any other episode. 536If cross-episode impact exists, write it under "CONTINUITY NOTES" as follow-up notes for later episodes (do not rewrite them now). 537Formatting lock: output plain text shot blocks only. Do NOT output markdown table rows or code fences. 538Do NOT output JSON, YAML, XML, or structured tags (including ${Wn} or legacy [[GREENLIGHT_STRUCTURE_JSON]]). 539Do NOT output any JSON code snippets, including [TEXT_SHOT_LIST_JSON] blocks, payload objects, or code-fenced data. 540If the user prompt shows progress like "written shots: X/Y" or "Start strictly from SHOT", you are in a continuation pass: do NOT begin your reply with a line starting "EPISODE BLUEPRINT"; append the next shots only until Y is reached. 541Only after screenplay shots actually reach the target count in the user prompt, end with: "EPISODE COMPLETE. You can close this modal and click GO TO Workflow." Until then, do not treat the episode as finished. 542Before target shots are fully completed, never output the phrase "æ¬éç»æ" (or equivalents like "æ¬éå·²å ¨é¨å®æ"). 543Do NOT append clickable options for this modal.`:"",C,_,B,g,A,l].filter(
543Boolean).join(` 544 545`);if(y?Ai.current+=1:ji.current+=1,y)yn(q=>{const G=q[h]??[];return{...q,[h]:[...G,{role:"user",text:l}]}});else{ie(V=>[...V,{role:"user",text:l}]);const q=SC(Se);if(!(o!=null&&o.skipStoryflowFastPath)&&q&&!qr({uiPhase:m.storyflowUiPhase,inEpisodeScriptContext:y})){const V=w==="zh"?vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,recentUserTexts:J.filter(X=>X.role==="user").map(X=>String(X.text||""))})?"ä½ ç°å¨åªå·®ãè§è§é£æ ¼ãè¿ä¸é¡¹ã宿飿 ¼éæ©åï¼è¯·ç»§ç»å¨å¯¹è¯ä¸å®åæ¬ç大纲ä¸è§è²ï¼å¾ç请ç¨åå¨å³ä¾§ Tab ç¹å»å¡ç设计ã":"ä½ ç°å¨åªå·®âè§è§é£æ ¼âè¿ä¸ä¸ªé¡¹ç®ã宿飿 ¼éæ©åï¼è¯·ç»§ç»å¨å¯¹è¯ä¸å®å大纲ä¸åéï¼å¾ç请ç¨åå¨å³ä¾§ Tab ç¹å»å¡ç设计ã":vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,recentUserTexts:J.filter(X=>X.role==="user").map(X=>String(X.text||""))})?"You only have one missing item: visual style. Finish style selection, then keep refining this filmâs outline and characters in chat. Design images later from the right-hand tabs.":"You only have one missing item: visual style. Finish style selection, then keep refining the outline and episodes in chat. Design images later from the right-hand tabs.";ie(X=>[...X,{role:"assistant",text:V}]),is("home");return}const G=qr({uiPhase:m.storyflowUiPhase,inEpisodeScriptContext:y}),Y=vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:[...J.filter(V=>V.role==="user").map(V=>String(V.text||"")),l]})||Xe&&$d({descriptiveScriptV1:!0,storyflowStandaloneFilmMode:ke,plannedEpisodeCount:Ce,recentUserTexts:[...J.filter(V=>V.role==="user").map(V=>String(V.text||"")),l]}),F=yh(l);if(G||(du(l,{setStoryflowStandaloneFilmMode:Jr,setPlannedEpisodeCount:Nt,setPlannedEpisodeCountDraft:Dt,setEpisodeDurationSeconds:ar,setEpisodeDurationMinutesDraft:gr,setStoryflowPlanAck:kt}),Xe&&$d({descriptiveScriptV1:!0,storyflowStandaloneFilmMode:ke,plannedEpisodeCount:Ce,recentUserTexts:[...J.filter(V=>V.role==="user").map(V=>String(V.text||"")),l]})&&(Jr(!0),Nt(1),Dt(null),kt(V=>({...V,episodeCount:!0})))),G){du(l,{setStoryflowStandaloneFilmMode:Jr,setPlannedEpisodeCount:Nt,setPlannedEpisodeCountDraft:Dt,setEpisodeDurationSeconds:ar,setEpisodeDurationMinutesDraft:gr,setStoryflowPlanAck:kt}),!vs(l)&&vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:[...J.filter(se=>se.role==="user").map(se=>String(se.text||"")),l]})&&(Jr(!0),Nt(1),Dt(null),kt(se=>({...se,episodeCount:!0})));const V=fu(m,Gt,Wt);(se=>{!se||!tr(se)||Tt(Gi(se,l,rt,{allowReplace:Yr.current.dramaCategory!=="user"}),V,{applyEpisodes:Vd({bloomBotMode:j??bs(m.storyflowLayoutTab),inEpisodeScriptContext:!1,missingFoundationCount:b.length}),userTextForIntent:l})})(Kn(l,{defaultDurationSeconds:vs(l)?void 0:te===Ji?90:void 0}));const ce=aa(l);ce&&Tt({dramaCategory:ce},V,{applyEpisodes:!1,userTextForIntent:l});const he=ec(l);he.length>0&&Tt({characters:he},V,{applyEpisodes:!1,userTextForIntent:l,userSpecifiedCast:!0,keepCast:!0})}if(!(o!=null&&o.skipStoryflowFastPath)&&!F){if(!G){const X=zo(l);if(X&&tr(X)){const ce=fu(m,Gt,Wt);Tt(X,ce,{applyEpisodes:Vd({bloomBotMode:j??bs(m.storyflowLayoutTab),inEpisodeScriptContext:!1,missingFoundationCount:b.length})})}}const V=Gf({message:l,locale:w,uiPhase:m.storyflowUiPhase,readiness:Se,episodeCount:Ce,selectedEpisodeNumber:Math.max(1,(m.selectedEpisodeIndex??0)+1),hasEpisodes:m.seasonEpisodes.length>0,hasDashboard:!!m.dashboardData,talkExtractActive:G,standaloneFilmMode:Y,bloomBotMode:j??void 0,layoutTab:m.storyflowLayoutTab});if(V){ie(X=>[...X,{role:"assistant",text:V.text}]),is("home");return}}}y?(ys.current=!0,qs(l),jr("episode"),Wr(!0)):(jr("home"),He.current=!0,re(!0)),is(y?"episode":"home");try{const q=im(y),G=y?"episode":"home",Y={onDelta:Me=>{nd(G,Me),is(y?"episode":"home")},...d!=null&&!y?{storyflowSetupScriptChars:d}:{}},F=q.sendMessage(T,Y);let{text:V,truncated:X}=await F;const ce=!y&&qr({uiPhase:m.storyflowUiPhase,inEpisodeScriptContext:!1});if(ce&&!String(V||"").trim()&&!/^(?:ä½ å¥½|å¨|hi|hello)\b/i.test(l)){jr("home");try{const Me=await q.sendMessage(T,{...Y,onDelta:Zt=>{nd("home",Zt),is("home")}});String(Me.text||"").trim()&&(V=Me.text,X=Me.truncated)}catch{}}const he=Cl(V);let se=he.cleanedText;y||(se=Wk({reply:se,truncated:!!X,storyArcReady:Se.storyArcReady,worldBibleReady:Se.worldBibleReady,locale:Ye==="zh"?"zh":"en"}));const Ke=X&&y?`${se} 546 547[NEXT STEP HINT] 548Output was truncated by length. Continue from the last unfinished sce
548ne in the next turn.`:se,De=Cw(Ql(Ke)),Je=y?Ky(De.text):De.text,bt=ur.current,Sr=y&&bt.episodeIndex===h&&bt.target>0&&bt.written>=bt.target,Zs=y&&!Sr?yu(Je):Je,Mn=y&&(Ly(Je)||CC(De.text)||HC(De.text)),Qe={...De,text:Mn?"[FORMAT FILTER] JSON output was blocked. Please continue in plain-text shot blocks only.":Zs,optionChips:y?void 0:De.options};if(ce&&!String(Qe.text||"").trim()){const Me=w==="zh"?"åææ²¡ææ¶å°å®æ´åå¤ã请åå䏿¬¡ï¼è¥ä½ å·²åè¿è§æ ¼åæ äºï¼å¯ç´æ¥ç²è´´ä¸ä¸å¥ã":"I did not receive a full reply. Please send again, or paste your story and episode spec in one message.";ie(Zt=>[...Zt,{role:"assistant",text:Me}]),is("home");return}let Ae=Qe.text;const Ue=m.seasonEpisodes[h],mt=[Ue==null?void 0:Ue.detailedScript,Ue==null?void 0:Ue.detailedScriptBloomDraft].map(Me=>String(Me||"").trim()).filter(Boolean).join(` 549 550`),Jt=!1,Qt=fu(m,Gt,Wt),xs={applyEpisodes:Vd({bloomBotMode:j??bs(m.storyflowLayoutTab),inEpisodeScriptContext:y,missingFoundationCount:b.length})&&(!y||b.length>0),userTextForIntent:l},en=!y&&ab({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:[...J.filter(Me=>Me.role==="user").map(Me=>String(Me.text||"")),l],recentAssistantTexts:[Qe.text,...J.filter(Me=>Me.role==="assistant").map(Me=>String(Me.rawAssistantReply||Me.text||""))]}),_d=!y&&(ke||en)?lb(X&&y?`${Ae} 551 552[NEXT STEP HINT] 553Output was truncated by length. Continue from the last unfinished scene in the next turn.`:Ae,w):X&&y?`${Ae} 554 555[NEXT STEP HINT] 556Output was truncated by length. Continue from the last unfinished scene in the next turn.`:Ae,Gx=Xd(_d,w),Ui=Zf(Qe.text);(Ui.scenes.length||Ui.props.length)&&(xo(Ui.scenes,Ui.props),an&&!y&&Ko(Qe.text).length===0&&(Ui.scenes.length?Ht("scenes"):Ht("props")));const tf=!an&&!y&&m.storyflowUiPhase==="immersive"&&Se.allFoundationReady&&!qr({uiPhase:m.storyflowUiPhase,inEpisodeScriptContext:y}),Yx=n("page.storyflow.foundationSetupCompleteChatBody");en&&ca(Qe.text)&&(Jr(!0),Nt(1),ar(We(ca(Qe.text),!0)),kt(Me=>({...Me,episodeCount:!0,episodeDuration:!0})));const Bd={role:"assistant",text:tf?Yx:Gx,rawAssistantReply:Ke,optionChips:cb(tf?[n("page.storyflow.continueStoryWorkspace")]:Qe.options,en||ke===!0)};if(y)yn(Me=>{const Zt=Me[h]??[];return{...Me,[h]:[...Zt,Bd]}});else if(ie(Me=>[...Me,Bd]),en&&!Xe){const Me=py([...J,{role:"user",text:l},Bd]);Me.trim()&&Fe(Zt=>{const Lo=We(te),Hi=Zt[0]??{id:Cr(),title:(ge||"").trim()||n("page.storyflow.filmDetailedScriptSection"),summary:String(U.synopsis||U.logline||"").trim(),attribution:{userName:Z,withBloomBot:!0},durationMin:Lo/60,sceneCount:Ut(Lo)},Od=[...Zt];return Od[0]={...Hi,detailedScript:Me,detailedScriptBloomDraft:void 0,durationMin:Lo/60},Od})}is(y?"episode":"home");const Vx=!(y&&b.length===0);let Wi=!1,xl=!1;const kr=qr({uiPhase:m.storyflowUiPhase,inEpisodeScriptContext:y}),Ln=wh(l),Mo=kr&&vh({userTurnKind:Ln.kind,assistantText:Qe.text,userText:l}),Md=kr&&(Sh(Qe.text)||Ln.kind==="world_build"),Ld=kr&&Ch(Qe.text);if(Vx){const Me={allowReplace:kr&&Yr.current.dramaCategory!=="user",assistantText:Qe.text},Zt=Xs.current,Lo=Nu({projectName:Zt.projectName,logline:Zt.storyOutline.logline});if(kr){const Ir={...xs,fromAssistantDraft:!0,keepLabeledStory:Mo,keepCast:Ld,keepWorldFromDraft:Md};if(Mo){const ot=ey(Qe.text,{proseFallback:Ln.kind==="premise"&&!kh(l)});ot&&(Tt(Gi(ot,l,rt,Me),Qt,Ir),Wi=!0,(ot.seriesTitle||ot.title||"").trim()&&(xl=!0))}if(Md){const ot=zo(Qe.text);ot!=null&&ot.worldBible&&tr({worldBible:ot.worldBible})&&Tt({worldBible:ot.worldBible},Qt,Ir)}else if(Ln.kind==="world_build"){const ot=zo(Qe.text);ot!=null&&ot.worldBible&&tr({worldBible:ot.worldBible})&&Tt({worldBible:ot.worldBible},Qt,{...Ir,keepWorldFromDraft:!0})}if(Ld&&!Mo){if(!(Ln.kind==="world_build"&&!Lo&&Ko(l).length===0)){const rf=Ko(Qe.text);rf.length>0&&Tt({characters:rf},Qt,Ir)}}else if(Mo){const ot=Ko(Qe.text);ot.length>0&&Tt({characters:ot},Qt,Ir)}}else{const Ir=tr(he.payload)?he.payload:null;if(Ir)Tt(Gi(Ir,l,rt,Me),Qt,xs),Wi=!0,(Ir.seriesTitle||Ir.title||"").trim()&&(xl=!0);else{const ot=zo(Qe.text);ot&&tr(ot)&&(Tt(Gi(ot,l,rt,Me),Qt,xs),Wi=!0,(ot.seriesTitle||ot.title||"").trim()&&(xl=!0))}}const Hi=f0(Qe.text);if(Hi&&tr({worldBible:Hi})&&Tt({worldBible:Hi},Qt,xs),Q0({flagActive:kr,structureAppliedThisTurn:Wi,skipBecauseWatchdogOrFailed:ht.current})&&q0({flagActive:kr,userTurnKind:Ln.kind,assistantText:Qe.text,canApplyWorldBible:Lo})){const Ir=vo.current,ot=kr?A0([...J,{role:"user",text:l},{role:"assistant",text:Qe.text}]):Qe.text;kr&&Yn(!0),rl(ot,Qt,kr?{...xs,stateless:!0,userTextForCategory:l,fromAssistantDraft:!0,keepLabeledStory:Mo,keepCast:Ld,keepWorldFromDraft:Md}:xs,Ir).finally(()=>{Ir===vo.current&&Yn(!1)})}}if(!y&&an&&ok({bloomBotMode:j??bs(m.storyflowLayoutTab),inEpisodeScriptContext:y,unifiedShellWorksp
556ace:an,hierarchySelectedId:m.hierarchySelectedId,assistantText:Qe.text||Ke})){const Me=ra(m.hierarchySelectedId),Zt=Du(Qe.text||Ke);Me&&Zt&&Tn(Me.episodeIndex,Me.unitIndex,Zt)}if((!Wi||kr&&!xl&&Ud(m.projectName,Yr.current.title))&&!(kr&&!Ln.allowStoryFields&&!Mo)){const Me=EC(Qe.text||he.cleanedText||V),Zt=kr?Ud(m.projectName,Yr.current.title):Wd(m.projectName);Me&&!Bs(Me)&&Me!==m.projectName&&Zt?(Xr(Me),kr&&ms("title","auto"),zs(null),x&&t&&x(Me)):Me&&!Bs(Me)&&Me!==m.projectName&&$n()&&!Zt&&ws(m.projectName)&&zs(Me)}}catch(q){yt.current=!0;const G=q instanceof Error?q.message:n("page.storyflow.requestFailedBody"),Y=String(G||"").toLowerCase(),F=n("page.storyflow.requestFailedBody");G===F||Y.includes("not authenticated")||Y.includes("session expired")||Y.includes("timeout")||Y.includes("timed out")||Y.includes("failed to fetch")||Y.includes("networkerror")||Y.includes("connection closed")||Y.includes("http 5")||Y.includes("service unavailable");const X=Bt(G);H.error(n("page.storyflow.toastTitleBloomBot"),X);const ce={role:"assistant",text:y?`${n("page.storyflow.episodeTurnFailedPrefix")}${X}`:`${n("page.storyflow.assistantErrorPrefix")}${X}`};y?yn(he=>{const se=he[h]??[];return{...he,[h]:[...se,ce]}}):ie(he=>[...he,ce]),is(y?"episode":"home")}finally{jr(y?"episode":"home"),y?(ys.current=!1,qs(""),Wr(!1)):(He.current=!1,re(!1))}},[Wr,im,is,Wt,Gt,Tt,rl,x,t,ge,at,td,te,J,rt,n,nd,jr,z,pn,xo,Tn]),Co=c.useCallback(e=>{Ws(e);const o=Ye,l=Gv(e,o),m=Uv(o,e==="outline"?"page.storyflow.storyOutlineStarterPrompt":e==="world_bible"?"page.storyflow.worldBibleStarterPrompt":e==="episode_board"?"page.storyflow.optimizeSeasonPrompt":"page.storyflow.assetsStarterPrompt"),y=Xs.current,h=Gf({message:l,locale:o,uiPhase:y.storyflowUiPhase,readiness:Se,episodeCount:Ce,selectedEpisodeNumber:Math.max(1,(y.selectedEpisodeIndex??0)+1),hasEpisodes:y.seasonEpisodes.length>0,hasDashboard:!!y.dashboardData,bloomBotMode:y.storyflowUiPhase==="workspace"?bs(y.storyflowLayoutTab):void 0,layoutTab:y.storyflowLayoutTab}),b=[m.trim(),h==null?void 0:h.text.trim()].filter(Boolean).join(` 557 558`);ie(w=>[...w,{role:"user",text:l},{role:"assistant",text:b}]),is("home")},[Ce,is,Ye,Se]),dm=c.useCallback(e=>{Co(e),os("guided_step_prompt",{step:e})},[Co,os]);c.useEffect(()=>{Be==="immersive"||Be==="workspace"||(el.current=!1,tl.current=!1)},[Be]),c.useEffect(()=>{Vs||(tl.current=!1)},[Vs]),c.useEffect(()=>{if(ha==null||!ha.trim())return;const e=ha.trim(),o=ga.current!=null?ga.current:ff(e);ga.current=null,Ds(null),lt(e,{storyflowSetupScriptChars:o})},[ha,lt]);const um=c.useCallback(e=>{const o=typeof t=="string"?t.trim():"";if(!o)return;const l=e.map(d=>({role:d.role,text:d.text,rawAssistantReply:d.rawAssistantReply,optionChips:d.optionChips}));cr(wk(o,l))},[t]),pm=c.useCallback(()=>{if(_h(J)&&um(J),fr(null),Ft(!1),Re==="episode_unit")if(ve){const e=ve;fe(o=>({...o,[e]:[]}))}else Mr([]);else $t([]);ko(""),Ds(null),pn(!1),fn(Pl),qt(null),He.current=!1,re(!1),Wr(!1),ys.current=!1,qs(""),Gs.current=!0,qa(!1),ji.current=0,Ai.current=0,Cn.current=null,Nn.current=null,Na.current=null,zc.current=null,Kc.current=null,Ri.current=null,jr("home"),jr("episode")},[J,um,jr,Wr,Re,ve]),id=c.useCallback(e=>{const o={dramaCategory:ma,totalEpisodes:fa,durationSeconds:rc,protagonistGoal:sc,mainObstacle:nc};requestAnimationFrame(()=>{var l;return(l=o[e].current)==null?void 0:l.focus()})},[]),ad=c.useCallback(e=>{const o=String(e||"").trim();if(!o)return null;const l=[gC,xC];for(const d of l)for(const[m,y]of Object.entries(d))if(o===y)return m;return null},[]),ld=c.useCallback(async e=>{const o=String(e||"").trim().toLowerCase();if(ik(e)){nl();return}const l=n("page.storyflow.proSimpleSaveUnit").trim().toLowerCase();if(o===l||o==="确认"||o==="confirm"||o==="confirm this unit"){od();return}const d=n("page.storyflow.foundationReadyReviewTabsChip"),m=n("page.storyflow.foundationReadyContinueEpisodesChip",{episodesTab:Es});if(e===d){ue("outline"),be(_r);return}if(e===m){xr.current=!1,be(null),ue("episodes");return}if(o==="continue to story workspace"||o==="ç»§ç»è¿å ¥æ äºå·¥ä½åº"||o==="ç»§ç»è®¡å ¥æ äºå·¥ä½åº"||o==="continue with episode outlines"||o==="ç»§ç»å®ååé大纲"){Aa("workspace"),Ht("outline");return}if(ad(e)){lt(e);return}const h=Oy(e,J);h&&h!==ge&&(Xr(h),ms("title","user"),zs(null),x&&t&&x(h)),du(e,{setStoryflowStandaloneFilmMode:Jr,setPlannedEpisodeCount:Nt,setPlannedEpisodeCountDraft:Dt,setEpisodeDurationSeconds:ar,setEpisodeDurationMinutesDraft:gr,setStoryflowPlanAck:kt});const b=tw(J,e)?rw(e,Ye):e;await lt(b)},[nl,od,id,ad,lt,ge,J,Ye,x,t,n,Es]);c.useCallback(async()=>{var R;const e=mn,o=Number(e.totalEpisodes),l=lu(String(e.durationSeconds)),d=Number.isFinite(o)&&o>0,m=l!=null,y=!!e.dramaCategoryId,h=e.dramaCategoryId!=="custom"||!!(e.dramaCustomNote||"").trim(),b=Ye,w=b==="zh"?bC:wC,g=[!y||!h?{field:"dramaCategory",label:w.dramaCategory}:null,d?null:{field:"totalEpisodes",label:w.totalEpisodes},m?null:{field:"durationSeconds",label:w.durationSeconds},e.protagonistGoal.trim()?null:{field:"protagonistGoal",label:w.protagonistGoal},e.mainObstacle.trim()?null:{field:"mainObstacle",label:w.mainObstacle}].filter(T=>!!T);if(g.length>0){id(g[0].field),H.warning(b==="zh"?"请å è¡¥å ¨å¡«ç©ºé¡¹":"Please complete the blanks first",b==="zh"?`è¿ç¼ºï¼${g.map(T=>T.label).join("ã")}`:`Missing: ${g.map(T=>T.label).join(", ")}`);return}const A=sn(o),j=cu(l),B=e.dramaCategoryId;Yd(B,b);const _=(e.dramaCustomNote||"").trim();Nt(A),ar(j),kt(T=>({...T,episodeCount:!0,episodeDuration:!0})),di(B),to(B==="custom"?_:"");const C=Yv({dramaCategoryId:B,dramaCustomNote:_,totalEpisodes:A,durationSeconds:j,protagonistGoal:e.protagonistGoal.trim(),mainObstacle:e.mainObstacle.trim(),locale:b});Tt(C,"all",{applyEpisodes:!1}),(R=C.logline)!=null&&R.trim()&&Rr(T=>({...T,logline:T.logline.trim()||C.logline.trim()})),await lt(Vv[b]),yt.current||(pn(!1),fn(Pl))},[Tt,id,lt,Ye,mn]),c.useCallback(async()=>{const e=mn,o=Number(e.totalEpisodes),l=lu(String(e.durationSeconds)),d=Number.isFinite(o)&&o>0?sn(o):dC,m=l!=null?cu(l):uC,y=!!e.dramaCategoryId,h=Ye,b=y?e.dramaCategoryId:null,w=b?Yd(b,h):"",g=(e.dramaCustomNote||"").trim();b&&(di(b),to(b==="custom"?g:"")),Nt(d),ar(m),kt(j=>({...j,episodeCount:!0,episodeDuration:!0}));const A=Kv({locale:h,hasCategory:y,categoryLabel:w,isCustomCategory:b==="custom",customNote:g,totalEpisodes:d,durationSeconds:m,draft:e});await lt(A,{skipStoryflowFastPath:!0}),yt.current||(pn(!1),fn(Pl))},[lt,Ye,mn]);const $g=c.useCallback(e=>{const o=e.target.files;if(!(o!=null&&o.length))return;const l=o[0],d=l.name.toLowerCase(),m=l.type.startsWith("image/"),y=l.type.startsWith("video/"),h=/\.docx$/i.test(d),b=l.type.startsWith("text/")||/\.(txt|md)$/i.test(d);h||b?(async()=>{let w="";if(b&&!h)try{w=await l.text()}catch{H.warning(n("page.scriptDocument.documentParseFailedTitle"),n("page.scriptDocument.documentParseFailedBody"));return}else{const A=await th(l);if(A.ok===!1){A.code==="legacy_binary_doc"?H.info(n("page.scriptDocument.legacyBinaryDocTitle"),n("page.scriptDocument.legacyBinaryDocBody")):H.warning(n("page.scriptDocument.documentParseFailedTitle"),n("page.scriptDocument.documentParseFailedBody"));return}w=A.text}const g=w.length>48e3?`${w.slice(0,48e3)} 559${Ye==="zh"?"â¦ï¼å·²æªæï¼":"â¦(truncated)"}`:w;lt(Ye==="zh"?`è¿æ¯æ¬ç³»åçåèææ¬ï¼ 560 561--- 562${g} 563---`:`Here is reference text for the series: 564 565--- 566${g} 567---`),H.success(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.fileSentAsMessage"))})():m?(lt(Ye==="zh"?`ãåèæä»¶ï¼${l.name}ãå¯éçè§è§åèï¼ä¾æ¬ç³»å对è¯ä½¿ç¨ã`:`[Reference file: ${l.name}] Optional visual reference for this series conversation.`),H.success(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.referenceSent"))):y?(lt(Ye==="zh"?`ãåèè§é¢ï¼${l.name}ãå¯éçè§é¢åèï¼ä¾æ¬ç³»å对è¯ä½¿ç¨ã`:`[Reference video: ${l.name}] Optional video reference for this series conversation.`),H.success(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.referenceSent"))):H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.supportedFileTypesToast")),e.target.value=""},[lt,n,Ye]);c.useCallback(()=>{Ht("characters")},[]);const cd=c.useCallback(()=>
567{if(ft)return;const e=So.trim();!e||ee||(ko(""),lt(e))},[So,ee,lt,ft]),Fg=c.useCallback(e=>{const o=e.nativeEvent;e.key==="Enter"&&o.isComposing||e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),cd())},[cd]);c.useCallback(()=>{mc(!1);try{const e={v:1,savedAt:new Date().toISOString(),sourceProjectName:ge,storyOutline:{logline:U.logline,synopsis:U.synopsis},worldBible:{...pe},seasonEpisodes:P.map(o=>{var l;return{title:o.title,summary:o.summary,characterRefs:(l=o.characterRefs)==null?void 0:l.map(d=>({name:d.name})),scenes:o.scenes?[...o.scenes]:void 0,props:o.props?[...o.props]:void 0}}),dashboardData:Q};typeof window<"u"&&sessionStorage.setItem(Cf,JSON.stringify(e))}catch{}t?jp(!0):u==null||u()},[ge,U,pe,P,Q,t,u]);const Dg=c.useCallback(()=>{Ps.flushSync(()=>{Ta(!1)}),!kw()&&!Bf()&&Ta(!0)},[]),Ug=c.useCallback(()=>{Ta(!1),vw()},[]);c.useCallback(e=>{Fe(o=>{const l=Math.max(0,Math.min(o.length-1,e-1));return $r(l),oi(null),or(d=>(d==null?void 0:d.type)==="episode_outline"?null:d),qt(null),o})},[]);const dd=c.useCallback(e=>{$r(e),oi(null),or(o=>(o==null?void 0:o.type)==="episode_outline"?null:o),qt(null)},[]),Wg=c.useCallback((e,o)=>{Fe(l=>l.map((d,m)=>m===e?{...d,summary:o}:d))},[]),ud=c.useCallback(()=>{Fe(e=>{const o=e.length+1,l={id:`ep-${Date.now()}`,title:`Episode ${o}`,summary:"",attribution:{userName:Z,withBloomBot:!1},durationMin:We(te)/60,sceneCount:Ut(te)},d=[...e,l];return $r(d.length-1),d})},[Z,te]),pd=c.useCallback(()=>{Co("episode_board"),os("guided_step_prompt",{step:"episode_board",source:"optimize_button"})},[Co,os]),md=c.useCallback(async()=>{var B,_,C;if(Ur)return;const e=J.filter(R=>R.role==="assistant");let o=null,l=-1;for(let R=e.length-1;R>=0;R--){const T=e[R],M=[String(T.rawAssistantReply||""),String(T.text||"")].filter(W=>W.trim().length>0);for(const W of M){const G=Cl(W).payload;if(!tr(G))continue;const Y=Array.isArray(G.episodes)?G.episodes.length:0,F=Array.isArray(G.characters)?G.characters.length:0,V=G.worldBible||{},X=[V.geography,V.timeline,V.rules,V.culture,V.coreConflict].filter(he=>String(he||"").trim().length>0).length,ce=(String(G.logline||"").trim()?6:0)+(String(G.synopsis||"").trim()?6:0)+X*3+Y*3+F*2;ce>l&&(l=ce,o=G)}}let d=String(U.logline||"").trim(),m=String(U.synopsis||"").trim(),y={...pe},h=P,b=we;if(o){const R=o,T=String(R.logline||"").trim(),M=String(R.synopsis||"").trim();d=T||d,m=M||m,Rr(Y=>({logline:T||Y.logline,synopsis:M||Y.synopsis}));const W=R.worldBible||{};y={geography:String(W.geography||"").trim()||y.geography,timeline:String(W.timeline||"").trim()||y.timeline,rules:String(W.rules||"").trim()||y.rules,culture:String(W.culture||"").trim()||y.culture,coreConflict:String(W.coreConflict||"").trim()||y.coreConflict},Us(y);const q=Array.isArray(R.characters)?R.characters:[];if(q.length>0){const Y=qi(we,q.map(F=>({name:String((F==null?void 0:F.name)||"").trim(),note:String((F==null?void 0:F.note)||"").trim()})).filter(F=>F.name));xn(Y),b=Y}const G=Array.isArray(R.episodes)?R.episodes:[];if(G.length>0){const Y=G.map((F,V)=>{const X=String(F.title||`Episode ${V+1}`).trim()||`Episode ${V+1}`,ce=String(F.summary||"").trim();if(!X&&!ce)return null;const he=Array.isArray(F.characterRefs)?F.characterRefs.map(se=>({name:String((se==null?void 0:se.name)||"").trim(),imgUrl:typeof(se==null?void 0:se.imgUrl)=="string"?se.imgUrl:void 0})).filter(se=>se.name):void 0;return{id:Cr(),title:X,summary:ce,attribution:{userName:Z,withBloomBot:!0},durationMin:We(te)/60,sceneCount:Ut(te),scenes:Array.isArray(F.scenes)?F.scenes.map(se=>String(se).trim()).filter(Boolean):void 0,props:Array.isArray(F.props)?F.props.map(se=>String(se).trim()).filter(Boolean):void 0,characterRefs:he!=null&&he.length?he:void 0}}).filter(Boolean);if(Y.length>0){const F=Fd(P,Y,Cr);h=F,Fe(F),$r(0)}}}const w=[lo.length?`Characters: ${lo.join(", ")}`:"",co.length?`Scenes: ${co.join(", ")}`:"",uo.length?`Props: ${uo.join(", ")}`:""].filter(Boolean).join(` 568`),g=[m,dr?`Homepage BloomBot dialogue canon: 569${dr}`:"",w?`Asset hints extracted from homepage dialogue: 570${w}`:""].filter(Boolean).join(` 571 572`),A=h.map((R,T)=>({episodeIndex:T+1,title:String(R.title||"").trim(),summary:String(R.summary||"").trim(),detailedScript:String(Rt(R)||"").trim().slice(0,6e3)}));if(d||m||A.some(R=>R.title||R.summary)){Ap(!0);try{const R=Rs.trim();R&&b.length>0&&rs(W=>{const q={...W};for(const G of b){const Y=Dy(R,G.name);if(!Y.trim())continue;const F=`c:${G.id}`;q[F]={...q[F]||{},description:Y.trim()}}return queueMicrotask(()=>{try{Ze.current({silent:!0,workspaceAssetMedia:q})}catch{}}),q});const T=await If({logline:d,synopsis:g,worldBible:y,episodes:A});if(T!=null&&T.success&&T.dashboard&&typeof T.dashboard=="object"){const W=T.dashboard,q={...W,assets:{...W.assets||{characters:[],scenes:[],props:[]},characters:(((B=W.assets)==null?void 0:B.characters)||[]).map(G=>Mt(String(G||""))),scenes:((_=W.assets)==null?void 0:_.scenes)||[],props:((C=W.assets)==null?void 0:C.props)||[]},characterShare:(W.characterShare||[]).map(G=>({...G,name:Mt(String((G==null?void 0:G.name)||""))}))};pc(G=>Dd(G,q)||q)}const M=await vl({logline:d,synopsis:g,worldExcerpt:er.map(W=>`${W.label}: ${(y[W.id]||"").trim()}`).join(` 573`).slice(0,1200),episodes:h.map((W,q)=>({index:q,title:String(W.title||"").trim()||`Episode ${q+1}`}))});if(Array.isArray(M)&&M.length>0){const W=new Map;for(const q of M){const G=String(q.summary||"").trim();!Number.isFinite(q.index)||!G||W.set(q.index,G)}W.size>0&&Fe(q=>q.map((G,Y)=>W.has(Y)?{...G,summary:W.get(Y)}:G))}}finally{Ap(!1),typeof window<"u"&&window.setTimeout(()=>{try{Ze.current({silent:!0})}catch{}},0)}}},[Z,te,J,Ur,lo,co,uo,U.logline,U.synopsis,dr,Rs,P,we,pe]),ol=c.useCallback(async()=>{var A,j,B;if(Ts||Ur)return;if(P.length===0){H.info(n("page.storyflow.noEpisodesTitle"),n("page.storyflow.noEpisodesBody"));return}const e=String(U.logline||"").trim(),o=String(U.synopsis||"").trim(),l=dr.trim(),d=[lo.length?`Characters: ${lo.join(", ")}`:"",co.length?`Scenes: ${co.join(", ")}`:"",uo.length?`Props: ${uo.join(", ")}
573`:""].filter(Boolean).join(` 574`),m=we.map(_=>{const C=String(_.name||"").trim();if(!C)return"";const R=String(_.backstory||"").trim();return R?`${C}: ${R}`:C}).filter(Boolean).join(` 575`),y=[o,l?`Homepage BloomBot dialogue canon: 576${l}`:"",d?`Asset hints extracted from homepage dialogue: 577${d}`:"",m?`Character design and canon context (must stay consistent with outline/world bible): 578${m}`:""].filter(Boolean).join(` 579 580`);if(!(!!e||!!o||!!l||P.some(_=>String(_.title||"").trim()))){H.info(n("page.storyflow.notEnoughContextTitle"),n("page.storyflow.notEnoughContextBody"));return}const b=_=>{if(!_)return[];const C=new Set,R=_.match(/\[\[(?:CHAR|SCENE|PROP):[^[\]]+\]\]/g)||[];for(const M of R)C.add(M.trim());const T=_.match(/@@[^\sã\]\[,.!?;:ï¼ãï¼ï¼ï¼ï¼]+(?:ã[^ã]+ã)?/g)||[];for(const M of T)C.add(M.trim());return[...C]},w=P.map((_,C)=>{const R=C+1,T=(_.characterRefs||[]).map(G=>String(G.name||"").trim()).filter(Boolean),M=(_.scenes||[]).map(G=>String(G||"").trim()).filter(Boolean),W=(_.props||[]).map(G=>String(G||"").trim()).filter(Boolean),q=b(String(_.summary||""));return[`Episode ${R}:`,`- Characters (fixed): ${T.length?T.join(", "):"None"}`,`- Scenes (fixed): ${M.length?M.join(", "):"None"}`,`- Props (fixed): ${W.length?W.join(", "):"None"}`,"- Mention names explicitly, no role labels (主è§/åæ´¾/代å·), no marker syntax.",`- Existing tags snapshot: ${q.length?q.join(" | "):"None"}`].join(` 581`)}).join(` 582 583`),g=er.map(_=>`${_.label}: ${(pe[_.id]||"").trim()}`).join(` 584`).slice(0,1200);Ip(!0);try{const _=await vl({logline:e,synopsis:y,worldExcerpt:g,episodes:P.map((T,M)=>({index:M,title:String(T.title||"").trim()||`Episode ${M+1}`})),lockedEntitiesText:w});if(!Array.isArray(_)||_.length===0){H.warning(n("page.storyflow.reanalyzeTitle"),n("page.storyflow.reanalyzeNoSummariesBody"));return}const C=new Map;for(const T of _){const M=String(T.summary||"").trim();!Number.isFinite(T.index)||!M||C.set(T.index,M)}if(C.size===0){H.warning(n("page.storyflow.reanalyzeTitle"),n("page.storyflow.reanalyzeNoValidSummariesBody"));return}const R=P.map((T,M)=>C.has(M)?{...T,summary:C.get(M),attribution:{userName:Z,withBloomBot:!0}}:T);Fe(R);try{const T=await If({logline:e,synopsis:y,worldBible:pe,episodes:R.map((M,W)=>({episodeIndex:W+1,title:String(M.title||"").trim(),summary:String(M.summary||"").trim(),detailedScript:""}))});if(T!=null&&T.success&&T.dashboard&&typeof T.dashboard=="object"){const M=T.dashboard,W={...M,assets:{...M.assets||{characters:[],scenes:[],props:[]},characters:(((A=M.assets)==null?void 0:A.characters)||[]).map(q=>Mt(String(q||""))),scenes:((j=M.assets)==null?void 0:j.scenes)||[],props:((B=M.assets)==null?void 0:B.props)||[]},characterShare:(M.characterShare||[]).map(q=>({...q,name:Mt(String((q==null?void 0:q.name)||""))}))};pc(q=>Dd(q,W)||W)}}catch{}H.success(n("page.storyflow.episodeOutlinesUpdatedTitle"),n("page.storyflow.episodeOutlinesUpdatedBody"))}catch(_){H.error(n("page.storyflow.reanalyzeFailedTitle"),Bt(_ instanceof Error?_.message:String(_)))}finally{Ip(!1),typeof window<"u"&&window.setTimeout(()=>{try{Ze.current({silent:!0})}catch{}},0)}},[Ts,Ur,P,U.logline,U.synopsis,pe,dr,lo,co,uo,we,Z,n]);c.useCallback(()=>{ka(!0)},[]);const Hg=c.useCallback(async()=>{Ts||Ur||(ka(!1),Ht("outline"),await ol())},[Ts,Ur,ol]);c.useCallback(()=>{Ur||typeof window<"u"&&!window.confirm(n("page.storyflow.analyzeScriptConfirmBody"))||md()},[Ur,md,n]);const zg=c.useCallback(()=>{ee||Ts||Ur||typeof window<"u"&&!window.confirm(n("page.storyflow.reanalyzeEpisodesConfirmBody"))||ol()},[ee,Ts,Ur,ol,n]);c.useCallback(async()=>{if(Pp)return;const e=P.length;if(e<=0){io("No episodes available for adjustment.");return}const o=Math.max(0,Math.min(Bp,e));if(o>=e){io("All episodes have been adjusted.");return}const l=Math.min(o+4,e),d=P.slice(o,l).map((j,B)=>({index:o+B,title:String(j.title||"").trim()||`Episode ${o+B+1}`})),m=new Set,y=new Set,h=new Set;for(const j of P){for(const T of j.characterRefs||[]){const M=String(T.name||"").trim();M&&m.add(M)}for(const T of j.scenes||[]){const M=String(T||"").trim();M&&y.add(M)}for(const T of j.props||[]){const M=String(T||"").trim();M&&h.add(M)}const B=String(j.summary||""),_=[...B.matchAll(/\[\[CHAR:([^[\]]+)\]\]/g)].map(T=>(T[1]||"").trim()),C=[...B.matchAll(/\[\[SCENE:([^[\]]+)\]\]/g)].map(T=>(T[1]||"").trim()),R=[...B.matchAll(/\[\[PROP:([^[\]]+)\]\]/g)].map(T=>(T[1]||"").trim());for(const T of _)T&&m.add(T);for(const T of C)T&&y.add(T);for(const T of R)T&&h.add(T)}const b=j=>{if(!j)return[];const B=new Set,_=j.match(/\[\[(?:CHAR|SCENE|PROP):[^[\]]+\]\]/g)||[];for(const R of _)B.add(R.trim());const C=j.match(/@@[^\sã\]\[,.!?;:ï¼ãï¼ï¼ï¼ï¼]+(?:ã[^ã]+ã)?/g)||[];for(const R of C)B.add(R.trim());return[...B]},w=(j,B)=>{const _=Y=>{let F=String(Y||"").trim();return F?(F=F.replace(/(?:主è§|é è§|æ£æ´¾|åæ´¾)\s*[ï¼(]\s*代å·\s*[:ï¼]\s*([^ï¼)]+)\s*[ï¼)]/g,"$1").trim(),F=F.replace(/代å·\s*[:ï¼]\s*/g,"").trim(),F=F.replace(/\b(?:主è§|é è§|æ£æ´¾|åæ´¾)\b/g,"").trim(),F=F.replace(/\s{2,}/g," ").trim(),F):""};let C=String(j||"").trim();const R=(B.characterRefs||[]).map(Y=>
584String(Y.name||"").trim()).filter(Boolean),T=(()=>{const Y=[...R,...m.values()].filter(F=>/é¦é¢|leader/i.test(F));return Y.length===1?Y[0]:""})();C=C.replace(/\[\[CHAR:([^[\]]+)\]\]/gi,"$1").replace(/\[\[SCENE:([^[\]]+)\]\]/gi,"$1").replace(/\[\[PROP:([^[\]]+)\]\]/gi,"$1").replace(/@@([^\sã\]\[,.!?;:ï¼ãï¼ï¼ï¼ï¼]+)(?:ã[^ã]+ã)?/g,"$1"),C=C.replace(/(主è§|é è§|æ£æ´¾|åæ´¾)\s*[ï¼(]\s*代å·\s*[:ï¼]\s*([^ï¼)]+)\s*[ï¼)]/g,"$2").replace(/代å·\s*[:ï¼]\s*([^\sï¼ã,.!?ï¼ï¼ï¼;:ï¼)ï¼]+)/g,"$1").replace(/\bCHAR\b/gi,"").replace(/\b(protagonist|supporting|hero|villain|antagonist)\b/gi,"").replace(/(主è§|é è§|æ£æ´¾|åæ´¾|代å·)/g,"").replace(/\[\[[^[\]]+\]\]/g,"").replace(/对æ¹é¦é¢/g,T||"é¦é¢").replace(/\s{2,}/g," ").replace(/^[,ï¼;ï¼:\-â\s]+|[,ï¼;ï¼:\-â\s]+$/g,"").trim(),R.length>0&&(C=C.replace(/\b(主è§|ä¸»äººå ¬)\b/g,R[0]).replace(/\b(é è§)\b/g,R[Math.min(1,R.length-1)]||R[0]));const M=String(B.summary||"").trim(),W=b(M);if(C=C.replace(/\[\[[^[\]]+\]\]/g,"").replace(/@@/g,"").trim(),!C)return M;const G=W.map(Y=>{const F=Y.match(/\[\[(?:CHAR|SCENE|PROP):([^[\]]+)\]\]/i);return _(String((F==null?void 0:F[1])||""))}).filter(Boolean).filter(Y=>!C.toLowerCase().includes(Y.toLowerCase()));return G.length>0&&(C=`${C} ${G.join(" ")}`.trim()),C=C.replace(/(?:主è§|é è§|æ£æ´¾|åæ´¾)\s*[ï¼(]\s*代å·\s*[:ï¼]\s*([^ï¼)]+)\s*[ï¼)]/g,"$1").replace(/(主è§|é è§|æ£æ´¾|åæ´¾|代å·)/g,"").replace(/\s{2,}/g," ").replace(/^[,ï¼;ï¼:\-â\s]+|[,ï¼;ï¼:\-â\s]+$/g,"").trim(),C||String(M||"").replace(/(?:主è§|é è§|æ£æ´¾|åæ´¾)\s*[ï¼(]\s*代å·\s*[:ï¼]\s*([^ï¼)]+)\s*[ï¼)]/g,"$1").replace(/(主è§|é è§|æ£æ´¾|åæ´¾|代å·)/g,"").replace(/\s{2,}/g," ").trim()},g=P.slice(o,l).map((j,B)=>{const _=o+B+1,C=(j.characterRefs||[]).map(W=>String(W.name||"").trim()).filter(Boolean),R=(j.scenes||[]).map(W=>String(W||"").trim()).filter(Boolean),T=(j.props||[]).map(W=>String(W||"").trim()).filter(Boolean),M=b(String(j.summary||""));return[`Episode ${_}:`,`- Characters (fixed): ${C.length?C.join(", "):"None"}`,`- Scenes (fixed): ${R.length?R.join(", "):"None"}`,`- Props (fixed): ${T.length?T.join(", "):"None"}`,"- Mention names explicitly, no role labels (主è§/åæ´¾/代å·), no marker syntax.",`- Existing tags snapshot: ${M.length?M.join(" | "):"None"}`].join(` 585`)}).join(` 586 587`),A=er.map(j=>`${j.label}: ${(pe[j.id]||"").trim()}`).join(` 588`).slice(0,1200);_p(!0);try{const j=await vl({logline:U.logline,synopsis:U.synopsis,worldExcerpt:A,episodes:d,lockedEntitiesText:g,chatContextText:dr}),B=new Map(j.map(_=>[_.index,_.summary]));Fe(_=>_.map((C,R)=>
588{if(R<o||R>=l)return C;const T=B.get(R);return T?{...C,summary:w(T,C)}:C})),Ac(l),l<e?io(`${o+1}-${l} adjusted completed. Click again to continue.`):io(`${o+1}-${l} adjusted completed. All episodes adjusted.`)}catch{io("Adjustment failed. Click again to retry.")}finally{_p(!1)}},[Pp,P,Bp,U.logline,U.synopsis,pe,dr]),c.useEffect(()=>{if($a.current||P.length===0||!P.some(y=>{var h,b,w;return!((h=y.characterRefs)!=null&&h.length||(b=y.scenes)!=null&&b.length||(w=y.props)!=null&&w.length)}))return;const o=J.filter(y=>y.role==="assistant");if(o.length===0)return;const l=[];for(let y=o.length-1;y>=0;y--){const h=o[y],b=[String(h.rawAssistantReply||""),String(h.text||"")].filter(w=>w.trim().length>0);for(const w of b){const A=Cl(w).payload,j=Array.isArray(A==null?void 0:A.episodes)?A.episodes:[];if(j.length===0)continue;let B=0;for(const _ of j){const C=Array.isArray(_.characterRefs)?_.characterRefs.length:0,R=Array.isArray(_.scenes)?_.scenes.length:0,T=Array.isArray(_.props)?_.props.length:0;B+=C*3+R*2+T*2}B+=Math.min(20,j.length),B>0&&l.push({episodes:j,characters:A.characters,score:B})}}if(l.length===0){$a.current=!0;return}l.sort((y,h)=>h.score-y.score);const d=l[0];let m=!1;if(Fe(y=>y.map((h,b)=>{const w=d.episodes[b];if(!w)return h;const g={...h};if((!g.characterRefs||g.characterRefs.length===0)&&Array.isArray(w.characterRefs)){const A=w.characterRefs.map(j=>({name:String((j==null?void 0:j.name)||"").trim(),imgUrl:typeof(j==null?void 0:j.imgUrl)=="string"?j.imgUrl:void 0})).filter(j=>j.name);A.length>0&&(g.characterRefs=A,m=!0)}if((!g.scenes||g.scenes.length===0)&&Array.isArray(w.scenes)){const A=w.scenes.map(j=>String(j||"").trim()).filter(Boolean);A.length>0&&(g.scenes=[...new Set(A)],m=!0)}if((!g.props||g.props.length===0)&&Array.isArray(w.props)){const A=w.props.map(j=>String(j||"").trim()).filter(Boolean);A.length>0&&(g.props=[...new Set(A)],m=!0)}return g})),m&&(!we||we.length===0)&&Array.isArray(d.characters)){const y=qi(we,d.characters.map(h=>({name:String((h==null?void 0:h.name)||"").trim(),note:String((h==null?void 0:h.note)||"").trim()})).filter(h=>h.name));y.length>0&&xn(y)}m&&H.success(n("page.storyflow.entityRecoveredTitle"),n("page.storyflow.entityRecoveredBody")),$a.current=!0},[J,P,we,n]),c.useEffect(()=>{uf(te,ke)&&(ar(On),gr(String(On/60)))},[ke,te]),c.useEffect(()=>{if(ao.current||!Te.current||P.length===0)return;if(!P.some(h=>!Array.isArray(h.generationUnits)||h.generationUnits.length===0)){ao.current=!0;return}const o=[];for(const h of J){if(h.role!=="assistant")continue;const b=String(h.rawAssistantReply||h.text||"").trim();b&&o.push(b)}for(const h of wt){if(h.role!=="assistant")continue;const b=String(h.rawAssistantReply||h.text||"").trim();b&&o.push(b)}for(const h of Object.values(At))for(const b of h||[]){if(b.role!=="assistant")continue;const w=String(b.rawAssistantReply||b.text||"").trim();w&&o.push(w)}for(const h of Object.values(at))for(const b of h||[]){if(b.role!=="assistant")continue;const w=String(b.rawAssistantReply||b.text||"").trim();w&&o.push(w)}if(o.length===0){ao.current=!0;return}const l=[];for(let h=o.length-1;h>=0;h-=1){const b=o[h],w=Cl(b).payload,g=Array.isArray(w==null?void 0:w.episodes)?w.episodes:[];let A=0;for(const _ of g){const C=Array.isArray(_.sequences)?_.sequences:[];A+=C.filter(R=>String((R==null?void 0:R.label)||"").trim()).length*4}const j=Jl(b),B=j.length*2;A+B<=0||l.push({score:A+B+(g.length>0?1:0),episodes:g,proseBeats:j})}if(l.length===0){ao.current=!0;return}l.sort((h,b)=>b.score-h.score);const d=l[0],m=ke===!0;let y=null;if(Fe(h=>{const b=[...h],w=(g,A)=>{if(g<0||g>=b.length)return;const j=b[g];if(Array.isArray(j.generationUnits)&&j.generationUnits.length>0)return;const B=ku({...A,standaloneFilmMode:m});if(B.length===0)return;const _=Qf(j.generationUnits,B,{standaloneFilmMode:m,episodeIndex:g,totalMinutes:j.durationMin??te/60});_.units.length&&(b[g]={...j,generationUnits:_.units},y={epIndex:g,units:_.units})};if(d.episodes.length>0)for(let g=0;g<d.episodes.length;g+=1){const A=d.episodes[g],j=Array.isArray(A.sequences)?A.sequences:[];if(j.length===0)continue;w(m?0:g,{jsonBeats:j})}return!y&&d.proseBeats.length>0&&w(0,{jsonBeats:d.proseBeats}),b}),y){const{epIndex:h,units:b}=y;be(w=>Jf(w,h,b,g=>{const A=/^ep:(\d+):seq:(\d+)$/.exec(g);if(!A||Number(A[1])!==h)return null;const j=Number(A[2]);return b.some(B=>B.index===j)?{id:g}:null})),window.setTimeout(()=>Ze.current({silent:!0}),0)}ao.current=!0},[P,J,wt,At,at,ke,te,de]);const il=c.useCallback(()=>{const e=U.logline.trim()||"â",o=U.synopsis.trim()||"â",l=er.map(d=>`${d.label}: 589${(pe[d.id]||"").trim()||"(empty)"}`).join(` 590 591`);return`## Base requirements (keep the episode consistent with these) 592 593**Story outline** 594Logline: ${e} 595 596Synopsis: ${o} 597 598**World Bible** 599${l}`},[U,pe]),mm=c.useCallback(e=>{const o=[],l=new Set,d=y=>{const h=Mt(String(y||""));if(!h)return;const b=h.toLowerCase();l.has(b)||(l.add(b),o.push(h))},m=P[e];for(const y of(m==null?void 0:m.characterRefs)||[])d(y.name);for(const y of(Q==null?void 0:Q.characterShare)||[])d(y.name);for(const y of we)d(y.name);return o.slice(0,8)},[P,Q==null?void 0:Q.characterShare,we]),No=c.useCallback(e=>{var y,h,b,w;const o=mm(e);
599if(o.length===0)return"";const l=((y=((Q==null?void 0:Q.characterShare)||[]).find(g=>g.role==="protagonist"))==null?void 0:y.name)||((w=(b=(h=P[e])==null?void 0:h.characterRefs)==null?void 0:b[0])==null?void 0:w.name)||o[0],d=Mt(String(l||""))||o[0];return`Character lock (strict): 600- Use canonical character names from Asset Library only: ${o.map(g=>`@@${g}`).join(", ")} 601- Main protagonist for this episode: @@${d} 602- Do NOT rename, translate, or invent new character names. 603- Any dialogue speaker must use @@Name format (e.g. %%@@Name说ï¼...%% / %%@@Name: ...%%).`},[mm,Q==null?void 0:Q.characterShare,P]),fm=c.useCallback(e=>{P[e]&&(xa("edit"),$r(e),oi(e),Zn(l=>({...l,width:Qn(),height:eo()})),Lc("write"),$p(!1),Xn("episode"),Ea(),fs("docked"),qt((at[e]??[]).length),or({type:"episode_outline",episodeIndex:e}))},[P,at,eo,Qn,Ea]),Kg=c.useCallback(e=>{P[e]&&(xa("completed"),$r(e),oi(e),Xn("episode"),or(null),qt(null),fs("idle"),Zn(l=>({...l,width:Qn(),height:eo()})),Ea())},[P,eo,Qn,Ea]);c.useEffect(()=>{Kt>=P.length&&P.length>0&&$r(P.length-1)},[P.length,Kt,P]),c.useEffect(()=>{const e=We(te)/60,o=Ut(te);Fe(l=>{let d=!1;const m=l.map(y=>{const h=y.durationMin===e,b=y.sceneCount===o;return h&&b?y:(d=!0,{...y,durationMin:e,sceneCount:o})});return d?m:l})},[te]),c.useCallback(e=>{Xn(e),fs("to_modal")},[]);const Rn=c.useCallback(()=>{var d,m;if(!oe)return;if(oe==="episode"){Xn(null),xa("edit"),fs("idle"),or(null),qt(null),oi(null),Wa(""),qs(""),Wr(!1),ys.current=!1,Gs.current=!0,qa(!1),(d=ir.current)==null||d.call(ir),ir.current=null;return}const e=oe==="story-arc"?Ju.current:Xu.current,o=ac.current;if((m=ir.current)==null||m.call(ir),ir.current=null,!e||!o||hn!=="docked"){Xn(null),fs("idle"),or(null),qt(null);return}fs("to_source");const l=Yy(e.getBoundingClientRect(),o.getBoundingClientRect(),"backward",()=>{Xn(null),fs("idle"),or(null),qt(null)});ir.current=()=>{l(),ir.current=null}},[oe,hn,Wr]),qg=c.useCallback(()=>{Aa("workspace"),Ht("assets"),Rn()},[Rn]),Gg=c.useCallback(async()=>{if(oe!=="episode")return;const e=_e??0,o=P[e];if(!o)return;const l=[`Episode ${String(e+1).padStart(2,"0")}: ${o.title||"Untitled"}`,"","Episode summary (locked):",(o.summary||"").trim()||"(empty)","","Detailed episode script:",Rt(o).trim()||"(empty)"].join(` 604`);try{await navigator.clipboard.writeText(l),H.success(n("page.storyflow.copiedTitle"),n("page.storyflow.episodeCopiedBody"))}catch{try{const d=document.createElement("textarea");d.value=l,d.style.position="fixed",d.style.left="-9999px",document.body.appendChild(d),d.focus(),d.select();const m=document.execCommand("copy");d.remove(),m?H.success(n("page.storyflow.copiedTitle"),n("page.storyflow.episodeCopiedBody")):H.warning(n("page.storyflow.copyFailedTitle"),n("page.storyflow.copyPleaseManuallyBody"))}catch{H.warning(n("page.storyflow.copyFailedTitle"),n("page.storyflow.copyPleaseManuallyBody"))}}},[oe,_e,P,n]);c.useLayoutEffect(()=>{var h;if(!oe||hn!=="to_modal"){oe||((h=ir.current)==null||h.call(ir),ir.current=null);return}const e=oe==="story-arc"?Ju.current:Xu.current;let o=!1,l=0,d=0;const m=()=>{const b=ac.current,w=e;if(!b||!w)return!1;const g=Yy(w.getBoundingClientRect(),b.getBoundingClientRect(),"forward",()=>{o||fs("docked")});return ir.current=()=>{g(),ir.current=null},!0},y=()=>{if(!o&&!m()){if(d+=1,d>24){fs("docked");return}l=requestAnimationFrame(y)}};return l=requestAnimationFrame(y),()=>{o=!0,cancelAnimationFrame(l)}},[oe,hn]),c.useEffect(()=>{if(!Pt||ic===null)return;const e=Pt.type==="episode_outline"?at[Pt.episodeIndex]??[]:J,o=e[e.length-1];if(!o||o.role!=="assistant"||e.length<=ic)return;if(Pt.type==="world_bible"){if(oe!==Pt.dimensionId)return;Us(d=>({...d,[Pt.dimensionId]:o.text}));return}if(Pt.type==="episode_outline"){const d=Pt.episodeIndex;Fe(m=>{var se,Ke;if(d<0||d>=m.length)return m;const y=m[d],h=[],b=new Set,w=De=>{const Je=Mt(String(De||""));if(!Je)return;const bt=Je.toLowerCase();b.has(bt)||(b.add(bt),h.push(Je))};for(const De of y.characterRefs||[])w(De.name);for(const De of(Q==null?void 0:Q.characterShare)||[])w(De.name);for(const De of we)w(De.name);const g=Ky(o.text).trim();if(!g||g.startsWith("[FORMAT FILTER]")||Ly(g))return m;const A=We(typeof y.durationMin=="number"&&y.durationMin>0?Math.round(y.durationMin*60):te),j=typeof y.sceneCount=="number"&&y.sceneCount>0?Math.round(y.sceneCount):Ut(A),B=yu(g),_=String(y.detailedScript||"").trim(),C=String(y.detailedScriptBloomDraft||"").trim(),R=_.length>0?String(y.detailedScript||""):C||"",T=KC(R,B),M=Pu(zt(T).scriptBody);let W=T;M<j&&(W=zC(W),W=yu(W));const q=qC(W,h),G=_.length>0&&(()=>{const De=zt(_).scriptBody;return Pu(De)>=j&&j>0})(),Y=Xe?sa(q):M>=j&&j>0;let F,V;G||Y?(F=q,V=void 0):(F="",V=q);const X=y.scriptStage==="adjusting"?"adjusted_once":y.scriptStage||"drafting",ce=((se=y.attribution)==null?void 0:se.userName)===Z&&((Ke=y.attribution)==null?void 0:Ke.withBloomBot)===!0,he=String(V??"")===String(y.detailedScriptBloomDraft??"");return F===(y.detailedScript||"")&&he&&X===y.scriptStage&&ce?m:m.map((De,Je)=>Je===d?{...De,detailedScript:F,...V!==void 0&&V!==""?{detailedScriptBloomDraft:V}:{detailedScriptBloomDraft:void 0},attribution:{userName:Z,withBloomBot:!0},scriptStage:X}:De)});return}if(oe!=="story-arc")return;const l=LC(o.text);Rr(d=>{const m=l.logline.trim().length>0,y=l.synopsis.trim().length>0;return!m&&!y&&o.text.trim()?{...d,synopsis:o.text.trim()}:{logline:m?l.logline:d.logline,synopsis:y?l.synopsis:d.synopsis}})},[J,at,Pt,ic,oe,Z,Q==null?void 0:Q.characterShare,we,te,Xe]);const Yg=c.useCallback(()=>
604{if(!oe||hn!=="docked")return;if(qt(oe==="episode"?(at[_e??0]??[]).length:J.length),oe==="story-arc"){or({type:"story_arc"});const o=`Logline: 605${U.logline.trim()||"â"} 606 607Synopsis: 608${U.synopsis.trim()||"â"}`;Ds(`I'm editing Global Story Arc (logline and synopsis). 609 610Current content: 611${o} 612 613How would you like to change this? Describe your edits and I'll help revise; the expanded panel will update from our conversation.`)}else if(oe==="episode"){const o=_e??0,l=P[o];if(!l)return;or({type:"episode_outline",episodeIndex:o});const d=il(),m=No(o),y=o>0?P[o-1]:null,h=o<P.length-1?P[o+1]:null,b=Rt(l).trim(),w=hu(b),g=We(typeof l.durationMin=="number"&&l.durationMin>0?Math.round(l.durationMin*60):te),A=Ut(g),j={episodeIndex:o,episodeTitle:l.title,durationSeconds:g,baseContext:d,characterLockContext:m,prevEp:y?{title:y.title,summary:y.summary}:null,nextEp:h?{title:h.title,summary:h.summary}:null,episodeSummary:String(l.summary||"")},B=Xe?tv(j):`Continue screenplay writing for Ep. ${String(o+1).padStart(2,"0")}: "${l.title}". 614 615${d} 616 617${m} 618 619Duration & density target: 620- Episode duration: ${g}s 621- Target shot count: around ${A} 622- This turn: write exactly ${ou} shots 623 624Continuity anchors: 625- Previous episode: ${y?`${y.title} â ${(y.summary||"").trim()||"(empty)"}`:"(none)"} 626- Current episode summary (locked): ${(l.summary||"").trim()||"(empty)"} 627- Next episode: ${h?`${h.title} â ${(h.summary||"").trim()||"(empty)"}`:"(none)"} 628 629Use staged drafting: 630- Keep existing blueprint as source of truth. 631- Write in shot blocks (SHOT 01, SHOT 02...) with concise action/dialogue. 632- Run an internal editor pass before final output (hook, continuity, character consistency, world rules, seed/payoff clarity). 633- Do NOT output delivery checklist / ledger footer sections (including Chinese/English checklist headings). 634 635${Zi} 636 637Scope lock: 638- Write ONLY this episode. 639- Do NOT draft Episode ${o+2} or any other episode content now. 640- If later episodes are impacted, add notes only in CONTINUITY NOTES. 641 642Formatting constraints: 6431) Keep episode summary unchanged. 6442) Use screenplay-friendly structure and Workflow tags when needed (@@ / %% / $$). 6453) Keep names aligned with Asset Library canonical names. 6464) Preserve canon continuity and seed/payoff logic. 647 648If this episode is complete for target shots, add this line at the end: 649EPISODE COMPLETE. You can close this modal and click GO TO Workflow. 650`,_=Xe?rv(j):`Create a blueprint-first detailed screenplay plan for Ep. ${String(o+1).padStart(2,"0")}: "${l.title}". 651 652${d} 653 654${m} 655 656Duration & density target: 657- Episode duration: ${g}s 658- Target shot count: around ${A} 659 660Continuity anchors: 661- Previous episode: ${y?`${y.title} â ${(y.summary||"").trim()||"(empty)"}`:"(none)"} 662- Current episode summary (locked): ${(l.summary||"").trim()||"(empty)"} 663- Next episode: ${h?`${h.title} â ${(h.summary||"").trim()||"(empty)"}`:"(none)"} 664 665${Zi} 666 667Scope lock: 668- Build blueprint for ONLY this episode. 669- Do NOT draft any other episode. 670- Cross-episode impacts go to continuity notes only. 671 672This turn output ONLY "EPISODE BLUEPRINT" with sections: 673A) Episode objective 674B) Escalation chain (3-5 beats) 675C) Shot map (SHOT 01..N, one-line purpose each, target around ${A}) 676D) Hook at ending (why audience watches next episode) 677E) Seeds (new seeds + pending payoffs) 678F) Continuity checks against previous/next episode 679 680Do NOT write full screenplay paragraphs in this turn.`;Ds(w?B:_)}else{const o=er.find(l=>l.id===oe);or({type:"world_bible",dimensionId:oe}),Ds(`I'm editing World Bible â "${(o==null?void 0:o.label)??oe}". 681 682Current text: 683${(pe[oe]||"").trim()||"(empty)"} 684 685How would you like to change this? Describe your edits and I'll help revise; the expanded panel will update from our conversation.`)}},[oe,hn,J.length,at,U,pe,_e,P,il,No,te,Xe]),ym=c.useCallback(()=>{const e=po.trim();if(!e||ze||xt||oe!=="episode")return;const o=_e??0,l=P[o];if(!l)return;const d=il(),m=No(o),y=o>0?P[o-1]:null,h=o<P.length-1?P[o+1]:null,b=Rt(l).trim(),w=hu(b),g=b.length>1800?b.slice(-1800):b,A=We(typeof l.durationMin=="number"&&l.durationMin>0?Math.round(l.durationMin*60):te),j=Ut(A);or({type:"episode_outline",episodeIndex:o}),qt((at[o]??[]).length),Wa("");const B=`Continue the detailed screenplay for Ep. ${String(o+1).padStart(2,"0")}: "${l.title}". 686 687${d} 688 689${m} 690 691Duration & density target: 692- Episode duration: ${A}s 693- Target shot count: around ${j} 694- This turn: write exactly ${ou} shots 695 696Continuity anchors: 697- Previous episode: ${y?`${y.title} â ${(y.summary||"").trim()||"(empty)"}`:"(none)"} 698- Current episode summary (locked): ${(l.summary||"").trim()||"(empty)"} 699- Next episode: ${h?`${h.title} â ${(h.summary||"").trim()||"(empty)"}`:"(none)"} 700 701Existing draft tail (for continuation, do not rewrite): 702${g||"(empty)"} 703 704Additional direction: 705${e} 706 707This turn: 7081) Write in shot blocks (SHOT 01, SHOT 02...) with concise action/dialogue. 7092) Keep hook/seed continuity with the existing blueprint. 7103) Run an internal editor pass before final output. 7114) Do NOT output delivery checklist / ledger footer sections (including Chinese/English checklist headings). 712 713${Zi} 714 715Scope lock: 716- Write ONLY this episode. 717- Do NOT draft next episode or other episodes. 718- If later episodes are impacted, record notes only in CONTINUITY NOTES. 719 720If this episode is complete for target shots, add this line at the end: 721EPISODE COMPLETE. You can close this modal and click GO TO Workflow. 722`,_=`We do not have an approved blueprint yet for Ep. ${String(o+1).padStart(2,"0")}: "${l.title}". 723 724${d} 725 726${m} 727 728Duration & density target: 729- Episode duration: ${A}s 730- Target shot count: around ${j} 731 732Current episode summary (locked): ${(l.summary||"").trim()||"(empty)"} 733 734User direction: 735${e} 736 737${Zi} 738 739Scope lock: 740- Blueprint for ONLY this episode. 741- Do NOT draft next/other episodes. 742- Cross-episode impacts go to continuity notes only. 743 744Output ONLY "EPISODE BLUEPRINT" sections A-F: 745A) Episode objective 746B) Escalation chain (3-5 beats) 747C) Shot map (SHOT 01..N, target around ${j}) 748D) Ending hook 749E) Seeds ledger (new/pending) 750F) Continuity checks with previous/next episode. 751 752Do not output full screenplay paragraphs yet.`;lt(w?B:_)},[po,ze,xt,oe,_e,P,te,il,No,at,lt]),al=c.useCallback((e,o,l)=>{const d=Rt(e).trim(),m=`Ep. ${String(o+1).padStart(2,"0")}`,y=zt(d).scriptBody,{count:h,lastMax:b}
752=Fn(y),g=[...d.matchAll(/\bSHOT\s*0*(\d{1,3})\b/gi)].reduce((G,Y)=>{const F=Number(Y[1]||0);return Number.isFinite(F)?Math.max(G,F):G},0),A=Math.max(0,Math.round((l==null?void 0:l.written)??0)),j=Math.max(0,Math.round((l==null?void 0:l.target)??0)),B=Math.max(A,b,h,g),_=Math.max(1,B+1),C=hu(d),R=Jh(d),T=C||A>0||b>0||h>0||R,M=j>0?String(j):"?",W=(e.title||"").trim()||n("page.storyflow.episodePromptUntitledEpisode"),q=(e.summary||"").trim()||n("page.storyflow.episodePromptEmptySummary");return T?n("page.storyflow.episodeAutoPromptContinue",{episodeLabel:m,title:W,summary:q,currentWritten:String(B),target:M,startShot:String(_).padStart(2,"0"),fixedShots:String(ou)}):n("page.storyflow.episodeAutoPromptStart",{episodeLabel:m,title:W})},[n]),Vg=c.useCallback(()=>{if(ze||xt||oe!=="episode")return;const e=_e??0,o=P[e];if(!o)return;const l=Rt(o),d=zt(l),m=Fn(d.scriptBody),y=al(o,e,{written:Math.max(ur.current.episodeIndex===e?ur.current.written:0,m.lastMax,m.count),target:ur.current.episodeIndex===e?ur.current.target:Ut(We(typeof o.durationMin=="number"&&o.durationMin>0?Math.round(o.durationMin*60):te))});or({type:"episode_outline",episodeIndex:e}),qt((at[e]??[]).length),lt(y)},[ze,xt,oe,_e,P,at,lt,al,te]),Xg=c.useCallback(async()=>{if(xt||oe!=="episode")return;const e=_e??0;if(!wi.current[e])return;Gs.current=!1,qa(!0);let l=0;const d=Date.now(),m=b=>new Promise(w=>setTimeout(w,b)),y=async b=>{const w=Date.now();for(;Date.now()-w<b;){if(!yo.current&&!ys.current)return!0;await m(120)}return!yo.current&&!ys.current},h=()=>{const b=wi.current[e],w=Rt(b);return w.trim()?Fn(zt(w).scriptBody):{count:0,lastMax:0}};try{for(yo.current&&(await y(2e4)||(qs(""),Wr(!1),await m(500)));!Gs.current&&!(Date.now()-d>3600*1e3);){const b=ur.current;if(b.episodeIndex!==e)break;const w=b.target;if(!await y(15e3)){if(qs(""),ys.current||Wr(!1),l+=1,l>=au)break;await m(Math.min(18e3,1e3*(l+2)));continue}l>0&&await m(550);const A=h();if(w>0&&(A.lastMax>=w||A.count>=w))break;const j=wi.current[e];if(!j)break;or({type:"episode_outline",episodeIndex:e}),qt(Ca.current.length);const B=Math.max(A.lastMax,A.count,ur.current.written),C=al(j,e,{written:B,target:w}),R=Ca.current.length;let T=!1;if(await Promise.race([lt(C),m(125e3).then(()=>{T=!0})]),T){if(qs(""),ys.current||Wr(!1),l+=1,l>=au)break;await m(Math.min(25e3,2e3*(l+1)));continue}let M=A;for(let G=0;G<40&&(await m(100),M=h(),!(M.lastMax>A.lastMax||M.count>A.count));G+=1);ur.current={...ur.current,written:Math.max(ur.current.written,M.lastMax,M.count)};const W=Ca.current.length>R;if(M.lastMax>A.lastMax||M.count>A.count){if(l=0,!Gs.current){const G=_y+Math.floor(Math.random()*(pC-_y));await m(G)}}else{if(l+=1,W||(l+=1),l>=au)break;await m(Math.min(15e3,800*(l+1)))}}}finally{const b=Gs.current;Gs.current=!1,qa(!1);const w=ur.current;b?H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.bloomBotAutoStoppedBody")):w.target>0&&w.written>=w.target?H.success(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.bloomBotTargetShotsDoneBody")):H.info(n("page.storyflow.toastTitleBloomBot"),n("page.storyflow.bloomBotAutoPausedBody"))}},[xt,oe,_e,lt,al,n]),Jg=c.useCallback(()=>{Gs.current=!0},[]),Qg=c.useCallback(()=>{if(ze||xt||oe!=="episode")return;const e=_e??0;P[e]&&(Fe(l=>l.map((d,m)=>m===e?{...d,detailedScript:"",detailedScriptBloomDraft:void 0,scriptStage:"drafting",scriptQaDecision:null,scriptQualityRadar:null}:d)),Wa(""),yn(l=>({...l,[e]:[]})),Nn.current=null,Ai.current=0,or({type:"episode_outline",episodeIndex:e}),qt(0),H.success(n("page.storyflow.resetDoneTitle"),n("page.storyflow.resetDoneBody")))},[ze,xt,oe,_e,P,n]),Zg=c.useCallback(async()=>{if(oe!=="episode")return;if(Xe){H.info(n("page.storyflow.compileDescriptiveScriptButton"),n("page.storyflow.scriptPolishDescriptiveModeBody"));return}if(ze||xt||ii)return;const e=_e??0,o=P[e];if(!o)return;const d=aC(va)||Rt(o).trim();if(!d){H.warning(n("page.storyflow.scriptPolishTitle"),n("page.storyflow.scriptPolishNoContentBody"));return}Vu(!0);try{const m=await td(d);if(!m){H.warning(n("page.storyflow.scriptPolishTitle"),n("page.storyflow.scriptPolishNoOutputBody"));return}Fe(y=>y.map((h,b)=>b===e?{...h,detailedScript:m,detailedScriptBloomDraft:void 0,attribution:{userName:Z,withBloomBot:!0}}:h)),H.success(n("page.storyflow.scriptPolishedTitle"),n("page.storyflow.scriptPolishedBody"))}finally{Vu(!1)}},[oe,ze,xt,ii,_e,P,va,td,Z,Xe,n]),hm=hn==="docked"&&!(oe==="episode"&&Vr==="completed"),Pi=c.useMemo(()=>{var o;return(((o=P[_e??0])==null?void 0:o.detailedScript)||"").trim()},[_e,P]),jn=c.useMemo(()=>{var o;return(((o=P[_e??0])==null?void 0:o.detailedScriptBloomDraft)||"").trim()},[_e,P]),Js=c.useMemo(()=>Rt(P[_e??0]),[_e,P]),le=c.useMemo(()=>P[_e??0]||null,[_e,P]),An=c.useMemo(()=>zt(Js),[Js]),ll=c.useMemo(()=>zt(Pi||jn),[Pi,jn]),as=c.useMemo(()=>jn&&!Pi?An:ll,[jn,Pi,An,ll]),gm=c.useMemo(()=>Js.includes("[NEXT STEP HINT]"),[Js]),et=c.useMemo(()=>{const e=We(typeof(le==null?void 0:le.durationMin)=="number"&&le.durationMin>0?Math.round(le.durationMin*60):te),l=(typeof(le==null?void 0:le.sceneCount)=="number"&&le.sceneCount>
7520?Math.round(le.sceneCount):null)??Ut(e),{count:d,lastMax:m}=Fn(An.scriptBody),y=Math.max(d,m);return{durationText:`${e}s (${(e/60).toFixed(1).replace(/\.0$/,"")} min)`,targetShots:l,writtenShots:y}},[le==null?void 0:le.durationMin,le==null?void 0:le.sceneCount,An.scriptBody,te]),Eo=c.useMemo(()=>FC({detailedScript:Js,parsed:An,targetShots:et.targetShots,writtenShots:et.writtenShots,descriptiveScriptV1:Xe,t:n}),[Js,An,et.targetShots,et.writtenShots,Xe,n]),Ar=c.useMemo(()=>(le==null?void 0:le.scriptQualityRadar)||Eo.radar,[le==null?void 0:le.scriptQualityRadar,Eo.radar]),Ct=c.useMemo(()=>Xe?sa(Js):et.writtenShots>=et.targetShots&&et.targetShots>0,[Xe,Js,et.writtenShots,et.targetShots]);c.useEffect(()=>{xt||(ur.current={episodeIndex:_e??-1,written:et.writtenShots,target:et.targetShots})},[xt,_e,et.writtenShots,et.targetShots]);const xm=c.useMemo(()=>{const e=Math.max(0,et.targetShots),o=Math.max(0,et.writtenShots),l=Math.min(o,e),d=[];for(let h=1;h<=e;h+=iu){const b=Math.min(h+iu-1,e);l>=b&&d.push({start:h,end:b})}const m=d.length>0?d[d.length-1].end+1:1,y=Math.min(m+iu-1,e);return{completedRanges:d,nextRange:e>0&&m<=e?{start:m,end:y}:null}},[et.targetShots,et.writtenShots]),fd=c.useMemo(()=>{if(!Ct)return!1;const e=(le==null?void 0:le.characterRefs)||[],o=e.length>0?e.map(l=>({name:l.name,imgUrl:l.imgUrl})):we.map(l=>({name:l.name,imgUrl:void 0}));return o.length===0?!1:o.some(l=>{if(qy(l.imgUrl))return!1;const d=Mt(String(l.name||"")),m=we.find(w=>Mt(w.name).toLowerCase()===d.toLowerCase()),y=(m==null?void 0:m.id)||Il(d||l.name||""),h=st[`c:${y}`],b=(h==null?void 0:h.designUrl)||(h==null?void 0:h.conceptUrl);return!qy(b)})},[Ct,le==null?void 0:le.characterRefs,we,st]),ex=!Ct&&et.writtenShots>0,tx=c.useMemo(()=>{const e=Math.max(0,et.writtenShots),o=Math.max(0,et.targetShots);if(o<=0)return n("page.storyflow.episodeContinueAnchorWaiting");if(e>=o)return n("page.storyflow.episodeContinueAnchorCompleted",{target:String(o)});const l=Math.max(1,e+1);return n("page.storyflow.episodeContinueAnchorActive",{nextShot:String(l).padStart(2,"0"),written:String(e),target:String(o)})},[n,et.writtenShots,et.targetShots]),rx=xt||ze||!!Sn.trim()||gm,cl=Ct&&!rx,In=oe==="episode"&&(ze||xt||!!Sn.trim());c.useEffect(()=>{if(!In)return;const e=window.setInterval(()=>fg(o=>o+1),900);return()=>window.clearInterval(e)},[In]);const yd=c.useMemo(()=>[{key:"prep",label:n("page.storyflow.episodeRunStepParseRequest")},{key:"pack",label:n("page.storyflow.episodeRunStepGenerateShotPack")},{key:"polish",label:n("page.storyflow.episodeRunStepContinuityPolish")},{key:"sync",label:n("page.storyflow.episodeRunStepSyncToBoard")}],[n]),dl=c.useMemo(()=>{if(!In&&!Ct)return 0;if(Ct)return 4;if(xt)return 3;const e=Ga.current?Math.max(0,Date.now()-Ga.current):0;return e>=13e3?3:e>=6e3?2:(ze||Sn.trim(),1)},[In,Ct,xt,ze,Sn,mg]);c.useEffect(()=>{if(oe!=="episode"||Vr!=="edit")return;const e=_e??-1;if(Fp.current!==e){Fp.current=e,Ha(cl),za(!cl),$c.current=Ct;return}!$c.current&&Ct&&(Ha(!0),cl&&za(!1)),$c.current=Ct},[oe,Vr,_e,Ct,cl]),c.useEffect(()=>{if(oe!=="episode"||Vr!=="edit")return;const e=_e??0;Fe(o=>{if(e<0||e>=o.length)return o;const l=o[e],d=l.scriptStage||"drafting",m=l.scriptQaDecision??null,y=Eo.radar,h=JSON.stringify(l.scriptQualityRadar||null)!==JSON.stringify(y||null),b=Eo.ready&&d!=="completed"&&d!=="adjusting"&&d!=="adjusted_once"&&m==null&&d!=="qa_reported";if(!b&&!h)return o;const w={...l,scriptQualityRadar:y};return b&&(w.scriptStage="qa_reported"),o.map((g,A)=>A===e?w:g)})},[oe,Vr,_e,Eo]);const wr=c.useCallback(e=>{if(typeof window>"u")return!0;if(!Te.current)return!1;try{const o=Oo(ae),l=o?JSON.parse(o):{},d=(e==null?void 0:e.workspaceAssetMedia)??st,m=sw({liveStoryOutline:U,liveWorldBible:pe,liveSeasonEpisodes:P,liveDashboardSnapshot:Q,liveWorkspaceAssetMedia:d,liveSeriesBibleCharacters:we,base:l}),y={...l,greenlightProjectId:typeof t=="string"?t.trim():void 0,updatedAt:new Date().toISOString(),storyflowDescriptiveScriptSchemaVersion:nw,guidedMode:Wt,guidedStep:Gt,projectName:ge,storyOutline:m.storyOutline,worldBible:m.worldBible,seasonEpisodes:m.seasonEpisodes,plannedEpisodeCount:Ce,episodeDurationSeconds:te,storyflowPlanAck:Dr,storyflowStandaloneFilmMode:ke,seriesBibleCharacters:m.seriesBibleCharacters,dramaCategoryId:rt,dramaCustomNote:Yt,storyflowUiPhase:Be,workspaceMainTab:gt,storyflowLayoutTab:je,storyflowProjectSetupComplete:Qr,foun
752dationLockedAt:tt,storyflowAspectRatio:hp,setupCollaboratorUserIds:xp,selectedHierarchyNodeId:ve,outlinePosterUrl:Vt,outlinePosterSeriesTitle:yi,outlinePosterPrompt:bn.trim()||void 0,worldPosterUrl:Zr,skeletonApplyMode:Hs,skeletonApplyRangeStart:ui,skeletonApplyRangeEnd:pi,dashboardSnapshot:m.dashboardSnapshot,narrativePhase:ja,seriesVisualStyleId:Le,seriesCustomStylePrompt:Oe,seriesVisualStylePickerDismissed:yr,workspaceAssetMedia:m.workspaceAssetMedia,messages:_s(bl(qe,l.messages)),messagesEpisodeUnit:_s(bl(wt,l.messagesEpisodeUnit)),messagesEpisodeUnitByHierarchyId:(()=>{const h=l.messagesEpisodeUnitByHierarchyId&&typeof l.messagesEpisodeUnitByHierarchyId=="object"&&!Array.isArray(l.messagesEpisodeUnitByHierarchyId)?l.messagesEpisodeUnitByHierarchyId:{},b=new Set([...Object.keys(h),...Object.keys(At)]);return Object.fromEntries([...b].map(w=>[w,_s(bl(At[w],h[w]))]))})(),messagesEpisodeByIndex:Object.fromEntries(Object.entries(at).map(([h,b])=>{const w=l.messagesEpisodeByIndex&&typeof l.messagesEpisodeByIndex=="object"&&!Array.isArray(l.messagesEpisodeByIndex)?l.messagesEpisodeByIndex[h]:void 0;return[h,_s(bl(b,w))]}))};return localStorage.setItem(ae,JSON.stringify(y)),e!=null&&e.silent||H.success(n("page.storyflow.savedTitle"),n("page.storyflow.savedLocallyBody")),!0}catch(o){return e!=null&&e.silent||H.error(n("page.storyflow.saveFailedTitle"),o instanceof Error?Bt(o.message):n("page.storyflow.couldNotSaveGeneric")),!1}},[ae,U,pe,P,Q,ja,ge,Ce,te,Dr,ke,we,rt,Yt,Be,Le,Oe,yr,gt,je,Qr,tt,hp,xp,ve,Vt,yi,bn,Zr,Hs,ui,pi,Wt,Gt,st,qe,wt,At,at,n]);Ze.current=wr;const hd=c.useCallback(()=>{Ze.current({silent:!0})},[]),bm=c.useCallback(e=>{wr({silent:e==null?void 0:e.silent})},[wr]),zr=c.useCallback(async e=>{if(wr({silent:!0}),!p)return!0;try{return await p(),!0}catch{return e!=null&&e.showToastOnError&&H.warning(n("page.storyflow.syncPendingTitle"),n("page.storyflow.syncPendingBody")),!1}},[wr,p,n]),To=c.useCallback(e=>{const o=_e??0;Fe(l=>l.map((d,m)=>m===o?{...d,...e}:d))},[_e]),sx=c.useCallback(()=>{if(oe!=="episode"||Vr!=="edit")return;const e=_e??0,o=P[e];if(!o||!Ar)return;const l=No(e),d=Ar.dimensions.filter(y=>y.stars<4),m=d.length?d.map(y=>`- ${y.label}: ${y.note}`).join(` 753`):"- Apply one concise polish pass for hook, continuity, and seed/payoff clarity.";To({scriptStage:"adjusting",scriptQaDecision:"needs_adjustment",scriptQualityRadar:Ar}),or({type:"episode_outline",episodeIndex:e}),qt((at[e]??[]).length),lt(`Do a single focused polish pass for Ep. ${String(e+1).padStart(2,"0")}: "${o.title}". 754 755Only revise the weak points once (no multi-round loop): 756${m} 757 758${l} 759 760${Zi} 761 762Constraints: 7631) Keep episode summary locked. 7642) Keep existing structure; revise weak lines/scenes only. 7653) Keep canon, character consistency, and continuity anchors. 7664) Scope lock: revise ONLY this episode. Do not draft other episodes. 7675) Cross-episode impacts should be notes only in CONTINUITY NOTES. 7686) If this episode is complete, add: EPISODE COMPLETE. You can close this modal and click GO TO Workflow. 7697) Do NOT output delivery checklist / ledger footer sections (including Chinese/English checklist headings).`)},[oe,Vr,_e,P,Ar,To,No,at,lt]),nx=c.useCallback(()=>{To({scriptStage:"qa_reported",scriptQaDecision:"looks_good",scriptQualityRadar:Ar||null})},[To,Ar]),wm=c.useCallback(async()=>{To({scriptStage:"completed",scriptQaDecision:(le==null?void 0:le.scriptQaDecision)||"looks_good",scriptQualityRadar:Ar||null});const e=await zr({showToastOnError:!0});Rn(),H.success(n("page.storyflow.episodeCompletedTitle"),n(e?"page.storyflow.episodeCompletedSyncedBody":"page.storyflow.episodeCompletedPendingBody"))},[To,le==null?void 0:le.scriptQaDecision,Ar,zr,Rn,n]),ox=c.useCallback(async()=>{if(((le==null?void 0:le.scriptStage)||"")!=="completed")return;const e=await zr({showToastOnError:!0});Rn(),H.success(n("page.storyflow.editingFinishedTitle"),n(e?"page.storyflow.editingFinishedSyncedBody":"page.storyflow.editingFinishedPendingBody"))},[le==null?void 0:le.scriptStage,zr,Rn,n]);c.useEffect(()=>{if(typeof window>"u")return;const e=window.setTimeout(()=>{wr({silent:!0})},280);return()=>window.clearTimeout(e)},[wr]),c.useEffect(()=>{if(!t){wa("synced");return}const e=()=>{const l=Zx(t);if(l.lastError){wa("error");return}l.issyncing||l.pendingChanges?wa("pending"):wa("synced")};e();const o=window.setInterval(e,1200);return()=>window.clearInterval(o)},[t]),c.useEffect(()=>{if(!t)return;const e=()=>{if(wl(t)&&!Qr){wr({silent:!0});return}wr({silent:!0});const o=Date.now();o-Gu.current<2500||(Gu.current=o,p&&p().catch(()=>{}))};return window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),()=>{window.removeEventListener("pagehide",e),window.removeEventListener("beforeunload",e)}},[t,p,wr,Qr]),c.useEffect(()=>{if(!t||!p||!Te.current||wl(t)&&!Qr)return;const e=window.setTimeout(()=>{Te.current&&(wl(t)&&!Qr||(Ze.current({silent:!0}),p().catch(()=>{})))},1e3);return()=>window.clearTimeout(e)},[t,p,J,qe,wt,At,at,U,pe,P,Ce,te,ge,Vt,yi,Zr,de,Qr]),c.useEffect(()=>{if(f===void 0)return;const e=String(f||"").trim();e&&Xr(o=>{const l=String(o||"").trim();return l===e||ws(e)&&!ws(l)?o:Wd(l)||!ws(e)?e:o})},[f]);const Sm=c.useMemo(()=>xk(Vt,yi,ge),[Vt,yi,ge]),Ro=c.useRef(null);c.useEffect(()=>()=>{Ro.current&&window.clearTimeout(Ro.current)},[]);const _i=c.useCallback(e=>{!x||!t||(Ro.current&&clearTimeout(Ro.current),Ro.current=setTimeout(()=>{Ro.current=null;const l=e.trim()||"Untitled STORYFLOW";x(l)},450))},[x,t]),ix=c.useCallback(()=>{const e=String(ro||"").trim();e&&(Xr(e),zs(null),x&&t&&x(e))},[ro,x,t]),ax=c.useCallback(()=>{zs(null)},[]),lx=c.useCallback(()=>{const e=Ks;if(!(e!=null&&e.length))return;xn(qi([],e));const o=e.map(l=>({name:l.name,imgUrl:void 0}));Fe(l=>l.map((d,m)=>m===0?{...d,characterRefs:o}:!d.characterRefs||d.characterRefs.length===0?{...d,characterRefs:o.slice(0,6)}:d)),Ia(null)},[Ks]),cx=c.useCallback(()=>{Ia(null)},[]),dx=c.useCallback(()=>{const e=xc;if(!e)return;const{episodeIndex:o,diff:l}=e;Fe(d=>{if(!d[o])return d;const m=[...d];return m[o]={...m[o],generationUnits:l.proposedFull},m}),Pa(null),Ze.current({silent:!0})},[xc]),ux=c.useCallback(()=>{Pa(null)},[]),gd=ro&&!Bs(ro)&&ro.trim()!==String(ge||"").trim()?s.jsxs("div",{className:"mt-1.5 rounded-md border border-amber-500/35 bg-amber-500/10 px-2 py-1.5","data-testid":"storyflow-title-proposal",children:[s.jsx("p",{className:"text-[11px] leading-snug text-amber-100",children:n("page.storyflow.titleProposalHint",{title:ro})}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[s.jsx("button",{type:"button","data-testid":"storyflow-title-proposal-adopt",className:`curs
769or-pointer rounded-md border border-primary/50 bg-primary/20 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-primary transition-colors duration-150 hover:bg-primary/30 ${tn}`,onClick:ix,children:n("page.storyflow.titleProposalAdopt")}),s.jsx("button",{type:"button","data-testid":"storyflow-title-proposal-keep",className:`cursor-pointer rounded-md border border-white/15 bg-black/30 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-slate-400 transition-colors duration-150 hover:border-white/30 hover:text-slate-200 ${tn}`,onClick:ax,children:n("page.storyflow.titleProposalKeep")})]})]}):null,xd=Ks!=null&&Ks.length?s.jsxs("div",{className:"mt-1.5 rounded-md border border-amber-500/35 bg-amber-500/10 px-2 py-1.5","data-testid":"storyflow-cast-replace-proposal",children:[s.jsx("p",{className:"text-[11px] leading-snug text-amber-100",children:n("page.storyflow.castReplaceProposalHint")}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[Ks.slice(0,6).map(e=>s.jsx("span",{className:"rounded border border-white/10 bg-black/25 px-1.5 py-0.5 text-[10px] text-slate-300",children:e.name},e.name)),Ks.length>6?s.jsxs("span",{className:"text-[10px] text-slate-500",children:["+",Ks.length-6]}):null]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[s.jsx("button",{type:"button","data-testid":"storyflow-cast-replace-adopt",className:`cursor-pointer rounded-md border border-primary/50 bg-primary/20 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-primary transition-colors duration-150 hover:bg-primary/30 ${tn}`,onClick:lx,children:n("page.storyflow.castReplaceAdopt")}),s.jsx("button",{type:"button","data-testid":"storyflow-cast-replace-keep",className:`cursor-pointer rounded-md border border-white/15 bg-black/30 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-slate-400 transition-colors duration-150 hover:border-white/30 hover:text-slate-200 ${tn}`,onClick:cx,children:n("page.storyflow.castReplaceKeep")})]})]}):null,bd=xc?s.jsxs("div",{className:"mt-1.5 rounded-md border border-amber-500/35 bg-amber-500/10 px-2 py-1.5","data-testid":"storyflow-sequence-beat-replace-proposal",children:[s.jsx("p",{className:"text-[11px] leading-snug text-amber-100",children:n("page.storyflow.sequenceBeatReplaceProposalHint")}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[s.jsx("button",{type:"button","data-testid":"storyflow-sequence-beat-replace-adopt",className:`cursor-pointer rounded-md border border-primary/50 bg-primary/20 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-primary transition-colors duration-150 hover:bg-primary/30 ${tn}`,onClick:dx,children:n("page.storyflow.sequenceBeatReplaceAdopt")}),s.jsx("button",{type:"button","data-testid":"storyflow-sequence-beat-replace-keep",className:`cursor-pointer rounded-md border border-white/15 bg-black/30 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-slate-400 transition-colors duration-150 hover:border-white/30 hover:text-slate-200 ${tn}`,onClick:ux,children:n("page.storyflow.sequenceBeatReplaceKeep")})]})]}):null;c.useEffect(()=>{var A;if(!E)return;const e=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),o=st[e]||{},l=E.kind==="CHARACTERS"?"reference_led":"consistent",d=((A=Ti[0])==null?void 0:A.id)||"default",m=ds(Le,Oe),y=o.conceptRefImage||"",h=!!String(y||"").trim(),b=typeof o.imageModelId=="string"&&o.imageModelId.trim()?o.imageModelId.trim():Jo,w=on(E.name),g=E.kind==="CHARACTERS"?"":E.kind==="SCENES"?bo.get(w)||"":wo.get(w)||"";if(E.kind==="CHARACTERS"){const j=we.find(W=>W.id===E.characterId)||Et.find(W=>on(W.name)===w),B=Sl({kind:"CHARACTERS",name:E.name,mediaDescription:o.description,bibleOrMarkerDesc:j==null?void 0:j.backstory,markerDesc:j==null?void 0:j.backstory,timeline:pe.timeline,logline:U.logline,synopsis:U.synopsis}),_=rn({timeline:pe.timeline,description:B,logline:U.logline,synopsis:U.synopsis,characterName:E.name}),C=String(o.characterStyleId||d).trim(),R=String(o.characterStyleCustomPrompt||"").trim(),T=$o({assetType:"CHARACTERS",profile:{characterStyleId:C,characterStyleCustomPrompt:R},filmStyleId:ss,stage:"phase2"}),M=na(b)?Vi({kind:"CHARACTERS",name:E.name,description:B,hasReference:h,styleId:m.id,styleLabel:m.label,styleKeywords:m.presetKeywords,periodLock:_,characterStyleHint:T}):"";lr({description:B,imagePrompt:M,imagePromptDirty:!1,conceptUrl:o.conceptUrl||"",conceptRefImage:y,designUrl:o.designUrl||"",generationPath:o.generationPath==="banana2_only"?"banana2_only":"hybrid",styleStrategy:o.styleStrategy==="consistent"||o.styleStrategy==="reference_led"||o.styleStrategy==="exploratory"?o.styleStrategy:l,characterStyleId:C,characterStyleCustomPrompt:R,imageModelId:b,approvedGender:"neutral",characterConfirmed:!1})}else{const j=Sl({kind:E.kind,name:E.name,mediaDescription:o.description,markerDesc:g,bibleOrMarkerDesc:g,timeline:pe.timeline,logline:U.logline,synopsis:U.synopsis}),B=rn({timeline:pe.timeline,description:j,logline:U.logline,synopsis:U.synopsis}),_=na(b)?Vi({kind:E.kind,name:E.name,description:j,hasReference:h,styleId:m.id,styleLabel:m.label,styleKeywords:m.presetKeywords,periodLock:B}):"";lr({description:j,imagePrompt:_,imagePromptDirty:!1,conceptUrl:o.conceptUrl||"",conceptRefImage:y,designUrl:o.designUrl||"",generationPath:o.generationPath==="banana2_only"?"banana2_only":"hybrid",styleStrategy:o.styleStrategy==="consistent"||o.styleStrategy==="reference_led"||o.styleStrategy==="exploratory"?o.styleStrategy:l,characterStyleId:String(o.characterStyleId||d).trim(),characterStyleCustomPrompt:String(o.characterStyleCustomPrompt||"").trim(),imageModelId:b,approvedGender:"neutral",characterConfirmed:!1})}}
769,[E,st,we,Et,Ve,Ti,ss,bo,wo,Le,Oe,pe.timeline,U.logline,U.synopsis]);const px=c.useCallback(()=>{if(!E)return;const e=ds(Le,Oe),o=!!String(L.conceptRefImage||"").trim(),l=rn({timeline:pe.timeline,description:L.description.trim(),logline:U.logline,synopsis:U.synopsis,characterName:E.kind==="CHARACTERS"?E.name:void 0}),d=E.kind==="CHARACTERS"?$o({assetType:"CHARACTERS",profile:{characterStyleId:L.characterStyleId,characterStyleCustomPrompt:L.characterStyleCustomPrompt},filmStyleId:ss,stage:"phase2"}):"",m=Vi({kind:E.kind,name:E.name,description:L.description.trim(),hasReference:o,styleId:e.id,styleLabel:e.label,styleKeywords:e.presetKeywords,periodLock:l,characterStyleHint:d});lr(y=>({...y,imagePrompt:m,imagePromptDirty:!1}))},[E,L.description,L.conceptRefImage,L.characterStyleId,L.characterStyleCustomPrompt,ss,Le,Oe,pe.timeline,U.logline,U.synopsis]);c.useEffect(()=>{if(!E||L.imagePromptDirty||!na(L.imageModelId))return;const e=ds(Le,Oe),o=!!String(L.conceptRefImage||"").trim(),l=rn({timeline:pe.timeline,description:L.description.trim(),logline:U.logline,synopsis:U.synopsis,characterName:E.kind==="CHARACTERS"?E.name:void 0}),d=E.kind==="CHARACTERS"?$o({assetType:"CHARACTERS",profile:{characterStyleId:L.characterStyleId,characterStyleCustomPrompt:L.characterStyleCustomPrompt},filmStyleId:ss,stage:"phase2"}):"",m=Vi({kind:E.kind,name:E.name,description:L.description.trim(),hasReference:o,styleId:e.id,styleLabel:e.label,styleKeywords:e.presetKeywords,periodLock:l,characterStyleHint:d});lr(y=>y.imagePromptDirty||y.imagePrompt===m?y:{...y,imagePrompt:m})},[E,L.description,L.conceptRefImage,L.imageModelId,L.imagePromptDirty,L.characterStyleId,L.characterStyleCustomPrompt,ss,Le,Oe,pe.timeline,U.logline,U.synopsis]),c.useEffect(()=>{if(!E){Lp(!1),Fa(!1),Pc(!1),Bc(!1),Ya.current=!1,Va.current=!1,Si.current=0,ki.current=0,Da(""),gi(""),Ua(""),kn(!1),ho(null),vi("concept"),Ci([]),ut.current.concept!=null&&(window.clearTimeout(ut.current.concept),ut.current.concept=null),ut.current.design!=null&&(window.clearTimeout(ut.current.design),ut.current.design=null),pt.current={key:"",conceptPrompt:"",designPrompt:""};return}let e=!1;Lp(!1),Fa(!0);const o=window.setTimeout(()=>{var B;if(e)return;const l=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),d=(((B=st[l])==null?void 0:B.description)||"").trim();if(d.length>=20&&!/notes inferred from BloomBot chat/i.test(d)){e||Fa(!1);return}const y=on(E.name),h=E.kind==="SCENES"?bo.get(y)||"":E.kind==="PROPS"&&wo.get(y)||"",b=E.kind==="CHARACTERS"?we.find(_=>_.name.trim().toLowerCase()===E.name.trim().toLowerCase())||Et.find(_=>on(_.name)===y):void 0,w=Sl({kind:E.kind,name:E.name,mediaDescription:d,bibleOrMarkerDesc:(b==null?void 0:b.backstory)||h,markerDesc:h||(b==null?void 0:b.backstory),timeline:pe.timeline,logline:U.logline,synopsis:U.synopsis}),g=E.kind==="CHARACTERS"?Dy(Rs,E.name).trim()||jC(Rs,E.name).trim():E.kind==="PROPS"?AC(Rs,E.name).trim():"",A=g||IC(Rs,E.kind,E.name);let j=w;(Of(j)||g&&g.length>String(j).length+40)&&(j=g||w||A),j&&lr(_=>{const C=(_.description||"").trim();return C.length>=20&&!/notes inferred from BloomBot chat/i.test(C)?_:{..._,description:j}}),e||Fa(!1)},120);return()=>{e=!0,window.clearTimeout(o)}},[E,Rs,st,Ve,we,Et,bo,wo,pe.timeline,U.logline,U.synopsis]);const jo=c.useCallback(()=>E?Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name):"",[E,Ve]),js=c.useCallback(e=>{if(!E)return;const o=(e==null?void 0:e.draftOverride)??L,l=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);rs(d=>{var y,h,b;const m={...d,[l]:{...d[l],description:o.description.trim()||void 0,generationPath:o.generationPath,styleStrategy:o.styleStrategy,characterStyleId:o.characterStyleId||void 0,characterStyleCustomPrompt:o.characterStyleCustomPrompt||void 0,conceptUrl:o.conceptUrl.trim()||void 0,conceptRefImage:((y=o.conceptRefImage)==null?void 0:y.trim())||void 0,designUrl:o.designUrl.trim()||void 0,conceptHistoryUrls:cs((h=d[l])==null?void 0:h.conceptHistoryUrls,[o.conceptUrl]),designHistoryUrls:cs((b=d[l])==null?void 0:b.designHistoryUrls,[o.designUrl])}};return queueMicrotask(()=>{try{Ze.current({silent:!0,workspaceAssetMedia:m})}catch{}}),m}),E.kind==="CHARACTERS"&&xn(d=>d.findIndex(y=>y.id===E.characterId)>=0?d.map(y=>y.id===E.characterId?{...y,backstory:o.description.trim()}:y):[...d,{id:E.characterId,name:E.name,backstory:o.description.trim()}]),(e==null?void 0:e.close)!==!1&&Mp(null)},[E,L,Ve]),Bi=c.useMemo(()=>String(L.designUrl||L.conceptUrl||"").trim(),[L.designUrl,L.conceptUrl]);c.useEffect(()=>{if(!E){Ja(!1),go(!1),Ei(!1);return}Ja(!1),go(!1);const e=String(L.designUrl||L.conceptUrl||"").trim();if(!e||E.kind!=="CHARACTERS")return;let o=!1;return Nf(e).then(l=>{o||go(l)}).catch(()=>{o||go(!1)}),()=>{o=!0}},[E,L.designUrl,L.conceptUrl]);const mx=c.useCallback(async()=>
769{if(!E||Ni)return;const e=Bi;if(!e)return;const o=typeof t=="string"?t.trim():"";if(!o){H.warning(n("page.storyflow.toastTitleBloomBot"),n("canvas.library.quickActionMissingProject"));return}Ei(!0);try{const l=Hd(e),d=await Ef({projectId:o,name:E.name,type:E.kind,imageUrl:l},void 0,{replaceSameNameSlot:!0});if(!await Tf(o,d.asset,e,l,E.kind))throw new Error(n("canvas.library.quickActionProjectVerifyFailed"));Ja(!0),Rf(o,d.asset),H.success(n("page.storyflow.toastTitleBloomBot"),n("canvas.library.quickActionProjectDone"))}catch(l){H.warning(n("page.storyflow.toastTitleBloomBot"),Bt(l))}finally{Ei(!1)}},[t,n,Ni,E,Bi]),fx=c.useCallback(async()=>{if(!E||Ni)return;if(E.kind!=="CHARACTERS"){H.info(n("page.storyflow.toastTitleBloomBot"),n("canvas.library.quickActionApprovedIneligible"));return}const e=Bi;if(!e)return;const o=typeof t=="string"?t.trim():"";Ei(!0);try{if(await Nf(e)){go(!0),await jf(100),H.success(n("page.storyflow.toastTitleBloomBot"),n("canvas.library.quickActionApprovedAlreadyInLibrary"));return}if(o&&!Dc){const y=Hd(e),h=await Ef({projectId:o,name:E.name,type:"CHARACTERS",imageUrl:y},void 0,{replaceSameNameSlot:!0});if(!await Tf(o,h.asset,e,y,"CHARACTERS"))throw new Error(n("canvas.library.quickActionProjectVerifyFailed"));Ja(!0),Rf(o,h.asset)}const l=Hd(e);if(!ow({imageUrl:l,assetName:E.name,assetKind:"CHARACTERS",libraryAssetType:"CHARACTERS"}).ok)throw new Error(n("canvas.library.quickActionApprovedIneligible"));const m=await iw({imageUrl:l,assetName:E.name,sourceProjectId:o||void 0,libraryAssetType:"CHARACTERS",tags:{gender:L.approvedGender||"neutral",assetKind:"CHARACTERS"}});await jf(100),aw(m.atlasAssetId),go(!0),lr(y=>({...y,characterConfirmed:!0})),H.success(n("page.storyflow.toastTitleBloomBot"),n("canvas.library.quickActionApprovedDone")),lw().catch(()=>{})}catch(l){H.warning(n("page.storyflow.toastTitleBloomBot"),Bt(l))}finally{Ei(!1)}},[t,n,Ni,E,L.approvedGender,Bi,Dc]);c.useEffect(()=>{const e=jo();e&&pt.current.key!==e&&(pt.current={key:e,conceptPrompt:"",designPrompt:""})},[jo]);const Pn=c.useCallback(e=>{Mp(e)},[]),km=c.useMemo(()=>{var l;if(!E)return[];const e=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),o=(l=st[e])==null?void 0:l.conceptMjVariants;return Array.isArray(o)&&o.length>1?o:[]},[E,st,Ve]),vm=c.useMemo(()=>{if(!E)return[];const e=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),o=st[e]||{};return cs(o.conceptHistoryUrls,[L.conceptUrl,...o.conceptMjVariants||[],o.conceptUrl])},[E,st,Ve,L.conceptUrl]),Cm=c.useMemo(()=>{if(!E)return[];const e=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),o=st[e]||{};return cs(o.designHistoryUrls,[L.designUrl,o.designUrl])},[E,st,Ve,L.designUrl]);c.useMemo(()=>{const e=String(L.characterStyleId||"").trim();return Ti.find(o=>o.id===e)||Ti[0]||null},[L.characterStyleId,Ti]);const yx=c.useMemo(()=>"16:9",[E]),ul=c.useCallback(()=>{var l;if(!E)return null;const e=E.kind==="CHARACTERS"?"CHARACTERS":E.kind==="SCENES"?"SCENES":"PROPS",o=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);return{id:PC(o),name:E.name,type:e,desc:L.description||"",conceptImage:L.conceptUrl||void 0,conceptRefImage:((l=L.conceptRefImage)==null?void 0:l.trim())||void 0,assetProfile:{generationPath:L.generationPath,styleStrategy:L.styleStrategy,characterDesign:L.description||void 0,...E.kind==="CHARACTERS"?{characterStyleId:L.characterStyleId||void 0,characterStyleCustomPrompt:L.characterStyleCustomPrompt||void 0}:{}}}},[E,L.description,L.conceptUrl,L.conceptRefImage,L.generationPath,L.styleStrategy,L.characterStyleId,L.characterStyleCustomPrompt,Ve]),Kr=c.useCallback(async(e,o)=>{const l=String(e||"").trim();if(!l||!t||!E)return l;try{if(/^https?:\/\/(?:cdn\.bloomway\.ai|storage\.googleapis\.com)\//i.test(l))return l;let m=l;if(l.startsWith("blob:")||/^https?:\/\//i.test(l)){const A=await fetch(l);if(!A.ok)throw new Error("Could not fetch generated image for storage.");const j=await A.blob();m=await new Promise((B,_)=>{const C=new FileReader;C.onload=()=>B(String(C.result||"")),C.onerror=()=>_(new Error("Could not encode image.")),C.readAsDataURL(j)})}if(!m.startsWith("data:image"))return l;const h=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name).replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,64)||"asset",b=`storyflow-${o}-${h}-${Date.now()}.png`,w=await db(m,b,t,"images");return String((w==null?void 0:w.url)||"").trim()||l}catch(d){return H.warning(n("page.storyflow.storageTitle"),d instanceof Error?Bt(d.message):n("page.storyflow.persistImageFailedGeneric")),l}},[t,E,Ve,n]),hx=c.useCallback(async e=>{if(!E)return;const o=String(e||"").trim();if(!o.startsWith("data:image"))throw H.warning(n("page.storyflow.persistImageFailedGeneric"),""),new Error("invalid image");Xa(!0),gi("");try{const l=await Kr(o,"design");if((!l||l.startsWith("data:"))&&!l)throw new Error("upload failed");const d=l||o,m=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);lr(y=>({...y,designUrl:d})),rs(y=>{const h=y[m]||{},b={...h,designUrl:d,designHistoryUrls:cs(h.designHistoryUrls,[d])},w={...y,[m]:b};return window.setTimeout(()=>{Ze.current({silent:!0,workspaceAssetMedia:w})},0),w}),H.success(n("page.storyflow.uploadLocalImageReadyTitle"),n("page.storyflow.uploadLocalImageReadyBody"))}catch(l){throw H.warning(n("page.storyflow.persistImageFailedGeneric"),Bt(l)),l}finally{Xa(!1)}},[E,Kr,Ve,n]),gx=c.useCallback(async e=>{if(!E)return;const o=String(e||"").trim();if(!o.startsWith("data:image"))throw H.warning(n("page.storyflow.persistImageFailedGeneric"),""),new Error("invalid image");Xa(!0);try{const d=await Kr(o,"concept")||o,m=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);lr(y=>({...y,conceptRefImage:d})),rs(y=>{const b={...y[m]||{},conceptRefImage:d},w={...y,[m]:b};return window.setTimeout(()=>{Ze.current({silent:!0,workspaceAssetMedia:w})},0),w}),H.success(n("page.storyflow.uploadReferenceReadyTitle"),n("page.storyflow.uploadReferenceReadyBody"))}catch(l){throw H.warning(n("page.storyflow.persistImageFailedGeneric"),Bt(l)),l}finally{Xa(!1)}},[E,Kr,Ve,n]),xx=c.useCallback(async e=>{if(!E)return;const o=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name),l=await Kr(e,"concept");lr(m=>({...m,conceptUrl:l,designUrl:l,conceptRefImage:""}
769)),rs(m=>{var h,b,w,g;const y={...m,[o]:{...m[o],description:L.description.trim()||((h=m[o])==null?void 0:h.description),generationPath:L.generationPath,styleStrategy:L.styleStrategy,characterStyleId:L.characterStyleId||void 0,characterStyleCustomPrompt:L.characterStyleCustomPrompt||void 0,conceptUrl:l,designUrl:l,conceptRefImage:void 0,conceptMjVariants:(b=m[o])==null?void 0:b.conceptMjVariants,conceptHistoryUrls:cs((w=m[o])==null?void 0:w.conceptHistoryUrls,[l]),designHistoryUrls:cs((g=m[o])==null?void 0:g.designHistoryUrls,[l])}};return queueMicrotask(()=>{try{Ze.current({silent:!0,workspaceAssetMedia:y})}catch{}}),y}),kn(!1),ho(null);const d={...L,conceptUrl:l,conceptRefImage:""};js({close:!1,draftOverride:d})},[E,Ve,Kr,js,L,L.description,L.designUrl,L.generationPath,L.styleStrategy,L.characterStyleId,L.characterStyleCustomPrompt]),Nm=c.useCallback(async e=>{if(!E)return;if(!Ee){H.warning(n("page.storyflow.conceptDesignProRequiredTitle"),n("page.storyflow.conceptDesignProRequiredBody"));return}if(!t){H.warning(n("page.storyflow.generationUnavailableTitle"),n("page.storyflow.generationUnavailableBody"));return}if(Ya.current||Ic)return;const o=ul();if(!o)return;const l=jo(),d=e!=null&&e.reuseCachedPrompt&&l&&pt.current.key===l&&pt.current.conceptPrompt?pt.current.conceptPrompt:void 0;!(e!=null&&e.reuseCachedPrompt)&&l&&(pt.current.key!==l?pt.current={key:l,conceptPrompt:"",designPrompt:""}:pt.current.conceptPrompt=""),e!=null&&e.reuseCachedPrompt||(Si.current=0),Da(""),Ya.current=!0,Pc(!0);try{const m=ds(Le,Oe),y=$o({assetType:o.type,profile:o.assetProfile,filmStyleId:ss,stage:Hr.includes("midjourney")?"mj":"banana2"}),h=`FILM STYLE LOCK: ${m.label}. (Server expands full preset keywords from styleId=${m.id}.)`,b=await $f({asset:o,worldContext:Ys,projectId:t,modelId:kl(Hr)?Hr:"midjourney/relaxed",resultSlot:"concept",fixedPrompt:d,profileConceptDescriptionOverride:d?void 0:(()=>{const R=zd(L.description);return E.kind==="CHARACTERS"?Yo(R).slice(0,6e3)||void 0:[R,Ys].filter(Boolean).join(` 770 771`).slice(0,6e3)||void 0})(),visualStyleCompose:{styleId:String(m.id||Le||"Cinematic").trim()||"Cinematic",...m.presetKeywords?{customStylePrompt:m.presetKeywords}:{},hasCharacterRefs:o.type==="CHARACTERS"},promptSuffixLines:[h,E.kind==="CHARACTERS"?rn({timeline:pe.timeline,description:L.description,logline:U.logline,synopsis:U.synopsis,characterName:E.name}):"",y].filter(Boolean).join(` 772`),onPromptResolved:R=>{l&&(pt.current.key!==l&&(pt.current={key:l,conceptPrompt:"",designPrompt:""}),pt.current.conceptPrompt||(pt.current.conceptPrompt=R))}}),w=Array.isArray(b)?b.map(R=>String(R||"").trim()).filter(Boolean):[String(b||"").trim()].filter(Boolean);if(w.length===0)throw new Error("No concept image was returned.");let g,A;if(w.length>1){const R=[];for(const T of w)R.push(await Kr(T,"concept"));A=R,g=R[R.length-1]||R[0]||""}else g=await Kr(w[0],"concept"),A=void 0;if(!g)throw new Error("No concept image was returned.");const j=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);lr(R=>({...R,conceptUrl:g,designUrl:g,conceptRefImage:""}));const B=st[j],_={...B,description:L.description.trim()||(B==null?void 0:B.description),generationPath:L.generationPath,styleStrategy:L.styleStrategy,characterStyleId:L.characterStyleId||void 0,characterStyleCustomPrompt:L.characterStyleCustomPrompt||void 0,imageModelId:L.imageModelId||Hr,conceptUrl:g,designUrl:g,conceptRefImage:void 0,conceptMjVariants:A,conceptHistoryUrls:cs(B==null?void 0:B.conceptHistoryUrls,[g,...w]),designHistoryUrls:cs(B==null?void 0:B.designHistoryUrls,[g])},C={...st,[j]:_};rs(C),js({close:!1,draftOverride:{...L,conceptUrl:g,designUrl:g,conceptRefImage:""}}),wr({silent:!0,workspaceAssetMedia:C}),Si.current=0,H.success(n("page.storyflow.conceptReadyTitle"),n("page.storyflow.conceptReadyBody")),A&&A.length>1&&(vi("concept"),Ci(A),kn(!0)),ut.current.concept!=null&&(window.clearTimeout(ut.current.concept),ut.current.concept=null)}catch(m){H.warning(n("page.storyflow.generationFailedTitle"),Bt(m));const y=Si.current+1;y<=Dp?(Si.current=y,Da("Generation failed, will auto regenerate in 1 minute."),ut.current.concept!=null&&window.clearTimeout(ut.current.concept),ut.current.concept=window.setTimeout(()=>{ut.current.concept=null,Nm({reuseCachedPrompt:!0})},6e4)):(Da(n("page.storyflow.assetAutoRetryStoppedBody")),H.info(n("page.storyflow.assetAutoRetryStoppedTitle"),n("page.storyflow.assetAutoRetryStoppedBody")))}finally{Ya.current=!1,Pc(!1)}},[E,t,Ic,ul,Ys,Hr,Kr,js,Ve,L,L.description,L.designUrl,L.generationPath,L.styleStrategy,L.characterStyleId,L.characterStyleCustomPrompt,jo,n,st,wr,Ee]),Em=c.useCallback(async e=>{var y;if(!E)return;if(!t){H.warning(n("page.storyflow.generationUnavailableTitle"),n("page.storyflow.generationUnavailableBody"));return}if(Va.current||_c)return;const o=ul();if(!o)return;const l=jo(),d=e!=null&&e.reuseCachedPrompt&&l&&pt.current.key===l&&pt.current.designPrompt?pt.current.designPrompt:void 0;!(e!=null&&e.reuseCachedPrompt)&&l&&(pt.current.key!==l?pt.current={key:l,conceptPrompt:"",designPrompt:""}:pt.current.designPrompt=""),e!=null&&e.reuseCachedPrompt||(ki.current=0),gi(""),Va.current=!0,Bc(!0);let m=L.description.trim();try{const h=String(L.imageModelId||Hr||"google/gemini-3.1-flash-image-preview").trim(),b=kl(h)?h:h.startsWith("seedream/")?"seedream/5-lite-text-to-image":"google/gemini-3.1-flash-image-preview";let w;const g=!!String(L.conceptRefImage||"").trim(),A=!h.includes("midjourney")&&!kl(h);if(!A&&(kl(h)||h.includes("gemini")||h.startsWith("seedream/"))){const M=ds(Le,Oe),W=$o({assetType:o.type,profile:o.assetProfile,filmStyleId:ss,stage:"banana2"});w=await $f({asset:o,worldContext:Ys,projectId:t,modelId:b==="midjourney/relaxed"?"google/gemini-3.1-flash-image-preview":b,resultSlot:"concept",fixedPrompt:d,profileConceptDescriptionOverride:d?void 0:(()=>{const q=zd(L.description);return E.kind==="CHARACTERS"?Yo(q).slice(0,6e3)||void 0:[q,Ys].filter(
772Boolean).join(` 773 774`).slice(0,6e3)||void 0})(),visualStyleCompose:{styleId:String(M.id||Le||"Cinematic").trim()||"Cinematic",...M.presetKeywords?{customStylePrompt:M.presetKeywords}:{},hasCharacterRefs:o.type==="CHARACTERS"},promptSuffixLines:[`FILM STYLE LOCK: ${M.label}. (Server expands full preset keywords from styleId=${M.id}.)`,E.kind==="CHARACTERS"?rn({timeline:pe.timeline,description:L.description,logline:U.logline,synopsis:U.synopsis,characterName:E.name}):"",W].filter(Boolean).join(` 775`),onPromptResolved:q=>{l&&(pt.current.key!==l&&(pt.current={key:l,conceptPrompt:"",designPrompt:""}),pt.current.designPrompt||(pt.current.designPrompt=q))}})}else{const M=Ew(A?h||Jo:h,!0,g),W=ds(Le,Oe),q=String(L.imagePrompt||"").trim();let G=zd(L.description),Y="";const F=on(E.name),V=E.kind==="SCENES"?bo.get(F)||"":E.kind==="PROPS"&&wo.get(F)||"";if(A&&!d){const ce=E.kind==="CHARACTERS"?we.find(se=>se.id===E.characterId):void 0,he=Sl({kind:E.kind,name:E.name,mediaDescription:G,bibleOrMarkerDesc:(ce==null?void 0:ce.backstory)||V,markerDesc:V||(ce==null?void 0:ce.backstory),timeline:pe.timeline,logline:U.logline,synopsis:U.synopsis});G=he,Y=rn({timeline:pe.timeline,description:he,logline:U.logline,synopsis:U.synopsis,characterName:E.kind==="CHARACTERS"?E.name:void 0})}if(E.kind==="CHARACTERS"&&A&&!d){const ce=we.find(Ke=>Ke.id===E.characterId),he=G,se=Iw({characterName:E.name,description:he,backstory:ce==null?void 0:ce.backstory,worldContext:Ys,homepageChat:Rs,logline:U.logline,synopsis:U.synopsis});try{const Ke=await ub({scriptText:se,characterName:E.name,staleDescriptionHint:he}),De=String(Ke||"").trim();G=De.length>=40?De:he}catch{G=he}Of(L.description)||G!==L.description.trim()?(m=G,lr(Ke=>({...Ke,description:G}))):m=G}else E.kind==="CHARACTERS"&&(Y=rn({timeline:pe.timeline,description:G,logline:U.logline,synopsis:U.synopsis,characterName:E.name}));const X=d||(A?Yo(L.imagePromptDirty&&q?q:Vi({kind:E.kind,name:E.name,description:G,hasReference:g,styleId:W.id,styleLabel:W.label,styleKeywords:W.presetKeywords,periodLock:Y||void 0,characterStyleHint:E.kind==="CHARACTERS"?$o({assetType:"CHARACTERS",profile:{characterStyleId:L.characterStyleId,characterStyleCustomPrompt:L.characterStyleCustomPrompt},filmStyleId:ss,stage:"phase2"}):void 0})):E.kind==="CHARACTERS"?[Yo(G),Y].filter(Boolean).join(` 776 777`):[G,Ys].filter(Boolean).join(` 778 779`));l&&!d&&(pt.current.key!==l&&(pt.current={key:l,conceptPrompt:"",designPrompt:""}),pt.current.designPrompt=X,A&&q!==X&&lr(ce=>ce.imagePrompt===X?ce:{...ce,imagePrompt:X})),w=await pb({prompt:X,aspectRatio:Wh,size:wv,modelId:M,projectId:t,nodeId:`storyflow-asset-${E.kind}`,skipFullBleedLock:!0,visualStyleCompose:{styleId:String(W.id||Le||"Cinematic").trim()||"Cinematic",...W.presetKeywords?{customStylePrompt:W.presetKeywords}:{},hasCharacterRefs:g||E.kind==="CHARACTERS"},...g?{refImages:[String(L.conceptRefImage).trim()]}:{}})}const j=_C(w);if(!j)throw new Error("No design image was returned.");const B=await Kr(j,"design"),_=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);lr(M=>({...M,designUrl:B,description:m||M.description}));const C=st[_],R={...C,description:m||(C==null?void 0:C.description),generationPath:L.generationPath,styleStrategy:L.styleStrategy,characterStyleId:L.characterStyleId||void 0,characterStyleCustomPrompt:L.characterStyleCustomPrompt||void 0,conceptUrl:L.conceptUrl.trim()||(C==null?void 0:C.conceptUrl),conceptRefImage:((y=L.conceptRefImage)==null?void 0:y.trim())||(C==null?void 0:C.conceptRefImage),designUrl:B,conceptHistoryUrls:C==null?void 0:C.conceptHistoryUrls,designHistoryUrls:cs(C==null?void 0:C.designHistoryUrls,[B])},T={...st,[_]:R};rs(T),js({close:!1,draftOverride:{...L,description:m||L.description,designUrl:B}}),wr({silent:!0,workspaceAssetMedia:T}),ki.current=0,H.success(n("page.storyflow.designReadyTitle"),n("page.storyflow.designReadyBody")),ut.current.design!=null&&(window.clearTimeout(ut.current.design),ut.current.design=null)}catch(h){H.warning(n("page.storyflow.generationFailedTitle"),Bt(h));const b=ki.current+1;b<=Dp?(ki.current=b,gi("Generation failed, will auto regenerate in 1 minute."),ut.current.design!=null&&window.clearTimeout(ut.current.design),ut.current.design=window.setTimeout(()=>{ut.current.design=null,Em({reuseCachedPrompt:!0})},6e4)):(gi(n("page.storyflow.assetAutoRetryStoppedBody")),H.info(n("page.storyflow.assetAutoRetryStoppedTitle"),n("page.storyflow.assetAutoRetryStoppedBody")))}finally{Va.current=!1,Bc(!1)}}
779,[E,t,_c,ul,Ys,Rs,we,pe.timeline,U.logline,U.synopsis,Le,Oe,Kr,js,Ve,L,L.description,L.imagePrompt,L.imagePromptDirty,L.conceptUrl,L.generationPath,L.styleStrategy,L.characterStyleId,L.characterStyleCustomPrompt,jo,n,st,wr]),bx=c.useCallback(e=>{const o=String(e||"").trim();o&&Ua(o)},[]);c.useCallback(e=>{const o=e==="concept"?vm:Cm;if(!o.length){H.info(n("page.storyflow.noHistoryTitle"),n("page.storyflow.noHistoryBody"));return}const l=e==="concept"?gg.current:xg.current,d=l==null?void 0:l.getBoundingClientRect();vi(e),Ci(o),ho(d?{top:d.top,left:d.left,width:d.width,height:d.height}:null),kn(!0)},[vm,Cm,n]),c.useCallback(async(e,o)=>{const l=String(e||"").trim();if(l)try{let d=l,m=null;if(!l.startsWith("data:")&&!l.startsWith("blob:")){const h=await fetch(l);if(!h.ok)throw new Error("Download request failed.");const b=await h.blob();d=URL.createObjectURL(b),m=d}const y=document.createElement("a");y.href=d,y.download=o,y.rel="noopener",document.body.appendChild(y),y.click(),document.body.removeChild(y),m&&window.setTimeout(()=>URL.revokeObjectURL(m),1200)}catch(d){H.warning(n("page.storyflow.downloadFailedTitle"),d instanceof Error?Bt(d.message):n("page.storyflow.downloadImageFailedBody"))}},[n]),c.useEffect(()=>{if(!E)return;const e=o=>{o.key==="Escape"&&js({close:!0})};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[E,js]),c.useEffect(()=>S?(S(async()=>{bm({silent:!0})}),()=>S(null)):void 0,[S,bm]);const Tm=c.useCallback(async()=>{const e=GC(ge,U,pe,P,we),o=YC(e);try{const{Document:l,Packer:d,Paragraph:m,TextRun:y}=await Xl(async()=>{const{Document:_,Packer:C,Paragraph:R,TextRun:T}=await import("./index-CdieiN8Z.js");return{Document:_,Packer:C,Paragraph:R,TextRun:T}},[]),b=o.split(/\r?\n/).map(_=>new m({children:[new y({text:_.length>0?_:" "})]})),w=new l({sections:[{properties:{},children:b}]}),g=await d.toBlob(w),A=URL.createObjectURL(g),j=document.createElement("a");j.href=A;const B=ge.replace(/[^\w\-]+/g,"_").slice(0,40)||"STORYFLOW";j.download=`${B}-export-${new Date().toISOString().slice(0,10)}.docx`,j.click(),URL.revokeObjectURL(A),H.success(n("page.storyflow.exportedTitle"),n("page.storyflow.exportedBody"))}catch(l){console.error("[Storyflow] export docx failed",l),H.warning(n("page.storyflow.exportedTitle"),n("page.storyflow.exportDocxFailedBody"))}},[ge,U,pe,P,we,n]);c.useEffect(()=>{if(k)return k(async()=>{await Tm()}),()=>k(null)},[k,Tm]),c.useCallback(e=>{Jn(e)},[]);const Ao=c.useCallback(e=>{var B,_,C;const o=(e==null?void 0:e.episodeIndex)??Sa;if(o==null)return;const l=ns;if(!l.allReady&&!(e!=null&&e.bypassWarnings))return;const d=(ge||"").trim()||"Untitled StoryFlow";vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:J.filter(R=>R.role==="user").map(R=>String(R.text||"")).filter(Boolean)});const m=typeof(e==null?void 0:e.unitIndex)=="number",y=cw({seriesTitle:d,episodeIndex:o,unitIndex:m?e.unitIndex:void 0,fallbackTitle:"Untitled StoryFlow"}),h=P[o];if(!h){Jn(null);return}const b=ds(Le,Oe),w=String((e==null?void 0:e.scriptOverride)||"").trim()||Rt(h).trim();if(!w){H.warning(n("page.storyflow.goToWorkflowNeedsScript"));return}const{text:g}=dw(w),A=h.scriptFormat&&h.scriptFormat!=="unknown"?h.scriptFormat:eh(g),j={v:1,handoffVersion:"1",sourceProjectId:(t||"").trim()||void 0,source:"creative_brain",seriesTitle:((ge||"").trim()||"Untitled Series").trim(),episodeIndex:o,unitIndex:m?e.unitIndex:void 0,unitLabel:m&&String((e==null?void 0:e.unitLabel)||"").trim()||void 0,defaultProjectName:y,outlineComplete:l.episodeListReady,episodeId:h.id,episodeTitle:h.title,episodeSummary:h.summary,episodeDetailedScript:g,scriptFormat:A,episodeScenes:(B=h.scenes)!=null&&B.length?[...h.scenes]:void 0,episodeProps:(_=h.props)!=null&&_.length?[...h.props]:void 0,episodeCharacterNames:(C=h.characterRefs)!=null&&C.length?h.characterRefs.map(R=>(R.name||"").trim()).filter(Boolean):void 0,storyLogline:U.logline,storySynopsis:U.synopsis,worldBibleSnapshot:{...pe},seriesVisualStyleId:b.id,seriesVisualStyleLabel:b.label,seriesVisualStylePresetKeywords:b.presetKeywords||void 0,episodeDurationSeconds:We(typeof h.durationMin=="number"&&h.durationMin>0?Math.round(h.durationMin*60):te),savedAt:new Date().toISOString()};try{if(typeof window<"u"){const R={v:1,savedAt:new Date().toISOString(),sourceProjectName:ge,storyOutline:{logline:U.logline,synopsis:U.synopsis},worldBible:{...pe},seasonEpisodes:P.map(T=>{var M;return{title:T.title,summary:T.summary,characterRefs:(M=T.characterRefs)==null?void 0:M.map(W=>({name:W.name})),scenes:T.scenes?[...T.scenes]:void 0,props:T.props?[...T.props]:void 0}}),dashboardData:Q};sessionStorage.setItem(Cf,JSON.stringify(R))}}catch{}
779Jn(null),os("guided_create_workflow",{episodeIndex:o,bypassWarnings:!!(e!=null&&e.bypassWarnings),readinessAllReady:l.allReady}),a==null||a({episodeIndex:o,projectName:y,handoff:j}).catch(R=>{H.error(n("page.storyflow.createWorkflowFailedTitle"),R instanceof Error?Bt(R.message):n("page.storyflow.tryAgainGeneric"))}),zr({showToastOnError:!1})},[Sa,ns,P,te,Le,Oe,t,a,os,n,ge,U,pe,Q,zr,ke,Ce,J]),Io=c.useCallback(()=>{},[]),wd=c.useCallback((e,o)=>{},[]),Sd=c.useCallback(e=>{},[]),_n=c.useCallback(e=>{N(null),$s(e),e!=="Custom (Upload Ref)"&&(ri(null),Or("")),Er(!0),Tr(!1),hr(null)},[]);c.useCallback(()=>{Er(!1),Tr(!0)},[]);const wx=c.useCallback(()=>{var e;if(St){if(St.kind==="preset"){_n(St.style.id);return}Oe.trim()?_n("Custom (Upload Ref)"):(hr(null),(e=K.current)==null||e.click())}},[St,Oe,_n]);c.useEffect(()=>{if(!si&&!St)return;const e=o=>{o.key==="Escape"&&(St?hr(null):Tr(!1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[si,St]);const kd=c.useCallback(async e=>{var d;const o=(d=e.target.files)==null?void 0:d[0];if(e.target.value="",!o)return;const l=new FileReader;l.onloadend=async()=>{const m=l.result;ri(m),$s("Custom (Upload Ref)"),ni(!0);try{const y=await Qy(m),h=await ih(y);h.success&&h.styleKeywords?(Or(h.styleKeywords),Er(!0)):(H.warning(n("page.storyflow.styleAnalysisTitle"),n("page.storyflow.styleNoKeywordsBody")),Or(""))}catch(y){H.warning(n("page.storyflow.styleAnalysisTitle"),Bt(y instanceof Error?y.message:String(y))),Or("")}finally{ni(!1)}},l.readAsDataURL(o)},[n]),Mi=c.useMemo(()=>{if(Le==="Custom (Upload Ref)"&&Oe.trim()){const e=Oe.trim();return e.length>42?`${e.slice(0,39)}â¦`:e}return us(Le,z)},[Le,Oe,z]),Sx=Wt&&Gt!=="episode_board";c.useCallback(()=>{if(gn(e=>!e),cp){Ra(!1);try{localStorage.setItem(uu,"1")}catch{}}},[cp]),c.useEffect(()=>{if(!Wt||Gt!=="assets")return;gn(!1),mc(!0);const e=window.setTimeout(()=>mc(!1),2900);return()=>window.clearTimeout(e)},[Wt,Gt]);const vd=c.useRef(!1),Cd=c.useCallback(async()=>{{try{Ze.current({silent:!0})}catch{}await zr();return}},[st,we,md,zr]);c.useCallback(()=>{},[Ce,Z,te,Cd]),c.useEffect(()=>{if(Be!=="workspace"){vd.current=!1;return}Te.current&&(vd.current||(vd.current=!0,Cd()))},[Be,de,Cd]),c.useCallback(()=>{Aa("immersive")},[]);const pl=c.useCallback(()=>{Ht("characters"),ko(e=>e.trim()?e:n("page.storyflow.characterDraftInputSuggestion"))},[n]);c.useCallback(()=>{Co("outline")},[Co]),c.useCallback(()=>{pd()},[pd]),c.useCallback(()=>{Ws("episode_board"),Nt(100),kt(e=>({...e,episodeCount:!0})),dp("overwrite_range"),up(1),pp(100),Ds(n("page.storyflow.generate100EpisodeSkeletonPrompt")),os("guided_step_prompt",{step:"episode_board",source:"generate_100_skeleton"})},[n,os]),c.useCallback(()=>{const e=J.filter(_=>_.role==="assistant");if(e.length===0){H.info(n("page.storyflow.skeletonNoReplyTitle"),n("page.storyflow.skeletonNoReplyBody"));return}let o=[];for(let _=e.length-1;_>=0;_--){const C=e[_],R=[String(C.rawAssistantReply||""),String(C.text||"")];let T=[];for(const M of R){const W=t1(M);W.length>T.length&&(T=W)}if(T.length>0){o=T;break}}if(o.length===0){H.warning(n("page.storyflow.skeletonParseTitle"),n("page.storyflow.skeletonParseBody"));return}const l=o.reduce((_,C)=>Math.max(_,C.episodeNo),0),d=Math.max(1,Math.min(pr,Math.max(Ce,l))),m=new Map(o.map(_=>[_.episodeNo,_.summary])),y=We(te)/60,h=Ut(te),b=Math.max(1,Math.min(pr,Math.floor(ui))),w=Math.max(1,Math.min(pr,Math.floor(pi))),g=Math.min(b,w),A=Math.max(b,w),j=(_,C,R)=>R?Hs==="overwrite_all"?!0:Hs==="overwrite_range"?_>=g&&_<=A:!C.trim():!1;Fe(_=>{const C=[];for(let R=0;R<d;R++){const T=_[R],M=m.get(R+1);if(T){const W=String(T.summary||""),q=j(R+1,W,M);C.push(q?{...T,title:String(T.title||"").trim()||`Episode ${R+1}`,summary:M||W,attribution:{userName:Z,withBloomBot:!0},durationMin:typeof T.durationMin=="number"&&T.durationMin>0?T.durationMin:y,sceneCount:typeof T.sceneCount=="number"&&T.sceneCount>0?T.sceneCount:h}:T);continue}C.push({id:Cr(),title:`Episode ${R+1}`,summary:M||"",attribution:{userName:Z,withBloomBot:!!M},durationMin:y,sceneCount:h})}return C}),Nt(sn(d)),Dt(null),kt(_=>({..._,episodeCount:!0}));const B=Hs==="fill_empty"?n("page.storyflow.fillEmpty"):Hs==="overwrite_all"?n("page.storyflow.overwriteAll"):`${n("page.storyflow.overwriteRange")} E${String(g).padStart(2,"0")}-E${String(A).padStart(2,"0")}`;H.success(n("page.storyflow.skeletonAppliedTitle"),n("page.storyflow.skeletonAppliedBody",{rowCount:o.length,strategy:B,targetCount:d}))},[J,Ce,te,Z,Hs,ui,pi,n]),c.useCallback(async()=>{var o,l;if(!(!Xe||!vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,re
779centUserTexts:J.filter(d=>d.role==="user").map(d=>String(d.text||"")),recentAssistantTexts:J.filter(d=>d.role==="assistant").map(d=>String(d.rawAssistantReply||d.text||""))}))&&!Wc.current){if(!Se.storyArcReady){H.warning(n("page.storyflow.compileDescriptiveScriptBlockedTitle"),n("page.storyflow.unifiedShellFilmScriptAfterOutlineHint"));return}if(!Se.worldBibleReady){H.warning(n("page.storyflow.compileDescriptiveScriptBlockedTitle"),n("page.storyflow.unifiedShellFilmScriptAfterWorldHint"));return}Wc.current=!0;try{const d=Math.max(1,Math.round(We(te)/60)),m=((o=P[0])==null?void 0:o.generationUnits)??[],h=Do()&&m.length>0&&m.some(B=>String(B.label||"").trim())?Xo(m.map(B=>({...B,targetMinutes:B.targetMinutes||Math.max(3,Math.min(8,d/m.length))}))):Jk(d);Uc({done:0,total:h.length,label:((l=h[0])==null?void 0:l.label)||""});const b=J.slice(-12).map(B=>`${B.role}: ${String(B.text||"").trim()}`).filter(B=>B.length>6).join(` 780`).slice(-8e3),w=er.map(B=>`${B.label}: ${(pe[B.id]||"").trim()}`).filter(B=>B.length>3).join(` 781`).slice(0,4e3),g=Ye==="zh"?"zh":"en",A=await sv({units:h,facts:{projectTitle:ge,logline:U.logline,synopsis:U.synopsis,worldBibleExcerpt:w,episodeTitle:ge,episodeSummary:U.synopsis,chatExcerpt:b},locale:g,onProgress:B=>Uc(B)}),j=We(te);Fe(B=>{const _=B[0]??{id:Cr(),title:(ge||"").trim()||n("page.storyflow.filmDetailedScriptSection"),summary:String(U.synopsis||U.logline||"").trim(),attribution:{userName:Z,withBloomBot:!0},durationMin:j/60,sceneCount:Ut(j)},C=[...B];return C[0]={..._,generationUnits:A.units,detailedScript:A.mergedScript,detailedScriptBloomDraft:void 0,scriptFormat:"descriptive",durationMin:j/60},C}),Ze.current({silent:!0}),zr({showToastOnError:!1}),A.errors.length?H.warning(n("page.storyflow.compileDescriptiveScriptPartialTitle"),A.errors.slice(0,2).join(" · ")):H.success(n("page.storyflow.compileDescriptiveScriptSuccessTitle"),n("page.storyflow.compileDescriptiveScriptSuccessBody"))}catch(d){H.error(n("page.storyflow.compileDescriptiveScriptFailedTitle"),Bt(d instanceof Error?d.message:String(d)))}finally{Wc.current=!1,Uc(null)}}},[Xe,ke,Ce,te,Se.storyArcReady,te,J,pe,Ye,ge,U.logline,U.synopsis,Z,P,zr,n]);const Li=c.useCallback(async e=>{const o=(e==null?void 0:e.messages)??J,l=o.filter(b=>b.role==="assistant");if(l.length===0){e!=null&&e.silent||H.info(n("page.storyflow.syncBoardFromChatNoMessagesTitle"),n("page.storyflow.syncBoardFromChatNoMessagesBody"));return}const d=o.filter(b=>b.role==="user").map(b=>String(b.text||"")).filter(Boolean);xn(b=>b.filter(w=>Ss(w.name)));for(const b of d)if(vs(b)){Jr(!0),Nt(1),Dt(null),kt(w=>({...w,episodeCount:!0}));break}const m=vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:d,recentAssistantTexts:l.map(b=>String(b.rawAssistantReply||b.text||""))}),y={applyEpisodes:!m&&hS(),manualChatBackfill:!0,fromAssistantDraft:!0,keepLabeledStory:!0,keepCast:!0,keepWorldFromDraft:!0};let h=!1;for(const b of l){const w=String(b.rawAssistantReply||b.text||"").trim();if(w.length<24)continue;const g=ey(w,{proseFallback:!0});g&&tr(g)&&(Tt(g,"all",y),h=!0);const A=zo(w);A&&tr(A)&&(Tt(A,"all",y),h=!0);const j=Ko(w);j.length>0&&(Tt({characters:j},"all",y),h=!0);const{scenes:B,props:_}=Zf(w);(B.length>0||_.length>0)&&(xo(B,_),h=!0)}if(!h){const b=l.map(w=>String(w.rawAssistantReply||w.text||"").trim()).filter(w=>w.length>=24).join(` 782 783`).slice(-12e3);b.length>=24&&(await rl(b,"all",{...y,stateless:!0,userTextForCategory:d[d.length-1]||b.slice(0,400)}),h=!0)}if(!h){e!=null&&e.silent||H.warning(n("page.storyflow.syncBoardFromChatNothingFoundTitle"),n("page.storyflow.syncBoardFromChatNothingFoundBody"));return}if(m&&!Xe){const b=py(o);b.trim()&&Fe(w=>{const g=We(te),A=w[0]??{id:Cr(),title:(ge||"").trim()||n("page.storyflow.filmDetailedScriptSection"),summary:String(U.synopsis||U.logline||"").trim(),attribution:{userName:Z,withBloomBot:!0},durationMin:g/60,sceneCount:Ut(g)},j=[...w];return j[0]={...A,detailedScript:b,detailedScriptBloomDraft:void 0,durationMin:g/60},j})}Ze.current({silent:!0}),zr({showToastOnError:!1}),e!=null&&e.silent||H.success(n("page.storyflow.syncBoardFromChatSuccessTitle"),n("page.storyflow.syncBoardFromChatSuccessBody"))},[J,ke,Ce,te,ge,U.logline,U.synopsis,Z,Tt,xo,rl,zr,n]);c.useEffect(()=>{if(!(Be==="immersive"||Be==="workspace")||!Vs||Re==="episode_unit"||el.current)return;if([...Be==="workspace"?qe:J].reverse().find(m=>m.role==="assistant"&&zu(m.text))){el.current=!0;return}el.current=!0;const d=Be==="workspace"?[n("page.storyflow.foundationReadyReviewTabsChip"),n("page.storyflow.foundationReadyContinueEpisodesChip",{episodesTab:Es})]:void 0;
783Be==="workspace"?$t(m=>[...m,{role:"assistant",text:Gl,optionChips:d}]):ie(m=>[...m,{role:"assistant",text:Gl,optionChips:d}]),requestAnimationFrame(()=>{Ii.current&&(Ii.current.scrollTop=Ii.current.scrollHeight)})},[Be,Vs,Re,J,qe,Es,n]),c.useEffect(()=>{Be==="workspace"&&Re==="foundation"&&Vs&&(tl.current||qe.filter(e=>e.role==="assistant").length!==0&&(tl.current=!0,Li({silent:!0,messages:qe})))},[Be,Re,Vs,qe,Li]);const Rm=c.useMemo(()=>er.map(e=>`${e.label}: ${(pe[e.id]||"").trim()}`).join(` 784`).slice(0,1200),[pe]),Nd=c.useRef(!1);c.useEffect(()=>{if(Be!=="workspace"){Nd.current=!1;return}if(!t||Nd.current)return;const e=Math.max(1,Math.min(10,Math.max(P.length,Ce))),o=Array.from({length:e},(d,m)=>{var y;return{index:m,title:String(((y=P[m])==null?void 0:y.title)||"").trim()||`Episode ${m+1}`}});if(o.length===0)return;Nd.current=!0;const l="Analyzing episode brief...";Fe(d=>{const m=[...d];for(let y=0;y<e;y++){if(!m[y]){m.push({id:Cr(),title:`Episode ${y+1}`,summary:l,attribution:{userName:Z,withBloomBot:!0},durationMin:We(te)/60,sceneCount:Ut(te)});continue}String(m[y].summary||"").trim()||(m[y]={...m[y],summary:l})}return m}),(async()=>{try{H.info(n("page.storyflow.episodesTitle"),n("page.storyflow.episodesAnalyzingBody"));const d=U.logline.trim()||ge.trim()||"Series overview",m=U.synopsis.trim()||dr.trim()||"Generate concise one-line episode briefs based on title order.",y=await vl({logline:d,synopsis:m,worldExcerpt:Rm,episodes:o});Fe(h=>{const b=[...h];for(const w of y)if(w.index>=0&&w.index<b.length){const g=String(b[w.index].summary||"").trim();(!g||g===l)&&(b[w.index]={...b[w.index],summary:w.summary})}return b})}catch(d){Fe(m=>m.map(y=>String(y.summary||"").trim()===l?{...y,summary:"Pending brief. Use Refine to regenerate this episode summary."}:y)),H.warning(n("page.storyflow.episodesTitle"),Bt(d instanceof Error?d.message:String(d)))}})()},[Be,t,P,Ce,U.logline,U.synopsis,ge,Z,te,dr,Rm,n]);const jm=c.useMemo(()=>er.map(e=>`${e.label} 785${(pe[e.id]||"").trim()}`).join(` 786 787`),[pe]);c.useEffect(()=>{Ac(e=>Math.min(e,Math.max(0,P.length)))},[P.length]),c.useEffect(()=>{Ac(0),io("")},[t]);const Ed=c.useCallback(()=>{const e=ds(Le,Oe);return Iy("outline",{seriesTitle:ge,visualStyleLabel:e.label,visualStyleKeywords:e.presetKeywords,logline:U.logline,synopsisExcerpt:U.synopsis,worldExcerpt:"",dramaCategoryId:rt,dramaCustomNote:Yt},{aspectRatio:"16:9"})},[Le,Oe,ge,U.logline,U.synopsis,rt,Yt]),Bn=c.useCallback(async e=>{const o=(e==null?void 0:e.billing)??"auto_free",l=(e==null?void 0:e.force)===!0||o==="user_regen";if(!(!l&&Date.now()<no.current.outline)&&!oo.current.outline&&!(!t||es||!l&&Vt)){oo.current.outline=!0,Ep(!0);try{const d=((e==null?void 0:e.promptOverride)||bn||Ed()).trim();if(!d)throw new Error("Poster prompt is empty");Ba(d);const m=await Py({prompt:d,projectId:t,kind:"outline",aspectRatio:"16:9",billing:o});no.current.outline=0,typeof window<"u"&&ts.current.outline!=null&&(window.clearTimeout(ts.current.outline),ts.current.outline=null),vp(m),hi((ge||"").trim()||null)}catch(d){const m=Bt(d instanceof Error?d.message:String(d));/failed to lock credits|busy|try again in a moment/i.test(m)?(no.current.outline=Date.now()+3e5,Ma("outline",305e3)):H.warning(n("page.storyflow.posterTitle"),m)}finally{oo.current.outline=!1,Ep(!1)}}},[t,es,Vt,bn,Ed,Ma,n]),Am=c.useCallback(async e=>{const o=(e==null?void 0:e.force)===!0;if(!(!o&&Date.now()<no.current.world)&&!oo.current.world&&!(!t||wn||!o&&Zr)){oo.current.world=!0,Tp(!0);try{const l=ds(Le,Oe),d=Iy("world",{seriesTitle:ge,visualStyleLabel:l.label,visualStyleKeywords:l.presetKeywords,logline:U.logline,synopsisExcerpt:U.synopsis,worldExcerpt:jm,dramaCategoryId:rt,dramaCustomNote:Yt}),m=await Py({prompt:d,projectId:t,kind:"world"});no.current.world=0,typeof window<"u"&&ts.current.world!=null&&(window.clearTimeout(ts.current.world),ts.current.world=null),Np(m)}catch(l){const d=Bt(l instanceof Error?l.message:String(l));/failed to lock credits|busy|try again in a moment/i.test(d)?(no.current.world=Date.now()+3e5,Ma("world",305e3)):H.warning(n("page.storyflow.posterTitle"),d)}finally{oo.current.world=!1,Tp(!1)}}},[t,wn,Zr,Le,Oe,ge,U.logline,U.synopsis,jm,rt,Yt,Ma,n]);c.useEffect(()=>{},[Be,t,bi,Vt,Zr,es,wn,Rp,Bn,Am]),c.useEffect(()=>{},[t,bi,Be,Se.storyArcReady,Se.worldBibleReady,Se.titleReady,Vt,Zr,es,wn,Rp,Bn,Am]),c.useEffect(()=>{Be!=="workspace"&&Be!=="immersive"||!t||bi||!(Se.storyArcReady&&Se.titleReady)||!Vt&&!es&&Bn({billing:"auto_free"})},[t,bi,Be,Se.storyArcReady,Se.titleReady,Vt,es,Bn]);const Td="/cloud.png",ls=c.useCallback((e,o,l)=>{if(e==="CHARACTERS"){const y=uw(l,o,st,we),h=st[y];
787return(h==null?void 0:h.designUrl)||(h==null?void 0:h.conceptUrl)||"/cloud.png"}const d=Ve(e,o,l),m=st[d];return(m==null?void 0:m.designUrl)||(m==null?void 0:m.conceptUrl)||"/cloud.png"},[Ve,st,we]),kx=c.useMemo(()=>{const e={};for(const o of Xt){const l=ls("SCENES",void 0,o);l&&l!=="/cloud.png"&&/^https?:\/\//i.test(l)&&(e[o]=l)}return e},[Xt,ls]),vx=c.useMemo(()=>{const e={};for(const o of Et){const l=ls("CHARACTERS",o.id,o.name);if(l&&l!=="/cloud.png"&&/^https?:\/\//i.test(l)){e[o.name]=l;const d=Mt(o.name);d&&(e[d]=l)}}return e},[Et,ls]);s.Fragment,yr?(n("page.storyflow.seriesVisualStyle"),n("page.storyflow.changeAction")):(n("page.storyflow.seriesVisualStyle"),n("page.storyflow.hideAction"),n("page.storyflow.styleStripHint"),Uy.map(e=>s.jsxs("button",{type:"button",onMouseEnter:o=>wd(o.currentTarget,e),onMouseLeave:Io,onClick:()=>_n(e.id),className:`w-12 shrink-0 flex flex-col rounded-md overflow-hidden border-2 transition-all ${Le===e.id?"border-primary ring-1 ring-primary/40":"border-white/10 hover:border-white/30"} disabled:opacity-40 disabled:pointer-events-none`,title:us(e.id,z),children:[e.preview?s.jsx(cn,{src:e.preview,alt:"",className:"aspect-video w-full min-h-[28px] max-h-[32px]"}):s.jsx("div",{className:"flex aspect-video w-full min-h-[28px] max-h-[32px] items-center justify-center bg-black/50",children:s.jsx("span",{className:"text-white/40 text-[8px]",children:"â"})}),s.jsx("span",{className:"px-0.5 py-0.5 bg-black/70 text-white text-[7px] truncate text-center leading-tight",children:us(e.id,z)})]},e.id)),n("page.storyflow.styleCustomUploadRefTitle"),sr?(s.Fragment,cn,n(Oe?"page.storyflow.styleTapToLock":"page.storyflow.ellipsis")):(s.Fragment,n("page.storyflow.styleCustomLabel")),Le==="Custom (Upload Ref)"&&Oe&&n("page.storyflow.styleKeywordsEditablePlaceholder")),n("page.storyflow.seriesVisualStyle"),n("page.storyflow.styleLockedPrefix"),n("page.storyflow.styleStripHint"),Uy.map(e=>s.jsxs("button",{type:"button",onMouseEnter:o=>wd(o.currentTarget,e),onMouseLeave:Io,onClick:()=>_n(e.id),className:`w-[76px] shrink-0 flex flex-col rounded-lg overflow-hidden border-2 transition-all ${Le===e.id?"border-primary ring-1 ring-primary/40":"border-white/10 hover:border-white/30"} disabled:opacity-40 disabled:pointer-events-none`,title:us(e.id,z),children:[e.preview?s.jsx(cn,{src:e.preview,alt:"",className:"aspect-video w-full min-h-[42px]"}):s.jsx("div",{className:"flex aspect-video w-full min-h-[42px] items-center justify-center bg-black/50",children:s.jsx("span",{className:"text-white/40 text-[8px]",children:"â"})}),s.jsx("span",{className:"truncate bg-black/70 px-0.5 py-1 text-center text-xs leading-tight text-white",children:us(e.id,z)})]},e.id)),n("page.storyflow.styleCustomUploadRefTitle"),sr?(s.Fragment,cn,Oe&&n("page.storyflow.styleTapToLock")):(s.Fragment,n("page.storyflow.styleCustomLabel")),Le==="Custom (Upload Ref)"&&Oe&&n("page.storyflow.styleKeywordsEditablePlaceholder");const Cx=s.jsxs("div",{className:"mb-2 flex w-full min-w-0 items-center justify-between gap-2 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px]",children:[s.jsxs("span",{className:"min-w-0 truncate text-zinc-400",children:[s.jsx("span",{className:"text-zinc-500",children:n("page.bloomBotCard.styleLabelPrefix")})," ",s.jsx("span",{className:"text-zinc-200",children:yr?Mi:z==="zh"?"æªéæ©ï¼é确认ï¼":"Not selected (confirm required)"}),yr?s.jsx("span",{className:"text-zinc-500",children:n("page.bloomBotCard.styleLockedSuffix")}):null]}),s.jsx("button",{type:"button","data-testid":"storyflow-select-style-chip",onClick:()=>{Er(!1),Tr(!0)},className:"shrink-0 font-medium text-primary hover:text-primary/90",children:yr?n("page.storyflow.styleChangeInChat"):z==="zh"?xw:bw})]}),Nx=s.jsxs(s.Fragment,{children:[si?s.jsx("div",{className:"fixed inset-0 z-[10050] flex items-end justify-center bg-black/70 p-3 sm:items-center sm:p-4",role:"presentation","data-testid":"storyflow-style-picker-modal",onClick:()=>Tr(!1),children:s.jsxs("div",{className:"flex max-h-[min(88vh,720px)] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-white/15 bg-zinc-900 shadow-2xl",role:"dialog","aria-modal":"true","aria-labelledby":"storyflow-style-picker-title",onClick:e=>e.stopPropagation(),children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-white/10 px-4 py-3",children:[s.jsx("h2",{id:"storyflow-style-picker-title",className:"text-sm font-semibold text-white",children:n("page.storyflow.styleSuggestionsTitle")}),s.jsx("button",{type:"button",onClick:()=>Tr(!1),className:"rounded-lg border border-white/15 px-2.5 py-1 text-[11px] text-zinc-300 hover:bg-white/10",children:z==="zh"?"å
³é":"Close"})]}),s.jsx("p",{className:"shrink-0 px-4 pt-2 text-[11px] leading-snug text-zinc-500",children:n("page.storyflow.styleStr
787ipHint")}),s.jsx("input",{ref:K,type:"file",accept:"image/*",className:"hidden sr-only","aria-hidden":!0,tabIndex:-1,onChange:kd}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-3 custom-scrollbar",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[Qx().map(e=>{const o=Le===e.id;return s.jsxs("button",{type:"button",onMouseEnter:l=>wd(l.currentTarget,e),onMouseLeave:Io,onClick:()=>hr({kind:"preset",style:e}),className:`relative w-[76px] shrink-0 flex flex-col overflow-hidden rounded-lg border-2 transition-all ${o?"border-primary ring-1 ring-primary/40":"border-white/10 hover:border-white/30"}`,title:us(e.id,z),children:[o?s.jsx("span",{className:"absolute right-1 top-1 z-[1] flex h-4 w-4 items-center justify-center rounded-full bg-primary text-black",children:s.jsx("span",{className:"material-symbols-outlined text-[12px] leading-none",children:"check"})}):null,e.preview?s.jsx(cn,{src:e.preview,alt:"",className:"aspect-video w-full min-h-[42px]"}):s.jsx("div",{className:"flex aspect-video w-full min-h-[42px] items-center justify-center bg-black/50",children:s.jsx("span",{className:"text-white/40 text-[8px]",children:"â"})}),s.jsx("span",{className:"truncate bg-black/70 px-0.5 py-1 text-center text-[10px] leading-tight text-white",children:us(e.id,z)})]},e.id)}),s.jsx("button",{type:"button",onMouseEnter:e=>{sr&&Sd(e.currentTarget)},onMouseLeave:Io,onClick:()=>{var e;Ns||(sr&&Oe.trim()?hr({kind:"custom"}):(e=K.current)==null||e.click())},className:`relative w-[76px] shrink-0 flex flex-col overflow-hidden rounded-lg border-2 border-dashed transition-all ${Le==="Custom (Upload Ref)"?"border-primary":"border-white/20 hover:border-white/40"}`,title:n("page.storyflow.styleCustomUploadRefTitle"),children:sr?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative w-full",children:[s.jsx(cn,{src:sr,alt:"",className:"aspect-video w-full min-h-[42px]"}),Ns?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60",children:s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm text-primary",children:"sync"})}):null]}),s.jsx("span",{className:"truncate bg-black/70 px-0.5 py-1 text-center text-[10px] text-primary",children:Oe?n("page.storyflow.styleTapToLock"):"â¦"})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex aspect-video min-h-[42px] w-full items-center justify-center bg-black/30",children:s.jsx("span",{className:"material-symbols-outlined text-lg text-white/50",children:"add_photo_alternate"})}),s.jsx("span",{className:"truncate bg-black/70 px-0.5 py-1 text-center text-[10px] text-white",children:n("page.storyflow.styleCustomLabel")})]})})]}),Le==="Custom (Upload Ref)"&&Oe?s.jsx("textarea",{value:Oe,onChange:e=>Or(e.target.value.slice(0,200)),placeholder:n("page.storyflow.styleKeywordsEditablePlaceholder"),maxLength:200,rows:2,className:"mt-3 w-full resize-none rounded border border-white/10 bg-black/50 px-2 py-1.5 text-xs text-white/90 placeholder:text-slate-600 focus:border-primary/50 focus:outline-none"}):null]})]})}):null,St?s.jsx("div",{className:"fixed inset-0 z-[10060] flex items-center justify-center bg-black/70 p-4",role:"presentation",onClick:()=>hr(null),children:s.jsxs("div",{className:"w-full max-w-md rounded-xl border border-white/15 bg-zinc-900 p-4 shadow-2xl",role:"dialog","aria-modal":"true","aria-labelledby":"storyflow-style-confirm-title",onClick:e=>e.stopPropagation(),children:[(()=>{const e=St.kind==="preset"?us(St.style.id,z):z==="zh"?"èªå®ä¹åèå¾":"Custom reference";return s.jsxs(s.Fragment,{children:[s.jsx("h2",{id:"storyflow-style-confirm-title",className:"text-sm font-semibold text-white",children:z==="zh"?"使ç¨è¿ä¸ªè§è§é£æ ¼åï¼":"Use this visual style?"}),s.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:z==="zh"?`æ¬ç³»ååéä¸èµäº§è®¾è®¡å°ä½¿ç¨ã${e}ãã`:`Series episode art and asset design will use ${e}.`})]})})(),s.jsx("div",{className:"mt-3 flex max-h-[min(52vh,420px)] min-h-[120px] justify-center overflow-hidden rounded-lg bg-black/40 p-2",children:St.kind==="preset"&&St.style.preview?s.jsx("img",{src:St.style.preview,alt:"",className:"max-h-[min(48vh,380px)] w-full object-contain"}):St.kind==="custom"&&sr?s.jsx("img",{src:sr,alt:"",className:"max-h-[min(48vh,380px)] w-full object-contain"}):s.jsx("span",{className:"self-center text-xs text-zinc-500",children:z==="zh"?"æ é¢è§å¾":"No preview image"})}),s.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",className:"rounded-lg border border-white/15 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-white/10",onClick:()=>hr(null),children:z==="zh"?"åæ¶":"Cancel"}),s.jsx("button",{type:"button",className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-semibold text-black hover:brightness-110",onClick:wx,children:z==="zh"?"确认":"Confirm"})]})]})}):null]}),Rd=c.useMemo(()=>{const e=vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,re
787centUserTexts:J.filter(l=>l.role==="user").map(l=>String(l.text||"")).filter(Boolean),recentAssistantTexts:J.filter(l=>l.role==="assistant").map(l=>String(l.rawAssistantReply||l.text||"")).filter(Boolean)}),o=s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"sr-only",htmlFor:"cb-episode-duration-minutes",children:n(e?"page.storyflow.filmRuntimeMinutesInputLabel":"page.storyflow.episodeDurationMinutesInputLabel")}),s.jsxs("div",{className:"ml-0.5 inline-flex h-8 items-center gap-1 align-middle",children:[s.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide text-slate-500","aria-hidden":!0,children:n(e?"page.storyflow.durationShortFilm":"page.storyflow.durationShortSeries")}),s.jsx("input",{id:"cb-episode-duration-minutes",type:"text",inputMode:"numeric",autoComplete:"off",readOnly:!e,title:e?n("page.storyflow.filmRuntimeMinutesRangeHint",{min:hf,max:yf}):n("page.storyflow.seriesEpisodeDurationFixedHint",{minutes:ln}),"aria-label":n(e?"page.storyflow.filmRuntimeMinutesInputLabel":"page.storyflow.episodeDurationMinutesInputLabel"),value:e?yc??String(Al(te,!0)):String(ln),onFocus:Rc,onChange:l=>Tc(l.target.value),onBlur:Ec,onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),l.target.blur())},className:`min-w-[2.5rem] rounded-md border border-white/10 bg-black/40 px-1.5 py-0.5 text-center text-[11px] font-bold text-primary focus:border-primary/40 focus:outline-none ${e?"w-12":"w-10 cursor-default opacity-90"}`}),s.jsx("span",{className:"shrink-0 text-[9px] font-semibold uppercase tracking-wide text-slate-500",children:n("page.storyflow.durationMinutesUnit")})]})]});return e?s.jsx("div",{className:"flex max-w-full flex-wrap items-center gap-x-2 gap-y-1.5",title:n("page.storyflow.headerFilmRuntimeTitle"),"data-testid":"storyflow-header-film-runtime",children:o}):s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:"cb-episode-duration-ticks",children:[30,60,90,120,150,180,210,240,270,300].map(l=>s.jsx("option",{value:l},l))}),s.jsxs("div",{className:"flex max-w-full flex-wrap items-center gap-x-2 gap-y-1.5",title:n("page.storyflow.headerUnifiedEpisodesDurationTitle"),children:[s.jsx("label",{className:"sr-only",htmlFor:"cb-planned-eps",children:n("page.storyflow.plannedEpisodesLabel")}),s.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide text-slate-500","aria-hidden":!0,children:n("page.storyflow.episodesShort")}),s.jsxs("div",{className:"inline-flex h-7 items-stretch overflow-hidden rounded-md border border-white/10 bg-black/40",role:"group","aria-label":n("page.storyflow.plannedEpisodeCountAria"),children:[s.jsx("button",{type:"button",disabled:Ce<=dn,onClick:()=>{Dt(null),Nt(l=>Math.max(dn,l-1)),kt(l=>({...l,episodeCount:!0}))},className:"min-w-7 px-1.5 text-sm font-bold leading-none text-slate-400 transition-colors hover:bg-white/10 hover:text-white disabled:pointer-events-none disabled:opacity-35","aria-label":n("page.storyflow.decreasePlannedEpisodesAria"),children:"â"}),s.jsx("input",{id:"cb-planned-eps",type:"text",inputMode:"numeric",autoComplete:"off","aria-valuemin":dn,"aria-valuemax":pr,value:fc??String(Ce),onFocus:Nc,onChange:l=>Cc(l.target.value),onBlur:vc,onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),l.target.blur())},className:"w-9 min-w-[2.25rem] border-x border-white/10 bg-transparent py-0 text-center text-[11px] font-bold text-primary focus:border-primary/40 focus:outline-none"}),s.jsx("button",{type:"button",disabled:Ce>=pr,onClick:()=>{Dt(null),Nt(l=>Math.min(pr,l+1)),kt(l=>({...l,episodeCount:!0}))},className:"min-w-7 px-1.5 text-sm font-bold leading-none text-slate-400 transition-colors hover:bg-white/10 hover:text-white disabled:pointer-events-none disabled:opacity-35","aria-label":n("page.storyflow.increasePlannedEpisodesAria"),children:"+"})]}),o]})]})},[ee,Ce,fc,te,yc,ke,J,Nc,Cc,vc,Rc,Tc,Ec,n]);c.useLayoutEffect(()=>{if(v){v(null);return}},[t,v,Rd]);const Im=Se.storyArcReady?Se.worldBibleReady?Se.titleReady?Se.charactersReady?Se.episodePlanReady?Se.dramaReady?Se.styleLocked?null:"style":"category":"episodes":"characters":"title":"world_bible":"story_outline",Pm=qr({uiPhase:Be}),Ex=Be==="immersive"&&Pg&&!Se.allFoundationReady&&Im!=null&&!Pm,Tx={story_outline:1,world_bible:2,title:3,characters:4,episodes:5,category:6,style:7},_m=e=>Ex&&Im===e,Po=e=>`relative rounded-lg border bg-black/20 p-2.5 ${_m(e)?"border-primary shadow-[0_0_0_1px_rgba(163,230,53,0.45),0_0_20px_rgba(163,230,53,0.16)]":"border-white/10"}`,As=e=>ti.has(e)?" ring-2 ring-primary/70 motion-safe:transition-shadow motion-safe:duration-200":"",_o=e=>_m(e)?s.jsxs("div",{className:"pointer-events-none absolute -left-2 -top-2 z-10",children:[s.jsx("span",{className:"absolute inline-flex h-6 w-6 motion-safe:animate-ping rounded-full bg-primary/35"}),s.jsx("span",{className:"relative inline-flex h-6 w-6 items-center justify-center rounded-full border border-primary bg-black text-[11px] font-bold text-primary",children:Tx[e]})]}):null;`${Po("title")}${As("title")}`,_o("title"),n("page.storyflow.titleSection"),n("page.storyflow.titlePlaceholder"),n("page.storyflow.seriesTitleAria"),`${Po("characters")}${As("characters")}`,_o("characters"),n("page.storyflow.charactersSection"),Math.max(0,we.length),we.length>0?(s.Fragment,we.slice(0,4).map(e=>s.jsx("span",{className:"rounded-md border border-white/10 bg-black/25 px-1.5 py-0.5 text-xs text-slate-300",title:e.name,children:e.name},e.id)),we.length>4&&we.length-4):(n("page.storyflow.noCharactersYet"),n("page.storyflow.addCharacterButton")),n("page.storyflow.draftButton"),`${Po("episodes")}${As("episodes")}`,_o("episodes"),n("page.storyflow.episodePlanSection"),n("page.storyflow.plannedEpisodeCountAria"),fc??String(Ce),n("page.storyflow.episodesShort"),n(ke?"page.storyflow.durationShortFilm":"page.storyflow.durationShortSeries"),ke?n("page.storyflow.filmRuntimeMinutesRangeHint",{min:hf,max:yf}):n("page.storyflow.seriesEpisodeDurationFixedHint",{minutes:ln}),n(ke?"page.storyflow.filmRuntimeMinutesInputLabel":"page.storyflow.episodeDurationMinutesInputLabel"),ke?yc??String(Al(te,!0)):String(ln),n("page.storyflow.durationMinutesUnit"),`${Po("story_outline")}${As("logline")}${As("synopsis")}`,_o("story_outline"),n("page.storyflow.loglineSynopsisSection"),U.logline,n("page.storyflow.loglinePlaceholder"),`${As("logline")}`,U.synopsis,n("page.storyflow.shortSynopsisPlaceholder"),`${As("synopsis")}`,`${Po("world_bible")}`,["geography","timeline","rules","culture","coreConflict"].some(e=>ti.has(e)),_o("world_bible"),n("page.storyflow.worldBibleSection"),er.map(e=>s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"mb-0.5 text-xs font-semibold uppercase tracking-wide text-neutral-500",children:Pe(e.id)}),s.jsx("textarea",{value:pe[e.id],"data-storyflow-board-field":e.id,onChange:o=>{nr(e.id),Us(l=>({...l,[e.id]:o.target.value}))},placeholder:xe(e.id),rows:1,className:`w-full resize-none rounded-md border border-white/10 bg-black/30 px-2 py-1.5 text-xs text-slate-200 placeholder:text-slate-500${As(e.id)}`})]},e.id)),`${Po("category")}${As("dramaCategory")}`,_o("category"),n("page.storyflow.categorySection"),oa.map(e=>s.jsx("button",{type:"button",onClick:()=>{nr("dramaCategory"),di(e.id),e.id!=="custom"&&to("")},className:`rounded-md border px-2 py-0.5 text-xs font-semibold transition-colors ${rt===e.id?"border-primary bg-primary/15 text-primary":"border-white/10 text-slate-300 hover:border-primary/35 hover:bg-white/5 hover:text-white"} disabled:opacity-40`,children:Yd(e.id,z)},e.id)),rt==="custom"&&n("page.storyflow.customCategoryNotePlaceholder"),Se.storyArcReady,n("page.storyflow.progressStoryOutline"),Se.worldBibleReady,n("page.storyflow.progressWorldBible"),Se.episodePlanReady,n("page.storyflow.progressEpisodes"),Se.charactersReady,n("page.storyflow.progressCharacters");const Bo=c.useMemo(()=>ft?Lr.find(e=>e.id===ft):void 0,[Lr,ft]),ml=ft!=null,Oi=c.useMemo(()=>Bo?Bo.messages.map(e=>({role:e.role,text:e.text,rawAssistantReply:e.rawAssistantReply,optionChips:e.optionChips}
787)):J,[J,Bo]),Bm=Ye==="zh"?"zh":"en",Mm=(()=>{var o;const e=[...Oi].reverse().find(l=>{var d;return l.role==="assistant"&&((d=l.optionChips)==null?void 0:d.length)});return(o=e==null?void 0:e.optionChips)!=null&&o.length?e.optionChips:null})(),Rx=(()=>{var e;for(let o=Oi.length-1;o>=0;o-=1){const l=Oi[o];if(l.role==="assistant"&&((e=l.optionChips)!=null&&e.length))return o}return-1})();c.useMemo(()=>P.reduce((e,o)=>String(Rt(o)||"").trim().length>=120?e+1:e,0),[P]),c.useMemo(()=>P.length===0?-1:Kt>=0&&Kt<P.length?Kt:0,[P.length,Kt]),Mm&&(()=>{const{variant:e,items:o}=lS(Mm);return o.map((l,d)=>e==="numbered"?s.jsx("button",{type:"button",disabled:ee,title:l.title||l.sendText,onClick:()=>void ld(l.sendText),className:"size-9 shrink-0 rounded-lg border border-white/15 bg-white/[0.06] hover:bg-primary/20 hover:border-primary/40 text-xs font-bold text-slate-100 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-40 disabled:pointer-events-none",children:l.label},d):s.jsx("button",{type:"button",disabled:ee,title:l.title,onClick:()=>void ld(l.sendText),className:"px-3 py-1.5 rounded-full text-[10px] font-semibold bg-white/10 hover:bg-primary/25 text-zinc-200 hover:text-white border border-white/10 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-40 disabled:pointer-events-none max-w-[min(100%,280px)] text-left truncate",children:l.label},d))})();const Lm=s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden","data-tour":"gl-bloombot",children:s.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden flex-col gap-0 px-2 pb-0",children:[s.jsxs("div",{className:"flex min-w-0 flex-col overflow-hidden rounded-xl border border-white/10 bg-surface-dark min-h-0 flex-1",children:[s.jsxs("div",{className:"relative flex shrink-0 flex-wrap items-center gap-3 border-b border-white/10 bg-dark-900/90 px-4 py-3",children:[s.jsx(of,{className:"h-9 w-9 shrink-0 rounded-full border border-white/20 bg-black/25 p-[2px]"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"truncate font-display text-sm font-bold tracking-tight text-slate-100",children:n("page.storyflow.scriptDeskTitle")}),Be==="workspace"&&wp?s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-primary","data-testid":"storyflow-bloombot-mode-label",children:wp}):null,null]}),null,s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{type:"button",onClick:pm,className:"text-[11px] font-bold uppercase tracking-wide text-primary hover:text-primary/90 hover:underline transition-colors","aria-label":n("page.storyflow.newChatAria"),children:n("page.storyflow.newChatButton")}),s.jsx("div",{ref:It,className:"relative shrink-0",children:s.jsx("button",{type:"button",onClick:()=>Ft(e=>!e),className:`rounded-lg p-2 transition-colors ${dt?"bg-primary/20 text-primary":"text-zinc-400 hover:bg-white/10 hover:text-white"}`,title:n("page.storyflow.chatHistoryButton"),"aria-label":n("page.storyflow.chatHistoryAria"),"aria-expanded":dt,children:s.jsx(Go,{name:"history",size:"inline",className:"!text-lg"})})})]}),dt?s.jsxs("div",{ref:ua,className:"absolute left-0 right-0 top-full z-20 max-h-52 overflow-y-auto border-b border-white/10 bg-zinc-900/98 shadow-xl backdrop-blur-md",children:[s.jsxs("button",{type:"button",className:"w-full border-b border-white/5 px-3 py-2.5 text-left transition-colors hover:bg-white/5",onClick:()=>{fr(null),Ft(!1)},children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-wide text-primary",children:n("page.storyflow.chatHistoryCurrent")}),s.jsx("div",{className:"mt-0.5 truncate text-xs text-zinc-200",children:Ph(J)}),s.jsx("div",{className:"mt-0.5 text-[9px] text-zinc-500",children:n("page.storyflow.chatHistoryInProgress")})]}),Lr.map(e=>s.jsxs("button",{type:"button",className:"w-full border-b border-white/5 px-3 py-2.5 text-left transition-colors hover:bg-white/5",onClick:()=>{fr(e.id),Ft(!1)},children:[s.jsx("div",{className:"text-[10px] text-zinc-500",children:dy(e.savedAt,Bm)}),s.jsx("div",{className:"mt-0.5 truncate text-xs text-zinc-200",children:e.summary})]},e.id)),Lr.length===0?s.jsx("p",{className:"border-t border-white/5 px-3 py-2.5 text-[10px] text-zinc-500",children:n("page.storyflow.chatHistoryEmpty")}):null]}):null]}),ml&&Bo?s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-white/10 bg-zinc-900/80 px-3 py-2",children:[s.jsx("button",{type:"button",onClick:()=>fr(null),className:"shrink-0 text-xs font-bold text-primary hover:underline",children:n("page.storyflow.chatHistoryBack")}),s.jsxs("span",{className:"truncate text-[10px] text-zinc-500",children:[dy(Bo.savedAt,Bm)," ·"," ",Bo.summary]})]}):null,null,s.jsxs("div",{ref:Ii,className:"min-h-0 flex-1 overflow-y-auto custom-scrollbar space-y-3 px-4 py-3 md:px-4",children:[Oi.length===0?s.jsx("div",{className:"rounded-xl border border-white/10 bg-black/25 p-4 text-sm leading-relaxed text-neutral-300",children:Pm?n("page.storyflow.welcomeCardBodyTalk"):ig}):null,Oi.map((e,o)=>{var y,h;const l=Ay(e.text,Ye,{unifiedShell:Be==="workspace"}
787),d=e.role==="assistant"?Xd(l,Ye):l,m=e.role==="assistant"&&((y=e.rawAssistantReply)==null?void 0:y.trim())||d;return s.jsx(c.Fragment,{children:s.jsxs("div",{className:`flex shrink-0 flex-col gap-1.5 ${e.role==="user"?"items-end":"items-start"}`,children:[s.jsxs("div",{className:`relative max-w-[90%] rounded-xl px-3 py-2.5 ${e.role==="user"?"rounded-tr-sm border border-primary/30 bg-primary/20":"rounded-tl-sm border border-white/10 bg-black/35"} ${e.text.trim()?"pr-8":""}`,children:[d.trim()?rm(e.text,e.role,`select-text whitespace-pre-wrap break-words text-sm leading-relaxed ${e.role==="user"?"text-slate-100":"font-medium text-slate-300"}`):null,m.trim()?s.jsx("button",{type:"button",onClick:async b=>{b.stopPropagation();const w=`${e.role}-${o}`;try{await navigator.clipboard.writeText(m),ei(w),Cs.current!=null&&window.clearTimeout(Cs.current),Cs.current=window.setTimeout(()=>{ei(g=>g===w?null:g)},1600),H.success(n("page.storyflow.copiedTitle"),n("page.storyflow.contentCopiedToClipboardBody"))}catch{H.warning(n("page.storyflow.copyFailedTitle"),n("page.storyflow.copyToClipboardFailedBody"))}},className:`absolute right-1.5 top-1.5 z-10 rounded p-1 opacity-70 transition-opacity hover:bg-white/10 hover:opacity-100 ${e.role==="user"?"text-slate-100":"text-slate-300"}`,title:Zo===`${e.role}-${o}`?z==="zh"?"å·²å¤å¶":"Copied":n("page.storyflow.copyAction"),"aria-label":Zo===`${e.role}-${o}`?z==="zh"?"å·²å¤å¶":"Copied":n("page.storyflow.copyAction"),children:Zo===`${e.role}-${o}`?s.jsx("svg",{className:"h-3.5 w-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24","aria-hidden":!0,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):s.jsx("svg",{className:"h-3.5 w-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24","aria-hidden":!0,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}):null]}),e.role==="assistant"&&((h=e.optionChips)!=null&&h.length)?s.jsx("div",{className:"flex max-w-[95%] flex-wrap gap-1.5 pl-0.5",children:e.optionChips.map((b,w)=>{const g=ad(b)!=null,A=!ee&&!ml&&(o===Rx||g);return s.jsx("button",{type:"button",disabled:!A,"aria-disabled":!A,onClick:()=>{A&&ld(b)},className:`max-w-full rounded-full border px-3 py-1.5 text-left text-xs font-semibold transition-colors ${A?"cursor-pointer border-white/10 bg-white/10 text-zinc-200 hover:border-primary/40 hover:bg-primary/25 hover:text-white":"pointer-events-none cursor-default border-white/5 bg-white/[0.04] text-zinc-500 opacity-50"}`,children:b},`${o}-${w}`)})}):null]})},o)}),ee&&!ml?s.jsx("div",{className:"flex shrink-0 justify-start","aria-busy":"true","aria-live":"polite",children:s.jsx("div",{className:"max-w-[90%] rounded-xl rounded-tl-sm border border-primary/25 bg-black/35 px-3 py-2.5 shadow-[0_0_16px_rgba(163,230,53,0.12)]",children:Vn.trim()?s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"material-symbols-outlined mt-0.5 shrink-0 animate-spin text-lg leading-none text-primary","aria-hidden":!0,children:"progress_activity"}),s.jsxs("p",{className:"min-w-0 whitespace-pre-wrap break-words text-sm leading-relaxed font-medium text-slate-300",children:[Vn,s.jsx("span",{className:"ml-0.5 inline-block h-4 w-[1px] translate-y-[2px] animate-pulse bg-primary/80 align-bottom"})]})]}):s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"material-symbols-outlined shrink-0 animate-spin text-lg leading-none text-primary","aria-hidden":!0,children:"progress_activity"}),s.jsx("span",{className:"text-sm font-semibold leading-none tracking-tight text-slate-200",children:n("page.storyflow.statusThinking")})]})})}):null]}),s.jsx("div",{className:"shrink-0 border-t border-white/10 bg-black/35 p-3",children:ml?s.jsx("p",{className:"px-1 text-center text-xs text-zinc-500",children:n("page.storyflow.chatHistoryViewingLabel")}):s.jsxs("div",{className:"w-full px-0",children:[Cx,s.jsx("div",{className:"overflow-hidden rounded-xl border border-white/10 bg-zinc-950/70 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]",children:s.jsxs("div",{className:"relative w-full",children:[s.jsx("textarea",{value:So,onChange:e=>Ag(e.target.value),onKeyDown:Fg,placeholder:og,rows:4,disabled:ee,className:"box-border min-h-[4.75rem] w-full cursor-text resize-none overflow-y-auto border-0 bg-transparent px-3 pb-11 pl-12 pt-2.5 text-sm leading-snug text-white placeholder-zinc-500 focus:outline-none disabled:opacity-70 select-text","aria-label":n("page.storyflow.bloomBotMessageAria")}),s.jsx("div",{className:"absolute bottom-3 left-3 z-[1] flex h-7 items-center",children:s.jsxs("div",{className:"relative shrink-0",children:[s.jsx("button",{ref:Jp,type:"button",onClick:()=>Yc(e=>!e),disabled:ee,className:"flex size-7 shrink-0 items-center justify-center rounded-lg border border-primary/50 bg-primary/15 text-primary transition-all duration-150 hover:border-primary/70 hover:bg-primary/25 hover:text-primary disabled:opacity-50",title:n("page.bloomBotCard.attachTitle"),"aria-label":n("page.bloomBotCard.attachAria"),"aria-expanded":Xp,children:s.jsx(Go,{name:"add",size:"inline",className:"!text-base leading-none"})}),s.jsx(ww,{open:Xp,anchorRef:Jp,onClose:()=>Yc(!1),onPick:Ig,labels:{image:n("page.bloomBotCard.attachmentTypeImage"),video:n("page.bloomBotCard.attachmentTypeVideo"),script:n("page.bloomBotCard.attachmentTypeScript")}})]})}),s.jsxs("div",{className:"absolute bottom-3 right-3 flex max-w-[calc(100%-1.5rem)] flex-col items-end gap-1",children:[s.jsxs("div",{className:"flex h-7 shrink-0 items-center gap-1",children:[Jc?s.jsx("button",{type:"button",onClick:jg,disabled:ee,className:`flex size-7 shrink-0 items-center justify-center rounded-lg border transition-all duration-150 disabled:opacity-50 ${En?"border-primary/70 bg-primary/20 text-primary":"border-white/20 bg-black/40 text-zinc-400 hover:bg-white/10 hover:text-white"}`,title:n(En?"page.bloomBotCard.speechStopTitle":"page.bloomBotCard.speechStartTitle"),"aria-label":n(En?"page.bloomBotCard.speechStopAria":"page.bloomBotCard.speechStartAria"),children:s.jsx(Go,{name:En?"mic_off":"mic",size:"inline",className:"!text-base leading-none"})}
787):null,s.jsxs("button",{type:"button",onClick:cd,disabled:ee||!So.trim(),className:"bw-bloombot-send-fold-btn h-7 min-w-[132px] shrink-0 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:pointer-events-none disabled:opacity-40",title:n("page.bloomBotCard.sendWithTokens",{tokens:Xc}),"aria-label":n("page.storyflow.sendMessageWithTokensAria",{tokens:Xc}),children:[ee?null:s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bw-bloombot-send-fold-btn__fold","aria-hidden":!0}),s.jsx("span",{className:"bw-bloombot-send-fold-btn__points","aria-hidden":!0,children:Array.from({length:10},(e,o)=>s.jsx("span",{className:"bw-bloombot-send-fold-btn__point"},o))})]}),s.jsx("span",{className:"bw-bloombot-send-fold-btn__inner",children:ee?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"size-3.5 shrink-0 animate-spin rounded-full border-2 border-zinc-500/35 border-t-zinc-200","aria-hidden":!0}),s.jsx("span",{className:"min-w-0 shrink truncate",children:n("page.storyflow.statusThinking")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bw-bloombot-send-fold-btn__icon inline-flex shrink-0 items-center justify-center","aria-hidden":!0,children:s.jsx(Go,{name:"send",size:"dense",className:"!text-[14px] leading-none text-current",style:{fontVariationSettings:"'FILL' 1, 'wght' 600"}})}),s.jsx("span",{className:"min-w-0 shrink truncate",children:n("page.bloomBotCard.sendWithTokens",{tokens:Xc})})]})})]})]}),Jc&&En?s.jsx("p",{className:"max-w-full text-right text-[10px] text-primary/90",children:`${n("page.bloomBotCard.speechListeningPrefix")}${Rg||n("page.bloomBotCard.speechSpeakNow")}`}):null,Jc&&em?s.jsx("p",{className:"max-w-full text-right text-[10px] text-rose-300",role:"alert",children:em}):null]})]})})]})})]}),null,null,null]})});c.useMemo(()=>Ho.some(e=>String(pe[e]||"").trim().length>0),[pe]);const Ne=c.useMemo(()=>vr({standaloneFilmMode:ke,plannedEpisodeCount:Ce,episodeDurationSeconds:te,recentUserTexts:J.filter(e=>e.role==="user").map(e=>String(e.text||"")).filter(Boolean),recentAssistantTexts:J.filter(e=>e.role==="assistant").map(e=>String(e.rawAssistantReply||e.text||"")).filter(Boolean)}),[ke,Ce,te,J]),Om=c.useMemo(()=>iy(P,{standaloneFilmMode:Ne,plannedEpisodeCount:Ce}),[P,Ne,Ce]),Qs=c.useMemo(()=>ye?Ik({setupComplete:Qr,foundationLockedAt:tt,hasEpisodes:P.length>0,hierarchySelectedId:ve}):"foundation",[ye,Qr,tt,P.length,ve]),ct=rr??Qs;c.useEffect(()=>{if(!rr)return;const e=Qo(rr),o=Qo(Qs);(e>o||rr===Qs)&&Lt(null)},[rr,Qs]);const _t=c.useMemo(()=>_k({logline:U.logline,characterCount:we.length,worldBibleReady:Se.worldBibleReady}),[U.logline,we.length,Se.worldBibleReady]),jx=c.useMemo(()=>{const e=[],o=d=>d==="done"?{statusLabel:n("page.storyflow.proSimpleStatusDone"),statusTone:"done"}:d==="editing"?{statusLabel:n("page.storyflow.proSimpleStatusWriting"),statusTone:"writing"}:{statusLabel:n("page.storyflow.proSimpleStatusIdle"),statusTone:"idle"};let l=0;return P.forEach((d,m)=>{const y=Array.isArray(d.generationUnits)?d.generationUnits:[];if(y.length===0){l+=1;const h=Ne?l:m+1,b=String(d.descriptiveScript||d.detailedScript||"").trim(),w=String(d.summary||"").trim(),g=my({detailConfirmed:d.detailConfirmed===!0,hasEditedContent:fy(b)}),A=Ne?n("page.storyflow.proSimpleUnitFallbackFilm",{n:h}):n("page.storyflow.proSimpleUnitFallbackSeries",{n:h});e.push({hierarchyId:`ep:${m}:seq:0`,title:String(d.title||"").trim()||A,subtitle:A,...o(g),synopsis:w});return}y.forEach((h,b)=>{l+=1;const w=typeof h.index=="number"?h.index:b,g=Ne?l:m+1,A=String(h.descriptiveScript||"").trim(),j=String(h.beatSummary||h.summary||d.summary||"").trim(),B=my({detailConfirmed:h.detailConfirmed===!0,hasEditedContent:fy(A)}),_=Ne?n("page.storyflow.proSimpleUnitFallbackFilm",{n:g}):n("page.storyflow.proSimpleUnitFallbackSeries",{n:g}),C=String(h.title||h.label||"").trim(),R=tc(C,g-1,d.title);e.push({hierarchyId:`ep:${m}:seq:${w}`,title:R||_,subtitle:_,...o(B),synopsis:j})})}),e},[P,Ne,n]),Ax=c.useMemo(()=>!ye&&an&&Be==="workspace"&&je==="episodes"&&Vs&&!Om,[ye,Be,je,Vs,Om]),$i=c.useCallback(()=>
787{if(xr.current=!1,be(null),ue("episodes"),Ws("episode_board"),P.length===0){const l=Math.max(1,We(te)/60);if(Ne){const d=Yf(l);Fe([{id:Cr(),title:ge.trim()||n("page.storyflow.episodePromptUntitledEpisode"),summary:String(U.synopsis||"").trim(),attribution:{userName:Z,withBloomBot:!0},durationMin:l,generationUnits:d,scriptFormat:"descriptive"}]),so(new Set),be(ye?null:"ep:0:seq:0")}else{const d=sn(Ce),m=Array.from({length:d},(y,h)=>{const b=`Episode ${h+1}`,w=Vf(h,b,l);return{id:Cr(),title:b,summary:"",attribution:{userName:Z,withBloomBot:!0},durationMin:l,sceneCount:Ut(te),generationUnits:w,scriptFormat:"descriptive"}});Fe(m),so(new Set),be(ye?null:"ep:0:seq:0")}}const e=We(te),o=sn(Ce);lt(n(Ne?"page.storyflow.episodeUnitBreakdownStarterPromptFilm":"page.storyflow.episodeUnitBreakdownStarterPromptSeries",{episodeCount:String(o),durationSec:String(e)}))},[P.length,Ne,te,Ce,ge,U.synopsis,Z,lt,n,ye]),$m=c.useCallback(()=>{const e=Bk(_t.missing);e&&ue(e)},[_t.missing]),jd=c.useCallback(()=>{if(!_t.ready){it(!0),$m();return}it(!1),Lt(null),mr(new Date().toISOString()),xr.current=!1,be(null),ue("episodes"),Ws("episode_board"),(P.length===0||Mk({hasEpisodes:P.length>0,plannedEpisodeCount:Ce}))&&$i(),window.setTimeout(()=>{Ze.current({silent:!0})},0)},[_t.ready,$m,P.length,Ce,$i]),Ix=c.useCallback(e=>{xr.current=!0,Lt(null),ue("episodes");const o=/^ep:(\d+):seq:(\d+)$/.exec(e);if(o){const l=Number(o[1]),d=Number(o[2]);$r(l),Fe(m=>{const y=m[l];if(!y)return m;const h=Array.isArray(y.generationUnits)?y.generationUnits:[];if(h.some(g=>g.index===d))return m;const b={index:d,label:String(y.title||"").trim()||(Ne?`Scene ${d+1}`:`Episode ${l+1}`),targetMinutes:Math.max(1,Math.round(We(te)/60)||1),beatSummary:String(y.summary||"").trim()||void 0,descriptiveScript:String(y.descriptiveScript||"").trim()||void 0,status:"pending"},w=[...m];return w[l]={...y,generationUnits:[...h,b],scriptFormat:"descriptive"},w})}be(e),jt(!1)},[Ne,te]),Ad=c.useCallback(()=>{xr.current=!1,Lt(null),be(null),ue("episodes"),jt(!1)},[]),Px=c.useCallback(e=>{if($k({target:e,unlockedThrough:Qs})){if(e==="foundation"){Lt(Qs==="foundation"?null:"foundation"),xr.current=!0,be(_r),ue("outline"),Ht("outline"),jt(!1);return}if(e==="episode_wall"){Ad();return}e==="detail_script"&&Lt(null)}},[Qs,Ad]),Id=c.useMemo(()=>pk({standaloneFilmMode:Ne,projectTitle:ge,episodes:P,collapsedIds:kp,labels:{structureRoot:n("page.storyflow.hierarchyStructureTitle"),rootFilm:ge||n("page.storyflow.hierarchyModeFilm"),rootSeries:ge||n("page.storyflow.hierarchyModeSeries"),act:e=>n("page.storyflow.hierarchyActLabel",{n:e}),episode:(e,o)=>n("page.storyflow.hierarchyEpisodeLabel",{n:e,title:o}),sequence:(e,o)=>o?n("page.storyflow.hierarchySequenceLabel",{n:e,title:o}):n("page.storyflow.hierarchySequenceLabelShort",{n:e})}}),[Ne,ge,P,kp,n]),_x=c.useCallback(e=>{if(xr.current=!0,e.kind==="root"){ue("outline"),be(_r),Ht("outline");return}if(ue("episodes"),e.kind==="sequence"){be(e.id),typeof e.episodeIndex=="number"&&$r(e.episodeIndex);return}if(e.kind==="episode"||e.kind==="act"){const o=Tu(e);be((o==null?void 0:o.id)??e.id);const l=typeof(o==null?void 0:o.episodeIndex)=="number"?o.episodeIndex:typeof e.episodeIndex=="number"?e.episodeIndex:void 0;typeof l=="number"&&$r(l);return}be(e.id)},[]),Bx=c.useCallback(e=>{Do()&&(Fe(o=>{const l=[...o],d=e.episodeIndex;for(;l.length<=d;)l.push({id:Cr(),title:`Episode ${l.length+1}`,summary:"",attribution:{userName:Z,withBloomBot:!0}});const m=l[d],y=[...m.generationUnits||[]],h=e.unitIndex==null?y.length:e.unitIndex+1;return y.splice(h,0,{index:h,label:Ne?`Sequence ${h+1}`:`åº${h+1}`,targetMinutes:5,actId:Ne?1:void 0,episodeIndex:d,status:"pending"}),l[d]={...m,generationUnits:Xo(y)},l}),Ze.current({silent:!0}))},[Z,Ne]),Mx=c.useMemo(()=>({menuAriaSequence:n("page.storyflow.hierarchyMenuAriaSequence"),menuAriaEpisode:n("page.storyflow.hierarchyMenuAriaEpisode"),menuRename:n("page.storyflow.hierarchyMenuRename"),menuDelete:n("page.storyflow.hierarchyMenuDelete"),renameTitleSequence:n("page.storyflow.hierarchyRenameTitleSequence"),renameTitleEpisode:n("page.storyflow.hierarchyRenameTitleEpisode"),renamePlaceholderSequence:n("page.storyflow.hierarchyRenamePlaceholderSequence"),renamePlaceholderEpisode:n("page.storyflow.hierarchyRenamePlaceholderEpisode"),renameSave:n("page.storyflow.hierarchyRenameSave"),renameCancel:n("page.storyflow.hierarchyRenameCancel"),deleteConfirmSequence:n("page.storyflow.hierarchyDeleteConfirmSequence"),deleteConfirmEpisode:n("page.storyflow.hierarchyDeleteConfirmEpisode")}),[n]),Lx=c.useCallback(e=>e.kind==="episode"?P.length>1:e.kind==="sequence",[P.length]),Ox=c.useCallback((e,o)=>{const l=o.trim();if(l){if(e.kind==="episode"&&typeof e.episodeIndex=="number"){const d=e.episodeIndex;Fe(m=>m.map((y,h)=>h===d?{...y,title:l}:y))}else if(e.kind==="sequence"&&typeof e.episodeIndex=="number"&&typeof e.unitIndex=="number"){const d=e.episodeIndex,m=e.unitIndex;Fe(y=>{const h=[...y],b=h[d];if(!b)return y;const w=(b.generationUnits||[]).map(g=>g.index===m?{...g,label:l,beatSummary:String(g.beatSummary||"").trim()?g.beatSummary:l}:g);return h[d]={...b,generationUnits:w},h})}Ze.current({silent:!0})}},[]),$x=c.useCallback(e=>{var o;if(e.kind==="episode"&&typeof e.episodeIndex=="number"){const l=e.episodeIndex;if(P.length<=1)return;Fe(d=>d.filter((m,y)=>y!==l)),fe(d=>Lv(d,l)),yn(d=>Ov(d,l)),$r(d=>d>l?d-1:d===l?Math.max(0,l-1):d),be(d=>{const m=Math.max(0,l-1);if(!d)return`ep:${m}:seq:0`;if(d===`episode:${l}`||d.startsWith(`ep:${l}:`))return`ep:${m}:seq:0`;const y=/^ep:(\d+):seq:(\d+)$/.exec(d);if(y){const b=Number(y[1]),w=y[2];if(b===l)return`ep:${m}:seq:0`;if(b>l)return`ep:${b-1}:seq:${w}`}const h=/^episode:(\d+)$/.exec(d);if(h){const b=Number(h[1]);if(b===l)return`episode:${m}`;if(b>l)return`episode:${b-1}`}return d}),Ze.current({silent:!0});return}if(e.kind==="sequence"&&typeof e.episodeIndex=="number"&&typeof e.unitIndex=="number"){const l=e.episodeIndex,d=e.unitIndex,m=((o=P[l])==null?void 0:o.generationUnits)||[],y=m.findIndex(b=>
787b.index===d),h=Xo(m.filter(b=>b.index!==d));Fe(b=>{const w=[...b],g=w[l];return g?(w[l]={...g,generationUnits:h},w):b}),fe(b=>Mv(b,l,m,h)),be(b=>{if(b!==e.id)return b;if(h.length>0){const w=Math.min(Math.max(0,y),h.length-1),g=h[w];return`ep:${l}:seq:${g.index}`}return Ne&&e.actId?`act:${e.actId}`:Ne?null:`episode:${l}`}),Ze.current({silent:!0})}},[P,Ne]),$e=c.useMemo(()=>{if(!ve||ve===_r)return null;const e=jh(Id,ve);if(e&&e.kind!=="root")return e.kind==="sequence"?e:Tu(e);const o=ra(ve);if(!o)return null;const l=P[o.episodeIndex];return l?{id:ve,kind:"sequence",label:Ne?n("page.storyflow.proSimpleUnitFallbackFilm",{n:o.unitIndex+1}):n("page.storyflow.proSimpleUnitFallbackSeries",{n:o.episodeIndex+1}),title:String(l.title||"").trim(),summary:String(l.summary||"").trim(),episodeIndex:o.episodeIndex,unitIndex:o.unitIndex,status:"empty"}:null},[ve,Id,P,Ne,n]),Ge=c.useMemo(()=>{const e=$e;if(!e||typeof e.episodeIndex!="number"||typeof e.unitIndex!="number")return null;const o=P[e.episodeIndex],d=((o==null?void 0:o.generationUnits)||[]).find(m=>m.index===e.unitIndex)??null;return d||(o?{index:e.unitIndex,label:String(o.title||"").trim()||(Ne?n("page.storyflow.proSimpleUnitFallbackFilm",{n:e.unitIndex+1}):n("page.storyflow.proSimpleUnitFallbackSeries",{n:e.episodeIndex+1})),targetMinutes:Math.max(1,Math.round(We(te)/60)||1),beatSummary:String(o.summary||"").trim()||void 0,descriptiveScript:String(o.descriptiveScript||"").trim()||void 0,status:"pending"}:null)},[$e,P,Ne,te,n]),gs=c.useMemo(()=>{if(!Ge||!$e)return"";const e=$e.episodeIndex,o=typeof e=="number"?P[e]:void 0;return wy({unit:Ge,episodeTitle:o==null?void 0:o.title,episodeSummary:o==null?void 0:o.summary,standaloneFilmMode:Ne})},[Ge,$e,P,Ne]),Is=c.useMemo(()=>{if(!Ge)return"";const e=String(Ge.descriptiveScript||"");return gs?Zd(e,gs):e},[Ge,gs]);c.useEffect(()=>{if(!$e||!Ge||!gs)return;const e=$e.episodeIndex,o=$e.unitIndex;if(typeof e!="number"||typeof o!="number")return;const l=String(Ge.descriptiveScript||"");lv(l,gs)||Tn(e,o,Zd(l,gs))},[ve,$e,Ge,gs,Tn]);const Fx=c.useCallback(()=>{if(!$e||typeof $e.unitIndex!="number"||ee)return;const e=$e.unitIndex+1,o=gs.trim()||"â",l=Is.trim().slice(0,3500)||"â";ue("episodes"),Ds(n("page.storyflow.refineSelectedUnitStarterPrompt",{n:e,brief:o,scriptExcerpt:l}))},[$e,gs,Is,ee,n]),fl=c.useCallback(()=>{if(!a)return;const e=typeof($e==null?void 0:$e.episodeIndex)=="number"?$e.episodeIndex:Kt>=0?Kt:0;if(e<0||e>=P.length){H.warning(n("page.storyflow.goToWorkflowNeedsScript"));return}let o="",l,d;if(($e==null?void 0:$e.kind)==="sequence"&&typeof $e.unitIndex=="number"?(l=$e.unitIndex,d=String((Ge==null?void 0:Ge.label)||$e.title||"").trim()||void 0,o=Is.trim()):o=Rt(P[e]).trim(),!o){H.warning(n("page.storyflow.goToWorkflowNeedsScript"));return}Jn(null),Ao({bypassWarnings:!0,episodeIndex:e,scriptOverride:o,unitIndex:l,unitLabel:d})},[a,$e,Kt,P,Ge,Is,Ao,n]),Fm=c.useMemo(()=>fk(P),[P]),yl=c.useMemo(()=>{const e=je,o=Ho.find(l=>!String(pe[l]||"").trim())||null;return hk({layoutTab:e,storyArcReady:Se.storyArcReady,worldBibleReady:Se.worldBibleReady,hierarchySelectedId:ve,sequences:Fm,loglineIncomplete:String(U.logline||"").trim().length<12,firstEmptyWorldDimensionId:o})},[je,Se.storyArcReady,Se.worldBibleReady,ve,Fm,U.logline,pe]),Pd=c.useCallback(e=>{if(ye&&e==="episodes"&&!Pk({foundationLockedAt:tt,hasEpisodes:P.length>0})){it(!0),ue("outline");return}ue(e),(e==="outline"||e==="world"||e==="assets")&&(xr.current=!0,be(_r)),e==="episodes"&&(xr.current=!1,ye&&be(null)),Ws(e==="outline"?"outline":e==="world"?"world_bible":e==="episodes"?"episode_board":"assets"),e==="outline"&&Ht("outline"),e==="world"&&Ht("world"),e==="assets"&&Ht(o=>o==="characters"||o==="scenes"||o==="props"?o:"characters")},[ye,tt,P.length]),Dx=c.useCallback(()=>{const e=yl;if(e.kind==="open_workflow"){fl();return}if(e.kind==="start_breakdown"){$i();return}if(e.kind==="select_sequence"&&e.sequenceId){ue("episodes"),Ws("episode_board"),xr.current=!0,be(e.sequenceId),window.setTimeout(()=>cy({...e,kind:"focus_sequence_editor"}),40);return}if(e.kind==="set_tab"&&e.tab){Pd(e.tab);return}(e.kind==="focus_field"||e.kind==="focus_sequence_editor")&&cy(e)},[yl,fl,$i,Pd]),Ux=c.useCallback(e=>{so(o=>{const l=new Set(o);return l.has(e)?l.delete(e):l.add(e),l})},[]),Wx=c.useCallback(e=>{var d;const o=((d=kc.current)==null?void 0:d.clientWidth)??0,l=qh(mi.current+e,{containerPx:o,rightPx:fi.current});mi.current=l,ag(l)},[]),Hx=c.useCallback(e=>{var d;const o=((d=kc.current)==null?void 0:d.clientWidth)??0,l=Au(fi.current+e,{containerPx:o,leftPx:mi.current});fi.current=l,lg(l)},[]),Dm=c.useCallback(()=>{Bv({leftPx:mi.current,rightPx:fi.current})},[]),zx=c.useCallback(e=>{const o=yv(e);Xr(o.projectName),_i(o.projectName),Jr(o.storyflowStandaloneFilmMode),Nt(o.plannedEpisodeCount),Dt(null),o.storyflowStandaloneFilmMode?(ar(On),gr(String(On/60)),kt({episodeCount:!0,episodeDuration:!0})):(ar(Br),gr(String(ln)),kt(d=>({...d,episodeDuration:!0}))),gp(o.storyflowAspectRatio),$s(o.seriesVisualStyleId),Or(o.seriesCustomStylePrompt),ri(o.seriesVisualStyleId==="Custom (Upload Ref)"?e.customStyleImage??null:null),Er(!0),bp(o.setupCollaboratorUserIds);const l=String(o.storyOutlineSynopsis||"").trim();if(ye)Fe([]),mr(null),so(new Set);else if(o.storyflowStandaloneFilmMode){const d=Yf(90);Fe([{id:`film-${Date.now()}`,title:o.projectName,summary:"",attribution:{userName:Z,withBloomBot:!1},durationMin:90,generationUnits:d,scriptFormat:"descriptive"}]),so(new Set),be((d[0],"ep:0:seq:0"))}else{const d=Ji,m=cC,y=Array.from({length:o.plannedEpisodeCount},(h,b)=>{const w=Vf(b,`Episode ${b+1}`,Math.max(1,m));return{id:`ep-${Date.now()}-${b}`,title:`Episode ${b+1}`,summary:"",attribution:{userName:Z,withBloomBot:!1},durationMin:m,sceneCount:Ut(d),generationUnits:w,scriptFormat:"descriptive"}});Fe(y),so(new Set),be("ep:0:seq:0")}bc(!0),ue("outline"),be(_r),Ht("outline"),t&&(pw(t),$==null||$({projectId:t,projectName:o.projectName})),l&&(ga.current=ff(l),Ds(l)),window.setTimeout(()=>{Ze.current({silent:!0}),p==null||p().catch(()=>{})},0)},[Z,t,_i,p,$,ye]),hl=Lk(ye?ct:"foundation");(()=>{if(ye&&Ne&&ct==="episode_wall")return n("page.storyflow.proSimplePathNowFilmWall");
787if(ye&&Ne&&ct==="detail_script")return n("page.storyflow.proSimplePathNowWrite");const e="page.storyflow.proSimple"+hl.nowKey.charAt(0).toUpperCase()+hl.nowKey.slice(1);return n(e)})();const gl=c.useMemo(()=>{for(let e=J.length-1;e>=0;e--){const o=J[e];if((o==null?void 0:o.role)!=="assistant")continue;const l=String(o.rawAssistantReply||o.text||"").trim();if(l)return l}return""},[J]),Fi=c.useMemo(()=>{if(!ye)return null;const e=Kl(String((Ge==null?void 0:Ge.descriptiveScript)||"")).trim(),o=!!ny(J);return Kk({stage:ct,lockMissing:_t.missing,lockReady:_t.ready,storyArcReady:Se.storyArcReady,worldBibleReady:Se.worldBibleReady,layoutTab:je,hasEpisodes:P.length>0,lastAssistantText:gl,detailScriptHasBody:e.length>0,lastAssistantLooksLikeUnitScript:o})},[ye,ct,_t.missing,_t.ready,Se.storyArcReady,Se.worldBibleReady,je,P.length,gl,Ge==null?void 0:Ge.descriptiveScript,J]),Di=c.useMemo(()=>{if(!Fi)return null;const e=Fi,o=Gk(gl),l=Ne,d={proSimpleSitWriteTitle:l?"proSimpleSitWriteTitleFilm":"proSimpleSitWriteTitle",proSimpleSitWriteEmptyTitle:l?"proSimpleSitWriteEmptyTitleFilm":"proSimpleSitWriteEmptyTitle",proSimpleSitWriteApplyChatTitle:l?"proSimpleSitWriteApplyChatTitleFilm":"proSimpleSitWriteApplyChatTitle",proSimpleSitWallEmptyTitle:l?"proSimpleSitWallEmptyTitleFilm":"proSimpleSitWallEmptyTitle",proSimpleSitWallPickTitle:l?"proSimpleSitWallPickTitleFilm":"proSimpleSitWallPickTitle",proSimpleSitReadyLockTitle:l?"proSimpleSitReadyLockTitleFilm":"proSimpleSitReadyLockTitle"},m={proSimpleSitWriteBody:l?"proSimpleSitWriteBodyFilm":"proSimpleSitWriteBody",proSimpleSitWriteEmptyBody:l?"proSimpleSitWriteEmptyBodyFilm":"proSimpleSitWriteEmptyBody",proSimpleSitWriteApplyChatBody:l?"proSimpleSitWriteApplyChatBodyFilm":"proSimpleSitWriteApplyChatBody",proSimpleSitWallEmptyBody:l?"proSimpleSitWallEmptyBodyFilm":"proSimpleSitWallEmptyBody",proSimpleSitWallPickBody:l?"proSimpleSitWallPickBodyFilm":"proSimpleSitWallPickBody",proSimpleSitReadyLockBody:l?"proSimpleSitReadyLockBodyFilm":"proSimpleSitReadyLockBody"},y=d[e.titleKey]||e.titleKey,h=m[e.bodyKey]||e.bodyKey;let b=n(`page.storyflow.${h}`);return e.bodyKey==="proSimpleSitIncompleteBoardBodyProgress"&&o&&(b=n("page.storyflow.proSimpleSitIncompleteBoardBodyProgress",{rows:o.rows,claimed:o.claimed})),{title:n(`page.storyflow.${y}`),body:b,actions:e.actions.filter(w=>w.kind!=="none").map(w=>({label:n(`page.storyflow.${w.labelKey}`),primary:!!w.primary,testId:w.testId,onClick:()=>{if(w.kind==="open_tab"&&w.tab){ue(w.tab);return}if(w.kind==="sync_board"){Li();return}if(w.kind==="lock"){jd();return}if(w.kind==="open_fab"){jt(!0);return}if(w.kind==="apply_chat_script"){nl();return}if(w.kind==="ask_bloombot"&&w.bloombotPromptKey){const g=n(`page.storyflow.${w.bloombotPromptKey}`);jt(!0),lt(g)}}}))}},[Fi,gl,Ne,n,Li,jd,lt,nl]),Kx=(()=>{if(ye&&(Di!=null&&Di.title))return Fk(n("page.storyflow.proSimpleNextPrefix"),Di.title);if(ye&&ct==="foundation"&&!_t.ready)return n("page.storyflow.proSimplePathNextFoundationGaps");if(ye&&Ne&&ct==="episode_wall")return n("page.storyflow.proSimplePathNextFilmWrite");const e="page.storyflow.proSimple"+hl.nextKey.charAt(0).toUpperCase()+hl.nextKey.slice(1);return n(e)})(),qx=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden px-2 pb-0 pt-2","data-tour":"gl-workspace-tabs","data-storyflow-layout-tab":je,"data-storyflow-pro-simple":ye?"1":"0","data-storyflow-pro-simple-stage":ye?ct:"off",children:[ye?s.jsx(Vk,{ariaLabel:n("page.storyflow.proSimpleProgressAria"),nextHint:Kx,steps:Ok(ct,{filmMode:Ne,unlockedThrough:Qs}).map(e=>({id:e.id,tone:e.tone,label:e.labelKey==="proSimpleStepSetup"?n("page.storyflow.proSimpleStepSetup"):e.labelKey==="proSimpleStepFoundation"?n("page.storyflow.proSimpleStepFoundation"):e.labelKey==="proSimpleStepWallFilm"?n("page.storyflow.proSimpleStepWallFilm"):e.labelKey==="proSimpleStepWall"?n("page.storyflow.proSimpleStepWall"):n("page.storyflow.proSimpleStepWrite")})),onSelectStep:Px,primaryCtaLabel:ct==="foundation"?n(Ne?"page.storyflow.proSimpleLockCtaFilm":"page.storyflow.proSimpleLockCta"):null,onPrimaryCta:ct==="foundation"?jd:null,primaryCtaHighlight:ct==="foundation"&&Ot,primaryCtaReady:ct==="foundation"?_t.ready:!0,readinessChips:ct==="foundation"?[{ok:!_t.missing.includes("logline"),label:_t.missing.includes("logline")?n("page.storyflow.proSimpleChipLoglineMiss"):n("page.storyflow.proSimpleChipLoglineOk"),testId:"storyflow-pro-simple-chip-logline",onClick:_t.missing.includes("logline")?()=>ue("outline"):void 0},{ok:!_t.missing.includes("world"),label:_t.missing.includes("world")?n("page.storyflow.proSimpleChipWorldMiss"):n("page.storyflow.proSimpleChipWorldOk"),testId:"storyflow-pro-simple-chip-world",onClick:_t.missing.includes("world")?()=>ue("world"):void 0},{ok:!_t.missing.includes("character"),label:_t.missing.includes("character")?n("page.storyflow.proSimpleChipRoleMiss"):n("page.storyflow.proSimpleChipRoleOk"),testId:"storyflow-pro-simple-chip-role",onClick:_t.missing.includes("character")?()=>ue("assets"):void 0}]:null,readinessWarn:ct==="foundation"&&!_t.ready?n("page.storyflow.proSimpleLockWarn"):null,situationGuide:Fi&&qk(Fi.id)?Di:null}):null,s.jsxs("div",{className:"flex shrink-0 flex-wrap items-end justify-between gap-2 border-b border-white/10",children:[s.jsxs("div",{className:"flex flex-wrap gap-0.5",children:[(ye&&(ct==="episode_wall"||ct==="detail_script")?[["episodes",n(Ne?"page.storyflow.proSimpleTabScenes":"page.storyflow.proSimpleTabEpisodes")]]:ye?[["outline",n("page.storyflow.proSimpleTabPlot")],["world",n("page.storyflow.proSimpleTabWorld")],["assets",n("page.storyflow.proSimpleTabAssets")]]:[["outline",n("page.storyflow.tabPlotOutline")],["world",n("page.storyflow.tabWorldBible")],["assets",n("page.storyflow.tabAssetLibrary")],["episodes",wc(Ne)]]).map(([e,o])=>s.jsx("button",{type:"button","data-testid":`storyflow-layout-tab-${e}`,"aria-selected":je===e,onClick:()=>{Pd(e),e==="episodes"&&!ye&&(xr.current=!1,be(null))},className:`px-3 py-2 text-sm font-bold transition-colors ${je===e?"border-b-2 border-primary text-primary":"border-b-2 border-transparent text-slate-400 hover:text-slate-200"}`,children:o},e)),ye&&ct==="detail_script"&&$e&&typeof $e.unitIndex=="number"?s.jsx("div",{className:"mb-1 ml-2 flex min-w-0 max-w-[min(100%,420p
787x)] flex-col justify-center border-l border-white/10 pl-3","data-testid":"storyflow-pro-simple-detail-heading",children:s.jsxs("span",{className:"truncate text-[11px] font-extrabold text-primary",children:[typeof $e.episodeIndex=="number"?Ne?n("page.storyflow.proSimpleDetailIndexScene",{n:$e.unitIndex+1}):n("page.storyflow.proSimpleDetailIndexEpisode",{ep:$e.episodeIndex+1}):n("page.storyflow.proSimpleDetailIndexScene",{n:$e.unitIndex+1}),s.jsx("span",{className:"mx-1.5 text-neutral-600",children:"·"}),s.jsx("span",{className:"text-white",children:String((Ge==null?void 0:Ge.label)||$e.title||((Vm=P[$e.episodeIndex??-1])==null?void 0:Vm.title)||"").trim()||n("page.storyflow.proSimpleDetailUntitled")})]})}):null]}),s.jsxs("div",{className:"mb-1 flex max-w-[min(100%,640px)] shrink-0 flex-wrap items-center justify-end gap-2","aria-label":n("page.storyflow.seriesPlanMetaAria"),children:[ye&&ct==="detail_script"?s.jsx("button",{type:"button","data-testid":"storyflow-pro-simple-back-wall",onClick:Ad,className:"inline-flex h-7 items-center rounded-md border border-white/15 bg-black/30 px-2.5 text-[10px] font-bold uppercase tracking-wide text-slate-200 hover:border-primary/40 hover:text-primary",children:n(Ne?"page.storyflow.proSimpleBackToWallFilm":"page.storyflow.proSimpleBackToWall")}):null,ye&&ct==="detail_script"?null:s.jsx("button",{type:"button","data-testid":"storyflow-sync-board-from-chat",onClick:()=>void Li(),disabled:ee||J.filter(e=>e.role==="assistant").length===0,title:n("page.storyflow.syncBoardFromChatTitle"),className:"inline-flex h-7 items-center rounded-md border border-white/15 bg-black/30 px-2.5 text-[10px] font-semibold uppercase tracking-wide text-slate-300 transition-colors hover:border-primary/40 hover:text-primary disabled:cursor-not-allowed disabled:opacity-40",children:n("page.storyflow.syncBoardFromChat")}),Rd,ye&&ct==="detail_script"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","data-testid":"storyflow-pro-simple-save-unit",onClick:od,disabled:!Is.trim(),className:"inline-flex h-7 items-center rounded-md border border-white/15 bg-black/30 px-2.5 text-[10px] font-bold uppercase tracking-wide text-slate-200 hover:border-primary/40 hover:text-primary disabled:cursor-not-allowed disabled:opacity-40",children:n("page.storyflow.proSimpleSaveUnit")}),s.jsx("button",{type:"button","data-testid":"storyflow-pro-simple-go-workflow",onClick:fl,disabled:!a||!Is.trim()||(Ge==null?void 0:Ge.detailConfirmed)!==!0,title:(Ge==null?void 0:Ge.detailConfirmed)===!0?void 0:n("page.storyflow.proSimpleGoWorkflowNeedConfirm"),className:"inline-flex h-7 items-center gap-1 rounded-md border border-primary/45 bg-primary/20 px-2.5 text-[10px] font-bold uppercase tracking-wide text-primary transition-colors hover:bg-primary/30 disabled:cursor-not-allowed disabled:opacity-40",children:n("page.storyflow.proSimpleGoWorkflow")})]}):ye?null:s.jsxs("button",{type:"button","data-testid":"storyflow-next-step",onClick:Dx,disabled:yl.kind==="open_workflow"&&!a,className:"inline-flex h-7 items-center gap-1 rounded-md border border-primary/45 bg-primary/20 px-2.5 text-[10px] font-bold uppercase tracking-wide text-primary transition-colors hover:bg-primary/30 disabled:cursor-not-allowed disabled:opacity-40",children:[s.jsx("span",{className:"material-symbols-outlined text-[12px] leading-none",style:{fontSize:"12px"},children:"arrow_forward"}),yl.useGoToWorkflowLabel?n("page.storyflow.goToWorkflowButton"):n("page.storyflow.nextStep")]})]})]}),s.jsx("div",{className:`mt-3 flex min-h-0 flex-col overflow-hidden rounded-xl border border-white/10 bg-surface-dark ${je==="episodes"?"hidden":"flex-1"}`,"data-testid":"storyflow-unified-tab-panel",children:s.jsx("div",{className:`min-h-0 flex-1 p-4 custom-scrollbar ${je==="outline"?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:je==="outline"?s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[s.jsx("p",{className:"shrink-0 text-[11px] leading-snug text-neutral-500",children:n("page.storyflow.unifiedShellOutlineFieldHint")}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4 lg:flex-row lg:gap-5",children:[s.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:[s.jsxs("div",{className:"min-w-0 shrink-0",children:[s.jsx("h3",{className:"mb-1.5 text-sm font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.titleSection")}),s.jsx("input",{type:"text",className:"block w-full border-0 bg-transparent p-0 font-display text-sm font-bold text-white outline-none placeholder:text-neutral-500 focus:ring-0",value:ge,onChange:e=>{const o=e.target.value;nr("title"),Xr(o),_i(o)},placeholder:n("page.storyflow.seriesOrFilmTitlePlaceholder"),"aria-label":n("page.storyflow.seriesOrFilmTitleAria")}),gd,xd,bd]}),s.jsxs("div",{className:"min-w-0 shrink-0 border-t border-white/10 pt-4",children:[s.jsx("h3",{className:"mb-1.5 text-sm font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.loglineLabel")}),s.jsx("textarea",{className:"block min-h-[3.5rem] w-full resize-none border-0 bg-transparent p-0 text-sm leading-relaxed text-neutral-200 outline-none placeholder:text-neutral-500 focus:ring-0",value:U.logline,"data-storyflow-focus":"outline-logline",onChange:e=>{nr("logline"),Rr(o=>({...o,logline:e.target.value}))},placeholder:n("page.storyflow.loglinePlaceholder"),"aria-label":n("page.storyflow.loglineAria")})]}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col border-t border-white/10 pt-4",children:[s.jsx("h3",{className:"mb-1.5 shrink-0 text-sm font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.synopsisLabel")}),s.jsx("textarea",{className:"block min-h-0 flex-1 w-full resize-none overflow-y-auto border-0 bg-transparent p-0 text-sm leading-relaxed text-neutral-200 outline-none placeholder:text-neutral-500 focus:ring-0",value:U.synopsis,"data-storyflow-focus":"outline-synopsis",onChange:e=>{nr("synopsis"),Rr(o=>({...o,synopsis:e.target.value}))},placeholder:n("page.storyflow.shortSynopsisPlaceholder"),"aria-label":n("page.storyflow.synopsisAria")})]})]}),s.jsx(Zv,{posterUrl:Vt,placeholderSrc:Td,busy:es,titleStale:Sm,editorOpen:cg,promptDraft:bn,sparksLabel:n("page.storyflow.outlinePosterRegenSp
787arks",{sparks:Qv}),clickToEditHint:n("page.storyflow.outlinePosterClickHint"),promptLabel:n("page.storyflow.outlinePosterPromptLabel"),promptPlaceholder:n("page.storyflow.outlinePosterPromptPlaceholder"),staleBadge:n("page.storyflow.posterTitleStaleBadge"),staleHint:n("page.storyflow.posterTitleStaleHint"),remakeLabel:n("page.storyflow.posterRemakeWithNewTitle"),keepLabel:n("page.storyflow.posterKeepCurrent"),onOpenEditor:()=>{bn.trim()||Ba(Ed()),Cp(!0)},onCloseEditor:()=>Cp(!1),onPromptChange:Ba,onGenerate:()=>void Bn({billing:"user_regen",force:!0,promptOverride:bn}),onRemakeWithTitle:()=>void Bn({force:!0,billing:"auto_free"}),onKeepCurrentTitle:()=>hi((ge||"").trim()||null)})]})]}):je==="world"?s.jsxs("div",{className:"flex flex-col gap-3","data-testid":"storyflow-world-bible-panel",children:[s.jsx("p",{className:"text-[11px] leading-snug text-neutral-500",children:n("page.storyflow.unifiedShellWorldFieldHint")}),er.map((e,o)=>s.jsxs("div",{className:`min-w-0 ${o>0?"border-t border-white/10 pt-3":""}`,children:[s.jsx("h3",{className:"mb-1.5 text-sm font-bold uppercase tracking-wider text-primary",children:Pe(e.id)}),s.jsx("textarea",{className:"block min-h-[2.75rem] w-full resize-none border-0 bg-transparent p-0 text-sm leading-relaxed text-neutral-200 outline-none placeholder:text-neutral-500 focus:ring-0",value:pe[e.id],"data-storyflow-focus":"world-dimension","data-world-dimension":e.id,onChange:l=>{nr(e.id),Us(d=>({...d,[e.id]:l.target.value}))},placeholder:xe(e.id),"aria-label":Pe(e.id)})]},e.id))]}):je==="assets"?s.jsxs("div",{className:"flex min-h-full flex-col",children:[s.jsx("div",{className:"flex gap-1 border-b border-white/10 pb-2",children:[["characters",n("page.storyflow.tabCharacters")],["scenes",n("page.storyflow.tabScenes")],["props",n("page.storyflow.tabProps")]].map(([e,o])=>s.jsx("button",{type:"button",onClick:()=>Ht(e),className:`rounded-md px-2.5 py-1 text-[11px] font-semibold ${gt===e?"bg-primary/20 text-primary":"text-slate-400 hover:text-slate-200"}`,children:o},e))}),gt==="characters"||gt!=="scenes"&>!=="props"?s.jsx("div",{className:"mt-1.5 flex min-h-0 flex-1 flex-col overflow-y-auto custom-scrollbar",children:s.jsx("div",{className:"grid grid-cols-3 gap-3",children:Et.length>0?Et.map(e=>{var o;return s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"CHARACTERS",characterId:e.id,name:e.name}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl border border-white/10 bg-black/20 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:(()=>{const l=ls("CHARACTERS",e.id,e.name);return l&&l!=="/cloud.png"?s.jsx("img",{src:l,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):s.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center bg-gradient-to-br from-zinc-800 to-zinc-950 px-2",children:[s.jsx("span",{className:"text-lg font-bold text-white/35",children:e.name.slice(0,1)}),s.jsx("span",{className:"mt-1 line-clamp-2 text-center text-[10px] font-semibold text-white/50",children:e.name})]})})()}),s.jsxs("div",{className:"space-y-0.5 p-2.5",children:[s.jsx("p",{className:"truncate font-display text-sm font-bold text-white",children:e.name}),(o=e.backstory)!=null&&o.trim()?s.jsx("p",{className:"line-clamp-2 text-[11px] leading-snug text-neutral-400",children:e.backstory.trim()}):Xe?s.jsx("p",{className:"text-[10px] text-neutral-500",children:n("page.storyflow.markerDescPending")}):null]})]},e.id)}):s.jsxs("div",{className:"col-span-3 rounded-lg border border-white/10 bg-black/20 px-3 py-2.5",children:[s.jsx("p",{className:"text-xs text-neutral-400",children:n("page.storyflow.noCharactersYet")}),s.jsx("button",{type:"button",onClick:pl,className:"mt-2 inline-flex items-center rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary transition-colors hover:bg-primary/20",children:n("page.storyflow.addCharacterButton")})]})})}):null,gt==="scenes"?s.jsx("div",{className:"mt-1.5 flex min-h-0 flex-1 flex-col overflow-y-auto custom-scrollbar",children:s.jsx("div",{className:"grid grid-cols-3 gap-3",children:Xt.length>0?Xt.map(e=>s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"SCENES",name:e}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl border border-white/10 bg-black/20 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:(()=>{const o=ls("SCENES",void 0,e);return o&&o!=="/cloud.png"?s.jsx("img",{src:o,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-full w-full flex-col items-center justify-center bg-gradient-to-br from-zinc-800 to-zinc-950 px-2",children:s.jsx("span",{className:"line-clamp-2 text-center text-[11px] font-semibold text-white/50",children:e})})})()}),s.jsxs("div",{className:"p-2.5",children:[s.jsx("p",{className:"truncate font-display text-sm font-bold text-white",children:e}),(()=>{const o=bo.get(on(e));return o?s.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-snug text-neutral-400",children:o}):Xe?s.jsx("p",{className:"mt-0.5 text-[10px] text-neutral-500",children:n("page.storyflow.markerDescPending")}):null})()]})]},e)):s.jsx("p",{className:"col-span-3 text-xs text-neutral-500",children:n("page.storyflow.noKeyScenesYet")})})}):null,gt==="props"?s.jsx("div",{className:"mt-1.5 flex min-h-0 flex-1 flex-col overflow-y-auto custom-scrollbar",children:s.jsx("div",{className:"grid grid-cols-3 gap-3",children:br.length>0?br.map(e=>s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"PROPS",name:e}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl border border-white/10 bg-black/20 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:(()=>{const o=ls("PROPS",void 0,e);return o&&o!=="/cloud.png"?s.jsx("img",{src:o,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-full w-full flex-col items-center justify-center bg-gradient-to-br from-zinc-800 to-zinc-950 px-2",children:s.jsx("span",{className:"line-clamp-2 text-center text-[11px] font-semibold text-white/50",children:e})})})()}),s.jsxs("div",{className:"p-2.5",children:[s.jsx("p",{className:"truncate font-display text-sm font-bold text-white",children:e}),(()=>{const o=wo.get(on(e));return o?s.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-snug text-neutral-400",children:o}):Xe?s.jsx("p",{className:"mt-0.5 text-[10px] text-neutral-500",children:n("page.storyflow.markerDescPending")}):null})()]})]},e)):s.jsx("p",{className:"col-span-3 text-xs text-neutral-500",children:n("page.storyflow.noKeyPropsYet")})})}):null]}):null})}),ye&&ct==="episode_wall"?s.jsx("div",{className:"mt-3 flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-white/10 bg-surface-dark p-4",children:s.jsx(Yk,{cards:jx,emptyLabel:n("page.storyflow.proSimpleWallEmpty"),hintLabel:n("page.storyflow.proSimpleWallHint"),synopsisFallbackLabel:n("page.storyflow.proSimpleWallNoSynopsis"),onSelect:Ix})}):null,ye&&ct==="detail_script"||!ye&&je==="episodes"&&Se.storyArcReady&&Se.worldBibleReady?s.jsxs("section",{className:"mt-3 flex min-h-0 flex-1 flex-col overflow-y-auto custom-scrollbar roun
787ded-xl border border-white/10 bg-surface-dark p-4","aria-label":n(Ne?"page.storyflow.filmDetailedScriptSection":"page.storyflow.episodesSectionShort"),"data-testid":Ne?"storyflow-unified-film-script-section":"storyflow-unified-episodes-section",children:[ye&&ct==="detail_script"?null:s.jsx("div",{className:"mb-3 shrink-0",children:s.jsx("h3",{className:"text-sm font-bold text-white",children:n(Ne?"page.storyflow.filmDetailedScriptSection":"page.storyflow.episodesSectionShort")})}),Ax?s.jsxs("div",{className:"mb-4 rounded-xl border border-primary/30 bg-primary/5 p-4","data-testid":"storyflow-episode-unit-breakdown-cta",children:[s.jsx("h4",{className:"text-sm font-bold text-white",children:n("page.storyflow.episodeUnitBreakdownEmptyTitle")}),s.jsx("p",{className:"mt-2 text-xs leading-relaxed text-neutral-300",children:n("page.storyflow.episodeUnitBreakdownEmptyBody",{episodesTab:Es})}),s.jsx("button",{type:"button",className:"mt-3 rounded-lg bg-primary px-4 py-2 text-xs font-bold text-black hover:brightness-110 disabled:opacity-50",disabled:ee,onClick:()=>void $i(),"data-testid":"storyflow-episode-unit-breakdown-start",children:n("page.storyflow.episodeUnitBreakdownStartButton",{episodesTab:Es})})]}):null,Ne&&!ye&&((Xm=P[0])==null?void 0:Xm.scriptFormat)==="legacy_shot"?s.jsx("p",{className:"mb-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-relaxed text-amber-100/90","data-testid":"storyflow-legacy-shot-script-banner",children:n("page.storyflow.descriptiveScriptLegacyShotBanner")}):null,$e&&typeof $e.unitIndex=="number"?s.jsx(_v,{title:ye?n("page.storyflow.proSimpleDetailPanelTitle"):n("page.storyflow.selectedSequencePanelTitle",{n:$e.unitIndex+1}),indexLabel:typeof $e.episodeIndex=="number"?Ne?n("page.storyflow.proSimpleDetailIndexScene",{n:$e.unitIndex+1}):n("page.storyflow.proSimpleDetailIndexEpisode",{ep:$e.episodeIndex+1}):void 0,unitTitle:String((Ge==null?void 0:Ge.label)||$e.title||((Jm=P[$e.episodeIndex??-1])==null?void 0:Jm.title)||"").trim()||void 0,summary:(()=>{var m;const e=String((Ge==null?void 0:Ge.beatSummary)||"").trim();if(e)return e;const o=String(((m=P[$e.episodeIndex??-1])==null?void 0:m.summary)||"").trim();if(o)return o;const l=String(gs||"").trim();if(!l)return;const d=l.split(` 788`).map(y=>y.trim()).filter(Boolean);return d.length>1?d.slice(1).join(` 789`):d[0]})(),summaryPlaceholder:n("page.storyflow.proSimpleDetailSynopsisEmpty"),alwaysShowSynopsis:ye,indexFieldLabel:n("page.storyflow.proSimpleDetailFieldIndex"),titleFieldLabel:n("page.storyflow.proSimpleDetailFieldTitle"),synopsisFieldLabel:n("page.storyflow.proSimpleDetailFieldSynopsis"),value:ye?Kl(Is):Is,emptyText:n("page.storyflow.noDetailedScriptSavedYet"),refineWithBloomBotLabel:ye?void 0:n("page.storyflow.refineSelectedUnitWithBloomBot"),onRefineWithBloomBot:ye?void 0:Fx,refineWithBloomBotDisabled:ee,goToWorkflowLabel:ye?void 0:n("page.storyflow.goToWorkflowButton"),onGoToWorkflow:ye||!a?void 0:fl,goToWorkflowDisabled:!Is.trim(),onChange:Ge&&typeof $e.episodeIndex=="number"?e=>Tn($e.episodeIndex,$e.unitIndex,e):void 0}):Ne&&!Xe?(()=>{const e=P[0],o=e?String(Rt(e)||"").trim():"",l=String((e==null?void 0:e.summary)||"").trim();return o?s.jsx("pre",{className:"max-h-[min(40vh,420px)] overflow-y-auto custom-scrollbar whitespace-pre-wrap rounded-lg border border-white/10 bg-black/20 p-3 text-xs leading-relaxed text-neutral-300","data-testid":"storyflow-unified-film-merged-script",children:o.slice(0,12e3)}):l?s.jsx("p",{className:"text-xs leading-relaxed text-neutral-400",children:l}):s.jsx("p",{className:"text-xs text-neutral-500",children:n("page.storyflow.noDetailedScriptSavedYet")})})():s.jsx("p",{className:"text-xs text-neutral-500","data-testid":"storyflow-selected-sequence-empty",children:n(ye?Ne?"page.storyflow.proSimpleDetailNeedCardHintFilm":"page.storyflow.proSimpleDetailNeedCardHint":"page.storyflow.selectedSequenceEmptyHint")})]}):!ye&&je==="episodes"?s.jsx("p",{className:"mt-4 shrink-0 text-center text-[11px] leading-snug text-neutral-500","data-testid":"storyflow-episodes-locked-hint",children:Se.storyArcReady?n(Ne?"page.storyflow.unifiedShellFilmScriptAfterWorldHint":"page.storyflow.unifiedShellEpisodesAfterWorldHint"):n(Ne?"page.storyflow.unifiedShellFilmScriptAfterOutlineHint":"page.storyflow.unifiedShellEpisodesAfterOutlineHint")}):ye&&ct==="foundation"&&je==="episodes"?s.jsx("p",{className:"mt-4 shrink-0 text-center text-[11px] leading-snug text-neutral-500","data-testid":"storyflow-pro-simple-gate-need-lock",children:n(Ne?"page.storyflow.proSimpleGateNeedLockFilm":"page.storyflow.proSimpleGateNeedLock")}):null]});return[["outline",n("page.storyflow.tabStoryOutline"),"article"],["
789world",n("page.storyflow.tabWorldBible"),"public"],["characters",n("page.storyflow.tabCharacters"),"person"],["scenes",n("page.storyflow.tabScenes"),"landscape"],["props",n("page.storyflow.tabProps"),"category"]].map(([e,o,l])=>s.jsxs("button",{type:"button",onClick:()=>Ht(e),className:`px-3 sm:px-5 py-2 text-sm font-bold rounded-t-xl flex items-center gap-2 transition-all ${gt===e?"bg-surface-dark border border-white/10 border-b-0 text-primary -mb-px z-10 shadow-[0_-2px_10px_rgba(0,0,0,0.3)]":"bg-black/40 border border-white/5 border-b-white/10 text-primary/75 hover:text-primary"}`,children:[s.jsx("span",{className:"material-symbols-outlined text-[22px] shrink-0",children:l}),s.jsx("span",{className:"whitespace-nowrap",children:o})]},e)),n("page.storyflow.seriesPlanMetaAria"),gt==="outline"?(Sm&&Vt&&(n("page.storyflow.posterTitleStaleBadge"),n("page.storyflow.posterTitleStaleHint"),`${tn}`,n("page.storyflow.posterRemakeWithNewTitle"),`${tn}`,n("page.storyflow.posterKeepCurrent")),n("page.storyflow.titleSection"),n("page.storyflow.seriesOrFilmTitlePlaceholder"),n("page.storyflow.seriesOrFilmTitleAria"),n("page.storyflow.loglineLabel"),U.logline,n("page.storyflow.loglineAria"),n("page.storyflow.synopsisLabel"),U.synopsis,n("page.storyflow.synopsisAria")):gt==="world"?er.map((e,o)=>s.jsxs("div",{className:`min-w-0 ${o>0?"border-t border-white/10 pt-3":""}`,children:[s.jsx("h3",{className:"text-sm font-bold text-primary uppercase tracking-wider mb-1.5",children:Pe(e.id)}),s.jsx("textarea",{className:"block w-full min-h-[2.75rem] bg-transparent border-0 p-0 text-sm text-neutral-200 placeholder:text-neutral-500 outline-none focus:ring-0 resize-none leading-relaxed",value:pe[e.id],onChange:l=>{nr(e.id),Us(d=>({...d,[e.id]:l.target.value}))},onBlur:hd,"aria-label":Pe(e.id)})]},e.id)):gt==="assets"||gt==="characters"||gt==="scenes"||gt==="props"?(n("page.storyflow.keyAssetsTitle"),n("page.storyflow.designClickCardHint"),(gt==="assets"||gt==="characters")&&(n("page.storyflow.charactersSection"),Et.length>0?Et.map(e=>s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"CHARACTERS",characterId:e.id,name:e.name}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl bg-surface-dark border border-white/5 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:s.jsx("img",{src:ls("CHARACTERS",e.id,e.name),alt:"",className:"h-full w-full object-contain"})}),s.jsx("div",{className:"p-3",children:s.jsx("p",{className:"truncate text-sm font-bold text-white font-display",children:e.name})})]},e.id)):(n("page.storyflow.noCharactersYet"),n("page.storyflow.addCharacterButton"))),(gt==="assets"||gt==="scenes")&&(n("page.storyflow.scenesShort"),Xt.length>0?Xt.map(e=>s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"SCENES",name:e}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl bg-surface-dark border border-white/5 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:s.jsx("img",{src:ls("SCENES",void 0,e),alt:"",className:"h-full w-full object-contain"})}),s.jsx("div",{className:"p-3",children:s.jsx("p",{className:"truncate text-sm font-bold text-white font-display",children:e})})]},e)):n("page.storyflow.noKeyScenesYet")),(gt==="assets"||gt==="props")&&(n("page.storyflow.propsShort"),br.length>0?br.map(e=>s.jsxs("button",{type:"button",onClick:()=>Pn({kind:"PROPS",name:e}),className:"flex min-w-0 flex-col overflow-hidden rounded-xl bg-surface-dark border border-white/5 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("div",{className:"relative aspect-video w-full overflow-hidden bg-black",children:s.jsx("img",{src:ls("PROPS",void 0,e),alt:"",className:"h-full w-full object-contain"})}),s.jsx("div",{className:"p-3",children:s.jsx("p",{className:"truncate text-sm font-bold text-white font-display",children:e})})]},e)):n("page.storyflow.noKeyPropsYet"))):n("page.storyflow.designClickCardHint"),n("page.storyflow.episodeBreakdownSection"),n("page.storyflow.episodeBreakdownSection"),n("page.storyflow.regenerateEpisodeSummariesTitle"),n("page.storyflow.reanalyzeTitle"),P.map((e,o)=>{var R,T;e1(e);const l=We(typeof e.durationMin=="number"&&e.durationMin>0?Math.round(e.durationMin*60):te),d=typeof e.sceneCount=="number"&&e.sceneCount>0?Math.round(e.sceneCount):Ut(l),m=zt(Rt(e)||"").scriptBody,{count:y,lastMax:h}=Fn(m),b=Math.max(y,h),w=Xe?sa(Rt(e)||""):d>0&&b>=d,g=RC(e.title),A=`${String(e.title||"")} 790${String(e.summary||"")}`,j=A.toLowerCase(),B=(R=e.characterRefs)!=null&&R.length?e.characterRefs.map(M=>
790Mt(String(M.name||"").trim())).filter(Boolean):Cg.filter(M=>j.includes(M.toLowerCase())),_=(T=e.characterRefs)!=null&&T.length?e.characterRefs.map(M=>({...M,name:Mt(String(M.name||""))})):B.map(M=>({name:M})),C=(()=>{var Y;if((Y=e.scenes)!=null&&Y.length)return e.scenes.map(F=>String(F||"").trim()).filter(Boolean);const M=Ng.filter(F=>j.includes(F.toLowerCase())),W=Wo(A,"SCENE"),q=pu(A,["scenes","scene","åºæ¯"]),G=Fy(A);return[...new Set([...M,...W,...q,...G])].filter(Boolean)})();return s.jsxs("div",{className:`relative flex h-[220px] flex-col gap-2 overflow-hidden rounded-xl border border-white/5 bg-surface-dark p-3 sm:h-[220px] sm:p-4 ${a?"pb-8 pr-[4.5rem]":""}`,children:[s.jsx("div",{className:"relative -mx-3 -mt-3 mb-0 aspect-video w-[calc(100%+1.5rem)] overflow-hidden bg-black/50 sm:-mx-4 sm:-mt-4 sm:w-[calc(100%+2rem)]",children:(()=>{const M=fS({scenes:C,characterNames:_.map(W=>W.name),sceneMediaByName:kx,characterMediaByName:vx});return M?s.jsx("img",{src:M,alt:"",className:"h-full w-full object-cover"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-zinc-800 to-zinc-950",children:s.jsx("span",{className:"text-lg font-bold tabular-nums text-white/40",children:n("page.storyflow.episodeCoverPlaceholder",{n:o+1})})})})()}),s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("p",{className:"line-clamp-1 min-w-0 text-sm font-bold text-white font-display",children:[s.jsx("span",{className:"text-xs uppercase tracking-wide text-primary tabular-nums",children:ne(o+1)}),s.jsx("span",{className:"ml-[1ch]",children:Ie(g||e.title,o+1)})]}),w?s.jsx("span",{className:"shrink-0 rounded-md border border-primary/60 bg-primary px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-black",children:n("page.storyflow.completed")}):null]}),s.jsx("textarea",{value:String(e.summary||""),onChange:M=>Wg(o,M.target.value),placeholder:n("page.storyflow.episodeSummaryEditablePlaceholder"),className:"w-full min-h-[56px] max-h-[72px] resize-none rounded-md border border-white/10 bg-black/15 px-2 py-1.5 text-xs leading-relaxed text-neutral-300 placeholder:text-neutral-500 focus:outline-none focus:ring-1 focus:ring-primary/40"}),_.length?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:_.slice(0,5).map((M,W)=>s.jsx("div",{className:"size-7 shrink-0 overflow-hidden rounded-full border border-white/10 bg-slate-700",title:M.name,children:M.imgUrl?s.jsx("img",{src:M.imgUrl,alt:"",className:"h-full w-full object-cover"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-slate-700/80",children:s.jsx("span",{className:"text-[12px] font-bold text-slate-200",children:$y(M.name)})})},`${M.name}-${W}`))}):null,C.length?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:C.slice(0,4).map((M,W)=>s.jsx("span",{className:"rounded-md border border-amber-500/35 bg-amber-500/20 px-2 py-0.5 text-[10px] font-semibold text-amber-200",title:M,children:M},`${M}-${W}`))}):null,s.jsx("button",{type:"button",onClick:()=>fm(o),className:`text-xs font-bold uppercase text-primary ${a?"absolute bottom-3 left-3":""}`,children:n("page.storyflow.edit")}),a?s.jsx("button",{type:"button",onClick:()=>{const M=Rt(e).trim();if(!M){H.warning(n("page.storyflow.goToWorkflowNeedsScript"));return}Ao({bypassWarnings:!0,episodeIndex:o,scriptOverride:M})},className:"absolute bottom-3 right-3 max-w-[5rem] text-right text-[10px] font-bold uppercase leading-tight text-emerald-400",children:n("page.storyflow.goToWorkflowButton")}):null]},e.id)}),s.jsxs("div",{className:"flex h-full flex-1 flex-col overflow-hidden bg-background-dark",children:[Nx,yp&&!Qr&&t&&(ye||wl(t))?s.jsx(bv,{initialTitle:ws(ge)?"":ge,onSubmit:zx,onClose:I,t:n,locale:z}):null,rg&&yp&&(Qr||!ye)?s.jsxs("div",{role:"dialog","aria-label":n("page.storyflow.startTourAria"),className:"fixed bottom-4 left-1/2 z-[9998] w-[min(420px,calc(100vw-24px))] -translate-x-1/2 rounded-xl border border-white/15 bg-[#1e2226] p-3 shadow-[0_16px_40px_rgba(0,0,0,0.45)]","data-testid":"storyflow-first-visit-tour-gate",children:[s.jsx("p",{className:"text-sm leading-relaxed text-slate-300",children:n("page.storyflow.quickStartTourHint")}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:Ug,className:"rounded-lg border border-white/15 bg-white/5 px-3 py-1.5 text-[11px] font-semibold text-slate-200 hover:bg-white/10",children:n("page.storyflow.skipTourButton")}),s.jsx("button",{type:"button",onClick:Dg,className:"rounded-lg bg-primary px-3 py-1.5 text-[11px] font-semibold text-black hover:brightness-110",children:n("page.storyflow.startTourButton")})]})]}
790):null,s.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:[s.jsxs("div",{ref:sm,className:"grid flex-1 min-h-0 min-w-0 overflow-hidden",style:{gridTemplateColumns:Be==="classic"?Og:"minmax(0, 1fr)"},children:[s.jsxs("aside",{ref:lc,className:"min-w-0 bg-background-dark flex flex-col overflow-hidden",children:[Be==="classic"?s.jsxs("div",{className:"shrink-0 flex flex-wrap items-center gap-2 border-b border-white/10 px-3 py-2 bg-[#1a1d20]",children:[s.jsx("button",{type:"button",role:"switch","aria-checked":Za,onClick:Eg,className:`shrink-0 rounded-md border px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wide transition-colors ${Za?"border-primary/50 bg-primary/15 text-primary":"border-white/15 text-slate-500 hover:border-white/25 hover:text-slate-300"}`,title:n("page.storyflow.textTableToggleTitle"),"aria-label":n("page.storyflow.textTableToggleAria"),children:n("page.storyflow.textTableButton")}),s.jsx("button",{type:"button",onClick:pm,className:"shrink-0 text-[11px] font-bold text-primary hover:text-primary/90 hover:underline transition-colors uppercase",style:{marginRight:3},"aria-label":n("page.storyflow.newChatAria"),children:n("page.storyflow.newChatButton")})]}):null,s.jsxs("div",{ref:kc,className:"relative flex min-h-0 flex-1 flex-row overflow-hidden px-2 pb-2 pt-1.5 max-lg:flex-col","data-testid":"storyflow-three-col-shell",children:[ye?null:s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex min-w-0 shrink-0 flex-col overflow-hidden max-lg:max-h-[32vh] max-lg:!w-full max-lg:min-w-0 max-lg:max-w-none",style:{width:Sc},"data-testid":"storyflow-col-left",children:s.jsx(Pv,{root:Id,selectedId:ve,standaloneFilmMode:Ne,modeLabel:n(Ne?"page.storyflow.hierarchyModeFilm":"page.storyflow.hierarchyModeSeries"),newEpisodeLabel:n(Ne?"page.storyflow.hierarchyNewAct":"page.storyflow.hierarchyNewEpisode"),onSelect:_x,onToggleExpand:Ux,onAddEpisode:Ne?void 0:ud,showAddEpisode:!Ne,onInsertSequence:Do()?Bx:void 0,emptySequenceSummary:n("page.storyflow.hierarchySequenceSummaryEmpty"),insertSequenceAriaLabel:n("page.storyflow.hierarchyInsertSequenceAria"),menuLabels:Mx,onRenameNode:Ox,onDeleteNode:$x,canDeleteNode:Lx})}),s.jsx(Ry,{side:"left",ariaLabel:n("page.storyflow.columnResizeLeftAria"),onResizeDelta:Wx,onResizeEnd:Dm,testId:"storyflow-col-splitter-left"})]}),s.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden max-lg:border-t","data-tour":"gl-workspace",children:[qx,ye&&ct==="detail_script"&&!Ls?s.jsx(hy,{open:!1,showFab:!0,fabLabel:n("page.storyflow.proSimpleFabLabel"),titleLabel:n("page.storyflow.proSimpleFabTitle"),closeLabel:n("page.storyflow.proSimpleFabClose"),onOpen:()=>jt(!0),onClose:()=>jt(!1),children:null}):null]}),ye&&ct==="detail_script"?Ls?s.jsx("div",{className:"flex min-w-0 shrink-0 flex-col overflow-hidden bg-[#0d0f12] max-lg:max-h-[40vh] max-lg:!w-full",style:{width:_a},"data-testid":"storyflow-bloombot-dock","data-tour":"gl-bloombot-dock",children:s.jsx(hy,{open:!0,showFab:!1,fabLabel:n("page.storyflow.proSimpleFabLabel"),titleLabel:n("page.storyflow.proSimpleFabTitle"),closeLabel:n("page.storyflow.proSimpleFabClose"),onOpen:()=>jt(!0),onClose:()=>jt(!1),children:s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:Lm})})}):null:s.jsxs(s.Fragment,{children:[s.jsx(Ry,{side:"right",ariaLabel:n("page.storyflow.columnResizeRightAria"),onResizeDelta:Hx,onResizeEnd:Dm,testId:"storyflow-col-splitter-right"}),s.jsx("div",{className:"flex min-w-0 shrink-0 flex-col overflow-hidden bg-[#0d0f12] max-lg:max-h-[40vh] max-lg:!w-full max-lg:min-w-0 max-lg:max-w-none max-lg:border-t",style:{width:_a},"data-testid":"storyflow-bloombot-dock","data-tour":"gl-bloombot-dock",children:s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:Lm})})]})]})]}),Be==="classic"?s.jsxs(s.Fragment,{children:[s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":n("page.storyflow.resizeStoryAndEpisodeColumnsAria"),className:"min-w-[6px] w-[6px] cursor-col-resize bg-[#2a2e35] hover:bg-primary/25 border-x border-white/5 flex items-center justify-center group shrink-0 z-10",onPointerDown:Lg,children:s.jsx("span",{className:"w-0.5 h-14 roun
790ded-full bg-white/15 group-hover:bg-primary/70 transition-colors","aria-hidden":!0})}),s.jsxs("section",{className:"relative min-w-0 flex flex-col overflow-hidden bg-[#15181c]","data-tour":"gl-episode-board",children:[s.jsxs("div",{className:"shrink-0 flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between px-2 sm:px-3 py-2 border-b border-[#2a2e35] min-w-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[s.jsx("span",{className:"material-symbols-outlined text-primary text-lg shrink-0","aria-hidden":!0,children:"auto_awesome"}),s.jsx("h3",{className:"text-slate-100 font-bold text-sm truncate",children:n("page.storyflow.episodeBoardTitle")})]}),s.jsxs("p",{className:"text-[10px] text-slate-500 mt-0.5 line-clamp-2 sm:truncate",children:[s.jsxs("span",{className:"text-slate-500",children:[n("page.storyflow.episodeBoardSubtitlePrefix")," "]}),s.jsx("span",{className:"text-primary font-bold tabular-nums",children:r1})]})]}),s.jsx("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 shrink-0 justify-end sm:justify-start",children:s.jsxs("button",{type:"button",onClick:pd,className:"flex items-center gap-1 px-2 py-1.5 sm:px-2.5 rounded-lg border border-white/15 bg-white/5 text-[9px] sm:text-[10px] font-bold text-slate-300 hover:bg-white/10 transition-colors",title:n("page.storyflow.optimizeSeasonTitle"),children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"tune"}),n("page.storyflow.optimizeButton")]})})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto custom-scrollbar px-3 py-3",children:s.jsxs("div",{className:"flex flex-col gap-0",children:[P.map((e,o)=>{var _,C,R;const l=String(o+1).padStart(2,"0"),d=Kt===o,m=_e===o,y=We(typeof e.durationMin=="number"&&e.durationMin>0?Math.round(e.durationMin*60):te),h=typeof e.sceneCount=="number"&&e.sceneCount>0?Math.round(e.sceneCount):Ut(y),b=zt(Rt(e)||"").scriptBody,{count:w,lastMax:g}=Fn(b),A=Math.max(w,g),j=Xe?sa(Rt(e)||""):h>0&&A>=h,B=e.attribution.withBloomBot?n("page.storyflow.byWithBloomBot",{name:e.attribution.userName}):n("page.storyflow.byAuthorOnly",{name:e.attribution.userName});return s.jsxs("div",{className:"flex gap-3 shrink-0",children:[s.jsxs("button",{type:"button",onClick:()=>dd(o),className:"flex flex-col items-center w-11 shrink-0 cursor-pointer group/rail",children:[o>0&&s.jsx("div",{className:"w-px h-2 bg-white/15 shrink-0","aria-hidden":!0}),s.jsx("div",{className:`relative z-10 flex items-center justify-center w-9 h-9 rounded-full border-2 text-[10px] font-bold tabular-nums transition-all ${d?"border-primary bg-primary/15 text-primary shadow-[0_0_14px_rgba(163,230,53,0.45)]":"border-white/20 bg-[#1e2226] text-slate-500 group-hover/rail:border-white/35"}`,children:l}),o<P.length-1&&s.jsx("div",{className:"w-px flex-1 min-h-[16px] bg-white/15 shrink-0","aria-hidden":!0})]}),s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>dd(o),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),dd(o))},className:`flex-1 min-w-0 rounded-xl p-3 mb-3 text-left cursor-pointer transition-colors ${d?"border-2 border-primary bg-[#1a1f24] shadow-[0_0_20px_rgba(163,230,53,0.12)]":"border border-white/10 bg-[#1e2226] hover:border-white/18"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-wrap",children:[d&&s.jsx("span",{className:"material-symbols-outlined text-primary text-base shrink-0","aria-hidden":!0,children:"wand_stars"}),s.jsx("span",{className:"text-[12px] font-bold text-slate-100 truncate",children:Ie(e.title,o+1)}),s.jsx("span",{className:"text-[9px] text-slate-500 shrink-0",children:B})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 text-slate-500",children:[j?s.jsx("span",{className:"rounded-md border border-primary/60 bg-primary px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-black",children:n("page.storyflow.completed")}):null,s.jsx("button",{type:"button",onClick:T=>T.stopPropagation(),className:"p-1 rounded hover:bg-white/10","aria-label":n("page.storyflow.reorderAria"),children:s.jsx("span",{className:"material-symbols-outlined text-base",children:"drag_indicator"})}),s.jsx("button",{type:"button",onClick:T=>T.stopPropagation(),className:"p-1 rounded hover:bg-white/10","aria-label":n("page.storyflow.moreAria"),children:s.jsx("span",{className:"material-symbols-outlined text-base",children:"more_vert"})})]})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1 min-h-[22px]",children:[m&&s.jsx("p",{className:"text-[9px] font-bold text-primary uppercase tracking-widest",children:n("page.storyflow.editingNow")}),d&&s.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),(e.scriptStage||"")==="completed"?Kg(o):fm(o)},className:"ml-auto text-[9px] font-bold text-primary uppercase tracking-wide px-2 py-0.5 rounded-md border border-primary/40 hover:bg-primary/10",children:(e.scriptStage||"")==="completed"?n("page.storyflow.completed"):n("page.storyflow.edit")})]}),s.jsx("p",{className:`mt-1 text-[10px] text-slate-400 leading-relaxed ${d?"italic":""}`,children:e.summary||"â"}),(_=e.characterRefs)!=null&&_.length||(C=e.scenes)!=null&&C.length||(
790R=e.props)!=null&&R.length?s.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 relative isolate",children:[e.characterRefs&&e.characterRefs.length>0&&s.jsxs("div",{className:"flex items-start gap-1.5 w-full min-w-0",children:[s.jsx("span",{className:"text-[9px] text-slate-500 w-8 shrink-0 pt-2 leading-none",children:n("page.storyflow.charsShort")}),s.jsx("div",{className:"flex flex-1 min-w-0 flex-nowrap gap-1.5 items-start justify-start overflow-x-auto custom-scrollbar pt-2 pb-1 -mt-1",children:e.characterRefs.slice(0,6).map((T,M)=>{var q;const W=((q=T.imgUrl)==null?void 0:q.trim())||"";return s.jsxs("div",{className:"relative z-0 group shrink-0 flex flex-col items-center max-w-full group-hover:z-30","aria-label":T.name,role:"group",children:[s.jsx("div",{className:"rounded-full bg-slate-600/40 border border-slate-500/50 overflow-hidden flex items-center justify-center origin-center transition-transform duration-150 ease-out group-hover:scale-[1.2] group-hover:-translate-y-0.5",style:{width:26,height:26},children:W?s.jsx("img",{src:W,alt:"",className:"w-full h-full object-cover",width:26,height:26}):s.jsx("span",{className:"text-slate-200 text-[10px] font-bold",children:$y(T.name)})}),s.jsx("span",{className:"text-[9px] text-slate-300 whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity duration-75 pointer-events-none mt-0.5 max-w-[64px] truncate text-center",style:{textShadow:"0 1px 2px rgba(0,0,0,0.9)"},"aria-hidden":!0,children:T.name})]},`${T.name}-${M}`)})})]}),e.scenes&&e.scenes.length>0&&s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[s.jsx("span",{className:"text-[9px] text-slate-500 w-8 shrink-0",children:n("page.storyflow.scenesShort")}),s.jsx("div",{className:"flex flex-wrap gap-1 min-w-0",children:e.scenes.slice(0,4).map(T=>s.jsx("span",{className:"rounded px-1.5 py-0.5 text-[10px] font-medium bg-amber-500/20 text-amber-200 border border-amber-500/30 truncate max-w-[72px]",title:T,children:T},T))})]}),e.props&&e.props.length>0&&s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[s.jsx("span",{className:"text-[9px] text-slate-500 w-8 shrink-0",children:n("page.storyflow.propsShort")}),s.jsx("div",{className:"flex flex-wrap gap-1 min-w-0",children:e.props.slice(0,4).map(T=>s.jsx("span",{className:"rounded px-1.5 py-0.5 text-[10px] font-medium bg-violet-500/20 text-violet-200 border border-violet-500/30 truncate max-w-[72px]",title:T,children:T},T))})]})]}):null,e.pipelineStatus&&s.jsxs("div",{className:"mt-2 flex items-center gap-1",children:[e.pipelineStatus.storyboard!=null&&s.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded text-slate-400",title:e.pipelineStatus.storyboard==="complete"?n("page.storyflow.storyboardComplete"):n("page.storyflow.storyboardPending"),children:s.jsx("span",{className:"material-symbols-outlined text-base",children:e.pipelineStatus.storyboard==="complete"?"check_circle":"schedule"})}),e.pipelineStatus.video!=null&&s.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded text-slate-400",title:e.pipelineStatus.video==="complete"?n("page.storyflow.videoComplete"):n("page.storyflow.videoPending"),children:s.jsx("span",{className:"material-symbols-outlined text-base",children:e.pipelineStatus.video==="complete"?"check_circle":"movie"})}),e.pipelineStatus.review!=null&&s.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded text-slate-400",title:e.pipelineStatus.review==="ready"?n("page.storyflow.readyForReview"):n("page.storyflow.reviewPending"),children:s.jsx("span",{className:"material-symbols-outlined text-base",children:e.pipelineStatus.review==="ready"?"rate_review":"schedule"})})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[9px] text-slate-500",children:[e.durationMin!=null&&s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"schedule"}),e.durationMin,"m"]}),e.sceneCount!=null&&s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"movie"}),n("page.storyflow.sceneCountWithNumber",{count:e.sceneCount})]})]}),a&&s.jsxs("button",{type:"button",onClick:T=>{T.stopPropagation();const M=Rt(e).trim();if(!M){H.warning(n("page.storyflow.goToWorkflowNeedsScript"));return}Ao({bypassWarnings:!0,episodeIndex:o,scriptOverride:M})},className:"text-[9px] font-bold text-primary hover:underline inline-flex items-center gap-0.5",title:n("page.storyflow.createWorkflowForEpisodeTitle"),children:[n("page.storyflow.createWorkflowButton"),s.jsx("span",{className:"material-symbols-outlined text-sm",children:"arrow_forward"})]})]})]})]},e.id)}),s.jsxs("div",{className:"flex gap-3 shrink-0 pt-1",children:[s.jsxs("div",{className:"flex flex-col items-center w-11 shrink-0",children:[s.jsx("div",{className:"w-px h-2 bg-white/15 shrink-0","aria-hidden":!0}),s.jsx("button",{type:"button",onClick:ud,className:"flex items-center justify-center w-9 h-9 rounded-full border-2 border-dashed border-white/25 text-slate-500 hover:border-primary/50 hover:text-primary transition-colors","aria-label":n("page.storyflow.addEpisodeAria"),children:s.jsx("span",{className:"material-symbols-outlined text-lg",children:"add"})})]}),s.jsx("button",{type:"button",onClick:ud,className:"flex-1 min-h-[36px] rounded-xl border border-dashed border-white/10 flex items-center px-3 text-[10px] text-slate-500 hover:border-primary/35 hover:text-slate-400 text-left transition-colors",children:n("page.storyflow.addEpisodeToSeason")})]})]})}),Sx?s.jsx("div",{className:"absolute inset-0 z-20 bg-[#121416]/85 backdrop-blur-[1px] flex items-center justify-center p-4 pointer-events-none",children:s.jsx("div",{className:"w-full max-w-sm rounded-xl border border-white/12 bg-[#1e2226] p-4 text-center pointer-events-auto",children:Gt==="assets"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-[10px] uppercase tracking-wider text-slate-500 font-semibold",children:n("page.storyflow.step3")}),s.jsx("h4",{className:"mt-1 text-sm font-bold text-slate-100",children:n("page.storyflow.episodeListBreakdown")}),s.jsxs("p",{className:"mt-2 text-[11px] text-slate-400",children:[n("page.storyflow.step3BreakdownBodyPrefix")," ",s.jsx("span",{className:"text-slate-300",children:n("page.storyflow.step3BreakdownBodyEmphasis")})," ",n("page.storyflow.step3BreakdownBodyMid")," ",s.jsx("span",{className:"text-slate-300",children:n("page.storyflow.step4AssetLibrary")}),n("page.storyflow.step3BreakdownBodySuffix")]}),s.jsxs("button",{type:"button",onClick:()=>dm("assets"),className:"mt-3 inline-flex items-center gap-1.5 rounded-lg border border-primary/35 bg-primary/15 px-3 py-1.5 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"inventory_2"}),n("page.storyflow.continueToStep4AssetLibrary")]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-[10px] uppercase tracking-wider text-slate-500 font-semibold",children:n("page.storyflow.step3")}),s.jsx("h4",{className:"mt-1 text-sm font-bold text-slate-100",children:n("page.storyflow.episodeBoardPlanning")}),s.jsx("p",{className:"mt-2 text-[11px] text-slate-400",children:n("page.storyflow.useBloomBotDraftEpisodes")}),s.jsxs("button",{type:"button",onClick:()=>dm("episode_board"),className:"mt-3 inline-flex items-center gap-1.5 rounded-lg border border-primary/35 bg-primary/15 px-3 py-1.5 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"auto_awesome"}),n("page.storyflow.askBloomBotEpisodeFlow")]})]})})}):null]})]}):null]}),s.jsx("input",{ref:Vp,type:"file",accept:"image/*,video/*,.txt,.md,text/plain,.docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document",className:"sr-only pointer-events-none fixed h-px w-px opacity-0","aria-hidden":!0,tabIndex:-1,onChange:$g}),E&&typeof document<"u"?Ps.createPortal(s.jsxs(s.Fragment,{children:[s.jsx(Rv,{kind:E.kind,name:E.name,draft:{description:L.description,imagePrompt:L.imagePrompt,imagePromptDirty:L.imagePromptDirty,conceptUrl:L.conceptUrl,conceptRefImage:L.conceptRefImage,designUrl:L.designUrl,imageModelId:L.imageModelId||Hr,approvedGender:L.approvedGender,characterConfirmed:L.characterConfirmed},onDraftChange:e=>lr(o=>({...o,...e})),previewUrl:Bi,generating:_c||Ic,errorText:pg||ug,mjVariants:km,sparks:Tv(L.imageModelId||Hr),t:n,libraryT:n,onClose:()=>js({close:!0}),onGenerate:()=>{String(L.imageModelId||Hr||"").trim().includes("midjourney")?Nm():Em()},onUploadToProjectLibrary:()=>{mx()},onUploadToApprovedLibrary:()=>{fx()},onOpenMjPicker:e=>
790{e&&ho({top:e.top,left:e.left,width:e.width,height:e.height}),vi("concept"),Ci(km),kn(!0)},onOpenPreview:e=>bx(e),onUploadDesign:e=>hx(e),onUploadRef:e=>gx(e),onRebuildImagePrompt:()=>px(),generateDisabled:!t||(na(L.imageModelId||Hr)?!String(L.imagePrompt||"").trim():!String(L.description||"").trim()),libraryBusy:Ni,uploadBusy:kg,projectUploaded:Dc,approvedUploaded:vg,showApprovedUpload:E.kind==="CHARACTERS"&&Oa}),s.jsx(c.Suspense,{fallback:null,children:s.jsx(rC,{elevatedZ:!0,isOpen:bg,anchorRect:wg,aspectRatio:Fc==="concept"?yx:"16:9",variants:Sg,currentSelection:Fc==="concept"?L.conceptUrl:L.designUrl,onSelect:e=>{if(Fc==="concept"){xx(e);return}if(!E)return;const o=Ve(E.kind,E.kind==="CHARACTERS"?E.characterId:void 0,E.name);(async()=>{const l=await Kr(e,"design");lr(d=>({...d,designUrl:l})),rs(d=>{var y,h,b,w,g,A;const m={...d,[o]:{...d[o],description:L.description.trim()||((y=d[o])==null?void 0:y.description),generationPath:L.generationPath,styleStrategy:L.styleStrategy,characterStyleId:L.characterStyleId||void 0,characterStyleCustomPrompt:L.characterStyleCustomPrompt||void 0,conceptUrl:L.conceptUrl.trim()||((h=d[o])==null?void 0:h.conceptUrl),conceptRefImage:((b=L.conceptRefImage)==null?void 0:b.trim())||((w=d[o])==null?void 0:w.conceptRefImage),designUrl:l,conceptHistoryUrls:(g=d[o])==null?void 0:g.conceptHistoryUrls,designHistoryUrls:cs((A=d[o])==null?void 0:A.designHistoryUrls,[l])}};return queueMicrotask(()=>{try{Ze.current({silent:!0,workspaceAssetMedia:m})}catch{}}),m}),kn(!1),ho(null)})()},onClose:()=>{kn(!1),ho(null),Ci([]),vi("concept")}})})]}),document.body):null,Op&&typeof document<"u"?Ps.createPortal(s.jsx("div",{className:"fixed inset-0 z-[10030] flex items-center justify-center bg-black/75 p-4",role:"presentation",onMouseDown:e=>{e.target===e.currentTarget&&Ua("")},children:s.jsxs("div",{className:"relative w-full max-w-6xl rounded-xl border border-white/15 bg-[#0f1114] p-3 shadow-2xl",role:"dialog","aria-modal":"true","aria-label":n("page.storyflow.imagePreviewAria"),onMouseDown:e=>e.stopPropagation(),children:[s.jsx("button",{type:"button",onClick:()=>Ua(""),className:"absolute right-2 top-2 z-10 rounded-lg bg-black/55 p-1.5 text-slate-300 hover:text-white hover:bg-black/75 transition-colors","aria-label":n("page.storyflow.closePreviewAria"),children:s.jsx("span",{className:"material-symbols-outlined text-lg",children:"close"})}),s.jsx("div",{className:"flex max-h-[82vh] items-center justify-center overflow-hidden rounded-lg bg-black",children:s.jsx("img",{src:Op,alt:"",className:"max-h-[82vh] w-auto max-w-full object-contain"})})]})}),document.body):null,oe&&Ps.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[9998] pointer-events-none","aria-hidden":!0}),s.jsxs("div",{className:"fixed z-[9999] pointer-events-none overflow-visible",style:{left:Fr.left-Dn,top:Fr.top-Dn,width:Fr.width+Dn*2,height:Fr.height+Dn*2},children:[s.jsxs("div",{ref:ap,className:`pointer-events-none absolute inset-0 z-0 transition-opacity duration-300 ease-in-out ${oe==="episode"||Pt==null?"opacity-100":"opacity-0"}`,"aria-hidden":!0,children:[s.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[18px]",style:{background:"radial-gradient(ellipse 76% 72% at 50% 52%, rgba(163,230,53,0.4) 0%, rgba(163,230,53,0.2) 38%, rgba(163,230,53,0.08) 62%, transparent 76%)",filter:"blur(14px)"},"aria-hidden":!0}),s.jsx("div",{className:"pointer-events-none absolute rounded-xl bg-transparent",style:{left:Dn,top:Dn,width:Fr.width,height:Fr.height,boxShadow:"0 0 16px rgba(163,230,53,0.62), 0 0 28px rgba(163,230,53,0.38), 0 0 44px rgba(163,230,53,0.16)"},"aria-hidden":!0})]}),s.jsxs("div",{className:"relative z-10 flex flex-col h-full pointer-events-auto overflow-hidden rounded-xl border-0 bg-[#1e2226] shadow-[0_20px_48px_rgba(0,0,0,0.45)] ring-0 outline-none",role:"dialog","aria-label":n(oe==="story-arc"?"page.storyflow.storyOutlineExpandedAria":oe==="episode"?"page.storyflow.episodeOutlineExpandedAria":"page.storyflow.worldDimensionExpandedAria"),style:{margin:Dn,width:Fr.width,height:Fr.height},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 p-3 border-b border-white/10 shrink-0 cursor-grab active:cursor-grabbing",onPointerDown:e=>{e.target.closest("button")||(e.preventDefault(),ai.current={x:e.clientX,y:e.clientY,left:Fr.left,top:Fr.top},np(!0))},children:[s.jsx("h4",{className:"text-slate-100 font-bold text-sm min-w-0 truncate pr-2",children:oe==="story-arc"?n("page.storyflow.globalStoryArcFullView"):oe==="episode"?(()=>{const e=_e??0,o=P[e];return o?`${ne(e+1)}: ${Ie(o.title,e+1)}`:n("page.storyflow.episodeOutline")})():er.some(e=>e.id===oe)?Pe(oe):n("page.storyflow.tabWorldBible")}),s.jsxs("div",{className:"flex items-center shrink-0",style:{gap:10},children:[oe==="episode"&&Vr==="completed"?s.jsxs("button",{type:"button",onClick:()=>{xa("edit"),fs("docked"),or({type:"episode_outline",episodeIndex:_e??0}),qt((at[_e??0]??[]).length)},onPointerDown:e=>e.stopPropagation(),className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",title:n("page.storyflow.reEdit"),"aria-label":n("page.storyflow.reEdit"),children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"edit"}),n("page.storyflow.reEdit")]}):s.jsxs(s.Fragment,{children:[oe==="episode"&&Vr==="edit"?s.jsxs("button",{type:"button",onClick:Qg,onPointerDown:e=>e.stopPropagation(),disabled:ze||xt,className:"inline-flex items-center gap-1 rounded-md border border-rose-300/35 bg-rose-400/10 px-2 py-1 text-[11px] font-semibold text-rose-200 hover:bg-rose-400/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:n("page.storyflow.resetEpisodeScript"),"aria-label":n("page.storyflow.resetEpisodeScript"),children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"autorenew"}),n("page.storyflow.resetButton")]}):null,oe==="episode"?s.jsxs("button",{type:"button",onClick:Gg,onPointerDown:e=>e.stopPropagation(),className:"inline-flex items-center gap-1 rounded-md border border-white/20 bg-white/5 px-2 py-1 text-[11px] font-semibold text-slate-100 hover:bg-white/10 transition-colors",title:n("page.storyflow.copyAllContent"),"aria-label":n("page.storyflow.copyAllContent"),children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"content_copy"}),n("page.storyflow.copyAllButton")]}
790):null,s.jsx("div",{ref:ac,className:"flex items-center justify-center size-9 rounded-lg border border-transparent","aria-hidden":!hm,children:hm?s.jsx("button",{type:"button",onClick:Yg,onPointerDown:e=>e.stopPropagation(),className:"flex items-center justify-center size-8 rounded-lg bg-primary/10 border border-primary/25 hover:bg-primary/20 transition-colors",title:n("page.storyflow.editWithBloomBot"),"aria-label":n("page.storyflow.editWithBloomBot"),children:s.jsx(of,{className:"size-5 shrink-0"})}):s.jsx("span",{className:"size-8"})})]}),s.jsx("button",{type:"button",onClick:Rn,onPointerDown:e=>e.stopPropagation(),className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/10","aria-label":n("page.storyflow.closeAria"),children:s.jsx("span",{className:"material-symbols-outlined text-lg",children:"close"})})]})]}),s.jsx("div",{className:`flex-1 p-4 custom-scrollbar flex flex-col gap-4 min-h-0 ${oe==="episode"&&Vr==="edit"?"overflow-hidden":"overflow-y-auto"}`,children:oe==="story-arc"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"shrink-0",children:[s.jsx("span",{className:"text-[10px] font-bold text-primary uppercase tracking-wider",children:n("page.storyflow.loglineLabel")}),s.jsx("textarea",{className:"mt-1 block w-full min-h-[72px] p-2.5 rounded-lg bg-background-dark/50 border border-white/10 text-[13px] text-slate-300 placeholder:text-slate-500 leading-relaxed focus:ring-1 focus:ring-primary outline-none resize-y select-text cursor-text",placeholder:n("page.storyflow.storyArcLoglinePlaceholder"),value:U.logline,onChange:e=>{nr("logline"),Rr(o=>({...o,logline:e.target.value}))}})]}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[s.jsx("span",{className:"text-[10px] font-bold text-primary uppercase tracking-wider",children:n("page.storyflow.synopsisLabel")}),s.jsx("textarea",{className:"mt-1 flex-1 min-h-[160px] w-full p-2.5 rounded-lg bg-background-dark/50 border border-white/10 text-[13px] text-slate-300 placeholder:text-slate-500 leading-relaxed whitespace-pre-wrap focus:ring-1 focus:ring-primary outline-none resize-y select-text cursor-text",placeholder:n("page.storyflow.storyArcSynopsisPlaceholder"),value:U.synopsis,onChange:e=>{nr("synopsis"),Rr(o=>({...o,synopsis:e.target.value}))}})]})]}):oe==="episode"?s.jsx("div",{className:"flex-1 min-h-0 flex flex-col gap-3",children:Vr==="edit"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex shrink-0 rounded-lg border border-white/10 bg-black/30 overflow-hidden lg:hidden",children:[s.jsx("button",{type:"button",onClick:()=>Lc("read"),className:`flex-1 px-2 py-2 text-[11px] font-semibold transition-colors ${Ka==="read"?"bg-primary/20 text-primary":"text-slate-400 hover:text-slate-200"}`,children:n("page.storyflow.episodeModalTabEpisodeDetails")}),s.jsx("button",{type:"button",onClick:()=>Lc("write"),className:`flex-1 border-l border-white/10 px-2 py-2 text-[11px] font-semibold transition-colors ${Ka==="write"?"bg-primary/20 text-primary":"text-slate-400 hover:text-slate-200"}`,children:n("page.storyflow.episodeModalTabBloomBot")})]}),s.jsxs("div",{className:"flex flex-1 min-h-0 flex-col gap-3 lg:flex-row lg:gap-4 lg:items-stretch",children:[s.jsxs("div",{className:`min-h-0 min-w-0 flex flex-col gap-3 overflow-y-auto custom-scrollbar lg:w-[42%] lg:max-w-[min(520px,46vw)] lg:flex-shrink-0 ${Ka==="read"?"flex-1":"hidden"} lg:flex`,children:[s.jsx("div",{className:"shrink-0 rounded-lg border border-primary/20 bg-primary/5 p-2",children:Xe?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.descriptiveScriptProgressTitle")}),s.jsx("p",{className:"mt-1 text-[10px] text-slate-300",children:n("page.storyflow.descriptiveScriptProgressHint")}),Ct?s.jsx("p",{className:"mt-2 text-[10px] font-semibold text-emerald-300",children:n("page.storyflow.descriptiveScriptReady")}):s.jsx("p",{className:"mt-2 text-[10px] text-slate-400",children:n("page.storyflow.descriptiveScriptDrafting")})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.progressSteps")}),s.jsx("p",{className:"mt-1 text-[10px] text-slate-300",children:n("page.storyflow.primaryGoalFinis
790hShots")}),s.jsxs("div",{className:"mt-2 rounded-md border border-white/10 bg-black/20 p-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"pointer-events-none absolute left-3 right-3 top-[11px] h-[2px] rounded-full bg-white/10"}),s.jsx("div",{className:"pointer-events-none absolute left-3 right-3 top-[11px] h-[2px] overflow-hidden rounded-full",children:s.jsx("span",{className:`block h-full w-1/3 bg-gradient-to-r from-transparent via-primary to-transparent ${In?"animate-[cbProgressScan_1.8s_linear_infinite]":"opacity-30"}`})}),s.jsx("div",{className:"grid grid-cols-4 gap-1",children:yd.map((e,o)=>{const l=o+1,d=l===dl&&In,m=l<dl||Ct;return s.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[s.jsxs("div",{className:`relative flex h-6 w-6 items-center justify-center rounded-full border text-[10px] font-bold ${m?"border-emerald-300/80 bg-emerald-300/20 text-emerald-200":d?"border-primary bg-primary/15 text-primary":"border-white/20 bg-black/30 text-slate-400"}`,children:[d?s.jsx("span",{className:"pointer-events-none absolute -inset-[2px] rounded-full border-2 border-transparent border-t-primary border-r-primary animate-[cbRingSpin_1.2s_linear_infinite]"}):null,l]}),s.jsx("span",{className:`text-[9px] leading-tight ${m?"text-emerald-300":d?"text-primary":"text-slate-400"}`,children:e.label})]},e.key)})})]}),In?s.jsxs("p",{className:"mt-2 text-[10px] text-primary",children:[n("page.storyflow.runningStepWithTotal",{current:dl,total:yd.length})," ",(Qm=yd[Math.max(0,dl-1)])==null?void 0:Qm.label]}):s.jsx("p",{className:"mt-2 text-[10px] text-slate-400",children:n("page.storyflow.startWritingHint")})]}),xt?s.jsxs("p",{className:"mt-1 inline-flex items-center gap-1 text-[10px] font-semibold text-primary",children:[s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),n("page.storyflow.autoWritingInProgress")]}):null,s.jsxs("div",{className:"mt-1.5 space-y-1 text-[10px] leading-relaxed",children:[xm.completedRanges.length>0?xm.completedRanges.map((e,o)=>s.jsx("p",{className:"text-emerald-300",children:n("page.storyflow.completedShotRange",{start:String(e.start).padStart(2,"0"),end:String(e.end).padStart(2,"0")})},`ep-progress-done-top-${o}`)):s.jsx("p",{className:"text-slate-400",children:n("page.storyflow.completedNoneYet")}),Ct?s.jsx("p",{className:"text-emerald-300",children:n("page.storyflow.allTargetShotsComplete")}):null,ex?s.jsx("p",{className:"text-amber-200",children:n("page.storyflow.pausedAtShotContinueHint",{current:Math.min(et.writtenShots,et.targetShots),target:et.targetShots})}):null]}),s.jsx("style",{children:` 791 @keyframes cbProgressScan { 792 0% { transform: translateX(-130%); } 793 100% { transform: translateX(320%); } 794 } 795 @keyframes cbRingSpin { 796 0% { transform: rotate(0deg); } 797 100% { transform: rotate(360deg); } 798 } 799 @keyframes cbCtaBreath { 800 0%, 100% { transform: scale(1); } 801 50% { transform: scale(1.06); } 802 } 803 `})]})}),s.jsxs("div",{className:"shrink-0",children:[s.jsx("span",{className:"text-[10px] font-bold text-primary uppercase tracking-wider",children:n("page.storyflow.episodeSummaryLocked")}),s.jsx("div",{className:"mt-1 max-h-[9rem] overflow-y-auto rounded-lg border border-white/10 bg-background-dark/50 p-2.5 text-[13px] text-slate-300 leading-relaxed whitespace-pre-wrap select-text cursor-text",children:(((Zm=P[_e??0])==null?void 0:Zm.summary)||"").trim()||n("page.storyflow.emptySummary")})]}),s.jsxs("div",{className:`flex flex-col gap-2 rounded-lg border border-white/10 bg-black/20 p-2 ${fo?"flex-1 min-h-0":"shrink-0"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Ha(e=>{const o=!e;return o&&!xi&&za(!1),o})},className:"inline-flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider text-primary hover:text-primary/85 transition-colors",title:n(fo?"page.storyflow.collapseDetailedScript":"page.storyflow.expandDetailedScript"),children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:fo?"expand_less":"expand_more"}
803),n("page.storyflow.detailedEpisodeScript")]}),fo?s.jsxs("button",{type:"button",onClick:()=>void Zg(),disabled:ze||xt||ii,className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[10px] font-semibold text-primary disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/20 transition-colors",title:n("page.storyflow.polishScriptWithTranscriptTitle"),children:[s.jsx("span",{className:`material-symbols-outlined text-xs ${ii?"animate-spin":""}`,children:ii?"progress_activity":"auto_fix_high"}),n("page.storyflow.polishScriptButton")]}):null]}),fo?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-2.5 py-2 text-[11px] text-slate-300 leading-relaxed",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[s.jsxs("span",{children:[n("page.storyflow.targetDuration")," ",s.jsx("span",{className:"font-semibold text-slate-100",children:et.durationText})]}),Xe?s.jsxs("span",{children:[n("page.storyflow.descriptiveScriptFormatLabel")," ",s.jsx("span",{className:"font-semibold text-slate-100",children:n("page.storyflow.descriptiveScriptFormatValue")})]}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:[n("page.storyflow.targetShots")," ",s.jsx("span",{className:"font-semibold text-slate-100",children:et.targetShots})]}),s.jsxs("span",{children:[n("page.storyflow.progress")," ",s.jsxs("span",{className:"font-semibold text-primary",children:[Math.min(et.writtenShots,et.targetShots)," / ",et.targetShots]})]})]})]}),s.jsx("p",{className:"mt-1 text-[10px] text-slate-400",children:n(Xe?"page.storyflow.descriptiveScriptPanelHint":"page.storyflow.bloomBotWritesInBatchesHint")})]}),Xe?s.jsx(Dh,{value:ll.scriptBody||jn||n("page.storyflow.episodeScriptPlaceholder"),readOnly:!0,maxHeightClass:"max-h-[min(36vh,420p
803x)] min-h-[180px]",testId:"storyflow-episode-script-panel"}):s.jsxs("div",{className:"flex-1 min-h-[180px] overflow-y-auto rounded-lg border border-white/10 bg-background-dark/50 p-2.5 text-[13px] text-slate-300 leading-relaxed whitespace-pre-wrap select-text cursor-text","data-testid":"storyflow-episode-script-panel",children:[jn&&!Pi?s.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[s.jsx("span",{"data-testid":"storyflow-draft-badge",className:"inline-flex items-center rounded border border-primary/35 bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-primary",children:n("page.storyflow.draftInProgressBadge")}),s.jsx("span",{className:"text-[10px] text-slate-500",children:n("page.storyflow.draftVisibleInPanelHint")})]}):null,ll.scriptBody||n(jn?"page.storyflow.draftBuildingHint":"page.storyflow.noDetailedScriptYetHint")]}),as.nextStep?s.jsxs("div",{className:"rounded-lg border border-amber-300/30 bg-amber-300/10 p-2 text-[11px] text-amber-100 leading-relaxed",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-amber-200",children:n("page.storyflow.nextStep")}),s.jsx("p",{className:"mt-0.5",children:as.nextStep})]}):null,as.ledger?s.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-2 text-[11px] text-slate-300 leading-relaxed",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1.5",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.hookType")}),s.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-slate-200",children:as.ledger.hookType||"â"})]}),s.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1.5",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.newSeeds")}),s.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-slate-200",children:as.ledger.newSeeds||"â"})]}),s.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1.5",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.pendingPayoffs")}),s.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-slate-200",children:as.ledger.pendingPayoffs||"â"})]}),s.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1.5",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.continuityNotes")}),s.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-slate-200",children:as.ledger.continuityNotes||"â"})]})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.editorPass")}),s.jsx("p",{className:`mt-0.5 font-semibold ${String(as.ledger.editorPass||"").toUpperCase()==="PASS"?"text-green-400":String(as.ledger.editorPass||"").toUpperCase()==="WARN"?"text-amber-400":"text-slate-300"}`,children:as.ledger.editorPass||"â"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.editorNotes")}),s.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-slate-300",children:as.ledger.editorNotes||"â"})]})]})]}):null,Eo.ready&&Ar?s.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-1.5 text-[10px] text-slate-300 leading-relaxed",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.episodeQualityRadar")}),s.jsx("span",{className:"text-[10px] font-semibold text-slate-200",children:n("page.storyflow.overallStars",{stars:Wy(Ar.overallStars)})})]}),s.jsx("p",{className:"mt-0.5 text-[10px] text-slate-500",children:n("page.storyflow.localAnalysisNoSparks")}),s.jsx("div",{className:"mt-1 grid grid-cols-2 gap-1",children:Ar.dimensions.map(e=>s.jsx("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:s.jsxs("div",{className:"flex items-center justify-between gap-1",children:[s.jsx("span",{className:"truncate text-slate-200",children:e.label}),s.jsx("span",{className:"font-semibold text-amber-200 shrink-0",children:Wy(e.stars)})]})},e.key))}),Ar.dimensions.some(e=>e.stars<4)?s.jsxs("p",{className:"mt-1 text-[10px] text-slate-400",children:[n("page.storyflow.needsPolish"),": ",Ar.dimensions.filter(e=>e.stars<4).map(e=>
803e.label).join(", ")]}):s.jsx("p",{className:"mt-1 text-[10px] text-emerald-300",children:n("page.storyflow.qaGatePassed")}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-end gap-2",children:[((le==null?void 0:le.scriptStage)||"drafting")==="qa_reported"&&((le==null?void 0:le.scriptQaDecision)??null)==null?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:sx,className:"inline-flex items-center gap-1 rounded-md border border-amber-300/35 bg-amber-300/10 px-2 py-1 text-[11px] font-semibold text-amber-200 hover:bg-amber-300/20 transition-colors",children:n("page.storyflow.needAdjustment")}),s.jsx("button",{type:"button",onClick:nx,className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:n("page.storyflow.looksGood")})]}):null,((le==null?void 0:le.scriptQaDecision)??null)==="needs_adjustment"&&((le==null?void 0:le.scriptStage)||"")==="adjusting"?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-amber-300/35 bg-amber-300/10 px-2 py-1 text-[11px] font-semibold text-amber-200",children:[s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),n("page.storyflow.adjusting")]}):null,((le==null?void 0:le.scriptQaDecision)??null)==="needs_adjustment"&&((le==null?void 0:le.scriptStage)||"")!=="completed"?s.jsx("button",{type:"button",onClick:wm,className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:n("page.storyflow.finalizeCurrentVersion")}):null,((le==null?void 0:le.scriptQaDecision)??null)==="looks_good"&&((le==null?void 0:le.scriptStage)||"")!=="completed"?s.jsx("button",{type:"button",onClick:wm,className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:n("page.storyflow.finalizeEpisode")}):null]})]}):null]}):s.jsx("p",{className:"text-[10px] text-slate-400",children:n("page.storyflow.detailedScriptCollapsedHint")})]})]}),s.jsx("div",{className:`min-h-0 min-w-0 flex flex-col flex-1 ${Ka==="write"?"flex":"hidden"} lg:flex lg:min-w-0`,children:s.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:s.jsxs("div",{className:"relative z-20 isolate flex min-h-0 flex-1 flex-col rounded-lg border border-white/10 bg-[#11161b] p-2 shadow-[0_-10px_20px_rgba(0,0,0,0.4)]",children:[s.jsxs("button",{type:"button",onClick:()=>za(e=>{const o=!e;return o&&!xi&&fo&&Ha(!1),o}),className:"mb-2 inline-flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-300 hover:text-slate-100 transition-colors",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:Mc?"expand_less":"expand_more"}),n("page.storyflow.episodeBloomBot")]}),Mc||xi?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-2 shrink-0",children:[s.jsxs("button",{type:"button",onClick:()=>$p(e=>!e),className:"inline-flex w-full items-center justify-between gap-2 rounded-md border border-white/10 bg-black/25 px-2 py-1.5 text-left text-[10px] font-semibold text-slate-300 hover:bg-white/10 transition-colors","aria-expanded":Oc,children:[s.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0",children:[s.jsx("span",{className:"material-symbols-outlined text-sm text-slate-400 shrink-0","aria-hidden":!0,children:"info"}),s.jsx("span",{className:"truncate",children:n("page.storyflow.episodeModalQuotaBillingToggle")})]}),s.jsx("span",{className:"material-symbols-outlined text-sm text-slate-500 shrink-0","aria-hidden":!0,children:Oc?"expand_less":"expand_more"})]}),Oc?s.jsxs("div",{className:"mt-1.5 rounded-md border border-emerald-400/25 bg-emerald-400/8 p-2",children:[s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider text-emerald-300",children:n("page.storyflow.episodeScriptFreeTokenQuotaMonthly")}),s.jsx("p",{className:"mt-1 text-[10px] text-slate-200",children:n("page.storyflow.episodeScriptTokenPlanQuota")}),s.jsx("p",{className:"mt-1 text-[10px] text-slate-400 leading-relaxed",children:n("page.storyflow.templateFreeBillingHint")})]}):null]}),s.jsxs("div",{ref:Yp,className:"min-h-0 flex-1 overflow-y-auto custom-scrollbar space-y-2 rounded-lg border border-white/10 bg-black/20 p-2",children:[va.length===0&&!(Sn&&ze)?s.jsx("p",{className:"text-[10px] text-slate-500 px-0.5 leading-relaxed",children:n("page.storyflow.separateEpisodeChatHint")}):null,va.map((e,o)=>{var d;const l=e.role==="assistant"&&((d=e.rawAssistantReply)==null?void 0:d.trim())||e.text;return s.jsx("div",{className:`flex shrink-0 flex-col gap-1 ${e.role==="user"?"items-end":"items-start"}`,children:s.jsxs("div",{className:`relative max-w-[95%] rounded-md px-2 py-1.5 ${e.role==="user"?"rounded-tr-sm border border-primary/30 bg-primary/15":"rounded-tl-sm border border-white/10 bg-black/35"} ${e.text.trim()?"pr-7":""}`,children:[e.text.trim()?rm(e.text,e.role,`select-text whitespace-pre-wrap break-words text-[11px] leading-relaxed ${e.role==="user"?"text-slate-100":"text-slate-300"}`):null,l.trim()?s.jsx("button",{type:"button",onClick:async m=>{m.stopPropagation();try{await navigator.clipboard.writeText(l),H.success(n("page.storyflow.copiedTitle"),n("page.storyflow.contentCopiedToClipboardBody"))}catch{H.warning(n("page.storyflow.copyFailedTitle"),n("page.storyflow.copyToClipboardFailedBody"))}},className:"absolute right-1 top-1 z-10 rounded p-0.5 opacity-70 transition-opacity hover:bg-white/10 hover:opacity-100 text-slate-300",title:n("page.storyflow.copyAction"),"aria-label":n("page.storyflow.copyAction"),children:s.jsx("svg",{className:"h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24","aria-hidden":!0,
803children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}):null]})},o)}),Sn&&ze?s.jsxs("div",{className:"rounded-md border border-primary/25 bg-black/35 p-2 text-[11px] leading-relaxed text-slate-200","aria-live":"polite","aria-busy":"true",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary",children:n("page.storyflow.sent")}),s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-primary",children:[s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),n("page.storyflow.statusThinking")]})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-slate-300",children:Sn})]}):null,qu.trim()&&ze?s.jsxs("div",{className:"rounded-md border border-primary/25 bg-black/35 p-2 text-[11px] leading-relaxed text-slate-200","aria-live":"polite","aria-busy":"true",children:[s.jsxs("div",{className:"mb-1 inline-flex items-center gap-1 text-[10px] font-semibold text-primary",children:[s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),n("page.storyflow.statusThinking")]}),s.jsxs("p",{className:"whitespace-pre-wrap text-slate-300",children:[qu,s.jsx("span",{className:"ml-0.5 inline-block h-3 w-[1px] animate-pulse bg-primary/80 align-middle"})]})]}):null]})]}):xi?null:s.jsx("p",{className:"text-[10px] text-slate-500",children:n("page.storyflow.bloomBotPanelCollapsedHint")}),!Mc&&!xi?s.jsx("div",{className:"min-h-0 flex-1","aria-hidden":!0}):null,s.jsxs("div",{className:"mt-auto shrink-0 border-t border-white/10 pt-2",children:[s.jsx("textarea",{className:"block h-20 w-full resize-none rounded-md border border-white/10 bg-[#0f1418] p-1.5 text-[12px] text-slate-200 placeholder:text-slate-500 outline-none focus:ring-0",value:po,onChange:e=>Wa(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),ym())},placeholder:n("page.storyflow.askBlueprintPlaceholder"),"aria-label":n("page.storyflow.detailedScriptDirectionAria")}),s.jsxs("div",{className:"mt-1 flex min-w-0 items-start justify-between gap-2",children:[s.jsx("p",{className:`min-w-0 flex-1 text-[10px] leading-snug ${Ct?"text-emerald-300":"text-amber-200"}`,children:tx}),s.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[gm?s.jsxs("button",{type:"button",onClick:Vg,disabled:ze||xt,title:n("page.storyflow.continueAutoChunkCapTooltip"),className:"inline-flex items-center gap-1 rounded-md border border-amber-400/30 bg-amber-400/10 px-2.5 py-1 text-[11px] font-semibold text-amber-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-amber-400/20 transition-colors",children:[ze?s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm leading-none",children:"progress_activity"}):s.jsx(Gy,{className:"size-5 shrink-0 text-current opacity-95"}),n("page.storyflow.nextWithTokenCap")]}):null,Ct?null:xt?s.jsxs("button",{type:"button",onClick:Jg,className:"inline-flex items-center gap-1 rounded-md border border-rose-300/35 bg-rose-400/10 px-2 py-1 text-[11px] font-semibold text-rose-200 hover:bg-rose-400/20 transition-colors",children:[s.jsx("span",{className:"material-symbols-outlined text-sm",children:"stop"}),n("page.storyflow.stop")]}):s.jsxs("button",{type:"button",onClick:()=>void Xg(),disabled:ze,title:n("page.storyflow.continueAutoChunkCapTooltip"),className:`inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-[11px] font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${Ct?"border-primary/35 bg-primary/15 text-primary hover:bg-primary/20":"border-amber-300/45 bg-amber-300/12 text-amber-200 hover:bg-amber-300/20 animate-[cbCtaBreath_1.6s_ease-in-out_infinite]"}`,children:[ze?s.jsx("span",{className:"material-symbols-outlined animate-spin text-sm leading-none",children:"progress_activity"}):s.jsx(Gy,{className:"size-5 shrink-0 text-current opacity-95"}),n(Ct?"page.storyflow.autoWithTokenCap":"page.storyflow.continueWithTokenCap")]}),s.jsxs("button",{type:"button",onClick:ym,disabled:ze||xt||!po.trim(),title:n("page.storyflow.sendDraftTokenEstimateTooltip"),className:"inline-flex items-center gap-1 rounded-md border border-primary/30 bg-primary/15 px-2.5 py-1 text-[11px] font-semibold text-primary disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/20 transition-colors",children:[s.jsx("span",{className:`material-symbols-outlined text-sm ${ze?"animate-spin":""}`,children:ze?"progress_activity":"send"}),n("page.storyflow.sendWithTokens",{tokens:tm})]})]}),s.jsxs("p",{className:`max-w-[11rem] text-right text-[9px] leading-tight ${ba==="synced"?"text-emerald-300":ba==="pending"?"text-amber-300":"text-rose-300"}`,children:[n("page.storyflow.syncPrefix"),":"," ",n(ba==="synced"?"page.storyflow.synced":ba==="pending"?"page.storyflow.pending":"page.storyflow.needsAttention")]})]})]}),s.jsxs("div",{className:"mt-1 min-w-0 text-[10px] text-slate-500 leading-relaxed",children:[s.jsx("p",{children:n("page.storyflow.blueprintToScenePacksHint")}),Ct?s.jsx("p",{className:"text-emerald-300",children:n("page.storyflow.episodeShotsCompleteGoToWorkflowHint")}):null,Ct&&fd?s.jsx("p",{className:"text-amber-300",children:n("page.storyflow.characterImagesMissingHint")}
803):null,s.jsx("p",{className:"text-[10px] text-zinc-500",children:n("page.storyflow.chatTurnsTokenBillingHint")}),s.jsx("p",{className:"text-[10px] text-zinc-500",children:n("page.storyflow.currentPromptEstimateWithTokens",{tokens:tm})}),s.jsx("p",{className:"mt-0.5 block min-w-0 max-w-full overflow-x-auto whitespace-nowrap text-[9px] text-zinc-600 leading-normal custom-scrollbar",children:n("page.storyflow.episodeModalTokenSendVsContinueHint")})]}),((le==null?void 0:le.scriptStage)||"")==="completed"||Ct&&fd?s.jsxs("div",{className:"mt-2 flex w-full min-w-0 flex-wrap items-center justify-end gap-2 border-t border-white/10 pt-2",children:[((le==null?void 0:le.scriptStage)||"")==="completed"?s.jsx("button",{type:"button",onClick:ox,className:"inline-flex items-center gap-1 rounded-md border border-primary/35 bg-primary/15 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20 transition-colors",children:n("page.storyflow.doneEditing")}):null,Ct&&fd?s.jsx("button",{type:"button",onClick:qg,className:"inline-flex items-center gap-1 rounded-md border border-amber-300/35 bg-amber-300/10 px-2 py-1 text-[11px] font-semibold text-amber-200 hover:bg-amber-300/20 transition-colors",children:n("page.storyflow.goToAssetLibraryForCharacters")}):null]}):null]})]})})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"shrink-0",children:[s.jsx("span",{className:"text-[10px] font-bold text-primary uppercase tracking-wider",children:n("page.storyflow.episodeSummaryLocked")}),s.jsx("div",{className:"mt-1 max-h-[9rem] overflow-y-auto rounded-lg border border-white/10 bg-background-dark/50 p-2.5 text-[13px] text-slate-300 leading-relaxed whitespace-pre-wrap select-text cursor-text",children:(((ef=P[_e??0])==null?void 0:ef.summary)||"").trim()||n("page.storyflow.emptySummary")})]}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col gap-2",children:[s.jsx("span",{className:"text-[10px] font-bold text-primary uppercase tracking-wider",children:n("page.storyflow.finalDetailedEpisodeScript")}),s.jsx("div",{className:"flex-1 min-h-[240px] overflow-y-auto rounded-lg border border-white/10 bg-background-dark/50 p-3 text-[13px] text-slate-200 leading-relaxed whitespace-pre-wrap select-text cursor-text",children:An.scriptBody||n("page.storyflow.noDetailedScriptSavedYet")})]})]})}):s.jsx("div",{className:"flex-1 min-h-0 flex flex-col gap-2",children:s.jsx("textarea",{className:"flex-1 min-h-0 w-full p-2.5 rounded-lg bg-background-dark/50 border border-white/10 text-[13px] text-slate-300 placeholder:text-slate-500 leading-relaxed focus:ring-1 focus:ring-primary outline-none resize-none select-text cursor-text",placeholder:n("page.storyflow.worldBiblePasteHintPlaceholder"),value:pe[oe],onChange:e=>{(oe==="geography"||oe==="timeline"||oe==="rules"||oe==="culture"||oe==="coreConflict")&&nr(oe),Us(o=>({...o,[oe]:e.target.value}))}})})}),s.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",style:{background:"linear-gradient(135deg, transparent 50%, rgba(255,255,255,0.1) 50%)"},onPointerDown:e=>{e.preventDefault(),e.stopPropagation(),li.current={x:e.clientX,y:e.clientY,w:Fr.width,h:Fr.height},ip(!0)},"aria-label":n("page.storyflow.resizeAria")})]})]})]}),document.body),Zh&&Ps.createPortal(s.jsx("div",{className:"fixed inset-0 z-[10060] flex items-center justify-center p-4 bg-black/65 backdrop-blur-[2px] pointer-events-auto",role:"presentation",onMouseDown:e=>{e.target===e.currentTarget&&ka(!1)},children:s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cb-consistency-rewrite-title",className:"w-full max-w-md rounded-2xl border border-white/12 bg-[#1e2226] shadow-[0_24px_64px_rgba(0,0,0,0.5)] p-5 sm:p-6 pointer-events-auto",onMouseDown:e=>e.stopPropagation(),children:(()=>{const e=Ts||Ur;return s.jsxs(s.Fragment,{children:[s.jsx("h2",{id:"cb-consistency-rewrite-title",className:"text-lg font-bold text-slate-100 tracking-tight",children:n("page.storyflow.consistencyRewriteConfirmTitle")}),s.jsx("p",{className:"mt-2 text-xs leading-relaxed text-slate-400",children:n("page.storyflow.consistencyRewriteConfirmBody")}),e?s.jsx("p",{className:"mt-3 rounded-lg border border-primary/30 bg-primary/10 px-3 py-2 text-xs leading-relaxed text-primary",children:n("page.storyflow.consistencyRewriteBusyBody")}
803):null,s.jsxs("div",{className:"mt-6 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",className:"px-3 py-2 rounded-lg text-xs font-semibold text-slate-400 hover:text-slate-200 hover:bg-white/5",onClick:()=>ka(!1),children:n("page.storyflow.consistencyRewriteConfirmCancel")}),s.jsx("button",{type:"button",className:"px-3 py-2 rounded-lg text-xs font-bold bg-primary text-background-dark hover:opacity-90 disabled:opacity-40 disabled:pointer-events-none",disabled:e,onClick:()=>void Hg(),children:n(e?"page.storyflow.consistencyRewriteBusyButton":"page.storyflow.consistencyRewriteConfirmAction")})]})]})})()})}),document.body),Sa!=null&&Ps.createPortal(s.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/65 backdrop-blur-[2px]",role:"presentation",onMouseDown:e=>{e.target===e.currentTarget&&Jn(null)},children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cb-create-workflow-title",className:"w-full max-w-md rounded-2xl border border-white/12 bg-[#1e2226] shadow-[0_24px_64px_rgba(0,0,0,0.5)] p-5 sm:p-6",onMouseDown:e=>e.stopPropagation(),children:[s.jsx("h2",{id:"cb-create-workflow-title",className:"text-lg font-bold text-slate-100 tracking-tight",children:n("page.storyflow.startProduction")}),s.jsx("p",{className:"mt-1 text-xs text-slate-500",children:(()=>{const e=Sa,o=e!=null?P[e]:null;return o?n("page.storyflow.newWorkflowProjectForEpisode",{episode:e+1,title:Ie(o.title,e+1)}):n("page.storyflow.newWorkflowProject")})()}),s.jsx("p",{className:"mt-3 text-[11px] text-slate-400 leading-relaxed",children:n("page.storyflow.preProductionChecklistHint")}),s.jsx("ul",{className:"mt-4 space-y-2 text-[12px] text-slate-300",children:["storyArcReady","worldBibleReady","assetsReady","episodeListReady"].map(e=>{const o=ns[e],l=e==="storyArcReady"?"page.storyflow.pipelineCheckStoryArc":e==="worldBibleReady"?"page.storyflow.pipelineCheckWorldBible":e==="assetsReady"?"page.storyflow.pipelineCheckAssets":"page.storyflow.pipelineCheckEpisodes";return s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`material-symbols-outlined text-base shrink-0 ${o?"text-primary":"text-slate-500"}`,"aria-hidden":!0,children:o?"check_circle":"radio_button_unchecked"}),s.jsx("span",{children:n(l)})]},e)})}),s.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-end gap-2",children:[s.jsx("button",{type:"button",className:"px-3 py-2 rounded-lg text-xs font-semibold text-slate-400 hover:text-slate-200 hover:bg-white/5",onClick:()=>Jn(null),children:n("page.storyflow.back")}),!ns.allReady&&s.jsx("button",{type:"button",className:"px-3 py-2 rounded-lg text-xs font-semibold text-slate-300 border border-white/15 hover:bg-white/5",onClick:()=>Ao({bypassWarnings:!0}),children:n("page.storyflow.openAnyway")}),s.jsx("button",{type:"button",className:"px-3 py-2 rounded-lg text-xs font-bold bg-primary text-background-dark hover:opacity-90 disabled:opacity-40 disabled:pointer-events-none",disabled:!ns.allReady,onClick:()=>Ao(),children:n("page.storyflow.createWorkflowButton")})]})]})}),document.body),La&&typeof document<"u"?Ps.createPortal(s.jsx(tC,{open:La,onClose:()=>jp(!1),characters:Et.map(e=>({id:e.id,name:e.name})),scenes:Xt,props:br,getThumbSrc:ls,onPickProjectAsset:e=>Pn(e),seedanceApprovedEnabled:Oa,greenlightProjectId:t,initialEntityTab:(E==null?void 0:E.kind)==="SCENES"?"SCENES":(E==null?void 0:E.kind)==="PROPS"?"PROPS":"CHARACTERS",approvedTargetCharacterName:(E==null?void 0:E.kind)==="CHARACTERS"?E.name:null,approvedTargetCharacterLocalId:(E==null?void 0:E.kind)==="CHARACTERS"?n1(E.characterId):null,onApprovedRefApplied:e=>{if(!E||E.kind!=="CHARACTERS")return;lr(l=>({...l,conceptUrl:e,conceptRefImage:e}));const o=Ve("CHARACTERS",E.characterId,E.name);rs(l=>{const d={...l,[o]:{...l[o],conceptUrl:e,conceptRefImage:e}};return queueMicrotask(()=>{try{Ze.current({silent:!0,workspaceAssetMedia:d})}catch{}}),d})},onDeleteLocalWorkspaceAsset:e=>{const o=Ve(e.kind,e.kind==="CHARACTERS"?e.characterId:void 0,e.name);rs(l=>{if(!(o in l))return l;const d={...l};return delete d[o],Ze.current({silent:!0,workspaceAssetMedia:d}),d})}}),document.body):null]})]})};export{Z1 as CreativeBrain,Z1 as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.