1import{r as l,s as se,j as e,R as xe}from"./site-C5SUB8ov.js";import{authorizedFunctionHeaders as Ft}from"./functionAuth-BsNFH-jK.js";import{a0 as ke,dL as dt,L as re,bo as ge,j as At,x as Dt,d as It,k as pe,C as he,H as Be,X as Le,q as Ue,u as ie,bT as X,b6 as Pt,bp as Ze,D as Tt,c as M,R as et,dN as Re,bF as ct,cW as ot,w as ce,T as xt,A as tt,e as Mt,M as Ot,dO as Ve,b7 as mt,aK as gt,a4 as Rt,df as Vt,U as Bt,bc as Ut,v as Kt,P as qt,bW as Ke,t as pt,g as at}from"./main-_fPdXjGG.js";import{S as Ht}from"./smartphone-DXyHKCRV.js";import{S as ut}from"./skip-forward-C7gIOyhH.js";import{L as zt}from"./link-2-cnckghPv.js";function st(s){return(s||"").toLowerCase().replace(/[^a-zа-ÑÑÑÑÒ0-9]/gi,"")}function Jt(s,m){const N=st(s),n=st(m);if(!N||!n)return 0;if(N===n)return 1;const i=A=>{const b=new Map;for(let P=0;P<A.length-1;P++){const U=A.slice(P,P+2);b.set(U,(b.get(U)||0)+1)}return b},u=i(N),F=i(n);let j=0;for(const[A,b]of u)j+=Math.min(b,F.get(A)||0);return 2*j/(N.length-1+(n.length-1))}function Gt(s,m){let N=null;for(const n of m){const i=Jt(s,n.value);(!N||i>N.score)&&(N={enum:n,score:i})}return N&&N.score>=.55?N:null}const rt=[["full_name","ÐмʼÑ"],["phone","ТелеÑон"],["email","Email"],["campaign_name","Ðазва кампанÑÑ"],["ad_name","Ðазва оголоÑеннÑ"],["adset_name","ÐÑÑпа оголоÑенÑ"],["form_name","ФоÑма"],["platform","ÐлаÑÑоÑма (fb/ig)"],["lead_id","ID лÑда в Meta"]],Me=[["name","ÐÐ¼Ê¼Ñ ÐºÐ¾Ð½ÑакÑÑ"],["PHONE","ТелеÑон конÑакÑÑ"],["EMAIL","Email конÑакÑÑ"]];function Wt(){const[s,m]=l.useState([]),[N,n]=l.useState([]),[i,u]=l.useState([]),[F,j]=l.useState(!0),[A,b]=l.useState(null),[P,U]=l.useState(""),[C,z]=l.useState([]),[I,G]=l.useState([]),[ee,Y]=l.useState([]),[_,w]=l.useState([]),T=l.useCallback(async()=>{j(!0);try{const[o,k,S]=await Promise.all([fetch("/.netlify/functions/kommo-fetch-fields?type=pipelines").then(r=>r.json()).catch(()=>({})),se.from("meta_campaign_mapping").select("*"),se.from("meta_leads").select("campaign_id, campaign_name, created_at, field_data").gte("created_at",new Date(Date.now()-5184e6).toISOString()).limit(5e3)]),x="/.netlify/functions/kommo-fetch-fields";Promise.all([fetch(`${x}?type=leads`).then(r=>r.json()).catch(()=>({})),fetch(`${x}?type=contacts`).then(r=>r.json()).catch(()=>({})),fetch(`${x}?type=users`).then(r=>r.json()).catch(()=>({}))]).then(([r,g,y])=>{z((r==null?void 0:r.fields)||[]),G((g==null?void 0:g.fields)||[]),Y((y==null?void 0:y.users)||[])}),m((o==null?void 0:o.pipelines)||[]),n(k.data||[]);const V=new Set;for(const r of S.data||[])for(const g of r.field_data||[])g!=null&&g.name&&V.add(g.name);w([...V].sort());const J=new Map;for(const r of S.data||[]){const g=r.campaign_id||`name:${r.campaign_name||"â"}`,y=J.get(g);y?(y.leads+=1,r.created_at>y.last_at&&(y.last_at=r.created_at)):J.set(g,{campaign_id:r.campaign_id,campaign_name:r.campaign_name,leads:1,last_at:r.created_at})}u([...J.values()].sort((r,g)=>g.leads-r.leads))}catch(o){ke.error((o instanceof Error?o.message:String(o))||"Ðе вдалоÑÑ Ð·Ð°Ð²Ð°Ð½ÑажиÑи маÑÑÑÑÑи")}finally{j(!1)}},[]);l.useEffect(()=>{T()},[T]);const c=N.find(o=>o.is_default)||null,f=l.useMemo(()=>{const o=new Map;for(const k of N)k.is_default||!k.campaign_id||o.set(String(k.campaign_id),k);return o},[N]),p=o=>{var k;return((k=s.find(S=>String(S.id)===String(o)))==null?void 0:k.statuses)||[]},K=async(o,k,S,x,V)=>{const J=(o==null?void 0:o.campaign_id)||"default";b(J);try{const r=s.find(L=>String(L.id)===k),g=p(k).find(L=>String(L.id)===S),y={pipeline_id:k?Number(k):null,pipeline_name:(r==null?void 0:r.name)||null,status_id:S?Number(S):null,status_name:(g==null?void 0:g.name)||null,auto_send:!0,updated_at:new Date().toISOString(),...x!==void 0&&{field_mappings:x},...V!==void 0&&{responsible_user_id:V?Number(V):null}},q=o?f.get(String(o.campaign_id)):c;if(q){const{error:L}=await se.from("meta_campaign_mapping").update(y).eq("id",q.id);if(L)throw L}else{const{error:L}=await se.from("meta_campaign_mapping").insert([{...y,campaign_id:(o==null?void 0:o.campaign_id)||null,campaign_name:(o==null?void 0:o.campaign_name)||"УÑÑ ÑнÑÑ ÐºÐ°Ð¼Ð¿Ð°Ð½ÑÑ (за замовÑÑваннÑм)",is_default:!o,field_mappings:[]}]);if(L)throw L}ke.success(o?`ÐаÑÑÑÑÑ Ð·Ð±ÐµÑежено: ${o.campaign_name}`:"ÐаÑÑÑÑÑ Ð·Ð° замовÑÑваннÑм збеÑежено"),await T()}catch(r){ke.error((r instanceof Error?r.message:String(r))||"Ðомилка збеÑеженнÑ")}finally{b(null)}},Z=async o=>{const k=f.get(String(o.campaign_id));if(k){b(String(o.campaign_id));try{const{error:S}=await se.from("meta_campaign_mapping").delete().eq("id",k.id);if(S)throw S;ke.success("СвÑй маÑÑÑÑÑ Ð¿ÑибÑано â пÑде за замовÑÑваннÑм"),await T()}catch(S){ke.error((S instanceof Error?S.message:String(S))||"Ðомилка")}finally{b(null)}}},H=i.filter(o=>
1!P.trim()||(o.campaign_name||"").toLowerCase().includes(P.trim().toLowerCase())),h=i.filter(o=>o.campaign_id&&f.has(String(o.campaign_id))).length;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-white border border-slate-200 rounded-2xl p-4 shadow-sm flex items-center gap-3",children:[e.jsx("span",{className:"w-9 h-9 rounded-xl bg-violet-50 flex items-center justify-center shrink-0",children:e.jsx(dt,{className:"w-5 h-5 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"ÐаÑÑÑÑÑи лÑдÑв Ñ Kommo"}),e.jsxs("div",{className:"text-[11px] text-slate-400",children:["ÐампанÑÑ Ð· влаÑним маÑÑÑÑÑом: ",e.jsx("b",{className:"text-slate-600",children:h})," з ",i.length," · ÑеÑÑа йде за замовÑÑваннÑм"]})]}),e.jsx("button",{onClick:T,className:"w-8 h-8 rounded-lg text-slate-400 hover:bg-slate-100 flex items-center justify-center shrink-0",children:F?e.jsx(re,{className:"w-4 h-4 animate-spin"}):e.jsx(ge,{className:"w-4 h-4"})})]}),e.jsx(nt,{title:"Ðа замовÑÑваннÑм",subtitle:"СÑди йде вÑе, Ð´Ð»Ñ Ñого нижÑе не задано окÑемий маÑÑÑÑÑ",highlight:!0,pipelines:s,statusesOf:p,leadFields:C,contactFields:I,users:ee,formFields:_,currentPipeline:(c==null?void 0:c.pipeline_id)??"",currentStatus:(c==null?void 0:c.status_id)??"",currentFields:(c==null?void 0:c.field_mappings)||[],currentResponsible:(c==null?void 0:c.responsible_user_id
1)??"",saving:A==="default",onSave:(o,k,S,x)=>K(null,o,k,S,x)}),e.jsxs("div",{className:"relative",children:[e.jsx(At,{className:"absolute left-2.5 top-2.5 w-3.5 h-3.5 text-slate-300"}),e.jsx("input",{value:P,onChange:o=>U(o.target.value),placeholder:"ÐоÑÑк кампанÑÑâ¦",className:"w-full pl-8 pr-3 py-2 text-xs border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-violet-100"})]}),F?e.jsx("div",{className:"py-10 text-center",children:e.jsx(re,{className:"w-5 h-5 animate-spin text-slate-300 inline"})}):H.length===0?e.jsx("div",{className:"py-8 text-center text-xs text-slate-400",children:"ÐампанÑй не знайдено"}):e.jsx("div",{className:"space-y-2",children:H.map(o=>{const k=o.campaign_id?f.get(String(o.campaign_id)):void 0;return e.jsx(nt,{title:o.campaign_name||"(без назви)",campaignName:o.campaign_name||void 0,subtitle:`${o.leads} лÑдÑв за 60 днÑв · оÑÑаннÑй ${new Date(o.last_at).toLocaleDateString("uk-UA",{day:"2-digit",month:"2-digit"})}`,badge:k?{text:"ÑвÑй маÑÑÑÑÑ",tone:"own"}:{text:"за замовÑÑваннÑм",tone:"default"},pipelines:s,statusesOf:p,leadFields:C,contactFields:I,users:ee,formFields:_,currentPipeline:(k==null?void 0:k.pipeline_id)??"",currentStatus:(k==null?void 0:k.status_id)??"",currentFields:(k==null?void 0:k.field_mappings)||[],currentResponsible:(k==null?void 0:k.responsible_user_id
1)??"",saving:A===String(o.campaign_id),onSave:(S,x,V,J)=>K(o,S,x,V,J),onClear:k?()=>Z(o):void 0},o.campaign_id||o.campaign_name||"none")})}),!F&&!c&&e.jsxs("div",{className:"flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-xl px-3.5 py-2.5",children:[e.jsx(Dt,{className:"w-4 h-4 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[11px] text-amber-800",children:["ÐаÑÑÑÑÑ Ð·Ð° замовÑÑваннÑм не задано â лÑди з кампанÑй без влаÑного маÑÑÑÑÑÑ",e.jsx("b",{children:" не поÑÑаплÑÑÑ Ñ Kommo"}),". Ðадай воÑÐ¾Ð½ÐºÑ Ð¹ еÑап Ñ ÐºÐ°ÑÑÑÑ Ð·Ð²ÐµÑÑ
Ñ."]})]})]})}function nt({title:s,subtitle:m,badge:N,highlight:n,pipelines:i,statusesOf:u,leadFields:F=[],contactFields:j=[],users:A=[],formFields:b=[],campaignName:P,currentPipeline:U,currentStatus:C,currentFields:z,currentResponsible:I,saving:G,onSave:ee,onClear:Y}){const[_,w]=l.useState(String(U||"")),[T,c]=l.useState(String(C||"")),[f,p]=l.useState(z),[K,Z]=l.useState(String(I||"")),[H,h]=l.useState(!1);l.useEffect(()=>{w(String(U||""))},[U]),l.useEffect(()=>{c(String(C||""))},[C]),l.useEffect(()=>{p(z)},[z]),l.useEffect(()=>{Z(String(I||""))},[I]);const o=u(_),k=_!==String(U||"")||T!==String(C||"")||K!==String(I||"")||JSON.stringify(f)!==JSON.stringify(z),S=(x,V)=>p(J=>J.map((r,g)=>g===x?{...r,...V}:r));return e.jsxs("div",{className:`rounded-2xl border p-3.5 shadow-sm ${n?"bg-violet-50/40 border-violet-200":"bg-white border-slate-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-800 truncate",children:s}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate",children:m})]}),N&&e.jsx("span",{className:`shrink-0 text-[10px] px-2 py-0.5 rounded-full ${N.tone==="own"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-400"}`,children:N.text})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("select",{value:_,onChange:x=>{w(x.target.value),c("")},className:"flex-1 min-w-[160px] px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"",children:"â воÑонка â"}),i.map(x=>e.jsx("option",{value:String(x.id),children:x.name},x.id))]}),e.jsxs("select",{value:T,onChange:x=>c(x.target.value),disabled:!_,className:"flex-1 min-w-[160px] px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100 disabled:opacity-40",children:[e.jsx("option",{value:"",children:"â пеÑÑий еÑап â"}),o.map(x=>e.jsx("option",{value:String(x.id),children:x.name},x.id))]}),e.jsxs("button",{onClick:()=>ee(_,T,f,K),disabled:!_||G||!k,className:"shrink-0 inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium bg-slate-900 text-white rounded-lg hover:bg-slate-700 disabled:opacity-30",children:[G?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(It,{className:"w-3.5 h-3.5"}),"ÐбеÑегÑи"]}),Y&&e.jsx("button",{onClick:Y,disabled:G,className:"shrink-0 px-2.5 py-2 text-[11px] text-slate-400 hover:text-red-600 rounded-lg hover:bg-red-50",children:"ÑкинÑÑи"})]}),e.jsxs("button",{onClick:()=>h(x=>!x),className:"mt-2 inline-flex items-center gap-1 text-[11px] text-slate-500 hover:text-slate-700",children:[H?e.jsx(pe,{className:"w-3.5 h-3.5"}):e.jsx(he,{className:"w-3.5 h-3.5"}),"ÐÐ¾Ð»Ñ Ñа вÑдповÑдалÑний",f.length>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded bg-slate-100 text-[10px]",children:f.length})]}),H&&e.jsxs("div",{className:"mt-2 space-y-2 border-t border-slate-100 pt-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-slate-500 w-28 shrink-0",children:"ÐÑдповÑдалÑний"}),e.jsxs("select",{value:K,onChange:x=>Z(x.target.value),className:"flex-1 px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"",children:"â Ñк Ñ Kommo за замовÑÑваннÑм â"}),A.map(x=>e.jsx("option",{value:String(x.id),children:x.name},x.id))]})]}),f.length===0&&e.jsx("div",{className:"text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2.5",children:"ÐолÑв не задано â Ñ Kommo пÑдÑÑÑ Ð»Ð¸Ñе ÑмʼÑ, ÑелеÑон Ñ email."}),f.map((x,V)=>{var ae,oe,R;const J=x.fixed_value!==void 0&&x.fixed_value!==null,r=x.target||"lead",g=r==="lead"?F:j,y=g.find(E=>E.id===x.kommo_field_id),q=(y==null?void 0:y.enums)||[],L=J&&q.length&&P?Gt(P,q):null,$=J?x.fixed_value||"Ð
1·Ð½Ð°ÑÐµÐ½Ð½Ñ Ð½Ðµ вибÑано":((ae=rt.find(([E])=>E===x.meta_field))==null?void 0:ae[1])||((oe=x.meta_field)!=null&&oe.startsWith("custom:")?x.meta_field.slice(7):"не вибÑано"),D=x.kommo_field?((R=Me.find(([E])=>E===x.kommo_field))==null?void 0:R[1])||x.kommo_field:(y==null?void 0:y.name)||"поле не вибÑано",ne=$.includes("не вибÑано")||D.includes("не вибÑано");return e.jsxs("div",{className:`bg-white border rounded-xl overflow-hidden ${ne?"border-amber-200":"border-slate-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50 border-b border-slate-100",children:[e.jsx("span",{className:`text-[11px] font-medium truncate ${ne?"text-amber-700":"text-slate-700"}`,children:$}),e.jsx(Be,{className:"w-3 h-3 text-slate-300 shrink-0"}),e.jsx("span",{className:"text-[11px] text-slate-600 truncate",children:D}),e.jsx("span",{className:"text-[10px] text-slate-400 shrink-0 px-1.5 py-0.5 rounded bg-white border border-slate-200",children:r==="lead"?"Ñгода":"конÑакÑ"}),e.jsx("button",{onClick:()=>p(E=>E.filter((W,de)=>de!==V)),className:"ml-auto shrink-0 w-6 h-6 rounded text-slate-300 hover:text-red-600 hover:bg-red-50 flex items-center justify-center",children:e.jsx(Le,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"p-3 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 min-w-0",children:[e.jsx("div",{className:"text-[10px] font-semibold text-slate-400 uppercase tracking-wide",children:"ÐвÑдки взÑÑи"}),e.jsxs("select",{value:J?"__fixed__":x.meta_field||"",onChange:E=>{const W=E.target.value;W==="__fixed__"?S(V,{meta_field:void 0,fixed_value:""}):S(V,{meta_field:W,fixed_value:void 0,fixed_enum_id:void 0})},className:"w-full px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"",children:"â не вибÑано â"}),e.jsx("option",{value:"__fixed__",children:"ФÑкÑоване знаÑеннÑ"}),e.jsx("optgroup",{label:"ÐÐ°Ð½Ñ Ð»Ñда",children:rt.map(([E,W])=>e.jsx("option",{value:E,children:W},E))}),b.length>0&&e.jsx("optgroup",{label:"ÐÑдповÑÐ´Ñ Ñ ÑоÑмÑ",children:b.map(E=>e.jsx("option",{value:`custom:${E}`,children:E},E))})]}),J&&(q.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:x.fixed_enum_id?String(x.fixed_enum_id):"",onChange:E=>{var de;const W=E.target.value?Number(E.target.value):void 0;S(V,{fixed_enum_id:W,fixed_value:((de=q.find(ve=>ve.id===W))==null?void 0:de.value)||""})},className:"w-full px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"",children:"â вибеÑи знаÑÐµÐ½Ð½Ñ Ð·Ñ ÑпиÑÐºÑ â"}),q.map(E=>e.jsx("option",{value:String(E.id),children:E.value},E.id))]}),L&&L.enum.id!==x.fixed_enum_id&&e.jsxs("button",{onClick:()=>S(V,{fixed_enum_id:L.enum.id,fixed_value:L.enum.value}),className:"text-[10px] text-violet-700 hover:text-violet-900 underline text-left",children:["пÑдÑÑавиÑи «",L.enum.value,"»"]})]}):e.jsx("input",{value:x.fixed_value||"",onChange:E=>S(V,{fixed_value:E.target.value,fixed_enum_id:void 0}),placeholder:"ÐапиÑÑÑÑ Ð·Ð½Ð°ÑеннÑ, напÑ. Meta",className:"w-full px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white outline-none focus:ring-2 focus:ring-violet-100"}))]}),e.jsxs("div",{className:"space-y-1.5 min-w-0",children:[e.jsx("div",{className:"text-[10px] font-semibold text-slate-400 uppercase tracking-wide",children:"ÐÑди запиÑаÑи"}),e.jsxs("select",{value:r,onChange:E=>S(V,{target:E.target.value,kommo_field_id:void 0,kommo_field:void 0}),className:"w-full px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"lead",children:"Ð ÑгодÑ"}),e.jsx("option",{value:"contact",children:"РконÑакÑ"})]}),e.jsxs("select",{value:x.kommo_field||(x.kommo_field_id?String(x.
1kommo_field_id):""),onChange:E=>{const W=E.target.value;Me.some(([de])=>de===W)?S(V,{kommo_field:W,kommo_field_id:void 0}):S(V,{kommo_field:void 0,kommo_field_id:W?Number(W):void 0})},className:"w-full px-2.5 py-2 text-xs border border-slate-200 rounded-lg bg-white text-slate-700 outline-none focus:ring-2 focus:ring-violet-100",children:[e.jsx("option",{value:"",children:"â поле не вибÑано â"}),e.jsx("optgroup",{label:"СÑандаÑÑнÑ",children:Me.map(([E,W])=>e.jsx("option",{value:E,children:W},E))}),e.jsx("optgroup",{label:r==="lead"?"ÐÐ¾Ð»Ñ Ñгоди":"ÐÐ¾Ð»Ñ ÐºÐ¾Ð½ÑакÑÑ",children:g.map(E=>e.jsx("option",{value:String(E.id),children:E.name},E.id))})]})]})]})]},V)}),e.jsxs("button",{onClick:()=>p(x=>[...x,{target:"lead"}]),className:"inline-flex items-center gap-1 px-2.5 py-1.5 text-[11px] text-violet-700 bg-violet-50 rounded-lg hover:bg-violet-100",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"})," ÐодаÑи поле"]})]})]})}const Ee={uk:"uk-UA",en:"en-US",pl:"pl-PL"},a="admin.metaLeads";function Qt(s){return[{value:"full_name",label:s(`${a}.mapping.metaFields.fullName`)},{value:"phone",label:s(`${a}.mapping.metaFields.phone`)},{value:"email",label:s(`${a}.mapping.metaFields.email`)},{value:"campaign_name",label:s(`${a}.mapping.metaFields.campaignName`)},{value:"ad_name",label:s(`${a}.mapping.metaFields.adName`)}]}function Oe({value:s,onChange:m,options:N,placeholder:n,emptyLabel:i,disabled:u,className:F}){const{t:j}=ie(),A=n??j("common.select"),[b,P]=l.useState(!1),[U,C]=l.useState(""),z=l.useRef(null),I=l.useRef(null),G=N.find(_=>_.value===s),ee=N.filter(_=>_.label.toLowerCase().includes(U.toLowerCase()));l.useEffect(()=>{b&&(C(""),setTimeout(()=>{var _;return(_=I.current)==null?void 0:_.focus()},50))},[b]),l.useEffect(()=>{const _=w=>{z.current&&!z.current.contains(w.target)&&P(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const Y=_=>{m(_),P(!1)};return e.jsxs("div",{ref:z,className:M("relative",F),children:[e.jsxs("button",{type:"button",disabled:u,onClick:()=>!u&&P(_=>!_),className:M("w-full flex items-center justify-between gap-1.5 text-xs px-2.5 py-2 rounded-lg border transition-all","bg-white dark:bg-gray-800 text-left",b?"border-purple-400 dark:border-purple-500 ring-1 ring-purple-300 dark:ring-purple-700":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500",u&&"opacity-50 cursor-not-allowed",!G&&"text-gray-400 dark:text-gray-500",G&&"text-gray-800 dark:text-white"),children:[e.jsx("span",{className:"truncate flex items-center gap-1.5 min-w-0",children:G?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"truncate",children:G.label}),G.badge&&e.jsx("span",{className:M("flex-shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium",G.badgeColor||"bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"),children:G.badge})]}):e.jsx("span",{children:A})}),e.jsx(pe,{className:M("w-3 h-3 flex-shrink-0 text-gray-400 transition-transform",b&&"rotate-180")})]}),b&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[220px] bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-xl shadow-xl overflow-hidden",children:[e.jsx("div",{className:"border-b border-gray-100 p-2 dark:border-gray-700",children:e.jsx(pt,{className:"w-full [&_input]:text-xs",inputRef:I,value:U,onChange:C,placeholder:j("common.search")})}),e.jsxs("div",{className:"max-h-52 overflow-y-auto py-1",children:[i&&e.jsx("button",{onClick:()=>Y(""),className:M("w-full text-left px-3 py-2 text-xs transition-colors flex items-center gap-2",s?"text-gray-400 dark:text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700/50":"bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300"),children:e.jsx("span",{className:"italic",children:i})}),ee.length===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-gray-400",children:j(`${a}.searchable.noResults`)}):ee.map(_=>e.jsxs("button",{onClick:()=>Y(_.value),className:M("w-full text-left px-3 py-2 text-xs transition-colors flex items-center justify-between gap-2",_.value===s?"bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 font-medium":"text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50"),children:[e.jsx("span",{className:"truncate",children:_.label}),_.badge&&e.jsx("span",{className:M("flex-shrink-0 text-[10px] px-1.5 py-0.5 rounded-full",_.badgeColor||"bg-gray-100 dark:bg-gray-700 text-gray-500"),children:_.badge})]},_.value))]})]})]})}function Xt(s,m,N){const n=new Date,i=u=>u.toISOString().slice(0,10);switch(s){case"today":return{from:i(n),to:i(n)};case"yesterday":{const u=new Date(n);return u.setDate(u.getDate()-1),{from:i(u),to:i(u)}}case"7days":{const u=new Date(n);return u.setDate(u.getDate()-6),{from:i(u),to:i(n)}}case"30days":{const u=new Date(n);return u.setDate(u.getDate()-29),{from:i(u),to:i(n)}}
1case"custom":return{from:m||i(n),to:N||i(n)}}}function Yt({campaigns:s}){const{t:m,language:N}=ie(),n=Ee[N],[i,u]=l.useState("yesterday"),[F,j]=l.useState(""),[A,b]=l.useState(""),[P,U]=l.useState(!1),[C,z]=l.useState([]),[I,G]=l.useState(null),[ee,Y]=l.useState(""),[_,w]=l.useState(!1),[T,c]=l.useState(""),f=l.useRef(null),p=xe.useMemo(()=>{const r={};for(const g of s)if(g.ads)for(const y of g.ads)r[y.id]={thumbnail:y.creative_thumbnail||null,video_id:y.video_id||null,page_id:y.page_id||null};return r},[s]),K=l.useCallback(async()=>{U(!0);try{const{from:r,to:g}=Xt(i,F,A),{data:y,error:q}=await se.from("meta_ads_daily_stats").select("*").gte("date",r).lte("date",g).order("date",{ascending:!1});if(q)throw new Error(q.message);z(y||[])}catch(r){X.error(r instanceof Error?r.message:String(r))}finally{U(!1)}},[i,F,A]);l.useEffect(()=>{K()},[K]);const Z=async r=>{if(!_){w(!0),c("running");try{await fetch(r==="backfill"?"/.netlify/functions/meta-sync-daily-stats-background?mode=backfill&months=6":"/.netlify/functions/meta-sync-daily-stats-background?mode=daily"),X.success(m(r==="backfill"?`${a}.toasts.backfill6moStarted`:`${a}.toasts.syncStartedShort`)),f.current&&clearInterval(f.current),f.current=setInterval(async()=>{const{data:y}=await se.from("meta_sync_status").select("*").eq("id","daily_stats").single();y&&(c(y.status),y.status==="done"?(clearInterval(f.current),f.current=null,w(!1),X.success(m(`${a}.toasts.recordsLoaded`,{count:y.campaigns_synced})),await K()):y.status==="error"&&(clearInterval(f.current),f.current=null,w(!1),X.error(m(`${a}.errors.withDetails`,{details:y.error}))))},5e3)}catch(g){X.error(g instanceof Error?g.message:String(g)),w(!1)}}};l.useEffect(()=>()=>{f.current&&clearInterval(f.current)},[]);const H=ee?C.filter(r=>r.account_id===ee):C,h=xe.useMemo(()=>{const r=H.reduce((L,$)=>L+Number($.spend),0),g=H.reduce((L,$)=>L+$.leads,0),y=H.reduce((L,$)=>L+$.impressions,0),q=H.reduce((L,$)=>L+$.clicks,0);return{spend:r,leads:g,cpl:g>0?r/g:null,impressions:y,clicks:q,ctr:y>0?q/y*100:0,campaigns:new Set(H.map(L=>L.campaign_id)).size}},[H]),o=xe.useMemo(()=>{const r=new Map;for(const g of H){const y=g.campaign_id;r.has(y)||r.set(y,{campaign_id:y,campaign_name:g.campaign_name||"",account_name:g.account_name||"",currency:g.currency||"USD",spend:0,leads:0,impressions:0,clicks:0,ads:[]});const q=r.get(y);q.spend+=Number(g.spend),q.leads+=g.leads,q.impressions+=g.impressions,q.clicks+=g.clicks,q.ads.push(g)}return Array.from(r.values()).sort((g,y)=>y.spend-g.spend)},[H]),k=xe.useMemo(()=>{const r=new Map;for(const g of C)r.set(g.account_id,g.account_name||g.account_id);return Array.from(r.entries())},[C]),S=(r,g)=>{const y=g||"USD";return new Intl.NumberFormat(n,{style:"currency",currency:y,minimumFractionDigits:2,maximumFractionDigits:2}).format(r)},x=r=>new Intl.NumberFormat(n).format(r),V=C.length>0&&C[0].currency||"USD",J=[{key:"today",label:m(`${a}.analytics.presets.today`)},{key:"yesterday",label:m(`${a}.analytics.presets.yesterday`)},{key:"7days",label:m(`${a}.analytics.presets.days7`)},{key:"30days",label:m(`${a}.analytics.presets.days30`)},{key:"custom",label:m(`${a}.analytics.presets.custom`)}];return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-0.5",children:J.map(r=>e.jsx("button",{onClick:()=>u(r.key),className:M("px-3 py-1.5 text-xs font-medium rounded-md transition-all",i===r.key?"bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"),children:r.label},r.key))}),i==="custom"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"date",value:F,onChange:r=>j(r.target.value),className:"text-xs px-2 py-1.5 border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white"}),e.jsx("span",{className:"text-gray-400 text-xs",children:"â"}),e.jsx("input",{type:"date",value:A,onChange:r=>b(r.target.value),className:"text-xs px-2 py-1.5 border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white"})]}),k.length>1&&e.jsxs("select",{value:ee,onChange:r=>Y(r.target.value),className:"text-xs px-2 py-1.5 border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white",children:[e.jsx("option",{value:"",children:m(`${a}.filters.allAccounts`)}),k.map(([r,g])=>e.jsx("option",{value:r,children:g},r))]}),P&&e.jsx(re,{className:"w-4 h-4 animate-spin text-blue-500"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[_&&e.jsx("span",{className:"text-xs text-purple-500 animate-pulse",children:T==="running"?m(`${a}.analytics.syncRunning`):T}),e.jsxs("button",{onClick:()=>Z("daily"),disabled:_,className:"flex items-center gap-1.5 text-xs px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors",children:[_?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ge,{className:"w-3.5 h-3.5"}),m(`${a}.analytics.syncYesterday`)]}),e.jsxs("button",{onClick:()=>Z("backfill"),disabled:_,className:"flex items-center gap-1.5 text-xs px-3 py-1.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors",children:[_?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ge,{className:"w-3.5 h-3.5"}),m(`${a}.analytics.syncBackfill6mo`)]})]})]})}),H.length>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-1",children:[e.jsx(Vt,{className:"w-4 h-4"})," ",m(`${a}.analytics.spend`)]}),e.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:S(h.spend,V)})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-1",children:[e.jsx(Bt,{className:"w-4 h-4"})," ",m(`${a}.analytics.leads`)]}),e.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:x(h.leads)})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-1",children:[e.jsx(Ut,{className:"w-4 h-4"})," CPL"]}),e.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:h.cpl!==null?S(h.cpl,V):"â"})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-1",children:[e.jsx(Kt,{className:"w-4 h-4"})," ",m(`${a}.analytics.impressionsClicks`)]}),e.jsxs("div",{className:"text-lg font-bold text-gray-900 dark:text-white",children:[x(h.impressions)," ",e.jsx("span",{className:"text-sm font-normal text-gray-400",children:"/"})," ",x(h.clicks)]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["CTR: ",h.ctr.toFixed(2),"%"]})]})]}),!P&&H.length===0&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center",children:[e.jsx(ct,{className:"w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-3"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-4",children:m(`${a}.analytics.emptyPeriod`)}),e.jsxs("button",{onClick:()=>Z("backfill"),disabled:_,className:"inline-flex items-center gap-2 px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors",children:[e.jsx(ge,{className:"w-4 h-4"}),m(`${a}.analytics.loadData6mo`)]})]}),o.length>0&&e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50",children:[e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-300 w-8"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:m(`${a}.columns.campaignCreative`)}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:m(`${a}.columns.spend`)}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:m(`${a}.columns.leads`)}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:"CPL"}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:m(`${a}.columns.impressions`)}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:m(`${a}.columns.clicks`)}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-300",children:"CTR"})]})}),e.jsxs("tbody",{children:[o.map(r=>{const g=I===r.campaign_id,y=r.leads>0?r.spend/r.leads:null,q=r.impressions>0?r.clicks/r.impressions*100:0,L=(()=>{const $=new Map;for(const D of r.ads){const ne=D.ad_id||D.ad_name||"unknown";$.has(ne)||$.set(ne,{ad_id:D.ad_id||"",ad_name:D.ad_name||"",spend:0,leads:0,impressions:0,clicks:0});const ae=$.get(ne);ae.spend+=Number(D.spend),ae.leads+=D.leads,ae.impressions+=D.impressions,ae.clicks+=D.clicks}return Array.from($.values()).sort((D,ne)=>ne.spend-D.spend)})();return e.jsxs(xe.Fragment,{children:[e.jsxs("tr",{onClick:()=>G(g?null:r.campaign_id),className:"border-b border-gray-100 dark:border-gray-700/50 hover:bg-gray-50 dark:hover:bg-gray-700/30 cursor-pointer transition-colors",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx(he,{className:M("w-4 h-4 text-gray-400 transition-transform",g&&"rotate-90")})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-gray-900 dark:text-white",children:r.campaign_name}),e.jsxs("div",{className:"text-xs text-gray-400",children:[r.account_name," · ",m(`${a}.analytics.adsCount`,{count:L.length})]})]}),e.jsx("td",{className:"px-4 py-3 text-right font-semibold text-gray-900 dark:text-white",children:S(r.spend,r.currency)}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx("span",{className:M("font-semibold",r.leads>0?"text-green-600 dark:text-green-400":"text-gray-400"),children:r.leads})}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-700 dark:text-gray-300",children:y!==null?S(y,r.currency):"â"}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500",children:x(r.impressions)}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500",children:x(r.clicks)}),e.jsxs("td",{className:"px-4 py-3 text-right text-gray-500",children:[q.toFixed(2),"%"]})]}),g&&L.map($=>{const D=$.leads>0?$.spend/$.leads:null,ne=$.impressions>0?$.clicks/$.impressions*100:0,ae=$.ad_id?p[$.ad_id]:null;return e.jsxs("tr",{className:"border-b border-gray-50 dark:border-gray-700/30 bg-gray-50/50 dark:bg-gray-800/30",children:[e.jsx("td",{className:"px-4 py-2.5"}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[ae!=null&&ae.thumbnail?e.jsxs("div",{className:"relative w-10 h-10 rounded-lg overflow-hidden flex-shrink-0 border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700",children:[e.jsx("img",{src:ae.thumbnail,alt:"",className:"w-full h-full object-cover"}),ae.video_id&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx(qt,{className:"w-4 h-4 text-white"})})]}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex-shrink-0 border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 flex items-center justify-center",children:e.jsx(Ke,{className:"w-4 h-4 text-gray-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-gray-700 dark:text-gray-300 truncate max-w-xs",children:$.ad_name}),e.jsx("div",{className:"text-[10px] text-gray-400",children:$.ad_id})]})]})}),e.jsx("td",{className:"px-4 py-2.5 text-right text-gray-700 dark:text-gray-300",children:S($.spend,r.currency)}),e.jsx("td",{className:"px-4 py-2.5 text-right",children:e.jsx("span",{className:M("font-medium",$.leads>0?"text-green-600 dark:text-green-400":"text-gray-400"),children:$.leads})}),e.jsx("td",{className:"px-4 py-2.5 text-right text-gray-500",children:D!==null?S(D,r.currency):"â"}),e.jsx("td",{className:"px-4 py-2.5 text-right text-gray-400",children:x($.impressions)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-gray-400",children:x($.clicks)}),e.jsxs("td",{className:"px-4 py-2.5 text-right text-gray-400",children:[ne.toFixed(2),"%"]})]},$.ad_id||$.ad_name)})]},r.campaign_id)}),e.jsxs("tr",{className:"bg-gray-50 dark:bg-gray-800/80 border-t-2 border-gray-200 dark:border-gray-600 font-semibold",children:[e.jsx("td",{className:"px-4 py-3"}),e.jsx("td",{className:"px-4 py-3 text-gray-700 dark:text-gray-200",children:m(`${a}.analytics.totalCampaigns`,{count:o.length})}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-900 dark:text-white",children:S(h.spend,V)}),e.jsx("td",{className:"px-4 py-3 text-right text-green-600 dark:text-green-400",children:h.leads}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-700 dark:text-gray-300",children:h.cpl!==null?S(h.cpl,V):"â"}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500",children:x(h.impressions)}),e.jsx("td",{className:"px-4 py-3 text-right text-gray-500",children:x(h.clicks)}),e.jsxs("td",{className:"px-4 py-3 text-right text-gray-500",children:[h.ctr.toFixed(2),"%"]})]})]})]})})]})}function xa(){const{t:s,language:m}=ie(),N=Ee[m],[n,i]=l.useState("leads"),[u,F]=l.useState([]),[j,A]=l.useState([]),[b,P]=l.useState([]),[U,C]=l.useState(!0),[z,I]=l.useState(!1),[G,ee]=l.useState(null),[Y,_]=l.useState(null),[w,T]=l.useState(!1),[c,f]=l.useState(null),[p,K]=l.useState({}),[Z,H]=l.useState(null),[h,o]=l.useState({}),[k,S]=l.useState({}),[x,V]=l.useState([]),[J,r]=l.useState(!1),[,g]=l.useState("idle"),[y,q]=l.useState(null),L=l.useRef(null),[$,D]=l.useState(!1),[ne,ae]=l.useState(null),oe=l.useRef(null),[R,E]=l.useState(null),[W,de]=l.useState([]),[ve,qe]=l.useState(!1),[He,ze]=l.useState(!1),[ue,ht]=l.useState(""),[ye,yt]=l.useState(""),[Ne,Je]=l.useState(""),[_e,bt]=l.useState(!1),we=l.useCallback(async()=>{try{const t=await fetch("/.netlify/functions/sendpulse-api?action=config");if(t.ok){const d=await t.json();E(d),d.list_id&&Je(d.list_id)}}catch(t){console.warn("SP config error",t)}},[]),Ge=l.useCallback(async()=>{qe(!0);try{const t=await fetch("/.netlify/functions/sendpulse-api?action=lists");if(t.ok){const d=await t.json();de(Array.isArray(d)?d:[])}}catch(t){console.warn("SP lists error",t)}qe(!1)},[]),Fe=l.useCallback(async t=>{ze(!0);try{const d=W.find(te=>String(te.id)===Ne),v={...ue&&{client_id:ue},...ye&&{client_secret:ye},list_id:Ne||null,list_name:(d==null?void 0:d.name)||null,...t},B=await fetch("/.netlify/functions/sendpulse-api?action=save-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)}),Q=await B.text();let O=null;try{O=JSON.parse(Q)}catch{}B.ok?(X.success(s(`${a}.toasts.spConfigSaved`)),await we()):X.error((O==null?void 0:O.error)||s(`${a}.errors.httpError`,{status:B.status,text:Q.slice(0,120)}))}catch(d){X.error(d instanceof Error?d.message:String(d))}ze(!1)},[ue,ye,Ne,W,we,s]),ft=async()=>
1{if(!$){D(!0),ae(s(`${a}.sync.starting`));try{const t=await fetch("/.netlify/functions/meta-backfill-leads-background?months=6");if(!t.ok&&t.status!==202)throw new Error(`HTTP ${t.status}`);ae(s(`${a}.sync.leadsBackfill6mo`)),oe.current&&clearInterval(oe.current),oe.current=setInterval(async()=>{const{data:d}=await se.from("meta_sync_status").select("*").eq("id","leads_backfill").single();d&&(ae(d.message||d.status),(d.status==="done"||d.status==="error")&&(clearInterval(oe.current),D(!1),d.status==="done"?(X.success(d.message||s(`${a}.toasts.leadsLoaded`)),be()):X.error(d.message||s(`${a}.toasts.loadFailed`)),ae(null)))},5e3)}catch(t){X.error(s(`${a}.toasts.startFailed`,{message:t instanceof Error?t.message:String(t)})),D(!1),ae(null)}}},jt=async t=>{if(c===t){f(null);return}f(t),H(t);const{data:d}=await se.from("meta_lead_logs").select("*").eq("meta_lead_id",t).order("created_at",{ascending:!1});K(v=>({...v,[t]:d||[]})),H(null)},be=l.useCallback(async()=>{const{data:t}=await se.from("meta_leads").select("*").order("created_at",{ascending:!1}).limit(100);if(t){F(t);const d=t.filter(v=>!v.sent_to_kommo).map(v=>v.id);if(d.length>0){const{data:v}=await se.from("meta_lead_logs").select("meta_lead_id, status, error_message").in("meta_lead_id",d).order("created_at",{ascending:!1});if(v){const B={},Q={};for(const O of v)B[O.meta_lead_id]||(B[O.meta_lead_id]=O.status,O.error_message&&(Q[O.meta_lead_id]=O.error_message));o(B),S(Q)}}}},[]),We=l.useCallback(async()=>{try{const d=await(await fetch("/.netlify/functions/kommo-fetch-fields?type=pipelines")).json();d.pipelines&&A(d.pipelines)}catch{}},[]),Se=l.useCallback(async()=>{const{data:t}=await se.from("meta_campaign_mapping").select("*").order("created_at",{ascending:!1});t&&P(t.map(d=>({...d,field_mappings:d.field_mappings||[]})))},[]),$e=l.useCallback(async()=>{const{data:t}=await se.from("meta_ad_campaigns").select("*").order("synced_at",{ascending:!1});t&&V(t)},[]),kt=async()=>{if(!J){r(!0),g("running");try{await fetch("/.netlify/functions/meta-sync-campaigns-background"),X.success(s(`${a}.toasts.syncStarted`)),L.current&&clearInterval(L.current),L.current=setInterval(async()=>{const{data:t}=await se.from("meta_sync_status").select("*").eq("id","campaigns").single();t&&(g(t.status),t.status==="done"?(clearInterval(L.current),L.current=null,r(!1),X.success(s(`${a}.toasts.campaignsSynced`,{count:t.campaigns_synced})),await $e()):t.status==="error"&&(clearInterval(L.current),L.current=null,r(!1),X.error(s(`${a}.errors.withDetails`,{details:t.error}))))},5e3)}catch(t){X.error(t instanceof Error?t.message:String(t)),r(!1),g("error")}}};l.useEffect(()=>{Promise.all([be(),We(),Se(),$e(),we()]).finally(()=>C(!1))},[be,We,Se,$e,we]);const Qe=t=>{if(t.form_id){const d=b.find(v=>v.form_id&&String(v.form_id)===String(t.form_id));if(d)return d}if(t.campaign_id){const d=b.find(v=>v.campaign_id&&String(v.campaign_id)===String(t.campaign_id));if(d)return d}if(t.campaign_name){const d=t.campaign_name.toLowerCase();return b.find(v=>v.campaign_name&&v.campaign_name.toLowerCase()===d)}},[Ae,Xe]=l.useState(null),vt=async(t,d)=>{const v=Qe(t),B=v==null?void 0:v.pipeline_id;if(!B){X.error(s(`${a}.errors.specifyPipelineCampaign`));return}Xe(t.id);let Q=!1;try{const O=await fetch("/api/meta-lead-to-kommo",{method:"POST",headers:await Ft(),body:JSON.stringify({lead_id:t.id,pipeline_id:B})}),te=await O.json();if(!O.ok)throw new Error(te.error||s(`${a}.errors.kommo`));Q=!0;let le="";if(t.email&&(R!=null&&R.enabled))try{(await fetch("/.netlify/functions/sendpulse-api?action=add-contact",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t.email,name:t.full_name||void 0,phone:t.phone||void 0,variables:t.campaign_name?[{name:"Campaign",value:t.campaign_name}]:[]})})).ok&&(await se.from("meta_leads").update({sent_to_sendpulse:!0,sent_to_sendpulse_at:new Date().toISOString()}).eq("id",t.id),le=s(`${a}.toasts.kommoSpSuffix`))}catch{}X.success(s(`${a}.toasts.kommoSuccess`,{id:te.kommo_lead_id,sp:le})),await be()}catch(O){Q||o(te=>({...te,[t.id]:"error"})),X.error(O instanceof Error?O.message:String(O))}finally{Xe(null)}},fe=async(t,d,v,B,Q,O,te,le,De)=>
1{const Ie=j.find(Te=>String(Te.id)===B),Pe=te?W.find(Te=>String(Te.id)===String(te)):null,Ye={campaign_id:d||null,campaign_name:v||null,pipeline_id:B,pipeline_name:(Ie==null?void 0:Ie.name)||null,auto_send:Q,updated_at:new Date().toISOString(),...le!==void 0&&{form_id:le||null},...De!==void 0&&{form_name:De||null},...O!==void 0&&{field_mappings:O},...te!==void 0&&{sendpulse_list_id:te||null,sendpulse_list_name:(Pe==null?void 0:Pe.name)||null}};t?await se.from("meta_campaign_mapping").update(Ye).eq("id",t):await se.from("meta_campaign_mapping").insert([{...Ye,field_mappings:O||[]}]),await Se(),X.success(s(`${a}.toasts.saved`))},Nt=["OUTCOME_LEADS","LEAD_GENERATION"],_t=x.filter(t=>t.effective_status==="ACTIVE"&&Nt.includes(t.objective||"")),wt=(()=>{const t=new Map;for(const d of u){if(!d.form_id||d.form_id==="444444444444")continue;const v=t.get(d.form_id);v?(v.leads_count+=1,!v.campaign_name&&d.campaign_name&&(v.campaign_name=d.campaign_name),!v.campaign_id&&d.campaign_id&&(v.campaign_id=d.campaign_id)):t.set(d.form_id,{form_id:d.form_id,campaign_id:d.campaign_id,campaign_name:d.campaign_name,leads_count:1})}return Array.from(t.values()).sort((d,v)=>v.leads_count-d.leads_count)})(),St=new Set(b.filter(t=>t.form_id).map(t=>String(t.form_id))),je=wt.filter(t=>!St.has(t.form_id)),$t=new Set(x.map(t=>t.campaign_id)),Ct=Array.from(new Map(u.filter(t=>(t.campaign_id||t.campaign_name)&&!$t.has(t.campaign_id||"")).map(t=>[t.campaign_id||t.campaign_name,{id:t.campaign_id,name:t.campaign_name}])).values()),Lt=[..._t.map(t=>({id:t.campaign_id,name:t.campaign_name}
1)),...Ct],Et=new Set(b.filter(t=>!t.form_id).map(t=>t.campaign_id||t.campaign_name)),Ce=Lt.filter(t=>!Et.has(t.id||t.name));return U?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(re,{className:"w-8 h-8 animate-spin text-blue-500"})}):e.jsxs("div",{className:"p-6 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:s(`${a}.title`)}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:s(`${a}.subtitle`)})]}),e.jsxs("div",{className:"flex gap-2",children:[n==="leads"&&e.jsxs("button",{onClick:()=>I(!z),className:"flex items-center gap-2 px-3 py-2 text-sm bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",children:[e.jsx(Pt,{className:"w-4 h-4"}),s(`${a}.actions.configurator`),z?e.jsx(Ze,{className:"w-4 h-4"}):e.jsx(pe,{className:"w-4 h-4"})]}),n==="campaigns"&&e.jsxs("div",{className:"flex items-center gap-2",children:[J&&e.jsx("span",{className:"text-xs text-purple-500 dark:text-purple-400 animate-pulse",children:s(`${a}.sync.allAccounts`)}),e.jsxs("button",{onClick:kt,disabled:J,className:"flex items-center gap-2 px-3 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors",children:[J?e.jsx(re,{className:"w-4 h-4 animate-spin"}):e.jsx(ge,{className:"w-4 h-4"}),s(J?`${a}.sync.syncing`:`${a}.actions.syncMeta`)]})]}),n==="leads"&&e.jsxs("div",{className:"flex items-center gap-2",children:[ne&&e.jsx("span",{className:"text-xs text-purple-500 dark:text-purple-400 animate-pulse max-w-[200px] truncate",children:ne}),e.jsxs("button",{onClick:ft,disabled:$,title:s(`${a}.actions.leadsBackfillTitle`),className:"flex items-center gap-2 px-3 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors",children:[$?e.jsx(re,{className:"w-4 h-4 animate-spin"}):e.jsx(Tt,{className:"w-4 h-4"}),s($?"common.loading":`${a}.actions.leadsBackfill6mo`)]})]}),e.jsxs("button",{onClick:()=>{C(!0),(n==="leads"?be():$e()).finally(()=>C(!1))},className:"flex items-center gap-2 px-3 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:[e.jsx(ge,{className:"w-4 h-4"}),s(`${a}.actions.refresh`)]})]})]}),e.jsxs("div",{className:"flex gap-1 bg-gray-100 dark:bg-gray-800 rounded-xl p-1",children:[e.jsxs("button",{onClick:()=>i("leads"),className:M("flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",n==="leads"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"),children:[e.jsx(et,{className:"w-4 h-4"}),s(`${a}.tabs.leads`,{count:u.length})]}),e.jsxs("button",{onClick:()=>i("campaigns"),className:M("flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",n==="campaigns"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"),children:[e.jsx(Re,{className:"w-4 h-4"}),s(`${a}.tabs.campaigns`,{count:x.length})]}),e.jsxs("button",{onClick:()=>i("analytics"),className:M("flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",n==="analytics"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"),children:[e.jsx(ct,{className:"w-4 h-4"}),s(`${a}.tabs.analytics`)]}),e.jsxs("button",{onClick:()=>i("routing"),className:M("flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",n==="routing"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"),children:[e.jsx(dt,{className:"w-4 h-4"}),"ÐаÑÑÑÑÑи в Kommo"]})]}),n==="routing"&&e.jsx(Wt,{}),n==="campaigns"&&e.jsx(ea,{campaigns:x,expandedCampaignId:y,setExpandedCampaignId:q}),n==="analytics"&&e.jsx(Yt,{campaigns:x}),n==="leads"&&e.jsxs(e.Fragment,{children:[z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"font-semibold text-gray-800 dark:text-white flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5 text-blue-500"}),s(`${a}.mapping.title`)]}),e.jsxs("button",{onClick:()=>T(!0),className:"flex items-center gap-1.5 text-sm px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:[e.jsx(Ue,{className:"w-4 h-4"}),s(`${a}.actions.addCampaign`)]})]}),w&&e.jsx(ta,{pipelines:j,onSave:(t,d,v,B)=>{fe(null,t,d,v,B,[]),T(!1)},onCancel:()=>T(!1)}),b.length===0&&Ce.length===0&&je.length===0?e.jsx("p",{className:"text-sm text-gray-400 italic",children:s(`${a}.empty.noRules`)}):e.jsxs("div",{className:"space-y-2",children:[b.map(t=>{var Q;const d=!!t.form_id,v=d?t.form_name||s(`${a}.mapping.formFallback`,{id:t.form_id??""}):t.campaign_name||t.campaign_id||s(`${a}.mapping.noName`),B=d&&t.campaign_name?s(`${a}.mapping.campaignPrefix`,{name:t.campaign_name}):null;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg",children:[e.jsx(ce,{className:"w-4 h-4 text-green-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 px-1.5 py-0.5 rounded",children:s(`${a}.mapping.formBadge`)}),e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-white truncate",children:v}),d&&t.form_id&&e.jsxs("span",{className:"text-xs text-gray-400 font-mono hidden sm:inline",children:["#",t.form_id]}),!d&&t.campaign_id&&e.jsxs("span",{className:"text-xs text-gray-400 font-mono hidden sm:inline",children:["#",t.campaign_id]})]}),B&&e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate",children:B})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-xs text-blue-600 dar
1k:text-blue-400 bg-blue-50 dark:bg-blue-900/20 px-2 py-0.5 rounded-full",children:t.pipeline_name||`#${t.pipeline_id}`}),t.sendpulse_list_name&&e.jsxs("span",{className:"text-xs text-emerald-700 dark:text-emerald-300 bg-emerald-50 dark:bg-emerald-900/20 px-2 py-0.5 rounded-full",title:`SendPulse â ${t.sendpulse_list_name}`,children:["SP: ",t.sendpulse_list_name]}),t.auto_send&&e.jsx("span",{className:"text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 px-1.5 py-0.5 rounded",children:s(`${a}.mapping.autoBadge`)}),e.jsx("span",{className:"text-xs text-gray-400",children:s(`${a}.mapping.fieldsCount`,{count:((Q=t.field_mappings)==null?void 0:Q.length)||0})}),e.jsx("button",{onClick:()=>_(Y===t.id?null:t.id),className:"text-xs px-2 py-1 bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded hover:bg-purple-200 dark:hover:bg-purple-900/50 transition-colors",children:s(`${a}.actions.fields`)}),e.jsx("button",{onClick:()=>ee(G===t.id?null:t.id),className:"text-xs px-2 py-1 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors",children:s(`${a}.actions.edit`)}),e.jsx("button",{onClick:async()=>{await se.from("meta_campaign_mapping").delete().eq("id",t.id),await Se()},className:"text-xs px-1.5 py-1 text-red-400 hover:text-red-600 transition-colors",children:e.jsx(xt,{className:"w-3.5 h-3.5"})})]})]}),G===t.id&&e.jsx("div",{className:"mt-1 ml-4 p-3 border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800",children:e.jsx(aa,{pipelines:j,spLists:W,initialPipelineId:t.pipeline_id,initialAutoSend:t.auto_send,initialSendPulseListId:t.sendpulse_list_id||null,onSave:(O,te,le)=>{fe(t.id,t.campaign_id,t.campaign_name,O,te,void 0,le,t.form_id||null,t.form_name||null),ee(null)},onCancel:()=>ee(null)})}),Y===t.id&&e.jsx("div",{className:"mt-1 ml-4",children:e.jsx(sa,{mapping:t,leads:u,onSave:O=>{fe(t.id,t.campaign_id,t.campaign_name,t.pipeline_id,t.auto_send,O,t.sendpulse_list_id||null,t.form_id||null,t.form_name||null),_(null)},onCancel:()=>_(null)})})]},t.id)}),je.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 pt-1 pb-0.5",children:[e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-gray-700"}),e.jsx("span",{className:"text-[11px] text-gray-400 font-medium uppercase tracking-wide",children:s(`${a}.mapping.unmappedForms`,{count:je.length})}),e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-gray-700"})]}),je.map(t=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-indigo-50 dark:bg-indigo-900/10 rounded-lg border border-indigo-200 dark:border-indigo-800/30",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-indigo-300 dark:border-indigo-600 flex-shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 px-1.5 py-0.5 rounded",children:s(`${a}.mapping.formBadge`)}),e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-white truncate",children:t.campaign_name||s(`${a}.mapping.formFallback`,{id:t.form_id})}),e.jsxs("span",{className:"text-xs text-gray-400 font-mono hidden sm:inline",children:["#",t.form_id]}),e.jsx("span",{className:"text-[10px] text-gray-500 bg-gray-100 dark:bg-gray-700 px-1.5 py-0.5 rounded",children:s(`${a}.mapping.leadsCount`,{count:t.leads_count})})]})}),e.jsx(it,{pipelines:j,onSave:d=>{fe(null,t.campaign_id,t.campaign_name,d,!1,[],null,t.form_id,t.campaign_name||s(`${a}.mapping.formFallbackShort`,{id:t.form_id}))}})]},t.form_id))]}),Ce.length>0&&e.jsxs(e.Fragment,{children:[(b.length>0||je.length>0)&&e.jsxs("div",{className:"flex items-center gap-2 pt-1 pb-0.5",children:[e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-gray-700"}),e.jsx("span",{className:"text-[11px] text-gray-400 font-medium uppercase tracking-wide",children:s(`${a}.mapping.unmappedCampaigns`,{count:Ce.length})}),e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-gray-700"})]}),Ce.map(t=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-orange-50 dark:bg-orange-900/10 rounded-lg border border-orange-200 dark:border-orange-800/30",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-orange-300 dark:border-orange-600 flex-shrink-0"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 flex-1 truncate",children:t.name||t.id}),t.id&&e.jsxs("span",{className:"text-xs text-gray-400 font-mono hidden sm:inline",children:["#",t.id]}),e.jsx(it,{pipelines:j,onSave:d=>{fe(null,t.id,t.name,d,!1,[])}})]},t.id||t.name))]})]})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden",children:[e.jsxs("button",{onClick:()=>{bt(!_e),!_e&&(R!=null&&R.has_credentials)&&Ge()},className:"w-full px-5 py-4 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-purple-500"}),e.jsx("span",{className:"font-semibold text-gray-800 dark:text-white",children:s(`${a}.sendPulse.title`)}),(R==null?void 0:R.enabled)&&e.jsx("span",{className:"text-[10px] bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 px-1.5 py-0.5 rounded font-medium",children:s(`${a}.sendPulse.active`)}),(R==null?void 0:R.list_name)&&e.jsx("span",{className:"text-xs text-purple-600 dar
1k:text-purple-400 bg-purple-50 dark:bg-purple-900/20 px-2 py-0.5 rounded-full",children:R.list_name})]}),_e?e.jsx(Ze,{className:"w-4 h-4 text-gray-400"}):e.jsx(pe,{className:"w-4 h-4 text-gray-400"})]}),_e&&e.jsxs("div",{className:"px-5 pb-5 space-y-4 border-t border-gray-200 dark:border-gray-700 pt-4",children:[e.jsx("p",{className:"text-xs text-gray-500",children:s(`${a}.sendPulse.hint`)}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Client ID"}),e.jsx("input",{type:"text",placeholder:R!=null&&R.has_credentials?"â¢â¢â¢â¢â¢â¢â¢â¢":s(`${a}.sendPulse.clientIdPlaceholder`),value:ue,onChange:t=>ht(t.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Client Secret"}),e.jsx("input",{type:"password",placeholder:R!=null&&R.has_credentials?"â¢â¢â¢â¢â¢â¢â¢â¢":s(`${a}.sendPulse.clientSecretPlaceholder`),value:ye,onChange:t=>yt(t.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white"})]})]}),(ue||(R==null?void 0:R.has_credentials))&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:async()=>{ue&&ye&&await Fe({enabled:(R==null?void 0:R.enabled)||!1}),Ge()},disabled:ve,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors",children:[ve?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ge,{className:"w-3.5 h-3.5"}),s(`${a}.actions.loadLists`)]}),e.jsxs("button",{onClick:async()=>{var t;try{const v=await(await fetch("/.netlify/functions/sendpulse-api?action=test")).json(),B=(t=v.steps)==null?void 0:t[v.steps.length-1];(B==null?void 0:B.ok)===!1?X.error(`SendPulse: ${B.error||B.step}`):X.success(s(`${a}.toasts.spConnectionOk`)),console.log("SendPulse test:",v)}catch(d){X.error(d instanceof Error?d.message:String(d))}},className:"flex items-center gap-1.5 text-sm px-3 py-1.5 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",children:[e.jsx(ce,{className:"w-3.5 h-3.5"}),s(`${a}.actions.test`)]})]}),W.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:s(`${a}.sendPulse.mailingList`)}),e.jsxs("select",{value:Ne,onChange:t=>Je(t.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-white",children:[e.jsx("option",{value:"",children:s(`${a}.sendPulse.selectList`)}),W.map(t=>e.jsxs("option",{value:String(t.id),children:[t.name," (",s(`${a}.sendPulse.contactsCount`,{count:t.all_email_qty}),")"]},t.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:(R==null?void 0:R.enabled)||!1,onChange:t=>Fe({enabled:t.target.checked}),className:"w-4 h-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:s(`${a}.sendPulse.autoTransfer`)})]}),e.jsxs("button",{onClick:()=>Fe(),disabled:He,className:"flex items-center gap-1.5 text-sm px-4 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors",children:[He?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ce,{className:"w-3.5 h-3.5"}),s("common.save")]})]})]})]})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between",children:[e.jsx("span",{className:"font-semibold text-gray-800 dark:text-white",children:s(`${a}.leads.tableTitle`,{count:u.length})}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ce,{className:"w-4 h-4 text-green-500"}),s(`${a}.leads.sentCount`,{count:u.filter(t=>t.sent_to_kommo).length})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tt,{className:"w-4 h-4 text-yellow-500"}),s(`${a}.leads.newCount`,{count:u.filter(t=>!t.sent_to_kommo).length})]})]})]}),e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700",children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:s(`${a}.columns.contact`)}),e.jsx("th",{className:"px-4 py-3 font-medium",children:s(`${a}.columns.campaignAd`)}),e.jsx("th",{className:"px-4 py-3 font-medium",children:s(`${a}.columns.pipeline`)}),e.jsx("th",{className:"px-4 py-3 font-medium",children:s(`${a}.columns.sent`)}),e.jsx("th",{className:"px-4 py-3 font-medium",children:s(`${a}.columns.date`)}),e.jsx("th",{className:"px-4 py-3 font-medium w-10"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:u.map(t=>{const d=Qe(t),v=c===t.id,B=p[t.id]||[];return e.jsxs(xe.Fragment,{children:[e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"space-y-1",children:[t.full_name&&e.jsxs("div",{className:"flex items-center gap-1.5 font-medium text-gray-800 dark:text-white",children:[e.jsx(et,{className:"w-3.5 h-3.5 text-gray-400"}),t.full_name]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-500 dark:text-gray-400 text-xs",children:[e.jsx(Mt,{className:"w-3 h-3"}),t.phone]}),t.email&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-500 dark:text-gray-400 text-xs",children:[e.jsx(Ot,{className:"w-3 h-3"}),t.email]}),!t.full_name&&!t.phone&&!t.email&&e.jsx("span",{className:"text-xs text-gray-400 italic",children:s(`${a}.empty.noData`)})]})}),e.jsx("td",{className:"px-4 py-3 max-w-[200px]",children:e.jsxs("div",{className:"space-y-1",children:[t.platform&&e.jsxs("span",{className:M("inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium",t.platform==="instagram"?"bg-pink-100 dark:bg-pink-900/30 text-pink-600 dark:text-pink-400":"bg-blue-100 dar
1k:bg-blue-900/30 text-blue-600 dark:text-blue-400"),children:[e.jsx(Ht,{className:"w-2.5 h-2.5"}),t.platform==="instagram"?"IG":"FB"]}),t.campaign_name&&e.jsxs("div",{title:t.campaign_name,className:"flex items-start gap-1 text-xs font-medium text-gray-700 dark:text-gray-200",children:[e.jsx(Ve,{className:"w-3 h-3 text-blue-400 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"line-clamp-2 leading-tight",children:t.campaign_name})]}),t.ad_name&&e.jsx("div",{title:t.ad_name,className:"text-[11px] text-gray-400 dark:text-gray-500 pl-4 line-clamp-1",children:t.ad_name}),!t.campaign_name&&!t.ad_name&&e.jsx("span",{className:"text-xs text-gray-400 italic",children:s(`${a}.leads.testLead`)})]})}),e.jsx("td",{className:"px-4 py-3",children:d?e.jsx("span",{className:"text-xs text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 px-2 py-0.5 rounded-full",children:d.pipeline_name||`#${d.pipeline_id}`}):t.campaign_id||t.campaign_name?e.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[e.jsx(tt,{className:"w-3 h-3"}),s(`${a}.kommo.notConfigured`)]}):e.jsx("span",{className:"text-xs text-gray-400",children:"â"})}),e.jsx("td",{className:"px-4 py-3",children:(()=>{const Q=h[t.id],O=!t.sent_to_kommo&&Q==="error",te=!t.sent_to_kommo&&Q==="skipped",le=k[t.id];return e.jsxs("button",{onClick:()=>jt(t.id),title:le||void 0,className:M("group flex items-center gap-1.5 text-xs rounded-lg px-2.5 py-1.5 transition-all cursor-pointer",t.sent_to_kommo?v?"bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300 ring-1 ring-green-300 dark:ring-green-700":"text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20":O?v?"bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 ring-1 ring-red-300 dark:ring-red-700":"text-red-500 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20":te?v?"bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 ring-1 ring-amber-300 dark:ring-amber-700":"text-amber-600 dark:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-900/20":v?"bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 ring-1 ring-gray-300 dark:ring-gray-600":"text-gray-400 dark:text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-800"),children:[t.sent_to_kommo?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"w-4 h-4"}),e.jsx("span",{className:"font-medium",children:s(`${a}.leads.sent`)}),t.kommo_lead_id&&e.jsxs("span",{className:"text-green-500/70 dark:text-green-400/60",children:["#",t.kommo_lead_id]})]}):O?e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"w-4 h-4"}),e.jsx("span",{className:"font-medium",children:s(`${a}.leads.error`)})]}):te?e.jsxs(e.Fragment,{children:[e.jsx(ut,{className:"w-4 h-4"}),e.jsx("span",{className:"font-medium",children:"ÐÑопÑÑено"}),le&&e.jsxs("span",{className:"hidden lg:inline text-amber-500/80 dark:text-amber-400/70 truncate max-w-[220px]",children:["· ",le]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-gray-300 dark:border-gray-600 flex-shrink-0"}),e.jsx("span",{children:s(`${a}.leads.pending`)})]}),e.jsx(pe,{className:M("w-3 h-3 transition-transform ml-0.5",t.sent_to_kommo?"text-green-400":O?"text-red-400":te?"text-amber-400":"text-gray-400",v&&"rotate-180")})]})})()}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-400",children:e.jsx("div",{className:"space-y-0.5",children:t.meta_created_time?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-gray-700 dark:text-gray-300 font-medium",children:new Date(t.meta_created_time).toLocaleString(N,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsx("div",{className:"text-[10px] text-gray-400",children:s(`${a}.leads.fillTime`)})]}):new Date(t.created_at).toLocaleString(N,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"flex flex-col items-end gap-1.5",children:t.sent_to_kommo?e.jsxs("div",{className:"flex items-center gap-1.5",children:[t.kommo_lead_id&&e.jsxs("a",{href:`https://touchcsbua.kommo.com/leads/detail/${t.kommo_lead_id}`,target:"_blank",rel:"noopener noreferrer",title:s(`${a}.actions.openKommo`),className:"flex items-center gap-1 text-[11px] text-blue-500 hover:text-blue-600 hover:underline",children:[e.jsx(gt,{className:"w-3 h-3"}),"Kommo"]}),t.sent_to_sendpulse&&e.jsxs("span",{className:"text-[11px] text-purple-500 flex items-center gap-0.5",children:[e.jsx(ce,{className:"w-3 h-3"}),"SP"]})]}):e.jsxs("button",{onClick:()=>vt(t),disabled:Ae===t.id,title:s(`${a}.actions.sendKommoSp`),className:M("flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg font-medium transition-all",h[t.id]==="error"?"bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30":"bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-100 dark:hover:bg-indigo-900/30",Ae===t.id&&"opacity-50 cursor-not-allowed"),children:[Ae===t.id?e.jsx(re,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Be,{className:"w-3.5 h-3.5"}),h[t.id]==="error"?s(`${a}.actions.retry`):s(`${a}.actions.run`)]})})})]}),v&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-0 py-0",children:e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800/80 border-t border-b border-gray-200 dark:border-gray-700 px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3",children:[t.platform&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.platform`)}),e.jsx("div",{className:M("text-xs font-medium",t.platform==="instagram"?"text-pink-600 dark:text-pink-400":"text-blue-600 dar
1k:text-blue-400"),children:t.platform==="instagram"?"Instagram":"Facebook"})]}),t.is_organic!=null&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.trafficType`)}),e.jsx("div",{className:M("text-xs font-medium",t.is_organic?"text-green-600 dark:text-green-400":"text-purple-600 dark:text-purple-400"),children:t.is_organic?s(`${a}.leads.organic`):s(`${a}.leads.paidAd`)})]}),t.meta_created_time&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.formFilled`)}),e.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:new Date(t.meta_created_time).toLocaleString(N,{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})})]}),t.adset_name&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.adset`)}),e.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-300 truncate",children:t.adset_name})]}),t.creative_id&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.creativeId`)}),e.jsx("div",{className:"text-xs font-mono text-purple-500 dark:text-purple-400 truncate",children:t.creative_id})]}),t.post_id&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.postId`)}),e.jsx("div",{className:"text-xs font-mono text-gray-500 dark:text-gray-400 truncate",children:t.post_id})]}),t.form_id&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] text-gray-400 uppercase tracking-wide mb-0.5",children:s(`${a}.leads.formId`)}),e.jsx("div",{className:"text-xs font-mono text-gray-500 dark:text-gray-400 truncate",children:t.form_id})]})]}),t.field_data&&t.field_data.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-2",children:s(`${a}.leads.allFormFields`)}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.field_data.map((Q,O)=>{var te;return e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5",children:[e.jsxs("span",{className:"text-[10px] text-gray-400",children:[Q.name,": "]}),e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:((te=Q.values)==null?void 0:te[0])||"â"})]},O)})})]}),t.custom_disclaimer_responses!=null&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-2",children:s(`${a}.leads.disclaimer`)}),e.jsx("pre",{className:"text-xs bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2 text-gray-600 dark:text-gray-400 overflow-x-auto",children:JSON.stringify(t.custom_disclaimer_responses,null,2)})]}),e.jsx("div",{children:Z===t.id?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-400 py-2",children:[e.jsx(re,{className:"w-4 h-4 animate-spin"}),s(`${a}.leads.loadingLogs`)]}):B.length===0?e.jsx("div",{className:"text-sm text-gray-400 py-1 italic",children:s(`${a}.leads.noLogs`)}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wide flex items-center gap-1.5",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"}),s(`${a}.leads.transferHistory`,{count:B.length})]}),B.map(Q=>e.jsx(ra,{log:Q},Q.id))]})})]})})})]},t.id)})})]}),u.length===0&&e.jsxs("div",{className:"text-center py-16 text-gray-400",children:[e.jsx(Ve,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:s(`${a}.empty.noLeads`)})]})]})]})]})]})}const me={ACTIVE:"bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400",PAUSED:"bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400",DELETED:"bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400",ARCHIVED:"bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"};function lt(s,m){if(!s)return"â";const N=s/100,n=m||"";return`${N.toFixed(2)} ${n}`}function Zt({ad:s}){const{t:m}=ie(),[N,n]=l.useState(!1),i=!!s.video_id,u=i&&s.page_id?`https://www.facebook.com/${s.page_id}/videos/${s.video_id}`:null,F=s.creative_thumbnail||null,j=()=>{i&&u?window.open(u,"_blank"):n(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden flex flex-col shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative bg-gray-100 dark:bg-gray-900 cursor-pointer group",style:{paddingBottom:"100%"},onClick:j,children:[F?e.jsx("img",{src:F,alt:s.name,className:"absolute inset-0 w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(Ke,{className:"w-8 h-8 text-gray-300 dark:text-gray-600"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center",children:i?e.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex flex-col items-center gap-1.5 transition-opacity",children:[e.jsx("div",{className:"w-12 h-12 bg-white/90 rounded-full flex items-center justify-center shadow-lg",children:e.jsx("svg",{className:"w-6 h-6 text-gray-800 ml-0.5",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"text-white text-[10px] bg-black/60 px-2 py-0.5 rounded-full",children:m(`${a}.actions.playVideo`)})]}):F?e.jsx("span",{className:"opacity-0 group-hover:opacity-100 text-white text-xs bg-black/50 px-2.5 py-1 rounded-full transition-opacity",children:m(`${a}.actions.enlarge`)}):null}),e.jsx("span",{className:M("absolute top-1.5 right-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium shadow-sm",me[s.effective_status]||me.ARCHIVED),children:s.effective_status}),i&&e.jsxs("div",{className:"absolute bottom-1.5 left-1.5 bg-black/70 backdrop-blur-sm rounded-md px-1.5 py-0.5 flex items-center gap-1",children:[e.jsx("svg",{className:"w-2.5 h-2.5 text-white",f
1ill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M8 5v14l11-7z"})}),e.jsx("span",{className:"text-[9px] text-white font-medium",children:m(`${a}.campaigns.video`)})]})]}),e.jsxs("div",{className:"p-2.5 flex flex-col gap-0.5 border-t border-gray-100 dark:border-gray-700",children:[e.jsx("span",{className:"text-xs font-medium text-gray-800 dark:text-gray-200 line-clamp-2 leading-tight",children:s.name}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsxs("span",{className:"text-[10px] text-gray-400 font-mono truncate",children:["#",s.id]}),i&&u&&e.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",onClick:A=>A.stopPropagation(),className:"text-[10px] text-blue-500 hover:text-blue-600 font-medium flex items-center gap-0.5",children:[e.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M8 5v14l11-7z"})}),m(`${a}.campaigns.video`)]})]}),s.creative_id&&e.jsxs("span",{className:"text-[10px] text-purple-500 dark:text-purple-400 font-mono",children:["creative: #",s.creative_id]})]})]}),N&&!i&&F&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/85 flex items-center justify-center p-4",onClick:()=>n(!1),children:e.jsxs("div",{className:"relative w-full max-w-xl",onClick:A=>A.stopPropagation(),children:[e.jsx("img",{src:F,alt:s.name,className:"w-full rounded-xl object-contain max-h-[80vh]"}),e.jsxs("div",{className:"mt-3 text-center",children:[e.jsx("p",{className:"text-white text-sm font-medium",children:s.name}),s.creative_id&&e.jsxs("p",{className:"text-purple-300 text-xs font-mono mt-0.5",children:["creative: #",s.creative_id]})]}),e.jsx("button",{onClick:()=>n(!1),className:"absolute -top-3 -right-3 w-7 h-7 bg-white rounded-full flex items-center justify-center text-gray-700 hover:bg-gray-100 shadow-lg",children:e.jsx(Le,{className:"w-4 h-4"})})]})})]})}function ea({campaigns:s,expandedCampaignId:m,setExpandedCampaignId:N}){const{t:n,language:i}=ie(),u=Ee[i],F=w=>w?n(`${a}.campaigns.objectives.${w}`):"â",[j,A]=l.useState("ACTIVE"),[b,P]=l.useState("ALL"),[U,C]=l.useState(""),z=w=>{if(w.effective_status!=="ACTIVE")return!1;const T=w.ad_sets||[],c=w.ads||[];return!(T.length>0&&T.every(f=>f.effective_status!=="ACTIVE")||c.length>0&&c.every(f=>f.effective_status==="DISAPPROVED"))},I=s.filter(w=>!(j==="ACTIVE"&&!z(w)||j==="PAUSED"&&z(w)||b==="LEADS"&&!["OUTCOME_LEADS","LEAD_GENERATION"].includes(w.objective||"")||U&&!(w.campaign_name||"").toLowerCase().includes(U.toLowerCase()))),G=I.reduce((w,T)=>{const c=T.account_name||T.account_id;return w[c]||(w[c]=[]),w[c].push(T),w},{}),ee=s.filter(z).length,Y=s.length-ee,_=s.filter(w=>["OUTCOME_LEADS","LEAD_GENERATION"].includes(w.objective||"")).length;return s.length===0?e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center",children:[e.jsx(Re,{className:"w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-3",children:n(`${a}.campaigns.emptyTitle`)}),e.jsx("p",{className:"text-sm text-gray-400",children:n(`${a}.campaigns.emptyHint`)})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(pt,{className:"min-w-[200px] [&_input]:text-xs",value:U,onChange:C,placeholder:n(`${a}.filters.search`),title:n(`${a}.filters.searchCampaign`)}),e.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-gray-700"}),e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 font-medium",children:n(`${a}.filters.status`)}),["ALL","ACTIVE","PAUSED"].map(w=>e.jsx("button",{onClick:()=>A(w),className:M("text-xs px-3 py-1.5 rounded-lg font-medium transition-all",j===w?w==="ACTIVE"?"bg-green-600 text-white":w==="PAUSED"?"bg-yellow-500 text-white":"bg-gray-800 dark:bg-gray-200 text-white dark:text-gray-900":"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-500"),children:w==="ALL"?n(`${a}.filters.allStatus`,{count:s.length}):w==="ACTIVE"?n(`${a}.filters.activeStatus`,{count:ee}):n(`${a}.filters.inactiveStatus`,{count:Y})},w)),e.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700 mx-1"}),e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 font-medium",children:n(`${a}.filters.objective`)}),e.jsx("button",{onClick:()=>P("ALL"),className:M("text-xs px-3 py-1.5 rounded-lg font-medium transition-all",b==="ALL"?"bg-gray-800 dark:bg-gray-200 text-white dark:text-gray-900":"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-500"),children:n(`${a}.filters.allObjectives`)}),e.jsx("button",{onClick:()=>P("LEADS"),className:M("text-xs px-3 py-1.5 rounded-lg font-medium transition-all",b==="LEADS"?"bg-blue-600 text-white":"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-500"),children:n(`${a}.filters.leadsOnly`,{count:_})}),I.length!==s.length&&e.jsx("span",{className:"text-xs text-gray-400 ml-1",children:n(`${a}.filters.shownOf`,{shown:I.length,total:s.length})})]}),Object.keys(G).length===0&&e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center text-gray-400 text-sm",children:n(`${a}.campaigns.noFilterMatch`)}),Object.entries(G).map(([w,T])=>{var c,f;return e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-4 h-4 text-blue-500"}),e.jsx("span",{className:"font-semibold text-gray-800 dark:text-white text-sm",children:w}),e.jsx("span",{className:"text-xs text-gray-400 font-mono",children:(c=T[0])==null?void 0:c.account_id})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400",children:[e.jsx("span",{children:n(`${a}.campaigns.campaignsCount`,{count:T.length})}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ce,{className:"w-3.5 h-3.5 text-green-500"}),n(`${a}.campaigns.reallyActive`,{count:T.filter(z).length})]}),((f=T[0])==null?void 0:f.currency)&&e.jsx("span",{className:"font-medium",children:T[0].currency})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-gray-700",children:[e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.campaign`)}),e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.objective`)}),e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.status`)}),e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.budget`)}
1),e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.ads`)}),e.jsx("th",{className:"px-4 py-2.5 font-medium",children:n(`${a}.columns.syncedAt`)}),e.jsx("th",{className:"px-4 py-2.5 font-medium w-10"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:T.map(p=>{var J,r,g,y,q,L,$;const K=m===p.campaign_id,Z=((J=p.ads)==null?void 0:J.length)||0,H=((r=p.ads)==null?void 0:r.filter(D=>D.effective_status==="ACTIVE").length)||0,h=((g=p.ads)==null?void 0:g.filter(D=>D.effective_status==="DISAPPROVED").length)||0,o=Z>0&&h===Z,k=((y=p.ad_sets)==null?void 0:y.length)||0,S=((q=p.ad_sets)==null?void 0:q.filter(D=>D.effective_status==="ACTIVE").length)||0,x=k>0&&S===0,V=p.effective_status==="ACTIVE"&&(x||o);return e.jsxs(xe.Fragment,{children:[e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors cursor-pointer",onClick:()=>N(K?null:p.campaign_id),children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-gray-800 dark:text-white truncate max-w-[280px]",children:p.campaign_name||n(`${a}.mapping.noName`)}),e.jsxs("div",{className:"text-xs text-gray-400 font-mono mt-0.5",children:["#",p.campaign_id]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400",children:F(p.objective)})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:M("text-xs px-2 py-0.5 rounded-full font-medium w-fit",V?me.PAUSED:me[p.effective_status||""]||me.ARCHIVED),children:p.effective_status||"â"}),x&&p.effective_status==="ACTIVE"&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 font-medium w-fit",children:n(`${a}.campaigns.allAdSetsPaused`)}),o&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 font-medium w-fit",children:n(`${a}.campaigns.adsDisapproved`)}),!o&&h>0&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-100 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 font-medium w-fit",children:n(`${a}.campaigns.adsDisapprovedCount`,{count:h})})]})}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-600 dark:text-gray-300",children:p.daily_budget?e.jsxs("div",{children:[lt(p.daily_budget,p.currency),e.jsx("span",{className:"text-gray-400",children:n(`${a}.campaigns.perDay`)})]}):p.lifetime_budget?e.jsxs("div",{children:[lt(p.lifetime_budget,p.currency),e.jsx("span",{className:"text-gray-400",children:" lifetime"})]}):e.jsx("span",{className:"text-gray-400",children:"CBO"})}),e.jsx("td",{className:"px-4 py-3",children:Z>0?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:n(`${a}.campaigns.totalAds`,{count:Z})}),H>0&&e.jsx("span",{className:"text-[10px] text-green-600 dark:text-green-400",children:n(`${a}.campaigns.activeAds`,{count:H})}),h>0&&e.jsx("span",{className:"text-[10px] text-red-500 dark:text-red-400",children:n(`${a}.campaigns.adsDisapprovedCount`,{count:h})})]}):e.jsx("span",{className:"text-xs text-gray-400",children:"â"})}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-400",children:p.synced_at?new Date(p.synced_at).toLocaleString(u,{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"â"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(pe,{className:M("w-4 h-4 text-gray-400 transition-transform",K&&"rotate-180")})})]}),K&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-0 py-0",children:e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800/80 border-t border-gray-200 dark:border-gray-700 px-6 py-4 space-y-4",children:[p.ad_sets&&p.ad_sets.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-2 flex items-center gap-1.5",children:[e.jsx(ot,{className:"w-3.5 h-3.5"}),n(`${a}.campaigns.adSets`,{count:p.ad_sets.length})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2",children:p.ad_sets.map(D=>e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300 truncate",children:D.name}),e.jsx("span",{className:M("text-[10px] px-1.5 py-0.5 rounded-full",me[D.effective_status||""]||me.ARCHIVED),children:D.effective_status})]}),e.jsxs("div",{className:"text-[10px] text-gray-400 font-mono mt-0.5",children:["#",D.id]}),D.optimization_goal&&e.jsx("div",{className:"text-[10px] text-gray-500 mt-1",children:n(`${a}.campaigns.adSetGoal`,{goal:D.optimization_goal})})]},D.id))})]}),p.ads&&p.ads.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-3 flex items-center gap-1.5",children:[e.jsx(Ke,{className:"w-3.5 h-3.5"}),n(`${a}.campaigns.adsCreatives`,{count:p.ads.length})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3",children:p.ads.map(D=>e.jsx(Zt,{ad:D},D.id))})]}),!((L=p.ads)!=null&&L.length)&&!(($=p.ad_sets)!=null&&$.length)&&e.jsx("p",{className:"text-sm text-gray-400 italic",children:n(`${a}.campaigns.noAdSetData`)})]})})})]},p.campaign_id)})})]})})]},w)})]})}function ta({pipelines:s,onSave:m,onCancel:N}){const{t:n}=ie(),[i,u]=l.useState(""),[F,j]=l.useState(""),[A,b]=l.useState(""),[P,U]=l.useState(!1);return e.jsxs("div",{className:"p-4 border border-blue-200 dark:border-blue-800 rounded-lg bg-blue-50 dark:bg-blue-900/10 space-y-3",children:[e.jsx("h3",{className:"text-sm font-medium text-gray-800 dark:text-white",children:n(`${a}.mapping.newCampaign`)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 block",children:n(`${a}.mapping.campaignName`)}),e.jsx("input",{value:i,onChange:C=>u(C.target.value),placeholder:n(`${a}.mapping.campaignNamePlaceholder`),className:"w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 bg-white dark:bg-gray-700 text-gray-800 dark:text-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 block",children:n(`${a}.mapping.campaignIdOptional`)}),e.jsx("input",{value:F,onChange:C=>j(C.target.value),placeholder:n(`${a}.mapping.campaignIdPlaceholder`),className:"w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 bg-white dark:bg-gray-700 text-gray-800 dark:text-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1 block",children:n(`${a}.mapping.kommoPipeline`)}),e.jsxs("select",{value:A,onChange:C=>b(C.target.value),className:"w-full text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 bg-white dark:bg-gray-700 text-gray-800 dark:text-white",children:[e.jsx("option",{value:"",children:n(`${a}.kommo.selectPipeline`)}),s.map(C=>e.jsx("option",{value:String(C.id),children:C.name},C.id))]})]}),e.jsx("div",{className:"flex items-end",children:e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:P,onChange:C=>U(C.target.checked),className:"w-4 h-4 rounded"}),n(`${a}.mapping.autoSendKommo`)]})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>i&&A&&m(F||null,i,A,P),disabled:!i||!A,className:"text-sm px-4 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors",children:n("common.save")}),e.jsx("button",{onClick:N,className:"text-sm px-4 py-1.5 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors",children:n("common.cancel")})]})]})}function aa({pipelines:s,spLists:m,initialPipelineId:N,initialAutoSend:n,initialSendPulseListId:i,onSave:u,onCancel:F}){const{t:j}=ie(),[A,b]=l.useState(N),[P,U]=l.useState(n),[C,z]=l.useState(i||"");return e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("select",{value:A,onChange:I=>b(I.target.value),className:"text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-2 py-1 bg-white dark:bg-gray-700 text-gray-800 dark:text-white",children:[e.jsx("option",{value:"",children:j(`${a}.kommo.selectPipeline`)}),s.map(I=>e.jsx("option",{value:String(I.id),children:I.name},I.id))]}),e.jsxs("select",{value:C,onChange:I=>z(I.target.value),className:"text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-2 py-1 bg-white dark:bg-gray-700 text-gray-800 dark:text-white",title:j(`${a}.mapping.sendPulseListTitle`),children:[e.jsx("option",{value:"",children:j(`${a}.mapping.sendPulseDefault`)}),m.map(I=>
1e.jsxs("option",{value:String(I.id),children:[I.name," (",I.all_email_qty,")"]},I.id))]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:P,onChange:I=>U(I.target.checked),className:"w-3.5 h-3.5 rounded"}),j(`${a}.mapping.autoSendKommo`)]}),e.jsx("button",{onClick:()=>A&&u(A,P,C||null),disabled:!A,className:"text-sm px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 transition-colors",children:j("common.save")}),e.jsx("button",{onClick:F,className:"text-sm px-3 py-1 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded hover:bg-gray-300 transition-colors",children:j("common.cancel")})]})}function sa({mapping:s,leads:m,onSave:N,onCancel:n}){var T;const{t:i}=ie(),[u,F]=l.useState(((T=s.field_mappings)==null?void 0:T.length)>0?s.field_mappings:[{meta_field:"full_name",kommo_field:"name",kommo_field_id:null,fixed_value:null,target:"contact"},{meta_field:"phone",kommo_field:"PHONE",kommo_field_id:null,fixed_value:null,target:"contact"},{meta_field:"email",kommo_field:"EMAIL",kommo_field_id:null,fixed_value:null,target:"contact"}]),[j,A]=l.useState([]),[b,P]=l.useState([]),[U,C]=l.useState(!0);l.useEffect(()=>{Promise.all([fetch("/api/kommo-fetch-fields?type=leads").then(c=>c.json()),fetch("/api/kommo-fetch-fields?type=contacts").then(c=>c.json())]).then(([c,f])=>{A(c.fields||[]),P(f.fields||[])}).catch(()=>{}).finally(()=>C(!1))},[]);const z=Array.from(new Set(m.filter(c=>c.campaign_id===s.campaign_id||c.campaign_name===s.campaign_name).flatMap(c=>(c.field_data||[]).map(f=>f.name)))),I=[...Qt(i),...z.map(c=>({value:`custom:${c}`,label:i(`${a}.mapping.customField`,{name:c})}))],G=c=>{const f=c==="contact"?b:j,p=h=>{const o=i(`${a}.mapping.fieldTypes.${h}`);return o===h||o.includes(".")?h:o},K=i(`${a}.mapping.autoBadge`),Z=c==="contact"?[{value:"name",label:i(`${a}.mapping.kommoStandard.contactName`),badge:K,badgeColor:"bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400"},{value:"PHONE",label:i(`${a}.mapping.kommoStandard.phone`),badge:K,badgeColor:"bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400"},{value:"EMAIL",label:i(`${a}.mapping.kommoStandard.email`),badge:K,badgeColor:"bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400"}]:[],H=f.map(h=>{var o;return{value:`custom:${h.id}`,label:h.name,badge:p(h.field_type)||h.field_type,badgeColor:((o=h.enums)==null?void 0:o.length)>0?"bg-purple-100 dark:bg-purple-900/40 text-purple-600 dark:text-purple-400":"bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"}});return[...Z,...H]},ee=c=>{if(!c.kommo_field_id)return[];const p=[...b,...j].find(K=>String(K.id)===c.kommo_field_id);return(p==null?void 0:p.enums)||[]},Y=(c,f)=>{F(p=>p.map((K,Z)=>Z===c?{...K,...f}:K))},_=(c,f)=>{if(f.startsWith("custom:")){const p=f.replace("custom:","");Y(c,{kommo_field:"custom",kommo_field_id:p,fixed_value:null,fixed_enum_id:null})}else Y(c,{kommo_field:f,kommo_field_id:null,fixed_value:null,fixed_enum_id:null})},w=c=>c.kommo_field_id?`custom:${c.kommo_field_id}`:c.kommo_field;return e.jsxs("div",{className:"p-4 border border-purple-200 dark:border-purple-800 rounded-lg bg-purple-50 dark:bg-purple-900/10 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-gray-800 dark:text-white flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-purple-500"}),i(`${a}.mapping.fieldMatching`,{name:s.campaign_name||s.campaign_id||""})]}),e.jsx("button",{onClick:n,className:"text-gray-400 hover:text-gray-600",children:e.jsx(Le,{className:"w-4 h-4"})})]}),U?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-400",children:[e.jsx(re,{className:"w-4 h-4 animate-spin"}),i(`${a}.mapping.loadingKommoFields`)]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_90px_auto_1fr_auto_auto] gap-2 items-center text-[11px] font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wide px-1",children:[e.jsx("span",{children:i(`${a}.mapping.metaField`)}),e.jsx("span",{}),e.jsx("span",{children:i(`${a}.mapping.target`)}),e.jsx("span",{}),e.jsx("span",{children:i(`${a}.mapping.kommoField`)}),e.jsx("span",{children:i(`${a}.mapping.value`)}),e.jsx("span",{})]}),u.map((c,f)=>{const p=ee(c),K=G(c.target),Z=I.map(h=>({value:h.value,label:h.label})),H=p.map(h=>({value:String(h.id),label:h.value}));return e.jsxs("div",{className:"grid grid-cols-[1fr_auto_90px_auto_1fr_auto_auto] gap-2 items-center bg-white dark:bg-gray-800/60 rounded-xl border border-gray-100 dark:border-gray-700 px-3 py-2 shadow-sm",children:[e.jsx(Oe,{value:c.meta_field||"",onChange:h=>Y(f,{meta_field:h||null}),options:Z,placeholder:i(`${a}.mapping.fixedValue`),emptyLabel:i(`${a}.mapping.fixedValueAlt`)}
1),e.jsx(he,{className:"w-3.5 h-3.5 text-gray-300 dark:text-gray-600 flex-shrink-0"}),e.jsxs("select",{value:c.target,onChange:h=>Y(f,{target:h.target.value,kommo_field:"",kommo_field_id:null,fixed_value:null,fixed_enum_id:null}),className:"text-xs border border-gray-200 dark:border-gray-600 rounded-lg px-2 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-white focus:ring-1 focus:ring-purple-400 outline-none",children:[e.jsx("option",{value:"contact",children:i(`${a}.mapping.contact`)}),e.jsx("option",{value:"lead",children:i(`${a}.mapping.deal`)})]}),e.jsx(he,{className:"w-3.5 h-3.5 text-gray-300 dark:text-gray-600 flex-shrink-0"}),e.jsx(Oe,{value:w(c),onChange:h=>_(f,h),options:K,placeholder:i(`${a}.mapping.selectField`),emptyLabel:i(`${a}.mapping.notSelected`)}),e.jsx("div",{className:"w-40",children:p.length>0?e.jsx(Oe,{value:c.fixed_enum_id?String(c.fixed_enum_id):"",onChange:h=>{const o=h?Number(h):null,k=p.find(S=>S.id===o);Y(f,{fixed_value:(k==null?void 0:k.value)||null,fixed_enum_id:o})},options:H,placeholder:c.meta_field?i(`${a}.mapping.autoFromMeta`):i("common.select"),emptyLabel:c.meta_field?i(`${a}.mapping.autoFromMetaEmpty`):i(`${a}.mapping.notSelected`)}):e.jsx("input",{value:c.fixed_value||"",onChange:h=>Y(f,{fixed_value:h.target.value||null}),placeholder:c.meta_field?i(`${a}.mapping.autoFromMeta`):i(`${a}.mapping.fixedValueInput`),className:"w-full text-xs border border-gray-200 dark:border-gray-600 rounded-lg px-2.5 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-white placeholder-gray-400 focus:ring-1 focus:ring-purple-400 outline-none"})}),e.jsx("button",{onClick:()=>F(h=>h.filter((o,k)=>k!==f)),className:"p-1.5 rounded-lg text-gray-300 dark:text-gray-600 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:e.jsx(xt,{className:"w-3.5 h-3.5"})})]},f)}),e.jsxs("button",{onClick:()=>F(c=>[...c,{meta_field:null,kommo_field:"",kommo_field_id:null,fixed_value:null,fixed_enum_id:null,target:"contact"}]),className:"flex items-center gap-1.5 text-xs text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 font-medium transition-colors px-1 py-1",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"}),i(`${a}.actions.addRow`)]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t border-purple-200 dark:border-purple-800",children:[e.jsx("button",{onClick:()=>N(u),className:"text-sm px-4 py-1.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors",children:i(`${a}.actions.saveMapping`)}),e.jsx("button",{onClick:n,className:"text-sm px-4 py-1.5 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-300 transition-colors",children:i("common.cancel")})]})]})}function ra({log:s}){const{t:m,language:N}=ie(),n=Ee[N],[i,u]=l.useState(!1),F={success:{icon:ce,label:m(`${a}.status.log.success`),color:"text-green-600 dark:text-green-400",bg:"bg-green-50 dark:bg-green-900/20",border:"border-green-200 dark:border-green-800"},error:{icon:mt,label:m(`${a}.status.log.error`),color:"text-red-600 dark:text-red-400",bg:"bg-red-50 dark:bg-red-900/20",border:"border-red-200 dark:border-red-800"},skipped:{icon:ut,label:m(`${a}.status.log.skipped`),color:"text-yellow-600 dark:text-yellow-400",bg:"bg-yellow-50 dark:bg-yellow-900/20",border:"border-yellow-200 dark:border-yellow-800"},pending:{icon:at,label:m(`${a}.status.log.pending`),color:"text-gray-500 dark:text-gray-400",bg:"bg-gray-50 dark:bg-gray-800",border:"border-gray-200 dark:border-gray-700"}},j=F[s.status]||F.pending,A=j.icon;return e.jsxs("div",{className:M("rounded-xl border",j.border,j.bg,"overflow-hidden"),children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-white/40 dark:hover:bg-white/5 transition-colors",onClick:()=>u(!i),children:[e.jsx(A,{className:M("w-4 h-4 flex-shrink-0",j.color)}),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:M("text-xs font-semibold",j.color),children:j.label}),s.pipeline_name&&e.jsx("span",{className:"text-xs text-blue-600 dar
1k:text-blue-400 bg-blue-100 dark:bg-blue-900/30 px-2 py-0.5 rounded-full",children:s.pipeline_name}),s.kommo_deal_url&&e.jsxs("a",{href:s.kommo_deal_url,target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),className:"flex items-center gap-1 text-xs text-blue-500 hover:text-blue-600 hover:underline font-medium",children:[e.jsx(zt,{className:"w-3 h-3"}),m(`${a}.logs.deal`,{id:s.kommo_lead_id??""}),e.jsx(gt,{className:"w-3 h-3"})]}),s.contact_id&&e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:m(`${a}.logs.contact`,{id:s.contact_id})}),s.error_message&&e.jsx("span",{className:"text-xs text-red-600 dark:text-red-400 truncate max-w-xs",children:s.error_message})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0 text-xs text-gray-400",children:[s.duration_ms!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(at,{className:"w-3 h-3"}),s.duration_ms,"ms"]}),e.jsx("span",{children:new Date(s.created_at).toLocaleString(n,{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}),e.jsx(pe,{className:M("w-3.5 h-3.5 transition-transform",i&&"rotate-180")})]})]}),i&&e.jsxs("div",{className:"border-t border-gray-200 dark:border-gray-700 px-4 py-3 space-y-3 bg-white/60 dark:bg-gray-900/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400",children:[e.jsx("span",{className:"font-medium",children:m(`${a}.logs.lastStep`)}),e.jsx("span",{className:"bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded font-mono",children:s.step})]}),s.field_mappings_used&&s.field_mappings_used.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400 block mb-1.5",children:[m(`${a}.logs.fieldMapping`,{count:s.field_mappings_used.length}),":"]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1",children:s.field_mappings_used.map((b,P)=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-gray-100 dark:bg-gray-700 rounded px-2 py-1",children:[e.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:b.meta_field||m(`${a}.logs.fixed`)}),e.jsx(he,{className:"w-3 h-3 text-gray-400"}),e.jsx("span",{className:M("font-medium",b.target==="lead"?"text-purple-600 dark:text-purple-400":"text-blue-600 dark:text-blue-400"),children:b.target==="lead"?m(`${a}.mapping.deal`):m(`${a}.mapping.contact`)}),e.jsx(he,{className:"w-3 h-3 text-gray-400"}),e.jsxs("span",{className:"text-gray-800 dark:text-white",children:[b.kommo_field,b.kommo_field_id?` #${b.kommo_field_id}`:""]}),b.fixed_value&&e.jsxs("span",{className:"text-orange-500",children:["= ",b.fixed_value]})]},P))})]}),s.contact_payload!=null&&e.jsxs("details",{className:"text-xs",children:[e.jsx("summary",{className:"font-medium text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-300",children:m(`${a}.logs.contactPayload`)}),e.jsx("pre",{className:"mt-1.5 bg-gray-100 dark:bg-gray-800 rounded-lg p-3 overflow-x-auto text-[11px] text-gray-600 dark:text-gray-300 max-h-40",children:JSON.stringify(s.contact_payload,null,2)})]}),s.deal_payload!=null&&e.jsxs("details",{className:"text-xs",children:[e.jsx("summary",{className:"font-medium text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-300",children:m(`${a}.logs.dealPayload`)}),e.jsx("pre",{className:"mt-1.5 bg-gray-100 dark:bg-gray-800 rounded-lg p-3 overflow-x-auto text-[11px] text-gray-600 dark:text-gray-300 max-h-40",children:JSON.stringify(s.deal_payload,null,2)})]}),s.error_message&&e.jsxs("div",{className:"bg-red-100 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg px-3 py-2 text-xs text-red-700 dark:text-red-300",children:[e.jsx("span",{className:"font-medium",children:m(`${a}.logs.errorLabel`)})," ",s.error_message]})]})]})}function it({pipelines:s,onSave:m}){const{t:N}=ie(),[n,i]=l.useState(!1),[u,F]=l.useState("");return n?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("select",{value:u,onChange:j=>F(j.target.value),className:"text-xs border border-gray-300 dark:border-gray-600 rounded px-1.5 py-1 bg-white dark:bg-gray-700 text-gray-800 dark:text-white",children:[e.jsx("option",{value:"",children:N(`${a}.kommo.pipeline`)}),s.map(j=>e.jsx("option",{value:String(j.id),children:j.name},j.id))]}),e.jsx("button",{onClick:()=>{u&&(m(u),i(!1))},disabled:!u,className:"text-xs px-2 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 transition-colors",children:"OK"}),e.jsx("button",{onClick:()=>i(!1),className:"text-gray-400 hover:text-gray-600",children:e.jsx(Le,{className:"w-3.5 h-3.5"})})]}):e.jsx("button",{onClick:()=>
1i(!0),className:"text-xs px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded hover:bg-blue-200 transition-colors",children:N(`${a}.actions.configure`)})}export{xa 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.