1import{r as n,j as e,B as b,T as p,f as ie,aj as vt,n as It,l as v}from"./index-CzOd9Km7.js";import{beatCatalogQuery as St}from"./wizardCatalogQueries-CFHwzzA3.js";import{u as kt}from"./useQuery-BcbK_yvX.js";import{g as Tt}from"./axiosConfig-BS0LIV0L.js";import"./projectSchemas-h1QnwtOV.js";import"./screenplaySchemas-D4JI8Qiv.js";import{a as zt,d as ye}from"./supabaseAuthClient-D4COccm1.js";import{b as je}from"./beatWizardApi-Dv9a4vr-.js";import{I as Ve}from"./IconButton-DX7NfjoN.js";import{A as At}from"./ArrowBack-wuTO0s01.js";import{A as Wt}from"./ArrowForward-C5xjcR3b.js";import{T as He,F as Ge,I as Je,S as Ue}from"./TextField-BLDfXARA.js";import{D as et,a as tt,b as rt,d as be,L as _e,c as Pt}from"./TrendingUp-DOlPqcSv.js";import{L as Bt}from"./Menu-BAMQbaXI.js";import{L as we}from"./ListItem-B456oJov.js";import{A as Mt,c as Rt,B as Ft,M as Et,S as Ot}from"./ProjectView-Mi3StT_6.js";import{I as Lt}from"./Info-CA3gQy_l.js";import{W as $t}from"./Warning-Ps4lknT4.js";import{W as Dt}from"./WizardResultDialogShell-vrBwouF1.js";import{F as Nt}from"./FullScreenLoader-BjP_n07h.js";import{S as qt,u as Qt,D as Kt,b as Vt,c as Ht}from"./defaultImportSteps-DEPn5duJ.js";import{i as Gt,r as Jt}from"./weaveApi-BNjBXpjA.js";import{C as Ut}from"./CircularProgress-CFKeHsf1.js";import{A as oe}from"./Alert-BXc9IPcV.js";import{M as Ye}from"./MenuItem-CKC7Jjka.js";import{F as Xe}from"./FormControlLabel-Cvt0lc2T.js";import{C as Ze}from"./Checkbox-CDjSoqnY.js";import{S as Yt}from"./Snackbar-zJwnOmcl.js";import"./screenplayWizardApi-QWoWm3Tf.js";import"./useProjects-CIew3vEQ.js";import"./useInfiniteQuery-DMg-BX9J.js";import"./taskCenterStorage-CJYyvdpT.js";import"./useControlled-C1WEhlQX.js";import"./ownerWindow-D5LHhVun.js";import"./Paper-2iw6XA5a.js";import"./createSvgIcon-DaEeqn1R.js";import"./requirePropFactory-CXHKSpYe.js";import"./dividerClasses-CE6pxdyz.js";import"./useMutation-CJKToZ6s.js";import"./useTemplate-ViNE3wSO.js";import"./useBillingPreference-D9W5TnwM.js";import"./useSupabaseAuth-DG28FngJ.js";import"./SupabaseProvider-CTgOxySk.js";import"./authRedirect-DCYLoor1.js";import"./billingApi-B525x-Ud.js";import"./Add-DR3ny3xK.js";import"./Popper-t1n9sSlv.js";import"./Avatar-C-SXWBlB.js";import"./Divider-UFPhkgyE.js";import"./Person-Bgotsgvw.js";import"./Tabs-Ba5iDgru.js";import"./Restore-ruzW0M8I.js";import"./usePreviousProps-D6D_fzw_.js";import"./designTokens-CHJCN-yJ.js";import"./Grid-NNIo4zT1.js";import"./Stack-E99Gdh2J.js";import"./styled-D002SLmF.js";import"./useThemeProps-Dhrs3fnV.js";import"./getThemeProps-whaKXyLK.js";import"./ExpandMore-5fy3CFZO.js";import"./Edit-hGaSq1bW.js";import"./Card-BXrAfFWw.js";import"./Collapse-Bnk0IQSm.js";import"./ButtonGroup-CVCxmEpG.js";import"./useMediaQuery-BbaHISUJ.js";import"./collaborationApi-Bg8o2r1s.js";import"./chunkPrefetch-Db-BfmQX.js";import"./Toolbar-Cld6iuHK.js";import"./CheckCircle-D4YsMZEr.js";import"./Error--n9aLARG.js";import"./WarningAmber-CiMpmQi5.js";import"./InfoOutlined-D-D5tVgC.js";import"./screenplayApi-BvqHAum1.js";import"./RadioButtonUnchecked-Cs2dH0Md.js";import"./SwitchBase-B_U2OR8-.js";const Xt=({templates:c,currentTemplateIndex:s,onTemplateChange:j,values:z,onChange:_,showTemplateNavigation:S=!0})=>{const[A,i]=n.useState([]),u=n.useRef(null),m=c[s],W=n.useCallback(a=>
1{if(!a)return[];const x=a.template_text,d=/\[([^\]]+)\]/g,g=[];let w=0,I;for(;(I=d.exec(x))!==null;){if(I.index>w){const B=x.slice(w,I.index);B&&g.push({type:"text",content:B})}const P=I[1],l=a.placeholders[P]||"";g.push({type:"input",content:I[0],placeholder:P,hint:l}),w=I.index+I[0].length}if(w<x.length){const P=x.slice(w);P&&g.push({type:"text",content:P})}return g},[]);n.useEffect(()=>{if(m){const a=W(m);i(a)}},[m,W]),n.useEffect(()=>{m&&Object.keys(m.placeholders).find(d=>{var g;return!((g=z[d])!=null&&g.trim())})&&u.current&&setTimeout(()=>{var d;(d=u.current)==null||d.focus()},100)},[m]);const f=()=>{const a=s===0?c.length-1:s-1;j(a)},k=()=>{const a=s===c.length-1?0:s+1;j(a)},R=m?Object.keys(m.placeholders):[],h=R.filter(a=>{var x;return(x=z[a])==null?void 0:x.trim()}),F=h.length===R.length;return m?e.jsxs(b,{sx:{width:"100%",maxWidth:"100%",borderRadius:"12px",p:4,border:"1px solid rgba(241, 245, 249, 0.1)",position:"relative"},children:[S&&e.jsx(e.Fragment,{children:e.jsxs(b,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:3,pb:2,borderBottom:"1px solid rgba(241, 245, 249, 0.1)"},children:[e.jsx(Ve,{onClick:f,disabled:c.length<=1,size:"small",sx:{backgroundColor:"rgba(173, 119, 255, 0.1)",color:"text.primary","&:hover":{backgroundColor:"rgba(173, 119, 255, 0.2)"},"&:disabled":{backgroundColor:"rgba(173, 119, 255, 0.05)",color:"text.disabled"}},children:e.jsx(At,{fontSize:"small"})}),e.jsxs(b,{sx:{textAlign:"center",flex:1,mx:2},children:[e.jsx(p,{variant:"h6",sx:{fontWeight:"bold",color:"#ffffff",mb:.5},children:m.name}),e.jsxs(p,{variant:"caption",color:"text.secondary",children:[`Template ${s+1} of ${c.length}`,m.description?` - ${m.description}`:""]})]}),e.jsx(Ve,{onClick:k,disabled:c.length<=1,size:"small",sx:{backgroundColor:"rgba(173, 119, 255, 0.1)",color:"text.primary","&:hover":{backgroundColor:"rgba(173, 119, 255, 0.2)"},"&:disabled":{backgroundColor:"rgba(173, 119, 255, 0.05)",color:"text.disabled"}},children:e.jsx(Wt,{fontSize:"small"})})]})}),e.jsx(b,{sx:{fontSize:"1.2rem",lineHeight:3.2,color:"text.primary"},children:A.map((a,x)=>{if(a.type==="text")return e.jsx(b,{component:"span",children:a.content},x);{const d=a.placeholder,g=z[d]||"",w=a.hint||"",I=g.length,P=d==="FULL_TEXT"?1e6:200,l=I>P,B=!g.trim()&&x===A.findIndex($=>{var H;return $.type==="input"&&!((H=z[$.placeholder])!=null&&H.trim())});return d==="FULL_TEXT"?e.jsx(b,{sx:{display:"block",width:"100%",my:3},children:e.jsx(He,{value:g,onChange:$=>_(d,$.target.value),label:w,placeholder:"Paste your screenplay, treatment, or story outline here...",inputRef:B?u:void 0,variant:"outlined",multiline:!0,minRows:10,maxRows:20,fullWidth:!0,error:l,helperText:l?`Content too long! Please shorten to under ${P.toLocaleString()} characters.`:`${I.toLocaleString()} characters`,sx:{"& .MuiOutlinedInput-root":{fontSize:"0.95rem",fontFamily:'"Courier New", "Monaco", monospace',backgroundColor:g?l?"rgba(244, 67, 54, 0.1)":"rgba(173, 119, 255, 0.1)":"rgba(241, 245, 249, 0.05)",color:"text.primary",borderRadius:"8px","& fieldset":{borderColor:l?"error.main":"rgba(173, 119, 255, 0.3)",borderWidth:1},"&:hover fieldset":{borderColor:l?"error.main":"rgba(173, 119, 255, 0.5)"},"&.Mui-focused fieldset":{borderColor:l?"error.main":"#ad77ff",borderWidth:2}},"& .MuiInputLabel-root":{color:l?"error.main":"#c4a7fb",fontSize:"1rem",fontWeight:500},"& .MuiFormHelperText-root":{fontSize:"0.98rem",color:l?"error.main":"text.secondary",margin:"4px 0 0 0",textAlign:"right"},"& .MuiOutlinedInput-input":{padding:"16px",color:"text.primary",lineHeight:1.5}}})},x):e.jsx(b,{component:"span",sx:{position:"relative",display:"inline-block",verticalAlign:"top"},children:e.jsx(He,{value:g,onChange:$=>_(d,$.target.value),label:w,inputRef:B?u:void 0,variant:"outlined",size:"small",error:l,helperText:l?"Too long! Please shorten.":void 0,sx:{width:g?`${Math.max(g.length*1.84,13.8)}ch`:"18.4ch",minWidth:"13.8ch",maxWidth:"46ch",mx:.5,"& .MuiOutlinedInput-root":{fontSize:"inherit",fontFamily:'"Courier New", "Monaco", monospace',fontWeight:"bold",backgroundColor:g?l?"rgba(244, 67, 54, 0.1)":"rgba(173, 119, 255, 0.1)":"rgba(241, 245, 249, 0.05)",color:"text.primary",borderRadius:"8px",border:"none","& fieldset":{borderColor:l?"error.main":"rgba(173, 119, 255, 0.3)",borderWidth:1},"&:hover fieldset":{borderColor:l?"error.main":"rgba(173, 119, 255, 0.5)"},"&.Mui-focused fieldset":{borderColor:l?"error.main":"#ad77ff",borderWidth:2}},"& .MuiInputLabel-root":{color:l?"error.main":"#c4a7fb",fontSize:"0.98rem",fontWeight:500},"& .MuiInputLabel-root.MuiInputLabel-shrink":{transform:"translate(14px, -6px) scale(0.75)"},"& .MuiFormHelperText-root":{fontSize:"0.81rem",color:l?"error.main":"text.secondary",margin:"2px 0 0 0",textAlign:"center"},"& .MuiOutlinedInput-input":{textAlign:"center",padding:"12px 8px",color:"text.primary",transition:"all 0.3s ease"}}})},x)}})}),e.jsx(b,{sx:{mt:6,pt:3,borderTop:"1px solid #e0e0e0"},children:e.jsxs(b,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Progress: ",h.length," of ",R.length," fields completed"]}),e.jsx(b,{sx:{width:120,height:6,backgroundColor:"#e0e0e0",borderRadius:3,overflow:"hidden"},children:e.jsx(b,{sx:{width:`${h.length/R.length*100}%`,height:"100%",background:F?"linear-gradient(90deg, #4caf50, #66bb6a, #4caf50)":"linear-gradient(90deg, #ad77ff, #c9a7ff, #ad77ff)",backgroundSize:"200% 100%",animation:F?"shimmer 2s ease-in-out infinite":"none",transition:"width 0.5s ease",borderRadius:3,boxShadow:"0 2px 4px rgba(0, 0, 0, 0.2)","@keyframes shimmer":{"0%":{backgroundPosition:"200% 0"},"100%":{backgroundPosition:"-200% 0"}}}})})]})})]}):e.jsx(b,{sx:{textAlign:"center",p:3},children:e.jsx(p,{color:"text.secondary",children:"No templates available"})})},Zt=({open:c,onClose:s,onConfirm:j,existingCardCount:z})=>e.jsxs(et,{open:c,onClose:s,maxWidth:"md",fullWidth:!0,PaperProps:{sx:{borderRadius:"12px",backgroundColor:"background.paper"}},children:[e.jsxs(tt,{sx:{textAlign:"center",pb:2,pt:3},children:[e.jsx(p,{variant:"h4",sx:{fontWeight:400,color:"text.primary",mb:1},children:"Confirm Beat Wizard Use"}),e.jsx(p,{variant:"body2",sx:{color:"text.secondary",fontStyle:"italic"},children:"This action will permanently replace your existing beat cards"})]}),e.jsxs(rt,{sx:{py:3},children:[e.jsxs(b,{sx:{mb:3},children:[e.jsx(p,{variant:"body1",sx:{mb:3,lineHeight:1.6,textAlign:"center"}
1,children:"The Beat Wizard will overwrite your existing story beats with new content. Here's what will happen:"}),e.jsxs(Bt,{sx:{py:1},children:[e.jsxs(we,{children:[e.jsx(be,{children:e.jsx(Mt,{sx:{color:"text.primary"}})}),e.jsx(_e,{primary:"All story beats will be replaced",secondary:"Your current story beats will be lost",primaryTypographyProps:{color:"text.primary",fontWeight:600},secondaryTypographyProps:{color:"text.secondary"}})]}),e.jsxs(we,{children:[e.jsx(be,{children:e.jsx(Lt,{sx:{color:"text.primary"}})}),e.jsx(_e,{primary:"New story will be outlined from your input",secondary:"AI will create a complete story structure based on your inputs",primaryTypographyProps:{color:"text.primary",fontWeight:600},secondaryTypographyProps:{color:"text.secondary"}})]}),e.jsxs(we,{children:[e.jsx(be,{children:e.jsx($t,{sx:{color:"text.primary"}})}),e.jsx(_e,{primary:"This action cannot be undone",secondary:"Make sure you're ready to replace your current work",primaryTypographyProps:{color:"text.primary",fontWeight:600},secondaryTypographyProps:{color:"text.secondary"}})]})]})]}),e.jsxs(p,{variant:"body2",sx:{color:"text.secondary",mb:2,p:2,fontStyle:"italic",textAlign:"center"},children:[e.jsx("strong",{children:"Tip:"})," If you want to keep your current beat cards, consider duplicating your project first, or manually copying any important content before proceeding."]}),e.jsx(p,{variant:"body1",sx:{textAlign:"center",color:"text.primary",mt:2,fontWeight:600},children:"Are you sure you want to proceed?"})]}),e.jsxs(Pt,{sx:{p:3,gap:2,justifyContent:"center"},children:[e.jsx(ie,{onClick:s,variant:"outlined",size:"large",sx:{minWidth:120,fontSize:"1rem"},children:"Cancel"}),e.jsx(ie,{onClick:j,variant:"contained",size:"large",sx:{minWidth:200,fontSize:"1rem"},children:"Yes, I believe in you!"})]})]});function er({isOpen:c,onClose:s,result:j,onViewResults:z}){var d,g,w,I,P;if(!j)return null;const{success:_,updated_card_codes:S,credits_used:A,partial_results:i,message:u}=j,m=Math.max(S.length,((d=j.import_summary)==null?void 0:d.beat_cards_updated)??0),W=_&&m>0&&i&&(i.failed_llm_cards.length>0||i.failed_update_cards.length>0),f=W?"warning":_?"success":"error",k=W?"Partially Complete":_?"Beats Generated":"Generation Failed",R=u||(_?`${S.length} beat card${S.length!==1?"s":""} generated successfully.`:"Beat generation failed. Please try again."),h=[];(g=i==null?void 0:i.warnings)!=null&&g.length&&h.push(...i.warnings.map(l=>typeof l=="string"?l:JSON.stringify(l))),(w=i==null?void 0:i.failed_llm_cards)!=null&&w.length&&h.push(`AI generation failed for ${i.failed_llm_cards.length} card${i.failed_llm_cards.length!==1?"s":""}`),(I=i==null?void 0:i.failed_update_cards)!=null&&I.length&&h.push(`Save failed for ${i.failed_update_cards.length} card${i.failed_update_cards.length!==1?"s":""}`);const F=(P=j.import_summary)==null?void 0:P.warnings_count;F&&F>0&&h.push(`${F} warning${F!==1?"s":""} detected during import.`);const a=[];if(j.import_summary){const l=j.import_summary;typeof l.scenes_count=="number"&&l.scenes_count>0&&a.push({label:"Scenes analyzed",value:l.scenes_count}),typeof l.beat_cards_updated=="number"&&l.beat_cards_updated>0&&a.push({label:"Beat cards updated",value:l.beat_cards_updated}),typeof l.document_ops=="number"&&l.document_ops>0&&a.push({label:"Screenplay edits",value:l.document_ops})}A!==null&&a.push({label:"Credits used",value:A});const x=i&&i.success_rate!==void 0&&i.success_rate<100?`Success rate: ${i.success_rate}%`:void 0;return e.jsx(Dt,{open:c,onClose:s,tone:f,title:k,message:R,stats:a.length>0?a:void 0,footerNote:x,debugDetails:h.length>0?h.join(` 2`):void 0,debugLabel:`${h.length} issue${h.length!==1?"s":""}`,secondaryAction:{label:f==="success"?"Done":"Close",variant:"contained",onClick:s}})}const st=({project_name:c,...s})=>je.quote(c,s);function tr({request:c,onClose:s,onConfirm:j}){return e.jsx(Rt,{title:"Generate beats",request:c,getQuote:st,onClose:s,onConfirm:j})}function rr({request:c,enabled:s=!0}){return e.jsx(Ft,{title:"Generate beats",request:c,getQuote:st,enabled:s})}const sr=({open:c,onClose:s,onImport:j,excludeLlms:z=[],title:_="Import Scenes from Screenplay",de
2scription:S="Paste your entire screenplay below. We'll analyze it alongside your existing beats and characters to derive a clean scene list.",confirmLabel:A="Import Screenplay",costMultiplier:i,helperText:u,guidanceMaxLength:m=5e5})=>e.jsxs(et,{open:c,onClose:s,maxWidth:"md",fullWidth:!0,children:[e.jsx(tt,{children:_}),e.jsx(rt,{children:e.jsx(qt,{onImport:j,excludeLlms:z,title:_,description:S,confirmLabel:A,costMultiplier:i,helperText:u,guidanceMaxLength:m,variant:"dialog",active:c,onCancel:s,actionsPlacement:"bottom"})})]}),ae="beat_wizard_draft",nr=1200,or=c=>{var w,I,P;if(!c)return null;const j=c.summary||{},z=j.scenes||{},_=j.beats||{},S=j.document||{},A=new Map(c.steps.map(l=>[l.id,l])),i=((w=A.get("scene_generation"))==null?void 0:w.detail)||{},u=((I=A.get("beat_generation"))==null?void 0:I.detail)||{},m=((P=A.get("document_import"))==null?void 0:P.detail)||{},W=typeof(z==null?void 0:z.count)=="number"?z.count:typeof(i==null?void 0:i.scene_count)=="number"?i.scene_count:typeof(i==null?void 0:i.count)=="number"?i.count:0,f=u;let k=Array.isArray(_==null?void 0:_.updated_cards)?_.updated_cards:Array.isArray(f==null?void 0:f.updated_card_codes)?f.updated_card_codes:[];const R=k.length||(typeof(u==null?void 0:u.updated_cards)=="number"?u.updated_cards:0);!k.length&&R>0&&(k=Array.from({length:R},(l,B)=>`imported-beat-${B+1}`));const h=Array.isArray(_==null?void 0:_.warnings)?_.warnings:Array.isArray(u==null?void 0:u.warnings)?u.warnings:[],F=h.length||(typeof(u==null?void 0:u.warnings)=="number"?u.warnings:0),a=(S==null?void 0:S.applied_ops)??(S==null?void 0:S.ops_applied)??(m==null?void 0:m.applied_ops)??(m==null?void 0:m.ops_applied)??0,x=[];W>0&&x.push(`${W} scenes analyzed`),R>0&&x.push(`${R} beat cards updated`),typeof a=="number"&&a>0&&x.push(`${a} screenplay edits applied`);const d=c.status==="completed",g=d?x.length?`Screenplay import finished: ${x.join(" ⢠")}`:"Screenplay import finished.":c.error_message||"Screenplay import failed.";return{success:d,updated_card_codes:k,credits_used:c.credits_used??null,partial_results:{successful_cards:R,failed_llm_cards:[],failed_update_cards:[],warnings:h,success_rate:d?100:0},import_summary:{scenes_count:W,beat_cards_updated:R,document_ops:typeof a=="number"?a:0,warnings_count:F},message:g}},Ts=({stage:c,project:s,onUpdateProject:j,onIsDirtyChange:z,onNavigateToStage:_,navigationData:S,clearNavigationData:A})=>{var Ne,qe,Qe,Ke;const[i]=n.useState(zt),u=vt(),m=s.mode==="short_movie",W=kt(St(s.name,s.mode||"movie")),f=n.useMemo(()=>{var t;return((t=W.data)==null?void 0:t.templates)??[]},[W.data]),k=n.useMemo(()=>{var t;return((t=W.data)==null?void 0:t.style_templates)??[]},[W.data]),R=W.isLoading,[h,F]=n.useState(0),[a,x]=n.useState(""),[d,g]=n.useState({}),[w,I]=n.useState(!1),[P,l]=n.useState(!1),[B,$]=n.useState(null);n.useEffect(()=>$(null),[s.name]);const[H,Ce]=n.useState(null),[nt,ee]=n.useState(!1),[E,te]=n.useState(null),[G,ve]=n.useState(!0),[J,Ie]=n.useState(!1),[ot,fe]=n.useState(!1),[K,he]=n.useState(null),[re,le]=n.useState(null),[D,at]=n.useState(null),O=It(),{settings:N}=Et(),U=S&&typeof S=="object"&&"type"in S&&S.type==="beat-wizard"?S:null,[it,lt]=n.useState(null),[Se,ke]=n.useState(!1),Y=n.useRef(null),ge=n.useRef(null),Te=n.useRef(null),ze=n.useRef(null),ce=it===s.name,de=n.useMemo(()=>{try{return localStorage.getItem(`${ae}:${s.id||s.name}`)}catch{return null}},[s.id,s.name]),ue=n.useCallback((t,r="info")=>{Ce({message:t,severity:r})},[]),ct=()=>{W.refetch()};n.useEffect(()=>{(()=>{if(f.length===0)return;const r=f[h];if(!r||Object.keys(d).length>0)return;const o=`beat-wizard-prefill-${s.name}`;let C=null;try{C=localStorage.getItem(o)}catch(L){v.warn("Failed to read Beat Wizard prefill locally:",L)}let T="";if(C)try{const L=JSON.parse(C);T=typeof(L==null?void 0:L.summaryText)=="string"?L.summaryText:C}catch{T=C}if(T){v.log("Idea Wizard prefill found in localStorage, populating first placeholder");const Q=Object.keys(r.placeholders)[0];if(Q){g({[Q]:T});try{localStorage.removeItem(o)}catch(q){v.warn("Failed to clear Beat Wizard prefill locally:",q)}}}})()},[f,h,d,s.name]),n.useEffect(()=>{if(!U)return;const t=typeof U.guidanceText=="string"?U.guidanceText:"",r=Array.isArray(U.cardCodes)?U.cardCodes.filter(o=>
2typeof o=="string"&&o.trim().length>0):[];at({cardCodes:r,guidanceText:t}),A==null||A()},[U,A]),n.useEffect(()=>{if(!(D!=null&&D.guidanceText)||f.length===0||Object.keys(d).length>0)return;const t=f[h],r=t?Object.keys(t.placeholders)[0]:null;r&&g({[r]:D.guidanceText})},[h,d,D,f]);const Ae=n.useMemo(()=>{if(!m)return"";const t=s.template_settings,r=t==null?void 0:t.story_development;if(!r||typeof r!="object")return"";const o=r.beat_style_template_id;return typeof o=="string"?o:""},[m,s.template_settings]);n.useEffect(()=>{if(k.length>0&&!a){const t=k.find(r=>r.id===Ae);x((t==null?void 0:t.id)||k[0].id)}},[Ae,k,a]),n.useEffect(()=>{if(Te.current!==s.name){try{if(de){const{templateId:t,templateIndex:r,values:o,styleTemplateId:C,includeContext:T,addMissingBeats:L}=JSON.parse(de),Q=typeof t=="string"?f.findIndex(q=>q.id===t):-1;Q>=0?F(Q):typeof r=="number"&&r>=0&&r<f.length&&F(r),o&&typeof o=="object"&&g(o),C&&typeof C=="string"&&(k.length===0||k.some(q=>q.id===C))&&x(C),typeof T=="boolean"&&ve(T),typeof L=="boolean"&&Ie(L)}}catch(t){v.warn("Failed to load Beat Wizard draft from project settings:",t)}Te.current=s.name,lt(s.name),ge.current=de}},[de,s.name,k,f]);const We=n.useMemo(()=>{var t;return JSON.stringify({templateId:((t=f[h])==null?void 0:t.id)||"",values:d,styleTemplateId:a,includeContext:G,addMissingBeats:J})},[h,d,a,G,J,f]),Pe=n.useCallback(async t=>{if(ge.current!==t)try{localStorage.setItem(`${ae}:${s.id||s.name}`,t),ge.current=t}catch(r){v.warn("Failed to persist Beat Wizard draft locally:",r)}},[s.id,s.name]);n.useEffect(()=>{if(!(!ce||f.length===0))return Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{Pe(We)},nr),()=>{Y.current&&(clearTimeout(Y.current),Y.current=null)}},[ce,Pe,We,f.length]),n.useEffect(()=>{const t=s.template_settings;if(!t||!(ae in t))return;const r=String(s.id||s.name);if(ze.current===r)return;ze.current=r;const o={};Object.entries(t).forEach(([C,T])=>{C!==ae&&(typeof T=="string"||typeof T=="number"||typeof T=="boolean")&&(o[C]=T)}),delete o[ae],j({...s,template_settings:o}).catch(C=>{v.warn("Failed to remove shared Beat Wizard draft from project settings:",C)})},[j,s]);const Be=n.useRef(z);n.useEffect(()=>{Be.current=z},[z]);const Me=n.useRef(null);n.useEffect(()=>{const t=Object.keys(d).length>0;Me.current!==t&&(Me.current=t,Be.current(t))},[d]);const se=n.useMemo(()=>{const t=(s.stages||[]).map(o=>o.id);return["core","series_core","season_engine","storylines","tentpoles","characters"].find(o=>t.includes(o))||t[0]||null},[s.stages]),Re=n.useCallback(()=>{Ce(null)},[]),M=n.useMemo(()=>f[h]||null,[f,h]),me=n.useMemo(()=>!M||!M.placeholders?[]:Object.keys(M.placeholders),[M]);n.useEffect(()=>{!ce||!Se||(g({}),ke(!1))},[h,ce,Se]);const xe=n.useMemo(()=>{if(!M)return"";let t=M.template_text;return me.forEach(r=>{const o=d[r]||"";t=t.replace(new RegExp(`\\[${r}\\]`,"g"),o)}),t},[M,me,d]),V=n.useMemo(()=>me.every(t=>{const r=d[t]||"",o=t==="FULL_TEXT"?1e6:200;return r.trim().length>0&&r.length<=o}),[me,d]),Fe=n.useCallback((t,r)=>r.endsWith("*")?t.startsWith(r.slice(0,-1)):t===r,[]),Ee=n.useMemo(()=>{const t=Array.isArray(c.linked_card_codes)?c.linked_card_codes:[];return t.length?t:["10.*","20.*","30.*","40.*"]},[c.linked_card_codes]),ne=n.useMemo(()=>{const t=s.cards||{};return Object.entries(t).filter(([r])=>Ee.some(o=>Fe(r,o))).filter(([,r])=>!r||!r.fields?!1:Object.values(r.fields).some(o=>typeof o=="string"?o.trim().length>0:Array.isArray(o)?o.length>0:o&&typeof o=="object"?Object.values(o).some(C=>!!C):!!o)).map(([r])=>r)},[s.cards,Ee,Fe]),Oe=n.useCallback(t=>{ke(!0),F(t)},[]),dt=n.useCallback((t,r)=>{g(o=>({...o,[t]:r}))},[]),ut=n.useCallback(async t=>{if(!B)throw new Error("Quote is no longer available.");try{I(!0),le("generate"),ye(i);const{project_name:r,...o}=B,C={...o,...t},T=await je.runWizard(s.name,C);if(ye(i),v.log("API call completed, result:",T),Gt(T)){const L=T.job_id,Q=T.reservation_id;Jt(T,{projectName:s.name,finalize:(q,Ct)=>je.finalize(q,Ct,Q),task:{id:`beat-wizard:${L}`,projectName:s.name,title:"Generating beats",nounTitle:"Story beats",livePreview:!0,sourceStageId:c.id,sourceStageLabel:c.name,resumeKey:"wizard_live_job",resumePayload:{workflow:"beat",reservationId:Q},completionEffectKey:"beat_wizard_result",action:{type:"open_stage",stageId:se||c.id,label:"Open beats"}}}).catch(q=>v.error("Beat wizard background task failed",q))}else te(T),ee(!0);v.log("Dialog state set after Beat Wizard run")}catch(r){throw v.error("Error running beat wizard:",r),r}finally{I(!1),le(null)}},[i,B,se,s.name,c.id,c.name]),pe=n.useCallback(()=>{M&&(ye(i),$({project_name:s.name,template_id:M.id,filled_text:xe,placeholder_values:{...d},include_context:G,llmIdentifier:N==null?void 0:N.llmIdentifier,options:{style_template_id:a,add_missing_beats:J}}))},[i,M,s.name,xe,d,G,N==null?void 0:N.llmIdentifier,a,J]),mt=n.useCallback(()=>
2{if(v.log("handleSubmit called",{isFormValid:V,currentTemplate:!!M,overwritableCards:ne.length}),!V||!M){v.log("Form validation failed:",{isFormValid:V,hasTemplate:!!M});return}ne.length>0?(v.log("Showing confirmation dialog for",ne.length,"existing cards"),l(!0)):(v.log("No existing cards, running beat wizard directly"),pe())},[V,M,ne.length,pe]),pt=n.useCallback(()=>{v.log("handleConfirmedSubmit called - closing dialog and running beat wizard"),l(!1),pe()},[pe]),ft=n.useCallback(async()=>{const t=E==null?void 0:E.success;ee(!1),te(null),t&&(v.log("Beat wizard was successful, invalidating queries..."),await O.invalidateQueries({queryKey:["project",s.name]}),await O.invalidateQueries({queryKey:["project-stage",s.name]}),await O.invalidateQueries({queryKey:["cards",s.name]}),v.log("Queries invalidated after dialog close."),_&&se&&(v.log("Navigating to Core stage..."),_(se)))},[E==null?void 0:E.success,O,s.name,_,se]),ht=n.useCallback(async()=>{const t=E==null?void 0:E.success;ee(!1),te(null),t&&(v.log("Beat wizard was successful, invalidating queries..."),await O.invalidateQueries({queryKey:["project",s.name]}),await O.invalidateQueries({queryKey:["project-stage",s.name]}),await O.invalidateQueries({queryKey:["cards",s.name]}),v.log("Queries invalidated after view results."))},[E==null?void 0:E.success,O,s.name]),gt=n.useCallback(t=>{x(t)},[]),X=c.config,Le=(X==null?void 0:X.beat_wizard_import)||{},$e=Le.enabled??!0,xt=Le.exclude_llms||(X==null?void 0:X.exclude_llms)||[],Z=n.useMemo(()=>{const t=s,r=t.id;if(typeof r=="number")return r;const o=t.project_id??t.projectId,C=Number(o??r);return Number.isFinite(C)?C:0},[s]),{startImportJob:De,importJob:y,overlayVisible:yt,steps:bt}=Qt({projectId:Z||void 0,projectName:s.name,stepDefinitions:Kt}),_t=n.useCallback(async t=>{if(K){v.log("BeatWizard import job requested");try{if(I(!0),le("import-job"),!Z)throw new Error("Project identifier unavailable for import job.");te(null),ee(!1);const r=await De(K.kind==="fdx"?{kind:"fdx",formData:K.payload}:K.payload,t);r.status==="completed"?(ue("Screenplay imported successfully.","success"),await O.invalidateQueries({queryKey:["project",s.name]}),await O.invalidateQueries({queryKey:["project-stage",s.name]}),await O.invalidateQueries({queryKey:["cards",s.name]}),await O.invalidateQueries({queryKey:["screenplay",Z]})):ue(r.error_message||"Screenplay import failed.","error");const o=or(r);o&&(te(o),ee(!0))}catch(r){v.error("Screenplay import job failed:",r);const o=Tt(r);throw ue(o,"error"),r}finally{I(!1),le(null)}}},[K,Z,s.name,ue,O,De]),wt=n.useMemo(()=>{if(!w)return"Planning your story...";if(re==="import-job"){if(!y)return"Importing screenplayâ¦";const t=y.steps.find(r=>r.status==="processing");return t?`Importing screenplay â ${t.label}`:y.status==="failed"?"Import failed":y.status==="completed"?"Import complete":"Importing screenplayâ¦"}return"Planning your story..."},[w,re,y]),jt=n.useMemo(()=>!w||re==="import-job"?"":"Full-season generation can take 20 minutes or longer. You can leave this page while it continues on our servers.",[w,re]);return R?e.jsxs(b,{sx:{p:2,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:[e.jsx(Ut,{}),e.jsx(p,{sx:{ml:2},children:"Loading templates..."})]}):f.length===0?e.jsxs(b,{sx:{p:2,textAlign:"center"},children:[e.jsx(p,{color:"error",children:"No templates available. Please try refreshing the page."}),e.jsx(ie,{onClick:ct,sx:{mt:2},children:"Retry"})]}):e.jsx(b,{className:"wizard-background use-css-pattern",sx:{p:3,height:"100%",overflowY:"auto",position:"relative"},children:e.jsxs(b,{sx:{position:"relative",zIndex:2},children:[e.jsx(Ot,{title:c.name,description:c.description,variant:"wizard",actions:e.jsxs(e.Fragment,{children:[K&&e.jsx(Vt,{request:K,onClose:()=>he(null),onConfirm:_t}),$e&&e.jsx(ie,{variant:"outlined",size:"large",onClick:()=>fe(!0),disabled:!!B||w,children:"Import Screenplay"}),e.jsx(ie,{variant:"contained",size:"large",onClick:mt,disabled:!!B||!V||w,children:w?"Generating...":V?"Generate Beat Cards!":"Fill in the details"})]}),sx:{mb:4}}),e.jsx(oe,{severity:"info",sx:{mb:3},children:"Complex projectsâespecially full seasonsâcan take 20 minutes or longer. Generation continues on our servers, so you can leave this page and return later."}),D&&e.jsxs(oe,{severity:"info",sx:{mb:3},children:[e.jsx(p,{variant:"subtitle2",sx:{fontWeight:700,mb:.5},children:"Room Review context"}),D.cardCodes.length>0&&e.jsxs(p,{variant:"body2",sx:{mb:.75},children:["Affected cards: ",D.cardCodes.map(t=>{var r;return((r=s.cards[t])==null?void 0:r.name)||t}
2).join(", ")]}),e.jsx(p,{variant:"body2",children:D.guidanceText})]}),y&&e.jsxs(b,{sx:{mb:3,p:2,borderRadius:2,border:`1px solid ${u.palette.divider}`,backgroundColor:u.palette.background.paper},children:[e.jsxs(p,{variant:"subtitle1",sx:{fontWeight:600,mb:1},children:["Screenplay Import Status: ",y.status.toUpperCase()]}),y.reserved_credits!==void 0&&y.reserved_credits!==null&&e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Reserved credits: ",y.reserved_credits]}),y.llm_provider&&y.llm_model&&e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Model: ",y.llm_provider,"/",y.llm_model]}),((Ne=y.summary)==null?void 0:Ne.document)&&e.jsxs(p,{variant:"body2",color:"text.secondary",sx:{mb:1},children:["Applied ops: ",y.summary.document.applied_ops??0]}),((qe=y.summary)==null?void 0:qe.scenes)&&e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Scenes generated: ",y.summary.scenes.count??0]}),((Qe=y.summary)==null?void 0:Qe.beats)&&e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Beat cards updated: ",((Ke=y.summary.beats.updated_cards)==null?void 0:Ke.length)??0]}),e.jsx(b,{sx:{display:"flex",flexDirection:"column",gap:1},children:y.steps.map(t=>e.jsxs(b,{sx:{display:"flex",justifyContent:"space-between",gap:2},children:[e.jsx(p,{variant:"body2",sx:{fontWeight:500},children:t.label}),e.jsxs(p,{variant:"body2",color:"text.secondary",children:[t.status==="completed"?"Completed":t.status==="processing"?"In progressâ¦":"Pending",t.duration_ms?` (${Math.round(t.duration_ms/100)/10}s)`:""]})]},t.id))}),y.error_message&&e.jsx(oe,{severity:"error",sx:{mt:2},children:y.error_message})]}),e.jsxs(b,{sx:{mb:4,p:3,borderRadius:2,backgroundColor:u.customTokens.wizard.instructionBox.backgroundColor,border:u.customTokens.wizard.instructionBox.border},children:[e.jsx(p,{variant:"body1",sx:{color:u.customTokens.wizard.instructionBox.textColor,lineHeight:1.6,mb:2,fontSize:"1.1rem"},children:"Turn your story idea into story beats. Your input can be just a few words or several pages of notes."}),e.jsx(p,{variant:"body2",sx:{color:u.customTokens.wizard.instructionBox.textColor,opacity:.8,lineHeight:1.6},children:"BeatBandit analyses your idea, using advanced screenwriting techniques to fill in the story beats, filling in the blanks to form a complete story outline."})]}),e.jsxs(b,{sx:{mt:2,display:"flex",flexDirection:{xs:"column",md:"row"},gap:3,mb:4},children:[e.jsxs(b,{sx:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[e.jsxs(Ge,{fullWidth:!0,children:[e.jsx(Je,{id:"style-template-select-label",children:m?"Story Form":"Story Style"}),e.jsx(Ue,{labelId:"style-template-select-label",id:"style-template-select",value:a,label:m?"Story Form":"Story Style",onChange:t=>gt(t.target.value),children:k.map(t=>e.jsx(Ye,{value:t.id,children:t.name},t.id))})]}),a&&k.length>0&&e.jsx(oe,{severity:"info",children:(()=>{const t=k.find(r=>r.id===a);return t?e.jsxs(e.Fragment,{children:[e.jsx(p,{variant:"subtitle2",gutterBottom:!0,children:t.name}),e.jsx(p,{variant:"body2",children:t.description})]}):null})()})]}),e.jsxs(b,{sx:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[e.jsx(Xe,{control:e.jsx(Ze,{checked:G,onChange:t=>ve(t.target.checked),sx:{color:u.palette.primary.main,"&.Mui-checked":{color:u.palette.primary.main}}}),label:e.jsx(p,{variant:"body1",sx:{fontWeight:500},children:"Include existing beat and character content as context"}),sx:{"& .MuiFormControlLabel-label":{ml:1}}}),e.jsx(Xe,{control:e.jsx(Ze,{checked:J,onChange:t=>Ie(t.target.checked),sx:{color:u.palette.primary.main,"&.Mui-checked":{color:u.palette.primary.main}}}),label:e.jsx(p,{variant:"body1",sx:{fontWeight:500},children:"Add missing Story Beats (append a few beats if essential)"}),sx:{"& .MuiFormControlLabel-label":{ml:1}}})]})]}),m&&e.jsxs(Ge,{fullWidth:!0,sx:{mb:3},children:[e.jsx(Je,{id:"concept-prompt-select-label",children:"Concept Prompt"}),e.jsx(Ue,{labelId:"concept-prompt-select-label",id:"concept-prompt-select",value:String(h),label:"Concept Prompt",onChange:t=>Oe(Number(t.target.value)),children:f.map((t,r)=>e.jsx(Ye,{value:String(r),children:t.name},t.id))})]}),e.jsx(Xt,{templates:f,currentTemplateIndex:h,onTemplateChange:Oe,values:d,onChange:dt,showTemplateNavigation:!m}),e.jsx(Zt,{open:P,onClose:()=>l(!1),onConfirm:pt,existingCardCount:ne.length}),M&&e.jsx(rr,{enabled:V&&!B,request:{project_name:s.name,template_id:M.id,filled_text:xe,placeholder_values:{...d},include_context:G,llmIdentifier:N==null?void 0:N.llmIdentifier,options:{style_template_id:a,add_missing_beats:J}}}),B&&e.jsx(tr,{request:B,onClose:()=>$(null),onConfirm:ut}),e.jsx(er,{isOpen:nt,onClose:ft,result:E,onViewResults:ht}),$e&&e.jsx(sr,{open:ot,onClose:()=>fe(!1),excludeLlms:xt,onImport:async t=>{if(t.mode==="fdx"){const r=new FormData;r.append("fdx_file",t.file),t.guidance&&r.append("guidance",t.guidance),r.append("replace_existing","true"),r.append("assume_scene_markers","false"),he({projectId:Z,kind:"fdx",payload:r})}else he({projectId:Z,kind:"text",payload:{content:t.screenplayText,guidance:t.guidance,replace_existing:!0,assume_scene_markers:!1}});fe(!1)},title:"Import Screenplay into Beat Wizard",description:"Paste your screenplay and we'll analyze it to seed the Beat Wizard cards with your existing story structure.",confirmLabel:"Analyze & Import",helperText:e.jsx(p,{variant:"body2",color:"text.secondary",children:"Tip: include notes or goals in the optional guidance field so the import
2can prioritize the right beats."})}),H&&e.jsx(Yt,{open:!0,autoHideDuration:6e3,onClose:Re,anchorOrigin:{vertical:"bottom",horizontal:"right"},children:e.jsx(oe,{onClose:Re,severity:H.severity,sx:{width:"100%"},children:H.message})}),e.jsx(Nt,{isVisible:w&&re!=="import-job",message:wt,subtitle:jt}),e.jsx(Ht,{visible:yt,job:y,steps:bt})]})})};export{Ts as BeatWizardStage}; 3//# sourceMappingURL=BeatWizardStage-Cyxv19FB.js.map
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.