1try{let e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="696479bc-51e5-4d24-9103-d20b3b8194cf",e._sentryDebugIdIdentifier="sentry-dbid-696479bc-51e5-4d24-9103-d20b3b8194cf")}catch(e){}"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[82759],{33721:(e,t,n)=>{n.d(t,{Df:()=>m,F9:()=>a,It:()=>f,Je:()=>h,NS:()=>p,Nq:()=>s,lw:()=>o,p7:()=>c,tq:()=>g,zw:()=>x});let a="campaignManagerIntent",r="ad-maker:campaign-manager-intent:";function l(e){return String(e||"").trim().replace(/\s+/g," ")}function s(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():"".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2))}function i(e){let t=l(e).toLowerCase();return t?t.includes("tiktok")||t.includes("tik tok")?"tiktok":t.includes("linkedin")?"linkedin":t.includes("instagram")?"instagram":t.includes("facebook")?"facebook":t.includes("youtube")?"youtube":t.includes("twitter")||/(^|[^a-z0-9])x([^a-z0-9]|$)/.test(t)?"x":null:null}function o(e){var t;return e&&"object"==typeof e?{summary:e.summary,top_hooks:Array.isArray(e.top_hooks)?e.top_hooks.slice(0,8):[],common_angles:e.common_angles,format_mix:e.format_mix,creative_playbook:Array.isArray(e.creative_playbook)?e.creative_playbook.slice(0,8):[],leading_ad_formula:null!=(t=e.leading_ad_formula)?t:null}:null}function c(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=Array.isArray(e.channels)?e.channels.slice(0,6):[],r=Array.from(new Set(a.map(e=>i(null==e?void 0:e.name)).filter(e=>!!e))),s=l(n.businessName)||"Market Research",c={sourceLabel:l(n.sourceLabel)||"Market Research: ".concat(s),business_name:s,industry:l(n.industry)||void 0,description:l(n.description)||void 0,target_audience:l(n.targetAudience)||(null==(t=e.audience)?void 0:t.summary)||void 0,market_validation_context:e,campaign_focus:{type:"ad_formula",source:"market_research_ad_intelligence"}},d=o(e.ad_intelligence);return d&&(c.ad_intelligence=d),e.advertising_costs&&(c.advertising_costs=e.advertising_costs),a.length>0&&(c.research_channels=a),r.length>0&&(c.target_platforms=r),c}function d(e,t){let n=l(null==t?void 0:t.description);return n?"".concat(e,": ").concat(n):""}function u(e){return Array.from(new Set((Array.isArray(null==e?void 0:e.channels)?e.channels:[]).map(e=>i(null==e?void 0:e.name)).filter(e=>!!e)))}function m(e,t){try{return window.sessionStorage.setItem("".concat(r).concat(e),JSON.stringify(t)),!0}catch(e){return!1}}function p(e){if(e)try{window.sessionStorage.removeItem("".concat(r).concat(e))}catch(e){}}function h(e){if(!e)return null;try{let t=window.sessionStorage.getItem("".concat(r).concat(e));if(!t)return null;let n=JSON.parse(t),a=l(n.message),s=n.source;if(!a||!(null==s?void 0:s.source_type))return null;return{...n,intentId:e,message:a,boardName:l(n.boardName)||"Campaign"}}catch(e){return null}}function f(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.push(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new URLSearchParams;return n.set(a,e),"campaign_manager"===t.surface&&n.set("surface","campaign_manager"),t.contextId&&n.set("contextId",t.contextId),t.from&&n.set("from",t.from),"/dashboard/tools/ad-maker?".concat(n.toString())}(t,{surface:"campaign_manager",...n}))}function g(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||"object"!=typeof t||"scratch"!==e.source_type&&"strategy_snapshot"in e&&e.strategy_snapshot)return e;let a=c(t,n);if("campaign_context"===e.source_type||"marketing_strategy"===e.source_type){var r;return{...e,strategy_snapshot:{...null!=(r=e.strategy_snapshot)?r:{},...a}}}return{source_type:"marketing_strategy",source_ref_id:"org-research-".concat(Date.now()),name:n.businessName||"Market Research",strategy_snapshot:a}}function x(e){var t;let n=l(e.businessName)||"Market Research",a=c(e.research,{businessName:n,industry:e.industry,description:e.description,targetAudience:e.targetAudience}),r=function(e,t){var n,a,r,s;let i=[d("Hook",null==e?void 0:e.hook_pattern),d("Structure",null==e?void 0:e.structure),d("Offer",null==e?void 0:e.offer),d("CTA",null==e?void 0:e.cta),d("Visual style",null==e?void 0:e.visual_style)].filter(
1Boolean),o=Array.isArray(null==t||null==(n=t.demand)?void 0:n.trending_now)?t.demand.trending_now.map(e=>l("string"==typeof e?e:null==e?void 0:e.topic)).filter(Boolean).slice(0,4):[],c=(null!=(s=null==t||null==(a=t.ad_intelligence)?void 0:a.top_hooks)?s:[]).slice(0,3).map((e,t)=>{let n=l((null==e?void 0:e.hook)||(null==e?void 0:e.text));return n?"".concat(t+1,". ").concat(n):""}).filter(Boolean);return["Build campaign creative using our market's proven ad formula from market research.",i.length>0?"Leading ad formula:\n".concat(i.join("\n")):"",c.length>0?"Top-performing hooks in our market:\n".concat(c.join("\n")):"",o.length>0?"What's trending now: ".concat(o.join(", "),"."):"",(null==t||null==(r=t.ad_intelligence)?void 0:r.format_mix)?"Preferred format mix from research: ".concat(l(t.ad_intelligence.format_mix),"."):"",u(t).length>0?"Focus on platforms our research identified: ".concat(u(t).join(", "),"."):"","Ground every headline, body copy, and visual in this research â adapt hooks and angles, do not invent generic filler."].filter(Boolean).join("\n\n")}(null==(t=e.research.ad_intelligence)?void 0:t.leading_ad_formula,e.research),i=s(),o=e.campaignContextId?{source_type:"campaign_context",source_ref_id:e.campaignContextId,campaign_context_id:e.campaignContextId,name:n,strategy_snapshot:a}:{source_type:"marketing_strategy",source_ref_id:"market-research-".concat(i),name:n,strategy_snapshot:a};return{token:i,intent:{version:1,boardName:"".concat(n," â ad formula campaign"),message:r,source:o,handoffSource:"market-research"}}}},38853:(e,t,n)=>{n.d(t,{B:()=>a});let a={suspense:!1}},45719:(e,t,n)=>{function a(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;return Array.isArray(e)?e.map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0).slice(0,t):[]}function l(e,t){var n,l,s,i,o;let c=null!=(n=e.audience)?n:{},d=null!=(l=e.voice_of_customer)?l:{},u=null!=(s=e.competitor_landscape)?s:{},m=null!=(i=e.content_strategy)?i:{},p=null!=(o=e.demand)?o:{},h=(Array.isArray(c.segments)?c.segments:[]).map(e=>{let t=a(null==e?void 0:e.name),n=a(null==e?void 0:e.description);return t||n?{name:null!=t?t:"Segment",description:null!=n?n:"",demographics:a(null==e?void 0:e.demographics),psychographics:a(null==e?void 0:e.psychographics),jobsToBeDone:r(null==e?void 0:e.jobs_to_be_done,4),whereToReach:r(null==e?void 0:e.where_to_reach,5),willingnessToPay:a(null==e?void 0:e.willingness_to_pay)}:null}).filter(e=>null!==e).slice(0,4),f=h.slice(0,3).map(e=>({name:e.name,description:e.description,needs:e.jobsToBeDone,channels:e.whereToReach})),g=(Array.isArray(u.competitors)?u.competitors:[]).map(e=>{let t=a(null==e?void 0:e.name);return t?{name:t,websiteUrl:a(null==e?void 0:e.website_url),usp:a(null==e?void 0:e.positioning),weaknesses:a(null==e?void 0:e.weaknesses)}:null}).filter(e=>null!==e).slice(0,5),x=(Array.isArray(e.channels)?e.channels:[]).map(e=>a(null==e?void 0:e.name)).filter(e=>!!e),b=Array.from(new Set([...r(c.primary_channels,6),...x])).slice(0,8),y=(Array.isArray(e.opportunities)?e.opportunities:[]).map(e=>a(null==e?void 0:e.title)).filter(e=>!!e);return{analysedAt:t?new Date(t).toISOString():void 0,differentiationPoints:[],marketGaps:y.length>0?y.slice(0,3).join("; "):void 0,customerQuestions:r(d.common_questions,6).length?r(d.common_questions,6):r(p.customer_questions,6),personaSeeds:f,topCompetitors:g,audienceSummary:a(c.summary),audienceSegments:h,primaryChannels:b,customerLoves:r(d.loves,6),customerComplaints:r(d.complaints,6),unmetNeeds:r(d.unmet_needs,6),marketSizing:function(e){let t=[(null==e?void 0:e.tam)?"TAM ".concat(e.tam):"",(null==e?void 0:e.sam)?"SAM ".concat(e.sam):"",(null==e?void 0:e.som)?"SOM ".concat(e.som):""].filter(Boolean);return t.length>0?t.join(" \xb7 "):void 0}(e.market_sizing),contentPillars:r(m.pillars,6),source:"research"}}function s(e,t){var n,l,s;let i=null!=(n=e.usp)?n:{},o=null!=(l=e.competitors)?l:{},c=null!=(s=e.demand)?s:{},d=[...Array.isArray(o.identified_competitors)?o.identified_competitors:[],...Array.isArray(o.additional_competitors)?o.additional_competitors:[]].map(e=>{let t=a(null==e?void 0:e.name);return t?{name:t,websiteUrl:a(null==e?void 0:e.website_url),usp:a(null==e?void 0:e.usp),weaknesses:a(null==e?void 0:e.weaknesses),pricePositioning:a(null==e?void 0:e.price_positioning)}:null}).filter(e=>null!==e).slice(0,5),u=(Array.isArray(e.audience_personas)?e.audie
1nce_personas:[]).map(e=>{let t=a(null==e?void 0:e.name),n=a(null==e?void 0:e.description);return t||n?{name:null!=t?t:"Customer",description:null!=n?n:"",needs:r(null==e?void 0:e.needs,4),channels:r(null==e?void 0:e.channels,4)}:null}).filter(e=>null!==e).slice(0,3);return{analysedAt:t?new Date(t).toISOString():void 0,viabilityScore:"number"==typeof e.viability_score?e.viability_score:void 0,uspPrimary:a(i.primary_statement),uspPlainLanguage:a(i.plain_language_version),differentiationPoints:r(i.differentiation_points,5),marketGaps:a(o.gaps_in_market),marketTrends:a(o.market_trends),demandSummary:a(c.summary),customerQuestions:r(c.customer_questions,6),personaSeeds:u,topCompetitors:d,audienceSegments:[],primaryChannels:[],customerLoves:[],customerComplaints:[],unmetNeeds:[],contentPillars:[],source:"validation"}}function i(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:220,n="string"==typeof e?e.trim():"";return n?n.length>t?"".concat(n.slice(0,t-1),"â¦"):n:""}function o(e){var t,n,s,o;let c=[],d=(e,t)=>{Array.isArray(t)?t.length>0&&c.push("- ".concat(e,": ").concat(t.join("; "))):t&&c.push("- ".concat(e,": ").concat(t))},u=function(e){let t=[],n=(e,n)=>{Array.isArray(n)?n.length>0&&t.push("- ".concat(e,": ").concat(n.join("; "))):n&&t.push("- ".concat(e,": ").concat(n))};"number"==typeof e.viabilityScore&&n("Market viability score","".concat(e.viabilityScore,"/100")),n("USP",e.uspPrimary),n("Differentiation",e.differentiationPoints),n("Gaps in the market (positioning/messaging opportunities)",e.marketGaps),n("Market trends",e.marketTrends),n("Market sizing",e.marketSizing),n("Search demand",e.demandSummary),n("Questions customers ask",e.customerQuestions),n("Target audience",e.audienceSummary),n("Primary channels to reach buyers",e.primaryChannels),n("What customers love (voice of customer)",e.customerLoves),n("Customer complaints (voice of customer)",e.customerComplaints),n("Unmet needs to exploit",e.unmetNeeds),n("Content pillars",e.contentPillars);let a=e=>Array.isArray(e)?e:[];for(let n of a(e.audienceSegments)){let e=[n.description];n.demographics&&e.push("demographics: ".concat(n.demographics)),a(n.jobsToBeDone).length>0&&e.push("jobs: ".concat(n.jobsToBeDone.join("; "))),a(n.whereToReach).length>0&&e.push("reach via: ".concat(n.whereToReach.join(", "))),t.push('- Audience segment "'.concat(n.name,'": ').concat(e.filter(Boolean).join(" | ")).slice(0,400))}for(let n of a(e.personaSeeds)){let e=[n.description];a(n.needs).length>0&&e.push("needs: ".concat(n.needs.join("; "))),a(n.channels).length>0&&e.push("channels: ".concat(n.channels.join(", "))),t.push('- Audience persona "'.concat(n.name,'": ').concat(e.filter(Boolean).join(" | ")).slice(0,400))}for(let n of a(e.topCompetitors)){let e=[];n.usp&&e.push("their USP: ".concat(n.usp)),n.weaknesses&&e.push("weaknesses: ".concat(n.weaknesses)),n.pricePositioning&&e.push("pricing: ".concat(n.pricePositioning)),t.push('- Competitor "'.concat(n.name,'": ').concat(e.join(" | ")||"verified competitor").slice(0,400))}return 0===t.length?"":["research"===e.source?"[MARKET RESEARCH â verified insights from the org's market research. Ground audience targeting, channels, content, positioning and messaging in this data]":"[MARKET RESEARCH â verified insights from the org's market validation. Ground positioning, messaging and differentiation in this data]",...t].join("\n")}(l(e));u&&c.push(u.replace(/^\[MARKET RESEARCH[^\]]*\]\n?/,"").trim());let m=null!=(t=e.demand)?t:{};d("High-intent keywords",(Array.isArray(m.keywords)?m.keywords:[]).map(e=>{let t=i(e.keyword||e.term);if(!t)return"";let n=null!=e.volume?" vol ".concat(e.volume):"",a=i(e.intent,40);return a?"".concat(t).concat(n," (").concat(a,")"):"".concat(t).concat(n)}).filter(Boolean).slice(0,8)),d("Trending now",r(m.trending_now,6));let p=null!=(n=e.ad_intelligence)?n:{};for(let e of(d("Ad intelligence summary",a(p.summary)),d("Common angles",r(p.common_angles,6)),d("Format mix",a(p.format_mix)),(Array.isArray(p.top_hooks)?p.top_hooks:[]).slice(0,5))){let t=i(e.hook||e.text),n=i(e.hook_type||e.type,40);t&&c.push("- Proven hook".concat(n?" (".concat(n,")"):"",": ").concat(t))}for(let e of(Array.isArray(p.creative_playbook)?p.creative_playbook:[]).slice(0,5)){let t=i(e.move||e.title||e.recommendation,80),n=i(e.rationale||e.detail||e.description,160);t&&c.push("- Creative playbook: ".concat(t).concat(n?" â ".concat(n):""))}let h=null!=(s=p.leading_ad_formula)?s:{};for(let[e,t]of[["Hook pattern",h.hook_pattern],["Structure",h.structure],["Offer",h.offer],["CTA",h.cta],["Visual style",h.visual_style]]){let n=i(null==t?void 0:t.description,200);n&&c.push("- Leading ad formula â ".concat(e,": ").concat(n))}for(let t of(Array.isArray(e.ad_examples)?e.ad_examples:[]).slice(0,5)){let e=i(t.platform,24),n=i(t.text,180),a=i(t.format,40);
1if(n){let t=[e,a].filter(Boolean).join(" \xb7 ");c.push("- Competitor ad example".concat(t?" (".concat(t,")"):"",": ").concat(n))}}d("Priority channels",(Array.isArray(e.channels)?e.channels:[]).map(e=>{let t=i(e.name,60),n=i(e.why,120);return t?n?"".concat(t,": ").concat(n):t:""}).filter(Boolean).slice(0,5)),d("Market opportunities",(Array.isArray(e.opportunities)?e.opportunities:[]).map(e=>i(e.title||e.description,120)).filter(Boolean).slice(0,4));let f=null!=(o=e.advertising_costs)?o:{},g=[];for(let e of["google","meta","tiktok"]){let t=f[e];if(!t)continue;let n=i(t.range||t.cpc_range||t.median_cpc,40);n&&g.push("".concat(e,": ").concat(n))}return(d("Advertising costs",g),0===c.length)?"":["[MARKET RESEARCH â verified org research. Ground hooks, angles, formats, audience, and trending topics in this data]",...c.filter(Boolean)].join("\n")}n.d(t,{Ec:()=>l,j$:()=>o,sb:()=>s})},58750:(e,t,n)=>{n.d(t,{BK:()=>o,eu:()=>i,q5:()=>c});var a=n(80601),r=n(67277),l=n(86034),s=n(64697);let i=r.forwardRef((e,t)=>{let{className:n,...r}=e;return(0,a.jsx)(l.bL,{ref:t,className:(0,s.cn)("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",n),...r})});i.displayName=l.bL.displayName;let o=r.forwardRef((e,t)=>{let{className:n,...r}=e;return(0,a.jsx)(l._V,{ref:t,className:(0,s.cn)("aspect-square h-full w-full",n),...r})});o.displayName=l._V.displayName;let c=r.forwardRef((e,t)=>{let{className:n,...r}=e;return(0,a.jsx)(l.H4,{ref:t,className:(0,s.cn)("flex h-full w-full items-center justify-center rounded-full bg-muted",n),...r})});c.displayName=l.H4.displayName},69152:(e,t,n)=>{n.d(t,{Hc:()=>s,p_:()=>l,vt:()=>i,yo:()=>o});var a=n(26290);async function r(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=await fetch("".concat("/api/business/campaign-context").concat(e),{...n,headers:{"Content-Type":"application/json",...(0,a.vL)(),...n.headers}});if(204!==r.status){try{t=await r.json()}catch(e){throw Error("Campaign Context API error ".concat(r.status))}if(!r.ok)throw Object.assign(Error((t||{}).error||"Campaign Context API error ".concat(r.status)),{status:r.status,data:t});return t}}function l(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.includeDeleted?"?includeDeleted=1":"";return r("/".concat(t))}function s(e){return r("/".concat(encodeURIComponent(e)))}function i(e){return r("/",{method:"POST",body:JSON.stringify(e)})}function o(e,t){return r("/".concat(encodeURIComponent(e)),{method:"PATCH",body:JSON.stringify(t)})}},79087:(e,t,n)=>{n.d(t,{$i:()=>g,IY:()=>f,pA:()=>h});var a=n(73667),r=n(71407);function l(){let e=(0,a._)(["\n query getUserByKratosUserId($kratosUserId: String!) {\n getUserByKratosUserId(input: { kratosUserId: $kratosUserId }) {\n id\n }\n }\n"]);return l=function(){return e},e}function s(){let e=(0,a._)(["\n query User($id: BigInt!, $appId: BigInt!) {\n users(filter: { id: { equalTo: $id }, appId: { equalTo: $appId } }) {\n nodes {\n id\n email\n userProfiles {\n nodes {\n firstName\n lastName\n }\n }\n userRoles {\n nodes {\n role {\n roleName\n }\n }\n }\n }\n }\n }\n"]);return s=function(){return e},e}function i(){let e=(0,a._)(["\n query GetUserByCognitoSub($cognitoSub: UUID!) {\n getUserByCognitoSub(input: { cognitoSub: $cognitoSub }) {\n id\n email\n roleName\n }\n }\n"]);return i=function(){return e},e}function o(){let e=(0,a._)(["\n query GetUsersForApp($appId: BigInt!, $first: Int, $offset: Int!, $orderBy: [UsersOrderBy!]) {\n users(\n filter: { appId: { equalTo: $appId } }\n first: $first\n offset: $offset\n orderBy: $orderBy\n ) {\n nodes {\n id\n email\n cognitoSub\n kratosUserId\n identity {\n id\n traits\n createdAt\n name\n verified\n }\n userProfiles {\n nodes {\n firstName\n lastName\n }\n }
1\n userRoles {\n nodes {\n role {\n roleName\n }\n }\n }\n createdAt\n updatedAt\n }\n totalCount\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n }\n }\n"]);return o=function(){return e},e}function c(){let e=(0,a._)(["\n query Users($first: Int!, $offset: Int!) {\n users(first: $first, offset: $offset, orderBy: [CREATED_AT_DESC]) {\n nodes {\n id\n email\n userProfiles {\n nodes {\n firstName\n lastName\n }\n }\n userRoles {\n nodes {\n role {\n roleName\n }\n }\n }\n createdAt\n updatedAt\n }\n totalCount\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n }\n }\n"]);return c=function(){return e},e}function d(){let e=(0,a._)(["\n query SearchUsers($search: String) {\n usersList(filter: { email: { includesInsensitive: $search } }, first: 10) {\n id\n email\n userProfiles {\n nodes {\n firstName\n lastName\n }\n }\n }\n }\n"]);return d=function(){return e},e}function u(){let e=(0,a._)(["\n query GetCurrentUserId {\n currentUserId\n }\n"]);return u=function(){return e},e}function m(){let e=(0,a._)(["\n query SearchUsersInApp($appId: BigInt!, $first: Int, $offset: Int!, $search: String!) {\n searchUsersInApp(appId: $appId, first: $first, offset: $offset, search: $search) {\n nodes {\n id\n email\n firstName\n lastName\n roleName\n createdAt\n updatedAt\n cognitoSub\n identity {\n verified\n }\n }\n totalCount\n }\n }\n"]);return m=function(){return e},e}function p(){let e=(0,a._)(["\n query GetCurrentUserOrganizationId {\n currentOrgId\n }\n"]);return p=function(){return e},e}(0,r.J1)(l()),(0,r.J1)(s()),(0,r.J1)(i());let h=(0,r.J1)(o());(0,r.J1)(c()),(0,r.J1)(d());let f=(0,r.J1)(u());(0,r.J1)(m());let g=(0,r.J1)(p())},82759:(e,t,n)=>{n.r(t),n.d(t,{default:()=>lM});var a=n(80601),r=n(71361),l=n.n(r),s=n(37218),i=n(67361),o=n(67277),c=n(70063),d=n(50715),u=n(61998),m=n(8873),p=n(49052),h=n(74316),f=n(72896),g=n(56535),x=n(32678),b=n(52786),y=n(41009),v=n(52817),w=n(80241),j=n(24387),N=n(37392),_=n(73667),k=n(71407);function A(){let e=(0,_._)(["\n mutation CreateAdMakerBoard($name: String!, $metadata: JSON) {\n createAdMakerBoard(input: { adMakerBoard: { name: $name, metadata: $metadata } }) {\n adMakerBoard {\n id\n createdBy\n name\n metadata\n createdAt\n updatedAt\n }\n }\n }\n"]);return A=function(){return e},e}function C(){let e=(0,_._)(["\n mutation UpdateAdMakerBoard($id: UUID!, $name: String!) {\n updateAdMakerBoard(input: { id: $id, patch: { name: $name } }) {\n adMakerBoard {\n id\n name\n updatedAt\n }\n }\n }\n"]);return C=function(){return e},e}function S(){let e=(0,_._)(["\n mutation DeleteAdMakerBoard($id: UUID!) {\n deleteAdMakerBoard(input: { id: $id }) {\n adMakerBoard {\n id\n }\n }\n }\n"]);return S=function(){return e},e}function I(){let e=(0,_._)(["\n mutation CreateAdMakerAssetLibraryWithMedia($input: CreateAdMakerAssetLibraryWithMediaInput!) {\n createAdMakerAssetLibraryWithMedia(input: $input) {\n asset {\n id\n type\n name\n description\n metadata\n lastUsedAt\n createdAt\n updatedAt\n media {\n id\n assetId\n sourceUrl\n storageBucket\n s3Key\n fileName\n mimeType\n sizeBytes\n width\n height\n sortOrder\n metadata\n createdAt\n updatedAt\n }\n }\n }\n }\n"]);return I=function(){return e},e}function T(){let e=(0,_._)(["\n mutation PrepareAdMakerAssetMediaUpload($input: PrepareAdMakerAssetMediaUploadInput!) {\n prepareAdMakerAssetMediaUpload(input: $input) {\n uploadUrl\n sourceUrl\n storageBucket\n s3Key\n fileName\n mimeType\n sizeBytes\n metadata\n }\n }\n"]);return T=function(){return e},e}function M(){let e=(0,_._)(["\n mutation DeleteAdMakerAssetLibraries($input
1: DeleteAdMakerAssetLibrariesInput!) {\n deleteAdMakerAssetLibraries(input: $input) {\n deletedCount\n }\n }\n"]);return M=function(){return e},e}function R(){let e=(0,_._)(["\n mutation ReplaceAdMakerBoardState($input: ReplaceAdMakerBoardStateInput!) {\n replaceAdMakerBoardState(input: $input) {\n success\n count\n }\n }\n"]);return R=function(){return e},e}let E=(0,k.J1)(A()),U=(0,k.J1)(C()),P=(0,k.J1)(S());(0,k.J1)(I()),(0,k.J1)(T());let B=(0,k.J1)(M());function D(){let e=(0,_._)(["\n query ListAdMakerBoards($first: Int!, $offset: Int!) {\n list: adMakerBoards(first: $first, offset: $offset, orderBy: UPDATED_AT_DESC) {\n nodes {\n id\n createdBy\n name\n createdAt\n updatedAt\n }\n }\n }\n"]);return D=function(){return e},e}function z(){let e=(0,_._)(["\n query GetAdMakerBoard($boardId: UUID!) {\n detail: adMakerBoards(filter: { id: { equalTo: $boardId } }, first: 1) {\n nodes {\n id\n createdBy\n name\n metadata\n createdAt\n updatedAt\n }\n }\n }\n"]);return z=function(){return e},e}function O(){let e=(0,_._)(["\n query ListAdMakerJobs($boardId: UUID!, $first: Int!, $offset: Int!) {\n list: adMakerJobs(\n filter: { boardId: { equalTo: $boardId } }\n first: $first\n offset: $offset\n orderBy: CREATED_AT_DESC\n ) {\n nodes {\n id\n boardId\n createdBy\n status\n prompt\n analysis\n extractedContext\n plan\n outputs\n errorCode\n errorMessage\n startedAt\n completedAt\n createdAt\n updatedAt\n }\n }\n }\n"]);return O=function(){return e},e}function F(){let e=(0,_._)(["\n query ListAssetLibraries($first: Int!, $offset: Int!, $type: String) {\n list: adMakerAssetLibrary(first: $first, offset: $offset, type: $type) {\n id\n type\n name\n description\n metadata\n lastUsedAt\n createdAt\n updatedAt\n media {\n id\n assetId\n sourceUrl\n storageBucket\n s3Key\n fileName\n mimeType\n sizeBytes\n width\n height\n sortOrder\n metadata\n createdAt\n updatedAt\n }\n }\n }\n"]);return F=function(){return e},e}function L(){let e=(0,_._)(["\n query GetAdMakerBoardState($boardId: UUID!) {\n adMakerBoardState(boardId: $boardId) {\n items\n }\n }\n"]);return L=function(){return e},e}function q(){let e=(0,_._)(["\n query GetAdMakerJob($jobId: UUID!) {\n detail: adMakerJobs(filter: { id: { equalTo: $jobId } }, first: 1) {\n nodes {\n id\n boardId\n createdBy\n status\n prompt\n analysis\n extractedContext\n plan\n outputs\n errorCode\n errorMessage\n startedAt\n completedAt\n createdAt\n updatedAt\n adMakerJobEventsByJobId(orderBy: EVENT_INDEX_ASC, first: 500) {\n nodes {\n id\n jobId\n eventIndex\n eventType\n phase\n message\n detail\n payload\n durationMs\n createdAt\n }\n }\n }\n }\n }\n"]);return q=function(){return e},e}(0,k.J1)(R());let $=(0,k.J1)(D()),K=(0,k.J1)(z());(0,k.J1)(O()),(0,k.J1)(F()),(0,k.J1)(L()),(0,k.J1)(q());let W=(0,o.createContext)(null),J=(0,o.forwardRef)(function(e,t){let{children:n,minZoom:r=.1,maxZoom:l=4,dotSpacing:s=48,dotRadius:i=2,onViewportChange:c,disableBackgroundPan:d=!1}=e,u=(0,o.useRef)(null),m=(0,o.useRef)(null),p=(0,o.useRef)({x:0,y:0,zoom:1}),[h,f]=(0,o.useState)(!1),[g,x]=(0,o.useState)(!1),b=(0,o.useRef)(null),y=(0,o.useRef)(null),v=(0,o.useRef)(c);v.current=c;let w=(0,o.useCallback)(()=>{let e=p.current,t=m.current;t&&(t.style.transform="translate3d(".concat(e.x,"px, ").concat(e.y,"px, 0) scale(").concat(e.zoom,")"));let n=u.current;if(n){let t=s*e.zoom,a=Math.max(1,Math.min(i*e.zoom,2*i));n.style.backgroundImage="radial-gradient(circle, rgba(15, 23, 42, 0.2) ".concat(a,"px, transparent ").concat(a+.5,"px)"),n.style.backgroundSize="".concat(t,"px ").concat(t,"px"),n.style.backgroundPosition="".concat(e.x,"px ").concat(e.y,"px")}},[i,s]),j=(0,o.useCallback)(()=>{null===y.current&&(y.current=requestAnimationFrame(()=>{var e;y.current=null,w(),null==(e=v.current)||e.call(v,{...p.current})}))},[w]);(0,o.useEffect)(()=>()=>{null!==y.current&&cancelAnimationFrame(y.current)},[]);let N=(0,o.useCallback)(e=>{p.current=e,j()},[j]),_=(0,o.useCallback)(e=>Math.min(l,Math.max(r,e)),[r,l]),k=(0,o.useCallback)((e,t,n)=>{let a=p.current,r=_(e);if(r===a.zoom)return;let l=(t-a.x)/a.zoom,s=(n-a.y)/a.zoom;N({x:t-l*r,y:n-s*r,zoom:r})},[_,N]);(0,o.useImperativeHandle)(t,()=>({getViewport:()=>p.current,setViewport:e=>{var t,n,a;return N({x:null!=(t=e.x)?t:p.current.x,y:null!=(n=e.y)?n:p.current.y,zoom:_(null!=(a=e.zoom)?a:p.current.zoom)})},zoomBy:e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect();k(p.current.zoom*e,n.width/2,n.height/2)},resetView:()=>N({x:0,y:0,zoom:1}),getViewportCenterWorld:()=>{let e=u.current,t=p.current;if(!e)return{x:0,y:0};let n=e.getBoundingClientRect();return{x:(n.width/2-t.x)/t.zoom,y:(n.height/2-t.y)/t.zoom}}
1}),[_,N,k]);let A=(0,o.useMemo)(()=>({getViewport:()=>p.current}),[]);(0,o.useEffect)(()=>{let e=u.current;if(!e)return;let t=t=>{t.preventDefault();let n=e.getBoundingClientRect(),a=t.clientX-n.left,r=t.clientY-n.top;if(t.ctrlKey||t.metaKey){let e=Math.exp(-(.0015*t.deltaY));k(p.current.zoom*e,a,r)}else{let e=p.current;N({x:e.x-t.deltaX,y:e.y-t.deltaY,zoom:e.zoom})}};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[N,k]),(0,o.useEffect)(()=>{let e=e=>{if("Space"===e.code&&!e.repeat){let t=e.target,n=null==t?void 0:t.tagName;"INPUT"===n||"TEXTAREA"===n||null!=t&&t.isContentEditable||(x(!0),e.preventDefault())}},t=e=>{"Space"===e.code&&x(!1)};return window.addEventListener("keydown",e),window.addEventListener("keyup",t),()=>{window.removeEventListener("keydown",e),window.removeEventListener("keyup",t)}},[]);let C=(0,o.useCallback)(e=>{let t=1===e.button,n=0===e.button,a=e.target===e.currentTarget;(t||n&&(g||a&&!d))&&(e.currentTarget.setPointerCapture(e.pointerId),b.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,startViewportX:p.current.x,startViewportY:p.current.y},f(!0))},[d,g]),S=(0,o.useCallback)(e=>{let t=b.current;if(!t||t.pointerId!==e.pointerId)return;let n=e.clientX-t.startX,a=e.clientY-t.startY;N({x:t.startViewportX+n,y:t.startViewportY+a,zoom:p.current.zoom})},[N]),I=(0,o.useCallback)(e=>{let t=b.current;if(t&&t.pointerId===e.pointerId){try{e.currentTarget.releasePointerCapture(e.pointerId)}catch(e){}b.current=null,f(!1)}},[]);(0,o.useEffect)(()=>{w()},[]);let T=h?"grabbing":g?"grab":"default";return(0,a.jsx)("div",{ref:u,onPointerDown:C,onPointerMove:S,onPointerUp:I,onPointerCancel:I,style:{cursor:T},className:"relative h-full w-full select-none overflow-hidden bg-white touch-none",children:(0,a.jsx)("div",{ref:m,style:{willChange:"transform",transformOrigin:"0 0"},className:"pointer-events-none absolute left-0 top-0 h-0 w-0",children:(0,a.jsx)("div",{className:"pointer-events-auto",children:(0,a.jsx)(W.Provider,{value:A,children:n})})})})});var G=n(53825),H=n(9017),Y=n(64697);let V=(0,Y.cn)("grid h-8 w-8 place-items-center rounded-lg text-auth-ink-soft transition-colors","hover:bg-cloud-slate hover:text-midnight-logic","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue");function X(e){let{zoom:t,onZoomIn:n,onZoomOut:r,onReset:l}=e,s=Math.round(100*t);return(0,a.jsxs)("div",{className:"flex items-center gap-0.5 rounded-xl border border-auth-hairline bg-white/95 p-1 shadow-soft backdrop-blur",children:[(0,a.jsx)("button",{type:"button",onClick:r,"aria-label":"Zoom out",className:V,children:(0,a.jsx)(G.A,{className:"h-4 w-4"})}),(0,a.jsxs)("button",{type:"button",onClick:l,"aria-label":"Reset zoom to 100%",className:"min-w-[3.25rem] rounded-lg px-2 py-1.5 text-[0.78rem] font-extrabold tabular-nums text-midnight-logic transition-colors hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",children:[s,"%"]}),(0,a.jsx)("button",{type:"button",onClick:n,"aria-label":"Zoom in",className:V,children:(0,a.jsx)(d.A,{className:"h-4 w-4"})}),(0,a.jsx)("span",{"aria-hidden":!0,className:"mx-1 h-5 w-px bg-auth-hairline"}),(0,a.jsx)("button",{type:"button",onClick:l,"aria-label":"Reset view",className:V,children:(0,a.jsx)(H.A,{className:"h-4 w-4"})})]})}function Q(e){let{children:t}=e;return(0,a.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-5 z-20 flex justify-center px-4",children:(0,a.jsx)("div",{className:"pointer-events-auto flex h-14 items-center gap-1.5 rounded-2xl border border-auth-hairline bg-white/95 px-2.5 shadow-[0_12px_32px_rgba(13,14,29,0.12)] backdrop-blur",onPointerDown:e=>e.stopPropagation(),children:null!=t?t:(0,a.jsx)("span",{className:"px-3 text-[0.78rem] font-semibold text-auth-muted",children:"Tools coming soon"})})})}var Z=n(73969),ee=n(99411),et=n(69936),en=n(36480),ea=n(83154);function er(e){let{recentAssets:t,onOpenLibrary:n,onQuickAddAsset:r,disabled:l=!1}=e,[s,i]=(0,o.useState)(!1);return(0,a.jsx)(ea.Bc,{delayDuration:300,children:(0,a.jsxs)(en.AM,{open:s&&t.length>0&&!l,onOpenChange:i,children:[(0,a.jsxs)(ea.m_,{children:[(0,a.jsx)(ea.k$,{asChild:!0,children:(0,a.jsx)(en.Wv,{asChild:!0,children:(0,a.jsx)("button",{type:"button",onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),disabled:l,"aria-label":"Open asset library",className:"flex h-10 w-10 items-center justify-center rounded-lg text-charcoal-700 transition-colors hover:bg-charcoal-100 hover:text-charcoal focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:opacity-40",children:(0,a.jsx)(Z.A,{className:"h-5 w-5"})})})}),(0,a.jsx)(ea.ZI,{side:"top",children:"Asset library"})]}),(0,a.jsx)(en.hl,{side:"top",align:"center",className:"w-72 p-2",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onPointerDown:e=>e.stopPropagation(),children:(0,a.jsx)("div",{className:"grid gap-1",children:t.slice(0,5).map(e=>(0,a.jsxs)("button",{type:"button",className:"flex min-w-0 items-center gap-2 rounded-lg p-2 text-left transition hover:bg-charcoal-100",onClick:()=>{r(e),i(!1)},children:[(0,a.jsx)("span",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center overflow-hidden rounded-md bg-charcoal-100",children:e.url&&"font_reference"!==e.role?(0,a.jsx)("img",{src:e.url,alt:e.name,className:"h-full w-full object-cover"}):"font_reference"===e.role?(0,a.jsx)(ee.A,{className:"h-4 w-4 text-indigo-600"}):(0,a.jsx)(et.A,{className:"h-4 w-4 text-charcoal-400"})}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block truncate text-xs font-bold text-charcoal",children:e.name}),(0,a.jsx)("span",{className:"block truncate text-[11px] font-medium text-charcoal-500",children:e.groupName||e.role.replace("_"," ")})]})]},e.id))})})]})})}function el(e){let{onAddText:t,disabled:n=!1}=e;return(0,a.jsx)(ea.Bc,{delayDuration:300,children:(0,a.jsxs)(ea.m_,{children:[(0,a.jsx)(ea.k$,{asChild:!0,children:(0,a.jsx)("button",{type:"button",onClick:t,disabled:n,"aria-label":"Add text box to the board",className:"flex h-10 w-10 items-center justify-center rounded-lg text-charcoal-700 transition-colors hover:bg-charcoal-100 hover:text-charcoal focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:opacity-40",children:(0,a.jsx)(ee.A,{className:"h-5 w-5"})})}),(0,a.jsx)(ea.ZI,{side:"top",children:"Add text box"})]})})}var es=n(38713),ei=n(99247),eo=n(92134),ec=n(78936),ed=n(80047),eu=n(25830),em=n(78383),ep=n(81506),eh=n(61225),ef=n(78357),eg=n(59216),ex=n(51836),eb=n(69694),ey=n(29829);let ev={image:es.A,video:ei.A,audio:eo.A,pdf:ec.A,font:ee.A,doc:ed.A,spreadsheet:eu.A,presentation:em.A,archive:ep.A,code:eh.A,text:ed.A,other:ef.A},ew={image:"Image",video:"Video",audio:"Audio",pdf:"PDF",font:"Font",doc:"Document",spreadsheet:"Spreadsheet",presentation:"Presentation",archive:"Archive",code:"Code",text:"Text",other:"File"},ej={image:"bg-system-violet-20 text-system-violet",video:"bg-signal-blue-20 text-signal-blue",audio:"bg-system-violet-20 text-system-violet",pdf:"bg-red-100 text-red-700",font:"bg-indigo-100 text-indigo-700",doc:"bg-signal-blue-20 text-signal-blue",spreadsheet:"bg-emerald-100 text-emerald-700",presentation:"bg-amber-100 text-amber-700",archive:"bg-charcoal-200 text-charcoal-700",code:"bg-charcoal-200 text-charcoal-700",text:"bg-charcoal-200 text-charcoal-700",other:"bg-charcoal-200 text-charcoal-700"},eN='\n <meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src https: http: data: blob:; style-src \'unsafe-inline\' https: http:; font-src https: http: data:; media-src https: http: data:;">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n html, body { min-height: 100%; margin: 0; background: #f3f4f6; }\n img { max-width: 100%; height: auto; }\n </style>\n';function e_(e){let{item:t,className:n,children:r,onPointerDown:l,onPointerMove:s,onPointerUp:i,onPointerCancel:o,onDoubleClick:c}=e;return(0,a.jsx)("div",{"data-board-item-id":t.id,onPointerDown:l,onPointerMove:s,onPointerUp:i,onPointerCancel:o,onDoubleClick:c,style:{left:t.x,top:t.y,width:t.width,height:t.height},className:"group absolute overflow-hidden rounded-xl border border-charcoal-200 bg-white transition-shadow ".concat(n),children:r})}function ek(e){let{item:t,isEditingText:n,textDraft:r,onChangeTextDraft:l,onCommitTextEdit:s,onCancelTextEdit:i}=e;if("image"===t.kind){var o,c,d;let e=null!=(d=null==(o=t.metadata)?void 0:o.generationStatus)?d:null==(c=t.asset)?void 0:c.metadata.generationStatus;return t.src||"pending"!==e?t.src||"failed"!==e?(0,a.jsx)("div",{className:"relative h-full w-full overflow-hidden",style:{backgroundImage:"linear-gradient(45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(-45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, rgba(15,23,42,0.08) 75%), linear-gradient(-45deg, transparent 75%, rgba(15,23,42,0.08) 75%)",backgroundSize:"12px 12px",backgroundPosition:"0 0, 0 6px, 6px -6px, -6px 0"},children:t.src?(0,a.jsx)("img",{src:(0,ey.eC)(t.src),alt:t.fileName,crossOrigin:"anonymous",draggable:!1,
1className:"pointer-events-none h-full w-full object-contain"}):null}):(0,a.jsxs)("div",{className:"flex h-full w-full flex-col items-center justify-center gap-2 bg-charcoal-100 text-charcoal-500",children:[(0,a.jsx)(eg.A,{className:"h-5 w-5"}),(0,a.jsx)("span",{className:"text-xs font-medium",children:"Image generation failed"})]}):(0,a.jsxs)("div",{className:"relative flex h-full w-full items-center justify-center overflow-hidden bg-charcoal-100",children:[(0,a.jsx)("div",{className:"absolute inset-0 bg-[linear-gradient(110deg,transparent_25%,rgba(255,255,255,0.72)_45%,transparent_65%)] bg-[length:200%_100%] motion-safe:animate-shimmer-bg"}),(0,a.jsxs)("div",{className:"relative flex flex-col items-center gap-2 text-charcoal-500",children:[(0,a.jsx)(p.A,{className:"h-5 w-5 animate-spin"}),(0,a.jsx)("span",{className:"text-xs font-medium",children:"Generating imageâ¦"})]})]})}if("pdf"===t.kind)return(0,a.jsx)("div",{className:"h-full w-full bg-charcoal-100",children:(0,a.jsx)("img",{src:t.previewDataUrl,alt:"Preview of ".concat(t.fileName),draggable:!1,className:"pointer-events-none h-full w-full object-contain"})});if("video"===t.kind)return(0,a.jsx)("div",{className:"h-full w-full bg-black",children:(0,a.jsx)("video",{src:t.src,controls:!0,preload:"metadata",className:"h-full w-full object-contain"})});if("font"===t.kind)return(0,a.jsx)(eA,{item:t});if("text"===t.kind){if(n)return(0,a.jsx)("div",{className:"h-full w-full bg-white p-2",children:(0,a.jsx)("textarea",{value:r,onChange:e=>l(e.target.value),onBlur:s,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key?(e.preventDefault(),s()):"Escape"===e.key&&(e.preventDefault(),i())},autoFocus:!0,placeholder:"Add your text...",className:"h-full w-full resize-none rounded-lg border border-signal-blue/40 bg-white px-2 py-1.5 text-sm leading-relaxed text-charcoal outline-none focus:border-signal-blue"})});let e=t.text.trim();return(0,a.jsx)("div",{className:"h-full w-full bg-white p-3",children:e?(0,a.jsx)("p",{className:"h-full whitespace-pre-wrap break-words text-sm leading-relaxed text-charcoal",children:t.text}):(0,a.jsx)("p",{className:"h-full whitespace-pre-wrap break-words text-sm leading-relaxed text-charcoal-400",children:"Add your text..."})})}if("html"===t.kind){let e=function(e){let t=e.trim();return t?/<head(?:\s[^>]*)?>/i.test(t)?t.replace(/<head(?:\s[^>]*)?>/i,e=>"".concat(e).concat(eN)):/<html(?:\s[^>]*)?>/i.test(t)?t.replace(/<html(?:\s[^>]*)?>/i,e=>"".concat(e,"<head>").concat(eN,"</head>")):"<!doctype html><html><head>".concat(eN,"</head><body>").concat(t,"</body></html>"):""}(t.html);return(0,a.jsxs)("div",{className:"flex h-full w-full flex-col bg-charcoal-50",children:[(0,a.jsx)("div",{className:"shrink-0 border-b border-charcoal-200 bg-white px-4 py-3",children:(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-signal-blue-20 text-signal-blue",children:(0,a.jsx)(ex.A,{className:"h-4 w-4"})}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"text-[10px] font-bold uppercase tracking-wide text-charcoal-400",children:"Email preview"}),(0,a.jsx)("p",{className:"truncate text-sm font-bold text-charcoal",title:t.subject||t.fileName,children:t.subject||t.fileName}),t.preheader?(0,a.jsx)("p",{className:"mt-0.5 line-clamp-2 text-xs leading-4 text-charcoal-500",children:t.preheader}):null]})]})}),e?(0,a.jsx)("iframe",{title:"Preview of ".concat(t.fileName),srcDoc:e,sandbox:"",referrerPolicy:"no-referrer",tabIndex:-1,className:"pointer-events-none min-h-0 w-full flex-1 border-0 bg-white"}):(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden bg-white p-4",children:(0,a.jsx)("p",{className:"whitespace-pre-wrap text-sm leading-6 text-charcoal-600",children:t.plainText||"No HTML preview was generated for this email."})})]})}let u=(0,eb.Z3)({name:t.fileName,type:t.mimeType}),m=ev[u],h=ew[u],f=ej[u];return(0,a.jsxs)("div",{className:"flex h-full w-full flex-col p-3",children:[(0,a.jsx)("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg ".concat(f),children:(0,a.jsx)(m,{className:"h-5 w-5"})}),(0,a.jsxs)("div",{className:"mt-2 min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"truncate text-sm font-bold text-charcoal",title:t.fileName,children:t.fileName}),(0,a.jsxs)("p",{className:"mt-0.5 text-xs font-semibold text-charcoal-500",children:[h," \xb7 ",(0,eb.z3)(t.sizeBytes)]})]})]})}function eA(e){var t;let{item:n}=e,r=(null==(t=n.googleFontsHref)?void 0:t.trim())||"";(0,o.useEffect)(()=>
1{if(!r||document.querySelector('link[data-ad-maker-board-font="'.concat(n.id,'"]')))return;let e=document.createElement("link");e.rel="stylesheet",e.href=r,e.dataset.adMakerBoardFont=n.id,document.head.appendChild(e)},[r,n.id]);let l="body"===n.fontRole?"Body font":"Display font",s="body"===n.fontRole?"Body copy and supporting text.":"Headlines & display";return(0,a.jsxs)("div",{className:"flex h-full w-full flex-col justify-between bg-white p-3",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-[10px] font-bold uppercase tracking-wide text-indigo-600",children:l}),(0,a.jsx)("p",{className:"mt-1 truncate text-xl leading-tight text-charcoal",style:{fontFamily:'"'.concat(n.fontFamily,'", sans-serif')},children:n.fontFamily}),(0,a.jsx)("p",{className:"mt-2 text-sm text-charcoal-600",style:{fontFamily:'"'.concat(n.fontFamily,'", sans-serif')},children:s})]}),(0,a.jsx)("p",{className:"text-[10px] font-semibold text-charcoal-400",children:"Font reference"})]})}function eC(e){let{name:t,suppress:n}=e;return(0,a.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex justify-center px-2 pb-2 ".concat(n?"opacity-0":"opacity-0 group-hover:opacity-100"," transition-opacity"),children:(0,a.jsx)("span",{className:"max-w-full truncate rounded-md bg-midnight-logic/90 px-2 py-1 text-xs font-semibold text-white shadow-soft",children:t})})}let eS=(0,o.memo)(function(e){let{item:t,isSelected:n,interactive:r=!0,onMove:l,onSelect:s,onUpdateText:i,onInteractionStart:c,onInteractionEnd:d}=e,{getViewport:u}=function(){let e=(0,o.useContext)(W);if(!e)throw Error("useCanvasContext must be used inside <PannableCanvas>");return e}(),m=(0,o.useRef)(null),[p,h]=(0,o.useState)(!1),[f,g]=(0,o.useState)(!1),[x,b]=(0,o.useState)("text"===t.kind?t.text:""),y="text"===t.kind,v="text"===t.kind?t.text:"";(0,o.useEffect)(()=>{"text"===t.kind&&b(t.text)},[t]);let w=(0,o.useCallback)(()=>{if(!y)return;let e=x.trim();e!==v&&(null==i||i(t.id,e)),g(!1)},[v,y,t.id,i,x]),j=(0,o.useCallback)(e=>{if(!r)return;if(f)return void e.stopPropagation();if(0!==e.button)return;e.stopPropagation();let n=(null==c?void 0:c(t.id,e))===!0;e.currentTarget.setPointerCapture(e.pointerId),m.current={pointerId:e.pointerId,startClientX:e.clientX,startClientY:e.clientY,startItemX:t.x,startItemY:t.y,moved:!1,suppressClickSelect:n}},[r,f,t.id,t.x,t.y,c]),N=(0,o.useCallback)(e=>{if(!r||f)return;let n=m.current;if(!n||n.pointerId!==e.pointerId)return;let a=e.clientX-n.startClientX,s=e.clientY-n.startClientY;if(!n.moved&&Math.hypot(a,s)>4&&(n.moved=!0,h(!0)),!n.moved)return;let{zoom:i}=u();l(t.id,n.startItemX+a/i,n.startItemY+s/i)},[u,r,f,t.id,l]),_=(0,o.useCallback)(e=>{if(!r||f)return;let n=m.current;if(!n||n.pointerId!==e.pointerId)return;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch(e){}let a=!n.moved,l=n.suppressClickSelect;m.current=null,h(!1),null==d||d(),a&&!l&&s(t.id)},[r,f,t.id,d,s]),k=(0,o.useCallback)(()=>{r&&y&&(b(v),g(!0),s(t.id))},[v,r,y,t.id,s]),A=n||p?"shadow-medium":"shadow-soft hover:shadow-medium",C=r?p?"cursor-grabbing":"cursor-grab":"cursor-default";return(0,a.jsxs)(e_,{item:t,onPointerDown:j,onPointerMove:N,onPointerUp:_,onPointerCancel:_,onDoubleClick:k,className:"".concat(A," ").concat(n?"ring-2 ring-signal-blue ring-offset-2 ring-offset-charcoal-50":p?"ring-2 ring-signal-blue/40":""," ").concat(C),children:[(0,a.jsx)(ek,{item:t,isEditingText:f,textDraft:x,onChangeTextDraft:b,onCommitTextEdit:w,onCancelTextEdit:()=>{b("text"===t.kind?t.text:""),g(!1)}}),(0,a.jsx)(eC,{name:t.fileName,suppress:p})]})}),eI=[{id:"nw",className:"-left-2 -top-2 -translate-x-1/2 -translate-y-1/2",cursor:"nwse-resize"},{id:"n",className:"left-1/2 -top-2 -translate-x-1/2 -translate-y-1/2",cursor:"ns-resize"},{id:"ne",className:"right-0 -top-2 translate-x-1/2 -translate-y-1/2",cursor:"nesw-resize"},{id:"e",className:"right-0 top-1/2 translate-x-1/2 -translate-y-1/2",cursor:"ew-resize"},{id:"se",className:"right-0 bottom-0 translate-x-1/2 translate-y-1/2",cursor:"nwse-resize"},{id:"s",className:"left-1/2 bottom-0 -translate-x-1/2 translate-y-1/2",curs
1or:"ns-resize"},{id:"sw",className:"-left-2 bottom-0 -translate-x-1/2 translate-y-1/2",cursor:"nesw-resize"},{id:"w",className:"-left-2 top-1/2 -translate-x-1/2 -translate-y-1/2",cursor:"ew-resize"}];function eT(e){let{bounds:t,viewport:n,onResizeStart:r,onResize:l,onResizeEnd:s}=e,i=(0,o.useRef)(null),c=n.x+t.x*n.zoom,d=n.y+t.y*n.zoom,u=t.width*n.zoom,m=t.height*n.zoom,p=(0,o.useCallback)(()=>{i.current&&(i.current=null,s())},[s]);(0,o.useEffect)(()=>{let e=e=>{var t,a,r,s,o;let c=i.current;if(!c||c.pointerId!==e.pointerId)return;let d=(e.clientX-c.startClientX)/n.zoom,u=(e.clientY-c.startClientY)/n.zoom,m=e.shiftKey;l((t=c.handle,a=c.startBounds,r=d,s=u,o=48,m?eM(t,a,r,s,48):function(e,t,n,a,r){let l,s=eM(e,t,n,a,r),i=s.width/t.width,o=s.height/t.height;l="e"===e||"w"===e?i:"n"===e||"s"===e?o:Math.abs(i-1)>=Math.abs(o-1)?i:o;let c=Math.max(r,t.width*l),d=Math.max(r,t.height*l);var u=e,m=t,p=c,h=d;let f=m.x+m.width,g=m.y+m.height;switch(u){case"se":default:return{x:m.x,y:m.y,width:p,height:h};case"nw":return{x:f-p,y:g-h,width:p,height:h};case"ne":return{x:m.x,y:g-h,width:p,height:h};case"sw":return{x:f-p,y:m.y,width:p,height:h};case"n":return{x:m.x+(m.width-p)/2,y:g-h,width:p,height:h};case"s":return{x:m.x+(m.width-p)/2,y:m.y,width:p,height:h};case"e":return{x:m.x,y:m.y+(m.height-h)/2,width:p,height:h};case"w":return{x:f-p,y:m.y+(m.height-h)/2,width:p,height:h}}}(t,a,r,s,o)))},t=e=>{let t=i.current;t&&t.pointerId===e.pointerId&&p()};return window.addEventListener("pointermove",e),window.addEventListener("pointerup",t),window.addEventListener("pointercancel",t),()=>{window.removeEventListener("pointermove",e),window.removeEventListener("pointerup",t),window.removeEventListener("pointercancel",t)}},[p,l,n.zoom]);let h=(0,o.useCallback)((e,n)=>{0===n.button&&(n.stopPropagation(),n.preventDefault(),r(),i.current={pointerId:n.pointerId,handle:e,startClientX:n.clientX,startClientY:n.clientY,startBounds:{...t}})},[t,r]);return(0,a.jsxs)("div",{"data-board-item-handles":!0,className:"pointer-events-none absolute z-20",style:{left:c,top:d,width:u,height:m},children:[(0,a.jsx)("div",{className:"pointer-events-none absolute inset-0 rounded-xl border-2 border-signal-blue","aria-hidden":!0}),eI.map(e=>{let{id:t,className:n,cursor:r}=e;return(0,a.jsx)("div",{role:"presentation",className:"pointer-events-auto absolute ".concat(n),style:{width:10,height:10,cursor:r},onPointerDown:e=>h(t,e),children:(0,a.jsx)("div",{className:"mx-auto mt-[3px] h-4 w-4 rounded-full border-2 border-charcoal bg-white shadow-soft"})},t)})]})}function eM(e,t,n,a,r){let{x:l,y:s,width:i,height:o}=t,c=l+i,d=s+o;if(e.includes("e")&&(i=Math.max(r,i+n)),e.includes("w")){let e=Math.max(r,i-n);l=c-e,i=e}if(e.includes("s")&&(o=Math.max(r,o+a)),e.includes("n")){let e=Math.max(r,o-a);s=d-e,o=e}return{x:l,y:s,width:i,height:o}}var eR=n(65190),eE=n(17311),eU=n(50932);function eP(e){let{item:t,bounds:n,selectedCount:r=1,viewport:l,onRename:s,onDownload:i,onDelete:c,onDeleteMany:d}=e,u=r>1,[m,p]=(0,o.useState)(!1),[h,f]=(0,o.useState)(t.fileName),g=(0,o.useRef)(null),x=(0,o.useRef)(null),[b,y]=(0,o.useState)(0);(0,o.useEffect)(()=>{p(!1),f(t.fileName)},[u,t.id,t.fileName]),(0,o.useEffect)(()=>{if(m){var e,t;null==(e=g.current)||e.focus(),null==(t=g.current)||t.select()}},[m]),(0,o.useLayoutEffect)(()=>{x.current&&y(x.current.offsetWidth)},[m,h]);let v=null!=n?n:t,w=l.x+(v.x+v.width/2)*l.zoom,j=l.y+v.y*l.zoom,N=()=>{if(u)return;let e=h.trim();e&&e!==t.fileName&&s(t.id,e),p(!1)};return(0,a.jsx)("div",{ref:x,style:{left:w,top:j-10,transform:"translate(-50%, -100%) translateX(".concat(0,"px)")},className:"pointer-events-auto absolute z-30 flex items-center gap-1 rounded-xl border border-charcoal-200 bg-white px-1.5 py-1 shadow-medium",onPointerDown:e=>e.stopPropagation(),children:m&&!u?(0,a.jsx)("input",{ref:g,value:h,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),N()):"Escape"===e.key&&(e.preventDefault(),f(t.fileName),p(!1))},onBlur:N,className:"h-7 w-56 rounded-md border border-charcoal-200 bg-white px-2 text-xs font-semibold text-charcoal outline-none focus:border-signal-blue","aria-label":"Rename asset"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"max-w-[14rem] truncate px-2 text-xs font-semibold text-charcoal",title:u?"".concat(r," selected"):t.fileName,children:u?"".concat(r," selected"):t.fileName}),(0,a.jsx)("div",{className:"mx-1 h-5 w-px bg-charcoal-200"}),!u&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eB,{onClick:()=>p(!0),ariaLabel:"Rename asset",children:(0,a.jsx)(eR.A,{className:"h-4 w-4"})}),(0,a.jsx)(eB,{onClick:()=>i(t.id),ariaLabel:"Download asset",children:(0,a.jsx)(eE.A,{className:"h-4 w-4"})})]}),(0,a.jsx)(eB,{onClick:()=>
1u?null==d?void 0:d():c(t.id),ariaLabel:u?"Delete selected assets":"Delete asset",tone:"danger",children:(0,a.jsx)(eU.A,{className:"h-4 w-4"})})]})})}function eB(e){let{children:t,onClick:n,ariaLabel:r,tone:l="default"}=e;return(0,a.jsx)("button",{type:"button",onClick:n,"aria-label":r,className:"flex h-7 w-7 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue ".concat("danger"===l?"text-charcoal-700 hover:bg-red-50 hover:text-red-600":"text-charcoal-700 hover:bg-charcoal-100 hover:text-charcoal"),children:t})}var eD=n(8068),ez=n(65421);function eO(e){let{item:t,viewport:n,onChangePage:r,isPageLoading:l}=e;if(t.pageCount<=1)return null;let s=n.x+(t.x+t.width/2)*n.zoom,i=n.y+(t.y+t.height)*n.zoom,o=t.currentPage<=1,c=t.currentPage>=t.pageCount;return(0,a.jsxs)("div",{style:{left:s,top:i-12,transform:"translate(-50%, -100%)"},className:"pointer-events-auto absolute z-30 flex items-center gap-1 rounded-full border border-charcoal-200 bg-white/95 px-1 py-1 shadow-medium backdrop-blur",onPointerDown:e=>e.stopPropagation(),children:[(0,a.jsx)(eF,{onClick:()=>{o||l||r(t.id,t.currentPage-1)},disabled:o||l,ariaLabel:"Previous page",children:(0,a.jsx)(eD.A,{className:"h-4 w-4"})}),(0,a.jsxs)("span",{className:"min-w-[3.25rem] px-2 text-center text-xs font-bold tabular-nums text-charcoal",children:[t.currentPage," / ",t.pageCount]}),(0,a.jsx)(eF,{onClick:()=>{c||l||r(t.id,t.currentPage+1)},disabled:c||l,ariaLabel:"Next page",children:(0,a.jsx)(ez.A,{className:"h-4 w-4"})})]})}function eF(e){let{children:t,onClick:n,disabled:r,ariaLabel:l}=e;return(0,a.jsx)("button",{type:"button",onClick:n,disabled:r,"aria-label":l,className:"flex h-7 w-7 items-center justify-center rounded-full text-charcoal-700 transition-colors hover:bg-charcoal-100 hover:text-charcoal disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",children:t})}var eL=n(90488),eq=n(86965),e$=n(82454),eK=n(77640),eW=n(12517),eJ=n(70885),eG=n(80897),eH=n(88476),eY=n(54233),eV=n(45917),eX=n(67817),eQ=n(33889),eZ=n(14375),e0=n(26290),e1=n(61367),e2=n(85400),e5=n(95573),e4=n(64311),e3=n(69152),e8=n(49346),e6=n(45719);function e7(){let e=(0,_._)(["\n query AdMakerBusinessContext($id: BigInt!) {\n organizationalUnit(id: $id) {\n id\n name\n industry\n productService\n keyBenefit\n targetAudience\n additionalContext\n toneOfVoice\n websiteUrl\n }\n }\n"]);return e7=function(){return e},e}let e9=(0,k.J1)(e7());function te(){let{currentOrgId:e}=(0,x.x)(),[{data:t,fetching:n}]=(0,h.IT)({query:e9,variables:{id:e},pause:!e,requestPolicy:"cache-and-network"});return{context:(0,o.useMemo)(()=>{let e=null==t?void 0:t.organizationalUnit;return function(e){var t,n,a,r,l,s,i,o;if(!e)return null;let c={organizationName:null!=(t=e.name)?t:void 0,industry:null!=(n=e.industry)?n:void 0,productService:null!=(a=e.productService)?a:void 0,keyBenefit:null!=(r=e.keyBenefit)?r:void 0,targetAudience:null!=(l=e.targetAudience)?l:void 0,toneOfVoice:null!=(s=e.toneOfVoice)?s:void 0,additionalContext:null!=(i=e.additionalContext)?i:void 0,websiteUrl:null!=(o=e.websiteUrl)?o:void 0};return c.organizationName||c.industry||c.productService||c.keyBenefit||c.targetAudience||c.toneOfVoice||c.additionalContext||c.websiteUrl?c:null}(null!=e?e:null)},[null==t?void 0:t.organizationalUnit]),loading:n}}function tt(){var e;let{currentOrgId:t}=(0,x.x)(),[{data:n,fetching:a}]=(0,h.IT)({query:e8.M,variables:{orgId:t},pause:!t,requestPolicy:"cache-and-network"}),r=(0,o.useMemo)(()=>{var e,t;let a=null==n||null==(t=n.marketResearchAnalyses)||null==(e=t.nodes)?void 0:e[0],r=function(e){if(!e)return null;if("string"==typeof e)try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:null}catch(e){return null}return"object"!=typeof e||Array.isArray(e)?null:e}(null==a?void 0:a.analysisData);return null!=r?r:null},[null==n||null==(e=n.marketResearchAnalyses)?void 0:e.nodes]),l=(0,o.useMemo)(()=>r?(0,e6.j$)(r):"",[r]);return{researchData:r,formattedPrompt:l,loading:a}}function tn(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0):[]}var ta=n(83983);function tr(){let e=navigator.platform.includes("Mac")?"â":"Ctrl";return(0,a.jsxs)("span",{className:"hidden items-center gap-0.5 sm:inline-flex",children:[(0,a.jsx)("kbd",{className:"inline-flex h-4 select-none items-center rounded border border-white/25 bg-white/10 px-1 font-mono text-[9px] font-medium leading-none text-white/80",children:e}),(0,a.jsx)("kbd",{className:"inline-flex h-4 select-none items-center rounded border border-white/25 bg-white/10 px-1 font-mono text-[9px] font-medium leading-none text-white/80",children:"âµ"})]})}function tl(e){return"ad-maker:campaign-manager:draft:".concat(e)}function ts(e,t){return"ad-maker:board-chat:draft:".concat(e,":").concat(t)}function ti(e){try{var t;return null!=(t=window.localStorage.getItem(e))?t:""}catch(e){return""}}function to(e,t){try{t.trim()?window.localStorage.setItem(e,t):window.localStorage.removeItem(e)}catch(e){}}function tc(e){to(e,"")}let td=[{formatKey:"instagram_post",label:"Instagram post",platform:"instagram",width:1080,height:1080,aspectRatio:"1:1"},{formatKey:"instagram_portrait",label:"Instagram portrait post",platform:"instagram",width:1080,height:1350,aspectRatio:"4:5"},{formatKey:"instagram_story",label:"Instagram story",platform:"instagram",width:1080,height:1920,aspectRatio:"9:16"},{formatKey:"instagram_reel",label:"Instagram reel",platform:"instagram",width:1080,height:1920,aspectRatio:"9:16"},{formatKey:"facebook_feed",label:"Facebook feed",platform:"facebook",width:1200,height:628,aspectRatio:"1.91:1"},{formatKey:"facebook_square",label:"Facebook square",platform:"facebook",width:1080,height:1080,aspectRatio:"1:1"},{formatKey:"facebook_cover",label:"Facebook cover photo",platform:"facebook",width:1640,height:624,aspectRatio:"21:9"},{formatKey:"facebook_story",label:"Facebook story",platform:"facebook",width:1080,height:1920,aspectRatio:"9:16"},{formatKey:"linkedin_feed",label:"LinkedIn feed",platform:"linkedin",width:1200,height:627,aspectRatio:"1.91:1"}
1,{formatKey:"linkedin_square",label:"LinkedIn square",platform:"linkedin",width:1080,height:1080,aspectRatio:"1:1"},{formatKey:"linkedin_banner",label:"LinkedIn banner",platform:"linkedin",width:1584,height:396,aspectRatio:"4:1"},{formatKey:"x_post",label:"X post",platform:"x",width:1600,height:900,aspectRatio:"16:9"},{formatKey:"x_header",label:"X header",platform:"x",width:1500,height:500,aspectRatio:"3:1"},{formatKey:"tiktok_video",label:"TikTok",platform:"tiktok",width:1080,height:1920,aspectRatio:"9:16"},{formatKey:"youtube_thumbnail",label:"YouTube thumbnail",platform:"youtube",width:1280,height:720,aspectRatio:"16:9"},{formatKey:"youtube_banner",label:"YouTube banner",platform:"youtube",width:2560,height:1440,aspectRatio:"16:9"},{formatKey:"youtube_short",label:"YouTube short",platform:"youtube",width:1080,height:1920,aspectRatio:"9:16"},{formatKey:"pinterest_pin",label:"Pinterest pin",platform:"pinterest",width:1e3,height:1500,aspectRatio:"2:3"},{formatKey:"threads_post",label:"Threads post",platform:"threads",width:1080,height:1350,aspectRatio:"4:5"},{formatKey:"google_business_post",label:"Google Business post",platform:"google_business",width:1200,height:900,aspectRatio:"4:3"},{formatKey:"bluesky_post",label:"Bluesky post",platform:"bluesky",width:1600,height:900,aspectRatio:"16:9"}],tu=Object.fromEntries(td.map(e=>[e.formatKey,e])),tm=new Set(["visual_direction_approval","prompt_generation","image_generation"]);var tp=n(83390),th=n(62790),tf=n(45559);function tg(e){let{items:t}=e;return 0===t.length?null:(0,a.jsxs)("div",{className:"space-y-2 rounded-lg border border-charcoal-200 bg-charcoal-50 p-2.5",children:[(0,a.jsx)("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-charcoal-500",children:"Execution checklist"}),(0,a.jsx)("div",{className:"space-y-1.5",children:t.map((e,t)=>{var n,r;return(0,a.jsxs)("div",{className:"rounded-md border px-2.5 py-2 ".concat("active"===(n=e.status)?"border-blue-200 bg-blue-50":"completed"===n?"border-emerald-200 bg-emerald-50":"failed"===n?"border-red-200 bg-red-50":"repairing"===n?"border-amber-200 bg-amber-50":"border-charcoal-200 bg-white"),children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:["completed"===(r=e.status)?(0,a.jsx)(tp.A,{className:"h-4 w-4 text-emerald-600"}):"active"===r?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin text-blue-600"}):"failed"===r?(0,a.jsx)(eH.A,{className:"h-4 w-4 text-red-600"}):"repairing"===r?(0,a.jsx)(th.A,{className:"h-4 w-4 text-amber-600"}):(0,a.jsx)(tf.A,{className:"h-4 w-4 text-charcoal-400"}),(0,a.jsxs)("p",{className:"flex-1 text-xs font-medium text-charcoal",children:[t+1,". ",e.label]}),(0,a.jsx)("span",{className:"text-[10px] uppercase tracking-wide text-charcoal-500",children:e.status})]}),e.detail?(0,a.jsx)("p",{className:"mt-1 pl-6 text-[11px] text-charcoal-600",children:e.detail}):null]},e.id)})})]})}var tx=n(73e3),tb=n(26731),ty=n(58750),tv=n(33703);let tw=Object.fromEntries(e4.ALL_PLATFORMS.map(e=>[e.network,e.icon])),tj=Object.fromEntries(e4.ALL_PLATFORMS.map(e=>[e.network,e.name]));function tN(e){return String(e||"").trim().toLowerCase().replace(/-/g,"_")}function t_(e){let t=String(e.nickname||"").trim();if(t)return t;let n=String(e.username||"").trim();return n?n.startsWith("@")?n:"@".concat(n):tj[tN(e.network)]||e.network||e.id}function tk(e){let t=t_(e).replace(/^@/,""),n=t.split(/\s+/).filter(Boolean);if(n.length>=2){var a,r,l,s;return"".concat(null!=(l=null==(a=n[0])?void 0:a[0])?l:"").concat(null!=(s=null==(r=n[1])?void 0:r[0])?s:"").toUpperCase()}return t.slice(0,2).toUpperCase()||"?"}function tA(e){let{url:t,className:n}=e,[r,l]=(0,o.useState)(!1);return r?(0,a.jsx)("div",{className:(0,Y.cn)("flex shrink-0 items-center justify-center rounded-md border border-stone-200 bg-stone-100 text-stone-400",n),children:(0,a.jsx)(et.A,{className:"h-4 w-4","aria-hidden":!0})}):(0,a.jsx)("img",{src:t,alt:"",className:(0,Y.cn)("shrink-0 rounded-md border border-stone-200 object-cover",n),onError:()=>l(!0)})}function tC(e){let{accounts:t}=e;if(0===t.length)return null;let n=t.slice(0,4),r=t.length-n.length;return(0,a.jsxs)("div",{className:"flex items-center","aria-label":"".concat(t.length," account(s)"),children:[n.map((e,t)=>(0,a.jsxs)(ty.eu,{className:(0,Y.cn)("h-6 w-6 border-2 border-white bg-white",t>0&&"-ml-2"),title:"".concat(t_(e)," (").concat(e.id,")"),children:[e.profilePictureUrl?(0,a.jsx)(ty.BK,{src:e.profilePictureUrl,alt:""}):null,(0,a.jsx)(ty.q5,{className:"bg-mint text-[9px] font-semibold text-charcoal",children:tk(e)})]},e.id)),r>0?(0,a.jsxs)("span",{className:"-ml-2 flex h-6 min-w-6 items-center justify-center rounded-full border-2 border-white bg-stone-100 px-1 text-[9px] font-medium text-stone-600",children:["+",r]}):null]})}function tS(e){let{requiresConnectionSetup:t,canApprove:n,isRunning:r,accountsRefreshing:l,onConnectAccounts:s,onRefreshAccounts:i,onApprove:o,onRequestChanges:c,compact:d}=e,u=d?"h-7 flex-1 text-[11px]":"h-8 flex-1 text-xs";return t?(0,a.jsxs)("div",{className:"flex gap-1.5",children:[(0,a.jsxs)(y.$,{type:"button",className:(0,Y.cn)(u,"gap-1"),disabled:r,onClick:s,children:[(0,a.jsx)(tx.A,{className:"h-3 w-3"}),"Connect"]}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:(0,Y.cn)(d?"h-7 px-2":"h-8 px-2.5","text-xs"),disabled:r||l,onClick:i,"aria-label":"Refresh accounts",children:(0,a.jsx)(tb.A,{className:(0,Y.cn)("h-3 w-3",l&&"animate-spin")})})]}):(0,a.jsxs)("div",{className:"flex gap-1.5",children:[(0,a.jsx)(y.$,{type:"button",className:u,disabled:r||!n,onClick:o,children:"Approve"}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:u,disabled:r,onClick:c,children:"Request changes"})]})}function tI(e){var t;let{accounts:n,captionText:r,imageUrls:l,scheduledFor:s,scheduleTimeLocal:i,scheduleTimeReadable:c,timezoneLabel:d,requiresConnectionSetup:u,canApprove:m,approvalMessage:p,isRunning:h,accountsRefreshing:f,onScheduleTimeChange:g,onConnectAccounts:x,onRefreshAccounts:b,onApprove:v,onRequestChanges:w}=e,[j,N]=(0,o.useState)(!1),_=r.trim(),k=p.trim(),A=(0,o.useMemo)(()=>Array.isArray(l)?l.map(e=>
1String(e).trim()).filter(Boolean):[],[l]),C=null!=(t=A[0])?t:null,S=Math.max(0,A.length-1),I=!!(_||C),T=0===n.length?u?"No accounts connected":"No accounts matched":1===n.length?t_(n[0]):"".concat(n.length," accounts"),M={requiresConnectionSetup:u,canApprove:m,isRunning:h,accountsRefreshing:f,onConnectAccounts:x,onRefreshAccounts:b,onApprove:v,onRequestChanges:w};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"mb-2 rounded-lg border border-stone-200 bg-white p-2 shadow-sm",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsx)("p",{className:"text-xs font-semibold text-charcoal",children:"Schedule post"}),(0,a.jsxs)(y.$,{type:"button",variant:"ghost",className:"h-6 gap-0.5 px-1.5 text-[10px] text-stone-600 hover:text-charcoal",onClick:()=>N(!0),children:["Details",(0,a.jsx)(ez.A,{className:"h-3 w-3"})]})]}),I?(0,a.jsxs)("button",{type:"button",className:"mt-1.5 flex w-full gap-2 rounded-md text-left hover:bg-stone-50/80",onClick:()=>N(!0),children:[C?(0,a.jsxs)("div",{className:"relative shrink-0",children:[(0,a.jsx)(tA,{url:C,className:"h-11 w-11"}),S>0?(0,a.jsxs)("span",{className:"absolute -bottom-0.5 -right-0.5 rounded bg-stone-700 px-1 text-[8px] font-medium text-white",children:["+",S]}):null]}):null,(0,a.jsx)("p",{className:"min-w-0 flex-1 line-clamp-2 text-[11px] leading-snug text-stone-600",children:_||"No caption"})]}):null,!I&&k?(0,a.jsx)("p",{className:"mt-1.5 rounded-md bg-amber-50 px-2 py-1.5 text-[11px] leading-snug text-amber-800",children:k}):!m&&k?(0,a.jsx)("p",{className:"mt-1.5 rounded-md bg-stone-50 px-2 py-1.5 text-[11px] leading-snug text-stone-600",children:k}):null,(0,a.jsxs)("div",{className:"mt-1.5 flex items-center gap-2",children:[(0,a.jsx)(tC,{accounts:n}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"truncate text-[10px] text-stone-500",title:T,children:T}),(0,a.jsx)(tv.p,{id:"ad-maker-social-schedule-time",type:"datetime-local",value:i,onChange:e=>g(e.target.value),disabled:h,className:"mt-0.5 h-7 border-stone-200 bg-white px-2 text-[11px]","aria-label":"Scheduled time"})]})]}),(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(tS,{...M,compact:!0})})]}),(0,a.jsx)(eQ.lG,{open:j,onOpenChange:N,children:(0,a.jsxs)(eQ.Cf,{className:"max-h-[85vh] max-w-md gap-0 overflow-y-auto p-5",children:[(0,a.jsxs)(eQ.c7,{className:"border-b border-stone-100 px-4 py-3",children:[(0,a.jsx)(eQ.L3,{className:"text-base",children:"Schedule post"}),(0,a.jsx)("p",{className:"text-xs text-stone-500",children:"Review everything before you approve."})]}),(0,a.jsxs)("div",{className:"space-y-4 px-4 py-3",children:[(0,a.jsxs)("section",{children:[(0,a.jsx)("h4",{className:"text-[10px] font-medium uppercase tracking-wide text-stone-500",children:"Accounts"}),n.length>0?(0,a.jsx)("ul",{className:"mt-1.5 space-y-1",children:n.map(e=>{let t=tN(e.network),n=tw[t],r=tj[t]||e.network;return(0,a.jsxs)("li",{className:"flex items-center gap-2 rounded-md border border-stone-200 bg-stone-50/50 px-2 py-1.5",children:[(0,a.jsxs)(ty.eu,{className:"h-8 w-8 border border-stone-200 bg-white",children:[e.profilePictureUrl?(0,a.jsx)(ty.BK,{src:e.profilePictureUrl,alt:""}):null,(0,a.jsx)(ty.q5,{className:"bg-mint text-[10px] font-semibold text-charcoal",children:tk(e)})]}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"truncate text-sm font-medium text-charcoal",children:t_(e)}),(0,a.jsxs)("p",{className:"flex items-center gap-1 text-[11px] text-stone-500",children:[n?(0,a.jsx)(n,{className:"h-3 w-3","aria-hidden":!0}):null,r]}),(0,a.jsx)("p",{className:"truncate font-mono text-[10px] text-stone-400",children:e.id})]})]},e.id)})}):(0,a.jsx)("p",{className:"mt-1 text-xs text-stone-600",children:u?"No connected accounts for this platform yet.":"No accounts matched."})]}),(0,a.jsxs)("section",{children:[(0,a.jsx)("h4",{className:"text-[10px] font-medium uppercase tracking-wide text-stone-500",children:"Time"}),(0,a.jsx)(tv.p,{type:"datetime-local",value:i,onChange:e=>g(e.target.value),disabled:h,className:"mt-1.5 h-9 border-stone-200 bg-white text-sm"}),s&&c?(0,a.jsxs)("p",{className:"mt-1 text-xs text-stone-500",children:[c,d?" \xb7 ".concat(d):null]}):null]}),I?(0,a.jsxs)("section",{children:[(0,a.jsx)("h4",{className:"text-[10px] font-medium uppercase tracking-wide text-stone-500",children:"Preview"}),(0,a.jsxs)("div",{className:"mt-1.5 space-y-2",children:[C?(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(tA,{url:C,className:"aspect-square w-full max-h-72"}),S>
10?(0,a.jsxs)("span",{className:"absolute bottom-2 right-2 rounded-md bg-stone-800/90 px-2 py-0.5 text-[11px] font-medium text-white",children:["+",S," more"]}):null]}):null,_?(0,a.jsx)("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-stone-700",children:_}):(0,a.jsx)("p",{className:"text-sm italic text-stone-500",children:"No caption text"})]})]}):null,!I&&k?(0,a.jsxs)("section",{children:[(0,a.jsx)("h4",{className:"text-[10px] font-medium uppercase tracking-wide text-stone-500",children:"Status"}),(0,a.jsx)("p",{className:"mt-1.5 rounded-md bg-amber-50 px-2 py-1.5 text-sm leading-relaxed text-amber-800",children:k})]}):null]}),(0,a.jsx)("div",{className:"sticky bottom-0 border-t border-stone-100 bg-white px-4 py-3",children:(0,a.jsx)(tS,{...M})})]})})]})}function tT(e){let{open:t,onOpenChange:n,onAddPhoto:r,onContinueWithoutPhotos:l}=e;return(0,a.jsx)(eQ.lG,{open:t,onOpenChange:n,children:(0,a.jsxs)(eQ.Cf,{className:"max-w-md bg-white",children:[(0,a.jsxs)(eQ.c7,{children:[(0,a.jsx)("div",{className:"mb-2 inline-flex h-10 w-10 items-center justify-center rounded-lg border border-amber-200 bg-amber-50",children:(0,a.jsx)(et.A,{className:"h-5 w-5 text-amber-700",strokeWidth:2.5})}),(0,a.jsx)(eQ.L3,{children:"Add a photo for a better ad?"}),(0,a.jsx)(eQ.rr,{className:"text-sm leading-6 text-charcoal-600",children:"Ad Maker can create something from text alone, but ads look much better when you drag images onto the canvas or use the library and click Add to board first."})]}),(0,a.jsxs)(eQ.Es,{className:"flex-col gap-2 sm:flex-col sm:space-x-0",children:[(0,a.jsx)(y.$,{type:"button",className:"w-full",onClick:r,children:"Add a photo"}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"w-full",onClick:l,children:"Continue without photos"})]})]})})}var tM=n(82852),tR=n(57376);let tE={twitter:"x","google business":"google_business"},tU=new Set;function tP(e,t){console.log("[ad-maker][social-debug] ".concat(e),null!=t?t:{})}async function tB(e){let t=e.fontFamily.trim();if(!t)return null;try{var n,a,r;let l=null!=(r=null==(n=e.asset)?void 0:n.metadata)?r:{},s="string"==typeof l.brandName&&l.brandName.trim()?l.brandName.trim():"string"==typeof(null==(a=e.asset)?void 0:a.name)&&e.asset.name.trim()?e.asset.name.replace(new RegExp("\\s+[â-]\\s+".concat(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"$")),"").trim():"Brand",i="string"==typeof l.brandKitOrganizationId?l.brandKitOrganizationId:void 0,o=await fetch("/api/business/brand-studio/font-sheet",{method:"POST",headers:{"Content-Type":"application/json",...(0,e0.vL)()},credentials:"include",body:JSON.stringify({fontFamily:t,brandName:s,organizationId:i})}),c=await o.json().catch(()=>({}));if(!o.ok||"string"!=typeof c.url||!c.url.trim())return null;return c.url.trim()}catch(e){return console.warn("[ad-maker] Failed to create font sheet reference:",e),null}}function tD(e){var t;let n=String(e||"").trim().toLowerCase().replaceAll("-","_");return n?null!=(t=tE[n])?t:n:""}function tz(e){return Array.from(new Set((Array.isArray(e)?e:String(e||"").toLowerCase().replaceAll(" and ",",").replaceAll(" & ",",").replaceAll("&",",").replaceAll("+",",").replaceAll("/",",").replaceAll("|",",").split(",")).map(e=>tD(e)).filter(Boolean)))}function tO(e){var t,n;let a=e.map(e=>(function(e){var t,n;let a=tD(e);return null!=(n=null==(t=e4.ALL_PLATFORMS.find(e=>e.network===a))?void 0:t.name)?n:a})(e));if(0===a.length)return"social";if(1===a.length)return null!=(t=a[0])?t:"social";let r=null!=(n=a[a.length-1])?n:"social";return"".concat(a.slice(0,-1).join(", ")," and ").concat(r)}function tF(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}function tL(e){let t=String(e||"").trim();if(!t)return"the proposed time";let n=new Date(t);return Number.isNaN(n.getTime())?t:new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(n)}function tq(e,t,n){var a,r;let l=null!=(r=null!=(a=e.tenantId)?a:e.tenant_id)?r:null;return{index:t,id:e.id,network:e.network,normalizedNetwork:tD(e.network),username:e.username,nickname:e.nickname,isActive:e.isActive,accountType:e.accountType,orgId:e.orgId,accountTenantId:l,tenantMatchesRequest:n&&l?l===n:null,createdAt:e.createdAt}}function t$(e,t){return t?e.filter(e=>{var n,a;return(null!=(a=null!=(n=e.tenantId)?n:e.tenant_id)?a:null)===t}):e}function tK(e,t,n,a){var r,l;if("social_media_scheduler"!==e.stepType)return e;let s=tz(null!=(r=e.pendingOutput.platforms)?r:e.pendingOutput.platform),i=s.filter(e=>!t.includes(e)),o=s.length>0&&0===i.length;if(tP("reconciling pending social approval",{stepId:e.stepId,stepType:e.stepType,rawPlatform:e.pendingOutput.platform,requestedPlatforms:s,missingPlatforms:i,connectedNetworks:t,hasConnectedPlatform:o,previousRequiresConnectionSetup:e.requiresConnectionSetup,previousCanApprove:e.canApprove,pendingOutputRequiresConnectionSetup:e.pendingOutput.requires_connection_setup,pendingOutputCanApprove:e.pendingOutput.can_approve,hasCaptionText:!!String(e.pendingOutput.caption_text||"").trim()}),0===s.length||!o)return e;let c=tL(null!=(l=e.pendingOutput.readable_scheduled_for)?l:e.pendingOutput.scheduled_for),d=String(e.pendingOutput.caption_text||"").trim(),u=Array.isArray(e.pendingOutput.image_urls)?e.pendingOutput.image_urls.filter(e=>"string"==typeof e&&e.trim().length>0):[],m=function(e,t,n){let a=new Set(t.map(e=>tD(e))),r=t$(e,n),l=[],s=new Set;for(let e of r){let t=String(e.id||"").trim(),n=tD(e.network);!t||!a.has(n)||s.has(t)||(s.add(t),l.push(t))}return l}(n,s,a),p=!!d&&u.length>0&&m.length>0,h={...e.pendingOutput,platform:tO(s),platforms:s,missing_platforms:[],connected_social_networks:t,outstand_account_ids:m,requires_connection_setup:!1,can_approve:p,approval_message:p?"Account connected. Ready to schedule this ".concat(tO(s)," post for ").concat(c,". Approve to continue or reject with a reason."):d?0===u.length?"Account connected, but no image is attached to the post yet.":"Account connected, but no matching account is available for the selected platform.":"Account connected, but no caption content is available for the post yet."},f={...e,pendingOutput:h,requiresConnectionSetup:!1,canApprove:p,approvalMessage:String(h.approval_message)};return tP("pending social approval reconciled",{stepId:e.stepId,requestedPlatforms:s,connectedNetworks:t,nextRequiresConnectionSetup:f.requiresConnectionSetup,nextCanApprove:f.canApprove}),f}function tW(){return"".concat(Date.now().toString(36),"-").concat(Math.random().toString(36).slice(2,9))}
1function tJ(e){let{content:t}=e;return(0,a.jsx)("div",{className:"prose prose-sm max-w-none text-charcoal prose-headings:text-charcoal prose-p:my-2 prose-p:leading-relaxed prose-code:rounded-md prose-code:bg-charcoal-100/90 prose-code:px-1.5 prose-code:py-px prose-code:before:content-none prose-code:after:content-none prose-pre:bg-charcoal-100 prose-ol:my-2 prose-ul:my-2 prose-li:my-0.5",children:(0,a.jsx)(eV.oz,{remarkPlugins:[eX.A],children:t})})}function tG(e){var t,n;let{row:r}=e,[l,s]=(0,o.useState)(!1),i=!!(null==(t=r.detail)?void 0:t.trim());return(0,a.jsxs)("div",{className:"w-full max-w-[92%] rounded-md",children:[(0,a.jsxs)("button",{type:"button",disabled:!i,className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left disabled:cursor-default",onClick:()=>{i&&s(e=>!e)},children:[(0,a.jsxs)("span",{className:"min-w-0 flex-1 truncate text-xs font-medium text-stone-400 ".concat(r.active?"animate-pulse":""),children:[r.label," ",r.active?"":(n=r.durationMs)&&!(n<=0)?"".concat(Math.max(1,Math.round(n/1e3)),"s"):"0s"]}),i&&(l?(0,a.jsx)(eL.A,{className:"h-3.5 w-3.5 text-charcoal-500"}):(0,a.jsx)(eq.A,{className:"h-3.5 w-3.5 text-charcoal-500"}))]}),l&&i&&(0,a.jsx)("div",{className:"border-t border-charcoal-200 px-2.5 py-2",children:(0,a.jsx)("p",{className:"text-charcoal-700 text-xs leading-relaxed",children:r.detail})})]})}function tH(){return[{id:"welcome",role:"system",text:"Drag logo and product images onto the white canvas (or add them from the library). Chat only uses images that are on the board â not files sitting in the library alone.",seq:0}]}function tY(){return{input:"",messages:tH(),timelineRows:[],jobId:null,status:"created",currentPlan:null,stepperItems:[],eventCount:0,lastRunPrompt:"",lastRunMemory:"",lastExtractedContext:null,activeAssetContext:[],hasInjectedBusinessContext:!1,clarificationQuestions:[],clarificationIndex:0,clarificationAnswers:[],clarificationFreeText:"",pendingStepApproval:null,stepRejectionReason:"",stepRejectionTargetFrames:"",seqCursor:1,phaseRows:[]}}let tV={prompt_generation:"Write generation brief",image_generation:"Generate image",qa_review:"Review image quality",caption_writing:"Prepare post caption",social_media_scheduler:"Schedule social post",direct_video_generation:"Generate 15-second video",script_writing:"Write script",storyboard_planning:"Plan storyboard",frame_generation:"Generate frames",frame_edit:"Edit frame",image_edit:"Edit image",visual_direction_approval:"Review visual direction",storyboard_approval:"Review storyboard",transition_prompt_generation:"Write motion prompts",clip_generation:"Generate clips",video_stitching:"Assemble video",repair:"Repair output"};function tX(e){return e.replaceAll("_"," ").trim().replace(/\b\w/g,e=>e.toUpperCase())}function tQ(e,t,n){let a=e.trim().toLowerCase(),r=(t||"").trim(),l=tV[a];return!r||r.toLowerCase()===a||r.includes("_")?l||tX(a||n||"step"):r||l||tX(n||a||"step")}function tZ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,n=e.replace(/\s+/g," ").trim();return n.length<=t?n:"".concat(n.slice(0,t).trim(),"...")}function t0(e,t){let n=tZ(t,900);return n?[e.trim(),n].filter(Boolean).join("\n").split("\n").slice(-12).join("\n"):e}function t1(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function t2(e){return e?function e(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(n>5)return null;if("string"==typeof t)return t.startsWith("data:image/")||t.startsWith("data:application/")?"[data-url-omitted]":t.length>1800?"".concat(t.slice(0,1800),"..."):t;if(Array.isArray(t))return t.slice(0,20).map(t=>e(t,n+1));if(!t||"object"!=typeof t)return t;let a={};for(let[r,l]of Object.entries(t).slice(0,60)){if("input_image_data_url"===r||"input_image_matted_data_url"===r){a[r]="[data-url-omitted]";continue}a[r]=e(l,n+1)}return a}(e):null}function t5(e){var t;let n=t1(null==e||null==(t=e.metadata)?void 0:t.adMakerExtractedContext);return n||function(e){var t;if((null==e||null==(t=e.metadata)?void 0:t.brandStudioAssetKind)!=="colour-palette")return null;let n=t1(e.metadata.palette);if(!n)return null;let a=[["Primary",n.primary],["Secondary",n.secondary],["Accent",n.accent],["Backgroun
1d",n.background],["Text",n.text]].map(e=>{let[t,n]=e;return"string"==typeof n&&n.trim()?"".concat(t,": ").concat(n.trim()):""}).filter(Boolean);if(0===a.length)return null;let r="".concat(e.name||"Brand"," exact colour palette: ").concat(a.join("; "),". Use these exact hex values for on-brand adverts.");return{version:1,selection_reason:"brand_studio_colour_palette_metadata",selected_count:1,files:[{file_name:"".concat(e.fileName||e.name||"colour-palette",".txt"),mime_type:"text/plain",summary:r,raw:{palette:n,color_names:t1(e.metadata.colorNames)}}],context_summary:r,processing_summary:"Brand Studio colour palette reference â exact hex values supplied from asset metadata."}}(e)}function t4(e){if("image"===e.kind||"pdf"===e.kind||"file"===e.kind||"font"===e.kind){var t;return null!=(t=e.asset)?t:null}return null}function t3(e){return{item_id:e.item_id,asset_id:e.asset_id,file_name:e.file_name,mime_type:e.mime_type,size_bytes:e.size_bytes,selected:!0,selection_source:"chat_asset_context",asset_role:e.asset_role,asset_name:e.asset_name,asset_description:e.asset_description,asset_type:e.asset_type,asset_media_urls:e.asset_media_urls,asset_url:e.asset_url,extracted_context:e.extracted_context,board_position:e.board_position}}function t8(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.trim().length>0):[]}function t6(e){return"complete"===e||"failed"===e||"awaiting_approval"===e||"awaiting_input"===e||"awaiting_step_approval"===e}function t7(e){return"awaiting_approval"===e||"awaiting_input"===e||"awaiting_step_approval"===e}function t9(e){return{...e,chatStateById:Object.fromEntries(Object.entries(e.chatStateById).map(e=>{let[t,n]=e;return[t,{...n,currentPlan:null,lastExtractedContext:null,timelineRows:[],phaseRows:[]}]}))}}function ne(e){var t,n,r;let{boardId:l,contextId:s=null,items:i,selectedItemIds:c,itemFilesById:u,onRunningChange:m,onMaterializedBoardItems:h,onGeneratedStoryboardFrames:f,onGeneratedStoryboardTransitions:x,onGeneratedCaption:b,onGeneratedVideo:v,onClearSelection:w,onRequestOpenAssetLibrary:j,prefillPrompt:N=null,onPrefillPromptApplied:_}=e,k=(0,o.useRef)("chat-".concat(tW())),[A,C]=(0,o.useState)(!0),[S,I]=(0,o.useState)([{id:k.current,title:"Chat 1",createdAt:Date.now(),updatedAt:Date.now()}]),[T,M]=(0,o.useState)({[k.current]:tY()}),[R,E]=(0,o.useState)(k.current),[U,P]=(0,o.useState)(""),[B,D]=(0,o.useState)(tH()),[z,O]=(0,o.useState)([]),[F,L]=(0,o.useState)(!1),[q,$]=(0,o.useState)(null),[K,W]=(0,o.useState)(0),[J,G]=(0,o.useState)("created"),[H,Y]=(0,o.useState)(null),V=(0,o.useMemo)(()=>(function(e){for(let t of Array.isArray(null==e?void 0:e.steps)?null==e?void 0:e.steps:[]){let e="string"==typeof(null==t?void 0:t.type)?t.type:"";if(!tm.has(e))continue;let n=t.input&&"object"==typeof t.input?t.input:{},a=n.resolved_format&&"object"==typeof n.resolved_format?n.resolved_format:null,r="string"==typeof(null==a?void 0:a.format_key)&&a.format_key||"string"==typeof n.format_key&&n.format_key||null,l=r?tu[r]:void 0,s=n.image_size&&"object"==typeof n.image_size?n.image_size:null,i="number"==typeof(null==a?void 0:a.width)&&a.width||"number"==typeof(null==s?void 0:s.width)&&s.width||(null==l?void 0:l.width)||null,o="number"==typeof(null==a?void 0:a.height)&&a.height||"number"==typeof(null==s?void 0:s.height)&&s.height||(null==l?void 0:l.height)||null,c="string"==typeof(null==a?void 0:a.aspect_ratio)&&a.aspect_ratio||"string"==typeof n.aspect_ratio&&n.aspect_ratio||(null==l?void 0:l.aspectRatio)||null;if(r||i||c)return{formatKey:r,label:"string"==typeof(null==a?void 0:a.label)&&a.label||(null==l?void 0:l.label)||null,aspectRatio:c,width:i,height:o}}return null})(H),[H]),[X,Q]=(0,o.useState)([]),[Z,ee]=(0,o.useState)(0),[et,en]=(0,o.useState)(""),[ea,er]=(0,o.useState)(""),[el,es]=(0,o.useState)(null),[ei,eo]=(0,o.useState)([]),[ec,ed]=(0,o.useState)(!1),[eu,em]=(0,o.useState)(!1),[ep,eh]=(0,o.useState)(!1),[ef,eg]=(0,o.useState)([]),[ex,eb]=(0,o.useState)(0),[ey,ev]=(0,o.useState)([]),[ew,ej]=(0,o.useState)(""),[eN,e_]=(0,o.useState)([]),[ek,eA]=(0,o.useState)([]),[eC,eS]=(0,o.useState)(!1),[eI,eT]=(0,o.useState)(!1),[eM,eR]=(0,o.useState)(null),[eE,eU]=(0,o.useState)(""),[eP,eB]=(0,o.useState)(""),[eD,ez]=(0,o.useState)(!1),[eO,eF]=(0,o.useState)(!1),[eL,eq]=(0,o.useState)(null),[eV,eX]=(0,o.useState)(!1),e0=(0,o.useRef)(null),e4=(0,o.useRef)(null),e8=(0,o.useRef)(null),e6=(0,o.useRef)(null),e7=(0,o.useRef)(null),e9=(0,o.useRef)(null),tl=(0,o.useRef)([]),tp=(0,o.useRef)([]),th=(0,o.useRef)(null),tf=(0,o.useRef)(null),tx=(0,o.useRef)(c),tb=(0,o.useRef)(1),ty=(0,o.useRef)(-1),tv=(0,o.useRef)(new Map),tw=(0,o.useRef)(""),tj=(0,o.useRef)(!1),tN=(0,o.useRef)(new Set),t_=(0,o.useRef)(new Map),tk=(0,o.useRef)(null),tA=(0,o.useRef)(null),tC=(0,o.useRef)(()=>{}),{context:tS}=te(),{campaignContext:tE}=function(e){let[t,n]=(0,o.useState)(null),[a,r]=(0,o.useState)(!1);return(0,o.useEffect)(()=>
1{if(!e){n(null),r(!1);return}let t=!1;return r(!0),(async()=>{try{let a,r=await e3.Hc(e);if(t||!r)return;let l=r.organizationalUnitId;if(l)try{let e=await fetch("/api/business/brand-studio/kit/load?organizationId=".concat(encodeURIComponent(l)));if(e.ok){let t=await e.json();a=function(e){var t,n,a,r,l,s,i,o,c,d,u,m,p,h,f,g,x,b,y,v,w;if(!e)return;let j={};j.name=(null==(n=e.discovery)||null==(t=n.name)?void 0:t.trim())||void 0,j.archetype=(null==(a=e.strategy)?void 0:a.archetype)||void 0,j.positioning=(null==(s=e.strategy)||null==(l=s.positioning)||null==(r=l.composed)?void 0:r.trim())||void 0,j.promise=(null==(o=e.strategy)||null==(i=o.promise)?void 0:i.trim())||void 0,j.voiceDescription=(null==(d=e.verbal)||null==(c=d.voiceDescription)?void 0:c.trim())||void 0;let N=null!=(v=null==(u=e.verbal)?void 0:u.taglines)?v:[],_=null!=(w=null==(m=e.verbal)?void 0:m.selectedTaglineIndex)?w:-1,k=_>=0?null==(p=N[_])?void 0:p.text:null==(h=N[0])?void 0:h.text;j.tagline=(null==k?void 0:k.trim())||void 0;let A=tn(null==(f=e.verbal)?void 0:f.voicePersonality);A.length>0&&(j.voicePersonality=A);let C=null==(x=e.visual)||null==(g=x.colorTokens)?void 0:g.palette;if(C){let e=[C.primary,C.secondary,C.accent].map(e=>"string"==typeof e?e.trim():"").filter(Boolean);e.length>0&&(j.palette=e)}let S=tn(null==(y=e.discovery)||null==(b=y.aestheticBrief)?void 0:b.moodWords);return S.length>0&&(j.moodWords=S),j.name||j.tagline||j.archetype||j.positioning||j.promise||j.voiceDescription||j.voicePersonality||j.palette||j.moodWords?j:void 0}(null==t?void 0:t.kit)}}catch(e){console.warn("[ad-maker] Failed to load campaign brand kit:",e)}if(t)return;n(function(e,t){var n,a,r;let l=e.audience;return{contextId:e.id,campaignName:(null==(n=e.name)?void 0:n.trim())||void 0,audienceDescription:(null==l||null==(a=l.description)?void 0:a.trim())||void 0,audienceLocations:tn(null==l?void 0:l.locations),audienceInterests:tn(null==l?void 0:l.interests),seedCopy:tn(null==(r=e.keywords)?void 0:r.seeds),brand:t}}(r,a))}catch(e){console.warn("[ad-maker] Failed to load campaign context:",e),t||n(null)}finally{t||r(!1)}})(),()=>{t=!0}},[e]),{campaignContext:t,loading:a}}(s),{formattedPrompt:tV}=tt(),{user:tX}=(0,g.Z)(),{addAdMakerJob:ne,dismissAdMakerJob:nt}=(0,e1.S_)(),nn=null==tX?void 0:tX.id,na=(0,o.useMemo)(()=>(0,tM.Ep)(i,ei),[ei,i]),nr=0===Z&&!B.some(e=>"user"===e.role);(0,o.useEffect)(()=>{eX((0,tM.f5)(l))},[l]),(0,o.useEffect)(()=>{(null==N?void 0:N.trim())&&(P(N),window.requestAnimationFrame(()=>{let e=e4.current;e&&(e.focus(),e.style.height="auto",e.style.height="".concat(Math.min(e.scrollHeight,140),"px"))}),null==_||_())},[_,N]);let nl=(0,o.useCallback)(()=>{let e=tb.current;return tb.current+=1,e},[]),ns=(0,o.useCallback)(()=>({input:U,messages:B,timelineRows:z,jobId:q,status:J,currentPlan:H,stepperItems:X,eventCount:Z,lastRunPrompt:et,lastRunMemory:ea,lastExtractedContext:el,activeAssetContext:ei,hasInjectedBusinessContext:ec,clarificationQuestions:ef,clarificationIndex:ex,clarificationAnswers:ey,clarificationFreeText:ew,pendingStepApproval:eM,stepRejectionReason:eE,stepRejectionTargetFrames:eP,seqCursor:tb.current,phaseRows:Array.from(t_.current.entries())}),[ey,ew,eM,eE,eP,ex,ef,ei,H,X,Z,ec,U,q,el,et,ea,B,J,z]),ni=(0,o.useCallback)(e=>{var t,n,a,r,l;P(e.input),D(e.messages),O(e.timelineRows),$(e.jobId),G(e.status),Y(e.currentPlan),Q(e.stepperItems),ee(e.eventCount),en(e.lastRunPrompt),er(null!=(t=e.lastRunMemory)?t:""),es(t1(e.lastExtractedContext)),eo(Array.isArray(l=e.activeAssetContext)?l.map(e=>{var t;let n=t1(e);if(!n)return null;let a="string"==typeof n.item_id?n.item_id.trim():"",r="string"==typeof n.file_name?n.file_name.trim():"";if(!a||!r)return null;let l="string"==typeof n.asset_name&&n.asset_name.trim()?n.asset_name.trim():r;return{item_id:a,asset_id:"string"==typeof n.asset_id&&n.asset_id.trim()?n.asset_id.trim():null,file_name:r,mime_type:"string"==typeof n.mime_type&&n.mime_type.trim()?n.mime_type.trim():null,size_bytes:"number"==typeof n.size_bytes?n.size_bytes:null,asset_role:"string"==typeof n.asset_role&&n.asset_role.trim()?n.asset_role.trim():null,asset_name:l,asset_description:"string"==typeof n.asset_description&&n.asset_description.trim()?n.asset_description.trim():null,asset_type:"string"==typeof n.asset_type&&n.asset_type.trim()?n.asset_type.trim():null,asset_media_urls:Array.isArray(t=n.asset_media_urls)?t.filter(e=>"string"==typeof e&&e.trim().length>0):[],asset_url:"string"==typeof n.asset_url&&n.asset_url.trim()?n.asset_url.trim():null,extracted_context:t2(t1(n.extracted_context)),board_position:function(e){let t=t1(e);return{x:"number"==typeof(null==t?void 0:t.x)?t.x:0,y:"number"==typeof(null==t?void 0:t.y)?t.y:0,width:"number"==typeof(null==t?void 0:t.width)?t.width:0,height:"number"==typeof(null==t?void 0:t.height)?t.height:0}}(n.board_position),preview_url:"string"==typeof n.preview_url&&n.preview_url.trim()?n.preview_url.trim():null,added_at:"number"==typeof n.added_at?n.added_at:Date.now()}}).filter(e=>!!e):[]),ed(e.hasInjectedBusinessContext),eg(e.clarificationQuestions),eb(e.clarificationIndex),ev(e.clarificationAnswers),ej(e.clarificationFreeText),eR(null!=(n=e.pendingStepApproval)?n:null),eU(null!=(a=e.stepRejectionReason)?a:""),eB(null!=(r=e.stepRejectionTargetFrames)?r:""),tb.current=e.seqCursor,tw.current=e.jobId||"";let s=Math.max(-1,e.eventCount-1);
1ty.current=s,e.jobId&&tv.current.set(e.jobId,s),t_.current=new Map(e.phaseRows)},[]);(0,o.useEffect)(()=>{var e;tw.current=q||"",ty.current=q&&null!=(e=tv.current.get(q))?e:-1},[q]),(0,o.useEffect)(()=>{eD&&(M(e=>({...e,[R]:ns()})),I(e=>e.map(e=>e.id===R?{...e,updatedAt:Date.now()}:e)))},[R,ns,eD]),(0,o.useEffect)(()=>{var e;let t=!1;return ez(!1),tN.current=new Set,null==(e=e8.current)||e.abort(),e6.current&&(clearTimeout(e6.current),e6.current=null),(async()=>{(e=>{if(t)return;if(e){let t=e.chatStateById[e.activeChatId];if(!t)return;I(e.chatSessions),M(e.chatStateById),E(e.activeChatId),ni(t);let n=ti(ts(l,e.activeChatId));n&&n!==t.input&&P(n),ez(!0);return}let n="chat-".concat(tW()),a=tY();I([{id:n,title:"Chat 1",createdAt:Date.now(),updatedAt:Date.now()}]),M({[n]:a}),E(n),ni(a),ez(!0)})(await (0,ta.eM)(l).then(e=>e&&1===e.version&&Array.isArray(e.chatSessions)&&e.chatStateById&&"object"==typeof e.chatStateById&&"string"==typeof e.activeChatId&&e.activeChatId.trim()&&e.chatStateById[e.activeChatId]?e:null).catch(()=>null))})(),()=>{t=!0}},[ni,l]),(0,o.useEffect)(()=>{if(!l||!R||!eD)return;let e=ns(),t={...T,[R]:e},n={version:1,activeChatId:R,chatSessions:S,chatStateById:t};return e6.current&&clearTimeout(e6.current),e7.current={boardId:l,state:n},e6.current=setTimeout(()=>{e7.current=null,(0,ta.Ts)(l,t9(n)).catch(e=>{console.warn("[ad-maker] Failed to save board chat state:",e)})},750),()=>{e6.current&&clearTimeout(e6.current)}},[R,l,ns,S,T,eD]),(0,o.useEffect)(()=>()=>{e6.current&&(clearTimeout(e6.current),e6.current=null);let e=e7.current;e&&(e7.current=null,(0,ta.Ts)(e.boardId,t9(e.state)).catch(e=>{console.warn("[ad-maker] Failed to flush board chat state:",e)}))},[l]),(0,o.useEffect)(()=>{if(!l||!eD)return;e9.current=U;let e=window.setTimeout(()=>{to(ts(l,R),U)},300);return()=>window.clearTimeout(e)},[R,l,U,eD]),(0,o.useEffect)(()=>{if(!eD){e9.current=null;return}if(!l)return;let e=ts(l,R);return()=>{null!==e9.current&&to(e,e9.current)}},[R,l,eD]);let no=(0,o.useCallback)(e=>{let t=function(e,t){let n=t$(e,t),a=n.map((e,n)=>tq(e,n,t)),r=a.filter(e=>!1===e.tenantMatchesRequest);return tP("normalising accounts from Outstand",{requestTenantId:null!=t?t:null,rawAccountCount:e.length,tenantScopedAccountCount:n.length,uniqueNetworkCount:new Set(a.map(e=>e.normalizedNetwork).filter(Boolean)).size,accounts:a,tenantMismatches:r.length,tenantMismatchAccountIds:r.map(e=>e.id)}),Array.from(new Set(n.filter(e=>0!==e.isActive).map(e=>tD(e.network)).filter(Boolean)))}(e,nn);return e_(t),eA(e),eR(n=>(tP("applying connected social accounts to ad maker state",{tenantId:null!=nn?nn:null,networks:t,pendingStepApproval:n?{stepId:n.stepId,stepType:n.stepType,platform:n.pendingOutput.platform,requiresConnectionSetup:n.requiresConnectionSetup,canApprove:n.canApprove}:null}),n?tK(n,t,e,nn):n)),{networks:t,accounts:e}},[nn]),nc=(0,o.useCallback)(async()=>{tP("refreshing connected social accounts",{tenantId:nn,hasTenantId:!!nn}),eT(!0);try{let e=await (0,e2.B)({tenantId:nn,limit:100,offset:0}),t=Array.isArray(e.data)?e.data:[];return tP("Outstand listAccounts response received",{tenantId:nn,count:e.count,limit:e.limit,offset:e.offset,dataCount:t.length,accounts:t.map((e,t)=>tq(e,t,nn))}),no(t)}catch(e){return tP("Outstand listAccounts failed",{error:e instanceof Error?e.message:String(e)}),e_([]),eA([]),{networks:[],accounts:[]}}finally{eT(!1)}},[no,nn]);(0,o.useEffect)(()=>{let e=!1;return(async()=>{tP("board mounted or changed; loading connected social networks",{boardId:l});let{networks:t}=await nc();e||e_(t)})(),()=>{e=!0}},[l,nc]);let nd=(0,o.useMemo)(()=>i.filter(e=>"image"===e.kind&&!!e.asset),[i]),nu=(0,o.useMemo)(()=>(0,tM.ts)(i),[i]),nm=(0,o.useMemo)(()=>(0,tM.QX)(i),[i]),np=(0,o.useMemo)(()=>(0,tM.UZ)(i),[i]),nh=(0,o.useMemo)(()=>{let e=new Set(c);return 0===e.size?[]:nd.filter(t=>e.has(t.id))},[nd,c]),nf=(0,o.useMemo)(()=>i.map(e=>{var t;return{item:e,file:null!=(t=u.get(e.id))?t:null}}).filter(e=>!!e.file),[u,i]),ng=(0,o.useMemo)(()=>{let e=new Set(c);return 0===e.size?[]:i.filter(t=>e.has(t.id)).map(e=>{var t;return{item:e,file:null!=(t=u.get(e.id))?t:null}}).filter(e=>!!e.file)},[u,i,c]),nx=(0,o.useMemo)(()=>{let e=new Set(c);return 0===e.size?[]:i.filter(t=>e.has(t.id)&&("pdf"===t.kind||"file"===t.kind||"font"===t.kind)&&!!t.asset&&!u.has(t.id))},[u,i,c]),nb=(0,o.useMemo)(()=>{let e=new Set(c);return 0===e.size?[]:i.filter(t=>("text"===t.kind||"html"===t.kind)&&e.has(t.id)).map(e=>({item_id:e.id,text:"html"===e.kind?e.plainText:e.text,selected:!0,selection_source:"user_selected",x:e.x,y:e.y,width:e.width,height:e.height}))},[i,c]),ny=(0,o.useMemo)(()=>{let e=new Set(c);return i.flatMap(t=>{let n=t.metadata&&"object"==typeof t.metadata?t.metadata:null,a="string"==typeof(null==n?void 0:n.kind)?n.kind:"";if(!a.startsWith("storyboard_"))return[];let r="image"===t.kind||"video"===t.kind?t.src:"",l="text"===t.kind?t.text:"";return[{item_id:t.id,kind:a,selected:e.has(t.id),sequence_id:"string"==typeof(null==n?void 0:n.sequenceId)?n.sequenceId:null,run_id:"string"==typeof(null==n?void 0:n.runId)?n.runId:null,frame_index:"number"==typeof(null==n?void 0:n.frameIndex)?n.frameIndex:null,start_frame_index:"number"==typeof(null==n?void 0:n.startFrameIndex)?n.startFrameIndex:null,end_frame_index:"number"==typeof(null==n?void 0:n.endFrameIndex)?n.endFrameIndex:null,prompt:"string"==typeof(null==n?void 0:n.prompt)?n.prompt:null,title:"string"==typeof(null==n?void 0:n.title)?n.title:t.fileName,description:"string"==typeof(null==n?void 0:n.description)?n.description:null,camera:"string"==typeof(null==n?void 0:n.camera)?n.camera:null,continuity_anchor:"string"==typeof(null==n?void 0:n.continuityAnchor)?n.continuityAnchor:null,cta_moment:"string"==typeof(null==n?void 0:n.ctaMoment)?n.ctaMoment:null,narrative_purpose:"string"==typeof(null==n?void 0:n.narrativePurpose)?n.narrativePurpose:null,previous_state_continuity:"string"==typeof(null==n?void 0:n.previousStateContinuity)?n.previousStateContinuity:null,next_frame_setup:"str
1ing"==typeof(null==n?void 0:n.nextFrameSetup)?n.nextFrameSetup:null,visual_handoff:"string"==typeof(null==n?void 0:n.visualHandoff)?n.visualHandoff:null,file_name:t.fileName,image_url:"image"===t.kind?r:null,video_url:"video"===t.kind?r:null,text:l,board_position:{x:t.x,y:t.y,width:t.width,height:t.height}}]})},[i,c]);(0,o.useEffect)(()=>{let e=e0.current;e&&(e.scrollTop=e.scrollHeight)},[B,z,X]),(0,o.useEffect)(()=>{m(F)},[F,m]),(0,o.useEffect)(()=>{tx.current=c},[c]);let nv=(0,o.useCallback)(()=>{let e=th.current;e&&(th.current=null,function(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(e=>n.has(e))}(tx.current,e)&&(null==w||w()))},[w]),nw=(0,o.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";e&&D(n=>[...n,{id:tW(),role:"assistant",text:e,seq:nl(),kind:t}])},[nl]),nj=(0,o.useCallback)(e=>{Q((Array.isArray(e.steps)?e.steps:[]).map((e,t)=>{let n="string"==typeof e.type?e.type:"step",a=tQ(n,"string"==typeof e.name?e.name:void 0,"Step ".concat(t+1));return{id:"string"==typeof e.id&&e.id?e.id:"step_".concat(t+1),label:a,type:n,status:"pending"}}))},[]),nN=(0,o.useCallback)(e=>{Q(t=>{let n=t.findIndex(t=>t.id===e.id);return -1===n?[...t,e]:t.map((t,a)=>a===n?{...t,...e}:t)})},[]),n_=(0,o.useCallback)(e=>{var t,n,a,r,l,s,i,o,c;let d="string"==typeof e.job_id?e.job_id:tw.current;d&&(tw.current=d,"string"==typeof e.job_id&&$(e.job_id));let u="number"==typeof e.event_index?e.event_index:"number"==typeof e.eventIndex?e.eventIndex:null;if(null!==u){if(d){if(u<=(null!=(t=tv.current.get(d))?t:-1))return;tv.current.set(d,u)}d&&d!==tw.current||(ty.current=Math.max(ty.current,u)),ee(e=>Math.max(e,u+1))}else ee(e=>e+1);let m=!!e.from_persistence;if("job_status"===e.type){let t=e.payload&&"string"==typeof e.payload.to?e.payload.to:null;t&&(G(t),t6(t)&&(L(!1),"failed"===t&&Q(e=>e.map(e=>"active"===e.status||"repairing"===e.status?{...e,status:"failed"}:e))));return}if("phase_started"===e.type){let t=e.phase?String(e.phase):"working",n=tW();t_.current.set(t,n),O(a=>[...a,{id:n,label:t.replaceAll("_"," "),active:!0,seq:nl(),detail:"string"==typeof e.detail?e.detail:void 0,durationMs:null}]);return}if("phase_update"===e.type){let t=e.phase?String(e.phase):"working",n=t_.current.get(t);if(!n||"string"!=typeof e.detail)return;let a=e.detail;O(e=>e.map(e=>e.id===n?{...e,detail:a}:e));return}if("phase_completed"===e.type){let t=e.phase?String(e.phase):"working",a=t_.current.get(t),r=("string"==typeof(null==(n=e.payload)?void 0:n.summary_label)?e.payload.summary_label:null)||("string"==typeof e.message?e.message:null)||"completed phase";return a?(O(t=>t.map(t=>t.id===a?{...t,label:r,active:!1,durationMs:"number"==typeof e.duration_ms?e.duration_ms:null,detail:"string"==typeof e.detail?e.detail:t.detail}:t)),void t_.current.delete(t)):void O(t=>[...t,{id:"".concat(tW(),"-").concat(r),label:r,active:!1,seq:nl(),durationMs:"number"==typeof e.duration_ms?e.duration_ms:null,detail:"string"==typeof e.detail?e.detail:void 0}])}if("plan_created"===e.type){if(e.payload&&"object"==typeof e.payload){let t=e.payload;Y(t),nj(t);let n="string"==typeof t.plan_summary?t.plan_summary.trim():"",a=[n,"string"==typeof t.approval_notes?t.approval_notes.trim():"","Approve to run, or reply with plan changes in chat."].filter(Boolean).join("\n\n");n&&er(e=>t0(e,"Previous plan: ".concat(n))),m||nw(a||"Plan ready for approval.","plan")}if("string"==typeof e.detail&&e.detail.trim().length>0){let t=e.detail;O(e=>[...e,{id:"".concat(tW(),"-plan-note"),label:"planner notes",active:!1,seq:nl(),durationMs:null,detail:t}])}return}if("answer_created"===e.type){let t=e.payload&&"string"==typeof e.payload.answer&&e.payload.answer||("string"==typeof e.message?e.message:"");t&&nw(t),nv();return}if("context_extracted"===e.type){let t=t1(null==(c=e.payload)?void 0:c.extracted_context);if(t){es(t),eo(e=>(function(e,t){let n=Array.isArray(t.files)?t.files:[];if(0===e.length||0===n.length)return e;let a=new Map;return(n.forEach(e=>{var t;let n=t1(e);if(!n)return;let r="string"==typeof(null==n?void 0:n.item_id)?n.item_id.split(":")[0]:"";r&&a.set(r,[...null!=(t=a.get(r))?t:[],n])}),0===a.size)?e:e.map(e=>{var n;let r=a.get(e.item_id);return r&&0!==r.length?{...e,extracted_context:t2({version:null!=(n=t.version)?n:1,selection_reason:t.selection_reason,selected_count:r.length,files:r,context_summary:t.context_summary,processing_summary:t.processing_summary})}:e})})(e,t));let e=function(e){let t=(Array.isArray(e.files)?e.files:[]).map(e=>{var t;return null==(t=t1(e))?void 0:t.file_name}).filter(e=>"string"==typeof e&&e.trim().length>0),n="string"==typeof e.context_summary?e.context_summary:"";return[t.length>0?"Current file context: ".concat(t.slice(0,6).join(", ")):"",n?"Context summary: ".concat(n):""].filter(
1Boolean).join("\n")}(t);e&&er(t=>t0(t,e))}return}if("responder_chunk"!==e.type){if("awaiting_input"===e.type){G("awaiting_input"),L(!1);let t=function(e){let t=e.payload,n=[];if((t&&"object"==typeof t&&Array.isArray(t.questions)?t.questions:[]).forEach((e,t)=>{if(!e||"object"!=typeof e)return;let a="string"==typeof e.question?e.question.trim():"";if(!a)return;let r=(Array.isArray(e.options)?e.options:[]).map(e=>"string"==typeof e?e.trim():"").filter(Boolean).filter(e=>!e.toLowerCase().startsWith("other")).slice(0,3);n.push({id:"string"==typeof e.id&&e.id.trim().length>0?e.id:"clarify_".concat(t+1),question:a,options:r,allowFreeText:!0})}),n.length>0)return n;let a="string"==typeof e.detail?e.detail.trim():"";return a?[{id:"clarify_1",question:a,options:[],allowFreeText:!0}]:[]}(e);if(eg(t),eb(0),ev([]),ej(""),t.length>0)nw("I need a few quick clarifications before I continue. Please answer below.");else{let t="string"==typeof e.detail?e.detail:"Please provide one clarification to continue.";nw("I need one clarification before I continue:\n\n".concat(t))}return}if("awaiting_approval"===e.type){G("awaiting_approval"),L(!1),m||nw("If this plan looks good, approve it. If not, reply with changes and Iâll replan."),nv();return}if("awaiting_step_approval"===e.type){G("awaiting_step_approval"),L(!1);let t=e.payload&&"object"==typeof e.payload?e.payload:{},n=t&&"object"==typeof t.pending_output?t.pending_output:{},a="string"==typeof t.step_id?t.step_id:"step_approval",r="string"==typeof t.step_type?t.step_type:"social_media_scheduler",l={stepId:a,stepName:tQ(r,"string"==typeof t.step_name?t.step_name:void 0,"Step approval"),stepType:r,pendingOutput:n,canApprove:!!n.can_approve,requiresConnectionSetup:!!n.requires_connection_setup,approvalMessage:"string"==typeof n.approval_message&&n.approval_message||("string"==typeof e.detail?e.detail:"A step needs your approval.")};tP("received awaiting_step_approval event",{stepId:a,stepType:r,platform:n.platform,requiresConnectionSetup:l.requiresConnectionSetup,canApprove:l.canApprove,connectedSocialNetworks:eN,pendingOutputConnectedNetworks:n.connected_social_networks,approvalMessage:l.approvalMessage}),eR(tK(l,eN,ek,nn)),eU(""),eB(""),nw("social_media_scheduler"===r?"Review the schedule below, then approve or request changes.":"visual_direction_approval"===r?"Here's the creative brief for your ad. Approve to generate the image, or describe any changes below.":"One execution step is waiting for your approval.");return}if("step_started"===e.type&&"string"==typeof e.message){let t=null!=(a=e.payload)?a:{},n="string"==typeof t.step_id?t.step_id:tW(),r="string"==typeof t.step_type?t.step_type:"step",l=tQ(r,"string"==typeof t.step_name?t.step_name:"string"==typeof e.message?e.message:void 0),s="repair"===r;nN({id:n,label:l,type:r,status:s?"repairing":"active"});return}if("action_started"!==e.type){if("clip_progress"===e.type){let t=null!=(r=e.payload)?r:{},n="string"==typeof t.step_id?t.step_id:tW(),a="string"==typeof t.step_type?t.step_type:"clip_generation";nN({id:n,label:tQ(a,"string"==typeof t.step_name?t.step_name:"Generate clips"),type:a,status:"active",detail:"string"==typeof e.detail?e.detail:"string"==typeof t.detail?t.detail:void 0});return}if("image_placeholder_created"===e.type){let t=null!=(l=e.payload)?l:{},n=(0,ta.J_)(t.board_items);n.length>0&&h(n),nN({id:"string"==typeof t.step_id?t.step_id:tW(),label:tQ("image_generation","Generate image"),type:"image_generation",status:"active",detail:"Generating imageâ¦"});return}if("step_completed"===e.type&&"string"==typeof e.message){let t=null!=(s=e.payload)?s:{},n="string"==typeof t.step_id?t.step_id:tW(),a="string"==typeof t.step_type?t.step_type:"step";nN({id:n,label:tQ(a,"string"==typeof t.step_name?t.step_name:"string"==typeof e.message?e.message:void 0),type:a,status:"completed",detail:"string"==typeof e.detail?e.detail:void 0});let r=t&&"object"==typeof t.output?t.output:null,l=(0,ta.J_)(t.board_items);if(l.length>0&&h(l),"image_generation"===a&&r){let e=(Array.isArray(r.image_urls)?r.image_urls:[]).filter(e=>"string"==typeof e&&e.length>0),t="string"==typeof r.image_url?[r.image_url]:[];tl.current=e.length>0?e:t,!m&&tl.current.length>0&&(0,tR.hA)("image_ad",{count:tl.current.length})}if("script_writing"===a&&r){if(m)return;let e="string"==typeof r.script?r.script.trim():"";e&&Promise.resolve(b(e,[]))}if("frame_generation"===a&&r){if(m)return;let e=(Array.isArray(r.frames)?r.frames:[]).filter(e=>!!e&&"object"==typeof e&&!Array.isArray(e));e.length>0&&Promise.resolve(f(e,"frame_generation"))}if("frame_edit"===a&&r){if(m)return;let e=(Array.isArray(r.frames)?r.frames:[]).filter(e=>!!e&&"object"==typeof e&&!Array.isArray(e));e.length>0&&Promise.resolve(f(e,"frame_edit"))}if("transition_prompt_generation"===a&&r){if(m)return;let e=(Array.isArray(r.transitions)?r.transitions:[]).filter(e=>!!e&&"object"==typeof e&&!Array.isArray(e));e.length>0&&Promise.resolve(x(e))}if("qa_review"===a&&r){if(m)return;let e=!!r.pass,t=!!(r.exhausted_retries||r.continued_without_pass);if(e||t){let e=tl.current.filter(e=>"string"==typeof e&&e.length>0);e.length>0&&0===tp.current.length&&(tp.current=e)}}if("caption_writing"===a&&r){if(m)return;let e=!!r.skipped,t="string"==typeof r.caption_text?r.caption_text.trim():"",n="string"==typeof r.caption_source?r.caption_source:"";if(!e&&t){let e=(Array.isArray(r.image_urls)?r.image_urls:[]).filter(e=>"string"==typeof e&&e.length>0),a=e.length>0?e:tp.current;er(e=>t0(e,["Previous caption: ".concat(tZ(t,500)),a.length>
10?"Media URLs: ".concat(a.slice(0,4).join(", ")):""].filter(Boolean).join("\n"))),"selected_text_context"!==n&&Promise.resolve(b(t,a))}}if(("direct_video_generation"===a||"video_stitching"===a)&&r){if(m)return;let e="string"==typeof r.video_url?r.video_url.trim():"",t="string"==typeof r.file_name?r.file_name.trim():"";e&&(Promise.resolve(v(e,t||void 0)),(0,tR.hA)("video_ad",{step:a}))}"social_media_scheduler"===a&&(r&&er(e=>t0(e,function(e){let t=t8(e.platforms),n=t.length>0?t.join(", "):"string"==typeof e.platform?e.platform:"social",a="string"==typeof e.caption_text?tZ(e.caption_text,500):"",r=t8(e.image_urls),l="string"==typeof e.readable_scheduled_for?e.readable_scheduled_for:"string"==typeof e.scheduled_for?e.scheduled_for:"",s="string"==typeof e.scheduler_status?e.scheduler_status:"";return["Previous scheduled post: platform=".concat(n).concat(s?" status=".concat(s):"").concat(l?" scheduled_for=".concat(l):"","."),a?"Caption: ".concat(a):"",r.length>0?"Media URLs: ".concat(r.slice(0,4).join(", ")):""].filter(Boolean).join("\n")}(r))),eR(null),eU(""),eB(""));return}if("step_failed"===e.type){let t=null!=(i=e.payload)?i:{},n=(0,ta.J_)(t.board_items);n.length>0&&h(n);let a="string"==typeof t.step_id?t.step_id:tW(),r="string"==typeof t.step_type?t.step_type:"step";nN({id:a,label:tQ(r,"string"==typeof t.step_name?t.step_name:"string"==typeof e.message?e.message:void 0),type:r,status:"failed",detail:"string"==typeof t.error&&t.error||("string"==typeof e.detail?e.detail:void 0)}),"social_media_scheduler"===r&&(eR(null),eU(""),eB(""));return}if("action_completed"!==e.type){if("execution_recap"===e.type){let t=e.payload&&"string"==typeof e.payload.recap&&e.payload.recap.trim()||("string"==typeof e.detail?e.detail.trim():"")||("string"==typeof e.message?e.message.trim():"");t&&nw(t),t&&er(e=>t0(e,"Previous run recap: ".concat(t))),nv();return}if("job_complete"===e.type){G("complete"),L(!1),nv();return}if("job_failed"===e.type){let t=(0,ta.J_)(null==(o=e.payload)?void 0:o.board_items);t.length>0&&h(t);let n="string"==typeof e.detail&&e.detail.trim()?e.detail.trim():null;nw(null!=n?n:"Something went wrong â please try again."),L(!1),Q(e=>e.map(e=>"active"===e.status||"repairing"===e.status?{...e,status:"failed"}:e)),nv()}}}}},[nv,eN,nl,b,f,x,v,h,ek,nw,nj,nn,nN]),nk=(0,o.useCallback)(e=>{if(F||!e||e===R)return;let t=T[e];t&&(M(e=>({...e,[R]:ns()})),E(e),ni(t))},[R,ni,ns,T,F]),nA=(0,o.useCallback)(()=>{if(F)return;let e=S.length+1,t="chat-".concat(tW()),n=tY();M(e=>({...e,[R]:ns(),[t]:n})),I(n=>[{id:t,title:"Chat ".concat(e),createdAt:Date.now(),updatedAt:Date.now()},...n]),E(t),ni(n)},[R,ni,ns,S.length,F]),nC=(0,o.useCallback)(async()=>{var e;let t=S.map(e=>e.id),n=[...new Set(Object.values(T).map(e=>e.jobId).filter(e=>"string"==typeof e&&e.length>0))];for(let t of(null==(e=e8.current)||e.abort(),e8.current=null,n))nt(t);try{for(let e of(await (0,ta.Cq)(l,{chatIds:t,jobIds:n})))nt(e)}catch(e){console.warn("[ad-maker] Failed to cancel jobs for cleared chats:",e)}let a="chat-".concat(tW()),r=tY(),s=[{id:a,title:"Chat 1",createdAt:Date.now(),updatedAt:Date.now()}],i={[a]:r};for(let e of((0,ta.Ts)(l,t9({version:1,activeChatId:a,chatSessions:s,chatStateById:i})).catch(e=>{console.warn("[ad-maker] Failed to clear remote board chat state:",e)}),t))tc(ts(l,e));e9.current="",I(s),M(i),E(a),L(!1),ni(r)},[ni,l,S,T,nt]),nS=(0,o.useCallback)(async e=>{if(e&&!tj.current){tj.current=!0;try{var t,n,a;let r=tv.current.get(e);tw.current=e,ty.current=null!=r?r:-1;let l=await (0,ta.pC)(e);if(!l)return;if($(l.id),l.status&&G(l.status),l.prompt&&!et.trim()){let e="string"==typeof(null==(t=l.metadata)?void 0:t.display_prompt)&&l.metadata.display_prompt.trim()?l.metadata.display_prompt:l.prompt;en(l.prompt),D(t=>t.some(e=>"user"===e.role)?t:[...t,{id:"persisted-prompt-".concat(l.id),role:"user",text:e,seq:nl()}])}let s=B.some(e=>"assistant"===e.role),i=s&&null!=(n=tv.current.get(l.id))?n:-1;s||(ty.current=-1,tv.current.set(l.id,-1),ee(0),t_.current.clear(),O([]));let o=l.events.filter(e=>e.eventIndex>i);for(let e of o)n_({type:e.eventType,job_id:e.jobId,timestamp:e.createdAt,phase:e.phase,message:e.message,detail
1:e.detail,payload:e.payload,duration_ms:e.durationMs,event_index:e.eventIndex,from_persistence:!0});if(0===o.length&&(!s||t7(l.status))){let e=l.plan;if(e&&n_({type:"plan_created",job_id:l.id,timestamp:l.updatedAt,phase:"planning",message:"string"==typeof e.plan_summary?e.plan_summary:null,detail:"string"==typeof e.reasoning?e.reasoning:null,payload:e,from_persistence:!0}),"awaiting_input"===l.status){let t=Array.isArray(null==e?void 0:e.clarification_questions)?e.clarification_questions:[],n=t.length>0&&"string"==typeof(null==(a=t[0])?void 0:a.question)?String(t[0].question):"string"==typeof(null==e?void 0:e.clarification_question)?e.clarification_question:"Please provide one clarification to continue.";n_({type:"awaiting_input",job_id:l.id,timestamp:l.updatedAt,phase:"awaiting_input",message:"Clarification required",detail:n,payload:{question:n,questions:t},from_persistence:!0})}else"awaiting_approval"===l.status?n_({type:"awaiting_approval",job_id:l.id,timestamp:l.updatedAt,phase:"awaiting_approval",message:"Plan ready for approval",detail:"string"==typeof(null==e?void 0:e.approval_notes)?e.approval_notes:null,payload:{job_id:l.id},from_persistence:!0}):"failed"===l.status&&n_({type:"job_failed",job_id:l.id,timestamp:l.updatedAt,phase:"failed",message:"Job failed",detail:l.errorMessage||"Something went wrong â please try again.",payload:{error_code:l.errorCode},from_persistence:!0})}l.plan&&t7(l.status)&&Y(e=>null!=e?e:l.plan),t6(l.status)?(L(!1),e8.current=null,"failed"===l.status&&Q(e=>e.map(e=>"active"===e.status||"repairing"===e.status?{...e,status:"failed"}:e))):t7(l.status)?L(!1):L(!0)}catch(e){console.warn("[ad-maker] Failed to sync persisted job:",e)}finally{tj.current=!1}}},[n_,et,B,nl]);(0,o.useEffect)(()=>{if(!l)return;let e=!1,t=new URLSearchParams(window.location.search).get("job");return(async()=>{let n=q||t||null;if(!n){let t="".concat(l,":latest");if(tU.has(t))return;tU.add(t);let a=await (0,ta.yB)(l).catch(()=>null);if(e||!a||"complete"===a.status||"failed"===a.status)return;n=a.id,$(a.id),G(a.status),ne(l,a.id,(0,e1.nP)(a.metadata,a.prompt))}let a="".concat(l,":").concat(n);!tN.current.has(a)&&(tN.current.add(a),e||nS(n))})(),()=>{e=!0}},[ne,l,q,nS]);let nI=(0,o.useCallback)(async(e,t)=>{let n=await fetch(e,{...t,credentials:"include"}),a=await n.json().catch(()=>({}));if(!n.ok)throw Error("string"==typeof a.detail?a.detail:"string"==typeof a.error?a.error:"Request failed (".concat(n.status,")"));let r="string"==typeof a.job_id?a.job_id:"";if(!r)throw Error("Background run did not return a job id.");r!==(tw.current||q)&&(tw.current=r,ty.current=-1,tv.current.set(r,-1),ee(0));let s="string"==typeof a.display_name&&a.display_name.trim()?a.display_name.trim():void 0;return $(r),L(!0),ne(l,r,s),nS(r),a},[ne,l,q,nS]),nT="complete"===J||"failed"===J,nM=!!q&&!nT&&!t7(J)&&(F||"running"===J||"queued"===J||"created"===J);(0,o.useEffect)(()=>{tC.current=n_},[n_]),(0,o.useEffect)(()=>{var e,t;if(!q||nT){null==(e=tk.current)||e.call(tk),tk.current=null;return}let n=()=>{nS(q)},a=(0,ta.Yt)(q,null!=(t=tv.current.get(q))?t:-1,{onJob:e=>{for(let n of(e.job&&"string"==typeof e.job.status&&(G(e.job.status),("complete"===e.job.status||"failed"===e.job.status||t7(e.job.status))&&L(!1),"failed"===e.job.status&&Q(e=>e.map(e=>"active"===e.status||"repairing"===e.status?{...e,status:"failed"}:e))),Array.isArray(e.events)?e.events:[])){var t;let e="number"==typeof n.event_index?n.event_index:"number"==typeof n.eventIndex?n.eventIndex:null,a="string"==typeof n.job_id?n.job_id:q||"";a&&a===q&&(null!==e&&e<=(null!=(t=tv.current.get(a))?t:-1)||tC.current(n))}},onDone:()=>{tk.current=null,n()},onError:()=>{n(),null===tA.current&&(tA.current=window.setTimeout(()=>{tA.current=null,W(e=>e+1)},1500))}});return tk.current=a,()=>{null!==tA.current&&(window.clearTimeout(tA.current),tA.current=null),a(),tk.current===a&&(tk.current=null)}},[q,nT,K,nS]),(0,o.useEffect)(()=>{if(!nM||!q)return;let e=()=>{document.hidden||nS(q)};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[q,nM,nS]);let nR=(0,o.useCallback)(async(e,t)=>{var n,a;if(!e||F||!l)return;let r=q&&"complete"!==J&&"failed"!==J&&"created"!==J?q:null,i=nb.length>0,o=nh.length>0||i||ng.length>0||nx.length>0,d=!o&&np>0,m=nh.length>0?nh:nu,p=nx.length>0?nx:d?nm:[],h=o||d,f=ng.length>0?ng:d?nf.filter(e=>{let{item:t}=e,n=t4(t);return!n||!(0,tM.ij)(n)}):[],g=f.filter(e=>{let{item:t}=e;return!t5(t4(t))}),x=new Set(c),b=m.map(e=>{var t,n,a,r,l,s,i,o,c,m,p,h,f;let g=null!=(t=u.get(e.id))?t:null,b=null!=(n=e.asset)?n:null,y=t5(b);return{item_id:e.id,asset_id:null!=(r=null!=(a=e.assetId)?a:null==b?void 0:b.id)?r:null,file_name:(null==g?void 0:g.name)||(null==b?void 0:b.fileName)||e.fileName,mime_type:(null==g?void 0:g.type)||(null==b?void 0:b.mimeType)||null,size_bytes:null!=(s=null!=(l=null==g?void 0:g.size)?l:null==b?void 0:b.sizeBytes)?s:null,
1selected:x.has(e.id)||d,selection_source:x.has(e.id)?"user_selected":d?"board_context":"none",asset_role:null!=(i=null==b?void 0:b.role)?i:null,asset_name:null!=(o=null==b?void 0:b.name)?o:e.fileName,asset_description:null!=(c=null==b?void 0:b.description)?c:null,asset_type:null!=(m=null==b?void 0:b.role)?m:null,asset_media_urls:null!=(p=null==b?void 0:b.media.map(e=>e.sourceUrl))?p:[],asset_url:null!=(f=null!=(h=null==b?void 0:b.url)?h:e.src)?f:null,extracted_context:y,board_position:{x:e.x,y:e.y,width:e.width,height:e.height}}}),y=[...b,...f.filter(e=>{let{item:t}=e;return"image"!==t.kind}).map(e=>{var t,n,a,r,l,s,i,o,c,u,m;let{item:p,file:h}=e,f=("pdf"===p.kind||"file"===p.kind)&&null!=(t=p.asset)?t:null,g=t5(f),b=null!=(n=null==f?void 0:f.url)?n:("pdf"===p.kind||"file"===p.kind)&&p.objectUrl&&!p.objectUrl.startsWith("blob:")?p.objectUrl:null;return{item_id:p.id,asset_id:("pdf"===p.kind||"file"===p.kind)&&null!=(r=null!=(a=p.assetId)?a:null==f?void 0:f.id)?r:null,file_name:h.name||(null==f?void 0:f.fileName)||p.fileName,mime_type:h.type||(null==f?void 0:f.mimeType)||("pdf"===p.kind?"application/pdf":"file"===p.kind?p.mimeType:null),size_bytes:null!=(s=null!=(l=h.size)?l:null==f?void 0:f.sizeBytes)?s:"pdf"===p.kind||"file"===p.kind?p.sizeBytes:null,selected:x.has(p.id)||d,selection_source:x.has(p.id)?"user_selected":d?"board_context":"none",asset_role:null!=(i=null==f?void 0:f.role)?i:null,asset_name:null!=(o=null==f?void 0:f.name)?o:p.fileName,asset_description:null!=(c=null==f?void 0:f.description)?c:null,asset_type:null!=(u=null==f?void 0:f.role)?u:null,asset_media_urls:null!=(m=null==f?void 0:f.media.map(e=>e.sourceUrl))?m:[],asset_url:b,extracted_context:g,board_position:{x:p.x,y:p.y,width:p.width,height:p.height}}}),...await Promise.all(p.map(async e=>{var t,n,a,r,l,s,i,o,c,u,m;let p=null!=(t=e.asset)?t:null,h=t5(p),f="font"===e.kind?await tB(e):null,g="font"===e.kind?f:null!=(n=null==p?void 0:p.url)?n:("pdf"===e.kind||"file"===e.kind)&&e.objectUrl&&!e.objectUrl.startsWith("blob:")?e.objectUrl:null,b=[...f?[f]:[],..."font"===e.kind?[]:null!=(a=null==p?void 0:p.media.map(e=>e.sourceUrl))?a:[]];return{item_id:e.id,asset_id:null!=(l=null!=(r=e.assetId)?r:null==p?void 0:p.id)?l:null,file_name:"font"===e.kind&&f?"".concat(e.fontFamily.toLowerCase().replaceAll(" ","-"),"-").concat(e.fontRole,"-font-sheet.png"):(null==p?void 0:p.fileName)||e.fileName,mime_type:"font"===e.kind&&f?"image/png":(null==p?void 0:p.mimeType)||("pdf"===e.kind?"application/pdf":"file"===e.kind?e.mimeType:"application/x-ad-maker-font-reference"),size_bytes:null!=(s=null==p?void 0:p.sizeBytes)?s:"pdf"===e.kind||"file"===e.kind?e.sizeBytes:null,selected:x.has(e.id)||d,selection_source:x.has(e.id)?"user_selected":d?"board_context":"none",asset_role:null!=(i=null==p?void 0:p.role)?i:null,asset_name:null!=(o=null==p?void 0:p.name)?o:e.fileName,asset_description:"font"===e.kind?"".concat(null!=(c=null==p?void 0:p.description)?c:"Font reference for ".concat(e.fontFamily,".")," Use the attached font sheet as the source of truth for ").concat(e.fontRole," typography in generated ads."):null!=(u=null==p?void 0:p.description)?u:null,asset_type:null!=(m=null==p?void 0:p.role)?m:null,asset_media_urls:b,asset_url:g,extracted_context:h,board_position:{x:e.x,y:e.y,width:e.width,height:e.height}}}))],v=y.map(e=>{var t,n,a;return a=null!=(n=null!=(t=e.asset_url)?t:e.asset_media_urls[0])?n:null,e.asset_id||e.asset_url||e.asset_media_urls.length>0||e.extracted_context?{item_id:e.item_id,asset_id:e.asset_id,file_name:e.file_name,mime_type:e.mime_type,size_bytes:e.size_bytes,asset_role:e.asset_role,asset_name:e.asset_name||e.file_name,asset_description:e.asset_description,asset_type:e.asset_type,asset_media_urls:e.asset_media_urls,asset_url:e.asset_url,extracted_context:t2(e.extracted_context),board_position:e.board_position,preview_url:a,added_at:Date.now()}:null}).filter(e=>!!e),w=h?function(e,t){let n=new Map;return e.forEach(e=>n.set(e.asset_id||e.item_id,e)),t.forEach(e=>{var t,a;let r=e.asset_id||e.item_id;n.set(r,{...n.get(r),...e,added_at:null!=(a=null==(t=n.get(r))?void 0:t.added_at)?a:e.added_at})}),Array.from(n.values()).slice(-12)}(ei,v):ei,j=new Set(y.map(e=>e.asset_id||e.item_id)),N=[...y,...w.filter(e=>!j.has(e.asset_id||e.item_id)).map(t3)],_=[nh.length>0?"Manually selected now image(s): ".concat(nh.map(e=>{var t;return(null==(t=e.asset)?void 0:t.name)||e.fileName}
1).filter(Boolean).join(", "),". If the user says selected image/current image/this image, they mean these asset(s), not older chat assets."):d?"Board brand context: ".concat([...nu.map(e=>{var t;return(null==(t=e.asset)?void 0:t.name)||e.fileName}),...nm.map(e=>{var t;return"font"===e.kind?"".concat(e.fontFamily," (").concat(e.fontRole," font)"):(null==(t=e.asset)?void 0:t.name)||e.fileName})].filter(Boolean).join(", "),". These assets are on the board and should be treated as active ad context."):"",ng.filter(e=>{let{item:t}=e;return"image"!==t.kind}).length>0?"Manually selected now file(s): ".concat(ng.filter(e=>{let{item:t}=e;return"image"!==t.kind}).map(e=>{let{item:t,file:n}=e;return n.name||t.fileName}).filter(Boolean).join(", "),". If the user says selected file/current file/this file, they mean these asset(s), not older chat assets."):"",nx.length>0?"Manually selected now reference asset(s): ".concat(nx.map(e=>{var t;return"font"===e.kind?"".concat(e.fontFamily," (").concat(e.fontRole," font)"):(null==(t=e.asset)?void 0:t.name)||e.fileName}).filter(Boolean).join(", "),". If the user says selected/current/this asset, they mean these asset(s), not older chat assets."):"",nb.length>0?"Selected text note(s): ".concat(nb.map(e=>tZ(e.text,260)).filter(Boolean).join(" | ")):"",function(e,t){let n=e.filter(e=>!t.has(e.asset_id||e.item_id));return 0===n.length?"":"Assets kept from earlier in this chat: ".concat(n.map(e=>"".concat(e.asset_name||e.file_name).concat(e.asset_role?" (".concat(e.asset_role,")"):"")).join(", "),". Treat these as available background assets, but if the user says selected/current/this image, prefer the manually selected asset(s) from this message.")}(w,j)].filter(Boolean).join("\n");(h||w.length>0)&&_&&er(e=>t0(e,"Previous selected context:\n".concat(_)));let k=new FormData,A="plan:".concat(l,":").concat(R,":").concat(Date.now()),C={board_id:l,context_id:null!=s?s:null,prompt:e,display_prompt:t,chat_id:R,idempotency_key:A,mode:"auto",selection_mode:h||w.length>0?"selected":"auto",attachment_candidates:N,text_context_items:nb,storyboard_context_items:ny,previous_extracted_context:el,connected_social_networks:eN,outstand_accounts:t$(ek,nn).filter(e=>0!==e.isActive).map(e=>({id:String(e.id||"").trim(),network:String(e.network||"").trim()})).filter(e=>e.id&&e.network),client_timezone:tF()};k.set("payload_json",JSON.stringify(C)),g.forEach(e=>{let{item:t,file:n}=e;k.append("file_".concat(t.id),n,n.name)}),th.current=h?[...c]:null,tf.current=1===nh.length&&null!=(a=null==(n=nh[0])?void 0:n.id)?a:null;let S=tW();P(""),e9.current="",tc(ts(l,R)),en(e),eo(w),O([]),t_.current.clear(),Y(null),Q([]),eg([]),eb(0),ev([]),ej(""),eR(null),eU(""),eB(""),G("created"),ee(0),tl.current=[],tp.current=[],e4.current&&(e4.current.style.height="auto"),D(e=>[...e,{id:S,role:"user",text:t,seq:nl()}]),L(!0);try{let e=await nI("/ai/business/ad-maker/orchestrate/background/",{method:"POST",body:k}),t="string"==typeof e.job_id?e.job_id:"";r&&r!==t&&((0,ta.Cq)(l,{chatIds:[],jobIds:[r]}).catch(e=>{console.warn("[ad-maker] Failed to cancel superseded clarification job:",e)}),nt(r))}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;let e=t instanceof Error?t.message:"Something went wrong.";nw("Error: ".concat(e)),G("failed"),nv(),L(!1)}},[ei,R,nm,nu,np,nf,l,nv,eN,s,nt,nI,F,u,q,el,nl,ek,nw,nx,ng,nh,c,nb,J,ny,nn]),nE=(0,o.useCallback)(async()=>{if(!F&&q&&l&&H){L(!0);try{await nI("/ai/business/ad-maker/jobs/".concat(q,"/approve/background/"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:l,context_id:null!=s?s:null,plan:H,starting_event_index:Z,chat_id:R,idempotency_key:"execute:".concat(q,":").concat(Z)})})}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;let e=t instanceof Error?t.message:"Something went wrong.";nw("Error: ".concat(e)),G("failed"),L(!1)}}},[R,l,s,H,nI,Z,F,q,nw]),nU=(0,o.useCallback)(async(e,t)=>{if(F||!q||!l||!eM)return;let n=(null!=t?t:eE).trim();if(!e&&!n)return;let a=eM;if(e&&"social_media_scheduler"===eM.stepType){tP("approval clicked for social step; refreshing before submit",{stepId:eM.stepId,platform:eM.pendingOutput.platform,currentRequiresConnectionSetup:eM.requiresConnectionSetup,currentCanApprove:eM.canApprove});let{networks:e,accounts:t}=await nc();eR(a=tK(eM,e,t,nn))}tP("submitting step approval",{approved:e,stepId:a.stepId,stepType:a.stepType,platform:a.pendingOutput.platform,requiresConnectionSetup:a.requiresConnectionSetup,canApprove:a.canApprove,pendingOutputRequiresConnectionSetup:a.pendingOutput.requires_connection_setup,pendingOutputCanApprove:a.pendingOutput.can_approve,connectedSocialNetworks:eN});let r=eP.split(",").map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isFinite(e)&&e>0).map(e=>e-1);L(!0);try{await nI("/ai/business/ad-maker/jobs/".concat(q,"/steps/approve/background/"),{method:"POST",headers:{"Content-Type":"application/json"}
1,body:JSON.stringify({board_id:l,context_id:null!=s?s:null,step_id:a.stepId,step_name:a.stepName,step_type:a.stepType,decision:e?"allow":"reject",reason:e?null:n,target_frame_indexes:e?[]:r,approved:e,rejection_reason:e?null:n,starting_event_index:Z,pending_output:a.pendingOutput,chat_id:R,idempotency_key:"step:".concat(q,":").concat(a.stepId,":").concat(e?"allow":"reject",":").concat(Z)})}),(e||!a.requiresConnectionSetup)&&eR(null),e||eU(""),e||eB("")}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;let e=t instanceof Error?t.message:"Something went wrong.";nw("Error: ".concat(e)),G("failed"),L(!1)}},[R,l,eN,s,nI,Z,F,q,eM,nw,nc,eE,eP,nn]),nP=(0,o.useCallback)(e=>{let t=!ec&&function(e,t){let n=e.trim().toLowerCase();if(!n)return!1;let a=n.includes("?")||n.startsWith("what ")||n.startsWith("which ")||n.startsWith("can you "),r=["pdf","document","doc","file","attachment","in this","from this","according to"].some(e=>n.includes(e));return(!a||!t.hasSelectedFile&&!t.hasBoardFiles||!r)&&["create ad","make an ad","ad campaign","plan","generate","compose","carousel","instagram post","tiktok ad","facebook ad","run mock executor"].some(e=>n.includes(e))}(e,{hasBoardFiles:nd.length>0||nf.length>0,hasSelectedFile:nh.length>0||ng.length>0||nx.length>0}),n=t?function(e,t){let n=e.trim();if(!n||!t)return n;let a=[];return(t.organizationName&&a.push("Business name: ".concat(t.organizationName)),t.industry&&a.push("Industry: ".concat(t.industry)),t.productService&&a.push("Product/service: ".concat(t.productService)),t.keyBenefit&&a.push("Key benefit: ".concat(t.keyBenefit)),t.targetAudience&&a.push("Target audience: ".concat(t.targetAudience)),t.toneOfVoice&&a.push("Tone of voice: ".concat(t.toneOfVoice)),t.additionalContext&&a.push("Additional context: ".concat(t.additionalContext)),t.websiteUrl&&a.push("Website: ".concat(t.websiteUrl)),0===a.length)?n:[n,"","[INTERNAL BUSINESS CONTEXT]","Background only. Never override the user's direct request.","If the user asks about an attached file/document, prioritise extracted file evidence over this context.","Do not infer intent from this block; use it only when helpful for ad planning tone/brand consistency.",...a].join("\n")}(e,tS):e;return t&&ed(!0),t&&!ep&&tV&&(n=function(e,t){let n=e.trim(),a="string"==typeof t?t.trim():"";return n&&a?[n,"",a,"Use this research for hooks, angles, audience, trending topics, and visual direction. Never override the user's direct request."].join("\n"):n}(n,tV),eh(!0)),!eu&&tE&&(n=function(e,t){let n=e.trim();if(!n||!t)return n;let a=[];t.campaignName&&a.push("Campaign: ".concat(t.campaignName)),t.audienceDescription&&a.push("Audience: ".concat(t.audienceDescription)),t.audienceLocations&&t.audienceLocations.length>0&&a.push("Audience locations: ".concat(t.audienceLocations.join(", "))),t.audienceInterests&&t.audienceInterests.length>0&&a.push("Audience interests: ".concat(t.audienceInterests.join(", "))),t.seedCopy&&t.seedCopy.length>0&&a.push("Campaign themes / seed copy: ".concat(t.seedCopy.join(", ")));let r=t.brand;return(r&&(r.name&&a.push("Brand name: ".concat(r.name)),r.tagline&&a.push("Brand tagline: ".concat(r.tagline)),r.archetype&&a.push("Brand archetype: ".concat(r.archetype)),r.positioning&&a.push("Brand positioning: ".concat(r.positioning)),r.promise&&a.push("Brand promise: ".concat(r.promise)),r.voiceDescription&&a.push("Brand voice: ".concat(r.voiceDescription)),r.voicePersonality&&r.voicePersonality.length>0&&a.push("Brand voice traits: ".concat(r.voicePersonality.join(", "))),r.palette&&r.palette.length>0&&a.push("Brand colours: ".concat(r.palette.join(", "))),r.moodWords&&r.moodWords.length>0&&a.push("Brand mood: ".concat(r.moodWords.join(", ")))),0===a.length)?n:[n,"","[CAMPAIGN CONTEXT]","Background only. Never override the user's direct request.","Keep generated creatives and copy on-brand and on-audience for this campaign.",...a].join("\n")}(n,tE),em(!0)),n},[nf.length,nd.length,tS,tE,ec,eu,ep,tV,nx.length,ng.length,nh.length]),nB=(0,o.useCallback)(async()=>{let e=U.trim();if(!e)return;if("awaiting_step_approval"===J&&eM){P(""),e9.current="",tc(ts(l,R)),e4.current&&(e4.current.style.height="auto"),D(t=>[...t,{id:tW(),role:"user",text:e,seq:nl()}]),await nU(!1,e);return}if("awaiting_approval"===J&&H){let t=et||e,n="string"==typeof H.plan_summary?H.plan_summary:"",a=[t,"","Revise the ad plan based on this user feedback:",e,n?"Previous plan summary: ".concat(n):"","Ask for one clarification only if essential information is still missing."].filter(
1Boolean).join("\n");await nR(a,e);return}if(et&&Z>0){let t=[et,"","Use the prior run context and outputs as memory for this follow-up request.",ea?"Prior run memory:\n".concat(ea):"","Decide intent from the latest user message: revise existing ad, create a supporting post/caption, or create a different ad concept.","If the latest request says to post it somewhere else too, reuse the prior caption/media unless the user asks for changes.","Only ask clarification if absolutely necessary.","","Latest user follow-up request:",e].filter(Boolean).join("\n");await nR(t,e);return}let t=nP(e);if((0,tM.p9)({boardId:l,items:i,activeAssetContext:ei,eventCount:Z})){eq({finalPrompt:t,userMessage:e}),eF(!0);return}await nR(t,e)},[ei,R,nf.length,l,nd.length,nP,tE,H,Z,ec,eu,ep,U,i,ea,et,tV,nl,eM,nR,nx.length,ng.length,nh.length,J,nU]),nD=(0,o.useCallback)(async e=>{if(F)return;let t=e.trim();if(!t)return;let n=ef[ex];if(!n)return;let a=[...ey,{questionId:n.id,question:n.question,answer:t}];if(ev(a),ej(""),D(e=>[...e,{id:tW(),role:"user",text:t,seq:nl()}]),ex<ef.length-1)return void eb(e=>e+1);let r=et.trim();if(!r)return void nw("I couldn't find the previous prompt. Please resend your ad request.");let l=[r,"\nClarification answers:",a.map((e,t)=>"".concat(t+1,". ").concat(e.question,"\nAnswer: ").concat(e.answer)).join("\n\n"),"\nUse these answers to continue planning and return an updated plan."].join("\n");eg([]),eb(0),ev([]),await nR(l,"Submitted clarifications.")},[ey,ex,ef,F,et,nl,nw,nR]),nz=(0,o.useCallback)(()=>{P(e=>e.trim().length>0?e:"Please revise the plan: "),requestAnimationFrame(()=>{let e=e4.current;if(!e)return;e.focus();let t=e.value;e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height="".concat(Math.min(e.scrollHeight,140),"px")})},[]),nO=(0,o.useCallback)(()=>{let e=(null==eM?void 0:eM.stepType)==="storyboard_approval"?"Please change this storyboard step: ":(null==eM?void 0:eM.stepType)==="visual_direction_approval"?"Please change the visual direction: ":"Please change this step: ";P(t=>t.trim().length>0?t:e),requestAnimationFrame(()=>{let e=e4.current;if(!e)return;e.focus();let t=e.value;e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height="".concat(Math.min(e.scrollHeight,140),"px")})},[null==eM?void 0:eM.stepType]),nF=(0,o.useCallback)(e=>{eo(t=>t.filter(t=>(t.asset_id||t.item_id)!==(e.asset_id||e.item_id)))},[]),nL=(0,o.useCallback)(()=>{eo([])},[]),nq=(0,o.useMemo)(()=>[...B.map(e=>({id:"m-".concat(e.id),seq:e.seq,type:"message",message:e})),...z.map(e=>({id:"r-".concat(e.id),seq:e.seq,type:"row",row:e}))].sort((e,t)=>e.seq-t.seq),[B,z]),n$=ng.filter(e=>{let{item:t}=e;return"image"!==t.kind}).length,nK=nh.length+n$+nx.length+nb.length,nW=np>0?nK>0?null:"".concat(np," brand asset").concat(1===np?"":"s"," on the board â included when you send chat"):nd.length>0?"Only generated ads on the board â add logos or product photos for chat to use":"No brand assets on the board yet â drag files onto the canvas or add from the library",nJ=null!=(n=ef[ex])?n:null,nG="awaiting_input"===J&&!!nJ,nH="awaiting_step_approval"===J&&!!eM,nY=(null==eM?void 0:eM.stepType)==="social_media_scheduler",nV=(0,o.useMemo)(()=>eM&&nY?function(e,t,n){var a;let r=t$(e,n).filter(e=>0!==e.isActive),l=t.outstand_account_ids;if(Array.isArray(l)&&l.length>0){let e=new Set(l.map(e=>String(e).trim()).filter(Boolean)),t=r.filter(t=>e.has(String(t.id)));if(t.length>0)return t}let s=new Set(tz(null!=(a=t.platforms)?a:t.platform).map(e=>tD(e))),i=new Set,o=[];for(let e of r){let t=String(e.id||"").trim(),n=tD(e.network);!t||!s.has(n)||i.has(t)||(i.add(t),o.push(e))}return o}(ek,eM.pendingOutput,nn):[],[nY,ek,eM,nn]),nX=nH&&!!(null==eM?void 0:eM.requiresConnectionSetup),nQ=nH&&!nX?"Tell me what to change in this step...":"Describe your ad â e.g. square Instagram post for our summer sale",nZ=(0,o.useCallback)(e=>{P(e),window.requestAnimationFrame(()=>{let e=e4.current;e&&(e.focus(),e.style.height="auto",e.style.height="".concat(Math.min(e.scrollHeight,140),"px"))})},[]),n0=(0,o.useCallback)(()=>{if(!eL)return void eF(!1);(0,tM.N4)(l),eq(null),eF(!1),nR(eL.finalPrompt,eL.userMessage)},[l,eL,nR]),n1=(0,o.useCallback)(()=>{eF(!1),null==j||j()},[j]);return A?(0,a.jsxs)("div",{className:"absolute right-4 top-[2%] z-30 flex h-[min(96%,calc(100%-2rem))] w-[min(100%,30rem)] max-w-[calc(100%-2rem)] flex-col overflow-hidden rounded-2xl border border-auth-hairline bg-white shadow-[0_16px_40px_rgba(13,14,29,0.14)]",onPointerDown:e=>e.stopPropagation(),children:[(0,a.jsxs)("div",{className:"flex flex-shrink-0 flex-col gap-3 border-b border-auth-hairline px-4 py-3.5",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2.5",children:[(0,a.jsx)("span",{"aria-hidden":!0,
1className:"grid h-8 w-8 shrink-0 place-items-center rounded-full bg-midnight-logic text-white",children:(0,a.jsx)(eK.A,{className:"h-4 w-4"})}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h2",{className:"truncate text-[0.9rem] font-extrabold text-midnight-logic",children:"Ad maker run"}),(0,a.jsxs)("p",{className:"flex items-center gap-1.5 text-[0.74rem] font-semibold capitalize text-auth-muted",children:[(0,a.jsx)("span",{"aria-hidden":!0,className:"h-1.5 w-1.5 rounded-full bg-signal-blue"}),J.replaceAll("_"," ")]})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)("button",{type:"button",className:"grid h-9 w-9 shrink-0 place-items-center rounded-[10px] text-auth-ink-soft transition-colors hover:bg-cloud-slate hover:text-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50",onClick:nA,disabled:F,"aria-label":"Start new chat",children:(0,a.jsx)(d.A,{className:"h-4 w-4"})}),(0,a.jsx)("button",{type:"button",className:"grid h-9 w-9 shrink-0 place-items-center rounded-[10px] text-auth-ink-soft transition-colors hover:bg-cloud-slate hover:text-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onClick:()=>C(!1),"aria-label":"Close chat panel",children:(0,a.jsx)(eW.A,{className:"h-4 w-4"})})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("div",{className:"flex min-w-0 flex-1 gap-1.5 overflow-x-auto pb-0.5",children:S.map(e=>{let t=e.id===R;return(0,a.jsx)("button",{type:"button",onClick:()=>nk(e.id),disabled:F,"aria-current":t?"true":void 0,className:"shrink-0 rounded-full px-3 py-1.5 text-[0.76rem] font-bold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue ".concat(t?"bg-auth-field text-anchor-blue":"bg-cloud-slate text-auth-ink-soft hover:bg-auth-hairline"," disabled:cursor-not-allowed disabled:opacity-60"),children:e.title},e.id)})}),(0,a.jsx)("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1.5 text-[0.74rem] font-bold text-auth-muted transition-colors hover:text-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onClick:()=>{nC()},children:"Clear chats"})]})]}),(0,a.jsxs)("div",{ref:e0,className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-3 py-2.5 sm:px-4 sm:py-3",children:[nq.map(e=>(0,a.jsx)("div",{className:"flex ".concat("row"===e.type?"justify-start":"user"===e.message.role?"justify-end":"justify-start"),children:"row"===e.type?(0,a.jsx)(tG,{row:e.row}):"user"===e.message.role?(0,a.jsx)("div",{className:"max-w-[92%] rounded-xl bg-auth-field px-3.5 py-2.5 text-[0.84rem] font-semibold text-midnight-logic",children:(0,a.jsx)("p",{className:"whitespace-pre-wrap break-words leading-[1.55]",children:e.message.text})}):"system"===e.message.role?(0,a.jsx)("p",{className:"text-[0.76rem] font-medium text-auth-muted",children:e.message.text}):(0,a.jsx)("div",{className:"w-full overflow-x-auto",children:(0,a.jsxs)("div",{className:"plan"===e.message.kind?"rounded-lg border border-charcoal-200 bg-white px-3 py-2.5":"",children:[e.message.text.trim().length>0?(0,a.jsx)(tJ,{content:e.message.text}):null,"plan"===e.message.kind&&X.length>0?(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(tg,{items:X})}):null]})})},e.id)),nr?(0,a.jsxs)("div",{className:"px-1 pb-2",children:[(0,a.jsx)("p",{className:"mb-2.5 text-[0.68rem] font-extrabold uppercase tracking-[0.1em] text-auth-muted",children:"Example prompts"}),(0,a.jsx)("div",{className:"flex flex-col gap-2",children:tM.IS.map(e=>(0,a.jsxs)("button",{type:"button",disabled:F,onClick:()=>nZ(e),className:"flex items-start gap-2.5 rounded-xl border border-auth-hairline bg-white px-3.5 py-2.5 text-left text-[0.78rem] font-semibold leading-[1.45] text-midnight-logic transition-colors hover:border-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60",children:[(0,a.jsx)(eK.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-signal-blue","aria-hidden":!0}),e]},e))})]}):null]}),(0,a.jsxs)("div",{className:"flex-shrink-0 border-t border-auth-hairline bg-white p-3 sm:p-3.5",children:[nG&&nJ&&(0,a.jsxs)("div",{className:"mb-3 rounded-lg border border-charcoal-200 bg-charcoal-50 p-3",children:[(0,a.jsxs)("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-charcoal-500",children:["Clarification ",ex+1," of ",ef.length]}),(0,a.jsx)("p",{className:"mt-1.5 text-sm font-medium text-charcoal",children:nJ.question}),nJ.options.length>0&&(0,a.jsx)("div",{className:"mt-2 space-y-1.5",children:nJ.options.map((e,t)=>(0,a.jsxs)(y.$,{type:"button",variant:"outline",className:"h-auto w-full justify-start whitespace-normal px-2.5 py-2 text-left text-xs",onClick:()=>void nD(e),disabled:F,children:[t+1,". ",e]},"".concat(nJ.id,"-option-").concat(t)))}),nJ.allowFreeText&&(0,a.jsxs)("div",{className:"mt-2",children:[(0,a.jsx)("label",{className:"mb-1 block text-[11px] font-medium text-charcoal-600",children:"4. Other (type your own answer)"}),(0,a.jsxs)("div",{className:"flex items-end gap-2",children:[(0,a.jsx)(eZ.T,{value:ew,onChange:e=>ej(e.target.value),placeholder:"Write your answer...",disabled:F,className:"max-h-[96px] min-h-[2.5rem] flex-1 resize-none rounded-lg border border-charcoal-200 bg-white py-1.5 pl-2 pr-2 text-xs text-charcoal placeholder:text-charcoal-400 focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-60",rows:2}),(0,a.jsx)(y.$,{type:"button",className:"h-8 shrink-0 px-3 text-xs",onClick:()=>void nD(ew),disabled:F||!ew.trim(),children:"Submit"})]})]})]}),eM&&nY?(0,a.jsx)(tI,{accounts:nV,captionText:String(eM.pendingOutput.caption_text||""),imageUrls:Array.isArray(eM.pendingOutput.image_urls)?eM.pendingOutput.image_urls.filter(e=>"string"==typeof e&&e.trim().length>0):[],scheduledFor:eM.pendingOutput.scheduled_for,scheduleTimeLocal:function(e){let t=String(e||"").trim();if(!t)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let a=6e4*n.getTimezoneOffset();return new Date(n.getTime()-a).toISOString().slice(0,16)}(eM.pendingOutput.scheduled_for),scheduleTimeReadable:tL(eM.pendingOutput.scheduled_for),timezoneLabel:tF(),requiresConnectionSetup:eM.requiresConnectionSetup,canApprove:eM.canApprove,approvalMessage:eM.approvalMessage,isRunning:F,accountsRefreshing:eI,onScheduleTimeChange:e=>{eR(t=>t?function(e,t){var n;let a=function(e){let t=e.trim();if(!t)return"";let n=new Date(t);return Number.isNaN(n.getTime())?"":n.toISOString()}(t);if(!a)return e;let r=tL(a),l={...e.pendingOutput,scheduled_for:a,readable_scheduled_for:r,client_timezone:tF()},s=String(l.caption_text||"").trim(),i=tO(tz(null!=(n=l.platforms)?n:l.platform));return{...e,pendingOutput:l,approvalMessage:e.requiresConnectionSetup?e.approvalMessage:s?"Ready to schedule this ".concat(i," post for ").concat(r,". Approve to continue or reject with a reason."):"Cannot schedule yet: no caption content is available for the post."}}(t,e):t)},onConnectAccounts:()=>eS(!0),onRefreshAccounts:()=>void nc(),onApprove:()=>void nU(!0),onRequestChanges:nO}):eM?(0,a.jsxs)("div",{className:"mb-3 rounded-lg border border-charcoal-200 bg-charcoal-50 p-3",children:[(0,a.jsx)("p",{className:"text-sm font-semibold text-charcoal",children:eM.stepName}),"storyboard_approval"===eM.stepType?(0,a.jsxs)("div",{className:"mt-2 grid grid-cols-2 gap-2 text-[11px] text-charcoal-600",children:[(0,a.jsxs)("p",{children:["Frames:"," ",String((null==(t=eM.pendingOutput.frames)?void 0:t.length)||0)]}),(0,a.jsxs)("p",{children:["Aspect:"," ",String(eM.pendingOutput.video_request&&"object"==typeof eM.pendingOutput.video_request&&eM.pendingOutput.video_request.aspect_ratio||"16:9")]})]}):"visual_direction_approval"===eM.stepType?(()=>{let e=eM.pendingOutput.copywriting,t=eM.pendingOutput.visual_direction;return(0,a.jsxs)("div",{className:"text-charcoal-700 mt-2 space-y-2 text-[11px]",children:[e?(0,a.jsxs)("div",{className:"space-y-0.5",children:[e.headline?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Headline:"}
1)," ",String(e.headline)]}):null,e.primary_text?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Body:"})," ",String(e.primary_text)]}):null,e.cta_text?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"CTA:"})," ",String(e.cta_text)]}):null]}):null,t?(0,a.jsxs)("div",{className:"space-y-0.5 border-t border-charcoal-200 pt-2",children:[t.style?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Style:"})," ",String(t.style)]}):null,t.mood?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Mood:"})," ",String(t.mood)]}):null,t.layout?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Layout:"})," ",String(t.layout)]}):null,Array.isArray(t.palette)&&t.palette.length>0?(0,a.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,a.jsx)("span",{className:"font-medium text-charcoal",children:"Palette:"}),(0,a.jsx)("div",{className:"flex gap-1",children:t.palette.slice(0,5).map((e,t)=>(0,a.jsx)("span",{className:"inline-block h-3 w-3 rounded-sm border border-charcoal-200",style:{backgroundColor:e},title:e},t))})]}):null]}):null]})})():null,(0,a.jsxs)("div",{className:"mt-2 flex gap-2",children:[(0,a.jsx)(y.$,{type:"button",className:"h-8 flex-1 text-xs",disabled:F||!eM.canApprove,onClick:()=>void nU(!0),children:"Approve"}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"h-8 flex-1 text-xs",disabled:F,onClick:nO,children:"Request changes"})]})]}):null,H&&"awaiting_approval"===J&&(0,a.jsxs)("div",{className:"mb-3 space-y-2",children:[V?(0,a.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-charcoal-200 bg-charcoal-50 px-2 py-1.5",children:[(0,a.jsx)("span",{className:"shrink-0 rounded-sm border border-charcoal-300 bg-white",style:{width:28,height:Math.max(6,Math.min(28,Math.round(28*(V.height||1)/(V.width||1))))},"aria-hidden":!0}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"truncate text-[11px] font-medium text-charcoal",children:V.label||"Custom size"}),(0,a.jsx)("p",{className:"text-[10px] text-charcoal-500",children:function(e){let t=[];return e.width&&e.height&&t.push("".concat(e.width,"\xd7").concat(e.height)),e.aspectRatio&&t.push(e.aspectRatio),t.join(" \xb7 ")}(V)})]}),(0,a.jsxs)("select",{className:"h-7 max-w-[170px] rounded-md border border-charcoal-200 bg-white px-1.5 text-[11px] text-charcoal",value:null!=(r=V.formatKey)?r:"",disabled:F,"aria-label":"Output format",onChange:e=>{let t=e.target.value;t&&Y(e=>e?function(e,t){let n=tu[t];if(!n)return e;let a=(Array.isArray(e.steps)?e.steps:[]).map(e=>{let t="string"==typeof(null==e?void 0:e.type)?e.type:"";if(!tm.has(t))return e;let a=e.input&&"object"==typeof e.input?e.input:{};return{...e,input:{...a,format_key:n.formatKey,format_label:n.label,aspect_ratio:n.aspectRatio,image_size:{width:n.width,height:n.height},resolved_format:{format_key:n.formatKey,label:n.label,aspect_ratio:n.aspectRatio,width:n.width,height:n.height}}}});return{...e,steps:a}}(e,t):e)},children:[V.formatKey?null:(0,a.jsx)("option",{value:"",children:"Custom size"}),td.map(e=>(0,a.jsx)("option",{value:e.formatKey,children:"".concat(e.label," (").concat(e.width,"\xd7").concat(e.height,")")},e.formatKey))]})]}):null,(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)(y.$,{type:"button",className:"h-9 flex-1 gap-2",onClick:()=>void nE(),disabled:F,children:[(0,a.jsx)(eJ.A,{className:"h-3.5 w-3.5"}),"Approve & Run"]}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"h-9 flex-1",onClick:nz,disabled:F,children:"Request Changes in Chat"})]})]}),ei.length>0?(0,a.jsxs)("div",{className:"mb-2 rounded-lg border border-charcoal-200 bg-charcoal-50 p-2",children:[(0,a.jsxs)("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[(0,a.jsx)("p",{className:"text-[11px] font-medium text-charcoal-600",children:"Using assets in this chat"}),(0,a.jsx)(y.$,{type:"button",variant:"ghost",className:"hover:text-charcoal-700 h-6 px-2 text-[10px] text-charcoal-500",onClick:nL,disabled:F,children:"Clear"})]}),(0,a.jsx)("div",{className:"flex gap-1.5 overflow-x-auto pb-1",children:ei.map(e=>(0,a.jsxs)("div",{className:"flex max-w-[170px] shrink-0 items-center gap-1.5 rounded-full border border-charcoal-200 bg-white py-1 pl-1 pr-1.5 text-[11px] text-charcoal",title:e.asset_description||e.asset_name||e.file_name,children:[e.preview_url?(0,a.jsx)("img",{src:e.preview_url,alt:"",className:"h-5 w-5 rounded-full object-cover"}):(0,a.jsx)("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-charcoal-100 text-[9px] font-semibold uppercase text-charcoal-500",children:(e.asset_role||"asset").slice(0,1)}),(0,a.jsxs)("span",{className:"truncate",children:[e.asset_name||e.file_name,e.asset_role?" (".concat(e.asset_role.replaceAll("_"," "),")"):""]}),(0,a.jsx)("button",{type:"button",className:"rounded-full p-0.5 text-charcoal-400 hover:bg-charcoal-100 hover:text-charcoal",onClick:()=>nF(e),disabled:F,"aria-label":"Remove ".concat(e.asset_name||e.file_name," from chat asset context"),children:(0,a.jsx)(eG.A,{className:"h-3 w-3"})})]},e.asset_id||e.item_id))})]}):null,nK>0||0===np?null:(0,a.jsx)("p",{className:"mb-2 text-[11px] text-charcoal-500",children:nW}),nK>0?(0,a.jsxs)("div",{className:"mb-2",children:[(0,a.jsx)("p",{className:"mb-1 text-[11px] font-medium text-charcoal-500",children:"Selected context"}),(0,a.jsxs)("div",{className:"flex gap-1.5 overflow-x-auto pb-1",children:[nh.map(e=>{var t,n;return(0,a.jsxs)("div",{className:"flex min-w-[92px] max-w-[120px] shrink-0 flex-col overflow-hidden rounded-md border border-signal-blue/50 bg-white",title:(null==(t=e.asset)?void 0:t.description)||e.fileName,children:[(0,a.jsx)("div",{className:"h-12 w-full",style:{backgroundImage:"linear-gradient(45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(-45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, rgba(15,23,42,0.08) 75%), linear-gradient(-45deg, transparent 75%, rgba(15,23,42,0.08) 75%)",backgroundSize:"12px 12px",backgroundPosition:"0 0, 0 6px, 6px -6px, -6px 0"},children:(0,a.jsx)("img",{src:e.src,alt:e.fileName,className:"h-12 w-full object-contain"})}),(0,a.jsx)("p",{className:"truncate px-1.5 py-1 text-[10px] font-medium text-charcoal",children:(null==(n=e.asset)?void 0:n.name)||e.fileName})]},e.id)}),ng.filter(e=>{let{item:t}=e;return"image"!==t.kind}).map(e=>{let{item:t,file:n}=e;return(0,a.jsxs)("div",{className:"flex min-w-[92px] max-w-[120px] shrink-0 flex-col overflow-hidden rounded-md border border-signal-blue/50 bg-white",title:n.name,children:["image"===t.kind?(0,a.jsx)("div",{className:"h-12 w-full",style:{backgroundImage:"linear-gradient(45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(-45deg, rgba(15,23,42,0.08) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, rgba(15,23,42,0.08) 75%), linear-gradient(-45deg, transparent 75%, rgba(15,23,42,0.08) 75%)",backgroundSize:"12px 12px",backgroundPosition:"0 0, 0 6px, 6px -6px, -6px 0"},children:(0,a.jsx)("img",{src:t.src,alt:n.name,className:"h-12 w-full object-contain"})}):"pdf"===t.kind?(0,a.jsx)("img",{src:t.previewDataUrl,alt:n.name,className:"h-12 w-full object-cover"}):(0,a.jsx)("div",{className:"flex h-12 items-center justify-center bg-charcoal-100 text-[10px] font-semibold text-charcoal-600",children:"FILE"}),(0,a.jsx)("p",{className:"truncate px-1.5 py-1 text-[10px] font-medium text-charcoal",children:n.name})]},t.id)}),nx.map(e=>{var t,n;return(0,a.jsxs)("div",{className:"flex min-w-[92px] max-w-[120px] shrink-0 flex-col overflow-hidden rounded-md border border-signal-blue/50 bg-white",title:(null==(t=e.asset)?void 0:t.description)||e.fileName,children:["pdf"===e.kind&&"previewDataUrl"in e?(0,a.jsx)("img",{src:e.previewDataUrl,alt:e.fileName,className:"h-12 w-full object-cover"}):(0,a.jsx)("div",{className:"flex h-12 items-center justify-center bg-charcoal-100 text-[10px] font-semibold text-charcoal-600",children:"FILE"}),(0,a.jsx)("p",{className:"truncate px-1.5 py-1 text-[10px] font-medium text-charcoal",children:(null==(n=e.asset)?void 0:n.name)||e.fileName})]},e.id)}),nb.map(e=>{let t=e.text.trim();return(0,a.jsxs)("div",{className:"flex min-w-[120px] max-w-[160px] shrink-0 flex-col overflow-hidden rounded-md border border-signal-blue/50 bg-white",title:t||"Empty text note",children:[(0,a.jsx)("div",{className:"line-clamp-2 h-12 px-2 py-1.5 text-[10px] leading-4 text-charcoal",children:t||(0,a.jsx)("span",{className:"text-charcoal-400",children:"Add your text..."})}),(0,a.jsx)("p",{className:"truncate border-t border-charcoal-100 px-1.5 py-1 text-[10px] font-medium text-charcoal",children:"Text note"})]},e.item_id)})]})]}):null,na||eV?null:(0,a.jsxs)("div",{className:"mb-2 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2",children:[(0,a.jsx)(eH.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-700"}),(0,a.jsx)("p",{className:"flex-1 text-[11px] leading-relaxed text-amber-900",children:"Tip: drag logo and product images onto the canvas, or use the paperclip to add them to the board. Chat cannot use assets that are only in your library."}),(0,a.jsx)("button",{type:"button",className:"shrink-0 text-[10px] font-semibold text-amber-800 underline-offset-2 hover:underline",onClick:()=>{(0,tM.WH)(l),eX(!0)},children:"Dismiss"})]}),(0,a.jsxs)("div",{className:"flex items-end gap-2",children:[(0,a.jsx)(eZ.T,{ref:e4,value:U,onChange:e=>{P(e.target.value),e4.current&&(e4.current.style.height="auto",e4.current.style.height="".concat(Math.min(e4.current.scrollHeight,140),"px"))},onKeyDown:e=>
1{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),!U.trim()||F||nG||nX||nB())},placeholder:nQ,disabled:F||nG||nX,className:"max-h-[140px] min-h-[3.25rem] flex-1 resize-none rounded-xl border-2 border-charcoal bg-white py-2 pl-3 pr-3 text-sm font-medium text-charcoal placeholder:text-charcoal-400 focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-60",rows:2}),(0,a.jsx)(y.$,{type:"button",className:"h-10 shrink-0 gap-1.5 px-3",onClick:()=>void nB(),disabled:!U.trim()||F||nG||nX,"aria-label":"Run planner",children:F?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eY.A,{className:"h-4 w-4"}),(0,a.jsx)(tr,{})]})})]})]}),(0,a.jsx)(eQ.lG,{open:eC,onOpenChange:e=>{eS(e),e||nc()},children:(0,a.jsxs)(eQ.Cf,{className:"max-h-[88vh] max-w-6xl overflow-y-auto bg-white",children:[(0,a.jsx)(eQ.c7,{children:(0,a.jsx)(eQ.L3,{children:"Connect Social Accounts"})}),(0,a.jsx)(e5.PlatformConnections,{})]})}),(0,a.jsx)(tT,{open:eO,onOpenChange:e=>{eF(e),e||eq(null)},onAddPhoto:n1,onContinueWithoutPhotos:n0})]}):(0,a.jsx)("div",{className:"absolute bottom-6 right-4 z-30",children:(0,a.jsx)(y.$,{type:"button",size:"icon",variant:"default",className:"h-12 w-12 rounded-full border-2 border-charcoal shadow-medium",onClick:()=>C(!0),"aria-label":"Open chat",children:(0,a.jsx)(e$.A,{className:"h-5 w-5"})})})}var nt=n(8382),nn=n(7511),na=n(73690),nr=n(25266),nl=n(72119),ns=n(55606),ni=n(14950),no=n(80644),nc=n(73350),nd=n(39980),nu=n(43960),nm=n(37732),np=n(98648),nh=n(81118),nf=n(77624),ng=n(56757),nx=n(43525),nb=n(73953),ny=n(66536),nv=n(2907);function nw(e){let{imageUrl:t,videoUrl:n,heading:r,subheading:l,cta:s,caption:i,username:c="your_business",profileImageUrl:d}=e,[u,m]=o.useState(!1),[p,h]=o.useState(!0),[f,g]=o.useState(!1),x=o.useRef(null),b=i||"".concat(r,"\n\n").concat(l,"\n\n").concat(s),y=()=>{x.current&&(p?(x.current.pause(),h(!1)):(x.current.play(),h(!0)))};return o.useEffect(()=>{x.current&&(x.current.muted=f)},[f]),o.useEffect(()=>{let e=x.current;if(e){let t=()=>h(!0),n=()=>h(!1);return e.addEventListener("play",t),e.addEventListener("pause",n),()=>{e.removeEventListener("play",t),e.removeEventListener("pause",n)}}},[]),(0,a.jsx)("div",{className:"relative mx-auto max-w-sm",children:(0,a.jsx)(nv.Zp,{className:"overflow-hidden border border-gray-300 bg-black shadow-lg",children:(0,a.jsxs)("div",{className:"relative aspect-[9/16] bg-black",children:[n?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("video",{ref:x,src:n,className:"h-full w-full cursor-pointer object-contain",loop:!0,playsInline:!0,muted:f,onClick:y}),!p&&(0,a.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/30",onClick:y,children:[(0,a.jsx)("button",{onClick:e=>{e.stopPropagation(),x.current&&(x.current.muted=!f,g(!f))},className:"mb-4 flex h-10 w-10 items-center justify-center rounded-full bg-black/50 backdrop-blur-sm transition-all hover:bg-black/70",children:f?(0,a.jsx)(np.A,{className:"h-6 w-6 text-white"}):(0,a.jsx)(nh.A,{className:"h-6 w-6 text-white"})}),(0,a.jsx)("button",{className:"flex h-16 w-16 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm transition-all hover:bg-white/30",children:(0,a.jsx)(eJ.A,{className:"ml-1 h-10 w-10 fill-white text-white"})})]})]}):t?(0,a.jsx)("img",{src:t,alt:"YouTube Short",className:"h-full w-full object-cover"}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center bg-gray-900",children:(0,a.jsx)("span",{className:"text-sm text-gray-400",children:"No media available"})}),u&&(0,a.jsx)("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-48 bg-gradient-to-t from-black/80 via-black/50 to-transparent"}),(0,a.jsxs)("div",{className:"absolute bottom-6 right-3 flex flex-col items-center gap-3",children:[(0,a.jsxs)("div",{className:"flex flex-col items-center gap-0.5",children:[(0,a.jsx)("button",{className:"flex h-8 w-8 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)(nf.A,{className:"h-7 w-7 text-white drop-shadow-lg"})}),(0,a.jsx)("span",{className:"text-xs font-semibold text-white drop-shadow-lg",children:"1.2K"})]}),(0,a.jsx)("div",{className:"flex flex-col items-center gap-0.5",children:(0,a.jsx)("button",{className:"flex h-8 w-8 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)(ng.A,{className:"h-7 w-7 text-white drop-shadow-lg"})})}),(0,a.jsxs)("div",{className:"flex flex-col items-center gap-0.5",children:[(0,a.jsx)("button",{className:"flex h-8 w-8 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)(nx.A,{className:"h-7 w-7 text-white drop-shadow-lg"})}),(0,a.jsx)("span",{className:"text-xs font-semibold text-white drop-shadow-lg",children:"42"})]}),(0,a.jsx)("div",{className:"flex flex-col items-center gap-0.5",children:(0,a.jsx)("button",{className:"flex h-8 w-8 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)(nb.A,{className:"h-7 w-7 text-white drop-shadow-lg"})})}),(0,a.jsx)("div",{className:"flex flex-col items-center gap-0.5",children:(0,a.jsx)("button",{className:"flex h-8 w-8 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)(ny.A,{className:"h-7 w-7 text-white drop-shadow-lg"})})}),(0,a.jsx)("div",{className:"relative flex flex-col items-center gap-0.5",children:(0,a.jsx)("button",{className:"flex h-10 w-10 items-center justify-center transition-all hover:scale-110",children:(0,a.jsx)("div",{className:"relative flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-red-500 to-red-600 shadow-lg",children:(0,a.jsx)("div",{className:"absolute left-1/2 top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 roun
1ded-sm bg-white"})})})})]}),(0,a.jsxs)("div",{className:"absolute bottom-0 left-0 right-20 p-4 pb-6",children:[(0,a.jsx)("div",{className:"mb-1 flex items-center gap-2",children:(0,a.jsx)("span",{className:"text-sm font-semibold text-white drop-shadow-lg",children:c})}),(0,a.jsx)("div",{className:"text-sm text-white drop-shadow-lg",children:(0,a.jsxs)("p",{className:"flex items-end",children:[(0,a.jsx)("span",{className:"transition-all duration-200 ease-in-out ".concat(u?"mb-4":"line-clamp-2"),children:b.split(/(#[^\s#@]+|@[^\s#@]+)/g).map((e,t)=>e.match(/^[#@]/)?(0,a.jsx)("span",{className:"font-semibold text-white",children:e},t):(0,a.jsx)("span",{children:e},t))}),!u&&(0,a.jsx)("button",{className:"ml-1 font-semibold",onClick:()=>m(!0),children:"more"}),u&&(0,a.jsx)("button",{className:"ml-1 font-semibold",onClick:()=>m(!1),children:"less"})]})})]})]})})})}function nj(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function nN(e){return Array.isArray(e)?e.map(e=>String(e||"").trim()).filter(Boolean):[]}function n_(e){return Array.isArray(e)?e.flatMap(e=>{if("string"==typeof e)return e.trim()?[e.trim()]:[];let t=nj(e),n=String(t.url||t.src||t.mediaUrl||t.media_url||"").trim();return n?[n]:[]}):[]}function nk(e){let t=String(e||"").trim().toLowerCase().replaceAll("-","_");return"x"===t?"twitter":t}function nA(e){return Array.isArray(e.scheduled_post_inputs)||Array.isArray(e.inputs)||Array.isArray(e.post_drafts)||Array.isArray(e.posts)}function nC(e){return/\.(mp4|mov|avi|webm|mkv)(?:$|\?)/i.test(e)}function nS(e){let{post:t}=e,n=t.mediaUrls.find(nC),r=t.mediaUrls.find(e=>!nC(e)),l={heading:"",subheading:"",cta:"",caption:t.caption,imageUrl:r,videoUrl:n};return"instagram"===t.platform?(0,a.jsx)(nd.U,{...l}):"facebook"===t.platform?(0,a.jsx)(nc.Y,{...l}):"linkedin"===t.platform?(0,a.jsx)(nu.w,{...l}):"tiktok"===t.platform?(0,a.jsx)(nm.S,{...l}):"youtube"===t.platform?(0,a.jsx)(nw,{...l}):(0,a.jsxs)("div",{className:"overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm",children:[r?(0,a.jsx)("img",{src:r,alt:"",className:"aspect-square w-full object-cover"}):(0,a.jsx)("div",{className:"flex aspect-square items-center justify-center bg-slate-100 text-slate-400",children:(0,a.jsx)(et.A,{className:"h-8 w-8"})}),(0,a.jsx)("p",{className:"line-clamp-6 whitespace-pre-wrap p-4 text-sm leading-5 text-slate-700",children:t.caption||"No caption"})]})}function nI(e){let{data:t,messageText:n,approvalAction:r}=e;return(0,a.jsxs)("div",{className:"w-full overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm",children:[(0,a.jsxs)("div",{className:"flex items-start justify-between gap-4 border-b border-slate-100 px-5 py-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[t.scheduled?(0,a.jsx)(tp.A,{className:"h-5 w-5 text-emerald-600"}):(0,a.jsx)(nr.A,{className:"h-5 w-5 text-signal-blue"}),(0,a.jsx)("h3",{className:"text-base font-bold text-slate-950",children:t.scheduled?"Posts scheduled":"Your posting schedule"})]}),(0,a.jsxs)("p",{className:"mt-1 text-sm text-slate-500",children:[t.posts.length," post",1===t.posts.length?"":"s"," ",t.scheduled?"created and ready to publish.":"ready for your approval."]})]}),(0,a.jsx)("span",{className:"shrink-0 rounded-full px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide ".concat(t.scheduled?"bg-emerald-50 text-emerald-700":"bg-blue-50 text-blue-700"),children:t.scheduled?"Scheduled":"Proposed"})]}),(0,a.jsx)("div",{className:"grid gap-4 bg-slate-50/70 p-4 md:grid-cols-2 xl:grid-cols-3",children:t.posts.map(e=>{var t;return(0,a.jsxs)("article",{className:"min-w-0",children:[(0,a.jsxs)("div",{className:"mb-2 flex min-h-12 items-start justify-between gap-2",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-700",children:{facebook:"Facebook",instagram:"Instagram",linkedin:"LinkedIn",tiktok:"TikTok",twitter:"X / Twitter",youtube:"YouTube"}[t=e.platform]||t.replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase())}),e.contentRole?(0,a.jsx)("p",{className:"mt-0.5 line-clamp-1 text-xs text-slate-500",children:e.contentRole}):null]}),(0,a.jsx)("span",{className:"max-w-[9rem] text-right text-[10px] font-semibold leading-4 text-slate-500",children:function(e,t){if(!e)return"Time not set";let n=new Date(e);if(Number.isNaN(n.getTime()))return e;try{return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"numeric",minute:"2-digit",timeZone:t,timeZoneName:"short"}).format(n)}catch(e){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",hour:"numeric",minute:"2-digit"}).format(n)}}(e.scheduledFor,e.timezone)})]}),(0,a.jsx)("div",{className:"pointer-events-none max-h-[32rem] overflow-hidden rounded-lg",children:(0,a.jsx)(nS,{post:e})}),e.rationale?(0,a.jsx)("p",{className:"mt-2 line-clamp-2 text-xs leading-5 text-slate-500",children:e.rationale}):null]},e.id)})}),(0,a.jsxs)("div",{className:"border-t border-slate-100 px-5 py-3",children:[t.scheduled?(0,a.jsxs)("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3",role:"status","aria-live":"polite",children:[(0,a.jsx)("p",{className:"whitespace-pre-wrap text-sm leading-6 text-emerald-950",children:n}),(0,a.jsxs)(l(),{href:"/dashboard/tools/social-media-post-scheduler/calendar",className:"mt-2 inline-flex items-center gap-1.5 text-sm font-bold text-emerald-700 hover:text-emerald-900 hover:underline",children:[(0,a.jsx)(nr.A,{className:"h-4 w-4"}),"View in content calendar",(0,a.jsx)(nl.A,{className:"h-3.5 w-3.5"})]})]}):(0,a.jsxs)("details",{children:[(0,a.jsx)("summary",{className:"cursor-pointer text-xs font-semibold text-slate-500 hover:text-slate-800",children:"View schedule details"}),(0,a.jsx)("p",{className:"mt-3 whitespace-pre-wrap text-xs leading-5 text-slate-600",children:n})]}
1),r?(0,a.jsx)("div",{className:"mt-3",children:r}):null]})]})}async function nT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new URLSearchParams;n.set("ensure",!1===t.ensure?"0":"1"),t.runId&&n.set("run_id",t.runId),n.set("_",String(Date.now()));let a=await fetch("/ai/business/ad-maker/campaign-manager/boards/".concat(encodeURIComponent(e),"/state/?").concat(n.toString()),{credentials:"include",cache:"no-store",headers:{"Cache-Control":"no-cache"}}),r=await a.json().catch(()=>({}));if(!a.ok)throw Error(r.detail||r.error||"Could not load campaign manager");return r.state||{campaign:null,run:null,waves:[],tasks:[],messages:[]}}async function nM(e){var t;let n=await fetch("/ai/business/ad-maker/campaign-manager/runs/background/",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,message:e.message,source:e.source,client_timezone:e.clientTimezone,...e.platformScope?{platform_scope:e.platformScope}:{},...e.connectedSocialNetworks?{connected_social_networks:e.connectedSocialNetworks}:{},...e.outstandAccounts?{outstand_accounts:e.outstandAccounts}:{}})}),a=await n.json().catch(()=>({}));if(!n.ok)throw Error(a.detail||a.error||"Could not start campaign manager");return{runId:String(a.run_id||""),state:null!=(t=a.state)?t:null}}async function nR(e){var t;let n=await fetch("/ai/business/ad-maker/campaign-manager/boards/".concat(encodeURIComponent(e.boardId),"/reset/"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:null!=(t=e.source)?t:{source_type:"scratch"}})}),a=await n.json().catch(()=>({}));if(!n.ok)throw Error(a.detail||a.error||"Could not reset Campaign Manager");return a.state||{campaign:null,run:null,waves:[],tasks:[],messages:[]}}async function nE(e){var t,n,a;let r=await fetch("/ai/business/ad-maker/campaign-manager/runs/".concat(encodeURIComponent(e.runId),"/approve-wave/background/"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,wave_key:e.waveKey,approved:null==(t=e.approved)||t,feedback:null!=(n=e.feedback)?n:null,client_timezone:e.clientTimezone,outstand_accounts:null!=(a=e.outstandAccounts)?a:[],...e.scheduleOverrides&&e.scheduleOverrides.length>0?{schedule_overrides:e.scheduleOverrides.map(e=>({task_id:e.taskId,scheduled_time:e.scheduledTime}))}:{}})}),l=await r.json().catch(()=>({}));if(!r.ok)throw Error(l.detail||l.error||"Could not approve campaign wave")}async function nU(e){let t=await fetch("/ai/business/ad-maker/campaign-manager/runs/".concat(encodeURIComponent(e),"/cancel-message/"),{method:"POST",credentials:"include"}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.detail||n.error||"Could not stop the adjustment");return{cancelled:!!n.cancelled,message:String(n.message||"")}}function nP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,n=new URLSearchParams;return n.set("after_event_index",String(t)),"/api/ad-maker/campaign-manager/runs/".concat(encodeURIComponent(e),"/events/stream?").concat(n.toString())}async function nB(){var e,t;let n=(0,e0.Ar)(),a=await fetch("/api/graphql",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...(0,e0.vL)()},body:JSON.stringify({query:"\n query CampaignManagerMarketingStrategySources($orgId: BigInt) {\n marketingStrategyResults(\n first: 80\n orderBy: CREATED_AT_DESC\n condition: { organizationalUnitId: $orgId }\n ) {\n nodes {\n id\n resultType\n data\n checkedActions\n createdAt\n }\n }\n }\n ",variables:{orgId:n}})}),r=await a.json().catch(()=>({}));if(!a.ok||r.errors)return[];let l=null==(t=r.data)||null==(e=t.marketingStrategyResults)?void 0:e.nodes;if(!Array.isArray(l))return[];let s=new Map,i=new Map;return l.forEach(e=>{var t;let n=String(e.createdAt||""),a=n.slice(0,10)||"latest",r=String(e.resultType||"strategy"),l=e.data;if("string"==typeof l)try{l=JSON.parse(l)}catch(t){l=e.data}s.set(a,{...null!=(t=s.get(a))?t:{},[r]:l}),i.has(a)||i.set(a,n)}),Array.from(s.entries()).map(e=>{var t;let[n,a]=e;return{id:n,label:"Marketing strategy ".concat(n),createdAt:null!=(t=i.get(n))?t:"",snapshot:{sourceLabel:"Marketing strategy ".concat(n),...a}}})}var nD=n(33721);let nz=new Set(["complete","failed","cancelled"]);function nO(e){let{waveStatus:t,runStatus:n,sawExecuting:a}=e;return!!nz.has(n||"")||!!t&&"executing"!==t&&("awaiting_approval"===t?a:!["queued","pending"].includes(t))}function nF(e){return e.map(e=>"pending"===e.status?{...e,status:"failed",optimistic:!1}:e)}let nL="Use the selected marketing strategy as the campaign brief.";function nq(e,t){return e.some(e=>"user"===e.role&&e.content===t.content&&!t.existingMessageIds.includes(e.id))}function n$(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}function nK(e){return e.filter(e=>0!==e.isActive).map(e=>({id:String(e.id||"").trim(),network:String(e.network||"").trim().toLowerCase()})).filter(e=>e.id&&e.network)}let nW={x:"X / Twitter",twitter:"X / Twitter",linkedin:"LinkedIn",instagram:"Instagram",facebook:"Facebook",threads:"Threads",tiktok:"TikTok",youtube:"YouTube",bluesky:"Bluesky",pinterest:"Pinterest",google_business:"Google Business"};function nJ(e){return nW[e.toLowerCase()]||n2(e)}
1let nG=new Set(["instagram","facebook","linkedin","twitter","tiktok","threads","youtube","bluesky","pinterest","google_business"]);function nH(e){let t=String(e||"").trim().toLowerCase().replaceAll("-","_");return"x"===t?"twitter":t}function nY(e){let t=e.plan&&"object"==typeof e.plan?e.plan:{};return Array.from(new Set((Array.isArray(t.scheduled_post_inputs)?t.scheduled_post_inputs:[]).flatMap(e=>e&&"object"==typeof e?(Array.isArray(e.platforms)?e.platforms:[]).map(e=>String(e||"").trim().toLowerCase()).filter(Boolean):[])))}let nV={campaign:null,run:null,waves:[],tasks:[],messages:[]},nX=new Set(["completed","failed","skipped","cancelled"]);function nQ(e){let t=Date.parse(e||"");return Number.isFinite(t)?t:0}function nZ(e){return"planning"===e?"Planning":e.startsWith("content_creation")?"Content creation":e.startsWith("scheduling_proposal")?"Scheduling proposal":e.replaceAll("_"," ")}function n0(e){return"awaiting_wave_approval"===e||"awaiting_approval"===e?"Awaiting approval":"complete"===e?"Complete":"content_creation"===e?"Content creation":e.replaceAll("_"," ")}function n1(e){return"completed"===e||"complete"===e?(0,a.jsx)(tp.A,{className:"h-4 w-4 text-emerald-500"}):"failed"===e?(0,a.jsx)(nt.A,{className:"h-4 w-4 text-red-500"}):"running"===e||"executing"===e||"planning"===e?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin text-signal-blue"}):"queued"===e||"awaiting_approval"===e?(0,a.jsx)(nn.A,{className:"h-4 w-4 text-amber-500"}):(0,a.jsx)(tf.A,{className:"h-4 w-4 text-slate-300"})}function n2(e){return e.replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase())}function n5(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:260,n=e.split(/\s+/).join(" ");return n.length<=t?n:"".concat(n.slice(0,t).trim(),"...")}function n4(e){return null==e?"":"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):Array.isArray(e)?e.slice(0,4).map(e=>n4(e)).filter(Boolean).join("; "):"object"==typeof e?Object.entries(e).slice(0,5).map(e=>{let[t,n]=e,a=n4(n);return a?"".concat(t.replaceAll("_"," "),": ").concat(a):""}).filter(Boolean).join("; "):""}function n3(e){var t;if(!e)return[];let n=null==(t=e.snapshot)?void 0:t.content_pillars,a=[];if(Array.isArray(n))a=n;else if(n&&"object"==typeof n){let e=n.pillars;Array.isArray(e)&&(a=e)}return a.filter(e=>!!(e&&"object"==typeof e))}function n8(e){var t,n,a;let r=null==(t=e.run)?void 0:t.activeWaveKey;return null!=(a=null!=(n=e.waves.find(e=>"awaiting_approval"===e.status&&e.waveKey===r))?n:e.waves.find(e=>"awaiting_approval"===e.status))?a:null}function n6(e){var t;let{open:n,onOpenChange:r,onSelect:l}=e,[s,i]=(0,o.useState)([]),[c,d]=(0,o.useState)(null),[u,m]=(0,o.useState)(0),[h,f]=(0,o.useState)(!1);(0,o.useEffect)(()=>{if(!n)return;let e=!1;return f(!0),nB().then(t=>{if(!e){var n,a;i(t),d(null!=(a=null!=(n=t.find(e=>n3(e).length>0))?n:t[0])?a:null),m(0)}}).catch(()=>{e||i([])}).finally(()=>{e||f(!1)}),()=>{e=!0}},[n]);let g=n3(c),x=null!=(t=g[u])?t:null;return(0,o.useEffect)(()=>{m(0)},[c]),(0,a.jsx)(eQ.lG,{open:n,onOpenChange:r,children:(0,a.jsxs)(eQ.Cf,{className:"max-w-5xl bg-white",children:[(0,a.jsx)(eQ.c7,{children:(0,a.jsx)(eQ.L3,{children:"Choose a content pillar"})}),(0,a.jsxs)("div",{className:"mt-2 grid min-h-[28rem] gap-4 md:grid-cols-[18rem_1fr]",children:[(0,a.jsx)("div",{className:"min-h-0 overflow-y-auto rounded-md border border-slate-200 bg-slate-50 p-2",children:h?(0,a.jsx)("div",{className:"flex h-32 items-center justify-center",children:(0,a.jsx)(p.A,{className:"h-5 w-5 animate-spin text-slate-400"})}):0===s.length?(0,a.jsx)("div",{className:"rounded-md border border-dashed border-slate-300 bg-white p-4 text-sm text-slate-500",children:"No marketing strategies were found yet."}):(0,a.jsx)("div",{className:"space-y-2",children:s.map(e=>{let t=(null==c?void 0:c.id)===e.id,n=n3(e).length;return(0,a.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 rounded-md border p-3 text-left transition ".concat(t?"border-signal-blue bg-white shadow-sm":"border-transparent bg-transparent hover:bg-white"),onClick:()=>d(e),children:[(0,a.jsx)("span",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-signal-blue/10 text-signal-blue",children:(0,a.jsx)(na.A,{className:"h-4 w-4"})}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block truncate text-sm font-bold text-slate-900",children:e.label}),(0,a.jsx)("span",{className:"mt-1 block text-xs text-slate-500",children:n>0?"".concat(n," content pillar").concat(1===n?"":"s"):"No content pillars"})]})]},e.id)})})}),(0,a.jsxs)("div",{className:"flex min-h-0 flex-col rounded-md border border-slate-200 bg-white",children:[(0,a.jsxs)("div",{className:"border-b border-slate-200 px-4 py-3",children:[(0,a.jsx)("p",{className:"text-sm font-bold text-slate-950",children:"Campaign themes"}),(0,a.jsx)("p",{className:"mt-1 text-xs text-slate-500",children:"Pick the pillar that should guide the posts, message, audience, and objective."})]}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto bg-slate-50 p-4",children:c&&g.length>0?(0,a.jsx)("div",{className:"space-y-3",children:g.map((e,t)=>{let n=u===t,r=n4(e.theme_name)||"Content pillar ".concat(t+1),l=[["social post",e.social_posts],["blog",e.blog_topics],["website",e.website_pages],["video",e.podcast_video_topics],["email",e.email_content]].flatMap(e=>{let[t,n]=e,a=Array.isArray(n)?n.length:0;return a>0?["".concat(a," ").concat(t).concat(1===a?"":"s")]:[]});return(0,a.jsxs)("button",{type:"button",className:"w-full rounded-md border p-4 text-left transition ".concat(n?"border-signal-blue bg-white shadow-sm ring-1 ring-signal-blue":"border-slate-200 bg-white hover:border-slate-300"),onClick:()=>m(t),children:[(0,a.jsxs)("span",{className:"flex items-start justify-between gap-4",children:[(0,a.jsxs)("span",{className:"min-w-0",children:[(0,a.jsx)("span",{className:"block text-sm font-bold text-slate-950",children:r}),(0,a.jsxs)("span",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.primary_objective?(0,a.jsx)("span",{className:"rounded-full bg-signal-blue/10 px-2 py-1 text-[11px] font-bold text-signal-blue",children:n4(e.primary_objective)}):null,e.target_persona?(0,a.jsx)("span",{className:"rounded-full bg-slate-100 px-2 py-1 text-[11px] font-bold text-slate-600",children:n4(e.target_persona)}):null]})]}),(0,a.jsx)("span",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ".concat(n?"border-signal-blue bg-signal-blue text-white":"border-slate-300 bg-white"),children:n?(0,a.jsx)(tp.A,{className:"h-3.5 w-3.5"}):null})]}),e.description?(0,a.jsx)("span",{className:"mt-3 block text-sm leading-5 text-slate-700",children:n5(n4(e.description),320)}):null,l.length>0?(0,a.jsxs)("span",{className:"mt-3 block text-xs text-slate-500",children:["Includes ",l.join(", ")," ideas"]}):null]},"".concat(r,"-").concat(t))})}):(0,a.jsx)("div",{className:"rounded-md border border-dashed border-slate-300 bg-white p-5 text-sm text-slate-500",children:"This saved strategy does not contain content pillars yet. Generate and save its content pillars in Marketing Strategy, then return here."})}),(0,a.jsx)("div",{className:"border-t border-slate-200 p-3",children:(0,a.jsx)(y.$,{type:"button",className:"h-10 w-full rounded-md font-bold",disabled:!c||!x,onClick:()=>{c&&x&&l(c,x,u)},children:x?"Build campaign from ".concat(n4(x.theme_name)||"this pillar"):"Choose a content pillar"})})]})]})]})})}function n7(e){let{open:t,accounts:n,loading:r,error:l,onOpenChange:s,onRetry:i,onChoose:o}=e,c=Array.from(new Set(n.filter(e=>0!==e.isActive).map(e=>
1nJ(String(e.network||""))).filter(Boolean))),d=c.length>0?c.join(", "):"No connected social accounts";return(0,a.jsx)(eQ.lG,{open:t,onOpenChange:s,children:(0,a.jsxs)(eQ.Cf,{className:"max-w-xl bg-white",children:[(0,a.jsx)(eQ.c7,{children:(0,a.jsx)(eQ.L3,{children:"Which platforms can this campaign use?"})}),(0,a.jsx)("p",{className:"text-sm leading-6 text-slate-600",children:"Choose whether the manager should stay within accounts you have connected, or also prepare unschedulable drafts for other platforms."}),(0,a.jsxs)("div",{className:"rounded-md border border-slate-200 bg-slate-50 px-4 py-3",children:[(0,a.jsx)("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-400",children:"Connected now"}),r?(0,a.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-slate-500",children:[(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin"}),"Checking connected accounts..."]}):l?(0,a.jsxs)("div",{className:"mt-2 flex items-center justify-between gap-3",children:[(0,a.jsx)("p",{className:"text-sm text-red-600",children:l}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"h-8 shrink-0 text-xs",onClick:i,children:"Retry"})]}):(0,a.jsx)("p",{className:"mt-1 text-sm font-bold text-slate-800",children:d})]}),(0,a.jsxs)("div",{className:"grid gap-3",children:[(0,a.jsxs)("button",{type:"button",disabled:r||!!l,className:"rounded-md border-2 border-signal-blue bg-signal-blue/5 p-4 text-left transition hover:bg-signal-blue/10 disabled:cursor-not-allowed disabled:opacity-50",onClick:()=>o("connected_only"),children:[(0,a.jsx)("span",{className:"block text-sm font-bold text-slate-950",children:"Connected platforms only"}),(0,a.jsx)("span",{className:"mt-1 block text-xs leading-5 text-slate-600",children:c.length>0?"Recommended. The manager will only create social ads for ".concat(d,"."):"Recommended for safety. No social ads will be created until an account is connected."})]}),(0,a.jsxs)("button",{type:"button",disabled:r||!!l,className:"rounded-md border border-slate-200 bg-white p-4 text-left transition hover:border-slate-300 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50",onClick:()=>o("include_unconnected_drafts"),children:[(0,a.jsx)("span",{className:"block text-sm font-bold text-slate-950",children:"Include other platforms as drafts"}),(0,a.jsx)("span",{className:"mt-1 block text-xs leading-5 text-slate-600",children:"The manager may create extra platform concepts, but only connected platforms can be scheduled."})]})]})]})})}
1function n9(e){let{loading:t,onStartScratch:n,onOpenStrategyPicker:r}=e;return(0,a.jsx)("div",{className:"flex h-full items-center justify-center px-6",children:(0,a.jsxs)("div",{className:"w-full max-w-3xl text-center",children:[(0,a.jsx)("div",{className:"mx-auto mb-6 flex h-11 w-11 items-center justify-center rounded-md border border-charcoal-200 bg-white shadow-soft",children:t?(0,a.jsx)(p.A,{className:"h-5 w-5 animate-spin text-charcoal-400"}):(0,a.jsx)(eK.A,{className:"h-5 w-5 text-signal-blue"})}),(0,a.jsx)("h2",{className:"text-xl font-bold text-slate-950",children:"How should we gather the idea for this campaign?"}),(0,a.jsxs)("div",{className:"mt-8 flex flex-col items-center justify-center gap-3 sm:flex-row sm:gap-5",children:[(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"h-12 min-w-[12rem] rounded-md border-slate-300 bg-white text-sm font-bold text-slate-900 shadow-soft hover:bg-slate-50",disabled:t,onClick:n,children:"From scratch"}),(0,a.jsx)(y.$,{type:"button",variant:"outline",className:"h-12 min-w-[14rem] rounded-md border-slate-300 bg-white text-sm font-bold text-slate-900 shadow-soft hover:bg-slate-50",disabled:t,onClick:r,children:"From marketing strategy"})]})]})})}function ae(e,t){return e?"Starting tasks...":t?"Applying your changes...":"Approve tasks"}function at(e){var t;let n=ao(e);if("image"!==String(n.kind||""))return null;let a=ao(n.state),r=ao(a.metadata);if("generated_image"!==String(r.sourceKind||""))return null;let l=String(r.generationStatus||"pending"),s="ready"===l?"ready":"failed"===l?"failed":"pending",i=ao(n.asset),o=String((null==(t=(Array.isArray(i.media)?i.media.map(ao):[])[0])?void 0:t.sourceUrl)||i.url||r.sourceUrl||"").trim(),c=Number(r.imageSetPosition);return{id:String(n.id||r.outputId||""),status:s,url:"ready"===s?o:"",label:Number.isFinite(c)&&c>0?"Generated asset ".concat(c):"Generated asset",optimistic:!1}}function an(e){let{assets:t}=e;if(0===t.length)return null;let n=t.filter(e=>"pending"===e.status).length,r=t.filter(e=>"failed"===e.status).length;return(0,a.jsx)("div",{className:"flex justify-start",role:"status","aria-live":"polite",children:(0,a.jsxs)("div",{className:"max-w-[78%] rounded-md border border-slate-200 bg-white px-4 py-3 shadow-sm",children:[(0,a.jsxs)("div",{className:"mb-3 flex items-center gap-2 text-sm font-semibold text-slate-800",children:[n>0?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin text-signal-blue"}):(0,a.jsx)(tp.A,{className:"h-4 w-4 text-emerald-600"}),n>0?"Creating ".concat(t.length," asset").concat(1===t.length?"":"s","â¦"):r>0?"".concat(t.length-r," of ").concat(t.length," creative assets ready"):"Creative assets ready"]}),(0,a.jsx)("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3",children:t.map(e=>(0,a.jsx)("div",{className:"relative aspect-square min-w-24 overflow-hidden rounded-md border border-slate-200 bg-slate-100",children:"ready"===e.status&&e.url?(0,a.jsx)("img",{src:e.url,alt:e.label,className:"h-full w-full object-cover"}):"failed"===e.status?(0,a.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 bg-red-50 px-2 text-center text-xs font-semibold text-red-700",children:[(0,a.jsx)(nt.A,{className:"h-5 w-5"}),"Couldn't create this asset"]}):(0,a.jsxs)("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden",children:[(0,a.jsx)("div",{className:"absolute inset-0 animate-pulse bg-gradient-to-br from-slate-100 via-slate-200 to-slate-100"}),(0,a.jsx)(p.A,{className:"relative h-6 w-6 animate-spin text-signal-blue"})]})},e.id))}),n>0?(0,a.jsx)("p",{className:"mt-2 text-xs text-slate-500",children:"Theyâll appear here as soon as each one is saved."}):null]})})}function aa(e){let{state:t,pendingMessage:n,generatedAssets:r,onApprove:l,approving:s,adjusting:i}=e,o=t.messages.filter(e=>e.content!==nL),c=!!n&&nq(t.messages,n),d=n8(t);return(0,a.jsxs)("div",{className:"mx-auto w-full max-w-4xl space-y-4 px-5 py-6",children:[o.map(e=>{let n=t.waves.find(t=>t.id===e.waveId||t.messageId===e.id),r=!!(null==d?void 0:d.waveKey.startsWith("scheduling_proposal"))&&"assistant"===e.role&&((null==d?void 0:d.messageId)===e.id||(null==n?void 0:n.id)===(null==d?void 0:d.id)),o=function(e,t){var n,a;if("assistant"!==e.role)return null;let r=nj(e.metadata),l=nj(r.proposal),s=nj(t),i=nA(l)?l:nA(s)?s:{},o={idPrefix:e.id,scheduled:"run_complete"===r.kind&&Array.isArray(i.created_posts)&&i.created_posts.length>0};return null!=(n=function(e,t){let n=nj(e),a=(Array.isArray(n.scheduled_post_inputs)?n.scheduled_post_inputs:Array.isArray(n.inputs)?n.inputs:[]).flatMap((e,n)=>{let a=nj(e),r=nj(a.content),l=nj(a.campaignManager),s=nk(nN(a.platforms)[0]),i=nj(nj(a.platformSpecificContent)[s]),o=String(r.text||i.text||"").trim(),c=nN(r.mediaUrls).length>0?nN(r.mediaUrls):nN(i.mediaUrls);return s&&(o||0!==c.length)?[{id:"".concat(t.idPrefix,"-scheduled-post-").concat(n),platform:s,caption:o,mediaUrls:c,scheduledFor:String(a.scheduledTime||"").trim(),timezone:String(a.timezone||"UTC").trim()||"UTC",contentRole:String(l.contentRole||"").trim(),rationale:String(l.rationale||"").trim()}]:[]}),r=(Array.isArray(n.posts)?n.posts:[]).flatMap((e,n)=>{let a=nj(e),r=nk(a.platform||nN(a.platforms)[0]),l=String(a.caption||a.text||a.body_copy||a.bodyCopy||"").trim(),s=String(a.media_url||a.mediaUrl||"").trim(),i=[...s?[s]:[],...nN(a.mediaUrls),...nN(a.media_urls),...n_(a.mediaRefs),...n_(a.media_refs)].filter((e,t,n
1)=>e&&n.indexOf(e)===t);return r&&(l||0!==i.length)?[{id:"".concat(t.idPrefix,"-legacy-post-").concat(n),platform:r,caption:l,mediaUrls:i,scheduledFor:String(a.scheduled_for||a.scheduledFor||"").trim(),timezone:String(a.timezone||"UTC").trim()||"UTC",contentRole:String(a.content_role||a.contentRole||"").trim(),rationale:String(a.rationale||"").trim()}]:[]}),l=(Array.isArray(n.post_drafts)?n.post_drafts:[]).flatMap((e,n)=>{let a=nj(e),r=nk(a.platform||nN(a.platforms)[0]),l=String(a.caption||a.text||a.body_copy||a.bodyCopy||"").trim(),s=[...nN(a.mediaUrls),...nN(a.media_urls),...n_(a.mediaRefs),...n_(a.media_refs)].filter((e,t,n)=>e&&n.indexOf(e)===t);return r&&(l||0!==s.length)?[{id:"".concat(t.idPrefix,"-draft-post-").concat(n),platform:r,caption:l,mediaUrls:s,scheduledFor:String(a.scheduledFor||a.scheduled_for||"").trim(),timezone:String(a.timezone||"UTC").trim()||"UTC",contentRole:String(a.contentRole||a.content_role||a.title||"").trim(),rationale:String(a.rationale||"").trim()}]:[]}),s=a.length>0?a:l.length>0?l:r;return 0===s.length?null:{posts:s,scheduled:!!t.scheduled}}(i,o))?n:(a=e.content,/\b(scheduling tasks?|schedule proposal|scheduled posts?|posting schedule|posts scheduled)\b/i.test(a))?function(e,t){let n=e.split(/\r?\n/).map(e=>e.trim()),a=[],r=null,l=()=>{if(r){if(!r.platform||!r.caption&&0===r.mediaUrls.length){r=null;return}a.push({id:"".concat(t.idPrefix,"-text-post-").concat(a.length),platform:nk(r.platform),caption:r.caption,mediaUrls:r.mediaUrls,scheduledFor:r.scheduledFor,timezone:"UTC",contentRole:r.contentRole,rationale:r.rationale}),r=null}};for(let e of n){var s,i,o;let t=e.match(/^(\d+)\.\s+(.+)$/);if(t){l(),r={platform:(null==(o=t[2])?void 0:o.trim())||"",caption:"",mediaUrls:[],scheduledFor:"",contentRole:"",rationale:""};continue}if(!r)continue;let n=e.match(/^([A-Za-z /_-]+):\s*(.*)$/);if(!n)continue;let a=(null==(s=n[1])?void 0:s.trim().toLowerCase())||"",c=(null==(i=n[2])?void 0:i.trim())||"";"time"===a&&(r.scheduledFor=c),("approach"===a||"role"===a)&&(r.contentRole=c),("caption"===a||"draft message"===a||"draft post"===a)&&(r.caption=c),("image"===a||"media"===a||"media urls"===a||"asset"===a)&&(r.mediaUrls=function(e){var t,n;return null!=(n=null==(t=e.match(/https?:\/\/[^\s)]+/gi))?void 0:t.map(e=>e.trim()).filter(Boolean))?n:[]}(c)),("why"===a||"rationale"===a)&&(r.rationale=c)}return(l(),0===a.length)?null:{posts:a,scheduled:!!t.scheduled}}(e.content,o):null}(e,r&&d?function(e,t){var n;let a=ao(null==t?void 0:t.plan);if(Array.isArray(a.scheduled_post_inputs)||Array.isArray(a.inputs)||Array.isArray(a.post_drafts)||Array.isArray(a.posts))return a;let r=ao(null==(n=e.run)?void 0:n.outputs),l=ao(r.scheduling_proposal);return Array.isArray(l.scheduled_post_inputs)||Array.isArray(l.inputs)||Array.isArray(l.post_drafts)||Array.isArray(l.posts)?l:null}(t,d):null==n?void 0:n.plan),c=r&&d?(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:(0,a.jsxs)(y.$,{type:"button",className:"h-9 rounded-md px-4 text-xs font-bold",disabled:s||i,onClick:()=>l(d),children:[s||i?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin"}):null,ae(s,i)]})}):null;return(0,a.jsx)("div",{className:"flex ".concat("user"===e.role?"justify-end":"justify-start"," ").concat(o?"w-full":""),children:o?(0,a.jsx)(nI,{data:o,messageText:e.content,approvalAction:c}):(0,a.jsxs)("div",{className:"max-w-[78%] rounded-md border px-4 py-3 text-sm leading-6 shadow-sm ".concat("user"===e.role?"border-signal-blue bg-signal-blue text-white":"border-slate-200 bg-white text-slate-800"),children:[(0,a.jsx)("p",{className:"whitespace-pre-wrap break-words",children:e.content}),c?(0,a.jsx)("div",{className:"mt-4 border-t border-slate-100 pt-3",children:c}):null]})},e.id)}),n&&!c&&(0,a.jsx)("div",{className:"flex justify-end",role:"status","aria-live":"polite",children:(0,a.jsxs)("div",{className:"max-w-[78%] rounded-md border border-signal-blue bg-signal-blue px-4 py-3 text-sm leading-6 text-white shadow-sm",children:[(0,a.jsx)("p",{className:"whitespace-pre-wrap break-words",children:n.content}),(0,a.jsxs)("div",{className:"mt-1 flex items-center justify-end gap-1.5 text-[11px] text-white/75",children:[(0,a.jsx)(p.A,{className:"h-3 w-3 animate-spin"}),"Sending"]})]})}),(0,a.jsx)(an,{assets:r})]})}function ar(e){let{wave:t,tasks:n,approving:r,adjusting:l,onApprove:s}=e;if(!t)return null;let i=n.length;return(0,a.jsx)("div",{className:"border-b border-slate-200 bg-white px-3 py-3",children:(0,a.jsxs)("div",{className:"mx-auto flex max-w-5xl flex-col gap-3 rounded-md border border-slate-200 bg-slate-50 p-3 shadow-sm sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("p",{className:"text-sm font-bold text-slate-950",children:l?"The manager is applying your changes":"".concat(nZ(t.waveKey)," tasks are waiting for approval")}),(0,a.jsx)("p",{className:"mt-1 text-xs text-slate-500",children:l?"You can stop the adjustment to edit your message before it is applied.":i>0?"".concat(i," task").concat(1===i?"":"s"," ready. Send changes in chat, or approve to continue."):"Send changes in chat, or approve to continue."})]}),(0,a.jsxs)(y.$,{type:"button",className:"h-10 shrink-0 rounded-md px-4 text-sm font-bold",disabled:r||l,onClick:()=>s(t),children:[r||l?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin"}):null,ae(r,l)]})]})})}function al(){return(0,a.jsx)("div",{className:"border-b border-emerald-200 bg-emerald-50 px-4 py-2.5",role:"status",children:(0,a.jsxs)("div",{className:"mx-auto flex max-w-5xl flex-wrap items-center gap-2 text-sm text-emerald-900",children:[(0,a.jsx)(tp.A,{className:"h-4 w-4 shrink-0 text-emerald-600"}),(0,a.jsx)("span",{className:"font-semibold",children:"Your posts are scheduled."}),(0,a.jsxs)(l(),{href:"/dashboard/tools/social-media-post-scheduler/calendar",className:"inline-flex items-center gap-1 font-bold text-emerald-700 hover:text-emerald-900 hover:underline",children:[(0,a.jsx)(nr.A,{className:"h-4 w-4"}),"View in content calendar",(0,a.jsx)(nl.A,{className:"h-3.5 w-3.5"})]})]})})}function as(e){let{platforms:t}=e;return(0,a.jsx)("div",{className:"border-b border-amber-200 bg-amber-50 px-4 py-2.5",role:"status",children:(0,a.jsxs)("div",{className:"mx-auto flex max-w-5xl flex-wrap items-center gap-2 text-sm text-amber-900",children:[(0,a.jsx)(eH.A,{className:"h-4 w-4 shrink-0 text-amber-600"}),(0,a.jsxs)("span",{children:["This campaign targets"," ",(0,a.jsx)("span",{className:"font-bold",children:t.map(nJ).join(", ")}),", but no matching account is connected yet â those posts cannot be scheduled until you connect one."]}),(0,a.jsxs)(l(),{href:"/dashboard/tools/social-media-post-scheduler",className:"inline-flex items-center gap-1 font-bold text-amber-800 underline hover:text-amber-950",children:["Connect accounts",(0,a.jsx)(nl.A,{className:"h-3.5 w-3.5"})]})]})})}function ai(e){let{source:t}=e;return(0,a.jsx)("div",{className:"flex h-full items-center justify-center px-6 text-center",children:(0,a.jsxs)("div",{className:"max-w-md",children:[(0,a.jsx)("div",{className:"mx-auto mb-4 flex h-10 w-10 items-center justify-center rounded-md border border-charcoal-200 bg-white",children:(0,a.jsx)(ns.A,{className:"h-5 w-5 text-slate-500"})}),(0,a.jsx)("h2",{className:"text-lg font-bold text-slate-950",children:"Campaign Manager"}),(0,a.jsx)("p",{className:"mt-2 text-sm leading-6 text-slate-500",children:"marketing_strategy"===t.source_type?"Starting from the selected strategy.":"Tell the manager the campaign goal and it will start planning."})]})})}function ao(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function ac(e){var t,n;let{task:r}=e,l="completed"===r.status,s=function(e){let t=ao(e.input),n=ao(t.display_detail),a=ao(t.content_output),r=String(n.platform||a.platform||"").trim();return[r,function(e,t){let n=String(e||"").trim();if(!n)return"";let a=new Date(n);if(Number.isNaN(a.getTime()))return n;let r=String(t||"").trim()||n$();try{let e=new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit",timeZone:r,timeZoneName:"short"}).format(a);return"".concat(e," (").concat(r,")")}catch(e){return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(a)}}(n.scheduled_for,n.timezone),function(e,t){var n;let a=String(e.media_label||"").trim();if(a)return a;let r=String(e.asset_kind||t.asset_kind||t.assetKind||"").trim(),l=String(e.format||t.format||"").trim(),s=String(e.ordered_media_intent||t.ordered_media_intent||"").trim(),i=null!=(n=e.image_count)?n:t.image_count,o="number"==typeof i?i:Number.parseInt(String(i||""),10);return"email_html"===r?"Content":"social_video"===r?l&&l.toLowerCase().includes("video")?l:"15s video ad":"carousel"===s||Number.isFinite(o)&&o>1?"Carousel ad (".concat(Number.isFinite(o)&&o>1?o:2," slides)"):l&&l.toLowerCase().includes("image")?l:"Static image ad"}
1(n,a)].filter(Boolean).join(" \xb7 ")}(r),i=function(e){let t=ao(e.input);if("create_scheduled_post"!==t.mode)return null;let n=ao(t.display_detail),a=String(n.caption||"").trim(),r=Array.isArray(n.media_urls)?n.media_urls.map(e=>String(e||"").trim()).filter(Boolean):[];return{caption:a,asset:String(n.asset_label||"").trim()||(r.length>0?"".concat(r.length," generated media asset").concat(1===r.length?"":"s"):"No media asset"),assetUrl:r[0]||"",approach:String(n.content_role||"").trim(),rationale:String(n.rationale||"").trim()}}(r),o=i?null:function(e){let t=ao(e.input),n=ao(t.display_detail),a=ao(t.content_output),r=String(n.headline||a.headline||"").trim(),l=String(n.body_copy||a.body_copy||a.bodyCopy||"").trim(),s=String(n.visual_concept||a.visual_concept||a.visualConcept||"").trim(),i=String(n.cta||a.cta||"").trim();return[r,l,s,i].some(Boolean)?{role:String(n.content_role||a.content_role||a.contentRole||"").trim(),headline:r,bodyCopy:l,takeaway:String(n.audience_takeaway||a.audience_takeaway||a.audienceTakeaway||"").trim(),visualConcept:s,cta:i,tone:String(n.platform_tone||a.platform_tone||a.platformTone||"").trim(),assetUsage:String(n.asset_usage||a.asset_usage||a.assetUsage||"").trim()}:null}(r);return(0,a.jsxs)("div",{className:"group relative flex gap-3 py-2",children:[(0,a.jsx)("span",{className:"mt-1 flex h-5 w-5 shrink-0 items-center justify-center",children:n1(r.status)}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,a.jsx)("p",{className:"min-w-0 text-sm font-semibold leading-5 ".concat(l?"text-slate-500":"text-slate-900"),children:"Synthesize campaign plan"===r.title?"Prepare campaign direction":"Check the plan for missing campaign details"===r.title?"Review campaign assumptions":r.title.replace(/\s+\([^)]*(?:image|images|facebook|instagram|email|website|linkedin)[^)]*\)\s*$/i,"")}),(0,a.jsx)("span",{className:"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ".concat(l?"bg-emerald-50 text-emerald-700":"bg-slate-200 text-midnight-logic"),children:"completed"===(t=r.status)?"Complete":"running"===t||"executing"===t||"planning"===t?"In progress":"queued"===t||"pending"===t?"Proposed":n0(t)})]}),s?(0,a.jsx)("p",{className:"mt-0.5 text-xs text-slate-500",children:s}):null,i?(0,a.jsxs)("div",{className:"mt-1.5 space-y-1 rounded-md border border-slate-100 bg-white p-2 text-xs leading-5 text-slate-600",children:[i.approach?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Approach:"})," ",i.approach]}):null,(0,a.jsxs)("p",{className:"line-clamp-3 whitespace-pre-wrap",children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Caption:"})," ",i.caption||"No caption"]}),(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Asset:"})," ",i.asset,i.assetUrl?(0,a.jsxs)(a.Fragment,{children:[" \xb7 ",(0,a.jsx)("a",{href:i.assetUrl,target:"_blank",rel:"noreferrer",className:"font-semibold text-signal-blue hover:underline",children:"View asset"})]}):null]}),i.rationale?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Why this slot:"})," ",i.rationale]}):null]}):null,o?(0,a.jsxs)("div",{className:"mt-1.5 space-y-1 rounded-md border border-slate-100 bg-white p-2 text-xs leading-5 text-slate-600",children:[o.role?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Role:"})," ",o.role]}):null,o.headline?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Headline / subject:"})," ",o.headline]}):null,o.bodyCopy?(0,a.jsxs)("p",{className:"line-clamp-4 whitespace-pre-wrap",children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Draft message:"})," ",o.bodyCopy]}):null,o.takeaway?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Audience takeaway:"})," ",o.takeaway]}):null,o.visualConcept?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Visual / layout:"})," ",o.visualConcept]}):null,o.cta?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"CTA:"})," ",o.cta]}):null,o.tone?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Tone:"})," ",o.tone]}):null,o.assetUsage?(0,a.jsxs)("p",{children:[(0,a.jsx)("span",{className:"font-semibold text-slate-700",children:"Assets:"})," ",o.assetUsage]}):null]}):null,(0,a.jsx)("p",{className:"mt-0.5 text-[11px] uppercase tracking-wide text-slate-400",children:{campaign_manager:"Manager",campaign_planner:"Planner",content_creator:"Creative",email_marketer:"Content",image_creator:"Creative",social_media_manager:"Social",schedule_planner:"Scheduling",qa_reviewer:"Review",context_researcher:"Research"}[n=r.agentType]||n.replaceAll("_"," ")})]})]})}function ad(e){let{wave:t,tasks:n}=e,r="completed"===t.status;return(0,a.jsxs)("section",{className:"border-b border-slate-100 px-4 py-3 last:border-b-0",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-start gap-2",children:[(0,a.jsx)("span",{className:"mt-0.5",children:n1(t.status)}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"text-sm font-bold text-slate-950",children:nZ(t.waveKey)}),(0,a.jsx)("p",{className:"text-xs capitalize text-slate-500",children:n0(t.status)})]})]}),n.length>0?(0,a.jsx)("div",{className:r?"space-y-1 opacity-80":"space-y-1",children:n.map(e=>(0,a.jsx)(ac,{task:e},e.id))}):(0,a.jsx)("p",{className:"rounded-md border border-dashed border-slate-300 bg-slate-50 p-3 text-sm text-slate-500",children:"Proposed tasks will appear here."})]})}function au(e){let{trace:t}=e;return 0===t.length?null:(0,a.jsxs)("section",{className:"border-b border-slate-100 px-4 py-3",children:[(0,a.jsx)("div",{className:"mb-2",children:(0,a.jsx)("p",{className:"text-xs font-bold uppercase tracking-wide text-slate-500",children:"Context gathered"})}),(0,a.jsx)("div",{className:"space-y-2",children:t.map((e,t)=>{var n;return(0,a.jsxs)("div",{className:"flex items-start gap-2",children:[(0,a.jsx)("span",{className:"mt-0.5",children:n1(e.status)}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"text-sm font-semibold text-slate-950",children:"context_router"===(n=e.toolName)?"Chose context sources":"inspect_strategy"===n?"Read selected strategy":"inspect_board"===n?"Inspected board context":"web_research"===n?"Checked public context":n2(n)}),e.query?(0,a.jsx)("p",{className:"text-xs text-slate-500",children:e.query}):null,e.rationale?(0,a.jsx)("p",{className:"text-xs text-slate-500",children:e.rationale}):null]})]},"".concat(e.toolName,"-").concat(t))})})]})}function am(e){var t;let{state:n}=e,r=(0,o.useMemo)(()=>{var e,t=null==(e=n.run)?void 0:e.plan;let a=null==t?void 0:t.tool_router;if(!a||"object"!=typeof a)return[];let r=a.tool_trace;return Array.isArray(r)?r.map(e=>{if(!e||"object"!=typeof e)return null;let t=String(e.tool_name||e.toolName||"").trim();return t?{toolName:t,status:String(e.status||"completed"),rationale:n5(String(e.rationale||""),140),query:e.query?n5(String(e.query),120):void 0}:null}
1).filter(Boolean):[]},[null==(t=n.run)?void 0:t.plan]),l=(0,o.useMemo)(()=>n.tasks.filter(e=>"manager_tool"===e.agentType).map(e=>{var t;let n=null!=(t=e.input)?t:{},a=String(n.tool_name||e.title||"").trim();return a?{toolName:a,status:e.status,rationale:n5(String(n.rationale||""),140),query:n.query?n5(String(n.query),120):void 0}:null}).filter(Boolean),[n.tasks]),s=l.length>0?l:r,i=(0,o.useMemo)(()=>{let e=new Map;return n.tasks.filter(e=>"context_researcher"!==e.agentType&&"manager_tool"!==e.agentType&&"cancelled"!==e.status).forEach(t=>{var n;let a=null!=(n=e.get(t.waveId))?n:[];a.push(t),e.set(t.waveId,a)}),e},[n.tasks]);return(0,a.jsxs)("aside",{className:"flex h-64 w-full flex-col bg-white shadow-[0_-10px_24px_rgba(15,23,42,0.06)] lg:h-full lg:max-w-[24rem] lg:shadow-[-10px_0_24px_rgba(15,23,42,0.06)]",children:[(0,a.jsxs)("div",{className:"border-b border-slate-100 px-5 py-5",children:[(0,a.jsx)("p",{className:"text-lg font-bold text-slate-950",children:"Activities"}),(0,a.jsx)("p",{className:"mt-1 text-xs capitalize text-slate-500",children:n.run?n0(n.run.status):"Waiting to start"})]}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto",children:0===n.waves.length?(0,a.jsx)("div",{className:"p-4",children:(0,a.jsx)("p",{className:"rounded-md border border-dashed border-slate-300 bg-slate-50 p-3 text-sm text-slate-500",children:"Proposed tasks will appear here."})}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(au,{trace:s}),n.waves.map(e=>{var t;return(0,a.jsx)(ad,{wave:e,tasks:null!=(t=i.get(e.id))?t:[]},e.id)})]})})]})}function ap(e){var t,n,r,l,i,c,d,u,m,h,f;let{boardId:g,boardName:x,onBoardStateChanged:b,onRunningChange:v,initialStart:w}=e,[j,N]=(0,o.useState)(nV),[_,k]=(0,o.useState)({source_type:"scratch",name:x}),[A,C]=(0,o.useState)(""),[S,I]=(0,o.useState)(null),[T,M]=(0,o.useState)([]),[R,E]=(0,o.useState)(!0),[U,P]=(0,o.useState)(!1),[B,D]=(0,o.useState)(!1),[z,O]=(0,o.useState)(null),[F,L]=(0,o.useState)(!1),[q,$]=(0,o.useState)(null),[K,W]=(0,o.useState)(!1),[J,G]=(0,o.useState)(!1),[H,Y]=(0,o.useState)(!1),[V,X]=(0,o.useState)(null),[Q,Z]=(0,o.useState)([]),[ee,et]=(0,o.useState)(!1),[en,ea]=(0,o.useState)(null),[er,el]=(0,o.useState)(!1),es=(0,o.useRef)(-1),ei=(0,o.useRef)(null),eo=(0,o.useRef)(!1),ec=(0,o.useRef)(null),ed=(0,o.useRef)(null),eu=(0,o.useRef)(""),em=(0,o.useRef)(""),ep=(0,s.useRouter)(),eh=(0,s.usePathname)(),ef=(0,s.useSearchParams)(),eg=(0,o.useRef)(null),ex=(0,o.useRef)(null),eb=K||j.messages.length>0,ey=(null==(t=j.run)?void 0:t.awaitingUserAction)==="provide_campaign_context",ev=(0,o.useMemo)(()=>n8(j),[j]),ew=(0,o.useMemo)(()=>ev?j.tasks.filter(e=>e.waveId===ev.id&&"manager_tool"!==e.agentType&&"cancelled"!==e.status):[],[ev,j]),ej=null!==z,eN=(null==(n=j.run)?void 0:n.status)==="complete",e_=!!ev&&!!j.run&&!nz.has((null==(r=j.run)?void 0:r.status)||"")&&(null==(l=j.run)?void 0:l.awaitingUserAction)!=="approve_wave"&&!ej,ek=U||!!S||e_,eA=ek&&!!ev&&!!(null==(i=j.run)?void 0:i.id),{researchData:eC}=tt(),eS="ad-maker:campaign-manager:".concat(g,":run"),eI=tl(g),eT=U||B||ej||ek||!!(j.run&&!nz.has(j.run.status)&&"approve_wave"!==j.run.awaitingUserAction&&"provide_campaign_context"!==j.run.awaitingUserAction);(0,o.useEffect)(()=>{null==v||v(eT)},[eT,v]),(0,o.useEffect)(()=>()=>null==v?void 0:v(!1),[v]);let eM=(0,o.useCallback)(e=>{e&&window.sessionStorage.setItem(eS,e)},[eS]),eR=(0,o.useCallback)(async e=>{var t;let n=await nT(g,{ensure:!1,runId:e});return N(t=>(function(e,t,n){var a,r;if(n&&(null==(a=e.run)?void 0:a.id)===n&&(null==(r=t.run)?void 0:r.id)!==n)return e;if(!e.run||!t.run||e.run.id!==t.run.id)return t;let l=nQ(e.run.updatedAt);if(nQ(t.run.updatedAt)<l||nz.has(e.run.status)&&!nz.has(t.run.status))return e;let s=new Map(e.waves.map(e=>[e.id,e])),i=t.waves.map(e=>{let t=s.get(e.id);return t&&nX.has(t.status)&&!nX.has(e.status)?t:e});return{...t,waves:i}})(t,n,e)),eM(null==(t=n.run)?void 0:t.id),n},[g,eM]);(0,o.useEffect)(()=>{let e=!1;return E(!0),eR(window.sessionStorage.getItem(eS)).catch(t=>{e||$(t instanceof Error?t.message:"Could not load Campaign Manager")}).finally(()=>{e||E(!1)}),()=>{e=!0}},[eR,eS]),(0,o.useEffect)(()=>{em.current=A;let e=window.setTimeout(()=>{to(eI,A)},300);return()=>window.clearTimeout(e)},[eI,A]),(0,o.useEffect)(()=>()=>{to(eI,em.current)},[eI]),(0,o.useEffect)(()=>{W(!1),G(!1),Y(!1),X(null),Z([]),ea(null),el(!1),k({source_type:"scratch",name:x});let e=ti(tl(g));em.current=e,C(e),I(null),O(null),ei.current=null,eo.current=!1,ec.current=null,es.current=-1},[g,x]),(0,o.useEffect)(()=>{var e;if(!z){eo.current=!1;return}let t=j.waves.find(e=>e.waveKey===z);(null==t?void 0:t.status)==="executing"&&(eo.current=!0),nO({waveStatus:null==t?void 0:t.status,runStatus:null==(e=j.run)?void 0:e.status,sawExecuting:eo.current})&&(ei.current=null,O(null),M(e=>nF(e)))},[z,j.waves,null==(c=j.run)?void 0:c.status]),(0,o.useEffect)(()=>{var e;let t=null==(e=j.run)?void 0:e.id;if(!t||!z)return;let n=!1,a=null,r=async()=>{try{var e;let a=await eR(t);if(n)return;let r=a.waves.find(e=>e.waveKey===z);if((null==r?void 0:r.status)==="executing"&&(eo.current=!0),nO({waveStatus:null==r?void 0:r.status,runStatus:null==(e=a.run)?void 0:e.status,sawExecuting:eo.current})){ei.current=null,O(null),M(e=>nF(e));return}}catch(e){}n||(a=window.setTimeout(r,1500))};return a=window.setTimeout(r,750),()=>{n=!0,null!==a&&window.clearTimeout(a)}},[z,eR,null==(d=j.run)?void 0:d.id]),(0,o.useEffect)(()=>{var e;null==(e=eg.current)||e.scrollTo({top:eg.current.scrollHeight})},[S,j.messages.length]),(0,o.useEffect)(()=>{S&&nq(j.messages,S)&&I(null)},[S,j.messages]),(0,o.useEffect)(()=>{var e;let t=null==(e=j.run)?void 0:e.id;if(!S||!t)return;let n=!1,a=null,r=async()=>{try{let e=await eR(t);if(n||nq(e.messages,S))return}catch(e){}n||(a=window.setTimeout(r,1500))};return a=window.setTimeout(r,750),()=>{n=!0,null!==a&&window.clearTimeout(a)}},[S,eR,null==(u=j.run)?void 0:u.id]),(0,o.useEffect)(()=>{var e,t;let n=null==(e=j.run)?void 0:e.id,a=(null==(t=j.run)?void 0:t.status)||"";if(!n||["created","complete","failed","cancelled"].includes(a))return;let r=new EventSource(nP(n,es.current)),l=e=>{try{let t=JSON.parse(e.data||"{}"),a=Number(t.last_event_index);Number.isFinite(a)&&(es.current=a);let l=t.run&&"object"==typeof t.run?t.run:null;if(l&&String(l.id||"")===n){let e=String(l.status||"");N(t=>{var a,r;return(null==(a=t.run)?void 0:a.id)===n&&e?{...t,run:{...t.run,status:e,activeWaveIndex:Number(null!=(r=l.active_wave_index)?r:t.run.activeWaveIndex),activeWaveKey:null===l.active_wave_key?null:String(l.active_wave_key||t.run.activeWaveKey||"")||null,awaitingUserAction:null===l.awaiting_user_action?null:String(l.awaiting_user_action||t.run.awaitingUserAction||"")||null,updatedAt:String(l.updated_at||t.run.updatedAt)}}:t}),nz.has(e)&&(ei.current=null,O(null),r.close())}let s=Array.isArray(t.events)?t.events.filter(e=>!!(e&&"object"==typeof e&&!Array.isArray(e))):[],i=s.filter(e=>"content_generation_fallback"===e.type).length,o=s.some(e=>
1"content_generation_incomplete"===e.type);(i>0||o)&&(M(e=>{if(o)return nF(e);let t=i;return e.map(e=>"pending"!==e.status||t<=0?e:(t-=1,{...e,status:"failed",optimistic:!1}))}),o&&(ei.current=null,O(null)));let c=s.flatMap(e=>{let t=ao(e.payload),n=ao(t.payload);return(Array.isArray(n.board_items)?n.board_items:[]).map(at).filter(e=>!!(null==e?void 0:e.id))});c.length>0&&M(e=>{let t=new Map(e.filter(e=>!e.optimistic).map(e=>[e.id,e]));return c.forEach(e=>t.set(e.id,e)),Array.from(t.values())}),s.some(e=>{let t=e.payload&&"object"==typeof e.payload?e.payload:{},n=t.payload&&"object"==typeof t.payload?t.payload:{};return"board_clutter_removed"===e.type||Array.isArray(n.board_items)})&&(null==b||b()),eR(n).catch(()=>{})}catch(e){}};return r.addEventListener("run",l),r.addEventListener("done",e=>{r.close(),l(e)}),r.addEventListener("error",()=>{}),()=>r.close()},[b,eR,null==(m=j.run)?void 0:m.id,null==(h=j.run)?void 0:h.status]);let eE=(0,o.useCallback)(()=>{window.setTimeout(()=>{var e;return null==(e=ex.current)?void 0:e.focus()},50)},[]),eU=(0,o.useCallback)(async(e,t,n)=>{let a=e!==nL;P(!0),$(null),C(""),em.current="",a&&(eu.current=e,I({content:e,existingMessageIds:j.messages.map(e=>e.id)}));try{var r,l,s;let a=(0,nD.tq)(t,eC,{businessName:x}),i=await nM({boardId:g,message:e,source:a,clientTimezone:n$(),platformScope:null==n?void 0:n.scope,connectedSocialNetworks:n?nK(n.accounts).map(e=>e.network):void 0,outstandAccounts:n?nK(n.accounts):void 0});tc(eI),i.state&&(N(i.state),eM(null==(r=i.state.run)?void 0:r.id)),eM(i.runId);let o=ed.current;if(o&&((0,nD.NS)(o),ed.current=null,ef.get(nD.F9))){let e=new URLSearchParams(ef.toString());e.delete(nD.F9);let t=e.toString();ep.replace(t?"".concat(eh,"?").concat(t):eh)}await new Promise(e=>setTimeout(e,450));try{await eR(i.runId||(null==(s=i.state)||null==(l=s.run)?void 0:l.id))}catch(e){i.state||$(e instanceof Error?e.message:"Message sent, but the conversation could not refresh")}}catch(t){I(null),a&&C(t=>t||e),$(t instanceof Error?t.message:"Could not start Campaign Manager")}finally{P(!1)}},[g,x,eI,eh,eR,eM,eC,ep,ef,j.messages]),eP=(0,o.useCallback)(async()=>{et(!0),ea(null);try{let e=await (0,e2.B)({limit:100,offset:0});Z((Array.isArray(e.data)?e.data:[]).filter(e=>0!==e.isActive)),el(!0)}catch(e){Z([]),ea(e instanceof Error?e.message:"Could not check connected social accounts.")}finally{et(!1)}},[]);(0,o.useEffect)(()=>{!(!j.run||nz.has(j.run.status))&&(er||ee||en||eP())},[en,er,eP,ee,j.run]);let eB=(0,o.useMemo)(()=>(function(e){var t;let n=ao(null==(t=e.run)?void 0:t.outputs);if((Array.isArray(n.scheduled_posts)?n.scheduled_posts:[]).length>0)return!0;let a=ao(n.scheduling_proposal);return!!Array.isArray(a.created_posts)&&a.created_posts.length>0||e.waves.some(e=>{if(!e.waveKey.startsWith("scheduling_proposal"))return!1;let t=ao(e.plan);return Array.isArray(t.created_posts)&&t.created_posts.length>0})})(j),[j]),eD=(0,o.useMemo)(()=>{if(!j.run||nz.has(j.run.status)||!er)return[];let e=new Set(Q.filter(e=>0!==e.isActive).map(e=>nH(e.network)));return(function(e){var t;let n=ao(null==(t=e.run)?void 0:t.plan),a=ao(n.content_plan);return Array.from(new Set([...Array.isArray(a.platforms)?a.platforms:[],...e.waves.filter(e=>e.waveKey.startsWith("scheduling_proposal")).flatMap(e=>nY(e))].map(nH).filter(e=>e&&nG.has(nH(e)))))})(j).filter(t=>!e.has(t))},[Q,er,j]),ez=(0,o.useCallback)(async()=>{Y(!0),await eP()},[eP]),eO=(0,o.useCallback)(async(e,t)=>{if(j.messages.length>0)return void await eU(e,t);X({message:e,source:t}),await ez()},[ez,eU,j.messages.length]);(0,o.useEffect)(()=>{w&&!R&&!U&&!V&&ec.current!==w.intentId&&(j.messages.length>0||j.run||(ec.current=w.intentId,ed.current=w.intentId,k(w.source),W(!0),eO(w.message,w.source)))},[w,R,V,eO,U,j.messages.length,j.run]);let eF=(0,o.useCallback)(e=>{V&&(Y(!1),X(null),eU(V.message,V.source,{scope:e,accounts:Q}))},[Q,V,eU]),eL=(0,o.useCallback)(()=>{k({source_type:"scratch",name:x}),W(!0),eE()},[x,eE]),eq=(0,o.useCallback)((e,t,n)=>{let a=n4(t.theme_name)||"Content pillar ".concat(n+1),r={source_type:"marketing_strategy",source_ref_id:e.id,name:a,strategy_snapshot:function(e,t,n){let a=n4(t.theme_name)||"Content pillar ".concat(n+1);return{...e.snapshot,sourceLabel:"".concat(e.label,": ").concat(a),content_pillars:[t],selected_content_pillar:t,campaign_focus:{type:"content_pillar",theme_name:a,original_strategy_id:e.id,original_strategy_label:e.label}}}
1(e,t,n)};k(r),W(!0),G(!1),eO(function(e,t){let n=n4(e.theme_name)||"Content pillar ".concat(t+1),a=[e.primary_objective?"Primary objective: ".concat(n4(e.primary_objective),"."):"",e.target_persona?"Target audience: ".concat(n4(e.target_persona),"."):"",e.description?"Direction: ".concat(n4(e.description)):""].filter(Boolean);return['Create a campaign from the "'.concat(n,'" content pillar.'),...a].join(" ")}(t,n),r)},[eO]),e$=(0,o.useCallback)(async()=>{let e=A.trim();e&&!U&&!ek&&eb&&await eO(e,_)},[ek,eb,A,eO,U,_]),eK=(0,o.useCallback)(async()=>{var e;let t=null==(e=j.run)?void 0:e.id;if(t&&!B){D(!0),$(null);try{let e=await nU(t),n=e.message||eu.current;I(null),M([]),e.cancelled&&n&&C(e=>e.trim()?e:n),await eR(t).catch(()=>{}),eE()}catch(e){$(e instanceof Error?e.message:"Could not stop the adjustment")}finally{D(!1)}}},[eE,eR,null==(f=j.run)?void 0:f.id,B]),eW=(0,o.useCallback)(async e=>{if(!j.run||ei.current)return;let t=j.run.id;ei.current=e.waveKey,eo.current=!1,O(e.waveKey),$(null),N(t=>({...t,tasks:t.tasks.map(t=>t.waveId!==e.id||["completed","cancelled"].includes(t.status)?t:{...t,status:"running"})})),e.waveKey.startsWith("content_creation")&&M(Array.from({length:Math.min(8,Math.max(1,j.tasks.filter(t=>t.waveId===e.id&&"cancelled"!==t.status).reduce((e,t)=>{var n,a;let r=ao(t.input),l=ao(r.display_detail),s=ao(r.content_output),i=String(l.asset_kind||s.asset_kind||s.assetKind||"").toLowerCase();if(i.includes("email")||i.includes("video"))return e;let o=Number(null!=(a=null!=(n=l.image_count)?n:s.image_count)?a:1);return e+(Number.isFinite(o)?Math.max(1,o):1)},0)))},(n,a)=>({id:"optimistic-".concat(t,"-").concat(e.id,"-").concat(a),status:"pending",url:"",label:"Generated asset ".concat(a+1),optimistic:!0})));try{let n=[];if(e.waveKey.startsWith("scheduling_proposal")){let t=await (0,e2.B)({limit:100,offset:0});n=nK(Array.isArray(t.data)?t.data:[]);let a=new Set(n.map(e=>e.network)),r=nY(e).filter(e=>!a.has(e));if(r.length>0)throw Error("Connect ".concat(r.join(" and ")," before starting this schedule."))}await nE({boardId:g,runId:t,waveKey:e.waveKey,approved:!0,clientTimezone:n$(),outstandAccounts:n})}catch(e){ei.current=null,O(null),M([]),await eR(t).catch(()=>{}),$(e instanceof Error?e.message:"Could not approve tasks")}},[g,eR,j.run,j.tasks]),eJ=(0,o.useCallback)(async()=>{if(F)return;let e={source_type:"scratch",name:x};L(!0),$(null);try{var t;let n=await nR({boardId:g,source:e});es.current=-1,ei.current=null,eo.current=!1,O(null),N(n),eM(null==(t=n.run)?void 0:t.id),k(e),W(!1),G(!1),Y(!1),X(null),Z([]),ea(null),el(!1),C(""),em.current="",tc(eI),I(null),M([])}catch(e){$(e instanceof Error?e.message:"Could not start a new campaign chat")}finally{L(!1)}},[g,x,eI,eM,F]);return(0,a.jsxs)("div",{className:"absolute inset-0 z-0 flex flex-col bg-[#f7f8fb] pt-12 lg:flex-row",onPointerDown:e=>e.stopPropagation(),children:[(0,a.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[(j.messages.length>0||eb)&&(0,a.jsx)("div",{className:"absolute right-4 top-3 z-10",children:(0,a.jsxs)(y.$,{type:"button",variant:"outline",className:"h-9 gap-2 rounded-md bg-white px-3 text-xs font-bold shadow-sm",disabled:F||U||ej,onClick:()=>void eJ(),children:[F?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,a.jsx)(ni.A,{className:"h-3.5 w-3.5"}),"New chat"]})}),(0,a.jsx)(n6,{open:J,onOpenChange:G,onSelect:eq}),(0,a.jsx)(n7,{open:H,accounts:Q,loading:ee,error:en,onOpenChange:e=>{if(Y(e),!e&&V){let e=V.message;e&&e!==nL&&C(t=>t.trim()?t:e),X(null),eE()}},onRetry:()=>void eP(),onChoose:eF}),q&&(0,a.jsx)("div",{className:"border-b border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700",children:q}),eD.length>0&&(0,a.jsx)(as,{platforms:eD}),eB&&(0,a.jsx)(al,{}),(0,a.jsx)("div",{ref:eg,className:"min-h-0 flex-1 overflow-y-auto",children:eb?0!==j.messages.length||S?(0,a.jsx)(aa,{state:j,pendingMessage:S,generatedAssets:T,onApprove:eW,approving:ej,adjusting:ek}):(0,a.jsx)(ai,{source:_}):(0,a.jsx)(n9,{loading:R,onStartScratch:eL,onOpenStrategyPicker:()=>G(!0)})}),eb&&(0,a.jsxs)("div",{className:"border-t border-slate-200 bg-white",children:[(0,a.jsx)(ar,{wave:ev,tasks:ew,approving:ej,adju
1sting:ek,onApprove:eW}),(0,a.jsx)("div",{className:"p-3",children:(0,a.jsxs)("div",{className:"mx-auto flex max-w-5xl items-end gap-2",children:[(0,a.jsx)(eZ.T,{ref:ex,value:A,onChange:e=>C(e.target.value),placeholder:ey?"Answer the campaign questions...":eN?"Describe the next campaign you want to run from this strategy...":"marketing_strategy"===_.source_type?"Add extra direction...":"Tell the manager the campaign goal...",disabled:U,className:"max-h-36 min-h-[48px] flex-1 resize-none rounded-md border-slate-200 bg-white text-sm shadow-sm focus-visible:ring-0",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),!U&&A.trim()&&e$())}}),eA?(0,a.jsxs)(y.$,{type:"button",variant:"outline",className:"h-12 gap-2 rounded-md border-slate-300 px-5 font-bold text-slate-900",disabled:B,onClick:()=>void eK(),children:[B?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin"}):(0,a.jsx)(no.A,{className:"h-3.5 w-3.5 fill-current"}),B?"Stopping...":"Stop"]}):(0,a.jsx)(y.$,{type:"button",className:"h-12 gap-2 rounded-md px-5 font-bold",disabled:U||ek||!A.trim(),onClick:()=>void e$(),children:U||ek?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin"}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eY.A,{className:"h-4 w-4"}),"Send",(0,a.jsx)(tr,{})]})})]})})]})]}),(0,a.jsx)(am,{state:j})]})}var ah=n(71613),af=n(35888),ag=n(18835),ax=n(485);let ab=[{label:"Launch campaign from my website",icon:af.A},{label:"Week of posts",icon:ag.A},{label:"Promote an offer",icon:ax.A}];function ay(e){let{value:t,onChange:n,onSubmit:r,loading:l,disabled:s,disabledReason:i}=e,o=l||!!s,c=0===t.trim().length,d=!o&&!c;return(0,a.jsxs)("section",{"aria-labelledby":"studio-ask-heading",className:"flex flex-col gap-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{id:"studio-ask-heading",className:"text-[1.08rem] font-extrabold text-midnight-logic",children:"What do you want to make?"}),(0,a.jsx)("p",{className:"mt-1 text-[0.8rem] font-medium leading-[1.45] text-auth-muted",children:"We draft a brief from your Business Brain sources."})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)("p",{id:"studio-ask-suggestions",className:"text-[0.78rem] font-bold text-auth-ink-soft",children:"Start from"}),(0,a.jsx)("div",{role:"group","aria-labelledby":"studio-ask-suggestions",className:"flex flex-wrap gap-2",children:ab.map(e=>{let{label:r,icon:l}=e,s=t.trim()===r;return(0,a.jsxs)("button",{type:"button","aria-pressed":s,disabled:o,onClick:()=>n(r),className:(0,Y.cn)("inline-flex min-h-[38px] items-center gap-2 rounded-full border-[1.5px] px-3.5 text-[0.8rem] font-bold transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50",s?"border-signal-blue bg-signal-blue text-white":"border-auth-field-border bg-auth-field text-anchor-blue hover:border-signal-blue"),children:[(0,a.jsx)(l,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),r]},r)})})]}),(0,a.jsxs)("div",{className:(0,Y.cn)("flex flex-col rounded-[16px] border-[1.5px] border-control-border bg-white transition-colors","has-[textarea:focus-visible]:ring-2 has-[textarea:focus-visible]:ring-signal-blue has-[textarea:focus-visible]:ring-offset-2",o&&"bg-cloud-slate"),children:[(0,a.jsx)("label",{htmlFor:"studio-ask-field",className:"sr-only",children:"Describe your campaign"}),(0,a.jsx)("textarea",{id:"studio-ask-field",value:t,rows:3,disabled:o,placeholder:"Describe the campaign, launch or offer. Mention the product, the audience and the deal.",className:"max-h-48 min-h-[88px] w-full resize-none rounded-t-[16px] bg-transparent px-4 pt-3.5 text-[0.92rem] font-medium leading-[1.5] text-midnight-logic [field-sizing:content] placeholder:text-auth-placeholder focus:outline-none disabled:cursor-not-allowed",onChange:e=>n(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d&&r())}}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3 py-2.5 pl-4 pr-2.5",children:[(0,a.jsx)("p",{id:"studio-ask-hint",className:"min-w-0 text-[0.74rem] font-medium text-auth-muted",children:c?"Describe it, or start from a suggestion.":(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("kbd",{className:"rounded border border-auth-hairline bg-cloud-slate px-1 font-sans text-[0.7rem] font-bold text-auth-ink-soft",children:"â/Ctrl"})," ","+"," ",(0,a.jsx)("kbd",{className:"rounded border border-auth-hairline bg-cloud-slate px-1 font-sans text-[0.7rem] font-bold text-auth-ink-soft",children:"Enter"})," ","to draft"]})}),(0,a.jsxs)("button",{type:"button",disabled:!d,"aria-describedby":"studio-ask-hint",onClick:r,className:"inline-flex min-h-[44px] shrink-0 items-center justify-center gap-2 rounded-xl bg-signal-blue px-[18px] text-[0.86rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-auth-muted",children:[l?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin motion-reduce:animate-none","aria-hidden":!0}):(0,a.jsx)(eK.A,{className:"h-4 w-4","aria-hidden":!0}),l?"Drafting briefâ¦":"Draft brief"]})]})]}),s&&i?(0,a.jsx)("p",{className:"text-[0.8rem] font-semibold text-auth-ink-soft",children:i}):null]})}function av(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function aw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return"string"==typeof e?e:t}function aj(e){var t;let n=av(e);if(!n)return null;let a=av(n.date_range),r=Array.isArray(n.platform_mix)?n.platform_mix.map(e=>{let t=av(e);if(!t)return null;let n=aw(t.platform).trim(),a=aw(t.format_key).trim();if(!n||!a)return null;let r=Number(t.post_count);return{platform:n,format_key:a,post_count:Number.isFinite(r)&&r>0?Math.round(r):1}}).filter(e=>null!==e):[],l=Array.isArray(n.evidence_patterns)?n.evidence_patterns.map(e=>{let t=av(e);if(!t)return null;let n=aw(t.pattern).trim();return n?{pattern:n,..."string"==typeof t.how_to_apply?{how_to_apply:t.how_to_apply}:{},enabled:!1!==t.enabled}:null}).filter(e=>null!==e):[];return{goal:aw(n.goal),campaign_message:aw(n.campaign_message),key_angles:Array.isArray(t=n.key_angles)?t.filter(e=>"string"==typeof e&&e.trim().length>0):[],platform_mix:r,date_range:{start:aw(null==a?void 0:a.start),end:aw(null==a?void 0:a.end)}
1,cadence:aw(n.cadence),evidence_patterns:l}}async function aN(e){var t;return null!=(t=av(await e.json().catch(()=>({}))))?t:{}}function a_(e,t){return aw(e.detail)||aw(e.error)||t}async function ak(e){let t=await fetch("/ai/business/ad-maker/campaign-manager/briefs/generate/",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,ask:e.ask,...e.organizationalUnitId?{organizational_unit_id:e.organizationalUnitId}:{},...e.businessContext?{business_context:e.businessContext}:{},...e.connectedPlatforms?{connected_platforms:e.connectedPlatforms}:{}})}),n=await aN(t);if(!t.ok)throw Error(a_(n,"Could not generate the campaign brief"));let a=aj(n.brief);if(!a)throw Error("The brief generator returned an unexpected response");return a}async function aA(e){var t;let n=await fetch("/ai/business/ad-maker/campaign-manager/briefs/execute/",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,brief:e.brief,...e.organizationalUnitId?{organizational_unit_id:e.organizationalUnitId}:{},...e.businessContext?{business_context:e.businessContext}:{},...e.clientTimezone?{client_timezone:e.clientTimezone}:{},...e.connectedSocialNetworks?{connected_social_networks:e.connectedSocialNetworks}:{},...e.outstandAccounts?{outstand_accounts:e.outstandAccounts}:{}})}),a=await aN(n);if(!n.ok)throw Error(a_(a,"Could not start the campaign"));return{runId:aw(a.run_id),boardId:aw(a.board_id,e.boardId),state:null!=(t=a.state)?t:null}}async function aC(e){var t;let n=await fetch("/ai/business/ad-maker/campaign-manager/tasks/".concat(encodeURIComponent(e.taskId),"/regenerate/"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,run_id:e.runId,client_timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",...(null==(t=e.steer)?void 0:t.trim())?{steer:e.steer.trim()}:{}})}),a=await aN(n);if(!n.ok)throw Error(a_(a,"Could not regenerate this post"))}async function aS(e){let t=await fetch("/ai/business/ad-maker/campaign-manager/runs/".concat(encodeURIComponent(e.runId),"/prepare-schedule/"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,client_timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"})}),n=await aN(t);if(!t.ok)throw Error(a_(n,"Could not prepare the campaign schedule"))}async function aI(e){let t=await fetch("/ai/business/ad-maker/campaign-manager/tasks/".concat(encodeURIComponent(e.taskId),"/update/"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({board_id:e.boardId,run_id:e.runId,caption:e.caption})}),n=await aN(t);if(!t.ok)throw Error(a_(n,"Could not save the caption"))}async function aT(e){let t=await fetch("/ai/business/website-context/preview?url=".concat(encodeURIComponent(e)),{credentials:"include"}),n=await aN(t);if(!t.ok)throw Error(a_(n,"Could not preview this website"));return{url:aw(n.url,e),title:aw(n.title),screenshot:aw(n.screenshot),summary:aw(n.summary)}}async function aM(e){var t,n;let a=await fetch("/ai/business/website-context/ingest",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({organizational_unit_id:e.organizationalUnitId,root_url:e.rootUrl,...e.extraUrls&&e.extraUrls.length>0?{extra_urls:e.extraUrls}:{}})}),r=await aN(a);if(!a.ok)throw Error(a_(r,"Website analysis failed"));let l=av(r.website_context);if(!l)throw Error("Website analysis returned an unexpected response");let s=Array.isArray(l.pages)?l.pages.map(e=>{let t=av(e);return t?{url:aw(t.url),title:aw(t.title),summary:aw(t.summary)}:null}).filter(e=>null!==e):[];return{...l,root_url:aw(l.root_url,e.rootUrl),pages:s,text_analysis:null!=(t=l.text_analysis)?t:null,visual_analysis:null!=(n=l.visual_analysis)?n:null,generated_at:aw(l.generated_at)}}let aR=new Set(["complete","failed","cancelled"]),aE="/dashboard/tools/social-media-post-scheduler",aU={x:"X / Twitter",twitter:"X / Twitter",linkedin:"LinkedIn",instagram:"Instagram",facebook:"Facebook",threads:"Threads",tiktok:"TikTok",youtube:"YouTube",bluesky:"Bluesky",pinterest:"Pinterest",google_business:"Google Business"};function aP(e){return aU[e.toLowerCase()]||e.replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase())}function aB(e){let t=String(e||"").trim().toLowerCase().replaceAll("-","_");return"x"===t?"twitter":t}function aD(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}function az(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function aO(e){return"string"==typeof e?e:""}function aF(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function aL(e){let t=Date.parse(e||"");if(!Number.isFinite(t))return"";let n=Math.floor((Date.now()-t)/864e5);if(n<=0)return"Updated today";if(1===n)return"Updated yesterday";if(n<30)return"Updated ".concat(n," days ago");let a=new Date(t);return"Updated ".concat(a.toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"}))}function aq(e){return!e||aR.has(e.status)}function a$(e){let t=az(e.input),n=az(t.content_output),a=az(t.display_detail),r=az(e.output),l=aB(n.platform||a.platform),s=aO(n.format_key)||null,i=s?tu[s]:void 0,o=(null==i?void 0:i.label)||aO(a.format)||aO(n.format)||"Post",c=i?"".concat(i.width,"\xd7").concat(i.height," \xb7 ").concat(i.aspectRatio):"";return{taskId:e.id,status:e.status,error:e.error,platform:l,formatKey:s,formatLabel:o,dimensionsLabel:c,title:aO(n.title)||e.title,headline:aO(n.headline)||aO(a.headline),angle:aO(n.content_role)||aO(a.content_role)||aO(n.headline)||aO(a.headline)||aO(n.title)||e.title,caption:aO(r.caption_text)||aO(n.body_copy),imageUrls:aF(r.image_urls),videoUrls:aF(r.video_urls),mediaUrls:aF(r.media_urls)}}function aK(e){let t=az(e.input),n=az(t.scheduled_post_input),a=aO(n.scheduledTime);if(!a)return null;let r=az(n.content),l=az(n.campaignManager);return{taskId:e.id,status:e.status,platforms:aF(n.platforms).map(aB),scheduledTime:a,timezone:aO(n.timezone),text:aO(r.text),mediaUrls:aF(r.mediaUrls),sourceTaskId:aO(l.sourceTaskId)||null}}let aW=new Set(["tiktok_video","instagram_reel","youtube_short"]);function aJ(e){return e.formatKey||"".concat(aB(e.platform)||"post",":").concat(e.formatLabel)}let aG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function aH(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let[n,a,r]=[Number(t[1]),Number(t[2]),Number(t[3])],l=new Date(Date.UTC(n,a-1,r));return l.getUTCMonth()!==a-1||l.getUTCDate()!==r?null:l}function aY(e){return"".concat(e," post").concat(1===e?"":"s")}function aV(e){if(!e)return null;let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString("en-GB",{hour:"numeric",minute:"2-digit",hour12:!0}).replace(/\s/g," ")}function aX(e){var t,n;return"failed"===e.status||e.videoUrls.length>0?null:null!=(n=null!=(t=e.imageUrls[0])?t:e.mediaUrls[0])?n:null}function aQ(e,t){if(!e.toLowerCase().startsWith(t.toLowerCase()))return e;let n=e.slice(t.length).trim();return n?n.charAt(0).toUpperCase()+n.slice(1):e}let aZ="w-full rounded-[14px] border-[1.5px] border-control-border bg-auth-field px-3.5 py-3 text-[0.92rem] font-medium leading-[1.5] text-midnight-logic placeholder:text-auth-placeholder focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60",a0="text-[0.88rem] font-bold text-midnight-logic",a1="inline-flex min-h-[40px] items-center gap-1.5 self-start rounded-[10px] pl-2 pr-3 text-[0.82rem] font-bold text-signal-blue transition-colors hover:text-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a2="relative grid h-9 w-9 shrink-0 place-items-center rounded-[10px] text-auth-ink-soft transition-colors before:absolute before:-inset-1 before:rounded-xl before:content-[''] hover:bg-white hover:text-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:opacity-50";function a5(e){let{number:t,title:n,aside:r,children:l}=e;return(0,a.jsxs)("section",{className:"flex flex-col gap-3.5",children:[(0,a.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,a.jsxs)("h3",{className:"flex items-baseline gap-3 text-[1.08rem] font-extrabold text-midnight-logic",children:[(0,a.jsx)("span",{className:"text-[0.84rem] font-extrabold tracking-[0.06em] text-signal-blue",children:t}),n]}),r?(0,a.jsx)("span",{className:"shrink-0 text-right text-[0.78rem] font-medium text-auth-muted",children:r}):null]}),l]})}function a4(e){let{index:t,angle:n,disabled:r,initiallyEditing:l=!1,onCommit:s,onRemove:i}=e,[c,d]=(0,o.useState)(l),[u,m]=(0,o.useState)(n),p=(0,o.useRef)(null),h=t+1;(0,o.useEffect)(()=>{c||m(n)},[n,c]),(0,o.useEffect)(()=>{var e;c&&(null==(e=p.current)||e.focus())},[c]),(0,o.useEffect)(()=>{r&&c&&(d(!1),u!==n&&s(u))},[n,r,u,c,s]);let f=()=>{d(!1),u!==n&&s(u)};return(0,a.jsxs)("li",{className:"grid grid-cols-[24px_minmax(0,1fr)_36px] items-start gap-2.5 rounded-[14px] bg-cloud-slate py-3 pl-3.5 pr-2",children:[(0,a.jsx)("span",{"aria-hidden":!0,
1className:"grid h-6 w-6 place-items-center rounded-full bg-white text-[0.7rem] font-extrabold text-anchor-blue",children:h}),c?(0,a.jsx)("textarea",{ref:p,"aria-label":"Angle ".concat(h),value:u,rows:2,disabled:r,placeholder:"Angle ".concat(h),className:"min-h-[3rem] w-full resize-none rounded-[10px] border-[1.5px] border-control-border bg-white px-3 py-2 text-[0.88rem] font-medium leading-[1.5] text-midnight-logic [field-sizing:content] placeholder:text-auth-placeholder focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onChange:e=>m(e.target.value),onBlur:f,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing?"Escape"===e.key&&(e.preventDefault(),m(n),d(!1)):(e.preventDefault(),f())}}):(0,a.jsx)("span",{className:"pt-0.5 text-[0.88rem] font-medium leading-[1.5] text-midnight-logic",children:n.trim()?n:(0,a.jsx)("span",{className:"text-auth-muted",children:"Empty angle â edit to add one"})}),(0,a.jsx)("span",{className:"-mt-1.5",children:c?(0,a.jsx)("button",{type:"button",disabled:r,"aria-label":"Remove angle ".concat(h),className:a2,onMouseDown:e=>e.preventDefault(),onClick:i,children:(0,a.jsx)(eG.A,{className:"h-4 w-4","aria-hidden":!0})}):(0,a.jsx)("button",{type:"button",disabled:r,"aria-label":"Edit angle ".concat(h),className:a2,onClick:()=>d(!0),children:(0,a.jsx)(eR.A,{className:"h-[15px] w-[15px]","aria-hidden":!0})})})]})}var a3=n(23591);n(14051),n(46617),n(84709),n(15395),n(83e3),n(34577),n(86157),n(53984);let a8={instagram:{className:"bg-gradient-to-br from-[#F58529] via-[#DD2A7B] to-[#8134AF]",short:"IG",network:"instagram"},facebook:{className:"bg-[#1877F2]",short:"f",network:"facebook"},linkedin:{className:"bg-[#0A66C2]",short:"in",network:"linkedin"},tiktok:{className:"bg-midnight-logic",short:"TT",network:"tiktok"},twitter:{className:"bg-midnight-logic",short:"X",network:"x"},x:{className:"bg-midnight-logic",short:"X",network:"x"},youtube:{className:"bg-[#FF0000]",short:"YT",network:"youtube"},pinterest:{className:"bg-[#E60023]",short:"P",network:"pinterest"},threads:{className:"bg-midnight-logic",short:"@",network:"threads"}},a6={sm:"h-[18px] w-[18px] text-[0.44rem]",md:"h-8 w-8 text-[0.72rem]"},a7={sm:18,md:32};function a9(e){var t;let{platform:n,size:r="md",tone:l="brand"}=e,s=null!=(t=a8[n])?t:{className:"bg-signal-blue",short:n.slice(0,2).toUpperCase()};return"logo"===l&&s.network?(0,a.jsx)(a3.b6,{as:"span",network:s.network,"aria-hidden":!0,className:"shrink-0",style:{width:a7[r],height:a7[r]}}):(0,a.jsx)("span",{"aria-hidden":!0,className:(0,Y.cn)("grid shrink-0 place-items-center rounded-full font-extrabold text-white",a6[r],"mono"===l?"bg-midnight-logic":s.className),children:s.short})}let re="grid h-9 w-9 place-items-center text-midnight-logic transition-colors hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:opacity-40";function rt(e,t){return e?"".concat(aQ(e.label,t)," \xb7 ").concat(e.width,"\xd7").concat(e.height," \xb7 ").concat(e.aspectRatio):"Choose a format"}function rn(e){var t;let{entry:n,index:r,disabled:l,onChange:s,onRemove:i}=e,o=aP(n.platform),c=td.filter(e=>e.platform===n.platform),u=null!=(t=c.find(e=>e.formatKey===n.format_key))?t:c[0];return(0,a.jsxs)("li",{className:"grid grid-cols-[32px_minmax(0,1fr)_auto_36px] items-center gap-3 rounded-[14px] bg-cloud-slate py-3 pl-3.5 pr-2",children:[(0,a.jsx)(a9,{platform:n.platform,tone:"logo"}),(0,a.jsxs)("span",{className:"min-w-0",children:[(0,a.jsx)("span",{className:"block truncate text-[0.88rem] font-bold leading-tight text-midnight-logic",children:o}),(0,a.jsxs)("span",{className:"relative mt-0.5 inline-flex max-w-full items-center gap-1 rounded-md text-[0.78rem] font-medium leading-tight text-auth-ink-soft transition-colors hover:text-midnight-logic has-[:disabled]:hover:text-auth-ink-soft has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-signal-blue",children:[(0,a.jsx)("span",{className:"min-w-0 truncate",children:rt(u,o)}),(0,a.jsx)(eq.A,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),(0,a.jsx)("select",{value:n.format_key,disabled:l,"aria-label":"".concat(o," format"),className:"absolute -bottom-[5px] left-0 right-0 -top-[5px] cursor-pointer opacity-0 disabled:cursor-not-allowed",onChange:e=>s(r,{...n,format_key:e.target.value}),children:c.map(e=>(0,a.jsx)("option",{value:e.formatKey,children:rt(e,o)},e.formatKey))})]})]}),(0,a.jsxs)("span",{role:"group","aria-label":"".concat(o," posts"),className:"flex items-center overflow-hidden rounded-[10px] border-[1.5px] border-control-border bg-white",children:[(0,a.jsx)("button",{type:"button","aria-label":"Fewer posts",disabled:l||n.post_count<=1,className:re,onClick:()=>s(r,{...n,post_count:Math.max(1,n.post_count-1)}),children:(0,a.jsx)(G.A,{className:"h-3.5 w-3.5","aria-hidden":!0})}),(0,a.jsx)("span",{"aria-live":"polite",className:"min-w-[56px] text-center text-[0.82rem] font-bold tabular-nums text-midnight-logic",children:aY(n.post_count)}
1),(0,a.jsx)("button",{type:"button","aria-label":"More posts",disabled:l||n.post_count>=8,className:re,onClick:()=>s(r,{...n,post_count:Math.min(8,n.post_count+1)}),children:(0,a.jsx)(d.A,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),(0,a.jsx)("button",{type:"button",disabled:l,"aria-label":"Remove ".concat(o),className:a2,onClick:()=>i(r),children:(0,a.jsx)(eG.A,{className:"h-4 w-4","aria-hidden":!0})})]})}let ra=Array.from(new Set(td.map(e=>e.platform)));function rr(e){let{id:t,label:n,aside:r,children:l}=e;return(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"mb-2.5 flex items-baseline justify-between gap-3",children:[(0,a.jsx)("label",{htmlFor:t,className:a0,children:n}),r?(0,a.jsx)("span",{className:"text-[0.78rem] font-medium text-auth-muted",children:r}):null]}),l]})}function rl(e){let{brief:t,onChange:n,connectedPlatforms:r,disabled:l}=e,s=(0,o.useId)(),[i,c]=(0,o.useState)(null),u=(0,o.useMemo)(()=>t.platform_mix.reduce((e,t)=>e+t.post_count,0),[t.platform_mix]),m=function(e,t){var n;if(0===e.length)return null;let a=e.filter(e=>!t.has(aB(e.platform)));if(0===a.length)return null;if(a.length===e.length)return"None of these networks are connected yet. Posts save as drafts you can publish later.";let r=Array.from(new Set(a.map(e=>aB(e.platform)))).map(aP),l=1===r.length?"isnât":"arenât";return"".concat(r.length<=1?null!=(n=r[0])?n:"":"".concat(r.slice(0,-1).join(", ")," and ").concat(r[r.length-1])," ").concat(l," connected yet â those posts save as drafts you can publish later.")}(t.platform_mix,r),p=(e,a)=>n({...t,platform_mix:t.platform_mix.map((t,n)=>n===e?a:t)}),h=e=>n({...t,platform_mix:t.platform_mix.filter((t,n)=>n!==e)});return(0,a.jsxs)("div",{className:"flex flex-col gap-10",children:[(0,a.jsx)(a5,{number:"01",title:"Goal and message",children:(0,a.jsxs)("div",{className:"flex flex-col gap-[18px]",children:[(0,a.jsx)(rr,{id:"".concat(s,"-goal"),label:"Goal",children:(0,a.jsx)("textarea",{id:"".concat(s,"-goal"),rows:3,value:t.goal,disabled:l,placeholder:"What should this campaign achieve?",className:(0,Y.cn)(aZ,"resize-none [field-sizing:content]"),onChange:e=>n({...t,goal:e.target.value})})}),(0,a.jsx)(rr,{id:"".concat(s,"-message"),label:"Campaign message",aside:"Appears in every post",children:(0,a.jsx)("textarea",{id:"".concat(s,"-message"),rows:3,value:t.campaign_message,disabled:l,placeholder:"The core message every post should reinforceâ¦",className:(0,Y.cn)(aZ,"resize-none [field-sizing:content]"),onChange:e=>n({...t,campaign_message:e.target.value})})})]})}),(0,a.jsxs)(a5,{number:"02",title:"Key angles",aside:"One per post theme",children:[(0,a.jsx)("ol",{className:"flex flex-col gap-1.5",children:t.key_angles.map((e,r)=>(0,a.jsx)(a4,{index:r,angle:e,disabled:l,initiallyEditing:i===r,onCommit:e=>{c(null),n({...t,key_angles:t.key_angles.map((t,n)=>n===r?e:t)})},onRemove:()=>{c(null),n({...t,key_angles:t.key_angles.filter((e,t)=>t!==r)})}},"".concat(r,":").concat(e)))}),(0,a.jsxs)("button",{type:"button",disabled:l,className:a1,onClick:()=>{c(t.key_angles.length),n({...t,key_angles:[...t.key_angles,""]})},children:[(0,a.jsx)(d.A,{className:"h-4 w-4","aria-hidden":!0}),"Add angle"]})]}),(0,a.jsxs)(a5,{number:"03",title:"Platform mix",aside:"".concat(aY(u)," planned"),children:[m?(0,a.jsx)("p",{className:"-mt-1 text-[0.8rem] font-medium leading-[1.45] text-auth-muted",children:m}):null,(0,a.jsx)("ul",{className:"flex flex-col gap-1.5",children:t.platform_mix.map((e,t)=>(0,a.jsx)(rn,{entry:e,index:t,disabled:l,onChange:p,onRemove:h},"".concat(e.platform,"-").concat(t)))}),(0,a.jsxs)("button",{type:"button",disabled:l,className:a1,onClick:()=>{var e,a,r,l;let s=new Set(t.platform_mix.map(e=>e.platform)),i=null!=(a=null!=(e=ra.find(e=>!s.has(e)))?e:ra[0])?a:"instagram";n({...t,platform_mix:[...t.platform_mix,{platform:i,format_key:null!=(l=null==(r=td.find(e=>e.platform===i))?void 0:r.formatKey)?l:"",post_count:1}]})},children:[(0,a.jsx)(d.A,{className:"h-4 w-4","aria-hidden":!0}),"Add platform"]})]}),(0,a.jsxs)(a5,{number:"04",title:"Schedule",aside:function(e,t){let n=function(e){let t=aH(e.start),n=aH(e.end);if(!t||!n)return null;let a=e=>e.getUTCDate(),r=e=>aG[e.getUTCMonth()],l=e=>e.getUTCFullYear();return l(t)!==l(n)?"".concat(a(t)," ").concat(r(t)," ").concat(l(t),"â").concat(a(n)," ").concat(r(n)," ").concat(l(n)):t.getUTCMonth()!==n.getUTCMonth()?"".concat(a(t)," ").concat(r(t),"â").concat(a(n)," ").concat(r(n)):"".concat(a(t),"â").concat(a(n)," ").concat(r(t))}(e);return n?"".concat(n," \xb7 ").concat(aY(t)):aY(t)}(t.date_range,u),children:[(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,a.jsx)(rr,{id:"".concat(s,"-start"),label:"Start date",children:(0,a.jsx)("input",{id:"".concat(s,"-start"),type:"date",value:t.date_range.start,disabled:l,className:(0,Y.cn)(aZ,"h-[46px] py-0"),onChange:e=>n({...t,date_range:{...t.date_range,start:e.target.value}})})}),(0,a.jsx)(rr,{id:"".concat(s,"-end"),label:"End date",children:(0,a.jsx)("input",{id:"".concat(s,"-end"),type:"date",value:t.date_range.end,disabled:l,className:(0,Y.cn)(aZ,"h-[46px] py-0"),onChange:e=>n({...t,date_range:{...t.date_range,end:e.target.value}})})})]}),(0,a.jsx)(rr,{id:"".concat(s,"-cadence"),label:"Cadence",children:(0,a.jsx)("input",{id:"".concat(s,"-cadence"),value:t.cadence,disabled:l,placeholder:"e.g. 1 post per day",className:(0,Y.cn)(aZ,"h-[46px] py-0"),onChange:e=>n({...t,cadence:e.target.value})})})]}),t.evidence_patterns.length>0?(0,a.jsx)(a5,{number:"05",title:"Evidence patterns",aside:"From market research",children:(0,a.jsx)("div",{role:"group","aria-label":"Evidence patterns",className:"flex flex-col gap-1.5",children:t.evidence_patterns.map((e,r)=>(0,a.jsxs)("button",{type:"button","aria-pressed":e.enabled,disabled:l,title:e.how_to_apply||e.pattern,className:(0,Y.cn)("flex min-h-[44px] w-full items-center justify-between gap-3 rounded-[12px] border-[1.5px] px-3.5 py-2 text-left text-[0.84rem] font-bold leading-[1.4] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60",e.enabled?"border-signal-blue bg-auth-field text-anchor-blue":"border-control-border bg-white text-auth-muted"),onClick:()=>n({...t,evidence_patterns:t.evidence_patterns.map((e,t)=>t===r?{...e,enabled:!e.enabled}:e)}),children:[(0,a.jsx)("span",{className:e.enabled?void 0:"line-through",children:e.pattern}),(0,a.jsx)("span",{className:"shrink-0 text-[0.7rem] font-extrabold uppercase tracking-[0.06em]",children:e.enabled?"On":"Off"})]},"".concat(e.pattern,"-").concat(r)))})}):null]})}
1var rs=n(40627);let ri="inline-flex min-h-[44px] shrink-0 items-center gap-2 whitespace-nowrap rounded-xl bg-signal-blue px-[18px] text-[0.88rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-auth-muted",ro="inline-flex min-h-[44px] shrink-0 items-center gap-2 whitespace-nowrap rounded-xl border-[1.5px] border-control-border bg-white px-[18px] text-[0.88rem] font-bold text-midnight-logic transition-colors hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",rc="min-w-0 text-[0.8rem] font-medium leading-[1.4] text-auth-ink-soft";function rd(e){let t,{state:n,onGenerate:r}=e,l=(0,o.useId)(),[s,i]=(0,o.useState)(!1),c="regenerate"!==n.kind?n.kind:s&&!n.disabledReason?"confirm":"regenerate",d=(0,o.useRef)(null),u=(0,o.useRef)(null),h=(0,o.useRef)(null);if((0,o.useEffect)(()=>{var e,t;
1"cancel"===h.current&&(null==(e=d.current)||e.focus()),"regenerate-all"===h.current&&(null==(t=u.current)||t.focus()),h.current=null},[c]),"starting"===n.kind)t=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:rc,children:"Setting up your campaign run."}),(0,a.jsxs)("button",{type:"button",disabled:!0,className:ri,children:[(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin motion-reduce:animate-none","aria-hidden":!0}),"Starting campaignâ¦"]})]});else if("generate"===n.kind)t=(0,a.jsxs)(a.Fragment,{children:[n.disabledReason?(0,a.jsx)("p",{id:l,className:rc,children:n.disabledReason}):(0,a.jsx)("span",{className:rc,children:"Posts appear on the right as theyâre made."}),(0,a.jsxs)("button",{type:"button",disabled:!!n.disabledReason,"aria-describedby":n.disabledReason?l:void 0,className:ri,onClick:r,children:[(0,a.jsx)(rs.A,{className:"h-4 w-4","aria-hidden":!0}),"Generate campaign"]})]});else if("confirm"===c)t=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("p",{className:rc,children:"This starts a fresh run. Posts already on the board stay there."}),(0,a.jsxs)("span",{className:"flex shrink-0 gap-2",children:[(0,a.jsx)("button",{ref:d,type:"button",className:ro,onClick:()=>{h.current="regenerate-all",i(!1)},children:"Cancel"}),(0,a.jsx)("button",{type:"button",className:ri,onClick:()=>{i(!1),r()},children:"Regenerate"})]})]});else{let e=aV(n.generatedAt);t=(0,a.jsxs)(a.Fragment,{children:[n.disabledReason?(0,a.jsx)("p",{id:l,className:rc,children:n.disabledReason}):(0,a.jsxs)("span",{className:"".concat(rc," inline-flex items-center gap-2"),children:[(0,a.jsx)(m.A,{className:"h-3.5 w-3.5 shrink-0 text-anchor-blue","aria-hidden":!0}),e?"Generated ".concat(e):"Generated"]}),(0,a.jsxs)("button",{ref:u,type:"button",disabled:!!n.disabledReason,"aria-describedby":n.disabledReason?l:void 0,className:ro,onClick:()=>{h.current="cancel",i(!0)},children:[(0,a.jsx)(tb.A,{className:"h-4 w-4","aria-hidden":!0}),"Regenerate all"]})]})}return(0,a.jsx)("div",{className:"sticky bottom-0 flex flex-none items-center justify-between gap-4 border-t border-auth-hairline bg-white px-7 py-3.5 lg:static",children:t})}let ru="business-brain-drawer";function rm(e){let{open:t,onClose:n,subtitle:r,returnFocusRef:l,children:s}=e,i=(0,o.useId)(),c=(0,o.useRef)(null),d=(0,o.useRef)(null);return(0,o.useEffect)(()=>{var e,a;if(!t)return;null==(e=d.current)||e.focus();let r=e=>{if("Escape"===e.key){e.preventDefault(),n();return}let t=c.current;if("Tab"!==e.key||!t)return;let a=Array.from(t.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),r=a[0],l=a[a.length-1];r&&l&&(e.shiftKey&&document.activeElement===r?(e.preventDefault(),l.focus()):e.shiftKey||document.activeElement!==l||(e.preventDefault(),r.focus()))};document.addEventListener("keydown",r);let s=null!=(a=null==l?void 0:l.current)?a:null;return()=>{document.removeEventListener("keydown",r),null==s||s.focus()}},[n,t,l]),(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{"aria-hidden":!0,onClick:n,className:(0,Y.cn)("fixed inset-0 z-40 bg-midnight-logic/30 lg:absolute",t?"block":"hidden")}),(0,a.jsxs)("aside",{ref:c,id:ru,role:"dialog","aria-modal":"true","aria-labelledby":i,inert:!t,className:(0,Y.cn)("fixed inset-y-0 right-0 z-50 w-full flex-col bg-white shadow-[-12px_0_40px_rgba(13,14,29,0.18)] sm:w-[440px] lg:absolute",t?"flex":"hidden"),children:[(0,a.jsxs)("div",{className:"flex flex-none items-center gap-3 px-6 pb-4 pt-5",children:[(0,a.jsx)("span",{"aria-hidden":!0,className:"grid h-9 w-9 flex-none place-items-center rounded-[10px] bg-midnight-logic text-white",children:(0,a.jsx)(ah.A,{className:"h-[18px] w-[18px]"})}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("h2",{id:i,className:"text-[1.15rem] font-extrabold leading-[1.2] text-midnight-logic",children:"Business Brain"}),(0,a.jsx)("p",{className:"mt-1 text-[0.8rem] font-medium text-auth-muted",children:r})]}),(0,a.jsx)("button",{ref:d,type:"button","aria-label":"Close Business Brain",onClick:n,className:"grid h-10 w-10 place-items-center rounded-[10px] bg-cloud-slate text-midnight-logic transition-colors hover:bg-auth-hairline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",children:(0,a.jsx)(eG.A,{className:"h-[18px] w-[18px]","aria-hidden":!0})})]}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto",children:s}),(0,a.jsxs)("div",{className:"flex flex-none items-center justify-between gap-3 border-t border-auth-hairline px-6 py-3.5",children:[(0,a.jsx)("span",{className:"text-[0.8rem] font-medium leading-[1.4] text-auth-muted",children:"Changes apply the next time you regenerate."}),(0,a.jsx)("button",{type:"button",onClick:n,className:"inline-flex min-h-[44px] items-center rounded-xl bg-signal-blue px-5 text-[0.88rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",children:"Done"})]})]})]})}var rp=n(23063),rh=n(73465),rf=n(33386),rg=n(4533),rx=n(77177),rb=n(79087);function ry(e){return"ad-maker:campaign-studio:ask:".concat(e)}function rv(e){return"ad-maker:campaign-studio:brief:".concat(e)}function rw(e){let t=ti(e);if(!t)return null;try{return JSON.parse(t)}catch(e){return null}}function rj(e,t){if(null==t)return void to(e,"");try{to(e,JSON.stringify(t))}catch(e){}}function rN(e){if("string"==typeof e)try{return az(JSON.parse(e))}catch(e){return{}}return az(e)}function r_(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:"https://".concat(t):""}function rk(e){return e.split(/[\n,]+/).map(e=>
1r_(e)).filter(Boolean).slice(0,5)}function rA(e){let{htmlFor:t,children:n,aside:r}=e;return(0,a.jsxs)("div",{className:"mb-2.5 flex items-baseline justify-between gap-3",children:[(0,a.jsx)("label",{htmlFor:t,className:a0,children:n}),r?(0,a.jsx)("span",{className:"shrink-0 text-[0.78rem] font-medium text-auth-muted",children:r}):null]})}function rC(e){let{id:t,children:n}=e;return(0,a.jsx)("p",{id:t,className:"mt-1.5 text-[0.78rem] font-medium leading-[1.4] text-auth-muted",children:n})}function rS(e){let{icon:t,title:n,titleId:r,subtitle:l,included:s,onIncludedChange:i,children:o}=e;return(0,a.jsxs)("section",{"aria-labelledby":r,className:"flex flex-col gap-5 border-t border-auth-hairline px-6 py-6",children:[(0,a.jsxs)("div",{className:"grid grid-cols-[36px_minmax(0,1fr)_auto] items-start gap-3.5",children:[(0,a.jsx)("span",{"aria-hidden":!0,className:"grid h-9 w-9 place-items-center rounded-[10px] bg-auth-field text-signal-blue",children:t}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h3",{id:r,className:"text-[1.02rem] font-extrabold leading-[1.2] text-midnight-logic",children:n}),l?(0,a.jsx)("p",{className:"mt-1.5 break-words text-[0.84rem] font-medium leading-[1.5] text-auth-ink-soft",children:l}):null]}),(0,a.jsxs)("label",{className:"flex items-center gap-2.5 text-[0.8rem] font-bold text-midnight-logic",children:[(0,a.jsx)(rx.d,{checked:s,onCheckedChange:i,"aria-label":"Include ".concat(n," in this campaign")}),(0,a.jsx)("span",{"aria-hidden":!0,children:s?"On":"Off"})]})]}),(0,a.jsx)("div",{className:s?"pl-[50px]":"pl-[50px] opacity-50",children:o})]})}function rI(e){var t,n,r;let{onSnapshotChange:s,onSourcesChange:i}=e,{currentOrgId:c}=(0,x.x)(),[d,u]=(0,o.useState)(!0),[m,g]=(0,o.useState)(!0),[b,y]=(0,o.useState)(!0),[v,w]=(0,o.useState)(!0),[j,N]=(0,o.useState)(!0),[_,k]=(0,o.useState)(new Set),[{data:A,fetching:C},S]=(0,h.IT)({query:"\n query GetLatestWebsiteContext($orgId: BigInt!) {\n websiteContextSnapshots(\n condition: { organizationalUnitId: $orgId }\n filter: { deletedAt: { isNull: true } }\n orderBy: CREATED_AT_DESC\n first: 1\n ) {\n nodes {\n id\n rootUrl\n contextData\n createdAt\n }\n }\n }\n",variables:{orgId:c},pause:!c,requestPolicy:"cache-and-network"}),[{data:I}]=(0,h.IT)({query:rb.IY}),T=(null==I?void 0:I.currentUserId)?String(I.currentUserId):null,[,M]=(0,f.n_)("\n mutation CreateWebsiteContextSnapshot($userId: BigInt!, $organizationalUnitId: BigInt!, $rootUrl: String!, $contextData: JSON!, $inputData: JSON) {\n createWebsiteContextSnapshot(input: {\n websiteContextSnapshot: {\n userId: $userId\n organizationalUnitId: $organizationalUnitId\n rootUrl: $rootUrl\n contextData: $contextData\n inputData: $inputData\n }\n }) {\n websiteContextSnapshot {\n id\n rootUrl\n createdAt\n }\n }\n }\n"),R=(0,o.useMemo)(()=>{var e,t,n;let a=null==A||null==(t=A.websiteContextSnapshots)||null==(e=t.nodes)?void 0:e[0];return a&&"object"==typeof a?"string"!=typeof a.rootUrl?null:{id:String(null!=(n=a.id)?n:""),rootUrl:a.rootUrl,contextData:a.contextData,createdAt:"string"==typeof a.createdAt?a.createdAt:""}:null},[null==A||null==(t=A.websiteContextSnapshots)?void 0:t.nodes]),E=(0,o.useMemo)(()=>rN(null==R?void 0:R.contextData),[null==R?void 0:R.contextData]),[U,P]=(0,o.useState)(""),B=(0,o.useRef)(null);(0,o.useEffect)(()=>{var e;let t=null!=(e=null==R?void 0:R.id)?e:null;t&&B.current!==t&&(B.current=t,P(function(e){if("string"==typeof e.summary&&e.summary.trim())return e.summary;let t=e.text_analysis;if("string"==typeof t&&t.trim())return t;let n=az(t);return"string"==typeof n.summary&&n.summary.trim()?n.summary:""}(E)))},[E,null==R?void 0:R.id]);let[D,z]=(0,o.useState)(""),[O,F]=(0,o.useState)(""),[L,q]=(0,o.useState)({phase:"idle"}),[$,K]=(0,o.useState)(null),[W,J]=(0,o.useState)(!1),[G,H]=(0,o.useState)(!1),[V,X]=(0,o.useState)(null),Q=(0,f.tH)(),[,Z]=(0,f.n_)("\n mutation SoftDeleteWebsiteContextSnapshot($id: BigInt!, $deletedAt: Datetime!) {\n updateWebsiteContextSnapshot(input: { id: $id, patch: { deletedAt: $deletedAt } }) {\n websiteContextSnapshot {\n id\n deletedAt\n }\n }\n }\n"),ee=(0,o.useMemo)(()=>(function(e){let t=az(e.visual_analysis),n=Array.isArray(t.palette)?t.palette.filter(e=>"string"==typeof e&&/^#[0-9a-f]{6}$/i.test(e.trim())):[];return{logoUrl:"string"==typeof t.logo_url?t.logo_url:"",palette:n.slice(0,8)}})(E),[E]),et=(0,o.useMemo)(()=>(function(e){let t=(Array.isArray(e.image_assets)?e.image_assets:[]).map(e=>{let t=az(e),n="string"==typeof t.url?t.url:"";return n.startsWith("http")?{url:n,kind:"string"==typeof t.kind&&t.kind?t.kind:"content",caption:"string"==typeof t.caption&&t.caption||"string"==typeof t.alt&&t.alt||"",sourcePage:"string"==typeof t.source_page?t.source_page:void 0}:null}).filter(e=>null!==e),n=new Set;return t.filter(e=>!n.has(e.url)&&(n.add(e.url),!0))})(E),[E]),en=c?"ad-maker:campaign-studio:website-assets:".concat(c):null,[ea,er]=(0,o.useState)({});(0,o.useEffect)(()=>
1{if(!en)return;let e=az(rw(en)),t={};for(let[n,a]of Object.entries(e))"boolean"==typeof a&&(t[n]=a);er(t)},[en]);let el=(0,o.useCallback)((e,t)=>{var n;return null!=(n=ea[e])?n:"screenshot"!==t},[ea]),es=(0,o.useCallback)((e,t)=>{er(n=>{var a;let r={...n,[e]:!(null!=(a=n[e])?a:"screenshot"!==t)};return en&&rj(en,r),r})},[en]),ei=(0,o.useCallback)(async()=>{let e=r_(D),t=rk(O);if(e&&c){q({phase:"previewing",url:e,preview:null}),aT(e).then(e=>{q(t=>"previewing"===t.phase||"ingesting"===t.phase?{...t,preview:e}:t)}).catch(()=>{}),q(t=>({phase:"ingesting",url:e,preview:"previewing"===t.phase?t.preview:null}));try{let n=await aM({organizationalUnitId:c,rootUrl:e,...t.length>0?{extraUrls:t}:{}});if(q(t=>({phase:"saving",url:e,preview:"ingesting"===t.phase?t.preview:null})),T){let a=await M({userId:T,organizationalUnitId:c,rootUrl:e,contextData:n,inputData:{root_url:e,extra_urls:t}});if(a.error)throw Error(a.error.message)}B.current=null,q({phase:"idle"}),K(null),F(""),S({requestPolicy:"network-only"})}catch(t){q({phase:"error",url:e,message:t instanceof Error?t.message:"Website analysis failed"})}}},[M,c,T,O,S,D]),eo=(0,o.useCallback)(e=>{K(e),J(!1),q({phase:"idle"}),z("reanalyse"===e&&(null==R?void 0:R.rootUrl)||""),F("")},[null==R?void 0:R.rootUrl]),ec=(0,o.useCallback)(async()=>{if(c&&!G){H(!0),X(null);try{var e,t,n;let a=await Q.query("\n query GetWebsiteContextHistory($organizationalUnitId: BigInt!) {\n websiteContextSnapshots(\n orderBy: CREATED_AT_DESC\n first: 20\n condition: { organizationalUnitId: $organizationalUnitId }\n filter: { deletedAt: { isNull: true } }\n ) {\n nodes {\n id\n rootUrl\n contextData\n createdAt\n }\n }\n }\n",{organizationalUnitId:c}).toPromise();if(a.error)throw Error(a.error.message);let r=null!=(n=null==(t=a.data)||null==(e=t.websiteContextSnapshots)?void 0:e.nodes)?n:[],l=new Date().toISOString();for(let e of r){if(!(null==e?void 0:e.id))continue;let t=await Z({id:e.id,deletedAt:l});if(t.error)throw Error(t.error.message)}B.current=null,P(""),J(!1),K(null),S({requestPolicy:"network-only"})}catch(e){X(e instanceof Error?e.message:"Could not remove the website")}finally{H(!1)}}},[c,S,G,Z,Q]),{context:ed}=te(),{formattedPrompt:eu}=tt(),[{data:em}]=(0,h.IT)({query:e8.M,variables:{orgId:c},pause:!c,requestPolicy:"cache-and-network"}),ep=(0,o.useMemo)(()=>{var e,t;let n=null==em||null==(t=em.marketResearchAnalyses)||null==(e=t.nodes)?void 0:e[0];return n&&"object"==typeof n?n:null},[null==em||null==(n=em.marketResearchAnalyses)?void 0:n.nodes]),eh="string"==typeof(null==ep?void 0:ep.createdAt)?ep.createdAt:null,{patterns:ef,summary:eg}=(0,o.useMemo)(()=>(function(e){let t=az(rN(e).ad_visual_patterns);return{patterns:(Array.isArray(t.common_patterns)?t.common_patterns:[]).map(e=>{let t=az(e),n="string"==typeof t.pattern?t.pattern.trim():"";return n?{pattern:n,..."string"==typeof t.evidence&&t.evidence?{evidence:t.evidence}:{},..."string"==typeof t.how_to_apply&&t.how_to_apply?{how_to_apply:t.how_to_apply}:{}}:null}).filter(e=>null!==e),summary:"string"==typeof t.summary&&t.summary.trim()?t.summary:null}})(null==ep?void 0:ep.analysisData),[null==ep?void 0:ep.analysisData]),ex=(0,o.useMemo)(()=>(function(e){let t=az(rN(e).audience);return(Array.isArray(t.segments)?t.segments:[]).map(e=>{let t=az(e),n="string"==typeof t.name?t.name.trim():"";return n?{name:n,description:"string"==typeof t.description?t.description:""}:null}).filter(e=>null!==e)})(null==ep?void 0:ep.analysisData),[null==ep?void 0:ep.analysisData]),eb=(0,o.useMemo)(()=>(function(e){let t=az(rN(e).content_strategy);return Array.isArray(t.pillars)?t.pillars.filter(e=>"string"==typeof e&&e.trim().length>0):[]})(null==ep?void 0:ep.analysisData),[null==ep?void 0:ep.analysisData]),ey=(0,o.useMemo)(()=>{if(!ed)return null;let e=[];return ed.organizationName&&e.push("Business: ".concat(ed.organizationName)),ed.toneOfVoice&&e.push("Tone of voice: ".concat(ed.toneOfVoice)),ed.keyBenefit&&e.push("Key benefit: ".concat(ed.keyBenefit)),e.length>0?e.join("\n"):null},[ed]),ev=c?"ad-maker:campaign-studio:business-description:".concat(c):null,[ew,ej]=(0,o.useState)(""),eN=(0,o.useRef)("");(0,o.useEffect)(()=>
1{if(!ev)return;let e=ti(ev);eN.current=e,ej(e)},[ev]),(0,o.useEffect)(()=>{if(eN.current=ew,!ev)return;let e=window.setTimeout(()=>{to(ev,ew)},400);return()=>window.clearTimeout(e)},[ew,ev]),(0,o.useEffect)(()=>{if(ev)return()=>to(ev,eN.current)},[ev]);let e_=!!R,ek=!!ey,eA=!!ep,eC=ex.length>0||eb.length>0,eS=e_||ek||eA,eI=(0,o.useMemo)(()=>(function(e){let t=e.filter(e=>e.available);return{on:t.filter(e=>e.on).length,total:t.length}})([{available:e_,on:d},{available:ek,on:m},{available:eA,on:b},{available:eC,on:v},{available:!eS,on:j}]),[eS,ek,eC,eA,e_,m,j,v,b,d]);(0,o.useEffect)(()=>{null==i||i(eI)},[i,eI]);let eT=(0,o.useMemo)(()=>{let e=[],t=(t,n)=>{n&&n.trim()&&e.push([t,n])};return t("Business",null==ed?void 0:ed.organizationName),t("Tone of voice",null==ed?void 0:ed.toneOfVoice),t("Key benefit",null==ed?void 0:ed.keyBenefit),e},[ed]),eM=Array.isArray(E.pages)?E.pages.length:0,eR=rk(O).length,eE=(0,o.useMemo)(()=>{var e;let t=d&&R?{...E,root_url:null!=(e=E.root_url)?e:R.rootUrl,...U.trim()?{summary:U.trim()}:{}}:null,n=[];if(d&&R)for(let e of(ee.logoUrl&&el(ee.logoUrl,"logo")&&n.push({url:ee.logoUrl,kind:"logo",caption:"Brand logo"}),et))el(e.url,e.kind)&&n.push({url:e.url,kind:e.kind,caption:e.caption});return{hasAnySource:eS,websiteContext:t,brandVoice:m?ey:null,marketResearchSummary:b&&eu.trim()?eu.trim():null,personas:v&&ex.length>0?ex:null,visualPatterns:ef.map(e=>({...e,enabled:!_.has(e.pattern)})),visualPatternsSummary:eg,includeVisualPatterns:b,businessDescription:ew,includeBusinessDescription:j,referenceAssets:n.slice(0,6)}},[ee.logoUrl,ey,ew,_,eS,et,m,j,v,b,d,el,ex,eu,ef,eg,E,R,U]);(0,o.useEffect)(()=>{s(eE)},[s,eE]);let eP=(0,o.useCallback)(e=>{k(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),eB=(0,o.useId)(),eD=(0,o.useId)(),ez=(0,o.useId)(),eO="previewing"===L.phase||"ingesting"===L.phase||"saving"===L.phase,eF=(0,a.jsxs)("div",{className:"space-y-5",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(rA,{htmlFor:eB,children:"Website address"}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsx)(tv.p,{id:eB,value:D,onChange:e=>z(e.target.value),placeholder:"yourwebsite.com",disabled:eO,className:(0,Y.cn)(aZ,"h-11 min-w-0 flex-1 py-0")}),(0,a.jsxs)("button",{type:"button",className:"inline-flex h-11 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-xl border-[1.5px] border-control-border bg-white px-3.5 text-[0.82rem] font-bold text-midnight-logic transition-colors hover:border-signal-blue hover:text-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",disabled:eO||!D.trim()||!c,onClick:()=>void ei(),children:[eO?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}):null,"reanalyse"===$?"Re-analyse":"Analyse website"]})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(rA,{htmlFor:eD,aside:"".concat(eR," of 5"),children:"Extra pages"}),(0,a.jsx)(eZ.T,{id:eD,value:O,onChange:e=>F(e.target.value),disabled:eO,placeholder:"yourwebsite.com/pricing","aria-describedby":ez,className:(0,Y.cn)(aZ,"min-h-[64px] resize-none text-[0.88rem]")}),(0,a.jsx)(rC,{id:ez,children:"One per line. Read before the pages we find on our own."})]}),eO?(0,a.jsxs)("div",{className:"rounded-[12px] bg-cloud-slate p-2.5",children:[(null==(r=L.preview)?void 0:r.screenshot)?(0,a.jsx)("img",{src:L.preview.screenshot,alt:"Website preview",className:"mb-2 max-h-28 w-full rounded object-cover object-top"}):null,(0,a.jsxs)("p",{className:"flex items-center gap-2 text-xs text-auth-ink-soft",children:[(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}),"saving"===L.phase?"Saving the analysis...":"Analysing the website. This can take a minute or two."]})]}):null,"error"===L.phase?(0,a.jsx)("p",{className:"text-[0.8rem] font-semibold text-auth-error",children:L.message}):null]});return(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)(rS,{icon:(0,a.jsx)(af.A,{className:"h-[18px] w-[18px]"}
1),title:"Website",titleId:"brain-website",subtitle:R?"".concat(R.rootUrl," \xb7 ").concat(aL(R.createdAt).replace(/^Updated /,"analysed "),", ").concat(eM," page").concat(1===eM?"":"s"):C?"Checking for a saved analysisâ¦":"Not analysed yet",included:d,onIncludedChange:u,children:C&&!R?(0,a.jsxs)("div",{className:"flex items-center gap-2 text-[0.84rem] font-medium text-auth-ink-soft",children:[(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}),"Checking for a saved website analysis..."]}):R?(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsx)("div",{className:"flex items-center gap-2",children:ee.logoUrl?(0,a.jsx)("button",{type:"button",disabled:!d,title:el(ee.logoUrl,"logo")?"Logo will be used in generated creatives â click to exclude":"Logo excluded â click to include it in generated creatives",onClick:()=>es(ee.logoUrl,"logo"),className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-md border bg-white p-1 transition ".concat(el(ee.logoUrl,"logo")?"border-signal-blue/60 ring-1 ring-signal-blue/30":"border-auth-hairline opacity-40"),children:(0,a.jsx)("img",{src:ee.logoUrl,alt:"Brand logo",className:"max-h-full max-w-full object-contain"})}):null}),ee.palette.length>0?(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[ee.palette.map(e=>(0,a.jsx)("span",{title:e,className:"h-4 w-4 rounded-full border border-auth-hairline",style:{backgroundColor:e}},e)),(0,a.jsx)("span",{className:"ml-1 text-[0.72rem] font-bold text-auth-ink-soft",children:"Brand colours"})]}):null,(0,a.jsx)(eZ.T,{value:U,onChange:e=>P(e.target.value),disabled:!d,placeholder:"Website summary...","aria-label":"Website summary",className:"min-h-[88px] resize-none rounded-[14px] border-[1.5px] border-control-border bg-auth-field px-3.5 py-3 text-[0.84rem] font-medium leading-[1.5]"}),et.length>0?(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("p",{className:"text-[0.72rem] font-bold text-auth-ink-soft",children:"Website images â selected ones appear in your ads"}),(0,a.jsx)("div",{className:"grid grid-cols-4 gap-1.5",children:et.map(e=>{let t=el(e.url,e.kind);return(0,a.jsxs)("button",{type:"button",disabled:!d,title:"".concat(e.caption||e.kind).concat(t?" â click to exclude":" â click to include"),onClick:()=>es(e.url,e.kind),className:"relative aspect-square overflow-hidden rounded-md border transition ".concat(t?"border-signal-blue/60 ring-1 ring-signal-blue/30":"border-auth-hairline opacity-40 grayscale"),children:[(0,a.jsx)("img",{src:e.url,alt:e.caption||e.kind,loading:"lazy",className:"h-full w-full object-cover"}),(0,a.jsx)("span",{className:"absolute bottom-0 left-0 right-0 truncate bg-black/50 px-1 py-0.5 text-[9px] font-bold uppercase tracking-wide text-white",children:e.kind})]},e.url)})})]}):null,(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-auth-hairline pt-2",children:[(0,a.jsxs)("button",{type:"button",className:"inline-flex min-h-[40px] items-center gap-1.5 rounded-[10px] px-2 text-[0.8rem] font-bold hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50 text-midnight-logic",disabled:eO||G,onClick:()=>"reanalyse"===$?K(null):eo("reanalyse"),children:[(0,a.jsx)(tb.A,{className:"h-3.5 w-3.5"}),"Re-analyse"]}),(0,a.jsx)("button",{type:"button",className:"inline-flex min-h-[40px] items-center gap-1.5 rounded-[10px] px-2 text-[0.8rem] font-bold hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50 text-midnight-logic",disabled:eO||G,onClick:()=>"change"===$?K(null):eo("change"),children:"Change website"}),W?(0,a.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,a.jsx)("span",{className:"text-[0.8rem] font-medium text-auth-ink-soft",children:"Remove this analysis?"}),(0,a.jsxs)("button",{type:"button",className:"inline-flex min-h-[40px] items-center gap-1.5 rounded-[10px] px-2 text-[0.8rem] font-bold hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50 text-auth-error",disabled:G,onClick:()=>void ec(),children:[G?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none"}):null,"Yes, remove"]}),(0,a.jsx)("button",{type:"button",className:"inline-flex min-h-[40px] items-center gap-1.5 rounded-[10px] px-2 text-[0.8rem] font-bold hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50 text-auth-ink-soft",disabled:G,onClick:()=>J(!1),children:"Cancel"})]}):(0,a.jsxs)("button",{type:"button",className:"inline-flex min-h-[40px] items-center gap-1.5 rounded-[10px] px-2 text-[0.8rem] font-bold hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-50 text-auth-error",disabled:eO||G,onClick:()=>{J(!0),K(null)},children:[(0,a.jsx)(eU.A,{className:"h-3.5 w-3.5"}),"Remove"]})]}),V?(0,a.jsx)("p",{className:"text-xs text-auth-error",children:V}):null,$?(0,a.jsxs)("div",{className:"rounded-[12px] bg-cloud-slate p-3.5",children:[(0,a.jsx)("p",{className:"mb-2 text-[11px] font-bold text-auth-ink-soft",children:"reanalyse"===$?"Re-analyse this website (a fresh analysis replaces the current one)":"Analyse a different website (replaces the current analysis)"}),eF]}):null]}):(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsx)("p",{className:"text-[0.88rem] font-medium leading-[1.5] text-auth-ink-soft",children:"Analyse your website so campaigns reflect your real offer and pages."}),eF]})}),ek?(0,a.jsxs)(rS,{icon:(0,a.jsx)(rp.A,{className:"h-[18px] w-[18px]"}),title:"Brand voice",titleId:"brain-voice",subtitle:"From your business profile",included:m,onIncludedChange:g,children:[(0,a.jsx)("dl",{className:"flex flex-col",children:eT.map(e=>{let[t,n]=e;return(0,a.jsxs)("div",{className:"grid grid-cols-[120px_minmax(0,1fr)] gap-3 border-b border-auth-hairline py-2.5 text-[0.88rem] leading-[1.5]",children:[(0,a.jsx)("dt",{className:"font-medium text-auth-ink-soft",children:t}),(0,a.jsx)("dd",{className:"font-semibold text-midnight-logic",children:n})]},t)})}),(0,a.jsxs)(l(),{href:"/dashboard/tools/brand-identity",className:"mt-3 inline-flex min-h-[44px] items-center gap-1.5 text-[0.86rem] font-bold text-signal-blue hover:text-anchor-blue",children:["Edit in Brand Studio",(0,a.jsx)(rh.A,{className:"h-[15p
1x] w-[15px]","aria-hidden":!0})]})]}):null,eA?(0,a.jsxs)(rS,{icon:(0,a.jsx)(rf.A,{className:"h-[18px] w-[18px]"}),title:"Market research",titleId:"brain-research",subtitle:eh?aL(eh):void 0,included:b,onIncludedChange:y,children:[ef.length>0?(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)("p",{className:"text-[0.8rem] font-bold text-auth-ink-soft",children:"Winning ad patterns"}),(0,a.jsx)("div",{className:"flex flex-wrap gap-1.5",children:ef.map(e=>{let t=!_.has(e.pattern);return(0,a.jsx)("button",{type:"button","aria-pressed":t,disabled:!b,title:e.how_to_apply||e.evidence||e.pattern,onClick:()=>eP(e.pattern),className:t?"min-h-[36px] rounded-full border-[1.5px] border-signal-blue bg-auth-field px-3 text-[0.78rem] font-bold text-anchor-blue":"min-h-[36px] rounded-full border-[1.5px] border-control-border bg-white px-3 text-[0.78rem] font-bold text-auth-muted line-through",children:e.pattern},e.pattern)})})]}):(0,a.jsx)("p",{className:"text-[0.88rem] font-medium leading-[1.5] text-auth-ink-soft",children:"Latest research is included as campaign context."}),(0,a.jsxs)(l(),{href:"/dashboard/tools/market-research",className:"mt-3 inline-flex min-h-[44px] items-center gap-1.5 text-[0.86rem] font-bold text-signal-blue hover:text-anchor-blue",children:["View research",(0,a.jsx)(rh.A,{className:"h-[15px] w-[15px]","aria-hidden":!0})]})]}):null,eC?(0,a.jsxs)(rS,{icon:(0,a.jsx)(rg.A,{className:"h-[18px] w-[18px]"}),title:"Personas & pillars",titleId:"brain-personas",subtitle:eh?aL(eh):void 0,included:v,onIncludedChange:w,children:[(0,a.jsx)("div",{className:"flex flex-col gap-3.5",children:ex.slice(0,4).map(e=>(0,a.jsxs)("p",{className:"text-[0.88rem] font-medium leading-[1.5] text-auth-ink-soft",children:[(0,a.jsxs)("strong",{className:"font-bold text-midnight-logic",children:[e.name,"."]})," ",e.description]},e.name))}),eb.length>0?(0,a.jsxs)("div",{className:"mt-[18px] flex flex-col gap-2.5 border-t border-auth-hairline pt-[18px]",children:[(0,a.jsx)("p",{className:"text-[0.68rem] font-extrabold uppercase tracking-[0.09em] text-auth-ink-soft",children:"Content pillars"}),(0,a.jsx)("ul",{className:"flex flex-col gap-2",children:eb.map(e=>(0,a.jsx)("li",{className:"rounded-[12px] bg-auth-field px-3.5 py-3 text-[0.86rem] font-bold leading-[1.35] text-anchor-blue",children:e},e))})]}):null]}):null,eS?null:(0,a.jsx)(rS,{icon:(0,a.jsx)(rp.A,{className:"h-[18px] w-[18px]"}),title:"Describe your business",titleId:"brain-description",subtitle:"No saved context sources yet",included:j,onIncludedChange:N,children:(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)("label",{htmlFor:"brain-description-field",className:"block text-[0.88rem] font-bold text-midnight-logic",children:"What you sell, who itâs for, what makes it different"}),(0,a.jsx)(eZ.T,{id:"brain-description-field",value:ew,onChange:e=>ej(e.target.value),disabled:!j,placeholder:"What do you sell, who is it for, and what makes it different?",className:"min-h-[88px] resize-none rounded-[14px] border-[1.5px] border-control-border bg-auth-field text-[0.84rem]"})]})})]})}var rT=n(65240),rM=n(19680),rR=n(24543),rE=n(59122);function rU(e){let{open:t,onOpenChange:n,src:r,alt:l,platform:s,platformLabel:i,formatLine:o,headline:c,ordinal:d,total:u}=e;return(0,a.jsx)(eQ.lG,{open:t,onOpenChange:n,children:(0,a.jsxs)(eQ.Cf,{hideCloseButton:!0,overlayClassName:"bg-midnight-logic/80 backdrop-blur-sm",className:"flex w-auto max-w-[min(92vw,1100px)] flex-col items-center gap-3 border-0 bg-transparent p-0 shadow-none backdrop-blur-none",children:[(0,a.jsxs)("div",{className:"flex w-full items-center justify-between gap-4 text-white",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2.5",children:[(0,a.jsx)(a9,{platform:s||"post",size:"sm"}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsxs)(eQ.L3,{className:"truncate text-[0.92rem] font-extrabold leading-tight tracking-normal text-white",children:[i," \xb7 post ",d," of ",u]}),(0,a.jsx)(eQ.rr,{className:"truncate text-[0.78rem] font-medium text-white/80",children:o})]})]}),(0,a.jsx)(eQ.HM,{"aria-label":"Close preview",className:"grid h-10 w-10 shrink-0 place-items-center rounded-[10px] bg-white text-midnight-logic transition-colors hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-midnight-logic",children:(0,a.jsx)(eG.A,{className:"h-[18px] w-[18px]","aria-hidden":!0})})]}),(0,a.jsx)("img",{src:r,alt:l,className:"max-h-[calc(100vh-11rem)] max-w-full rounded-[14px] bg-cloud-slate object-contain shadow-large"}),c?(0,a.jsx)("p",{className:"max-w-[40rem] text-center text-[0.9rem] font-bold leading-[1.4] text-white",children:c}):null]})})}let rP="relative inline-flex min-h-[36px] items-center justify-center gap-1.5 rounded-[10px] text-[0.78rem] font-bold text-midnight-logic transition-colors before:absolute before:-inset-1 before:content-[''] hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:opacity-50",rB="".concat(rP," h-9 w-9 shrink-0");function rD(e){let{src:t,poster:n,ordinal:r,ratio:l}=e,s=(0,o.useRef)(null),[i,c]=(0,o.useState)(!1),[d,u]=(0,o.useState)(null);return(0,a.jsxs)("div",{className:"relative overflow-hidden rounded-xl bg-midnight-logic",style:{aspectRatio:String(l)},children:[(0,a.jsx)("video",{ref:s,src:t,poster:null!=n?n:void 0,preload:"metadata",playsInl
1ine:!0,controls:i,onLoadedMetadata:e=>u(function(e){if(!Number.isFinite(e)||e<=0)return null;let t=Math.round(e);return"".concat(Math.floor(t/60),":").concat(String(t%60).padStart(2,"0"))}(e.currentTarget.duration)),className:"h-full w-full object-cover"}),i?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("span",{"aria-hidden":!0,className:"absolute right-2.5 top-2.5 inline-flex items-center gap-1 rounded-full bg-midnight-logic/90 px-[7px] py-1 text-[0.66rem] font-bold tabular-nums text-white",children:[(0,a.jsx)(eJ.A,{className:"h-2.5 w-2.5"}),null!=d?d:"Video"]}),(0,a.jsx)("button",{type:"button","aria-label":d?"Play post ".concat(r,", ").concat(d):"Play post ".concat(r),onClick:()=>{var e;c(!0),null==(e=s.current)||e.play()},className:"absolute bottom-3.5 left-1/2 grid h-11 w-11 -translate-x-1/2 place-items-center rounded-full bg-midnight-logic/90 text-white transition-colors hover:bg-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white motion-reduce:transition-none",children:(0,a.jsx)(eJ.A,{className:"ml-0.5 h-[18px] w-[18px]","aria-hidden":!0})})]})]})}function rz(e){var t,n;let{card:r,ordinal:l,ratio:s,onPreview:i}=e,o=null!=(t=r.imageUrls[0])?t:null,c=null!=(n=r.videoUrls[0])?n:null;if("failed"===r.status)return(0,a.jsxs)("div",{className:"flex w-full flex-col items-center justify-center gap-2 rounded-xl bg-auth-error-bg text-auth-error",style:{aspectRatio:String(s)},children:[(0,a.jsx)(nt.A,{className:"h-6 w-6","aria-hidden":!0}),(0,a.jsx)("p",{className:"px-4 text-center text-xs font-semibold",children:r.error||"Generation failed"})]});if(c)return(0,a.jsx)(rD,{src:c,poster:o,ordinal:l,ratio:s});let d=aX(r);return d?(0,a.jsxs)("button",{type:"button",onClick:i,"aria-label":"Preview post ".concat(l),className:"group relative block w-full cursor-zoom-in overflow-hidden rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",style:{aspectRatio:String(s)},children:[(0,a.jsx)("img",{src:d,alt:r.title||"Generated post",className:"h-full w-full bg-auth-field object-cover"}),(0,a.jsxs)("span",{"aria-hidden":!0,className:"absolute bottom-2 right-2 inline-flex items-center gap-1.5 rounded-full bg-midnight-logic px-2.5 py-1 text-[0.7rem] font-bold text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none",children:[(0,a.jsx)(H.A,{className:"h-3 w-3"}),"Preview"]})]}):(0,a.jsxs)("div",{className:"relative w-full overflow-hidden rounded-xl bg-auth-field",style:{aspectRatio:String(s)},children:[(0,a.jsx)("div",{className:"absolute inset-0 animate-pulse bg-gradient-to-br from-auth-field via-auth-field-border to-auth-field motion-reduce:animate-none"}),(0,a.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-auth-muted",children:[(0,a.jsx)(p.A,{className:"h-5 w-5 animate-spin motion-reduce:animate-none","aria-hidden":!0}),(0,a.jsx)("p",{className:"text-[0.72rem] font-extrabold uppercase tracking-[0.06em]",children:"queued"===r.status?"Queued":"Generatingâ¦"})]})]})}function rO(e){var t,n,r;let{task:l,lane:s,ordinal:i,total:c,boardId:d,runId:u,onOpenInBoard:m,onError:h}=e,f=(0,o.useMemo)(()=>a$(l),[l]),g=(n=l.id,"ad-maker:campaign-studio:caption:".concat(n)),x=(r=l.id,"ad-maker:campaign-studio:steer:".concat(r)),[b,y]=(0,o.useState)(()=>ti(g)||f.caption),v=(0,o.useRef)(b),[w,j]=(0,o.useState)(!1),N=(0,o.useRef)(f.caption);(0,o.useEffect)(()=>{f.caption&&f.caption!==N.current&&(N.current=f.caption,ti(g)||(v.current=f.caption,y(f.caption)))},[g,f.caption]),(0,o.useEffect)(()=>{if(v.current=b,b===N.current)return;to(g,b);let e=window.setTimeout(()=>{let e=v.current;e!==N.current&&e.trim()&&(j(!0),aI({taskId:l.id,boardId:d,runId:u,caption:e}).then(()=>{N.current=e,v.current===e&&to(g,"")}).catch(e=>{h(e instanceof Error?e.message:"Could not save the caption")}).finally(()=>j(!1)))},900);return()=>window.clearTimeout(e)},[d,b,g,h,u,l.id]),(0,o.useEffect)(()=>()=>{v.current!==N.current&&to(g,v.current)},[g]);let[_,k]=(0,o.useState)(!1),[A,C]=(0,o.useState)(()=>ti(x)),S=(0,o.useRef)(A),[I,T]=(0,o.useState)(!1);(0,o.useEffect)(()=>{S.current=A;let e=window.setTimeout(()=>to(x,A),400);return()=>window.clearTimeout(e)},[A,x]),(0,o.useEffect)(()=>()=>to(x,S.current),[x]);let M=(0,o.useCallback)(async()=>{T(!0);
1try{await aC({taskId:l.id,boardId:d,runId:u,steer:A.trim()||void 0}),to(x,""),S.current="",C(""),k(!1)}catch(e){h(e instanceof Error?e.message:"Could not regenerate this post")}finally{T(!1)}},[d,h,u,A,x,l.id]),[R,E]=(0,o.useState)(!1),[U,P]=(0,o.useState)(!1),B=aX(f),D="queued"===f.status||"running"===f.status,z="completed"===f.status,O="failed"===f.status,F=aP(f.platform||"post"),L=aQ(f.formatLabel,F),q=f.angle||f.headline||f.title;return(0,a.jsxs)("li",{className:"flex flex-col gap-2.5 rounded-[14px] bg-cloud-slate p-2.5",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,a.jsx)(a9,{platform:f.platform||"post",size:"sm",tone:"logo"}),(0,a.jsxs)("span",{className:"min-w-0 flex-1 truncate text-[0.8rem] font-bold text-midnight-logic",children:[F," \xb7 ",L]}),(0,a.jsxs)("span",{className:"shrink-0 text-[0.72rem] font-semibold text-auth-ink-soft",children:[i," of ",c]})]}),(0,a.jsx)(rz,{card:f,ordinal:i,ratio:null!=(t=s.aspectRatio)?t:1,onPreview:()=>P(!0)}),q?(0,a.jsx)("h4",{className:"text-[0.86rem] font-bold leading-[1.35] text-midnight-logic [text-wrap:pretty]",children:q}):null,R?(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(eZ.T,{value:b,"aria-label":"Caption for post ".concat(i),autoFocus:!0,className:"min-h-[96px] resize-none rounded-xl border-control-border bg-white px-3 py-2.5 text-[0.78rem] font-medium leading-[1.5] text-midnight-logic",onChange:e=>y(e.target.value)}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsx)("span",{className:"flex items-center gap-1.5 text-[0.72rem] font-semibold text-auth-muted","aria-live":"polite",children:w?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(p.A,{className:"h-3 w-3 animate-spin motion-reduce:animate-none","aria-hidden":!0}),"Saving captionâ¦"]}):"Saves as you type"}),(0,a.jsx)("button",{type:"button",className:(0,Y.cn)(rP,"px-2.5"),onClick:()=>E(!1),children:"Done"})]})]}):null,(0,a.jsxs)("div",{className:"-mx-1 -mb-1 mt-auto flex items-center gap-0.5",children:[(0,a.jsxs)("button",{type:"button",className:(0,Y.cn)(rP,"flex-1 px-2"),disabled:D||I,onClick:()=>O?void M():k(e=>!e),children:[I?(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}):(0,a.jsx)(rT.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),O?"Retry":"Regenerate"]}),O?null:(0,a.jsxs)("button",{type:"button",className:(0,Y.cn)(rP,"px-2.5"),disabled:D,"aria-expanded":R,"aria-label":"Edit the caption for post ".concat(i),onClick:()=>E(e=>!e),children:[(0,a.jsx)(eR.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Edit"]}),(0,a.jsxs)(rE.rI,{children:[(0,a.jsx)(rE.ty,{asChild:!0,children:(0,a.jsx)("button",{type:"button","aria-label":"More actions for post ".concat(i),className:rB,children:(0,a.jsx)(rM.A,{className:"h-4 w-4","aria-hidden":!0})})}),(0,a.jsxs)(rE.SQ,{align:"end",className:"w-64",children:[(0,a.jsxs)(rE.lp,{className:"text-[0.72rem] font-semibold text-auth-ink-soft",children:[f.formatLabel,f.dimensionsLabel?" \xb7 ".concat(f.dimensionsLabel):""]}),(0,a.jsx)(rE.mB,{}),(0,a.jsxs)(rE._2,{disabled:!z||!m,onSelect:()=>null==m?void 0:m(),className:"gap-2 text-[0.82rem] font-bold",children:[(0,a.jsx)(rR.A,{className:"h-3.5 w-3.5","aria-hidden":!0}),z?"Open in Board":"Open in Board â available when ready"]})]})]})]}),B?(0,a.jsx)(rU,{open:U,onOpenChange:P,src:B,alt:f.title||"Generated post",platform:f.platform,platformLabel:F,formatLine:"".concat(f.formatLabel).concat(f.dimensionsLabel?" \xb7 ".concat(f.dimensionsLabel):""),headline:f.headline||f.title,ordinal:i,total:c}):null,_&&!D?(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(tv.p,{value:A,disabled:I,"aria-label":"Steer the redo for post ".concat(i),placeholder:"Steer the redo, e.g. brighter, less textâ¦",className:"h-10 flex-1 rounded-xl border-control-border bg-white text-[0.78rem] font-medium",onChange:e=>C(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),I||M())}}),(0,a.jsx)("button",{type:"button",className:"inline-flex min-h-[40px] items-center rounded-xl bg-signal-blue px-4 text-[0.78rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:opacity-60",disabled:I,onClick:()=>void M(),children:"Redo"})]}):null]})}let rF={wide:"grid-cols-1 sm:grid-cols-2 xl:grid-cols-3",tall:"grid-cols-2 sm:grid-cols-3"};function rL(e){let{tasks:t,lanes:n,filter:r,boardId:l,runId:s,onOpenInBo
1ard:i,onError:c}=e,d=(0,o.useMemo)(()=>t.map((e,t)=>({task:e,card:a$(e),ordinal:t+1})),[t]),u=n.filter(e=>"all"===r||r===e.key);return(0,a.jsx)("div",{className:"flex flex-col gap-4",children:u.map(e=>{let n=d.filter(t=>{let{card:n}=t;return aJ(n)===e.key});return 0===n.length?null:(0,a.jsxs)("section",{"aria-labelledby":"lane-".concat(e.key),className:"flex flex-col gap-5 rounded-[18px] bg-white p-4 pb-[18px] shadow-[0_8px_30px_rgba(13,14,29,0.06)]",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2.5",children:[(0,a.jsx)(a9,{platform:e.platform,size:"md",tone:"logo"}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h3",{id:"lane-".concat(e.key),className:"truncate text-[0.98rem] font-extrabold leading-[1.25] text-midnight-logic",children:e.title}),(0,a.jsx)("p",{className:"truncate text-[0.8rem] font-medium leading-[1.25] text-auth-ink-soft",children:e.specLine})]})]}),(0,a.jsx)("ul",{className:(0,Y.cn)("grid items-start gap-3",rF[e.tall?"tall":"wide"]),children:n.map(n=>{let{task:r,ordinal:o}=n;return(0,a.jsx)(rO,{task:r,lane:e,ordinal:o,total:t.length,boardId:l,runId:s,onOpenInBoard:i,onError:c},r.id)})})]},e.key)})})}var rq=n(75011);function r$(e){let{message:t,onDismiss:n}=e;return(0,a.jsxs)("div",{role:"alert",className:"flex items-start gap-2.5 rounded-[12px] bg-auth-error-bg px-3.5 py-3 text-[0.82rem] font-semibold leading-[1.45] text-auth-error",children:[(0,a.jsx)(eg.A,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":!0}),(0,a.jsx)("p",{className:"min-w-0 flex-1",children:t}),(0,a.jsx)("button",{type:"button",className:"relative min-h-[24px] shrink-0 rounded font-bold underline before:absolute before:-inset-2.5 before:content-[''] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onClick:n,children:"Dismiss"})]})}function rK(e){let{children:t,action:n}=e;return(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 rounded-[12px] border border-auth-field-border bg-auth-field px-3.5 py-3 text-[0.82rem] font-semibold leading-[1.45] text-midnight-logic",children:[(0,a.jsx)(rq.A,{className:"h-4 w-4 shrink-0 text-anchor-blue","aria-hidden":!0}),(0,a.jsx)("div",{className:"min-w-0 flex-1",children:t}),n]})}function rW(e){let{hasBrief:t}=e;return(0,a.jsxs)("div",{className:"flex flex-col items-center gap-3 rounded-[18px] border-[1.5px] border-dashed border-auth-field-border bg-white px-6 py-12 text-center",children:[(0,a.jsx)("img",{src:"/brand/sparky.svg",alt:"","aria-hidden":"true",width:72,height:72,className:"h-[72px] w-[72px] animate-sparky-float motion-reduce:animate-none"}),(0,a.jsx)("p",{className:"text-[1.05rem] font-extrabold text-midnight-logic",children:"Your first drafts land here"}),(0,a.jsx)("p",{className:"max-w-[26rem] text-[0.88rem] font-medium leading-[1.55] text-auth-ink-soft",children:t?"Check the brief on the left, then generate. Posts appear here as theyâre made, ready to edit, regenerate or open in the Board.":"Describe what you want to make and weâll draft a brief from your Business Brain sources."})]})}function rJ(e){let{loading:t,hasBrief:n,showGrid:r,tasks:s,boardId:i,runId:c,surfaceSwitch:d,onOpenBoard:u,completion:m,error:h,onError:f,onDismissError:g,schedule:x,drawer:b}=e,[y,v]=(0,o.useState)("all");(0,o.useEffect)(()=>v("all"),[c]);let w=(0,o.useMemo)(()=>(function(e){let t=[],n=new Map;for(let a of e){let e=aJ(a),r=n.get(e);if(r){r.count+=1;continue}n.set(e,{first:a,count:1}),t.push(e)}return t.map(e=>{let{first:t,count:a}=n.get(e),r=t.formatKey?tu[t.formatKey]:void 0,l=function(e,t){let n="post";"instagram_reel"===e?n="reel":e&&aW.has(e)?n="video":(null==e?void 0:e.endsWith("_story"))&&(n="story");let a="story"===n?"stories":"".concat(n,"s");return"".concat(t," ").concat(1===t?n:a)}(t.formatKey,a);return{key:e,platform:aB(t.platform)||"post",title:(null==r?void 0:r.label)||t.formatLabel||aP(t.platform||"post"),specLine:r?"".concat(l," \xb7 ").concat(r.aspectRatio," \xb7 ").concat(r.width,"\xd7").concat(r.height):l,aspectRatio:r?r.width/r.height:null,tall:!!r&&r.height>r.width,isVideo:!!t.formatKey&&aW.has(t.formatKey),count:a}})})(s.map(e=>a$(e))),[s]),j=(0,o.useMemo)(()=>[{key:"all",label:"All lanes",count:w.reduce((e,t)=>
1e+t.count,0)},...w.map(e=>({key:e.key,label:e.title,count:e.count}))],[w]),N=j.some(e=>e.key===y)?y:"all",_=s.filter(e=>"completed"===e.status).length,k=s.filter(e=>"failed"===e.status).length,A=s.length>0&&_===s.length;return(0,a.jsxs)("section",{"aria-labelledby":"studio-content-heading",className:"relative flex flex-col bg-cloud-slate lg:min-h-0 lg:overflow-hidden",children:[(0,a.jsxs)("div",{className:"flex flex-none flex-col gap-3 px-6 pt-3.5",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,a.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3.5 gap-y-1",children:[(0,a.jsx)("h2",{id:"studio-content-heading",className:"text-[1.15rem] font-extrabold text-midnight-logic",children:"Campaign content"}),s.length>0?(0,a.jsxs)("span",{className:"flex items-center gap-2 text-[0.8rem] font-semibold text-midnight-logic",children:[(0,a.jsx)("span",{role:"progressbar","aria-label":"Posts ready","aria-valuemin":0,"aria-valuemax":s.length,"aria-valuenow":_,className:"h-1.5 w-[120px] overflow-hidden rounded-full bg-auth-field-border",children:(0,a.jsx)("span",{className:"block h-full rounded-full bg-signal-blue transition-[width] duration-300 motion-reduce:transition-none",style:{width:"".concat(Math.round(_/s.length*100),"%")}})}),A?null:(0,a.jsx)(p.A,{className:"h-3.5 w-3.5 animate-spin text-signal-blue motion-reduce:animate-none","aria-hidden":!0}),_," of ",s.length," ready",k>0?" \xb7 ".concat(k," failed"):""]}):null]}),(0,a.jsxs)("div",{className:"flex items-center gap-2.5",children:[d,u&&_>0?(0,a.jsx)("button",{type:"button",onClick:u,className:"inline-flex min-h-[44px] items-center rounded-xl bg-signal-blue px-[18px] text-[0.88rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",children:"Open Board"}):null]})]}),w.length>1?(0,a.jsx)("div",{role:"group","aria-label":"Filter by lane",className:"flex flex-wrap gap-1.5 pb-3",children:j.map(e=>{let t=e.key===N;return(0,a.jsx)("button",{type:"button","aria-pressed":t,onClick:()=>v(e.key),className:(0,Y.cn)("min-h-[36px] rounded-full px-3.5 text-[0.8rem] font-bold transition-colors relative before:absolute before:inset-x-0 before:-inset-y-1 before:content-[''] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",t?"bg-signal-blue text-white":"border-[1.5px] border-control-border bg-white text-midnight-logic hover:bg-auth-field"),children:"all"===e.key?e.label:"".concat(e.label," \xb7 ").concat(e.count)},e.key)})}):(0,a.jsx)("div",{className:"pb-3"})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-4 px-6 pb-6 pt-1 lg:min-h-0 lg:flex-1 lg:overflow-y-auto",children:[h?(0,a.jsx)(r$,{message:h,onDismiss:g}):null,m?(0,a.jsx)(rK,{action:(0,a.jsxs)("span",{className:"flex flex-wrap items-center gap-3",children:[(0,a.jsx)(l(),{href:aE,className:"text-[0.82rem] font-bold text-signal-blue underline hover:text-anchor-blue",children:"View scheduled posts"}),(0,a.jsxs)("button",{type:"button",disabled:m.resetting,onClick:m.onStartNew,className:"inline-flex min-h-[40px] items-center gap-2 rounded-xl border-[1.5px] border-control-border bg-white px-3.5 text-[0.82rem] font-bold text-midnight-logic hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:opacity-60",children:[m.resetting?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin motion-reduce:animate-none","aria-hidden":!0}):null,m.resetting?"Startingâ¦":"Start new campaign"]})]}),children:(0,a.jsxs)("span",{className:"inline-flex items-center gap-2",children:[(0,a.jsx)(tp.A,{className:"h-4 w-4 shrink-0 text-anchor-blue","aria-hidden":!0}),(0,a.jsxs)("span",{children:["Campaign complete. ",m.scheduledPostCount||"Your"," post",1===m.scheduledPostCount?" has":"s have"," been scheduled. There are no further required steps."]})]})}):null,t?(0,a.jsxs)("p",{className:"flex items-center gap-2 text-[0.86rem] font-medium text-auth-ink-soft",children:[(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin motion-reduce:animate-none","aria-hidden":!0}),"Checking for an active campaignâ¦"]}):r&&c?0===s.length?(0,a.jsxs)("p",{className:"flex items-center gap-2 rounded-[14px] border-[1.5px] border-dashed border-auth-field-border bg-white px-4 py-6 text-[0.88rem] font-medium text-auth-ink-soft",children:[(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin text-signal-blue motion-reduce:animate-none","aria-hidden":!0}),"Preparing the content planâ¦"]}):(0,a.jsx)(rL,{tasks:s,lanes:w,filter:N,boardId:i,runId:c,onOpenInBo
1ard:u,onError:f}):(0,a.jsx)(rW,{hasBrief:n}),x]}),b]})}let rG=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function rH(e){let{active:t,onClick:n,children:r}=e;return(0,a.jsx)("button",{type:"button","aria-pressed":t,onClick:n,className:(0,Y.cn)("min-h-[36px] rounded-full px-4 text-[0.78rem] font-bold transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",t?"bg-signal-blue text-white":"bg-cloud-slate text-auth-ink-soft hover:bg-auth-hairline"),children:r})}function rY(e){let t=new Date(e);t.setHours(0,0,0,0);let n=(t.getDay()+6)%7;return t.getTime()-864e5*n}function rV(e){var t;let{wave:n,scheduleTasks:r,contentTasks:s,boardId:i,runId:c,accounts:d,onApproved:u,onError:m}=e,h="ad-maker:campaign-studio:schedule-overrides:".concat(c),[f,g]=(0,o.useState)(()=>(function(e){let t=rw(e);if(!t||"object"!=typeof t||Array.isArray(t))return{};let n={};return Object.entries(t).forEach(e=>{let[t,a]=e;"string"==typeof a&&a&&(n[t]=a)}),n})(h)),x=(0,o.useRef)(f),[b,y]=(0,o.useState)(!1),[v,w]=(0,o.useState)(!1),[j,N]=(0,o.useState)(null);(0,o.useEffect)(()=>{x.current=f,rj(h,Object.keys(f).length>0?f:null)},[f,h]),(0,o.useEffect)(()=>()=>{let e=x.current;rj(h,Object.keys(e).length>0?e:null)},[h]);let _=(0,o.useMemo)(()=>r.map(aK).filter(e=>null!==e),[r]),k=(0,o.useMemo)(()=>{let e=new Map;return s.forEach(t=>{var n;let a=a$(t),r=null!=(n=a.imageUrls[0])?n:a.mediaUrls[0];r&&e.set(t.id,r)}),e},[s]),A=(0,o.useMemo)(()=>new Set(d.filter(e=>0!==e.isActive).map(e=>aB(e.network))),[d]),C=(0,o.useCallback)(e=>{let t=Date.parse(f[e.taskId]||e.scheduledTime);return Number.isFinite(t)?t:Date.now()},[f]),S=(0,o.useMemo)(()=>Array.from(new Set(_.flatMap(e=>e.platforms))).sort(),[_]),I=(0,o.useMemo)(()=>j?_.filter(e=>e.platforms.includes(j)):_,[j,_]),T=(0,o.useMemo)(()=>Array.from(new Set(I.map(e=>rY(C(e))))).sort((e,t)=>e-t),[C,I]),[M,R]=(0,o.useState)(null),E=null!=(t=null!=M?M:T[0])?t:rY(Date.now()),U=T.length>1,P=(0,o.useMemo)(()=>{let e=new Map;return I.forEach(t=>{var n;let a=C(t);if(rY(a)!==E)return;let r=Math.min(6,Math.max(0,Math.floor((a-E)/864e5))),l=null!=(n=e.get(r))?n:[];l.push(t),e.set(r,l)}),e.forEach(e=>e.sort((e,t)=>C(e)-C(t))),e},[E,C,I]),B=(0,o.useCallback)((e,t)=>{if(!t)return;let n=new Date(t);if(Number.isNaN(n.getTime()))return;let a=n.toISOString();g(t=>{if(Date.parse(e.scheduledTime)===n.getTime()){if(!(e.taskId in t))return t;let n={...t};return delete n[e.taskId],n}return{...t,[e.taskId]:a}})},[]),D=(0,o.useCallback)(async()=>{y(!0);try{let e=Object.entries(f).map(e=>{let[t,n]=e;return{taskId:t,scheduledTime:n}});await nE({boardId:i,runId:c,waveKey:n.waveKey,approved:!0,clientTimezone:aD(),outstandAccounts:d,...e.length>0?{scheduleOverrides:e}:{}}),rj(h,null),x.current={},w(!0),u()}catch(e){m(e instanceof Error?e.message:"Could not approve the schedule")}finally{y(!1)}},[d,i,u,m,f,h,c,n.waveKey]),z=(0,o.useMemo)(()=>{let e=new Date(E),t=new Date(E+5184e5),n=e=>e.toLocaleDateString(void 0,{day:"numeric",month:"short"});return"".concat(n(e)," â ").concat(n(t))},[E]);return(0,a.jsxs)("section",{className:"rounded-[20px] border border-auth-hairline bg-white p-6 shadow-[0_12px_32px_rgba(13,14,29,0.05)] lg:px-7",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,a.jsx)("span",{"aria-hidden":!0,className:"grid h-7 w-7 shrink-0 place-items-center rounded-[9px] bg-signal-blue text-white",children:(0,a.jsx)(nr.A,{className:"h-3.5 w-3.5"})}),(0,a.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2.5",children:[(0,a.jsx)("h2",{className:"text-[0.95rem] font-extrabold text-midnight-logic",children:"Proposed schedule"}),(0,a.jsxs)("p",{className:"text-[0.8rem] font-medium text-auth-muted",children:[_.length," post",1===_.length?"":"s"," â adjust times, then approve"]})]})]}),(0,a.jsx)("div",{className:"flex items-center gap-1.5",children:U?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button","aria-label":"Previous week",className:"grid h-9 w-9 place-items-center rounded-[10px] border border-auth-hairline text-auth-ink-soft transition-colors hover:border-signal-blue hover:text-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onClick:()=>R(E-6048e5),children:(0,a.jsx)(eD.A,{className:"h-4 w-4"})}),(0,a.jsx)("span",{className:"px-2 text-[0.82rem] font-extrabold tabular-nums text-midnight-logic",children:z}),(0,a.jsx)("button",{type:"button","aria-label":"Next week",className:"grid h-9 w-9 place-items-center rounded-[10px] border border-auth-hairline text-auth-ink-soft transition-colors hover:border-signal-blue hover:text-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",onClick:()=>R(E+6048e5),children:(0,a.jsx)(ez.A,{className:"h-4 w-4"})})]}):(0,a.jsx)("span",{className:"px-2 text-[0.82rem] font-extrabold tabular-nums text-midnight-logic",children:z})})]}),S.length>1?(0,a.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[(0,a.jsx)(rH,{active:null===j,onClick:()=>N(null),children:"All platforms"}),S.map(e=>(0,a.jsx)(rH,{active:j===e,onClick:()=>N(t=>t===e?null:e),children:aP(e)},e))]}):null,(0,a.jsx)("div",{className:"mt-4 overflow-x-auto rounded-2xl border border-auth-hairline",children:(0,a.jsxs)("div",{className:"grid min-w-[820px] grid-cols-7",children:[rG.map((e,t)=>{let n=new Date(E+864e5*t);return(0,a.jsxs)("div",{className:(0,Y.cn)("bg-cloud-slate px-3 py-2.5 text-[0.68rem] font-extrabold uppercase tracking-[0.06em] text-auth-ink-soft",t>0&&"border-l border-auth-hairline"),children:[e," ",n.getDate()]},"head-".concat(e))}),rG.map((e,t)=>{var n;let r=null!=(n=P.get(t))?n:[];return(0,a.jsx)("div",{className:(0,Y.cn)("min-w-0 border-t border-auth-hairline p-2",t>0&&"border-l"),children:(0,a.jsx)("div",{className:"space-y-2",children:r.map(e=>{var t;let n=null!=(t=e.mediaUrls[0])?t:e.sourceTaskId?k.get(e.sourceTaskId):void 0,r=e.platforms.filter(e=>!A.has(e)),s=function(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=e=>String(e).padStart(2,"0");return"".concat(t.getFullYear(),"-").concat(n(t.getMonth()+1),"-").concat(n(t.getDate()),"T").concat(n(t.getHours()),":").concat(n(t.getMinutes()))}(f[e.taskId]||e.scheduledTime);return(0,a.jsxs)("div",{className:"flex flex-col gap-1.5 rounded-xl border border-auth-hairline bg-white p-2",children:[n?(0,a.jsx)("img",{src:n,alt:"",className:"aspect-square w-full rounded-lg bg-cloud-slate object-cover"}):null,(0,a.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5",children:[e.platforms[0]?(0,a.jsx)(a9,{platform:e.platforms[0],size:"sm"}):null,(0,a.jsx)("span",{className:"min-w-0 truncate text-[0.7rem] font-extrabold text-midnight-logic",children:e.platforms.map(aP).join(", ")||"Post"})]}),(0,a.jsx)("input",{type:"datetime-local",value:s,disabled:b||v,"aria-label":"Scheduled time for ".concat(e.platforms.map(aP).join(", ")||"post"),className:"w-full rounded-lg border border-control-border bg-white px-1.5 py-1 text-[0.68rem] font-semibold tabular-nums text-midnight-logic disabled:opacity-60",onChange:t=>B(e,t.target.value)}),r.length>0?(0,a.jsxs)(l(),{href:aE,className:"truncate rounded-full bg-campaign-draft px-2 py-1 text-center text-[0.6rem] font-extrabold uppercase tracking-[0.04em] text-midnight-logic transition-opacity hover:opacity-80",children:["Draft â connect ",r.map(aP).join(", ")
1]}):null]},e.taskId)})})},e)})]})}),(0,a.jsxs)("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-auth-hairline pt-5",children:[v?(0,a.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-auth-field-border bg-auth-field px-4 py-3 text-[0.86rem] font-bold text-anchor-blue",children:[(0,a.jsx)(tp.A,{className:"h-4 w-4 shrink-0","aria-hidden":!0}),"Schedule approved. Creating ",_.length," scheduled post",1===_.length?"":"s","â¦"]}):(0,a.jsxs)("button",{type:"button",className:"inline-flex min-h-[48px] items-center gap-2 rounded-xl bg-signal-blue px-[22px] text-[0.88rem] font-bold text-white shadow-[0_6px_16px_rgba(33,87,255,0.25)] transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:bg-auth-muted disabled:shadow-none",disabled:b,onClick:()=>void D(),children:[b?(0,a.jsx)(p.A,{className:"h-4 w-4 animate-spin motion-reduce:animate-none","aria-hidden":!0}):null,b?"Schedulingâ¦":"Approve schedule"]}),Object.keys(f).length>0?(0,a.jsxs)("p",{className:"text-[0.8rem] font-semibold text-auth-muted",children:[Object.keys(f).length," time",1===Object.keys(f).length?"":"s"," adjusted"]}):null]})]})}function rX(e){var t,n,r,l;let{boardId:s,onBoardStateChanged:i,onOpenInBoard:c,onOpenCampaignManager:d,surfaceSwitch:u,onSavedAtChange:m}=e,{currentOrgId:p}=(0,x.x)(),h=ry(s),f=rv(s),g="ad-maker:campaign-studio:".concat(s,":run"),[b,y]=(0,o.useState)(""),v=(0,o.useRef)(""),[w,j]=(0,o.useState)(null),N=(0,o.useRef)(null),_=(0,o.useRef)(!1),k=(0,o.useCallback)(e=>{_.current=!0,N.current=e,j(e)},[]),[A,C]=(0,o.useState)(!1),[S,I]=(0,o.useState)(null),[T,M]=(0,o.useState)(null),[R,E]=(0,o.useState)(!1),[U,P]=(0,o.useState)({on:0,total:0}),B=(0,o.useRef)(null),D=(0,o.useCallback)(()=>E(!1),[]);(0,o.useEffect)(()=>{null==m||m(T)},[m,T]),(0,o.useEffect)(()=>{let e=ti(ry(s));v.current=e,y(e);let t=aj(rw(rv(s)));N.current=t,j(t);let n=!1;return(0,ta.oT)(s).then(e=>{if(!n&&e){if(!N.current){let t=aj(e.brief);t&&(N.current=t,j(t),I(e.updatedAt||null))}e.ask&&!v.current&&(v.current=e.ask,y(e.ask))}}).catch(()=>{}),()=>{n=!0}},[s]),(0,o.useEffect)(()=>{v.current=b;let e=window.setTimeout(()=>to(h,b),400);return()=>window.clearTimeout(e)},[b,h]),(0,o.useEffect)(()=>()=>to(h,v.current),[h]),(0,o.useEffect)(()=>{if(!_.current)return;let e=window.setTimeout(()=>{rj(f,w)},800),t=window.setTimeout(()=>{w&&(0,ta.Bj)(s,{brief:w,ask:v.current,updatedAt:new Date().toISOString()}).then(()=>M(new Date().toISOString())).catch(()=>{})},1500);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[s,w,f]),(0,o.useEffect)(()=>()=>{_.current&&rj(f,N.current)},[f]);let[z,O]=(0,o.useState)(null),F=(0,o.useCallback)(e=>{O(e)},[]),[L,q]=(0,o.useState)([]);(0,o.useEffect)(()=>{let e=!1;return(0,e2.B)({limit:100,offset:0}).then(t=>{e||q((Array.isArray(t.data)?t.data:[]).filter(e=>0!==e.isActive))}).catch(()=>{}),()=>{e=!0}},[]);let $=(0,o.useMemo)(()=>new Set(L.map(e=>aB(e.network))),[L]),[K,W]=(0,o.useState)(null),[J,G]=(0,o.useState)(!0),[H,Y]=(0,o.useState)(null),V=(0,o.useCallback)(e=>Y({pane:"content",message:e}),[]),X=(0,o.useRef)(-1),Q=(0,o.useCallback)(async e=>{var t;let n=await nT(s,{ensure:!1,runId:e});return W(n),(null==(t=n.run)?void 0:t.id)&&window.sessionStorage.setItem(g,n.run.id),n},[s,g]);(0,o.useEffect)(()=>{let e=!1;return G(!0),Q(window.sessionStorage.getItem(g)).catch(()=>{}).finally(()=>{e||G(!1)}),()=>{e=!0}},[Q,g]);let Z=null!=(n=null==K?void 0:K.run)?n:null,ee=(0,o.useMemo)(()=>(function(e){let t=az(az(null==e?void 0:e.metadata).studio);return 0===Object.keys(t).length?null:{brief:aj(t.brief),ask:aO(t.ask)}})(Z),[Z]),et=!!(Z&&ee),en=!!(Z&&!ee&&!aq(Z)),ea=et&&(null==Z?void 0:Z.status)!=="created"&&!aq(Z),er=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(ee&&!er.current&&(er.current=!0,!v.current&&ee.ask&&(v.current=ee.ask,y(ee.ask)),!N.current&&ee.brief)){var e;N.current=ee.brief,j(ee.brief),I(null!=(e=null==Z?void 0:Z.createdAt)?e:null)}},[null==Z?void 0:Z.createdAt,ee]),(0,o.useEffect)(()=>{let e=null==Z?void 0:Z.id,t=(null==Z?void 0:Z.status)||"";if(!e||!et||["created","complete","failed","cancelled"].includes(t))return;let n=new EventSource(nP(e,X.current)),a=t=>{try{let n=JSON.parse(t.data||"{}"),a=Number(n.last_event_index);Number.isFinite(a)&&(X.current=a),(Array.isArray(n.events)?n.events:[]).some(e=>{let t=e.payload&&"object"==typeof e.payload?e.payload:{},n=t.payload&&"object"==typeof t.payload?t.payload:{};return"draft_created"===e.type||"board_clutter_removed"===e.type||Array.isArray(n.board_items)||!!n.board_change})&&(null==i||i()),Q(e).catch(()=>{})}catch(e){}};return n.addEventListener("run",a),n.addEventListener("done",e=>{n.close(),a(e)}),n.addEventListener("error",()=>{}),()=>n.close()},[et,i,Q,null==Z?void 0:Z.id,null==Z?void 0:Z.status]),(0,o.useEffect)(()=>{let e=null==Z?void 0:Z.id;if(!e||!ea)return;let t=window.setInterval(()=>{Q(e).catch(()=>{})},5e3);return()=>window.clearInterval(t)},[Q,null==Z?void 0:Z.id,ea]);let[el,es]=(0,o.useState)(!1),[ei,eo]=(0,o.useState)(!1),[ec,ed]=(0,o.useState)(!1),eu=(0,o.useCallback)(async()=>
1{if(!ec){ed(!0),Y(null);try{var e;let t=await nR({boardId:s,source:{source_type:"studio_brief",name:"Campaign Studio campaign"}});v.current="",N.current=null,_.current=!1,er.current=!1,X.current=-1,y(""),j(null),W(t),to(h,""),rj(f,null),(null==(e=t.run)?void 0:e.id)?window.sessionStorage.setItem(g,t.run.id):window.sessionStorage.removeItem(g),I(null),M(null),C(!1),await (0,ta.Bj)(s,null).catch(()=>{})}catch(e){Y({pane:"content",message:e instanceof Error?e.message:"Could not start a new campaign"})}finally{ed(!1)}}},[h,s,f,ec,g]),em=(0,o.useMemo)(()=>(function(e){if(!e)return;let t={};if(e.includeBusinessDescription&&e.businessDescription.trim()&&(t.business_description=e.businessDescription.trim()),e.websiteContext&&(t.website_context=e.websiteContext),e.brandVoice&&(t.brand_voice=e.brandVoice),e.marketResearchSummary&&(t.market_research_summary=e.marketResearchSummary),e.personas&&e.personas.length>0&&(t.personas=e.personas),e.referenceAssets.length>0&&(t.reference_assets=e.referenceAssets),e.includeVisualPatterns){let n=e.visualPatterns.filter(e=>e.enabled);(n.length>0||e.visualPatternsSummary)&&(t.ad_visual_patterns={common_patterns:n.map(e=>{let{pattern:t,evidence:n,how_to_apply:a}=e;return{pattern:t,...n?{evidence:n}:{},...a?{how_to_apply:a}:{}}}),...e.visualPatternsSummary?{summary:e.visualPatternsSummary}:{}})}return Object.keys(t).length>0?t:void 0})(z),[z]),ep=(0,o.useCallback)(async()=>{let e=b.trim();if(e&&!el){es(!0),Y(null);try{let t=await ak({boardId:s,ask:e,organizationalUnitId:p,businessContext:em,connectedPlatforms:Array.from($)});_.current=!0,N.current=t,j(t),I(new Date().toISOString()),C(!1),(0,tR.hA)("campaign_manager",{action:"generate_brief"})}catch(e){Y({pane:"brief",message:e instanceof Error?e.message:"Could not generate the campaign brief"})}finally{es(!1)}}},[b,s,em,$,p,el]),eh=(0,o.useCallback)(async()=>{let e=N.current;if(e&&!ei){eo(!0),Y(null);try{let t=await aA({boardId:s,brief:e,organizationalUnitId:p,businessContext:em,clientTimezone:aD(),connectedSocialNetworks:Array.from($),outstandAccounts:L});_.current=!1,rj(f,null),to(h,""),(0,ta.Bj)(s,null).catch(()=>{}),t.runId&&window.sessionStorage.setItem(g,t.runId),X.current=-1,er.current=!0,await Q(t.runId||null).catch(()=>{})}catch(e){Y({pane:"brief",message:e instanceof Error?e.message:"Could not start the campaign"})}finally{eo(!1)}}},[L,h,s,f,em,$,p,ei,Q,g]),ef=(0,o.useMemo)(()=>et&&K?K.tasks.filter(e=>"content_creator"===e.agentType):[],[et,K]),eg=(0,o.useMemo)(()=>{var e;return et&&K&&null!=(e=K.waves.find(e=>e.waveKey.startsWith("scheduling_proposal")&&"awaiting_approval"===e.status))?e:null},[et,K]),ex=(0,o.useMemo)(()=>K&&eg?K.tasks.filter(e=>e.waveId===eg.id&&"schedule_planner"===e.agentType):[],[eg,K]),eb=(0,o.useRef)(null),ey=ef.length>0&&ef.every(e=>"completed"===e.status),ev=ef.filter(e=>"completed"===e.status).map(e=>"".concat(e.id,":").concat(e.completedAt||"")).sort().join("|"),ew=(0,o.useRef)("");(0,o.useEffect)(()=>{ev&&ew.current!==ev&&(ew.current=ev,null==i||i())},[ev,i]);let ej=!eg||ex.filter(e=>"cancelled"!==e.status).length<ef.length;(0,o.useEffect)(()=>{let e=null==Z?void 0:Z.id;if(!e||!et||!ej||!ey)return;let t="".concat(e,":").concat(ex.length,":").concat(ef.length);eb.current!==t&&(eb.current=t,aS({boardId:s,runId:e}).then(()=>Q(e)).catch(e=>{eb.current=null,Y({pane:"content",message:e instanceof Error?e.message:"Could not prepare the campaign schedule"})}))},[ey,s,et,Q,null==Z?void 0:Z.id,ej,ex.length,ef.length]);let eN=et&&(ef.length>0||ea),e_=et&&(null==Z?void 0:Z.status)==="complete",ek=Array.isArray(null==Z||null==(t=Z.outputs)?void 0:t.scheduled_posts)?Z.outputs.scheduled_posts.length:0,eA=en?"A Campaign Manager run is active on this board. You can start a studio campaign once it finishes.":void 0,eC=ea?"A studio campaign is already running on this board.":null!=eA?eA:null,eS=function(e){var t;if(e.executing)return{kind:"starting"};let n=null!=(t=e.blockedReason)?t:0===e.platformCount?"Add at least one platform first.":null;return e.runFinished?{kind:"regenerate",generatedAt:e.generatedAt,disabledReason:n}:{kind:"generate",disabledReason:n}}({platformCount:null!=(r=null==w?void 0:w.platform_mix.length)?r:0,executing:ei,blockedReason:eC,runFinished:et&&aq(Z),generatedAt:function(e){let t=null,n=-1/0;for(let a of e){if(!a)continue;let e=Date.parse(a);Number.isFinite(e)&&e>n&&(n=e,t=a)}return t}(ef.map(e=>e.completedAt))}),eI=!w||A,eT=aV(S);return(0,a.jsxs)("div",{className:"absolute inset-0 overflow-y-auto bg-cloud-slate lg:grid lg:grid-cols-[480px_minmax(0,1fr)] lg:overflow-hidden",onPointerDown:e=>e.stopPropagation(),children:[(0,a.jsxs)("section",{"aria-labelledby":"studio-brief-heading",className:"flex flex-col bg-white lg:min-h-0 lg:border-r lg:border-auth-hairline",children:[(0,a.jsxs)("div",{className:"flex flex-none items-center justify-between gap-3 border-b border-auth-hairline px-7 pb-4 pt-5",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h2",{id:"studio-brief-heading",className:"text-[1.15rem] font-extrabold leading-[1.2] text-midnight-logic",children:"Campaign brief"}),(0,a.jsx)("p",{className:"mt-1 truncate text-[0.8rem] font-medium text-auth-muted",children:w?(0,a.jsxs)(a.Fragment,{children:[eT?"Drafted ".concat(eT," \xb7 "):"",U.total," source",1===U.total?"":"s",eI?null:(0,a.jsxs)(a.Fragment,{children:[" \xb7 ",(0,a.jsx)("button",{type:"button",className:"font-bold text-signal-blue underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue disabled:cursor-not-allowed disabled:text-auth-muted",disabled:ei||ea,onClick:()=>C(!0),children:"Redraft"})]})]}):"Start by describing what you want to make"})]}),(0,a.jsxs)("button",{ref:B,type:"button","aria-haspopup":"dialog","aria-expanded":R,"aria-controls":ru,onClick:()=>E(!0),className:"inline-flex h-10 flex-none items-center gap-2 whitespace-nowrap rounded-xl border-[1.5px] border-control-border bg-auth-field px-3 text-[0.8rem] font-bold text-midnight-logic transition-colors hover:bg-auth-field-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",children:[(0,a.jsx)(ah.A,{className:"h-4 w-4","aria-hidden":!0}),"Sources"]})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-10 px-7 pb-3 pt-7 lg:min-h-0 lg:flex-1 lg:overflow-y-auto",children:[(null==H?void 0:H.pane)==="brief"?(0,a.jsx)(r$,{message:H.message,onDismiss:()=>Y(null)}):null,en?(0,a.jsx)(rK,{action:d?(0,a.jsx)("button",{type:"button",onClick:d,className:"inline-flex min-h-[40px] items-center rounded-xl border-[1.5px] border-control-border bg-white px-3.5 text-[0.82rem] font-bold text-midnight-logic hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue",children:"Open Campaign Manager"}):void 0,children:"A Campaign Manager run is active on this board."}):null,eI?(0,a.jsx)(ay,{value:b,onChange:y,onSubmit:()=>void ep(),loading:el,disabled:en||ei,disabledReason:eA}):null,w?(0,a.jsx)(rl,{brief:w,onChange:k,connectedPlatforms:$,disabled:en||ea||ei}):null]}),w?(0,a.jsx)(rd,{state:eS,onGenerate:()=>void eh()}):null]}),(0,a.jsx)(rJ,{loading:J&&!K,hasBrief:!!w,showGrid:eN,tasks:ef,boardId:s,runId:null!=(l=null==Z?void 0:Z.id)?l:null,surfaceSwitch:u,onOpenBoard:c?()=>c():void 0,completion:e_?{scheduledPostCount:ek,resetting:ec,onStartNew:()=>void eu()}:null,error:(null==H?void 0:H.pane)==="content"?H.message:null,onError:V,onDismissError:()=>Y(null),schedule:eg&&Z?(0,a.jsx)(rV,{wave:eg,scheduleTasks:ex,contentTasks:ef,boardId:s,runId:Z.id,accounts:L,onApproved:()=>{Q(Z.id).catch(()=>{})},onError:V}):null,drawer:(0,a.jsx)(rm,{open:R,onClose:D,subtitle:0===U.total?"No sources yet":"".concat(U.on," of ").concat(U.total," source").concat(1===U.total?"":"s"," on"),returnFocusRef:B,children:(0,a.jsx)(rI,{onSnapshotChange:F,onSourcesChange:P})})})]})}function rQ(e){let{value:t,onChange:n,boardItemCount:r}=e;return(0,a.jsx)("div",{role:"group","aria-label":"View",className:"grid shrink-0 grid-cols-2 rounded-xl bg-auth-
1hairline p-[3px]",children:[{surface:"studio",label:"Studio"},{surface:"board",label:"Board \xb7 ".concat(r)}].map(e=>{let{surface:r,label:l}=e,s=t===r;return(0,a.jsx)("button",{type:"button","aria-pressed":s,onClick:()=>n(r),className:(0,Y.cn)("min-h-[38px] min-w-[84px] rounded-[9px] px-3 text-[0.82rem] text-midnight-logic transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",s?"bg-white font-bold shadow-[0_1px_3px_rgba(13,14,29,0.1)]":"font-semibold hover:bg-white/60"),children:l},r)})})}var rZ=n(84815),r0=n(76973),r1=n(7613);let r2=[{value:"product",label:"Product"},{value:"visual",label:"Visual / image"},{value:"style_reference",label:"Style reference"},{value:"document",label:"Guidelines / document"},{value:"other",label:"Other"}];function r5(e){var t,n,r,l,s,i;let{pendingUploads:c,saving:u=!1,onSubmit:m,onCancelAll:p,onUploadFiles:h}=e,f=(0,o.useRef)(null),[g,x]=(0,o.useState)(0),[b,v]=(0,o.useState)(null);if((0,o.useEffect)(()=>{v(e=>{var t;return 0===c.length?null:null!=e?e:{name:(t=c[0]).file.name.replace(/\.[^.]+$/,"").replace(/[_-]+/g," ").trim()||t.file.name,description:"",role:"product"}}),x(e=>Math.min(e,c.length))},[c]),0===c.length)return null;let w=null!=(t=c[g])?t:null,j=!w,N=c.length+1,_=null!=(n=null==b?void 0:b.name.trim())?n:"",k=null!=(r=null==b?void 0:b.description.trim())?r:"",A=!!_&&!!k&&!u,C=e=>{v(t=>t?{...t,...e}:t)};return(0,a.jsx)(eQ.lG,{open:!0,onOpenChange:e=>{e||u||p()},children:(0,a.jsxs)(eQ.Cf,{className:"max-w-4xl p-0",children:[(0,a.jsx)(eQ.c7,{children:(0,a.jsx)(eQ.L3,{className:"sr-only",children:"Add asset"})}),(0,a.jsxs)("div",{className:"grid min-h-[560px] overflow-hidden rounded-lg md:grid-cols-2",children:[(0,a.jsxs)("div",{className:"relative flex min-h-[320px] items-center justify-center bg-charcoal-50 p-6",children:[(0,a.jsx)("input",{ref:f,type:"file",accept:"".concat(ta.oL,",.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.csv,.txt"),multiple:!0,className:"sr-only",onChange:e=>{var t=e.currentTarget.files;let n=Array.from(null!=t?t:[]);n.length>0&&(h(n),x(c.length)),e.currentTarget.value=""}}),j?(0,a.jsxs)("button",{type:"button",disabled:u,className:"text-charcoal-700 flex h-full min-h-[360px] w-full flex-col items-center justify-center gap-3 rounded-md border border-dashed border-charcoal-300 bg-white transition hover:border-charcoal-500 hover:bg-charcoal-50",onClick:()=>{var e;return null==(e=f.current)?void 0:e.click()},children:[(0,a.jsx)("span",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-charcoal-100",children:(0,a.jsx)(d.A,{className:"h-6 w-6"})}),(0,a.jsx)("span",{className:"text-sm font-semibold",children:"Add media to asset"})]}):w.file.type.startsWith("image/")||w.previewUrl.startsWith("data:image/")?(0,a.jsx)(a.Fragment,{children:(0,a.jsx)("img",{src:w.previewUrl,alt:w.file.name,className:"max-h-[500px] w-full rounded-md object-contain"})}):(0,a.jsxs)("div",{className:"flex h-full min-h-[360px] w-full flex-col items-center justify-center rounded-md border border-charcoal-200 bg-white p-6 text-center",children:[(0,a.jsx)("p",{className:"text-charcoal-900 max-w-full truncate text-sm font-semibold",children:w.file.name}),(0,a.jsx)("p",{className:"mt-2 text-xs text-charcoal-500",children:w.file.type||"Document"})]}),N>1&&(0,a.jsxs)("div",{className:"absolute inset-x-4 bottom-4 flex items-center justify-between",children:[(0,a.jsx)(y.$,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 rounded-full bg-white/90 shadow-soft",disabled:0===g,onClick:()=>x(e=>Math.max(0,e-1)),"aria-label":"Previous media",children:(0,a.jsx)(eD.A,{className:"h-4 w-4"})}),(0,a.jsxs)("div",{className:"text-charcoal-700 rounded-full bg-white/90 px-3 py-1 text-xs font-semibold shadow-soft",children:[Math.min(g+1,N)," / ",N]}),(0,a.jsx)(y.$,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 rounded-full bg-white/90 shadow-soft",disabled:g>=N-1,onClick:()=>x(e=>Math.min(N-1,e+1)),"aria-label":"Next media",children:(0,a.jsx)(ez.A,{className:"h-4 w-4"})})]})]}),(0,a.jsxs)("div",{className:"flex flex-col border-t border-charcoal-200 bg-white p-6 md:border-l md:border-t-0",children:[(0,a.jsxs)("div",{className:"mb-6",children:[(0,a.jsx)("h2",{className:"text-charcoal-900 text-xl font-semibold",children:"Asset details"}),(0,a.jsx)("p",{className:"mt-1 text-sm text-charcoal-600",children:"The AI uses this name and description as context when generating ads, so the more detail you add, the more accurate the results."})]}),(0,a.jsxs)("div",{className:"space-y-5",children:[(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsxs)(r0.J,{htmlFor:"asset-role",children:["Asset type ",(0,a.jsx)("span",{className:"text-destructive",children:"*"})]}),(0,a.jsxs)(r1.l6,{value:null!=(l=null==b?void 0:b.role)?l:"product",disabled:u,onValueChange:e=>C({role:e}),children:[(0,a.jsx)(r1.bq,{id:"asset-role",children:(0,a.jsx)(r1.yv,{})}),(0,a.jsx)(r1.gC,{children:r2.map(e=>(0,a.jsx)(r1.eb,{value:e.value,children:e.label},e.value))})]})]}),(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsxs)(r0.J,{htmlFor:"asset-name",children:["Name ",(0,a.jsx)("span",{className:"text-destructive",children:"*"})]}),(0,a.jsx)(tv.p,{id:"asset-name",value:null!=(s=null==b?void 0:b.name)?s:"",disabled:u,placeholder:"e.g. Linen summer shirt",onChange:e=>C({name:e.target.value})})]}),(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsxs)(r0.J,{htmlFor:"asset-description",children:["Description ",(0,a.jsx)("span",{className:"text-destructive",children:"*"})]}),(0,a.jsx)("p",{className:"text-xs text-charcoal-500",children:"Required. Tells the AI what this asset is for."}),(0,a.jsx)(eZ.T,{id:"asset-description",value:null!=(i=null==b?void 0:b.description)?i:"",disabled:u,placeholder:"Describe what this is â e.g. 'Beige short-sleeve linen shirt, relaxed fit, for our summer collection'.",onChange:e=>C({description:e.target.value}),className:"min-h-40"}),(0,a.jsx)("p",{className:"text-xs text-charcoal-500",children:"Required â this tells the AI what the asset is so it can place it correctly in generated ads."})]})]}),(0,a.jsxs)(eQ.Es,{className:"mt-auto pt-6",children:[(0,a.jsx)(y.$,{type:"button",variant:"ghost",disabled:u,onClick:p,children:"Cancel"}),(0,a.jsx)(y.$,{type:"button",disabled:!A,onClick:()=>{var e;let t=null!=(e=c[0])?e:null;A&&b&&t&&m({name:_,description:k,role:b.role,productView:null,assetGroupId:null,newGroupName:null,newGroupDescription:null,width:t.width,height:t.height,metadata:{originalFileName:t.file.name,mediaCount:c.length}},c)},children:u?"Saving...":"Save asset"})]})]})]})]})})}var r4=n(44232),r3=n(12499),r8=n(52576),r6=n(1294);function r7(e){return e.map(e=>({...e}))}function r9(e,t){if(e.length!==t.length)return!1;let n=new Map(t.map(e=>[e.id,e]));for(let t of e){let e=n.get(t.id);if(!e||t.kind!==e.kind||t.x!==e.x||t.y!==e.y||t.width!==e.width||t.height!==e.height||t.fileName!==e.fileName||"text"===t.kind&&"text"===e.kind&&t.text!==e.text)return!1}return!0}var le=n(19671),lt=n(43709),ln=n(2469);function la(e,t,n){if(!e)return!1;let a=(null!=t?t:"").toLowerCase(),r=(null!=n?n:"").toLowerCase();return!!(a.startsWith("image/")||"image/svg+xml"===a||r.endsWith(".svg"))||/\.(png|jpe?g|gif|webp|avif)(\?|$)/i.test(e)||/\.(png|jpe?g|gif|webp|avif)$/i.test(r)}function lr(e){var t,n,a;if(!e)return null;let r=null!=(a=null!=(n=e.url)?n:null==(t=e.media[0])?void 0:t.sourceUrl)?a:null;if(la(r,e.mimeType,e.fileName))return r;for(let t of e.media)if(la(t.sourceUrl,t.mimeType,t.fileName))return t.sourceUrl;return null}function ll(e){let{urls:t,loading:n=!1,className:r=""}=e,l=Array.from({length:6},(e,n)=>{var a;return null!=(a=t[n])?a:null}),s=t.length>0;return(0,a.jsx)("div",{className:"relative h-[180px] w-full overflow-hidden bg-ad-maker-field ".concat(r),"aria-hidden":!0,
1children:n?(0,a.jsx)("div",{className:"grid h-full w-full grid-cols-3 grid-rows-2 gap-2 p-3.5",children:l.map((e,t)=>(0,a.jsx)("div",{className:"animate-pulse rounded-lg bg-auth-field motion-reduce:animate-none"},t))}):s?(0,a.jsx)("div",{className:"grid h-full w-full grid-cols-3 grid-rows-2 gap-2 p-3.5",children:l.map((e,t)=>e?(0,a.jsx)("div",{className:"relative overflow-hidden rounded-lg bg-auth-field",children:(0,a.jsx)("img",{src:e,alt:"",className:"h-full w-full object-cover",loading:"lazy",draggable:!1})},"".concat(e,"-").concat(t)):(0,a.jsx)("div",{className:"rounded-lg bg-auth-field/60"},"empty-".concat(t)))}):(0,a.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[(0,a.jsx)("span",{className:"grid h-11 w-11 place-items-center rounded-[13px] bg-auth-field text-anchor-blue",children:(0,a.jsx)(et.A,{className:"h-[18px] w-[18px]",strokeWidth:2})}),(0,a.jsx)("span",{className:"text-[0.66rem] font-extrabold uppercase tracking-[0.1em] text-auth-muted",children:"Empty board"})]})})}function ls(e){let{board:t,href:n,onOpen:r,previewUrls:s,previewLoading:i=!1,onBoardsChanged:c,formatDate:d}=e,[,u]=(0,f.n_)(U),[,m]=(0,f.n_)(P),[p,h]=(0,o.useState)(!1),[g,x]=(0,o.useState)(t.name),[b,v]=(0,o.useState)(null),[w,j]=(0,o.useState)(!1),[N,_]=(0,o.useState)(!1),k=async()=>{let e=g.trim();if(!e)return void v("Board name cannot be empty.");if(e===t.name)return void h(!1);j(!0),v(null);try{let n=await u({id:t.id,name:e});if(n.error)throw Error(n.error.message);h(!1),c()}catch(e){v(e instanceof Error?e.message:"Could not rename board")}finally{j(!1)}},A=async()=>{if(window.confirm('Delete "'.concat(t.name,'"? This cannot be undone.'))){_(!0),v(null);try{let e=await m({id:t.id});if(e.error)throw Error(e.error.message);c()}catch(e){v(e instanceof Error?e.message:"Could not delete board")}finally{_(!1)}}},C=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(ll,{urls:s,loading:i,className:"border-b border-auth-hairline"}),(0,a.jsxs)("div",{className:"flex items-center gap-3 px-[18px] py-4",children:[(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)("p",{className:"truncate text-[0.92rem] font-extrabold text-midnight-logic",children:t.name}),(0,a.jsxs)("p",{className:"mt-0.5 truncate text-[0.74rem] font-semibold text-auth-muted",children:["Updated ",d(t.updatedAt)]}),b?(0,a.jsx)("p",{className:"mt-1.5 text-[0.72rem] font-semibold text-auth-error",children:b}):null]}),(0,a.jsx)(nl.A,{className:"h-4 w-4 shrink-0 text-anchor-blue",strokeWidth:2.5,"aria-hidden":!0})]})]});return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"group relative overflow-hidden rounded-[18px] border border-auth-hairline bg-white shadow-[0_8px_24px_rgba(13,14,29,0.04)] transition-[border-color,box-shadow] duration-150 hover:border-signal-blue hover:shadow-[0_12px_32px_rgba(13,14,29,0.1)]",children:[r?(0,a.jsx)("button",{type:"button",className:"block w-full border-0 bg-transparent p-0 text-left",onClick:e=>{e.preventDefault(),e.stopPropagation(),null==r||r()},"aria-label":"Open ".concat(t.name),children:C}):n?(0,a.jsx)(l(),{href:n,className:"block w-full text-left",children:C}):null,(0,a.jsxs)(rE.rI,{children:[(0,a.jsx)(rE.ty,{asChild:!0,children:(0,a.jsx)(y.$,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2 top-2 h-8 w-8 rounded-lg bg-white/90 text-auth-ink-soft opacity-100 shadow-sm backdrop-blur-sm transition hover:bg-white hover:text-midnight-logic sm:opacity-0 sm:group-hover:opacity-100 sm:data-[state=open]:opacity-100",disabled:w||N,onClick:e=>e.stopPropagation(),"aria-label":"Board actions for ".concat(t.name),children:(0,a.jsx)(ln.A,{className:"h-4 w-4"})})}),(0,a.jsxs)(rE.SQ,{align:"end",className:"w-40",children:[(0,a.jsxs)(rE._2,{onClick:e=>{e.stopPropagation(),v(null),x(t.name),h(!0)},children:[(0,a.jsx)(eR.A,{className:"mr-2 h-4 w-4"}),"Rename"]}),(0,a.jsxs)(rE._2,{className:"text-red-600 focus:bg-red-50 focus:text-red-700",disabled:N,onClick:e=>{e.stopPropagation(),A()},children:[(0,a.jsx)(eU.A,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]}),(0,a.jsx)(eQ.lG,{open:p,onOpenChange:h,children:(0,a.jsxs)(eQ.Cf,{className:"sm:max-w-md",onClick:e=>e.stopPropagation(),children:[(0,a.jsx)(eQ.c7,{children:(0,a.jsx)(eQ.L3,{children:"Rename board"})}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(r0.J,{htmlFor:"board-rename-".concat(t.id),children:"Name"}),(0,a.jsx)(tv.p,{id:"board-rename-".concat(t.id),value:g,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k()},disabled:w,autoFocus:!0}),b?(0,a.jsx)("p",{className:"text-xs text-red-600",children:b}):null]}),(0,a.jsxs)(eQ.Es,{children:[(0,a.jsx)(y.$,{type:"button",variant:"ghost",onClick:()=>h(!1),disabled:w,children:"Cancel"}),(0,a.jsx)(y.$,{type:"button",onClick:()=>void k(),disabled:w,children:w?"Savingâ¦":"Save"})]})]})})]})}var li=n(78052);function lo(){return(0,a.jsxs)("div",{role:"status","aria-busy":"true",className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[(0,a.jsx)("span",{className:"sr-only",children:"Loading your ad boardsâ¦"}),Array.from({length:3},(e,t)=>(0,a.jsx)(lu,{className:2===t?"hidden lg:block":void 0},t))]})}function lc(e){let{className:t}=e;return(0,a.jsx)(li.E,{"aria-hidden":"true",className:(0,Y.cn)("block bg-auth-field motion-reduce:animate-none",t)})}function ld(e){let{line:t,bar:n,width:r}=e;return(0,a.jsx)("span",{className:(0,Y.cn)("flex items-center",t),children:(0,a.jsx)(lc,{className:(0,Y.cn)("rounded-[4px]",n,r)})})}function lu(e){let{className:t}=e;return(0,a.jsxs)("div",{className:(0,Y.cn)("overflow-hidden rounded-[18px] border border-auth-hairline bg-white shadow-[0_8px_24px_rgba(13,14,29,0.04)]",t),children:[(0,a.jsx)("div",{className:"grid h-[180px] w-full grid-cols-3 grid-rows-2 gap-2 border-b border-auth-hairline bg-ad-maker-field p-3.5",children:Array.from({length:6},(e,t)=>t<3?(0,a.jsx)(lc,{className:"h-full w-full rounded-lg"}
1,t):(0,a.jsx)("div",{"aria-hidden":!0,className:"rounded-lg bg-auth-field/60"},t))}),(0,a.jsxs)("div",{className:"flex items-center gap-3 px-[18px] py-4",children:[(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsx)(ld,{line:"h-[1.38rem]",bar:"h-[13px]",width:"w-[68%]"}),(0,a.jsx)("span",{className:"mt-0.5 block",children:(0,a.jsx)(ld,{line:"h-[1.11rem]",bar:"h-[10px]",width:"w-[46%]"})})]}),(0,a.jsx)(nl.A,{className:"h-4 w-4 shrink-0 text-anchor-blue",strokeWidth:2.5,"aria-hidden":!0})]})]})}var lm=n(38853);let lp=["logo","logo-concept","colour-palette","font","signature-device","motif","application","brand-book"],lh=new Set(["mark","icon","monogram","social-avatar","favicon-16","favicon-32","favicon-48","favicon-ico","apple-touch-180","pwa-192","pwa-512","app-store-1024"]);function lf(e){let t=e.filter(e=>{var t;let n=null!=(t=e.metadata)?t:{};return"brand-studio-library"===n.source||"brand-studio-library-import"===n.source||"brand-studio-default-logo"===n.source||!!n.brandStudioAssetKind||!!n.brandKitOrganizationId}),n=[],a=e=>{let a=t.find(t=>e(t));a&&!n.some(e=>e.id===a.id)&&n.push(a)},r=(e,a)=>{for(let r of t){if(n.length>=14)break;if(e(r)&&!n.some(e=>e.id===r.id)&&(n.push(r),n.filter(e).length>=a))break}};return a(e=>"logo"===e.metadata.brandStudioAssetKind&&"primary"===e.metadata.brandStudioLogoRole),a(e=>"colour-palette"===e.metadata.brandStudioAssetKind),a(e=>"font"===e.metadata.brandStudioAssetKind&&"display"===e.metadata.fontRole),a(e=>"font"===e.metadata.brandStudioAssetKind&&"body"===e.metadata.fontRole),a(e=>"signature-device"===e.metadata.brandStudioAssetKind),r(e=>"motif"===e.metadata.brandStudioAssetKind,2),r(e=>"application"===e.metadata.brandStudioAssetKind,2),a(e=>"logo-concept"===e.metadata.brandStudioAssetKind),a(e=>"brand-book"===e.metadata.brandStudioAssetKind),n.sort((e,t)=>{let n=String(e.metadata.brandStudioAssetKind||""),a=String(t.metadata.brandStudioAssetKind||""),r=lp.indexOf(n),l=lp.indexOf(a);return(r<0?99:r)-(l<0?99:l)})}let lg=["Summer sale campaign","Product launch ads","Social media creatives","Holiday promotion"];function lx(e){var t;let{open:n,onOpenChange:r,brandingOffer:l,creating:s,createError:i,defaultName:c,onCreate:d}=e,[u,m]=(0,o.useState)("focus"),[h,f]=(0,o.useState)(null!=c?c:""),[g,x]=(0,o.useState)(!0),b=(0,o.useRef)(null),v=!!(null==l?void 0:l.available),w=!!(null==l?void 0:l.loading),j=(null==l||null==(t=l.brandName)?void 0:t.trim())||"your Brand Studio kit",N=v&&!w,_=h.trim(),[k,A]=(0,o.useState)(n);n!==k&&(A(n),n&&(m("focus"),f(null!=c?c:""),x(!0)));let C=async()=>{_&&!s&&await d({name:_,importBranding:!!N&&g})},S=()=>{if(_&&!s){if(N)return void m("branding");C()}},I="focus"===u;return(0,a.jsx)(eQ.lG,{open:n,onOpenChange:e=>{s||r(e)},children:(0,a.jsxs)(eQ.Cf,{overlayClassName:"bg-midnight-logic/50",hideCloseButton:!0,onOpenAutoFocus:e=>{b.current&&(e.preventDefault(),b.current.focus())},className:"max-w-[560px] gap-0 overflow-hidden rounded-gift-modal border-0 bg-white p-0 shadow-[0_24px_70px_rgba(13,14,29,0.35)] backdrop-blur-none",children:[(0,a.jsxs)("div",{className:"flex items-start gap-4 border-b border-auth-hairline px-[30px] pb-[22px] pt-[26px]",children:[(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[N&&(0,a.jsxs)("div",{className:"mb-2.5 flex items-center gap-2.5",children:[(0,a.jsxs)("span",{className:"rounded-full bg-auth-field px-3 py-[5px] text-[0.62rem] font-extrabold uppercase tracking-[0.1em] text-anchor-blue",children:["Step ",I?1:2," of 2"]}),(0,a.jsxs)("div",{"aria-hidden":"true",className:"flex gap-[5px]",children:[(0,a.jsx)("span",{className:"h-1 w-[18px] rounded-full bg-signal-blue"}),(0,a.jsx)("span",{className:I?"h-1 w-[18px] rounded-full bg-auth-field-border":"h-1 w-[18px] rounded-full bg-signal-blue"})]})]}),(0,a.jsx)(eQ.L3,{className:"mb-1.5 text-[1.35rem] font-extrabold leading-tight tracking-[-0.02em] text-charcoal",children:I?"New board":"Brand assets"}),(0,a.jsx)(eQ.rr,{className:"max-w-[420px] text-[0.9rem] font-medium leading-[1.6] text-auth-ink-soft",children:I?"Each board is one campaign or project â keep them separate so your work stays organised.":"Pull in ".concat(j," so generated ads stay on-brand.")})]}),(0,a.jsx)("button",{type:"button",onClick:()=>r(!1),disabled:s,"aria-label":"Close",className:"-mr-1.5 -mt-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-[10px] text-auth-muted transition-colors hover:bg-cloud-slate hover:text-midnight-logic focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-40",children:(0,a.jsx)(eG.A,{"aria-hidden":"true",className:"h-4 w-4"})})]}),(0,a.jsxs)("div",{className:"px-[30px] pb-[26px] pt-6",children:[I?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("label",{htmlFor:"board-focus",className:"mb-2 block text-[0.78rem] font-bold text-midnight-logic",children:"What's this board for?"}),(0,a.jsxs)("div",{className:"relative mb-3.5",children:[(0,a.jsx)("input",{id:"board-focus",ref:b,type:"text",value:h,maxLength:60,onChange:e=>f(e.target.value),placeholder:"e.g. Summer sale campaign",disabled:s,onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),S())},className:"h-12 w-full rounded-auth-field border border-auth-input-border bg-white pl-4 pr-[68px] text-[0.94rem] font-medium text-midnight-logic outline-none transition-[border-color,box-shadow] duration-150 placeholder:text-auth-placeholder focus:border-signal-blue focus:shadow-auth-ring disabled:bg-paused-surface disabled:text-auth-muted"}),h.length>0&&(0,a.jsxs)("span",{"aria-hidden":"true",className:"pointer-events-none absolute right-3.5 top-1/2 -translate-y-1/2 text-[0.72rem] font-semibold tabular-nums text-auth-muted",children:[h.length,"/",60]})]}),(0,a.jsx)("p",{className:"mb-2.5 text-[0.74rem] font-semibold text-auth-muted",children:"Or start from a suggestion"}),(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:lg.map(e=>{let t=_===e;return(0,a.jsx)("button",{type:"button",disabled:s,"aria-pressed":t,onClick:()=>f(e),className:"rounded-full border px-3.5 py-2 text-[0.82rem] font-bold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ".concat(t?"border-signal-blue bg-auth-field text-anchor-blue":"border-control-border bg-white text-auth-ink-soft hover:border-signal-blue hover:bg-auth-field hover:text-anchor-blue"),children:e},e)})})]}):(0,a.jsxs)("div",{className:"flex flex-col gap-2.5",children:[(0,a.jsx)(lb,{checked:g,disabled:s,onSelect:()=>x(!0),title:"Yes, add branding",detail:"Logo, colours, fonts and brand book, on the board."}),(0,a.jsx)(lb,{checked:!g,disabled:s,onSelect:()=>
1x(!1),title:"No, start blank",detail:"Add your own assets later."})]}),i?(0,a.jsx)("p",{role:"alert",className:"mt-4 rounded-auth-field border border-auth-error/30 bg-auth-error-bg px-3.5 py-2.5 text-[0.82rem] font-semibold text-auth-error",children:i}):null]}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3 border-t border-auth-hairline bg-paused-surface px-[30px] pb-[22px] pt-[18px]",children:[(0,a.jsx)("p",{className:"hidden text-[0.78rem] font-medium text-auth-muted sm:block",children:I?N?"Next: add your brand assets":"You can rename this board at any time":"Last step â your board opens next"}),(0,a.jsxs)("div",{className:"flex items-center gap-2.5 max-sm:w-full",children:[(0,a.jsx)(y.$,{type:"button",variant:"ghost",className:"h-11 max-sm:flex-1",disabled:s,onClick:()=>I?r(!1):m("focus"),children:I?"Cancel":"Back"}),(0,a.jsxs)(y.$,{type:"button",className:"h-11 max-sm:flex-1",disabled:s||I&&(!_||w),onClick:()=>I?S():void C(),children:[s||I&&w?(0,a.jsx)(p.A,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,s?"Creatingâ¦":I&&w?"Loadingâ¦":I&&N?"Continue":"Create board",I&&N&&!s&&!w?(0,a.jsx)(ez.A,{"aria-hidden":"true",className:"ml-1.5 h-4 w-4"}):null]})]})]})]})})}function lb(e){let{checked:t,disabled:n,onSelect:r,title:l,detail:s}=e;return(0,a.jsxs)("label",{className:"flex cursor-pointer items-start gap-3 rounded-auth-field border px-4 py-3.5 transition-colors ".concat(t?"border-signal-blue bg-auth-field":"border-control-border bg-white hover:border-signal-blue"," ").concat(n?"pointer-events-none opacity-60":""),children:[(0,a.jsx)("input",{type:"radio",name:"import-branding",className:"mt-[3px] h-4 w-4 shrink-0 accent-signal-blue",checked:t,disabled:n,onChange:r}),(0,a.jsxs)("span",{className:"min-w-0",children:[(0,a.jsx)("span",{className:"block text-[0.88rem] font-extrabold text-midnight-logic",children:l}),(0,a.jsx)("span",{className:"mt-0.5 block text-[0.78rem] font-medium leading-[1.5] text-auth-ink-soft",children:s})]})]})}var ly=n(65702),lv=n(10386);function lw(e){let{onAddPhoto:t}=e;return(0,a.jsx)("div",{className:"pointer-events-none absolute left-1/2 top-1/2 z-20 w-[min(92%,34rem)] -translate-x-1/2 -translate-y-1/2",children:(0,a.jsxs)("section",{className:"rounded-2xl border-2 border-dashed border-signal-blue/40 bg-white/95 p-6 shadow-medium backdrop-blur",children:[(0,a.jsxs)("div",{className:"text-center",children:[(0,a.jsx)("div",{className:"mx-auto mb-4 inline-flex items-center justify-center rounded-2xl border border-charcoal-200 bg-signal-blue/10 p-3",children:(0,a.jsx)(ly.A,{className:"h-7 w-7 text-signal-blue",strokeWidth:2.5})}),(0,a.jsx)("h2",{className:"text-lg font-bold text-charcoal",children:"Drag images onto the board"}),(0,a.jsx)("p",{className:"mt-1 text-sm text-charcoal-600",children:"Chat only uses logos and product photos that are on this canvas â not files sitting in your library alone."})]}),(0,a.jsxs)("div",{className:"mt-5 grid gap-3 text-left sm:grid-cols-3",children:[(0,a.jsx)(lj,{n:1,icon:(0,a.jsx)(ly.A,{className:"h-4 w-4 text-signal-blue",strokeWidth:2.5}),title:"Drop on the canvas",body:"Drag logo and product image files from your computer onto this white area."}),(0,a.jsx)(lj,{n:2,icon:(0,a.jsx)(lv.A,{className:"h-4 w-4 text-signal-blue",strokeWidth:2.5}),title:"Or use the library",body:"Paperclip â pick assets â Add to board puts them here on the canvas."}),(0,a.jsx)(lj,{n:3,icon:(0,a.jsx)(e$.A,{className:"h-4 w-4 text-signal-blue",strokeWidth:2.5}),title:"Then describe your ad",body:"Once images are on the board, chat can use them in your ad."})]}),(0,a.jsx)("div",{className:"pointer-events-auto mt-5 flex flex-wrap justify-center gap-2",children:(0,a.jsxs)(y.$,{type:"button",onClick:t,variant:"outline",className:"gap-2",children:[(0,a.jsx)(lv.A,{className:"h-4 w-4"}),"Open asset library"]})})]})})}function lj(e){let{n:t,icon:n,title:r,body:l}=e;return(0,a.jsxs)("div",{className:"rounded-xl border border-charcoal-200 bg-charcoal-50 p-3",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-center gap-2",children:[(0,a.jsx)("span",{className:"flex h-5 w-5 items-center justify-center rounded-full border border-charcoal-200 bg-white text-[10px] font-bold text-charcoal",children:t}),n]}),(0,a.jsx)("div",{className:"text-xs font-bold text-charcoal",children:r}),(0,a.jsx)("div",{className:"mt-1 text-[11px] font-medium leading-snug text-charcoal-600",children:l})]})}let lN=[],l_=new Map,lk="/dashboard/tools/ad-maker",lA="/dashboard/launch-wizard",lC=(0,b.Bb)("ad-maker"),lS="inline-flex min-h-[40px] shrink-0 items-center gap-1.5 rounded-[10px] border-[1.5px] border-control-border bg-white pl-2 pr-3 text-[0.84rem] font-bold text-midnight-logic transition-colors hover:bg-cloud-slate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",lI=[{title:"Describe your ad",body:"What you're promoting and the feel you want."},{title:"Add a photo",body:"Drag images onto the board â chat only uses the canvas."}
1,{title:"Approve & generate",body:"Review the result and generate the final creative."}];function lT(e){let t=(0,nD.Je)(e);return t?{intentId:t.intentId,message:t.message,source:t.source,version:t.version,boardName:t.boardName,handoffSource:t.handoffSource}:null}function lM(e){var t,n,r,b,_,k,A,C,S,I,T,M,R;let{initialBoardId:U=null,navigationMode:P="route",returnTo:D="dashboard",embeddedBoardId:z,onEmbeddedBoardChange:O,hideHeader:F=!1,contextId:L=null}=e,q=(0,s.useRouter)(),W=(0,s.useSearchParams)(),{user:G}=(0,g.Z)(),{currentOrgId:H}=(0,x.x)(),Y=(0,w.kq)(),V=null!=(t=null!=L?L:null==W?void 0:W.get("contextId"))?t:null,Z=null!=(n=null==W?void 0:W.get(nD.F9))?n:null,ee=null==W?void 0:W.get("surface"),et=(R=null!=(r=null==W?void 0:W.get("from"))?r:null)?"launchpad"===R?lA:R===lA||R.startsWith("".concat(lA,"?"))||R.startsWith("".concat(lA,"/"))?R:null:null,en="embedded"===P||!!et,ea=en&&void 0!==z,es=null!=U?U:en&&null!=z?z:null,ei=(0,o.useRef)(null),[eo,ec]=(0,o.useState)({x:0,y:0,zoom:1}),[ed,eu]=(0,o.useState)(es?"board":"gallery"),[em,ep]=(0,o.useState)("campaign_manager"===ee?"campaign_manager":"board"===ee?"board":"studio"),[eh,ef]=(0,o.useState)(null),[eg,ex]=(0,o.useState)(es),ev=(0,o.useRef)(es),[ew,ej]=(0,o.useState)(()=>lT(Z)),[eN,e_]=(0,o.useState)(null),[ek,eA]=(0,o.useState)([]),eC=(0,o.useRef)([]),[eI,eM]=(0,o.useState)(null),eR=(0,o.useRef)(null),eE=(0,o.useRef)(null),eU=(0,o.useRef)(null),[eB,eD]=(0,o.useState)({}),ez=(0,o.useRef)(eB),[eF,eL]=(0,o.useState)({}),[eq,e$]=(0,o.useState)(!1),[eK,eW]=(0,o.useState)(null),[eJ,eG]=(0,o.useState)([]),[eH,eY]=(0,o.useState)([]),[eV,eX]=(0,o.useState)(!1),[eQ,eZ]=(0,o.useState)(!1),[e0,e1]=(0,o.useState)(!1),[e2,e5]=(0,o.useState)(!1),[e4,e3]=(0,o.useState)(0),[e8,e6]=(0,o.useState)(!1),e7=(0,o.useRef)(new Set),e9=(0,o.useRef)(null),te=(0,o.useRef)(!1),tt=(0,o.useRef)(null),tn=(0,o.useRef)(null),tr=(0,o.useRef)(0),tl=(0,o.useRef)(null),[ts,ti]=(0,o.useState)(!1),[to,tc]=(0,o.useState)(!1),[td,tu]=(0,o.useState)(null),tm=(0,o.useRef)(new Map),tp=(0,o.useRef)(new Map),th=(0,o.useRef)(null),[tf,tg]=(0,o.useState)(()=>new Set),[{data:tx,fetching:tb,error:ty},tv]=(0,h.IT)({query:$,variables:{first:50,offset:0},requestPolicy:"cache-and-network",context:lm.B}),tw=!tb&&!!ty&&!tx,[{data:tj}]=(0,h.IT)({query:K,variables:{boardId:null!=eg?eg:""},pause:!eg,requestPolicy:"cache-and-network"}),[,tN]=(0,f.n_)(E),[,t_]=(0,f.n_)(B),tk=function(e){let t=(0,o.useRef)(new Map),n=(0,o.useRef)(null),a=(0,o.useCallback)(e=>{let n=t.current.get(e);return n||(n={past:[],future:[]},t.current.set(e,n)),n},[]),r=(0,o.useCallback)(e=>{var a;t.current.set(e,{past:[],future:[]}),(null==(a=n.current)?void 0:a.boardId)===e&&(n.current=null)},[]);(0,o.useEffect)(()=>{e&&r(e)},[e,r]);let l=(0,o.useCallback)((e,t)=>{let n=a(e);n.past.push(r7(t)),n.past.length>50&&n.past.shift(),n.future=[]},[a]),s=(0,o.useCallback)((e,t)=>{n.current={boardId:e,snapshot:r7(t)}},[]),i=(0,o.useCallback)((e,t)=>{let a=n.current;n.current=null,a&&a.boardId===e&&(r9(a.snapshot,t)||l(e,a.snapshot))},[l]),c=(0,o.useCallback)((e,t,a)=>{var r;(null==(r=n.current)?void 0:r.boardId)!==e&&(r9(t,a)||l(e,t))},[l]),d=(0,o.useCallback)((e,t)=>{let r=a(e),l=r.past.pop();return l?(r.future.push(r7(t)),n.current=null,r7(l)):null},[a]),u=(0,o.useCallback)((e,t)=>{let r=a(e),l=r.future.pop();return l?(r.past.push(r7(t)),n.current=null,r7(l)):null},[a]);return{beginTransaction:s,endTransaction:i,recordChange:c,undo:d,redo:u,canUndo:(0,o.useCallback)(e=>{var n,a;return(null!=(a=null==(n=t.current.get(e))?void 0:n.past.length)?a:0)>0},[]),canRedo:(0,o.useCallback)(e=>{var n,a;return(null!=(a=null==(n=t.current.get(e))?void 0:n.future.length)?a:0)>0},[]),resetHistory:r}}(eg),{assembledAssets:tA,fetching:tC,hasLoaded:tS,errorMessage:tI,refetchAssets:tT}=(0,r3.Q)(!0,H);(0,o.useEffect)(()=>{eG(e=>(0,ta.OQ)(tA,e))},[tA]),(0,o.useEffect)(()=>{if(ea){ex(null!=z?z:null),eu(z?"board":"gallery");return}en||(U?(ex(U),eu("board")):(ex(null),eu("gallery")))},[z,U,ea,en]);let tR=(0,o.useMemo)(()=>{var e;let t=null==tx||null==(e=tx.list)?void 0:e.nodes;return Array.isArray(t)?t.filter(e=>!!(null==e?void 0:e.id)).map(e=>({id:e.id,name:"string"==typeof e.name&&e.name.trim()?e.name:"Untitled board",updatedAt:"string"==typeof e.updatedAt?e.updatedAt:new Date().toISOString()})):[]},[tx]),[tE,tU]=(0,o.useState)(""),tP=(0,o.useMemo)(()=>{let e=tE.trim().toLowerCase();return e?tR.filter(t=>t.name.toLowerCase().includes(e)):tR},[tE,tR]),{previewsByBoardId:tB,previewsLoading:tD}=function(e){var t;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1],[a,r]=(0,o.useState)(null),l=(0,o.useMemo)(()=>e.join(","),[e]);(0,o.useEffect)(()=>{let e=l?l.split(","):[];
1if(!n||0===e.length)return;let t=!1;return(async()=>{let n=await Promise.all(e.map(async e=>{try{let t=await (0,ta.E)(e);return[e,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6,n=[],a=new Set,r=e=>{!e||a.has(e)||n.length>=t||(a.add(e),n.push(e))};for(let a of[...e].sort((e,t)=>{var n,a;return(null!=(n=e.zIndex)?n:0)-(null!=(a=t.zIndex)?a:0)})){if(n.length>=t)break;if("image"===a.kind){r(lr(a.asset));continue}("file"===a.kind||"pdf"===a.kind)&&r(lr(a.asset))}return n}(t)]}catch(t){return[e,[]]}}));t||r({key:l,previews:Object.fromEntries(n)})})(),()=>{t=!0}},[l,n]);let s=n&&e.length>0;return{previewsByBoardId:s&&null!=(t=null==a?void 0:a.previews)?t:{},previewsLoading:s&&(null==a?void 0:a.key)!==l}}((0,o.useMemo)(()=>tR.map(e=>e.id),[tR]),"gallery"===ed),tz="launchpad"===D?"launchpad":et?null!=(b=null==W?void 0:W.get("from"))?b:"launchpad":null,tO=(0,o.useCallback)(e=>{let t=new URLSearchParams;V&&t.set("contextId",V),tz&&t.set("from",tz);let n=t.toString();return n?"".concat(e,"?").concat(n):e},[tz,V]),tF=(0,o.useCallback)(e=>{en&&(null==O||O(e)),ex(e),eu("board")},[O,en]),tL=(0,o.useCallback)(e=>{"board"===e&&"board"!==em&&t2(),ep(e)},[em]),tq=(0,o.useCallback)(()=>{en&&(null==O||O(null)),ex(null),eu("gallery")},[O,en]),t$=(0,o.useMemo)(()=>{var e,t;let n=null==tj||null==(t=tj.detail)||null==(e=t.nodes)?void 0:e[0];return(null==n?void 0:n.id)?{id:n.id,name:"string"==typeof n.name&&n.name.trim()?n.name:"Untitled board",updatedAt:"string"==typeof n.updatedAt?n.updatedAt:new Date().toISOString()}:null},[tj]),tK=null!=(_=tR.find(e=>e.id===eg))?_:t$,tW=eg&&null!=(k=eB[eg])?k:lN,tJ=eg&&null!=(A=eF[eg])?A:l_,tG=eN&&null!=(C=tW.find(e=>e.id===eN))?C:null,tH=(0,o.useMemo)(()=>{if(0===ek.length)return[];let e=new Set(ek);return tW.filter(t=>e.has(t.id))},[tW,ek]),tY=(0,o.useMemo)(()=>{if(0===tH.length)return null;let e=Math.min(...tH.map(e=>e.x)),t=Math.min(...tH.map(e=>e.y));return{x:e,y:t,width:Math.max(...tH.map(e=>e.x+e.width))-e,height:Math.max(...tH.map(e=>e.y+e.height))-t}},[tH]),tV=null!=(S=null!=tG?tG:tH[0])?S:null,tX=(0,o.useMemo)(()=>(0,tM.Ep)(tW),[tW]),tQ="board"===em&&!e2&&!tX,tZ=(0,o.useMemo)(()=>[...eJ].sort((e,t)=>{let n=e.lastUsedAt?new Date(e.lastUsedAt).getTime():0;return(t.lastUsedAt?new Date(t.lastUsedAt).getTime():0)-n}).slice(0,5),[eJ]),t0=null!=eK?eK:tI,t1=(0,o.useCallback)(e=>{e6(e)},[]),t2=(0,o.useCallback)(()=>{e9.current&&(clearTimeout(e9.current),e9.current=null),e3(e=>e+1)},[]),t5=(0,o.useCallback)(e=>{if(!eg||0===e.length)return;let t=e.map(lH).filter(e=>null!==e);if(0===t.length)return;let n=new Map(t.map(e=>[e.id,e]));te.current=!0,eD(e=>{var a;let r=null!=(a=e[eg])?a:[],l=new Set(r.map(e=>e.id));return{...e,[eg]:[...r.map(e=>{var t;return null!=(t=n.get(e.id))?t:e}),...t.filter(e=>!l.has(e.id))]}});let a=e.map(e=>e.asset).filter(e=>null!==e);a.length>0&&eG(e=>(0,ta.OQ)(a,e))},[eg]);(0,o.useEffect)(()=>{ez.current=eB},[eB]),(0,o.useEffect)(()=>{eC.current=ek},[ek]),(0,o.useEffect)(()=>{let e=tm.current;return()=>{Object.values(ez.current).flat().forEach(e=>lZ(e)),e.forEach(e=>e.dispose()),e.clear()}},[]);let t4=(0,o.useCallback)(e=>{eg&&eD(t=>({...t,[eg]:e}))},[eg]);(0,o.useEffect)(()=>{ev.current!==eg&&(ev.current=eg,e_(null),eA([]),eM(null),ep("studio"),ef(null))},[eg]);let t3=(0,o.useCallback)((e,t)=>{eD(n=>{var a;if(!eg)return n;let r=null!=(a=n[eg])?a:[],l=e(r);return(null==t?void 0:t.skipHistory)||tk.recordChange(eg,r,l),{...n,[eg]:l}})},[eg,tk]),t8=(0,o.useCallback)(e=>{eL(t=>{var n;if(!eg)return t;let a=e(null!=(n=t[eg])?n:new Map);return{...t,[eg]:a}})},[eg]),t6=(0,o.useCallback)(e=>{let t=new Set(e);0!==t.size&&(t3(e=>(e.forEach(e=>{t.has(e.id)&&lZ(e)}),e.filter(e=>!t.has(e.id)))),t8(t=>{if(!e.some(e=>t.has(e)))return t;let n=new Map(t);return e.forEach(e=>n.delete(e)),n}),e.forEach(e=>{let t=tm.current.get(e);t&&(t.dispose(),tm.current.delete(e)),tp.current.delete(e)}),tg(t=>{if(!e.some(e=>t.has(e)))return t;let n=new Set(t);return e.forEach(e=>n.delete(e)),n}),e_(e=>e&&t.has(e)?null:e),eA(e=>e.filter(e=>!t.has(e))))},[!1,t3,t8]),t7=(0,o.useCallback)(()=>{var e;let t=tn.current;if(!t||!eg)return;tr.current+=1;let n=24*tr.current,{items:a,filesByItemId:r}=(0,ey.Yl)(t,{offsetX:n,offsetY:n,makeId:lP});
1t.items.forEach((e,t)=>{let n=a[t];if(!n||"pdf"!==e.kind||"pdf"!==n.kind)return;let r=tm.current.get(e.id);r&&tm.current.set(n.id,r)}),r.size>0&&t8(e=>{let t=new Map(e);return r.forEach((e,n)=>t.set(n,e)),t}),t3(e=>[...e,...a]);let l=a.map(e=>e.id);eA(l),e_(1===l.length&&null!=(e=l[0])?e:null)},[eg,!1,t3,t8]);(0,o.useEffect)(()=>{let e=e=>{var t;if(!eg){"Escape"===e.key&&e_(null);return}let n=e.target;if(null==n?void 0:n.closest("input, textarea, [contenteditable='true']"))return;if("Escape"===e.key){e_(null),eA([]);return}if("board"===em&&("Backspace"===e.key||"Delete"===e.key)){let t=eC.current;if(0===t.length)return;e.preventDefault(),t6(t);return}if(!(e.metaKey||e.ctrlKey))return;let a=null!=(t=ez.current[eg])?t:[];if("z"===e.key&&e.shiftKey){e.preventDefault();let t=tk.redo(eg,a);t&&t4(t);return}if("z"===e.key){e.preventDefault();let t=tk.undo(eg,a);t&&t4(t);return}if("y"===e.key){e.preventDefault();let t=tk.redo(eg,a);t&&t4(t)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eg,em,t4,tk,t6,!1]),(0,o.useEffect)(()=>{let e=e=>{if(!eg||0===tH.length)return;let t=e.target;if(null==t?void 0:t.closest("input, textarea, [contenteditable='true']"))return;let n=(0,ey.fl)(tH,tJ);tn.current=n,tr.current=0,e.preventDefault(),(0,ey.MO)(e,n,tJ)};return window.addEventListener("copy",e),()=>window.removeEventListener("copy",e)},[eg,!1,tJ,tH]);let t9=(0,o.useCallback)(()=>{eW(null),tT()},[tT]),nt=(0,o.useCallback)(()=>{e$(!0),t9()},[t9]),nn=(0,o.useCallback)(e=>{let t=new Set(e.map(e=>e.id)),n=new Date().toISOString();eG(e=>e.map(e=>t.has(e.id)?{...e,lastUsedAt:n}:e).sort((e,t)=>{let n=e.lastUsedAt?new Date(e.lastUsedAt).getTime():0;return(t.lastUsedAt?new Date(t.lastUsedAt).getTime():0)-n}))},[]),na=(0,o.useCallback)(async e=>{let t=e.map(e=>e.id);if(0!==t.length){e1(!0),eW(null);try{var n,a,r,l,s,i,o;let e=await t_({input:{ids:t}}),c=(null!=(l=null==(n=e.error)?void 0:n.graphQLErrors)?l:[]).map(e=>e.message).join(" \xb7 ")||(null==(a=e.error)?void 0:a.message)||null;if(c||(null==(r=e.data)?void 0:r.deleteAdMakerAssetLibraries)==null)return void eW(c||"Could not delete assets");let d=new Set(t),u=new Set;for(let e of Object.keys(eB))for(let t of null!=(s=eB[e])?s:[]){let e="image"===t.kind||"file"===t.kind?t.assetId:"pdf"===t.kind?null!=(o=t.assetId)?o:null==(i=t.asset)?void 0:i.id:null;e&&d.has(e)&&u.add(t.id)}eG(e=>e.filter(e=>!d.has(e.id))),te.current=!0,eD(e=>{let t={};for(let a of Object.keys(e)){var n;t[a]=(null!=(n=e[a])?n:[]).filter(e=>{var t,n;let a="image"===e.kind||"file"===e.kind?e.assetId:"pdf"===e.kind?null!=(n=e.assetId)?n:null==(t=e.asset)?void 0:t.id:null;return!(a&&d.has(a))})}return t}),eL(e=>{let t={};for(let a of Object.keys(e)){var n;let r=new Map(null!=(n=e[a])?n:[]);u.forEach(e=>{r.delete(e)}),t[a]=r}return t}),eA(e=>e.filter(e=>!u.has(e))),e_(e=>e&&u.has(e)?null:e),t9()}catch(e){eW(e instanceof Error?e.message:"Could not delete assets")}finally{e1(!1)}}},[eB,t_,!1,t9]);(0,o.useEffect)(()=>{if(!eg)return;let e=!1,t=!e7.current.has(eg);return t&&e5(!0),(async()=>{try{let t=await (0,ta.E)(eg),a=await lJ(t);if(e){var n;return void((n=a).items.forEach(e=>lZ(e)),n.pdfHandles.forEach(e=>e.dispose()),n.pdfHandles.clear())}tm.current.forEach(e=>e.dispose()),tm.current.clear(),a.pdfHandles.forEach((e,t)=>{tm.current.set(t,e)}),eL(e=>({...e,[eg]:a.filesByItemId})),eD(e=>{var t;return(null!=(t=e[eg])?t:[]).forEach(e=>lZ(e)),{...e,[eg]:a.items}})}catch(t){e||(console.warn("[ad-maker] Failed to load board state:",t),eD(e=>{var t;return{...e,[eg]:null!=(t=e[eg])?t:[]}}))}finally{!e&&(e7.current.add(eg),t&&e5(!1))}})(),()=>{e=!0}},[eg,e4]),(0,o.useEffect)(()=>{if(eg){if(e8||e2){e9.current&&(clearTimeout(e9.current),e9.current=null);return}if(e7.current.has(eg)){if(te.current){te.current=!1;return}return e9.current&&(clearTimeout(e9.current),e9.current=null),e9.current=setTimeout(()=>{(0,ta.ZE)(eg,tW).catch(e=>{console.warn("[ad-maker] Failed to save board state:",e)})},500),()=>{e9.current&&(clearTimeout(e9.current),e9.current=null)}}}},[eg,e8,e2,tW]);let nr=(0,o.useCallback)(async function(){var e,t,n,a,r;let l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=(null==(e=l.name)?void 0:e.trim())||"Board ".concat(tR.length+1),i=null==(n=(await tN({name:s,metadata:{source:"ad-maker",...V?{contextId:V}:{},...null!=(a=l.metadata)?a:{}}})).data)||null==(t=n.createAdMakerBoard)?void 0:t.adMakerBoard;if(null==i?void 0:i.id){let e=[],t=[],n=new Map;if(l.importBranding){let a=lf((0,ta.OQ)(tA,eJ));if(a.length>0){let r=await lU(a,{x:-460,y:-180});
1e=r.items,t=r.materializedAssets,n=r.filesByItemId,r.failedAssetNames.length>0&&(console.warn("[ad-maker] Some Brand Studio assets could not be imported:",r.failedAssetNames),eW("Board created, but some branding could not be imported: ".concat(r.failedAssetNames.join(", "),"."))),e.length>0&&await (0,ta.ZE)(i.id,e)}}return(t.length>0&&eG(e=>(0,ta.OQ)(t,e)),ex(i.id),eu("board"),ep(null!=(r=l.surface)?r:"studio"),eD(t=>{var n;return{...t,[i.id]:null!=(n=t[i.id])?n:e}}),eL(e=>{var t;return{...e,[i.id]:n.size>0?n:null!=(t=e[i.id])?t:new Map}}),tv({requestPolicy:"network-only"}),en)?null==O||O(i.id):!1!==l.route&&q.push(tO("".concat(lk,"/").concat(i.id))),i.id}return null},[tA,eJ,tR.length,tO,V,tN,tv,O,q,eW,en]),nl=(0,o.useCallback)(async e=>{tc(!0),tu(null);try{if(!await nr({name:e.name,importBranding:e.importBranding}))throw Error("Could not create the board.");ti(!1)}catch(e){tu(e instanceof Error?e.message:"Could not create the board.")}finally{tc(!1)}},[nr]);(0,o.useEffect)(()=>{if(!Z)return;let e=lT(Z);if(e)ej(e),ep("campaign_manager"),tS&&!tC&&(eg||tl.current===Z||(tl.current=Z,nr({name:e.boardName,surface:"campaign_manager",route:!1,importBranding:!0,metadata:{source:"market-research"===e.handoffSource?"market-research-ad-intelligence":"campaign-kickoff"===e.handoffSource?"campaign-hub-kickoff":"marketing-strategy-content-posts",campaignManagerIntent:Z}}).then(e=>{if(!e||en)return;let t=new URLSearchParams;V&&t.set("contextId",V),tz&&t.set("from",tz),t.set("surface","campaign_manager"),t.set(nD.F9,Z),q.replace("".concat(lk,"/").concat(encodeURIComponent(e),"?").concat(t.toString()))}).catch(e=>{tl.current=null,eW(e instanceof Error?e.message:"Could not create a campaign board")})))},[eg,tz,tC,tS,V,Z,nr,q,en]);let ns=(0,o.useCallback)(()=>{var e;null==(e=ei.current)||e.zoomBy(1.2)},[!1]),ni=(0,o.useCallback)(()=>{var e;null==(e=ei.current)||e.zoomBy(.8333333333333334)},[!1]),no=(0,o.useCallback)(()=>{var e;null==(e=ei.current)||e.resetView()},[!1]),nc=(0,o.useCallback)((e,t,n)=>{t3(a=>{let r=a.find(t=>t.id===e);if(!r)return a;let l=t-r.x,s=n-r.y,i=eE.current,o=i&&i.includes(e)?i:[e];if(o.length<=1)return a.map(a=>a.id===e?{...a,x:t,y:n}:a);let c=new Set(o);return a.map(e=>c.has(e.id)?{...e,x:e.x+l,y:e.y+s}:e)},{skipHistory:!0})},[!1,t3]),nd=(0,o.useCallback)((e,t)=>{var n,a;if(!eg)return;let r=eC.current,l=r.includes(e),s=t.shiftKey,i=t.metaKey||t.ctrlKey,o=r,c=!1;return s?(o=l?r:[...r,e],c=!0):i?(o=l?r.filter(t=>t!==e):[...r,e],c=!0):l||(o=[e],c=!0),c&&(eC.current=o,eA(o),e_(1===o.length&&null!=(n=o[0])?n:null)),eE.current=o.includes(e)?o:[e],tk.beginTransaction(eg,null!=(a=ez.current[eg])?a:[]),c},[eg,tk,!1]),nu=(0,o.useCallback)(()=>{var e;eE.current=null,eg&&tk.endTransaction(eg,null!=(e=ez.current[eg])?e:[])},[eg,tk,!1]),nm=(0,o.useCallback)(()=>{var e;tY&&eg&&(tk.beginTransaction(eg,null!=(e=ez.current[eg])?e:[]),tt.current={startBounds:tY,itemIds:[...ek],snapshots:new Map(tH.map(e=>[e.id,{x:e.x,y:e.y,width:e.width,height:e.height}]))})},[eg,tk,!1,ek,tH,tY]),np=(0,o.useCallback)(e=>{let t=tt.current;t&&t3(n=>(function(e,t,n,a,r){if(n.width<=0||n.height<=0)return e;let l=a.width/n.width,s=a.height/n.height,i=new Set(t);return e.map(e=>{if(!i.has(e.id))return e;let t=r.get(e.id);
1return t?{...e,x:a.x+(t.x-n.x)*l,y:a.y+(t.y-n.y)*s,width:Math.max(48,t.width*l),height:Math.max(48,t.height*s)}:e})})(n,t.itemIds,t.startBounds,e,t.snapshots),{skipHistory:!0})},[!1,t3]),nh=(0,o.useCallback)(()=>{tt.current=null,nu()},[nu]),nf=(0,o.useCallback)(e=>{eC.current=[e],e_(e),eA([e])},[!1]),ng=(0,o.useCallback)((e,t)=>{let n=t.trim();t3(a=>a.map(a=>a.id!==e||"text"!==a.kind?a:{...a,text:t,fileName:n?n.split(/\s+/).slice(0,6).join(" "):"Text note"}))},[!1,t3]),nx=(0,o.useCallback)((e,t)=>{t3(n=>n.map(n=>n.id===e?{...n,fileName:t}:n))},[!1,t3]),nb=(0,o.useCallback)(async e=>{var t,n,a,r,l,s,o,c,d;let u=tW.find(t=>t.id===e);if(!u)return;let m=tJ.get(e);if(m)return void(0,i.saveAs)(m,m.name||u.fileName||"asset");if("text"===u.kind)return void(0,i.saveAs)(new Blob([u.text],{type:"text/plain;charset=utf-8"}),u.fileName||"note.txt");if("html"===u.kind){let e=/\.html?$/i.test(u.fileName)?u.fileName:"".concat(u.fileName||"email-preview",".html");(0,i.saveAs)(new Blob([u.html],{type:"text/html;charset=utf-8"}),e);return}let p="image"===(t=u).kind?t.src||(null==(n=t.asset)?void 0:n.url)||(null==(l=t.asset)||null==(r=l.media)||null==(a=r[0])?void 0:a.sourceUrl)||"":"video"===t.kind?t.src:("pdf"===t.kind||"file"===t.kind)&&(t.objectUrl||(null==(s=t.asset)?void 0:s.url)||(null==(d=t.asset)||null==(c=d.media)||null==(o=c[0])?void 0:o.sourceUrl))||"";if(p)try{await lL(p,u.fileName||"asset"),eW(null)}catch(e){eW("Could not download that asset. The file URL may not allow browser downloads.")}},[tJ,tW]),ny=(0,o.useCallback)(e=>{t6([e])},[t6]),nv=(0,o.useCallback)(()=>{t6(tH.map(e=>e.id))},[t6,tH]),nw=(0,o.useCallback)(e=>{if(!eU.current||0!==e.button)return;let t=e.target;if(null==t?void 0:t.closest("[data-board-item-id], [data-board-item-handles]"))return;let n=eU.current.getBoundingClientRect(),a=e.clientX-n.left,r=e.clientY-n.top;eR.current=e.pointerId,eU.current.setPointerCapture(e.pointerId),eM({startX:a,startY:r,endX:a,endY:r}),e_(null),eA([])},[!1]),nj=(0,o.useCallback)(e=>{if(!eU.current||!eI||eR.current!==e.pointerId)return;let t=eU.current.getBoundingClientRect(),n=e.clientX-t.left,a=e.clientY-t.top;eM(e=>e?{...e,endX:n,endY:a}:e)},[eI]),nN=(0,o.useCallback)(e=>{var t;if(!eU.current||!eI||eR.current!==e.pointerId)return;try{eU.current.releasePointerCapture(e.pointerId)}catch(e){}eR.current=null;let n=Math.min(eI.startX,eI.endX),a=Math.min(eI.startY,eI.endY),r=Math.max(eI.startX,eI.endX),l=Math.max(eI.startY,eI.endY);if(r-n<4||l-a<4)return void eM(null);let s=(n-eo.x)/eo.zoom,i=(a-eo.y)/eo.zoom,o=(r-eo.x)/eo.zoom,c=(l-eo.y)/eo.zoom,d=tW.filter(e=>{let t=e.x,n=e.y,a=e.x+e.width,r=e.y+e.height;return a>=s&&t<=o&&r>=i&&n<=c}).map(e=>e.id);eA(d),e_(1===d.length&&null!=(t=d[0])?t:null),eM(null)},[tW,eI,eo.x,eo.y,eo.zoom]),n_=(0,o.useCallback)(async(e,t)=>{let{accepted:n,rejects:a}=(0,ta.qs)(e);if(a.length>0?eW((0,ta.KF)(a)):eW(null),0===n.length)return;let r=await Promise.all(n.map(async e=>{if((0,ta.X9)(e)){var n,a,r;let l=await (0,lt._)(e);if(!l){let n=URL.createObjectURL(e);return{id:lP(),file:e,previewUrl:n,width:null,height:null,placeAt:null!=t?t:null}}let s=await l.renderPage(1,480);l.dispose();let i=null!=(n=null==s?void 0:s.dataUrl)?n:URL.createObjectURL(e);return{id:lP(),file:e,previewUrl:i,width:null!=(a=null==s?void 0:s.width)?a:null,height:null!=(r=null==s?void 0:s.height)?r:null,placeAt:null!=t?t:null}}let l=await (0,le.Sc)(e),s=URL.createObjectURL(l),i=await l0(s).catch(()=>({width:null,height:null}));return{id:lP(),file:l,previewUrl:s,width:i.width,height:i.height,placeAt:null!=t?t:null}}));eY(e=>[...e,...r])},[]);(0,o.useEffect)(()=>{let e=e=>{var t,n,a,r,l,s,i,o,c,d;if(!eg)return;let u=e.target,m=null==u?void 0:u.tagName;if("INPUT"===m||"TEXTAREA"===m||(null==u?void 0:u.isContentEditable))return;let p=Array.from(null!=(l=null==(t=e.clipboardData)?void 0:t.items)?l:[]).filter(e=>e.type.startsWith("image/"));if((0,ey.ey)(e.clipboardData,tn.current)){e.preventDefault(),t7();return}let h=null!=(s=null==(a=e.clipboardData)||null==(n=a.getData("text/plain"))?void 0:n.trim())?s:"",f=tn.current;if((null==f?void 0:f.items.length)===1&&(null==(r=f.items[0])?void 0:r.kind)==="image"&&p.length>0&&!h){e.preventDefault(),t7();return}if(p.length>0){tn.current=null,e.preventDefault(),n_(p.map(e=>e.getAsFile()).filter(e=>null!==e),null!=(o=null==(i=ei.current)?void 0:i.getViewportCenterWorld())?o:{x:0,y:0});return}if(h){tn.current=null,e.preventDefault();let t=null!=(d=null==(c=ei.current)?void 0:c.getViewportCenterWorld())?d:{x:0,y:0},n=lP(),a={id:n,kind:"text",fileName:h.trim().split(/\s+/).slice(0,6).join(" "),text:h,x:t.x-eb.lz/2,y:t.y-eb.OF/2,width:eb.lz,height:eb.OF};t3(e=>[...e,a]),eA([n]),e_(n)}};return window.addEventListener("paste",e),()=>window.removeEventListener("paste",e)},[eg,!1,t7,n_,t3]);let nk=(0,o.useCallback)(async(e,t,n,a)=>{var r,l,s,i,o;if(!eg||0===e.length)return;let c=null!=(s=null!=t?t:null==(r=ei.current)?void 0:r.getViewportCenterWorld())?s:{x:0,y:0},d=[],u=new Map,m=null!=(i=ez.current[eg])?i:[];for(let t=0;t<e.length;t+=1){let r=e[t],l=r,s=null==n?void 0:n.get(r.id);if((0,r6.Rt)("board.add.start",{asset:(0,r6.BT)(r),isVirtual:(0,r8.Fk)(r),isFontReference:(0,r8.Q)(r)}),(0,r8.Fk)(r)&&!(0,r8.Q)(r))try{let e=await lD(r);
1l=e.asset,s=e.file,eG(e=>(0,ta.OQ)([l],e)),(0,r6.Rt)("board.add.materialized",{from:r.id,to:l.id,fileName:s.name,fileSize:s.size})}catch(e){(0,r6.Ml)("board.add.materializeFailed",{asset:(0,r6.BT)(r),message:e instanceof Error?e.message:String(e)}),eW(e instanceof Error?e.message:"Could not prepare that Brand Studio asset.");continue}let i=(null==a?void 0:a.layout)==="brand-reference-grid"?lE(c,t):c,o=(null==a?void 0:a.layout)==="brand-reference-grid"?0:t;if(lz(l))try{let e=await lq(l,i.x,i.y,o,s);if(!e){eW("Could not load that PDF on the board.");continue}tm.current.set(e.item.id,e.handle),d.push(e.item),s&&u.set(e.item.id,s)}catch(e){eW("Could not load that PDF on the board.")}else if((0,r8.Q)(l))d.push(lK(l,i.x,i.y,o));else if((0,r4.U$)(l)||lF(l)){let e=l$(l,i.x,i.y,o);d.push(e),s&&u.set(e.id,s)}else{let e=lW(l,i.x,i.y,o);d.push(e),s&&u.set(e.id,s)}}0!==d.length&&(t3(e=>[...e,...d]),(null==a?void 0:a.saveImmediately)&&await (0,ta.ZE)(eg,[...m,...d]),u.size>0&&t8(e=>{let t=new Map(e);return u.forEach((e,n)=>t.set(n,e)),t}),eA(d.map(e=>e.id)),e_(1===d.length&&null!=(o=null==(l=d[0])?void 0:l.id)?o:null),nn(d.flatMap(e=>("image"===e.kind||"pdf"===e.kind||"file"===e.kind||"font"===e.kind)&&e.asset?[e.asset]:[])))},[eg,!1,nn,t3,t8]),nA=(0,o.useMemo)(()=>(function(e,t){var n;let a=lf(e),r=a.find(e=>"brand-book"===e.metadata.brandStudioAssetKind);return{available:a.length>0,loading:null!=(n=null==t?void 0:t.loading)&&n,brandName:a.map(e=>String(e.name||"").replace(/\s+(brand book|colour palette|display font|body font).*$/i,"").trim()).find(Boolean)||null,brandBookUrl:r?(0,r8.X9)(r):null,assetLabels:a.map(e=>(function(e){let t=String(e.metadata.brandStudioAssetKind||"");return"logo"===t?!function(e){let t=String(e.metadata.brandStudioLogoRole||"").trim().toLowerCase();return lh.has(t)}(e)?"logo":"brand icon":"logo-concept"===t?"logo concept":"colour-palette"===t?"colour palette":"font"===t?"body"===e.metadata.fontRole?"body font":"display font":"brand-book"===t?"brand book PDF":"signature-device"===t?"signature brand device":"motif"===t?"brand motif":"application"===t?"brand application":e.name})(e))}})(eJ,{loading:tC||!tS}),[tC,tS,eJ]),nC=(0,o.useCallback)(async(e,t)=>{if(eg&&0!==t.length){eX(!0);try{var n,a,r,l;let s=await (0,ta.Ae)(t.map(e=>e.file)).catch(e=>(console.warn("[ad-maker] Failed to pre-extract asset context:",e),null)),i=await (0,ta.QR)(t.map(e=>e.file),{...e,metadata:(0,r4.We)({...null!=(r=e.metadata)?r:{},...s?{adMakerExtractedContext:{...s,extractedAt:new Date().toISOString()}}:{}},H)},t.map((e,t)=>{var n;return{width:e.width,height:e.height,metadata:{originalFileName:e.file.name,...(null==s||null==(n=s.files)?void 0:n[t])?{adMakerExtractedContextFile:s.files[t]}:{}}}}));t.forEach(e=>{lB(e)}),eY([]),eG(e=>[i,...e.filter(e=>e.id!==i.id)]);let o=null!=(l=null==(n=t[0])?void 0:n.placeAt)?l:null,c=null==(a=t[0])?void 0:a.file;await nk([i],null!=o?o:null,c?new Map([[i.id,c]]):void 0),t9(),e$(!1),eW(null)}catch(e){eW(e instanceof Error?e.message:"Failed to save asset")}finally{eX(!1)}}},[eg,nk,H,!1,t9]),nS=(0,o.useCallback)(()=>{eY(e=>(e.forEach(e=>lB(e)),[]))},[]),nI=(0,o.useCallback)(async(e,t,n,a,r)=>{if(eg){eZ(!0),eW(null);try{let r=await (0,ta.QR)([e],{name:t,description:n,role:a,width:null,height:null,metadata:(0,r4.We)({source:"product-url"},H)},[{width:null,height:null,metadata:{source:"product-url"}}]);eG(e=>[r,...e.filter(e=>e.id!==r.id)]),await nk([r]),t9(),e$(!1)}catch(e){eW(e instanceof Error?e.message:"Failed to save product asset")}finally{eZ(!1)}}},[eg,nk,H,!1,t9]),nT=(0,o.useCallback)(e=>{if(!eg)return;let t=Array.from(e.dataTransfer.files||[]),{accepted:n,rejects:a}=(0,ta.qs)(t);if(a.length>0?eW((0,ta.KF)(a)):eW(null),0===n.length||(e.preventDefault(),e.stopPropagation(),!eU.current))return;let r=eU.current.getBoundingClientRect(),l=e.clientX-r.left,s=e.clientY-r.top;n_(n,{x:(l-eo.x)/eo.zoom,y:(s-eo.y)/eo.zoom})},[eg,!1,n_,eo.x,eo.y,eo.zoom]),nM=(0,o.useCallback)(async function(e){var t,n,a,r,l,s,i,o;let c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"frame_generation";if(!eg||0===e.length)return;let d=e.map((e,t)=>{var n,a;let r=Number(null!=(a=null!=(n=e.index)?n:e.frame_index)?a:t+1),l="string"==typeof e.image_url?e.image_url.trim():"";return Number.isFinite(r)&&r>0&&l?{...e,frameIndex:r,imageUrl:l}:null}).filter(e=>!!e).sort((e,t)=>
1e.frameIndex-t.frameIndex);if(0===d.length)return;let u=null!=(n=ez.current[eg])?n:[],m=new Map;for(let e of d){let t=String(e.item_id||e.source_item_id||"").trim(),n=null!=(a=t?u.find(e=>e.id===t):null)?a:u.find(t=>{var n,a;return(null==(n=lV(t))?void 0:n.kind)==="storyboard_frame"&&(null==(a=lV(t))?void 0:a.frameIndex)===e.frameIndex});n&&m.set(e.frameIndex,n)}let p=null!=(l=null!=(r=[...m.values()].map(e=>{var t;return null==(t=lV(e))?void 0:t.sequenceId}).find(e=>!!e))?r:th.current)?l:lP(),h=lP();th.current=p;let f=[],g=new Map;for(let e of d){let t=m.get(e.frameIndex),n={...null!=(s=lV(t))?s:{},sequenceId:p,runId:h,kind:"storyboard_frame",frameIndex:e.frameIndex,prompt:"string"==typeof e.prompt?e.prompt:void 0,sourceStep:c,sourceItemId:String(e.item_id||e.source_item_id||(null==t?void 0:t.id)||"").trim()||void 0,title:"string"==typeof e.title?e.title:"Frame ".concat(e.frameIndex),description:"string"==typeof e.description?e.description:void 0,camera:"string"==typeof e.camera?e.camera:void 0,continuityAnchor:"string"==typeof e.continuity_anchor?e.continuity_anchor:void 0,ctaMoment:"string"==typeof e.cta_moment?e.cta_moment:void 0,narrativePurpose:"string"==typeof e.narrative_purpose?e.narrative_purpose:void 0,previousStateContinuity:"string"==typeof e.previous_state_continuity?e.previous_state_continuity:void 0,nextFrameSetup:"string"==typeof e.next_frame_setup?e.next_frame_setup:void 0,visualHandoff:"string"==typeof e.visual_handoff?e.visual_handoff:void 0};if(t){g.set(e.frameIndex,{...t,kind:"image",src:e.imageUrl,fileName:t.fileName||"Storyboard frame ".concat(e.frameIndex,".png"),metadata:n});continue}let a=eb.dT,r=eb.dT;try{let t=await l0(e.imageUrl),n=Math.min(1,eb.dT/Math.max(t.width,t.height));a=Math.round(t.width*n),r=Math.round(t.height*n)}catch(e){}let l="storyboard-frame-".concat(e.frameIndex,"-").concat(Date.now(),".png");try{let t=await (0,ta.uz)({sourceUrl:e.imageUrl,fileName:l,name:"Storyboard frame ".concat(e.frameIndex),width:a,height:r}),s={...l$(t,0,0,0),fileName:l,width:a,height:r,metadata:n};f.push(s),g.set(e.frameIndex,s)}catch(s){let t={id:lP(),kind:"image",src:e.imageUrl,fileName:l,x:0,y:0,width:a,height:r,metadata:n};f.push(t),g.set(e.frameIndex,t)}}let x=f.length>0?function(e){let{frames:t,existingItems:n,center:a}=e;if(0===t.length)return[];let r=[...t].sort((e,t)=>{var n,a,r,l;return(null!=(r=null==(n=lV(e))?void 0:n.frameIndex)?r:0)-(null!=(l=null==(a=lV(t))?void 0:a.frameIndex)?l:0)}),l=Math.max(...r.map(e=>e.height),140),s=r.reduce((e,t)=>e+t.width,0)+290*Math.max(0,r.length-1),i=a.x-s/2,o=a.y-l/2;for(let e=0;e<40;e+=1)for(let t=0;t<10;t+=1){let a=lQ(r,{x:i+t*(s+15),y:o+e*(l+15)},l),c=[...a,...function(e){let t=[...e].sort((e,t)=>{var n,a,r,l;return(null!=(r=null==(n=lV(e))?void 0:n.frameIndex)?r:0)-(null!=(l=null==(a=lV(t))?void 0:a.frameIndex)?l:0)}),n=[];for(let e=0;e<t.length-1;e+=1){let a=t[e],r=t[e+1];n.push({id:"transition-slot-".concat(e),kind:"text",fileName:"Transition slot",text:"",x:a.x+a.width+15,y:Math.min(a.y,r.y)+(Math.max(a.y+a.height,r.y+r.height)-Math.min(a.y,r.y)-140)/2,width:260,height:140})}return n}(a)];if(c.every((e,t)=>c.filter((e,n)=>n!==t).every(t=>!lX(e,t))&&n.every(t=>!lX(e,t))))return a}return lQ(r,{x:i,y:o+l+15},l)}({frames:f,existingItems:u,center:null!=(i=null==(t=ei.current)?void 0:t.getViewportCenterWorld())?i:{x:0,y:0}}):[],b=new Map(x.map(e=>[e.id,e]));t3(e=>{let t=new Map;for(let e of d){let n=m.get(e.frameIndex),a=g.get(e.frameIndex);n&&a&&t.set(n.id,a)}for(let e of x)t.set(e.id,e);let n=e.map(e=>{var n;return null!=(n=t.get(e.id))?n:e});for(let e of x){var a;n.some(t=>t.id===e.id)||n.push(null!=(a=b.get(e.id))?a:e)}return n});let y=d.map(e=>{var t;return null==(t=g.get(e.frameIndex))?void 0:t.id}).filter(e=>!!e);y.length>0&&(eA(y),e_(1===y.length&&null!=(o=y[0])?o:null))},[eg,t3]),nR=(0,o.useCallback)(e=>{if(!eg||0===e.length)return;let t=lP();t3(n=>{var a,r,l,s,i,o,c;let d=null!=(l=null!=(r=th.current)?r:null==(a=n.map(e=>lV(e)).find(e=>(null==e?void 0:e.kind)==="storyboard_frame"))?void 0:a.sequenceId)?l:lP();th.current=d;let u=[...n];for(let n of e){let e=Number(null!=(i=null!=(s=n.index)?s:n.start_frame_index)?i:1),a=Number(null!=(o=n.start_frame_index)?o:e),r=Number(null!=(c=n.end_frame_index)?c:a+1),l=String(n.prompt||"").trim();if(!Number.isFinite(a)||!Number.isFinite(r)||!l)continue;let m=u.findIndex(e=>{let t=lV(e);return(null==t?void 0:t.kind)==="storyboard_transition"&&t.sequenceId===d&&t.startFrameIndex===a&&t.endFrameIndex===r}),p=function(e,t,n,a){let r=e.find(e=>{let a=lV(e);return(null==a?void 0:a.kind)==="storyboard_frame"&&a.sequenceId===t&&a.frameIndex===n}),l=e.find(e=>{let n=lV(e);return(null==n?void 0:n.kind)==="storyboard_frame"&&n.sequenceId===t&&n.frameIndex===a});if(r&&l)return{x:r.x+r.width+15,y:Math.min(r.y,l.y)+(Math.max(r.y+r.height,l.y+l.height)-Math.min(r.y,l.y)-140)/2};let s=null!=r?r:l;return s?{x:s.x+s.width+15,y:s.y}:{x:0,y:0}}
1(u,d,a,r),h={sequenceId:d,runId:t,kind:"storyboard_transition",startFrameIndex:a,endFrameIndex:r,prompt:l,sourceStep:"transition_prompt_generation",title:"Transition ".concat(a,"-").concat(r)},f={id:m>=0?u[m].id:lP(),kind:"text",fileName:"Transition ".concat(a,"-").concat(r),text:l,x:p.x,y:p.y,width:260,height:140,metadata:h};m>=0?u[m]=f:u.push(f)}return u})},[eg,t3]),nE=(0,o.useCallback)((e,t)=>{var n,a;if(!eg)return;let r=e.trim();if(!r)return;let l=tW.find(e=>"text"===e.kind&&e.text.trim()===r);if(l){eA([l.id]),e_(l.id);return}let s=new Set(t),i=tW.filter(e=>"image"===e.kind&&(0===s.size||s.has(e.src))),o=null!=(a=null==(n=ei.current)?void 0:n.getViewportCenterWorld())?a:{x:0,y:0},c=o.x-eb.lz/2,d=o.y-eb.OF/2;if(i.length>0){let e=Math.min(...i.map(e=>e.x)),t=Math.max(...i.map(e=>e.x+e.width)),n=Math.max(...i.map(e=>e.y+e.height));c=e+(t-e)/2-eb.lz/2,d=n+16}let u=lP(),m={id:u,kind:"text",fileName:r.split(/\s+/).slice(0,6).join(" ")||"Generated caption",text:r,x:c,y:d,width:eb.lz,height:eb.OF};t3(e=>[...e,m]),eA([u]),e_(u)},[eg,tW,t3]),nU=(0,o.useCallback)((e,t)=>{var n,a;if(!eg)return;let r=e.trim();if(!r)return;let l=null!=(a=null==(n=ei.current)?void 0:n.getViewportCenterWorld())?a:{x:0,y:0},s=lP(),i={id:s,kind:"video",src:r,fileName:(null==t?void 0:t.trim())||"generated-video-".concat(Date.now(),".mp4"),mimeType:"video/mp4",x:l.x-eb.HT/2,y:l.y-eb._q/2,width:eb.HT,height:eb._q,metadata:th.current?{sequenceId:th.current,runId:lP(),kind:"generated_video",sourceStep:"direct_video_generation"}:void 0};t3(e=>[...e,i]),eA([s]),e_(s)},[eg,t3]),nP=(0,o.useCallback)(()=>{var e,t;if(!eg)return;let n=null!=(t=null==(e=ei.current)?void 0:e.getViewportCenterWorld())?t:{x:0,y:0},a=lP(),r={id:a,kind:"text",fileName:"Text note",text:"",x:n.x-eb.lz/2,y:n.y-eb.OF/2,width:eb.lz,height:eb.OF};t3(e=>[...e,r]),eA([a]),e_(a)},[eg,!1,t3]),nB=(0,o.useCallback)((e,t)=>{let n=tm.current.get(e);n&&(t<1||t>n.pageCount||(tp.current.set(e,t),tg(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n}),n.renderPage(t,1080).then(n=>{let a=tp.current.get(e)===t;tg(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),n&&a&&t3(a=>a.map(a=>a.id!==e||"pdf"!==a.kind?a:{...a,previewDataUrl:n.dataUrl,currentPage:t}))})))},[!1,t3]);if("gallery"===ed){let e=()=>{tu(null),ti(!0)};return(0,a.jsxs)("div",{className:"flex h-full w-full flex-col bg-cloud-slate",children:[en&&!F?(0,a.jsxs)("header",{className:"flex flex-shrink-0 items-center gap-3 border-b border-auth-hairline bg-white px-4 py-2",children:[(0,a.jsx)(y.$,{variant:"ghost",asChild:!0,withLeftArrow:!0,children:(0,a.jsx)(l(),{href:"launchpad"===D?lA:null!=et?et:"/dashboard",children:"launchpad"===D||et?"Back to Launchpad":"Back to Dashboard"})}),(0,a.jsx)("div",{className:"h-5 w-px flex-shrink-0 bg-auth-hairline"}),(0,a.jsx)("h1",{className:"truncate text-sm font-bold text-midnight-logic",children:"Ad Maker"})]}):null,(0,a.jsx)(lx,{open:ts,onOpenChange:ti,brandingOffer:nA,creating:to,createError:td,onCreate:nl}),(0,a.jsx)("div",{className:"mx-auto flex min-h-0 w-full max-w-[1248px] flex-1 flex-col overflow-y-auto px-4 pb-8 pt-6 lg:px-8",children:(0,a.jsxs)("div",{className:"flex flex-col gap-[22px] rounded-[20px] border border-auth-hairline bg-white p-6 lg:px-8 lg:py-7",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-5 px-1 lg:flex-row lg:flex-nowrap lg:items-start lg:justify-between",children:[(0,a.jsxs)("div",{className:"min-w-0 max-w-[40rem] lg:flex-1",children:[(0,a.jsx)("h1",{className:"text-[1.45rem] font-extrabold tracking-[-0.02em] text-midnight-logic",children:"Your ad boards"}),(0,a.jsx)("p",{className:"mt-1.5 text-pretty text-[0.92rem] font-medium leading-[1.55] text-auth-ink-soft",children:"Each board is a canvas for one campaignâs ad creatives. Open a board to keep working, or start a new one."})]}),(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2.5 lg:shrink-0 lg:flex-nowrap",children:[tb||tR.length>0?(0,a.jsxs)("div",{className:"relative w-full sm:w-[230px]",children:[(0,a.jsx)(c.A,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-auth-muted","aria-hidden":!0}),(0,a.jsx)("input",{type:"search",value:tE,onChange:e=>tU(e.target.value),placeholder:"Search boards","aria-label":"Search boards",className:"h-12 w-full rounded-xl border border-control-border bg-white pl-10 pr-3 text-[0.86rem] font-medium text-midnight-logic transition-colors placeholder:text-auth-placeholder hover:border-signal-blue focus-visible:border-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2"})]}):null,(0,a.jsxs)("button",{type:"button",disabled:!(null==G?void 0:G.internalId),onClick:e,className:"inline-flex min-h-[48px] shrink-0 items-center gap-2 rounded-xl bg-signal-blue px-[22px] text-[0.88rem] font-bold text-white shadow-[0_6px_16px_rgba(33,87,255,0.25)] transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:opacity-60",children:[(0,a.jsx)(d.A,{className:"h-4 w-4","aria-hidden":!0}),"Create board"]})]})]}),(0,a.jsxs)("ol",{className:"grid items-center gap-5 rounded-2xl border border-auth-field-border bg-auth-field px-[22px] py-4 md:grid-cols-[auto_1fr_1fr_1fr]",children:[(0,a.jsxs)("li",{className:"text-[0.68rem] font-extrabold uppercase leading-[1.25] tracking-[0.1em] text-anchor-blue md:whitespace-nowrap",children:["How it",(0,a.jsx)("br",{className:"hidden md:inline"})," works"]}),lI.map((e,t)=>(0,a.jsxs)("li",{className:"flex items-center gap-3 border-auth-field-border md:border-l md:pl-5",children:[(0,a.jsx)("span",{"aria-hidden":!0,
1className:"grid h-[26px] w-[26px] shrink-0 place-items-center rounded-full bg-signal-blue text-[0.68rem] font-extrabold text-white",children:t+1}),(0,a.jsxs)("span",{className:"min-w-0",children:[(0,a.jsx)("span",{className:"block text-[0.84rem] font-extrabold text-midnight-logic",children:e.title}),(0,a.jsx)("span",{className:"block text-[0.76rem] font-medium leading-[1.45] text-auth-ink-soft",children:e.body})]})]},e.title))]}),(0,a.jsxs)("section",{className:"flex min-h-0 flex-col gap-3.5",children:[(0,a.jsxs)("h2",{className:"text-[0.68rem] font-extrabold uppercase tracking-[0.12em] text-auth-muted",children:["Your boards",tb&&0===tR.length||tw?null:" \xb7 ".concat(tR.length)]}),tb&&0===tR.length?(0,a.jsx)(lo,{}):tw?(0,a.jsxs)("div",{role:"alert",className:"flex flex-col items-center gap-3 rounded-2xl border border-auth-hairline bg-white px-6 py-8 text-center",children:[(0,a.jsx)("p",{className:"text-[0.94rem] font-bold text-midnight-logic",children:"Your boards didn't load"}),(0,a.jsx)("p",{className:"max-w-[26rem] text-[0.86rem] font-medium leading-[1.5] text-auth-ink-soft",children:"Nothing has been lost. Check your connection, then try again."}),(0,a.jsx)("button",{type:"button",onClick:()=>tv({requestPolicy:"network-only"}),className:"mt-1 inline-flex min-h-[44px] items-center gap-2 rounded-xl border-[1.5px] border-control-border bg-white px-[18px] text-[0.88rem] font-bold text-midnight-logic transition-colors hover:border-signal-blue hover:text-signal-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2",children:"Try again"})]}):0===tR.length?(0,a.jsxs)("div",{className:"flex flex-col items-center gap-3 rounded-2xl border-[1.5px] border-dashed border-auth-field-border bg-white px-6 py-8 text-center",children:[(0,a.jsx)("p",{className:"text-[0.94rem] font-bold text-midnight-logic",children:"No boards yet"}),(0,a.jsx)("p",{className:"max-w-[26rem] text-[0.86rem] font-medium leading-[1.5] text-auth-ink-soft",children:"A board is where you gather the photos for one campaign and generate its ad creatives."}),(0,a.jsxs)("button",{type:"button",disabled:!(null==G?void 0:G.internalId),onClick:e,className:"mt-1 inline-flex min-h-[44px] items-center gap-2 rounded-xl bg-signal-blue px-[18px] text-[0.88rem] font-bold text-white transition-colors hover:bg-anchor-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:opacity-60",children:[(0,a.jsx)(d.A,{className:"h-4 w-4","aria-hidden":!0}),"Create your first board"]})]}):0===tP.length?(0,a.jsxs)("p",{className:"rounded-2xl border border-auth-hairline bg-white px-5 py-6 text-[0.88rem] font-medium text-auth-ink-soft",children:["No board matches â",tE.trim(),"â."]}):(0,a.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[tP.map(e=>{var t;return(0,a.jsx)(ls,{board:e,href:en?void 0:tO("".concat(lk,"/").concat(encodeURIComponent(e.id))),onOpen:en?()=>tF(e.id):void 0,previewUrls:null!=(t=tB[e.id])?t:[],previewLoading:tD&&void 0===tB[e.id],onBoardsChanged:()=>tv({requestPolicy:"network-only"}),formatDate:l1},e.id)}),tE.trim()?null:(0,a.jsxs)("button",{type:"button",disabled:!(null==G?void 0:G.internalId),onClick:e,className:"flex min-h-[260px] flex-col items-center justify-center gap-2.5 rounded-[18px] border-[1.5px] border-dashed border-control-border bg-transparent transition-colors hover:border-signal-blue hover:bg-ad-maker-field focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-signal-blue focus-visible:ring-offset-2 disabled:opacity-60",children:[(0,a.jsx)("span",{"aria-hidden":!0,className:"grid h-12 w-12 place-items-center rounded-full bg-auth-field text-anchor-blue",children:(0,a.jsx)(d.A,{className:"h-5 w-5"})}),(0,a.jsx)("span",{className:"text-[0.9rem] font-extrabold text-anchor-blue",children:"Create a new board"}),(0,a.jsx)("span",{className:"text-[0.76rem] font-medium text-auth-muted",children:"Start a fresh campaign canvas"})]})]})]})]})})]})}return eg?(0,a.jsxs)("div",{className:"flex h-full w-full flex-col overflow-hidden bg-cloud-slate",children:[(0,a.jsxs)("header",{className:"flex h-[60px] flex-shrink-0 items-center justify-between gap-3 border-b border-auth-hairline bg-white px-4 lg:px-6",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[en?(0,a.jsxs)("button",{type:"button",onClick:tq,className:lS,children:[(0,a.jsx)(u.A,{className:"h-4 w-4","aria-hidden":!0}),"Boards"]}):(0,a.jsxs)(l(),{href:tO(lk),className:lS,children:[(0,a.jsx)(u.A,{className:"h-4 w-4","aria-hidden":!0}),"Boards"]}
1),(0,a.jsx)("span",{"aria-hidden":!0,className:"hidden h-6 w-px shrink-0 bg-auth-hairline sm:block"}),(0,a.jsxs)("h1",{className:"flex min-w-0 items-baseline gap-2.5 text-[1.05rem] font-extrabold text-midnight-logic",children:[(0,a.jsx)("span",{className:"shrink-0",children:"Ad Maker"}),(0,a.jsxs)("span",{className:"truncate text-[0.92rem] font-semibold text-auth-ink-soft",children:["/ ",null!=(I=null==tK?void 0:tK.name)?I:"Untitled board"]})]}),(0,a.jsx)("span",{className:"shrink-0 rounded-full bg-auth-field px-2.5 py-1 text-[0.62rem] font-extrabold uppercase tracking-[0.06em] text-anchor-blue",children:"Beta"})]}),(0,a.jsxs)("div",{className:"flex shrink-0 items-center gap-2.5",children:["studio"===em&&aV(eh)?(0,a.jsxs)("span",{className:"mr-1.5 hidden items-center gap-1.5 text-[0.8rem] font-semibold text-auth-ink-soft md:inline-flex",children:[(0,a.jsx)(m.A,{className:"h-3.5 w-3.5 text-anchor-blue","aria-hidden":!0}),"Saved ",aV(eh)]}):null,"studio"!==em?(0,a.jsx)(rQ,{value:em,onChange:tL,boardItemCount:tW.length}):null,lC&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(j.A,{tool:lC,size:"sm",showText:!1}),(0,a.jsx)(N.A,{tool:lC,size:"sm",showText:!1})]}),en?null:(0,a.jsx)(v.v,{organizationalUnitId:H,userId:null==G?void 0:G.internalId,isParticipant:null!=(T=null==Y?void 0:Y.isParticipant)&&T})]})]}),(0,a.jsx)("div",{ref:eU,className:"relative min-h-0 flex-1",onPointerDown:"board"===em?nw:void 0,onPointerMove:"board"===em?nj:void 0,onPointerUp:"board"===em?nN:void 0,onPointerCancel:"board"===em?nN:void 0,onDragOver:e=>{"board"===em&&e.preventDefault()},onDrop:"board"===em?nT:void 0,children:"campaign_manager"===em?(0,a.jsx)(ap,{boardId:eg,boardName:null!=(M=null==tK?void 0:tK.name)?M:"Untitled campaign",initialStart:ew,onBoardStateChanged:t2,onRunningChange:t1}):"studio"===em?(0,a.jsx)(rX,{boardId:eg,onBoardStateChanged:t2,surfaceSwitch:(0,a.jsx)(rQ,{value:em,onChange:tL,boardItemCount:tW.length}),onSavedAtChange:ef,onOpenInBoard:()=>{t2(),ep("board")}}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(J,{ref:ei,onViewportChange:ec,disableBackgroundPan:!0,children:[(0,a.jsx)(lR,{}),tW.map(e=>(0,a.jsx)(eS,{item:e,isSelected:ek.includes(e.id),interactive:!0,onMove:nc,onSelect:nf,onUpdateText:ng,onInteractionStart:nd,onInteractionEnd:nu},e.id))]}),tY&&ek.length>0&&(0,a.jsx)(eT,{bounds:tY,viewport:eo,onResizeStart:nm,onResize:np,onResizeEnd:nh}),tV&&tY&&(0,a.jsx)(eP,{item:tV,bounds:tY,selectedCount:tH.length,viewport:eo,onRename:nx,onDownload:nb,onDelete:ny,onDeleteMany:nv}),(null==tG?void 0:tG.kind)==="pdf"&&(0,a.jsx)(eO,{item:tG,viewport:eo,onChangePage:nB,isPageLoading:tf.has(tG.id)}),e2&&(0,a.jsx)("div",{className:"pointer-events-none absolute inset-0 z-30 flex items-center justify-center bg-white/40 backdrop-blur-md",children:(0,a.jsxs)("div",{className:"flex flex-col items-center gap-3",children:[(0,a.jsx)(p.A,{className:"h-8 w-8 animate-spin text-charcoal-400"}),(0,a.jsx)("span",{className:"text-sm font-medium text-charcoal-500",children:"Loading boardâ¦"})]})}),tQ?(0,a.jsx)(lw,{onAddPhoto:nt}):null,(0,a.jsx)(ne,{boardId:eg,contextId:V,items:tW,itemFilesById:tJ,onRunningChange:t1,onMaterializedBoardItems:t5,onGeneratedStoryboardFrames:nM,onGeneratedStoryboardTransitions:nR,onGeneratedCaption:nE,onGeneratedVideo:nU,selectedItemIds:ek,onClearSelection:()=>eA([]),onRequestOpenAssetLibrary:nt}),eI&&(0,a.jsx)("div",{className:"pointer-events-none absolute z-20 border border-signal-blue bg-signal-blue/10",style:{left:Math.min(eI.startX,eI.endX),top:Math.min(eI.startY,eI.endY),width:Math.abs(eI.endX-eI.startX),height:Math.abs(eI.endY-eI.startY)},"aria-hidden":!0}),(0,a.jsxs)("div",{className:"absolute left-4 top-4 z-10 flex flex-wrap items-center gap-2",onPointerDown:e=>e.stopPropagation(),children:[(0,a.jsx)(X,{zoom:eo.zoom,onZoomIn:ns,onZoomOut:ni,onReset:no}),tX?(0,a.jsx)("p",{className:"pointer-events-none hidden rounded-xl border border-auth-hairline bg-white/90 px-3.5 py-2 text-[0.72rem] font-semibold text-auth-ink-soft shadow-soft backdrop-blur lg:block",children:"Drag to select \xb7 â/Ctrl+C copy \xb7 â/Ctrl+V paste \xb7 scroll to pan \xb7 â/Ctrl + scroll to zoom"}):null]}),(0,a.jsxs)(Q,{children:[(0,a.jsx)(er,{recentAssets:tZ,onOpenLibrary:nt,onQuickAddAsset:e=>void nk([e]),disabled:!1}),(0,a.jsx)(el,{onAddText:nP,disabled:!1})]})]})}),(0,a.jsx)(rZ.A,{open:eq,assets:eJ,loading:tC,disabled:!1,deleteBusy:e0,onOpenChange:e$,onUploadFiles:e=>void n_(e),onAddAssets:e=>void nk(e),onDeleteAssets:na,onUploadProductUrl:(e,t,n,a,r)=>void nI(e,t,n,a,r),savingProductUrl:eQ}),(0,a.jsx)(r5,{pendingUploads:eH,saving:eV,onSubmit:(e,t)=>
1void nC(e,t),onCancelAll:nS,onUploadFiles:e=>void n_(e)}),t0&&(0,a.jsx)("div",{className:"fixed bottom-4 right-4 z-[60] max-w-sm rounded-lg border border-red-200 bg-white px-4 py-3 text-sm font-semibold text-red-700 shadow-medium",children:t0})]}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center bg-charcoal-50",children:en?(0,a.jsx)(y.$,{type:"button",onClick:tq,children:"Back to boards"}):(0,a.jsx)(y.$,{asChild:!0,children:(0,a.jsx)(l(),{href:tO(lk),children:"Back to boards"})})})}function lR(){return(0,a.jsx)("div",{className:"absolute flex h-2 w-2 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-charcoal-300",style:{left:0,top:0},"aria-hidden":!0})}function lE(e,t){let n=Math.floor(t/4);return{x:e.x+t%4*290,y:e.y+230*n}}async function lU(e,t){let n=[],a=new Map,r=[],l=[];for(let s=0;s<e.length;s+=1){let i=e[s];try{let e,o=i;if((0,r8.Fk)(i)&&!(0,r8.Q)(i)){let t=await lD(i);o=t.asset,e=t.file,r.push(o)}let c=lE(t,s);if(lz(o)){let t=await lq(o,c.x,c.y,0,e);if(!t){l.push(o.name);continue}n.push(t.item),e&&a.set(t.item.id,e)}else if((0,r8.Q)(o))n.push(lK(o,c.x,c.y,0));else if((0,r4.U$)(o)||lF(o)){let t=l$(o,c.x,c.y,0);n.push(t),e&&a.set(t.id,e)}else{let t=lW(o,c.x,c.y,0);n.push(t),e&&a.set(t.id,e)}}catch(e){l.push(i.name),(0,r6.Ml)("branding.import.assetFailed",{asset:(0,r6.BT)(i),message:e instanceof Error?e.message:String(e)})}}return{items:n,filesByItemId:a,materializedAssets:r,failedAssetNames:l}}function lP(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^16*Math.random()>>Number(e)/4).toString(16))}function lB(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}async function lD(e){let t=(0,r8.X9)(e);if(!t)throw(0,r6.Ml)("materialize.noUrl",{asset:(0,r6.BT)(e)}),Error("That Brand Studio asset has no downloadable file.");(0,r6.Rt)("materialize.download.start",{asset:(0,r6.BT)(e),downloadUrl:(0,r6.Rq)(t)});let n=await (0,ey.Qz)(t);if(!n)throw(0,r6.Ml)("materialize.download.failed",{asset:(0,r6.BT)(e),downloadUrl:(0,r6.Rq)(t)}),Error("Could not download ".concat(e.name,"."));lz(e)&&await lO(n,e.name),(0,r6.Rt)("materialize.download.ok",{name:e.name,blobType:n.type,blobSize:n.size});let a=new File([n],e.fileName||e.name,{type:e.mimeType||n.type||"application/octet-stream"}),r=(0,r4.We)({...e.metadata,source:"brand-studio-library-import",deferPdfPreview:!1},"string"==typeof e.metadata.brandKitOrganizationId?e.metadata.brandKitOrganizationId:null);try{var l;let t=await (0,ta.QR)([a],{name:e.name,description:e.description,role:e.role,width:e.width,height:e.height,metadata:r},[{width:e.width,height:e.height,metadata:r}]);return(0,r6.Rt)("materialize.upload.ok",{from:e.id,savedId:t.id,savedUrl:(0,r6.Rq)(null!=(l=t.url)?l:"")}),{asset:t,file:a}}catch(t){throw(0,r6.Ml)("materialize.upload.failed",{asset:(0,r6.BT)(e),fileName:a.name,fileSize:a.size,message:t instanceof Error?t.message:String(t)}),t}}function lz(e){return"application/pdf"===e.mimeType||e.fileName.toLowerCase().endsWith(".pdf")}async function lO(e,t){let n=new Uint8Array(await e.slice(0,5).arrayBuffer());if(n.length>=4&&"%PDF"===String.fromCharCode(...n.slice(0,4)))return;let a=await e.text().catch(()=>"");if(a.trim().startsWith("{"))try{let e=JSON.parse(a);if(e.error)throw Error(e.details?"".concat(e.error,": ").concat(e.details):e.error)}catch(e){if(e instanceof SyntaxError);else throw e}throw Error("".concat(t," did not download as a PDF. Generate or save the brand book in Brand Studio first, then try again."))}function lF(e){return e.mimeType.startsWith("image/")&&"image/svg+xml"!==e.mimeType&&!e.fileName.toLowerCase().endsWith(".svg")}async function lL(e,t){if(!e)return;let n=await fetch(e);if(!n.ok)throw Error("Download fetch failed");let a=await n.blob();(0,i.saveAs)(a,t||"asset")}async function lq(e,t,n,a,r){let l,s=lP(),i=24*a,o=0,c=null;if(r)o=r.size,l=URL.createObjectURL(r),c=await (0,lt._)(r);else{if(!e.url)return null;let t=await (0,ey.Qz)(e.url);if(!t)return null;o=t.size,l=URL.createObjectURL(t),c=await (0,lt._)(new File([t],e.fileName||"document.pdf",{type:"application/pdf"}))}if(!c)return URL.revokeObjectURL(l),null;let d=await c.renderPage(1,eb.uj);if(!d)return c.dispose(),URL.revokeObjectURL(l),null;let u=d.width,m=d.height,p=Math.min(1,eb.uj/Math.max(u,m)),h=Math.max(80,Math.round(u*p)),f=Math.max(80,Math.round(m*p));return{item:{id:s,kind:"pdf",fileName:e.fileName||e.name,sizeBytes:o,assetId:e.id,asset:e,objectUrl:l,previewDataUrl:d.dataUrl,pageCount:c.pageCount,currentPage:1,x:t-h/2+i,y:n-f/2+i,width:h,height:f},handle:c}}function l$(e,t,n,a){var r;let l=24*a,s=e.width&&e.width>0?e.width:eb.dT,i=e.height&&e.height>0?e.height:eb.dT,o=Math.min(1,eb.dT/Math.max(s,i)),c=Math.max(80,Math.round(s*o)),d=Math.max(80,Math.round(i*o));return{id:lP(),kind:"image",src:null!=(r=e.url)?r:"",fileName:e.fileName||e.name,assetId:e.id,asset:e,x:t-c/2+l,y:n-d/2+l,width:c,height:d}}function lK(e,t,n,a){let r=24*a,l="string"==typeof e.metadata.fontFamily?e.metadata.fontFamily:e.name,s="body"===e.metadata.fontRole?"body":"display",i=Array.isArray(e.metadata.fontWeights)?e.metadata.fontWeights.filter(e=>"number"==typeof e):[],o="string"==typeof e.metadata.googleFontsHref?e.metadata.googleFontsHref:null;return{id:lP(),kind:"font",fileName:e.fileName||e.name,fontFamily:l,fontRole:s,googleFontsHref:o,weights:i,assetId:e.id,asset:e,x:t-eb.wr/2+r,y:n-eb.v_/2+r,width:eb.wr,height:eb.v_}}function lW(e,t,n,a){var r;let l=24*a;return{id:lP(),kind:"file",fileName:e.fileName||e.name,assetId:e.id,asset:e,mimeType:e.mimeType||"application/octet-stream",sizeBytes:e.sizeBytes||0,objectUrl:null!=(r=e.url)?r:"",x:t-110+l,y:n-70+l,width:220,height:140}}async function lJ(e){let t=await Promise.all(e.map(lG)),n=new Map,a=new Map,r=[];
1return t.forEach(e=>{(null==e?void 0:e.item)&&(r.push(e.item),e.pdfHandle&&n.set(e.item.id,e.pdfHandle),e.file&&a.set(e.item.id,e.file))}),{items:r,pdfHandles:n,filesByItemId:a}}async function lG(e){if(!e.asset||!lz(e.asset))return{item:lH(e)};let t="string"==typeof e.state.fileName?e.state.fileName:e.asset.fileName||e.asset.name,n=Math.max(1,Number(e.state.currentPage)||1);if(!e.asset.url)return{item:lH(e)};let a=null,r=null;try{let l=await (0,ey.Qz)(e.asset.url);if(!l)throw Error("PDF fetch failed");let s=new File([l],t||"document.pdf",{type:e.asset.mimeType||l.type||"application/pdf"});if(a=URL.createObjectURL(l),!(r=await (0,lt._)(s)))throw Error("PDF could not be parsed");let i=Math.min(n,r.pageCount),o=await r.renderPage(i,eb.uj);if(!o)throw Error("PDF page could not be rendered");return{item:{id:e.id,kind:"pdf",fileName:t,sizeBytes:e.asset.sizeBytes||l.size,assetId:e.asset.id,asset:e.asset,objectUrl:a,previewDataUrl:o.dataUrl,pageCount:r.pageCount,currentPage:i,x:e.x,y:e.y,width:e.width,height:e.height,metadata:lY(e.state)},pdfHandle:r,file:s}}catch(t){return"undefined"!=typeof console&&console.warn("[ad-maker] Failed to hydrate persisted PDF board item:",t),r&&r.dispose(),a&&URL.revokeObjectURL(a),{item:lH(e)}}}function lH(e){var t,n,a,r,l,s;let i=lY(e.state);if("text"===e.kind&&(null==i?void 0:i.sourceKind)==="email_html"){let l="string"==typeof e.state.text?e.state.text:"",s=(e,t)=>{let n="".concat(e,":\n"),a=l.indexOf(n);if(a<0)return"";let r=a+n.length,s=t.map(e=>l.indexOf("\n\n".concat(e,":\n"),r)).filter(e=>e>=0),i=s.length>0?Math.min(...s):l.length;return l.slice(r,i).trim()},o=s("HTML email",["Notes"]);if(o){let c=(null==(n=l.match(/^Subject:\s*(.+)$/m))||null==(t=n[1])?void 0:t.trim())||"",d=(null==(r=l.match(/^Preheader:\s*(.+)$/m))||null==(a=r[1])?void 0:a.trim())||"",u="string"==typeof i.subject?i.subject:c;return{id:e.id,kind:"html",fileName:"string"==typeof e.state.fileName?e.state.fileName:u||"Email marketing draft",html:o,subject:u,preheader:d,plainText:s("Plain text",["HTML email","Notes"]),x:e.x,y:e.y,width:Math.max(e.width,680),height:Math.max(e.height,760),metadata:i}}}if("html"===e.kind){let t="string"==typeof e.state.subject?e.state.subject:"",n="string"==typeof e.state.fileName?e.state.fileName:t||"Email marketing draft";return{id:e.id,kind:"html",fileName:n,html:"string"==typeof e.state.html?e.state.html:"",subject:t,preheader:"string"==typeof e.state.preheader?e.state.preheader:"",plainText:"string"==typeof e.state.plainText?e.state.plainText:"string"==typeof e.state.text?e.state.text:"",x:e.x,y:e.y,width:e.width,height:e.height,metadata:i}}if("text"===e.kind){let t="string"==typeof e.state.text?e.state.text:"",n="string"==typeof e.state.fileName?e.state.fileName:t.split(/\s+/).slice(0,6).join(" ")||"Text note";return{id:e.id,kind:"text",fileName:n,text:t,x:e.x,y:e.y,width:e.width,height:e.height,metadata:i}}if("image"===e.kind&&e.asset){let t="string"==typeof e.state.fileName?e.state.fileName:e.asset.fileName||e.asset.name,n={...e.asset,role:"string"==typeof e.asset.role?e.asset.role:"other"};return{id:e.id,kind:"image",src:null!=(l=n.url)?l:"",fileName:t,assetId:e.asset.id,asset:n,x:e.x,y:e.y,width:e.width,height:e.height,metadata:lY(e.state)}}if("font"===e.kind&&e.asset){let t="string"==typeof e.state.fileName?e.state.fileName:e.asset.fileName||e.asset.name,n="string"==typeof e.state.fontFamily?e.state.fontFamily:"string"==typeof e.asset.metadata.fontFamily?e.asset.metadata.fontFamily:e.asset.name,a="body"===e.state.fontRole||"body"===e.asset.metadata.fontRole?"body":"display",r=Array.isArray(e.state.weights)?e.state.weights.filter(e=>"number"==typeof e):Array.isArray(e.asset.metadata.fontWeights)?e.asset.metadata.fontWeights.filter(e=>"number"==typeof e):[],l="string"==typeof e.state.googleFontsHref?e.state.googleFontsHref:"string"==typeof e.asset.metadata.googleFontsHref?e.asset.metadata.googleFontsHref:null;return{id:e.id,kind:"font",fileName:t,fontFamily:n,fontRole:a,googleFontsHref:l,weights:r,assetId:e.asset.id,asset:e.asset,x:e.x,y:e.y,width:e.width,height:e.height,metadata:lY(e.state)}}if(("file"===e.kind||"pdf"===e.kind)&&e.asset){let t="string"==typeof e.state.fileName?e.state.fileName:e.asset.fileName||e.asset.name;return{id:e.id,kind:"file",fileName:t,assetId:e.asset.id,asset:e.asset,mimeType:e.asset.mimeType||"application/octet-stream",sizeBytes:e.asset.sizeBytes||0,objectUrl:null!=(s=e.asset.url)?s:"",x:e.x,y:e.y,width:e.width,height:e.height,metadata:lY(e.state)}}if("video"===e.kind){let t="string"==typeof e.state.fileName?e.state.fileName:"generated-video.mp4",n="string"==typeof e.state.src?e.state.src:"",a="str
1ing"==typeof e.state.mimeType?e.state.mimeType:"video/mp4";return{id:e.id,kind:"video",src:n,fileName:t,mimeType:a,x:e.x,y:e.y,width:e.width,height:e.height,metadata:lY(e.state)}}return null}function lY(e){let t=e.metadata;return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}function lV(e){let t=null==e?void 0:e.metadata;if(!t||"object"!=typeof t)return null;let n=String(t.kind||"");if(!["storyboard_frame","storyboard_transition","storyboard_video","generated_video"].includes(n))return null;let a=String(t.sequenceId||"").trim(),r=String(t.runId||"").trim();return a?{sequenceId:a,runId:r,kind:n,frameIndex:"number"==typeof t.frameIndex?t.frameIndex:void 0,startFrameIndex:"number"==typeof t.startFrameIndex?t.startFrameIndex:void 0,endFrameIndex:"number"==typeof t.endFrameIndex?t.endFrameIndex:void 0,prompt:"string"==typeof t.prompt?t.prompt:void 0,sourceStep:"string"==typeof t.sourceStep?t.sourceStep:void 0,sourceItemId:"string"==typeof t.sourceItemId?t.sourceItemId:void 0,title:"string"==typeof t.title?t.title:void 0,description:"string"==typeof t.description?t.description:void 0,camera:"string"==typeof t.camera?t.camera:void 0,continuityAnchor:"string"==typeof t.continuityAnchor?t.continuityAnchor:void 0,ctaMoment:"string"==typeof t.ctaMoment?t.ctaMoment:void 0,narrativePurpose:"string"==typeof t.narrativePurpose?t.narrativePurpose:void 0,previousStateContinuity:"string"==typeof t.previousStateContinuity?t.previousStateContinuity:void 0,nextFrameSetup:"string"==typeof t.nextFrameSetup?t.nextFrameSetup:void 0,visualHandoff:"string"==typeof t.visualHandoff?t.visualHandoff:void 0}:null}function lX(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:15;return!(e.x+e.width+n<=t.x||e.x>=t.x+t.width+n||e.y+e.height+n<=t.y||e.y>=t.y+t.height+n)}function lQ(e,t,n){let a=t.x;return e.map((r,l)=>{let s={...r,x:a,y:t.y+(n-r.height)/2};return a+=r.width,l<e.length-1&&(a+=290),s})}function lZ(e){"image"===e.kind&&e.src.startsWith("blob:")||"video"===e.kind&&e.src.startsWith("blob:")?URL.revokeObjectURL(e.src):("file"===e.kind||"pdf"===e.kind)&&URL.revokeObjectURL(e.objectUrl)}function l0(e){return new Promise((t,n)=>{let a=new Image;a.onload=()=>t({width:a.naturalWidth,height:a.naturalHeight}),a.onerror=n,a.src=e})}function l1(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}},83154:(e,t,n)=>{n.d(t,{Bc:()=>i,ZI:()=>d,k$:()=>c,m_:()=>o});var a=n(80601),r=n(67277),l=n(36240),s=n(64697);let i=l.Kq,o=l.bL,c=l.l9,d=r.forwardRef((e,t)=>{let{className:n,sideOffset:r=4,...i}=e;return(0,a.jsx)(l.ZL,{children:(0,a.jsx)(l.UC,{ref:t,sideOffset:r,className:(0,s.cn)("z-50 overflow-hidden rounded-lg border border-cloud-slate bg-midnight-logic px-3 py-2 text-xs font-bold text-white shadow-medium animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n),...i})})});d.displayName=l.UC.displayName}}]);
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.