1import{j as i}from"./query-Q_ThwKGI.js";import{u as Z,r as w}from"./react-vendor-wefok28f.js";import{B as ee}from"./button-DrepnwkX.js";import{C as te}from"./card-DYyqUxY6.js";import{L as P}from"./icons-By8asZST.js";import{u as re}from"./index-C4Kq7kkR.js";import{s as d}from"./client-DjLwxtrO.js";import{r as ae,f as W}from"./redirectService-hDxAAvGF.js";import{u as se}from"./useLogger-CDsXA2_R.js";import{trackRedirectEvent as ie,initializeTrackingForCampaign as ne,trackPageView as oe}from"./trackingScripts-1XOvU7Jx.js";import{d as ce,s as le}from"./consolidatedMessageService-CxI_JEnX.js";import{F as ge}from"./FormUnavailableError-D5g8vwrQ.js";import"./supabase-COHOFxoQ.js";const de=r=>{switch(r){case"small":return"text-xl md:text-xl";case"medium":return"text-2xl md:text-2xl";case"extra large":return"text-4xl md:text-4xl";case"large":default:return"text-3xl md:text-3xl"}},ue=r=>{switch(r){case"small":return"text-lg md:text-lg";case"medium":return"text-xl md:text-xl";case"large":return"text-2xl md:text-2xl";case"extra large":return"text-3xl md:text-3xl";default:return"text-lg md:text-lg"}},pe=({title:r="Join our WhatsApp Group",subtitle:u="Click the button below to join the group",buttonText:n="Join Group",buttonColor:o="#25D366",titleSize:e="large",titleColor:y="#222222",subtitleSize:b="medium",subtitleColor:c="#666666",redirectDelay:E=0,loading:l=!1,fullGroupsMessage:v="All groups are currently full. Please try again later.",isFullGroup:C=!1,redirectTimer:_=null,redirecting:B=!1,onRedirect:A=()=>{}})=>l?i.jsx("div",{className:"flex items-center justify-center",children:i.jsx(P,{className:"h-8 w-8 animate-spin text-primary"})}):i.jsxs(te,{className:"max-w-md w-full p-8 space-y-6 animate-fade-in shadow-lg",children:[i.jsxs("div",{className:"text-center space-y-4",children:[i.jsx("h1",{className:`font-semibold ${de(e)}`,style:{color:y},children:C?v:r}),!C&&i.jsxs(i.Fragment,{children:[i.jsx("p",{className:`${ue(b)}`,style:{color:c},children:u}),_!==null&&_>0&&i.jsx("div",{className:"mt-4",children:i.jsxs("div",{className:"text-sm font-medium py-2 px-4 bg-muted inline-block rounded-full",children:["Redirecting in ",i.jsx("span",{className:"font-bold text-primary",children:_})," ",_===1?"second":"seconds","..."]})})]})]}),!C&&i.jsx(ee,{className:"w-full",style:{backgroundColor:o},onClick:A,children:B?i.jsxs(i.Fragment,{children:[i.jsx(P,{className:"mr-2 h-4 w-4 animate-spin"}),"Redirecting..."]}):n})]}),me=async(r,u,n)=>{try{console.log("[EnhancedBgMsg] Started",{groupId:r,campaignId:u,newRedirectCount:n});const{data:o,error:e}=await d.from("campaigns").select("first_message_settings, uazapi_settings, name, status").eq("id",u).single();if(e||!o){console.error("[EnhancedBgMsg] Campaign fetch error:",e);return}const y=o.first_message_settings,b=o.uazapi_settings,c=ce(y,b);if(c.provider==="none"){console.log("[EnhancedBgMsg] No messaging provider configured, skipping");return}console.log("[EnhancedBgMsg] Provider detected:",c.provider);const{data:E,error:l}=await d.from("whatsapp_groups").select("max_participants, name, status").eq("id",r).single();if(l||!E){console.error("[EnhancedBgMsg] Group fetch error:",l);return}const{data:v,error:C}=await d.from("campaign_groups").select("provider_group_id, provider_connection_status").eq("group_id",r).eq("campaign_id",u).single();if(C||!(v!=null&&v.provider_group_id)){console.error("[EnhancedBgMsg] Campaign group fetch error:",C);return}const{data:_}=await d.from("group_redirect_counts_table").select("message_count, full_message_sent, redirect_count").eq("group_id",r).maybeSingle(),B=(_==null?void 0:_.message_count)||0,A=(_==null?void 0:_.full_message_sent)||!1,f=c.messageConfig.redirectsBeforeMessage,G=f>0&&n>0&&n%f===0&&!!c.messageConfig.message;console.log("[EnhancedBgMsg] Welcome check:",{threshold:f,newRedirectCount:n,shouldSendWelcome:G});const F=E.max_participants||256,q=n>=F,I=q&&!A&&!!c.messageConfig.fullGroupMessage;console.log("[EnhancedBgMsg] Completion check:",{maxParticipants:F,willBeFull:q,shouldSendCompletion:I}),G&&(console.log("[EnhancedBgMsg] Sending welcome message"),await O(u,r,v.provider_group_id,"welcome",c.messageConfig.message,n,c),await d.from("group_redirect_counts_table").upsert({group_id:r,message_count:B+1,redirect_count:n,last_message_sent_at:new Date().toISOString()},{onConflict:"group_id"})),I&&(console.log("[EnhancedBgMsg] Sending completion message"),await O(u,r,v.provider_group_id,"completion",c.messageConfig.fullGroupMessage,n,c),await d.from("group_redirect_counts_table").upsert({group_id:r,full_message_sent:!0,last_full_message_sent_at:new Date().toISOString(),redirect_count:n},{onConflict:"group_id"})),console.log("[EnhancedBgMsg] Completed")}catch(o){console.error("[EnhancedBgMsg] Critical error:",o instanceof Error?o.message:String(o))}},O=async(r,u,n,o,e,y,b)=>{try{const{data:c}=await d.rpc("log_message_attempt",{p_campaign_id:r,p_group_id:u,p_message_type:o,p_message_content:e,p_redirect_count:y}),{data:E,error:l}=await le(b,n,e);c&&await d.rpc("update_message_delivery",{p_log_id:c,p_status:l?"failed":"sent",p_error_message:(l==null?void 0:l.message)||null,p_z_api_response:E||null}),l?console.error(`[EnhancedBgMsg] ${o} failed:`,l.message):console.log(`[EnhancedBgMsg] ${o} sent successfully`)}catch(c){console.error(`[EnhancedBgMsg] Error sending ${o}:`,c)}},je=()=>{const{campaignId:r,userCode:u,campaignSlug:n}=Z(),{toast:o}=re(),e=se("Redirect"),[y,b]=w.useState(!0),[c,E]=w.useState(!1),[l,v]=w.useState(null),[C,_]=w.useState("Loading c
1ampaign data..."),[B,A]=w.useState(!1),[f,G]=w.useState(null),[F,q]=w.useState(null),[I,J]=w.useState(!1),[h,K]=w.useState({title:"Join our WhatsApp Group",subtitle:"Click the button below to join the group",title_size:"large",subtitle_size:"medium",title_color:"#222222",subtitle_color:"#666666",button_text:"Join Group",button_color:"#25D366",background_color:"#ffffff",full_groups_message:"All groups are currently full. Please try again later.",redirect_delay:0});w.useEffect(()=>(e.info("ð Enhanced redirect page loaded",{campaignId:r||"N/A",userCode:u||"N/A",campaignSlug:n||"N/A",timestamp:new Date().toISOString()}),()=>{e.debug("ð Enhanced redirect page unmounted")}),[]),w.useEffect(()=>{(async()=>{var s;try{_("Loading campaign data..."),e.info("ð Fetching campaign data");let a=d.from("campaigns").select("id, user_id, status");if(r)/^\d+$/.test(r)?a=a.like("id::text",`%${r}%`):a=a.eq("id",r);else if(u&&n){const p=parseInt(u);if(!isNaN(p)){const{data:j}=await d.from("profiles").select("id").eq("user_code",p).single();j&&(a=a.eq("user_id",j.id).eq("slug",n))}}const{data:x,error:S}=await a.maybeSingle();if(S)throw S;if(!x)throw new Error("Campaign not found");e.debug("Checking campaign owner account status",{userId:x.user_id});const{data:M,error:$}=await d.from("profiles").select("subscription_plan, trial_end_date, leads_count, leads_limit").eq("id",x.user_id).maybeSingle();if($||!M)throw e.error("Failed to fetch profile",{error:$}),new Error("Campaign owner not found");const H=new Date,L=M.trial_end_date?new Date(M.trial_end_date):null,R=M.subscription_plan==="FREE"&&L&&H>L;if(R)throw e.info("Account blocked, not loading campaign",{isTrialExpired:R}),new Error("OWNER_BLOCKED");let N=d.from("campaigns").select(` 2 id, 3 name, 4 status, 5 redirect_settings, 6 ip_validation, 7 first_message_settings, 8 uazapi_settings, 9 campaign_groups!inner( 10 id, 11 group_id, 12 provider_group_id, 13 provider_connection_status, 14 provider_participants_count, 15 whatsapp_groups!inner( 16 id, 17 name, 18 invite_link, 19 status, 20 current_participants, 21 max_participants 22 ) 23 ) 24 `);if(r)/^\d+$/.test(r)?N=N.like("id::text",`%${r}%`):N=N.eq("id",r);else if(u&&n){const p=parseInt(u);if(!isNaN(p)){const{data:j}=await d.from("profiles").select("id").eq("user_code",p).single();j&&(e.info("ð¤ Found user profile"),N=N.eq("user_id",j.id).eq("slug",n))}}const{data:g,error:D}=await N.maybeSingle();if(D)throw e.error("â Error fetching campaign",{error:D.message}),D;if(g){e.info("â Campaign data retrieved with enhanced debugging",{id:g.id,name:g.name,status:g.status||"active",groupCount:((s=g.campaign_groups)==null?void 0:s.length)||0,hasFirstMessageSettings:!!g.first_message_settings});let p={};g.first_message_settings&&typeof g.first_message_settings=="object"&&(p=g.first_message_settings,e.info("ð Message Settings Found:",{integration:p.integration,hasIntegrationId:!!p.integration_id,hasToken:!!p.integration_token,hasClientToken:!!p.integration_client_token,hasWelcomeMessage:!!p.message,hasCompletionMessage:!!p.full_group_message,threshold:p.redirects_before_message||0}));const j=g.campaign_groups.map(m=>{const z=m.whatsapp_groups.status,X=z==="available"||z==="full"||z==="pending"||z==="closed"?z:"available",Y={id:m.whatsapp_groups.id,name:m.whatsapp_groups.name,invite_link:m.whatsapp_groups.invite_link,status:X,current_participants:Number(m.whatsapp_groups.current_participants),max_participants:Number(m.whatsapp_groups.max_participants)};return{id:m.id,campaign_id:g.id,group_id:m.group_id,provider_group_id:m.provider_group_id||null,provider_participants_count:m.provider_participants_count||null,provider_connection_status:m.provider_connection_status||null,whatsapp_groups:Y}}),k={id:g.id,name:g.name,status:g.status||"active",redirect_settings:typeof g.redirect_settings=="object"?g.redirect_settings:{},first_message_settings:p,campaign_groups:j,ip_validation:!!g.ip_validation};if(G(k),k.redirect_settings){K({...h,...k.redirect_settings}),I||(e.info("ð Initializing tracking"),ne(k.redirect_settings),oe(`WhatsApp Group Redirect - ${k.name}`,window.location.href),J(!0));const m=k.redirect_settings.redirect_delay;m&&m>0&&v(m)}b(!1),k.status==="active"?(_("Finding available group..."),await Q(k)):e.info("â ï¸ Campaign is inactive, skipping group finding")}else e.error("â Campaign not found"),o({title:"Campaign not found",description:"The requested campaign could not be found",variant:"destructive"}),b(!1)}catch(a){if(e.error("â Error fetching campaign",{error:a instanceof Error?a.message:String(a)}),a instanceof Error&&a.message==="OWNER_BLOCKED"){A(!0),b(!1);return}o({title:"Error",description:"Failed to load campaign details",variant:"destructive"}),b(!1)}})()},[r,u,n]);const Q=async t=>{try{await d.rpc("sync_campaign_groups",{p_campaign_id:t.id});const s=await W(t.id);if(s){const a=t.campaign_groups.find(x=>x.group_id===s);if(a){const{count:x}=await d.from("group_redirects").select("*",{count:"exact",head:!0}).eq("group_id",s),S=x||0,M=Number(a.whatsapp_groups.max_participants)||256;e.info("â Available group found",{groupId:s,groupName:a.whatsapp_groups.name,participants:`${S}/${M}`}),q(a)}}
24else e.warning("â ï¸ No available groups found")}catch(s){e.error("â Error in background processing",{error:s instanceof Error?s.message:String(s)})}};w.useEffect(()=>{if(l&&l>0){const t=setTimeout(()=>{v(l-1),l===1&&(e.info("â±ï¸ Timer completed, triggering redirect"),T())},1e3);return()=>clearTimeout(t)}},[l]);const T=async()=>{if(!f){e.error("â Cannot redirect - no campaign data");return}if(f.status==="inactive"){e.warning("â ï¸ Cannot redirect - campaign is inactive");return}try{E(!0);const t=F||await U(f);if(!t){e.warning("â ï¸ No available groups found"),o({title:"No groups available",description:"There are no available groups to join at the moment",variant:"destructive"}),E(!1);return}const{count:s}=await d.from("group_redirects").select("*",{count:"exact",head:!0}).eq("group_id",t.group_id),a=s||0,x=a+1;e.info("ð Enhanced redirect process starting:",{groupId:t.group_id,groupName:t.whatsapp_groups.name,currentCount:a,newRedirectCount:x}),f.redirect_settings&&(ie(f.id,t.group_id),e.info("ð Tracked group join event")),e.info("ð Recording redirect",{groupId:t.group_id,groupName:t.whatsapp_groups.name}),await ae(t.group_id,{toast:o},f.id),e.info("ð Starting enhanced background message processing"),me(t.group_id,f.id,x).then(()=>{e.info("â
Enhanced background message processing completed successfully")}).catch(S=>{e.error("â Enhanced background message processing failed",{error:S instanceof Error?S.message:String(S)})}),setTimeout(()=>{e.info("ð Redirecting user to WhatsApp group"),window.location.href=t.whatsapp_groups.invite_link},300)}catch(t){e.error("â Error during enhanced redirect",{error:t instanceof Error?t.message:String(t)}),E(!1),o({title:"Error",description:"Failed to redirect to the WhatsApp group",variant:"destructive"})}},U=async t=>{if(!t||!t.id)return null;try{await d.rpc("sync_campaign_groups",{p_campaign_id:t.id});const s=await W(t.id);if(!s)return null;const a=t.campaign_groups.find(x=>x.group_id===s);return a?(q(a),a):null}catch(s){return e.error("â Error finding available group",{error:s instanceof Error?s.message:String(s)}),null}},V=!!(f&&f.status==="active"&&f.campaign_groups.some(t=>{const s=Number(t.whatsapp_groups.current_participants),a=Number(t.whatsapp_groups.max_participants);return t.whatsapp_groups.status==="available"&&s<a}));return y?i.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",style:{backgroundColor:h.background_color||"#ffffff"},children:i.jsxs("div",{className:"text-center",children:[i.jsx(P,{className:"h-12 w-12 animate-spin mx-auto mb-4 text-primary"}),i.jsx("p",{className:"text-muted-foreground",children:C})]})}):B?i.jsx(ge,{isOwnerBlocked:!0}):i.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",style:{backgroundColor:h.background_color||"#ffffff"},children:i.jsx(pe,{title:h.title,subtitle:h.subtitle,buttonText:h.button_text,buttonColor:h.button_color,titleSize:h.title_size,titleColor:h.title_color,subtitleSize:h.subtitle_size,subtitleColor:h.subtitle_color,redirectDelay:h.redirect_delay,loading:!1,fullGroupsMessage:h.full_groups_message,isFullGroup:!V&&!y,redirectTimer:l,redirecting:c,onRedirect:T})})};export{je 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.