PageSourceSearch

https://app.healthychurchestoolkit.com/assets/LeaderProfiles-BYFVgL0o.js

js healthychurchestoolkit.com collected 2026-10-04 06:28:41 UTC 55,634 bytes, 13 lines download raw bytes

1import{c as ts,r as a,b as X,j as e,B as C,o as Le,e as P,L as Ae,R as As}from"./index-uPuoBMhx.js";import{u as Ps}from"./useOpenOnCreateParam-DbbvE1w7.js";import{I as ae}from"./input-BmSpt0Eh.js";import"./textarea-lM6uA-MR.js";import{C as ke,b as Fs,c as Ms,d as Is,a as Ds}from"./card-1lN1_Se8.js";import{B as oe}from"./badge-CrRB5M6z.js";import{D as Ie,a as De,b as Te,c as Re,e as Pe,d as qe}from"./dialog-DXhopuNX.js";import{S as Ts,a as Rs,b as Es,c as $s,d as Vs,e as Os}from"./sheet-CRixps9Y.js";import{S as ue,a as he,b as pe,c as xe,d as L}from"./select-D07I9jAC.js";import{L as J}from"./label-BejpMhEw.js";import{C as Fe}from"./checkbox-Chkf7-xA.js";import{T as Ls,a as Bs,b as $e,c as me,d as Us,e as ie}from"./table-C44Ca0MX.js";import{R as qs,a as zs}from"./radio-group-BnNX8VAb.js";import{T as Gs,a as Hs,b as Qs,c as Ys}from"./tooltip-B-l-dOqs.js";import{c as Me}from"./index-A7ElDbZk.js";import{T as Js,a as Ws,b as Ve,c as Oe}from"./tabs-CJ62Nd3v.js";import{A as as,a as ls}from"./alert-DhGFo-aW.js";import{A as rs,a as ns,b as is}from"./avatar-Bhxn90qL.js";import{L as ze,a as Xs}from"./constants-C7eot9Ct.js";import{S as Zs}from"./scroll-area-PVGhhXG6.js";import{C as Be}from"./circle-alert-C0QDXt7F.js";import{L as le}from"./loader-circle-CClJTEjr.js";import{a as Ks}from"./quickAssignUtils-B7qgPg_3.js";import{S as os}from"./search-CqNdnPxG.js";import{C as Ue}from"./circle-check-big-DOAasZi7.js";import{P as Xe}from"./PageContainer-DxZiU86J.js";import{j as te,n as et,o as st}from"./pages.config-hgExbgEC.js";import{P as tt}from"./PageSkeleton-C4cCZsu0.js";import{E as cs}from"./eye-CjABOWJP.js";import{S as ds,a as ms}from"./square-pen-CBgOWTmU.js";import{T as us}from"./trash-2-CNhP3AqE.js";import{U as hs}from"./users-U-Rdm9PF.js";import{A as at}from"./arrow-right-VpgmkQjv.js";import{S as Ze}from"./shield-check-Ds0sNnHc.js";import{R as lt}from"./RevealMore-KEkRkQnc.js";import{U as ps}from"./upload-BpeK1eLh.js";import{P as Ke}from"./plus-nao29ywL.js";import{A as rt,a as nt}from"./arrow-up-AttvlR97.js";import{A as it}from"./arrow-up-down-vjGAMNOZ.js";import{X as es}from"./x-ChRmB3ff.js";import"./index-Cu1sS3TT.js";import"./index-BaASz1SR.js";import"./index-CPcWs2mZ.js";import"./index-Wvdu2dI_.js";import"./index-BmCJDWmK.js";import"./index-BIK2eHIR.js";import"./index-BdQq_4o_.js";import"./index-DoY6TkfM.js";import"./index-BLbwat6W.js";import"./index-ovzA6VBT.js";import"./chevron-down-BNqv1YJ1.js";import"./dropdown-menu-iCIlU9cC.js";import"./link-q-TY0bPt.js";import"./trending-up-DI8OWV5v.js";import"./mail-Dn9HRcgA.js";import"./clock-D9btEWFO.js";import"./skeleton-DOGFCoEw.js";import"./quill.snow-CfUTnqzn.js";import"./switch-BehuccBp.js";import"./format-WoXbaKoi.js";import"./sparkles-BMLEjkPv.js";import"./crown-Dka_-Nxk.js";import"./waypoints-DB6uEXAV.js";import"./graduation-cap-DFwKZhhE.js";import"./SupervisedGuidesRoster-DrArdAB4.js";import"./ChurchTag-FinbzF8x.js";import"./building-2-CH0TgYOF.js";import"./circle-check-BO0sHK-q.js";import"./clipboard-list-3xEa1kOf.js";import"./journeyApi-CQ6eKrk4.js";import"./external-link-DCG1godj.js";import"./video-CYNXJfA8.js";import"./proxy-kYcqYoy3.js";import"./JourneyCard-6WViabqj.js";import"./info-D7uJ7LVm.js";import"./globe-CcruHzdM.js";import"./badge-check-D0W_elOA.js";import"./megaphone-CGb0rIfX.js";import"./user-plus-DYMIVDGV.js";import"./useQuery-BHFaz3Mh.js";import"./Loader-yhtKwwRu.js";import"./lock-BWkWm970.js";import"./index-Ck7DnIc4.js";import"./user-CtT-IPS_.js";import"./ellipsis-CzlaRWtW.js";/**
2 * @license lucide-react v0.475.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const ot=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],ct=ts("FileSpreadsheet",ot);/**
7 * @license lucide-react v0.475.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const dt=[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]],mt=ts("Merge",dt);function ut({isOpen:m,onClose:b,corporateAccountId:s,onImportSuccess:y}
11){const[d,N]=a.useState([]),[x,B]=a.useState(new Set),[T,f]=a.useState(!1),[F,M]=a.useState(!1),[R,I]=a.useState(null),[E,Q]=a.useState("");a.useEffect(()=>{m&&Y()},[m]);const Y=async()=>{var p;f(!0),I(null);try{const i=await X.functions.invoke("fetchAllPCPeople",{corporateAccountId:s});console.log("fetchAllPCPeople response:",i),N(((p=i.data)==null?void 0:p.people)||[])}catch(i){I("Failed to load people from Planning Center"),console.error("Error loading people:",i)}finally{f(!1)}},W=p=>{const i=new Set(x);i.has(p)?i.delete(p):i.add(p),B(i)},U=async()=>{M(!0);try{const p=d.filter(g=>x.has(g.id));console.log("Importing people:",p);const i=p.map(g=>({corporate_account_id:s,first_name:g.name.split(" ")[0],last_name:g.name.split(" ").slice(1).join(" ")||"",full_name:g.name,email:g.email||`${g.id}@planning-center.local`,phone:g.phone||"",planning_center_person_id:g.id,pc_email:g.email,is_active:!0}));console.log("Creating profiles:",i);const v=await X.entities.VolunteerProfile.bulkCreate(i);console.log("Import result:",v),y&&y(),b(),B(new Set)}catch(p){I("Failed to import volunteers: "+p.message),console.error("Import error:",p)}finally{M(!1)}},z=d.filter(p=>p.name.toLowerCase().includes(E.toLowerCase())||p.email.toLowerCase().includes(E.toLowerCase()));return e.jsx(Ie,{open:m,onOpenChange:b,children:e.jsxs(De,{className:"max-w-2xl max-h-[80vh] flex flex-col",children:[e.jsx(Te,{children:e.jsx(Re,{children:"Import Volunteers from Planning Center"})}),R&&e.jsxs("div",{className:"p-3 bg-red-50 text-red-700 rounded-lg text-sm flex items-start gap-2",children:[e.jsx(Be,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:R})]}),e.jsx(ae,{placeholder:"Search by name or email...",value:E,onChange:p=>Q(p.target.value),className:"mb-2"}),e.jsx("div",{className:"h-[50vh] border rounded-lg bg-gray-50 overflow-hidden",children:e.jsx(Zs,{className:"h-full",children:e.jsx("div",{className:"p-4 space-y-2",children:T?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(le,{className:"w-5 h-5 animate-spin text-gray-400"})}):z.length===0?e.jsx("div",{className:"text-sm text-gray-500 py-4 text-center",children:E?"No matching people found":"No people found in Planning Center"}):z.map(p=>e.jsxs("label",{className:"flex items-center gap-3 p-2 hover:bg-white rounded cursor-pointer border-b",children:[e.jsx(Fe,{checked:x.has(p.id),onCheckedChange:()=>W(p.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:p.name}),e.jsx("div",{className:"text-xs text-gray-500 truncate",children:p.email})]})]},p.id))})})}),e.jsxs(Pe,{children:[e.jsx(C,{variant:"outline",onClick:b,className:"bg-white",children:"Cancel"}),e.jsx(C,{onClick:U,disabled:x.size===0||F,className:"bg-white text-gray-900 border border-gray-300 hover:bg-gray-50",children:F?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}),"Importing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("img",{src:"https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68d5721b1b37e5d85630c192/a423d233c_planning-center-icon.png",alt:"Planning Center",className:"w-4 h-4 object-contain"}),"Import from Planning Center"]})})]})]})})}function ht({isOpen:m,onClose:b,leader:s,roles:y,teams:d,roleAssignments:N,corporateAccountId:x,clientId:B=null,onComplete:T}){const[f,F]=a.useState(""),[M,R]=a.useState(null),[I,E]=a.useState(!1);a.useEffect(()=>{m&&(F(""),R(null))},[m]);const Q=a.useMemo(()=>N.reduce((i,v)=>(i[v.org_chart_role_id]=(i[v.org_chart_role_id]||0)+1,i),{}),[N]),Y=a.useMemo(()=>new Set(N.filter(i=>i.volunteer_profile_id===(s==null?void 0:s.id)).map(i=>i.org_chart_role_id)),[N,s]),W=i=>{var v;return((v=d.find(g=>g.id===i))==null?void 0:v.team_name)||"No Team"},U=a.useMemo(()=>{const i=f.toLowerCase();return[...y].filter(v=>!i||v.role_title.toLowerCase().includes(i)||W(v.team_id).toLowerCase().includes(i)).sort((v,g)=>v.role_title.localeCompare(g.role_title))},[y,f,d]),z=async i=>{E(!0);try{(await Ks({leaderId:s.id,role:i,corporateAccountId:x,clientId:B})).pcSyncFailed?P.warning("Assigned, but could not roster in Planning Center."):P.success(`${s.first_name} assigned to ${i.role_title}`),T(),b()}catch(v){console.error("Quick assign failed:",v),P.error("Failed to assign role. Please try again.")}finally{E(!1),R(null)}},p=i=>{const v=Q[i.id]||0,g=i.position_count||1;v>=g?R(i):z(i)};return s?e.jsx(Ie,{open:m,onOpenChange:b,children:e.jsxs(De,{className:"max-w-lg",children:[e.jsxs(Te,{children:[e.jsx(Re,{children:"Assign a Role"}),e.jsxs(qe,{children:["Choose a role for ",s.first_name," ",s.last_name,". Availability is shown for each role."]})]}),M?e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 bg-amber-50 border border-amber-200 rounded-lg p-4",children:[e.jsx(Le,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold text-amber-900",children:"This role is already full"}),e.jsxs("p",{className:"text-amber-800 mt-1",children:[e.jsx("span",{className:"font-medium",children:M.role_title})," has all"," ",M.position_count||1," position",(M.position_count||1)>1?"s":""," filled (",Q[M.id]||0,"/",M.position_count||1,"). Assigning"," ",s.first_name," will exceed the available positions. Do you want to over-assign?"]})]})]}),e.jsxs(Pe,{children:[e.jsx(C,{variant:"outline",onClick:()=>R(null),disabled:I,children:"Go Back"}),e.jsxs(C,{onClick:()=>z(M),disabled:I,className:"bg-amber-600 hover:bg-amber-700 text-white",children:[I?e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}):null,"Yes, Over-Assign"]})]})]}):e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(os,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(ae,{placeholder:"Search roles...",value:f,onChange:i=>F(i.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"max-h-80 overflow-y-auto overflow-x-hidden space-y-1.5 pr-1",children:[U.length===0&&e.jsx("p",{className:"text-center text-sm text-gray-500 py-8",children:"No roles found."}),U.map(i=>{const v=Q[i.id]||0,g=i.position_count||1,u=Y.has(i.id),w=v>=g;return e.jsxs("button",{type:"button",disabled:u||I,onClick:()=>p(i),className:`w-full min-w-0 flex items-center justify-between gap-3 border rounded-lg px-3 py-2.5 text-left transition-colors ${u?"bg-gray-50 opacity-60 cursor-not-allowed":"hover:border-[var(--color-accent)] hover:bg-[var(--bg-accent-1)]"}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:i.role_title}),e.jsx(oe,{variant:"outline",className:`text-xs ${ze[i.leadership_level]||""}`,children:i.leadership_level})]}),e.jsx("p",{className:"text-xs text-gray-500 truncate mt-0.5",children:W(i.team_id)})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:u?e.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-700 font-medium",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"})," Assigned"]}):e.jsxs("span",{className:`text-xs font-semibold px-2 py-1 rounded-full ${w?"bg-amber-100 text-amber-800":"bg-green-100 text-green-800"}`,children:[v,"/",g," filled"]})})]},i.id)})]})]})]})}):null}function pt({leader:m,roleInfo:b,profilePictureUrl:s,onEdit:y,onDelete:d,onAssignRole:N}){var B,T;const x=(((B=m.first_name)==null?void 0:B[0])||"")+(((T=m.last_name)==null?void 0:T[0])||"");return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsxs(rs,{className:"h-10 w-10 flex-shrink-0",children:[e.jsx(ns,{src:s,alt:`${m.first_name} ${m.last_name}`}),e.jsx(is,{className:"text-xs",children:x})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs(Ae,{to:Me(`LeaderDetails?id=${m.
11id}`),className:"font-medium text-[var(--color-text)] hover:underline block truncate",children:[m.first_name," ",m.last_name]}),e.jsx("a",{href:`mailto:${m.email}`,className:"text-xs text-muted-foreground block truncate",children:m.email})]}),e.jsx(oe,{variant:m.is_active?"default":"secondary",className:m.is_active?"bg-green-100 text-green-800 flex-shrink-0":"text-gray-500 flex-shrink-0",children:m.is_active?"Active":"Inactive"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:N,className:`text-sm underline-offset-2 hover:underline ${b.title==="Unassigned"?"text-gray-400 italic":"text-[var(--color-text)]"}`,children:b.title}),b.level&&e.jsx(oe,{variant:"outline",className:ze[b.level],children:b.level})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1 border-t border-border",children:[e.jsx(C,{variant:"ghost",size:"sm",asChild:!0,className:"flex-1",children:e.jsxs(Ae,{to:Me(`LeaderDetails?id=${m.id}`),children:[e.jsx(cs,{className:"w-4 h-4 mr-1.5"}),"View"]}
11)}),e.jsxs(C,{variant:"ghost",size:"sm",onClick:y,className:"flex-1",children:[e.jsx(ds,{className:"w-4 h-4 mr-1.5"}),"Edit"]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:d,className:"text-red-600 hover:text-red-700",children:e.jsx(us,{className:"w-4 h-4"})})]})]})}const xt={corporate_owner:{label:"Corporate Owner",className:"bg-purple-100 text-purple-800"},corporate_sub:{label:"Sub-Account",className:"bg-blue-100 text-blue-800"}};function ft({accountType:m}){const b=xt[m];return b?e.jsx(oe,{variant:"outline",className:b.className,children:b.label}):e.jsx("span",{className:"text-gray-400 italic",children:"None"})}const xs={first_name:"First Name",last_name:"Last Name",phone:"Phone",disc_style:"DiSC Style",onboarding_status:"Onboarding Status",is_active:"Active?",planning_center_person_id:"Planning Center Person ID"},ss=Object.keys(xs);function _t({isOpen:m,onClose:b,leaders:s,corporateAccountId:y,onComplete:d}){const[N,x]=a.useState("groups"),[B,T]=a.useState(!1),[f,F]=a.useState([]),[M,R]=a.useState([]),[I,E]=a.useState([]),[Q,Y]=a.useState({}),[W,U]=a.useState(null),[z,p]=a.useState(!1);a.useEffect(()=>{m&&(x("groups"),R([]),i())},[m]);const i=async()=>{var n;T(!0);try{const h=await X.functions.invoke("findDuplicateLeaderProfiles",{corporateAccountId:y});F(((n=h.data)==null?void 0:n.duplicate_groups)||[])}catch(h){console.error("Failed to load duplicate groups:",h),P.error("Failed to scan for duplicates.")}finally{T(!1)}},v=n=>{const h=n.map(G=>s.find(se=>se.id===G)).filter(Boolean);if(h.length<2){P.error("Couldn't find those profiles — try refreshing the page.");return}const q=h.find(G=>G.user_id);E(h),U(q?q.id:h[0].id);const S={};for(const G of ss){const se=h.find(K=>K[G]!==void 0&&K[G]!==null&&K[G]!=="");S[G]=se?se.id:h[0].id}Y(S),x("compare")},g=n=>{R(h=>h.includes(n)?h.filter(q=>q!==n):[...h,n])},u=async()=>{var n,h;p(!0);try{const q=await X.functions.invoke("mergeLeaderProfiles",{corporateAccountId:y,profileIds:I.map(S=>S.id),primaryProfileId:W,fieldSelections:Q});(n=q.data)!=null&&n.success?(P.success(`Merged ${I.length} profiles into one.`),d(),b()):P.error(((h=q.data)==null?void 0:h.error)||"Merge failed.")}catch(q){console.error("Merge failed:",q),P.error("Merge failed. Please try again.")}finally{p(!1)}},w=a.useMemo(()=>[...s||[]].sort((n,h)=>(n.last_name||"").localeCompare(h.last_name||"")),[s]),j=I.find(n=>n.user_id);return e.jsx(Ie,{open:m,onOpenChange:b,children:e.jsxs(De,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Te,{children:[e.jsxs(Re,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-5 h-5"}),"Merge Duplicate Leader Profiles"]}),e.jsx(qe,{children:N==="compare"?"Choose which value to keep for each field, then confirm the merge.":"Combine duplicate profiles for the same person into a single source of truth."})]}),N==="groups"&&e.jsxs("div",{className:"space-y-4",children:[B?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(le,{className:"w-5 h-5 animate-spin text-gray-400"})}):f.length===0?e.jsx("p",{className:"text-center text-gray-500 py-4",children:"No profiles sharing the same email were found."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Profiles sharing the same email:"}),f.map((n,h)=>e.jsxs("div",{className:"border rounded-lg p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[n[0].first_name," ",n[0].last_name]}),e.jsx("p",{className:"text-sm text-gray-500",children:n[0].email}),e.jsxs(oe,{variant:"secondary",className:"mt-1",children:[n.length," entries"]})]}),e.jsxs(C,{size:"sm",onClick:()=>v(n.map(q=>q.id)),children:["Review & Merge ",e.jsx(at,{className:"w-4 h-4 ml-1"})]})]},h))]}),e.jsx("div",{className:"pt-4 border-t",children:e.jsx(C,{variant:"outline",className:"w-full",onClick:()=>x("manual"),children:"Merge Profiles with Different Emails Instead"})})]}),N==="manual"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Select two or more profiles that are the same person (e.g. a personal email and a work email)."}),e.jsx("div",{className:"max-h-80 overflow-y-auto border rounded-lg divide-y",children:w.map(n=>e.jsxs("label",{className:"flex items-center gap-3 p-3 cursor-pointer hover:bg-gray-50",children:[e.jsx(Fe,{checked:M.includes(n.id
11),onCheckedChange:()=>g(n.id)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-medium text-sm",children:[n.first_name," ",n.last_name]}),e.jsx("p",{className:"text-xs text-gray-500",children:n.email})]}),n.user_id&&e.jsxs(oe,{variant:"outline",className:"text-xs flex items-center gap-1",children:[e.jsx(Ze,{className:"w-3 h-3"})," Has Account"]})]},n.id))}),e.jsxs(Pe,{children:[e.jsx(C,{variant:"outline",onClick:()=>x("groups"),children:"Back"}),e.jsxs(C,{disabled:M.length<2,onClick:()=>v(M),children:["Compare Selected (",M.length,")"]})]})]}),N==="compare"&&e.jsxs("div",{className:"space-y-4",children:[j&&e.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800 flex items-start gap-2",children:[e.jsx(Ze,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:j.email})," has a linked login account, so it will always be kept as the final email and record. You can still choose which other details to keep below."]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"p-3 bg-gray-50 border-b font-medium text-sm",children:"Email (kept)"}),e.jsx("div",{className:"p-3 text-sm",children:(I.find(n=>n.id===W)||{}).email})]}),ss.map(n=>{const h=I.map(S=>({id:S.id,value:S[n]}));return h.every(S=>JSON.stringify(S.value)===JSON.stringify(h[0].value))?null:e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsx(J,{className:"text-sm font-medium mb-2 block",children:xs[n]}),e.jsx(qs,{value:Q[n],onValueChange:S=>Y(G=>({...G,[n]:S})),className:"space-y-1",children:I.map(S=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(zs,{value:S.id,id:`${n}-${S.id}`}),e.jsx(J,{htmlFor:`${n}-${S.id}`,className:"font-normal cursor-pointer text-sm",children:String(S[n]??"— empty —")})]},S.id))})]},n)}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Spiritual gifts, strengths, ministry interests, coaching history, review history, and competencies will be automatically combined from all selected profiles. The other ",I.length-1," profile(s) will be removed after merging."]}),e.jsxs(Pe,{children:[e.jsx(C,{variant:"outline",onClick:()=>x("groups"),children:"Cancel"}),e.jsxs(C,{onClick:u,disabled:z,children:[z&&e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}),"Confirm Merge"]})]})]})]})})}const gt=({isOpen:m,onClose:b,leader:s,roles:y,divineDesignSubmissions:d,existingLeaders:N,currentUser:x,onSave:B,corporateAccountId:T,clientId:f=null})=>{var ve,_e;const[F,M]=a.useState(!1),[R,I]=a.useState(!1),[E,Q]=a.useState([]),[Y,W]=a.useState([]),[U,z]=a.useState(null),[p,i]=a.useState(""),[v,g]=a.useState({}),[u,w]=a.useState(""),[j,n]=a.useState({user_id:"",first_name:"",last_name:"",email:"",phone:"",current_role_id:null,leadership_level:null,onboarding_status:"not_started",background_check:{status:"not_submitted",last_checked_date:null},is_active:!0,divine_design_results_id:null}),h=a.useMemo(()=>{if(T)return T;if(!x)return null;if(s!=null&&s.corporate_account_id)return s.corporate_account_id;switch(x.account_type){case"corporate_owner":return x.id;case"corporate_sub":return x.corporate_account_id;default:return x.id}},[x,s,T]),q=a.useCallback(async()=>{var l;if(!(!h||!m)){I(!0),z(null);try{console.log("[ImprovedModal] Loading users for corporate account:",h);let t=[];try{const o=await X.functions.invoke("getCorporateAccountUsers",{corporateAccountId:h});(l=o.data)!=null&&l.success&&Array.isArray(o.data.data)?(t=o.data.data,console.log("[ImprovedModal] Function returned users:",t.length)):console.warn("[ImprovedModal] Function returned unexpected data:",o.data)}catch(o){console.warn("[ImprovedModal] Function call failed, trying direct entity query:",o);try{t=[await X.entities.User.get(h)];const k=await X.entities.User.filter({corporate_account_id:h,account_type:"corporate_sub"});t=[...t,...k],console.log("[ImprovedModal] Direct query returned users:",t.length)}catch(A){throw console.error("[ImprovedModal] Direct query also failed:",A),new Error("Could not load users from either method")}}t.some(o=>
11o.id===x.id)||(x.id===h||x.corporate_account_id===h)&&t.push(x),t.sort((o,A)=>{if(o.account_type==="corporate_owner"&&A.account_type!=="corporate_owner")return-1;if(A.account_type==="corporate_owner"&&o.account_type!=="corporate_owner")return 1;const k=o.full_name||`${o.first_name||""} ${o.last_name||""}`.trim()||o.email,H=A.full_name||`${A.first_name||""} ${A.last_name||""}`.trim()||A.email;return k.localeCompare(H)}),Q(t)}catch(t){console.error("[ImprovedModal] Failed to load users:",t),z(t.message),Q([])}finally{I(!1)}}},[h,x,m]);a.useEffect(()=>{m&&q()},[m,q]),a.useEffect(()=>{(async()=>{if(!(!m||!h))try{const t=await te(f,"TeamStructure").filter({corporate_account_id:h,deleted_at:null});W(t)}catch(t){console.error("Failed to load teams:",t),W([])}})()},[m,h]);const S=a.useCallback(l=>{if(!l||l==="no_team")return"Unassigned";const t=Y.find(o=>o.id===l);return(t==null?void 0:t.team_name)||"Unknown Team"},[Y]);a.useMemo(()=>{if(!j.leadership_level)return{};const t=y.filter(k=>k.leadership_level===j.leadership_level).reduce((k,H)=>{const ce=H.team_id||"no_team";return k[ce]||(k[ce]=[]),k[ce].push(H),k},{});Object.keys(t).forEach(k=>{t[k].sort((H,ce)=>H.role_title.localeCompare(ce.role_title))});const o=Object.keys(t).sort((k,H)=>k==="no_team"?1:H==="no_team"?-1:S(k).localeCompare(S(H))),A={};for(const k of o)A[k]=t[k];return A},[y,j.leadership_level,S]);const G=a.useMemo(()=>{if(!E.length||!N)return[];const l=new Set(N.filter(t=>t.user_id).map(t=>t.user_id));return E.filter(t=>(s==null?void 0:s.user_id)===t.id?!0:!l.has(t.id))},[E,N,s]),se=a.useMemo(()=>{if(!d||!N)return[];const l=d.filter(o=>o.assessment_type==="divine_design"),t=new Set(N.map(o=>o.email.toLowerCase()));return l.filter(o=>(s==null?void 0:s.divine_design_results_id)===o.id?!0:!t.has(o.participant_email.toLowerCase()))},[d,N,s]),K=(x==null?void 0:x.role)==="admin"||(x==null?void 0:x.account_type)==="corporate_owner",V=a.useMemo(()=>{if(!K||!(s!=null&&s.user_id)||!E.length)return null;const l=E.find(t=>t.id===s.user_id);return(l==null?void 0:l.account_type)==="corporate_sub"?l:null},[s,E,K]);a.useEffect(()=>{m&&(s?(i(s.user_id||""),w(s.divine_design_results_id||""),n({user_id:s.user_id||"",first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",corporate_account_id:s.corporate_account_id||"",phone:s.phone||"",current_role_id:s.current_role_id||null,leadership_level:s.leadership_level||null,onboarding_status:s.onboarding_status||"not_started",background_check:s.background_check||{status:"not_submitted",last_checked_date:null},is_active:s.is_active!==void 0?s.is_active:!0,divine_design_results_id:s.divine_design_results_id||null})):(i(""),w(""),n({user_id:"",first_name:"",last_name:"",email:"",corporate_account_id:h,phone:"",onboarding_status:"not_started",background_check:{status:"not_submitted",last_checked_date:null},is_active:!0,divine_design_results_id:null})))},[m,s,h]),a.useEffect(()=>{g(V?{can_manage_volunteer_profiles:V.can_manage_volunteer_profiles||!1,can_manage_church_training:V.can_manage_church_training||!1,can_schedule_social_posts:V.can_schedule_social_posts||!1,can_view_all_reviews:V.can_view_all_reviews||!1,can_launch_reviews:V.can_launch_reviews||!1,can_manage_review_questions:V.can_manage_review_questions||!1,can_edit_strategic_foundation:V.can_edit_strategic_foundation||!1,can_manage_vision_indicators:V.can_manage_vision_indicators||!1,can_manage_strategy_projects:V.can_manage_strategy_projects||!1,can_manage_org_chart:V.can_manage_org_chart||!1,can_manage_competencies:V.can_manage_competencies||!1}:{})},[V]);const fe=l=>{if(i(l),w(""),!l){n(o=>({...o,user_id:"",first_name:"",last_name:"",email:"",divine_design_results_id:null}));return}const t=E.find(o=>o.id===l);if(t){const o=d==null?void 0:d.find(A=>A.participant_email.toLowerCase()===t.email.toLowerCase()&&A.assessment_type==="divine_design");n(A=>{var k,H;return{...A,user_id:t.id,first_name:t.first_name||((k=t.full_name)==null?void 0:k.split(" ")[0])||"",last_name:t.last_name||((H=t.full_name)==null?void 0:H.split(" ").slice(1).join(" "))||"",email:t.email,divine_design_results_id:(o==null?void 0:o.id)||null}})}},Ee=l=>{if(w(l),i(""),!l){n(o=>({...o,user_id:"",first_name:"",last_name:"",email:"",divine_design_results_id:null}));return}const t=d.find(o=>o.id===l);t&&n(o=>({...o,user_id:"",first_name:t.participant_name.split(" ")[0]||"",last_name:t.participant_name.split(" ").slice(1).join(" ")||"",email:t.participant_email,divine_design_results_id:t.id}))},be=async l=>{var t;if(l.preventDefault(),!j.first_name||!j.last_name||!j.email){P.error("First Name, Last Name and Email are required.");return}M(!0);try{const o=`${j.first_name} ${j.last_name}`.trim(),A={...j,full_name:o,corporate_account_id:(s==null?void 0:s.corporate_account_id)||h},k=te(f,"VolunteerProfile");if(s!=null&&s.id?await k.update(s.id,A):await k.create(A),K&&V&&Object.keys(v).length>0)try{(t=(await X.functions.invoke("updateSubAccountPermissions",{subAccountId:V.id,permissions:v})).data)!=null&&t.success||P.warning("Profile saved, but account permissions couldn't be updated.")}catch{P.warning("Profile saved, but account permissions couldn't be updated.")}P.success(`Leader profile ${s!=null&&s.id?"updated":"created"} successfully!`),B(),b()}catch(o){console.error("Failed to save leader profile:",o),P.error("Failed to save profile. Please try again.")}finally{M(!1)}};return m?e.jsx(Ts,{open:m,onOpenChange:b,children:e.jsxs(Rs,{side:"right",className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsxs(Es,{children:[e.jsxs($s,{children:[s!=null&&s.id?"Edit":"Add New"," Leader Profile"]}),e.jsx(Vs,{children:s!=null&&s.id?`Update ${s.first_name||"the leader"}'s information below.`:"Add a leader by selecting from your team, from Divine Design submissions, or entering manually."})]}),e.jsxs("form",{onSubmit:be,className:"space-y-4 py-4",children:[(!s||!s.user_id
11)&&e.jsxs(e.Fragment,{children:[R&&e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Loading team members..."})]})}),U&&e.jsxs(as,{children:[e.jsx(Be,{className:"h-4 h-4"}),e.jsxs(ls,{children:[e.jsx("p",{className:"font-semibold mb-1",children:"Unable to load team members"}),e.jsx("p",{className:"text-sm",children:U}),e.jsx(C,{variant:"link",className:"p-0 h-auto mt-1",onClick:q,children:"Try again"})]})]}),!R&&G.length>0&&e.jsxs("div",{className:"space-y-2 p-4 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx(J,{htmlFor:"user_select",className:"text-base font-medium",children:s?"Link to User Account":`Select from Your Team (${G.length} available)`}),e.jsx("p",{className:"text-sm text-gray-600",children:s?"Connect this leader profile to an existing user account to sync data and enable full platform access.":"Choose from your existing account users or sub-accounts who don't yet have a leader profile."}),e.jsxs(ue,{value:p,onValueChange:fe,children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"-- Select a team member --"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"null",children:"-- None --"}),G.map(l=>{const t=`${l.first_name||""} ${l.last_name||""}`.trim()||l.full_name||l.email,o=l.account_type==="corporate_owner"?"Owner":l.account_type==="corporate_sub"?"Team Member":"User";return e.jsxs(L,{value:l.id,children:[t," (",l.email,") - ",o]},l.id)})]})]})]}),!R&&!U&&G.length===0&&E.length>0&&e.jsx("div",{className:"p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-yellow-600 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-yellow-800",children:"All team members already have profiles"}),e.jsxs("p",{className:"text-yellow-700",children:["All ",E.length," users in your account already have leader profiles. You can still add external volunteers using the options below."]})]})]})}),se.length>0&&e.jsxs("div",{className:"space-y-2 p-4 bg-gray-50 rounded-lg",children:[e.jsxs(J,{htmlFor:"assessment_select",className:"text-base font-medium",children:["Or Select from Divine Design Submissions (",se.length," available)"]}),e.jsx("p",{className:"text-sm text-gray-500",children:"People who have completed an assessment but are not yet linked to a leader profile."}),e.jsxs(ue,{value:u,onValueChange:Ee,children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"-- Select from assessments --"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"null",children:"-- None --"}),se.map(l=>e.jsxs(L,{value:l.id,children:[l.participant_name," (",l.participant_email,")"]},l.id))]})]})]}),!s&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("p",{className:"text-base font-medium text-gray-700 mb-3",children:"Or Enter Details Manually"}),e.jsx("p",{className:"text-sm text-gray-500",children:"For external volunteers or new users not yet in the system or with an assessment."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"first_name",children:"First Name *"}),e.jsx(ae,{id:"first_name",value:j.first_name,onChange:l=>n(t=>({...t,first_name:l.target.value})),disabled:!!p||!!u,required:!0})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"last_name",children:"Last Name *"}),e.jsx(ae,{id:"last_name",value:j.last_name,onChange:l=>n(t=>({...t,last_name:l.target.value})),disabled:!!p||!!u,required:!0})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"email",children:"Email *"}),e.jsx(ae,{id:"email",type:"email",value:j.email,onChange:l=>n(t=>({...t,email:l.target.value})),disabled:!!p||!!u,required:!0}),(!!p||!!u)&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Name and email are synchronized from the selected source."})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ae,{id:"phone",value:j.phone||"",onChange:l=>n(t=>({...t,phone:l.target.value})),placeholder:"Contact phone number"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Role assignments are managed separately after creating the profile"})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"onboarding_status",children:"Onboarding Status"}),e.jsxs(ue,{value:j.onboarding_status||"not_started",onValueChange:l=>n(t=>({...t,onboarding_status:l})),children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"Select status"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"not_started",children:"Not Started"}),e.jsx(L,{value:"in_progress",children:"In Progress"}),e.jsx(L,{value:"completed",children:"Completed"})]})]})]}
11),e.jsxs("div",{children:[e.jsx(J,{children:"Background Check"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 border p-3 rounded-lg",children:[e.jsxs("div",{children:[e.jsx(J,{htmlFor:"bg_check_status",className:"text-xs",children:"Status"}),e.jsxs(ue,{value:((ve=j.background_check)==null?void 0:ve.status)||"not_submitted",onValueChange:l=>n(t=>({...t,background_check:{...t.background_check||{},status:l}})),children:[e.jsx(he,{id:"bg_check_status",children:e.jsx(pe,{placeholder:"Select status"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"not_submitted",children:"Not Submitted"}),e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"cleared",children:"Cleared"}),e.jsx(L,{value:"failed",children:"Failed"})]})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"bg_check_date",className:"text-xs",children:"Last Checked Date"}),e.jsx(ae,{id:"bg_check_date",type:"date",value:((_e=j.background_check)==null?void 0:_e.last_checked_date)||"",onChange:l=>n(t=>({...t,background_check:{...t.background_check||{},last_checked_date:l.target.value||null}}))})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fe,{id:"is_active",checked:j.is_active||!1,onCheckedChange:l=>n(t=>({...t,is_active:l}))}),e.jsx(J,{htmlFor:"is_active",children:"This leader is active in ministry"})]}),V&&e.jsxs("div",{className:"border rounded-lg p-4 space-y-3 bg-blue-50 border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"w-4 h-4 text-blue-600"}),e.jsx("p",{className:"text-sm font-semibold text-blue-800",children:"Account Permissions"})]}),e.jsxs("p",{className:"text-xs text-blue-700",children:["This leader has a linked sub-account (",V.email,"). Manage their platform permissions below."]}),e.jsx("div",{className:"space-y-2",children:[{key:"can_manage_volunteer_profiles",label:"Can Manage Volunteer Profiles"},{key:"can_manage_church_training",label:"Can Manage Church Training"},{key:"can_schedule_social_posts",label:"Can Schedule Social Posts"},{key:"can_view_all_reviews",label:"Can View All Reviews"},{key:"can_launch_reviews",label:"Can Launch Reviews"},{key:"can_manage_review_questions",label:"Can Manage Review Questions"},{key:"can_edit_strategic_foundation",label:"Can Edit Strategic Foundation"},{key:"can_manage_vision_indicators",label:"Can Manage Vision Indicators"},{key:"can_manage_strategy_projects",label:"Can Manage Strategy Projects"},{key:"can_manage_org_chart",label:"Can Manage Org Chart"},{key:"can_manage_competencies",label:"Can Manage Competencies"}].map(({key:l,label:t})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fe,{id:`perm-${l}`,checked:v[l]||!1,onCheckedChange:o=>g(A=>({...A,[l]:o}))}),e.jsx(J,{htmlFor:`perm-${l}`,className:"font-normal cursor-pointer text-sm",children:t})]},l))})]}),e.jsxs(Os,{children:[e.jsx(C,{type:"button",variant:"outline",onClick:b,children:"Cancel"}),e.jsxs(C,{type:"submit",disabled:F,children:[F?e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}):null,"Save Profile"]})]})]})]})}):null},jt=({isOpen:m,onClose:b,onSuccess:s,currentUser:y,corporateAccountId:d})=>{var U,z,p,i,v,g;const[N,x]=a.useState(null),[B,T]=a.useState(!1),[f,F]=a.useState(null),[M,R]=a.useState(!1),I=u=>{const w=u.target.files[0];w&&w.type==="text/csv"?(x(w),F(null)):(P.error("Please select a valid CSV file"),x(null))},E=async()=>{if(!N){P.error("Please select a file first");return}T(!0);try{const{file_url:u}=await X.integrations.Core.UploadFile({file:N}),w=d||y.corporate_account_id||y.id,j=await X.functions.invoke("processVolunteerUpload",{file_url:u,corporate_account_id:w});j.data.success?(F(j.data),P.success("File processed successfully. Review the preview below.")):(P.error(j.data.error||"Failed to process file"),F(null))}catch(u){console.error("Upload or processing error:",u),P.error("Failed to process file. Please try again."),F(null)}finally{T(!1)}},Q=async()=>{if(!f||!f.new_volunteers||f.new_volunteers.length===0){P.error("No new volunteers to import");return}R(!0);try{const u=d||y.corporate_account_id||y.id,w=await X.functions.invoke("importVolunteers",{volunteers:f.new_volunteers,corporate_account_id:u});w.data.success?(P.success(`Successfully imported ${w.data.imported_count} volunteer(s)`),s(),Y()):P.error(w.data.error||"Failed to import volunteers")}catch(u){console.error("Import error:",u),P.error("Failed to import volunteers. Please try again.")}finally{R(!1)}},Y=()=>{x(null),F(null),T(!1),R(!1),b()},W=()=>{const u=`first_name,last_name,email,phone
12John,Doe,[email protected],555-0100
13Jane,Smith,[email protected],555-0101`,w=new Blob([u],{type:"text/csv"}),j=window.URL.createObjectURL(w),n=document.createElement("a");n.href=j,n.download="volunteer_upload_template.csv",document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(j),n.remove()};return m?e.jsx(Ie,{open:m,onOpenChange:Y,children:e.jsxs(De,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Te,{children:[e.jsx(Re,{children:"Bulk Upload Volunteers"}),e.jsx(qe,{children:"Upload a CSV file to add multiple volunteers at once. Duplicates will be automatically detected."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs(as,{children:[e.jsx(ct,{className:"h-4 w-4"}),e.jsxs(ls,{children:[e.jsx("p",{className:"font-semibold mb-2",children:"CSV Format Requirements:"}),e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1 ml-4",children:[e.jsxs("li",{children:["Required columns: ",e.jsx("code",{children:"first_name"}),", ",e.jsx("code",{children:"last_name"}),", ",e.jsx("code",{children:"email"})]}),e.jsxs("li",{children:["Optional column: ",e.jsx("code",{children:"phone"})]}),e.jsx("li",{children:"First row should contain column headers"})]}),e.jsx(C,{variant:"link",className:"p-0 h-auto mt-2",onClick:W,children:"Download CSV Template"})]})]}),e.jsxs("div",{children:[e.jsx(J,{htmlFor:"csv_file",children:"Select CSV File"}),e.jsx(ae,{id:"csv_file",type:"file",accept:".csv",onChange:I,className:"mt-1"}),N&&e.jsxs("p",{className:"text-sm text-gray-600 mt-1",children:["Selected: ",N.name]})]}),!f&&e.jsx(C,{onClick:E,disabled:!N||B,className:"w-full",children:B?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Upload and Preview"]})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"w-5 h-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:((U=f.new_volunteers)==null?void 0:U.length)||0}),e.jsx("p",{className:"text-sm text-gray-600",children:"New Volunteers"})]})]})}),e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-5 h-5 text-yellow-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:((z=f.duplicates)==null?void 0:z.length)||0}),e.jsx("p",{className:"text-sm text-gray-600",children:"Duplicates Found"})]})]})}),e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-5 h-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:((p=f.errors)==null?void 0:p.length)||0}),e.jsx("p",{className:"text-sm text-gray-600",children:"Errors"})]})]})})]}),e.jsxs(Js,{defaultValue:"new",className:"w-full",children:[e.jsxs(Ws,{className:"w-full",children:[e.jsxs(Ve,{value:"new",className:"flex-1",children:["New Volunteers (",((i=f.new_volunteers)==null?void 0:i.length)||0,")"]}),e.jsxs(Ve,{value:"duplicates",className:"flex-1",children:["Duplicates (",((v=f.duplicates)==null?void 0:v.length)||0,")"]}),f.errors&&f.errors.length>0&&e.jsxs(Ve,{value:"errors",className:"flex-1",children:["Errors (",f.errors.length,")"]})]}),e.jsx(Oe,{value:"new",className:"max-h-64 overflow-y-auto",children:f.new_volunteers&&f.new_volunteers.length>0?e.jsx("div",{className:"space-y-2",children:f.new_volunteers.map((u,w)=>e.jsxs("div",{className:"border rounded p-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[u.first_name," ",u.last_name]}),e.jsx("p",{className:"text-sm text-gray-600",children:u.email}),u.phone&&e.jsx("p",{className:"text-sm text-gray-500",children:u.phone})]}),e.jsx(Ue,{className:"w-5 h-5 text-green-600"})]},w))}):e.jsx("p",{className:"text-center text-gray-500 py-8",children:"No new volunteers to import"})}),e.jsx(Oe,{value:"duplicates",className:"max-h-64 overflow-y-auto",children:f.duplicates&&f.duplicates.length>0?e.jsx("div",{className:"space-y-2",children:f.duplicates.map((u,w)=>e.jsxs("div",{className:"border border-yellow-300 bg-yellow-50 rounded p-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[u.first_name," ",u.last_name]}),e.jsx("p",{className:"text-sm text-gray-600",children:u.email})]}),e.jsx(Le,{className:"w-5 h-5 text-yellow-600"})]}),e.jsx("p",{className:"text-sm text-yellow-800 mt-2",children:u.reason})]},w))}):e.jsx("p",{className:"text-center text-gray-500 py-8",children:"No duplicates found"})}),f.errors&&f.errors.length>0&&e.jsx(Oe,{value:"errors",className:"max-h-64 overflow-y-auto",children:e.jsx("div",{className:"space-y-2",children:f.errors.map((u,w)=>e.jsx("div",{className:"border border-red-300 bg-red-50 rounded p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(es,{className:"w-5 h-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-red-900",children:["Row ",u.row]}),e.jsx("p",{className:"text-sm text-red-700",children:u.message})]})]})},w))})})]}),e.jsxs("div",{className:"flex gap-3 pt-4 border-t",children:[e.jsx(C,{variant:"outline",onClick:Y,className:"flex-1",children:"Cancel"}),e.jsx(C,{onClick:Q,disabled:!f.new_volunteers||f.new_volunteers.length===0||M,className:"flex-1",children:M?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-4 h-4 mr-2 animate-spin"}),"Importing..."]}):e.jsxs(e.Fragment,{children:["Import ",((g=f.new_volunteers)==null?void 0:g.length)||0," Volunteer(s)"]})})]})]})]})]})}):null};function Za({isEditorMode:m=!1,clientId:b=null,onViewLeaderDetails:s}
13){const y=m?b:null,[d,N]=a.useState(null),[x,B]=a.useState(null),[T,f]=a.useState([]),[F,M]=a.useState([]),[R,I]=a.useState([]),[E,Q]=a.useState([]),[Y,W]=a.useState([]),[U,z]=a.useState([]),[p,i]=a.useState([]),[v,g]=a.useState(!0),[u,w]=a.useState(""),[j,n]=a.useState(()=>new URLSearchParams(window.location.search).get("role")==="unassigned"?"unassigned":"all"),[h,q]=a.useState("all"),[S,G]=a.useState("all"),[se,K]=a.useState(null),[V,fe]=a.useState(!1);Ps(()=>fe(!0));const[Ee,be]=a.useState(!1),[ve,_e]=a.useState(null),[l,t]=a.useState(null),[o,A]=a.useState("asc"),[k,H]=a.useState(!1),[ce,Ge]=a.useState(!1),[ye,He]=a.useState(!1),Qe=As.useRef(!1),de=a.useCallback(async(r=!1)=>{var _;r||g(!0);try{let c=d;c||(c=await X.auth.me(),N(c));const $=(c==null?void 0:c.role)==="admin",O=(c==null?void 0:c.account_type)!=="corporate_sub"&&((c==null?void 0:c.subscription_tier)==="plus"||(c==null?void 0:c.subscription_tier)==="guide"),Z=(c==null?void 0:c.account_type)==="corporate_sub"&&(c==null?void 0:c.can_manage_volunteer_profiles),D=m&&b;if(!c||!($||O||Z||D)){g(!1),B(null);return}const ee=D?b:c.account_type==="corporate_sub"?c.corporate_account_id:c.id;B(ee);const[Ce,Se,ws,Cs]=await Promise.all([te(y,"VolunteerProfile").filter({corporate_account_id:ee,deleted_at:null},"-updated_date"),te(y,"OrgChartRole").filter({corporate_account_id:ee,deleted_at:null,is_active:!0}),te(y,"TeamStructure").filter({corporate_account_id:ee,deleted_at:null}),te(y,"VolunteerRoleAssignment").filter({corporate_account_id:ee,deleted_at:null})]);if(f(Ce),M(Se),I(ws),i(Cs),g(!1),!Qe.current){Qe.current=!0;const[Ss,ks]=await Promise.all([te(y,"AssessmentResult").filter({corporate_account_owner_id:ee,deleted_at:null}),te(y,"CoreCompetency").filter({corporate_account_id:ee,deleted_at:null})]);W(Ss),Q(ks);try{const ne=await X.functions.invoke("getCorporateAccountUsers",{corporateAccountId:ee});z(((_=ne==null?void 0:ne.data)==null?void 0:_.data)||[])}catch(ne){console.error("Failed to load users for profile pictures:",ne),z([])}try{const ne=await X.entities.PlanningCenterConnection.filter({corporate_account_id:ee,status:"active"});He(ne.length>0)}catch{He(!1)}}}catch(c){P.error("Failed to load data."),console.error("Data loading error:",c),N(null),B(null),g(!1)}},[d,m,b]);a.useEffect(()=>{de()},[]);const re=a.useCallback(r=>{const _=et(p.filter(D=>D.volunteer_profile_id===r),F),c=_.find(D=>D.is_primary);if(!c)return{title:"Unassigned",teamName:"N/A",level:null,roleCount:0};const $=F.find(D=>D.id===c.org_chart_role_id),O=R.find(D=>D.id===$.team_id),Z=[..._].sort((D,je)=>Number(je.is_primary)-Number(D.is_primary)).map(D=>F.find(je=>je.id===D.org_chart_role_id));return{title:Z.map(D=>D.role_title).join(", "),teamName:O?O.team_name:"No Team",level:st(Z),roleCount:Z.length}},[F,R,p]),Ye=a.useCallback(r=>{if(r.profile_picture_url)return r.profile_picture_url;if(r.user_id){const _=U.find(c=>c.id===r.user_id);if(_!=null&&_.profile_picture_url)return _.profile_picture_url}return null},[U]),Ne=a.useCallback(r=>{if(!r.user_id)return null;const _=U.find(c=>c.id===r.user_id);return(_==null?void 0:_.account_type)||null},[U]),we=a.useMemo(()=>{let r=T.filter(_=>{var Ce;const c=_.first_name&&_.last_name?`${_.first_name} ${_.last_name}`:_.full_name||"",$=re(_.id),O=p.find(Se=>Se.volunteer_profile_id===_.id&&Se.is_primary),Z=!u||c.toLowerCase().includes(u.toLowerCase())||((Ce=_.email)==null?void 0:Ce.toLowerCase().includes(u.toLowerCase()))||$.title.toLowerCase().includes(u.toLowerCase()),D=j==="all"||j==="unassigned"&&$.title==="Unassigned"||O&&O.org_chart_role_id===j,je=h==="all"||$.level===h,ee=S==="all"||(S==="active"?_.is_active:!_.is_active);return Z&&D&&je&&ee});return l&&r.sort((_,c)=>{let $,O;switch(l){case"name":$=`${_.last_name||""} ${_.first_name||""}`.toLowerCase(),O=`${c.last_name||""} ${c.first_name||""}`.toLowerCase();break;case"email":$=(_.email||"").toLowerCase(),O=(c.email||"").toLowerCase();break;case"role":$=re(_.id).title.toLowerCase(),O=re(c.id).title.toLowerCase();break;case"level":const Z={L1:1,L2:2,L3:3,L4:4,L5:5};$=Z[re(_.id).level]||0,O=Z[re(c.id).level]||0;break;case"account":const D={corporate_owner:2,corporate_sub:1};$=D[Ne(_)]||0,O=D[Ne(c)]||0;break;case"status":$=_.is_active?1:0,O=c.is_active?1:0;break;default:return 0}return $<O?o==="asc"?-1:1:$>O?o==="asc"?1:-1:0}),r},[T,u,j,h,S,re,Ne,l,o]),fs=r=>{l===r?A(o==="asc"?"desc":"asc"):(t(r),A("asc"))},ge=({column:r,children:_})=>{const c=l===r;return e.jsxs("button",{type:"button",onClick:()=>fs(r),className:"flex items-center gap-1 hover:text-gray-900 transition-colors",children:[_,c?o==="asc"?e.jsx(rt,{className:"w-4 h-4"}):e.jsx(nt,{className:"w-4 h-4"}):e.jsx(it,{className:"w-4 h-4 opacity-40"})]})},_s=()=>{K(null),fe(!0)},Je=r=>{K(r),fe(!0)},We=async r=>{if(window.confirm("Are you sure you want to delete this leader profile? This action cannot be undone."))try{const _=p.filter(c=>c.volunteer_profile_id===r);for(const c of _)await te(y,"VolunteerRoleAssignment").update(c.id,{deleted_at:new Date().toISOString()});await te(y,"VolunteerProfile").update(r,{deleted_at:new Date().toISOString()}),P.success("Leader deleted successfully"),de(!0)}catch(_){console.error("Failed to delete leader:",_),P.error("Failed to delete leader. Please try again.")}},gs=()=>{fe(!1),K(null)},js=()=>{de(!0)};if(v)return e.jsx(Xe,{width:"wide",children:e.jsx(tt,{cards:2,columns:1})});const vs=(d==null?void 0:d.role)==="admin",bs=m&&b&&(d==null?void 0:d.subscription_tier)==="guide",ys=(d==null?void 0:d.account_type)!=="corporate_sub"&&((d==null?void 0:d.subscription_tier)==="plus"||(d==null?void 0:d.subscription_tier)==="guide"),Ns=(d==null?void 0:d.account_type)==="corporate_sub"&&(d==null?void 0:d.can_manage_volunteer_profiles);
13return!d||!(vs||bs||ys||Ns)?e.jsxs("div",{className:"text-center py-16",children:[e.jsx(ms,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-800",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"You don't have permission to manage Volunteer Profiles."}),e.jsx("p",{className:"text-gray-500 text-sm mt-1",children:"Contact your account administrator for access."})]}):e.jsxs(Xe,{width:"wide",className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Fs,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Ms,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-6 h-6 text-[var(--color-accent)]"}),"Leader Profiles"]}),e.jsx(Is,{children:"Manage your volunteers and leadership team"})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(lt,{label:"More tools",variant:"actions",className:"contents",children:[e.jsxs(C,{variant:"outline",onClick:()=>be(!0),children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Bulk Upload"]}),e.jsxs(C,{variant:"outline",onClick:()=>Ge(!0),children:[e.jsx(mt,{className:"w-4 h-4 mr-2"}),"Merge Duplicates"]}),e.jsx(Gs,{delayDuration:100,children:e.jsxs(Hs,{children:[e.jsx(Qs,{asChild:!0,children:e.jsx("span",{tabIndex:0,children:e.jsxs(C,{onClick:()=>H(!0),disabled:!ye,variant:ye?"outline":"ghost",className:ye?"":"opacity-50 cursor-not-allowed",children:[e.jsx("img",{src:"https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68d5721b1b37e5d85630c192/a423d233c_planning-center-icon.png",alt:"Planning Center",className:"w-4 h-4 object-contain"}),"Import from Planning Center"]})})}),!ye&&e.jsx(Ys,{className:"max-w-xs",children:"Planning Center isn't connected yet. The corporate account owner can activate it under Account → Integrations → Connect Planning Center."})]})})]}),e.jsxs(C,{onClick:_s,children:[e.jsx(Ke,{className:"w-4 h-4 mr-2"}),"Add Leader"]})]})]})}),e.jsxs(Ds,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(os,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(ae,{placeholder:"Search leaders...",value:u,onChange:r=>w(r.target.value),className:"pl-10"})]}),e.jsxs(ue,{value:j,onValueChange:n,children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"Filter by Role"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"all",children:"All Roles"}),e.jsx(L,{value:"unassigned",children:"Unassigned"}),F.map(r=>e.jsx(L,{value:r.id,children:r.role_title},r.id))]})]}),e.jsxs(ue,{value:h,onValueChange:q,children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"Filter by Level"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"all",children:"All Levels"}),Xs.map(r=>e.jsx(L,{value:r,children:r},r))]})]}),e.jsxs(ue,{value:S,onValueChange:G,children:[e.jsx(he,{children:e.jsx(pe,{placeholder:"Filter by Status"})}),e.jsxs(xe,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"active",children:"Active"}),e.jsx(L,{value:"inactive",children:"Inactive"})]})]})]}),e.jsx("div",{className:"md:hidden space-y-3",children:we.length>0?we.map(r=>e.jsx(pt,{leader:r,roleInfo:re(r.id),profilePictureUrl:Ye(r),onEdit:()=>Je(r),onDelete:()=>We(r.id),onAssignRole:()=>_e(r)},r.id)):e.jsx("p",{className:"text-center py-8 text-gray-500",children:"No leaders found matching your filters."})}),e.jsx("div",{className:"hidden md:block overflow-x-auto",children:e.jsxs(Ls,{children:[e.jsx(Bs,{children:e.jsxs($e,{children:[e.jsx(me,{children:e.jsx(ge,{column:"name",children:"Name"})}),e.jsx(me,{children:e.jsx(ge,{column:"email",children:"Email"})}),e.jsx(me,{children:e.jsx(ge,{column:"role",children:"Role"})}),e.jsx(me,{children:e.jsx(ge,{column:"level",children:"Level"})}),e.jsx(me,{children:e.jsx(ge,{column:"account",children:"Account"})}),e.jsx(me,{children:e.jsx(ge,{column:"status",children:"Status"})}),e.jsx(me,{className:"text-right",children:"Actions"})]})}),e.jsx(Us,{children:we.length>0?we.map(r=>{var O,Z;const _=(((O=r.first_name)==null?void 0:O[0])||"")+(((Z=r.last_name)==null?void 0:Z[0])||""),c=Ye(r),$=re(r.id);return e.jsxs($e,{children:[e.jsx(ie,{className:"font-medium",children:e.jsxs(Ae,{to:Me(`LeaderDetails?id=${r.id}`),className:"flex items-center gap-3 hover:text-brand-primary transition-colors",children:[e.jsxs(rs,{className:"h-8 w-8",children:[e.jsx(ns,{src:c,alt:`${r.first_name} ${r.last_name}`}),e.jsx(is,{className:"text-xs",children:_})]}),e.jsxs("span",{className:"hover:underline",children:[r.first_name," ",r.last_name]})]})}),e.jsx(ie,{children:e.jsx("a",{href:`mailto:${r.email}`,className:"text-blue-600 hover:underline",onClick:D=>D.stopPropagation(),children:r.email})}),e.jsx(ie,{children:e.jsxs("button",{type:"button",onClick:()=>_e(r),title:"Quick-assign a role",className:"flex items-center gap-2 group hover:text-[var(--color-accent)] transition-colors",children:[e.jsx("span",{className:`group-hover:underline ${$.title==="Unassigned"?"text-gray-400 italic":""}`,children:$.title}),e.jsx(Ke,{className:"w-3.5 h-3.5 opacity-0 group-hover:opacity-100 transition-opacity"})]})}),e.jsx(ie,{children:$.level?e.jsx(oe,{variant:"outline",className:ze[$.level],children:$.level}):e.jsx("span",{className:"text-gray-400",children:"Not set"})}),e.jsx(ie,{children:e.jsx(ft,{accountType:Ne(r)})}),e.jsx(ie,{children:e.jsx(oe,{variant:r.is_active?"default":"secondary",className:r.is_active?"bg-green-100 text-green-800":"text-gray-500",children:r.is_active?"Active":"Inactive"})}),e.jsxs(ie,{className:"text-right space-x-2",children:[e.jsx(C,{variant:"ghost",size:"icon",asChild:!0,children:e.jsx(Ae,{to:Me(`LeaderDetails?id=${r.id}`),children:e.jsx(cs,{className:"w-4 h-4"})})}),e.jsx(C,{variant:"ghost",size:"icon",onClick:()=>Je(r),children:e.jsx(ds,{className:"w-4 h-4"})}),e.jsx(C,{variant:"ghost",size:"icon",onClick:()=>We(r.id),className:"text-red-600 hover:text-red-700",children:e.jsx(us,{className:"w-4 h-4"})})]})]},r.id)}
13):e.jsx($e,{children:e.jsx(ie,{colSpan:7,className:"text-center py-8 text-gray-500",children:"No leaders found matching your filters."})})})]})})]})]}),e.jsx(gt,{isOpen:V,onClose:gs,leader:se,roles:F,divineDesignSubmissions:Y,existingLeaders:T,currentUser:d,onSave:js,corporateAccountId:x,clientId:y}),e.jsx(jt,{isOpen:Ee,onClose:()=>be(!1),onSuccess:()=>de(!0),currentUser:d,corporateAccountId:x}),e.jsx(ht,{isOpen:!!ve,onClose:()=>_e(null),leader:ve,roles:F,teams:R,roleAssignments:p,corporateAccountId:x,clientId:y,onComplete:()=>de(!0)}),e.jsx(ut,{isOpen:k,onClose:()=>H(!1),corporateAccountId:x,onImportSuccess:()=>de(!0)}),e.jsx(_t,{isOpen:ce,onClose:()=>Ge(!1),leaders:T,corporateAccountId:x,onComplete:()=>de(!0)})]})}export{Za 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.