PageSourceSearch

https://pingenerator.app/assets/CreateCampaign-DfjS_sWs.js

js pingenerator.app collected 2026-10-02 01:14:46 UTC 52,090 bytes, 1 lines download raw bytes

1import{j as e}from"./vendor-query-BySM1YRy.js";import{r as m,u as rs,d as is}from"./vendor-react-hdCwoW0Z.js";import{r as dt,B as _,L as B,E as ut,f as ns,a0 as Se,b as mt,aR as os,g as ls,u as cs,ae as ds,s as He,al as pe,t as Te,aS as us,o as Ze,A as ms,j as G,a4 as ps,n as Je,v as We,ai as hs,C as gs,y as xs,ak as fs}from"./index-Dx8dgW2R.js";import{C as vs}from"./ConnectedSourcePicker-BQkMiyxP.js";import{L as I}from"./label-7X-t8hK4.js";import{S as ae,a as re,b as ie,c as ne,d as L}from"./select-BiYCehR9.js";import{A as Xe,a as et,b as tt,u as bs}from"./useCampaigns-CooA8_FN.js";import{C as js}from"./circle-alert-DS3I68aJ.js";import{C as z,b as H,c as Z,a as O}from"./card-DSLSpSka.js";import{M as ys,N as ws,Q as Ns,g as pt,u as Ae,h as ge,l as Ee,U as _s,J as Cs,K as Is,X as ht,Y as Ss,G as Ts,Z as Es,_ as ks}from"./vendor-radix-Bnq4Vbxr.js";import{T as Ne}from"./textarea-BI9xFSI2.js";import{r as As,T as gt,a as Ps,g as Rs}from"./templateCopy-DVBOGNLu.js";import{c as _e}from"./campaignApi-Dsh6FRQh.js";import{u as $s}from"./useCampaign-Z3Ch_Lyy.js";import{u as Ms}from"./useQueueSettings-CODleXFd.js";import{u as Ls}from"./useScheduledPins-BhG9XY9B.js";import{A as st}from"./arrow-left-DhRNcJrR.js";import{S as Ds}from"./save-DyhSFEOF.js";import{I as at}from"./image-plus-DqsWrFR3.js";import{C as Bs}from"./copy-DyvSvnfm.js";import"./vendor-supabase-MEHSyf2E.js";import"./useConnectedSources-mOzz196m.js";import"./WalmartIcon-0Qskt3FN.js";import"./popover-gK7k74EB.js";import"./database-CBtEWomA.js";import"./globe-DyGbVkal.js";import"./SiEtsy-CBsiDVMV.js";import"./addDays-3KR_yGZ_.js";import"./startOfDay-DB61a6dQ.js";function zs(r){const{accounts:c,fetchBoards:u,connectPinterest:p,isConnecting:l}=dt(),[h,b]=m.useState(null),[S,n]=m.useState(null);m.useEffect(()=>{if(!r.accountId){b(null),n(null);return}let j=!0;const v=r.accountId;return b(null),n(v),u(v).then(y=>{j&&b({accountId:v,boards:y})}).finally(()=>{j&&n(null)}),()=>{j=!1}},[r.accountId,u]);const E=j=>{const v=c.find(y=>y.id===j);b(null),r.onAccountChange(j,(v==null?void 0:v.username)??"")};if(c.length===0)return e.jsxs("div",{className:"rounded-xl border border-dashed p-5 text-center",children:[e.jsx("p",{className:"text-sm font-semibold",children:"No Pinterest account connected"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"You can keep this campaign as a draft or connect Pinterest to schedule it."}),e.jsxs(_,{className:"mt-4 gap-2",variant:"outline",onClick:()=>void p(),disabled:l,children:[l?e.jsx(B,{className:"h-4 w-4 animate-spin"}):e.jsx(ut,{className:"h-4 w-4"}),"Connect Pinterest"]})]});const k=(h==null?void 0:h.accountId)===r.accountId?h.boards:[],T=S===r.accountId;return e.jsxs("div",{className:"grid gap-5 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Pinterest account"}),e.jsxs(ae,{value:r.accountId||void 0,onValueChange:E,disabled:r.disabled,children:[e.jsx(re,{children:e.jsx(ie,{placeholder:"Choose an account"})}),e.jsx(ne,{children:c.map(j=>e.jsxs(L,{value:j.id,children:["@",j.username]},j.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No account is selected automatically."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Pinterest board"}),e.jsxs(ae,{value:r.boardId||void 0,onValueChange:j=>{const v=k.find(y=>y.id===j);r.onBoardChange(j,(v==null?void 0:v.name)??"")},disabled:r.disabled||!r.accountId||T||(h==null?void 0:h.accountId)!==r.accountId,children:[e.jsx(re,{children:e.jsx(ie,{placeholder:T?"Loading boards…":r.accountId?"Choose a board":"Choose an account first"})}),e.jsx(ne,{children:k.map(j=>e.jsx(L,{value:j.id,children:j.name},j.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing the account clears the previous board."})]})]})}function Os({issues:r}){if(r.length===0)return e.jsxs(Xe,{className:"border-emerald-200 bg-emerald-50 text-emerald-900",children:[e.jsx(ns,{className:"h-4 w-4 text-emerald-600"}),e.jsx(et,{children:"Ready to schedule"}),e.jsx(tt,{children:"All campaign checks passed."})]});const c=r.some(u=>u.level==="error");return e.jsxs(Xe,{className:c?"border-red-200 bg-red-50":"border-amber-200 bg-amber-50",children:[c?e.jsx(js,{className:"h-4 w-4 text-red-600"}):e.jsx(Se,{className:"h-4 w-4 text-amber-600"}),e.jsx(et,{children:c?"Campaign needs attention":"Review these notes"}),e.jsx(tt,{children:e.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-4",children:r.map(u=>e.jsx("li",{children:u.message},u.id))})})]})}const Fs=ys,qs=ws,Gs=Ns;var Pe="Radio",[Us,xt]=pt(Pe),[Vs,Ks]=Us(Pe),ft=m.forwardRef((r,c)=>{const{__scopeRadio:u,name:p,checked:l=!1,required:h,disabled:b,value:S="on",onCheck:n,form:E,...k}=r,[T,j]=m.useState(null),v=Ae(c,q=>j(q)),y=m.useRef(!1),F=T?E||!!T.closest("form"):!0;return e.jsxs(Vs,{scope:u,checked:l,disabled:b,children:[e.jsx(ge.button,{type:"button",role:"radio","aria-checked":l,"data-state":yt(l),"data-disabled":b?"":void 0,disabled:b,value:S,...k,ref:v,onClick:Ee(r.onClick,q=>{l||n==null||n(),F&&(y.current=q.isPropagationStopped(),y.current||q.stopPropagation())})}),F&&e.jsx(jt,{control:T,bubbles:!y.current,name:p,value:S,checked:l,required:h,disabled:b,form:E,style:{transform:"translateX(-100%)"}})]})});ft.displayName=Pe;var vt="RadioIndicator",bt=m.forwardRef((r,c)=>{const{__scopeRadio:u,forceMount:p,...l}=r,h=Ks(vt,u);return e.jsx(_s,{present:p||h.checked,children:e.jsx(ge.span,{"data-state":yt(h.checked),"data-disabled":h.disabled?"":void 0,...l,ref:c})})});bt.displayName=vt;var Ys="RadioBubbleInput",jt=m.forwardRef(({__scopeRadio:r,control:c,checked:u,bubbles:p=!0,...l},h)=>{const b=m.useRef(null),S=Ae(b,h),n=Cs(u),E=Is(c);return m.useEffect(()=>{const k=b.current;if(!k)return;const T=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(T,"checked").set;if(n!==u&&v){const y=new Event("click",{bubbles:p});v.call(k,u),k.dispatchEvent(y)}},[n,u,p]),e.jsx(ge.input,{type:"radio","aria-hidden":!0,defaultChecked:u,...l,tabIndex:-1,ref:S,style:{...l.style,...E,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});jt.displayName=Ys;function yt(r){return r?"checked":"unchecked"}var Qs=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],xe="RadioGroup",[Hs,za]=pt(xe,[ht,xt]),wt=ht(),Nt=xt(),[Zs,Js]=Hs(xe),_t=m.forwardRef((r,c)=>{const{__scopeRadioGroup:u,name:p,defaultValue:l,value:h,required:b=!1,disabled:S=!1,orientation:n,dir:E,loop:k=!0,onValueChange:T,...j}=r,v=wt(u),y=Ss(E),[F,q]=Ts({prop:h,defaultProp:l??null,onChange:T,caller:xe});return e.jsx(Zs,{scope:u,name:p,required:b,disabled:S,value:F,onValueChange:q,children:e.jsx(Es,{asChild:!0,...v,orientation:n,dir:y,loop:k,
1children:e.jsx(ge.div,{role:"radiogroup","aria-required":b,"aria-orientation":n,"data-disabled":S?"":void 0,dir:y,...j,ref:c})})})});_t.displayName=xe;var Ct="RadioGroupItem",It=m.forwardRef((r,c)=>{const{__scopeRadioGroup:u,disabled:p,...l}=r,h=Js(Ct,u),b=h.disabled||p,S=wt(u),n=Nt(u),E=m.useRef(null),k=Ae(c,E),T=h.value===l.value,j=m.useRef(!1);return m.useEffect(()=>{const v=F=>{Qs.includes(F.key)&&(j.current=!0)},y=()=>j.current=!1;return document.addEventListener("keydown",v),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",v),document.removeEventListener("keyup",y)}},[]),e.jsx(ks,{asChild:!0,...S,focusable:!b,active:T,children:e.jsx(ft,{disabled:b,required:h.required,checked:T,...n,...l,name:h.name,ref:k,onCheck:()=>h.onValueChange(l.value),onKeyDown:Ee(v=>{v.key==="Enter"&&v.preventDefault()}),onFocus:Ee(l.onFocus,()=>{var v;j.current&&((v=E.current)==null||v.click())})})})});It.displayName=Ct;var Ws="RadioGroupIndicator",St=m.forwardRef((r,c)=>{const{__scopeRadioGroup:u,...p}=r,l=Nt(u);return e.jsx(bt,{...l,...p,ref:c})});St.displayName=Ws;var Tt=_t,Et=It,Xs=St;const kt=m.forwardRef(({className:r,...c},u)=>e.jsx(Tt,{className:mt("grid gap-2",r),...c,ref:u}));kt.displayName=Tt.displayName;const At=m.forwardRef(({className:r,...c},u)=>e.jsx(Et,{ref:u,className:mt("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",r),...c,children:e.jsx(Xs,{className:"flex items-center justify-center",children:e.jsx(os,{className:"h-2.5 w-2.5 fill-current text-current"})})}));At.displayName=Et.displayName;const he=["Basics","Source","Creatives","Destinations","Schedule","Review"],Ce=he.length-1,ea=r=>{const c=[...r];for(let u=c.length-1;u>0;u--){const p=Math.floor(Math.random()*(u+1));[c[u],c[p]]=[c[p],c[u]]}return c},Ie=new Map([["America/New_York","Eastern Time (ET)"],["America/Chicago","Central Time (CT)"],["America/Denver","Mountain Time (MT)"],["America/Los_Angeles","Pacific Time (PT)"],["Europe/London","London (GMT/BST)"],["Europe/Paris","Central European (CET)"],["Europe/Berlin","Berlin (CET)"],["Asia/Kolkata","India (IST)"],["Asia/Tokyo","Japan (JST)"],["Australia/Sydney","Sydney (AEST)"]]),rt=(()=>{const r=Intl.DateTimeFormat().resolvedOptions().timeZone,c=Intl.supportedValuesOf,u=c?c.call(Intl,"timeZone"):[...Ie.keys()];return Array.from(new Set([r,...Ie.keys(),...u])).map(l=>({value:l,label:Ie.get(l)||l.replaceAll("_"," ")}))})(),ta=r=>{if(!r||typeof r!="object")return!1;const c=r;return typeof c.id=="string"&&typeof c.image_url=="string"&&typeof c.source_type=="string"&&["blog","etsy","shopify","amazon","gumroad","walmart"].includes(c.source_type)},sa=r=>Array.isArray(r)?r.flatMap(c=>typeof c=="string"&&c.trim()?[c]:ta(c)?[c]:c&&typeof c=="object"&&typeof c.image_url=="string"?[c.image_url]:[]):[],ke=r=>typeof r=="string"?r:r.image_url,W=r=>typeof r=="string"?`url:${r}`:`asset:${r.id}`,X=r=>typeof r!="string",it=(r,c)=>({id:r.id,image_url:r.image_url,source_id:r.source_id,source_type:(c==null?void 0:c.source_type)??"blog",product_title:r.product_title,product_description:r.product_description,product_url:r.product_url,ai_template_title:r.ai_template_title,ai_template_description:r.ai_template_description,ai_template_prompt_version:r.ai_template_prompt_version,ai_template_status:r.ai_template_status}),nt=r=>!X(r)||r.ai_template_status!=="completed"||r.ai_template_prompt_version!==gt?null:Rs(r.ai_template_title,r.ai_template_description),aa=(r,c)=>{const u=c.filter(h=>ke(h)===r.image_url);if(u.length<=1)return u[0];const p=u.filter(h=>X(h)&&(h.product_url||"")===r.link);if(p.length===1)return p[0];const l=u.filter(h=>X(h)&&(h.product_title||"").trim().slice(0,100)===r.title);return l.length===1?l[0]:void 0},ra=(r,c)=>{const u=Te(r.html_content),p=Object.fromEntries(u.map(l=>[l.id,l.defaultValue]));return c&&u.forEach(l=>{const h=`${l.id} ${l.label}`.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);h.includes("headline")||h.includes("title")?p[l.id]=c.title:h.includes("description")&&(p[l.id]=c.description)}),p},ia=()=>({basics:{name:"",description:"",campaignType:"content",objective:"traffic"},source:{type:null,url:"",images:[]},brandKitId:null,destination:{accountId:"",accountName:"",boardId:"",boardName:""},schedule:{mode:"draft",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,itemTimes:{}}}),na=r=>new Promise((c,u)=>{const p=new FileReader;p.onload=()=>c(String(p.result).split(",")[1]??""),p.onerror=()=>u(new Error(`Could not read ${r.name}`)),p.readAsDataURL(r)}),oa=40,la=["description","body","subtitle","text"],Pt=r=>{const c=`${r.id} ${r.label}`.toLowerCase();return la.some(u=>c.includes(u))},ot=r=>Pt(r)?500:200,lt=r=>{if(!r)return"";const c=new Date(r),u=c.getTimezoneOffset()*6e4;return new Date(c.getTime()-u).toISOString().slice(0,16)};function Oa(){var Qe;const r=rs(),[c,u]=is(),p=c.get("campaignId"),{toast:l}=ls(),{workspace:h,effectiveUserId:b}=cs(),{createCampaign:S}=bs(),n=$s(p),E=((Qe=n.campaign)==null?void 0:Qe.id)??null,k=m.useRef(n.updateCampaign);k.current=n.updateCampaign;const{plan:T,creditsUsed:j,isTrialActive:v,refreshSubscription:y}=ds(),{accounts:F,isLoading:q,connectPinterest:Rt,isConnecting:Re}=dt(),V=F.length>0,[i,ee]=m.useState(ia),[N,K]=m.useState(0),[D,$t]=m.useState([]),[fe,oe]=m.useState(()=>new Set),[ve,Mt]=m.useState(12),[le,be]=m.useState({}),[w,R]=m.useState(!1),[$e,Me]=m.useState(!1),[te,je]=m.useState("saved"),[Lt,Le]=m.useState(!1),[De,Dt]=m.useState({}),ce=m.useRef(null),de=m.useRef(""),Bt=m.useRef(new Map),{settings:zt,getNextAvailableSlots:Ot}=Ms(b,i.destination.accountId||null),{scheduledPins:Ft,fetchScheduledPins:qt}=Ls(b,i.destination.accountId||null);m.useEffect(()=>{(async()=>{const{data:s,error:a}=await He.from("templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0,nullsFirst:!1}).order("created_at",{ascending:!0});if(!a&&s){const d=s.filter(o=>!pe(o.html_content));$t(d),oe(new Set(d.map(o=>o.id)))}})()},[]),m.useEffect(()=>{const t=n.campaign;if(!t||ce.current===t.id)return;const s=Object.fromEntries(n.items.filter(o=>o.scheduled_at).map(o=>[o.id,o.scheduled_at])),a={basics:{name:t.name,description:t.description??"",campaignType:t.campaign_type??"content",objective:t.objective??"traffic"},source:{type:t.source_type,url:t.source_url??"",images:sa(t.source_images)},brandKitId:t.brand_kit_id,destination:{accountId:t.pinterest_account_id??"",accountName:t.pinterest_account_name??"",boardId:t.default_board_id??"",boardName:t.default_board_name??""},schedule:{mode:t.schedule_mode,timezone:t.timezone,itemTimes:s}},d=Math.min(Ce,Math.max(0,t.current_step??0));ce.current=t.id,ee(a),K(d),de.current=JSON.stringify({form:a,step:d})},[n.campaign,n.items]);const Be=m.useCallback((t,s)=>({name:t.basics.name.trim(),description:t.basics.description.trim()||null,campaign_type:t.basics.campaignType,objective:t.basics.objective,source_type:t.source.type,source_url:t.source.url.trim()||null,source_images:t.source.images,brand_kit_id:t.brandKitId,pinterest_account_id:t.destination.accountId||null,pinterest_account_name:t.destination.accountName||null,default_board_id:t.destination.boardId||null,default_board_name:t.destination.boardName||null,schedule_mode:t.schedule.mode,timezone:t.schedule.timezone,current_step:s}),[]);m.useEffect(()=>{if(!E||ce.current!==E)return;const t=JSON.stringify({form:i,step:N});if(t===de.current)return;const s=window.setTimeout(async()=>{je("saving");try{await k.current(Be(i,N)),de.current=t,je("saved")}catch{je("error")}},700);return()=>window.clearTimeout(s)},[i,N,E,Be]);const A=(t,s)=>ee(a=>({...a,[t]:s})),ze=async()=>
1{if(p)return p;if(!i.basics.name.trim())throw new Error("Enter a campaign name first.");const t=await S({name:i.basics.name.trim(),description:i.basics.description.trim()||null,campaignType:i.basics.campaignType,objective:i.basics.objective,timezone:i.schedule.timezone});return ce.current=t.id,de.current=JSON.stringify({form:i,step:0}),u({campaignId:t.id},{replace:!0}),l({title:"Draft created",description:"Your campaign will now autosave."}),t.id};m.useEffect(()=>{i.source.images.length>0&&Le(!1)},[i.source.images.length]);const Oe=()=>i.source.images.length>0?!0:(Le(!0),l({title:"Choose source images",description:"Upload at least one image or choose a connected source before continuing.",variant:"destructive"}),!1),Gt=t=>{if(t>N&&t>1&&!Oe()){K(1);return}K(t)},Ut=async()=>{if(N===0&&!i.basics.name.trim()){l({title:"Campaign name required",variant:"destructive"});return}if(!(N===1&&!Oe())){if(N===2&&n.items.length===0){l({title:"Add at least one creative",variant:"destructive"});return}R(!0);try{await ze(),K(t=>Math.min(Ce,t+1))}catch(t){l({title:"Could not save draft",description:t instanceof Error?t.message:"Please try again.",variant:"destructive"})}finally{R(!1)}}},Vt=async()=>{if(i.source.url.trim()){Me(!0);try{const t=await xs(i.source.url.trim()),s=t.images.map(a=>a.url||a.src).filter(Boolean);A("source",{type:"url",url:t.url,images:s}),l({title:`${s.length} images found`})}catch(t){l({title:"Extraction failed",description:t instanceof Error?t.message:"Try another URL.",variant:"destructive"})}finally{Me(!1)}}},Kt=async t=>{if(!(t!=null&&t.length))return;const s=await ze();R(!0);try{const a=[];for(const d of Array.from(t)){if(!d.type.startsWith("image/"))continue;const o=await na(d);a.push(await _e.uploadAsset({campaignId:s,fileName:d.name,contentType:d.type,base64:o}))}A("source",{type:"upload",url:"",images:[...i.source.images,...a]})}catch(a){l({title:"Upload failed",description:a instanceof Error?a.message:"Please try again.",variant:"destructive"})}finally{R(!1)}},Fe=m.useCallback(async t=>{if(!b||!t.some(o=>typeof o=="string"))return t;const s=Array.from(new Set(t.filter(o=>typeof o=="string"))),a=[];for(let o=0;o<s.length;o+=100){const{data:g,error:x}=await He.from("user_images").select("*").eq("user_id",b).in("image_url",s.slice(o,o+100));if(x)throw x;a.push(...g??[])}const d=new Map;return a.forEach(o=>d.set(o.image_url,[...d.get(o.image_url)||[],o])),t.map(o=>{var x;if(typeof o!="string")return o;const g=(x=d.get(o))==null?void 0:x[0];return g?it(g):o})},[b]),qe=m.useCallback(async t=>{const s=new Map,a=Array.from(new Map(t.filter(X).map(o=>[o.id,o])).values());a.forEach(o=>{const g=nt(o);g&&s.set(W(o),g)});const d=a.filter(o=>!s.has(W(o)));if(d.length===0)return s;try{const o=await As({imageIds:d.map(x=>x.id),targetUserId:b||void 0}),g=o.copyByImageId;g.forEach((x,f)=>s.set(`asset:${f}`,x)),console.info("[TemplateCopy][Campaign] Applying validated copy to creatives",{copies:Array.from(g,([x,f])=>({imageId:x,...f})),pendingImageIds:o.pendingImageIds,failedImageIds:o.failedImageIds}),g.size>0&&ee(x=>({...x,source:{...x.source,images:x.source.images.map(f=>{if(typeof f=="string")return f;const $=g.get(f.id);return $?{...f,ai_template_title:$.title,ai_template_description:$.description,ai_template_prompt_version:gt,ai_template_status:"completed"}:f})}})),o.quota?l({title:o.quota.reason==="daily_request_limit"?"Daily AI generation limit reached":"AI generation rate limit reached",description:Ps(o.quota),variant:"destructive"}):(o.pendingImageIds.length>0||o.failedImageIds.length>0)&&l({title:"Some short text is still being prepared",description:"Generated copy was applied where ready; remaining creatives kept their template defaults."})}catch(o){console.warn("Campaign template-copy generation unavailable; using template defaults:",o),l({title:"Short template copy unavailable",description:"Creatives will use the template defaults. You can edit their text afterward."})}return s},[b,l]),C=m.useMemo(()=>D.filter(t=>fe.has(t.id)&&!pe(t.html_content)),[D,fe]),Yt=m.useMemo(()=>{const t=new Map;return D.forEach(s=>{t.set(s.id,Object.fromEntries(Te(s.html_content).map(a=>[a.id,a.defaultValue])))}),t},[D]),se=m.useMemo(()=>
1{if(!C.length||!i.source.images.length)return[];const t=[];C.forEach(o=>{i.source.images.forEach(g=>t.push({template:o,image:g}))});const s=new Set(n.items.flatMap(o=>{const g=aa(o,i.source.images);return g?[`${o.template_id||""}::${W(g)}`]:[]})),a=new Set,d=Math.min(50,Math.max(1,ve));return ea(t).filter(({template:o,image:g})=>{const x=`${o.id}::${W(g)}`;return s.has(x)||a.has(x)?!1:(a.add(x),!0)}).slice(0,d)},[C,i.source.images,n.items,ve]),Ge=(t,s,a,d=new Map)=>{if(pe(t.html_content))throw new Error("Multi-image templates are not supported in campaigns.");const o=d.get(W(s))??nt(s),g=X(s)?s:null;return{position:a,status:"draft",template_id:t.id,template_name:t.name,template_html:t.html_content,tag_values:ra(t,o),image_url:ke(s),title:((g==null?void 0:g.product_title)||(o==null?void 0:o.title)||"").trim().slice(0,100),description:((g==null?void 0:g.product_description)||(o==null?void 0:o.description)||"").trim().slice(0,500),link:((g==null?void 0:g.product_url)||"").trim(),pinterest_account_id:i.destination.accountId||null,board_id:i.destination.boardId||null,board_name:i.destination.boardName||null,scheduled_at:null}},Qt=async()=>{if(!C.length){l({title:"Select at least one template",variant:"destructive"});return}if(!i.source.images.length){l({title:"Add source images first",variant:"destructive"});return}const t=C[Math.floor(Math.random()*C.length)],s=i.source.images[Math.floor(Math.random()*i.source.images.length)];R(!0);try{const[a]=await Fe([s]),d=await qe([a]);await n.saveItem(Ge(t,a,n.items.length,d)),a!==s&&ee(o=>({...o,source:{...o.source,images:o.source.images.map(g=>g===s?a:g)}}))}catch(a){l({title:"Creative could not be added",description:a instanceof Error?a.message:"Please try again.",variant:"destructive"})}finally{R(!1)}},Ht=async()=>{if(!C.length){l({title:"Select at least one template",variant:"destructive"});return}if(!se.length){l({title:"No new combinations to add",description:"Select more templates or add source images. Existing combinations are skipped."});return}const t=se.map((a,d)=>({...a,position:n.items.length+d}));let s=0;R(!0);try{const a=await Fe(t.map(x=>x.image)),d=t.map((x,f)=>({...x,image:a[f]})),o=new Map(a.filter(X).map(x=>[x.image_url,x]));o.size>0&&ee(x=>({...x,source:{...x.source,images:x.source.images.map(f=>typeof f=="string"?o.get(f)??f:f)}}));const g=await qe(a);for(let x=0;x<d.length;
1x+=5){const f=d.slice(x,x+5),$=await Promise.allSettled(f.map(P=>n.saveItem(Ge(P.template,P.image,P.position,g))));s+=$.filter(P=>P.status==="fulfilled").length;const M=$.find(P=>P.status==="rejected");if((M==null?void 0:M.status)==="rejected")throw M.reason}l({title:`${s} creative${s===1?"":"s"} added`,description:"Templates and source images were paired randomly. You can review and edit each creative below."})}catch(a){l({title:s?`${s} creatives added before the batch stopped`:"Creatives could not be added",description:a instanceof Error?a.message:"Please try again. Already-added combinations will be skipped.",variant:"destructive"})}finally{R(!1)}},ye=async t=>{try{await n.saveItem(t)}catch(s){l({title:"Creative could not be saved",description:s instanceof Error?s.message:"Please try again.",variant:"destructive"})}},Zt=async t=>{try{await n.deleteItem(t)}catch(s){l({title:"Creative could not be removed",description:s instanceof Error?s.message:"Please try again.",variant:"destructive"})}},we=(t,s)=>{n.setItems(a=>a.map(d=>d.id===t?{...d,...s}:d))},Y=m.useCallback(t=>{if(!t)return[];const s=Bt.current,a=s.get(t);if(a)return a;const d=Te(t);if(s.size>=oa){const o=s.keys().next();o.done||s.delete(o.value)}return s.set(t,d),d},[]),ue=m.useMemo(()=>{const t=[];return n.items.forEach(s=>{Y(s.template_html).forEach(a=>{t.some(d=>d.id===a.id)||t.push(a)})}),t},[n.items,Y]),J=m.useMemo(()=>ue.map(t=>[t.id,(le[t.id]??"").trim()]).filter(([,t])=>!!t),[ue,le]),Ue=m.useMemo(()=>{const t=new Map;return n.items.forEach(s=>{Y(s.template_html).forEach(a=>{t.set(a.id,(t.get(a.id)??0)+1)})}),t},[n.items,Y]),Jt=async()=>{var x;const t=[...n.items];if(t.length===0)return;if(J.length===0){l({title:"Enter at least one override",description:"Blank fields preserve each creative’s current template text."});return}const s=new Map;t.forEach(f=>{const $=new Set(Y(f.template_html).map(P=>P.id)),M=J.filter(([P])=>$.has(P));M.length>0&&s.set(f.id,{...f.tag_values,...Object.fromEntries(M)})});const a=t.filter(f=>s.has(f.id));if(a.length===0){l({title:"No creatives use those fields",description:"Fill in a field that at least one creative template contains."});return}n.setItems(f=>f.map($=>{const M=s.get($.id);return M?{...$,tag_values:M}:$})),R(!0);let d=0,o=0,g;try{for(let f=0;f<a.length;f+=5){const $=a.slice(f,f+5),M=await Promise.allSettled($.map(Q=>n.saveItem({id:Q.id,tag_values:s.get(Q.id)??Q.tag_values})));d+=M.filter(Q=>Q.status==="fulfilled").length;const P=M.filter(Q=>Q.status==="rejected");o+=P.length,g===void 0&&((x=P[0])==null?void 0:x.status)==="rejected"&&(g=P[0].reason)}if(o>0){await n.refresh(),l({title:`${d} of ${a.length} creatives updated`,description:g instanceof Error?`${o} failed: ${g.message}. The campaign was refreshed.`:`${o} failed. The campaign was refreshed to show the saved template text.`,variant:"destructive"});return}be({}),l({title:`Template text updated on ${d} creative${d===1?"":"s"}`,description:"Only the fields you filled in changed. Templates, source images, and Pinterest details were preserved."})}finally{R(!1)}},Wt=(t,s)=>{A("destination",{accountId:t,accountName:s,boardId:"",boardName:""}),n.setItems(a=>a.map(d=>({...d,pinterest_account_id:t,board_id:null,board_name:null}))),n.items.forEach(a=>void n.saveItem({...a,pinterest_account_id:t,board_id:null,board_name:null}))},Xt=(t,s)=>{A("destination",{...i.destination,boardId:t,boardName:s}),n.setItems(a=>a.map(d=>({...d,board_id:t,board_name:s}))),n.items.forEach(a=>void n.saveItem({...a,board_id:t,board_name:s}))},Ve=async t=>{R(!0);try{for(const s of n.items){const a=t[s.id]||null;await n.saveItem({...s,scheduled_at:a,status:a?"ready":"draft"})}A("schedule",{...i.schedule,itemTimes:t}),l({title:"Campaign times saved",description:"Your Queue settings were not changed."})}finally{R(!1)}},es=async()=>{if(!V){l({title:"Connect a Pinterest account first",description:"Queue slots are based on your Pinterest account schedule. Connect an account to preview and save next slots.",variant:"destructive"});return}if(!i.destination.accountId){l({title:"Choose an account before previewing its queue",description:"Pick your Pinterest account and board in the Destinations step.",variant:"destructive"});return}const t=await qt(!0)??Ft,s=Ot(t,n.items.length);if(s.length<n.items.length){l({title:"Not enough queue slots available",description:"Adjust Queue settings or choose manual times.",variant:"destructive"});return}const a=Object.fromEntries(n.items.map((d,o)=>[d.id,s[o].toISOString()]));Dt(a),await Ve(a)},ts=fs[v?"starter":T],me=Math.max(0,ts-j),Ke=m.useMemo(()=>{const t=[];
1return i.basics.name.trim()||t.push({id:"name",level:"error",message:"Campaign name is required.",step:0}),i.source.images.length===0&&t.push({id:"source-images",level:"error",message:"Upload an image or choose a connected source.",step:1}),n.items.length===0&&t.push({id:"items",level:"error",message:"Add at least one creative.",step:3}),n.items.forEach(s=>{pe(s.template_html||"")&&t.push({id:`template-${s.id}`,level:"error",message:`Creative ${s.position+1} uses an unsupported multi-image template. Remove it and create a new creative.`,step:3}),s.image_url||t.push({id:`image-${s.id}`,level:"error",message:`Creative ${s.position+1} needs an image.`,step:3}),s.title.trim()||t.push({id:`title-${s.id}`,level:"error",message:`Creative ${s.position+1} needs a title.`,step:3}),Y(s.template_html).forEach(a=>{(s.tag_values[a.id]??"").trim()||t.push({id:`tag-${s.id}-${a.id}`,level:"error",message:`Creative ${s.position+1} needs template text for ${a.label}.`,step:3})})}),i.schedule.mode!=="draft"?(V?i.destination.accountId||t.push({id:"account",level:"error",message:"Choose a Pinterest account.",step:4}):t.push({id:"account",level:"error",message:"Connect a Pinterest account before scheduling this campaign.",step:4}),i.destination.boardId||t.push({id:"board",level:"error",message:"Choose a Pinterest board.",step:4}),n.items.forEach(s=>{(!s.scheduled_at||new Date(s.scheduled_at)<=new Date)&&t.push({id:`time-${s.id}`,level:"error",message:`Creative ${s.position+1} needs a future publish time.`,step:5})}),n.items.length>me&&t.push({id:"credits",level:"error",message:`This campaign needs ${n.items.length} credits; ${me} are available today.`,step:6})):V?i.destination.accountId||t.push({id:"draft-destination",level:"warning",message:"No Pinterest destination is selected. This campaign can still be saved as a draft.",step:4}):t.push({id:"draft-destination",level:"warning",message:"No Pinterest account is connected. This campaign can still be saved as a draft.",step:4}),t},[i,n.items,me,Y,V]),Ye=Ke.some(t=>t.level==="error"),ss=async()=>{if(n.campaign){if(i.schedule.mode==="draft"){r(`/dashboard/campaigns/${n.campaign.id}`);return}if(Ye){l({title:"Resolve validation errors before scheduling",variant:"destructive"});return}R(!0);try{const t=await _e.render(n.campaign.id);if(n.setItems(t.items),!t.success)throw new Error(`${t.failedCount} creative${t.failedCount===1?"":"s"} could not be rendered.`);const s=await _e.schedule(n.campaign.id,n.campaign.version,crypto.randomUUID());await y(),l({title:"Campaign scheduled",description:s.message||`${s.scheduledCount} pins added to publishing.`}),r(`/dashboard/campaigns/${n.campaign.id}`)}catch(t){l({title:"Campaign was not scheduled",description:t instanceof Error?t.message:"Please try again.",variant:"destructive"})}finally{R(!1)}}},as=()=>N===0?e.jsxs(z,{children:[e.jsx(H,{children:e.jsx(Z,{children:"Campaign basics"})}),e.jsxs(O,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"campaign-name",children:"Campaign name"}),e.jsx(G,{id:"campaign-name",value:i.basics.name,maxLength:120,placeholder:"Spring product launch",onChange:t=>A("basics",{...i.basics,name:t.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Campaign type"}),e.jsxs(ae,{value:i.basics.campaignType,onValueChange:t=>A("basics",{...i.basics,campaignType:t}),children:[e.jsx(re,{children:e.jsx(ie,{})}),e.jsxs(ne,{children:[e.jsx(L,{value:"content",children:"Content"}),e.jsx(L,{value:"product",children:"Product"}),e.jsx(L,{value:"seasonal",children:"Seasonal"}),e.jsx(L,{value:"evergreen",children:"Evergreen"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Objective"}),e.jsxs(ae,{value:i.basics.objective,onValueChange:t=>A("basics",{...i.basics,objective:t}),children:[e.jsx(re,{children:e.jsx(ie,{})}),e.jsxs(ne,{children:[e.jsx(L,{value:"traffic",children:"Drive traffic"}),e.jsx(L,{value:"awareness",children:"Build awareness"}),e.jsx(L,{value:"sales",children:"Generate sales"}),e.jsx(L,{value:"engagement",children:"Increase engagement"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"campaign-description",children:"Description"}),e.jsx(Ne,{id:"campaign-description",rows:5,value:i.basics.description,placeholder:"Goals, audience, and n
1otes for collaborators",onChange:t=>A("basics",{...i.basics,description:t.target.value})})]})]})]}):N===1?e.jsxs(z,{children:[e.jsx(H,{children:e.jsx(Z,{children:"Choose source images"})}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Extract from your URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{value:i.source.url,placeholder:"https://yoursite.com/article",onChange:t=>A("source",{...i.source,type:"url",url:t.target.value})}),e.jsxs(_,{variant:"outline",onClick:()=>void Vt(),disabled:$e,children:[$e&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Extract"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(vs,{onImagesLoaded:(t,s,a)=>A("source",{type:"connected",url:"",images:s!=null&&s.length?s.map(d=>it(d,a)):t}),disabled:w}),e.jsxs(I,{className:"inline-flex h-10 cursor-pointer items-center rounded-md border px-4 text-sm font-medium hover:bg-muted",children:[e.jsx(ps,{className:"mr-2 h-4 w-4"}),"Upload images",e.jsx(G,{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:t=>void Kt(t.target.files)})]})]}),Lt&&i.source.images.length===0&&e.jsx("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-sm font-medium text-destructive",children:"Upload at least one image or choose a connected source before continuing."}),i.source.images.length>0?e.jsx("div",{className:"grid grid-cols-3 gap-3 sm:grid-cols-5",children:i.source.images.map((t,s)=>e.jsxs("div",{className:"group relative aspect-square overflow-hidden rounded-xl border",children:[e.jsx("img",{src:ke(t),alt:`Source ${s+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",className:"absolute right-1 top-1 rounded-full bg-black/70 p-1 text-white opacity-0 group-hover:opacity-100",onClick:()=>A("source",{...i.source,images:i.source.images.filter((a,d)=>d!==s)}),children:e.jsx(Je,{className:"h-3 w-3"})})]},`${W(t)}-${s}`))}):e.jsxs("div",{className:"rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground",children:[e.jsx(at,{className:"mx-auto mb-2 h-7 w-7"}),"Extract, load, or upload durable campaign images."]})]})]}):N===2?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(z,{children:[e.jsxs(H,{
1children:[e.jsx(Z,{children:"Add creatives"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a template. Your source images are applied automatically from the Source step, and the preview shows exactly what will be added."})]}),e.jsx(O,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(I,{children:["Templates ",e.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:"(required)"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"All templates are selected by default. Unselect any you do not want, and creatives are generated from a random mix of the rest."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-medium ${C.length===0?"text-destructive":"text-muted-foreground"}`,children:[C.length," of ",D.length," selected"]}),e.jsx(_,{type:"button",variant:"outline",size:"sm",onClick:()=>oe(new Set(D.map(t=>t.id))),disabled:w||C.length===D.length,children:"Select all"}),e.jsx(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>oe(new Set),disabled:w||C.length===0,children:"Clear"})]})]}),D.length>0&&C.length===0&&e.jsx("p",{className:"rounded-lg bg-destructive/10 px-3 py-2 text-xs font-medium text-destructive",children:"Select at least one template to generate creatives."}),D.length>0?e.jsx("div",{className:"grid max-h-[520px] grid-cols-2 gap-3 overflow-y-auto pr-1 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6",children:D.map(t=>{const s=fe.has(t.id),a=Yt.get(t.id)??{};return e.jsxs("button",{type:"button","aria-label":`${s?"Unselect":"Select"} ${t.name} template`,"aria-pressed":s,title:t.description||t.name,onClick:()=>oe(d=>{const o=new Set(d);return o.has(t.id)?o.delete(t.id):o.add(t.id),o}),className:`group relative overflow-hidden rounded-xl border-2 bg-background text-left transition ${s?"border-red-500 ring-2 ring-red-100":"border-border opacity-60 hover:border-red-300 hover:opacity-100 hover:shadow-md"}`,children:[e.jsx("div",{className:"pointer-events-none aspect-[2/3] overflow-hidden bg-muted",children:e.jsx(ct,{rootMargin:"200px 0px",children:()=>e.jsx(We,{html:t.html_content,values:a})})}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:t.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.category||t.description||"Pinterest template"})]}),e.jsx("span",{className:`absolute right-2 top-2 rounded-full border p-1 shadow ${s?"border-red-600 bg-red-600 text-white":"border-border bg-white/90 text-transparent"}`,children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]},t.id)})}):e.jsx("div",{className:"rounded-xl border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No active templates are available."})]}),i.source.images.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed p-6 text-center",children:[e.jsx(at,{className:"mx-auto mb-2 h-6 w-6 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add images in the Source step before creating a creative."}),e.jsx(_,{type:"button",variant:"link",className:"mt-1",onClick:()=>K(1),children:"Go to Source"})]})]}),e.jsx("div",{className:"rounded-xl border bg-muted/20 p-5",children:e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"max-w-xl text-left",children:[e.jsx("p",{className:"text-base font-semibold leading-6",children:"Create creatives"}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:["Use one random combination, or mix ",C.length," template",C.length===1?"":"s"," with ",i.source.images.length," image",i.source.images.length===1?"":"s"," in a batch."]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end",children:[e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>void Qt(),disabled:w||C.length===0||!i.source.images.length,children:[w?e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(hs,{className:"mr-2 h-4 w-4"}),"Add one"]}),e.jsxs("div",{className:"space-y-1.5 sm:w-20",children:[e.jsx(I,{htmlFor:"campaign-batch-limit",className:"text-xs",children:"Maximum"}),e.jsx(G,{id:"campaign-batch-limit",type:"number",min:1,max:50,value:ve,onChange:t=>Mt(Math.min(50,Math.max(1,Number(t.target.value)||1))),className:"h-9 bg-background"})]}),e.jsxs(_,{size:"sm",onClick:()=>void Ht(),disabled:w||C.length===0||se.length===0,children:[w?e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Bs,{className:"mr-2 h-4 w-4"}),C.length===0?"Select templates":se.length>0?`Create ${se.length}`:"No new items"]})]})]})})]})})]}),n.items.length>0&&e.jsx(Fs,{asChild:!0,children:e.jsxs(z,{children:[e.jsxs(qs,{className:"group flex w-full items-center justify-between gap-4 p-6 text-left",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:"text-lg font-semibold leading-none tracking-tight",children:["Customize template text ",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"(optional)"})]}),e.jsx("p",{className:"mt-1 max-w-3xl text-xs leading-5 text-muted-foreground",children:"Open only if you want to override image text across matching creatives."})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("span",{className:"rounded-full border bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground",children:J.length>0?`${J.length} override${J.length===1?"":"s"}`:"No overrides"}),e.jsx(gs,{className:"h-4 w-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180","aria-hidden":"true"})]})]}),e.jsx(Gs,{children:e.jsx(O,{className:"space-y-4 border-t pt-5",children:ue.length>0?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"Leave fields blank to preserve product-specific or existing values. Pinterest metadata is not changed."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:ue.map(t=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(I,{htmlFor:`campaign-bulk-tag-${t.id}`,className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{children:t.label}),e.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 font-normal text-muted-foreground",children:[Ue.get(t.id)??0," creative",(Ue.get(t.id)??0)===1?"":"s"]})]}),Pt(t)?e.jsx(Ne,{id:`campaign-bulk-tag-${t.id}`,rows:3,className:"bg-background",placeholder:"Leave unchanged",maxLength:ot(t),value:le[t.id]??"",onChange:s=>be(a=>({...a,[t.id]:s.target.value})),disabled:w}):e.jsx(G,{id:`campaign-bulk-tag-${t.id}`,className:"bg-background",placeholder:"Leave unchanged",maxLength:ot(t),value:le[t.id]??"",onChange:s=>be(a=>({...a,[t.id]:s.target.value})),disabled:w})]},t.id))}),e.jsxs(_,{onClick:()=>void Jt(),disabled:w||J.length===0||n.items.length===0,children:[w&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Apply text to matching creatives"]})]}):e.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"These templates have no editable text fields."})})})]})}),n.items.length===0?e.jsx("div",{className:"rounded-xl border border-dashed bg-white p-10 text-center text-sm text-muted-foreground",children:"Choose a template to create the first editable campaign item."}):e.jsx("div",{className:"grid items-start gap-5 sm:grid-cols-2 xl:grid-cols-4",children:n.items.map((t,s)=>e.jsxs(z,{className:"flex h-full min-w-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-[2/3] overflow-hidden bg-gray-50",children:[e.jsx(_,{type:"button",variant:"secondary",size:"icon",className:"absolute right-2 top-2 z-10 h-8 w-8 bg-white/90 text-destructive shadow-sm hover:bg-white hover:text-destructive",onClick:()=>void Zt(t.id),"aria-label":"Delete creative",title:"Delete",children:e.jsx(Je,{className:"h-4 w-4"})}),e.jsx(ct,{children:()=>t.rendered_image_url?e.jsx("img",{src:t.rendered_image_url,alt:t.title||`Creative ${s+1}`,loading:"lazy",decoding:"async",className:"h-full w-full object-cover"}):t.template_html?e.jsx(We,{html:t.template_html,values:t.tag_values,backgroundImage:t.image_url}):e.jsx("img",{src:t.image_url,alt:t.title||`Creative ${s+1}`,loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})})]}),e.jsx(O,{className:"flex min-w-0 flex-1 flex-col gap-4 p-4",children:e.jsxs("section",{className:"space-y-3 rounded-xl bg-muted/30 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Pinterest metadata"}),e.jsx("p",{className:"text-xs leading-4 text-muted-foreground",children:"Editable publishing details."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(I,{htmlFor:`item-${t.id}-title`,children:"Title"}),e.jsx(G,{id:`item-${t.id}-title`,value:t.title,maxLength:100,placeholder:"Add the pin title",onCh
1ange:a=>we(t.id,{title:a.target.value}),onBlur:()=>{const a=n.items.find(d=>d.id===t.id);a&&ye({id:t.id,title:a.title})}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(I,{htmlFor:`item-${t.id}-description`,children:"Description"}),e.jsx(Ne,{id:`item-${t.id}-description`,rows:3,value:t.description,maxLength:500,placeholder:"Add the pin description",onChange:a=>we(t.id,{description:a.target.value}),onBlur:()=>{const a=n.items.find(d=>d.id===t.id);a&&ye({id:t.id,description:a.description})}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(I,{htmlFor:`item-${t.id}-link`,children:"Destination URL"}),e.jsx(G,{id:`item-${t.id}-link`,value:t.link,placeholder:"https://yoursite.com/page",onChange:a=>we(t.id,{link:a.target.value}),onBlur:()=>{const a=n.items.find(d=>d.id===t.id);a&&ye({id:t.id,link:a.link})}})]})]})]})})]},t.id))})]}):N===3?e.jsxs(z,{children:[e.jsx(H,{children:e.jsx(Z,{children:"Choose destination"})}),e.jsxs(O,{className:"space-y-4",children:[e.jsx(zs,{accountId:i.destination.accountId,boardId:i.destination.boardId,onAccountChange:Wt,onBoardChange:Xt,disabled:w}),e.jsx("p",{className:"rounded-lg bg-blue-50 p-3 text-sm text-blue-800",children:"Account and board selection is always explicit. You may continue without Pinterest only if you keep the campaign draft-only."})]})]}):N===4?e.jsxs(z,{children:[e.jsx(H,{children:e.jsx(Z,{children:"Schedule campaign"})}),e.jsxs(O,{className:"space-y-6",children:[e.jsx(kt,{value:i.schedule.mode,onValueChange:t=>A("schedule",{...i.schedule,mode:t}),className:"grid gap-3 sm:grid-cols-3",children:[{value:"draft",title:"Draft only",text:"Save without Pinterest."},{value:"queue",title:"Use Queue",text:"Preview next open slots."},{value:"manual",title:"Manual times",text:"Choose every datetime."}].map(t=>e.jsxs(I,{htmlFor:`mode-${t.value}`,className:`cursor-pointer rounded-xl border p-4 ${i.schedule.mode===t.value?"border-red-500 ring-2 ring-red-100":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{id:`mode-${t.value}`,value:t.value}),e.jsx("span",{className:"font-semibold",children:t.title})]}),e.jsx("p",{className:"mt-2 pl-6 text-xs text-muted-foreground",children:t.text})]},t.value))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Timezone"}),e.jsxs(ae,{value:i.schedule.timezone,onValueChange:t=>A("schedule",{...i.schedule,timezone:t}),children:[e.jsx(re,{children:e.jsx(ie,{placeholder:"Choose a timezone"})}),e.jsxs(ne,{className:"max-h-80",children:[!rt.some(t=>t.value===i.schedule.timezone)&&e.jsx(L,{value:i.schedule.timezone,children:i.schedule.timezone}),rt.map(t=>e.jsx(L,{value:t.value,children:t.label},t.value))]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Queue preview uses ",zt.timezone,"; campaign display uses ",i.schedule.timezone,"."]})]}),i.schedule.mode==="queue"&&e.jsxs("div",{className:"space-y-4",children:[!q&&!V&&e.jsxs("div",{className:"flex flex-wrap items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900",role:"alert",children:[e.jsx(Se,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-[220px] flex-1",children:[e.jsx("p",{className:"font-semibold",children:"Connect your Pinterest account first"}),e.jsxs("p",{className:"mt-1 text-xs",children:["Next slots are calculated from your Pinterest account's queue, so you need a connected account to preview and save them. Or switch to ",e.jsx("strong",{children:"Draft only"})," and schedule later."]})]}),e.jsxs(_,{size:"sm",variant:"outline",className:"gap-2",onClick:()=>void Rt(),disabled:Re,children:[Re?e.jsx(B,{className:"h-4 w-4 animate-spin"}):e.jsx(ut,{className:"h-4 w-4"}),"Connect Pinterest"]})]}),V&&!i.destination.accountId&&e.jsxs("div",{className:"flex flex-wrap items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900",role:"alert",children:[e.jsx(Se,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-[220px] flex-1",children:[e.jsx("p",{className:"font-semibold",children:"Select a Pinterest account and board"}),e.jsx("p",{className:"mt-1 text-xs",children:"Pick the destination account so we can read its queue and reserve the next open slots."})]}),e.jsx(_,{size:"sm",variant:"outline",onClick:()=>K(3),children:"Go to Destinations"})]}),e.jsxs(_,{variant:"outline",onClick:()=>void es(),disabled:w||!V||!i.destination.accountId,children:[w?e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ca,{}),"Preview and save next slots"]}),n.items.map(t=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-4 py-3 text-sm",children:[e.jsxs("span",{children:["Creative ",t.position+1]}),e.jsx("span",{className:"font-medium",children:De[t.id]||t.scheduled_at?new Date(De[t.id]||t.scheduled_at).toLocaleStr
1ing([],{timeZone:i.schedule.timezone}):"No slot saved"})]},t.id))]}),i.schedule.mode==="manual"&&e.jsxs("div",{className:"space-y-3",children:[n.items.map(t=>e.jsxs("div",{className:"grid items-center gap-2 rounded-lg border p-3 sm:grid-cols-[1fr_260px]",children:[e.jsxs(I,{htmlFor:`time-${t.id}`,children:["Creative ",t.position+1]}),e.jsx(G,{id:`time-${t.id}`,type:"datetime-local",min:lt(new Date(Date.now()+6e4).toISOString()),value:lt(i.schedule.itemTimes[t.id]||t.scheduled_at),onChange:s=>{const a=s.target.value?new Date(s.target.value).toISOString():"";A("schedule",{...i.schedule,itemTimes:{...i.schedule.itemTimes,[t.id]:a}})}})]},t.id)),e.jsx(_,{onClick:()=>void Ve(i.schedule.itemTimes),disabled:w,children:"Save manual times"})]}),i.schedule.mode==="draft"&&e.jsx("div",{className:"rounded-xl border border-dashed p-5 text-sm text-muted-foreground",children:"No publishing rows or credits are created. You can resume this campaign later."})]})]}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[1fr_340px]",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(Os,{issues:Ke}),e.jsxs(z,{children:[e.jsx(H,{children:e.jsx(Z,{children:"Final review"})}),e.jsxs(O,{className:"divide-y text-sm",children:[e.jsx(U,{label:"Campaign",value:i.basics.name||"Untitled"}),e.jsx(U,{label:"Type",value:i.basics.campaignType}),e.jsx(U,{label:"Objective",value:i.basics.objective}),e.jsx(U,{label:"Creatives",value:`${n.items.length}`}),e.jsx(U,{label:"Pinterest account",value:i.destination.accountName?`@${i.destination.accountName}`:"Not selected"}),e.jsx(U,{label:"Board",value:i.destination.boardName||"Not selected"}),e.jsx(U,{label:"Schedule",value:i.schedule.mode==="draft"?"Draft only":i.schedule.mode==="queue"?"Queue slots":"Manual times"}),e.jsx(U,{label:"Timezone",value:i.schedule.timezone})]})]})]}),e.jsxs(z,{className:"h-fit",children:[e.jsx(H,{children:e.jsx(Z,{children:"Publishing credits"})}),e.jsxs(O,{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Required"}),e.jsx("strong",{children:i.schedule.mode==="draft"?0:n.items.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Available today"}),e.jsx("strong",{children:me})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Plan"}),e.jsx("strong",{className:"capitalize",children:v?"Trial":T})]}),e.jsxs(_,{className:"mt-3 w-full bg-red-500 hover:bg-red-600",onClick:()=>void ss(),disabled:w||i.schedule.mode!=="draft"&&Ye,children:[w&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),i.schedule.mode==="draft"?"Save draft":"Approve & schedule"]})]})]})]});return p&&n.loading&&!n.campaign?e.jsx(us,{}):p&&n.error?e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-6",children:[e.jsx("h1",{className:"font-bold text-red-900",children:"Campaign could not be loaded"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:n.error}),e.jsx(_,{className:"mt-4",variant:"outline",onClick:()=>void n.refresh(),children:"Try again"})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-6 pb-10",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(_,{variant:"ghost",className:"mb-2 -ml-3",onClick:()=>r("/dashboard/campaigns"),children:[e.jsx(st,{className:"mr-2 h-4 w-4"}),"Campaigns"]}),e.jsx("h1",{className:"text-3xl font-bold",children:p?"Edit campaign":"New campaign"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Step ",N+1," of ",he.length," · ",he[N]]})]}),p&&e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold ${te==="error"?"border-red-200 text-red-600":"text-muted-foreground"}`,children:[te==="saving"?e.jsx(B,{className:"h-3.5 w-3.5 animate-spin"}):te==="saved"?e.jsx(Ze,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ds,{className:"h-3.5 w-3.5"}),te==="saving"?"Saving…":te==="saved"?"Saved":"Autosave failed"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("ol",{className:"flex min-w-[680px] gap-2",children:he.map((t,s)=>e.jsx("li",{className:"flex-1",children:e.jsxs("button",{type:"button",disabled:!p&&s>0,onClick:()=>p&&Gt(s),className:`w-full rounded-lg border px-2 py-2 text-xs font-semibold ${s===N?"border-red-500 bg-red-50 text-red-700":s<N?"border-emerald-200 bg-emerald-50 text-emerald-700":"bg-white text-muted-foreground"}`,children:[s+1,". ",t]})},t))})}),as(),N<Ce&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(_,{variant:"outline",onClick:()=>K(t=>Math.max(0,t-1)),disabled:N===0,children:[e.jsx(st,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsxs(_,{onClick:()=>void Ut(),disabled:w,children:[w&&e.jsx(B,{className:"mr-2 h-4 w-4 animate-spin"}),"Continue",e.jsx(ms,{className:"ml-2 h-4 w-4"})]})]})]})})}function ct({children:r,rootMargin:c="400px 0px"}){const u=m.useRef(null),[p,l]=m.useState(!1);return m.useEffect(()=>{const h=u.current;if(!h)return;
1if(!("IntersectionObserver"in window)){l(!0);return}const b=new IntersectionObserver(S=>{const n=S[S.length-1];n&&l(n.isIntersecting)},{rootMargin:c});return b.observe(h),()=>b.disconnect()},[c]),e.jsx("div",{ref:u,className:"aspect-[2/3] w-full",children:p?r():e.jsx("div",{className:"h-full w-full bg-muted/40","aria-hidden":"true"})})}function ca(){return e.jsx("span",{className:"mr-2",children:"↗"})}function U({label:r,value:c}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{className:"text-muted-foreground",children:r}),e.jsx("strong",{className:"text-right",children:c})]})}export{Oa as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.